Build and run agents you can see, understand and trust.
Python agentchatbotlarge-language-modelsllmllm-agentmcpmulti-agentmulti-modalreact-agentrealtime-agentvoice-agentvoice-assistant
fix(formatter): keep text before media in Anthropic multi-agent history (#3525)
Kiko030158d146c5b4cc
diff --git a/src/agentscope/formatter/_anthropic_formatter.py b/src/agentscope/formatter/_anthropic_formatter.pyindex 71003c3ea..f6995666c 100644--- a/src/agentscope/formatter/_anthropic_formatter.py+++ b/src/agentscope/formatter/_anthropic_formatter.py@@ -469,6 +469,14 @@ class AnthropicMultiAgentFormatter(_AnthropicFormatterBase):elif isinstance(block, DataBlock):formatted_block = self._format_anthropic_data_block(block)if formatted_block:+ # Commit this message's pending text first, so a+ # media part never precedes the caption that+ # introduces it within the same message.+ if agent_text_parts:+ accumulated_text.append(+ f"{agent_name}: {' '.join(agent_text_parts)}",+ )+ agent_text_parts = []if accumulated_text:conversation_blocks.append({diff --git a/tests/formatter_anthropic_test.py b/tests/formatter_anthropic_test.pyindex 4f617fc2c..903b71a3a 100644--- a/tests/formatter_anthropic_test.py+++ b/tests/formatter_anthropic_test.py@@ -757,6 +757,62 @@ class TestAnthropicFormatter( # pylint: disable=too-many-public-methodsres,)+ async def test_multiagent_text_before_media_in_same_message(+ self,+ ) -> None:+ """A media part must not precede the text of its own message."""+ fmt = AnthropicMultiAgentFormatter()+ res = await fmt.format(+ [+ UserMsg(+ name="alice",+ content=[+ TextBlock(text="look at this"),+ DataBlock(+ source=Base64Source(+ data=self.image_b64,+ media_type="image/png",+ ),+ ),+ ],+ ),+ UserMsg(+ name="bob",+ content=[TextBlock(text="ok")],+ ),+ ],+ )++ self.assertListEqual(+ [+ {+ "role": "user",+ "content": [+ {+ "type": "text",+ "text": (+ fmt.conversation_history_prompt+ + "<history>\nalice: look at this"+ ),+ },+ {+ "type": "image",+ "source": {+ "type": "base64",+ "media_type": "image/png",+ "data": self.image_b64,+ },+ },+ {+ "type": "text",+ "text": "bob: ok\n</history>",+ },+ ],+ },+ ],+ res,+ )+async def test_chat_formatter_complex_multi_step(self) -> None:"""Complex multi-step sequence with interleaved thinking, text,tool calls, and tool results."""