Skip to content

fix(gemini): keep Google's reason on streamed chunks and the assembled response - #52242

Merged
ryan-crabbe-berri merged 6 commits into
mainfrom
litellm_gemini_stream_filter_reason
Nov 18, 2026
Merged

ryan-crabbe-berri merged 6 commits into
mainfrom
litellm_gemini_stream_filter_reason

Conversation

@ryan-crabbe-berri

@ryan-crabbe-berri ryan-crabbe-berri commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

googles response says why it stopped: a safety block, a copyright block, a blocked prompt, or a normal finish.

a non-streamed gemini answer already had a field with that reason, and this PR adds the same field to the last chunk of every streamed answer.

Details

TLDR

  • When you stream a Gemini answer, Google tells us why it stopped.
  • We threw that reason away, so a blocked or filtered stream just said "content_filter".
  • Now the last chunk and the rebuilt full response carry Google's own reason code, like SAFETY or RECITATION.
  • Normal streams get it too ("STOP"), so streamed and non-streamed answers now match.
  • Google's free-text note about why it stopped is still never passed on, because it can quote the model's own output and our guardrails don't scan it.

Intentional product change: every streamed Gemini answer gains a provider_specific_fields object on its last chunk. Non-streamed answers are unchanged.

User Flow

Before: a developer streaming Gemini through the proxy can't tell a safety block from a recitation block or a blocked prompt

  1. They send POST http://localhost:4000/v1/chat/completions with "stream": true to a Gemini model, and Google filters the answer
  2. The last SSE chunk says "finish_reason": "content_filter" with nothing else on the choice
  3. They rebuild the response with litellm.stream_chunk_builder and the choice still has no reason

After: the same stream tells them exactly what Google said

  1. They send the same streamed POST http://localhost:4000/v1/chat/completions, and Google filters the answer
  2. The last SSE chunk says "finish_reason": "content_filter" and "provider_specific_fields": {"native_finish_reason": "SAFETY"}, the same as the non-streamed answer
  3. A blocked prompt shows {"block_reason": "SAFETY"} instead, and a normal answer shows {"native_finish_reason": "STOP"}
  4. The response rebuilt by litellm.stream_chunk_builder carries the same fields on its choice

Relevant issues

Related to #51613. The non-streamed half was closed by #52208. This also covers #47577, where a streamed MALFORMED_FUNCTION_CALL showed up as a plain "stop".

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • The handful of test files covering my change pass locally, e.g. uv run pytest tests/unit/<your_test_file>.py -v. Leave the suites (make test-unit-*, make test-unit) to CI: it finishes in ~15 minutes where a laptop takes an hour or more
  • My PR passes all required CI/CD checks (e.g., lint, schema.d.ts sync check, etc.)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • Every automated review on my PR's latest commit has finished, and I have addressed or replied to each of its findings before requesting a maintainer review

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Live against real Vertex AI gemini-3.8-flash. Before is the merge base ea96ea3db59, After is the tip 25d3e9cd429. Each proxy ran with one worker and no Redis, because this change only touches how a provider's stream is translated and shares no router or spend state between workers. Both proxies ran with PYTHON_DOTENV_DISABLED=1 so neither picked up an unrelated .env from a parent folder.

Google never blocked a harmless prompt at the prompt level during testing, so the blocked-prompt case (block_reason) is proven by the scripted-upstream integration tests below, not live. Google also sent no free-text note in these runs, so the tests that check a note never reaches the caller use scripted upstreams too.

Setup, the same for both commits. Env vars VERTEXAI_PROJECT and VERTEXAI_LOCATION come from the shell, and Vertex auth is gcloud application default credentials.

config.yaml and proxy command
model_list:
  - model_name: gemini-flash
    litellm_params:
      model: vertex_ai/gemini-3.8-flash
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: os.environ/VERTEXAI_LOCATION
general_settings:
  master_key: sk-e2e-local-1
