Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

fix(anthropic): keep tool exchanges intact around midturn system write-back

mateo-berrib9b200b3489e
diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 3747e03660d..e4a4d23b438 100644
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@ -507,6 +507,43 @@ class AnthropicMessagesHandler(BaseTranslation):
isinstance(message, dict) and isinstance(hoisted_system_message, dict) and message == hoisted_system_message
)
+ @staticmethod
+ def _is_system(message: object) -> bool:
+ """Whether the row is an in-sequence system message."""
+ return isinstance(message, dict) and str(message.get("role") or "").lower() == "system"
+
+ @staticmethod
+ def _defer_systems_inside_tool_exchanges(
+ structured_messages: list, # mutable-ok: API message payload
+ ) -> list:
+ """Hold a system row until the tool exchange around it completes so the call/result pair converts together."""
+ from litellm.litellm_core_utils.prompt_templates.factory import group_tool_exchanges
+
+ non_system_positions: Final[list[int]] = [
+ index
+ for index, message in enumerate(structured_messages)
+ if not AnthropicMessagesHandler._is_system(message)
+ ]
+ exchange_end_for_start: Final[dict[int, int]] = {
+ non_system_positions[group[0]]: non_system_positions[group[-1]]
+ for group in group_tool_exchanges([structured_messages[index] for index in non_system_positions])
+ if len(group) > 1
+ }
+ ordered: Final[list] = [] # mutable-ok: API message payload
+ deferred_systems: Final[list] = [] # mutable-ok: API message payload
+ open_exchange_end = -1 # rebind-ok: advances to the enclosing exchange's last index
+ for index, message in enumerate(structured_messages):
+ if AnthropicMessagesHandler._is_system(message) and index < open_exchange_end:
+ deferred_systems.append(message)
+ continue
+ open_exchange_end = exchange_end_for_start.get(index, open_exchange_end)
+ ordered.append(message)
+ if index >= open_exchange_end and deferred_systems:
+ ordered.extend(deferred_systems)
+ deferred_systems.clear()
+ ordered.extend(deferred_systems)
+ return ordered
+
@staticmethod
def _write_back_structured_messages(
data: dict, # mutable-ok: API message payload
@@ -520,9 +557,7 @@ class AnthropicMessagesHandler(BaseTranslation):
group_tool_exchanges,
)
- def _is_system(message: object) -> bool:
- return isinstance(message, dict) and str(message.get("role") or "").lower() == "system"
-
+ _is_system: Final = AnthropicMessagesHandler._is_system
model: Final = str(data.get("model") or "")
converted: Final[list] = [] # mutable-ok: API message payload
@@ -536,9 +571,10 @@ class AnthropicMessagesHandler(BaseTranslation):
)
)
+ ordered: Final = AnthropicMessagesHandler._defer_systems_inside_tool_exchanges(structured_messages)
run: Final[list] = [] # mutable-ok: API message payload
hoisted_dropped = False # rebind-ok: flips once the hoisted prompt is dropped
- for message in structured_messages:
+ for message in ordered:
if not _is_system(message):
run.append(message)
continue
diff --git a/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py b/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
index 1470056fd93..cefbaf17d57 100644
--- a/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
+++ b/tests/test_litellm/llms/anthropic/chat/guardrail_translation/test_anthropic_guardrail_handler.py
@@ -534,6 +534,47 @@ class TestAnthropicMessagesHandlerInputProcessing:
assert data["messages"][2]["content"] == [{"type": "text", "text": "continue"}]
assert data["system"] == "trusted top-level system prompt"
+ @pytest.mark.asyncio
+ async def test_midturn_system_inside_tool_exchange_keeps_the_pair_intact(self):
+ """A system row between an assistant tool call and its result must not split the
+ exchange into orphaned halves; it is emitted right after the exchange instead."""
+ handler = AnthropicMessagesHandler()
+ guardrail = MockCompactingGuardrail(
+ replacement_messages=[
+ {"role": "user", "content": "run the tool"},
+ {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [
+ {
+ "id": "call_1",
+ "type": "function",
+ "function": {"name": "get_weather", "arguments": "{}"},
+ }
+ ],
+ },
+ {"role": "system", "content": "use the corrected result"},
+ {"role": "tool", "tool_call_id": "call_1", "content": "sunny"},
+ ]
+ )
+ data = {
+ "model": "claude-3-5-sonnet-20241022",
+ "messages": [
+ {"role": "user", "content": "run the tool"},
+ {"role": "system", "content": "use the corrected result"},
+ ],
+ }
+
+ await handler.process_input_messages(data=data, guardrail_to_apply=guardrail)
+
+ assert [m["role"] for m in data["messages"]] == ["user", "assistant", "user", "system"]
+ assistant_blocks = data["messages"][1]["content"]
+ assert any(block.get("type") == "tool_use" and block.get("id") == "call_1" for block in assistant_blocks)
+ result_blocks = data["messages"][2]["content"]
+ assert [block["type"] for block in result_blocks] == ["tool_result"]
+ assert result_blocks[0]["tool_use_id"] == "call_1"
+ assert data["messages"][3]["content"] == "use the corrected result"
+
@pytest.mark.asyncio
async def test_compaction_rewrite_does_not_duplicate_hoisted_top_level_system(self):
handler = AnthropicMessagesHandler()