Agent Short-Term Memory in Python: Trim and Summarize Chat History
The problem: the history list grows until it no longer fits
Lesson 1 showed that the API forgets, so your code keeps the conversation in a list and sends all of it on every call. That works for a few turns. But every user message, every assistant reply, every tool call and every tool result goes into the list, and the list never shrinks.
Sooner or later three things go wrong:
- The context window fills up. Every model has a maximum number of tokens it can read in one request. Past that, the request fails, or the server silently cuts the oldest text. Ollama, for example, uses a default context window of 4096 tokens according to its FAQ, which is often far below the model's maximum. You can raise it by starting the server with the
OLLAMA_CONTEXT_LENGTHenvironment variable, but on a small machine memory is the limit. - Cost and speed get worse. Hosted APIs bill input tokens on every call, and long prompts take longer to process, on a laptop CPU most of all.
- Answers get worse. A long history full of old tool results gives the model more irrelevant text to sort through.
So the agent needs short-term memory management: keep what matters for the current task, drop or compress the rest. This lesson builds the two standard techniques, trimming and summarizing, as small functions you can drop into any agent loop.
Measure before you manage
You cannot keep the history under a budget without measuring it. Exact token counts depend on the model's tokenizer, which differs between models. For budgeting, a rough estimate is enough: English text averages about four characters per token for common tokenizers. The code uses that rule and counts the JSON of each message, which also covers tool calls and tool results.
If you need the exact number after a call, the response tells you: response.usage.prompt_tokens is the real count the server used. Lesson 15 logs it on every step.
The context window helpers
Save this as context_window.py:
python# file: context_window.py import json from llm import client, MODEL def as_dict(message) -> dict: """The SDK returns message objects; history is easier to handle as plain dicts.""" return message if isinstance(message, dict) else message.model_dump(exclude_none=True) def estimate_tokens(messages: list) -> int: """Rough count: about 4 characters per token for English text. Good enough for budgeting.""" return sum(len(json.dumps(as_dict(m))) for m in messages) // 4 def turn_starts(messages: list) -> list[int]: """Indexes where a user turn begins. Cutting only here never orphans a tool message.""" return [i for i, m in enumerate(messages) if as_dict(m)["role"] == "user"] def trim_history(messages: list, max_tokens: int) -> list: system, rest = messages[:1], messages[1:] while estimate_tokens(system + rest) > max_tokens: starts = turn_starts(rest) if len(starts) < 2: # only the current turn is left, keep it break rest = rest[starts[1]:] # drop the oldest whole turn return system + rest def summarize_history(messages: list, keep_turns: int = 2) -> list: """Replace everything except the last few turns with a short summary.""" system, rest = messages[:1], messages[1:] starts = turn_starts(rest) if len(starts) <= keep_turns: return messages cut = starts[-keep_turns] old, recent = rest[:cut], rest[cut:] transcript = "\n".join(f"{as_dict(m)['role']}: {as_dict(m).get('content') or ''}" for m in old) summary = client.chat.completions.create( model=MODEL, messages=[{"role": "system", "content": "You write notes about a chat between a user and a trip " "helper. List every fact the user stated (name, dates, places, budget, likes, dislikes) " "as short bullet points. Do not continue the chat."}, {"role": "user", "content": "Chat to take notes on:\n<<<\n" + transcript + "\n>>>"}], temperature=0, ).choices[0].message.content note = {"role": "system", "content": "Summary of the earlier conversation:\n" + summary} return system + [note] + recent
There are four small functions here. Each one solves a specific trap.
Trap 1: SDK objects and dicts mixed in one list
In lesson 2 the loop appended the SDK's message object directly (messages.append(msg)), while user and tool messages are plain dicts. Both work when sent to the API, but code that reads the history has to handle both. as_dict converts SDK objects with pydantic's model_dump(exclude_none=True), so the rest of the code only deals with dicts.
Trap 2: cutting in the middle of a tool exchange
The obvious way to trim is "drop the oldest messages until it fits". That breaks agents. If you drop an assistant message that requested a tool but keep the tool message that answered it, the next request contains a tool result with a tool_call_id nobody asked for. Servers can reject that request outright.
turn_starts finds every index where a user message begins. A turn is a user message plus everything that follows it until the next user message: assistant replies, tool calls and tool results. Cutting only at turn boundaries keeps every tool call together with its results.
Trimming: drop the oldest whole turns
trim_history keeps the system message, then drops the oldest turn, one at a time, until the estimate is under max_tokens. It never drops the current turn, even if that one alone is over budget, because an agent with no question to answer is useless.
Test it without a model. Save this as trim_demo.py:
python# file: trim_demo.py from context_window import estimate_tokens, trim_history history = [{"role": "system", "content": "You are a trip helper."}] for i in range(1, 9): history.append({"role": "user", "content": f"Question {i}: tell me about day {i} in Lisbon. " * 3}) history.append({"role": "assistant", "content": f"Answer {i}: visit a viewpoint and eat pastries. " * 3}) print("before:", len(history), "messages, about", estimate_tokens(history), "tokens") trimmed = trim_history(history, max_tokens=250) print("after: ", len(trimmed), "messages, about", estimate_tokens(trimmed), "tokens") print("first kept user message:", trimmed[1]["content"][:30])
The tested output:
textbefore: 17 messages, about 681 tokens after: 5 messages, about 180 tokens first kept user message: Question 7: tell me about day
The system message plus the last two turns survived. Turns 1 to 6 are gone.
Trimming is fast, free and predictable. Its weakness is obvious: anything said in a dropped turn is lost. If the user gave their name and budget in turn 1, the agent no longer knows them in turn 9.

