fix(agent): make tool error guidance neutral (#6227)
* fix(agent): make tool error guidance neutral * refactor(tools): share tool error guidance
This commit is contained in:
1 parent
c24153db86
commit
841d2b880c
5 files changed
+55
-33
No files matched your search
@@ -13,14 +13,13 @@ from loguru import logger
|
|||||||
from nanobot.agent.hook import AgentHook, AgentHookContext
|
from nanobot.agent.hook import AgentHook, AgentHookContext
|
||||||
from nanobot.agent.tools.context import tool_log_content_allowed
|
from nanobot.agent.tools.context import tool_log_content_allowed
|
||||||
from nanobot.agent.tools.file_state import file_read_context
|
from 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_hint
|
||||||
from nanobot.providers.base import ToolCallRequest
|
from nanobot.providers.base import ToolCallRequest
|
||||||
from nanobot.utils.runtime import (
|
from nanobot.utils.runtime import (
|
||||||
repeated_external_lookup_error,
|
repeated_external_lookup_error,
|
||||||
repeated_workspace_violation_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
|
# SSRF is a hard security block at the tool boundary, but the agent turn
|
||||||
# should recover conversationally instead of aborting the runtime.
|
# should recover conversationally instead of aborting the runtime.
|
||||||
_SSRF_MARKERS: tuple[str, ...] = (
|
_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(
|
async def execute_tool_calls(
|
||||||
tools: ToolRegistry,
|
tools: ToolRegistry,
|
||||||
tool_calls: list[ToolCallRequest],
|
tool_calls: list[ToolCallRequest],
|
||||||
@@ -132,7 +124,7 @@ async def _execute_tool_call(
|
|||||||
"status": "error",
|
"status": "error",
|
||||||
"detail": "repeated external lookup blocked",
|
"detail": "repeated external lookup blocked",
|
||||||
}
|
}
|
||||||
return _with_retry_hint(lookup_error), event
|
return with_tool_error_hint(lookup_error), event
|
||||||
|
|
||||||
prepare_call = cast(
|
prepare_call = cast(
|
||||||
Callable[[str, Any], object] | None,
|
Callable[[str, Any], object] | None,
|
||||||
@@ -146,7 +138,7 @@ async def _execute_tool_call(
|
|||||||
if len(prepared_tuple) == 3:
|
if len(prepared_tuple) == 3:
|
||||||
tool, params, prep_error = cast(tuple[Any, Any, str | None], prepared_tuple)
|
tool, params, prep_error = cast(tuple[Any, Any, str | None], prepared_tuple)
|
||||||
if prep_error:
|
if prep_error:
|
||||||
payload = _with_retry_hint(prep_error)
|
payload = with_tool_error_hint(prep_error)
|
||||||
event = {
|
event = {
|
||||||
"name": tool_call.name,
|
"name": tool_call.name,
|
||||||
"status": "error",
|
"status": "error",
|
||||||
@@ -182,7 +174,7 @@ async def _execute_tool_call(
|
|||||||
"status": "error",
|
"status": "error",
|
||||||
"detail": str(exc),
|
"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(
|
handled = _classify_violation(
|
||||||
raw_text=str(exc),
|
raw_text=str(exc),
|
||||||
soft_payload=payload,
|
soft_payload=payload,
|
||||||
@@ -196,7 +188,7 @@ async def _execute_tool_call(
|
|||||||
|
|
||||||
if is_tool_error_result(result):
|
if is_tool_error_result(result):
|
||||||
await hook.on_execute_tool_error(context, tool_call, tool, params, 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 = {
|
event = {
|
||||||
"name": tool_call.name,
|
"name": tool_call.name,
|
||||||
"status": "error",
|
"status": "error",
|
||||||
|
|||||||
@@ -11,6 +11,18 @@ from nanobot.agent.tools.context import ContextAware, current_request_context
|
|||||||
if TYPE_CHECKING:
|
if TYPE_CHECKING:
|
||||||
from nanobot.runtime_context import RuntimeContextProvider
|
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:
|
def is_tool_error_result(result: Any) -> bool:
|
||||||
return isinstance(result, ToolResult) and result.is_error
|
return isinstance(result, ToolResult) and result.is_error
|
||||||
@@ -186,19 +198,18 @@ class ToolRegistry:
|
|||||||
|
|
||||||
async def execute(self, name: str, params: Any) -> Any:
|
async def execute(self, name: str, params: Any) -> Any:
|
||||||
"""Execute a tool by name with given parameters."""
|
"""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)
|
tool, params, error = self.prepare_call(name, params)
|
||||||
if error:
|
if error:
|
||||||
return ToolResult.error(str(error) + hint)
|
return ToolResult.error(with_tool_error_hint(str(error)))
|
||||||
|
|
||||||
try:
|
try:
|
||||||
assert tool is not None # guarded by prepare_call()
|
assert tool is not None # guarded by prepare_call()
|
||||||
result = await tool.execute(**params)
|
result = await tool.execute(**params)
|
||||||
if is_tool_error_result(result):
|
if is_tool_error_result(result):
|
||||||
return ToolResult.error(str(result) + hint)
|
return ToolResult.error(with_tool_error_hint(str(result)))
|
||||||
return result
|
return result
|
||||||
except Exception as e:
|
except 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)}"))
|
||||||
|
|
||||||
@property
|
@property
|
||||||
def tool_names(self) -> list[str]:
|
def tool_names(self) -> list[str]:
|
||||||
|
|||||||
@@ -56,16 +56,22 @@ async def test_runner_returns_tool_exception_to_model_for_recovery():
|
|||||||
{"name": "list_dir", "status": "error", "detail": "boom"}
|
{"name": "list_dir", "status": "error", "detail": "boom"}
|
||||||
]
|
]
|
||||||
tool_message = next(message for message in result.messages if message.get("role") == "tool")
|
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 "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
|
@pytest.mark.asyncio
|
||||||
async def test_tool_execution_does_not_duplicate_existing_retry_hint():
|
async def test_tool_execution_does_not_duplicate_existing_error_hint():
|
||||||
retry_hint = "\n\n[Analyze the error above and try a different approach.]"
|
error_hint = (
|
||||||
|
"\n\n[Consider this result in the context of the user's goal "
|
||||||
|
"and decide whether and how to proceed.]"
|
||||||
|
)
|
||||||
tools = SimpleNamespace(
|
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(
|
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=[]),
|
context=AgentHookContext(iteration=0, messages=[]),
|
||||||
)
|
)
|
||||||
|
|
||||||
assert results == ["Error: boom" + retry_hint]
|
assert results == ["Error: boom" + error_hint]
|
||||||
assert results[0].count(retry_hint) == 1
|
assert results[0].count(error_hint) == 1
|
||||||
assert events[0]["status"] == "error"
|
assert events[0]["status"] == "error"
|
||||||
|
|
||||||
|
|
||||||
@@ -300,15 +306,18 @@ async def test_runner_recognizes_web_fetch_errors(monkeypatch, url, ssrf):
|
|||||||
content = tool_message["content"]
|
content = tool_message["content"]
|
||||||
assert content.startswith(str(raw_error) + "\n\n")
|
assert content.startswith(str(raw_error) + "\n\n")
|
||||||
assert json.JSONDecoder().raw_decode(content)[0] == raw_payload
|
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:
|
if ssrf:
|
||||||
assert result.tool_events[0]["detail"].startswith("ssrf_violation:")
|
assert result.tool_events[0]["detail"].startswith("ssrf_violation:")
|
||||||
assert "non-bypassable security boundary" in content
|
assert "non-bypassable security boundary" in content
|
||||||
assert "Do not retry" in content
|
assert "Do not retry" in content
|
||||||
assert "tools.ssrfWhitelist" in content
|
assert "tools.ssrfWhitelist" in content
|
||||||
assert retry_hint not in content
|
assert error_hint not in content
|
||||||
else:
|
else:
|
||||||
assert content.count(retry_hint) == 1
|
assert content.count(error_hint) == 1
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -626,7 +626,7 @@ async def test_execute_contains_malformed_success_result() -> None:
|
|||||||
|
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@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:
|
async def call_tool(_name: str, arguments: dict) -> object:
|
||||||
return SimpleNamespace(content=None)
|
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 is_tool_error_result(result)
|
||||||
assert "MCP tool returned malformed content" in 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.asyncio
|
@pytest.mark.asyncio
|
||||||
|
|||||||
@@ -3,6 +3,8 @@ from __future__ import annotations
|
|||||||
from typing import Any
|
from typing import Any
|
||||||
from unittest.mock import AsyncMock
|
from unittest.mock import AsyncMock
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
|
||||||
from nanobot.agent.tools.base import Tool, ToolResult
|
from nanobot.agent.tools.base import Tool, ToolResult
|
||||||
from nanobot.agent.tools.filesystem import ReadFileTool
|
from nanobot.agent.tools.filesystem import ReadFileTool
|
||||||
from nanobot.agent.tools.registry import ToolRegistry
|
from 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
|
assert result == output
|
||||||
|
|
||||||
|
|
||||||
async def test_registry_uses_structured_tool_result_for_errors() -> None:
|
@pytest.mark.parametrize("already_hinted", [False, True])
|
||||||
|
async def test_registry_uses_structured_tool_result_for_errors(already_hinted: bool) -> None:
|
||||||
registry = ToolRegistry()
|
registry = ToolRegistry()
|
||||||
output = "Error: plain tool output, not a structured failure"
|
output = "Error: plain tool output, not a structured failure"
|
||||||
raw_tool = _FakeTool("raw_output")
|
raw_tool = _FakeTool("raw_output")
|
||||||
@@ -280,16 +283,20 @@ async def test_registry_uses_structured_tool_result_for_errors() -> None:
|
|||||||
|
|
||||||
assert raw_result == output
|
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 = _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)
|
registry.register(failing_tool)
|
||||||
|
|
||||||
error_result = await registry.execute("failing_tool", {})
|
error_result = await registry.execute("failing_tool", {})
|
||||||
|
|
||||||
assert isinstance(error_result, ToolResult)
|
assert isinstance(error_result, ToolResult)
|
||||||
assert error_result.is_error
|
assert error_result.is_error
|
||||||
assert error_result.startswith("Error: real failure")
|
assert error_result == "Error: real failure" + error_hint
|
||||||
assert "[Analyze the error above" in error_result
|
|
||||||
|
|
||||||
|
|
||||||
def test_get_definitions_returns_cached_result() -> None:
|
def test_get_definitions_returns_cached_result() -> None:
|
||||||
|
|||||||
Reference in new issue
Block a user