Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(formatter): drop empty text blocks for anthropic (#2007)
nolanchic432279d9bd72
diff --git a/src/agentscope/formatter/_anthropic_formatter.py b/src/agentscope/formatter/_anthropic_formatter.pyindex f3741cbdd..42c9ba7e4 100644--- a/src/agentscope/formatter/_anthropic_formatter.py+++ b/src/agentscope/formatter/_anthropic_formatter.py@@ -72,9 +72,14 @@ class _AnthropicFormatterBase(FormatterBase, ABC):has_tool_result = Falseif isinstance(block, TextBlock):- content_blocks.append(- {"type": "text", "text": block.text},- )+ # Anthropic rejects empty text blocks with a 400+ # ("text blocks must be non-empty"). Empty TextBlocks+ # occur after a tool-call-only assistant turn whose+ # streamed text is empty, so drop them here.+ if block.text:+ content_blocks.append(+ {"type": "text", "text": block.text},+ )elif isinstance(block, ThinkingBlock):# Anthropic rejects thinking blocks without a valid@@ -173,15 +178,22 @@ class _AnthropicFormatterBase(FormatterBase, ABC):tool_result_content: list[dict] = []output = block.outputif isinstance(output, str):- tool_result_content.append(- {"type": "text", "text": output},- )+ if output:+ tool_result_content.append(+ {"type": "text", "text": output},+ )else:for out_block in output:if isinstance(out_block, TextBlock):- tool_result_content.append(- {"type": "text", "text": out_block.text},- )+ # Skip empty text — Anthropic rejects+ # {"type": "text", "text": ""}.+ if out_block.text:+ tool_result_content.append(+ {+ "type": "text",+ "text": out_block.text,+ },+ )elif isinstance(out_block, DataBlock):fmt_block = self._format_anthropic_data_block(out_block,@@ -205,6 +217,15 @@ class _AnthropicFormatterBase(FormatterBase, ABC):{"type": "text", "text": fallback},)+ # Anthropic rejects a tool_result whose content list is+ # empty. If every output block was an empty text (or the+ # output was an empty string), fall back to a placeholder+ # so the tool_result remains valid.+ if not tool_result_content:+ tool_result_content.append(+ {"type": "text", "text": "(empty tool output)"},+ )+content_blocks.append({"type": "tool_result",diff --git a/tests/formatter_anthropic_test.py b/tests/formatter_anthropic_test.pyindex d02a08bb1..46a9ec52a 100644--- a/tests/formatter_anthropic_test.py+++ b/tests/formatter_anthropic_test.py@@ -988,3 +988,180 @@ class TestAnthropicFormatter(IsolatedAsyncioTestCase):][0]# Repaired to a dict rather than crashing.self.assertIsInstance(tool_use["input"], dict)++ async def test_empty_text_block_is_dropped(self) -> None:+ """Empty ``TextBlock`` must be skipped, not forwarded.++ Anthropic rejects ``{"type": "text", "text": ""}`` with a 400+ ("text blocks must be non-empty"). Empty text blocks arise in+ practice after a tool-call-only assistant turn whose streamed text+ block is empty. The formatter must drop them rather than emit them.+ """+ fmt = AnthropicChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ TextBlock(text=""),+ ToolCallBlock(+ id="call_1",+ name="get_weather",+ input='{"city": "Tokyo"}',+ ),+ ],+ ),+ ]++ res = await fmt.format(msgs)++ # The empty TextBlock is dropped — the assistant message contains+ # only the tool_use block, nothing else.+ self.assertListEqual(+ [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "call_1",+ "name": "get_weather",+ "input": {"city": "Tokyo"},+ },+ ],+ },+ ],+ res,+ )++ async def test_empty_tool_result_text_is_dropped(self) -> None:+ """Empty text inside a tool result is skipped too.++ A ``ToolResultBlock`` whose only output is an empty TextBlock must+ not produce an empty text content entry, which Anthropic would+ reject. The formatter falls back to a non-empty placeholder so the+ tool_result content list stays valid.+ """+ fmt = AnthropicChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ ToolCallBlock(+ id="call_1",+ name="get_weather",+ input='{"city": "Tokyo"}',+ ),+ ],+ ),+ AssistantMsg(+ name="assistant",+ content=[+ ToolResultBlock(+ id="call_1",+ name="get_weather",+ output=[TextBlock(text="")],+ state=ToolResultState.SUCCESS,+ ),+ ],+ ),+ ]++ res = await fmt.format(msgs)++ self.assertListEqual(+ [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "call_1",+ "name": "get_weather",+ "input": {"city": "Tokyo"},+ },+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "call_1",+ "content": [+ {+ "type": "text",+ "text": "(empty tool output)",+ },+ ],+ },+ ],+ },+ ],+ res,+ )++ async def test_empty_string_tool_output_uses_placeholder(self) -> None:+ """An empty-string tool output becomes a placeholder text block.++ Anthropic rejects both empty text blocks and a tool_result whose+ content list is empty, so a wholly-empty output must be replaced+ with a non-empty placeholder.+ """+ fmt = AnthropicChatFormatter()+ msgs = [+ AssistantMsg(+ name="assistant",+ content=[+ ToolCallBlock(+ id="call_1",+ name="noop",+ input="{}",+ ),+ ],+ ),+ AssistantMsg(+ name="assistant",+ content=[+ ToolResultBlock(+ id="call_1",+ name="noop",+ output="",+ state=ToolResultState.SUCCESS,+ ),+ ],+ ),+ ]++ res = await fmt.format(msgs)++ self.assertListEqual(+ [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "call_1",+ "name": "noop",+ "input": {},+ },+ ],+ },+ {+ "role": "user",+ "content": [+ {+ "type": "tool_result",+ "tool_use_id": "call_1",+ "content": [+ {+ "type": "text",+ "text": "(empty tool output)",+ },+ ],+ },+ ],+ },+ ],+ res,+ )