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]

VertexAILlama3StreamingHandler

Ishaan Jafferbd766706c5a6
diff --git a/.circleci/config.yml b/.circleci/config.yml
index e2f1f27b6dd..c5260165877 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -1670,8 +1670,9 @@ jobs:
name: Run proxy tests
command: |
prisma generate
- python -m pytest tests/test_litellm/proxy --cov=litellm --cov-report=xml --junitxml=test-results/junit-proxy.xml --durations=10 -n 16 --maxfail=5 --timeout=300 -vv --log-cli-level=WARNING
- no_output_timeout: 120m
+ export PYTHONUNBUFFERED=1
+ python -m pytest tests/test_litellm/proxy --cov=litellm --cov-report=xml --junitxml=test-results/junit-proxy.xml --durations=10 -n 8 --maxfail=5 --timeout=60 -vv --log-cli-level=WARNING -r A
+ no_output_timeout: 60m
- run:
name: Rename the coverage files
command: |
diff --git a/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py b/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py
index a70e16000b6..51310e4fa85 100644
--- a/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py
+++ b/litellm/llms/vertex_ai/vertex_ai_partner_models/llama3/transformation.py
@@ -9,7 +9,13 @@ from litellm.llms.openai.chat.gpt_transformation import (
OpenAIGPTConfig,
)
from litellm.types.llms.openai import AllMessageValues, OpenAIChatCompletionResponse
-from litellm.types.utils import ModelResponse, ModelResponseStream, Usage
+from litellm.types.utils import (
+ Delta,
+ ModelResponse,
+ ModelResponseStream,
+ StreamingChoices,
+ Usage,
+)
from ...common_utils import VertexAIError
@@ -145,17 +151,74 @@ class VertexAILlama3StreamingHandler(OpenAIChatCompletionStreamingHandler):
"""
Vertex AI Llama models may not include role in streaming chunk deltas.
This handler ensures the first chunk always has role="assistant".
+
+ When Vertex AI returns a single chunk with both role and finish_reason (empty response),
+ this handler splits it into two chunks:
+ 1. First chunk: role="assistant", content="", finish_reason=None
+ 2. Second chunk: role=None, content=None, finish_reason="stop"
+
+ This matches OpenAI's streaming format where the first chunk has role and
+ the final chunk has finish_reason but no role.
"""
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.sent_role = False
+ self._pending_chunk: Optional[ModelResponseStream] = None
def chunk_parser(self, chunk: dict) -> ModelResponseStream:
result = super().chunk_parser(chunk)
if not self.sent_role and result.choices:
delta = result.choices[0].delta
- if delta.role is None:
+ finish_reason = result.choices[0].finish_reason
+
+ # If this is both the first chunk AND the final chunk (has finish_reason),
+ # we need to split it into two chunks to match OpenAI format
+ if finish_reason is not None:
+ # Create a pending final chunk with finish_reason but no role
+ self._pending_chunk = ModelResponseStream(
+ id=result.id,
+ object="chat.completion.chunk",
+ created=result.created,
+ model=result.model,
+ choices=[
+ StreamingChoices(
+ index=0,
+ delta=Delta(content=None, role=None),
+ finish_reason=finish_reason,
+ )
+ ],
+ )
+ # Modify current chunk to be the first chunk with role but no finish_reason
+ result.choices[0].finish_reason = None
+ delta.role = "assistant"
+ # Ensure content is empty string for first chunk, not None
+ if delta.content is None:
+ delta.content = ""
+ # Prevent downstream stream wrapper from dropping this chunk
+ # (it drops empty-content chunks unless special fields are present)
+ if delta.provider_specific_fields is None:
+ delta.provider_specific_fields = {}
+ elif delta.role is None:
delta.role = "assistant"
+ # If the first chunk has empty content, ensure it's still emitted
+ if (delta.content == "" or delta.content is None) and delta.provider_specific_fields is None:
+ delta.provider_specific_fields = {}
self.sent_role = True
return result
+
+ def __next__(self):
+ # First return any pending chunk from a previous split
+ if self._pending_chunk is not None:
+ chunk = self._pending_chunk
+ self._pending_chunk = None
+ return chunk
+ return super().__next__()
+
+ async def __anext__(self):
+ # First return any pending chunk from a previous split
+ if self._pending_chunk is not None:
+ chunk = self._pending_chunk
+ self._pending_chunk = None
+ return chunk
+ return await super().__anext__()