Short-Term Memory: Keep a Long Run Small
Everything an agent knows during a run sits in one list of messages, and that list is sent to the model again with every call. Each step makes it longer, so a long run gets slower, costs more and leaves the model less able to find what matters in it. This page shows how to measure that growth and how to keep the list small by emptying old tool results, without breaking the rules the chat API sets for the list and without taking away what the agent still needs.
The transcript is the memory of one run
A chat API does not remember earlier calls. In Chat Completions your program keeps the conversation itself: it stores the list of messages, called the transcript, and sends the whole list with every request. The model reads that list from the start each time it is called. Whatever the list holds, the model can use: the instructions, the customer's request, every tool call it made and every result it got back. Whatever the list does not hold, the model has never seen.
That makes the transcript the short-term memory of the agent: a working memory that lasts as long as one run. When the run ends and the list is thrown away, the memory goes with it. A support agent that read a refund policy in one run will not know it in the next unless something outside the transcript carries it over.
Here is the transcript of a short run in which an agent answers a customer about a broken order. The last column gives the size of each message in characters.
| # | role | what it holds | characters |
|---|---|---|---|
| 1 | system | the instructions of the agent | 1,200 |
| 2 | user | Order A-1042 arrived broken. Can I get a refund? | 60 |
| 3 | assistant | tool call: search_help("refund damaged") | 90 |
| 4 | tool | five matching help pages, each with its id | 400 |
| 5 | assistant | tool call: read_page("refund-damaged-item") | 80 |
| 6 | tool | the full text of that help page | 3,500 |
| 7 | assistant | tool call: get_order("A-1042") | 70 |
| 8 | tool | the order record | 600 |
Two things stand out. The tool results (rows 4, 6 and 8) are most of the text, far more than the request itself. And nothing in the list is ever removed by the loop: each step only appends.
True or false?
After the model has read a help page once, it keeps the page in mind for the later calls of the run, even if the page is no longer in the messages.
False. The model keeps nothing between calls. It knows the page in a later call only if the page, or something that stands for it, is still in the messages that call sends.
A fact the agent learned in one run is gone in the next run unless the program stores it somewhere outside the transcript.
True. The transcript lives for one run. A new run starts from a new list, so anything to keep has to be saved and brought back by the program.
Why each call is larger than the last
An agent loop calls the model, runs the tool calls of the reply, appends the calls and their results to the transcript and calls the model again. The input of each call is therefore the input of the previous call plus everything the last step added. In the run above, the four calls send these amounts:
- call 1
- call 2
- call 3
- call 4
- instructions and request
- tool calls
- tool results
The transcript ends at 6,000 characters, but the model was sent 14,340 characters in total, because the instructions went out four times and the help page went out twice. The amount sent over a whole run grows faster than the transcript. If every step adds a result of about the same size \( r \) to a start of size \( s \), the input of call \( k \) and the total over \( n \) calls are:
input of call k
sent over n calls
The second term grows with the square of the number of steps: twice as many steps send about four times as much tool output.
Each single call also has a hard limit. The context window is the maximum number of tokens one request may use, input and output together. The tool definitions count against it too, since they are sent with every call.
Measuring the size
To act on the size, the program needs it before it makes the call. A simple measure is the length of the messages written out as JSON, which is close to what goes over the wire:
import json
def transcript_size(messages: list[dict]) -> int:
"""Characters of the messages as they are sent."""
return sum(len(json.dumps(m, ensure_ascii=False)) for m in messages)Characters are not tokens, but the two grow together. A character count needs no tokenizer and works the same for every provider. An exact token count is harder to get: it depends on the tokenizer of the model. Even a tokenizer library gives only an estimate for chat messages, because the way messages are turned into tokens can change from model to model. Logging transcript_size(messages) before each call shows the curve of a run, and the same number can decide when to act.
True or false?
If a run takes twice as many steps, and each step returns a result of similar size, the model is sent about twice as much text in total.
False. Each call resends all earlier results, so the total sent grows with the square of the number of steps: about four times as much.
The size of the transcript can be computed before a call, from the messages the program is about to send.
True. The program holds the list, so it can measure it at any time. The usage in a reply only tells you afterwards.
Context rot: more context, worse recall
Staying inside the context window is not enough. A model does not use everything in its context equally well, and it gets worse at it as the context grows. This decline is called context rot: as the number of tokens in the context grows, the model's ability to recall and use the information in it decreases, well before the window is full.
The clearest evidence is a 2025 technical report by Chroma that tested 18 models from several families on deliberately simple tasks. Across all its experiments, performance went down as the input got longer. Two of its results fit an agent run closely:
The report also found that a single distractor, a passage that resembles the answer but is not it, lowers accuracy, and that four distractors lower it further. Old tool results are exactly that kind of text: five help pages about refunds, of which one was the right one, or the record of an order the customer mentioned first and later corrected.
One explanation, given by Anthropic's engineering team, is that a model has a limited attention budget. The model relates every token to every other token, so \( n \) tokens make \( n^2 \) pairs, and each new token takes a share of the model's attention. The result is a gradient, not a cliff. There is no size at which a run suddenly fails; each extra page of old output makes the next decision a little less reliable.
Context rot is not the same finding as lost in the middle, a 2023 study which showed that models use information best at the start or the end of a long input and worst in its middle. That study is about where the relevant text sits; context rot is about how much other text surrounds it. Both point to the same practice: keep in the transcript what the next decisions need, and little else.
True or false?
As long as a run stays inside the context window, the model uses everything in the transcript equally well.
False. Recall and use decline as the context grows, even far below the limit, and similar but irrelevant text makes it worse.
A model that scores close to perfect at finding one planted sentence in a long text can still do worse on a real task as the input grows.
True. Finding one exact sentence is an easy test. Chroma notes that it underestimates what long-context tasks need in practice.
Clearing old tool results
Once the model has read a tool result and acted on it, the raw text is rarely needed again. The search listing led to a page; the page led to a decision. Yet both stay in the transcript and are resent with every call. Clearing old tool results replaces the content of those results with a short marker and leaves everything else as it was. It is the lightest way to shrink a transcript: it needs no model call and its result is predictable.
{
"role": "tool",
"tool_call_id": "call_2",
- "content": "Refunds for damaged items. If an item arrives damaged, ... (3,500 characters)"
+ "content": "[old result cleared; call the tool again if you need it]"
}What makes this safe is the identifier. The assistant message just before the result still holds the call, read_page("refund-damaged-item"), so the model can see which page it read and fetch it again with the same call if a later step needs the details. Clearing loses the text, not the way back to it. A result is a good candidate for clearing when it is old, when the model has already used it, and when a tool can return it again by its id. A result that cannot be fetched again should be kept, or reduced to the facts it contributed.
Here is a version that keeps the newest results whole and clears the rest, with every message stored as a dictionary. It builds a new list, so the program can still keep the full record for its own log:
CLEARED = "[old result cleared; call the tool again if you need it]"
def clear_old_tool_results(messages: list[dict], keep: int = 2) -> list[dict]:
tool_positions = [i for i, m in enumerate(messages) if m["role"] == "tool"]
old = tool_positions[: max(0, len(tool_positions) - keep)]
cleared = list(messages)
for i in old:
cleared[i] = {**messages[i], "content": CLEARED}
return clearedRun before every call, or only when transcript_size passes a threshold, this turns the growth from a steady climb into a slow one. With a start of 1,300 characters, steps of about 3,100 characters and the two newest results kept:
characters against call
- nothing cleared
- old results cleared
Clearing has costs. When the model does need a cleared result, it spends a step fetching it again. And some providers cache the beginning of a prompt that repeats between calls. Clearing edits a message inside that repeated part, so the cache stops matching from the first edited message onwards. Clearing in batches, when the size passes a threshold, keeps the edits rare. Some providers also offer clearing on their side as a feature of their own API; with a plain Chat Completions call the program edits its own list, as above.
True or false?
After a result is cleared, the model can no longer tell which item it had looked up.
False. The assistant message with the call stays, arguments included, so the model sees which item it asked for and can request it again.
Keeping only the newest results whole can still leave a large transcript if one of those results is very long.
True. Clearing bounds the number of full results, not their size. A long result also needs a length limit in the tool itself.
A call and its result stay together
The messages of a transcript are not independent. When the model asks for tools, the reply is an assistant message with a list of tool_calls, each with its own id. Each result goes back as a tool message whose tool_call_id names the call it answers. A reply that asks for two tools at once is answered by two tool messages.
- assistant message
- tool_calls[0].id call_7
- tool_calls[1].id call_8
- tool message
- tool_call_id call_7
- content the order record
- tool message
- tool_call_id call_8
- content the help page
- assistant message to tool message: answered by
- assistant message to tool message: answered by
The API checks this pairing on every request. A tool message with no assistant call before it is rejected with an error such as messages with role 'tool' must be a response to a preceding message with 'tool_calls'. An assistant message whose calls are not all answered is rejected too: An assistant message with 'tool_calls' must be followed by tool messages responding to each 'tool_call_id'.
So every edit of the transcript has to treat a call and its results as one unit. Emptying the content of a tool message is safe: its role, its tool_call_id and its place in the list stay, so the pair is intact. Deleting messages is where edits break. Dropping the oldest messages one by one can cut between an assistant message and its results; dropping a tool message to save space leaves a call with no answer.
# Leaves tool messages whose assistant call is gone
messages = [messages[0]] + messages[-6:]
# Leaves an assistant call with no result
messages = [m for m in messages if m["role"] != "tool"]When messages must be removed, cut only at a turn boundary. A turn is a user message and everything after it up to the next user message: the assistant replies, with all their tool calls and results. An edit that respects these boundaries never separates a request from its answer. Not every OpenAI-compatible server reports a broken pair the same way, but every one expects the pairs to be whole, and a model given half a pair has to guess what happened.
True or false?
Replacing the content of an old tool message with a marker keeps the transcript valid for the API.
True. The message keeps its role, its tool_call_id and its position, so it still answers its call.
Keeping only the last few messages of a transcript is always a valid edit, because each message is complete on its own.
False. The cut can fall between an assistant message with tool_calls and its tool messages, leaving results that answer nothing, which the API rejects.
Compaction: a summary in place of the past
Clearing empties results but keeps every message. In a very long run even the calls, the assistant's reasoning and the markers add up. Compaction goes further: it takes the older part of the transcript, asks a model to summarize it, and replaces that part with the summary. The run then continues from the instructions, the summary and the most recent steps, which are kept word for word.
- older steps whole turns only
- model call write a summary
- summary one message
- next call instructions + summary + recent steps
- older steps to model call
- model call to summary
- summary to next call
The older part is cut at a turn boundary, for the pairing reason above, and the summary goes in as an ordinary message, so the transcript stays valid. What changes is that a model, not your code, now decides what the past contains, and that has costs clearing does not have:
- Lost detail. A summary drops what looked unimportant when it was written: the exact order number, an amount, a condition the customer stated once. Such a detail may matter only several steps later, when it is gone.
- Carried mistakes. If the summary states something wrong, every later call reads it as fact. OpenAI's guide on session memory calls this context poisoning.
- An extra call. Each compaction is one more model call, with its time and cost, and its output varies from run to run.
A compaction prompt is written for recall first: ask for every identifier, number, decision and open question in the older steps, then tighten it once you see what the summaries keep. Some providers compact on their side as a feature of their own API; the trade-offs are the same.
| clearing old results | compaction | |
|---|---|---|
| what changes | the content of old tool results | the older part of the transcript |
| model call | none | one per compaction |
| result | the same every time | varies with the model |
| what can be lost | text that can be fetched again | any detail the summary leaves out |
The two work together. Clearing comes first because it is cheap and loses nothing that cannot be fetched again; compaction is the step for a run so long that even a cleared transcript keeps growing.
True or false?
A good summary keeps everything a later step of the run will need.
False. The summary is written before the later steps happen, so it can drop a detail whose importance shows only afterwards.
Compaction needs a model call, while clearing old tool results can be done by the program alone.
True. Clearing replaces text with a fixed marker in code; compaction asks a model to write the summary.