Skip to content
Stream Gemini Thinking: Build a Show-Your-Work CLI — ContentBuffer guide

Stream Gemini Thinking: Build a Show-Your-Work CLI

K
Kodetra Technologies··8 min read Intermediate

Summary

Stream Gemini's thought summaries live, control reasoning effort, and track thinking-token cost.

Why "thinking" suddenly matters

On June 22, 2026 Google shipped Gemini 2.5 Pro with Deep Think and made it generally available on the API. Deep Think leans on extended, parallel reasoning: the model explores several lines of attack, weighs them, and only then answers. The launch put one question in front of every developer at once: how do I actually see and control that reasoning from code, instead of staring at a spinner?

The answer is the Interactions API, which became generally available alongside the launch and is now the recommended surface for the Gemini 3 and 2.5 thinking models. Unlike the old generateContent call, it treats reasoning as a first-class thing: every response is a list of steps, and the model's reasoning shows up as dedicated thought steps that you can stream as they happen.

In this guide you will build a small command-line tool that streams the model's thought summaries live, prints the final answer underneath, lets you turn the reasoning effort up or down, and reports exactly how many thinking tokens you paid for. It is the developer version of toggling "Deep Think" in the app, with the cost meter switched on.

Prerequisites

  • Python 3.10 or newer.
  • A Gemini API key from Google AI Studio, set as the GEMINI_API_KEY environment variable.
  • The google-genai SDK (install command below).
  • Basic comfort reading Python loops. No prior Gemini experience required.

Step 1 - Install and make a thinking call

Install the SDK and set your key:

pip install -U google-genai
export GEMINI_API_KEY="your_key_here"

Now the simplest possible call. Notice you call client.interactions.create, not the old generate_content. The model picks how much to think on its own, and output_text is a convenience that concatenates the final answer:

from google import genai

# The client reads GEMINI_API_KEY from your environment.
client = genai.Client()

interaction = client.interactions.create(
    model="gemini-2.5-pro",
    input="What is the sum of the first 50 prime numbers?",
)

print(interaction.output_text)

Example output:

The sum of the first 50 prime numbers is 5117.

That works, but the reasoning is invisible. The model still thought hard about the problem; you just did not get to watch. Next we surface it.

Step 2 - Surface the thought summaries

