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 'main' into fix/openrouter-stream-usage-no-stream-options
Cesar Garciaacf2fd9828d1
diff --cc litellm/litellm_core_utils/streaming_handler.pyindex df8095e64d8,baf274f2c62..2c2291ae889--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@@ -149,14 -161,48 +161,49 @@@ class CustomStreamWrapper) # keep track of the returned chunks - used for calculating the input/output tokens for stream optionsself.is_function_call = self.check_is_function_call(logging_obj=logging_obj)self.created: Optional[int] = None+ self._last_returned_hidden_params: Optional[dict] = None- def __iter__(self):+ def _check_max_streaming_duration(self) -> None:+ """Raise litellm.Timeout if the stream has exceeded LITELLM_MAX_STREAMING_DURATION_SECONDS."""+ from litellm.constants import LITELLM_MAX_STREAMING_DURATION_SECONDS++ if LITELLM_MAX_STREAMING_DURATION_SECONDS is None:+ return+ elapsed = time.time() - self._stream_created_time+ if elapsed > LITELLM_MAX_STREAMING_DURATION_SECONDS:+ raise litellm.Timeout(+ message=f"Stream exceeded max streaming duration of {LITELLM_MAX_STREAMING_DURATION_SECONDS}s (elapsed {elapsed:.1f}s)",+ model=self.model or "",+ llm_provider=self.custom_llm_provider or "",+ )++ def __iter__(self) -> Iterator["ModelResponseStream"]:return self- def __aiter__(self):+ def __aiter__(self) -> AsyncIterator["ModelResponseStream"]:return self+ async def aclose(self):+ if self.completion_stream is not None:+ stream_to_close = self.completion_stream+ self.completion_stream = None+ # Shield from anyio cancellation so cleanup awaits can complete.+ # Without this, CancelledError is thrown into every await during+ # task group cancellation, preventing HTTP connection release.+ with anyio.CancelScope(shield=True):+ try:+ if hasattr(stream_to_close, "aclose"):+ await stream_to_close.aclose()+ elif hasattr(stream_to_close, "close"):+ result = stream_to_close.close()+ if result is not None:+ await result+ except BaseException as e:+ verbose_logger.debug(+ "CustomStreamWrapper.aclose: error closing completion_stream: %s",+ e,+ )+def check_send_stream_usage(self, stream_options: Optional[dict]):return (stream_options is not Nonediff --cc tests/test_litellm/litellm_core_utils/test_streaming_handler.pyindex b5922378645,73ecaa20a2d..153ca5d5aab--- a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py+++ b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py@@@ -1187,90 -1187,48 +1187,135 @@@ def test_is_chunk_non_empty_with_valid_)+def test_usage_chunk_after_finish_reason_updates_hidden_params(logging_obj):+ """+ Test that provider-reported usage from a post-finish_reason chunk+ is surfaced in _hidden_params even when stream_options is NOT set.++ Reproduces issue #20760: OpenRouter sends a final chunk with usage data+ after the finish_reason chunk. The hidden_params["usage"] on the last+ user-visible chunk was being calculated before this usage chunk arrived,+ resulting in zeros. The fix recalculates it in the StopIteration handler+ after stream_chunk_builder processes all chunks.+ """+ # Simulate OpenRouter's actual streaming pattern:+ # 1) content chunk+ # 2) finish_reason chunk (content="")+ # 3) usage chunk (content="", finish_reason=None, usage={...})+ chunks = [+ ModelResponseStream(+ id="gen-abc",+ object="chat.completion.chunk",+ created=1000000,+ model="openrouter/openai/gpt-4o-mini",+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(role="assistant", content="Hello"),+ finish_reason=None,+ )+ ],+ ),+ ModelResponseStream(+ id="gen-abc",+ object="chat.completion.chunk",+ created=1000000,+ model="openrouter/openai/gpt-4o-mini",+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(content=""),+ finish_reason="stop",+ )+ ],+ ),+ ModelResponseStream(+ id="gen-abc",+ object="chat.completion.chunk",+ created=1000000,+ model="openrouter/openai/gpt-4o-mini",+ choices=[+ StreamingChoices(+ index=0,+ delta=Delta(role="assistant", content=""),+ finish_reason=None,+ )+ ],+ usage=Usage(+ prompt_tokens=20,+ completion_tokens=135,+ total_tokens=155,+ ),+ ),+ ]++ # Create a CustomStreamWrapper with NO stream_options+ wrapper = CustomStreamWrapper(+ completion_stream=ModelResponseListIterator(model_responses=chunks),+ model="openrouter/openai/gpt-4o-mini",+ logging_obj=logging_obj,+ custom_llm_provider="openrouter",+ stream_options=None,+ )++ # Consume the stream+ collected = []+ for chunk in wrapper:+ collected.append(chunk)++ # The last user-visible chunk's _hidden_params["usage"] should+ # contain the provider-reported values, not zeros.+ last_chunk = collected[-1]+ hidden_usage = last_chunk._hidden_params.get("usage")+ assert hidden_usage is not None, "Expected usage in _hidden_params"+ assert hidden_usage.prompt_tokens == 20, (+ f"Expected prompt_tokens=20 from provider, got {hidden_usage.prompt_tokens}"+ )+ assert hidden_usage.completion_tokens == 135, (+ f"Expected completion_tokens=135 from provider, got {hidden_usage.completion_tokens}"+ )+ @pytest.mark.asyncio+ async def test_custom_stream_wrapper_aclose():+ """Test that aclose() delegates to the underlying completion_stream's aclose()"""+ mock_stream = AsyncMock()+ mock_stream.aclose = AsyncMock()++ wrapper = CustomStreamWrapper(+ completion_stream=mock_stream,+ model=None,+ logging_obj=MagicMock(),+ custom_llm_provider=None,+ )++ await wrapper.aclose()+ mock_stream.aclose.assert_awaited_once()+++ @pytest.mark.asyncio+ async def test_custom_stream_wrapper_aclose_no_underlying():+ """Test that aclose() is safe when completion_stream has no aclose method"""+ mock_stream = MagicMock(spec=[]) # No aclose attribute++ wrapper = CustomStreamWrapper(+ completion_stream=mock_stream,+ model=None,+ logging_obj=MagicMock(),+ custom_llm_provider=None,+ )++ # Should not raise+ await wrapper.aclose()+++ @pytest.mark.asyncio+ async def test_custom_stream_wrapper_aclose_none_stream():+ """Test that aclose() is safe when completion_stream is None"""+ wrapper = CustomStreamWrapper(+ completion_stream=None,+ model=None,+ logging_obj=MagicMock(),+ custom_llm_provider=None,+ )++ # Should not raise+ await wrapper.aclose()