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
Merge branch 'litellm_internal_staging' into bugfix/streaming-stable-response-id
mateo-berri24393be4a6fc
diff --cc tests/test_litellm/litellm_core_utils/test_streaming_handler.pyindex a76d427495c,7f54fbfb4c2..4c99bce2b0f--- a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py+++ b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py@@@ -4462,80 -4477,218 +4477,297 @@@ def test_handle_stream_fallback_error_rsession_id_var.set("")+ def test_chunk_creator_preserves_hidden_provider_specific_fields_from_parsed_chunk():+ wrapper = CustomStreamWrapper(+ completion_stream=None,+ model="gemini-3.5-flash",+ logging_obj=MagicMock(),+ custom_llm_provider="vertex_ai",+ )+ parsed_chunk = ModelResponseStream(+ choices=[StreamingChoices(index=0, delta=Delta(content="hello", role="assistant"), finish_reason=None)],+ )+ parsed_chunk._hidden_params["provider_specific_fields"] = {"traffic_type": "ON_DEMAND_FLEX"}++ result = wrapper.chunk_creator(chunk=parsed_chunk)++ assert result is not None+ assert result._hidden_params["provider_specific_fields"] == {"traffic_type": "ON_DEMAND_FLEX"}+ assembled = litellm.stream_chunk_builder(chunks=[result])+ assert assembled is not None+ assert assembled._hidden_params["provider_specific_fields"] == {"traffic_type": "ON_DEMAND_FLEX"}+++ def test_chunk_creator_keeps_provider_model_private_across_stream():+ from litellm.router_utils.add_retry_fallback_headers import (+ get_hidden_params_dict,+ )++ wrapper = CustomStreamWrapper(+ completion_stream=None,+ model="requested-route",+ logging_obj=MagicMock(),+ custom_llm_provider="openai",+ )+ selected_chunk = ModelResponseStream(+ id="chunk-1",+ model="selected-model",+ choices=[+ StreamingChoices(+ finish_reason=None,+ index=0,+ delta=Delta(content="hello"),+ )+ ],+ )+ terminal_chunk = ModelResponseStream(+ id="chunk-1",+ model=None,+ choices=[+ StreamingChoices(+ finish_reason="stop",+ index=0,+ delta=Delta(),+ )+ ],+ )++ first_result = wrapper.chunk_creator(chunk=selected_chunk)+ terminal_result = wrapper.chunk_creator(chunk=terminal_chunk)++ assert first_result is not None+ assert terminal_result is not None+ assert first_result.model == "requested-route"+ assert terminal_result.model == "requested-route"+ assert (+ get_hidden_params_dict(first_result)["provider_response_model"]+ == "selected-model"+ )+ assert (+ get_hidden_params_dict(terminal_result)["provider_response_model"]+ == "selected-model"+ )++ assembled = litellm.stream_chunk_builder(chunks=[first_result, terminal_result])+ assert assembled is not None+ assert assembled.model == "requested-route"+ assert (+ get_hidden_params_dict(assembled)["provider_response_model"]+ == "selected-model"+ )+++ def test_assembled_stream_uses_later_provider_model_for_cost(+ monkeypatch: pytest.MonkeyPatch,+ ):+ from litellm.router_utils.add_retry_fallback_headers import (+ get_hidden_params_dict,+ )++ selected_model_info = {+ "input_cost_per_token": 0.000002,+ "output_cost_per_token": 0.000004,+ "litellm_provider": "azure",+ }+ monkeypatch.setitem(+ litellm.model_cost,+ "azure/gpt-4.1-nano-2025-04-14",+ selected_model_info,+ )+ monkeypatch.setitem(+ litellm.model_cost,+ "azure/azure-model-router",+ {+ "input_cost_per_token": 0.00002,+ "output_cost_per_token": 0.00004,+ "litellm_provider": "azure",+ },+ )+ logging_obj = MagicMock()+ logging_obj.model_call_details = {"custom_llm_provider": "azure"}+ wrapper = CustomStreamWrapper(+ completion_stream=None,+ model="azure-model-router",+ logging_obj=logging_obj,+ custom_llm_provider="azure",+ )+ router_chunk = ModelResponseStream(+ id="chunk-1",+ model="azure-model-router",+ choices=[+ StreamingChoices(+ finish_reason=None,+ index=0,+ delta=Delta(content="hello "),+ )+ ],+ )+ selected_chunk = ModelResponseStream(+ id="chunk-1",+ model="gpt-4.1-nano-2025-04-14",+ choices=[+ StreamingChoices(+ finish_reason=None,+ index=0,+ delta=Delta(content="world"),+ )+ ],+ )+ terminal_chunk = ModelResponseStream(+ id="chunk-1",+ model="azure-model-router",+ choices=[+ StreamingChoices(+ finish_reason="stop",+ index=0,+ delta=Delta(),+ )+ ],+ )++ router_result = wrapper.chunk_creator(chunk=router_chunk)+ selected_result = wrapper.chunk_creator(chunk=selected_chunk)+ terminal_result = wrapper.chunk_creator(chunk=terminal_chunk)++ assert router_result is not None+ assert selected_result is not None+ assert terminal_result is not None+ assert (+ get_hidden_params_dict(router_result)["provider_response_model"]+ == "azure-model-router"+ )+ assert (+ get_hidden_params_dict(selected_result)["provider_response_model"]+ == "gpt-4.1-nano-2025-04-14"+ )+ assert (+ get_hidden_params_dict(terminal_result)["provider_response_model"]+ == "azure-model-router"+ )++ assembled = litellm.stream_chunk_builder(+ chunks=[router_result, selected_result, terminal_result]+ )+ assert assembled is not None+ assert assembled.model == "gpt-4.1-nano-2025-04-14"+ assert (+ get_hidden_params_dict(assembled)["provider_response_model"]+ == "gpt-4.1-nano-2025-04-14"+ )+ assembled.usage = Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15)+ assert litellm.completion_cost(+ completion_response=assembled,+ custom_llm_provider="azure",+ ) == pytest.approx(+ 10 * selected_model_info["input_cost_per_token"]+ + 5 * selected_model_info["output_cost_per_token"]+ )+++ @pytest.mark.asyncio+ async def test_async_stream_assembled_response_keeps_vertex_traffic_type(logging_obj: Logging):+ content_chunk = ModelResponseStream(+ choices=[StreamingChoices(index=0, delta=Delta(content="hello", role="assistant"), finish_reason=None)],+ )+ final_chunk = ModelResponseStream(+ choices=[StreamingChoices(index=0, delta=Delta(content=""), finish_reason="stop")],+ )+ setattr(final_chunk, "usage", Usage(prompt_tokens=7, completion_tokens=5, total_tokens=12))+ final_chunk._hidden_params["provider_specific_fields"] = {"traffic_type": "ON_DEMAND_FLEX"}++ async def _stream():+ yield content_chunk+ yield final_chunk++ wrapper = CustomStreamWrapper(+ completion_stream=_stream(),+ model="gemini-3.5-flash",+ logging_obj=logging_obj,+ custom_llm_provider="vertex_ai",+ stream_options={"include_usage": True},+ )++ received = [chunk async for chunk in wrapper]++ assembled = litellm.stream_chunk_builder(chunks=received, messages=[{"role": "user", "content": "hi"}])+ assert assembled is not None+ assert assembled._hidden_params["provider_specific_fields"]["traffic_type"] == "ON_DEMAND_FLEX"+++++class TestStableStreamingResponseId:+ """+ All chunks of one streamed response must share the same top-level id+ (OpenAI streaming contract). Providers streaming via GenericStreamingChunk+ (e.g. GigaChat) do not propagate an upstream response id, so+ CustomStreamWrapper must pin the id from the first chunk it creates,+ mirroring the existing `created` pinning (issue #11437).++ Clients such as goose merge streamed deltas into one assistant message by+ chunk id; per-chunk ids split a single reply into many messages.+ """++ def test_generic_chunks_share_one_id(self):+ def _generic_chunks():+ return iter(+ [+ {+ "text": "Hello",+ "tool_use": None,+ "is_finished": False,+ "finish_reason": "",+ "usage": None,+ "index": 0,+ },+ {+ "text": " world",+ "tool_use": None,+ "is_finished": False,+ "finish_reason": "",+ "usage": None,+ "index": 0,+ },+ {+ "text": "",+ "tool_use": None,+ "is_finished": True,+ "finish_reason": "stop",+ "usage": {+ "prompt_tokens": 1,+ "completion_tokens": 2,+ "total_tokens": 3,+ },+ "index": 0,+ },+ ]+ )++ wrapper = CustomStreamWrapper(+ completion_stream=_generic_chunks(),+ model="gigachat/GigaChat-2-Max",+ logging_obj=MagicMock(),+ custom_llm_provider="gigachat",+ )+ ids = [chunk.id for chunk in wrapper if chunk.id]+ assert ids, "no chunks emitted"+ assert len(set(ids)) == 1, f"chunk ids differ across one stream: {ids}"++ def test_creator_pins_id_from_first_chunk(self):+ wrapper = CustomStreamWrapper(+ completion_stream=iter([]),+ model="gigachat/GigaChat-2-Max",+ logging_obj=MagicMock(),+ custom_llm_provider="gigachat",+ )+ first = wrapper.model_response_creator()+ assert wrapper.response_id == first.id+ assert wrapper.model_response_creator().id == first.id++ def test_provider_supplied_id_still_wins(self):+ wrapper = CustomStreamWrapper(+ completion_stream=iter([]),+ model="gigachat/GigaChat-2-Max",+ logging_obj=MagicMock(),+ custom_llm_provider="gigachat",+ )+ wrapper.response_id = "chatcmpl-from-provider"+ assert wrapper.model_response_creator().id == "chatcmpl-from-provider"