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
[Feat] New Model - Azure Model Router on LiteLLM AI Gateway (#19054)
Ishaan Jaff1b0057671190
diff --git a/docs/my-website/docs/providers/azure_ai/azure_model_router.md b/docs/my-website/docs/providers/azure_ai/azure_model_router.mdnew file mode 100644index 00000000000..5e14c7283f6--- /dev/null+++ b/docs/my-website/docs/providers/azure_ai/azure_model_router.md@@ -0,0 +1,232 @@+# Azure Model Router++Azure Model Router is a feature in Azure AI Foundry that automatically routes your requests to the best available model based on your requirements. This allows you to use a single endpoint that intelligently selects the optimal model for each request.++## Key Features++- **Automatic Model Selection**: Azure Model Router dynamically selects the best model for your request+- **Cost Tracking**: LiteLLM automatically tracks costs based on the actual model used (e.g., `gpt-4.1-nano`), not the router endpoint+- **Streaming Support**: Full support for streaming responses with accurate cost calculation++## LiteLLM Python SDK++### Basic Usage++```python+import litellm+import os++response = litellm.completion(+ model="azure_ai/azure-model-router",+ messages=[{"role": "user", "content": "Hello!"}],+ api_base="https://your-endpoint.cognitiveservices.azure.com/openai/v1/",+ api_key=os.getenv("AZURE_MODEL_ROUTER_API_KEY"),+)++print(response)+```++### Streaming with Usage Tracking++```python+import litellm+import os++response = await litellm.acompletion(+ model="azure_ai/azure-model-router",+ messages=[{"role": "user", "content": "hi"}],+ api_base="https://your-endpoint.cognitiveservices.azure.com/openai/v1/",+ api_key=os.getenv("AZURE_MODEL_ROUTER_API_KEY"),+ stream=True,+ stream_options={"include_usage": True},+)++async for chunk in response:+ print(chunk)+```++## LiteLLM Proxy (AI Gateway)++### config.yaml++```yaml+model_list:+ - model_name: azure-model-router+ litellm_params:+ model: azure_ai/azure-model-router+ api_base: https://your-endpoint.cognitiveservices.azure.com/openai/v1/+ api_key: os.environ/AZURE_MODEL_ROUTER_API_KEY+```++### Start Proxy++```bash+litellm --config config.yaml+```++### Test Request++```bash+curl -X POST http://localhost:4000/chat/completions \+ -H "Content-Type: application/json" \+ -H "Authorization: Bearer sk-1234" \+ -d '{+ "model": "azure-model-router",+ "messages": [{"role": "user", "content": "Hello!"}]+ }'+```++## Add Azure Model Router via LiteLLM UI++This walkthrough shows how to add an Azure Model Router endpoint to LiteLLM using the Admin Dashboard.++### Select Provider++Navigate to the Models page and select "Azure AI Foundry (Studio)" as the provider.++#### Navigate to Models Page++++#### Click Provider Dropdown++++#### Choose Azure AI Foundry++++### Configure Model Name++Set up the model name by entering `azure_ai/` followed by your model router deployment name from Azure.++#### Click Model Name Field++++#### Select Custom Model Name++++#### Enter LiteLLM Model Name++++#### Click Custom Model Name Field++++#### Type Model Prefix++Type `azure_ai/` as the prefix.++++#### Copy Model Name from Azure Portal++Switch to Azure AI Foundry and copy your model router deployment name.++++++#### Paste Model Name++Paste to get `azure_ai/azure-model-router`.++++### Configure API Base and Key++Copy the endpoint URL and API key from Azure portal.++#### Copy API Base URL from Azure++++#### Enter API Base in LiteLLM++++++#### Copy API Key from Azure++++#### Enter API Key in LiteLLM++++### Test and Add Model++Verify your configuration works and save the model.++#### Test Connection++++#### Close Test Dialog++++#### Add Model++++### Verify in Playground++Test your model and verify cost tracking is working.++#### Open Playground++++#### Select Model++++#### Send Test Message++++#### View Logs++++#### Verify Cost Tracking++Cost is tracked based on the actual model used (e.g., `gpt-4.1-nano`).++++## Cost Tracking++LiteLLM automatically handles cost tracking for Azure Model Router by:++1. **Detecting the actual model**: When Azure Model Router routes your request to a specific model (e.g., `gpt-4.1-nano-2025-04-14`), LiteLLM extracts this from the response+2. **Calculating accurate costs**: Costs are calculated based on the actual model used, not the router endpoint name+3. **Streaming support**: Cost tracking works correctly for both streaming and non-streaming requests++### Example Response with Cost++```python+import litellm++response = litellm.completion(+ model="azure_ai/azure-model-router",+ messages=[{"role": "user", "content": "Hello!"}],+ api_base="https://your-endpoint.cognitiveservices.azure.com/openai/v1/",+ api_key="your-api-key",+)++# The response will show the actual model used+print(f"Model used: {response.model}") # e.g., "gpt-4.1-nano-2025-04-14"++# Get cost+from litellm import completion_cost+cost = completion_cost(completion_response=response)+print(f"Cost: ${cost}")+```++diff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_01.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_01.jpegnew file mode 100644index 00000000000..42654600f74Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_01.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_02.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_02.jpegnew file mode 100644index 00000000000..b9feab050ecBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_02.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_03.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_03.jpegnew file mode 100644index 00000000000..3f55ebf0121Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_03.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_04.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_04.jpegnew file mode 100644index 00000000000..1626c78bd1bBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_04.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_05.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_05.jpegnew file mode 100644index 00000000000..bef736e361dBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_05.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_06.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_06.jpegnew file mode 100644index 00000000000..bfeb767eea7Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_06.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_07.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_07.jpegnew file mode 100644index 00000000000..eed742a8c68Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_07.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_08.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_08.jpegnew file mode 100644index 00000000000..e72a6e92e77Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_08.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_09.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_09.jpegnew file mode 100644index 00000000000..5fe1421c2a4Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_09.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_10.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_10.jpegnew file mode 100644index 00000000000..60aa80063fcBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_10.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_11.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_11.jpegnew file mode 100644index 00000000000..98694fbb9beBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_11.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_12.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_12.jpegnew file mode 100644index 00000000000..77922ccea01Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_12.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_13.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_13.jpegnew file mode 100644index 00000000000..2cb80d0826aBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_13.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_14.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_14.jpegnew file mode 100644index 00000000000..8225023658cBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_14.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_15.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_15.jpegnew file mode 100644index 00000000000..7bd72852881Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_15.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_16.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_16.jpegnew file mode 100644index 00000000000..e3dbd75acaeBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_16.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_17.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_17.jpegnew file mode 100644index 00000000000..ba5fd539138Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_17.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_18.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_18.jpegnew file mode 100644index 00000000000..1ead4bee962Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_18.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_19.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_19.jpegnew file mode 100644index 00000000000..ec7fa9c3bcbBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_19.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_20.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_20.jpegnew file mode 100644index 00000000000..2999fcd678eBinary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_20.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_21.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_21.jpegnew file mode 100644index 00000000000..1226e29d648Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_21.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_22.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_22.jpegnew file mode 100644index 00000000000..4455b552b81Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_22.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_23.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_23.jpegnew file mode 100644index 00000000000..4fa88bdb965Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_23.jpeg differdiff --git a/docs/my-website/docs/providers/azure_ai/img/azure_model_router_24.jpeg b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_24.jpegnew file mode 100644index 00000000000..7fb61d1cce1Binary files /dev/null and b/docs/my-website/docs/providers/azure_ai/img/azure_model_router_24.jpeg differdiff --git a/docs/my-website/sidebars.js b/docs/my-website/sidebars.jsindex 2e8ea07ab75..033aef06003 100644--- a/docs/my-website/sidebars.js+++ b/docs/my-website/sidebars.js@@ -602,6 +602,7 @@ const sidebars = {label: "Azure AI",items: ["providers/azure_ai",+ "providers/azure_ai/azure_model_router","providers/azure_ai_agents","providers/azure_ocr","providers/azure_document_intelligence",diff --git a/litellm/cost_calculator.py b/litellm/cost_calculator.pyindex af7dd078107..870b97530fa 100644--- a/litellm/cost_calculator.py+++ b/litellm/cost_calculator.py@@ -587,6 +587,24 @@ def _model_contains_known_llm_provider(model: str) -> bool:return _provider_prefix in LlmProvidersSet+def _get_response_model(completion_response: Any) -> Optional[str]:+ """+ Extract the model name from a completion response object.++ Used as a fallback for cost calculation when the input model name+ doesn't exist in model_cost (e.g., Azure Model Router).+ """+ if completion_response is None:+ return None++ if isinstance(completion_response, BaseModel):+ return getattr(completion_response, "model", None)+ elif isinstance(completion_response, dict):+ return completion_response.get("model", None)++ return None++def _get_usage_object(completion_response: Any,) -> Optional[Usage]:@@ -933,9 +951,8 @@ def completion_cost( # noqa: PLR0915router_model_id=router_model_id,)- potential_model_names = [selected_model]- if model is not None:- potential_model_names.append(model)+ potential_model_names = [selected_model, _get_response_model(completion_response)]+for idx, model in enumerate(potential_model_names):try:diff --git a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py b/litellm/litellm_core_utils/streaming_chunk_builder_utils.pyindex c332e5f88f7..0fb6a449ab6 100644--- a/litellm/litellm_core_utils/streaming_chunk_builder_utils.py+++ b/litellm/litellm_core_utils/streaming_chunk_builder_utils.py@@ -17,8 +17,8 @@ from litellm.types.utils import (ModelResponse,ModelResponseStream,PromptTokensDetailsWrapper,+ ServerToolUse,Usage,- ServerToolUse)from litellm.utils import print_verbose, token_counter@@ -68,12 +68,31 @@ class ChunkProcessor:return chunk["id"]return ""+ @staticmethod+ def _get_model_from_chunks(chunks: List[Dict[str, Any]], first_chunk_model: str) -> str:+ """+ Get the actual model from chunks, preferring a model that differs from the first chunk.++ For Azure Model Router, the first chunk may have the request model (e.g., 'azure-model-router')+ while subsequent chunks have the actual model (e.g., 'gpt-4.1-nano-2025-04-14').+ This method finds the actual model for accurate cost calculation.+ """+ # Look for a model in chunks that differs from the first chunk's model+ for chunk in chunks:+ chunk_model = chunk.get("model")+ if chunk_model and chunk_model != first_chunk_model:+ return chunk_model+ # Fall back to first chunk's model if no different model found+ return first_chunk_model+def build_base_response(self, chunks: List[Dict[str, Any]]) -> ModelResponse:chunk = self.first_chunkid = ChunkProcessor._get_chunk_id(chunks)object = chunk["object"]created = chunk["created"]- model = chunk["model"]+ first_chunk_model = chunk["model"]+ # Get the actual model - for Azure Model Router, this finds the real model from later chunks+ model = ChunkProcessor._get_model_from_chunks(chunks, first_chunk_model)system_fingerprint = chunk.get("system_fingerprint", None)role = chunk["choices"][0]["delta"]["role"]diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex 6baaae7ae3f..3093a37c26a 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -25,6 +25,7 @@ from litellm.types.utils import ()from litellm.types.utils import GenericStreamingChunk as GChunkfrom litellm.types.utils import (+ LlmProviders,ModelResponse,ModelResponseStream,StreamingChoices,@@ -1301,7 +1302,7 @@ class CustomStreamWrapper:if response_obj["is_finished"]:self.received_finish_reason = response_obj["finish_reason"]else: # openai / azure chat model- if self.custom_llm_provider == "azure":+ if self.custom_llm_provider in [LlmProviders.AZURE.value, LlmProviders.AZURE_AI.value]:if isinstance(chunk, BaseModel) and hasattr(chunk, "model"):# for azure, we need to pass the model from the original chunkself.model = getattr(chunk, "model", self.model)diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex 8a8fd6794e7..576ba24aac2 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -6,3 +6,5 @@ model_list:litellm_params:model: openai/*+general_settings:+ store_prompts_in_spend_logs: true\ No newline at end of filediff --git a/litellm/utils.py b/litellm/utils.pyindex 05118f5b892..ea29d22221d 100644--- a/litellm/utils.py+++ b/litellm/utils.py@@ -5128,6 +5128,11 @@ def _check_provider_match(model_info: dict, custom_llm_provider: Optional[str])custom_llm_provider == "litellm_proxy"): # litellm_proxy is a special case, it's not a provider, it's a proxy for the providerreturn True+ elif custom_llm_provider == "azure_ai" and model_info["litellm_provider"] in ("azure", "openai"):+ # Azure AI also works with azure models+ # as a last attempt if the model is not on Azure AI, Azure then fallback to OpenAI cost+ # tracking the cost is better than attributing 0 cost to it.+ return Trueelse:return Falsediff --git a/tests/llm_translation/test_azure_ai.py b/tests/llm_translation/test_azure_ai.pyindex 8d1ebd95904..1633fb4cc82 100644--- a/tests/llm_translation/test_azure_ai.py+++ b/tests/llm_translation/test_azure_ai.py@@ -31,6 +31,8 @@ import pytestimport litellmfrom litellm import completion+from litellm.integrations.custom_logger import CustomLogger+from litellm.types.utils import StandardLoggingPayload@pytest.mark.parametrize(@@ -364,4 +366,150 @@ def test_completion_azure_ai_gpt_4o_with_flexible_api_base(api_base):except litellm.Timeout as e:passexcept Exception as e:- pytest.fail(f"Error occurred: {e}")\ No newline at end of file+ pytest.fail(f"Error occurred: {e}")+++async def test_azure_ai_model_router():+ """+ Test Azure AI model router non-streaming response cost tracking.+ """+ litellm._turn_on_debug()+ response = await litellm.acompletion(+ model="azure_ai/azure-model-router",+ messages=[{"role": "user", "content": "hi who is this"}],+ api_base="https://ishaa-mh6uutut-swedencentral.cognitiveservices.azure.com/openai/v1/",+ api_key=os.getenv("AZURE_MODEL_ROUTER_API_KEY"),+ )+ print("response: ", response)++ # Check response cost+ tracked_cost = response._hidden_params["response_cost"]+ assert tracked_cost > 0+ print("Tracked cost: ", tracked_cost)+++async def test_azure_ai_model_router_streaming_model_in_chunk():+ """+ Test that Azure AI model router streaming returns the actual model in each chunk.+ The response should contain the actual model used (e.g., gpt-4.1-nano) not the request model (azure-model-router).+ """+ litellm._turn_on_debug()+ response = await litellm.acompletion(+ model="azure_ai/azure-model-router",+ messages=[{"role": "user", "content": "hi"}],+ api_base="https://ishaa-mh6uutut-swedencentral.cognitiveservices.azure.com/openai/v1/",+ api_key=os.getenv("AZURE_MODEL_ROUTER_API_KEY"),+ stream=True,+ )++ # Collect chunks and check model field+ chunks_with_model = []+ async for chunk in response:+ print(f"Chunk model: {chunk.model}")+ if chunk.model and chunk.model.strip():+ chunks_with_model.append(chunk.model)++ print(f"All chunk models: {chunks_with_model}")++ # At least some chunks should have a model+ assert len(chunks_with_model) > 0, "No chunks had a model field set"++ # The model should NOT be azure-model-router (the request model)+ # It should be the actual model from the response (e.g., gpt-4.1-nano, gpt-5-nano, etc.)+ for model in chunks_with_model:+ assert model != "azure-model-router", f"Chunk model should be actual model, not request model. Got: {model}"+ # The actual model should be a real model name like gpt-4.1-nano, gpt-5-nano, etc.+ print(f"Verified chunk has actual model: {model}")+++class AzureModelRouterStreamingCallback(litellm.integrations.custom_logger.CustomLogger):+ """+ Custom callback to capture streaming cost tracking for Azure Model Router.+ """+ def __init__(self):+ self.standard_logging_payload = None+ self.response_cost = None+ self.async_success_called = False+ self.complete_streaming_response = None+ super().__init__()++ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):+ print(f"async_log_success_event called")+ self.async_success_called = True+ self.standard_logging_payload = kwargs.get("standard_logging_object")+ self.complete_streaming_response = kwargs.get("complete_streaming_response")++ if self.standard_logging_payload:+ self.response_cost = self.standard_logging_payload.get("response_cost")+ print(f"standard_logging_payload model: {self.standard_logging_payload.get('model')}")+ print(f"standard_logging_payload response_cost: {self.response_cost}")++ if self.complete_streaming_response:+ print(f"complete_streaming_response model: {self.complete_streaming_response.model}")+ print(f"complete_streaming_response usage: {self.complete_streaming_response.usage}")+++++async def test_azure_ai_model_router_streaming_cost_with_stream_options():+ """+ Test Azure AI model router streaming cost tracking with stream_options include_usage=True.+ This tests the specific case where cost tracking fails with stream_options.+ """+ litellm.logging_callback_manager._reset_all_callbacks()+ test_callback = AzureModelRouterStreamingCallback()+ litellm.callbacks = [test_callback]++ try:+ litellm._turn_on_debug()+ response = await litellm.acompletion(+ model="azure_ai/azure-model-router",+ messages=[{"role": "user", "content": "hi"}],+ api_base="https://ishaa-mh6uutut-swedencentral.cognitiveservices.azure.com/openai/v1/",+ api_key=os.getenv("AZURE_MODEL_ROUTER_API_KEY"),+ stream=True,+ stream_options={"include_usage": True},+ )++ # Consume the stream and check chunks+ full_response = ""+ chunks_with_model = []+ async for chunk in response:+ print(f"Chunk: model={chunk.model}, choices={len(chunk.choices) if chunk.choices else 0}")+ if chunk.model:+ chunks_with_model.append(chunk.model)+ if chunk.choices and chunk.choices[0].delta and chunk.choices[0].delta.content:+ full_response += chunk.choices[0].delta.content++ print(f"Full streamed response: {full_response}")+ print(f"Chunks with model: {chunks_with_model}")++ # Give async logging time to complete+ import asyncio+ await asyncio.sleep(1)++ # Verify callback was called+ assert test_callback.async_success_called is True, "async_log_success_event was not called"+ assert test_callback.standard_logging_payload is not None, "standard_logging_payload is None"++ # Check response cost+ print(f"Final response_cost: {test_callback.response_cost}")++ # The first chunk may have the request model (azure-model-router) because it's created+ # before the API response is received. Subsequent chunks should have the actual model.+ # At least some chunks should have the actual model (not azure-model-router)+ actual_model_chunks = [m for m in chunks_with_model if m != "azure-model-router"]+ assert len(actual_model_chunks) > 0, "No chunks had the actual model from the API response"+ print(f"Chunks with actual model: {actual_model_chunks}")++ # Verify response cost is tracked - this is the main goal of this test+ assert test_callback.response_cost is not None, "response_cost is None with stream_options"+ assert test_callback.response_cost > 0, f"response_cost should be > 0, got {test_callback.response_cost}"+ print(f"Streaming cost tracking with stream_options passed. Cost: {test_callback.response_cost}")++ finally:+ litellm.logging_callback_manager._reset_all_callbacks()+ litellm.callbacks = []\ No newline at end of filediff --git a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.pyindex 2164a3b82e3..eef206ca667 100644--- a/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py+++ b/tests/test_litellm/litellm_core_utils/test_streaming_chunk_builder_utils.py@@ -328,6 +328,42 @@ def test_stream_chunk_builder_litellm_usage_chunks():assert usage.total_tokens == 77+def test_get_model_from_chunks_azure_model_router():+ """+ Test that _get_model_from_chunks finds the actual model from Azure Model Router chunks.++ Azure Model Router returns the request model (e.g., 'azure-model-router') in the first chunk,+ but subsequent chunks contain the actual model (e.g., 'gpt-4.1-nano-2025-04-14').+ This is important for accurate cost calculation.+ """+ # First chunk has request model, subsequent chunks have actual model+ chunks = [+ {"model": "azure-model-router", "id": "chatcmpl-123", "choices": []},+ {"model": "gpt-4.1-nano-2025-04-14", "id": "chatcmpl-123", "choices": []},+ {"model": "gpt-4.1-nano-2025-04-14", "id": "chatcmpl-123", "choices": []},+ ]++ result = ChunkProcessor._get_model_from_chunks(+ chunks=chunks, first_chunk_model="azure-model-router"+ )++ # Should return the actual model, not the request model+ assert result == "gpt-4.1-nano-2025-04-14"++ # Test when all chunks have the same model (non-router case)+ chunks_same_model = [+ {"model": "gpt-4", "id": "chatcmpl-456", "choices": []},+ {"model": "gpt-4", "id": "chatcmpl-456", "choices": []},+ ]++ result_same = ChunkProcessor._get_model_from_chunks(+ chunks=chunks_same_model, first_chunk_model="gpt-4"+ )++ # Should return the first chunk's model when all are the same+ assert result_same == "gpt-4"++def test_stream_chunk_builder_anthropic_web_search():# Prepare two mocked streaming chunks with usage split across themchunk1 = ModelResponseStream(diff --git a/tests/test_litellm/test_cost_calculator.py b/tests/test_litellm/test_cost_calculator.pyindex 0f618aeadbd..4d6599fc1b5 100644--- a/tests/test_litellm/test_cost_calculator.py+++ b/tests/test_litellm/test_cost_calculator.py@@ -14,6 +14,7 @@ from pydantic import BaseModelimport litellmfrom litellm.cost_calculator import (+ completion_cost,handle_realtime_stream_cost_calculation,response_cost_calculator,)@@ -22,6 +23,33 @@ from litellm.types.utils import ModelResponse, PromptTokensDetailsWrapper, Usagefrom litellm.utils import TranscriptionResponse+def test_completion_cost_uses_response_model_for_dynamic_routing():+ """+ Test that completion_cost uses the model from the response object+ when the input model (e.g., azure-model-router) is not in model_cost.+ This supports Azure Model Router and similar dynamic routing scenarios.+ """+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"+ litellm.model_cost = litellm.get_model_cost_map(url="")++ # Simulate Azure Model Router: input is generic router, response has actual model+ response = ModelResponse(+ id="test-id",+ model="azure_ai/gpt-4o-2024-08-06", # Response contains actual model used+ choices=[],+ usage=Usage(prompt_tokens=100, completion_tokens=50, total_tokens=150),+ )++ # Should calculate cost using the response model, not the input model+ cost = completion_cost(+ completion_response=response,+ model="azure_ai/azure-model-router", # Input model doesn't exist in model_cost+ custom_llm_provider="azure_ai",+ )++ assert cost > 0, "Cost should be calculated using response model"++def test_cost_calculator_with_response_cost_in_additional_headers():class MockResponse(BaseModel):_hidden_params = {diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.pyindex da52b7bcb39..6c9c1f31c09 100644--- a/tests/test_litellm/test_utils.py+++ b/tests/test_litellm/test_utils.py@@ -21,6 +21,7 @@ from litellm.types.utils import (from litellm.utils import (ProviderConfigManager,TextCompletionStreamWrapper,+ _check_provider_match,get_llm_provider,get_optional_params_image_gen,is_cached_message,@@ -29,6 +30,30 @@ from litellm.utils import (# Adds the parent directory to the system path+def test_check_provider_match_azure_ai_allows_openai_and_azure():+ """+ Test that azure_ai provider can match openai and azure models.+ This is needed for Azure Model Router which can route to OpenAI models.+ """+ # azure_ai should match openai models+ assert _check_provider_match(+ model_info={"litellm_provider": "openai"},+ custom_llm_provider="azure_ai"+ ) is True++ # azure_ai should match azure models+ assert _check_provider_match(+ model_info={"litellm_provider": "azure"},+ custom_llm_provider="azure_ai"+ ) is True++ # azure_ai should NOT match other providers+ assert _check_provider_match(+ model_info={"litellm_provider": "anthropic"},+ custom_llm_provider="azure_ai"+ ) is False++def test_get_optional_params_image_gen():from litellm.llms.azure.image_generation import AzureGPTImageGenerationConfig