Skip to content

fix(gemini): backport keeping thought images out of message.images to lts/1.108.x - #53441

Merged
mateo-berri merged 7 commits into
BerriAI:lts/1.108.xfrom
edvinsq:litellm_gemini_drop_thought_images_lts
Nov 21, 2026
Merged

mateo-berri merged 7 commits into
BerriAI:lts/1.108.xfrom
edvinsq:litellm_gemini_drop_thought_images_lts

Conversation

@edvinsq

@edvinsq edvinsq commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

Handwritten 1-3 sentence description

On the 1.108 LTS line, a thinking Gemini image model like Nano Banana 2.1 returns its draft thought image in message.images next to the final one, so clients cannot tell which image is final

This brings the same fix as #50709 to the line

Details

TLDR

Problem this solves:

  • Gemini image chat returns the thought draft image next to the final one
  • message.images holds two entries, client cannot tell which is final
  • /v1/responses returns two image_generation_call items the same way
  • Each thought image also adds an empty entry to thinking_blocks

How it solves it:

  • Leave image parts marked thought: true out of message.images and thinking_blocks
  • Thought text still goes to reasoning_content and thinking_blocks
  • A reply cut off before its final image still returns the last thought image, as before
  • A reply that ends in content_filter returns no thought image
  • Covers streaming and non-streaming
Backport checklist
  • fix(gemini): keep thought images out of message.images #50709 merges into main first. The line picks all seven of its non-merge commits with -x, as the table below lists
  • The first two picks applied clean. The third conflicted only at its anchor, because main's context names helpers from fix(gemini): keep Google's reason on streamed chunks and the assembled response #52242 that the line lacks. The resolution copies the one-line _names_its_finish helper from main unchanged, leaves out the main-only helpers the pick never calls, and adds ModelResponseStream to the test import. The fourth conflicted at its imports, its new helpers and the stream chunk's return, because main's context there names the finish-reason helpers from fix(gemini): keep Google's reason on streamed chunks and the assembled response #52242. The resolution keeps the pick's own changes and leaves those helpers and one main-only test out. The fifth, sixth and seventh applied clean, and the seventh's tests needed the dataclass, Iterator and AsyncIterator imports the line's test file lacked
  • The picked tests pass on the line (745 in the Gemini unit folder). The 2 thought image tests fail without the first two picks, the 3 cut-off tests fail without the third, the 5 content_filter tests fail without the fourth, the 5 stream-end cases fail without the fifth, the response id check fails without the sixth, and the 4 dropped stream tests fail without the seventh
  • No dependency moves, and no enterprise/ or litellm-proxy-extras/ change
  • make check passes on the line with BASE_REF=origin/lts/1.108.x
Main commit LTS commit
398d38e9e053b8292705f79083a7a2cafd847bf4 3d138a2855d350e4a169bdd0d32585912c1e4a43
706d9bf76e041bfa7983a40b9ee70d974bfcb28e 5e8ef44b72142f4fe3c242c5a142a4d80ef12165
8990f8aaf98c5be7dd3479e2ded146253bce0cd4 9580e307dbf68611400bfd1470e458a29a3c207d (conflict resolved as above)
79bad9e478d925cff1583a6c3419fd5b368fa2ac f033ea59c251f7acbe7860010faf44e8c94522ae (conflict resolved as above)
b34727d5c47e5e49f06d123c08e268f0c282482b c3a40b3fff9d6475b5f47eaa42218bf4600545e8
0a35a928f1d69b5155939a84c68898440447338a 25fea762d9d5ebb0d0ce13f78817b82467c54d21
be0a98b959088f0fb7346aa0e5768de7ae0b2765 db200b0497563e587f36b07bb52192cc3dfbddd0 (test imports added as above)

User Flow

Before: a developer asking a thinking Gemini image model for one image gets two back and cannot tell which is the final render

  1. They send POST http://localhost:4000/v1/chat/completions with "model": "gemini-nano-banana-2.1" on Vertex AI, or on AI Studio with reasoning_effort
  2. The response has reasoning_content, two entries in message.images with "index": 0, and an empty thinking_blocks entry
  3. Their app shows the first entry, which is an interim thought image, or shows both, and POST /v1/responses returns two image_generation_call items

