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): trim trailing empty assistants in stream(), not the builder
xf gong13631637e06c
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.pyindex 38bea3e..5eaea0c 100644--- a/cubepi/providers/anthropic.py+++ b/cubepi/providers/anthropic.py@@ -152,6 +152,12 @@ class AnthropicProvider(BaseProvider):cap = self._resolve_capability(model.id)cache_control = self._get_cache_control()+ # Strip persisted "this turn errored before any output" markers (empty+ # AssistantMessages at the tail) before BOTH the API conversion and the+ # cache-policy query: leaving them in would make Anthropic treat the+ # trailing empty assistant as a prefill, and querying the policy with+ # the original list would point cache_control at a now-dropped message.+ messages = self._strip_trailing_empty_assistants(messages)api_messages, breakpoints = self._build_api_messages(messages)if cache_control:indices = self._cache_policy.message_breakpoint_indices(messages)@@ -425,19 +431,6 @@ class AnthropicProvider(BaseProvider):an interior tool result stays on that result's block instead of slidingto the end of the merge."""- # Trim trailing empty AssistantMessage(s) — the persisted marker of a- # turn that errored before producing any content. Anthropic treats the- # last assistant message as a prefill, so handing it back (or even a- # synthesised placeholder in its place) would make the model continue- # *from* the empty turn instead of regenerating from the preceding- # user prompt, which is exactly the stuck-retry path this fix targets.- while (- messages- and isinstance(messages[-1], AssistantMessage)- and not messages[-1].content- ):- messages = messages[:-1]-api_messages: list[dict[str, Any]] = []breakpoints: list[tuple[int, int]] = []prev_tool_result = False@@ -456,6 +449,30 @@ class AnthropicProvider(BaseProvider):prev_tool_result = is_tool_resultreturn api_messages, breakpoints+ @staticmethod+ def _strip_trailing_empty_assistants(messages: list[Message]) -> list[Message]:+ """Drop trailing ``AssistantMessage`` entries with no content blocks.++ These are the persisted markers of a turn that errored before the+ model emitted anything. Two reasons to strip before doing anything+ else with the history:++ * Anthropic treats the last assistant message as a prefill, so a+ synthesised placeholder in that position would make the model+ continue *from* the empty turn instead of regenerating from the+ preceding user prompt.+ * The cache marker policy is queried with this same message list;+ if we trimmed only inside ``_build_api_messages`` the policy+ would still point ``cache_control`` at a message we just dropped.+ """+ while (+ messages+ and isinstance(messages[-1], AssistantMessage)+ and not messages[-1].content+ ):+ messages = messages[:-1]+ return messages+@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 4f30668..b51d4ae 100644--- a/tests/providers/test_anthropic.py+++ b/tests/providers/test_anthropic.py@@ -69,20 +69,27 @@ class TestAnthropicMessageConversion:block.get("text") or block.get("input") for block in result["content"])- def test_build_api_messages_drops_trailing_empty_assistant(self):- # If the trailing message is an empty error assistant, dropping it is- # the only correct option: Anthropic treats the last assistant as a- # prefill, so a placeholder there would make the model continue from- # "[empty response]" instead of regenerating the failed reply.+ def test_strip_trailing_empty_assistants_drops_persisted_error_tail(self):+ # Trailing empty error assistant must be dropped before both the API+ # build and the cache-policy query: Anthropic treats the last assistant+ # as a prefill, and leaving the dropped index visible to the policy+ # would point cache_control at a non-existent message.messages = [UserMessage(content=[TextContent(text="ask")]),AssistantMessage(content=[], stop_reason="error", error_message="boom"),+ AssistantMessage(content=[], stop_reason="error"),+ ]+ stripped = AnthropicProvider._strip_trailing_empty_assistants(messages)+ assert len(stripped) == 1+ assert isinstance(stripped[0], UserMessage)++ def test_strip_trailing_empty_assistants_preserves_real_tail(self):+ messages = [+ UserMessage(content=[TextContent(text="ask")]),+ AssistantMessage(content=[TextContent(text="reply")]),]- api_messages, breakpoints = AnthropicProvider._build_api_messages(messages)- assert len(api_messages) == 1- assert api_messages[0]["role"] == "user"- # Breakpoints stay aligned with the (now shorter) api_messages list.- assert len(breakpoints) == 1+ stripped = AnthropicProvider._strip_trailing_empty_assistants(messages)+ assert stripped == messagesdef test_build_api_messages_fills_non_trailing_empty_assistant(self):# Mid-history empty error assistant must be filled with a placeholder@@ -894,6 +901,35 @@ class TestAnthropicStreamKwargsBuilding:assert captured["status"] == 200assert captured["headers"]["x-request-id"] == "req-xyz"+ @pytest.mark.asyncio+ async def test_trailing_empty_assistant_dropped_and_cache_marker_preserved(self):+ """Stripping the trailing empty error assistant must keep cache_control+ on the new last message, not silently drop it because the policy was+ queried against the original (un-trimmed) message list."""+ events = []+ final = _make_final_message(content=[])+ mock_stream = _MockAnthropicStream(events, final)++ provider = _make_provider("short")+ mock_client = _inject_mock_stream(provider, mock_stream)++ history = [+ UserMessage(content=[TextContent(text="ask")]),+ AssistantMessage(content=[TextContent(text="reply")]),+ AssistantMessage(content=[], stop_reason="error", error_message="boom"),+ ]+ ms = await provider.stream(_anthropic_model(), history)+ async for _ in ms:+ pass+ await ms.result()++ sent = mock_client.messages.stream.call_args[1]["messages"]+ assert len(sent) == 2 # trailing empty error assistant dropped+ # Default cache policy marks the now-last message; cache_control must+ # still reach the wire.+ last_block = sent[-1]["content"][-1]+ assert last_block.get("cache_control") == {"type": "ephemeral"}+class TestAnthropicParallelToolResults:"""Parallel tool calls: all tool_results must land in ONE user message.