Skip to content

Module 04 · Lesson 4.2

Managing Context Windows and Conversation History

40 minUpdated 18 Nov 2026Part of State, Memory and Retrieval · AI Agent Development
On this page
  1. What you will learn
  2. Why a growing history needs managing
  3. Build a context budget
  4. Four ways to keep a history within budget
  5. Fit a history into a budget with Python
  6. Trade-offs, and how to test your trimming
  7. Conclusion and your next step
  8. Common errors and fixes
  9. Validation checklist
  10. Hands-on exercise
  11. Knowledge check
  12. Frequently asked questions
  13. References

Picture a suitcase with a strict weight limit. You cannot take everything. You decide first what must go in (passport, tickets), then fill the rest with the things you are most likely to use. An AI agent's context is a suitcase like that, and a long chat is a pile of clothes that keeps growing.

In this lesson you learn to give each part of the agent's context a budget, so the important parts always fit. You will see four ways to make a long history smaller, and the mistakes each one can cause. Most of the lesson needs no coding. A short Python example at the end shows a small function that fits a history into a budget.

What you will learn

  • Create a context budget that gives each part of the context its own share.
  • Choose between pinning, trimming, summarising and shrinking for a given piece of context.
  • Explain what can go wrong with a summary and how to check that it kept the key facts.
  • Run a short Python function that fits a message history into a budget.

Before you start

Why a growing history needs managing

In Context Design: What the Agent Needs at Each Step you met the context window: the limit on how much text a model can read in one call. Text is counted in tokens, which are small pieces of words. You also met the simplest fix, which is to keep only the last few messages.

Keeping the last N messages is a good start, but it is blunt. It counts messages, not tokens, so one huge tool result can still overflow the window. It also throws away the oldest messages, which often hold the most important fact, such as the order number the customer gave at the start.

A better plan has two ideas. First, decide in advance how much room each part of the context may use. Second, protect the facts that matter before you trim anything.

Build a context budget

A context budget is a plan for how many tokens each part of the request may use. Think of a monthly household budget: rent, food and savings each get a share, so one big shopping trip cannot eat the rent.

The parts of an agent request are the instructions, pinned facts, recent messages, tool results and room for the answer. The last one is easy to forget. If you fill the whole window with input, the model has no space left to reply.

PartExample shareRule
Instructions1,000 tokensFixed. Never cut.
Pinned facts300 tokensSmall and always included.
Recent messages2,000 tokensNewest first. Trim from the old end.
Tool results1,200 tokensShrink each one after it has been used.
Room for the answer500 tokensReserved. Never filled with input.
A made-up budget for the Quillfeather agent. The numbers are examples. Take your real limit from your model provider and test with your own chats.

Leave a safety margin

Keep some budget unspent. Your estimate can be wrong, and tool results vary in size. A margin of ten or twenty percent means a bad guess becomes a small problem and not a failed request.

Four ways to keep a history within budget

You do not have to pick only one. A practical agent often uses all four, in this order of importance.

1. Pin the key facts

To pin a fact means to keep it in its own small field, outside the message list, and add it to every request. Think of the card taped to a hospital bed with the patient's name and allergies. It does not move when the paperwork pile changes.

For Quillfeather, pin the order number and the customer's request in one line each. Your code can fill these when it first sees them. Because they are pinned, trimming old messages can never lose them.

2. Keep the newest messages

Add messages from newest to oldest until the budget for messages is used. The newest messages usually matter most, because the customer's latest question depends on the reply just before it. Count tokens, not messages, so one long message cannot sneak through.

3. Replace old turns with a summary

A summary is a short note that stands in for older messages. For example, ten old messages become: "Customer asked about QF-1042, was told it is dispatched, then asked about changing the address." It keeps the thread without keeping every word.

