-
-
Notifications
You must be signed in to change notification settings - Fork 11.6k
[internal copy of #28007] Fix/gcp model garden streaming #28363
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mateo-berri
merged 4 commits into
litellm_internal_staging
from
litellm_fix/gcp-model-garden-streaming
Jun 10, 2026
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2e84ba6
fix(vertex): stream Model Garden Gemma/Qwen responses correctly throu…
stvnksslr 7a09a94
test(vertex): cover _CombinedChunkSplitter defensive branches
stvnksslr 0dd7a87
test(databricks): rename test file to avoid duplicate basename collision
stvnksslr 0d562cc
fix(databricks,anthropic): defensive token defaults; document single-…
claude File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
150 changes: 150 additions & 0 deletions
150
...ms/anthropic/experimental_pass_through/adapters/test_streaming_iterator_combined_chunk.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,150 @@ | ||
| """ | ||
| Regression tests for fake-streamed providers routed through `/v1/messages`. | ||
|
|
||
| A fake-streaming provider (e.g. Vertex AI Gemma `:predict`) collapses its whole | ||
| response into a single `MockResponseIterator` chunk that carries content text AND a | ||
| `finish_reason` together. `AnthropicStreamWrapper` previously dropped all content in | ||
| this case — `translate_streaming_openai_response_to_anthropic` sees the finish_reason | ||
| and emits only a `message_delta`. `_CombinedChunkSplitter` splits such chunks so the | ||
| content survives. | ||
| """ | ||
|
|
||
| import asyncio | ||
| import json | ||
| from types import SimpleNamespace | ||
|
|
||
| from litellm.llms.anthropic.experimental_pass_through.adapters.streaming_iterator import ( | ||
| AnthropicStreamWrapper, | ||
| _CombinedChunkSplitter, | ||
| ) | ||
| from litellm.llms.base_llm.base_model_iterator import MockResponseIterator | ||
| from litellm.types.utils import ( | ||
| Choices, | ||
| Delta, | ||
| Message, | ||
| ModelResponse, | ||
| ModelResponseStream, | ||
| StreamingChoices, | ||
| Usage, | ||
| ) | ||
|
|
||
|
|
||
| def _build_fake_stream( | ||
| content: str, finish_reason: str = "stop" | ||
| ) -> MockResponseIterator: | ||
| """Mimic a Vertex Gemma `:predict` fake stream: one collapsed chunk.""" | ||
| model_response = ModelResponse() | ||
| model_response.choices = [ | ||
| Choices( | ||
| index=0, | ||
| message=Message(role="assistant", content=content), | ||
| finish_reason=finish_reason, | ||
| ) | ||
| ] | ||
| model_response.usage = Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15) | ||
| model_response.model = "gemma4" | ||
| return MockResponseIterator(model_response=model_response) | ||
|
|
||
|
|
||
| def _collect_async(wrapper: AnthropicStreamWrapper) -> str: | ||
| async def _run() -> str: | ||
| out = [] | ||
| async for raw in wrapper.async_anthropic_sse_wrapper(): | ||
| out.append(raw.decode() if isinstance(raw, bytes) else raw) | ||
| return "".join(out) | ||
|
|
||
| return asyncio.run(_run()) | ||
|
|
||
|
|
||
| def test_fake_stream_content_reaches_anthropic_sse(): | ||
| """Content from a collapsed fake-stream chunk must be emitted as a delta.""" | ||
| wrapper = AnthropicStreamWrapper( | ||
| completion_stream=_build_fake_stream("Hello, the answer is 2."), | ||
| model="gemma4", | ||
| ) | ||
| sse = _collect_async(wrapper) | ||
|
|
||
| assert "content_block_delta" in sse | ||
| assert "Hello, the answer is 2." in sse | ||
| assert "message_delta" in sse | ||
| assert "message_stop" in sse | ||
|
|
||
|
|
||
| def test_fake_stream_usage_preserved(): | ||
| """The finish chunk keeps usage so output_tokens is non-zero.""" | ||
| wrapper = AnthropicStreamWrapper( | ||
| completion_stream=_build_fake_stream("Two."), | ||
| model="gemma4", | ||
| ) | ||
| sse = _collect_async(wrapper) | ||
|
|
||
| message_delta = next( | ||
| json.loads(line[len("data: ") :]) | ||
| for block in sse.split("\n\n") | ||
| for line in block.splitlines() | ||
| if line.startswith("data: ") and '"message_delta"' in line | ||
| ) | ||
| assert message_delta["usage"]["output_tokens"] == 5 | ||
| assert message_delta["usage"]["input_tokens"] == 10 | ||
|
|
||
|
|
||
| def test_splitter_passes_through_non_combined_chunks(): | ||
| """A chunk with content but no finish_reason is not split.""" | ||
| chunk = ModelResponseStream( | ||
| choices=[ | ||
| StreamingChoices( | ||
| index=0, delta=Delta(content="partial"), finish_reason=None | ||
| ) | ||
| ] | ||
| ) | ||
| chunks = list(_CombinedChunkSplitter(iter([chunk]))) | ||
| assert len(chunks) == 1 | ||
| assert chunks[0].choices[0].delta.content == "partial" | ||
|
|
||
|
|
||
| def test_splitter_splits_combined_chunk_into_content_then_finish(): | ||
| """A chunk with both content and finish_reason becomes two chunks.""" | ||
| chunk = ModelResponseStream( | ||
| choices=[ | ||
| StreamingChoices(index=0, delta=Delta(content="done"), finish_reason="stop") | ||
| ] | ||
| ) | ||
| content_chunk, finish_chunk = list(_CombinedChunkSplitter(iter([chunk]))) | ||
|
|
||
| assert content_chunk.choices[0].delta.content == "done" | ||
| assert content_chunk.choices[0].finish_reason is None | ||
|
|
||
| assert finish_chunk.choices[0].finish_reason == "stop" | ||
| assert finish_chunk.choices[0].delta.content is None | ||
|
|
||
|
|
||
| def test_is_combined_false_when_choices_empty(): | ||
| """A metadata-only chunk with no choices is never treated as combined.""" | ||
| assert _CombinedChunkSplitter._is_combined(SimpleNamespace(choices=[])) is False | ||
|
|
||
|
|
||
| def test_is_combined_false_when_delta_missing(): | ||
| """A finish chunk whose choice has no delta is not combined.""" | ||
| chunk = SimpleNamespace(choices=[SimpleNamespace(finish_reason="stop", delta=None)]) | ||
| assert _CombinedChunkSplitter._is_combined(chunk) is False | ||
|
|
||
|
|
||
| def test_split_clears_reasoning_and_thinking_on_finish_chunk(): | ||
| """When the combined delta carries reasoning/thinking, only the content | ||
| chunk keeps them — the finish chunk is cleared.""" | ||
| delta = SimpleNamespace( | ||
| content="hi", | ||
| tool_calls=None, | ||
| reasoning_content="some reasoning", | ||
| thinking_blocks=[{"type": "thinking"}], | ||
| ) | ||
| chunk = SimpleNamespace( | ||
| choices=[SimpleNamespace(finish_reason="stop", delta=delta)] | ||
| ) | ||
|
|
||
| content_chunk, finish_chunk = _CombinedChunkSplitter._split(chunk) | ||
|
|
||
| assert content_chunk.choices[0].delta.reasoning_content == "some reasoning" | ||
| assert content_chunk.choices[0].delta.thinking_blocks == [{"type": "thinking"}] | ||
| assert finish_chunk.choices[0].delta.reasoning_content is None | ||
| assert finish_chunk.choices[0].delta.thinking_blocks is None |
64 changes: 64 additions & 0 deletions
64
tests/test_litellm/llms/databricks/test_databricks_streaming_utils.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| """ | ||
| Regression test for the databricks streaming chunk parser. | ||
|
|
||
| OpenAI-compatible servers (e.g. Vertex AI Model Garden vLLM endpoints) send a final | ||
| usage-only chunk with an empty `choices` list when `stream_options.include_usage` is | ||
| set. `chunk_parser` previously did `choices[0]` unconditionally, raising | ||
| `IndexError` -> `MidStreamFallbackError` and crashing the stream. | ||
| """ | ||
|
|
||
| from litellm.llms.databricks.streaming_utils import ModelResponseIterator | ||
|
|
||
|
|
||
| def test_chunk_parser_handles_empty_choices_usage_chunk(): | ||
| """A usage-only final chunk (empty choices) must not raise IndexError.""" | ||
| iterator = ModelResponseIterator(streaming_response=None, sync_stream=True) | ||
| usage_only_chunk = { | ||
| "id": "chatcmpl-x", | ||
| "object": "chat.completion.chunk", | ||
| "created": 1, | ||
| "model": "m", | ||
| "choices": [], | ||
| "usage": {"prompt_tokens": 20, "completion_tokens": 8, "total_tokens": 28}, | ||
| } | ||
|
|
||
| result = iterator.chunk_parser(chunk=usage_only_chunk) | ||
|
|
||
| assert result["text"] == "" | ||
| assert result["is_finished"] is False | ||
| assert result["usage"] is not None | ||
| assert result["usage"]["prompt_tokens"] == 20 | ||
| assert result["usage"]["completion_tokens"] == 8 | ||
|
|
||
|
|
||
| def test_chunk_parser_empty_choices_without_usage(): | ||
| """An empty-choices chunk with no usage block returns usage=None, no error.""" | ||
| iterator = ModelResponseIterator(streaming_response=None, sync_stream=True) | ||
| chunk = { | ||
| "id": "chatcmpl-x", | ||
| "object": "chat.completion.chunk", | ||
| "created": 1, | ||
| "model": "m", | ||
| "choices": [], | ||
| } | ||
|
|
||
| result = iterator.chunk_parser(chunk=chunk) | ||
|
|
||
| assert result["text"] == "" | ||
| assert result["usage"] is None | ||
|
|
||
|
|
||
| def test_chunk_parser_normal_content_chunk_still_works(): | ||
| """A regular content chunk is unaffected by the empty-choices guard.""" | ||
| iterator = ModelResponseIterator(streaming_response=None, sync_stream=True) | ||
| chunk = { | ||
| "id": "chatcmpl-x", | ||
| "object": "chat.completion.chunk", | ||
| "created": 1, | ||
| "model": "m", | ||
| "choices": [{"index": 0, "delta": {"content": "hi"}, "finish_reason": None}], | ||
| } | ||
|
|
||
| result = iterator.chunk_parser(chunk=chunk) | ||
|
|
||
| assert result["text"] == "hi" |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.