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 /messages with lowest latency routing (#12180)
Ishaan Jaffd65a9fdcc788
diff --git a/litellm/constants.py b/litellm/constants.pyindex b34e7a5569a..f0b38d21a12 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -718,6 +718,8 @@ MAXIMUM_TRACEBACK_LINES_TO_LOG = int(os.getenv("MAXIMUM_TRACEBACK_LINES_TO_LOG",# Headers to control callbacksX_LITELLM_DISABLE_CALLBACKS = "x-litellm-disable-callbacks"+LITELLM_METADATA_FIELD = "litellm_metadata"+OLD_LITELLM_METADATA_FIELD = "metadata"########################### LiteLLM Proxy Specific Constants ###################################################################################################################diff --git a/litellm/integrations/custom_logger.py b/litellm/integrations/custom_logger.pyindex 1cbcd360ce9..890482761a5 100644--- a/litellm/integrations/custom_logger.py+++ b/litellm/integrations/custom_logger.py@@ -408,3 +408,19 @@ class CustomLogger: # https://docs.litellm.ai/docs/observability/custom_callbacif len(text) > max_lengthelse text)+++ def _select_metadata_field(self, request_kwargs: Optional[Dict] = None) -> Optional[str]:+ """+ Select the metadata field to use for logging++ 1. If `litellm_metadata` is in the request kwargs, use it+ 2. Otherwise, use `metadata`+ """+ from litellm.constants import LITELLM_METADATA_FIELD, OLD_LITELLM_METADATA_FIELD+ if request_kwargs is None:+ return None+ if LITELLM_METADATA_FIELD in request_kwargs:+ return LITELLM_METADATA_FIELD+ return OLD_LITELLM_METADATA_FIELD+\ No newline at end of filediff --git a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py b/litellm/llms/anthropic/experimental_pass_through/messages/handler.pyindex 37fd839b3c5..58e40ce1b1b 100644--- a/litellm/llms/anthropic/experimental_pass_through/messages/handler.py+++ b/litellm/llms/anthropic/experimental_pass_through/messages/handler.py@@ -17,6 +17,7 @@ from litellm.llms.base_llm.anthropic_messages.transformation import ()from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandlerfrom litellm.llms.custom_httpx.llm_http_handler import BaseLLMHTTPHandler+from litellm.types.llms.anthropic_messages.anthropic_request import AnthropicMetadatafrom litellm.types.llms.anthropic_messages.anthropic_response import (AnthropicMessagesResponse,)@@ -91,6 +92,16 @@ async def anthropic_messages(response = init_responsereturn response+def validate_anthropic_api_metadata(metadata: Optional[Dict] = None) -> Optional[Dict]:+ """+ Validate Anthropic API metadata - This is done to ensure only allowed `metadata` fields are passed to Anthropic API++ If there are any litellm specific metadata fields, use `litellm_metadata` key to pass them.+ """+ if metadata is None:+ return None+ anthropic_metadata_obj = AnthropicMetadata(**metadata)+ return anthropic_metadata_obj.model_dump(exclude_none=True)def anthropic_messages_handler(max_tokens: int,@@ -120,6 +131,7 @@ def anthropic_messages_handler(Makes Anthropic `/v1/messages` API calls In the Anthropic API Spec"""from litellm.types.utils import LlmProviders+ metadata = validate_anthropic_api_metadata(metadata)local_vars = locals()is_async = kwargs.pop("is_async", False)diff --git a/litellm/router_strategy/lowest_latency.py b/litellm/router_strategy/lowest_latency.pyindex 55ca98843d7..9b37b4745d3 100644--- a/litellm/router_strategy/lowest_latency.py+++ b/litellm/router_strategy/lowest_latency.py@@ -44,10 +44,11 @@ class LowestLatencyLoggingHandler(CustomLogger):"""Update latency usage on success"""- if kwargs["litellm_params"].get("metadata") is None:+ metadata_field = self._select_metadata_field(kwargs)+ if kwargs["litellm_params"].get(metadata_field) is None:passelse:- model_group = kwargs["litellm_params"]["metadata"].get(+ model_group = kwargs["litellm_params"][metadata_field].get("model_group", None)@@ -181,12 +182,13 @@ class LowestLatencyLoggingHandler(CustomLogger):Check if Timeout Error, if timeout set deployment latency -> 100"""try:+ metadata_field = self._select_metadata_field(kwargs)_exception = kwargs.get("exception", None)if isinstance(_exception, litellm.Timeout):- if kwargs["litellm_params"].get("metadata") is None:+ if kwargs["litellm_params"].get(metadata_field) is None:passelse:- model_group = kwargs["litellm_params"]["metadata"].get(+ model_group = kwargs["litellm_params"][metadata_field].get("model_group", None)@@ -251,10 +253,11 @@ class LowestLatencyLoggingHandler(CustomLogger):"""Update latency usage on success"""- if kwargs["litellm_params"].get("metadata") is None:+ metadata_field = self._select_metadata_field(kwargs)+ if kwargs["litellm_params"].get(metadata_field) is None:passelse:- model_group = kwargs["litellm_params"]["metadata"].get(+ model_group = kwargs["litellm_params"][metadata_field].get("model_group", None)@@ -519,9 +522,9 @@ class LowestLatencyLoggingHandler(CustomLogger):# Pick a random deployment from valid deploymentsrandom_valid_deployment = random.choice(valid_deployments)deployment = random_valid_deployment[0]-- if request_kwargs is not None and "metadata" in request_kwargs:- request_kwargs["metadata"][+ metadata_field = self._select_metadata_field(request_kwargs)+ if request_kwargs is not None and metadata_field in request_kwargs:+ request_kwargs[metadata_field]["_latency_per_deployment"] = _latency_per_deploymentreturn deploymentdiff --git a/litellm/types/llms/anthropic_messages/anthropic_request.py b/litellm/types/llms/anthropic_messages/anthropic_request.pynew file mode 100644index 00000000000..00b2590ba7c--- /dev/null+++ b/litellm/types/llms/anthropic_messages/anthropic_request.py@@ -0,0 +1,13 @@+from typing import Optional++from pydantic import BaseModel+++class AnthropicMetadata(BaseModel):+ """+ Object with allowed fields for Anthropic API metadata++ https://docs.anthropic.com/en/api/messages#body-metadata-user-id+ """+ user_id: Optional[str] = None+diff --git a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.pyindex 2a7ac967e39..929ed9baf60 100644--- a/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py+++ b/tests/pass_through_unit_tests/test_anthropic_messages_passthrough.py@@ -231,6 +231,140 @@ async def test_anthropic_messages_litellm_router_non_streaming():print(f"Non-streaming response: {json.dumps(response, indent=2)}")return response+async def test_anthropic_messages_litellm_router_routing_strategy():+ """+ Test the anthropic_messages with routing strategy + non-streaming request+ """+ litellm._turn_on_debug()+ router = Router(+ model_list=[+ {+ "model_name": "claude-special-alias",+ "litellm_params": {+ "model": "claude-3-haiku-20240307",+ "api_key": os.getenv("ANTHROPIC_API_KEY"),+ },+ }+ ],+ routing_strategy="latency-based-routing",+ )++ # Set up test parameters+ messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]++ # Call the handler+ response = await router.aanthropic_messages(+ messages=messages,+ model="claude-special-alias",+ max_tokens=100,+ metadata={+ "user_id": "hello",+ }+ )++ # Verify response+ assert "id" in response+ assert "content" in response+ assert "model" in response+ assert response["role"] == "assistant"++ print(f"Non-streaming response: {json.dumps(response, indent=2)}")+ return response+++async def test_anthropic_messages_litellm_router_latency_metadata_tracking():+ """+ Test the anthropic_messages with routing strategy and verify that _latency_per_deployment+ field is passed in litellm_metadata when calling litellm.anthropic_messages+ """+ with unittest.mock.patch('litellm.anthropic_messages') as mock_anthropic_messages:+ # Mock the return value+ mock_response = {+ "id": "msg_123456",+ "type": "message",+ "role": "assistant",+ "content": [{"type": "text", "text": "Here's a joke for you!"}],+ "model": "claude-3-haiku-20240307",+ "stop_reason": "end_turn",+ "usage": {"input_tokens": 10, "output_tokens": 20},+ }+ mock_anthropic_messages.return_value = mock_response+ # Set the __name__ attribute that the router expects+ mock_anthropic_messages.__name__ = "anthropic_messages"++ MODEL_GROUP = "claude-special-alias"+ router = Router(+ model_list=[+ {+ "model_name": MODEL_GROUP,+ "litellm_params": {+ "model": "claude-3-haiku-20240307",+ "api_key": os.getenv("ANTHROPIC_API_KEY"),+ },+ }+ ],+ routing_strategy="latency-based-routing",+ )++ # Set up test parameters+ messages = [{"role": "user", "content": "Hello, can you tell me a short joke?"}]++ # Call the handler+ response = await router.aanthropic_messages(+ messages=messages,+ model=MODEL_GROUP,+ max_tokens=100,+ metadata={+ "user_id": "hello",+ }+ )++ # Verify response+ assert response == mock_response++ # Verify that litellm.anthropic_messages was called+ mock_anthropic_messages.assert_called_once()++ # Get the call arguments+ call_args = mock_anthropic_messages.call_args+ call_kwargs = call_args.kwargs++ print("Call kwargs:", json.dumps(call_kwargs, indent=2, default=str))++ # Verify that litellm_metadata was passed and contains _latency_per_deployment+ assert "litellm_metadata" in call_kwargs, "litellm_metadata should be passed to anthropic_messages"++ litellm_metadata = call_kwargs["litellm_metadata"]+ assert litellm_metadata is not None, "litellm_metadata should not be None"+ assert isinstance(litellm_metadata, dict), "litellm_metadata should be a dictionary"++ # Verify _latency_per_deployment is present+ assert "_latency_per_deployment" in litellm_metadata, "litellm_metadata should contain _latency_per_deployment field"++ # Verify the structure of _latency_per_deployment+ latency_per_deployment = litellm_metadata["_latency_per_deployment"]+ assert isinstance(latency_per_deployment, dict), "_latency_per_deployment should be a dictionary"++ print(f"✅ Latency per deployment data: {latency_per_deployment}")++ # Verify other expected fields in litellm_metadata+ assert "model_group" in litellm_metadata+ assert litellm_metadata["model_group"] == MODEL_GROUP+ assert "deployment" in litellm_metadata+ assert "model_info" in litellm_metadata++ # Verify other call parameters+ assert call_kwargs["model"] == "claude-3-haiku-20240307"+ assert call_kwargs["messages"] == messages+ assert call_kwargs["max_tokens"] == 100+ assert call_kwargs["metadata"] == {"user_id": "hello"}++ print("✅ Successfully verified that _latency_per_deployment is passed in litellm_metadata to anthropic_messages")++ return response+class TestCustomLogger(CustomLogger):def __init__(self):@@ -492,7 +626,15 @@ async def test_anthropic_messages_bedrock_credentials_passthrough():messages=[{"role": "user", "content": "Hello, test credentials"}],model="bedrock/us.anthropic.claude-3-5-sonnet-20240620-v1:0",max_tokens=100,- **aws_params+ aws_access_key_id=aws_params["aws_access_key_id"],+ aws_secret_access_key=aws_params["aws_secret_access_key"],+ aws_session_token=aws_params["aws_session_token"],+ aws_region_name=aws_params["aws_region_name"],+ aws_role_name=aws_params["aws_role_name"],+ aws_session_name=aws_params["aws_session_name"],+ aws_profile_name=aws_params["aws_profile_name"],+ aws_web_identity_token=aws_params["aws_web_identity_token"],+ aws_sts_endpoint=aws_params["aws_sts_endpoint"],)# Verify get_credentials was called with the correct parameters@@ -581,5 +723,8 @@ def test_sync_openai_messages():assert response is not Noneassert isinstance(response, dict)- assert response["content"][0].text is not None+ assert "content" in response+ assert response["content"] is not None+ assert len(response["content"]) > 0+ assert response["content"][0]["text"] is not None