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-06-22Advanced

Compressing Gemini API Chat History with Rolling Summaries — Designing Chatbots That Survive Hundreds of Turns

When a Gemini chatbot grows long enough, your bills balloon and one day a request hits the token ceiling. The rolling-summary pattern keeps long chats stable.

gemini-api277chat4historysummaryrolling-summaryproduction140

Premium Article

If you have shipped a Gemini-backed chatbot, you have probably seen the moment when one specific user starts getting silent failures while everyone else is fine. Dig into the logs and you find Request contains too many tokens repeating, and the cause turns out to be a chat history that simply got too long.

I have walked into this wall on a personal side project and on a Discord bot, and the fix that has consistently worked for me is an old idea applied carefully: rolling summaries. The implementation is small, the cost is predictable, and once it is in place you stop worrying about the user who chats every day.

Why a plain sliding window is not enough

The first instinct is to keep only the last N turns. The implementation takes ten lines, but it ruins the user experience. A user who told the bot their name eleven turns ago will hear the bot ask for it again, which feels broken. Pruning by recency alone throws away exactly the kind of information that makes a chat useful.

Rolling summaries solve this with a two-tier approach: older turns are compressed into a short paragraph that is kept in the prompt, while the most recent turns are preserved verbatim. The compressed portion stays roughly the same size no matter how long the conversation grows, so the total prompt budget stays bounded.

Architecture in three pieces

Three small functions are enough.

  • count_tokens(history) reports the current size of the history.
  • should_compress(history, threshold) decides whether it is time to compress.
  • compress(history, keep_recent) replaces the older portion with a summary and keeps the last few turns intact.

The two interesting questions are when to trigger compression and what to put in the summary. Pick the threshold based on cost rather than the model's hard limit. Gemini 2.5 Pro can hold a million tokens, but sending hundreds of thousands every turn is not financially realistic for a chatbot.

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
Turn a chatbot whose bill balloons and eventually hits the token ceiling into one whose input cost is bounded
Pre-empt the three production-only pitfalls — default-model swaps, summaries dropping facts, and the double-compression race — with working code
Encode the line between what is safe to summarize and what must never be summarized, so sessions stay stable across hundreds of turns
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-07-18
The Same gemini-flash-latest Pointed to Different Models in Different Regions
Alias resolution rolls out region by region. Send the same gemini-flash-latest to Tokyo and us-central1 and, for a few days, different models answer. Here is why that quietly invalidates your comparisons, and how a one-shot probe catches it.
API / SDK2026-07-15
Sample what you already accepted — an audit budget that catches silent quality drift
A confidence gate only ever looks at output the model hesitated on. Silent drift sinks into the batch that sailed through. Working from a fixed 30-minutes-a-day review budget, this walks through deriving detection time from the binomial, reallocating the same budget across risk strata, and catching slow decay with a cumulative monitor.
API / SDK2026-07-06
Measure a Managed Agent's Behavior Against Fixed Scenarios Before It Reaches Production
The public-preview Managed Agents run autonomously inside an isolated sandbox, so a small prompt or config change can quietly shift their behavior. Diffing the output once, the way you would for a single prompt, is not enough. Here is how to build a regression harness that runs fixed scenarios repeatedly and judges on pass rate, plus a shadow to canary to full promotion with automatic rollback, all with runnable Python.
📚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 →