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
[Fix] Streaming - consistent 'finish_reason' chunk index (#13560)
Krish Dholakia6afaf5721a79
diff --git a/litellm/litellm_core_utils/model_response_utils.py b/litellm/litellm_core_utils/model_response_utils.pynew file mode 100644index 00000000000..5f6fced9d44--- /dev/null+++ b/litellm/litellm_core_utils/model_response_utils.py@@ -0,0 +1,213 @@+"""+Utility functions for ModelResponse and ModelResponseStream objects.+"""++from typing import Any++from litellm.types.utils import Delta, ModelResponseBase, ModelResponseStream+++def is_model_response_stream_empty(model_response: ModelResponseStream) -> bool:+ """+ Check if a ModelResponseStream is empty based on:+ - If finish_reason is set -> it's non empty+ - If any field in choices is set (e.g. content, tool calls, etc.) it's non empty+ - If usage exists -> it's non empty++ This function is robust and ignores fields that are always set (from ModelResponseBase)+ and checks for any meaningful content in other fields.++ Args:+ model_response: The ModelResponseStream to check++ Returns:+ bool: True if the stream is empty, False if it contains meaningful data+ """+ # Fields that are always set in ModelResponseBase and should be ignored+ # These are structural fields that don't indicate content+ BASE_FIELDS = ModelResponseBase.model_fields.keys()++ # Check if usage exists - this indicates meaningful data+ if getattr(model_response, "usage", None) is not None:+ return False++ # Check provider_specific_fields at the top level+ if (+ hasattr(model_response, "provider_specific_fields")+ and model_response.provider_specific_fields is not None+ and model_response.provider_specific_fields != {}+ ):+ return False++ # Check model_extra for dynamically added fields (this is where Pydantic stores them)+ if hasattr(model_response, "model_extra") and model_response.model_extra:+ for extra_field_name, extra_field_value in model_response.model_extra.items():+ if _has_meaningful_content(extra_field_value):+ return False++ # Check for any non-base fields that are set+ for model_response_field in model_response.model_fields.keys():+ # Skip base fields that are always set+ if model_response_field in BASE_FIELDS:+ continue++ # Skip choices - we'll handle them separately with deep inspection+ if model_response_field == "choices":+ continue++ # Check if any other field has meaningful content+ model_response_value = getattr(model_response, model_response_field, None)+ if _has_meaningful_content(model_response_value):+ return False++ # Deep check of choices for any meaningful content+ if hasattr(model_response, "choices") and model_response.choices:+ for choice in model_response.choices:+ if _is_choice_non_empty(choice):+ return False++ # If we get here, the stream is empty+ return True+++def _has_meaningful_content(value: Any) -> bool:+ """+ Check if a value contains meaningful content.++ Args:+ value: The value to check++ Returns:+ bool: True if the value has meaningful content, False otherwise+ """+ if value is None:+ return False++ if isinstance(value, str):+ return len(value.strip()) > 0++ if isinstance(value, (list, dict)):+ return len(value) > 0++ if isinstance(value, bool):+ return True # Any boolean value is meaningful++ if isinstance(value, (int, float)):+ return True # Any numeric value is meaningful++ # For other types (objects), consider them meaningful if they exist+ return True+++def _is_choice_non_empty(choice: Any) -> bool:+ """+ Deep check if a choice contains any meaningful content.++ Args:+ choice: The choice object to check++ Returns:+ bool: True if the choice has meaningful content, False otherwise+ """+ # Check finish_reason+ if hasattr(choice, "finish_reason") and choice.finish_reason is not None:++ return True++ # Check logprobs+ if hasattr(choice, "logprobs") and choice.logprobs is not None:++ return True++ # Check enhancements (if present)+ if hasattr(choice, "enhancements") and choice.enhancements is not None:++ return True++ # Deep check delta object+ if hasattr(choice, "delta") and choice.delta is not None:+ if _is_delta_non_empty(choice.delta):++ return True++ # Check model_extra for dynamically added fields on the choice+ if hasattr(choice, "model_extra") and choice.model_extra:+ for extra_field_name, extra_field_value in choice.model_extra.items():+ # Skip certain structural fields that are just default/None placeholders+ if extra_field_name == "index" and extra_field_value == 0:++ continue+ if (+ extra_field_name in {"finish_reason", "logprobs"}+ and extra_field_value is None+ ):++ continue+ if extra_field_name == "delta":++ continue+ if _has_meaningful_content(extra_field_value):++ return True++ # Check for any other non-standard fields on the choice+ for attr_name in dir(choice):+ # Skip private attributes, methods, and known empty fields+ if (+ attr_name.startswith("_")+ or callable(getattr(choice, attr_name))+ or attr_name.startswith("model_")+ or attr_name+ in {+ "finish_reason",+ "index",+ "delta",+ "logprobs",+ "enhancements",+ }+ ):++ continue++ attr_value = getattr(choice, attr_name, None)+ if _has_meaningful_content(attr_value):++ return True++ return False+++def _is_delta_non_empty(delta: Delta) -> bool:+ """+ Deep check if a delta object contains any meaningful content.++ Args:+ delta: The delta object to check++ Returns:+ bool: True if the delta has meaningful content, False otherwise+ """+ # Check model_extra for dynamically added fields (this is where Pydantic stores them)+ if hasattr(delta, "model_extra") and delta.model_extra:+ for extra_field_name, extra_field_value in delta.model_extra.items():+ # Even structural fields are meaningful if they have actual content+ if _has_meaningful_content(extra_field_value):++ return True++ # Check all regular attributes of the delta object+ for attr_name in dir(delta):+ # Skip private attributes, methods, and Pydantic-specific fields+ if (+ attr_name.startswith("_")+ or callable(getattr(delta, attr_name))+ or attr_name.startswith("model_")+ ):+ continue++ attr_value = getattr(delta, attr_name, None)+ if _has_meaningful_content(attr_value):++ return True++ return Falsediff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.pyindex 3721851a38f..1b6036fef86 100644--- a/litellm/litellm_core_utils/streaming_handler.py+++ b/litellm/litellm_core_utils/streaming_handler.py@@ -13,6 +13,9 @@ from pydantic import BaseModelimport litellmfrom litellm import verbose_logger+from litellm.litellm_core_utils.model_response_utils import (+ is_model_response_stream_empty,+)from litellm.litellm_core_utils.redact_messages import LiteLLMLoggingObjectfrom litellm.litellm_core_utils.thread_pool_executor import executorfrom litellm.types.llms.openai import ChatCompletionChunk@@ -1574,6 +1577,13 @@ class CustomStreamWrapper:response = self.model_response_creator(chunk=obj_dict, hidden_params=response._hidden_params)+ ## check if empty+ is_empty = is_model_response_stream_empty(+ model_response=cast(ModelResponseStream, response)+ )++ if is_empty:+ continue# add usage as hidden paramif self.sent_last_chunk is True and self.stream_options is None:usage = calculate_total_usage(chunks=self.chunks)@@ -1730,6 +1740,12 @@ class CustomStreamWrapper:# Create a new object without the removed attributeprocessed_chunk = self.model_response_creator(chunk=obj_dict)+ is_empty = is_model_response_stream_empty(+ model_response=cast(ModelResponseStream, processed_chunk)+ )++ if is_empty:+ continueprint_verbose(f"final returned processed chunk: {processed_chunk}")return processed_chunkraise StopAsyncIterationdiff --git a/tests/local_testing/test_streaming.py b/tests/local_testing/test_streaming.pyindex 0f25ef4b6e3..323c8097326 100644--- a/tests/local_testing/test_streaming.py+++ b/tests/local_testing/test_streaming.py@@ -476,6 +476,7 @@ def test_completion_azure_stream():async def test_completion_predibase_streaming(sync_mode):try:litellm.set_verbose = True+ litellm._turn_on_debug()if sync_mode:response = completion(model="predibase/llama-3-8b-instruct",@@ -701,7 +702,12 @@ async def test_completion_gemini_stream(sync_mode):},}]- messages = [{"role": "user", "content": "What is the weather like in Boston, MA?. You must provide me with a tool call in your response."}]+ messages = [+ {+ "role": "user",+ "content": "What is the weather like in Boston, MA?. You must provide me with a tool call in your response.",+ }+ ]print("testing gemini streaming")complete_response = ""# Add any assertions here to check the response@@ -817,7 +823,12 @@ async def test_completion_gemini_stream_accumulated_json(sync_mode):},}]- messages = [{"role": "user", "content": "What is the weather like in Boston, MA?. You must provide me with a tool call in your response."}]+ messages = [+ {+ "role": "user",+ "content": "What is the weather like in Boston, MA?. You must provide me with a tool call in your response.",+ }+ ]print("testing gemini streaming")complete_response = ""# Add any assertions here to check the response@@ -3990,3 +4001,48 @@ def test_streaming_with_cost_calculation():assert usage_object.prompt_tokens > 0assert usage_object.cost is not Noneassert usage_object.cost > 0+++def test_streaming_finish_reason():+ litellm.set_verbose = False++ openai_finish_reason_idx: Optional[int] = None+ openai_last_chunk_idx: Optional[int] = None+ anthropic_finish_reason_idx: Optional[int] = None+ anthropic_last_chunk_idx: Optional[int] = None++ ## OpenAI+ response = litellm.completion(+ model="gpt-4o-mini",+ messages=[{"role": "user", "content": "What is the capital of France?"}],+ stream=True,+ stream_options={"include_usage": True},+ )+ for idx, chunk in enumerate(response):+ print(f"OPENAI CHUNK: {chunk}")+ if chunk.choices[0].finish_reason is not None:+ openai_finish_reason_idx = idx+ openai_last_chunk_idx = idx++ assert openai_finish_reason_idx is not None+ assert openai_finish_reason_idx > 0++ ## Anthropic+ response = litellm.completion(+ model="anthropic/claude-3-5-sonnet-latest",+ messages=[{"role": "user", "content": "What is the capital of France?"}],+ stream=True,+ stream_options={"include_usage": True},+ )+ for idx, chunk in enumerate(response):+ print(f"ANTHROPIC CHUNK: {chunk}")+ if chunk.choices[0].finish_reason is not None:+ anthropic_finish_reason_idx = idx+ anthropic_last_chunk_idx = idx++ assert anthropic_finish_reason_idx is not None+ assert anthropic_finish_reason_idx > 0++ relative_anthropic_idx = anthropic_finish_reason_idx - anthropic_last_chunk_idx+ relative_openai_idx = openai_finish_reason_idx - openai_last_chunk_idx+ assert relative_anthropic_idx == relative_openai_idxdiff --git a/tests/test_litellm/litellm_core_utils/test_model_response_utils.py b/tests/test_litellm/litellm_core_utils/test_model_response_utils.pynew file mode 100644index 00000000000..2ffe5853c4d--- /dev/null+++ b/tests/test_litellm/litellm_core_utils/test_model_response_utils.py@@ -0,0 +1,60 @@+from litellm.litellm_core_utils.model_response_utils import (+ is_model_response_stream_empty,+)+from litellm.types.utils import Delta, ModelResponseStream, StreamingChoices+++def test_is_model_response_stream_empty():+ chunk = ModelResponseStream(+ id="chatcmpl-C3sWKN2RWbn6CZ1IGU2QCpRh4RhYf",+ created=1755040596,+ model="gpt-4o-mini",+ object="chat.completion.chunk",+ system_fingerprint="fp_34a54ae93c",+ choices=[+ StreamingChoices(+ finish_reason=None,+ index=0,+ delta=Delta(+ provider_specific_fields=None,+ content=None,+ role=None,+ function_call=None,+ tool_calls=None,+ audio=None,+ ),+ logprobs=None,+ )+ ],+ provider_specific_fields=None,+ )+ assert is_model_response_stream_empty(chunk) is True+++def test_is_model_response_stream_empty_with_custom_value():+ chunk = ModelResponseStream(+ id="chatcmpl-C3sWKN2RWbn6CZ1IGU2QCpRh4RhYf",+ created=1755040596,+ model="gpt-4o-mini",+ object="chat.completion.chunk",+ system_fingerprint="fp_34a54ae93c",+ choices=[+ StreamingChoices(+ finish_reason=None,+ index=0,+ delta=Delta(+ provider_specific_fields=None,+ content=None,+ role=None,+ function_call=None,+ tool_calls=None,+ audio=None,+ ),+ logprobs=None,+ )+ ],+ provider_specific_fields=None,+ )++ setattr(chunk.choices[0].delta, "custom_field", "test")+ assert is_model_response_stream_empty(chunk) is False