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(guardrails/headroom): stop compressing the turn the model must act on (#35294)

tin-berrib408b1d6dcdd
diff --git a/.github/workflows/test-unit-misc.yml b/.github/workflows/test-unit-misc.yml
index 7c3b195f0ad..9afaaaead93 100644
--- a/.github/workflows/test-unit-misc.yml
+++ b/.github/workflows/test-unit-misc.yml
@@ -27,6 +27,7 @@ jobs:
tests/test_litellm/a2a_protocol
tests/test_litellm/anthropic_interface
tests/test_litellm/completion_extras
+ tests/test_litellm/compression
tests/test_litellm/containers
tests/test_litellm/experimental_mcp_client
tests/test_litellm/models
diff --git a/litellm/compression/compress.py b/litellm/compression/compress.py
index 004dd82cbaa..9c5f57bc98f 100644
--- a/litellm/compression/compress.py
+++ b/litellm/compression/compress.py
@@ -3,6 +3,7 @@ Main compress() function — normalizes input messages, orchestrates BM25/embedd
scoring, message stubbing, and retrieval tool injection.
"""
+from collections.abc import Mapping, Sequence
from typing import Any, Dict, List, Optional, Set, Tuple, Union, cast
from litellm.caching.dual_cache import DualCache
@@ -204,33 +205,21 @@ def _extract_anthropic_tool_exchange_spans(
return spans, None
-def _get_protected_indices(messages: List[dict]) -> List[int]:
+def get_protected_indices(messages: Sequence[Mapping[str, object]]) -> tuple[int, ...]:
"""
Return indices of messages that must never be compressed:
- All system messages
- The last user message
- The last assistant message
- """
- protected: List[int] = []
-
- last_user_idx = None
- last_assistant_idx = None
-
- for i, msg in enumerate(messages):
- role = msg.get("role", "")
- if role == "system":
- protected.append(i)
- elif role == "user":
- last_user_idx = i
- elif role == "assistant":
- last_assistant_idx = i
- if last_user_idx is not None:
- protected.append(last_user_idx)
- if last_assistant_idx is not None:
- protected.append(last_assistant_idx)
-
- return protected
+ The last user message is what the model is being asked to act on right now,
+ so compressing it replaces the live instruction with a marker. Compression
+ guardrails share this policy; see the Headroom guardrail.
+ """
+ system_indices = tuple(index for index, msg in enumerate(messages) if msg.get("role", "") == "system")
+ last_user = tuple(index for index, msg in enumerate(messages) if msg.get("role", "") == "user")[-1:]
+ last_assistant = tuple(index for index, msg in enumerate(messages) if msg.get("role", "") == "assistant")[-1:]
+ return system_indices + last_user + last_assistant
def _combine_scores(
@@ -432,7 +421,7 @@ def compress(
combined_scores = bm25_scores
# Protected messages are never compressed
- protected_indices = _get_protected_indices(normalized_messages)
+ protected_indices = get_protected_indices(normalized_messages)
kept_indices: Set[int] = set(protected_indices)
tool_exchange_spans: List[Set[int]] = []
diff --git a/litellm/litellm_core_utils/prompt_templates/factory.py b/litellm/litellm_core_utils/prompt_templates/factory.py
index d8ce48f05de..0752bf2d771 100644
--- a/litellm/litellm_core_utils/prompt_templates/factory.py
+++ b/litellm/litellm_core_utils/prompt_templates/factory.py
@@ -6,7 +6,7 @@ import mimetypes
import re
import xml.etree.ElementTree as ET
from enum import Enum
-from collections.abc import Mapping
+from collections.abc import Iterator, Mapping, Sequence
from typing import Any, Dict, List, Optional, Set, Tuple, TypedDict, Union, cast, overload
from jinja2.sandbox import ImmutableSandboxedEnvironment
@@ -2210,6 +2210,49 @@ def _is_orphaned_tool_result(
return False
+def _declared_tool_call_ids(message: Mapping[str, Any]) -> frozenset[str]:
+ tool_calls = message.get("tool_calls")
+ if not isinstance(tool_calls, list):
+ return frozenset()
+ return frozenset(
+ str(tool_call["id"]) for tool_call in tool_calls if isinstance(tool_call, Mapping) and tool_call.get("id")
+ )
+
+
+def group_tool_exchanges(messages: Sequence[Mapping[str, Any]]) -> tuple[tuple[int, ...], ...]:
+ """Group message indices into tool exchanges: an assistant row that made
+ tool calls, together with the tool rows answering the ids it declared.
+
+ Membership is by ``tool_call_id`` ownership rather than adjacency, so a tool
+ row belonging to some other call opens its own group instead of being swept
+ into the exchange it happens to sit next to. Every other row is its own
+ group. Groups stay contiguous and in order, so a caller can convert or
+ protect them without reordering the conversation.
+
+ Callers need this because an assistant row and the tool rows answering it
+ are only well-formed together: ``sanitize_messages_for_tool_calling`` reads
+ an assistant row whose results are missing as an orphaned tool call, and
+ a tool row whose call is missing as an orphaned result.
+ """
+ return tuple(_iter_tool_exchange_groups(messages))
+
+
+def _iter_tool_exchange_groups(messages: Sequence[Mapping[str, Any]]) -> Iterator[tuple[int, ...]]:
+ index = 0
+ while index < len(messages):
+ declared = _declared_tool_call_ids(messages[index])
+ end = index + 1
+ while (
+ declared
+ and end < len(messages)
+ and messages[end].get("role") in ("tool", "function")
+ and str(messages[end].get("tool_call_id")) in declared
+ ):
+ end += 1
+ yield tuple(range(index, end))
+ index = end
+
+
def sanitize_messages_for_tool_calling(
messages: List[AllMessageValues],
) -> List[AllMessageValues]:
diff --git a/litellm/llms/anthropic/chat/guardrail_translation/handler.py b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
index 90f735707bf..a549db94224 100644
--- a/litellm/llms/anthropic/chat/guardrail_translation/handler.py
+++ b/litellm/llms/anthropic/chat/guardrail_translation/handler.py
@@ -361,14 +361,34 @@ class AnthropicMessagesHandler(BaseTranslation):
@staticmethod
def _write_back_structured_messages(data: dict, structured_messages: list) -> None:
- """Convert compressed structured_messages back to Anthropic format and write to data."""
+ """Convert compressed structured_messages back to Anthropic format and write to data.
+
+ ``anthropic_messages_pt`` merges every run of consecutive user/tool rows
+ into a single message, so a turn carrying only tool results and the user
+ turn that follows it come back fused, and the request the model sees no
+ longer has the boundaries the client sent. Converting a row at a time
+ would keep them apart but breaks tool pairing: an assistant row whose
+ tool results sit outside its own call reads as an orphaned tool call,
+ and under ``modify_params`` the sanitizer answers it with a synthetic
+ "tool execution skipped" result and drops the real one. Converting each
+ assistant row together with the tool rows that answer it, and every
+ other row on its own, satisfies both.
+ """
from litellm.litellm_core_utils.prompt_templates.factory import (
anthropic_messages_pt,
+ group_tool_exchanges,
)
model = str(data.get("model") or "")
non_system = [m for m in structured_messages if m.get("role") != "system"]
- converted = anthropic_messages_pt(messages=non_system, model=model, llm_provider="anthropic")
+ groups = tuple([non_system[index] for index in group] for group in group_tool_exchanges(non_system)) or (
+ non_system,
+ )
+ converted = [
+ message
+ for group in groups
+ for message in anthropic_messages_pt(messages=group, model=model, llm_provider="anthropic")
+ ]
for msg in converted:
content = msg.get("content")
if isinstance(content, list):
diff --git a/litellm/proxy/guardrails/guardrail_hooks/compresr/compresr.py b/litellm/proxy/guardrails/guardrail_hooks/compresr/compresr.py
index e512be23fc9..4627b298d09 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/compresr/compresr.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/compresr/compresr.py
@@ -48,6 +48,7 @@ from litellm.llms.custom_httpx.http_handler import (
)
from litellm.proxy._types import UserAPIKeyAuth
from litellm.proxy.guardrails.guardrail_hooks.content_text import (
+ assistant_text_from_response,
content_to_text,
is_all_text_parts,
merge_rewritten_text_parts,
@@ -391,47 +392,6 @@ def _is_anthropic_messages_response(response: object) -> bool:
return isinstance(get_attribute_or_key(response, "content", None), list)
-def _assistant_text_from_response(response: object) -> str | None:
- """The assistant's natural-language text from a model response, across chat,
- Anthropic, and Responses shapes. Preserved when the turn is rebuilt for the
- retrieval follow-up so the model's reasoning is not lost."""
- choices = get_attribute_or_key(response, "choices", None)
- if isinstance(choices, list) and choices:
- message = get_attribute_or_key(choices[0], "message", None)
- if message is not None:
- text = content_to_text(get_attribute_or_key(message, "content", None))
- if text:
- return text
- content = get_attribute_or_key(response, "content", None)
- if isinstance(content, list):
- parts = [
- text
- for block in content
- if get_attribute_or_key(block, "type", None) == "text"
- for text in (get_attribute_or_key(block, "text", None),)
- if isinstance(text, str) and text
- ]
- if parts:
- return "".join(parts)
- output = get_attribute_or_key(response, "output", None)
- if isinstance(output, list):
- parts = []
- for item in output:
- if get_attribute_or_key(item, "type", None) != "message":
- continue
- item_content = get_attribute_or_key(item, "content", None)
- if not isinstance(item_content, list):
- continue
- for chunk in item_content:
- if get_attribute_or_key(chunk, "type", None) == "output_text":
- text = get_attribute_or_key(chunk, "text", None)
- if isinstance(text, str) and text:
- parts.append(text)
- if parts:
- return "".join(parts)
- return None
-
-
def _build_assistant_message_from_response(
response: object,
retrieved: list[tuple[dict[str, object], str]],
@@ -446,7 +406,7 @@ def _build_assistant_message_from_response(
"""
return {
"role": "assistant",
- "content": _assistant_text_from_response(response),
+ "content": assistant_text_from_response(response),
"tool_calls": [
{
"id": tool_call.get("id"),
@@ -470,7 +430,7 @@ def _build_anthropic_followup_messages(
assistant text is preserved; non-retrieve tool calls are re-planned by the
follow-up (see _build_assistant_message_from_response)."""
assistant_content: list[dict[str, object]] = []
- text = _assistant_text_from_response(response)
+ text = assistant_text_from_response(response)
if text:
assistant_content.append({"type": "text", "text": text})
assistant_content.extend(
@@ -501,7 +461,7 @@ def _build_responses_followup_items(
with a function_call_output keyed by the same call_id. The assistant text is
preserved; non-retrieve tool calls are re-planned by the follow-up."""
items: list[dict[str, object]] = []
- text = _assistant_text_from_response(response)
+ text = assistant_text_from_response(response)
if text:
items.append({"role": "assistant", "content": text})
for tool_call, content in retrieved:
diff --git a/litellm/proxy/guardrails/guardrail_hooks/content_text.py b/litellm/proxy/guardrails/guardrail_hooks/content_text.py
index f4211e67512..4111c909d01 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/content_text.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/content_text.py
@@ -14,6 +14,8 @@ non-text part, which is what ``is_all_text_parts`` gates.
from collections.abc import Sequence
+from litellm.litellm_core_utils.prompt_templates.factory import get_attribute_or_key
+
def content_to_text(content: object) -> str:
"""Collapse a message ``content`` (str or list-of-parts) to plain text.
@@ -53,3 +55,41 @@ def merge_rewritten_text_parts(parts: Sequence[object], new_text: str) -> list[o
breakpoints = tuple(part["cache_control"] for part in dict_parts if part.get("cache_control") is not None)
base = {**dict_parts[0], "text": new_text} if dict_parts else {"type": "text", "text": new_text}
return [{**base, "cache_control": breakpoints[-1]} if breakpoints else base]
+
+
+def assistant_text_from_response(response: object) -> str | None:
+ """The assistant's natural-language text from a model response, across chat,
+ Anthropic, and Responses shapes. Preserved when the turn is rebuilt for the
+ retrieval follow-up so the model's reasoning is not lost."""
+ choices = get_attribute_or_key(response, "choices", None)
+ if isinstance(choices, list) and choices:
+ message = get_attribute_or_key(choices[0], "message", None)
+ if message is not None:
+ text = content_to_text(get_attribute_or_key(message, "content", None))
+ if text:
+ return text
+ content = get_attribute_or_key(response, "content", None)
+ if isinstance(content, list):
+ parts = [
+ text
+ for block in content
+ if get_attribute_or_key(block, "type", None) == "text"
+ for text in (get_attribute_or_key(block, "text", None),)
+ if isinstance(text, str) and text
+ ]
+ if parts:
+ return "".join(parts)
+ output = get_attribute_or_key(response, "output", None)
+ if isinstance(output, list):
+ output_parts = [
+ text
+ for item in output
+ if get_attribute_or_key(item, "type", None) == "message"
+ for chunk in (get_attribute_or_key(item, "content", None) or ())
+ if get_attribute_or_key(chunk, "type", None) == "output_text"
+ for text in (get_attribute_or_key(chunk, "text", None),)
+ if isinstance(text, str) and text
+ ]
+ if output_parts:
+ return "".join(output_parts)
+ return None
diff --git a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
index 2735acd7787..1667bb604ba 100644
--- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
+++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py
@@ -7,6 +7,7 @@ import uuid
from typing import TYPE_CHECKING, Any, ClassVar, List, Literal, Optional
import httpx
+from collections.abc import Mapping, Sequence
from fastapi import HTTPException
import litellm
@@ -15,6 +16,7 @@ from litellm.proxy.spend_tracking.compression_savings import HEADROOM_GUARDRAIL_
from typing_extensions import TypeGuard
from litellm._logging import verbose_proxy_logger
+from litellm.compression.compress import get_protected_indices
from litellm.integrations.custom_guardrail import (
CustomGuardrail,
log_guardrail_information,
@@ -22,6 +24,7 @@ from litellm.integrations.custom_guardrail import (
from litellm.litellm_core_utils.prompt_templates.factory import (
get_attribute_or_key,
get_tool_calls_from_response,
+ group_tool_exchanges,
has_tool_with_name,
)
from litellm.llms.custom_httpx.http_handler import (
@@ -29,6 +32,7 @@ from litellm.llms.custom_httpx.http_handler import (
httpxSpecialProvider,
)
from litellm.proxy.guardrails.guardrail_hooks.content_text import (
+ assistant_text_from_response,
content_to_text,
is_all_text_parts,
merge_rewritten_text_parts,
@@ -110,6 +114,42 @@ def _restore_content_shapes(
return restored
+def _protected_indices(messages: Sequence[Mapping[str, object]]) -> frozenset[int]:
+ """Indices headroom must not send to the compression service.
+
+ ``get_protected_indices`` is litellm's own compression policy: the system
+ rows, the last user row, the last assistant row. It is expanded over whole
+ tool exchanges the way ``compress()`` expands it, so a protected assistant
+ tool call cannot end up answered by a marker standing in for the result the
+ model just asked for.
+ """
+ protected = frozenset(get_protected_indices(messages))
+ return protected | frozenset(
+ index
+ for group in group_tool_exchanges(messages)
+ if any(member in protected for member in group)
+ for index in group
+ )
+
+
+def _restore_protected_messages(
+ messages: Sequence[dict[str, object]],
+ compressed: Sequence[dict[str, object]],
+ protected_indices: frozenset[int],
+) -> Sequence[dict[str, object]]:
+ """Put the rows that were held back from compression at their original positions.
+
+ Requires one returned row per row actually sent, which ``_call_compress``
+ enforces; a service that changed the row count is treated as a failure
+ there, because a reshaped conversation cannot be re-interleaved.
+ """
+ sent_positions = tuple(index for index in range(len(messages)) if index not in protected_indices)
+ compressed_by_index = dict(zip(sent_positions, compressed))
+ return [
+ messages[index] if index in protected_indices else compressed_by_index[index] for index in range(len(messages))
+ ]
+
+
def extract_hashes_from_messages(messages: list[dict[str, object]]) -> list[str]:
hashes: list[str] = []
for msg in messages:
@@ -175,30 +215,33 @@ def _extract_headroom_tool_calls(response: object) -> list[dict[str, object]]:
]
-def _build_assistant_message_from_response(response: object) -> dict[str, object]:
- choices = getattr(response, "choices", None)
- if not isinstance(choices, list) or not choices:
- return {"role": "assistant", "content": None, "tool_calls": []}
- message = getattr(choices[0], "message", None)
- if message is None:
- return {"role": "assistant", "content": None, "tool_calls": []}
- content = getattr(message, "content", None)
- tool_calls = getattr(message, "tool_calls", None)
- raw_tool_calls: list[dict[str, object]] = []
- if isinstance(tool_calls, list):
- for tc in tool_calls:
- fn = getattr(tc, "function", None)
- raw_tool_calls.append(
- {
- "id": getattr(tc, "id", None),
- "type": "function",
- "function": {
- "name": getattr(fn, "name", None) if fn else None,
- "arguments": getattr(fn, "arguments", "{}") if fn else "{}",
- },
- }
- )
- return {"role": "assistant", "content": content, "tool_calls": raw_tool_calls}
+def _build_assistant_message_from_response(
+ response: object,
+ retrieved: Sequence[tuple[dict[str, object], str]],
+) -> dict[str, object]:
+ """Rebuild the chat-completions assistant turn for the retrieval follow-up.
+
+ Only the ``headroom_retrieve`` calls are echoed, each answered by a tool
+ result below. Other tool calls made in the same turn are omitted on purpose:
+ the follow-up re-runs the model with the recovered content so it re-plans
+ them. Echoing them would leave tool_calls with no matching tool result and
+ the provider would reject the request.
+ """
+ return {
+ "role": "assistant",
+ "content": assistant_text_from_response(response),
+ "tool_calls": [
+ {
+ "id": tool_call.get("id"),
+ "type": "function",
+ "function": {
+ "name": tool_call.get("name"),
+ "arguments": json.dumps(tool_call.get("arguments", {})),
+ },
+ }
+ for tool_call, _ in retrieved
+ ],
+ }
def _is_responses_api_response(response: object) -> bool:
@@ -213,17 +256,22 @@ def _is_anthropic_messages_response(response: object) -> bool:
def _build_anthropic_followup_messages(
+ response: object,
retrieved: list[tuple[dict[str, object], str]],
) -> list[dict[str, object]]:
"""Build Anthropic Messages API follow-up messages for a tool round-trip.
Anthropic requires the tool_use block to be echoed back in an assistant
message, paired with a tool_result block in a user message keyed by the
- same tool_use_id -- it does not accept chat-style tool-role messages.
+ same tool_use_id -- it does not accept chat-style tool-role messages. Any
+ text the model wrote alongside the tool call is preserved, so its reasoning
+ survives into the follow-up turn.
"""
+ text = assistant_text_from_response(response)
assistant_message: dict[str, object] = {
"role": "assistant",
- "content": [
+ "content": ([{"type": "text", "text": text}] if text else [])
+ + [
{
"type": "tool_use",
"id": tool_call.get("id"),
@@ -244,15 +292,18 @@ def _build_anthropic_followup_messages(
def _build_responses_followup_items(
+ response: object,
retrieved: list[tuple[dict[str, object], str]],
) -> list[dict[str, object]]:
"""Build Responses API input items for a tool round-trip.
The Responses API does not accept chat-style assistant/tool messages as
follow-up input; it requires the model's function_call to be echoed back
- paired with a function_call_output keyed by the same call_id.
+ paired with a function_call_output keyed by the same call_id. Any text the
+ model wrote alongside the tool call is preserved.
"""
- items: list[dict[str, object]] = []
+ text = assistant_text_from_response(response)
+ items: List[dict[str, object]] = [{"role": "assistant", "content": text}] if text else []
for tool_call, content in retrieved:
call_id = tool_call.get("id")
items.append(
@@ -453,6 +504,19 @@ class HeadroomGuardrail(CustomGuardrail):
{},
)
+ if len(filtered) != len(messages):
+ # Rows are matched positionally when the never-compressed messages
+ # are put back, so a reshaped conversation cannot be applied at all.
+ return (
+ self._handle_compress_failure(
+ messages,
+ "Headroom compression service changed the message count",
+ {"sent": len(messages), "returned": len(filtered)},
+ ),
+ False,
+ {},
+ )
+
verbose_proxy_logger.debug(
"Headroom: compressed %s tokens -> %s tokens (ratio %.2f)",
body.get("tokens_before", "?"),
@@ -547,14 +611,27 @@ class HeadroomGuardrail(CustomGuardrail):
if not messages:
return inputs
+ # The last user message is the instruction the model is being asked to
+ # act on, so replacing it with a marker means the model answers a
+ # retrieval result instead of the request. Protected rows are held back
+ # from the payload rather than pinned after the fact, so their tokens
+ # are not counted as savings we never apply; the Anthropic write-back
+ # discards a compressed system prompt outright. Keep it that way unless
+ # /v1/compress grows a field for sending the live turn as the retrieval
+ # query without compressing it: query-aware compression reads the newest
+ # user message, so it is withheld here at some cost to history ranking.
+ protected_indices = _protected_indices(messages)
+ compressible = [m for i, m in enumerate(messages) if i not in protected_indices]
+ if not compressible:
+ return inputs
+
model = self.headroom_model or request_data.get("model")
start_time = time.time()
- compressed, compression_succeeded, stats = await self._call_compress(
- messages=_flatten_messages_for_compression(messages),
+ returned, compression_succeeded, stats = await self._call_compress(
+ messages=_flatten_messages_for_compression(compressible),
model=model if isinstance(model, str) else None,
)
end_time = time.time()
- compressed = _restore_content_shapes(originals=messages, returned=compressed)
from litellm.proxy.common_utils.callback_utils import (
add_guardrail_to_applied_guardrails_header,
@@ -571,7 +648,17 @@ class HeadroomGuardrail(CustomGuardrail):
duration=end_time - start_time,
)
add_guardrail_to_applied_guardrails_header(request_data=request_data, guardrail_name=self.guardrail_name)
- return {**inputs, "structured_messages": compressed} # pyright: ignore[reportReturnType]
+ # Hand back the caller's own inputs object. Translation handlers
+ # detect "the guardrail rewrote the messages" by identity, so
+ # returning a rebuilt copy sends an unchanged request through the
+ # write-back and restructures it for nothing.
+ return inputs
+
+ compressed = _restore_protected_messages(
+ messages=messages,
+ compressed=_restore_content_shapes(originals=compressible, returned=returned),
+ protected_indices=protected_indices,
+ )
self.add_standard_logging_guardrail_information_to_request_data(
guardrail_json_response=stats,
@@ -668,11 +755,11 @@ class HeadroomGuardrail(CustomGuardrail):
retrieved.append((tc, content))
if _is_responses_api_response(response):
- follow_up_messages = list(messages) + _build_responses_followup_items(retrieved)
+ follow_up_messages = list(messages) + _build_responses_followup_items(response, retrieved)
elif _is_anthropic_messages_response(response):
- follow_up_messages = list(messages) + _build_anthropic_followup_messages(retrieved)
+ follow_up_messages = list(messages) + _build_anthropic_followup_messages(response, retrieved)
else:
- assistant_message = _build_assistant_message_from_response(response)
+ assistant_message = _build_assistant_message_from_response(response, retrieved)
tool_results = [
{"role": "tool", "tool_call_id": tc.get("id"), "content": content} for tc, content in retrieved
]
diff --git a/tests/test_litellm/compression/test_compress.py b/tests/test_litellm/compression/test_compress.py
new file mode 100644
index 00000000000..6827c37dfd5
--- /dev/null
+++ b/tests/test_litellm/compression/test_compress.py
@@ -0,0 +1,55 @@
+"""
+Unit tests for litellm.compression.compress helpers.
+
+get_protected_indices is the shared policy for which messages a compressor may
+never rewrite. It is consumed by compress() and by the Headroom guardrail, so
+the two agree on what "never compress this" means.
+"""
+
+from litellm.compression.compress import get_protected_indices
+
+
+def test_protects_system_last_user_and_last_assistant():
+ messages = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "old question"},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "user", "content": "newer question"},
+ {"role": "assistant", "content": "newer answer"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ assert sorted(get_protected_indices(messages)) == [0, 4, 5]
+
+
+def test_history_is_not_protected():
+ messages = [
+ {"role": "user", "content": "old question"},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "tool", "tool_call_id": "t1", "content": "old tool output"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ protected = sorted(get_protected_indices(messages))
+
+ assert protected == [1, 3]
+ # The tool row and the older user turn stay compressible; protection that
+ # covered everything would make compression a no-op.
+ assert 0 not in protected
+ assert 2 not in protected
+
+
+def test_every_system_row_is_protected():
+ messages = [
+ {"role": "system", "content": "first"},
+ {"role": "user", "content": "q"},
+ {"role": "system", "content": "second, injected mid conversation"},
+ {"role": "user", "content": "live"},
+ ]
+
+ assert sorted(get_protected_indices(messages)) == [0, 2, 3]
+
+
+def test_no_user_or_assistant_rows():
+ assert sorted(get_protected_indices([{"role": "system", "content": "sys"}])) == [0]
+ assert get_protected_indices([]) == ()
diff --git a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
index 9565de1139c..dc745abb9e7 100644
--- a/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
+++ b/tests/test_litellm/litellm_core_utils/prompt_templates/test_litellm_core_utils_prompt_templates_factory.py
@@ -3197,3 +3197,75 @@ def test_get_tool_calls_from_response_include_all_choices_reads_every_choice():
names = [tc["name"] for tc in get_tool_calls_from_response(response, include_all_choices=True)]
assert names == ["tool_alpha", "tool_beta"]
+
+
+def test_group_tool_exchanges_pairs_assistant_with_its_tool_rows():
+ from litellm.litellm_core_utils.prompt_templates.factory import group_tool_exchanges
+
+ messages = [
+ {"role": "user", "content": "first turn"},
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [
+ {"id": "tu_1", "type": "function", "function": {"name": "Read", "arguments": "{}"}},
+ {"id": "tu_2", "type": "function", "function": {"name": "Grep", "arguments": "{}"}},
+ ],
+ },
+ {"role": "tool", "tool_call_id": "tu_1", "content": "file body"},
+ {"role": "tool", "tool_call_id": "tu_2", "content": "matches"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ assert group_tool_exchanges(messages) == ((0,), (1, 2, 3), (4,))
+
+
+def test_group_tool_exchanges_uses_ownership_not_adjacency():
+ """A tool row answering some other call must not be swept into the exchange
+ it happens to sit next to."""
+ from litellm.litellm_core_utils.prompt_templates.factory import group_tool_exchanges
+
+ messages = [
+ {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{"id": "tu_1", "type": "function", "function": {"name": "Read", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "unrelated", "content": "not an answer to tu_1"},
+ {"role": "tool", "tool_call_id": "tu_1", "content": "file body"},
+ ]
+
+ assert group_tool_exchanges(messages) == ((0,), (1,), (2,))
+
+
+def test_group_tool_exchanges_assistant_without_tool_calls_stands_alone():
+ from litellm.litellm_core_utils.prompt_templates.factory import group_tool_exchanges
+
+ messages = [
+ {"role": "assistant", "content": "no tools here"},
+ {"role": "user", "content": "next"},
+ ]
+
+ assert group_tool_exchanges(messages) == ((0,), (1,))
+ assert group_tool_exchanges([]) == ()
+
+
+def test_group_tool_exchanges_is_linear_in_message_count():
+ """Grouping runs on every guardrail write-back, over a message array the
+ caller controls, so it has to stay linear. Accumulating groups by rebuilding
+ a tuple each iteration made this O(n^2): 20k standalone messages took 312ms
+ and 100k would take minutes. Linear finishes in single-digit ms, so this
+ ceiling has ~200x headroom while a quadratic rewrite blows straight past it.
+ """
+ import time
+
+ from litellm.litellm_core_utils.prompt_templates.factory import group_tool_exchanges
+
+ messages = [{"role": "user", "content": "x"} for _ in range(100_000)]
+
+ started = time.perf_counter()
+ groups = group_tool_exchanges(messages)
+ elapsed = time.perf_counter() - started
+
+ assert len(groups) == 100_000
+ assert elapsed < 3.0, f"grouping 100k messages took {elapsed:.2f}s; suspect superlinear accumulation"
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
index 248893ed153..00ab39357b4 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
@@ -43,21 +43,35 @@ from litellm.types.utils import GenericGuardrailAPIInputs
FAKE_API_BASE = "https://headroom.example.com"
FAKE_API_KEY = "test-key"
+# The system prompt, the last user turn and the last assistant turn are never
+# sent to the compression service, so a fixture needs history for anything to
+# be eligible: only index 1 is.
ORIGINAL_MESSAGES = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "A" * 5000},
+ {"role": "assistant", "content": "Understood."},
+ {"role": "user", "content": "and what about B?"},
]
-COMPRESSED_MESSAGES = [
- {"role": "system", "content": "You are a helpful assistant."},
- {"role": "user", "content": "A" * 500},
-]
+COMPRESSIBLE_MESSAGES = [ORIGINAL_MESSAGES[1]]
+COMPRESSED_MESSAGES = [{"role": "user", "content": "A" * 500}]
COMPRESSED_MESSAGES_WITH_HASH = [
- {"role": "system", "content": "You are a helpful assistant."},
{
"role": "user",
"content": "Summary. Retrieve more: hash=b573993006976af767214fac",
},
]
+EXPECTED_MESSAGES = [
+ ORIGINAL_MESSAGES[0],
+ COMPRESSED_MESSAGES[0],
+ ORIGINAL_MESSAGES[2],
+ ORIGINAL_MESSAGES[3],
+]
+EXPECTED_MESSAGES_WITH_HASH = [
+ ORIGINAL_MESSAGES[0],
+ COMPRESSED_MESSAGES_WITH_HASH[0],
+ ORIGINAL_MESSAGES[2],
+ ORIGINAL_MESSAGES[3],
+]
def _make_guardrail(**kwargs) -> HeadroomGuardrail:
@@ -161,7 +175,7 @@ async def test_apply_guardrail_compresses_and_returns_structured_messages(
input_type="request",
)
- assert result.get("structured_messages") == COMPRESSED_MESSAGES
+ assert result.get("structured_messages") == EXPECTED_MESSAGES
entries = _recorded_guardrail_entries(request_data)
assert len(entries) == 1
@@ -275,7 +289,7 @@ async def test_apply_guardrail_skips_derivation_for_non_numeric_token_counts(
assert "tokens_saved" not in _recorded_guardrail_response(request_data)
# Compression itself is unaffected by the skipped derivation.
- assert result.get("structured_messages") == COMPRESSED_MESSAGES
+ assert result.get("structured_messages") == EXPECTED_MESSAGES
@pytest.mark.asyncio
@@ -1571,9 +1585,15 @@ PARTS_MESSAGES = [
"role": "system",
"content": [
{"type": "text", "text": "You are Claude Code.", "cache_control": {"type": "ephemeral"}},
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "Earlier turn.", "cache_control": {"type": "ephemeral"}},
{
"type": "text",
- "text": "Second system block. " + "B" * 5000,
+ "text": "Second block. " + "B" * 5000,
"cache_control": {"type": "ephemeral", "ttl": "1h"},
},
],
@@ -1586,9 +1606,10 @@ PARTS_MESSAGES = [
],
},
{"role": "tool", "content": "tool output " + "C" * 500},
+ {"role": "user", "content": "what does that file do?"},
]
-FLATTENED_SYSTEM_TEXT = "You are Claude Code.\n\nSecond system block. " + "B" * 5000
+FLATTENED_HISTORY_TEXT = "Earlier turn.\n\nSecond block. " + "B" * 5000
def _parts_copy() -> list:
@@ -1596,10 +1617,13 @@ def _parts_copy() -> list:
def _echo_wire_view() -> list:
- """What the service receives (and echoes back when it changes nothing)."""
+ """What the service receives (and echoes back when it changes nothing).
+
+ The system row and the trailing user row are never sent.
+ """
return [
- {"role": "system", "content": FLATTENED_SYSTEM_TEXT},
- json.loads(json.dumps(PARTS_MESSAGES[1])),
+ {"role": "user", "content": FLATTENED_HISTORY_TEXT},
+ json.loads(json.dumps(PARTS_MESSAGES[2])),
{"role": "tool", "content": "tool output " + "C" * 500},
]
@@ -1627,7 +1651,7 @@ async def test_apply_guardrail_flattens_all_text_rows_only(
)
wire_messages = mock_post.call_args.kwargs["json"]["messages"]
- assert wire_messages[0]["content"] == FLATTENED_SYSTEM_TEXT
+ assert wire_messages[0]["content"] == FLATTENED_HISTORY_TEXT
# Mixed text+image row is never flattened: merging its text would move a
# later cache_control breakpoint across the image part.
assert isinstance(wire_messages[1]["content"], list)
@@ -1643,7 +1667,7 @@ async def test_apply_guardrail_restores_rewritten_all_text_row(
structured_messages=_parts_copy(),
)
compressed = _echo_wire_view()
- compressed[0]["content"] = "compressed system. Retrieve more: hash=b573993006976af767214fac"
+ compressed[0]["content"] = "compressed history. Retrieve more: hash=b573993006976af767214fac"
mock_response = _make_compress_response(compressed)
with patch.object(
@@ -1659,17 +1683,17 @@ async def test_apply_guardrail_restores_rewritten_all_text_row(
)
messages = result["structured_messages"]
- system_content = messages[0]["content"]
+ history_content = messages[1]["content"]
# Rewritten all-text row collapses to one part carrying the LAST declared
# breakpoint: an Anthropic breakpoint caches the prefix ending at its
# part, so after the merge the last one (and its TTL) still describes the
# row.
- assert isinstance(system_content, list)
- assert len(system_content) == 1
- assert system_content[0]["text"] == "compressed system. Retrieve more: hash=b573993006976af767214fac"
- assert system_content[0]["cache_control"] == {"type": "ephemeral", "ttl": "1h"}
+ assert isinstance(history_content, list)
+ assert len(history_content) == 1
+ assert history_content[0]["text"] == "compressed history. Retrieve more: hash=b573993006976af767214fac"
+ assert history_content[0]["cache_control"] == {"type": "ephemeral", "ttl": "1h"}
# Mixed row passes through byte-identical.
- assert messages[1]["content"] == PARTS_MESSAGES[1]["content"]
+ assert messages[2]["content"] == PARTS_MESSAGES[2]["content"]
# Hashes inside restored parts still drive retrieve-tool injection.
assert has_headroom_retrieve_tool(result.get("tools") or [])
@@ -1701,19 +1725,43 @@ async def test_apply_guardrail_keeps_originals_when_service_echoes_unchanged(
@pytest.mark.asyncio
-async def test_apply_guardrail_adopts_service_output_when_rows_dropped(
+async def test_apply_guardrail_rejects_service_output_when_rows_dropped(
guardrail: HeadroomGuardrail,
):
+ """A reshaped conversation cannot be applied at all: the rows held back from
+ compression are matched positionally, so a response with a different row
+ count goes through the fail policy instead of being adopted."""
inputs = GenericGuardrailAPIInputs(
texts=["B" * 5000],
structured_messages=_parts_copy(),
)
- dropped = [
- {"role": "system", "content": FLATTENED_SYSTEM_TEXT},
- {"role": "user", "content": "B" * 50},
- ]
+ dropped = [{"role": "user", "content": "B" * 50}]
mock_response = _make_compress_response(dropped)
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ return_value=mock_response,
+ ):
+ with pytest.raises(HTTPException) as exc_info:
+ await guardrail.apply_guardrail(
+ inputs=inputs,
+ request_data={"model": "claude-fable-5"},
+ input_type="request",
+ )
+
+ assert exc_info.value.status_code == 502
+ assert "changed the message count" in str(exc_info.value.detail)
+
+
+async def test_apply_guardrail_forwards_original_when_rows_dropped_and_fail_open():
+ guardrail = _make_guardrail(unreachable_fallback="fail_open")
+ original = _parts_copy()
+ inputs = GenericGuardrailAPIInputs(texts=["B" * 5000], structured_messages=original)
+ mock_response = _make_compress_response([{"role": "user", "content": "B" * 50}])
+
with patch.object(
guardrail.async_handler,
"post",
@@ -1726,7 +1774,10 @@ async def test_apply_guardrail_adopts_service_output_when_rows_dropped(
input_type="request",
)
- assert result["structured_messages"] == dropped
+ # Same object back, so translation handlers that detect a rewrite by
+ # identity leave the request alone instead of round-tripping it.
+ assert result is inputs
+ assert result["structured_messages"] is original
@pytest.mark.asyncio
@@ -1739,7 +1790,7 @@ async def test_apply_guardrail_sends_textless_parts_rows_unflattened(
]
inputs = GenericGuardrailAPIInputs(
texts=["D" * 5000],
- structured_messages=json.loads(json.dumps(image_only)),
+ structured_messages=json.loads(json.dumps(image_only)) + [{"role": "user", "content": "and now?"}],
)
mock_response = _make_compress_response(json.loads(json.dumps(image_only)))
@@ -1782,3 +1833,243 @@ async def test_fail_open_returns_original_parts_shapes():
messages = result["structured_messages"]
assert [m["content"] for m in messages] == [m["content"] for m in PARTS_MESSAGES]
+
+
+# ---------------------------------------------------------------------------
+# LIT-5018: the turn the model is being asked to act on is never compressed.
+#
+# A Claude Code request ends with the live instruction, preceded by the tool
+# result answering the assistant's last tool call. Replacing either with a
+# marker makes the model answer a retrieval result instead of the request.
+# ---------------------------------------------------------------------------
+
+AGENTIC_MESSAGES = [
+ {"role": "system", "content": "You are Claude Code. " + "S" * 5000},
+ {"role": "user", "content": "H" * 5000},
+ {"role": "assistant", "content": "Older answer. " + "O" * 5000},
+ {"role": "tool", "tool_call_id": "old_1", "content": "older tool output " + "T" * 5000},
+ {
+ "role": "assistant",
+ "content": "Reading the file now.",
+ "tool_calls": [{"id": "tu_1", "type": "function", "function": {"name": "Read", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "tu_1", "content": "FILE BODY " + "F" * 5000},
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "<team expansion> " + "E" * 5000},
+ {"type": "text", "text": "can we run /team to fix this"},
+ ],
+ },
+]
+
+
+async def _wire_and_result(guardrail: HeadroomGuardrail, messages: list, returned: list | None = None):
+ inputs = GenericGuardrailAPIInputs(texts=["x"], structured_messages=json.loads(json.dumps(messages)))
+ sent: dict = {}
+
+ def _echo(**kwargs):
+ sent["messages"] = kwargs["json"]["messages"]
+ return _make_compress_response(
+ returned if returned is not None else json.loads(json.dumps(kwargs["json"]["messages"]))
+ )
+
+ with patch.object(guardrail.async_handler, "post", new_callable=AsyncMock, side_effect=_echo):
+ result = await guardrail.apply_guardrail(
+ inputs=inputs,
+ request_data={"model": "claude-sonnet-4-5-20250929"},
+ input_type="request",
+ )
+ return sent["messages"], result
+
+
+async def test_live_user_turn_is_never_sent_for_compression(guardrail: HeadroomGuardrail):
+ wire, result = await _wire_and_result(guardrail, AGENTIC_MESSAGES)
+
+ live_turn = AGENTIC_MESSAGES[-1]
+ assert live_turn not in wire
+ assert not any("can we run /team to fix this" in json.dumps(row) for row in wire)
+ # It reaches the model byte-identical, both text parts intact, so no
+ # marker and no retrieval round-trip stands in for the instruction.
+ assert result["structured_messages"][-1] == live_turn
+
+
+async def test_system_prompt_is_never_sent_for_compression(guardrail: HeadroomGuardrail):
+ wire, result = await _wire_and_result(guardrail, AGENTIC_MESSAGES)
+
+ assert not any(row.get("role") == "system" for row in wire)
+ # The Anthropic write-back drops compressed system rows, so sending it
+ # only inflates the savings the service reports back.
+ assert result["structured_messages"][0] == AGENTIC_MESSAGES[0]
+
+
+async def test_trailing_tool_exchange_is_never_sent_for_compression(guardrail: HeadroomGuardrail):
+ """The tool result answering the last assistant's tool call is protected
+ with it: a marker there stands in for the result of the call the model just
+ made, forcing an immediate retrieval of data it already asked for."""
+ wire, result = await _wire_and_result(guardrail, AGENTIC_MESSAGES)
+
+ assert not any(row.get("tool_call_id") == "tu_1" for row in wire)
+ assert result["structured_messages"][5] == AGENTIC_MESSAGES[5]
+
+
+async def test_history_is_still_compressed(guardrail: HeadroomGuardrail):
+ """Negative control: protection must not turn compression into a no-op."""
+ compressed_history = [
+ {"role": "user", "content": "hist. hash=b573993006976af767214fac"},
+ {"role": "assistant", "content": "older. hash=a73993006976af767214fac1"},
+ {"role": "tool", "tool_call_id": "old_1", "content": "older tool. hash=c73993006976af767214fac2"},
+ ]
+ wire, result = await _wire_and_result(guardrail, AGENTIC_MESSAGES, returned=compressed_history)
+
+ # Exactly the three history rows go to the service, in order.
+ assert [row["role"] for row in wire] == ["user", "assistant", "tool"]
+ assert wire[0]["content"] == "H" * 5000
+ assert wire[2]["tool_call_id"] == "old_1"
+
+ messages = result["structured_messages"]
+ assert len(messages) == len(AGENTIC_MESSAGES)
+ assert messages[1] == compressed_history[0]
+ assert messages[2] == compressed_history[1]
+ assert messages[3] == compressed_history[2]
+ # Hashes in the compressed history still drive retrieve-tool injection.
+ assert has_headroom_retrieve_tool(result.get("tools") or [])
+
+
+async def test_nothing_compressible_returns_inputs_untouched(guardrail: HeadroomGuardrail):
+ """A single-turn request is all protected, so there is nothing to send and
+ the caller's own inputs object comes back."""
+ inputs = GenericGuardrailAPIInputs(
+ texts=["A" * 5000],
+ structured_messages=[
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "A" * 5000},
+ ],
+ )
+
+ with patch.object(guardrail.async_handler, "post", new_callable=AsyncMock) as mock_post:
+ result = await guardrail.apply_guardrail(
+ inputs=inputs,
+ request_data={"model": "gpt-4o"},
+ input_type="request",
+ )
+
+ mock_post.assert_not_called()
+ assert result is inputs
+
+
+async def test_fail_open_returns_the_caller_inputs_object():
+ """Translation handlers detect a rewrite by object identity, so a request
+ that was not compressed must come back as the same object or it is
+ round-tripped through the write-back for nothing."""
+ guardrail = _make_guardrail(unreachable_fallback="fail_open")
+ original = json.loads(json.dumps(AGENTIC_MESSAGES))
+ inputs = GenericGuardrailAPIInputs(texts=["x"], structured_messages=original)
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ side_effect=httpx.ConnectError("boom"),
+ ):
+ result = await guardrail.apply_guardrail(inputs=inputs, request_data={}, input_type="request")
+
+ assert result is inputs
+ assert result["structured_messages"] is original
+
+
+# ---------------------------------------------------------------------------
+# LIT-5018: the retrieval follow-up keeps the model's own text.
+# ---------------------------------------------------------------------------
+
+
+def _anthropic_response_with_text_and_tool_call() -> dict:
+ return {
+ "content": [
+ {"type": "text", "text": "Let me pull the original back."},
+ {"type": "tool_use", "id": "call_1", "name": HEADROOM_RETRIEVE_TOOL_NAME, "input": {"hash": "h" * 24}},
+ ]
+ }
+
+
+async def _plan_for(guardrail: HeadroomGuardrail, response, messages: list):
+ guardrail._issued_hashes_by_call_id["call-1"] = (frozenset({"h" * 24}), time.monotonic() + 60)
+ logging_obj = MagicMock()
+ logging_obj.litellm_call_id = "call-1"
+ logging_obj.model_call_details = {}
+ with patch.object(
+ guardrail.async_handler,
+ "get",
+ new_callable=AsyncMock,
+ return_value=_make_retrieve_response("ORIGINAL CONTENT"),
+ ):
+ return await guardrail.async_build_agentic_loop_plan(
+ tools={"tool_calls": [{"id": "call_1", "name": HEADROOM_RETRIEVE_TOOL_NAME, "arguments": {"hash": "h" * 24}}]},
+ model="claude-sonnet-4-5-20250929",
+ messages=messages,
+ response=response,
+ anthropic_messages_provider_config=None,
+ anthropic_messages_optional_request_params={},
+ logging_obj=logging_obj,
+ stream=False,
+ kwargs={},
+ )
+
+
+async def test_anthropic_followup_preserves_assistant_text(guardrail: HeadroomGuardrail):
+ plan = await _plan_for(guardrail, _anthropic_response_with_text_and_tool_call(), [{"role": "user", "content": "q"}])
+
+ assistant = plan.request_patch.messages[-2] # type: ignore[union-attr]
+ assert assistant["role"] == "assistant"
+ # Text first, then the tool_use it accompanied: dropping it loses the
+ # model's stated reason for the retrieval from its own transcript.
+ assert assistant["content"][0] == {"type": "text", "text": "Let me pull the original back."}
+ assert assistant["content"][1]["type"] == "tool_use"
+
+
+async def test_responses_followup_preserves_assistant_text(guardrail: HeadroomGuardrail):
+ response = {
+ "output": [
+ {"type": "message", "content": [{"type": "output_text", "text": "Fetching the original."}]},
+ {"type": "function_call", "call_id": "call_1", "name": HEADROOM_RETRIEVE_TOOL_NAME, "arguments": "{}"},
+ ]
+ }
+
+ plan = await _plan_for(guardrail, response, [{"role": "user", "content": "q"}])
+
+ items = plan.request_patch.messages # type: ignore[union-attr]
+ assert items[1] == {"role": "assistant", "content": "Fetching the original."}
+ assert items[2]["type"] == "function_call"
+
+
+async def test_chat_followup_echoes_only_the_retrieve_call(guardrail: HeadroomGuardrail):
+ """A turn that called another tool alongside headroom_retrieve must not
+ echo that call: only the retrieve call gets a tool result, and a tool_call
+ without one is rejected by the provider."""
+ other = MagicMock()
+ other.id = "call_other"
+ other.type = "function"
+ other.function = MagicMock()
+ other.function.name = "Write"
+ other.function.arguments = "{}"
+
+ response = _make_openai_response_with_tool_call(HEADROOM_RETRIEVE_TOOL_NAME, {"hash": "h" * 24}, "call_1")
+ response.choices[0].message.content = "Getting the original first."
+ response.choices[0].message.tool_calls = [response.choices[0].message.tool_calls[0], other]
+
+ plan = await _plan_for(guardrail, response, [{"role": "user", "content": "q"}])
+
+ messages = plan.request_patch.messages # type: ignore[union-attr]
+ assistant = messages[1]
+ assert assistant["content"] == "Getting the original first."
+ assert [tc["id"] for tc in assistant["tool_calls"]] == ["call_1"]
+ assert [m["tool_call_id"] for m in messages[2:]] == ["call_1"]
diff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_structured_messages_writeback.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_structured_messages_writeback.py
index 642dd51b37b..d2e5b407e30 100644
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_structured_messages_writeback.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_structured_messages_writeback.py
@@ -7,6 +7,7 @@ For Anthropic: structured_messages (OpenAI format) converted back to Anthropic f
via anthropic_messages_pt before writing to data["messages"].
"""
+import json
from unittest.mock import MagicMock, patch
import pytest
@@ -127,3 +128,75 @@ async def test_anthropic_handler_converts_structured_messages_to_anthropic_forma
llm_provider="anthropic",
)
assert result["messages"] == converted_back
+
+
+# ---------------------------------------------------------------------------
+# LIT-5018: the write-back must not restructure the conversation.
+#
+# anthropic_messages_pt merges every run of consecutive user/tool rows into one
+# message, so a tool_result-only turn and the live user turn that follows it
+# came back fused: the current instruction stopped being its own turn purely
+# because a compression guardrail was enabled.
+# ---------------------------------------------------------------------------
+
+AGENTIC_ANTHROPIC_MESSAGES = [
+ {"role": "user", "content": [{"type": "text", "text": "first turn"}]},
+ {"role": "assistant", "content": [{"type": "tool_use", "id": "tu_1", "name": "Read", "input": {}}]},
+ {"role": "user", "content": [{"type": "tool_result", "tool_use_id": "tu_1", "content": "FILE BODY"}]},
+ {"role": "user", "content": [{"type": "text", "text": "can we run /team to fix this"}]},
+]
+
+
+async def _write_back_identity(messages: list) -> list:
+ """Run the request through a guardrail that changes nothing but returns a
+ new list, which is what puts a compression guardrail on the write-back
+ path, and return the resulting Anthropic messages."""
+ from litellm.llms.anthropic.chat.guardrail_translation.handler import (
+ AnthropicMessagesHandler,
+ )
+
+ guardrail = MagicMock()
+ guardrail.should_run_guardrail.return_value = True
+ guardrail.skip_system_message_in_guardrail = None
+ guardrail.skip_tool_message_in_guardrail = None
+ guardrail.experimental_use_latest_role_message_only = False
+
+ async def apply_guardrail(inputs, request_data, input_type, logging_obj=None):
+ return {**inputs, "structured_messages": list(inputs["structured_messages"])}
+
+ guardrail.apply_guardrail = apply_guardrail
+
+ data = {"model": "claude-sonnet-4-5-20250929", "messages": messages, "max_tokens": 1024}
+ result = await AnthropicMessagesHandler().process_input_messages(data=data, guardrail_to_apply=guardrail)
+ return result["messages"]
+
+
+async def test_write_back_keeps_the_live_user_turn_separate_from_the_tool_result_turn():
+ written = await _write_back_identity([dict(m) for m in AGENTIC_ANTHROPIC_MESSAGES])
+
+ assert [m["role"] for m in written] == ["user", "assistant", "user", "user"]
+ assert written[2]["content"] == [{"type": "tool_result", "tool_use_id": "tu_1", "content": "FILE BODY"}]
+ assert written[3]["content"] == [{"type": "text", "text": "can we run /team to fix this"}]
+
+
+async def test_write_back_keeps_real_tool_results_under_modify_params():
+ """Converting one row at a time would keep the turns apart too, but an
+ assistant row whose results are converted separately reads as an orphaned
+ tool call: with modify_params on, the sanitizer answers it with a synthetic
+ "tool execution skipped" result and drops the real one."""
+ import litellm
+
+ original = litellm.modify_params
+ litellm.modify_params = True
+ try:
+ written = await _write_back_identity([dict(m) for m in AGENTIC_ANTHROPIC_MESSAGES])
+ finally:
+ litellm.modify_params = original
+
+ serialized = json.dumps(written)
+ assert "FILE BODY" in serialized
+ assert "skipped" not in serialized
+ assert "Please continue" not in serialized
+ assert [m["role"] for m in written] == ["user", "assistant", "user", "user"]