Lesson 2 of 5 · Memory
Short-Term Memory
Manage an AI agent's short-term memory: sliding windows, token budgets, pinned facts, keeping tool calls with results and trimming big tool outputs. In Python.
- 6 min read
- Intermediate
- Reviewed
- List what goes into each request an agent sends to the model
- Keep a conversation inside a token budget with a sliding window
- Pin key facts so they are never trimmed away
- Trim history without breaking turns or tool-call pairs
What's in each request
A typical agent request is built from these parts, in this order:
- System prompt: the agent's role, rules and tool instructions.
- Pinned facts: a few key facts that must never be lost, such as the user's name and allergies, or the task's goal.
- Recalled memories: anything fetched from long-term memory for this turn (lesson 4).
- Recent conversation: the latest messages, including tool calls and their results.
- The new message.
Short-term memory management means deciding, on every turn, how much of part 4 to include, so the whole request stays inside a token budget you choose (well below the model's maximum, to leave room for the reply).
A sliding window with pinned facts
The simplest strategy is a sliding window: keep the most recent messages and drop older ones. On its own, that's how the allergy was lost in lesson 1. The fix is to pin the facts that matter, so they are sent every time, outside the window:
# Short-term memory: what goes into each request, and how to keep it inside a budget
def tokens(text):
return len(text.split()) * 4 // 3
class ShortTermMemory:
def __init__(self, budget, pinned):
self.budget = budget
self.pinned = pinned # always kept: system rules and key facts
self.messages = []
def add(self, role, text):
self.messages.append((role, text))
def context(self):
"""Pinned facts first, then as many recent messages as fit."""
used = sum(tokens(p) for p in self.pinned)
recent = []
for role, text in reversed(self.messages):
if used + tokens(text) > self.budget:
break
recent.insert(0, (role, text))
used += tokens(text)
while recent and recent[0][0] == "assistant": # start at a user turn, never mid-exchange
used -= tokens(recent.pop(0)[1])
return [("system", p) for p in self.pinned] + recent, used
memory = ShortTermMemory(budget=120, pinned=["User: Mei. Allergic to peanuts. Vegetarian."])
memory.add("user", "Suggest a quick lunch.")
memory.add("assistant", "Try a chickpea salad with lemon, parsley and toasted sunflower seeds.")
for i in range(6):
memory.add("user", f"Another idea please, number {i + 2}, something warm this time.")
memory.add("assistant", "How about a lentil soup with carrots, cumin and a squeeze of lime?")
ctx, used = memory.context()
print(f"{len(memory.messages)} messages stored, {len(ctx)} sent ({used} tokens):")
for role, text in ctx:
print(f" {role:>9}: {text[:60]}")Fourteen messages are stored, but only the pinned facts and the latest exchanges are sent, within 120 tokens. The allergy survives because it's pinned, however long the chat gets.
Notice the loop that drops a leading assistant message. Trimming by tokens can cut in the middle of an exchange, leaving a reply without its question. Starting at a user turn keeps the context readable, and many chat APIs require the first message to come from the user.
Counting tokens properly
The demo uses a rough rule (about 4 tokens for every 3 English words). For real budgets, count with the model's own tokenizer or the provider's token-counting endpoint, because code, numbers and non-English text use many more tokens per word. Count once when a message is added and store the number, rather than re-counting the whole history every turn.
Tool results are the biggest risk
In agents, the largest items in the history are usually tool results: a web page, a database query, a file's contents. One result can be bigger than the whole conversation. Good habits:
- Return less from tools: only the fields the model needs, a capped number of rows, short excerpts instead of whole pages.
- Shrink old results: once the model has used a result, replace it in the history with a short note such as “[search results used: 3 flights found, cheapest 129 EUR]”.
- Keep the full data outside the context (in a file or database) so the agent can fetch it again if needed.
Common mistakes
Implement the simplest short-term memory: a sliding window of the most recent complete turns.
messages = [("user", "a"), ("assistant", "b"), ("user", "c"), ("assistant", "d"),
("user", "e"), ("assistant", "f")]
keep_turns = 2 # one turn = a user message and the assistant's reply
# Keep only the last keep_turns complete turns and print the roles and texts, like:
# user c
Trimming the history leaves a tool result whose matching tool call was dropped. What is the likely outcome?
Summary
- Each request contains the system prompt, pinned facts, recalled memories, recent conversation and the new message.
- A sliding window keeps recent messages within a token budget that leaves room for the reply.
- Pin a few key facts so trimming can never remove them.
- Trim whole turns, and never split a tool call from its result.
- Tool results are usually the biggest items: return less, and shrink old results.
Next: summarising history, keeping the gist of what you drop.
Finished reading? Tick it off to track your progress.