How to make an AI agent remember things between chats (long-term memory)
How to make an AI agent remember things between chats (long-term memory)
Give an agent, an AI program that plans and uses tools to finish a task, long-term memory by storing facts outside the context window, which is all the text the AI model can see at once. Retrieve only the facts the current task needs. Keep a link back to the source of each fact. The agent still reasons in a short working context, the small set of facts it needs right now.
New to these terms? Every word is explained in the series glossary.
The short answer
Give an agent long-term memory by storing facts outside the context window. Retrieve only the facts the current task needs. Keep a link back to the source of each fact. The agent still reasons in a short working context.
I think of an agent with memory like a junior engineer with a good notebook. The notebook holds what happened last week, what the user prefers, and which fixes already failed. The engineer does not carry the whole notebook in their head. They open it, find the one page that matters, and get back to work. The rest of this article builds that notebook.
Why an agent forgets
A language model, the AI program that reads text and writes text back, reads only what is in its context window. The context window is the text the model can see in one go. When a session, one continuous stretch of work with the agent, ends, the window is gone. When a new session starts, the model knows nothing about the last one unless something hands it the facts.
This is not a bug in one model. It is how every current chat model works. The context window is short-term memory. Everything outside it does not exist until it is loaded back in.
The agent re-asks questions the user already answered. It repeats fixes that already failed. It loses decisions made last Tuesday.
The fix is not a bigger context window. A bigger window helps for one long session, but it does not help across sessions, and it gets expensive fast. The fix is a memory system that sits outside the model and feeds it only what matters.
The four layers of agent memory
Memory works best as four layers. Each layer has a different job, a different lifetime, and a different size. Mixing them up is a common design mistake.
Layer 1: working context. This is the current conversation plus the few facts the agent needs right now. It lives in the prompt, the text sent to the model. It is small, fast, and thrown away when the task ends.
Layer 2: session summary. When a session ends, the agent writes a short summary of what happened. Decisions, open items, and facts worth keeping. One page at most. This summary is what the next session reads first.
Layer 3: long-term store. This is the durable record. Individual facts, each with a source and a date. User preferences, project decisions, known bugs, and how things were fixed. It can grow for months. The agent never loads all of it. It searches it.
Layer 4: archive. Old sessions, full transcripts (word-for-word records of a session), and raw logs. Kept for audit and for digging up detail, but never loaded into a prompt by default. If a summary says something odd, the archive is where you check it.
Published systems split memory the same way. MemGPT, a 2023 research system from UC Berkeley, treats the context window like a computer's main memory and keeps everything else in external storage that the model pages facts in and out of through function calls. LangGraph's documentation separates short-term memory, the message history inside one conversation thread, from long-term memory kept in a store that is shared across threads and sessions.
Here is the diagram to picture. Draw four stacked boxes. The top box is the working context, small and labelled "this task only". Below it sits the session summary, labelled "this session, one page". Below that sits the long-term store, the biggest box, labelled "facts with sources and dates". At the bottom sits the archive, labelled "full history, read only when needed". Arrows run down the stack: the working context feeds the session summary, the summary feeds facts into the long-term store, and the store points down to the archive for proof. One arrow runs back up: a search query pulls a few facts from the store into the working context. That upward arrow is the whole system. If it works, the agent remembers. If it does not, the agent is just a chatbot with a diary.

