GEMINI LABJP
NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20NANOLITE — Nano Banana 2 Lite is here: Google's fastest and most cost-efficient Gemini Image model, made for running lightweight image generation cheaplyOMNIFLASH — Gemini Omni Flash is in public preview, a natively multimodal model that lets enterprises and developers build custom, dynamic video workflowsAGENTS — Managed Agents expand with background: true for async server-side runs and polling, remote MCP server integration, and refreshing credentials across interactionsMEMORY — The Memory Bank IngestEvents API is generally available, decoupling event ingestion from memory generation so you can stream content continuouslyTHROUGHPUT — Provisioned Throughput now lets you submit up to seven pending orders for the same model and regionDEPRECATE — Image generation models shut down on August 17, and the Grok 4.1 family on the Gemini Enterprise Agent Platform on August 20
Articles/API / SDK
API / SDK/2026-04-21Advanced

Rendering Gemini's Thought Summaries in a Next.js UI — A Production Pattern for Explainable AI

A production walkthrough for surfacing Gemini 2.5 / 3 thought summaries in a Next.js UI. Covers the SDK configuration, Server-Sent Events, a React collapsible component, observability, and the UX judgement calls you face when you decide how much of the AI's reasoning to show.

gemini-api277thought-summariesthinking7nextjs3production140ux-designstreaming28

Premium Article

After six months of running Gemini in production apps, I keep hearing the same question from users: "Why did it answer that way?" Saying "because the model decided so" erodes trust, whether you are building a solo indie product or a B2B SaaS. Support tickets go up, refund requests go up, and the lifetime value of your customers gradually drifts down. Retrieval citations and source links help, but they only show what the model was given, not how it reasoned. For tasks that do not touch external information at all — summarization, classification, draft generation, comparative judgement — you cannot even offer citations, so the transparency gap is even wider.

Gemini 2.5 Pro, 2.5 Flash, and 3 Pro expose thought summaries — short, structured glimpses of the model's intermediate reasoning. I have found that surfacing these in the UI visibly reduces support requests that start with "why". On one of my apps the refund rate fell from roughly 0.8% to 0.3% after the feature shipped. This article walks through the whole pipeline end-to-end: pulling summaries from the SDK, streaming them via Server-Sent Events from a Next.js Route Handler, rendering them with a collapsible React component, and — the part most guides skip — the UX judgement calls that decide whether your users actually benefit. It also covers the observability, multi-turn conversation, and mobile UX details that always bite you the week after launch.

Trust does not accumulate while the reasoning stays hidden

From the user's point of view, an LLM-powered app is a black box with a text input and a text output. RAG citations and source chips tell you what information was retrieved, but they do not tell you how the model chose between competing possibilities. The reasoning itself stays opaque. This is especially painful for tasks where no external retrieval happens at all: the model is pulling from its internal weights, and you literally have nothing external to cite.

Thought summaries change that dynamic. The model internally generates many reasoning tokens, but exposing the full thinking trace tends to overwhelm users rather than reassure them. Gemini's summary feature distills those thoughts into short, structured snippets before returning them. Setting include_thoughts=True is enough for the API to mix in chunks where part.thought = True. Turning that into a production experience takes a bit of plumbing, so let's take it step by step.

One caveat worth internalizing early: thought summaries are summaries of reasoning for display, not the model's actual internal computation. They are not what researchers use when they discuss mechanistic interpretability. Treat them as a user-facing explanation layer, not as ground truth about the model's inner state. If you skip this distinction, internal design discussions tend to stall on "but did the model really think this?" — which is the wrong question for an application-layer feature.

Start with the smallest possible thought-summary loop

Before you involve Next.js, React, or streaming, make sure you can pull thought summaries out of Gemini from a vanilla Python script. If this layer is broken, everything downstream is broken too. Personally, I always start every new SDK feature with a "smallest possible smoke test" before I touch any full-stack code. Diving straight into streaming and UI tends to burn hours on issues that are easy to isolate at the script level.

# gemini_thought_demo.py
# Purpose: verify that we can separate the answer from the thought summary.
import os
from google import genai
from google.genai import types
 
client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
 