trim_demo.py: 17 messages become 5, the system message plus the last two whole turns.
Animation: trim_demo.py: 17 messages and about 681 tokens trimmed to 5 messages and about 180 tokens under a 250 token budget.
Summarizing: compress old turns instead of dropping them
summarize_history keeps the last few turns word for word and replaces everything older with a short summary written by the model. The summary goes into the history as a second system message, so the model treats it as background, not as something the user just said.
Save this as summary_chat.py:
python# file: summary_chat.py from context_window import estimate_tokens, summarize_history from llm import client, MODEL messages = [{"role": "system", "content": "You are a trip helper. Keep answers to one sentence."}] def chat(text: str) -> str: global messages messages.append({"role": "user", "content": text}) if estimate_tokens(messages) > 150: # tiny budget so the demo triggers quickly messages = summarize_history(messages, keep_turns=1) print(" [history summarized]") reply = client.chat.completions.create(model=MODEL, messages=messages, temperature=0).choices[0].message.content messages.append({"role": "assistant", "content": reply}) return reply print(chat("Hi, I'm Asha. I'm planning 4 days in Kyoto in April with a budget of 600 EUR.")) print(chat("I love temples and I hate crowds.")) print(chat("Suggest one quiet morning activity.")) print(chat("Remind me: what is my name and my total budget?")) print("\nsystem notes now in history:") for m in messages: if m["role"] == "system": print("-", m["content"][:200].replace("\n", " "))
The budget is set to a tiny 150 estimated tokens so you can see the summary happen within four messages. In a real agent you would set it to a fraction of the model's context window.
When this was run with qwen2.5:1.5b, the history was summarized before the fourth question. The final question, "what is my name and my total budget?", came after the turn that stated the budget had been compressed away. The answer said the name was Asha and the budget was 600 EUR, so both facts survived through the summary.
An honest failure, and the fix
The first version of the summary prompt was simply "Summarize this chat in at most 3 short bullet points." With the 1.5B model, that version failed in testing: instead of summarizing, the model continued the conversation and wrote something like a new assistant reply about temples. The summary lost the budget, and the agent then said the budget was not specified.
Two changes fixed it in the tested runs:
- A narrower job description. "You write notes about a chat... List every fact the user stated (name, dates, places, budget, likes, dislikes)." Naming the fact types tells the model what to keep.
- Clear boundaries around the transcript. Wrapping it in
<<<and>>>and saying "Do not continue the chat" helps the model see the transcript as material to process, not a conversation to join.
The lesson is general: summarization is itself an LLM call, and it can fail like any other. Check what your summaries actually contain, especially with small models, and print them while developing.
Trim or summarize?
| Trimming | Summarizing | |
|---|---|---|
| Cost | free | one extra model call each time it runs |
| Predictable | yes | depends on the model |
| Keeps old facts | no | the important ones, if the summary works |
| Risk | forgets early facts | summary drops or distorts a fact |
Many agents combine them: summarize when the history crosses a soft limit, and trim as a hard safety net if it is still too long. Another common addition is pinning: facts that must never be lost (the user's name, the trip dates) are stored in code and inserted into the system message on every call, independent of history. That is the bridge to long-term memory in the next lesson.
Shrink tool results, not only turns
In agents, tool results are often the biggest messages: a hotel search can return pages of JSON. Before trimming whole turns, it helps to shrink old tool results. Save this as shrink_tool_results.py:
python# file: shrink_tool_results.py def shrink_old_tool_results(messages: list, keep_last: int = 4, max_chars: int = 300) -> list: """Shorten tool results except the most recent ones. The model already used the old ones.""" tool_idx = [i for i, m in enumerate(messages) if m.get("role") == "tool"] old = set(tool_idx[:-keep_last]) out = [] for i, m in enumerate(messages): if i in old and len(m["content"]) > max_chars: m = {**m, "content": m["content"][:max_chars] + " ...[truncated]"} out.append(m) return out if __name__ == "__main__": history = [{"role": "tool", "tool_call_id": f"c{i}", "content": "x" * 1000} for i in range(6)] print([len(m["content"]) for m in shrink_old_tool_results(history)])
This keeps the structure intact (every tool message still answers its call) while cutting the bulk. It works on dicts, so pass it the output of as_dict if your history holds SDK objects. Running it prints the lengths of the six messages: the first two shortened, the last four untouched.
Where to call these in the agent loop
Manage memory right before each model call, not after:
pythonmessages = trim_history(messages, max_tokens=3000) response = client.chat.completions.create(model=MODEL, messages=messages, tools=TOOLS)
Keep the full history somewhere else (a log file, a database) if you need it for debugging or auditing. The managed list is what the model sees; the full record is what you keep. Lesson 15 writes that full record as a trace.
Common mistakes
- Trimming by message count instead of by size. One tool result can be larger than twenty short turns.
- Cutting inside a tool exchange, which leaves orphaned tool results.
- Dropping the system message. Always keep it first.
- Summarizing on every turn. It costs a model call each time. Trigger it only when a budget is crossed.
- Never reading the summaries. They are model output and can be wrong.
What to try next
- In
summary_chat.py, setkeep_turns=2and add more questions. When does the budget fact get lost, if ever? - Swap
summarize_historyfortrim_historywith the same budget and ask the final question again. The name and budget should disappear. - Run
summarize_historywith the original one line prompt ("Summarize this chat in 3 bullet points") and compare the summaries. - Use
response.usage.prompt_tokensto compare your four characters per token estimate with the real count for your model.
Short-term memory keeps one conversation healthy. Next you will give the trip helper long-term memory: facts that survive after the conversation ends, stored as embeddings and searched with a few lines of numpy.
Sources
Trim old turns to fit a token budget
Every message you send costs tokens, and the context window has a limit. A simple fix keeps the system message and as many of the newest messages as fit.
Write trim_messages(messages, max_tokens, count).
- count(message) returns that message's token count.
- Always keep every message with role "system" from the start of the list.
- Then keep the longest run of the most recent messages whose total, plus the system messages, is at most max_tokens.
- Keep the original order. Never keep an older message while dropping a newer one.
The worked solution unlocks after your first attempt.
Check what you learned
Answer all 3 questions. You need at least 2 right to pass.
1. Why does trim_history cut only at user message boundaries?
2. What went wrong with the first one line summary prompt on the small model?
3. What is the main weakness of trimming compared with summarizing?