After: the same request returns only the final image, and the reasoning text is still there

  1. They send the same POST http://localhost:4000/v1/chat/completions
  2. The response has reasoning_content, one entry in message.images, and no empty thinking_blocks entry
  3. Their app shows that image, and streaming and POST /v1/responses return one image too

Relevant issues

Part of #50706, the same fix as #50709

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

Backport smoke on Vertex AI, run on 2026-11-20 with the headline case and the cut-off case of #50709's proof, the cut-off case streamed too, and a stream whose connection drops after a thought image, the same config, client and prompt. #50709 carries the full matrix across chat, streaming, /v1/responses and AI Studio. This line ignores --num_workers when --reload is on (the proxy printed "workers" flag is ignored when reloading is enabled), so each leg ran one worker with Redis. The run has no database, so --use_v2_migration_resolver is dropped. Image sizes change between runs because the images are model output.

Proxy command, run from the tree under test. The shell exported PYTHON_DOTENV_DISABLED=1 and LITELLM_LOCAL_MODEL_COST_MAP=True. Env var names are LITELLM_MASTER_KEY, VERTEXAI_PROJECT, GOOGLE_APPLICATION_CREDENTIALS and GEMINI_API_KEY.

.venv/bin/python litellm/proxy/proxy_cli.py --config config.yaml --port <port> --num_workers 2 --detailed_debug --reload --timeout_worker_healthcheck 60
config.yaml (Redis on 127.0.0.1:29198)
model_list:
  - model_name: google/gemini-nano-banana-2.1
    litellm_params:
      model: vertex_ai/gemini-nano-banana-2.1
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
      vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS
    model_info:
      mode: image_generation
  - model_name: cut-image
    litellm_params:
      model: vertex_ai/gemini-nano-banana-2.1
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
      vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS
      api_base: http://127.0.0.1:24175
  - model_name: google/gemini-3.1-flash-image
    litellm_params:
      model: vertex_ai/gemini-3.1-flash-image
      vertex_project: os.environ/VERTEXAI_PROJECT
      vertex_location: global
      vertex_credentials: os.environ/GOOGLE_APPLICATION_CREDENTIALS
    model_info:
      mode: image_generation
  - model_name: aistudio/gemini-nano-banana-2.1
    litellm_params:
      model: gemini/gemini-nano-banana-2.1
      api_key: os.environ/GEMINI_API_KEY
    model_info:
      mode: image_generation

router_settings:
  redis_host: 127.0.0.1
  redis_port: 29198

general_settings:
  master_key: os.environ/LITELLM_MASTER_KEY
  coordination_redis:
    host: 127.0.0.1
    port: 29198

litellm_settings:
  drop_params: True
client.py, run as python client.py <case> <port> with openai 2.x and anthropic installed
import base64
import io
import json
import os
import struct
import sys
import zlib

import anthropic
import openai

CASE = sys.argv[1]
PORT = sys.argv[2]
BASE = f"http://127.0.0.1:{PORT}"
KEY = os.environ["LITELLM_MASTER_KEY"]
PROMPT = "An infographic poster titled How to install a replacement window with exactly 6 numbered steps"
oa = openai.OpenAI(base_url=f"{BASE}/v1", api_key=KEY, timeout=600, max_retries=3)
an = anthropic.Anthropic(base_url=BASE, api_key=KEY, timeout=600, max_retries=3)


def short(url: str) -> dict:
    return {"prefix": url[:22], "chars": len(url)}


def chat_summary(message) -> dict:
    images = getattr(message, "images", None) or []
    return {
        "images": len(images),
        "image_sizes": [short(i["image_url"]["url"])["chars"] for i in images],
        "indexes": [i.get("index") for i in images],
        "reasoning_content_chars": len(getattr(message, "reasoning_content", None) or ""),
        "content_chars": len(message.content or ""),
        "thinking_block_lengths": [len(b.get("thinking") or "") for b in (getattr(message, "thinking_blocks", None) or [])],
    }


