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]

merge: main into litellm_headroom_protect_cached_prefix

jesus71186e4ec1d4
diff --cc litellm/compression/compress.py
index 0af9618382f,b80f78a50c1..bc2cb7c9fdc
--- a/litellm/compression/compress.py
+++ b/litellm/compression/compress.py
@@@ -209,19 -209,11 +209,19 @@@ def _message_has_cache_control(message
if message.get("cache_control") is not None:
return True
content: Final = message.get("content")
- return isinstance(content, list) and any(
- isinstance(part, Mapping) and part.get("cache_control") is not None for part in content
- )
+ if isinstance(content, list):
+ return any(isinstance(part, Mapping) and part.get("cache_control") is not None for part in content)
+ return False
+def _cached_prefix_indices(messages: Sequence[Mapping[str, object]]) -> tuple[int, ...]:
+ last_breakpoint: Final = max(
- (index for index, msg in enumerate(messages) if _has_cache_control(msg)),
++ (index for index, msg in enumerate(messages) if _message_has_cache_control(msg)),
+ default=-1,
+ )
+ return tuple(range(last_breakpoint + 1))
+
+
def get_protected_indices(messages: Sequence[Mapping[str, object]]) -> tuple[int, ...]:
"""
Return indices of messages that must never be compressed:
@@@ -232,16 -224,16 +232,15 @@@
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.
- The provider caches the exact bytes of that prefix, so rewriting any row inside
- it turns the next request's cache read into a cache write.
+ guardrails share this policy; see the Headroom guardrail. A cache_control
- breakpoint pins the provider's prompt-cache prefix to that row's exact
- bytes, so rewriting a marked row anywhere in history turns the next
- request's cache read into a cache write.
++ breakpoint pins the provider's prompt-cache prefix to the exact bytes of every
++ row up to it, so rewriting any row inside that prefix turns the next request's
++ cache read into a cache write.
"""
system_indices: Final = tuple(index for index, msg in enumerate(messages) if msg.get("role", "") == "system")
last_user: Final = tuple(index for index, msg in enumerate(messages) if msg.get("role", "") == "user")[-1:]
- last_assistant: Final = tuple(index for index, msg in enumerate(messages) if msg.get("role", "") == "assistant")[
- -1:
- ]
- return tuple(dict.fromkeys(system_indices + last_user + last_assistant + _cached_prefix_indices(messages)))
+ assistant_indices: Final = tuple(index for index, msg in enumerate(messages) if msg.get("role", "") == "assistant")
- cache_control_indices: Final = tuple(index for index, msg in enumerate(messages) if _message_has_cache_control(msg))
- return tuple(dict.fromkeys(system_indices + last_user + assistant_indices[-1:] + cache_control_indices))
++ return tuple(dict.fromkeys(system_indices + last_user + assistant_indices[-1:] + _cached_prefix_indices(messages)))
def _combine_scores(
diff --cc tests/test_litellm/compression/test_compress.py
index 57992ffcc55,6e908bcbdcd..70281f75196
--- a/tests/test_litellm/compression/test_compress.py
+++ b/tests/test_litellm/compression/test_compress.py
@@@ -55,85 -56,92 +56,164 @@@ def test_no_user_or_assistant_rows()
assert get_protected_indices([]) == ()
+def test_rows_before_last_cache_control_breakpoint_are_protected():
+ messages = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "old question"},
+ {
+ "role": "assistant",
+ "content": "old answer",
- "tool_calls": [
- {"id": "t1", "type": "function", "function": {"name": "Read", "arguments": "{}"}}
- ],
++ "tool_calls": [{"id": "t1", "type": "function", "function": {"name": "Read", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "t1", "content": "large file body"},
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": "cached turn", "cache_control": {"type": "ephemeral"}}],
+ },
+ {
+ "role": "assistant",
+ "content": "ack",
- "tool_calls": [
- {"id": "t2", "type": "function", "function": {"name": "Bash", "arguments": "{}"}}
- ],
++ "tool_calls": [{"id": "t2", "type": "function", "function": {"name": "Bash", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "t2", "content": "later tool output"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ protected = sorted(get_protected_indices(messages))
+
+ assert protected == [0, 1, 2, 3, 4, 5, 7]
+ assert 6 not in protected
+
+
+def test_cache_control_directly_on_message_protects_prefix():
+ messages = [
+ {"role": "system", "content": "sys"},
+ {"role": "tool", "tool_call_id": "before", "content": "large file body"},
+ {"role": "user", "content": "old question"},
+ {
+ "role": "tool",
+ "tool_call_id": "marked",
+ "content": "cached tool",
+ "cache_control": {"type": "ephemeral"},
+ },
+ {"role": "tool", "tool_call_id": "after", "content": "later tool output"},
+ {"role": "assistant", "content": "ack"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ protected = sorted(get_protected_indices(messages))
+
+ assert 1 in protected
+ assert 3 in protected
+ assert 4 not in protected
+
+
+def test_no_cache_control_leaves_history_compressible():
+ messages = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "old question"},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "tool", "tool_call_id": "t1", "content": "large file body"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ assert sorted(get_protected_indices(messages)) == [0, 2, 4]
+
+
+def test_non_mapping_content_parts_are_not_cache_control():
+ messages = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": ["not", "a", "dict"]},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "tool", "tool_call_id": "t1", "content": "plain string"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ protected = sorted(get_protected_indices(messages))
+
+ assert protected == [0, 2, 4]
+ assert 1 not in protected
+ assert 3 not in protected
++
++
+ def test_mid_history_cache_control_part_is_protected():
- # A large cached tool result from a few turns back, not the last user or
- # last assistant row -- exactly the row a provider prompt-cache pins to
- # exact bytes. Rewriting it (even leaving the marker on) changes those
- # bytes and turns the next request's cache read into a cache write.
+ messages = [
+ {"role": "user", "content": "old question"},
+ {"role": "assistant", "content": "old answer"},
+ {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "a large cached tool result", "cache_control": {"type": "ephemeral"}},
+ ],
+ },
+ {"role": "assistant", "content": "ack"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
- # index 3 = last assistant, index 4 = last user (both protected by role
- # regardless), index 2 = the cache_control-marked row itself.
- assert sorted(get_protected_indices(messages)) == [2, 3, 4]
++ assert sorted(get_protected_indices(messages)) == [0, 1, 2, 3, 4]
+
+
+ def test_cache_control_directly_on_message_is_protected():
+ messages = [
+ {"role": "user", "content": "old question", "cache_control": {"type": "ephemeral"}},
+ {"role": "assistant", "content": "old answer"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ assert sorted(get_protected_indices(messages)) == [0, 1, 2]
+
+
+ def test_cache_control_protection_does_not_duplicate_already_protected_rows():
+ # The last user row is already protected by role; marking it too must not
+ # produce a duplicate index.
+ messages = [
+ {"role": "system", "content": "sys"},
+ {"role": "user", "content": "live", "cache_control": {"type": "ephemeral"}},
+ ]
+
+ protected = get_protected_indices(messages)
+
+ assert sorted(protected) == [0, 1]
+ assert len(protected) == len(set(protected))
+
+
+ def test_content_that_is_not_a_list_of_mappings_is_not_treated_as_cache_control():
+ # Defensive: a plain string content, or a list of non-dict items, must not
+ # raise or be misread as carrying a breakpoint.
+ messages = [
+ {"role": "assistant", "content": "plain string content"},
+ {"role": "user", "content": ["not", "a", "dict", "list"]},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ assert sorted(get_protected_indices(messages)) == [0, 2]
+
+
+ def test_compress_keeps_part_level_cache_control_row_verbatim():
- # compress() scores text-only copies of the rows, where a part-level marker
- # is gone; protection has to read the original rows or the pinned row is stubbed.
+ stale_log = {"role": "user", "content": [{"type": "text", "text": "stale log line " * 2000}]}
+ pinned = {
+ "role": "user",
+ "content": [
+ {"type": "text", "text": "cached tool result " * 2000, "cache_control": {"type": "ephemeral"}},
+ ],
+ }
+ messages = [
- stale_log,
- {"role": "assistant", "content": "old answer"},
+ pinned,
++ {"role": "assistant", "content": "old answer"},
++ stale_log,
+ {"role": "assistant", "content": "ack"},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+ result = compress(
+ messages,
+ model="gpt-4o",
+ call_type=CallTypes.anthropic_messages,
+ compression_trigger=1000,
+ compression_target=500,
+ )
+
+ assert len(result["messages"]) == len(messages)
- assert result["messages"][2] == pinned
- assert result["messages"][0] != stale_log
++ assert result["messages"][0] == pinned
++ assert result["messages"][2] != stale_log
+ assert len(result["cache"]) >= 1
diff --cc tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
index 315c85936f3,d4531398ba1..bcecb5b27db
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
@@@ -900,7 -900,7 +900,7 @@@ async def test_service_declared_ccr_has
)
assert has_headroom_retrieve_tool(result.get("tools") or [])
-- (issued, _expiry), = guardrail._issued_hashes_by_call_id.values()
++ ((issued, _expiry),) = guardrail._issued_hashes_by_call_id.values()
assert issued == frozenset({"98ca69107318", "b573993006976af767214fac"})
@@@ -953,7 -953,7 +953,6 @@@ async def test_anthropic_assistant_hist
assert result["messages"][1]["content"] == [{"type": "text", "text": table}]
--
def test_has_headroom_retrieve_tool_recognizes_anthropic_native_shape():
"""By the time an Anthropic Messages API response reaches the agentic-loop
gate, the OpenAI-shaped tool this guardrail injects (type: "function")
@@@ -2342,9 -2342,9 +2341,7 @@@ async def test_streaming_responses_reso
)
assert streamed_text == final_answer
assert not any("function_call" in str(getattr(event, "type", "")) for event in events)
-- assert not any(
-- getattr(getattr(event, "item", None), "type", None) == "function_call" for event in events
-- )
++ assert not any(getattr(getattr(event, "item", None), "type", None) == "function_call" for event in events)
mock_get.assert_called_once()
assert CCR_HASH in (mock_get.call_args.kwargs.get("url") or mock_get.call_args.args[0])
@@@ -2399,9 -2399,9 +2396,7 @@@ def test_sync_streaming_responses_resol
getattr(event, "delta", "") for event in events if getattr(event, "type", None) == "response.output_text.delta"
)
assert streamed_text == final_answer
-- assert not any(
-- getattr(getattr(event, "item", None), "type", None) == "function_call" for event in events
-- )
++ assert not any(getattr(getattr(event, "item", None), "type", None) == "function_call" for event in events)
mock_get.assert_called_once()
assert len(upstream.calls) == 2
assert not json.loads(upstream.calls[1].request.content).get("stream")
@@@ -2514,42 -2514,35 +2509,68 @@@ async def test_history_is_still_compres
assert messages[3] == compressed_history[1]
+CACHED_PREFIX_MESSAGES = [
+ {"role": "system", "content": "You are Claude Code. " + "S" * 5000},
+ {"role": "user", "content": "old question " + "Q" * 5000},
+ {
+ "role": "assistant",
+ "content": "Reading the file now.",
- "tool_calls": [
- {"id": "old_1", "type": "function", "function": {"name": "Read", "arguments": "{}"}}
- ],
++ "tool_calls": [{"id": "old_1", "type": "function", "function": {"name": "Read", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "old_1", "content": "large file body " + "F" * 5000},
+ {
+ "role": "user",
+ "content": [{"type": "text", "text": "cached turn", "cache_control": {"type": "ephemeral"}}],
+ },
+ {
+ "role": "assistant",
+ "content": "Listing now.",
- "tool_calls": [
- {"id": "new_1", "type": "function", "function": {"name": "Bash", "arguments": "{}"}}
- ],
++ "tool_calls": [{"id": "new_1", "type": "function", "function": {"name": "Bash", "arguments": "{}"}}],
+ },
+ {"role": "tool", "tool_call_id": "new_1", "content": "volatile tail output " + "T" * 5000},
+ {"role": "assistant", "content": "Finished listing."},
+ {"role": "user", "content": "live instruction"},
+]
+
+
+async def test_rows_before_last_cache_control_breakpoint_are_never_sent(guardrail: HeadroomGuardrail):
+ wire, result = await _wire_and_result(guardrail, CACHED_PREFIX_MESSAGES)
+
+ assert [row.get("tool_call_id") for row in wire] == ["new_1"]
+ assert result["structured_messages"][:5] == CACHED_PREFIX_MESSAGES[:5]
+
+
+ CACHE_MARKED_HISTORY_MESSAGES = [
+ {"role": "system", "content": "You are Claude Code. " + "S" * 5000},
+ {"role": "user", "content": "old question " + "Q" * 5000},
+ {
+ "role": "assistant",
+ "content": "Reading the file now.",
+ "tool_calls": [{"id": "old_1", "type": "function", "function": {"name": "Read", "arguments": "{}"}}],
+ },
+ {
+ "role": "tool",
+ "tool_call_id": "old_1",
+ "content": [{"type": "text", "text": "large cached file body " + "F" * 5000}],
+ "cache_control": {"type": "ephemeral"},
+ },
+ {"role": "assistant", "content": "Summarized the file for you."},
++ {"role": "tool", "tool_call_id": "tail", "content": "volatile tail output " + "T" * 5000},
+ {"role": "user", "content": "live instruction"},
+ ]
+
+
+ @pytest.mark.asyncio
+ async def test_mid_history_cache_control_row_is_never_sent_for_compression(guardrail: HeadroomGuardrail):
+ wire, result = await _wire_and_result(guardrail, CACHE_MARKED_HISTORY_MESSAGES)
+
+ cached_row = CACHE_MARKED_HISTORY_MESSAGES[3]
+ assert cached_row not in wire
+ assert not any(row.get("tool_call_id") == "old_1" for row in wire)
+ assert result["structured_messages"][3] == cached_row
+
+
# ---------------------------------------------------------------------------
# #38558: a client that runs its own tool loop (e.g. Claude Code via the MCP
# gateway) executes headroom_retrieve and echoes the recovered original content