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 remote-tracking branch 'origin/litellm_internal_staging' into litellm_responses_bridge_replay_encrypted_reasoning

mateo-berri4d4906e94eb4
diff --cc litellm/router_utils/pre_call_checks/encrypted_content_affinity_check.py
index ba94bd86a56,d10153881d9..b2edb13a4bf
--- a/litellm/router_utils/pre_call_checks/encrypted_content_affinity_check.py
+++ b/litellm/router_utils/pre_call_checks/encrypted_content_affinity_check.py
@@@ -283,9 -269,8 +303,10 @@@ class EncryptedContentAffinityCheck(Cus
if "litellm_metadata" in request_kwargs:
request_kwargs["litellm_metadata"]["encrypted_content_affinity_enabled"] = True
+ request_input: Final = request_kwargs.get("input")
- model_id: Final = self._extract_model_id_from_input(request_input)
+ model_id: Final = self._extract_model_id_from_input(
- request_kwargs.get("input")
++ request_input
+ ) or self._extract_model_id_from_anthropic_messages(request_kwargs.get("messages"))
if not model_id:
return typed_healthy_deployments
diff --cc tests/test_litellm/router_utils/pre_call_checks/test_encrypted_content_affinity_check.py
index e858f7eb0a8,3961c8d74c2..99a650436b8
--- a/tests/test_litellm/router_utils/pre_call_checks/test_encrypted_content_affinity_check.py
+++ b/tests/test_litellm/router_utils/pre_call_checks/test_encrypted_content_affinity_check.py
@@@ -1658,41 -1584,288 +1584,328 @@@ async def test_model_group_encrypted_co
router.discard()
+async def test_encrypted_content_affinity_pins_anthropic_messages_replayed_through_the_bridge():
+ """
+ Claude Code behind /v1/messages replays the encrypted reasoning the bridge packed
+ into a thinking block's signature (or a redacted block's data). The pin has to be
+ read from those blocks because the bridge builds the Responses `input` only after
+ the router has picked a deployment.
+ """
+ check = EncryptedContentAffinityCheck()
+ deployments = [
+ {"model_info": {"id": "openai-org-a"}, "litellm_params": {"model": "openai/gpt-5.1"}},
+ {"model_info": {"id": "openai-org-b"}, "litellm_params": {"model": "openai/gpt-5.1"}},
+ ]
+ wrapped = ResponsesAPIRequestUtils._wrap_encrypted_content_with_model_id("gAAAAA_turn_one", "openai-org-b")
+ request_kwargs = {
+ "messages": [
+ {"role": "user", "content": "Solve the zebra puzzle"},
+ {
+ "role": "assistant",
+ "content": [
+ {"type": "thinking", "thinking": "Anthropic minted this one", "signature": "ErcCCpIBCBEYAipA"},
+ {"type": "redacted_thinking", "data": f"litellm_encrypted_reasoning:{wrapped}"},
+ {"type": "text", "text": "The zebra owner lives in the green house."},
+ ],
+ },
+ {"role": "user", "content": "And who drinks water?"},
+ ],
+ }
+
+ pinned = await check.async_filter_deployments(
+ model="gpt-5.1",
+ healthy_deployments=deployments,
+ messages=None,
+ request_kwargs=request_kwargs,
+ )
+
+ assert [d["model_info"]["id"] for d in pinned] == ["openai-org-b"]
+ assert request_kwargs["_encrypted_content_affinity_pinned"] is True
++
++
+ class TestStripEncryptedReasoningFromInput:
+ def test_keeps_summary_and_drops_encrypted_content_and_id(self):
+ wrapped = ResponsesAPIRequestUtils._wrap_encrypted_content_with_model_id("gAAAAA-blob", "deployment-a")
+ encoded_id = ResponsesAPIRequestUtils._build_encrypted_item_id("deployment-a", "rs_1")
+ request_input = [
+ {"role": "user", "content": "first turn"},
+ {
+ "type": "reasoning",
+ "id": encoded_id,
+ "encrypted_content": wrapped,
+ "summary": [{"type": "summary_text", "text": "thought about it"}],
+ },
+ {"type": "reasoning", "id": encoded_id, "encrypted_content": wrapped},
+ {"type": "reasoning", "encrypted_content": wrapped, "summary": []},
+ {"type": "message", "id": "msg_1", "role": "assistant", "content": "hi"},
+ {"role": "user", "content": "second turn"},
+ ]
+ ResponsesAPIRequestUtils.strip_encrypted_reasoning_from_input(request_input)
+ assert request_input == [
+ {"role": "user", "content": "first turn"},
+ {
+ "type": "reasoning",
+ "summary": [{"type": "summary_text", "text": "thought about it"}],
+ },
+ {"type": "message", "id": "msg_1", "role": "assistant", "content": "hi"},
+ {"role": "user", "content": "second turn"},
+ ]
+
+ def test_keeps_string_form_summary_when_stripping(self):
+ wrapped = ResponsesAPIRequestUtils._wrap_encrypted_content_with_model_id("gAAAAA-blob", "deployment-a")
+ request_input = [
+ {"type": "reasoning", "encrypted_content": wrapped, "summary": "plain string thought"},
+ {
+ "type": "reasoning",
+ "encrypted_content": wrapped,
+ "content": [{"type": "output_text", "text": "in content"}],
+ },
+ {"type": "reasoning", "encrypted_content": wrapped, "summary": "", "content": []},
+ ]
+ ResponsesAPIRequestUtils.strip_encrypted_reasoning_from_input(request_input)
+ assert request_input == [
+ {"type": "reasoning", "summary": "plain string thought"},
+ {"type": "reasoning", "content": [{"type": "output_text", "text": "in content"}]},
+ ]
+
+ def test_leaves_input_untouched_when_no_encrypted_reasoning(self):
+ request_input = [
+ {"role": "user", "content": "first turn"},
+ {"type": "reasoning", "summary": [{"type": "summary_text", "text": "no blob here"}]},
+ {"role": "user", "content": "second turn"},
+ ]
+ before = [dict(item) for item in request_input]
+ ResponsesAPIRequestUtils.strip_encrypted_reasoning_from_input(request_input)
+ assert request_input == before
+
+
+ def _cross_group_request_kwargs():
+ wrapped = ResponsesAPIRequestUtils._wrap_encrypted_content_with_model_id("gAAAAA-blob", "deployment-a")
+ return {
+ "litellm_metadata": {},
+ "input": [
+ {"role": "user", "content": "ZEBRA: why is the sky blue?"},
+ {
+ "type": "reasoning",
+ "encrypted_content": wrapped,
+ "summary": [{"type": "summary_text", "text": "scattering"}],
+ },
+ {"type": "message", "role": "assistant", "content": "Rayleigh scattering."},
+ {"role": "user", "content": "KIWI: and sunsets?"},
+ ],
+ }
+
+
+ @pytest.mark.asyncio
+ async def test_affinity_strips_encrypted_reasoning_when_routed_to_another_model_group():
+ """
+ An auto-router tier change (or a model switch with no boundary peer): the
+ routed pool holds no deployment of the origin's model group. The origin is
+ healthy, so a 503 would be wrong; the follow-up dispatches to the routed
+ pool with the origin's encrypted reasoning stripped and its summary kept.
+ """
+ from litellm.router_utils.pre_call_checks.encrypted_content_affinity_check import (
+ EncryptedContentAffinityCheck,
+ )
+
+ originating = _make_originating_mock(None, "key-a", model_name="gpt-reasoning-tier")
+ mock_router = _make_router_mock_with_cooldown(
+ originating, cooldown_entries=[], routed_group_model_ids=["deployment-b"]
+ )
+ check = EncryptedContentAffinityCheck(router=mock_router)
+ routed_pool = [
+ {
+ "model_info": {"id": "deployment-b"},
+ "model_name": "gpt-simple-tier",
+ "litellm_params": {
+ "api_base": "https://gateway.example/v1",
+ "api_key": "key-b",
+ "model": "openai/gpt-5-nano",
+ },
+ }
+ ]
+ request_kwargs = _cross_group_request_kwargs()
+ original_input = request_kwargs["input"]
+
+ result = await check.async_filter_deployments(
+ model="gpt-simple-tier",
+ healthy_deployments=routed_pool,
+ messages=None,
+ request_kwargs=request_kwargs,
+ )
+
+ assert result is routed_pool
+ assert "_encrypted_content_affinity_pinned" not in request_kwargs
+ assert request_kwargs["litellm_metadata"]["encrypted_content_affinity_enabled"] is True
+ assert request_kwargs["input"] is original_input
+ assert [item.get("type") or item["role"] for item in original_input] == [
+ "user",
+ "reasoning",
+ "message",
+ "user",
+ ]
+ assert original_input[1] == {
+ "type": "reasoning",
+ "summary": [{"type": "summary_text", "text": "scattering"}],
+ }
+ assert not any(isinstance(item, dict) and item.get("encrypted_content") for item in original_input)
+
+
+ @pytest.mark.asyncio
+ async def test_affinity_fails_fast_within_the_origins_own_group():
+ """
+ Negative class for the tier-change discriminator: the routed group IS the
+ origin's group (a same-group cooldown, not a tier change), so even with a
+ healthy non-origin sibling that cannot decrypt the content, the request
+ still fails fast and the encrypted reasoning is left intact rather than
+ stripped. Preserves the LIT-3051 cooldown contract.
+ """
+ from litellm.exceptions import ServiceUnavailableError
+ from litellm.router_utils.pre_call_checks.encrypted_content_affinity_check import (
+ EncryptedContentAffinityCheck,
+ )
+
+ originating = _make_originating_mock(
+ "https://account-a.openai.azure.com/", "key-a", model_name="gpt-reasoning-tier"
+ )
+ mock_router = _make_router_mock_with_cooldown(
+ originating, cooldown_entries=[], routed_group_model_ids=["deployment-a", "deployment-a2"]
+ )
+ check = EncryptedContentAffinityCheck(router=mock_router)
+ sibling_pool = [
+ {
+ "model_info": {"id": "deployment-a2"},
+ "model_name": "gpt-reasoning-tier",
+ "litellm_params": {
+ "api_base": "https://account-a2.openai.azure.com/",
+ "api_key": "key-a2",
+ "model": "azure/gpt-5.4",
+ },
+ }
+ ]
+ request_kwargs = _cross_group_request_kwargs()
+
+ with pytest.raises(ServiceUnavailableError):
+ await check.async_filter_deployments(
+ model="gpt-reasoning-tier",
+ healthy_deployments=sibling_pool,
+ messages=None,
+ request_kwargs=request_kwargs,
+ )
+
+ assert request_kwargs["input"][1].get("encrypted_content")
+
+
+ @pytest.mark.asyncio
+ async def test_affinity_does_not_strip_when_group_is_spelled_differently_but_same_by_id():
+ """
+ The discriminator must key on deployment-id membership, not on the model-group
+ name string. Here the origin's configured group is spelled ``openai/gpt-5.4-mini``
+ while the routed group is the canonical ``gpt-5.4-mini``: same group, different
+ spelling. A name compare (``originating.model_name != model``) would read this as
+ a tier change and strip the reasoning it did not have to. Because the origin's id
+ is a member of the routed group, this is a same-group cooldown instead: the request
+ fails fast and the encrypted reasoning is left intact.
+ """
+ from litellm.exceptions import ServiceUnavailableError
+ from litellm.router_utils.pre_call_checks.encrypted_content_affinity_check import (
+ EncryptedContentAffinityCheck,
+ )
+
+ originating = _make_originating_mock(None, "key-a", model_name="openai/gpt-5.4-mini")
+ mock_router = _make_router_mock_with_cooldown(
+ originating, cooldown_entries=[], routed_group_model_ids=["deployment-mini-a", "deployment-mini-b"]
+ )
+ check = EncryptedContentAffinityCheck(router=mock_router)
+ wrapped = ResponsesAPIRequestUtils._wrap_encrypted_content_with_model_id("gAAAAA-blob", "deployment-mini-a")
+ sibling_pool = [
+ {
+ "model_info": {"id": "deployment-mini-b"},
+ "model_name": "gpt-5.4-mini",
+ "litellm_params": {
+ "api_base": "https://gateway.example/v1",
+ "api_key": "key-b",
+ "model": "openai/gpt-5.4-mini",
+ },
+ }
+ ]
+ request_kwargs = {
+ "litellm_metadata": {},
+ "input": [
+ {"role": "user", "content": "why is the sky blue?"},
+ {
+ "type": "reasoning",
+ "encrypted_content": wrapped,
+ "summary": [{"type": "summary_text", "text": "scattering"}],
+ },
+ {"role": "user", "content": "and sunsets?"},
+ ],
+ }
+
+ with pytest.raises(ServiceUnavailableError):
+ await check.async_filter_deployments(
+ model="gpt-5.4-mini",
+ healthy_deployments=sibling_pool,
+ messages=None,
+ request_kwargs=request_kwargs,
+ )
+
+ assert request_kwargs["input"][1].get("encrypted_content")
+
+
+ @pytest.mark.asyncio
+ async def test_affinity_honors_router_candidate_ids_for_team_and_pattern_routes():
+ """
+ The exact `model_name` index does not include team-public or pattern routes, so a
+ same-group cooldown reached only through one of those would be misread as a tier change
+ and stripped. The check asks the router for the candidate ids it resolves for the route
+ (`get_candidate_model_ids_for_route`), which covers those paths, rather than the bare
+ index. Here that set marks the origin as a candidate, so the request fails fast with its
+ reasoning intact, and the routed group and team are passed through to the router.
+ """
+ from litellm.exceptions import ServiceUnavailableError
+ from litellm.router_utils.pre_call_checks.encrypted_content_affinity_check import (
+ EncryptedContentAffinityCheck,
+ )
+
+ originating = _make_originating_mock(None, "key-a", model_name="model_name_teamA_uuid")
+ mock_router = _make_router_mock_with_cooldown(
+ originating, cooldown_entries=[], routed_group_model_ids=["deployment-team-a", "deployment-team-b"]
+ )
+ check = EncryptedContentAffinityCheck(router=mock_router)
+ wrapped = ResponsesAPIRequestUtils._wrap_encrypted_content_with_model_id("gAAAAA-blob", "deployment-team-a")
+ sibling_pool = [
+ {
+ "model_info": {"id": "deployment-team-b"},
+ "model_name": "team-public-model",
+ "litellm_params": {
+ "api_base": "https://gateway.example/v1",
+ "api_key": "key-b",
+ "model": "openai/gpt-5.4-mini",
+ },
+ }
+ ]
+ request_kwargs = {
+ "litellm_metadata": {"user_api_key_team_id": "teamA"},
+ "input": [
+ {"role": "user", "content": "why is the sky blue?"},
+ {
+ "type": "reasoning",
+ "encrypted_content": wrapped,
+ "summary": [{"type": "summary_text", "text": "scattering"}],
+ },
+ {"role": "user", "content": "and sunsets?"},
+ ],
+ }
+
+ with pytest.raises(ServiceUnavailableError):
+ await check.async_filter_deployments(
+ model="team-public-model",
+ healthy_deployments=sibling_pool,
+ messages=None,
+ request_kwargs=request_kwargs,
+ )
+
+ assert request_kwargs["input"][1].get("encrypted_content")
+ mock_router.get_candidate_model_ids_for_route.assert_called_once_with(model="team-public-model", team_id="teamA")