{"slug": "how-i-manage-context-windows-in-long-llm-conversations-without-losing-the-thread", "title": "How I Manage Context Windows in Long LLM Conversations Without Losing the Thread - By Gopi Gugan", "summary": "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.", "body_md": "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.\n\nEvery 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:\n\nOnce I started thinking in tokens instead of messages, the design got much simpler.\n\nThe 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:\n\nHere's the trimming function I use in Python before every LLM call:\n\n``` php\ndef trim_messages(messages: list[dict], max_tokens: int, count_tokens) -> list[dict]:\n    \"\"\"Keep system prompt + first user message + newest turns within budget.\"\"\"\n    system, rest = messages[0], messages[1:]\n    budget = max_tokens - count_tokens([system])\n\n    # Walk backwards from the newest message, keeping what fits\n    kept: list[dict] = []\n    for msg in reversed(rest):\n        cost = count_tokens([msg])\n        if cost > budget:\n            break\n        kept.append(msg)\n        budget -= cost\n\n    # Always keep the first user message if it survived, else re-add it\n    kept = list(reversed(kept))\n    if rest and rest[0] not in kept and count_tokens([rest[0]]) <= budget:\n        kept.insert(0, rest[0])\n\n    return [system] + kept\n```\n\nIt'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.\n\nTrimming 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:\n\nThis 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.\n\nThe 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:\n\nHumans handle being told the limits of a system. What frustrates them is a system that pretends it remembers everything and then doesn't.\n\nManaging 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.\n\nIf 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.", "url": "https://wpnews.pro/news/how-i-manage-context-windows-in-long-llm-conversations-without-losing-the-thread", "canonical_source": "https://dev.to/gopigugan/how-i-manage-context-windows-in-long-llm-conversations-without-losing-the-thread-by-gopi-gugan-58mi", "published_at": "2026-12-04 21:59:52+00:00", "updated_at": "2026-12-04 22:14:17.717182+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "ai-tools", "developer-tools"], "entities": ["Gopi Gugan", "FastAPI", "Postgres", "pgvector", "React", "TypeScript", "tiktoken"], "also_reported_by": [], "takeaway": "Budget the context window in tokens before every LLM call: keep the system prompt, first user message and newest turns, and summarize rather than delete middle history once a session outgrows the budget.", "recommendation": {"advice": "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.", "playbook": "llm-cost", "playbook_url": "https://wpnews.pro/playbooks/llm-cost"}, "alternates": {"html": "https://wpnews.pro/news/how-i-manage-context-windows-in-long-llm-conversations-without-losing-the-thread", "markdown": "https://wpnews.pro/news/how-i-manage-context-windows-in-long-llm-conversations-without-losing-the-thread.md", "text": "https://wpnews.pro/news/how-i-manage-context-windows-in-long-llm-conversations-without-losing-the-thread.txt", "jsonld": "https://wpnews.pro/news/how-i-manage-context-windows-in-long-llm-conversations-without-losing-the-thread.jsonld"}}