DEV Community

Arun Purushothaman
Arun Purushothaman

Posted on

Agents in 60 lines of python : Part 6

Memory Across Runs

Lesson 6 of 9 — A Tour of Agents

The entire AI agent stack in 60 lines of Python.

State tracks everything — turns, tool calls, results. But close the session and it's gone. Start a new conversation and ask the agent your name. Blank. It has no idea.

ChatGPT remembers your name across chats. Here's how that works — and it's simpler than you think.


The problem

Your agent has a state dict. It records everything that happens during a run. But state lives in memory. When the process ends, the dict disappears. Next time you run the agent, it starts fresh — no history, no context, no memory of previous conversations.

This is the difference between a chatbot and an assistant. An assistant remembers.


The fix: a tool called remember

Give the agent a tool called remember. It doesn't do anything clever — it saves a key-value pair to a dictionary. That dictionary gets written to disk (or a database) and loaded back into the system prompt on every new run.

The agent calls remember like any other tool. Run 1 saves data. Run 2 loads it. The memory dict gets injected into the system prompt so the LLM can see everything it previously stored.


The code

tools = {
    "remember": lambda key, value:
        memory.update({key: value}) or f"saved {key}={value}",
}
Enter fullscreen mode Exit fullscreen mode

One tool. That's the whole trick. The remember lambda takes a key and value, updates the memory dict, and returns a confirmation string. Before each run, you load the dict from disk. After the agent finishes, you save it back.


Watch it work

Session 1: Tell the agent "my name is Alice." It calls remember(name, Alice) — saved. The memory dict now holds {name: "Alice"}.

Session 2: New process. The memory dict gets loaded from disk and injected into the system prompt. Ask "who am I?" The agent sees the memory and answers: "Alice."

No retrieval-augmented generation. No vector database. No embeddings. Just a dict that persists between runs and a tool that writes to it.


Try it

Run this code yourself at tinyagents.dev. Add your own memory fields — preferences, facts, conversation summaries — and watch your agent become an assistant that actually remembers.

Next up: Lesson 7 — Policy. The agent can remember and act. But who decides what it's allowed to do?


This is Lesson 6 of A Tour of Agents — a free interactive course that builds an AI agent from scratch. No frameworks. No abstractions. Just the code.

🎬 Video: lesson06-memory.mp4

Top comments (0)