Long-Term Memory: Notes That Outlive a Run
An agent run knows only what its transcript holds, and the transcript is gone when the run ends. That is a good thing between unrelated tasks, but it also means a lesson the agent learned the hard way in one run has to be learned again in the next. Long-term memory fixes that with something very plain: short notes the agent writes to a file. The program brings those notes back into later runs, and it keeps them small enough, and correct enough, to help instead of mislead.
A fresh run for every task
A chat API keeps no state between calls. Each request is independent: the model has exactly the messages list the program sends in that call, and nothing else. The transcript of a run is that list, growing step by step, and it is the agent's short-term memory.
When an agent handles many tasks one after another, the program has a choice. It can keep appending every task to one long transcript, or it can start each task with a new, empty transcript: only the system prompt and the new task. The second choice is the usual one, and the reason is that everything a run reads stays in its transcript. With one long transcript, the pages the agent searched, the tool results it read and the dead ends it tried for the first task are all still there while it works on the second, and they are sent again with every call. So the input keeps growing, and each call costs more and takes longer. On top of that, a model recalls and uses its context less well as that context grows, even well inside the limit of the window.
- One transcript for every task
- tasks 1, 2 and 3 all in one list
- A fresh run per task
- task 1
- task 2
- task 3
A fresh run has a price. When the run ends, its transcript is thrown away, and with it everything the agent learned along the way. Suppose an agent answers questions from a company wiki, and in one run it discovers after four failed searches that the wiki says "leave" where people say "vacation". The next run starts empty, so it makes the same four failed searches before it finds the same word. Nothing went wrong in the code: the second run simply has no way to know what the first one found.
True or false?
If an agent answered a question yesterday, the model remembers that conversation the next time the program calls it.
False. Every request is independent. The model sees only the messages sent in that call, so anything from an earlier run is gone unless the program puts it back.
Starting each task with an empty transcript can make an agent repeat work it has already done in an earlier run.
True. A fresh run keeps tasks from crowding each other, but it also forgets what earlier runs found. That gap is what long-term memory fills.
Memory that lives outside the transcript
Long-term memory is information kept outside the transcript, in storage that outlives a run, and brought back into a later run. The storage can be as simple as a text file next to the program. A run adds to it when it learns something worth keeping; a later run reads it and so starts with that knowledge instead of from nothing.
The difference from short-term memory is where the information lives and how long it lasts. The transcript lives in the program's memory during one run and holds everything: every request, every tool result. Long-term memory lives on disk across runs and holds very little: a few short facts chosen because a later run will need them. It is not a copy of old transcripts. Replaying a whole earlier conversation would bring back exactly the reading a fresh run is meant to leave behind.
- Run 1 ends, its transcript is gone
- A file that stays on disk
- Run 2 starts with the note
Two questions decide how such a memory works: how notes get written, and how they get back into a run. The next two sections take them in that order.
True or false?
Long-term memory for an agent needs a vector database, a store that finds saved text by its meaning.
False. A plain text file of short notes is a working long-term memory. Search by meaning, which turns each note into a list of numbers (an embedding) kept in a vector database, is one way to look notes up when there are very many, not a requirement.
Saving the full transcript of every run and loading it into the next one is a poor form of long-term memory.
True. It brings back all the old reading, which is what a fresh run avoids. Good long-term memory keeps only the few facts a later run will need.
Notes the agent writes
Who decides what is worth remembering? The model is in the best position, because it is the one that noticed the four failed searches. So the agent gets a tool, here called save_note, that lets the model save one short note when it learns something a later run will need. Like any other tool, the model only asks: it returns a tool call with the note as its argument, and the program checks the request and writes the file.
{
"type": "function",
"function": {
"name": "save_note",
"description": "Save one short fact that a later run will need and could not easily find again, such as a word the wiki uses or where a topic is documented. Do not save the answer to the current question, guesses, or anything you can read directly from a page.",
"parameters": {
"type": "object",
"properties": {
"text": {
"type": "string",
"description": "The fact in one sentence, at most 200 characters."
}
},
"required": ["text"]
}
}
}The description does most of the work, because it is the text the model decides by. A good note is durable (likely to stay true in later runs), useful (it changes what a later run does), and not something the agent can simply read again from its sources. The answer to today's question is usually a poor note: the next task is a different question. Guesses are poor notes too, and so are rules for the agent ("always answer in French"): rules belong in the instructions a person writes, not in a file the model fills.
On the program's side, the tool is a plain Python function. It cleans the text, rejects what is too long or already saved, adds the date, and writes the file.
import os
from datetime import date
from pathlib import Path
NOTES = Path("notes.md")
MAX_CHARS = 200
MAX_NOTES = 20
def read_notes() -> list[str]:
if not NOTES.exists(): # the first run has no file yet
return []
lines = NOTES.read_text(encoding="utf-8").splitlines()
return [line[2:] for line in lines if line.startswith("- ")]
def write_notes(notes: list[str]) -> None:
tmp = NOTES.with_name(NOTES.name + ".tmp")
tmp.write_text("".join(f"- {n}\n" for n in notes), encoding="utf-8")
os.replace(tmp, NOTES) # old file or new file, never half of one
def save_note(text: str) -> str:
text = " ".join(text.split()) # one line, no stray spaces
if not text:
return "Error: the note is empty."
if len(text) > MAX_CHARS:
return f"Error: a note holds at most {MAX_CHARS} characters. Shorten it."
notes = read_notes()
if any(n.endswith(text) for n in notes):
return "Already saved, nothing to do."
if len(notes) >= MAX_NOTES:
return f"Error: memory is full ({MAX_NOTES} notes). Save only what matters most."
notes.append(f"{date.today().isoformat()}: {text}")
write_notes(notes)
return "Saved."Two details matter. First, the notes are written to a temporary file, which is then swapped in for the old one with os.replace. The Python documentation describes that swap as an atomic operation when it succeeds, meaning it happens completely or not at all: if the program stops in the middle, the old notes file is still whole. Second, every refusal comes back as a tool result that tells the model what went wrong, so the run continues and the model can shorten the note or let it go.
Writing notes this way costs something too: each call to save_note adds a tool call and its result to the transcript, and a step of its own when the model does not make it in the same reply as another call, and the model spends some of its attention deciding what to keep.
True or false?
With a note-saving tool, the model itself writes to the notes file.
False. The model only returns a tool call. The program checks the request, applies its limits and performs the write.
"The wiki uses the word leave, not vacation" is a better note than the full answer the agent just gave.
True. The word helps every later run that searches the wiki. The answer helps only someone who asks the same question again.
Bringing notes into a run
Saved notes help only if a later run sees them, and there are two ways to make that happen. The program can place the notes at the start of the run, usually at the end of the system prompt, so the model has them before its first step. Or it can give the model a tool, such as read_notes, and let the model look them up when it thinks they could help.
def start_messages(instructions: str, task: str) -> list[dict]:
system = instructions
notes = read_notes()
if notes:
system += "\n\nNotes saved by earlier runs (hints, check them before relying on them):\n"
system += "\n".join(f"- {n}" for n in notes)
return [
{"role": "system", "content": system},
{"role": "user", "content": task},
]The two choices spend context differently, because the whole messages list is sent again with every call of a run. Notes placed at the start are part of every call, from the first to the last, whether the task needs them or not. A lookup tool is part of every call too, but only as its definition, and tool definitions count against the context and are billed as input tokens like any other text the model receives. The notes themselves enter the transcript only if the model calls the tool, and from then on they are in every later call of that run, like any other tool result.
| Placed at the start | Looked up with a tool | |
|---|---|---|
| In every call | all the notes | the tool definition |
| When the notes arrive | before the first step | after the model asks, one step later |
| What can go wrong | many notes crowd the context of every task | the model never looks, or looks too late |
| Fits best | a short file of notes most tasks need | a larger store most tasks do not need |
With a small notes file, placing it at the start is the simplest thing that works, and the size limit from the previous section keeps its cost fixed. Looking notes up pays off when memory grows past what is worth sending every time, at the cost of an extra step and the chance that the model never asks. Real agents often mix the two: a short, always-loaded file, and tools to fetch more when a task calls for it.
True or false?
A lookup tool for notes costs nothing in a run where the model never calls it.
False. The tool definition is sent as input in every call of the run, whether the tool is used or not.
Notes placed in the system prompt are sent again with every model call of the run.
True. The system prompt is part of the messages list, and the whole list goes with every call, so a longer notes file makes every call larger.
Keeping memory small and correct
A notes file is written by a model, a little at a time, over many runs, and nobody reviews each write. Left alone it goes wrong in three ways. A note can be wrong from the start, because the model drew a hasty conclusion. A note can become outdated, because the world changed after it was saved: the wiki was renamed, a page was moved. And there can be too many notes, near-duplicates and trivia that make every run larger and bury the few notes that matter. A loaded note carries weight with the model, so a bad one does harm in every run that reads it.
- 2026-10-02: The wiki says leave, not vacation.
- 2026-10-02: Leave rules are on the page Time off.
- 2026-10-09: Expense limits are on the page Travel.
- 2026-10-15: Parental leave is 12 weeks for everyone.
- 2026-11-03: The page Time off was renamed to Absence.Three habits keep the file healthy, and each answers one of those failures.
- A limit on size. The code, not the prompt, caps how long a note can be and how many notes the file holds, and refuses a duplicate. When the file is full, the program can refuse new notes, as above, or keep only the newest ones. Either way, the cost the notes add to every run stays bounded.
- A readable file a person can correct. Plain text, one note per line, with the date it was saved: a person can open it, see in a minute what the agent believes, and delete or fix a line. The dates also help the model, which can prefer the newer of two notes that disagree. A binary format or a database would hide the same mistakes.
- A note treated as a hint to verify. The instructions tell the model that notes come from earlier runs and may be wrong or out of date, so before it relies on one it checks it with its tools, and the sources win when they disagree. Checking is usually cheap: the note says where to look, and looking is one or two reads. A note that turns out wrong can then be replaced by a corrected one.
The same caution applies to anything else that reaches the file: notes are context the model weighs, not rules it must obey, so they should never override the instructions a person wrote. (Text in a notes file can also be a way to slip instructions into an agent, which is a security matter of its own.)
True or false?
The more notes an agent has saved, the better it performs.
False. Every loaded note adds to every call, and trivia buries the notes that matter. Pruning stale and duplicate notes is part of keeping memory useful.
When a note says a page is called Time off but the wiki shows a page called Absence, the agent should trust the wiki.
True. A note is a hint saved at some point in the past. The source is what is true now, and the outdated note should be corrected.
A limit on the number of notes is best enforced by asking the model in the prompt to keep the file short.
False. A prompt can be ignored. A limit checked in the code that writes the file holds in every run.