CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.
Python agent-frameworkagent-harnessagent-runtimeagentic-aiai-agentsai-frameworkanthropicharnessharness-engineeringharness-frameworklanggraphlanggraph-alternativellmmcpopenaipi-agentpi-agent-corepythonpython-agent
fix(anthropic): merge parallel tool results into one user message (#106)
Chris971717634457
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.pyindex 7842c5b..c8a39f6 100644--- a/cubepi/providers/anthropic.py+++ b/cubepi/providers/anthropic.py@@ -151,10 +151,11 @@ class AnthropicProvider(BaseProvider):cap = self._resolve_capability(model.id)cache_control = self._get_cache_control()- api_messages = [self._convert_message(m) for m in messages]+ api_messages, breakpoints = self._build_api_messages(messages)if cache_control:indices = self._cache_policy.message_breakpoint_indices(messages)- self._apply_indices_markers(api_messages, indices, cache_control)+ targets = [breakpoints[i] for i in indices if 0 <= i < len(breakpoints)]+ self._apply_breakpoint_markers(api_messages, targets, cache_control)kwargs: dict[str, Any] = {"model": model.id,@@ -331,29 +332,40 @@ class AnthropicProvider(BaseProvider):cc["ttl"] = "1h"return cc- def _apply_indices_markers(+ def _apply_breakpoint_markers(self,api_messages: list[dict[str, Any]],- indices: list[int],+ targets: list[tuple[int, int]],cache_control: dict[str, str],) -> None:- """Apply cache_control to the last content block of each indexed message."""- for idx in indices:- if 0 <= idx < len(api_messages):- msg = api_messages[idx]- content = msg.get("content")- if isinstance(content, list) and content:- last_block = content[-1]- if isinstance(last_block, dict):- content[-1] = {**last_block, "cache_control": cache_control}- elif isinstance(content, str):- msg["content"] = [- {- "type": "text",- "text": content,- "cache_control": cache_control,- }- ]+ """Apply cache_control to specific ``(message, block)`` positions.++ ``targets`` come from :meth:`_build_api_messages`, which tracks the exact+ block each source message contributed. Marking that block (rather than+ always ``content[-1]``) keeps a breakpoint on its intended message even+ after parallel tool results are merged into one message.+ """+ for msg_idx, block_idx in targets:+ if not (0 <= msg_idx < len(api_messages)):+ continue # pragma: no cover — stream pre-filters indices+ msg = api_messages[msg_idx]+ content = msg.get("content")+ if isinstance(content, list) and content:+ if 0 <= block_idx < len(content) and isinstance(+ content[block_idx], dict+ ):+ content[block_idx] = {+ **content[block_idx],+ "cache_control": cache_control,+ }+ elif isinstance(content, str):+ msg["content"] = [+ {+ "type": "text",+ "text": content,+ "cache_control": cache_control,+ }+ ]@staticmethoddef _apply_message_cache_control(@@ -383,6 +395,42 @@ class AnthropicProvider(BaseProvider):{"type": "text", "text": content, "cache_control": cache_control}]+ @staticmethod+ def _build_api_messages(+ messages: list[Message],+ ) -> tuple[list[dict[str, Any]], list[tuple[int, int]]]:+ """Convert messages, coalescing a contiguous run of tool results.++ Anthropic requires every ``tool_result`` for a parallel-tool-call turn+ to sit in the single ``user`` message immediately after the assistant's+ ``tool_use`` blocks. cubepi records one ``ToolResultMessage`` per call,+ so consecutive ones are merged into one user message here.++ Returns ``(api_messages, breakpoints)`` where ``breakpoints[i]`` is the+ ``(api_index, block_index)`` of the LAST content block that source+ message ``i`` contributed. Merging several sources into one message+ gives each a distinct block offset, so a cache breakpoint that targets+ an interior tool result stays on that result's block instead of sliding+ to the end of the merge.+ """+ api_messages: list[dict[str, Any]] = []+ breakpoints: list[tuple[int, int]] = []+ prev_tool_result = False+ for msg in messages:+ converted = AnthropicProvider._convert_message(msg)+ is_tool_result = isinstance(msg, ToolResultMessage)+ if is_tool_result and prev_tool_result and api_messages:+ merged = api_messages[-1]["content"]+ merged.extend(converted["content"])+ breakpoints.append((len(api_messages) - 1, len(merged) - 1))+ else:+ api_messages.append(converted)+ breakpoints.append(+ (len(api_messages) - 1, len(converted["content"]) - 1)+ )+ prev_tool_result = is_tool_result+ return api_messages, breakpoints+@staticmethoddef _convert_message(msg: Message) -> dict[str, Any]:if isinstance(msg, UserMessage):diff --git a/tests/providers/test_anthropic.py b/tests/providers/test_anthropic.pyindex 496f958..b8baf43 100644--- a/tests/providers/test_anthropic.py+++ b/tests/providers/test_anthropic.py@@ -751,6 +751,175 @@ class TestAnthropicStreamKwargsBuilding:assert captured["headers"]["x-request-id"] == "req-xyz"+class TestAnthropicParallelToolResults:+ """Parallel tool calls: all tool_results must land in ONE user message.++ Anthropic rejects a request where an assistant turn emits N parallel+ tool_use blocks but the immediately-following user message carries fewer+ than N tool_result blocks. cubepi stores one ToolResultMessage per call,+ so the provider must coalesce consecutive ones.+ """++ @staticmethod+ def _history():+ return [+ UserMessage(content=[TextContent(text="weather?")]),+ AssistantMessage(+ content=[+ ToolCall(id="call_0", name="fetch", arguments={"u": "a"}),+ ToolCall(id="call_1", name="fetch", arguments={"u": "b"}),+ ],+ stop_reason="tool_use",+ ),+ ToolResultMessage(+ tool_call_id="call_0",+ tool_name="fetch",+ content=[TextContent(text="result a")],+ ),+ ToolResultMessage(+ tool_call_id="call_1",+ tool_name="fetch",+ content=[TextContent(text="result b")],+ ),+ ]++ @pytest.mark.asyncio+ async def test_consecutive_tool_results_merged_into_one_user_message(self):+ mock_stream = _MockAnthropicStream([], _make_final_message(content=[]))+ provider = _make_provider("none")+ mock_client = _inject_mock_stream(provider, mock_stream)++ ms = await provider.stream(_anthropic_model(), self._history())+ async for _ in ms:+ pass+ await ms.result()++ messages = mock_client.messages.stream.call_args[1]["messages"]+ # user, assistant(2 tool_use), user(2 tool_result) — NOT 4 messages.+ assert len(messages) == 3+ tool_results = messages[2]["content"]+ assert messages[2]["role"] == "user"+ assert [b["tool_use_id"] for b in tool_results] == ["call_0", "call_1"]+ # Every tool_use id has a matching tool_result in the next message.+ tool_use_ids = {b["id"] for b in messages[1]["content"]}+ result_ids = {b["tool_use_id"] for b in tool_results}+ assert tool_use_ids == result_ids++ @pytest.mark.asyncio+ async def test_cache_breakpoint_lands_on_merged_message(self):+ # Default policy marks the last message; after merge it must still be+ # the (single) tool-result user message that gets the breakpoint.+ mock_stream = _MockAnthropicStream([], _make_final_message(content=[]))+ provider = _make_provider("short")+ mock_client = _inject_mock_stream(provider, mock_stream)++ ms = await provider.stream(_anthropic_model(), self._history())+ async for _ in ms:+ pass+ await ms.result()++ messages = mock_client.messages.stream.call_args[1]["messages"]+ assert len(messages) == 3+ # Breakpoint on the last content block of the merged tool-result message.+ assert messages[2]["content"][-1]["cache_control"] == {"type": "ephemeral"}++ @pytest.mark.asyncio+ async def test_breakpoint_on_interior_result_keeps_its_block(self):+ # A custom policy that targets the FIRST result of a parallel run must+ # mark THAT result's block, not slide to the last block of the merge.+ class _FirstResult:+ def mark_system(self) -> bool:+ return False++ def mark_last_tool(self) -> bool:+ return False++ def message_breakpoint_indices(self, messages):+ return [2] # the first ToolResultMessage in _history()++ mock_stream = _MockAnthropicStream([], _make_final_message(content=[]))+ provider = AnthropicProvider(+ api_key="x", cache_retention="short", cache_policy=_FirstResult()+ )+ mock_client = _inject_mock_stream(provider, mock_stream)++ ms = await provider.stream(_anthropic_model(), self._history())+ async for _ in ms:+ pass+ await ms.result()++ results = mock_client.messages.stream.call_args[1]["messages"][2]["content"]+ # call_0 (first result) carries the breakpoint; call_1 does not.+ assert results[0]["tool_use_id"] == "call_0"+ assert results[0]["cache_control"] == {"type": "ephemeral"}+ assert "cache_control" not in results[1]++ @pytest.mark.asyncio+ async def test_single_tool_result_not_affected(self):+ history = [+ UserMessage(content=[TextContent(text="time?")]),+ AssistantMessage(+ content=[ToolCall(id="call_0", name="now", arguments={})],+ stop_reason="tool_use",+ ),+ ToolResultMessage(+ tool_call_id="call_0",+ tool_name="now",+ content=[TextContent(text="noon")],+ ),+ ]+ mock_stream = _MockAnthropicStream([], _make_final_message(content=[]))+ provider = _make_provider("none")+ mock_client = _inject_mock_stream(provider, mock_stream)++ ms = await provider.stream(_anthropic_model(), history)+ async for _ in ms:+ pass+ await ms.result()++ messages = mock_client.messages.stream.call_args[1]["messages"]+ assert len(messages) == 3+ assert messages[2]["content"][0]["tool_use_id"] == "call_0"++ @pytest.mark.asyncio+ async def test_separate_turns_not_merged(self):+ # Two single-tool turns separated by an assistant message must stay+ # as two distinct user messages — merging only spans a contiguous run.+ history = [+ UserMessage(content=[TextContent(text="q")]),+ AssistantMessage(+ content=[ToolCall(id="c0", name="t", arguments={})],+ stop_reason="tool_use",+ ),+ ToolResultMessage(+ tool_call_id="c0",+ tool_name="t",+ content=[TextContent(text="r0")],+ ),+ AssistantMessage(+ content=[ToolCall(id="c1", name="t", arguments={})],+ stop_reason="tool_use",+ ),+ ToolResultMessage(+ tool_call_id="c1",+ tool_name="t",+ content=[TextContent(text="r1")],+ ),+ ]+ mock_stream = _MockAnthropicStream([], _make_final_message(content=[]))+ provider = _make_provider("none")+ mock_client = _inject_mock_stream(provider, mock_stream)++ ms = await provider.stream(_anthropic_model(), history)+ async for _ in ms:+ pass+ await ms.result()++ messages = mock_client.messages.stream.call_args[1]["messages"]+ roles = [m["role"] for m in messages]+ assert roles == ["user", "assistant", "user", "assistant", "user"]++class TestAnthropicStreamAbort:"""Test abort signal handling."""diff --git a/tests/providers/test_anthropic_cache_policy.py b/tests/providers/test_anthropic_cache_policy.pyindex 440e01f..4bb3d76 100644--- a/tests/providers/test_anthropic_cache_policy.py+++ b/tests/providers/test_anthropic_cache_policy.py@@ -50,29 +50,48 @@ def test_provider_uses_custom_policy() -> None:assert p._cache_policy.mark_system() is False-def test_apply_indices_markers_marks_specified_indices() -> None:- """Marker is applied to the last content block of each indexed message."""+def test_apply_breakpoint_markers_marks_specified_block() -> None:+ """Marker is applied to the targeted (message, block) position."""p = AnthropicProvider(api_key="x")api_messages = [{"role": "user", "content": [{"type": "text", "text": "a"}]},{"role": "user", "content": [{"type": "text", "text": "b"}]},]- p._apply_indices_markers(- api_messages, indices=[0], cache_control={"type": "ephemeral"}+ p._apply_breakpoint_markers(+ api_messages, targets=[(0, 0)], cache_control={"type": "ephemeral"})- assert api_messages[0]["content"][-1].get("cache_control") == {"type": "ephemeral"}+ assert api_messages[0]["content"][0].get("cache_control") == {"type": "ephemeral"}# message 1 untouchedassert "cache_control" not in api_messages[1]["content"][-1]-def test_apply_indices_markers_converts_string_content() -> None:- """When a message has string content, _apply_indices_markers converts to block list and marks it."""+def test_apply_breakpoint_markers_marks_interior_block() -> None:+ """A target block that isn't the last one still gets marked precisely."""+ p = AnthropicProvider(api_key="x")+ api_messages = [+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "t0"},+ {"type": "tool_result", "tool_use_id": "t1"},+ ],+ },+ ]+ p._apply_breakpoint_markers(+ api_messages, targets=[(0, 0)], cache_control={"type": "ephemeral"}+ )+ assert api_messages[0]["content"][0]["cache_control"] == {"type": "ephemeral"}+ assert "cache_control" not in api_messages[0]["content"][1]+++def test_apply_breakpoint_markers_converts_string_content() -> None:+ """String content is converted to a block list and marked."""p = AnthropicProvider(api_key="x")api_messages = [{"role": "user", "content": "plain string"},]- p._apply_indices_markers(- api_messages, indices=[0], cache_control={"type": "ephemeral"}+ p._apply_breakpoint_markers(+ api_messages, targets=[(0, 0)], cache_control={"type": "ephemeral"})assert isinstance(api_messages[0]["content"], list)assert api_messages[0]["content"][0] == {@@ -101,8 +120,9 @@ async def test_custom_policy_drives_message_marker_placement() -> None:UserMessage(content=[TextContent(text="zero")]),UserMessage(content=[TextContent(text="one")]),]- api_msgs = [p._convert_message(m) for m in msgs]- p._apply_indices_markers(api_msgs, indices=[0], cache_control={"type": "ephemeral"})+ api_msgs, breakpoints = p._build_api_messages(msgs)+ targets = [breakpoints[i] for i in _FirstOnly().message_breakpoint_indices(msgs)]+ p._apply_breakpoint_markers(api_msgs, targets, cache_control={"type": "ephemeral"})first_blocks = api_msgs[0]["content"]assert isinstance(first_blocks, list)