PYTHON_DOTENV_DISABLED=1 python litellm/proxy/proxy_cli.py --config config.yaml --port 4318 --num_workers 1

Before (ea96ea3)

Streamed answer that Google filters

  1. Send the request below. The prompt is a mild one that trips Google's harassment filter at the strictest setting.
curl -sN http://localhost:4318/v1/chat/completions -H 'Authorization: Bearer sk-e2e-local-1' -H 'Content-Type: application/json' -d '{"model": "gemini-flash", "messages": [{"role": "user", "content": "Write three harsh, rude insults aimed at a fictional coworker named Bob who is an idiot."}], "stream": true, "safety_settings": [{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "BLOCK_LOW_AND_ABOVE"}, {"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_LOW_AND_ABOVE"}, {"category": "HARM_CATEGORY_DANGEROUS_CONTENT", "threshold": "BLOCK_LOW_AND_ABOVE"}, {"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", "threshold": "BLOCK_LOW_AND_ABOVE"}]}'
  1. The only chunk says content_filter and gives no reason.
data: {"id":"DvH7aqiaGISTq8YPtoXA4Aw","created":1794896146,"model":"gemini-flash","object":"chat.completion.chunk","choices":[{"finish_reason":"content_filter","index":0,"delta":{}}]}
data: [DONE]

Streamed normal answer

  1. Send the same request with "messages": [{"role": "user", "content": "Say hello in one word."}] and no safety_settings.
  2. The last chunk says stop and gives no reason. The non-streamed answer to the same prompt does carry {"native_finish_reason": "STOP"}.
data: {..."choices":[{"index":0,"delta":{"content":"Hello","role":"assistant"}}],...}
data: {..."choices":[{"index":0,"delta":{"provider_specific_fields":{"thought_signatures":["<trimmed>"]}}}],...}
data: {..."choices":[{"finish_reason":"stop","index":0,"delta":{}}]}
data: [DONE]

After (25d3e9c)

Streamed answer that Google filters

  1. Send the same request.
  2. The chunk now carries Google's reason.
data: {"id":"kv_7auSdA-SU998Pr_XD2QY","created":1794899860,"model":"gemini-flash","object":"chat.completion.chunk","choices":[{"finish_reason":"content_filter","index":0,"delta":{},"provider_specific_fields":{"native_finish_reason":"SAFETY"}}]}
data: [DONE]

Streamed normal answer

  1. Send the same request.
  2. The last chunk now says STOP, matching the non-streamed answer. The thought-signature chunk before it is unchanged and doesn't get a copy of the reason.
data: {..."choices":[{"index":0,"delta":{"content":"Hello","role":"assistant"}}],...}
data: {..."choices":[{"index":0,"delta":{"provider_specific_fields":{"thought_signatures":["<trimmed>"]}}}],...}
data: {..."choices":[{"finish_reason":"stop","index":0,"delta":{},"provider_specific_fields":{"native_finish_reason":"STOP"}}]}
data: [DONE]

Also checked live at the tip, all as expected. A streamed tool call ends tool_calls with {"native_finish_reason": "STOP"}. A filtered stream with stream_options.include_usage still sends its usage chunk. Streamed /v1/messages and /v1/responses with the filtered prompt are unchanged event for event.

Red/green tests

The tests were written before the fix and run by Devin with scripted Gemini and Vertex upstreams, using the tip's test files against both the base code and the tip. Each regression failed on base on the missing reason, then passed three runs in a row at the tip. Each guard passed at both.