Four layers: working context, session summary, long-term store, archive, with search pulling facts back up.
Three ways to store facts
Once you have the layers, you need a store for layer 3. There are three common choices. Each one fails in a different way.
| Store | How it works | Cost | Freshness | Main failure mode |
|---|---|---|---|---|
| Vector store | Facts are embedded as numbers and found by similarity | Medium, you pay for embeddings and a database | Good, new facts are searchable at once | It returns facts that sound similar but are wrong |
| Knowledge graph | Facts are stored as linked items, like person, works on, project | High, building the graph takes real work | Good, but only if someone updates the links | It goes stale when links are not maintained |
| Plain summary files | Facts live in short text files, one per topic, searched by keyword | Low, files and grep cost almost nothing | Depends on discipline, files rot if nobody writes them | Search misses facts worded differently |
An embedding turns text into a list of numbers that captures meaning. Similarity search finds facts whose numbers sit close to the query. A knowledge graph stores facts as links between things, like a person linked to a project. Grep is a command line search tool that finds text in files.
Start with plain summary files. I say that because the failure mode is the easiest to see and fix. You can read the files. You can grep them. You can fix a wrong fact with a text editor. A vector store hides its mistakes behind similarity scores. A knowledge graph hides its mistakes behind missing links.
Move to a vector store when the files get too many to grep by hand, roughly past a few hundred facts. Move to a knowledge graph only when the relationships between facts matter more than the facts themselves. One example: the agent must answer who owns which service and what that service depends on.
A minimal build in about 20 lines
Here is the smallest version that works. It saves facts to a JSON file, finds them by keyword overlap, and injects the best matches into the prompt. No database. No embeddings. No framework, meaning no ready-made agent library. JSON is a plain text format for storing data.
pythonimport json, re FILE = "memory.json" def load_all(): try: return json.load(open(FILE)) except FileNotFoundError: return {} def save_fact(key, text): store = load_all() store[key] = text json.dump(store, open(FILE, "w")) def retrieve(query, top=3): words = set(re.findall(r"\w+", query.lower())) scored = sorted(((len(words & set(re.findall(r"\w+", t.lower()))), t) for t in load_all().values()), reverse=True) return [t for h, t in scored[:top] if h > 0] def build_prompt(user_message): facts = retrieve(user_message) context = "\n".join("- " + f for f in facts) return f"Facts I remember:\n{context}\n\nUser: {user_message}"
Run it like this. Call save_fact("payment-retry", "Payment handler uses tenacity, 3 attempts, backoff 2 to 10 seconds.") after the agent learns something. Call build_prompt("add a timeout to the charge call") before the next task. A timeout is a time limit after which a waiting action is cancelled. The prompt now carries the retry fact, so the agent does not suggest a hand-rolled loop it already rejected. Tenacity is a Python retry library. Backoff is the wait between retries, growing from 2 to 10 seconds.
This code has obvious limits. Keyword search misses facts worded differently. It has no dates, so old facts never expire. It has no source links, so a wrong fact cannot be traced. Those limits are features at this stage. Each one is a deliberate next step, not a surprise. Add dates first. Add sources second. Add embeddings third, only when keyword search actually fails on real queries.
The worked example: what a summary really saves
A small token count shows what a session summary saves. A token is a chunk of text, roughly three quarters of a word in English. The setup is simple: a made-up 8-turn history of a coding agent fixing a payment webhook. A webhook is a message one service sends another when an event happens. Then two prompts for the same next task. One prompt carried the full history. The other carried a short summary plus the same next task.
The token counter is a simple approximation: words plus punctuation marks, counted with a regular expression, a compact pattern for matching text. It is not a real tokenizer. A tokenizer is the tool that splits text into tokens. A real tokenizer such as OpenAI's tiktoken would give different absolute numbers. Real tokenizers will give different absolute numbers, but the gap between the two prompts is the point.
The results:
| Prompt | Approximate tokens |
|---|---|
| Full 8-turn history | 214 |
| Short summary | 95 |
| Saved | 119 |
| Reduction | 55.6 percent |
The summary prompt was less than half the size of the full-history prompt. The summary itself was 5 sentences. It kept the facts that mattered: tenacity with 3 attempts, backoff from 2 to 10 seconds, the 202 response with a job id (a reference number for work finished later), and the three passing tests. A 202 response means the server accepted the request and will process it later. The full history also carried the back-and-forth, the false starts, and the repeated phrasing. None of that helps the next task.
One run on a fake history proves nothing general. The history was invented for the measurement. It shows the shape of the saving, not the size of it. Your history will be longer. Your summary will be longer too. The ratio will move. What will not move is the direction: a good summary is much smaller than the history it replaces, and the saving grows with every turn you would otherwise replay.
Measure it on your own agent
The numbers above come from a toy example. The shape of the saving is what matters: a good summary is much smaller than the history it replaces. The only way to know the size on your agent is to measure it yourself, on your own tasks, with a held-out set, test tasks kept apart and never used for tuning.
The drift problem: summaries of summaries
Saving tokens has a cost, and the cost is truth. That cost is called summary drift. Every summary drops detail. Summarise a summary and more detail goes. Do it ten times and the fact you started with may be gone or changed.
Take the payment example. The original fact is precise: tenacity, stop after 3 attempts, wait 2 to 10 seconds. After one round of summarising, it reads: retries 3 times with backoff. After a second round, it reads: has retry logic. After a third, it reads: handles errors. Each version is shorter. Each version is also less useful. The third version could describe any retry code in any language. An agent reading it would have to guess the library, the attempt count, and the timing.
Frameworks offer summarising as a standard tool. LangGraph's documentation lists summarising earlier messages and replacing them with a summary as one of the common ways to keep a long conversation inside the context window. That makes it easy to summarise again and again, which is exactly how drift builds up.
Three rules slow the drift. First, never summarise a summary. Always summarise from the original session, or from the long-term store, never from a previous summary. Second, keep numbers and names out of the summary prose and in a structured fact instead. "3 attempts" belongs in a fact with a key, not in a sentence that a later summary can blur. Third, keep the link back to the source. Every fact in the long-term store should say where it came from, so the agent or a human can check it when it matters.
Drift is not a reason to skip memory. It is a reason to build memory with sources attached. A notebook with page numbers beats a notebook with vague recollections, and the same holds for an agent.
How to test memory: 10 questions
Test memory after a week of sessions. Write 10 questions the agent should still answer correctly.
- What did we decide about the payment retry library, and why?
- What is the user's preferred deployment region?
- Which service owns user billing?
- What bug did we fix last Tuesday, and how?
- What is the user's working hours preference?
- Which test file covers the retry path?
- What did the user say they never want the agent to do?
- What is the current status of the migration we started?
- Who is the contact for the staging environment?
- What did we try that failed, so we do not try it again?
Write your own 10 questions from your own sessions, not from a generic list. A memory system that answers 9 out of 10 is working.
Try this
Add a summary file to a small agent today. Pick one project you work on with an agent. After your next session, write a 5-sentence summary by hand: what changed, what was decided, what is still open. Save it as memory.md in the project folder. Next session, paste it at the top of your first message.
Then measure. Count the tokens in your first prompt with the summary and compare it with the tokens in the same prompt carrying the full previous session. You can count roughly by words: one token is about three quarters of a word in English text. If the summary prompt is much smaller and the agent still does the task correctly, the notebook works. If the agent asks a question the summary already answers, the summary is missing a fact. Fix the summary, not the agent.
What to read next
The KV cache article in the How LLM Inference Works series explains the memory budget that makes summaries worth doing. The agent evaluation article shows how to test an agent, not just the model behind it.
FAQs
Does long-term memory mean fine-tuning the model on my data?
No. Long-term memory here means storing facts outside the model and loading the relevant ones into the prompt. Fine-tuning, extra training on your own examples, changes the model weights, the numbers inside the model. Memory changes what the model reads. Memory is cheaper, faster to update, and easier to correct when a fact is wrong.
Is a vector store required for agent memory?
No. Start with plain text files and keyword search. A vector store helps when you have hundreds of facts and keyword search starts missing them. Most small agents never reach that point, and the ones that do should add the vector store after the file version works, not before.
How do I stop summaries from drifting?
Never summarise a summary. Keep numbers and names as structured facts with keys. Keep a source link on every fact so it can be checked. Re-test with the 10-question check monthly, and fix the facts that come back wrong.
What should the agent remember, and what should it forget?
Remember decisions, preferences, known bugs, and what already failed. Forget the back-and-forth, the false starts, and the exact wording of old messages. If a fact would change what the agent does next week, keep it. If it would not, let it go to the archive.
Sources
- Packer and colleagues, "MemGPT: Towards LLMs as Operating Systems", UC Berkeley, October 2023. Context window treated as main memory, with external storage paged in and out through function calls. https://ar5iv.labs.arxiv.org/html/2310.08560v2
- LangChain, LangGraph memory overview. Short-term memory scoped to one thread, long-term memory in a store shared across threads and sessions. https://langchain-ai.github.io/langgraphjs/concepts/memory/
- LangChain, LangGraph add memory guide. Trimming, deleting and summarising messages as ways to manage short-term memory. https://docs.langchain.com/oss/javascript/langgraph/add-memory
- OpenAI API documentation, Conversation state guide. Each text generation request is independent and stateless; earlier turns must be sent again. developers.openai.com
- OpenAI, tiktoken tokenizer library. https://github.com/openai/tiktoken
