Sub topic 1
Why Agents Need Memory: LLM Calls Are Stateless
Prerequisites
Assume you know basic Python, have called a chat-style LLM API, and understand that an agent runs an LLM in a loop with tools. You should also know that an embedding represents text as a vector, although embeddings are not needed in this chapter.
Why Agents Need Memory: LLM Calls Are Stateless
An LLM call is stateless: the model does not automatically remember earlier calls. Each request receives only the messages included in that request. If an agent needs conversation history, the surrounding application must store it and send relevant parts again.
This design makes the model easier to scale, but it gives the agent a memory responsibility. The application decides what to retain, remove, or summarize.
The Context Window as Working Space
A context window is the maximum amount of text an LLM can process in one request. The limit includes system instructions, conversation messages, retrieved documents, tool results, and the new user input.
Tokens are small pieces of text used to measure this limit. A request that exceeds the context window may fail, or the application may need to discard information. Memory therefore requires a budget, not just a database.
Short-Term Memory: The Conversation Buffer
Short-term memory is the recent conversation held in the current prompt. A conversation buffer commonly keeps the system message and recent user and assistant messages.
def trim_messages(messages, max_tokens):
system = [m for m in messages if m["role"] == "system"]
rest = [m for m in messages if m["role"] != "system"]
count = lambda text: len(text.split())
budget = max_tokens - sum(count(m["content"]) for m in system)
kept = []
for message in reversed(rest):
cost = count(message["content"])
if cost > budget:
break
kept.append(message)
budget -= cost
return system + list(reversed(kept))Keeping the Buffer Inside the Token Budget
The algorithm walks backward from the newest message. It keeps messages while they fit, so older turns are removed first. A production tokenizer should replace the rough word count. Reserve space for the model's expected response as well.
Summarizing Older Turns
Trimming loses old details. Summarization compresses those details into a shorter message, such as “The user is building a Python budgeting tool and prefers CSV output.” The summary should preserve decisions, unresolved tasks, constraints, and important facts. Treat generated summaries as fallible and revise them when later messages contradict them.
Exercise
Which strategy should you use when recent messages fit poorly but older decisions still matter?
Show answer
Summarize the older turns, keep the summary in the prompt, and reserve the remaining budget for recent messages and the response.