Someone has to write the summary. It is often the model, in a separate call, which costs tokens too. Your code can also build a simple one from pinned fields. Whichever you choose, treat the summary as a draft that needs checking.

  • Lost details. A short summary drops things. If the customer's address was in the old messages and not in the summary, the agent no longer knows it.
  • Invented details. A model-written summary can add something that was never said, and later steps then treat it as true.
  • The check. After summarising, make sure every pinned fact still appears in the context. A simple code check, such as "does the order number appear?", catches the worst losses.

4. Shrink tool results after use

A tool result is often much larger than what you need from it. A full order record has dozens of fields, but the customer asked only about the status. Once the agent has used the result, replace it with the few fields that mattered, such as status and estimated_delivery.

Do this carefully. If a later step might need another field, look the order up again with the tool. That is cheap, and it is safer than keeping stale copies.

Fit a history into a budget with Python

The function below keeps the pinned facts, then adds messages from newest to oldest until the budget is used. It uses a very rough token estimate, so it needs no model and runs offline. We run it on a ten-message history with two different budgets.

Pythonfit_history.py
def rough_tokens(text):
    # Rough rule for this example only: about 1.5 tokens per word.
    return int(len(text.split()) * 1.5) + 1


def fit_history(pinned, messages, budget):
    used = sum(rough_tokens(p) for p in pinned)  # pinned facts are always kept
    kept = []
    for message in reversed(messages):  # newest first
        cost = rough_tokens(message)
        if used + cost > budget:
            break
        kept.insert(0, message)
        used += cost
    return kept, len(messages) - len(kept), used


pinned = ["Order: QF-1042", "Request: where is my parcel?"]
messages = [f"Message {i}: " + "word " * (i + 2) for i in range(1, 11)]

for budget in (120, 60):
    kept, dropped, used = fit_history(pinned, messages, budget)
    print(f"budget={budget}: kept {len(kept)}, dropped {dropped}, about {used} tokens")
    print("  oldest kept:", kept[0].split(":")[0], "| newest kept:", kept[-1].split(":")[0])

Standard library only. The token estimate is a rough rule for this example, not a real tokenizer.

What each part does

  • rough_tokens guesses the size of a text by counting words and multiplying. The factor 1.5 is a made-up rule for this example. A real tokenizer gives different numbers.
  • used starts with the cost of the pinned facts. They are counted first and are never dropped.
  • reversed(messages) walks the list from the newest message to the oldest.
  • if used + cost > budget: break stops as soon as the next message would not fit. Everything older is dropped, so the kept messages always form one unbroken run.
  • kept.insert(0, message) puts each kept message at the front, so the kept list stays in time order.
  • The function returns the kept messages, the number dropped and the estimated total.
  • messages is built by a loop: ten messages, each a little longer than the last.
OutputCaptured from a real run
budget=120: kept 6, dropped 4, about 120 tokens
  oldest kept: Message 5 | newest kept: Message 10
budget=60: kept 2, dropped 8, about 54 tokens
  oldest kept: Message 9 | newest kept: Message 10

With the larger budget, six messages fit and four old ones are dropped. With the smaller budget, only the last two fit. In both runs the pinned order number and request are still in the context, because they were counted first.

Trade-offs, and how to test your trimming

Every way of shrinking history trades something away. Know what you give up, then test it.

MethodWhat you gainWhat you risk
Pin factsKey facts never vanishToo many pins fill the budget
Keep newest messagesSimple and predictableOld but important turns are lost
Summarise old turnsKeeps the thread of a long chatLost or invented details, extra cost
Shrink tool resultsFrees a lot of spaceA later step may need a field you removed
Start with pinning and newest-first. Add summaries only when chats are long enough to need them.

A simple test for your trimming

  1. Write a long fake chat where the order number appears only in the first message.
  2. Run your trimming with a small budget.
  3. Check that the order number is still in the final context.
  4. Check that the instructions are untouched and the answer room is still reserved.

For cost reasons, see also How to Reduce AI Token Costs When Coding with Claude or ChatGPT. Smaller contexts cost less, but never at the price of a lost fact.

Conclusion and your next step

