I'm Gopi Gugan, a software engineer building AI features with FastAPI, Postgres/pgvector, and React/TypeScript — and if you want to see more of my work, it's at gopigugan.ca. The first time I built a chat feature on top of an LLM, I sent the whole conversation history with every request. It worked beautifully for five messages. Then a user had a long session, the token count crept up, the API rejected the request for exceeding the context window, and the chat just stopped. That's when I learned that managing context is a real engineering problem — not something the model handles for you.

The context window is a budget, not a feature

Every model has a hard limit on how much text it can take in one request, and every token you send costs money and latency. I treat the context window like a budget:

  • The system prompt is non-negotiable. It's the first thing in every request, and I never drop it to save space.
  • Recent messages matter most. The last few turns usually carry the actual question and the answer the user is following up on.
  • Old messages are the most expensive and least useful. A 40-message-old greeting is costing tokens and contributing nothing.
  • Retrieved context competes with history. In my RAG app, pgvector chunks and conversation history draw from the same budget — I have to decide the split deliberately.

Once I started thinking in tokens instead of messages, the design got much simpler.

Trim from the middle, never from the ends

The naive fix is to keep only the last N messages. That works, but it has a failure mode: the model loses the original question the user asked, and starts answering a different conversation. My rule now is to protect both ends:

  • Keep the system prompt, always.
  • Keep the first user message. It usually states the goal — "help me debug this query" — and everything after it is a follow-up.
  • Keep the most recent turns. That's where the current state of the conversation lives.
  • Trim the middle first. The turns between the opening and the recent ones are the first to go.

Here's the trimming function I use in Python before every LLM call:

def trim_messages(messages: list[dict], max_tokens: int, count_tokens) -> list[dict]: """Keep system prompt + first user message + newest turns within budget.""" system, rest = messages[0], messages[1:] budget = max_tokens - count_tokens([system]) # Walk backwards from the newest message, keeping what fits kept: list[dict] = [] for msg in reversed(rest): cost = count_tokens([msg]) if cost > budget: break kept.append(msg) budget -= cost # Always keep the first user message if it survived, else re-add it kept = list(reversed(kept)) if rest and rest[0] not in kept and count_tokens([rest[0]]) <= budget: kept.insert(0, rest[0]) return [system] + kept 

It's simple, it runs before every call, and it means the model never sees a request that blows the window. A token counter like tiktoken makes count_tokens cheap and exact — I never guess at token counts from character length in production.

Summarize instead of deleting

Trimming works until a user has a genuinely long session — a debugging conversation that spans an hour. Deleting the middle means the model forgets what it already tried, and it starts suggesting the same failed fix again. For those cases I summarize:

  • When history passes a threshold, I ask the model to summarize it. A short summary — what the user is trying to do, what we've tried, what's still open — replaces the trimmed middle.
  • The summary is a message in the history, not a separate store. It sits right after the system prompt, so the model treats it as context.
  • I keep the summary factual, not interpretive. "Tried approach A, got error X" is useful. "The user seems frustrated" is not.
  • Summaries get summarized too. A long session produces several summaries; I roll them into one when the summary itself gets too long.

This is the part most people skip, and it's the difference between a chat that feels like it remembers you and one that resets every ten messages.

Tell the user what's happening

The worst version of context management is silent: the model quietly forgets something and the user has no idea why the answer changed. I'm honest about it in the UI:

  • When old messages are trimmed, I show it. A small note — "earlier messages in this conversation were summarized" — sets the right expectation.
  • When the conversation is summarized, I let the user see the summary. If the summary is wrong, they can correct it, which is far better than the model silently working from a bad one.
  • I give the user a reset. A "start a new conversation" button is a feature, not an admission of failure. A fresh context window often beats a heavily summarized one.

Humans handle being told the limits of a system. What frustrates them is a system that pretends it remembers everything and then doesn't.

The honest summary

Managing a context window means budgeting tokens deliberately, trimming from the middle while protecting the system prompt, the opening question, and the recent turns, and summarizing instead of deleting when a session runs long. The model won't do any of this for you — if you send the whole history every time, you'll hit the limit at the worst possible moment, mid-conversation with a real user. Budget the window like you'd budget anything else in production, and tell the user when history has been compressed. A chat that forgets gracefully is a much better product than one that crashes silently.

If you're building a chat feature and still sending the full history with every request, add the trimming step first. It's an afternoon of work, and it's the difference between a feature that works in a demo and one that works on a Tuesday night with a user on message forty-seven.