From a4c17c9aa64d12dc5950f0a36d7834e046355224 Mon Sep 17 00:00:00 2001 From: jxxghp Date: Sat, 12 Sep 2026 12:21:58 +0800 Subject: [PATCH] fix(agent): guide recovery after invocation outcomes --- app/agent/middleware/invocation.py | 12 ++++++++++-- tests/test_agent_invocation_middleware.py | 1 + 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/app/agent/middleware/invocation.py b/app/agent/middleware/invocation.py index e2eb9d55b..004c57fdb 100644 --- a/app/agent/middleware/invocation.py +++ b/app/agent/middleware/invocation.py @@ -102,9 +102,17 @@ class InvocationMiddleware(AgentMiddleware): # type: ignore[misc] @staticmethod def _message(request: ToolCallRequest, outcome: str, message: str, **extra: Any) -> ToolMessage: - """给模型明确结果状态,同时保留 LangChain 二态兼容字段。""" + """给模型明确结果状态和恢复动作,同时保留 LangChain 二态兼容字段。""" + recovery = extra.pop("recovery", None) + if recovery is None and outcome == "failed": + recovery = "根据错误信息修正输入或改用正确工具后重试;不要重复提交未确认的写入。" + elif recovery is None and outcome == "unknown": + recovery = "结果未知时先调用只读查询或 get_tool_execution 核验实际状态,不要直接重试写入。" + payload = {"execution_outcome": outcome, "message": message, **extra} + if recovery is not None: + payload["recovery"] = recovery return ToolMessage( - content=json.dumps({"execution_outcome": outcome, "message": message, **extra}, ensure_ascii=False), + content=json.dumps(payload, ensure_ascii=False), tool_call_id=str(request.tool_call.get("id") or ""), name=str(request.tool_call.get("name") or "unknown"), status="success" if outcome in {"succeeded", "pending"} else "error", diff --git a/tests/test_agent_invocation_middleware.py b/tests/test_agent_invocation_middleware.py index 52eba8c10..c916b5466 100644 --- a/tests/test_agent_invocation_middleware.py +++ b/tests/test_agent_invocation_middleware.py @@ -153,6 +153,7 @@ async def test_unknown_api_result_blocks_same_input_in_new_turn(invocation_runti replay = json.loads(_tool_messages(result)[-1].content) assert replay["execution_outcome"] == "unknown" assert replay["replayed"] is True + assert "先调用只读查询" in replay["recovery"] @pytest.mark.asyncio