def chat(model: str, **extra) -> None:
    r = oa.chat.completions.create(model=model, messages=[{"role": "user", "content": PROMPT}], **extra)
    print(json.dumps(chat_summary(r.choices[0].message)))


def chat_stream(model: str, **extra) -> None:
    images, reasoning, content, blocks = [], 0, 0, []
    for chunk in oa.chat.completions.create(model=model, messages=[{"role": "user", "content": PROMPT}], stream=True, **extra):
        if not chunk.choices:
            continue
        delta = chunk.choices[0].delta
        images.extend(getattr(delta, "images", None) or [])
        reasoning += len(getattr(delta, "reasoning_content", None) or "")
        content += len(delta.content or "")
        blocks.extend(len(b.get("thinking") or "") for b in (getattr(delta, "thinking_blocks", None) or []))
    print(json.dumps({"images": len(images), "image_sizes": [len(i["image_url"]["url"]) for i in images], "reasoning_content_chars": reasoning, "content_chars": content, "thinking_block_lengths": blocks}))


def chat_two_turns(model: str) -> None:
    history = [{"role": "user", "content": PROMPT}]
    first = oa.chat.completions.create(model=model, messages=history)
    print("turn 1:", json.dumps(chat_summary(first.choices[0].message)))
    history.append({"role": "assistant", "content": first.choices[0].message.content or "Here is the poster."})
    history.append({"role": "user", "content": "Make the poster title red and keep everything else the same"})
    second = oa.chat.completions.create(model=model, messages=history)
    print("turn 2:", json.dumps(chat_summary(second.choices[0].message)))


def chat_cut(model: str, max_tokens: int) -> None:
    r = oa.chat.completions.create(model=model, messages=[{"role": "user", "content": PROMPT}], max_tokens=max_tokens)
    print(json.dumps({"finish_reason": r.choices[0].finish_reason, **chat_summary(r.choices[0].message)}))


def chat_cut_stream(model: str, max_tokens: int) -> None:
    images, reasoning, finish = [], 0, []
    for chunk in oa.chat.completions.create(model=model, messages=[{"role": "user", "content": PROMPT}], max_tokens=max_tokens, stream=True):
        if not chunk.choices:
            continue
        delta = chunk.choices[0].delta
        images.extend(getattr(delta, "images", None) or [])
        reasoning += len(getattr(delta, "reasoning_content", None) or "")
        if chunk.choices[0].finish_reason:
            finish.append(chunk.choices[0].finish_reason)
    print(json.dumps({"finish_reasons": finish, "images": len(images), "image_sizes": [len(i["image_url"]["url"]) for i in images], "reasoning_content_chars": reasoning}))


def chat_dropped_stream(model: str) -> None:
    images, reasoning, error = [], 0, None
    try:
        for chunk in oa.chat.completions.create(model=model, messages=[{"role": "user", "content": PROMPT}], stream=True):
            if not chunk.choices:
                continue
            delta = chunk.choices[0].delta
            images.extend(getattr(delta, "images", None) or [])
            reasoning += len(getattr(delta, "reasoning_content", None) or "")
    except openai.APIError as e:
        error = f"{type(e).__name__}: {str(e)[:160]}"
    print(json.dumps({"images": len(images), "image_sizes": [len(i["image_url"]["url"]) for i in images], "reasoning_content_chars": reasoning, "error": error}))


def chat_two_turns_full_message(model: str) -> None:
    first = oa.chat.completions.create(model=model, messages=[{"role": "user", "content": PROMPT}])
    print("turn 1:", json.dumps(chat_summary(first.choices[0].message)))
    history = [
        {"role": "user", "content": PROMPT},
        first.choices[0].message.model_dump(exclude_none=True),
        {"role": "user", "content": "Make the poster title red and keep everything else the same"},
    ]
    second = oa.chat.completions.create(model=model, messages=history)
    print("turn 2:", json.dumps(chat_summary(second.choices[0].message)))


def responses(model: str) -> None:
    r = oa.responses.create(model=model, input=PROMPT)
    print(json.dumps({"output_types": [o.type for o in r.output], "image_generation_calls": sum(o.type == "image_generation_call" for o in r.output)}))


