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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
chore: merge litellm_internal_staging into litellm_lit_4913_headroom_streaming_ccr
shivamfd4bc41930ae
diff --cc litellm/litellm_core_utils/chat_completion_agentic_loop.pyindex 39d36f25143,07bed1f88ad..a5f5c6ac68f--- a/litellm/litellm_core_utils/chat_completion_agentic_loop.py+++ b/litellm/litellm_core_utils/chat_completion_agentic_loop.py@@@ -1,14 -1,16 +1,18 @@@# this is a patch to allow for agentic loops covering llm_http_handler.py and openai sdk based calling flows for the .completion() apiimport json+from collections.abc import Mapping- from typing import cast+ from typing import Final, castfrom litellm._logging import verbose_loggerfrom litellm.integrations.custom_logger import CustomLogger+ from litellm.litellm_core_utils.agentic_loop_settings import (+ DEFAULT_MAX_AGENTIC_LOOPS,+ validated_max_agentic_loops,+ )from litellm.types.integrations.custom_logger import (CHAT_COMPLETION_AGENTIC_SURFACE,+ HEADROOM_CONVERTED_STREAM_KEY,NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES,AgenticLoopPlan,AgenticLoopRequestPatch,diff --cc litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.pyindex 1189d9841e4,84c6b220e62..e4fe392b97f--- a/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py+++ b/litellm/proxy/guardrails/guardrail_hooks/headroom/headroom.py@@@ -34,14 -34,11 +34,15 @@@ from litellm.proxy.guardrails.guardrailis_all_text_parts,merge_rewritten_text_parts,)+ from litellm.proxy.spend_tracking.compression_savings import HEADROOM_GUARDRAIL_PROVIDERfrom litellm.secret_managers.main import get_secret_strfrom litellm.types.guardrails import GuardrailEventHooks, Mode-from litellm.types.integrations.custom_logger import AgenticLoopPlan, AgenticLoopRequestPatch-from litellm.types.utils import GenericGuardrailAPIInputs+from litellm.types.integrations.custom_logger import (+ HEADROOM_CONVERTED_STREAM_KEY,+ AgenticLoopPlan,+ AgenticLoopRequestPatch,+)+from litellm.types.utils import CallTypes, GenericGuardrailAPIInputsif TYPE_CHECKING:from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObjdiff --cc litellm/proxy/litellm_pre_call_utils.pyindex bd451cb4a18,f3df7c6580a..e071b78134a--- a/litellm/proxy/litellm_pre_call_utils.py+++ b/litellm/proxy/litellm_pre_call_utils.py@@@ -180,11 -251,15 +251,16 @@@ _UNTRUSTED_ROOT_CONTROL_FIELDS: Final"_code_interpreter_interception_converted_stream","_code_interpreter_interception_sandbox_key","_code_interpreter_interception_session_scoped",+ "_headroom_interception_converted_stream","max_agentic_loops",+ # Recomputed below from the actual caller-controlled timeout sources (headers and+ # body fields); a client-forged value here would let a request either dodge cooldown+ # protection on a real deployment failure or force a false "not caller-controlled"+ # reading that lets its own bad timeout cool down deployments other tenants rely on.+ "client_side_timeout",)- _UNTRUSTED_METADATA_CONTROL_FIELDS = (+ _UNTRUSTED_METADATA_CONTROL_FIELDS: Final = ("disable_global_guardrails","disable_global_guardrail","opted_out_global_guardrails",diff --cc litellm/types/integrations/custom_logger.pyindex 8dddeb40e09,2cca16351af..fd4648bff14--- a/litellm/types/integrations/custom_logger.py+++ b/litellm/types/integrations/custom_logger.py@@@ -2,19 -2,13 +2,21 @@@ from typing import Any, Finafrom pydantic import BaseModel, Field- CHAT_COMPLETION_AGENTIC_SURFACE = "chat_completions"- RESPONSES_AGENTIC_SURFACE = "responses"- CODE_INTERPRETER_INTERCEPTION_PREFIX = "_code_interpreter_interception"- HEADROOM_INTERCEPTION_PREFIX = "_headroom_interception"- HEADROOM_CONVERTED_STREAM_KEY = f"{HEADROOM_INTERCEPTION_PREFIX}_converted_stream"- NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES = frozenset(+ CHAT_COMPLETION_AGENTIC_SURFACE: Final = "chat_completions"+ RESPONSES_AGENTIC_SURFACE: Final = "responses"+ CODE_INTERPRETER_INTERCEPTION_PREFIX: Final = "_code_interpreter_interception"++HEADROOM_INTERCEPTION_PREFIX: Final = "_headroom_interception"++HEADROOM_CONVERTED_STREAM_KEY: Final = (++ f"{HEADROOM_INTERCEPTION_PREFIX}_converted_stream"++)+ NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES: Final = frozenset(- ("_websearch_interception", "_compression_interception")+ (+ "_websearch_interception",+ "_compression_interception",+ HEADROOM_INTERCEPTION_PREFIX,+ ))- INTERCEPTION_INTERNAL_PREFIXES = frozenset(+ INTERCEPTION_INTERNAL_PREFIXES: Final = frozenset((*NON_CODE_INTERPRETER_INTERCEPTION_INTERNAL_PREFIXES,CODE_INTERPRETER_INTERCEPTION_PREFIX,diff --cc litellm/types/utils.pyindex 5edd2806f7d,58103b84749..827bb7098d5--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@@ -3192,11 -3492,31 +3492,32 @@@ agentic_loop_internal_litellm_params: F"_code_interpreter_interception_sandbox_key","_code_interpreter_interception_session_scoped","_code_interpreter_interception_converted_stream",+ "_websearch_interception_emit_native_blocks",+ "_websearch_interception_converted_stream",+ "_headroom_interception_converted_stream",]+ # Proxy-owned callback credentials, stamped from admin-configured team/key callback+ # settings. Listed in all_litellm_params for the same reason as the agentic-loop+ # fields above: an unrecognized top-level key is swept into extra_body and sent to+ # the provider.+ TRUSTED_CALLBACK_VARS_FIELD: Final = "litellm_trusted_callback_vars"++ # Bedrock managed-batch deployment config, read from litellm_params by the batch and+ # files transformations. Listed for the same reason as the fields above: these sit on+ # a deployment that also serves chat, so leaking them into extra_body makes Bedrock+ # reject every non-batch request to that deployment.+ bedrock_batch_litellm_params: Final = (+ "aws_batch_role_arn",+ "s3_bucket_name",+ "s3_region_name",+ "s3_output_bucket_name",+ "bedrock_tags",+ )+all_litellm_params = (agentic_loop_internal_litellm_params+ + [TRUSTED_CALLBACK_VARS_FIELD, *bedrock_batch_litellm_params]+ ["metadata","litellm_metadata",diff --cc tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.pyindex 9f556a103da,7a2772ce78c..420b91c983b--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py@@@ -1796,123 -1893,241 +1905,363 @@@ async def test_fail_open_returns_originassert [m["content"] for m in messages] == [m["content"] for m in PARTS_MESSAGES]+CCR_HASH = "b573993006976af767214fac"+++def _retrieve_tool_definition() -> dict:+ return {+ "type": "function",+ "function": {+ "name": HEADROOM_RETRIEVE_TOOL_NAME,+ "description": "retrieve compressed content",+ "parameters": {"type": "object", "properties": {"hash": {"type": "string"}}},+ },+ }+++def _model_response_with_retrieve_call() -> ModelResponse:+ return ModelResponse(+ choices=[+ Choices(+ finish_reason="tool_calls",+ message=Message(+ role="assistant",+ content=None,+ tool_calls=[+ ChatCompletionMessageToolCall(+ id="call_ccr",+ type="function",+ function=Function(+ name=HEADROOM_RETRIEVE_TOOL_NAME,+ arguments=json.dumps({"hash": CCR_HASH}),+ ),+ )+ ],+ ),+ )+ ]+ )+++ "call_type, stream, tools, expect_conversion",+ [+ (CallTypes.acompletion, True, [_retrieve_tool_definition()], True),+ (CallTypes.completion, True, [_retrieve_tool_definition()], True),+ (CallTypes.acompletion, False, [_retrieve_tool_definition()], False),+ (CallTypes.acompletion, True, [{"type": "function", "function": {"name": "get_weather"}}], False),+ (CallTypes.acompletion, True, None, False),+ (CallTypes.aresponses, True, [_retrieve_tool_definition()], False),+ (CallTypes.anthropic_messages, True, [_retrieve_tool_definition()], False),+ ],+)+async def test_pre_call_deployment_hook_converts_stream_only_for_ccr_chat_completions(+ guardrail: HeadroomGuardrail,+ call_type: CallTypes,+ stream: bool,+ tools: Optional[list],+ expect_conversion: bool,+):+ kwargs = {"model": "gpt-4o", "stream": stream, "tools": tools}++ result = await guardrail.async_pre_call_deployment_hook(kwargs=kwargs, call_type=call_type)++ if not expect_conversion:+ assert result is None+ assert kwargs["stream"] is stream+ return++ assert result is not None+ assert result["stream"] is False+ assert result[HEADROOM_CONVERTED_STREAM_KEY] is True+ assert kwargs["stream"] is True+++async def test_streaming_chat_completion_resolves_ccr_retrieval_end_to_end(+ guardrail: HeadroomGuardrail,+):+ """Regression test for streaming /chat/completions: the retrieve tool call the+ model emits must be resolved by the agentic loop instead of being streamed back+ to a client that never declared the tool."""+ original_content = "the full uncompressed document"+ final_answer = "the document says hello"+ guardrail._issued_hashes_by_call_id["ccr-call-id"] = (+ frozenset({CCR_HASH}),+ time.monotonic() + 999,+ )++ real_acompletion = litellm.acompletion++ async def acompletion_with_followup_answer(*args, **kwargs):+ if kwargs.get("_agentic_loop_depth"):+ kwargs["mock_response"] = final_answer+ return await real_acompletion(*args, **kwargs)++ saved_callbacks = list(litellm.callbacks)+ litellm.callbacks = [guardrail]+ try:+ with patch.object(+ guardrail.async_handler,+ "get",+ new_callable=AsyncMock,+ return_value=_make_retrieve_response(original_content),+ ) as mock_get, patch.object(litellm, "acompletion", new=acompletion_with_followup_answer):+ response = await litellm.acompletion(+ model="openai/gpt-4o",+ messages=[{"role": "user", "content": f"summarize hash={CCR_HASH}"}],+ tools=[_retrieve_tool_definition()],+ stream=True,+ litellm_call_id="ccr-call-id",+ mock_response=_model_response_with_retrieve_call(),+ )+ chunks = [chunk async for chunk in response]+ finally:+ litellm.callbacks = saved_callbacks++ streamed_text = "".join(chunk.choices[0].delta.content or "" for chunk in chunks if chunk.choices)+ assert streamed_text == final_answer+ assert not any(chunk.choices and chunk.choices[0].delta.tool_calls for chunk in chunks)+ mock_get.assert_called_once()+ assert CCR_HASH in (mock_get.call_args.kwargs.get("url") or mock_get.call_args.args[0])+++++ # ---------------------------------------------------------------------------+ # 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+++ @pytest.mark.asyncio+ 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+++ @pytest.mark.asyncio+ 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]+++ @pytest.mark.asyncio+ 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]+++ @pytest.mark.asyncio+ 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 [])+++ @pytest.mark.asyncio+ 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+++ @pytest.mark.asyncio+ 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={},+ )+++ @pytest.mark.asyncio+ 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"+++ @pytest.mark.asyncio+ 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"+++ @pytest.mark.asyncio+ 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"]