Skip to main content
In this lesson we simulate a common production problem for conversational AI: the token crisis. When you naively append every user and assistant turn to the prompt, the conversation history grows without bound. Over time this increases token counts, latency, and cost, and eventually exceeds the model’s context window — making the system slow, expensive, or unusable. This demo demonstrates how periodic memory summarization controls token growth. It uses plain Python (no external APIs), so you can focus on architecture and behavior rather than infrastructure. Overview
  • Problem: Unbounded prompt growth (the “token crisis”)
  • Solution: Periodic summarization to compress older context into long-term memory while keeping recent turns verbatim
  • Demo: Two simulations (naive vs managed) and a visual comparison
Step 1 — Setup Install the optional plotting package (matplotlib is used below):
Import required modules:
Step 2 — Shared state and token estimation We simulate a small conversational memory container similar to what agent frameworks use. The state contains:
  • messages: list of recent message dictionaries (role and content)
  • summary: compressed long-term memory (string)
  • turn_count: counter to decide when to summarize
For visualization we use a simple token estimator: roughly one token per four characters. This is an approximation for illustrative purposes only.
Step 3 — Naive chatbot: append every turn forever This naive implementation appends both the user message and the assistant response to messages and increments turn_count. Nothing is removed or compressed.
Step 4 — Simulate a long conversation (naive) We simulate a series of turns across several topics with intentionally verbose messages to make token growth visible.
Run the naive simulation and record estimated tokens after each turn:
You should observe a steady upward curve: every turn increases the prompt size and estimated token count. This is the token crisis. Step 5 — Introduce a summarization node A practical solution is to periodically summarize older parts of the conversation into a compact summary, keeping only the most recent turns in full. The pattern is:
  • Compress older history into a summary string
  • Keep recent messages verbatim (short-term context)
  • Reset turn_count
  • Trigger summarization when turn_count reaches a threshold
Below is a deterministic demo summarizer that extracts topic-like fragments and builds a compact summary. In production, you would typically call a language model for higher-quality, semantic summarization.
Periodic summarization is a common pattern in production chat architectures: compress older context into a summary while keeping recent turns verbatim to preserve immediate context.
This demo’s token estimator and summarizer are simplified for illustration. In production, use a model-based summarizer and an accurate tokenizer for your target LLM (e.g., tiktoken for OpenAI models).
Step 6 — Run the memory-aware (managed) version Run a second simulation that summarizes every 4 turns (threshold is tunable). We record token estimates and the summaries created.
With summarization, token growth becomes controlled: older parts of the conversation are compressed while recent turns remain detailed. This prevents the unbounded upward curve seen in the naive approach. Step 7 — Visual comparison (plot) Plot naive vs managed token growth to see the difference.
Step 8 — Constructing the prompt: inject the summary + recent messages A production-ready prompt pattern combines:
  • A system instruction
  • A compressed summary (older context)
  • The most recent messages (short-term context) verbatim
This pattern preserves long-term context efficiently while keeping the active context small.
Example output (approximate):
Step 9 — Takeaways
  • The token crisis: without context management, conversation history grows until it exhausts the model’s context window, increasing cost and latency.
  • Summarization-based memory: periodically compress older interactions into a compact summary and keep recent turns verbatim — this reduces tokens while preserving relevant context.
  • Production pattern: build prompts combining a system instruction, a compressed long-term summary, and a short-term verbatim buffer. This scales well across many turns.
Comparison: naive vs managed Links and References
  • Kubernetes Basics (example reference)
  • Use tokenizer libraries such as tiktoken for accurate token counts with OpenAI models
  • Consider model-based summarizers or fine-tuned summarization prompts for production-quality memory
Memory design is one of the most important architectural choices for production conversational systems: it directly impacts cost, latency, and session lifetime. Use periodic summarization (or other memory management strategies) to avoid the token crisis and keep conversations scalable.

Watch Video