def responses_stream(model: str) -> None:
    added, final = [], []
    for event in oa.responses.create(model=model, input=PROMPT, stream=True):
        if event.type == "response.output_item.added":
            added.append(event.item.type)
        if event.type == "response.completed":
            final = [o.type for o in event.response.output]
    print(json.dumps({"output_item_added": added, "completed_output_types": final, "image_generation_calls": final.count("image_generation_call")}))


def messages(model: str) -> None:
    r = an.messages.create(model=model, max_tokens=8192, messages=[{"role": "user", "content": PROMPT}])
    print(json.dumps({"content_types": [b.type for b in r.content], "thinking_lengths": [len(b.thinking) for b in r.content if b.type == "thinking"]}))


def messages_stream(model: str) -> None:
    types, thinking = [], []
    with an.messages.stream(model=model, max_tokens=8192, messages=[{"role": "user", "content": PROMPT}]) as s:
        final = s.get_final_message()
    print(json.dumps({"content_types": [b.type for b in final.content], "thinking_lengths": [len(b.thinking) for b in final.content if b.type == "thinking"]}))


def images_generate(model: str) -> None:
    r = oa.images.generate(model=model, prompt=PROMPT, n=1)
    print(json.dumps({"data": len(r.data), "b64_chars": [len(d.b64_json or "") for d in r.data]}))


def png(width: int, height: int) -> bytes:
    raw = b"".join(b"\x00" + bytes([255, 255, 255]) * width for _ in range(height))
    def chunk(tag: bytes, data: bytes) -> bytes:
        return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
    return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(raw)) + chunk(b"IEND", b"")


def images_edit(model: str) -> None:
    r = oa.images.edit(model=model, image=("blank.png", io.BytesIO(png(512, 512)), "image/png"), prompt="Turn this blank canvas into " + PROMPT, n=1)
    print(json.dumps({"data": len(r.data), "b64_chars": [len(d.b64_json or "") for d in r.data]}))


VERTEX_NANO = "google/gemini-nano-banana-2.1"
VERTEX_FLASH = "google/gemini-3.1-flash-image"
STUDIO_NANO = "aistudio/gemini-nano-banana-2.1"
CASES = {
    "chat-vertex-nano": lambda: chat(VERTEX_NANO),
    "chat-vertex-nano-stream": lambda: chat_stream(VERTEX_NANO),
    "chat-vertex-flash": lambda: chat(VERTEX_FLASH),
    "chat-vertex-flash-stream": lambda: chat_stream(VERTEX_FLASH),
    "chat-vertex-nano-reasoning-high": lambda: chat(VERTEX_NANO, reasoning_effort="high"),
    "chat-studio-nano": lambda: chat(STUDIO_NANO),
    "chat-studio-nano-stream": lambda: chat_stream(STUDIO_NANO),
    "chat-studio-nano-reasoning-high": lambda: chat(STUDIO_NANO, reasoning_effort="high"),
    "chat-studio-nano-reasoning-high-stream": lambda: chat_stream(STUDIO_NANO, reasoning_effort="high"),
    "chat-vertex-nano-two-turns": lambda: chat_two_turns(VERTEX_NANO),
    "chat-vertex-nano-two-turns-full-message": lambda: chat_two_turns_full_message(VERTEX_NANO),
    "chat-vertex-nano-cut": lambda: chat_cut(VERTEX_NANO, 2600),
    "chat-vertex-nano-cut-stream": lambda: chat_cut_stream(VERTEX_NANO, 2600),
    "chat-vertex-nano-dropped-stream": lambda: chat_dropped_stream("cut-image"),
    "chat-vertex-flash-reasoning-high": lambda: chat(VERTEX_FLASH, reasoning_effort="high"),
    "responses-vertex-nano": lambda: responses(VERTEX_NANO),
    "responses-vertex-nano-stream": lambda: responses_stream(VERTEX_NANO),
    "messages-vertex-nano": lambda: messages(VERTEX_NANO),
    "messages-vertex-nano-stream": lambda: messages_stream(VERTEX_NANO),
    "images-generate-vertex-nano": lambda: images_generate(VERTEX_NANO),
    "images-generate-studio-nano": lambda: images_generate(STUDIO_NANO),
    "images-edit-vertex-nano": lambda: images_edit(VERTEX_NANO),
    "images-edit-studio-nano": lambda: images_edit(STUDIO_NANO),
}
try:
    CASES[CASE]()
