Skip to content

CubeLoop — a Pythonic, async-native agent harness core designed for high performance, readability, and production-grade persistence.

fix(anthropic): drop trailing empty error assistant; fill mid-history

xf gongf6b7e2a113a7
diff --git a/cubepi/providers/anthropic.py b/cubepi/providers/anthropic.py
index 2ac1074..38bea3e 100644
--- a/cubepi/providers/anthropic.py
+++ b/cubepi/providers/anthropic.py
@@ -425,6 +425,19 @@ class AnthropicProvider(BaseProvider):
an interior tool result stays on that result's block instead of sliding
to 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
diff --git a/tests/providers/test_anthropic.py b/tests/providers/test_anthropic.py
index a8e2c06..4f30668 100644
--- a/tests/providers/test_anthropic.py
+++ b/tests/providers/test_anthropic.py
@@ -69,6 +69,33 @@ 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.
+ messages = [
+ UserMessage(content=[TextContent(text="ask")]),
+ AssistantMessage(content=[], stop_reason="error", error_message="boom"),
+ ]
+ 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
+
+ def test_build_api_messages_fills_non_trailing_empty_assistant(self):
+ # Mid-history empty error assistant must be filled with a placeholder
+ # to preserve the user→assistant→user alternation Anthropic requires.
+ messages = [
+ UserMessage(content=[TextContent(text="first")]),
+ AssistantMessage(content=[], stop_reason="error"),
+ UserMessage(content=[TextContent(text="retry")]),
+ ]
+ api_messages, _ = AnthropicProvider._build_api_messages(messages)
+ assert [m["role"] for m in api_messages] == ["user", "assistant", "user"]
+ assert len(api_messages[1]["content"]) >= 1
+
class TestAnthropicToolConversion:
def test_convert_tool_definition(self):