def ask_with_thoughts(question: str) -> dict:
    """Return the answer text and thought summaries as a dict."""
    try:
        response = client.models.generate_content(
            model="gemini-2.5-pro",
            contents=question,
            config=types.GenerateContentConfig(
                thinking_config=types.ThinkingConfig(
                    include_thoughts=True,   # ← ask for thought summaries
                    thinking_budget=-1,       # ← auto (>=128 is a safe floor on Pro)
                ),
            ),
        )
    except Exception as e:
        # Catch network, quota, and safety-filter errors in one place.
        return {"answer": "", "thoughts": [], "error": str(e)}
 
    answer_parts, thought_parts = [], []
    for candidate in response.candidates or []:
        for part in candidate.content.parts:
            if getattr(part, "thought", False):
                thought_parts.append(part.text or "")
            elif part.text:
                answer_parts.append(part.text)
 
    return {
        "answer": "".join(answer_parts),
        "thoughts": thought_parts,
        "error": None,
    }
 
if __name__ == "__main__":
    r = ask_with_thoughts("Give me 3 reasons Japanese public holidays tend to shift to Mondays.")
    print("--- THOUGHTS ---")
    for t in r["thoughts"]:
        print(t)
    print("\n--- ANSWER ---")
    print(r["answer"])

Running GEMINI_API_KEY=... python gemini_thought_demo.py prints one to three short summaries under --- THOUGHTS --- — things like "Group reasons into economic, cultural, and legal" — followed by the actual answer. If the thoughts array is empty, you are almost certainly on a non-thinking model like gemini-2.5-flash-lite. Switch to gemini-2.5-pro or gemini-2.5-flash and retry. This is the single most common cause of "thoughts not appearing" reports I see.

The thinking_budget value of -1 (auto) is fine in almost all real-world scenarios. If you do want to set it explicitly, a lower bound of 128 on Pro and 64 on Flash tends to keep the summaries from shrinking to a useless trickle. If you need an upper bound for cost control near end-of-month, capping at 512–1024 avoids runaway spending while still giving you usable reasoning. For the deeper story on model choice between Pro and Flash, Gemini 2.5 Pro thinking budget reasoning control guide will save you a lot of trial and error.

Thank you for reading this far.

Continue Reading

What follows includes implementation code, benchmarks, and practical content we hope you'll find useful. This site runs without ads — server and development costs are supported entirely by members like you. If it's been helpful, we'd be truly grateful for your support.

WHAT YOU'LL LEARN
Developers who cannot explain why their Gemini-powered app gave a particular answer will be able to ship a UI that surfaces the reasoning today.
You will get complete, runnable code for pulling thought summaries from the SDK, streaming them over SSE, and rendering them as a collapsible React component.
You will learn the UX heuristics for deciding how much reasoning to expose and how to measure whether it actually improves user trust.
Secure payment via Stripe · Cancel anytime

Unlock This Article

Get full access to the rest of this article. Buy once, read anytime. This site is ad-free — your support goes directly toward keeping it running.

or
Unlock all articles with Membership →
Share

Thank You for Reading

Gemini Lab is ad-free, supported entirely by members like you. We publish practical guides daily with implementation code, benchmarks, and production-ready patterns. If you've found it useful, we'd love to have you on board.

  • Copy-paste ready implementation code
  • New advanced guides published daily
  • $5/mo or $10 for lifetime access
View Membership →

Related Articles

API / SDK2026-06-25
Gemini API × TypeScript Type-Safe AI Application Architecture — Integrating Zod Schemas, Structured Output, and Streaming
Type-safe AI applications with the Gemini API and TypeScript: Zod validation, Structured Output, streaming pipelines, and error handling that holds up in production.
API / SDK2026-05-23
When Gemini API Streaming Cuts Off Mid-Response in Production: The Diagnosis Order I Run
How I diagnose mid-response cutoffs in Gemini API streaming - the order I check network, SDK, and server-side suspects, with real cases from indie production.
API / SDK2026-04-12
Gemini API Production Performance Tuning — A Triple Optimization Strategy for Latency, Throughput, and Cost
Learn how to simultaneously optimize latency, throughput, and cost in production Gemini API deployments. Covers Flex/Priority inference, Context Caching, intelligent model routing, and async batch processing with working code and benchmark results.
📚RECOMMENDED BOOKS
Build a Large Language Model (From Scratch)
Sebastian Raschka
LLM Dev
Prompt Engineering for LLMs
Berryman & Ziegler
Prompting
AI Engineering
Chip Huyen
AI Eng
* Contains affiliate links
See all →