修复:智能分析空回答与工具结束条件冲突
统一自主分析工具范围与执行前校验,严格核验正常结束、最终正文和图表恢复状态,并显示空回答及恢复失败原因。 包含两次已上线修复及回归测试,保留已有回答与业务数据。 验证:1101 项 Python、469 项前端、97 项后端测试通过;前后端构建和真实模型、页面验收通过。
This commit is contained in:
@@ -62,20 +62,29 @@ def capability_context(task=None):
|
||||
}
|
||||
|
||||
|
||||
def apply_platform_tools(payload):
|
||||
"""Do not advertise a native SQL-result renderer for quality API evidence."""
|
||||
QUALITY_NATIVE_TOOLS = frozenset({'read', 'list', 'grep', 'search', 'mcp_call', 'mcp_connect'})
|
||||
|
||||
|
||||
def apply_platform_tools(payload, *, native_agent=False):
|
||||
"""Expose tools compatible with platform evidence and answer completion."""
|
||||
tools = payload.get('tools')
|
||||
if not isinstance(tools, list): return payload
|
||||
kept = [tool for tool in tools if not (isinstance(tool, dict)
|
||||
and isinstance(tool.get('function'), dict)
|
||||
and tool['function'].get('name') == 'display_chart')]
|
||||
if len(kept) == len(tools): return payload
|
||||
allowed = QUALITY_NATIVE_TOOLS if native_agent else QUALITY_NATIVE_TOOLS | {'story'}
|
||||
# Clarification/warehouse selection are upstream stop conditions with native
|
||||
# UI replies that this platform cannot consume. SQL, renderers and writers
|
||||
# also use a different data/artifact lifecycle. Unknown tools stay disabled.
|
||||
tools = tools if isinstance(tools, list) else []
|
||||
kept = [tool for tool in tools if isinstance(tool, dict) and tool.get('type') == 'function'
|
||||
and isinstance(tool.get('function'), dict) and isinstance(tool['function'].get('name'), str)
|
||||
and tool['function'].get('name') in allowed]
|
||||
if kept: payload['tools'] = kept
|
||||
else: payload.pop('tools', None)
|
||||
choice = payload.get('tool_choice')
|
||||
if ((isinstance(choice, dict) and (choice.get('function') or {}).get('name') == 'display_chart')
|
||||
kept_names = {tool['function']['name'] for tool in kept}
|
||||
choice_name = choice.get('function', {}).get('name') if isinstance(choice, dict) and isinstance(choice.get('function'), dict) else None
|
||||
if ((isinstance(choice, dict) and choice_name not in kept_names)
|
||||
or not kept and choice in ('auto', 'required')):
|
||||
payload.pop('tool_choice', None)
|
||||
if not kept: payload.pop('parallel_tool_calls', None)
|
||||
return payload
|
||||
|
||||
|
||||
|
||||
+50
-13
@@ -21,6 +21,10 @@ class _NoRedirect(HTTPRedirectHandler):
|
||||
return None
|
||||
|
||||
|
||||
class ToolPolicyError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class ModelGate:
|
||||
"""A stable per-session endpoint backed only by this turn's live delegation."""
|
||||
|
||||
@@ -41,7 +45,9 @@ class ModelGate:
|
||||
self._thinking = dict(thinking_options) if thinking_options is not None else None
|
||||
self._on_thinking = on_thinking
|
||||
self._native_turn_marker = native_turn_marker
|
||||
self.native_agent = False
|
||||
self.rejected_stale_requests = 0
|
||||
self.rejected_tool_calls = 0
|
||||
self._request_number = 0
|
||||
self._request_prefix = secrets.token_hex(4)
|
||||
self.request_audit = []
|
||||
@@ -92,9 +98,10 @@ class ModelGate:
|
||||
for message in messages)):
|
||||
with gate._audit_lock: gate.rejected_stale_requests += 1
|
||||
self.failure(403, '模型请求不属于当前轮次'); return
|
||||
decoded = gate.apply_thinking(decoded)
|
||||
from nao_agent_contract import apply_platform_tools
|
||||
decoded = apply_platform_tools(decoded)
|
||||
decoded = apply_platform_tools(decoded, native_agent=gate.native_agent)
|
||||
decoded = gate.apply_thinking(decoded)
|
||||
offered_tools = {tool['function']['name'] for tool in decoded.get('tools', [])}
|
||||
payload = json.dumps(decoded,ensure_ascii=False).encode()
|
||||
except (ValueError, OSError):
|
||||
self.failure(400, '模型请求格式无效'); return
|
||||
@@ -141,9 +148,10 @@ class ModelGate:
|
||||
thinking('start')
|
||||
# SSE termination is a transport concern even when no thinking
|
||||
# callback is installed (for example, native stream forwarding).
|
||||
observer = ProviderStream(lambda text:thinking('delta',text=text)) if gate._on_thinking or is_sse else None
|
||||
observer = ProviderStream(lambda text:thinking('delta',text=text))
|
||||
raw_json = bytearray()
|
||||
if not bridge:
|
||||
pending_wire = bytearray()
|
||||
if is_sse and not bridge:
|
||||
self.send_response(response.status)
|
||||
self.send_header('Content-Type', response.headers.get('Content-Type', 'application/json'))
|
||||
self.send_header('Cache-Control', 'no-store')
|
||||
@@ -161,21 +169,29 @@ class ModelGate:
|
||||
if time.monotonic() - checked_at >= 1:
|
||||
gate._check()
|
||||
checked_at = time.monotonic()
|
||||
if observer:
|
||||
if is_sse:observer.feed(chunk)
|
||||
else:raw_json.extend(chunk)
|
||||
if not bridge:
|
||||
self.wfile.write(chunk)
|
||||
self.wfile.flush()
|
||||
if is_sse:
|
||||
observer.feed(chunk)
|
||||
gate.check_returned_tools(observer, offered_tools)
|
||||
if not bridge:
|
||||
# A partial SSE line cannot be checked yet. Hold
|
||||
# it until its complete event has passed policy.
|
||||
pending_wire.extend(chunk)
|
||||
end=pending_wire.rfind(b'\n')+1
|
||||
if end:
|
||||
self.wfile.write(pending_wire[:end]);self.wfile.flush()
|
||||
del pending_wire[:end]
|
||||
else:raw_json.extend(chunk)
|
||||
# A provider may keep the HTTP connection alive with heartbeats
|
||||
# after its explicit terminal event. Do not wait for EOF, but
|
||||
# keep reading past finish_reason so the usage tail is preserved.
|
||||
if is_sse and observer.done:
|
||||
break
|
||||
gate._check()
|
||||
if observer:
|
||||
if is_sse:observer.finish()
|
||||
else:observer.document(json.loads(raw_json))
|
||||
if is_sse:observer.finish()
|
||||
else:observer.document(json.loads(raw_json))
|
||||
gate.check_returned_tools(observer, offered_tools, final=True)
|
||||
if is_sse and not bridge and pending_wire:
|
||||
self.wfile.write(pending_wire);self.wfile.flush()
|
||||
result = observer.completion() if bridge or is_sse else None
|
||||
stops = [row['finish_reason'] for row in observer.choices.values()] if observer else []
|
||||
thinking('end',finishReason='length' if 'length' in stops else (stops[-1] if stops else ''),interrupted=bool(observer and not stops))
|
||||
@@ -188,6 +204,15 @@ class ModelGate:
|
||||
self.send_response(200);self.send_header('Content-Type','application/json')
|
||||
self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(encoded)))
|
||||
self.end_headers();headers_sent=True;self.wfile.write(encoded);self.wfile.flush()
|
||||
elif not is_sse:
|
||||
self.send_response(response.status);self.send_header('Content-Type','application/json')
|
||||
self.send_header('Cache-Control','no-store');self.send_header('Content-Length',str(len(raw_json)))
|
||||
self.end_headers();headers_sent=True;self.wfile.write(raw_json);self.wfile.flush()
|
||||
except ToolPolicyError:
|
||||
if not headers_sent:self.failure(502,'模型返回了当前任务未开放的工具调用')
|
||||
else:
|
||||
with contextlib.suppress(OSError):
|
||||
self.wfile.write(b'data: {"error":{"message":"Tool call is unavailable for this task"}}\n\n');self.wfile.flush()
|
||||
except HTTPError as error:
|
||||
if not headers_sent:
|
||||
self.failure(error.code if 400 <= error.code <= 599 else 502, '模型接口暂不可用')
|
||||
@@ -230,6 +255,8 @@ class ModelGate:
|
||||
else:payload['reasoning_effort']=effort
|
||||
with self._audit_lock:
|
||||
if len(self.request_audit)<200:self.request_audit.append({'enabled':enabled,'effort':effort,
|
||||
'tools':[tool['function']['name'] for tool in payload.get('tools',[])],
|
||||
'nativeAgent':self.native_agent,
|
||||
'protocol':protocol,'stream':payload.get('stream',False),
|
||||
'maxCompletionTokens':payload.get('max_completion_tokens',payload.get('max_tokens')),
|
||||
'thinkingType':(payload.get('thinking') or {}).get('type'),
|
||||
@@ -237,6 +264,16 @@ class ModelGate:
|
||||
'reasoningEffort':payload.get('reasoning_effort',(payload.get('chat_template_kwargs') or {}).get('reasoning_effort'))})
|
||||
return payload
|
||||
|
||||
def check_returned_tools(self, observer, offered, *, final=False):
|
||||
for choice, tools in observer.tools.items():
|
||||
finished=final or bool(observer.choices.get(choice,{}).get('finish_reason')) or observer.done
|
||||
for tool in tools.values():
|
||||
name=tool.get('function',{}).get('name','')
|
||||
valid=(name in offered) if finished else (not name or any(allowed.startswith(name) for allowed in offered))
|
||||
if not valid:
|
||||
with self._audit_lock:self.rejected_tool_calls+=1
|
||||
raise ToolPolicyError('Unadvertised tool call')
|
||||
|
||||
def _check(self) -> None:
|
||||
if self._closed.is_set():
|
||||
raise PermissionError('模型授权已关闭')
|
||||
|
||||
@@ -112,7 +112,9 @@ def run_native_exploration(*, request, task, authority, actor_root, delegated, c
|
||||
and type(progress.get('noProgress')) is int and progress['noProgress'] >= 3)
|
||||
if controlled_no_progress:
|
||||
missing.append('连续三次没有取得新证据,调查已停止;其余线索尚未验证。')
|
||||
natural_finish = 'stop' in accumulator.finish_reasons and stop_succeeded is not False
|
||||
natural_finish = bool(accumulator.finish_reasons and accumulator.finish_reasons[-1] == 'stop'
|
||||
and stop_succeeded is not False
|
||||
and getattr(accumulator, 'final_answer_ready', True))
|
||||
corrected_tool_errors = (native_reason == 'mcp_error' and natural_finish
|
||||
and complete_scopes is not None and bool(documents)
|
||||
and not missing and not progress.get('halted'))
|
||||
|
||||
@@ -763,6 +763,17 @@ class ConversationAccumulator:
|
||||
return value
|
||||
return ""
|
||||
|
||||
@property
|
||||
def final_answer_ready(self) -> bool:
|
||||
if not self.answer or any(call.get('status') == 'started' for call in self.tool_calls):
|
||||
return False
|
||||
if not self.tool_calls:
|
||||
return True
|
||||
last_tool = max((i for i, entry in enumerate(self.timeline)
|
||||
if entry.get('kind') in ('tool_start', 'tool_result')), default=-1)
|
||||
return any(entry.get('kind') == 'assistant' and str(entry.get('text') or '').strip()
|
||||
for entry in self.timeline[last_tool + 1:])
|
||||
|
||||
def status(self, *, cancel_cause: str | None = None, stop_succeeded: bool | None = None,
|
||||
transport_failed: bool = False) -> tuple[str, str | None]:
|
||||
if cancel_cause == "user":
|
||||
@@ -781,18 +792,27 @@ class ConversationAccumulator:
|
||||
return ("PARTIAL" if self.answer else "FAILED", "transport_or_stream_error")
|
||||
if self.tool_error and (self.unattributed_tool_error or any(call["status"] == "failed" and not call.get("recovered") for call in self.tool_calls)):
|
||||
return ("PARTIAL" if self.answer else "FAILED", "mcp_error")
|
||||
if self.answer and (self.done_received or "stop" in self.finish_reasons):
|
||||
if (self.final_answer_ready and self.finish_reasons[-1] == 'stop'
|
||||
and stop_succeeded is not False):
|
||||
return "COMPLETED", "stop"
|
||||
return ("PARTIAL" if self.answer else "FAILED", "incomplete")
|
||||
|
||||
|
||||
def _contains_error_flag(value: Any) -> bool:
|
||||
if isinstance(value, dict):
|
||||
if value.get("isError") is True or value.get("error"):
|
||||
if (any(value.get(flag) is True for flag in ('isError', 'mcpValidationError', 'mcpAuthRequired'))
|
||||
or value.get('success') is False or value.get('error')):
|
||||
return True
|
||||
return any(_contains_error_flag(item) for item in value.values())
|
||||
# Inspect only known response envelopes. Rows, source cells, notes and
|
||||
# arbitrary JSON strings are business data, not nested tool outcomes.
|
||||
content = value.get('content')
|
||||
if isinstance(content, list) and any(isinstance(part, dict) and part.get('type') == 'text'
|
||||
and _contains_error_flag(part.get('text')) for part in content):
|
||||
return True
|
||||
return _contains_error_flag(value['structuredContent']) if isinstance(value.get('structuredContent'), dict) else False
|
||||
if isinstance(value, list):
|
||||
return any(_contains_error_flag(item) for item in value)
|
||||
return any(isinstance(part, dict) and part.get('type') == 'text'
|
||||
and _contains_error_flag(part.get('text')) for part in value)
|
||||
if isinstance(value, str) and len(value) <= 64 * 1024:
|
||||
stripped = value.strip()
|
||||
if stripped.startswith(("{", "[")):
|
||||
@@ -1922,6 +1942,10 @@ def _sse_request(
|
||||
ready_state: dict[str, Any] = {"identity": None, "since": None}
|
||||
|
||||
def completion_ready() -> bool:
|
||||
# The watchdog can observe a stale halted exploration state between a
|
||||
# natural model finish and the stream's trailing [DONE] marker.
|
||||
if accumulator.done_received or (accumulator.finish_reasons and accumulator.finish_reasons[-1] == 'stop'):
|
||||
return False
|
||||
if autonomous:
|
||||
progress_path = actor_root / 'private' / 'native-exploration-state.json'
|
||||
if not _require_private_regular_file(progress_path):
|
||||
@@ -2630,6 +2654,7 @@ def _run_turn(payload: dict[str, Any], *, stdout: Any = sys.stdout, stdin: Any =
|
||||
from nao_protocol_execution import execute
|
||||
request['_autonomousAnswer'] = protocol.get('autonomousEnabled') is True
|
||||
if authority['task'].get('executionMode') == 'native_agent':
|
||||
model_gate.native_agent = True
|
||||
from nao_native_run import run_native_exploration
|
||||
return run_native_exploration(request=request, task=authority['task'], authority=authority,
|
||||
actor_root=actor_root, delegated=delegated, connection=selected_connection,
|
||||
@@ -3108,6 +3133,7 @@ def _run_turn(payload: dict[str, Any], *, stdout: Any = sys.stdout, stdin: Any =
|
||||
if model_gate is not None:
|
||||
try:
|
||||
_atomic_json(actor_root/'private'/'last-model-audit.json',{'model':selected_model,'requests':model_gate.request_audit,
|
||||
'rejectedToolCalls':model_gate.rejected_tool_calls if isinstance(model_gate.rejected_tool_calls,int) else 0,
|
||||
'rejectedStaleRequests':model_gate.rejected_stale_requests if isinstance(model_gate.rejected_stale_requests,int) else 0})
|
||||
except (OSError,TypeError,ValueError):pass
|
||||
model_gate.close()
|
||||
|
||||
Reference in New Issue
Block a user