Sub topic 1
Why Agents Need Memory: LLM Calls Are Stateless
Prerequisites
This chapter assumes you have the following:
- Basic Python, including functions, lists, and dictionaries.
- Some experience calling a chat-style LLM API, where you send a list of messages and get a reply.
- The idea of an agent as an LLM running in a loop with tools.
- A basic idea of vectors and similarity. You will not need it until later chapters.
You do not need a specific provider. The examples use a fake model function so they run without an API key.
What "stateless" means
A language model call is a function. You pass in text and get text back. The model does not change between calls, and it keeps no record of earlier calls. The weights are fixed when you call it. Nothing you send is written into them.
This surprises people because chat products feel continuous. You say your name in one message and the assistant uses it in the next. The model is not remembering. The application sends the whole conversation again on every turn.
Here is a small simulation. The fake_llm function can only answer from the messages it receives, which matches how a real model behaves.
def fake_llm(messages):
"""Answer a name question using only the messages passed in."""
text = " ".join(m["content"] for m in messages if m["role"] == "user")
question = messages[-1]["content"].lower()
if "my name" in question:
for word in text.split():
if word.istitle() and word not in ("My", "What", "Is"):
return f"Your name is {word.strip('.')}."
return "I don't know your name."
return "OK."
# Call 1: tell the model something.
print(fake_llm([{"role": "user", "content": "My name is Priya."}]))
# Call 2: a separate call. Nothing from call 1 is included.
print(fake_llm([{"role": "user", "content": "What is my name?"}]))
# Call 3: the caller resends the earlier turn along with the new question.
print(fake_llm([
{"role": "user", "content": "My name is Priya."},
{"role": "assistant", "content": "OK."},
{"role": "user", "content": "What is my name?"},
]))The output is:
OK.
I don't know your name.
Your name is Priya.The second call fails because the information is missing from its input. The third call succeeds because the caller supplied it. Memory in an agent is the code that decides what to supply.
Where state actually lives
If the model holds no state, it must live somewhere else. In an agent, three places matter.
| Location | What it holds | Lifetime |
|---|---|---|
| Model weights | General knowledge from training | Fixed until the model is replaced |
| Prompt (context window) | The messages sent on this call | One call, rebuilt each time |
| External storage | Files, databases, vector stores | As long as you keep it |
Only the prompt and external storage are under your control at run time. Short-term memory is how you manage the prompt. Long-term memory is how you use external storage and bring parts of it back into the prompt.
The key point is that the arrow into the model comes from your code. The model never reaches out to history or storage by itself.
Why an agent needs memory more than a chatbot
A chatbot can often get by with a plain transcript. An agent runs a loop: it decides on an action, calls a tool, reads the result, and decides again. Each pass through the loop is another model call, and each call is stateless.
Consider an agent that books travel. In one task it may do the following:
- Read the user's request.
- Search flights and receive a long result.
- Ask a clarifying question.
- Receive the answer.
- Search hotels using details from steps 1 and 4.
By step 5 the model has no knowledge of steps 1 to 4 unless your code includes them. The agent's observations (tool results) and its own earlier reasoning are as easy to lose as the user's words. Forgetting them causes visible failures:
- The agent repeats a tool call it already made.
- It asks the user a question the user already answered.
- It contradicts a decision from earlier in the same task.
- It loses the goal after many steps.
Across sessions the problem grows. When the user comes back tomorrow, there is no transcript unless you saved one. Preferences, past decisions, and learned corrections are gone.
Two kinds of memory the code can build
The rest of this tutorial separates two kinds of memory, based on how long the information must survive.
- Short-term memory is the conversation or task state for the current session. It is kept in the application and sent in the prompt. It disappears when the session ends unless you save it.
- Long-term memory is information stored outside the prompt that persists across sessions. It is retrieved when relevant and inserted into the prompt.
A rule of thumb for choosing between them:
| Information | Better fit | Reason |
|---|---|---|
| The user's last question | Short-term | Needed only for the next few turns |
| Result of a tool call in this task | Short-term | Relevant to the current task |
| "The user prefers aisle seats" | Long-term | Useful in future sessions |
| "The user's company is in Pune" | Long-term | Stable fact about the user |
Both end up in the same place. Whatever the model uses on a call must be inside that call's prompt. The difference is where the information comes from and how long it lasts.
The cost of resending everything
If the application must resend history each time, the simplest design is to send all of it. This works for short conversations and then breaks down for three reasons.
- Size limit. A model accepts a maximum number of tokens per call. Past that limit the API returns an error or the input is cut off. The next chapter covers this limit in detail.
- Cost and latency. You pay for input tokens on every call, and long inputs take longer. A conversation of N turns resent on each turn means the total tokens processed grow roughly with the square of N.
- Attention quality. Models do not use all parts of a long prompt equally well. Relevant details buried in a large prompt can be missed.
A quick calculation shows the growth. Assume each turn adds 200 tokens and the full history is resent each time:
tokens_per_turn = 200
total = 0
for turn in range(1, 51):
prompt_size = tokens_per_turn * turn # history so far, resent in full
total += prompt_size
print("Prompt size at turn 50:", tokens_per_turn * 50)
print("Total input tokens over 50 turns:", total)The output is:
Prompt size at turn 50: 10000
Total input tokens over 50 turns: 255000The last prompt has 10,000 tokens, but the 50 calls together processed 255,000. Memory design is partly about avoiding that cost while still giving the model what it needs.
Common mistakes
- Assuming the model "learned" something. Telling a model a fact in one call does not change it. If the fact is not in the next prompt, it is gone.
- Confusing the transcript with memory. A saved transcript is raw material. Memory is the process that selects, compresses, and inserts parts of it.
- Forgetting tool results. Teams often keep user and assistant messages but drop tool outputs, so the agent repeats work.
- Sharing state across users by accident. A global list of messages in a web server leaks one user's conversation into another's prompt. Keep state per session and per user from the start.
- Treating provider features as the whole answer. Some APIs offer server-side conversation storage or caching. These still work by building the prompt for you. The limits on size, cost, and relevance still apply.
What the following chapters build
The remaining chapters follow the plan from the working space outward:
- The context window and its token budget.
- A short-term conversation buffer, with trimming and summarization.
- Long-term storage, memory types, embeddings, writing, and retrieval.
- Combining both in the agent loop.
- Scoping, maintenance, privacy, and evaluation.
Each step answers the same question: given a stateless model, what should be in this prompt right now?
Exercise
A user tells your agent "I'm vegetarian" in session 1. In session 2, the next day, the agent suggests a steak restaurant. The model and the code are unchanged. Explain why this happens and name the kind of memory that would prevent it.
Show answer
The model is stateless and keeps nothing between calls. Session 1's messages were not saved or were not included in session 2's prompt, so the model never saw the fact. Long-term memory would prevent it. The code would store "user is vegetarian" outside the prompt, retrieve it in session 2, and insert it into the prompt before the model call.
Exercise
Your agent sends the full history on every call. At 300 tokens per turn, how many input tokens does the first 10 turns' worth of calls process in total, and why does the total grow faster than the number of turns?
Show answer
The prompt at turn t has 300 t tokens, so the total is 300 (1 + 2 + ... + 10) = 300 * 55 = 16,500 tokens. It grows faster than linearly because each new call resends all earlier turns plus the new one, so the total grows roughly with the square of the number of turns.