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

> Source: <https://dev.to/gopigugan/how-i-manage-context-windows-in-long-llm-conversations-without-losing-the-thread-by-gopi-gugan-58mi>
> Published: 2026-12-04 21:59:52+00:00

**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 the playbook "Controlling LLM cost": <https://wpnews.pro/playbooks/llm-cost>

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](https://www.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:

``` php
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.

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.
