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 devin_ai_lit5443_mantle_chat_aws_creds

mateo-berridb909620fbe8
diff --cc litellm/llms/custom_httpx/llm_http_handler.py
index cadf4c701e2,834f7d564a2..bdd808dd58d
--- a/litellm/llms/custom_httpx/llm_http_handler.py
+++ b/litellm/llms/custom_httpx/llm_http_handler.py
@@@ -19,8 -20,17 +20,18 @@@ import litellm.types.util
from litellm._logging import _redact_string, verbose_logger
from litellm.anthropic_beta_headers_manager import update_headers_with_filtered_beta
from litellm.constants import REALTIME_WEBSOCKET_MAX_MESSAGE_SIZE_BYTES
+ from litellm.litellm_core_utils.agentic_loop_settings import (
+ DEFAULT_MAX_AGENTIC_LOOPS,
+ validated_max_agentic_loops,
+ )
from litellm.litellm_core_utils.asyncify import run_async_function
+ from litellm.litellm_core_utils.audio_utils.subtitle_utils import (
+ SUBTITLE_RESPONSE_FORMATS,
+ synthesize_subtitle_document,
+ )
+from litellm.litellm_core_utils.get_litellm_params import AWS_CREDENTIAL_KWARGS_KEYS
+ from litellm.litellm_core_utils.llm_request_utils import serialize_multipart_form_fields
+ from litellm.litellm_core_utils.realtime_errors import realtime_error_event, websocket_close_reason
from litellm.litellm_core_utils.realtime_streaming import RealTimeStreaming
from litellm.litellm_core_utils.url_utils import encode_url_path_segment
from litellm.llms.base_llm.anthropic_messages.transformation import (
@@@ -253,22 -270,27 +271,37 @@@ def _has_pre_call_deployment_hook(loggi
return False
+def _aws_signing_overrides(optional_params: Mapping[str, Any], litellm_params: Mapping[str, Any]) -> Mapping[str, Any]:
- """AWS credential params for SigV4 signers that read them off optional_params.
-
- Only `bedrock`/`sagemaker` keep `aws_*` in optional_params: every other provider
- spreads optional_params into the request body, so the params are stripped there
- and survive on litellm_params alone.
- """
+ return MappingProxyType(
+ {
+ key: litellm_params[key]
+ for key in AWS_CREDENTIAL_KWARGS_KEYS
+ if optional_params.get(key) is None and litellm_params.get(key) is not None
+ }
+ )
+
+
+ def _collect_ws_project_quota_callbacks() -> tuple[ProjectQuotaCallback, ...]:
+ """Duck-type discover proxy hooks exposing per-frame project ITPM/OTPM
+ enforcement, so the Responses WebSocket loop can charge every
+ ``response.create`` frame, not just the connection's first one.
+
+ Uses duck-typing on ``litellm.callbacks`` (rather than importing the
+ proxy hook directly) to avoid a layering violation (SDK importing from
+ the proxy layer).
+ """
+ import litellm as _litellm
+
+ callbacks: Final = cast( # cast-ok: callback registry is inspected before protocol use
+ Sequence[object], _litellm.callbacks
+ )
+ return tuple(
+ cast(ProjectQuotaCallback, callback) # cast-ok: required callback method is callable
+ for callback in callbacks
+ if callable(getattr(callback, "enforce_project_io_token_quota_for_frame", None))
+ )
+
+
class BaseLLMHTTPHandler:
async def _make_common_async_call(
self,
diff --cc tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_transformation.py
index 468cc9b9130,cd775abf136..56b111f294e
--- a/tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_transformation.py
+++ b/tests/test_litellm/llms/bedrock_mantle/test_bedrock_mantle_transformation.py
@@@ -489,83 -486,6 +486,71 @@@ class TestBedrockMantleChatAuth
assert "/us-east-2/bedrock/aws4_request" in authorization
assert requests[0]["url"].startswith("https://bedrock-mantle.us-east-2.api.aws")
- def test_completion_per_request_role_reaches_signer_and_not_the_body(
- self, monkeypatch
- ):
- # Per-request aws_role_name/aws_session_name are stripped from optional_params
- # for non-bedrock providers, so they must be sourced from litellm_params at
- # signing time, and must never be serialized into the provider request body.
++ def test_completion_per_request_role_reaches_signer_and_not_the_body(self, monkeypatch):
++ from unittest.mock import MagicMock, Mock
++
+ from botocore.credentials import Credentials
+
+ from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM
++ from litellm.llms.custom_httpx.http_handler import HTTPHandler
++ from litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler
++ from litellm.types.utils import ModelResponse
+
- for var in (
- "BEDROCK_MANTLE_API_KEY",
- "AWS_BEARER_TOKEN_BEDROCK",
- "BEDROCK_MANTLE_API_BASE",
- ):
++ for var in ("BEDROCK_MANTLE_API_KEY", "AWS_BEARER_TOKEN_BEDROCK", "BEDROCK_MANTLE_API_BASE"):
+ monkeypatch.delenv(var, raising=False)
+
- credential_calls = []
-
- def fake_get_credentials(self, **kwargs):
- credential_calls.append(kwargs)
- return Credentials(
++ signer = BaseAWSLLM()
++ signer.get_credentials = MagicMock(
++ return_value=Credentials(
+ access_key="ASIAEXAMPLE",
+ secret_key="YXNzdW1lZC1yb2xlLXNlY3JldC1hc3N1bWVk",
+ token="assumed-session-token",
+ )
-
- monkeypatch.setattr(BaseAWSLLM, "get_credentials", fake_get_credentials)
-
- requests = []
-
- def mock_post(self, url, data=None, headers=None, **kwargs):
- raw_body = data.decode("utf-8") if isinstance(data, bytes) else data
- requests.append({"headers": headers or {}, "body": json.loads(raw_body or "{}")})
- return httpx.Response(
++ )
++ url = "https://bedrock-mantle.us-east-1.api.aws/openai/v1/chat/completions"
++ client = HTTPHandler(client=httpx.Client())
++ client.post = Mock(
++ return_value=httpx.Response(
+ status_code=200,
+ json={
+ "id": "chatcmpl-test",
+ "object": "chat.completion",
+ "created": 1733529600,
+ "model": "google.gemma-4-31b",
- "choices": [
- {
- "index": 0,
- "message": {"role": "assistant", "content": "ok"},
- "finish_reason": "stop",
- }
- ],
- "usage": {
- "prompt_tokens": 1,
- "completion_tokens": 1,
- "total_tokens": 2,
- },
++ "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],
++ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ },
+ request=httpx.Request("POST", url),
+ )
++ )
+
- with patch(
- "litellm.llms.custom_httpx.http_handler.HTTPHandler.post", mock_post
- ):
- litellm.completion(
- model="bedrock_mantle/google.gemma-4-31b",
- messages=[{"role": "user", "content": "hello"}],
- aws_role_name="arn:aws:iam::000000000000:role/attributed-role",
- aws_session_name="user-123",
- aws_region_name="us-east-1",
- )
-
- assert len(credential_calls) == 1
- assert (
- credential_calls[0]["aws_role_name"]
- == "arn:aws:iam::000000000000:role/attributed-role"
++ BaseLLMHTTPHandler().completion(
++ model="google.gemma-4-31b",
++ messages=[{"role": "user", "content": "hello"}],
++ api_base=None,
++ custom_llm_provider="bedrock_mantle",
++ model_response=ModelResponse(),
++ encoding=None,
++ logging_obj=Mock(),
++ optional_params={},
++ timeout=10,
++ litellm_params={
++ "aws_role_name": "arn:aws:iam::000000000000:role/attributed-role",
++ "aws_session_name": "user-123",
++ "aws_region_name": "us-east-1",
++ },
++ acompletion=False,
++ client=client,
++ provider_config=BedrockMantleChatConfig(aws_signer=signer),
+ )
- assert credential_calls[0]["aws_session_name"] == "user-123"
- assert requests[0]["headers"]["Authorization"].startswith("AWS4-HMAC-SHA256")
- assert not [key for key in requests[0]["body"] if key.startswith("aws_")]
++
++ credential_kwargs = signer.get_credentials.call_args.kwargs
++ assert credential_kwargs["aws_role_name"] == "arn:aws:iam::000000000000:role/attributed-role"
++ assert credential_kwargs["aws_session_name"] == "user-123"
++ sent = client.post.call_args.kwargs
++ assert sent["headers"]["Authorization"].startswith("AWS4-HMAC-SHA256")
++ assert not [key for key in json.loads(sent["data"]) if key.startswith("aws_")]
+
class TestBedrockMantleProjectHeader:
def test_validate_environment_sets_openai_project_header(self):
diff --cc tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
index 0906b39c514,26f841c1146..1d583c16ad7
--- a/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
+++ b/tests/test_litellm/llms/custom_httpx/test_llm_http_handler.py
@@@ -2073,20 -2295,787 +2295,806 @@@ async def test_anthropic_invalid_thinki
assert retry_authorization != first_attempt_headers["Authorization"]
+def test_aws_signing_overrides_only_fills_missing_credentials():
+ from litellm.llms.custom_httpx.llm_http_handler import _aws_signing_overrides
+
+ overrides = _aws_signing_overrides(
+ {"temperature": 0.2, "aws_region_name": "us-west-2"},
+ {
+ "aws_role_name": "arn:aws:iam::000000000000:role/attributed",
+ "aws_session_name": "user-123",
+ "aws_region_name": "us-east-1",
+ "api_key": "not-an-aws-param",
+ },
+ )
+
+ assert dict(overrides) == {
+ "aws_role_name": "arn:aws:iam::000000000000:role/attributed",
+ "aws_session_name": "user-123",
+ }
++
++
+ class TestServerFulfilledToolsInRequest:
+ """_server_fulfilled_tools_in_request gates the buffered (non-leaking) streaming
+ mode for server-fulfilled tools like headroom_retrieve."""
+
+ @staticmethod
+ def _logging_obj_with(callbacks):
+ logging_obj = Mock()
+ logging_obj.dynamic_success_callbacks = callbacks
+ return logging_obj
+
+ def test_should_hold_back_when_callback_owns_tool_in_request(self):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class RetrievalCallback(CustomLogger):
+ server_fulfilled_tool_names = frozenset({"headroom_retrieve"})
+
+ tools = [
+ {"name": "Bash", "input_schema": {"type": "object"}},
+ {"name": "headroom_retrieve", "input_schema": {"type": "object"}},
+ ]
+ assert BaseLLMHTTPHandler._server_fulfilled_tools_in_request(
+ logging_obj=self._logging_obj_with([RetrievalCallback()]), tools=tools
+ ) == frozenset({"headroom_retrieve"})
+
+ def test_should_stream_live_when_tool_absent_from_request(self):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class RetrievalCallback(CustomLogger):
+ server_fulfilled_tool_names = frozenset({"headroom_retrieve"})
+
+ tools = [{"name": "Bash", "input_schema": {"type": "object"}}]
+ assert (
+ BaseLLMHTTPHandler._server_fulfilled_tools_in_request(
+ logging_obj=self._logging_obj_with([RetrievalCallback()]), tools=tools
+ )
+ == frozenset()
+ )
+
+ def test_should_stream_live_when_no_callback_declares_tool_names(self):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ tools = [{"name": "headroom_retrieve", "input_schema": {"type": "object"}}]
+ assert (
+ BaseLLMHTTPHandler._server_fulfilled_tools_in_request(
+ logging_obj=self._logging_obj_with([CustomLogger()]), tools=tools
+ )
+ == frozenset()
+ )
+
+ def test_should_stream_live_without_tools(self):
+ assert (
+ BaseLLMHTTPHandler._server_fulfilled_tools_in_request(logging_obj=self._logging_obj_with([]), tools=None)
+ == frozenset()
+ )
+
+ def test_interception_callbacks_declare_their_retrieval_tools(self):
+ from litellm.integrations.compression_interception.handler import (
+ LITELLM_CONTENT_RETRIEVE_TOOL_NAME,
+ CompressionInterceptionLogger,
+ )
+ from litellm.proxy.guardrails.guardrail_hooks.headroom.headroom import (
+ HEADROOM_RETRIEVE_TOOL_NAME,
+ HeadroomGuardrail,
+ )
+
+ assert HeadroomGuardrail.server_fulfilled_tool_names == frozenset({HEADROOM_RETRIEVE_TOOL_NAME})
+ assert CompressionInterceptionLogger.server_fulfilled_tool_names == frozenset(
+ {LITELLM_CONTENT_RETRIEVE_TOOL_NAME}
+ )
+
+
+ def _make_stub_direct_vector_store_config(response):
+ from litellm.llms.base_llm.vector_store.transformation import (
+ BaseDirectVectorStoreConfig,
+ )
+
+ class StubDirectVectorStoreConfig(BaseDirectVectorStoreConfig):
+ def __init__(self):
+ super().__init__()
+ self.sync_calls = []
+ self.async_calls = []
+
+ def execute_search_vector_store_request(self, **kwargs):
+ self.sync_calls.append(kwargs)
+ return response
+
+ async def aexecute_search_vector_store_request(self, **kwargs):
+ self.async_calls.append(kwargs)
+ return response
+
+ return StubDirectVectorStoreConfig()
+
+
+ def test_vector_store_search_handler_direct_config_sync_skips_http():
+ handler = BaseLLMHTTPHandler()
+ stub_response = {"object": "vector_store.search_results.page", "search_query": "q", "data": []}
+ config = _make_stub_direct_vector_store_config(stub_response)
+ logging_obj = Mock()
+
+ with patch("litellm.llms.custom_httpx.llm_http_handler._get_httpx_client") as mock_get_client:
+ result = handler.vector_store_search_handler(
+ vector_store_id="vs_direct",
+ query="q",
+ vector_store_search_optional_params={"max_num_results": 4},
+ vector_store_provider_config=config,
+ custom_llm_provider="valkey",
+ litellm_params=GenericLiteLLMParams(valkey_host="localhost"),
+ logging_obj=logging_obj,
+ timeout=12.5,
+ _is_async=False,
+ )
+
+ assert result is stub_response
+ mock_get_client.assert_not_called()
+ assert len(config.sync_calls) == 1
+ call = config.sync_calls[0]
+ assert call["vector_store_id"] == "vs_direct"
+ assert call["query"] == "q"
+ assert call["timeout"] == 12.5
+ assert call["vector_store_search_optional_params"] == {"max_num_results": 4}
+ assert isinstance(call["litellm_params"], dict)
+ assert call["litellm_params"]["valkey_host"] == "localhost"
+ pre_call_args = logging_obj.pre_call.call_args.kwargs["additional_args"]
+ assert pre_call_args["query"] == "q"
+ assert pre_call_args["vector_store_id"] == "vs_direct"
+
+
+ @pytest.mark.asyncio
+ async def test_vector_store_search_handler_direct_config_async_skips_http():
+ handler = BaseLLMHTTPHandler()
+ stub_response = {"object": "vector_store.search_results.page", "search_query": "q", "data": []}
+ config = _make_stub_direct_vector_store_config(stub_response)
+ logging_obj = Mock()
+
+ with patch("litellm.llms.custom_httpx.llm_http_handler.get_async_httpx_client") as mock_get_client:
+ result = await handler.vector_store_search_handler(
+ vector_store_id="vs_direct",
+ query=["q1", "q2"],
+ vector_store_search_optional_params={},
+ vector_store_provider_config=config,
+ custom_llm_provider="valkey",
+ litellm_params=GenericLiteLLMParams(valkey_host="localhost"),
+ logging_obj=logging_obj,
+ timeout=7.0,
+ _is_async=True,
+ )
+
+ assert result is stub_response
+ mock_get_client.assert_not_called()
+ assert len(config.async_calls) == 1
+ assert config.async_calls[0]["query"] == ["q1", "q2"]
+ assert config.async_calls[0]["litellm_params"]["valkey_host"] == "localhost"
+ assert config.async_calls[0]["timeout"] == 7.0
+ pre_call_args = logging_obj.pre_call.call_args.kwargs["additional_args"]
+ assert pre_call_args["query"] == ["q1", "q2"]
+ assert pre_call_args["vector_store_id"] == "vs_direct"
+
+
+ def _direct_vector_store_debug_logging_obj():
+ from litellm.litellm_core_utils.litellm_logging import Logging as LitellmLogging
+
+ logging_obj = LitellmLogging(
+ model="valkey",
+ messages=[{"role": "user", "content": "q"}],
+ stream=False,
+ call_type="vector_store_search",
+ start_time=time.time(),
+ litellm_call_id="vs-debug-call-id",
+ function_id="vs-debug-function-id",
+ log_raw_request_response=True,
+ )
+ logging_obj.update_environment_variables(
+ model="valkey",
+ optional_params={"vector_store_id": "vs_direct", "query": "q"},
+ litellm_params={
+ "litellm_call_id": "vs-debug-call-id",
+ "vector_store_id": "vs_direct",
+ "litellm_request_debug": True,
+ "metadata": {"user_api_key_alias": "vs-test-key"},
+ "valkey_host": "valkey.internal",
+ "valkey_password": "sup3r-s3cret-valkey-pw",
+ "litellm_embedding_config": {"api_key": "sk-embedding-s3cret"},
+ },
+ )
+ return logging_obj
+
+
+ @pytest.mark.parametrize("is_async", [False, True])
+ def test_direct_vector_store_search_debug_log_omits_stored_credentials(caplog, is_async):
+ """Regression: an empty api_base made pre_call dump the whole model_call_details, so every
+ search shipped the stored valkey_password / embedding api_key into the raw_request metadata."""
+ handler = BaseLLMHTTPHandler()
+ stub_response = {"object": "vector_store.search_results.page", "search_query": "q", "data": []}
+ config = _make_stub_direct_vector_store_config(stub_response)
+ logging_obj = _direct_vector_store_debug_logging_obj()
+
+ with caplog.at_level(logging.DEBUG, logger=verbose_logger.name):
+ result = handler.vector_store_search_handler(
+ vector_store_id="vs_direct",
+ query="q",
+ vector_store_search_optional_params={"max_num_results": 4},
+ vector_store_provider_config=config,
+ custom_llm_provider="valkey",
+ litellm_params=GenericLiteLLMParams(
+ valkey_host="valkey.internal",
+ valkey_password="sup3r-s3cret-valkey-pw",
+ ),
+ logging_obj=logging_obj,
+ _is_async=is_async,
+ )
+ if is_async:
+ result = asyncio.run(result)
+
+ assert result is stub_response
+ raw_request = logging_obj.model_call_details["litellm_params"]["metadata"]["raw_request"]
+ assert "sup3r-s3cret-valkey-pw" not in raw_request
+ assert "sk-embedding-s3cret" not in raw_request
+ assert "valkey://vs_direct" in raw_request
+ logged = "\n".join(record.getMessage() for record in caplog.records)
+ assert "sup3r-s3cret-valkey-pw" not in logged
+ assert "sk-embedding-s3cret" not in logged
+
+
+ @pytest.mark.asyncio
+ async def test_async_anthropic_messages_handler_carries_deployment_vertex_location_for_pricing(monkeypatch):
+ """
+ The proxy pre-creates the logging object before the router picks a deployment, so the
+ native /v1/messages path must copy the deployment's vertex_location into the logging
+ params it updates; otherwise cost resolution falls back to the environment and every
+ call on this surface prices with the regional uplift (#34393).
+ """
+ import contextlib
+ from datetime import datetime
+
+ from litellm.litellm_core_utils.litellm_logging import (
+ Logging,
+ _resolve_vertex_location_for_cost,
+ )
+
+ monkeypatch.setenv("VERTEXAI_LOCATION", "us-east5")
+ monkeypatch.setattr(litellm, "vertex_location", None)
+
+ handler = BaseLLMHTTPHandler()
+
+ async def logging_obj_after_handler(generic_params):
+ logging_obj = Logging(
+ model="vertex_ai/claude-haiku-4-5@20251001",
+ messages=[{"role": "user", "content": "hi"}],
+ stream=False,
+ call_type="anthropic_messages",
+ start_time=datetime.now(),
+ litellm_call_id="vertex-messages-location",
+ function_id="f",
+ )
+ logging_obj.update_environment_variables(
+ model="vertex_ai/claude-haiku-4-5@20251001",
+ user="",
+ optional_params={},
+ litellm_params={"api_base": ""},
+ custom_llm_provider="vertex_ai",
+ )
+ mock_config = Mock()
+ mock_config.validate_anthropic_messages_environment = Mock(
+ return_value=({"authorization": "Bearer t"}, "https://us-east5-aiplatform.googleapis.com")
+ )
+ mock_config.transform_anthropic_messages_request = Mock(
+ return_value={"model": "claude-haiku-4-5@20251001", "messages": []}
+ )
+ with contextlib.suppress(Exception):
+ await handler.async_anthropic_messages_handler(
+ model="claude-haiku-4-5@20251001",
+ messages=[{"role": "user", "content": "hi"}],
+ anthropic_messages_provider_config=mock_config,
+ anthropic_messages_optional_request_params={"max_tokens": 10},
+ custom_llm_provider="vertex_ai",
+ litellm_params=generic_params,
+ logging_obj=logging_obj,
+ client=AsyncMock(),
+ kwargs={},
+ )
+ return logging_obj
+
+ global_deployment = await logging_obj_after_handler(GenericLiteLLMParams(vertex_location="global"))
+ assert global_deployment.litellm_params["vertex_location"] == "global"
+ assert (
+ _resolve_vertex_location_for_cost(
+ custom_llm_provider="vertex_ai",
+ litellm_params=global_deployment.litellm_params,
+ optional_params=global_deployment.optional_params,
+ model="claude-haiku-4-5@20251001",
+ )
+ == "global"
+ )
+
+ unconfigured_deployment = await logging_obj_after_handler(GenericLiteLLMParams())
+ assert "vertex_location" not in unconfigured_deployment.litellm_params
+
+
+ _GENERIC_STREAM_SSE = (
+ b'data: {"id":"chatcmpl-1","object":"chat.completion.chunk","created":1,'
+ b'"model":"test-model","choices":[{"index":0,"delta":{"content":"hi"},'
+ b'"finish_reason":null}]}\n\n'
+ b"data: [DONE]\n\n"
+ )
+
+
+ def _generic_stream_upstream_response() -> httpx.Response:
+ return httpx.Response(
+ 200,
+ headers={
+ "x-request-id": "generic-req-123",
+ "x-ratelimit-remaining-requests": "42",
+ },
+ content=_GENERIC_STREAM_SSE,
+ request=httpx.Request("POST", "https://fake-vllm.test/v1/chat/completions"),
+ )
+
+
+ def test_generic_http_handler_sync_streaming_forwards_provider_response_headers():
+ """
+ Regression test for the generic BaseLLMHTTPHandler streaming path used by
+ ~30 providers (deepseek, groq, hosted_vllm, databricks, openrouter, ...).
+
+ The sync `completion()` streaming branch builds the CustomStreamWrapper from
+ `make_sync_call`, which returns the upstream response headers alongside the
+ stream. Those headers must reach the caller as `llm_provider-*` entries in
+ `_hidden_params["additional_headers"]`, which is what the proxy merges into
+ the client-facing response headers.
+ """
+ mock_client = Mock(spec=HTTPHandler)
+ mock_client.post = Mock(return_value=_generic_stream_upstream_response())
+
+ response = litellm.completion(
+ model="hosted_vllm/test-model",
+ messages=[{"role": "user", "content": "Hello"}],
+ api_base="https://fake-vllm.test/v1",
+ api_key="sk-test",
+ stream=True,
+ client=mock_client,
+ )
+
+ additional_headers = response._hidden_params["additional_headers"]
+ assert additional_headers["llm_provider-x-request-id"] == "generic-req-123"
+ assert additional_headers["llm_provider-x-ratelimit-remaining-requests"] == "42"
+
+ assert "".join([chunk.choices[0].delta.content or "" for chunk in response]) == "hi"
+
+
+ @pytest.mark.asyncio
+ async def test_generic_http_handler_async_streaming_forwards_provider_response_headers():
+ """
+ Companion to the sync test above for `acompletion_stream_function`, which
+ builds its CustomStreamWrapper from `make_async_call_stream_helper`.
+ """
+ mock_client = AsyncMock(spec=AsyncHTTPHandler)
+ mock_client.post = AsyncMock(return_value=_generic_stream_upstream_response())
+
+ response = await litellm.acompletion(
+ model="hosted_vllm/test-model",
+ messages=[{"role": "user", "content": "Hello"}],
+ api_base="https://fake-vllm.test/v1",
+ api_key="sk-test",
+ stream=True,
+ client=mock_client,
+ )
+
+ additional_headers = response._hidden_params["additional_headers"]
+ assert additional_headers["llm_provider-x-request-id"] == "generic-req-123"
+ assert additional_headers["llm_provider-x-ratelimit-remaining-requests"] == "42"
+
+ collected = [chunk async for chunk in response]
+ assert "".join([chunk.choices[0].delta.content or "" for chunk in collected]) == "hi"
+
+
+ @pytest.mark.parametrize(
+ "custom_llm_provider, litellm_params, expected",
+ [
+ ("openai", GenericLiteLLMParams(rust=True), True),
+ ("openai", GenericLiteLLMParams(), False),
+ ("openai", GenericLiteLLMParams(rust=False), False),
+ ("azure", GenericLiteLLMParams(rust=True), False),
+ ("hosted_vllm", GenericLiteLLMParams(rust=True), False),
+ (None, GenericLiteLLMParams(rust=True), False),
+ ],
+ )
+ def test_the_rust_responses_websocket_needs_both_openai_and_the_rust_flag(
+ custom_llm_provider, litellm_params, expected
+ ):
+ assert _rust_responses_websocket_enabled(custom_llm_provider, litellm_params) is expected
+
+
+ def test_a_plain_callback_does_not_advertise_a_pre_call_deployment_hook(monkeypatch):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class _PlainLogger(CustomLogger):
+ pass
+
+ logging_obj = Mock()
+ logging_obj.dynamic_success_callbacks = []
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+ assert _has_pre_call_deployment_hook(logging_obj) is False
+
+ monkeypatch.setattr(litellm, "callbacks", [_PlainLogger()])
+ assert _has_pre_call_deployment_hook(logging_obj) is False
+
+
+ def test_a_callback_that_overrides_the_deployment_hook_is_detected(monkeypatch):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class _DeploymentHookLogger(CustomLogger):
+ async def async_pre_call_deployment_hook(self, kwargs, call_type):
+ return None
+
+ class _InheritsTheHook(_DeploymentHookLogger):
+ pass
+
+ logging_obj = Mock()
+ logging_obj.dynamic_success_callbacks = []
+
+ monkeypatch.setattr(litellm, "callbacks", [_DeploymentHookLogger()])
+ assert _has_pre_call_deployment_hook(logging_obj) is True
+
+ monkeypatch.setattr(litellm, "callbacks", [_InheritsTheHook()])
+ assert _has_pre_call_deployment_hook(logging_obj) is True
+
+ monkeypatch.setattr(litellm, "callbacks", [])
+ logging_obj.dynamic_success_callbacks = [_DeploymentHookLogger()]
+ assert _has_pre_call_deployment_hook(logging_obj) is True
+
+
+ def test_only_callbacks_that_can_charge_a_frame_are_collected_for_ws_quota(monkeypatch):
+ from litellm.integrations.custom_logger import CustomLogger
+
+ class _PlainLogger(CustomLogger):
+ pass
+
+ class _QuotaLogger(CustomLogger):
+ async def enforce_project_io_token_quota_for_frame(self, *args, **kwargs):
+ return None
+
+ class _NotCallableAttribute:
+ enforce_project_io_token_quota_for_frame = "not a method"
+
+ plain, quota, decoy = _PlainLogger(), _QuotaLogger(), _NotCallableAttribute()
+
+ monkeypatch.setattr(litellm, "callbacks", [plain, decoy])
+ assert _collect_ws_project_quota_callbacks() == ()
+
+ monkeypatch.setattr(litellm, "callbacks", [plain, quota, decoy])
+ assert _collect_ws_project_quota_callbacks() == (quota,)
+
+
+ @pytest.mark.asyncio
+ async def test_async_rerank_records_llm_api_duration():
+ """arerank must feed the httpx timing into the logging obj, so the proxy can emit
+ x-litellm-overhead-duration-ms / x-litellm-timing-* on /rerank."""
+
+ def handle(request: httpx.Request) -> httpx.Response:
+ return httpx.Response(
+ 200,
+ json={
+ "id": "rerank-1",
+ "results": [{"index": 0, "relevance_score": 0.9}],
+ "meta": {"api_version": {"version": "2"}, "billed_units": {"search_units": 1}},
+ },
+ )
+
+ client = AsyncHTTPHandler()
+ client.client = httpx.AsyncClient(transport=httpx.MockTransport(handle))
+
+ response = await litellm.arerank(
+ model="cohere/rerank-v3.5",
+ query="what is the capital of france",
+ documents=["paris", "berlin"],
+ top_n=1,
+ api_key="fake-key",
+ client=client,
+ )
+
+ assert response._hidden_params["litellm_overhead_time_ms"] is not None
+ assert response._hidden_params["_response_ms"] >= response._hidden_params["litellm_overhead_time_ms"]
+
+
+ class _JSONBodyVideoConfig(OpenAIVideoConfig):
+ def use_multipart_form_data(self) -> bool:
+ return False
+
+
+ def _video_create_call_kwargs(config, **optional_params):
+ return {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "video_generation_provider_config": config,
+ "video_generation_optional_request_params": {"seconds": "4", **optional_params},
+ "custom_llm_provider": "openai",
+ "litellm_params": GenericLiteLLMParams(api_key="sk-test", api_base="https://video.example/v1"),
+ "logging_obj": Mock(),
+ "timeout": 10.0,
+ }
+
+
+ def _capture_video_create_request(captured):
+ def respond(request):
+ captured["content_type"] = request.headers.get("content-type")
+ captured["body"] = request.content
+ return httpx.Response(
+ 200,
+ json={"id": "video_123", "object": "video", "status": "queued", "created_at": 1712697600, "model": "sora-2"},
+ )
+
+ return respond
+
+
+ def _multipart_text_fields(content_type: str, body: bytes) -> dict:
+ boundary = content_type.split("boundary=")[1].encode()
+ return {
+ part.split(b'name="')[1].split(b'"')[0].decode(): part.partition(b"\r\n\r\n")[2].rstrip(b"\r\n-").decode()
+ for part in body.split(b"--" + boundary)
+ if b'name="' in part and b"filename=" not in part
+ }
+
+
+ def test_video_generation_without_file_sends_multipart_form_data():
+ """Regression for #36493: the OpenAI SDK always sends /videos requests as
+ multipart/form-data, so OpenAI-compatible backends (SGLang Diffusion,
+ vLLM-Omni) reject the JSON body LiteLLM used to send when no
+ input_reference file was attached."""
+ captured = {}
+ client = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_capture_video_create_request(captured))))
+
+ result = BaseLLMHTTPHandler().video_generation_handler(client=client, **_video_create_call_kwargs(OpenAIVideoConfig()))
+
+ assert captured["content_type"].startswith("multipart/form-data")
+ assert _multipart_text_fields(captured["content_type"], captured["body"]) == {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "seconds": "4",
+ }
+ assert result.status == "queued"
+
+
+ @pytest.mark.asyncio
+ async def test_async_video_generation_without_file_sends_multipart_form_data():
+ captured = {}
+ client = AsyncHTTPHandler()
+ client.client = httpx.AsyncClient(transport=httpx.MockTransport(_capture_video_create_request(captured)))
+
+ result = await BaseLLMHTTPHandler().async_video_generation_handler(
+ client=client, **_video_create_call_kwargs(OpenAIVideoConfig())
+ )
+
+ assert captured["content_type"].startswith("multipart/form-data")
+ assert _multipart_text_fields(captured["content_type"], captured["body"]) == {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "seconds": "4",
+ }
+ assert result.status == "queued"
+
+
+ def test_azure_video_generation_without_file_sends_multipart_form_data():
+ """AzureVideoConfig subclasses OpenAIVideoConfig, so it inherits the
+ file-less multipart behavior. Azure's /openai/v1/videos surface is
+ OpenAI-SDK-compatible (the SDK sends multipart there too), so this is
+ intentional; lock it so the inherited flip can't silently regress to JSON."""
+ assert AzureVideoConfig().use_multipart_form_data() is True
+
+ captured = {}
+ client = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_capture_video_create_request(captured))))
+
+ result = BaseLLMHTTPHandler().video_generation_handler(client=client, **_video_create_call_kwargs(AzureVideoConfig()))
+
+ assert captured["content_type"].startswith("multipart/form-data")
+ assert _multipart_text_fields(captured["content_type"], captured["body"]) == {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "seconds": "4",
+ }
+ assert result.status == "queued"
+
+
+ def test_video_generation_json_provider_keeps_json_body():
+ captured = {}
+ client = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_capture_video_create_request(captured))))
+
+ result = BaseLLMHTTPHandler().video_generation_handler(client=client, **_video_create_call_kwargs(_JSONBodyVideoConfig()))
+
+ assert captured["content_type"] == "application/json"
+ assert json.loads(captured["body"]) == {"model": "sora-2", "prompt": "a cat surfing", "seconds": "4"}
+ assert result.status == "queued"
+
+
+ def test_video_generation_with_input_reference_keeps_file_multipart():
+ captured = {}
+ client = HTTPHandler(client=httpx.Client(transport=httpx.MockTransport(_capture_video_create_request(captured))))
+
+ result = BaseLLMHTTPHandler().video_generation_handler(
+ client=client,
+ **_video_create_call_kwargs(OpenAIVideoConfig(), input_reference=b"\x89PNG\r\n\x1a\nfakepng"),
+ )
+
+ assert captured["content_type"].startswith("multipart/form-data")
+ assert b'name="input_reference"' in captured["body"]
+ assert b'filename="input_reference.png"' in captured["body"]
+ assert _multipart_text_fields(captured["content_type"], captured["body"]) == {
+ "model": "sora-2",
+ "prompt": "a cat surfing",
+ "seconds": "4",
+ }
+ assert result.status == "queued"
+
+
+ AZURE_AI_BASE = "https://myfoundry.services.ai.azure.com"
+ AZURE_AI_CHAT_COMPLETIONS_URL = f"{AZURE_AI_BASE}/models/chat/completions"
+
+ def _a_tool_with_an_unsupported_field() -> dict:
+ return {
+ "type": "function",
+ "function": {"name": "lookup", "parameters": {"type": "object", "properties": {}}},
+ "strict": True,
+ }
+
+ A_COMPLETION = {
+ "id": "chatcmpl-1",
+ "object": "chat.completion",
+ "created": 1,
+ "model": "grok-3",
+ "choices": [
+ {"index": 0, "message": {"role": "assistant", "content": "sent"}, "finish_reason": "stop"}
+ ],
+ "usage": {"prompt_tokens": 1, "completion_tokens": 1, "total_tokens": 2},
+ }
+
+ TOOL_LEVEL_REJECTION = "Extra inputs are not permitted: tools[0].strict"
+ UNRELATED_REJECTION = "Extra inputs are not permitted: temperature"
+ A_REJECTION_THE_PROVIDER_CANNOT_FIX = "The model is not available in this region"
+
+
+ class _RecordedAzureAI:
+ def __init__(self, responses: list[httpx.Response]) -> None:
+ self._responses = responses
+ self.bodies: list[dict] = []
+
+ def __call__(self, request: httpx.Request) -> httpx.Response:
+ self.bodies.append(json.loads(request.content))
+ return self._responses[min(len(self.bodies) - 1, len(self._responses) - 1)]
+
+
+ @pytest.fixture
+ def httpx_transport(monkeypatch):
+ monkeypatch.setattr(litellm, "disable_aiohttp_transport", True)
+
+
+ def _rejection(message: str) -> httpx.Response:
+ return httpx.Response(422, json={"error": {"message": message}})
+
+
+ def _call_azure_ai(recorder: _RecordedAzureAI, **overrides):
+ import respx
+
+ with respx.mock(assert_all_called=True) as router:
+ router.post(AZURE_AI_CHAT_COMPLETIONS_URL).mock(side_effect=recorder)
+ return litellm.completion(
+ model="azure_ai/grok-3",
+ messages=[{"role": "user", "content": "hi"}],
+ tools=[_a_tool_with_an_unsupported_field()],
+ api_base=AZURE_AI_BASE,
+ api_key="fake-key",
+ **overrides,
+ )
+
+
+ def test_a_tool_field_the_provider_rejects_is_dropped_and_the_call_retried():
+ recorder = _RecordedAzureAI(
+ [_rejection(TOOL_LEVEL_REJECTION), httpx.Response(200, json=A_COMPLETION)]
+ )
+
+ response = _call_azure_ai(recorder)
+
+ assert len(recorder.bodies) == 2
+ assert recorder.bodies[0]["tools"][0]["strict"] is True
+ assert "strict" not in recorder.bodies[1]["tools"][0]
+ assert response.choices[0].message.content == "sent"
+
+
+ def test_the_retry_changes_only_the_field_the_provider_named():
+ recorder = _RecordedAzureAI(
+ [_rejection(TOOL_LEVEL_REJECTION), httpx.Response(200, json=A_COMPLETION)]
+ )
+
+ _call_azure_ai(recorder)
+
+ first, second = recorder.bodies
+ assert second["messages"] == first["messages"]
+ assert second["model"] == first["model"]
+ assert second["tools"][0]["function"] == first["tools"][0]["function"]
+
+
+ def test_a_provider_that_keeps_rejecting_is_not_retried_forever():
+ recorder = _RecordedAzureAI([_rejection(TOOL_LEVEL_REJECTION)])
+
+ with pytest.raises(litellm.BadRequestError) as raised:
+ _call_azure_ai(recorder)
+
+ assert len(recorder.bodies) == 2
+ assert raised.value.status_code == 422
+
+
+ def test_a_rejection_the_provider_cannot_fix_is_not_retried_at_all():
+ recorder = _RecordedAzureAI([_rejection(A_REJECTION_THE_PROVIDER_CANNOT_FIX)])
+
+ with pytest.raises(litellm.BadRequestError):
+ _call_azure_ai(recorder)
+
+ assert len(recorder.bodies) == 1
+
+
+ def test_an_extra_input_outside_a_tool_is_not_retried_unless_dropping_params_was_asked_for():
+ recorder = _RecordedAzureAI([_rejection(UNRELATED_REJECTION)])
+
+ with pytest.raises(litellm.BadRequestError):
+ _call_azure_ai(recorder)
+
+ assert len(recorder.bodies) == 1
+
+
+ def test_an_extra_input_outside_a_tool_is_retried_when_dropping_params_was_asked_for():
+ recorder = _RecordedAzureAI(
+ [_rejection(UNRELATED_REJECTION), httpx.Response(200, json=A_COMPLETION)]
+ )
+
+ response = _call_azure_ai(recorder, drop_params=True)
+
+ assert len(recorder.bodies) == 2
+ assert response.choices[0].message.content == "sent"
+
+
+ @pytest.mark.asyncio
+ async def test_a_tool_field_the_provider_rejects_is_dropped_and_retried_on_the_async_path(
+ httpx_transport,
+ ):
+ import respx
+
+ recorder = _RecordedAzureAI(
+ [_rejection(TOOL_LEVEL_REJECTION), httpx.Response(200, json=A_COMPLETION)]
+ )
+
+ with respx.mock(assert_all_called=True) as router:
+ router.post(AZURE_AI_CHAT_COMPLETIONS_URL).mock(side_effect=recorder)
+ response = await litellm.acompletion(
+ model="azure_ai/grok-3",
+ messages=[{"role": "user", "content": "hi"}],
+ tools=[_a_tool_with_an_unsupported_field()],
+ api_base=AZURE_AI_BASE,
+ api_key="fake-key",
+ )
+
+ assert len(recorder.bodies) == 2
+ assert recorder.bodies[0]["tools"][0]["strict"] is True
+ assert "strict" not in recorder.bodies[1]["tools"][0]
+ assert response.choices[0].message.content == "sent"
+
+
+ @pytest.mark.asyncio
+ async def test_a_provider_that_keeps_rejecting_is_not_retried_forever_on_the_async_path(
+ httpx_transport,
+ ):
+ import respx
+
+ recorder = _RecordedAzureAI([_rejection(TOOL_LEVEL_REJECTION)])
+
+ with respx.mock(assert_all_called=True) as router:
+ router.post(AZURE_AI_CHAT_COMPLETIONS_URL).mock(side_effect=recorder)
+ with pytest.raises(litellm.BadRequestError):
+ await litellm.acompletion(
+ model="azure_ai/grok-3",
+ messages=[{"role": "user", "content": "hi"}],
+ tools=[_a_tool_with_an_unsupported_field()],
+ api_base=AZURE_AI_BASE,
+ api_key="fake-key",
+ )
+
+ assert len(recorder.bodies) == 2