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
[Bug Fix] Using `gemini-cli` with Vertex Anthropic Models (#12246)
Ishaan Jaff3387029723a3
diff --git a/litellm/google_genai/main.py b/litellm/google_genai/main.pyindex b87d5f143e5..2e80549f7a0 100644--- a/litellm/google_genai/main.py+++ b/litellm/google_genai/main.py@@ -304,7 +304,7 @@ def generate_content(if setup_result.generate_content_provider_config is None:# Use the adapter to convert to completion formatreturn GenerateContentToCompletionHandler.generate_content_handler(- model=setup_result.model,+ model=model,contents=contents, # type: ignoreconfig=setup_result.generate_content_config_dict,stream=False,@@ -385,15 +385,13 @@ async def agenerate_content_stream(# Check if we should use the adapter (when provider config is None)if setup_result.generate_content_provider_config is None:# Use the adapter to convert to completion format- return (- await GenerateContentToCompletionHandler.async_generate_content_handler(- model=setup_result.model,- contents=contents, # type: ignore- config=setup_result.generate_content_config_dict,- litellm_params=setup_result.litellm_params,- stream=True,- **kwargs,- )+ return await GenerateContentToCompletionHandler.async_generate_content_handler(+ model=model,+ contents=contents, # type: ignore+ config=setup_result.generate_content_config_dict,+ litellm_params=setup_result.litellm_params,+ stream=True,+ **kwargs)# Call the handler with async enabled and streaming@@ -462,7 +460,7 @@ def generate_content_stream(if setup_result.generate_content_provider_config is None:# Use the adapter to convert to completion formatreturn GenerateContentToCompletionHandler.generate_content_handler(- model=setup_result.model,+ model=model,contents=contents, # type: ignoreconfig=setup_result.generate_content_config_dict,stream=True,diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/main.pyindex 36c1704439c..78b281494e5 100644--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/main.py@@ -31,6 +31,25 @@ class VertexAIError(Exception):class VertexAIPartnerModels(VertexBase):def __init__(self) -> None:pass++ @staticmethod+ def is_vertex_partner_model(model: str):+ """+ Check if the model string is a Vertex AI Partner Model+ Only use this once you have confirmed that custom_llm_provider is vertex_ai++ Returns:+ bool: True if the model string is a Vertex AI Partner Model, False otherwise+ """+ if (+ model.startswith("meta/")+ or model.startswith("mistral")+ or model.startswith("codestral")+ or model.startswith("jamba")+ or model.startswith("claude")+ ):+ return True+ return Falsedef completion(self,diff --git a/litellm/main.py b/litellm/main.pyindex dfd4e71094a..8fc2d8719d9 100644--- a/litellm/main.py+++ b/litellm/main.py@@ -2603,11 +2603,7 @@ def completion( # type: ignore # noqa: PLR0915new_params = deepcopy(optional_params)if (- model.startswith("meta/")- or model.startswith("mistral")- or model.startswith("codestral")- or model.startswith("jamba")- or model.startswith("claude")+ vertex_partner_models_chat_completion.is_vertex_partner_model(model)):model_response = vertex_partner_models_chat_completion.completion(model=model,diff --git a/litellm/utils.py b/litellm/utils.pyindex 0f59870d1aa..1aaea9fbafc 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -7120,7 +7120,22 @@ class ProviderConfigManager:from litellm.llms.vertex_ai.google_genai.transformation import (VertexAIGoogleGenAIConfig,)+ from litellm.llms.vertex_ai.vertex_ai_partner_models.main import (+ VertexAIPartnerModels,+ )+ #########################################################+ # If Vertex Partner models like Anthropic, Mistral, etc. are used,+ # return None as we want this to go through the litellm.completion() adapter+ # and not the Google Gen AI adapter+ #########################################################+ if VertexAIPartnerModels.is_vertex_partner_model(model):+ return None++ #########################################################+ # If the model is not a Vertex Partner model, return the Vertex AI Google Gen AI Config+ # This is for Vertex `gemini` models+ #########################################################return VertexAIGoogleGenAIConfig()return Nonediff --git a/tests/unified_google_tests/base_google_test.py b/tests/unified_google_tests/base_google_test.pyindex 0f8503638e0..df6a886867f 100644--- a/tests/unified_google_tests/base_google_test.py+++ b/tests/unified_google_tests/base_google_test.py@@ -2,6 +2,7 @@ import asyncioimport jsonimport sysimport os+import tempfilefrom typing import Any, AsyncIterator, Dict, List, Optional, Unionimport pytest@@ -21,6 +22,57 @@ from litellm.integrations.custom_logger import CustomLoggerfrom litellm.types.utils import StandardLoggingPayload[email protected](scope="session")+def load_vertex_ai_credentials():+ """Fixture to load Vertex AI credentials for all tests"""+ # Define the path to the vertex_key.json file+ print("loading vertex ai credentials")+ filepath = os.path.dirname(os.path.abspath(__file__))+ vertex_key_path = filepath + "/vertex_key.json"++ # Read the existing content of the file or create an empty dictionary+ try:+ with open(vertex_key_path, "r") as file:+ # Read the file content+ print("Read vertexai file path")+ content = file.read()++ # If the file is empty or not valid JSON, create an empty dictionary+ if not content or not content.strip():+ service_account_key_data = {}+ else:+ # Attempt to load the existing JSON content+ file.seek(0)+ service_account_key_data = json.load(file)+ except FileNotFoundError:+ # If the file doesn't exist, create an empty dictionary+ service_account_key_data = {}++ # Update the service_account_key_data with environment variables+ private_key_id = os.environ.get("VERTEX_AI_PRIVATE_KEY_ID", "")+ private_key = os.environ.get("VERTEX_AI_PRIVATE_KEY", "")+ private_key = private_key.replace("\\n", "\n")+ service_account_key_data["private_key_id"] = private_key_id+ service_account_key_data["private_key"] = private_key++ # Create a temporary file+ with tempfile.NamedTemporaryFile(mode="w+", delete=False) as temp_file:+ # Write the updated content to the temporary files+ json.dump(service_account_key_data, temp_file, indent=2)++ # Export the temporary file as GOOGLE_APPLICATION_CREDENTIALS+ os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = os.path.abspath(temp_file.name)++ # Yield the path for tests that might need it+ yield os.path.abspath(temp_file.name)++ # Cleanup: remove the temporary file after all tests complete+ try:+ os.unlink(temp_file.name)+ except OSError:+ pass # File might already be deleted++class TestCustomLogger(CustomLogger):def __init__(self,diff --git a/tests/unified_google_tests/test_vertex_anthropic.py b/tests/unified_google_tests/test_vertex_anthropic.pynew file mode 100644index 00000000000..b71b2e2e8ce--- /dev/null+++ b/tests/unified_google_tests/test_vertex_anthropic.py@@ -0,0 +1,331 @@+import asyncio+import json+import sys+import os+from typing import Any, AsyncIterator, Dict, List, Optional, Union+import pytest+from unittest.mock import MagicMock, AsyncMock, patch++sys.path.insert(+ 0, os.path.abspath("../../..")+) # Adds the parent directory to the system path++import litellm+from litellm.google_genai import (+ agenerate_content,+ agenerate_content_stream+)+from google.genai.types import ContentDict, PartDict, GenerateContentResponse+from litellm.integrations.custom_logger import CustomLogger+from litellm.types.utils import StandardLoggingPayload+++def vertex_anthropic_mock_response(*args, **kwargs):+ """Mock response for vertex AI anthropic call"""+ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.headers = {"Content-Type": "application/json"}+ mock_response.json.return_value = {+ "id": "msg_vrtx_013Wki5RFQXAspL7rmxRFjZg",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4",+ "content": [+ {+ "type": "text",+ "text": "Why don't scientists trust atoms? Because they make up everything!"+ }+ ],+ "stop_reason": "end_turn",+ "stop_sequence": None,+ "usage": {"input_tokens": 15, "output_tokens": 20},+ }+ return mock_response+++async def test_vertex_anthropic_mocked():+ """Test agenerate_content with mocked HTTP calls to validate URL and request body"""+ from litellm.llms.custom_httpx.llm_http_handler import AsyncHTTPHandler++ # Set up test data+ contents = ContentDict(+ parts=[+ PartDict(+ text="Hello, can you tell me a short joke?"+ )+ ],+ role="user",+ )++ # Create HTTP client and mock response+ client = AsyncHTTPHandler()+ httpx_response = AsyncMock()+ httpx_response.side_effect = vertex_anthropic_mock_response++ # Expected values for validation+ expected_url = "https://us-east5-aiplatform.googleapis.com/v1/projects/internal-litellm-local-dev/locations/us-east5/publishers/anthropic/models/claude-sonnet-4:rawPredict"+ expected_body_keys = {"messages", "anthropic_version", "max_tokens"}+ expected_message_content = "Hello, can you tell me a short joke?"++ # Patch the HTTP client and make the call+ with patch.object(client, "post", new=httpx_response) as mock_call:+ response = await agenerate_content(+ contents=contents,+ model="vertex_ai/claude-sonnet-4",+ vertex_location="us-east5",+ vertex_project="internal-litellm-local-dev",+ custom_llm_provider="vertex_ai",+ client=client,+ )++ # Verify the call was made+ assert mock_call.call_count == 1++ # Get the call arguments+ call_args = mock_call.call_args+ call_kwargs = call_args.kwargs if call_args else {}++ # Extract URL (could be in args[0] or kwargs['url'])+ if call_args and len(call_args[0]) > 0:+ actual_url = call_args[0][0]+ else:+ actual_url = call_kwargs.get("url", "")++ # Validate URL+ print(f"Expected URL: {expected_url}")+ print(f"Actual URL: {actual_url}")+ assert actual_url == expected_url, f"Expected URL {expected_url}, but got {actual_url}"++ # Validate headers+ actual_headers = call_kwargs.get("headers", {})+ print(f"Actual headers: {actual_headers}")+++ # Validate Authorization header exists+ auth_header_found = any(k.lower() == "authorization" for k in actual_headers.keys())+ assert auth_header_found, f"Authorization header should be present. Found headers: {list(actual_headers.keys())}"++ # Validate request body+ request_body = None+ if "data" in call_kwargs:+ request_body = json.loads(call_kwargs["data"]) if isinstance(call_kwargs["data"], str) else call_kwargs["data"]+ elif "json" in call_kwargs:+ request_body = call_kwargs["json"]++ print(f"Request body: {json.dumps(request_body, indent=2)}")+ assert request_body is not None, "Request body should not be None"++ # Validate required keys in request body+ actual_body_keys = set(request_body.keys())+ assert expected_body_keys.issubset(actual_body_keys), f"Expected keys {expected_body_keys} not found in {actual_body_keys}"++ # Validate message content+ messages = request_body.get("messages", [])+ assert len(messages) > 0, "Messages should not be empty"+ assert messages[0]["role"] == "user", f"Expected first message role to be 'user', got {messages[0]['role']}"++ # Check message content structure+ content = messages[0]["content"]+ if isinstance(content, list):+ text_content = next((item["text"] for item in content if item.get("type") == "text"), None)+ else:+ text_content = content++ assert text_content == expected_message_content, f"Expected message content '{expected_message_content}', got '{text_content}'"++ # Validate anthropic_version+ assert request_body["anthropic_version"] == "vertex-2023-10-16", f"Expected anthropic_version 'vertex-2023-10-16', got {request_body['anthropic_version']}"++ # Validate max_tokens+ assert "max_tokens" in request_body, "max_tokens should be present in request body"+ assert isinstance(request_body["max_tokens"], int), f"max_tokens should be integer, got {type(request_body['max_tokens'])}"++ print("✅ All validations passed!")+ print(f"Response: {response}")+++def vertex_anthropic_streaming_mock_response(*args, **kwargs):+ """Mock streaming response for vertex AI anthropic call"""++ def create_streaming_response():+ """Generator that simulates streaming chunks"""+ chunks = [+ {+ "type": "message_start",+ "message": {+ "id": "msg_vrtx_013Wki5RFQXAspL7rmxRFjZg",+ "type": "message",+ "role": "assistant",+ "model": "claude-sonnet-4",+ "content": [],+ "stop_reason": None,+ "stop_sequence": None,+ "usage": {"input_tokens": 15, "output_tokens": 0},+ }+ },+ {+ "type": "content_block_start",+ "index": 0,+ "content_block": {"type": "text", "text": ""}+ },+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "text_delta", "text": "Why don't scientists trust atoms? "}+ },+ {+ "type": "content_block_delta",+ "index": 0,+ "delta": {"type": "text_delta", "text": "Because they make up everything!"}+ },+ {+ "type": "content_block_stop",+ "index": 0+ },+ {+ "type": "message_delta",+ "delta": {"stop_reason": "end_turn", "stop_sequence": None},+ "usage": {"output_tokens": 20}+ },+ {+ "type": "message_stop"+ }+ ]++ for chunk in chunks:+ # Convert to bytes as streaming responses typically return bytes+ yield f"data: {json.dumps(chunk)}\n\n".encode()++ mock_response = MagicMock()+ mock_response.status_code = 200+ mock_response.headers = {"Content-Type": "text/event-stream"}+ mock_response.iter_bytes = lambda chunk_size=1024: create_streaming_response()+ mock_response.aiter_bytes = lambda chunk_size=1024: create_streaming_response()+ return mock_response+++async def test_vertex_anthropic_streaming_mocked():+ """Test agenerate_content_stream with mocked HTTP calls to validate URL and request body"""+ from litellm.llms.custom_httpx.llm_http_handler import AsyncHTTPHandler++ # Set up test data+ contents = ContentDict(+ parts=[+ PartDict(+ text="Hello, can you tell me a short joke?"+ )+ ],+ role="user",+ )++ # Create HTTP client and mock response+ client = AsyncHTTPHandler()+ httpx_response = AsyncMock()+ httpx_response.side_effect = vertex_anthropic_streaming_mock_response++ # Expected values for validation (same as non-streaming)+ expected_url = "https://us-east5-aiplatform.googleapis.com/v1/projects/internal-litellm-local-dev/locations/us-east5/publishers/anthropic/models/claude-sonnet-4:streamRawPredict"+ expected_body_keys = {"messages", "anthropic_version", "max_tokens"}+ expected_message_content = "Hello, can you tell me a short joke?"++ # Patch the HTTP client and make the call+ with patch.object(client, "post", new=httpx_response) as mock_call:+ response_stream = await agenerate_content_stream(+ contents=contents,+ model="vertex_ai/claude-sonnet-4",+ vertex_location="us-east5",+ vertex_project="internal-litellm-local-dev",+ custom_llm_provider="vertex_ai",+ client=client,+ )++ # Verify the call was made+ assert mock_call.call_count == 1++ # Get the call arguments+ call_args = mock_call.call_args+ call_kwargs = call_args.kwargs if call_args else {}++ # Extract URL (could be in args[0] or kwargs['url'])+ if call_args and len(call_args[0]) > 0:+ actual_url = call_args[0][0]+ else:+ actual_url = call_kwargs.get("url", "")++ # Validate URL (same as non-streaming)+ print(f"Expected URL: {expected_url}")+ print(f"Actual URL: {actual_url}")+ assert actual_url == expected_url, f"Expected URL {expected_url}, but got {actual_url}"++ # Validate headers+ actual_headers = call_kwargs.get("headers", {})+ print(f"Actual headers: {actual_headers}")++ # Validate Authorization header exists+ auth_header_found = any(k.lower() == "authorization" for k in actual_headers.keys())+ assert auth_header_found, f"Authorization header should be present. Found headers: {list(actual_headers.keys())}"++ # Validate anthropic-version header exists and has correct value+ anthropic_version_found = False+ for header_name, header_value in actual_headers.items():+ if header_name.lower() == "anthropic-version":+ assert header_value == "2023-06-01", f"Expected anthropic-version: 2023-06-01, but got {header_value}"+ anthropic_version_found = True+ break+ assert anthropic_version_found, "anthropic-version header should be present"++ # Validate content-type and accept headers+ content_type_found = any(k.lower() == "content-type" for k in actual_headers.keys())+ accept_found = any(k.lower() == "accept" for k in actual_headers.keys())+ assert content_type_found, "content-type header should be present"+ assert accept_found, "accept header should be present"++ # Validate request body (same structure as non-streaming)+ request_body = None+ if "data" in call_kwargs:+ request_body = json.loads(call_kwargs["data"]) if isinstance(call_kwargs["data"], str) else call_kwargs["data"]+ elif "json" in call_kwargs:+ request_body = call_kwargs["json"]++ print(f"Request body: {json.dumps(request_body, indent=2)}")+ assert request_body is not None, "Request body should not be None"++ # Validate required keys in request body+ actual_body_keys = set(request_body.keys())+ assert expected_body_keys.issubset(actual_body_keys), f"Expected keys {expected_body_keys} not found in {actual_body_keys}"++ # Validate message content+ messages = request_body.get("messages", [])+ assert len(messages) > 0, "Messages should not be empty"+ assert messages[0]["role"] == "user", f"Expected first message role to be 'user', got {messages[0]['role']}"++ # Check message content structure+ content = messages[0]["content"]+ if isinstance(content, list):+ text_content = next((item["text"] for item in content if item.get("type") == "text"), None)+ else:+ text_content = content++ assert text_content == expected_message_content, f"Expected message content '{expected_message_content}', got '{text_content}'"++ # Validate anthropic_version in body+ assert request_body["anthropic_version"] == "vertex-2023-10-16", f"Expected anthropic_version 'vertex-2023-10-16', got {request_body['anthropic_version']}"++ # Validate max_tokens+ assert "max_tokens" in request_body, "max_tokens should be present in request body"+ assert isinstance(request_body["max_tokens"], int), f"max_tokens should be integer, got {type(request_body['max_tokens'])}"++ # Test that we can iterate over the streaming response+ chunks_received = []+ try:+ async for chunk in response_stream:+ chunks_received.append(chunk)+ print(f"Received streaming chunk: {chunk}")+ except Exception as e:+ print(f"Note: Streaming iteration might not work with mock response: {e}")++ print(f"✅ All streaming validations passed!")+ print(f"Total chunks received: {len(chunks_received)}")+ print(f"Response stream: {response_stream}")\ No newline at end of filediff --git a/tests/unified_google_tests/vertex_key.json b/tests/unified_google_tests/vertex_key.jsonnew file mode 100644index 00000000000..45ca6acc010--- /dev/null+++ b/tests/unified_google_tests/vertex_key.json@@ -0,0 +1,13 @@+{+ "type": "service_account",+ "project_id": "pathrise-convert-1606954137718",+ "private_key_id": "",+ "private_key": "",+ "client_email": "[email protected]",+ "client_id": "109577393201924326488",+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",+ "token_uri": "https://oauth2.googleapis.com/token",+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/ci-cd-723%40pathrise-convert-1606954137718.iam.gserviceaccount.com",+ "universe_domain": "googleapis.com"+}