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-05-14Advanced

Controlling thinking_budget in Gemini 2.5 Pro — Cut Costs by 70% Without Sacrificing Reasoning Quality

Leaving thinking_budget unset in Gemini 2.5 Pro leads to unexpected costs. This guide covers task-level budget design, dynamic control, and production monitoring with working Python code.

gemini-api277thinking-budget2gemini-2.5-pro13cost-optimization30indie-dev43python104

Premium Article

For an indie developer, API cost management is not a theoretical concern — it is a constraint that shows up as a monthly bill, and a mismanaged one can quietly threaten whether a service stays alive at all.

I found this out the hard way when I integrated Gemini 2.5 Pro into one of my apps shortly after its release. The first week's API bill came in at over three times what I had projected. The culprit: I had left thinking_budget unset, and the model was spinning up thousands of thinking tokens on requests that didn't need them at all.

This guide covers how thinking_budget actually works, how to build a task classifier that sets it dynamically, what the cost savings look like in real numbers, and how to add monitoring before things get out of hand.

Why Leaving thinking_budget Unset Is a Costly Mistake

Gemini 2.5 Pro runs an internal chain-of-thought process before producing its final response. The tokens consumed during this process are thinking tokens, and thinking_budget is the parameter that caps how many can be used per request.

The documentation says you can set it to 0 to disable thinking entirely. What it does not make entirely clear is what happens when you omit it. Based on my own testing in May 2026, omitting the parameter allows the model to automatically use up to the maximum budget — currently around 24,576 tokens per request.

A simple sentiment classification request — "is this review positive or negative?" — can trigger thousands of thinking tokens under the default behavior. Since thinking tokens are billed at a rate comparable to output tokens, this accumulates quickly across thousands of daily requests.

The Billing Structure That Makes This Matter

Gemini 2.5 Pro bills across three categories:

  • Input tokens — the text you send in
  • Output tokens — the final response the model generates
  • Thinking tokens — internal reasoning tokens (not included in the output)

Thinking tokens are billed at roughly the same rate as output tokens. This means if your final response is 150 tokens but 4,000 thinking tokens ran behind the scenes, your effective cost for that request is nearly 27x what the output tokens alone would suggest.

Checking Your Current Usage

Before changing anything, check how many thinking tokens your current requests are actually using:

import google.generativeai as genai
 
genai.configure(api_key="YOUR_GEMINI_API_KEY")
 
model = genai.GenerativeModel("gemini-2.5-pro")
 
# Run a representative sample request WITHOUT thinking_budget set
response = model.generate_content(
    "Classify the sentiment: 'The delivery was late but the product quality is excellent.'"
)
 
if hasattr(response, "usage_metadata"):
    meta = response.usage_metadata
    thinking_tokens = getattr(meta, "thoughts_token_count", 0) or 0
    output_tokens = meta.candidates_token_count or 0
    print(f"Output tokens:   {output_tokens}")
    print(f"Thinking tokens: {thinking_tokens}")
    print(f"Ratio:           {thinking_tokens / max(output_tokens, 1):.1f}x")

Expected output (uncontrolled):

Output tokens:   32
Thinking tokens: 4817
Ratio:           150.5x

If you see ratios above 10x on simple requests, you have a significant optimization opportunity.

Mapping Task Complexity to Budget Levels

Not every request needs the same reasoning depth. Through production use across several apps, I settled on a four-level classification:

  • Level 0 (thinking off, budget=0) — Purely mechanical tasks: JSON formatting, direct translations, template filling, simple lookups
  • Level 1 (light thinking, budget=1,024–4,096) — Basic judgment: sentiment analysis, category tagging, brief summarization
  • Level 2 (medium thinking, budget=8,192–16,384) — Multi-step reasoning: code debugging, business logic with multiple conditions, structured analysis
  • Level 3 (full thinking, budget=16,384–24,576) — Complex problem solving: architectural decisions, nuanced document analysis, creative planning

Setting thinking_budget: The Basic Pattern

import google.generativeai as genai
 
genai.configure(api_key="YOUR_GEMINI_API_KEY")
 
model = genai.GenerativeModel(
    model_name="gemini-2.5-pro",
    generation_config=genai.GenerationConfig(
        thinking_config=genai.types.ThinkingConfig(
            thinking_budget=4096  # Level 1: light thinking
        )
    )
)
 
response = model.generate_content(
    "Classify the sentiment of this review: 'Great product, fast shipping.'"
)
 
if hasattr(response, "usage_metadata"):
    meta = response.usage_metadata
    thinking_tokens = getattr(meta, "thoughts_token_count", 0) or 0
    print(f"Input tokens:    {meta.prompt_token_count}")
    print(f"Output tokens:   {meta.candidates_token_count}")
    print(f"Thinking tokens: {thinking_tokens}")

Expected output:

Input tokens:    28
Output tokens:   9
Thinking tokens: 211

One important nuance: thinking_budget is a ceiling, not a target. Setting budget=4096 does not mean 4,096 thinking tokens will be used — it means the model may use up to that many. If the model determines 211 tokens is sufficient, that is all it uses. This makes budget-setting a safe operation: you are not wasting tokens by setting a number higher than needed, you are simply allowing the model room to use more if it judges it necessary.

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
A four-level task classifier that assigns thinking_budget dynamically by request complexity
A three-tier Flash / Pro-light / Pro-full routing strategy and how to judge each setting
Production monitoring, weekly reports, and pre-flight batch cost estimation that keep spend predictable
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-04-28
Leveraging Gemini API's Cost Advantage for SaaS — How to Undercut Competitors by 50% and Still Profit
A deep analysis of Gemini API's cost structure with practical strategies to build a SaaS that's 50% cheaper than competitors while maintaining healthy margins. Includes P&L simulation and production code.
API / SDK2026-07-02
Routing Between Local Gemma 4 and the Gemini API Cut My Bill from ¥32,000 to ¥9,000 — A Production Hybrid Router Design
How I cut a ¥32,000/month Gemini API bill to the ¥9,000 range with hybrid inference: routing design, a full Python router, production pitfalls, and how Gemma 4 arriving on the Gemini API in July 2026 changes the decision.
API / SDK2026-06-22
Structured Product Image Analysis with the Gemini API — A Production Pipeline Built on Thousands of Photos
Turn a one-off image analysis script into a production pipeline that auto-generates tags, descriptions, and categories at scale — covering structured output, resumable batches, measured cost, and model routing learned from real indie-developer operation.
📚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 →