修复:查询局部刷新与智能分析会话交互,完善分析收尾和配置切换
This commit is contained in:
+264
-22
@@ -14,6 +14,7 @@ import fcntl
|
||||
import hashlib
|
||||
import http.cookiejar
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
@@ -59,7 +60,7 @@ _ALLOWED_PATHS = {
|
||||
"/api/releases", "/api/options", "/api/metrics",
|
||||
"/api/analysis/tools/catalog", "/api/analytics/top",
|
||||
},
|
||||
"POST": {"/api/analysis/tools/details", "/api/analysis/defects"},
|
||||
"POST": {"/api/analysis/tools/details", "/api/analysis/defects", "/api/analysis/investigate"},
|
||||
}
|
||||
|
||||
|
||||
@@ -362,17 +363,17 @@ class DelegatedApi:
|
||||
safe_detail = detail.get("detail") if isinstance(detail, dict) else None
|
||||
if isinstance(safe_detail, str) and len(safe_detail) <= 600:
|
||||
raise RuntimeErrorSafe(safe_detail.replace(snapshot.token, "[REDACTED]")) from None
|
||||
raise RuntimeErrorSafe(f"质量中心查询暂不可用(HTTP {error.code})。") from None
|
||||
raise RuntimeErrorSafe(f"质量数据分析平台查询暂不可用(HTTP {error.code})。") from None
|
||||
except (URLError, OSError, TimeoutError):
|
||||
raise RuntimeErrorSafe("质量中心查询暂不可用,请确认本机质量服务后重试。") from None
|
||||
raise RuntimeErrorSafe("质量数据分析平台查询暂不可用,请确认本机质量服务后重试。") from None
|
||||
if len(raw) > 8 * 1024 * 1024:
|
||||
raise RuntimeErrorSafe("质量中心查询响应超过允许大小。")
|
||||
raise RuntimeErrorSafe("质量数据分析平台查询响应超过允许大小。")
|
||||
try:
|
||||
result = json.loads(raw.decode("utf-8")) if raw else {}
|
||||
except (UnicodeDecodeError, json.JSONDecodeError):
|
||||
raise RuntimeErrorSafe("质量中心查询返回格式无效。") from None
|
||||
raise RuntimeErrorSafe("质量数据分析平台查询返回格式无效。") from None
|
||||
if not isinstance(result, dict):
|
||||
raise RuntimeErrorSafe("质量中心查询返回格式无效。")
|
||||
raise RuntimeErrorSafe("质量数据分析平台查询返回格式无效。")
|
||||
return _redact_credentials(result, snapshot.token)
|
||||
|
||||
|
||||
@@ -383,9 +384,9 @@ def public_tool_call(tool: str, raw_input: Any) -> dict[str, Any]:
|
||||
args = value.get("arguments") if isinstance(value.get("arguments"), dict) else {}
|
||||
labels = {"catalog": "确认可用数据", "query": "查询质量指标", "compare": "比较期间变化",
|
||||
"top": "查询重点对象排名", "changes": "追查变化较大对象", "defects": "分析具体缺陷",
|
||||
"details": "核查来源明细"}
|
||||
"details": "核查来源明细", "investigate": "核对全量明细与原表"}
|
||||
allowed = {"mode", "scope", "period", "comparisonPeriod", "filters", "view", "stage", "dimension",
|
||||
"defect", "category", "limit", "sort"}
|
||||
"defect", "category", "limit", "sort", "action", "offset", "recordFilter", "sourceRevisionId"}
|
||||
nested = {"year", "month", "quarter", "department", "group", "product", "projectGroup", "includeUnassigned"}
|
||||
public_input = {}
|
||||
for key, item in args.items():
|
||||
@@ -403,20 +404,151 @@ def public_tool_call(tool: str, raw_input: Any) -> dict[str, Any]:
|
||||
return {"label": {"python": "执行数据分析", "sql": "查询分析数据"}.get(tool, "执行分析工具")}
|
||||
|
||||
|
||||
def tool_operation_key(tool: str, raw_input: Any) -> str:
|
||||
def public_progress_text(value: str) -> str:
|
||||
value = re.sub(r"(?i)(?:bearer\s+)[A-Za-z0-9._~+/-]+", "Bearer [REDACTED]", value)
|
||||
return re.sub(r"(?i)(api[_-]?key|password|token|secret|authorization)(\s*[=::]\s*)[^\s,,;;]+", r"\1\2[REDACTED]", value)[:8000]
|
||||
|
||||
|
||||
def public_evidence_checks(output: Any) -> dict[str, str]:
|
||||
"""Only verified tool outcomes update coverage warnings; never assistant text."""
|
||||
if isinstance(output,str):
|
||||
try: output=json.loads(output)
|
||||
except ValueError:return {}
|
||||
if not isinstance(output,dict):return {}
|
||||
if isinstance(output.get("content"),list):
|
||||
checks={}
|
||||
for part in output["content"]:
|
||||
if isinstance(part,dict) and isinstance(part.get("text"),str):checks.update(public_evidence_checks(part["text"]))
|
||||
return checks
|
||||
checks={}
|
||||
def add(rows,period,proof=None):
|
||||
for row in rows if isinstance(rows,list) else []:
|
||||
if not isinstance(row,dict):continue
|
||||
key=hashlib.sha256(json.dumps([output.get("releaseId"),output.get("stage"),period,output.get("filters"),row.get("category")],ensure_ascii=False,sort_keys=True).encode()).hexdigest()[:16]
|
||||
if output.get("kind")=="quality_investigation":
|
||||
expected=(row.get("expectedTotalsOnly") or {}).get("rows",0)>0 and row.get("unexpectedDifferenceRows")==0 and row.get("requiresFurtherInvestigation") is False
|
||||
status="unresolved" if proof is not None and (proof.get("complete") is not True or proof.get("allSelectedValuesMatchStored") is not True) else "expected" if expected else "unresolved" if row.get("requiresFurtherInvestigation") else "checked"
|
||||
else:
|
||||
status="expected" if row.get("reconciliationStatus")=="EXPECTED_TOTALS_ONLY" else "unresolved" if row.get("reconciliationStatus")!="RECONCILED" else "checked"
|
||||
checks[key]=status
|
||||
if output.get("kind")=="quality_investigation":
|
||||
for name,period in (("current",output.get("period")),("comparison",output.get("comparisonPeriod"))):
|
||||
side=output.get(name)
|
||||
if isinstance(side,dict):add(side.get("categories"),period,side.get("sourceVerification"))
|
||||
elif output.get("kind")=="quality_fine_defects":
|
||||
add(output.get("categoryReconciliation"),output.get("period"));add(output.get("comparisonCategoryReconciliation"),output.get("comparisonPeriod"))
|
||||
return checks
|
||||
|
||||
|
||||
def public_tool_failure(output: Any) -> str:
|
||||
if isinstance(output,str):
|
||||
try:output=json.loads(output)
|
||||
except ValueError:return "工具调用未成功,未提供可展示的错误原因"
|
||||
if isinstance(output,dict):
|
||||
error=output.get("error")
|
||||
if isinstance(error,dict) and error.get("code")=="invalid_or_unavailable" and isinstance(error.get("message"),str):
|
||||
return "查询未成功:"+public_progress_text(error["message"])[:450]
|
||||
if isinstance(output.get("structuredContent"),dict):return public_tool_failure(output["structuredContent"])
|
||||
for part in output.get("content",[]) if isinstance(output.get("content"),list) else []:
|
||||
if isinstance(part,dict) and isinstance(part.get("text"),str):return public_tool_failure(part["text"])
|
||||
return "工具调用未成功,未提供可展示的错误原因"
|
||||
|
||||
|
||||
def public_tool_result(output: Any) -> str:
|
||||
"""Summarize only verified response structure; never forward raw tool payloads."""
|
||||
if isinstance(output, str):
|
||||
try: output = json.loads(output)
|
||||
except ValueError: return "工具已返回;未提供可展示的结构化摘要"
|
||||
if not isinstance(output, dict): return "工具已返回结果"
|
||||
content = output.get("content")
|
||||
if isinstance(content, list):
|
||||
for part in content:
|
||||
if isinstance(part, dict) and isinstance(part.get("text"), str):
|
||||
try:
|
||||
parsed = json.loads(part["text"])
|
||||
if isinstance(parsed, dict): return public_tool_result(parsed)
|
||||
except ValueError: pass
|
||||
parts = []
|
||||
if output.get("kind") == "quality_investigation":
|
||||
current = output.get("current", {})
|
||||
parts.append(f"全量统计 {current.get('totalRows', 0)} 行")
|
||||
proof = current.get("sourceVerification") or {}
|
||||
if proof: parts.append(f"原表核验 {proof.get('verifiedRows', 0)}/{proof.get('expectedRows', 0)} 行,差异 {proof.get('mismatchRows', 0)} 行")
|
||||
for key in ("evidenceRef", "evidenceId"):
|
||||
ref = output.get(key)
|
||||
if isinstance(ref, str) and re.fullmatch(r"[A-Za-z0-9_.:/#-]{1,160}", ref):
|
||||
parts.append("证据:" + ref); break
|
||||
if isinstance(output.get("rows"), list): parts.append(f"返回 {len(output['rows'])} 条结果")
|
||||
if isinstance(output.get("sourceRows"), int): parts.append(f"来源 {output['sourceRows']} 行")
|
||||
coverage = output.get("coverage")
|
||||
if isinstance(coverage, dict) and coverage.get("available") is False: parts.append("当前来源覆盖不足")
|
||||
reconciliation = [row for key in ("categoryReconciliation", "comparisonCategoryReconciliation")
|
||||
for row in (output[key] if isinstance(output.get(key), list) else [])]
|
||||
if reconciliation and any(isinstance(row, dict) and row.get("reconciliationStatus") not in ("RECONCILED", "EXPECTED_TOTALS_ONLY") for row in reconciliation):
|
||||
parts.append("细分与正式大类未对账:仅作为变化线索,不能据此判定正式报废主因")
|
||||
if output.get("rowsTruncated") is True or output.get("truncated") is True or output.get("pairedTruncated") is True: parts.append("仅覆盖返回集合,不代表全量排名")
|
||||
def number(value: Any) -> float | None:
|
||||
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
return float(value) if math.isfinite(value) else None
|
||||
return None
|
||||
|
||||
def metric_summary(snapshot: Any, prefix: str = "") -> None:
|
||||
if not isinstance(snapshot, dict): return
|
||||
rate = number(snapshot.get("compositeRate"))
|
||||
if rate is not None: parts.append(f"{prefix}综合合格率 {rate * 100:.2f}%")
|
||||
for stage, label in (("black", "黑片"), ("bright", "亮片")):
|
||||
metric = snapshot.get(stage)
|
||||
if not isinstance(metric, dict): continue
|
||||
weight = number(metric.get("scrapWeight"))
|
||||
if weight is not None: parts.append(f"{prefix}{label}报废 {weight:,.1f} kg")
|
||||
metric_summary(output.get("summary"))
|
||||
metric_summary(output.get("current"), "本期")
|
||||
metric_summary(output.get("comparison"), "对照期")
|
||||
rows = output.get("rows")
|
||||
if isinstance(rows, list) and rows and isinstance(rows[0], dict):
|
||||
label, weight = rows[0].get("label"), number(rows[0].get("weight"))
|
||||
if isinstance(label, str) and weight is not None:
|
||||
prefix = "来源细分" if output.get("grain") == "source_defect_weight" else "返回项"
|
||||
parts.append(f"首条{prefix}:{public_progress_text(label)[:160]} {weight:,.1f} kg")
|
||||
return ";".join(parts) or "工具已返回结果;可继续核查"
|
||||
|
||||
|
||||
def tool_operation_key(tool: str, raw_input: Any, *, complete_defects: bool = False) -> str:
|
||||
value = json.loads(json.dumps(raw_input)) if isinstance(raw_input, dict) else {}
|
||||
if tool == "read" and set(value) == {"path"} and value["path"] in ("/RULES.md", "/agent/mcps/quality/quality_data.json"):
|
||||
# The native provider sometimes uses `path` before correcting it to read's
|
||||
# real `file_path` parameter. Only the same known static file can recover it.
|
||||
value = {"file_path": value["path"]}
|
||||
if tool == "mcp_call" and value.get("tool") == "quality_data":
|
||||
args = value.get("arguments")
|
||||
if isinstance(args,dict) and args.get("scope")=="overall" and isinstance(args.get("filters"),dict) and args["filters"].get("group"):
|
||||
# Rejected conflicting scope is recovered only by the successful
|
||||
# same group query after the redundant overall scope is removed.
|
||||
args.pop("scope")
|
||||
if isinstance(args, dict) and args.get("mode") == "compare" and args.get("view") == "overall":
|
||||
# `compare` already operates on the selected overall scope; an explicit
|
||||
# overall view is the same investigation when the model corrects it.
|
||||
args.pop("view")
|
||||
if isinstance(args,dict) and args.get("mode")=="defects" and args.get("dimension")=="defect":
|
||||
if args.get("defect")=="all":args.pop("defect")
|
||||
if complete_defects:args.pop("limit",None)
|
||||
encoded = json.dumps([tool, value], sort_keys=True, ensure_ascii=False)
|
||||
return hashlib.sha256(encoded.encode()).hexdigest()
|
||||
|
||||
|
||||
def complete_defect_result(output: Any) -> bool:
|
||||
if isinstance(output,str):
|
||||
try:output=json.loads(output)
|
||||
except ValueError:return False
|
||||
if not isinstance(output,dict):return False
|
||||
if isinstance(output.get("content"),list):
|
||||
return any(complete_defect_result(part.get("text")) for part in output["content"] if isinstance(part,dict))
|
||||
return (output.get("kind")=="quality_fine_defects" and output.get("rankingComplete") is True
|
||||
and output.get("truncated") is False and output.get("pairedTruncated",False) is False)
|
||||
|
||||
|
||||
class ConversationAccumulator:
|
||||
"""Decode public text/tool events, ignoring reasoning and raw tool payloads."""
|
||||
"""Keep provider-emitted reasoning separate from answers and tool payloads."""
|
||||
|
||||
def __init__(self, on_answer: Callable[[str], None] | None = None) -> None:
|
||||
self.blocks: dict[str, str] = {}
|
||||
@@ -428,10 +560,22 @@ class ConversationAccumulator:
|
||||
self.tool_error = False
|
||||
self.unattributed_tool_error = False
|
||||
self.tool_operation_keys: dict[int, str] = {}
|
||||
self.complete_defect_keys: dict[int, str] = {}
|
||||
self.error_event = False
|
||||
self.on_answer = on_answer
|
||||
self.chat_id: str | None = None
|
||||
self.done_received = False
|
||||
self.reasoning_blocks: dict[str, str] = {}
|
||||
self.reasoning_truncated = False
|
||||
self.timeline: list[dict[str, Any]] = []
|
||||
self.timeline_text: dict[str, dict[str, Any]] = {}
|
||||
self.timeline_segments: dict[int, str] = {}
|
||||
|
||||
def record_event(self, kind: str, **fields: Any) -> dict[str, Any]:
|
||||
entry = {"sequence": (self.timeline[-1]["sequence"] if self.timeline else 0) + 1, "kind": kind, "at": datetime.now(timezone.utc).isoformat(), **fields}
|
||||
if len(self.timeline) < 3000:
|
||||
self.timeline.append(entry)
|
||||
return entry
|
||||
|
||||
def feed(self, event: dict[str, Any]) -> None:
|
||||
kind = event.get("type")
|
||||
@@ -439,6 +583,13 @@ class ConversationAccumulator:
|
||||
value = (event.get("data") or {}).get("id") if isinstance(event.get("data"), dict) else None
|
||||
if isinstance(value, str) and value and len(value) <= 256:
|
||||
self.chat_id = value
|
||||
elif kind == "reasoning-delta":
|
||||
block_id = event.get("id") if isinstance(event.get("id"), str) else "reasoning"
|
||||
delta = event.get("delta")
|
||||
if isinstance(delta, str):
|
||||
remaining = max(0, 200_000 - sum(len(value) for value in self.reasoning_blocks.values()))
|
||||
self.reasoning_blocks[block_id] = self.reasoning_blocks.get(block_id, "") + delta[:remaining]
|
||||
self.reasoning_truncated = self.reasoning_truncated or len(delta) > remaining
|
||||
elif kind == "text-start":
|
||||
block_id = event.get("id")
|
||||
if isinstance(block_id, str) and block_id:
|
||||
@@ -455,23 +606,37 @@ class ConversationAccumulator:
|
||||
delta = event.get("delta")
|
||||
if isinstance(delta, str):
|
||||
self.blocks[block_id] += delta
|
||||
segment = self.timeline_text.get(block_id)
|
||||
if segment is None or not self.timeline or self.timeline[-1] is not segment:
|
||||
segment = self.record_event("assistant", text="")
|
||||
self.timeline_text[block_id] = segment
|
||||
sequence = segment["sequence"]
|
||||
self.timeline_segments[sequence] = self.timeline_segments.get(sequence, "") + delta
|
||||
segment["text"] = public_progress_text(self.timeline_segments[sequence])
|
||||
if self.on_answer:
|
||||
self.on_answer(self.blocks[block_id])
|
||||
elif kind == "finish":
|
||||
reason = event.get("finishReason")
|
||||
if isinstance(reason, str):
|
||||
self.finish_reasons.append(reason)
|
||||
elif kind == "tool-input-available":
|
||||
elif kind in ("tool-input-available", "tool-input-error"):
|
||||
tool_name = event.get("toolName")
|
||||
if isinstance(tool_name, str):
|
||||
call_id = event.get("toolCallId")
|
||||
if isinstance(call_id, str) and any(c.get("toolCallId") == call_id for c in self.tool_calls): return
|
||||
call = {"tool": tool_name, "status": "started", "startedAt": datetime.now(timezone.utc).isoformat(),
|
||||
**public_tool_call(tool_name, event.get("input"))}
|
||||
if isinstance(call_id, str):
|
||||
call["toolCallId"] = call_id
|
||||
self.tool_calls.append(call)
|
||||
self.record_event("tool_start", tool=tool_name, toolCallId=call.get("toolCallId", ""), label=call["label"], input=call.get("input", {}), status="started")
|
||||
if isinstance(event.get("input"), dict):
|
||||
self.tool_operation_keys[id(call)] = tool_operation_key(tool_name, event["input"])
|
||||
self.complete_defect_keys[id(call)] = tool_operation_key(tool_name,event["input"],complete_defects=True)
|
||||
if kind == "tool-input-error":
|
||||
self.tool_error = True
|
||||
call.update(status="failed",finishedAt=datetime.now(timezone.utc).isoformat(),outputSummary="工具参数未通过校验")
|
||||
self.record_event("tool_result",tool=tool_name,toolCallId=call.get("toolCallId", ""),label=call["label"],status="failed",text=call["outputSummary"])
|
||||
elif kind in ("tool-output-available", "tool-result"):
|
||||
call_id = event.get("toolCallId")
|
||||
output = event.get("output")
|
||||
@@ -491,13 +656,17 @@ class ConversationAccumulator:
|
||||
matched = True
|
||||
item["status"] = "failed" if _contains_error_flag(output) else "completed"
|
||||
item["finishedAt"] = datetime.now(timezone.utc).isoformat()
|
||||
item["outputSummary"] = "工具返回错误,需要调整后继续" if item["status"] == "failed" else "已返回结果"
|
||||
item["outputSummary"] = public_tool_failure(output) if item["status"] == "failed" else public_tool_result(output)
|
||||
self.record_event("tool_result", tool=item["tool"], toolCallId=item.get("toolCallId", ""), label=item["label"], status=item["status"], text=item["outputSummary"], evidenceChecks=public_evidence_checks(output) if not output_failed else {})
|
||||
if not output_failed:
|
||||
key = self.tool_operation_keys.get(id(item))
|
||||
complete_key=self.complete_defect_keys.get(id(item)) if complete_defect_result(output) else None
|
||||
for previous in self.tool_calls:
|
||||
if previous is item:
|
||||
break
|
||||
if key is not None and previous["status"] == "failed" and self.tool_operation_keys.get(id(previous)) == key:
|
||||
same=(key is not None and self.tool_operation_keys.get(id(previous))==key)
|
||||
complete_same=(complete_key is not None and self.complete_defect_keys.get(id(previous))==complete_key)
|
||||
if previous["status"] == "failed" and (same or complete_same):
|
||||
previous["recovered"] = True
|
||||
previous["outputSummary"] = "调整调用后已重试成功"
|
||||
break
|
||||
@@ -510,11 +679,13 @@ class ConversationAccumulator:
|
||||
call_id = event.get("toolCallId")
|
||||
if isinstance(call_id, str):
|
||||
for item in reversed(self.tool_calls):
|
||||
if item.get("toolCallId") == call_id and item["status"] == "started":
|
||||
if item.get("toolCallId") == call_id and item["status"] in ("started", "failed"):
|
||||
matched = True
|
||||
if item["status"] == "failed": break
|
||||
item["status"] = "failed"
|
||||
item["finishedAt"] = datetime.now(timezone.utc).isoformat()
|
||||
item["outputSummary"] = "本次调用未成功"
|
||||
self.record_event("tool_result", tool=item["tool"], toolCallId=call_id, label=item["label"], status="failed", text="本次调用未成功")
|
||||
break
|
||||
if not matched:
|
||||
self.unattributed_tool_error = True
|
||||
@@ -523,6 +694,10 @@ class ConversationAccumulator:
|
||||
elif kind == "[DONE]":
|
||||
self.done_received = True
|
||||
|
||||
@property
|
||||
def model_reasoning(self) -> str:
|
||||
return "\n\n".join(self.reasoning_blocks.values())
|
||||
|
||||
@property
|
||||
def answer(self) -> str:
|
||||
for block_id in reversed(self.block_order):
|
||||
@@ -727,7 +902,7 @@ def _config_fingerprint(model_base: str, model_key: str, model_name: str) -> str
|
||||
paths = [TEMPLATES / "RULES.md", TEMPLATES / "agent" / "prompts" / "system.md",
|
||||
ROOT / "scripts" / "nao_quality_runtime.py", ROOT / "scripts" / "nao_quality_runtime_mcp.py",
|
||||
ROOT / "scripts" / "nao_quality_tools.py", ROOT / "scripts" / "nao_quality_mcp.py",
|
||||
ROOT / "scripts" / "nao_model_settings.py"]
|
||||
ROOT / "scripts" / "nao_model_settings.py", ROOT / "scripts" / "nao_evidence_finalizer.py", ROOT / "scripts" / "nao_evidence_report.py"]
|
||||
digest = hashlib.sha256()
|
||||
for path in paths:
|
||||
digest.update(str(path.relative_to(ROOT)).encode())
|
||||
@@ -817,7 +992,7 @@ def _write_project(actor_root: Path, session_id: str, model_name: str, *,
|
||||
f" - id: {json.dumps(model_name, ensure_ascii=False)}\n"
|
||||
" default: true\n"
|
||||
" settings:\n"
|
||||
" maxOutputTokens: 8192\n"
|
||||
f" maxOutputTokens: {32768 if model_name == 'mimo-v2.6-flash' else 8192}\n"
|
||||
" temperature: 0.2\n"
|
||||
" reasoningEffort: low\n"
|
||||
)
|
||||
@@ -1636,6 +1811,7 @@ def _sse_request(
|
||||
emit({"type": "answer", "answer": value})
|
||||
|
||||
accumulator = ConversationAccumulator(publish_answer)
|
||||
last_reasoning_emit = 0.0
|
||||
accumulator.chat_id = chat_id
|
||||
stopper.set_chat_id(chat_id)
|
||||
stopper.start()
|
||||
@@ -1668,11 +1844,17 @@ def _sse_request(
|
||||
session_state.set_chat_id(session_id, accumulator.chat_id)
|
||||
stopper.set_chat_id(accumulator.chat_id)
|
||||
kind = event.get("type")
|
||||
if kind in ("tool-input-available", "tool-output-available", "tool-result", "tool-output-error"):
|
||||
count = len(accumulator.tool_calls)
|
||||
latest = accumulator.tool_calls[-1] if count else {}
|
||||
emit({"type": "progress", "message": latest.get("label", "正在分析质量数据…"),
|
||||
"toolCount": count, "toolCalls": accumulator.tool_calls})
|
||||
if kind in ("text-delta", "text-end", "tool-input-available", "tool-output-available", "tool-result", "tool-output-error"):
|
||||
now = time.monotonic()
|
||||
if kind != "text-delta" or now - last_reasoning_emit >= 0.35:
|
||||
last_reasoning_emit = now
|
||||
latest = accumulator.tool_calls[-1] if accumulator.tool_calls else {}
|
||||
emit({"type": "progress", "message": latest.get("label", "正在整理分析说明…"),
|
||||
"toolCount": len(accumulator.tool_calls), "toolCalls": accumulator.tool_calls,
|
||||
"timeline": accumulator.timeline})
|
||||
elif kind == "reasoning-delta" and time.monotonic() - last_reasoning_emit >= 15:
|
||||
last_reasoning_emit = time.monotonic()
|
||||
emit({"type":"progress","message":"模型正在整理已返回的查询证据…","toolCount":len(accumulator.tool_calls),"toolCalls":accumulator.tool_calls,"timeline":accumulator.timeline})
|
||||
# A clean native finish or [DONE] closes the task. A plain EOF can leave
|
||||
# the upstream model task alive, so stop it before returning to Java.
|
||||
if not stopper.cause and not accumulator.done_received and "stop" not in accumulator.finish_reasons:
|
||||
@@ -1762,23 +1944,78 @@ def run_turn(payload: dict[str, Any], *, stdout: Any = sys.stdout, stdin: Any =
|
||||
actor_root, request["sessionId"], expected_actor_id=request["actorId"])
|
||||
# The model process receives only NAO's configured model credential. The delegated
|
||||
# user token remains in access.json, read only by the MCP shim.
|
||||
selected_connection = (model_base, model_key, model_name)
|
||||
del model_base, model_key
|
||||
client = _authenticate(actor_root, base_url)
|
||||
state = SessionState(actor_root, request["actorId"], request["sessionId"])
|
||||
native_chat_id = state.get_chat_id(request["sessionId"])
|
||||
emit({"type": "progress", "message": "正在查询质量中心并整理结论…"})
|
||||
emit({"type": "progress", "message": "正在查询质量数据分析平台并整理结论…"})
|
||||
|
||||
cancel_event = threading.Event()
|
||||
def request_cancel() -> None:
|
||||
cancel_event.set()
|
||||
_input_cancel_listener(stdin, request_cancel)
|
||||
|
||||
prior_evidence_files = frozenset(path.name for path in (actor_root / "evidence").glob("nao-quality-*.json"))
|
||||
visible_answer_path = actor_root / "private" / "last-visible-answer.json"
|
||||
if native_chat_id and _require_private_regular_file(visible_answer_path):
|
||||
previous_visible = _read_json(visible_answer_path)
|
||||
if (isinstance(previous_visible, dict) and previous_visible.get("releaseId") == request["releaseId"]
|
||||
and previous_visible.get("sessionId") == request["sessionId"]
|
||||
and isinstance(previous_visible.get("answer"), str)):
|
||||
context = {**(request["context"] if isinstance(request["context"], dict) else {}),
|
||||
"lastVisibleAnswer": previous_visible["answer"]}
|
||||
if len(json.dumps(context, ensure_ascii=False)) <= MAX_CONTEXT_CHARS:
|
||||
request["context"] = context
|
||||
|
||||
accumulator, status, stop_reason, stop_succeeded = _sse_request(
|
||||
client=client, base_url=base_url, model=model_name, question=request["question"],
|
||||
release_id=request["releaseId"], context=request["context"], chat_id=native_chat_id,
|
||||
session_state=state, session_id=request["sessionId"], emit=emit,
|
||||
actor_root=actor_root, cancel_event=cancel_event,
|
||||
timeout=480 if model_name == "mimo-v2.6-flash" else TURN_TIMEOUT_SECONDS,
|
||||
)
|
||||
from nao_evidence_finalizer import eligible, evidence_summaries, synthesize, coverage_sufficient, FinalizationUnavailable
|
||||
finalized = False
|
||||
if eligible(model_name, status, stop_reason, accumulator.tool_calls, cancel_event.is_set(), stop_succeeded):
|
||||
final_call = None
|
||||
try:
|
||||
native_answer = accumulator.answer
|
||||
native_completed = status == "COMPLETED"
|
||||
evidence = evidence_summaries(actor_root / "evidence", request["releaseId"], exclude_files=prior_evidence_files)
|
||||
if native_completed and not any(d["result"].get("kind")=="quality_comparison" for d in evidence):
|
||||
raise FinalizationUnavailable("本轮原生答复已完成,无期间比较需要整理")
|
||||
# An administrator may switch profiles while this turn runs. Its
|
||||
# one synthesis uses the original connection, just like native tools.
|
||||
selected_base, selected_key, selected_name = selected_connection
|
||||
if cancel_event.is_set(): raise FinalizationUnavailable("已取消")
|
||||
final_call = {"tool":"model.finalize", "toolCallId":"finalize-"+request["turnId"], "label":"整理已查询证据", "status":"started", "startedAt":datetime.now(timezone.utc).isoformat()}
|
||||
accumulator.tool_calls.append(final_call)
|
||||
accumulator.record_event("tool_start",tool=final_call["tool"],toolCallId=final_call["toolCallId"],label=final_call["label"],status="started")
|
||||
emit({"type":"progress","message":"查询证据已返回,正在进行一次有限的最终答复整理…","toolCalls":accumulator.tool_calls,"toolCount":len(accumulator.tool_calls),"timeline":accumulator.timeline})
|
||||
final = synthesize(base_url=selected_base,api_key=selected_key,model=selected_name,question=request["question"],evidence=evidence,cancel_event=cancel_event)
|
||||
del selected_key
|
||||
if cancel_event.is_set(): raise FinalizationUnavailable("已取消")
|
||||
final_call.update(status="completed",finishedAt=datetime.now(timezone.utc).isoformat(),outputSummary="已按本轮真实查询证据生成最终答复")
|
||||
accumulator.record_event("tool_result",tool=final_call["tool"],toolCallId=final_call["toolCallId"],label=final_call["label"],status="completed",text=final_call["outputSummary"])
|
||||
accumulator.blocks["evidence-final"] = final["answer"]
|
||||
accumulator.block_order.append("evidence-final")
|
||||
# Keep the final answer once. The preceding native draft is not a
|
||||
# second business answer after the verified report replaces it.
|
||||
accumulator.timeline = [entry for entry in accumulator.timeline
|
||||
if not (entry.get("kind") == "assistant" and native_answer
|
||||
and entry.get("text") == public_progress_text(native_answer))]
|
||||
accumulator.record_event("assistant",text=public_progress_text(final["answer"]))
|
||||
status = "COMPLETED" if final["evidenceSufficient"] and coverage_sufficient(evidence,request["question"]) else "PARTIAL"
|
||||
_atomic_json(actor_root / "finalization.json", {"turnId":request["turnId"],"status":status,"nativeStopReason":stop_reason,"model":final["model"],"requestParameters":{"max_completion_tokens":4096,"thinking":{"type":"disabled"},"stream":False},"evidenceRefs":[d["evidenceRef"] for d in evidence],"usage":final["usage"],"finishReason":final["finishReason"],"modelDeclaredEvidenceSufficient":final["evidenceSufficient"],"serverCoverageSufficient":coverage_sufficient(evidence,request["question"]),"missingEvidence":final["missingEvidence"]})
|
||||
stop_reason, finalized = "evidence_finalized" if status=="COMPLETED" else "evidence_incomplete", True
|
||||
accumulator.finish_reasons.append("stop")
|
||||
except (FinalizationUnavailable, OSError, ValueError) as error:
|
||||
_atomic_json(actor_root / "finalization.json", {"turnId":request["turnId"],"status":"CANCELLED" if cancel_event.is_set() else "COMPLETED" if status=="COMPLETED" else "PARTIAL","nativeStopReason":stop_reason,"reason":str(error) if isinstance(error,FinalizationUnavailable) else "证据整理不可用"})
|
||||
if final_call is not None:
|
||||
final_call.update(status="failed",finishedAt=datetime.now(timezone.utc).isoformat(),outputSummary="有限收尾未完成;查询证据和过程已保留")
|
||||
accumulator.record_event("tool_result",tool=final_call["tool"],toolCallId=final_call["toolCallId"],label=final_call["label"],status="failed",text=final_call["outputSummary"])
|
||||
if cancel_event.is_set(): status,stop_reason="CANCELLED","用户停止"
|
||||
answer = accumulator.answer
|
||||
if answer:
|
||||
emit({"type": "answer", "answer": answer})
|
||||
@@ -1789,9 +2026,14 @@ def run_turn(payload: dict[str, Any], *, stdout: Any = sys.stdout, stdin: Any =
|
||||
report_markdown, report_html = None, None
|
||||
if status == "COMPLETED" and not answer:
|
||||
status, stop_reason = "FAILED", "empty_answer"
|
||||
if status == "COMPLETED" and answer:
|
||||
_atomic_json(visible_answer_path, {"releaseId":request["releaseId"],"sessionId":request["sessionId"],
|
||||
"turnId":request["turnId"],"answer":answer})
|
||||
result = {
|
||||
"type": "result", "status": status, "engine": "NAO", "answer": answer,
|
||||
"nativeChatId": accumulator.chat_id,
|
||||
"completionMethod": "bounded_evidence_finalization" if finalized else "native",
|
||||
"timeline": accumulator.timeline,
|
||||
"toolCalls": accumulator.tool_calls,
|
||||
"stopReason": stop_reason,
|
||||
"nativeStopSucceeded": stop_succeeded,
|
||||
|
||||
Reference in New Issue
Block a user