except (openai.APIError, anthropic.APIError) as e:
    print(f"error: {type(e).__name__} {getattr(e, 'status_code', '')} {str(e)[:300]}")
cutter.py, run as python cutter.py 24175 https://aiplatform.googleapis.com thought-image <log>

The cut-image model sends its request through this local forwarder, which relays the real Vertex stream and closes the connection right after the first image event, with no closing chunk.

import http.client
import json
import socket
import sys
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlsplit

LISTEN_PORT, UPSTREAM, MODE, LOG_PATH = int(sys.argv[1]), sys.argv[2].rstrip("/"), sys.argv[3], sys.argv[4]
UPSTREAM_URL = urlsplit(UPSTREAM)
HOP = frozenset({"host", "content-length", "transfer-encoding", "connection"})
open(LOG_PATH, "w").close()


def log(entry: dict) -> None:
    with open(LOG_PATH, "a") as f:
        f.write(json.dumps(entry) + "\n")


def has_thought_image(event: dict) -> bool:
    parts = (p for c in event.get("candidates", []) for p in c.get("content", {}).get("parts", []))
    return any(p.get("thought") and "inlineData" in p for p in parts)


def should_cut(index: int, event: dict) -> bool:
    if MODE.startswith("events="):
        return index + 1 >= int(MODE.split("=", 1)[1])
    return MODE == "thought-image" and has_thought_image(event)


class Cutter(BaseHTTPRequestHandler):
    protocol_version = "HTTP/1.1"

    def do_POST(self) -> None:
        target = self.requestline.split()[1]
        body = self.rfile.read(int(self.headers.get("content-length") or 0))
        headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP}
        conn = http.client.HTTPSConnection(UPSTREAM_URL.hostname, UPSTREAM_URL.port, timeout=600)
        conn.request("POST", UPSTREAM_URL.path + target, body=body, headers=headers)
        resp = conn.getresponse()
        entry = {"ts": time.time(), "path": target.split("?")[0], "body": body.decode(errors="replace"), "status": resp.status}
        if resp.status != 200 or "alt=sse" not in target:
            payload = resp.read()
            self.send_response(resp.status)
            for k, v in resp.getheaders():
                if k.lower() not in HOP:
                    self.send_header(k, v)
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)
            log({**entry, "cut": None})
            return
        self.send_response(200)
        self.send_header("Content-Type", resp.getheader("Content-Type", "text/event-stream"))
        self.send_header("Transfer-Encoding", "chunked")
        self.end_headers()
        lines, index = [], 0
        while raw := resp.readline():
            lines.append(raw)
            if raw.strip():
                continue
            chunk = b"".join(lines)
            lines = []
            data = [l[6:] for l in chunk.decode().splitlines() if l.startswith("data: ")]
            if not data:
                continue
            self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))
            self.wfile.flush()
            if should_cut(index, json.loads(data[0])):
                log({**entry, "cut": f"after event {index + 1}"})
                conn.close()
                self.connection.shutdown(socket.SHUT_RDWR)
                self.close_connection = True
                return
            index += 1
        self.wfile.write(b"0\r\n\r\n")
        log({**entry, "cut": f"not cut, {index} events"})
        conn.close()


server = ThreadingHTTPServer(("127.0.0.1", LISTEN_PORT), Cutter)
print(f"listening on {LISTEN_PORT} mode={MODE}", flush=True)
server.serve_forever()
Case Before (7ab941f) After (db200b0)
Vertex chat, message.images 2 1
Vertex chat, empty thinking_blocks entries 1 0
Vertex chat cut off by max_tokens, message.images 1 1
Vertex chat cut off by max_tokens, empty thinking_blocks entries 1 0
Vertex chat stream cut off by max_tokens, images 1 1
Vertex chat stream whose connection drops after a thought image, images before the error 1 1

Before (7ab941f)

  1. Two images come back with "index": 0, and the thinking blocks hold one empty entry