Test Cases Label Base code ea96ea3db59 Tip 25d3e9cd429, 3 runs
test_gemini_content_filter_reason_wire.py::test_regression_streamed_finish_chunk_and_assembled_choice_carry_google_reason 14 regression fail, no reason on the last chunk pass, pass, pass
test_gemini_content_filter_reason_wire.py::test_regression_streamed_and_non_streamed_google_reason_agree 14 regression fail, streamed has no reason pass, pass, pass
test_vertex_and_google_ai_studio_gemini.py::test_streamed_finish_chunk_and_rebuilt_choice_carry_google_reason (sync and async) 14 regression fail pass, pass, pass
test_streaming_chunk_builder_utils.py::test_stream_chunk_builder_keeps_the_final_choices_provider_specific_fields 4 regression fail pass, pass, pass
Google's free-text note never reaches the caller, streamed or not (wire and unit) 21 guard pass pass, pass, pass
Non-streamed choice carries only the reason code (wire and unit) 21 guard pass pass, pass, pass
Other wire guards (text, usage, finish_reason, /v1/messages, /v1/responses, plain openai/ stream) 30 guard pass pass, pass, pass
Other unit guards (text, usage, no fields when none sent) 16 guard pass pass, pass, pass
Existing Gemini translation snapshots (chat completions basic, sampling, reasoning, cross model, messages, responses), unchanged from base 262 guard pass pass, pass, pass

Unit tests for the changed files pass locally, and each new unit test fails when its piece of the fix is reverted.

Type

🐛 Bug Fix

Caveats (if any)

Medium

  • Shared streaming code changed, so every OpenAI-compatible stream is affected
    • Choice-level provider_specific_fields sent on a finish chunk now move to the final chunk
    • The response rebuilt by stream_chunk_builder now keeps them on its choice
    • Before, they were dropped. No in-repo provider sends them today except Gemini
  • A Gemini stream that hit SAFETY and then sent one more empty chunk used to end as "stop". It now ends as "content_filter", the same as non-streamed

Low

  • A streamed cache hit still loses Google's reason, which is a separate follow-up
  • The blocked-prompt reason is proven only with scripted upstreams, since no harmless prompt triggers it live
  • Passing Google's free-text note would need every output guardrail to scan it, left for a follow-up if anyone asks

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@veria-ai

veria-ai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

All previously flagged issues have been addressed. No open security concerns remain on this pull request.

Fixed/addressed: 1 · PR risk: 0/10

Reviews

@greptile-apps

greptile-apps Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 5/5

[Medium impact] The reviewed changes appear safe to merge, with both previous findings addressed.

Summary

Gemini streams now keep Google's reason code on the closing choice and in the response rebuilt by stream_chunk_builder.

  • Gemini streams keep Google’s reason beside the final stop reason.
  • Rebuilt stream responses keep each choice’s last provider fields.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Google stream] --> B[Gemini adapter]
  B --> C[Reason code on choice]
  C --> D[Closing stream chunk]
  D --> E[stream_chunk_builder]
  E --> F[Reason code on assembled choice]
Loading

Reviews (4) · Last reviewed commit: "fix(gemini): pass only Google's reason c..." · Reviewed by Greptile

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@codspeed

codspeed Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

1 warning

⚠️ 2 benchmarks are dominated by system calls

System calls cannot be simulated consistently and are left out of the measure. The reported value understates the real cost. Switch to the Walltime instrument to measure them.

Learn more about system calls

See affected benchmarks

✅ 45 untouched benchmarks


Comparing litellm_gemini_stream_filter_reason (25d3e9c) with main (0cc072c)

Open in CodSpeed

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

@codecov

codecov Bot commented Nov 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

@greptileai

@ryan-crabbe-berri

Copy link
Copy Markdown
Contributor Author

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit 25d3e9c. Configure here.

@ryan-crabbe-berri
ryan-crabbe-berri enabled auto-merge (squash) November 17, 2026 22:24

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM. Thanks!

@ryan-crabbe-berri
ryan-crabbe-berri merged commit 0266dbb into main Nov 18, 2026
158 of 160 checks passed
@ryan-crabbe-berri
ryan-crabbe-berri deleted the litellm_gemini_stream_filter_reason branch November 18, 2026 00:01
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants