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
Only keep the builder's model when the client did not ask for it
mateo-berric010bd6a7ccd
diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex 7333111b6b4..1c6237f1c56 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -281,9 +281,11 @@ def _assembled_model_came_from_a_later_chunk(chunks: list, assembled_model: obje"""Report whether stream_chunk_builder picked a model the first chunk did not carry.Azure Model Router puts the routed model on the chunks after the first one, and the- proxy deliberately leaves those chunks unrestamped so the builder can recover it. The- assembled model is then more specific than the wrapper's, so the caller has to leave- it alone rather than stamping the wrapper's model over it.+ proxy deliberately leaves those chunks unrestamped so the builder can recover it.++ A stored chunk that carries usage is a pre-restamp copy of the one the proxy saw, so+ an alias-restamped stream reaches the builder with the same shape: a first chunk that+ disagrees with the rest. Those two are only told apart by what the client asked for."""first_chunk: Final = chunks[0]first_chunk_model: Final = (@@ -297,6 +299,18 @@ def _assembled_model_came_from_a_later_chunk(chunks: list, assembled_model: obje)+def _assembled_model_is_the_name_the_client_asked_for(request_data: dict, assembled_model: object) -> bool:+ """Report whether the assembled model is the public name the proxy stamps onto chunks.++ That stamp is what leaves an unpriced alias on the partial response, so the deployment's+ own model has to go back on before the row is costed.+ """+ return assembled_model in (+ request_data.get("_litellm_client_requested_model"),+ request_data.get("model"),+ )++async def _bill_partial_streamed_spend_on_disconnect(request_data: dict, response: object) -> bool:"""A client disconnect throws GeneratorExit/CancelledError into the streaming@@ -348,11 +362,10 @@ async def _bill_partial_streamed_spend_on_disconnect(request_data: dict, responsif partial_response is None:return Falsewrapper_model: Final = getattr(response, "model", None)- if (- isinstance(wrapper_model, str)- and wrapper_model- and not _assembled_model_came_from_a_later_chunk(chunks, partial_response.model)- ):+ builder_recovered_the_routed_model: Final = _assembled_model_came_from_a_later_chunk(+ chunks, partial_response.model+ ) and not _assembled_model_is_the_name_the_client_asked_for(request_data, partial_response.model)+ if isinstance(wrapper_model, str) and wrapper_model and not builder_recovered_the_routed_model:partial_response.model = wrapper_modelpartial_usage: Final = getattr(partial_response, "usage", None)if isinstance(partial_usage, Usage):diff --git a/tests/test_litellm/proxy/test_common_request_processing.py b/tests/test_litellm/proxy/test_common_request_processing.pyindex fd48d62a651..9e1fe5f8dac 100644--- a/tests/test_litellm/proxy/test_common_request_processing.py+++ b/tests/test_litellm/proxy/test_common_request_processing.py@@ -5519,7 +5519,7 @@ class TestStreamingClientDisconnectBilling:proxy_logging_obj._arelease_max_parallel_requests_on_disconnect.assert_awaited_once()- async def _bill_and_collect_success_event(self, prepare=None):+ async def _bill_and_collect_success_event(self, prepare=None, request_data=None):recorder = _RecordingSuccessLogger()original_callbacks = litellm.callbackslitellm.callbacks = [recorder]@@ -5528,7 +5528,7 @@ class TestStreamingClientDisconnectBilling:if prepare is not None:prepare(response)billed = await _bill_partial_streamed_spend_on_disconnect(- {"litellm_logging_obj": response.logging_obj}, response+ {"litellm_logging_obj": response.logging_obj, **(request_data or {})}, response)assert billed is Truefor _ in range(50):@@ -5554,6 +5554,28 @@ class TestStreamingClientDisconnectBilling:standard_logging_object = event["kwargs"]["standard_logging_object"]assert standard_logging_object["response_cost"] > 0.0+ @pytest.mark.asyncio+ async def test_disconnect_billing_prices_a_partly_restamped_chunk_list_at_real_model(self):+ """+ A chunk that carries usage is stored as a copy before the proxy restamps the+ one it forwards, so an aliased stream can reach billing with its first chunk+ still on the deployment model and the rest on the client's name.+ """+ assert "openai/my-public-alias" not in litellm.model_cost++ def restamp_only_the_chunks_the_proxy_forwarded(response):+ for chunk in response.chunks[1:]:+ chunk.model = "my-public-alias"++ event = await self._bill_and_collect_success_event(+ restamp_only_the_chunks_the_proxy_forwarded,+ request_data={"model": "my-public-alias"},+ )++ assert event["response_obj"].model == "gpt-4o-mini"+ standard_logging_object = event["kwargs"]["standard_logging_object"]+ assert standard_logging_object["response_cost"] > 0.0+@pytest.mark.asyncioasync def test_disconnect_billing_keeps_the_model_azure_model_router_picked(self):def restamp_like_azure_model_router(response):@@ -5561,7 +5583,10 @@ class TestStreamingClientDisconnectBilling:for chunk in response.chunks[1:]:chunk.model = "gpt-4.1-nano-2025-04-14"- event = await self._bill_and_collect_success_event(restamp_like_azure_model_router)+ event = await self._bill_and_collect_success_event(+ restamp_like_azure_model_router,+ request_data={"model": "azure-model-router"},+ )assert event["response_obj"].model == "gpt-4.1-nano-2025-04-14"standard_logging_object = event["kwargs"]["standard_logging_object"]