Skip to content

Build and run agents you can see, understand and trust.

fix(formatter): preserve anthropic tool error status (#3905)

Wang guanyu60649c74c703
diff --git a/src/agentscope/formatter/_anthropic_formatter.py b/src/agentscope/formatter/_anthropic_formatter.py
index fd2790716..9e483989b 100644
--- a/src/agentscope/formatter/_anthropic_formatter.py
+++ b/src/agentscope/formatter/_anthropic_formatter.py
@@ -20,6 +20,7 @@ from ..message import (
DataBlock,
ToolCallBlock,
ToolResultBlock,
+ ToolResultState,
URLSource,
Base64Source,
)
@@ -244,13 +245,14 @@ class _AnthropicFormatterBase(FormatterBase, ABC):
{"type": "text", "text": "(empty tool output)"},
)
- content_blocks.append(
- {
- "type": "tool_result",
- "tool_use_id": block.id,
- "content": tool_result_content,
- },
- )
+ tool_result: dict[str, Any] = {
+ "type": "tool_result",
+ "tool_use_id": block.id,
+ "content": tool_result_content,
+ }
+ if block.state == ToolResultState.ERROR:
+ tool_result["is_error"] = True
+ content_blocks.append(tool_result)
# Anthropic requires tool_result to be in a "user" message.
has_tool_result = True
diff --git a/tests/formatter_anthropic_test.py b/tests/formatter_anthropic_test.py
index ac2e5b7ac..d50cd2926 100644
--- a/tests/formatter_anthropic_test.py
+++ b/tests/formatter_anthropic_test.py
@@ -564,6 +564,70 @@ class TestAnthropicFormatter( # pylint: disable=too-many-public-methods
]
self.assertListEqual(tool_result_roles, ["user"])
+ async def test_tool_result_error_state(self) -> None:
+ """Only ERROR gains a flag, including when the output is empty."""
+ for formatter_type in (
+ AnthropicChatFormatter,
+ AnthropicMultiAgentFormatter,
+ ):
+ for state in ToolResultState:
+ for output in ("failed", ""):
+ with self.subTest(
+ formatter=formatter_type.__name__,
+ state=state,
+ output=output,
+ ):
+ msgs = [
+ AssistantMsg(
+ name="assistant",
+ content=[
+ ToolCallBlock(
+ id="call_1",
+ name="validate",
+ input="{}",
+ ),
+ ToolResultBlock(
+ id="call_1",
+ name="validate",
+ output=output,
+ state=state,
+ ),
+ ],
+ ),
+ ]
+ expected_result = {
+ "type": "tool_result",
+ "tool_use_id": "call_1",
+ "content": [
+ {
+ "type": "text",
+ "text": output or "(empty tool output)",
+ },
+ ],
+ }
+ if state == ToolResultState.ERROR:
+ expected_result["is_error"] = True
+ self.assertEqual(
+ await formatter_type().format(msgs),
+ [
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "call_1",
+ "name": "validate",
+ "input": {},
+ },
+ ],
+ },
+ {
+ "role": "user",
+ "content": [expected_result],
+ },
+ ],
+ )
+
async def test_chat_formatter_tool_result_with_image(self) -> None:
"""Tool result containing an image DataBlock inlines the image in the
tool_result content without crashing on TextBlock system-reminders."""
diff --git a/tests/model_anthropic_test.py b/tests/model_anthropic_test.py
index 82c506344..30f34db0a 100644
--- a/tests/model_anthropic_test.py
+++ b/tests/model_anthropic_test.py
@@ -24,6 +24,8 @@ from agentscope.message import (
AssistantMsg,
TextBlock,
ToolCallBlock,
+ ToolResultBlock,
+ ToolResultState,
ThinkingBlock,
)
from agentscope.model import AnthropicChatModel, ChatUsage
@@ -272,6 +274,77 @@ class TestAnthropicNonStream(IsolatedAsyncioTestCase):
),
)
+ async def test_tool_result_error_flag_on_wire(self) -> None:
+ """The SDK sends the error flag only for failed tool results."""
+ captured = []
+ backend = (
+ httpx2
+ if issubclass(DefaultAsyncHttpxClient, httpx2.AsyncClient)
+ else httpx
+ )
+
+ def handle(request: Any) -> Any:
+ captured.append(json.loads(request.content))
+ return backend.Response(
+ 200,
+ json={
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "model": "offline",
+ "content": [{"type": "text", "text": "ok"}],
+ "stop_reason": "end_turn",
+ "usage": {"input_tokens": 1, "output_tokens": 1},
+ },
+ )
+
+ async with DefaultAsyncHttpxClient(
+ transport=backend.MockTransport(handle),
+ ) as client:
+ model = AnthropicChatModel(
+ credential=AnthropicCredential(api_key="offline-test"),
+ model="offline",
+ stream=False,
+ client_kwargs={"http_client": client},
+ )
+ for state in (ToolResultState.ERROR, ToolResultState.SUCCESS):
+ await model(
+ [
+ AssistantMsg(
+ name="assistant",
+ content=[
+ ToolCallBlock(
+ id="call_1",
+ name="validate",
+ input="{}",
+ ),
+ ToolResultBlock(
+ id="call_1",
+ name="validate",
+ output="failed",
+ state=state,
+ ),
+ ],
+ ),
+ ],
+ )
+
+ expected_result = {
+ "type": "tool_result",
+ "tool_use_id": "call_1",
+ "content": [{"type": "text", "text": "failed"}],
+ }
+ self.assertEqual(
+ [body["messages"][-1] for body in captured],
+ [
+ {
+ "role": "user",
+ "content": [{**expected_result, "is_error": True}],
+ },
+ {"role": "user", "content": [expected_result]},
+ ],
+ )
+
async def test_thinking_response(self) -> None:
"""Non-stream response with reasoning creates ThinkingBlock."""
mock_create = AsyncMock(