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
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_pr_33195_head
mateo-berri0e0768df9f58
diff --cc litellm/main.pyindex 3b13e04bbe3,2a8ed6c87b6..f5aa777dc64--- a/litellm/main.py+++ b/litellm/main.py@@@ -403,50 -388,48 +388,50 @@@ class AsyncCompletionsasync def acompletion(model: str,# Optional OpenAI params: see https://platform.openai.com/docs/api-reference/chat/create- messages: List = [],- functions: Optional[List] = None,- function_call: Optional[str] = None,- timeout: Optional[Union[float, int]] = None,- temperature: Optional[float] = None,- top_p: Optional[float] = None,- n: Optional[int] = None,- stream: Optional[bool] = None,- stream_options: Optional[dict] = None,+ messages: list = [],+ functions: list | None = None,+ function_call: str | None = None,+ timeout: float | None = None,+ temperature: float | None = None,+ top_p: float | None = None,+ n: int | None = None,+ stream: bool | None = None,+ stream_options: dict | None = None,stop=None,- max_tokens: Optional[int] = None,- max_completion_tokens: Optional[int] = None,- modalities: Optional[List[ChatCompletionModality]] = None,- prediction: Optional[ChatCompletionPredictionContentParam] = None,- audio: Optional[ChatCompletionAudioParam] = None,- presence_penalty: Optional[float] = None,- frequency_penalty: Optional[float] = None,- logit_bias: Optional[dict] = None,- user: Optional[str] = None,+ max_tokens: int | None = None,+ max_completion_tokens: int | None = None,+ modalities: list[ChatCompletionModality] | None = None,+ prediction: ChatCompletionPredictionContentParam | None = None,+ audio: ChatCompletionAudioParam | None = None,+ presence_penalty: float | None = None,+ frequency_penalty: float | None = None,+ logit_bias: dict | None = None,+ user: str | None = None,# openai v1.0+ new params- response_format: Optional[Union[dict, Type[BaseModel]]] = None,- seed: Optional[int] = None,- tools: Optional[List] = None,- tool_choice: Optional[Union[str, dict]] = None,- parallel_tool_calls: Optional[bool] = None,- logprobs: Optional[bool] = None,- top_logprobs: Optional[int] = None,+ response_format: dict | type[BaseModel] | None = None,+ seed: int | None = None,+ tools: list | None = None,+ tool_choice: str | dict | None = None,+ parallel_tool_calls: bool | None = None,+ logprobs: bool | None = None,+ top_logprobs: int | None = None,deployment_id=None,- reasoning_effort: Optional[Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"]] = None,- verbosity: Optional[Literal["low", "medium", "high"]] = None,- safety_identifier: Optional[str] = None,- service_tier: Optional[str] = None,+ reasoning_effort: Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"] | None = None,+ verbosity: Literal["low", "medium", "high"] | None = None,+ safety_identifier: str | None = None,+ service_tier: str | None = None,+ store: bool | None = None,+ prompt_cache_key: str | None = None,# set api_base, api_version, api_key- base_url: Optional[str] = None,- api_version: Optional[str] = None,- api_key: Optional[str] = None,- model_list: Optional[list] = None, # pass in a list of api_base,keys, etc.- extra_headers: Optional[dict] = None,+ base_url: str | None = None,+ api_version: str | None = None,+ api_key: str | None = None,+ model_list: list | None = None, # pass in a list of api_base,keys, etc.+ extra_headers: dict | None = None,# Optional liteLLM function params- thinking: Optional[AnthropicThinkingParam] = None,- web_search_options: Optional[OpenAIWebSearchOptions] = None,- include_server_side_tool_invocations: Optional[bool] = None,+ thinking: AnthropicThinkingParam | None = None,+ web_search_options: OpenAIWebSearchOptions | None = None,+ include_server_side_tool_invocations: bool | None = None,# Session managementshared_session: Optional["ClientSession"] = None,# Per-request JSON schema validation (overrides litellm.enable_json_schema_validation)@@@ -4796,54 -4894,52 +4898,54 @@@ def _complete_langflow(ctx: _Completion@tracer.wrap()@client- def completion( # type: ignore+ def completion(model: str,# Optional OpenAI params: see https://platform.openai.com/docs/api-reference/chat/create- messages: List = [],- timeout: Optional[Union[float, str, httpx.Timeout]] = None,- temperature: Optional[float] = None,- top_p: Optional[float] = None,- n: Optional[int] = None,- stream: Optional[bool] = None,- stream_options: Optional[dict] = None,+ messages: list = [],+ timeout: float | str | httpx.Timeout | None = None,+ temperature: float | None = None,+ top_p: float | None = None,+ n: int | None = None,+ stream: bool | None = None,+ stream_options: dict | None = None,stop=None,- max_completion_tokens: Optional[int] = None,- max_tokens: Optional[int] = None,- modalities: Optional[List[ChatCompletionModality]] = None,- prediction: Optional[ChatCompletionPredictionContentParam] = None,- audio: Optional[ChatCompletionAudioParam] = None,- presence_penalty: Optional[float] = None,- frequency_penalty: Optional[float] = None,- logit_bias: Optional[dict] = None,- user: Optional[str] = None,+ max_completion_tokens: int | None = None,+ max_tokens: int | None = None,+ modalities: list[ChatCompletionModality] | None = None,+ prediction: ChatCompletionPredictionContentParam | None = None,+ audio: ChatCompletionAudioParam | None = None,+ presence_penalty: float | None = None,+ frequency_penalty: float | None = None,+ logit_bias: dict | None = None,+ user: str | None = None,# openai v1.0+ new params- reasoning_effort: Optional[Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"]] = None,- verbosity: Optional[Literal["low", "medium", "high"]] = None,- response_format: Optional[Union[dict, Type[BaseModel]]] = None,- seed: Optional[int] = None,- tools: Optional[List] = None,- tool_choice: Optional[Union[str, dict]] = None,- logprobs: Optional[bool] = None,- top_logprobs: Optional[int] = None,- parallel_tool_calls: Optional[bool] = None,- web_search_options: Optional[OpenAIWebSearchOptions] = None,- include_server_side_tool_invocations: Optional[bool] = None,+ reasoning_effort: Literal["none", "minimal", "low", "medium", "high", "xhigh", "default"] | None = None,+ verbosity: Literal["low", "medium", "high"] | None = None,+ response_format: dict | type[BaseModel] | None = None,+ seed: int | None = None,+ tools: list | None = None,+ tool_choice: str | dict | None = None,+ logprobs: bool | None = None,+ top_logprobs: int | None = None,+ parallel_tool_calls: bool | None = None,+ web_search_options: OpenAIWebSearchOptions | None = None,+ include_server_side_tool_invocations: bool | None = None,deployment_id=None,- extra_headers: Optional[dict] = None,- safety_identifier: Optional[str] = None,- service_tier: Optional[str] = None,+ extra_headers: dict | None = None,+ safety_identifier: str | None = None,+ service_tier: str | None = None,+ store: bool | None = None,+ prompt_cache_key: str | None = None,# soon to be deprecated params by OpenAI- functions: Optional[List] = None,- function_call: Optional[str] = None,+ functions: list | None = None,+ function_call: str | None = None,# set api_base, api_version, api_key- base_url: Optional[str] = None,- api_version: Optional[str] = None,- api_key: Optional[str] = None,- model_list: Optional[list] = None, # pass in a list of api_base,keys, etc.+ base_url: str | None = None,+ api_version: str | None = None,+ api_key: str | None = None,+ model_list: list | None = None, # pass in a list of api_base,keys, etc.# Optional liteLLM function params- thinking: Optional[AnthropicThinkingParam] = None,+ thinking: AnthropicThinkingParam | None = None,# Session managementshared_session: Optional["ClientSession"] = None,# Per-request JSON schema validation (overrides litellm.enable_json_schema_validation)diff --cc litellm/utils.pyindex bc5b2447761,68f4278c87a..fbef20078f3--- a/litellm/utils.py+++ b/litellm/utils.py@@@ -3787,17 -3968,15 +3968,17 @@@ def get_optional_paramsreasoning_effort=None,verbosity=None,additional_drop_params=None,- messages: Optional[List[AllMessageValues]] = None,- thinking: Optional[AnthropicThinkingParam] = None,- web_search_options: Optional[OpenAIWebSearchOptions] = None,- safety_identifier: Optional[str] = None,+ messages: list[AllMessageValues] | None = None,+ thinking: AnthropicThinkingParam | None = None,+ web_search_options: OpenAIWebSearchOptions | None = None,+ safety_identifier: str | None = None,+ store: bool | None = None,+ prompt_cache_key: str | None = None,- base_model: Optional[str] = None,+ base_model: str | None = None,**kwargs,):- passed_params = locals().copy()- special_params = passed_params.pop("kwargs")+ passed_params: Final = locals().copy()+ special_params: Final = passed_params.pop("kwargs")# Remove base_model from passed_params so it doesn't interfere with# non_default_params / _check_valid_arg — it's a routing hint, not an# OpenAI param.diff --cc tests/test_litellm/test_main.pyindex 0624b590df7,58373df024c..aad7fa208de--- a/tests/test_litellm/test_main.py+++ b/tests/test_litellm/test_main.py@@@ -2083,85 -2389,178 +2389,262 @@@ def test_stream_chunk_builder_text_compassert response.usage.total_tokens == response.usage.prompt_tokens + response.usage.completion_tokens+def test_completion_forwards_store_and_prompt_cache_key_to_openai():+ """+ Regression test for https://github.com/BerriAI/litellm/issues/33184++ store and prompt_cache_key are documented OpenAI chat completion params that+ were accepted as supported but silently dropped before the provider request+ was built, because they were not named parameters of completion() and+ get_optional_params() the way safety_identifier is.+ """+ from openai import OpenAI++ client = OpenAI(api_key="fake-api-key")++ with patch.object(client.chat.completions.with_raw_response, "create") as mock_client:+ try:+ litellm.completion(+ model="openai/gpt-4o",+ messages=[{"role": "user", "content": "Hello"}],+ store=False,+ prompt_cache_key="test-cache-key",+ client=client,+ )+ except Exception as e:+ print(e)++ mock_client.assert_called_once()+ request_body = mock_client.call_args.kwargs+ assert request_body["store"] is False+ assert request_body["prompt_cache_key"] == "test-cache-key"+++async def test_acompletion_forwards_store_and_prompt_cache_key_to_openai():+ """+ Async variant of the store/prompt_cache_key forwarding regression test for+ https://github.com/BerriAI/litellm/issues/33184+ """+ from openai import AsyncOpenAI++ client = AsyncOpenAI(api_key="fake-api-key")++ with patch.object(client.chat.completions.with_raw_response, "create") as mock_client:+ try:+ await litellm.acompletion(+ model="openai/gpt-4o",+ messages=[{"role": "user", "content": "Hello"}],+ store=False,+ prompt_cache_key="test-cache-key",+ client=client,+ )+ except Exception as e:+ print(e)++ mock_client.assert_called_once()+ request_body = mock_client.call_args.kwargs+ assert request_body["store"] is False+ assert request_body["prompt_cache_key"] == "test-cache-key"+++def test_completion_omits_store_and_prompt_cache_key_when_not_passed():+ """+ When store and prompt_cache_key are not passed, they must not appear in the+ outbound request body (guards against always forwarding None defaults).+ """+ from openai import OpenAI++ client = OpenAI(api_key="fake-api-key")++ with patch.object(client.chat.completions.with_raw_response, "create") as mock_client:+ try:+ litellm.completion(+ model="openai/gpt-4o",+ messages=[{"role": "user", "content": "Hello"}],+ client=client,+ )+ except Exception as e:+ print(e)++ mock_client.assert_called_once()+ request_body = mock_client.call_args.kwargs+ assert "store" not in request_body+ assert "prompt_cache_key" not in request_body+++++ @pytest.mark.asyncio+ @pytest.mark.parametrize(+ "aws_credential_kwargs",+ [+ {+ "aws_session_name": "litellm-gcp",+ "aws_role_name": "arn:aws:iam::123456789012:role/litellm-bedrock-role",+ "aws_web_identity_token": "oidc/google/108963886734710037768",+ },+ {+ "aws_access_key_id": "AKIASTATICKEYFORTEST",+ "aws_secret_access_key": "static-secret-key",+ "aws_session_token": "static-session-token",+ },+ ],+ ids=["web_identity", "static_keys"],+ )+ async def test_acompletion_forwards_aws_credentials_through_responses_bridge(+ respx_mock: respx.MockRouter, monkeypatch, aws_credential_kwargs: dict+ ):+ from botocore.credentials import Credentials++ from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM++ original_disable_aiohttp = litellm.disable_aiohttp_transport+ try:+ litellm.disable_aiohttp_transport = True+ monkeypatch.setenv("DISABLE_AIOHTTP_TRANSPORT", "True")+ litellm.in_memory_llm_clients_cache.flush_cache()+ monkeypatch.delenv("AWS_BEARER_TOKEN_BEDROCK", raising=False)+ monkeypatch.delenv("BEDROCK_MANTLE_API_KEY", raising=False)++ get_credentials_mock = MagicMock(return_value=Credentials("fake-key", "fake-secret"))+ monkeypatch.setattr(BaseAWSLLM, "get_credentials", get_credentials_mock)++ respx_mock.post("https://bedrock-mantle.us-east-2.api.aws/openai/v1/responses").respond(+ json={+ "id": "resp_123",+ "object": "response",+ "created_at": 1760144904,+ "status": "completed",+ "model": "openai.gpt-5.4",+ "output": [+ {+ "type": "message",+ "id": "msg_1",+ "role": "assistant",+ "status": "completed",+ "content": [{"type": "output_text", "text": "ok", "annotations": []}],+ }+ ],+ }+ )++ response = await litellm.acompletion(+ model="bedrock_mantle/openai.gpt-5.4",+ messages=[{"role": "user", "content": "hi"}],+ api_base="https://bedrock-mantle.us-east-2.api.aws/v1",+ aws_region_name="us-east-2",+ num_retries=0,+ **aws_credential_kwargs,+ )++ assert response.choices[0].message.content == "ok"+ credential_kwargs = get_credentials_mock.call_args.kwargs+ assert credential_kwargs["aws_region_name"] == "us-east-2"+ for key, value in aws_credential_kwargs.items():+ assert credential_kwargs[key] == value+ authorization = respx_mock.calls.last.request.headers["Authorization"]+ assert authorization.startswith("AWS4-HMAC-SHA256")+ assert "fake-key" in authorization+ finally:+ litellm.disable_aiohttp_transport = original_disable_aiohttp+ litellm.in_memory_llm_clients_cache.flush_cache()+++ _GEMINI_RESPONSE_BODY = {+ "candidates": [{"content": {"parts": [{"text": "hello"}], "role": "model"}, "finishReason": "STOP"}],+ "usageMetadata": {"promptTokenCount": 2, "candidatesTokenCount": 1, "totalTokenCount": 3},+ }+++ def _gemini_client_returning_a_reply():+ """An injected HTTP client whose post() answers like generativelanguage does."""+ from litellm.llms.custom_httpx.http_handler import HTTPHandler++ client = HTTPHandler()+ request = httpx.Request("POST", "https://generativelanguage.googleapis.com/")+ post = MagicMock(return_value=httpx.Response(200, json=_GEMINI_RESPONSE_BODY, request=request))+ return client, post+++ @pytest.fixture+ def restore_model_registry():+ """litellm.model_cost and the provider name sets are module-global.++ register_model merges into the existing entry in place, hence the deep copy.+ """+ model_cost = copy.deepcopy(litellm.model_cost)+ openai_models = set(litellm.open_ai_chat_completion_models)+ yield+ litellm.model_cost.clear()+ litellm.model_cost.update(model_cost)+ litellm.open_ai_chat_completion_models.clear()+ litellm.open_ai_chat_completion_models.update(openai_models)+++ def test_openai_model_name_does_not_outrank_explicit_provider():+ """`gemini/gpt-4o` goes to Google, not to litellm's OpenAI handler.++ completion() checks `model in litellm.open_ai_chat_completion_models` ahead of+ the gemini branch, so the call used to reach the OpenAI handler carrying+ VertexGeminiConfig, whose transform_request raises NotImplementedError.+ """+ assert "gpt-4o" in litellm.open_ai_chat_completion_models+ client, post = _gemini_client_returning_a_reply()++ with patch.object(client, "post", new=post):+ response = litellm.completion(+ model="gemini/gpt-4o",+ messages=[{"role": "user", "content": "hello"}],+ api_key="test-api-key",+ client=client,+ )++ assert "generativelanguage.googleapis.com" in post.call_args.kwargs["url"]+ assert "models/gpt-4o" in post.call_args.kwargs["url"]+ assert response.choices[0].message.content == "hello"+++ def test_mislabelled_pricing_entry_does_not_reroute_provider(restore_model_registry):+ """register_model is the other way into the same failure.++ An entry claiming litellm_provider "openai" adds its name to+ open_ai_chat_completion_models, so one mislabelled price reroutes every later+ call to that model in the process.+ """+ litellm.register_model(+ {+ "gemini-2.5-pro": {+ "litellm_provider": "openai",+ "mode": "chat",+ "input_cost_per_token": 1e-06,+ "output_cost_per_token": 4e-06,+ }+ }+ )+ assert "gemini-2.5-pro" in litellm.open_ai_chat_completion_models+ client, post = _gemini_client_returning_a_reply()++ with patch.object(client, "post", new=post):+ response = litellm.completion(+ model="gemini/gemini-2.5-pro",+ messages=[{"role": "user", "content": "hello"}],+ api_key="test-api-key",+ client=client,+ )++ assert "generativelanguage.googleapis.com" in post.call_args.kwargs["url"]+ assert response.choices[0].message.content == "hello"+++ def test_openai_model_without_a_provider_still_routes_to_openai():+ from openai import OpenAI++ client = OpenAI(api_key="fake-key")+ raw_response = client.chat.completions.with_raw_response+ with patch.object(raw_response, "create") as mock_create, contextlib.suppress(Exception):+ litellm.completion(+ model="gpt-4o",+ messages=[{"role": "user", "content": "hello"}],+ client=client,+ )++ mock_create.assert_called()