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
Apply Black formatting and fix Ruff issues
uzaxirr50d717cde077
diff --git a/litellm/main.py b/litellm/main.pyindex abdc03d3dd3..549c108d7b4 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -1079,7 +1079,6 @@ def completion( # type: ignore # noqa: PLR0915prompt_id=prompt_id, non_default_params=non_default_params)):-(model,messages,@@ -2034,7 +2033,6 @@ def completion( # type: ignore # noqa: PLR0915try:if use_base_llm_http_handler:-response = base_llm_http_handler.completion(model=model,messages=messages,@@ -2550,15 +2548,10 @@ def completion( # type: ignore # noqa: PLR0915)elif custom_llm_provider == "compactifai":api_key = (- api_key- or get_secret_str("COMPACTIFAI_API_KEY")- or litellm.api_key+ api_key or get_secret_str("COMPACTIFAI_API_KEY") or litellm.api_key)- api_base = (- api_base- or "https://api.compactif.ai/v1"- )+ api_base = api_base or "https://api.compactif.ai/v1"## COMPLETION CALLresponse = base_llm_http_handler.completion(@@ -3144,9 +3137,9 @@ def completion( # type: ignore # noqa: PLR0915"aws_region_name" not in optional_paramsor optional_params["aws_region_name"] is None):- optional_params["aws_region_name"] = (- aws_bedrock_client.meta.region_name- )+ optional_params[+ "aws_region_name"+ ] = aws_bedrock_client.meta.region_namebedrock_route = BedrockModelInfo.get_bedrock_route(model)if bedrock_route == "converse":@@ -3488,7 +3481,6 @@ def completion( # type: ignore # noqa: PLR0915)raise eelif custom_llm_provider == "gradient_ai":-api_base = litellm.api_base or api_baseresponse = base_llm_http_handler.completion(model=model,@@ -3848,7 +3840,7 @@ def embedding(*,aembedding: Literal[True],**kwargs,-) -> Coroutine[Any, Any, EmbeddingResponse]:+) -> Coroutine[Any, Any, EmbeddingResponse]:...@@ -3874,7 +3866,7 @@ def embedding(*,aembedding: Literal[False] = False,**kwargs,-) -> EmbeddingResponse:+) -> EmbeddingResponse:...# fmt: on@@ -5127,9 +5119,9 @@ def adapter_completion(new_kwargs = translation_obj.translate_completion_input_params(kwargs=kwargs)response: Union[ModelResponse, CustomStreamWrapper] = completion(**new_kwargs) # type: ignore- translated_response: Optional[Union[BaseModel, AdapterCompletionStreamWrapper]] = (- None- )+ translated_response: Optional[+ Union[BaseModel, AdapterCompletionStreamWrapper]+ ] = Noneif isinstance(response, ModelResponse):translated_response = translation_obj.translate_completion_output_params(response=response@@ -6117,9 +6109,9 @@ def stream_chunk_builder( # noqa: PLR0915]if len(content_chunks) > 0:- response["choices"][0]["message"]["content"] = (- processor.get_combined_content(content_chunks)- )+ response["choices"][0]["message"][+ "content"+ ] = processor.get_combined_content(content_chunks)thinking_blocks = [chunk@@ -6130,9 +6122,9 @@ def stream_chunk_builder( # noqa: PLR0915]if len(thinking_blocks) > 0:- response["choices"][0]["message"]["thinking_blocks"] = (- processor.get_combined_thinking_content(thinking_blocks)- )+ response["choices"][0]["message"][+ "thinking_blocks"+ ] = processor.get_combined_thinking_content(thinking_blocks)reasoning_chunks = [chunk@@ -6143,9 +6135,9 @@ def stream_chunk_builder( # noqa: PLR0915]if len(reasoning_chunks) > 0:- response["choices"][0]["message"]["reasoning_content"] = (- processor.get_combined_reasoning_content(reasoning_chunks)- )+ response["choices"][0]["message"][+ "reasoning_content"+ ] = processor.get_combined_reasoning_content(reasoning_chunks)audio_chunks = [chunkdiff --git a/tests/test_litellm/test_main.py b/tests/test_litellm/test_main.pyindex 8962f383e5b..631592f4c1f 100644--- a/tests/test_litellm/test_main.py+++ b/tests/test_litellm/test_main.py@@ -5,7 +5,6 @@ import sysimport httpximport pytestimport respx-from fastapi.testclient import TestClientsys.path.insert(0, os.path.abspath("../..")@@ -176,7 +175,7 @@ async def test_url_with_format_param(model, sync_mode, monkeypatch):else:response = await acompletion(**args, client=client)print(response)- except Exception as e:+ except Exception:passmock_client.assert_called()@@ -269,7 +268,6 @@ def test_bedrock_latency_optimized_inference():def test_custom_provider_with_extra_headers():- from litellm.llms.custom_httpx.http_handler import HTTPHandlerwith patch.object(litellm.llms.custom_httpx.http_handler.HTTPHandler, "post"@@ -286,7 +284,6 @@ def test_custom_provider_with_extra_headers():def test_custom_provider_with_extra_body():- from litellm.llms.custom_httpx.http_handler import HTTPHandlerwith patch.object(litellm.llms.custom_httpx.http_handler.HTTPHandler, "post"@@ -1132,52 +1129,57 @@ def test_anthropic_disable_url_suffix_env_var():# Test with environment variable disabled (default behavior)with patch.dict(os.environ, {"ANTHROPIC_API_BASE": "https://api.example.com"}):actual_api_base = None-+with patch("litellm.main.anthropic_chat_completions") as mock_anthropic:+def capture_completion(**kwargs):nonlocal actual_api_baseactual_api_base = kwargs.get("api_base")mock_response = MagicMock()mock_response.choices = [MagicMock()]return mock_response-+mock_anthropic.completion = capture_completion-+# This should append /v1/messagescompletion(model="anthropic/claude-3-sonnet",messages=[{"role": "user", "content": "test"}],- api_key="test-key"+ api_key="test-key",)-+# Verify the api_base has /v1/messages appendedassert actual_api_base.endswith("/v1/messages")assert actual_api_base == "https://api.example.com/v1/messages"# Test with environment variable enabled- with patch.dict(os.environ, {- "ANTHROPIC_API_BASE": "https://api.example.com/custom/path",- "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX": "true"- }):+ with patch.dict(+ os.environ,+ {+ "ANTHROPIC_API_BASE": "https://api.example.com/custom/path",+ "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX": "true",+ },+ ):actual_api_base = None-+with patch("litellm.main.anthropic_chat_completions") as mock_anthropic:+def capture_completion(**kwargs):nonlocal actual_api_baseactual_api_base = kwargs.get("api_base")mock_response = MagicMock()mock_response.choices = [MagicMock()]return mock_response-+mock_anthropic.completion = capture_completion-+# This should NOT append /v1/messagescompletion(model="anthropic/claude-3-sonnet",messages=[{"role": "user", "content": "test"}],- api_key="test-key"+ api_key="test-key",)-+# Verify the api_base does not have /v1/messages appendedassert actual_api_base == "https://api.example.com/custom/path"assert not actual_api_base.endswith("/v1/messages")@@ -1192,48 +1194,53 @@ def test_anthropic_text_disable_url_suffix_env_var():# Test with environment variable disabled (default behavior)with patch.dict(os.environ, {"ANTHROPIC_API_BASE": "https://api.example.com"}):actual_api_base = None-+with patch("litellm.main.base_llm_http_handler") as mock_handler:+def capture_completion(**kwargs):nonlocal actual_api_baseactual_api_base = kwargs.get("api_base")return MagicMock()-+mock_handler.completion = capture_completion-+# This should append /v1/completecompletion(model="anthropic_text/claude-instant-1",messages=[{"role": "user", "content": "test"}],- api_key="test-key"+ api_key="test-key",)-+# Verify the api_base has /v1/complete appendedassert actual_api_base.endswith("/v1/complete")assert actual_api_base == "https://api.example.com/v1/complete"# Test with environment variable enabled- with patch.dict(os.environ, {- "ANTHROPIC_API_BASE": "https://api.example.com/custom/complete",- "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX": "true"- }):+ with patch.dict(+ os.environ,+ {+ "ANTHROPIC_API_BASE": "https://api.example.com/custom/complete",+ "LITELLM_ANTHROPIC_DISABLE_URL_SUFFIX": "true",+ },+ ):actual_api_base = None-+with patch("litellm.main.base_llm_http_handler") as mock_handler:+def capture_completion(**kwargs):nonlocal actual_api_baseactual_api_base = kwargs.get("api_base")return MagicMock()-+mock_handler.completion = capture_completion-+# This should NOT append /v1/completecompletion(model="anthropic_text/claude-instant-1",messages=[{"role": "user", "content": "test"}],- api_key="test-key"+ api_key="test-key",)-+# Verify the api_base does not have /v1/complete appendedassert actual_api_base == "https://api.example.com/custom/complete"assert not actual_api_base.endswith("/v1/complete")@@ -1250,15 +1257,24 @@ def test_header_priority_and_merging():try:# Set global headers- litellm.headers = {"X-Global-Header": "global-value", "X-Shared-Header": "global"}+ litellm.headers = {+ "X-Global-Header": "global-value",+ "X-Shared-Header": "global",+ }captured_headers = {}- with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post") as mock_post:+ with patch(+ "litellm.llms.custom_httpx.http_handler.HTTPHandler.post"+ ) as mock_post:+def capture_headers(*args, **kwargs):captured_headers.update(kwargs.get("headers", {}))mock_response = MagicMock()- mock_response.json.return_value = {"choices": [{"message": {"content": "test"}}], "usage": {"total_tokens": 10}}+ mock_response.json.return_value = {+ "choices": [{"message": {"content": "test"}}],+ "usage": {"total_tokens": 10},+ }mock_response.status_code = 200return mock_response@@ -1270,10 +1286,16 @@ def test_header_priority_and_merging():model="custom/test-model",messages=[{"role": "user", "content": "test"}],api_base="https://example.com/api",- extra_headers={"X-Extra-Header": "extra-value", "X-Shared-Header": "extra"},- headers={"X-Request-Header": "request-value", "X-Shared-Header": "request"}+ extra_headers={+ "X-Extra-Header": "extra-value",+ "X-Shared-Header": "extra",+ },+ headers={+ "X-Request-Header": "request-value",+ "X-Shared-Header": "request",+ },)- except Exception as e:+ except Exception:# Expected since we're mockingpass@@ -1299,10 +1321,14 @@ def test_anthropic_header_passing():captured_headers = {}with patch("litellm.llms.anthropic.chat.handler.HTTPHandler.post") as mock_post:+def capture_headers(*args, **kwargs):captured_headers.update(kwargs.get("headers", {}))mock_response = MagicMock()- mock_response.json.return_value = {"content": [{"text": "test response"}], "usage": {"input_tokens": 5, "output_tokens": 5}}+ mock_response.json.return_value = {+ "content": [{"text": "test response"}],+ "usage": {"input_tokens": 5, "output_tokens": 5},+ }mock_response.status_code = 200return mock_response@@ -1314,10 +1340,10 @@ def test_anthropic_header_passing():messages=[{"role": "user", "content": "Hello"}],extra_headers={"X-API-Gateway-Key": "gateway-123",- "X-Tenant-ID": "tenant-456"- }+ "X-Tenant-ID": "tenant-456",+ },)- except Exception as e:+ except Exception:# Expected since we're mockingpass@@ -1337,7 +1363,9 @@ def test_openai_header_passing():captured_extra_headers = {}- with patch("litellm.llms.openai.chat.gpt_transformation.OpenAIGPTConfig.transform_request") as mock_transform:+ with patch(+ "litellm.llms.openai.chat.gpt_transformation.OpenAIGPTConfig.transform_request"+ ) as mock_transform:with patch("litellm.completion_cost") as mock_cost:mock_cost.return_value = 0.0mock_transform.return_value = {"model": "gpt-4", "messages": []}@@ -1357,10 +1385,10 @@ def test_openai_header_passing():messages=[{"role": "user", "content": "Hello"}],extra_headers={"X-Custom-Auth": "bearer-token",- "X-Request-ID": "req-789"- }+ "X-Request-ID": "req-789",+ },)- except Exception as e:+ except Exception:# Expected since we're mockingpass@@ -1384,18 +1412,21 @@ def test_global_headers_functionality():try:# Set global headers- litellm.headers = {- "X-Company-ID": "acme-corp",- "X-Environment": "production"- }+ litellm.headers = {"X-Company-ID": "acme-corp", "X-Environment": "production"}captured_headers = {}- with patch("litellm.llms.custom_httpx.http_handler.HTTPHandler.post") as mock_post:+ with patch(+ "litellm.llms.custom_httpx.http_handler.HTTPHandler.post"+ ) as mock_post:+def capture_headers(*args, **kwargs):captured_headers.update(kwargs.get("headers", {}))mock_response = MagicMock()- mock_response.json.return_value = {"choices": [{"message": {"content": "test"}}], "usage": {"total_tokens": 10}}+ mock_response.json.return_value = {+ "choices": [{"message": {"content": "test"}}],+ "usage": {"total_tokens": 10},+ }mock_response.status_code = 200return mock_response@@ -1405,9 +1436,9 @@ def test_global_headers_functionality():litellm.completion(model="custom/test-model",messages=[{"role": "user", "content": "test"}],- api_base="https://example.com/api"+ api_base="https://example.com/api",)- except Exception as e:+ except Exception:# Expected since we're mockingpass