Long-Term Agent Memory in Python With Embeddings and NumPy
The problem: the agent forgets everything when the conversation ends
Lesson 7 kept one conversation inside the context window. But when that conversation ends, the history list is gone. Next week the traveller opens a new chat and the trip helper has no idea that Asha is vegetarian, hates early flights, or has a 600 EUR budget.
You could save every old conversation and paste it all into the next one. That falls apart fast: it fills the context window, costs tokens on every call, and buries the one useful fact under hundreds of irrelevant lines.
What you want instead is a small store of lasting facts, and a way to pull out only the few facts that matter for the current request. "Suggest a dinner spot" should bring back "Asha is vegetarian", not "Asha prefers a window seat".
The standard tool for "find the stored text most related to this text" is an embedding search. This lesson builds one in about 40 lines of Python with numpy and a JSON file, with no vector database, then wires it into the trip helper.
Embeddings in one paragraph
An embedding model turns a piece of text into a list of numbers (a vector). Texts with similar meaning get vectors that point in similar directions. To compare two texts, you compare their vectors, usually with cosine similarity: 1 means the same direction, values near 0 mean unrelated. You do not need to understand how the model learns this to use it, in the same way you do not need to know how a hash function works to use a dictionary.
Get embeddings from the same endpoint
Ollama's OpenAI compatibility docs list a /v1/embeddings endpoint that accepts a model and an input that can be one string or a list of strings. So the same client from llm.py works, through client.embeddings.create. This course uses all-minilm, a small embedding model available in Ollama's library:
bashollama pull all-minilm
In the tested setup, all-minilm returned 384 numbers per text (you can check with embed(['hi']).shape). If you switch providers, set AGENT_EMBED_MODEL to an embedding model they offer. Vectors from different embedding models are not comparable, so if you change the model, re-embed everything you stored.
The memory store
Save this as memory_store.py:
python# file: memory_store.py import json import os from pathlib import Path import numpy as np from llm import client EMBED_MODEL = os.getenv("AGENT_EMBED_MODEL", "all-minilm") def embed(texts: list[str]) -> np.ndarray: response = client.embeddings.create(model=EMBED_MODEL, input=texts) vectors = np.array([item.embedding for item in response.data], dtype=np.float32) # Normalize so a plain dot product equals cosine similarity. return vectors / np.linalg.norm(vectors, axis=1, keepdims=True) class MemoryStore: def __init__(self, path: str = "memories.json"): self.path = Path(path) self.texts: list[str] = [] self.vectors = np.zeros((0, 0), dtype=np.float32) if self.path.exists(): saved = json.loads(self.path.read_text()) self.texts = saved["texts"] self.vectors = np.array(saved["vectors"], dtype=np.float32) def add(self, text: str) -> None: if text in self.texts: return vector = embed([text]) self.vectors = vector if len(self.texts) == 0 else np.vstack([self.vectors, vector]) self.texts.append(text) self.path.write_text(json.dumps({"texts": self.texts, "vectors": self.vectors.tolist()})) def search(self, query: str, k: int = 3, min_score: float = 0.1) -> list[tuple[float, str]]: if not self.texts: return [] scores = self.vectors @ embed([query])[0] # one dot product per memory best = np.argsort(-scores)[:k] return [(float(scores[i]), self.texts[i]) for i in best if scores[i] >= min_score]
Walk through it:
embedsends a list of texts in one request and gets backresponse.data, one item per input, each with an.embeddinglist. It stacks them into a numpy array.- Normalizing each vector to length 1 means a plain dot product equals cosine similarity. That turns search into one line of numpy.
MemoryStore.addembeds one fact, appends it, and writes texts and vectors to a JSON file, so memories survive after the program exits. Exact duplicates are skipped.MemoryStore.searchembeds the query, computesself.vectors @ query_vector(one score per memory, all at once), sorts, and returns the topkabovemin_score.
That is a vector database in miniature. Real vector databases add indexes that stay fast with millions of entries, filtering, and concurrent writes. For a personal agent with hundreds or a few thousand memories, a numpy array is fast enough on an ordinary computer and has nothing to install or run.
Try the search on its own
Save this as search_demo.py:
python# file: search_demo.py from pathlib import Path from memory_store import MemoryStore Path("demo_memories.json").unlink(missing_ok=True) # start fresh each run store = MemoryStore("demo_memories.json") for fact in [ "Asha is vegetarian.", "Asha prefers a window seat on flights.", "Asha's budget for the Kyoto trip is 600 EUR.", "Asha does not like flights that leave before 8 am.", "Asha's favourite thing to do on a trip is visiting temples.", ]: store.add(fact) for question in ["Which restaurant should I book for Asha?", "Pick a flight time for Asha", "How much can Asha spend?"]: print(question) for score, text in store.search(question, k=2): print(f" {score:.2f} {text}")
The tested output with all-minilm:
textWhich restaurant should I book for Asha? 0.54 Asha's favourite thing to do on a trip is visiting temples. 0.50 Asha prefers a window seat on flights. Pick a flight time for Asha 0.80 Asha does not like flights that leave before 8 am. 0.69 Asha prefers a window seat on flights. How much can Asha spend? 0.62 Asha's budget for the Kyoto trip is 600 EUR. 0.51 Asha's favourite thing to do on a trip is visiting temples.
Two of the three questions worked well. The restaurant question did not: "Asha is vegetarian." is not in its top two. To a small embedding model, "Which restaurant should I book for Asha?" looks more like the other sentences about Asha than like the word "vegetarian". The model has no idea that diet matters for restaurants unless the stored text says so.
This is the most important practical point about embedding memory: search quality depends on how you write the memories, not only on the model.
Animation: Each fact is stored as an embedding. A query scores them all and the nearest two go into the prompt.
Write memories that can be found
The fix is to store facts with the context words that future questions will use. A quick check with the same model, comparing cosine scores against the query "Which restaurant should I book for Asha?":
| Stored fact | Score |
|---|---|
| Asha is vegetarian. | 0.49 |
| Asha does not eat meat or fish, which matters for restaurants and meals. | 0.57 |
The longer version names the situations where the fact applies, so it scores higher for restaurant questions. That is why the remember tool in the next file asks the model for "one sentence with context words", with an example.
Other habits that help:
- One fact per memory. "Asha is vegetarian and likes window seats" splits its relevance between two topics.
- Name the person. "Is vegetarian" with no subject is ambiguous once several people's facts are stored.
- Keep
min_scorelow andksmall. Scores vary between embedding models. Withall-minilm, a vague query like "Suggest a dinner spot for my first night in Kyoto" scored only 0.16 against "Asha is vegetarian." in testing. The store uses a threshold of 0.1 and returns at most three facts. A few slightly irrelevant facts in the prompt cost little; a missing critical fact can ruin an answer.
Wire memory into the agent
There are two separate jobs: saving memories and recalling them. The design choice is who does each one.
Save this as memory_agent.py:
python# file: memory_agent.py import json from pathlib import Path from llm import client, MODEL from memory_store import MemoryStore store = MemoryStore("asha_memories.json") TOOLS = [{"type": "function", "function": { "name": "remember", "description": "Save one lasting fact about the user (a preference, a constraint, a plan) for future chats.", "parameters": {"type": "object", "properties": { "fact": {"type": "string", "description": "One sentence with context words, e.g. " "'Asha is vegetarian, so meals and restaurants must be vegetarian.'"}}, "required": ["fact"]}}}] def run_turn(user_text: str) -> str: # Recall runs on every turn in code, so it never depends on the model remembering to ask. recalled = [text for _, text in store.search(user_text, k=3)] print(f" recalled: {recalled}") system = "You are a trip helper. Use the remember tool when the user shares a lasting preference." if recalled: system += "\nKnown facts about the user:\n- " + "\n- ".join(recalled) messages = [{"role": "system", "content": system}, {"role": "user", "content": user_text}] for _ in range(4): msg = client.chat.completions.create( model=MODEL, messages=messages, tools=TOOLS, temperature=0 ).choices[0].message messages.append(msg) if not msg.tool_calls: return msg.content for call in msg.tool_calls: fact = json.loads(call.function.arguments).get("fact", "") store.add(fact) print(f" saved memory: {fact}") messages.append({"role": "tool", "tool_call_id": call.id, "content": json.dumps({"saved": True})}) return "Stopped at the step limit." if __name__ == "__main__": Path("asha_memories.json").unlink(missing_ok=True) # start the demo from an empty memory store = MemoryStore("asha_memories.json") # Session 1 print(run_turn("I'm Asha. Please remember that I am vegetarian.")) # Session 2: a brand new message list. Only the memory store connects them. print(run_turn("Suggest a dinner spot for my first night in Kyoto."))
- Saving is a tool. The model decides when something the user said is a lasting preference and calls
remember. That needs judgement, so it belongs to the model. - Recall happens in code, every turn. Before each model call, the code searches the store with the user's message and puts the matches into the system prompt. It does not wait for the model to decide to look something up.
Why recall in code? Because the model cannot know what it has forgotten. A model that does not know Asha is vegetarian has no reason to search for dietary facts before suggesting a steakhouse. Running recall automatically means relevant facts are always present.
sequenceDiagram autonumber actor U as User participant C as Agent code participant S as MemoryStore participant M as Model Note over U,M: Session 1 U->>C: Asha is vegetarian C->>S: search(user message) S-->>C: nothing, store is empty C->>M: messages + remember tool M-->>C: remember: Asha is vegetarian, so meals... C->>S: add(fact): embed and save to JSON Note over U,M: Session 2, new messages list U->>C: Suggest a dinner spot in Kyoto C->>S: search(user message) S-->>C: the vegetarian fact C->>M: system prompt with the recalled fact M-->>C: Kyoto has many vegetarian restaurants...
Diagram: Saving is a tool the model calls. Recall runs in code before every model call, so session 2 sees session 1's fact.
What happened in the test run
Running python memory_agent.py with qwen2.5:1.5b and all-minilm on Ollama:
- Session 1. Nothing was recalled because the store was empty. The model called
rememberwith "Asha is vegetarian, so meals and restaurants must be vegetarian." The sentence followed the tool description's example closely, context words included. - Session 2. A brand new messages list. Recall found the vegetarian fact for "Suggest a dinner spot for my first night in Kyoto." The reply mentioned that Kyoto has many vegetarian restaurants, but asked what kind of cuisine Asha wanted instead of suggesting a spot.
So memory worked end to end: a fact from one session shaped the next one. The final answer was cautious rather than specific, which is typical of a small model without a restaurant tool. The trip helper has no restaurant data, so asking a follow up question is a reasonable result.
In an earlier test, the memory was saved as the short "Asha is vegetarian." and the recall threshold was 0.2. In that run, session 2 recalled nothing and the reply ignored the diet completely. Lowering the threshold and adding context words to the stored fact fixed it. That before and after is a good reason to log what your agent recalls on every turn, as the code does with print.
Memory needs rules
Long-term memory stores personal information, so treat it with care:
- Save only what helps the task. A trip helper needs diet and travel preferences, not everything the user mentions.
- Let users see and delete memories. With a JSON file that is easy: show
store.texts, remove an entry, save. - Handle contradictions. If Asha later says "I eat fish now", the old fact should be replaced, not kept alongside. A simple approach is to search for close matches before saving and ask the model whether the new fact replaces one of them.
- Do not store secrets. Passwords and card numbers have no place in an agent's memory.
Common mistakes
- Comparing vectors from different embedding models. Re-embed everything when you change models.
- Forgetting to normalize and then treating the dot product as cosine similarity.
- Thresholds copied from a tutorial. Scores depend on the model. Print scores for your own data and pick a threshold from what you see.
- Letting the model decide when to recall. It cannot search for what it does not know it is missing.
- Saving everything. Memory full of trivia makes retrieval worse, not better.
What to try next
- Add "Asha does not eat meat or fish, which matters for restaurants and meals." to
search_demo.pyand see where it ranks for the restaurant question. - Set
AGENT_EMBED_MODEL=nomic-embed-text(afterollama pull nomic-embed-text), delete the JSON files, and compare scores. Notice that thresholds need adjusting. - Add a
forget(fact)tool that removes the closest matching memory. - Before saving, search for memories with a score above 0.8 and print them, to spot near duplicates.
Next you will use the same embedding search for a different job: letting the agent search a document collection when it needs facts it was never trained on. That is agentic RAG, with retrieval as a tool the agent chooses to call.
Sources
Find the memories closest to a question
Long-term memory stores facts as embedding vectors. To recall, embed the question and pick the stored facts whose vectors point the most the same way, measured by cosine similarity.
Write recall(query_vec, memories, k=2, min_score=0.0).
- memories is a list of (text, vector) pairs.
- Cosine similarity is dot(a, b) / (|a| * |b|).
- Drop memories scoring below min_score, sort the rest from highest to lowest score, and return the texts of the top k.
The worked solution unlocks after your first attempt.
Check what you learned
Answer all 3 questions. You need at least 2 right to pass.
1. Why are the vectors normalized to length 1?
2. Why does recall run in code on every turn instead of as a tool?
3. The restaurant question did not retrieve 'Asha is vegetarian.' What helped?