cd /news/large-language-models/how-i-manage-context-windows-in-long… · home › topics › large-language-models › article
[ARTICLE · art-182108] src=dev.to ↗ pub= topic=large-language-models verified=true sentiment=↑ positive

How I Manage Context Windows in Long LLM Conversations Without Losing the Thread - By Gopi Gugan

Software engineer Gopi Gugan described a token-budgeting approach to managing LLM context windows in long chat sessions, built on FastAPI, Postgres/pgvector and React/TypeScript. His method keeps the system prompt, the first user message and the newest turns within a token budget, summarizes rather than deletes middle history when sessions run long, and surfaces compression to the user in the UI. He recommends counting tokens exactly with tiktoken and trimming before every LLM call to avoid requests that exceed the window mid-conversation.

recommendation

Count tokens exactly with tiktoken and trim history to a fixed budget before each call, preserving the system prompt and opening question, and summarize older turns instead of dropping them.

more in playbook: Controlling LLM cost
by read3 min views7 publishedDec 4, 2026

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.

── more in #large-language-models 4 stories · sorted by recency
── more on @gopi gugan 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
→ Live at https://your-agent.zahid.host ✓
Get free account → Pricing
from €0/mo · no card required
LIVE [news/how-i-manage-context…] indexed:0 read:3min 2026-12-04 · —