$ clientvenv/bin/python client.py chat-vertex-nano 24871
{"images": 2, "image_sizes": [2017542, 2017542], "indexes": [0, 0], "reasoning_content_chars": 589, "content_chars": 0, "thinking_block_lengths": [280, 0, 309]}
Cases 2 to 4
  1. With max_tokens 2600 the reply stops before the final image, so the one image is the last thought image, and an empty thinking block comes with it
$ clientvenv/bin/python client.py chat-vertex-nano-cut 24871
{"finish_reason": "length", "images": 1, "image_sizes": [1835746], "indexes": [0], "reasoning_content_chars": 390, "content_chars": 0, "thinking_block_lengths": [390, 0]}
  1. Streamed with the same max_tokens, the one image is the last thought image
$ clientvenv/bin/python client.py chat-vertex-nano-cut-stream 24871
{"finish_reasons": ["length"], "images": 1, "image_sizes": [1851426], "reasoning_content_chars": 1358}
  1. The cut-image model sends the request through a local forwarder that closes the connection right after the first thought image event. That image arrives, then the stream's error
$ clientvenv/bin/python client.py chat-vertex-nano-dropped-stream 24871
{"images": 1, "image_sizes": [2270982], "reasoning_content_chars": 1276, "error": "APIError: litellm.APIConnectionError: Vertex_ai_betaException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transf"}

After (db200b0)

  1. One image comes back, the reasoning text is still there, and no thinking block is empty
$ clientvenv/bin/python client.py chat-vertex-nano 24871
{"images": 1, "image_sizes": [1887854], "indexes": [0], "reasoning_content_chars": 893, "content_chars": 176, "thinking_block_lengths": [285, 285, 323]}
Cases 2 to 4
  1. The cut-off reply still returns the last thought image, with no empty thinking block
$ clientvenv/bin/python client.py chat-vertex-nano-cut 24871
{"finish_reason": "length", "images": 1, "image_sizes": [1900290], "indexes": [0], "reasoning_content_chars": 241, "content_chars": 0, "thinking_block_lengths": [241]}
  1. The streamed cut-off reply still returns the last thought image
$ clientvenv/bin/python client.py chat-vertex-nano-cut-stream 24871
{"finish_reasons": ["length"], "images": 1, "image_sizes": [1934102], "reasoning_content_chars": 1160}
  1. When the connection drops after a thought image, that image still arrives before the error
$ clientvenv/bin/python client.py chat-vertex-nano-dropped-stream 24871
{"images": 1, "image_sizes": [2084506], "reasoning_content_chars": 870, "error": "APIError: litellm.APIConnectionError: Vertex_ai_betaException - Response payload is not completed: <TransferEncodingError: 400, message='Not enough data to satisfy transf"}

Type

🐛 Bug Fix

Caveats (if any)

Copied from #50709 and re-read against the line.

Medium

Low

Decisions
  • Thought images are dropped rather than exposed in a new reasoning field. [Feature]: Preserve Gemini image part.thought metadata in LiteLLM image responses #30355 asks to expose them, and that can build on this
  • When no final image comes back, as when max_tokens cuts the reply off, the last thought image is returned in message.images, the same as before this PR. Google's image generation guide says "The last image within Thinking is also the final rendered image". The alternative was returning no image at all
  • Only the last thought image is returned in that case, since the earlier ones are drafts
  • A stream holds that image until it ends, then sends it on its own chunk before the end. That covers a failed continuation hop, a finish Gemini leaves unspecified, a stream with no finish reason and a dropped connection. A dropped connection sends the image and then raises its error, the same as on the line's base
  • When the reply ends in content_filter, no thought image is returned, streaming or not. That covers IMAGE_SAFETY, IMAGE_RECITATION, NO_IMAGE and every other finish LiteLLM maps there, OTHER and LANGUAGE included. Non-streaming already answers the safety blocks with an empty response, and a draft image next to a content_filter finish would contradict that finish. The alternatives were the merge base's behavior, which returned every thought image, or a list of only the image-specific blocks

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
Bugbot summary

[!NOTE]
Medium Risk
Changes Vertex/Gemini response and streaming image handling on an LTS branch; behavior shifts for thinking image models but is covered by broad unit tests.