A long chat will outgrow any context window, so plan for it. Give each part a budget, protect the instructions and the pinned facts, keep the newest messages, summarise the old ones with care and shrink tool results once they are used. Then test that the facts that matter survive.

Your next step: write a context budget for an agent you are planning, with a share for each of the five parts. Then continue to Retrieval-Augmented Generation for Agent Knowledge, where you learn how to bring in the right facts from a knowledge base instead of keeping everything in the chat.

For background on the limits themselves, read Understanding Context Windows and Token Limits, or look up unfamiliar words in the Glossary of AI Engineering and Agent Terms.

Common errors and how to fix them

After a long chat, the agent asks again for the order number.

Why it happens: The number was only in an old message, and trimming removed it.

Fix: Pin the order number and the customer's request in their own field that is added to every request.

Requests fail with a context-length error even though only a few messages were kept.

Why it happens: Messages were counted, not tokens. A few large tool results filled the window.

Fix: Budget in tokens, shrink tool results after use, and leave a safety margin.

The model's answer is cut off.

Why it happens: The input filled the whole window, with no room reserved for the reply.

Fix: Reserve a share of the budget for the answer before you fill the rest.

The agent repeats a detail that the customer never said.

Why it happens: A model-written summary invented the detail, and later steps trusted it.

Fix: Treat summaries as drafts. Check pinned facts against them, and keep summaries short and factual.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Plan the context budget for a library helper

A town library has an agent that helps members renew books. Write a context budget and a trimming plan for it, then say how you would test that nothing important is lost in a long chat.

You will need

  • The agent has one tool that lists a member's loans. A typical result has 30 fields per loan and up to 15 loans.
  • Members often give their library card number once, at the start.
  • The instructions are about one page of text.
  • Chats sometimes run to 40 messages.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Which part of the budget will the loans result threaten most?
  • What would happen if the card number were lost after message 20?
  • Do you need a summary at 40 messages, or is newest-first enough?
Show a model answer

A strong answer gives each part a share, with the largest going to recent messages and tool results, and a small fixed share to instructions and pinned facts. The card number and the member's current request are pinned. After the loans result has been used, it is replaced with just the title and due date of the loans being discussed, and the agent calls the tool again if a different field is needed. Newest-first trimming handles most chats. A short summary is added only when a chat passes a set length, and the summary is checked to contain the pinned card number. The test uses a 40-message fake chat with the card number only in message one and confirms the number is still in the final context, the instructions are intact and the answer room is reserved.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Why pin the order number instead of leaving it in the message history?
    Show the answer and explanation

    Answer: B. Pinning protects the fact from trimming. It does not make the text smaller, so the first option is wrong. The model reads all the text you send, which rules out the third.

  2. 2.What can go wrong when a model writes a summary of old messages?
    Show the answer and explanation

    Answer: A. Summaries are short on purpose, so details are lost, and a model can add details of its own. The second option is the opposite of the goal. The third is not true, since summaries can sit alongside tool use.

  3. 3.Which part of the context budget should never be cut to make room?
    Show the answer and explanation

    Answer: B. The instructions hold the role, limits and output contract. Old messages and used tool results are the normal things to shrink, which makes them the tempting answers, but they are meant to be reduced.

Frequently asked questions

What is a context window in simple words?

It is the limit on how much text a model can read in one request, including your instructions, the chat so far and the space for its reply. Anything beyond the limit cannot be sent. The exact limit depends on the model, so check your provider's current page.

How do I count tokens before sending a request?

Use the token-counting tool your provider offers, then compare the result with the model's limit. For planning, a rough estimate is fine. Keep a safety margin because estimates can be off.

Should I send the whole chat history every time?

For short chats, yes, if it fits. For long chats it costs more and can overflow the window. Keep the pinned facts, the newest messages and, if needed, a short summary of the older part.

Is it safe to let the model summarise old messages?

It is useful but not perfectly safe. Summaries can drop or invent details. Keep important facts pinned outside the summary and check that they are still present after summarising.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.