Set thinking_summaries to "auto" and the response carries thought steps with human-readable summaries of what the model was doing. Each thought step has two fields: a signature (an encrypted handle to the model's internal reasoning state, always present) and an optional summary (text and sometimes images). Walk the steps array and split the thoughts from the final answer:

from google import genai

client = genai.Client()

interaction = client.interactions.create(
    model="gemini-2.5-pro",
    input="What is the sum of the first 50 prime numbers?",
    generation_config={"thinking_summaries": "auto"},
)

for step in interaction.steps:
    if step.type == "thought":
        # A thought step always has a signature, but the summary can be empty.
        if step.summary:
            for block in step.summary:
                if block.type == "text":
                    print("THOUGHT:", block.text)
    elif step.type == "model_output":
        for block in step.content:
            if block.type == "text":
                print("ANSWER:", block.text)

Example output (trimmed):

THOUGHT: Listing primes from 2 upward and keeping a running total...
THOUGHT: 50th prime is 229; summing the sequence carefully.
ANSWER: The sum of the first 50 prime numbers is 5117.

Two things to internalize here. First, the summary is a summary, not the full chain of thought; the model generates far more reasoning internally than it shows. Second, summary can be empty even on a valid thought step, so the if step.summary: guard is not optional.

Step 3 - Stream it live (the CLI)

Waiting for a slow, high-effort answer with no feedback is a poor experience. Pass stream=True and the Interactions API sends Server-Sent Events. The deltas you care about arrive as step.delta events with two delta types: thought_summary (incremental reasoning text) and text (the answer). Here is the full tool - save it as think.py:

#!/usr/bin/env python3
"""think.py - stream Gemini's reasoning, then its answer."""
import sys
from google import genai

client = genai.Client()

def stream_thinking(prompt, model="gemini-2.5-pro", thinking_level="high"):
    thoughts, answer = "", ""
    stream = client.interactions.create(
        model=model,
        input=prompt,
        generation_config={
            "thinking_level": thinking_level,   # how hard to think
            "thinking_summaries": "auto",        # emit summaries of the thoughts
        },
        stream=True,
    )
    for event in stream:
        if event.event_type != "step.delta":
            continue
        delta = event.delta
        if delta.type == "thought_summary":
            if not thoughts:
                print("\n=== THINKING ===")
            text = delta.content.text or ""
            print(text, end="", flush=True)
            thoughts += text
        elif delta.type == "text" and delta.text:
            if not answer:
                print("\n\n=== ANSWER ===")
            print(delta.text, end="", flush=True)
            answer += delta.text
    print()
    return thoughts, answer

if __name__ == "__main__":
    q = " ".join(sys.argv[1:]) or "Explain why the sky is blue."
    stream_thinking(q)

Run it:

python think.py "Three friends - Alice, Bob, Carol - each live in a different colored house (red, green, blue). Alice is not in red. Bob is not in green. Carol is not in red or green. Who lives where?"

Example output (trimmed):

=== THINKING ===
Carol can't be red or green, so Carol must be blue. That frees red
and green for Alice and Bob. Alice can't be red, so Alice is green and
Bob takes red...

=== ANSWER ===
Alice: green house
Bob: red house
Carol: blue house

You now see the reasoning scroll in real time, then the answer appears underneath. The key detail is the guard if event.event_type != "step.delta": continue - the stream also emits lifecycle events like interaction.created, step.start, step.stop, and interaction.completed, and you would crash if you treated those as deltas.

Step 4 - Control the reasoning effort

Thinking is not free, and not every prompt deserves maximum effort. The thinking_level parameter dials it from minimal through high. Use high for hard coding, math, and multi-step planning; drop to low or minimal for lookups and classification:

# Spend fewer tokens on an easy task by dialing thinking down.
interaction = client.interactions.create(
    model="gemini-2.5-pro",
    input="List 3 famous physicists and their key contributions.",
    generation_config={"thinking_level": "low"},
)
print(interaction.output_text)

Support differs by model, so check before you hardcode a level:

ModelDefault thinkingLevels supported
gemini-3.1-pro-previewOn (high)low, medium, high
gemini-3-flash-previewOn (high)minimal, low, medium, high
gemini-3-pro-previewOn (high)low, high
gemini-2.5-proOnlow, medium, high
gemini-2.5-flashOnlow, medium, high
gemini-2.5-flash-liteOfflow, medium, high

Note that gemini-2.5-pro - the model that just gained Deep Think - exposes low, medium, and high, while gemini-3-pro-preview only offers low and high. There is no boolean "deep think on" switch in the API; high is how you ask for the heaviest reasoning.

Step 5 - Pay attention to thinking tokens

This is the line item that surprises people. The summaries you stream are short, but you are billed for the full internal reasoning, which is far longer. The usage object breaks it out, and thinking tokens are charged at the output rate:

u = interaction.usage
print("Input tokens:   ", u.total_input_tokens)
print("Thinking tokens:", u.total_thought_tokens)
print("Output tokens:  ", u.total_output_tokens)

# Thinking tokens are billed at the OUTPUT rate even though you only
# see the short summaries. Always confirm live rates in the pricing docs.
PRICE_IN  = 2.50   # USD per 1M input tokens
PRICE_OUT = 15.00  # USD per 1M output tokens (also applies to thinking tokens)
cost = (u.total_input_tokens / 1e6) * PRICE_IN \
     + ((u.total_thought_tokens + u.total_output_tokens) / 1e6) * PRICE_OUT
print(f"Approx cost: ${cost:.5f}")

Example output:

Input tokens:    62
Thinking tokens: 297
Output tokens:   171
Approx cost: $0.00717

In that small run the model thought for 297 tokens but only emitted 171 tokens of answer - so reasoning was the majority of the output bill. On a high effort prompt the ratio swings further. The takeaway: treat thinking_level as a budget knob, and log total_thought_tokens in production so a single hard prompt does not quietly cost 5x what you expected.

Worked example - a stateful multi-turn assistant

Most real tools are conversations, not one-shots. Reasoning continuity matters: the model needs its earlier thought signatures to keep building on what it already worked out. The simplest correct approach is stateful mode - set store=True, then pass previous_interaction_id on the next turn. The server replays the prior thoughts and signatures for you:

# Multi-turn the easy way: let the server keep the reasoning state.
first = client.interactions.create(
    model="gemini-2.5-pro",
    input="Plan a 3-stop road trip in Japan. Start with Tokyo.",
    generation_config={"thinking_summaries": "auto"},
    store=True,                       # persist this interaction
)

followup = client.interactions.create(
    model="gemini-2.5-pro",
    input="Add a second stop known for hot springs.",
    previous_interaction_id=first.id,  # continue the same reasoning thread
    store=True,
)
print(followup.output_text)

If you instead manage history yourself (stateless mode, passing the full input list each turn), you take on a sharp obligation: you must resend every thought block exactly as you received it, signatures included. Drop them and the model loses its reasoning thread, and multi-turn quality silently degrades. For most apps, let the server hold state with store=True and skip that whole class of bug.

Common pitfalls

  • Treating lifecycle events as deltas. The stream emits interaction.created, step.start, step.stop, and interaction.completed alongside step.delta. Filter for the event type you want or you will hit attribute errors.
  • Assuming every thought has a summary. A thought step can carry only a signature and no summary - common on simple prompts or when summaries are disabled. Always guard with if step.summary:.
  • Mistaking summaries for the full reasoning. Summaries are a readable digest. You pay for the full hidden thoughts, reported in total_thought_tokens, not for the short summary you see.
  • Forgetting that thinking is billed at the output rate. A cheap-looking prompt can run up real cost on high effort. Log thinking tokens and cap the level for routine work.
  • Dropping thought blocks in stateless mode. If you build the input history yourself, you must resend every thought block and its signature, or reasoning continuity breaks across turns.
  • Hardcoding a thinking level the model does not support. minimal only exists on some models; gemini-3-pro-preview has no medium. Check the table before you ship.

Quick reference

What you wantHow to get it
Call a thinking modelclient.interactions.create(model=..., input=...)
Show reasoning summariesgeneration_config={"thinking_summaries": "auto"}
Stream livestream=True, then read step.delta events
Reasoning delta typedelta.type == "thought_summary"
Answer delta typedelta.type == "text"
Set reasoning effortgeneration_config={"thinking_level": "high"}
Count thinking costinteraction.usage.total_thought_tokens
Continue a conversationstore=True + previous_interaction_id

Next steps

  • Add a per-task router that picks thinking_level from the prompt type to keep average cost down.
  • Pipe thought_summary text to a separate panel in a web UI so users can expand or collapse the model's reasoning.
  • Combine thinking with function calling so the model can reason, call a tool, and reason again - the thought steps interleave with tool steps in the same list.
  • Log total_thought_tokens per request to a metrics backend and alert when a single call exceeds your budget.

Verify model names, supported thinking levels, and current pricing against the official Gemini API thinking docs, since these move quickly.

Comments

Subscribe to join the conversation...

Be the first to comment

Found this useful?

Get new AI guides for builders by email. Free.

Join 3,604 newsletter subscribers.

Also get