# Memory and State: Short-Term Context and Long-Term Recall
You tell a support agent "My name is Priya and my order is #4471." Three messages later it asks, "Can I get your name?" That is an agent with no memory, and it feels broken. But the opposite failure is just as bad: an agent that stuffs every past conversation into every reply, gets confused, slows down, and costs a fortune. Good agents remember the *right* things at the *right* time. That is what this lesson is about.
Human brains have working memory (what you are thinking about right now) and long-term memory (what you can recall when needed). AI agentsAI agentsAgentic AI refers to AI systems that pursue goals autonomously by planning, taking actions through tools, and adapting based on results, with minimal step-by-step human direction.Voir la définition complète → work the same way, and the distinction matters for how you build them.
The context windowcontext windowThe context window is the maximum amount of text (measured in tokens) a language model can process at once, including both the input prompt and the generated output.Voir la définition complète → is the block of text the model can "see" in a single request. It includes the system instructions, the conversation so far, and any data you paste in. Think of it as the agent's desk: everything on the desk is visible at once, but the desk has a fixed size.
That size is measured in tokenstokensA token is the basic unit of text that language models process, often a word fragment, whole word, or punctuation mark rather than a single character.Voir la définition complète → (roughly ¾ of a word each). Modern models in 2026 have large windows, often 200,000 tokenstokensA token is the basic unit of text that language models process, often a word fragment, whole word, or punctuation mark rather than a single character.Voir la définition complète → or more, but "large" is not "infinite," and a full window is slow and expensive.
Here is the key fact that surprises people: the model has no memory between calls. Each time you send a message, the entire conversation is re-sent. The agent only "remembers" your name because your app keeps the transcript and pastes it back in every turn.
# Short-term memory is just a list you resend every turn.
messages = [
{"role": "system", "content": "You are a support agent."},
]
def chat(user_text):
messages.append({"role": "user", "content": user_text})
reply = model.generate(messages) # whole list sent every time
messages.append({"role": "assistant", "content": reply})
return reply
chat("My name is Priya, order #4471.")
chat("When does it ship?") # 'Priya' and '#4471' are still in the listThat is the entire trick behind conversational memory. There is no magic, just a growing list.
The desk fills up. Old tickets, past chats, and account history cannot all live in the context windowcontext windowThe context window is the maximum amount of text (measured in tokens) a language model can process at once, including both the input prompt and the generated output.Voir la définition complète → forever. So we move them to long-term memory: an external store the agent can search when a topic comes up.
The common tool for this is a vector storevector storeA vector database stores data as high-dimensional numeric vectors (embeddings) and retrieves items by similarity rather than exact matches, powering semantic search and AI applications.Voir la définition complète → (also called a vector databasevector databaseA vector database stores data as high-dimensional numeric vectors (embeddings) and retrieves items by similarity rather than exact matches, powering semantic search and AI applications.Voir la définition complète →). It stores text as embeddings: numerical fingerprints that capture meaning. When Priya writes in again, the agent turns her new message into an embeddingembeddingAn embedding is a numerical vector that represents data (text, images, or items) in a way that captures meaning, so similar items sit close together in space.Voir la définition complète → and asks the store, "What past tickets are most similar to this?" It pulls back only the relevant few and drops them onto the desk.
This is called retrieval: fetch the handful of memories that matter, ignore the thousands that do not. If you want the deeper mechanics, this free primer on embeddings and vector search explains it clearly without assuming you code.
Let us make this real. Priya has contacted support four times over two years. She writes in today: "My blender is smoking again."
Here is what a well-designed agent does:
1. Short-term: It keeps today's conversation in the context windowcontext windowThe context window is the maximum amount of text (measured in tokens) a language model can process at once, including both the input prompt and the generated output.Voir la définition complète → so it does not re-ask her name mid-chat.
2. Long-term retrieval: It searches the vector storevector storeA vector database stores data as high-dimensional numeric vectors (embeddings) and retrieves items by similarity rather than exact matches, powering semantic search and AI applications.Voir la définition complète → for Priya's past tickets. It finds ticket #4471 from last year: "blender overheating, replaced under warranty." That is highly relevant, so it loads it.
3. It ignores her unrelated ticket about a late invoice. Not similar, not loaded.
4. It responds with context: "I see we replaced this blender for overheating last March. Let's check if it's still under warranty."
That feels like a human who actually remembers you. Notice the agent did not dump all four tickets into the window. It retrieved one.
# Long-term recall: search, then inject only what's relevant.
def build_context(user_text, user_id):
past = vector_store.search(
query=user_text,
filter={"user_id": user_id},
top_k=3 # only the 3 most relevant memories
)
memory_block = "\n".join(m.text for m in past)
return [
{"role": "system",
"content": f"You are a support agent.\nRelevant history:\n{memory_block}"},
{"role": "user", "content": user_text},
]The top_k=3 is doing a lot of work. It says "give me the three best matches, not everything." That single number is often the difference between a sharp agent and one that drowns in history.
Memory is not "save everything." It is a set of decisions. Here are practical rules.
When a conversation gets long, do not carry all fifty messages. Summarize the older ones into a short note and keep only that. This is often called a "rolling summary."
Example: forty messages of back-and-forth debugging become one line: *"User troubleshooting a smoking blender; confirmed model X200; warranty status unknown."* You just freed most of the desk while keeping what matters.
# When the transcript gets long, compress the old part.
if token_count(messages) > 6000:
old = messages[1:-6] # keep system + last 6 turns
summary = model.generate([
{"role": "user",
"content": f"Summarize these support messages in 3 sentences:\n{old}"}
])
messages[1:-6] = [{"role": "system", "content": f"Summary so far: {summary}"}]A useful mental model: keep facts, summarize journeys, forget noise.
Two failure modes sit on either side of good memory.
Too little memory: the agent re-asks questions, loses the thread, and feels robotic. Usually caused by not persisting the transcript, or setting top_k too low.
Too much memory: the agent gets confused by stale or irrelevant history, contradicts itself, runs slowly, and costs more per message. Usually caused by dumping full history instead of retrieving, or never summarizing.
The fix for both is the same discipline: be deliberate about what enters the window. Retrieve relevant long-term memories, summarize long conversations, and forget noise. The context windowcontext windowThe context window is the maximum amount of text (measured in tokens) a language model can process at once, including both the input prompt and the generated output.Voir la définition complète → is prime real estate. Treat every tokentokenA token is the basic unit of text that language models process, often a word fragment, whole word, or punctuation mark rather than a single character.Voir la définition complète → like it costs you something, because it does.
One more practical point: write memory back. After a ticket closes, save a short structured note to the vector storevector storeA vector database stores data as high-dimensional numeric vectors (embeddings) and retrieves items by similarity rather than exact matches, powering semantic search and AI applications.Voir la définition complète →: *"2026-03-11: Priya, blender X200, overheating, replaced under warranty."* That is what tomorrow's agent will retrieve. An agent that never writes new memories can only ever recall what it started with.
Vérification des acquis
1. What does it mean that 'the model has no memory between calls'?
2. In the lesson's analogy, the context window is compared to a desk. What is the main point of that analogy?
3. An agent that pastes every past conversation into every reply is described as a failure mode. Why is this bad rather than helpful?
4. Select ALL correct answers about what is included in a model's context window.
Sélectionnez toutes les réponses correctes.
5. Select ALL correct answers that correctly distinguish short-term from long-term memory in AI agents.
Sélectionnez toutes les réponses correctes.
Long-term memory means you are storing user data, sometimes sensitive data. Two rules keep you out of trouble:
You do not have to build all this plumbing yourself. Every major provider now ships an agent framework that handles transcripts, retrieval, and summarization for you: the OpenAI Agents SDK, the Claude Agent SDK, and Google's Agent Development Kit (ADK). They differ in the details but share the same shape you learned here: short-term context plus long-term retrieval. The provider deep-dive blocks in this course cover the specifics of each. The concepts transfer directly, so pick whichever provider you already use.
top_k), not the entire history.