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.
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:
Once I started thinking in tokens instead of messages, the design got much simpler.
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:
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])
kept: list[dict] = []
for msg in reversed(rest):
cost = count_tokens([msg])
if cost > budget:
break
kept.append(msg)
budget -= cost
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.
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:
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.
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:
Humans handle being told the limits of a system. What frustrates them is a system that pretends it remembers everything and then doesn't.
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.