Overview
Backports the Gemini thought-image fix to the 1.108 LTS line so thinking image models no longer put draft thought inline images into message.images or empty thinking_blocks entries alongside the final render.

Response mapping adds helpers that treat only non-thought inline image parts as final images, skip thought inline data when building thinking blocks, and on non-streaming completions fall back to the last thought image when the reply ends without a final image (e.g. MAX_TOKENS) but not when finish maps to content_filter.

Streaming (ModelResponseIterator) holds thought images until a candidate finishes or the stream ends; it can emit a trailing chunk with those images before continuation tokens, normal stream end, hop failures, or connection drops. Unit tests cover sync/async streaming, cut-offs, drops, and safety blocks.

Reviewed by Cursor Bugbot for commit db200b0. Bugbot is set up for automated code reviews on this repo. Configure here.

benlangfeld and others added 7 commits November 20, 2026 12:19
Gemini image models return their interim thought images as parts marked thought: true. Thought text already goes to reasoning_content, but every image part went into message.images, so a single image request came back with two entries and no way to tell which was final.

Fixes BerriAI#50706

(cherry picked from commit 398d38e)
A thought image part has no text, so it added an empty thinking block next to the real ones

(cherry picked from commit 706d9bf)
…back

A reply cut off by max_tokens before Gemini renders its final image now
returns the last thought image in message.images, and a stream sends it
on the finishing chunk, as it did before thought images were dropped

(cherry picked from commit 8990f8a)
…ating stream chunks

(cherry picked from commit 79bad9e)
@edvinsq
edvinsq requested a review from a team November 21, 2026 21:44
@veria-ai

veria-ai Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

PR overview

No security issues were found in this pull request.

Reviews

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@greptile-apps

greptile-apps Bot commented Nov 21, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5

[Medium impact] The change reaches Gemini chat replies on Vertex AI and Google AI Studio.

The code has no newly established defects, but the outstanding live-proof requirement must be satisfied before merging

Findings

  1. P2 Backport lacks required live proof ▶

Summary

Backports the Gemini thought-image fix to lts/1.108.x

  • Gemini chat replies keep draft images out when a final image arrives.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Gemini image part] --> B{Thought image?}
  B -->|No| C[Return final image]
  B -->|Yes| D[Hold latest draft]
  D --> E{How does generation end?}
  E -->|Final image arrives| F[Discard held draft]
  E -->|Content filter| F
  E -->|Stops early| G[Return held draft]
  E -->|Connection fails| H[Return held draft, then raise error]
Loading

Reviews (2) · Last reviewed commit: "fix(gemini): send a held thought image b..." · Reviewed by Greptile

Comment on lines +2515 to +2518
image_response = list(
_final_images(candidate["content"]["parts"])
if isinstance(model_response, ModelResponseStream)
else _final_images(candidate["content"]["parts"]) or _fallback_thought_image(candidate)

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.

P2 Backport lacks required live proof

This changes images returned through /v1/responses and AI Studio, but their live proof comes from #50709. Repository rules require live proxy checks on this backport’s latest product commit, db200b0497563e587f36b07bb52192cc3dfbddd0. Supply streaming and non-streaming runs before merging

Rule Used: Apply this rule only to PRs that fix LLM translation bugs or add LLM translation features. LLM translation means converting requests, responses, streaming events, tool calls, and errors between the API a caller uses on LiteLLM (any endpoint or SDK fu... (source)

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

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.

The body already has live streaming and non-streaming proxy runs at db200b0. /v1/responses and AI Studio share that code, proven on #50709

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.

You're right — I see the live runs at db200b0 in the proof section. The chat completions tests (both streaming and non-streaming) demonstrate the fix works on the backport, and since /v1/responses and AI Studio use that same translation code, the proof covers them. The full endpoint matrix on #50709 confirms the behavior.

The provided proof is sufficient for this backport.

@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

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 db200b0. Configure here.

@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

@mateo-berri
mateo-berri merged commit c36e1cf into BerriAI:lts/1.108.x Nov 21, 2026
60 checks passed
@codecov

codecov Bot commented Nov 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

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.

3 participants