Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(agent): make tool error guidance neutral (#6227)
chengyongru841d2b880ca7
diff --git a/nanobot/agent/tools/execution.py b/nanobot/agent/tools/execution.pyindex e81f45c4d..f0df01ed8 100644--- a/nanobot/agent/tools/execution.py+++ b/nanobot/agent/tools/execution.py@@ -13,14 +13,13 @@ from loguru import loggerfrom nanobot.agent.hook import AgentHook, AgentHookContextfrom nanobot.agent.tools.context import tool_log_content_allowedfrom nanobot.agent.tools.file_state import file_read_context-from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result+from nanobot.agent.tools.registry import ToolRegistry, is_tool_error_result, with_tool_error_hintfrom nanobot.providers.base import ToolCallRequestfrom nanobot.utils.runtime import (repeated_external_lookup_error,repeated_workspace_violation_error,)-_RETRY_HINT = "\n\n[Analyze the error above and try a different approach.]"# SSRF is a hard security block at the tool boundary, but the agent turn# should recover conversationally instead of aborting the runtime._SSRF_MARKERS: tuple[str, ...] = (@@ -47,13 +46,6 @@ _WORKSPACE_VIOLATION_MARKERS: tuple[str, ...] = ()-def _with_retry_hint(payload: str) -> str:- """Append the recovery hint exactly once."""- if payload.endswith(_RETRY_HINT):- return payload- return payload + _RETRY_HINT--async def execute_tool_calls(tools: ToolRegistry,tool_calls: list[ToolCallRequest],@@ -132,7 +124,7 @@ async def _execute_tool_call("status": "error","detail": "repeated external lookup blocked",}- return _with_retry_hint(lookup_error), event+ return with_tool_error_hint(lookup_error), eventprepare_call = cast(Callable[[str, Any], object] | None,@@ -146,7 +138,7 @@ async def _execute_tool_call(if len(prepared_tuple) == 3:tool, params, prep_error = cast(tuple[Any, Any, str | None], prepared_tuple)if prep_error:- payload = _with_retry_hint(prep_error)+ payload = with_tool_error_hint(prep_error)event = {"name": tool_call.name,"status": "error",@@ -182,7 +174,7 @@ async def _execute_tool_call("status": "error","detail": str(exc),}- payload = _with_retry_hint(f"Error: {type(exc).__name__}: {exc}")+ payload = with_tool_error_hint(f"Error: {type(exc).__name__}: {exc}")handled = _classify_violation(raw_text=str(exc),soft_payload=payload,@@ -196,7 +188,7 @@ async def _execute_tool_call(if is_tool_error_result(result):await hook.on_execute_tool_error(context, tool_call, tool, params, result)- payload = _with_retry_hint(result)+ payload = with_tool_error_hint(result)event = {"name": tool_call.name,"status": "error",diff --git a/nanobot/agent/tools/registry.py b/nanobot/agent/tools/registry.pyindex d4c2f2ebf..ba39a5823 100644--- a/nanobot/agent/tools/registry.py+++ b/nanobot/agent/tools/registry.py@@ -11,6 +11,18 @@ from nanobot.agent.tools.context import ContextAware, current_request_contextif TYPE_CHECKING:from nanobot.runtime_context import RuntimeContextProvider+_ERROR_HINT = (+ "\n\n[Consider this result in the context of the user's goal "+ "and decide whether and how to proceed.]"+)+++def with_tool_error_hint(payload: str) -> str:+ """Append tool error guidance exactly once."""+ if payload.endswith(_ERROR_HINT):+ return payload+ return payload + _ERROR_HINT+def is_tool_error_result(result: Any) -> bool:return isinstance(result, ToolResult) and result.is_error@@ -186,19 +198,18 @@ class ToolRegistry:async def execute(self, name: str, params: Any) -> Any:"""Execute a tool by name with given parameters."""- hint = "\n\n[Analyze the error above and try a different approach.]"tool, params, error = self.prepare_call(name, params)if error:- return ToolResult.error(str(error) + hint)+ return ToolResult.error(with_tool_error_hint(str(error)))try:assert tool is not None # guarded by prepare_call()result = await tool.execute(**params)if is_tool_error_result(result):- return ToolResult.error(str(result) + hint)+ return ToolResult.error(with_tool_error_hint(str(result)))return resultexcept Exception as e:- return ToolResult.error(f"Error executing {name}: {str(e)}" + hint)+ return ToolResult.error(with_tool_error_hint(f"Error executing {name}: {str(e)}"))@propertydef tool_names(self) -> list[str]:diff --git a/tests/agent/test_runner_errors.py b/tests/agent/test_runner_errors.pyindex de2c8b981..eec51f57e 100644--- a/tests/agent/test_runner_errors.py+++ b/tests/agent/test_runner_errors.py@@ -56,16 +56,22 @@ async def test_runner_returns_tool_exception_to_model_for_recovery():{"name": "list_dir", "status": "error", "detail": "boom"}]tool_message = next(message for message in result.messages if message.get("role") == "tool")- retry_hint = "[Analyze the error above and try a different approach.]"+ error_hint = (+ "[Consider this result in the context of the user's goal "+ "and decide whether and how to proceed.]"+ )assert "Error: RuntimeError: boom" in tool_message["content"]- assert tool_message["content"].count(retry_hint) == 1+ assert tool_message["content"].count(error_hint) == 1@pytest.mark.asyncio-async def test_tool_execution_does_not_duplicate_existing_retry_hint():- retry_hint = "\n\n[Analyze the error above and try a different approach.]"+async def test_tool_execution_does_not_duplicate_existing_error_hint():+ error_hint = (+ "\n\n[Consider this result in the context of the user's goal "+ "and decide whether and how to proceed.]"+ )tools = SimpleNamespace(- execute=AsyncMock(return_value=ToolResult.error("Error: boom" + retry_hint)),+ execute=AsyncMock(return_value=ToolResult.error("Error: boom" + error_hint)),)results, events = await execute_tool_calls(@@ -78,8 +84,8 @@ async def test_tool_execution_does_not_duplicate_existing_retry_hint():context=AgentHookContext(iteration=0, messages=[]),)- assert results == ["Error: boom" + retry_hint]- assert results[0].count(retry_hint) == 1+ assert results == ["Error: boom" + error_hint]+ assert results[0].count(error_hint) == 1assert events[0]["status"] == "error"@@ -300,15 +306,18 @@ async def test_runner_recognizes_web_fetch_errors(monkeypatch, url, ssrf):content = tool_message["content"]assert content.startswith(str(raw_error) + "\n\n")assert json.JSONDecoder().raw_decode(content)[0] == raw_payload- retry_hint = "[Analyze the error above and try a different approach.]"+ error_hint = (+ "[Consider this result in the context of the user's goal "+ "and decide whether and how to proceed.]"+ )if ssrf:assert result.tool_events[0]["detail"].startswith("ssrf_violation:")assert "non-bypassable security boundary" in contentassert "Do not retry" in contentassert "tools.ssrfWhitelist" in content- assert retry_hint not in content+ assert error_hint not in contentelse:- assert content.count(retry_hint) == 1+ assert content.count(error_hint) == 1@pytest.mark.asynciodiff --git a/tests/tools/test_mcp_tool.py b/tests/tools/test_mcp_tool.pyindex 0ac205d3b..1989489bc 100644--- a/tests/tools/test_mcp_tool.py+++ b/tests/tools/test_mcp_tool.py@@ -626,7 +626,7 @@ async def test_execute_contains_malformed_success_result() -> None:@pytest.mark.asyncio-async def test_registry_adds_retry_hint_to_malformed_mcp_result() -> None:+async def test_registry_adds_error_hint_to_malformed_mcp_result() -> None:async def call_tool(_name: str, arguments: dict) -> object:return SimpleNamespace(content=None)@@ -638,7 +638,10 @@ async def test_registry_adds_retry_hint_to_malformed_mcp_result() -> None:assert is_tool_error_result(result)assert "MCP tool returned malformed content" in result- assert "Analyze the error above and try a different approach" in result+ assert (+ "[Consider this result in the context of the user's goal "+ "and decide whether and how to proceed.]"+ ) in result@pytest.mark.asynciodiff --git a/tests/tools/test_tool_registry.py b/tests/tools/test_tool_registry.pyindex 14913fc15..26949983c 100644--- a/tests/tools/test_tool_registry.py+++ b/tests/tools/test_tool_registry.py@@ -3,6 +3,8 @@ from __future__ import annotationsfrom typing import Anyfrom unittest.mock import AsyncMock+import pytest+from nanobot.agent.tools.base import Tool, ToolResultfrom nanobot.agent.tools.filesystem import ReadFileToolfrom nanobot.agent.tools.registry import ToolRegistry@@ -269,7 +271,8 @@ async def test_registry_preserves_successful_exec_output_that_starts_with_error(assert result == output-async def test_registry_uses_structured_tool_result_for_errors() -> None:[email protected]("already_hinted", [False, True])+async def test_registry_uses_structured_tool_result_for_errors(already_hinted: bool) -> None:registry = ToolRegistry()output = "Error: plain tool output, not a structured failure"raw_tool = _FakeTool("raw_output")@@ -280,16 +283,20 @@ async def test_registry_uses_structured_tool_result_for_errors() -> None:assert raw_result == output+ error_hint = (+ "\n\n[Consider this result in the context of the user's goal "+ "and decide whether and how to proceed.]"+ )+ error_content = "Error: real failure" + (error_hint if already_hinted else "")failing_tool = _FakeTool("failing_tool")- failing_tool.execute = AsyncMock(return_value=ToolResult.error("Error: real failure"))+ failing_tool.execute = AsyncMock(return_value=ToolResult.error(error_content))registry.register(failing_tool)error_result = await registry.execute("failing_tool", {})assert isinstance(error_result, ToolResult)assert error_result.is_error- assert error_result.startswith("Error: real failure")- assert "[Analyze the error above" in error_result+ assert error_result == "Error: real failure" + error_hintdef test_get_definitions_returns_cached_result() -> None: