Skip to content

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]

refactor(streaming): extract chunk_creator dispatch so basedpyright can analyze it (#30793)

Mateo Wang6437b812beb0
diff --git a/litellm/litellm_core_utils/streaming_handler.py b/litellm/litellm_core_utils/streaming_handler.py
index d3330c3dcec..5f474b0800e 100644
--- a/litellm/litellm_core_utils/streaming_handler.py
+++ b/litellm/litellm_core_utils/streaming_handler.py
@@ -6,6 +6,7 @@ import logging
import threading
import time
import traceback
+from dataclasses import dataclass
from typing import (
Any,
AsyncIterator,
@@ -97,6 +98,19 @@ def print_verbose(print_statement):
pass
+@dataclass(frozen=True, slots=True)
+class _ProviderChunkParsed:
+ response_obj: dict[str, Any]
+
+
+@dataclass(frozen=True, slots=True)
+class _ProviderChunkEarlyReturn:
+ value: Any
+
+
+_ProviderChunkResult = Union[_ProviderChunkParsed, _ProviderChunkEarlyReturn]
+
+
class CustomStreamWrapper:
def __init__(
self,
@@ -1145,381 +1159,392 @@ class CustomStreamWrapper:
del model_response.choices[0].delta.reasoning_content
return
- def chunk_creator(self, chunk: Any): # type: ignore
- if hasattr(chunk, "id"):
- self.response_id = chunk.id
- model_response = self.model_response_creator()
- response_obj: Dict[str, Any] = {}
- try:
- # return this for all models
- completion_obj: Dict[str, Any] = {"content": ""}
- from litellm.types.utils import GenericStreamingChunk as GChunk
+ def _dispatch_provider_chunk(
+ self,
+ chunk: Any,
+ model_response: ModelResponseStream,
+ completion_obj: dict[str, Any],
+ ) -> _ProviderChunkResult:
+ response_obj: dict[str, Any] = {}
+ if (
+ isinstance(chunk, ModelResponseStream)
+ and self.custom_llm_provider is not None
+ and self.custom_llm_provider in litellm._custom_providers
+ ):
+ _has_content = bool(
+ chunk.choices
+ and chunk.choices[0].delta is not None
+ and (
+ chunk.choices[0].delta.content or chunk.choices[0].delta.tool_calls
+ )
+ )
+ if self.received_finish_reason is not None:
+ if not _has_content:
+ raise StopIteration
+ if chunk.choices and chunk.choices[0].finish_reason:
+ self.received_finish_reason = chunk.choices[0].finish_reason
+ if not _has_content:
+ return _ProviderChunkEarlyReturn(None)
+ # Strip finish_reason from the content chunk so it appears
+ # only on the trailing empty-delta chunk (OpenAI spec).
+ # finish_reason_handler() will emit the proper terminal chunk.
+ chunk.choices[0].finish_reason = None # type: ignore[assignment]
+ return _ProviderChunkEarlyReturn(chunk)
- if (
- isinstance(chunk, ModelResponseStream)
- and self.custom_llm_provider is not None
- and self.custom_llm_provider in litellm._custom_providers
- ):
- _has_content = bool(
- chunk.choices
- and chunk.choices[0].delta is not None
- and (
- chunk.choices[0].delta.content
- or chunk.choices[0].delta.tool_calls
- )
+ if (
+ isinstance(chunk, dict)
+ and generic_chunk_has_all_required_fields(
+ chunk=chunk
+ ) # check if chunk is a generic streaming chunk
+ ) or (
+ self.custom_llm_provider
+ and self.custom_llm_provider in litellm._custom_providers
+ ):
+ if self.received_finish_reason is not None:
+ _chunk_has_content = isinstance(chunk, dict) and (
+ bool(chunk.get("text", ""))
+ or chunk.get("tool_use") is not None
+ # Usage-only final chunks are valid and needed to surface
+ # finish_reason/usage to downstream translators.
+ or chunk.get("usage") is not None
+ )
+ if not _chunk_has_content and (
+ not isinstance(chunk, dict)
+ or "provider_specific_fields" not in chunk
+ ):
+ raise StopIteration
+ anthropic_response_obj: GChunk = cast(GChunk, chunk)
+ completion_obj["content"] = anthropic_response_obj["text"]
+ if anthropic_response_obj["is_finished"]:
+ self.received_finish_reason = anthropic_response_obj["finish_reason"]
+
+ if anthropic_response_obj["finish_reason"]:
+ self.intermittent_finish_reason = anthropic_response_obj[
+ "finish_reason"
+ ]
+
+ if anthropic_response_obj["usage"] is not None:
+ setattr(
+ model_response,
+ "usage",
+ litellm.Usage(**anthropic_response_obj["usage"]),
)
- if self.received_finish_reason is not None:
- if not _has_content:
- raise StopIteration
- if chunk.choices and chunk.choices[0].finish_reason:
- self.received_finish_reason = chunk.choices[0].finish_reason
- if not _has_content:
- return None
- # Strip finish_reason from the content chunk so it appears
- # only on the trailing empty-delta chunk (OpenAI spec).
- # finish_reason_handler() will emit the proper terminal chunk.
- chunk.choices[0].finish_reason = None # type: ignore[assignment]
- return chunk
if (
- isinstance(chunk, dict)
- and generic_chunk_has_all_required_fields(
- chunk=chunk
- ) # check if chunk is a generic streaming chunk
- ) or (
- self.custom_llm_provider
- and self.custom_llm_provider in litellm._custom_providers
+ "tool_use" in anthropic_response_obj
+ and anthropic_response_obj["tool_use"] is not None
):
- if self.received_finish_reason is not None:
- _chunk_has_content = isinstance(chunk, dict) and (
- bool(chunk.get("text", ""))
- or chunk.get("tool_use") is not None
- # Usage-only final chunks are valid and needed to surface
- # finish_reason/usage to downstream translators.
- or chunk.get("usage") is not None
- )
- if not _chunk_has_content and (
- not isinstance(chunk, dict)
- or "provider_specific_fields" not in chunk
- ):
- raise StopIteration
- anthropic_response_obj: GChunk = cast(GChunk, chunk)
- completion_obj["content"] = anthropic_response_obj["text"]
- if anthropic_response_obj["is_finished"]:
- self.received_finish_reason = anthropic_response_obj[
- "finish_reason"
- ]
-
- if anthropic_response_obj["finish_reason"]:
- self.intermittent_finish_reason = anthropic_response_obj[
- "finish_reason"
- ]
-
- if anthropic_response_obj["usage"] is not None:
- setattr(
- model_response,
- "usage",
- litellm.Usage(**anthropic_response_obj["usage"]),
- )
+ completion_obj["tool_calls"] = [anthropic_response_obj["tool_use"]]
- if (
- "tool_use" in anthropic_response_obj
- and anthropic_response_obj["tool_use"] is not None
- ):
- completion_obj["tool_calls"] = [anthropic_response_obj["tool_use"]]
-
- if (
- "provider_specific_fields" in anthropic_response_obj
- and anthropic_response_obj["provider_specific_fields"] is not None
- ):
- for key, value in anthropic_response_obj[
- "provider_specific_fields"
- ].items():
- setattr(model_response, key, value)
-
- response_obj = cast(Dict[str, Any], anthropic_response_obj)
- elif self.model == "replicate" or self.custom_llm_provider == "replicate":
- response_obj = self.handle_replicate_chunk(chunk)
- completion_obj["content"] = response_obj["text"]
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- elif self.custom_llm_provider and self.custom_llm_provider == "predibase":
- response_obj = self.handle_predibase_chunk(chunk)
- completion_obj["content"] = response_obj["text"]
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- elif (
- self.custom_llm_provider and self.custom_llm_provider == "baseten"
- ): # baseten doesn't provide streaming
- completion_obj["content"] = self.handle_baseten_chunk(chunk)
- elif (
- self.custom_llm_provider and self.custom_llm_provider == "ai21"
- ): # ai21 doesn't provide streaming
- response_obj = self.handle_ai21_chunk(chunk)
- completion_obj["content"] = response_obj["text"]
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- elif self.custom_llm_provider and self.custom_llm_provider == "maritalk":
- response_obj = self.handle_maritalk_chunk(chunk)
- completion_obj["content"] = response_obj["text"]
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- elif self.custom_llm_provider and self.custom_llm_provider == "vllm":
- completion_obj["content"] = chunk[0].outputs[0].text
- elif (
- self.custom_llm_provider and self.custom_llm_provider == "aleph_alpha"
- ): # aleph alpha doesn't provide streaming
- response_obj = self.handle_aleph_alpha_chunk(chunk)
+ if (
+ "provider_specific_fields" in anthropic_response_obj
+ and anthropic_response_obj["provider_specific_fields"] is not None
+ ):
+ for key, value in anthropic_response_obj[
+ "provider_specific_fields"
+ ].items():
+ setattr(model_response, key, value)
+
+ response_obj = cast(dict[str, Any], anthropic_response_obj)
+ elif self.model == "replicate" or self.custom_llm_provider == "replicate":
+ response_obj = self.handle_replicate_chunk(chunk)
+ completion_obj["content"] = response_obj["text"]
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ elif self.custom_llm_provider and self.custom_llm_provider == "predibase":
+ response_obj = self.handle_predibase_chunk(chunk)
+ completion_obj["content"] = response_obj["text"]
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ elif (
+ self.custom_llm_provider and self.custom_llm_provider == "baseten"
+ ): # baseten doesn't provide streaming
+ completion_obj["content"] = self.handle_baseten_chunk(chunk)
+ elif (
+ self.custom_llm_provider and self.custom_llm_provider == "ai21"
+ ): # ai21 doesn't provide streaming
+ response_obj = self.handle_ai21_chunk(chunk)
+ completion_obj["content"] = response_obj["text"]
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ elif self.custom_llm_provider and self.custom_llm_provider == "maritalk":
+ response_obj = self.handle_maritalk_chunk(chunk)
+ completion_obj["content"] = response_obj["text"]
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ elif self.custom_llm_provider and self.custom_llm_provider == "vllm":
+ completion_obj["content"] = chunk[0].outputs[0].text
+ elif (
+ self.custom_llm_provider and self.custom_llm_provider == "aleph_alpha"
+ ): # aleph alpha doesn't provide streaming
+ response_obj = self.handle_aleph_alpha_chunk(chunk)
+ completion_obj["content"] = response_obj["text"]
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ elif self.custom_llm_provider == "nlp_cloud":
+ try:
+ response_obj = self.handle_nlp_cloud_chunk(chunk)
completion_obj["content"] = response_obj["text"]
if response_obj["is_finished"]:
self.received_finish_reason = response_obj["finish_reason"]
- elif self.custom_llm_provider == "nlp_cloud":
- try:
- response_obj = self.handle_nlp_cloud_chunk(chunk)
- completion_obj["content"] = response_obj["text"]
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- except Exception as e:
- if self.received_finish_reason:
- raise e
- else:
- if self.sent_first_chunk is False:
- raise Exception("An unknown error occurred with the stream")
- self.received_finish_reason = "stop"
- elif self.custom_llm_provider == "vertex_ai" and not isinstance(
- chunk, ModelResponseStream
- ):
- import proto # type: ignore
+ except Exception as e:
+ if self.received_finish_reason:
+ raise e
+ else:
+ if self.sent_first_chunk is False:
+ raise Exception("An unknown error occurred with the stream")
+ self.received_finish_reason = "stop"
+ elif self.custom_llm_provider == "vertex_ai" and not isinstance(
+ chunk, ModelResponseStream
+ ):
+ chunk = cast(Any, chunk)
+ import proto # type: ignore
- if hasattr(chunk, "candidates") is True:
+ if hasattr(chunk, "candidates") is True:
+ try:
try:
- try:
- completion_obj["content"] = chunk.text # type: ignore
- except Exception as e:
- original_exception = e
- if "Part has no text." in str(e):
- ## check for function calling
- function_call = (
- chunk.candidates[0].content.parts[0].function_call # type: ignore
- )
+ completion_obj["content"] = chunk.text # type: ignore
+ except Exception as e:
+ original_exception = e
+ if "Part has no text." in str(e):
+ ## check for function calling
+ function_call = (
+ chunk.candidates[0].content.parts[0].function_call # type: ignore
+ )
- args_dict = {}
+ args_dict = {}
- # Check if it's a RepeatedComposite instance
- for key, val in function_call.args.items():
- if isinstance(
- val,
- proto.marshal.collections.repeated.RepeatedComposite, # type: ignore
- ):
- # If so, convert to list
- args_dict[key] = [v for v in val]
- else:
- args_dict[key] = val
-
- try:
- args_str = json.dumps(args_dict)
- except Exception as e:
- raise e
- _delta_obj = litellm.utils.Delta(
- content=None,
- tool_calls=[
- {
- "id": f"call_{str(uuid.uuid4())}",
- "function": {
- "arguments": args_str,
- "name": function_call.name,
- },
- "type": "function",
- }
- ],
- )
- _streaming_response = StreamingChoices(delta=_delta_obj)
- _model_response = ModelResponseStream()
- _model_response.choices = [_streaming_response]
- response_obj = {"original_chunk": _model_response}
- else:
- raise original_exception
- if (
- hasattr(chunk.candidates[0], "finish_reason") # type: ignore
- and chunk.candidates[0].finish_reason.name # type: ignore
- != "FINISH_REASON_UNSPECIFIED"
- ): # every non-final chunk in vertex ai has this
- self.received_finish_reason = map_finish_reason( # type: ignore
- chunk.candidates[0].finish_reason.name
- )
- except Exception:
- if chunk.candidates[0].finish_reason.name == "SAFETY": # type: ignore
- raise Exception(
- f"The response was blocked by VertexAI. {str(chunk)}"
+ # Check if it's a RepeatedComposite instance
+ for key, val in function_call.args.items():
+ if isinstance(
+ val,
+ proto.marshal.collections.repeated.RepeatedComposite, # type: ignore
+ ):
+ # If so, convert to list
+ args_dict[key] = [v for v in val]
+ else:
+ args_dict[key] = val
+
+ try:
+ args_str = json.dumps(args_dict)
+ except Exception as e:
+ raise e
+ _delta_obj = litellm.utils.Delta(
+ content=None,
+ tool_calls=[
+ {
+ "id": f"call_{str(uuid.uuid4())}",
+ "function": {
+ "arguments": args_str,
+ "name": function_call.name,
+ },
+ "type": "function",
+ }
+ ],
)
+ _streaming_response = StreamingChoices(delta=_delta_obj)
+ _model_response = ModelResponseStream()
+ _model_response.choices = [_streaming_response]
+ response_obj = {"original_chunk": _model_response}
+ else:
+ raise original_exception
+ if (
+ hasattr(chunk.candidates[0], "finish_reason") # type: ignore
+ and chunk.candidates[0].finish_reason.name # type: ignore
+ != "FINISH_REASON_UNSPECIFIED"
+ ): # every non-final chunk in vertex ai has this
+ self.received_finish_reason = map_finish_reason( # type: ignore
+ chunk.candidates[0].finish_reason.name
+ )
+ except Exception:
+ if chunk.candidates[0].finish_reason.name == "SAFETY": # type: ignore
+ raise Exception(
+ f"The response was blocked by VertexAI. {str(chunk)}"
+ )
+ else:
+ completion_obj["content"] = str(chunk)
+ elif self.custom_llm_provider == "petals":
+ if self.completion_stream is None or len(self.completion_stream) == 0:
+ if self.received_finish_reason is not None:
+ raise StopIteration
else:
- completion_obj["content"] = str(chunk)
- elif self.custom_llm_provider == "petals":
- if self.completion_stream is None or len(self.completion_stream) == 0:
- if self.received_finish_reason is not None:
- raise StopIteration
- else:
- self.received_finish_reason = "stop"
- chunk_size = 30
- new_chunk = self.completion_stream[:chunk_size] # type: ignore[index]
- completion_obj["content"] = new_chunk
- self.completion_stream = self.completion_stream[chunk_size:] # type: ignore[index]
- elif self.custom_llm_provider == "palm":
- # fake streaming
- response_obj = {}
- if self.completion_stream is None or len(self.completion_stream) == 0:
- if self.received_finish_reason is not None:
- raise StopIteration
- else:
- self.received_finish_reason = "stop"
- chunk_size = 30
- new_chunk = self.completion_stream[:chunk_size] # type: ignore[index]
- completion_obj["content"] = new_chunk
- self.completion_stream = self.completion_stream[chunk_size:] # type: ignore[index]
- elif self.custom_llm_provider == "triton":
- response_obj = self.handle_triton_stream(chunk)
- completion_obj["content"] = response_obj["text"]
- print_verbose(f"completion obj content: {completion_obj['content']}")
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- elif self.custom_llm_provider == "text-completion-openai":
- response_obj = self.handle_openai_text_completion_chunk(chunk)
- completion_obj["content"] = response_obj["text"]
- print_verbose(f"completion obj content: {completion_obj['content']}")
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- if response_obj["usage"] is not None:
+ self.received_finish_reason = "stop"
+ chunk_size = 30
+ stream = cast(Any, self.completion_stream)
+ new_chunk = stream[:chunk_size]
+ completion_obj["content"] = new_chunk
+ self.completion_stream = stream[chunk_size:]
+ elif self.custom_llm_provider == "palm":
+ # fake streaming
+ response_obj = {}
+ if self.completion_stream is None or len(self.completion_stream) == 0:
+ if self.received_finish_reason is not None:
+ raise StopIteration
+ else:
+ self.received_finish_reason = "stop"
+ chunk_size = 30
+ stream = cast(Any, self.completion_stream)
+ new_chunk = stream[:chunk_size]
+ completion_obj["content"] = new_chunk
+ self.completion_stream = stream[chunk_size:]
+ elif self.custom_llm_provider == "triton":
+ response_obj = self.handle_triton_stream(chunk)
+ completion_obj["content"] = response_obj["text"]
+ print_verbose(f"completion obj content: {completion_obj['content']}")
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ elif self.custom_llm_provider == "text-completion-openai":
+ response_obj = self.handle_openai_text_completion_chunk(chunk)
+ completion_obj["content"] = response_obj["text"]
+ print_verbose(f"completion obj content: {completion_obj['content']}")
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ if response_obj["usage"] is not None:
+ setattr(
+ model_response,
+ "usage",
+ litellm.Usage(
+ prompt_tokens=response_obj["usage"].prompt_tokens,
+ completion_tokens=response_obj["usage"].completion_tokens,
+ total_tokens=response_obj["usage"].total_tokens,
+ ),
+ )
+ elif self.custom_llm_provider == "text-completion-codestral":
+ if not isinstance(chunk, str):
+ raise ValueError(f"chunk is not a string: {chunk}")
+ response_obj = cast(
+ dict[str, Any],
+ litellm.CodestralTextCompletionConfig()._chunk_parser(chunk),
+ )
+ completion_obj["content"] = response_obj["text"]
+ print_verbose(f"completion obj content: {completion_obj['content']}")
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ if "usage" in response_obj is not None:
+ setattr(
+ model_response,
+ "usage",
+ litellm.Usage(
+ prompt_tokens=response_obj["usage"].prompt_tokens,
+ completion_tokens=response_obj["usage"].completion_tokens,
+ total_tokens=response_obj["usage"].total_tokens,
+ ),
+ )
+ elif self.custom_llm_provider == "azure_text":
+ response_obj = self.handle_azure_text_completion_chunk(chunk)
+ completion_obj["content"] = response_obj["text"]
+ print_verbose(f"completion obj content: {completion_obj['content']}")
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ elif self.custom_llm_provider == "cached_response":
+ chunk = cast(ModelResponseStream, chunk)
+ response_obj = {
+ "text": chunk.choices[0].delta.content,
+ "is_finished": True,
+ "finish_reason": chunk.choices[0].finish_reason,
+ "original_chunk": chunk,
+ "tool_calls": (
+ chunk.choices[0].delta.tool_calls
+ if hasattr(chunk.choices[0].delta, "tool_calls")
+ else None
+ ),
+ }
+
+ completion_obj["content"] = response_obj["text"]
+ if response_obj["tool_calls"] is not None:
+ completion_obj["tool_calls"] = response_obj["tool_calls"]
+ print_verbose(f"completion obj content: {completion_obj['content']}")
+ if hasattr(chunk, "id"):
+ model_response.id = chunk.id
+ self.response_id = chunk.id
+ if hasattr(chunk, "system_fingerprint"):
+ self.system_fingerprint = chunk.system_fingerprint
+ if response_obj["is_finished"]:
+ self.received_finish_reason = response_obj["finish_reason"]
+ else: # openai / azure chat model
+ 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 chunk
+ self.model = getattr(chunk, "model", self.model)
+ response_obj = self.handle_openai_chat_completion_chunk(chunk)
+ if response_obj is None:
+ return _ProviderChunkEarlyReturn(None)
+ completion_obj["content"] = response_obj["text"]
+ self.intermittent_finish_reason = response_obj.get("finish_reason", None)
+ if response_obj["is_finished"]:
+ if response_obj["finish_reason"] == "error":
+ raise Exception(
+ "{} raised a streaming error - finish_reason: error, no content string given. Received Chunk={}".format(
+ self.custom_llm_provider, response_obj
+ )
+ )
+ self.received_finish_reason = response_obj["finish_reason"]
+ if response_obj.get("original_chunk", None) is not None:
+ if hasattr(response_obj["original_chunk"], "id"):
+ model_response = self.set_model_id(
+ response_obj["original_chunk"].id, model_response
+ )
+ if hasattr(response_obj["original_chunk"], "system_fingerprint"):
+ model_response.system_fingerprint = response_obj[
+ "original_chunk"
+ ].system_fingerprint
+ self.system_fingerprint = response_obj[
+ "original_chunk"
+ ].system_fingerprint
+ if response_obj["logprobs"] is not None:
+ model_response.choices[0].logprobs = response_obj["logprobs"]
+
+ if response_obj["usage"] is not None:
+ if isinstance(response_obj["usage"], dict):
setattr(
model_response,
"usage",
litellm.Usage(
- prompt_tokens=response_obj["usage"].prompt_tokens,
- completion_tokens=response_obj["usage"].completion_tokens,
- total_tokens=response_obj["usage"].total_tokens,
+ prompt_tokens=response_obj["usage"].get(
+ "prompt_tokens", None
+ )
+ or None,
+ completion_tokens=response_obj["usage"].get(
+ "completion_tokens", None
+ )
+ or None,
+ total_tokens=response_obj["usage"].get("total_tokens", None)
+ or None,
),
)
- elif self.custom_llm_provider == "text-completion-codestral":
- if not isinstance(chunk, str):
- raise ValueError(f"chunk is not a string: {chunk}")
- response_obj = cast(
- Dict[str, Any],
- litellm.CodestralTextCompletionConfig()._chunk_parser(chunk),
- )
- completion_obj["content"] = response_obj["text"]
- print_verbose(f"completion obj content: {completion_obj['content']}")
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- if "usage" in response_obj is not None:
+ elif isinstance(response_obj["usage"], Usage):
setattr(
model_response,
"usage",
- litellm.Usage(
- prompt_tokens=response_obj["usage"].prompt_tokens,
- completion_tokens=response_obj["usage"].completion_tokens,
- total_tokens=response_obj["usage"].total_tokens,
- ),
+ response_obj["usage"],
)
- elif self.custom_llm_provider == "azure_text":
- response_obj = self.handle_azure_text_completion_chunk(chunk)
- completion_obj["content"] = response_obj["text"]
- print_verbose(f"completion obj content: {completion_obj['content']}")
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- elif self.custom_llm_provider == "cached_response":
- chunk = cast(ModelResponseStream, chunk)
- response_obj = {
- "text": chunk.choices[0].delta.content,
- "is_finished": True,
- "finish_reason": chunk.choices[0].finish_reason,
- "original_chunk": chunk,
- "tool_calls": (
- chunk.choices[0].delta.tool_calls
- if hasattr(chunk.choices[0].delta, "tool_calls")
- else None
- ),
- }
+ elif isinstance(response_obj["usage"], BaseModel):
+ setattr(
+ model_response,
+ "usage",
+ litellm.Usage(**response_obj["usage"].model_dump()),
+ )
+ return _ProviderChunkParsed(response_obj)
- completion_obj["content"] = response_obj["text"]
- if response_obj["tool_calls"] is not None:
- completion_obj["tool_calls"] = response_obj["tool_calls"]
- print_verbose(f"completion obj content: {completion_obj['content']}")
- if hasattr(chunk, "id"):
- model_response.id = chunk.id
- self.response_id = chunk.id
- if hasattr(chunk, "system_fingerprint"):
- self.system_fingerprint = chunk.system_fingerprint
- if response_obj["is_finished"]:
- self.received_finish_reason = response_obj["finish_reason"]
- else: # openai / azure chat model
- 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 chunk
- self.model = getattr(chunk, "model", self.model)
- response_obj = self.handle_openai_chat_completion_chunk(chunk)
- if response_obj is None:
- return
- completion_obj["content"] = response_obj["text"]
- self.intermittent_finish_reason = response_obj.get(
- "finish_reason", None
- )
- if response_obj["is_finished"]:
- if response_obj["finish_reason"] == "error":
- raise Exception(
- "{} raised a streaming error - finish_reason: error, no content string given. Received Chunk={}".format(
- self.custom_llm_provider, response_obj
- )
- )
- self.received_finish_reason = response_obj["finish_reason"]
- if response_obj.get("original_chunk", None) is not None:
- if hasattr(response_obj["original_chunk"], "id"):
- model_response = self.set_model_id(
- response_obj["original_chunk"].id, model_response
- )
- if hasattr(response_obj["original_chunk"], "system_fingerprint"):
- model_response.system_fingerprint = response_obj[
- "original_chunk"
- ].system_fingerprint
- self.system_fingerprint = response_obj[
- "original_chunk"
- ].system_fingerprint
- if response_obj["logprobs"] is not None:
- model_response.choices[0].logprobs = response_obj["logprobs"]
-
- if response_obj["usage"] is not None:
- if isinstance(response_obj["usage"], dict):
- setattr(
- model_response,
- "usage",
- litellm.Usage(
- prompt_tokens=response_obj["usage"].get(
- "prompt_tokens", None
- )
- or None,
- completion_tokens=response_obj["usage"].get(
- "completion_tokens", None
- )
- or None,
- total_tokens=response_obj["usage"].get(
- "total_tokens", None
- )
- or None,
- ),
- )
- elif isinstance(response_obj["usage"], Usage):
- setattr(
- model_response,
- "usage",
- response_obj["usage"],
- )
- elif isinstance(response_obj["usage"], BaseModel):
- setattr(
- model_response,
- "usage",
- litellm.Usage(**response_obj["usage"].model_dump()),
- )
+ def chunk_creator(self, chunk: Any): # type: ignore
+ if hasattr(chunk, "id"):
+ self.response_id = chunk.id
+ model_response = self.model_response_creator()
+ response_obj: dict[str, Any] = {}
+ try:
+ # return this for all models
+ completion_obj: dict[str, Any] = {"content": ""}
+ dispatch_result = self._dispatch_provider_chunk(
+ chunk=chunk,
+ model_response=model_response,
+ completion_obj=completion_obj,
+ )
+ if isinstance(dispatch_result, _ProviderChunkEarlyReturn):
+ return dispatch_result.value
+ response_obj = dispatch_result.response_obj
model_response.model = self.model
## FUNCTION CALL PARSING
diff --git a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
index e95cd656cc4..d7c54fe6707 100644
--- a/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
+++ b/tests/test_litellm/litellm_core_utils/test_streaming_handler.py
@@ -18,6 +18,8 @@ from litellm.litellm_core_utils.litellm_logging import Logging
from litellm.litellm_core_utils.streaming_handler import (
AUDIO_ATTRIBUTE,
CustomStreamWrapper,
+ _ProviderChunkEarlyReturn,
+ _ProviderChunkParsed,
)
from litellm.types.utils import (
CompletionTokensDetailsWrapper,
@@ -1801,6 +1803,344 @@ def test_usage_only_chunk_not_dropped_when_finish_reason_already_set(
assert result.usage is not None
+def _run_dispatch(wrapper: CustomStreamWrapper, chunk):
+ model_response = wrapper.model_response_creator()
+ completion_obj = {"content": ""}
+ result = wrapper._dispatch_provider_chunk(
+ chunk=chunk,
+ model_response=model_response,
+ completion_obj=completion_obj,
+ )
+ return result, model_response, completion_obj
+
+
+def test_dispatch_vllm_extracts_output_text(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """vllm chunks expose text at chunk[0].outputs[0].text; the dispatch must
+ surface that as the content and report a parsed result."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "vllm"
+
+ class _Output:
+ text = "hello from vllm"
+
+ class _VLLMChunk:
+ outputs = [_Output()]
+
+ result, _, completion_obj = _run_dispatch(
+ initialized_custom_stream_wrapper, [_VLLMChunk()]
+ )
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "hello from vllm"
+
+
+def test_dispatch_petals_slices_completion_stream(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """petals fakes streaming by slicing 30 chars off the buffered completion
+ stream each call, leaving the remainder for the next chunk."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "petals"
+ initialized_custom_stream_wrapper.completion_stream = "A" * 50
+
+ result, _, completion_obj = _run_dispatch(
+ initialized_custom_stream_wrapper, chunk=None
+ )
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "A" * 30
+ assert initialized_custom_stream_wrapper.completion_stream == "A" * 20
+ assert initialized_custom_stream_wrapper.received_finish_reason is None
+
+
+def test_dispatch_petals_empty_stream_sets_stop(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """An exhausted petals stream marks the turn finished with a stop reason."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "petals"
+ initialized_custom_stream_wrapper.completion_stream = ""
+
+ result, _, completion_obj = _run_dispatch(
+ initialized_custom_stream_wrapper, chunk=None
+ )
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == ""
+ assert initialized_custom_stream_wrapper.received_finish_reason == "stop"
+
+
+def test_dispatch_petals_empty_stream_after_finish_raises(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """Once petals has already finished, an empty stream signals end-of-iteration."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "petals"
+ initialized_custom_stream_wrapper.completion_stream = ""
+ initialized_custom_stream_wrapper.received_finish_reason = "stop"
+
+ with pytest.raises(StopIteration):
+ _run_dispatch(initialized_custom_stream_wrapper, chunk=None)
+
+
+def test_dispatch_palm_slices_completion_stream(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """palm uses the same fake-streaming slice strategy as petals."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "palm"
+ initialized_custom_stream_wrapper.completion_stream = "B" * 40
+
+ result, _, completion_obj = _run_dispatch(
+ initialized_custom_stream_wrapper, chunk=None
+ )
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "B" * 30
+ assert initialized_custom_stream_wrapper.completion_stream == "B" * 10
+
+
+def test_dispatch_cached_response_extracts_delta(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """cached_response replays a stored ModelResponseStream; the dispatch lifts
+ its delta content, finish_reason and id back onto the live response."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "cached_response"
+ chunk = ModelResponseStream(
+ id="chatcmpl-cache-1",
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(content="cached text"),
+ finish_reason="stop",
+ )
+ ],
+ )
+
+ result, model_response, completion_obj = _run_dispatch(
+ initialized_custom_stream_wrapper, chunk
+ )
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "cached text"
+ assert initialized_custom_stream_wrapper.received_finish_reason == "stop"
+ assert model_response.id == "chatcmpl-cache-1"
+ assert initialized_custom_stream_wrapper.response_id == "chatcmpl-cache-1"
+
+
+def test_dispatch_vertex_ai_legacy_text_and_finish_reason(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """Legacy vertex_ai chunks (non-ModelResponseStream) expose .text and a
+ candidate finish_reason enum that must be normalised to an OpenAI reason."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "vertex_ai"
+
+ class _FinishReason:
+ name = "STOP"
+
+ class _Candidate:
+ finish_reason = _FinishReason()
+
+ class _VertexChunk:
+ candidates = [_Candidate()]
+ text = "vertex content"
+
+ result, _, completion_obj = _run_dispatch(
+ initialized_custom_stream_wrapper, _VertexChunk()
+ )
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "vertex content"
+ assert initialized_custom_stream_wrapper.received_finish_reason == "stop"
+
+
+def test_dispatch_vertex_ai_legacy_without_candidates_stringifies_chunk(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """A legacy vertex_ai chunk with no candidates falls back to str(chunk)."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "vertex_ai"
+
+ class _RawChunk:
+ def __str__(self) -> str:
+ return "raw vertex blob"
+
+ result, _, completion_obj = _run_dispatch(
+ initialized_custom_stream_wrapper, _RawChunk()
+ )
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "raw vertex blob"
+
+
+def test_dispatch_vertex_ai_legacy_function_call(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """A legacy vertex_ai chunk whose part has no text but carries a
+ function_call is converted into an OpenAI tool-call delta."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "vertex_ai"
+
+ class _FunctionCall:
+ name = "get_weather"
+ args = {"location": "SF"}
+
+ class _Part:
+ function_call = _FunctionCall()
+
+ class _Content:
+ parts = [_Part()]
+
+ class _FinishReason:
+ name = "STOP"
+
+ class _Candidate:
+ content = _Content()
+ finish_reason = _FinishReason()
+
+ class _VertexFunctionChunk:
+ candidates = [_Candidate()]
+
+ @property
+ def text(self):
+ raise RuntimeError("Part has no text.")
+
+ result, _, _ = _run_dispatch(
+ initialized_custom_stream_wrapper, _VertexFunctionChunk()
+ )
+
+ assert isinstance(result, _ProviderChunkParsed)
+ tool_calls = result.response_obj["original_chunk"].choices[0].delta.tool_calls
+ assert tool_calls[0].function.name == "get_weather"
+ assert json.loads(tool_calls[0].function.arguments) == {"location": "SF"}
+ assert initialized_custom_stream_wrapper.received_finish_reason == "stop"
+
+
+def test_dispatch_custom_provider_returns_chunk_early(
+ monkeypatch: pytest.MonkeyPatch,
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """A registered custom provider passes its already-OpenAI-shaped chunk
+ straight through as an early return rather than re-parsing it."""
+ monkeypatch.setattr(litellm, "_custom_providers", ["my-custom-llm"])
+ initialized_custom_stream_wrapper.custom_llm_provider = "my-custom-llm"
+ chunk = ModelResponseStream(
+ choices=[
+ StreamingChoices(index=0, delta=Delta(content="hi"), finish_reason=None)
+ ]
+ )
+
+ result, _, _ = _run_dispatch(initialized_custom_stream_wrapper, chunk)
+
+ assert isinstance(result, _ProviderChunkEarlyReturn)
+ assert result.value is chunk
+
+
+def test_dispatch_custom_provider_finish_only_returns_none_early(
+ monkeypatch: pytest.MonkeyPatch,
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """A custom-provider chunk that carries only a finish_reason (no content)
+ records the reason and returns None so no empty delta is emitted."""
+ monkeypatch.setattr(litellm, "_custom_providers", ["my-custom-llm"])
+ initialized_custom_stream_wrapper.custom_llm_provider = "my-custom-llm"
+ chunk = ModelResponseStream(
+ choices=[
+ StreamingChoices(index=0, delta=Delta(content=None), finish_reason="stop")
+ ]
+ )
+
+ result, _, _ = _run_dispatch(initialized_custom_stream_wrapper, chunk)
+
+ assert isinstance(result, _ProviderChunkEarlyReturn)
+ assert result.value is None
+ assert initialized_custom_stream_wrapper.received_finish_reason == "stop"
+
+
+def test_dispatch_text_completion_codestral_parses_chunk(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """text-completion-codestral streams raw SSE JSON strings that the dispatch
+ routes through CodestralTextCompletionConfig to extract content/finish."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "text-completion-codestral"
+ chunk = json.dumps(
+ {"choices": [{"delta": {"content": "codestral text"}, "finish_reason": "stop"}]}
+ )
+
+ result, _, completion_obj = _run_dispatch(initialized_custom_stream_wrapper, chunk)
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "codestral text"
+ assert initialized_custom_stream_wrapper.received_finish_reason == "stop"
+
+
+def test_dispatch_text_completion_codestral_requires_string(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """The codestral branch only knows how to parse raw strings; anything else
+ is a programming error and must surface loudly."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "text-completion-codestral"
+
+ with pytest.raises(ValueError):
+ _run_dispatch(initialized_custom_stream_wrapper, {"not": "a string"})
+
+
+def test_dispatch_triton_stream(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """triton stream chunks arrive as dicts keyed by text_output/stop_reason."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "triton"
+ chunk = {"text_output": "triton text", "is_finished": True, "stop_reason": "stop"}
+
+ result, _, completion_obj = _run_dispatch(initialized_custom_stream_wrapper, chunk)
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "triton text"
+ assert initialized_custom_stream_wrapper.received_finish_reason == "stop"
+
+
+def test_dispatch_ai21_decodes_completion(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """ai21 does fake streaming over a single byte-encoded JSON completion."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "ai21"
+ chunk = json.dumps({"completions": [{"data": {"text": "ai21 text"}}]}).encode(
+ "utf-8"
+ )
+
+ result, _, completion_obj = _run_dispatch(initialized_custom_stream_wrapper, chunk)
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "ai21 text"
+ assert initialized_custom_stream_wrapper.received_finish_reason == "stop"
+
+
+def test_dispatch_text_completion_openai_with_usage(
+ initialized_custom_stream_wrapper: CustomStreamWrapper,
+):
+ """text-completion-openai chunks expose choices[].text and an optional usage
+ block that the dispatch lifts onto the model response."""
+ initialized_custom_stream_wrapper.custom_llm_provider = "text-completion-openai"
+
+ class _Choice:
+ text = "oai text"
+ finish_reason = "stop"
+
+ class _Usage:
+ prompt_tokens = 5
+ completion_tokens = 3
+ total_tokens = 8
+
+ class _TextChunk:
+ choices = [_Choice()]
+ usage = _Usage()
+
+ result, model_response, completion_obj = _run_dispatch(
+ initialized_custom_stream_wrapper, _TextChunk()
+ )
+
+ assert isinstance(result, _ProviderChunkParsed)
+ assert completion_obj["content"] == "oai text"
+ assert initialized_custom_stream_wrapper.received_finish_reason == "stop"
+ assert model_response.usage.prompt_tokens == 5
+ assert model_response.usage.total_tokens == 8
+
+
@pytest.mark.asyncio
async def test_custom_stream_wrapper_anext_does_not_block_event_loop_for_sync_iterators(
logging_obj: Logging,