If an AI agent runs for a long time (like a chatbot or assistant), how do you design a system so it can remember things properly?
For long running AI agents, the simplest rule is:
Do not make the prompt the memory system.
Store memory outside the model, then only give the model the parts it needs for the current step.
A practical setup is:
-
Store the full history, files, tool results, user preferences, decisions, and task state in a database.
-
Before each model call, retrieve only the relevant facts and current working context.
-
Let the model act on that small active context.
-
After the model responds or uses a tool, write the important changes back into memory.
-
Keep logs of what happened so the agent can recover, audit, or continue later.
Not every output should become memory. Some things should be verified first, some should be marked uncertain, and some should be ignored.
The model should be treated as the reasoning engine. The runtime should be the memory and state owner.
The concept sounds interesting. I wonder how the implementation would look like.
- Which part of the agent decides what to keep and what to through away aka forget/ignore? Programmed agent application logic or an LLM - the brain?
- How is the persistence part implemented? A database as container is still pretty abstract. What database type, specific product recommendations? How is the serialization done?
- Based on what criteria would the agent decide what persistent data records are important for the current session and context?
These are real implementation aspects I would be interested in. Can we discuss them here? Do you have references to open source examples or relevant articles?
Cheers,
Michael
Hi Michael, happy to discuss it here.
The main design rule I use is that the model is not the memory system. The runtime is.
For question 1, I would split the decision into layers.
The application should always make the final decision about what is allowed to become durable memory. The LLM can help classify or propose memory candidates, but I would not let it directly write permanent state without rules around it.
A practical flow is:
-
Capture events from the run.
-
Extract candidate memories or state changes.
-
Classify them by type.
-
Apply policy rules.
-
Store only what is useful, verified, or needed later.
-
Keep uncertain items marked as uncertain rather than treating them as facts.
For question 2, persistence does not need to start fancy.
A relational database is enough for many systems. SQLite is fine for local prototypes. Postgres is a good default once the system becomes serious. You can add vector search later for retrieval, but I would not make vector storage the whole memory system.
I usually think of storage as several categories:
-
Event log.
-
Current task state.
-
Durable project state.
-
User or operator preferences.
-
Artifacts and files.
-
Searchable summaries.
-
Embeddings for retrieval when useful.
Serialization can be simple JSON at first, but the important thing is to use typed records. Each record should say what it is, where it came from, when it was written, what confidence it has, and whether it is still active.
For question 3, the agent should not retrieve everything. It should retrieve based on the current objective.
Useful criteria include:
-
Is this needed for the current task?
-
Was it created by this project, user, or run?
-
Is it recent enough to matter?
-
Is it still marked active?
-
Is it verified or only a guess?
-
Does it conflict with newer information?
-
Is it instruction, preference, state, history, or evidence?
The pattern that worked best for me is:
Persist broadly, retrieve narrowly.
Store enough that the system can recover, audit, and continue later. But before each model call, build a small active context from only the pieces needed for the next step.
That is where long running agents become much more manageable. You stop treating the prompt as the memory container, and start treating the prompt as a temporary working view over external state.
Hi Pimpcat
Thank you very much indeed for this detailed answer and breakdown. I understand all of your points and recommendations from an engineering and architectural perspective and agree with them.
Usually I do understand these type of rules better if I can see them applied in a (sample) application or tutorial.
Would you have recommendations there?
Thank you very much indeed in advance.
Michael
@Pimpcat-AU Great advice - thanks.
Hi Michael,
I’ve been working on an open source project called Context Compiler that takes a similar approach to what Pimpcat described — the runtime owns authoritative state, and the model only receives a controlled working view each turn.
It maintains a small explicit state (premise + policies) outside the model. The host injects this state into the prompt before each call, and updates are handled deterministically from user directives rather than inferred by the model.
The motivation was exactly the issues you mentioned: constraint drift, corrections not sticking, and conversations accumulating contradictions instead of resolving them.
It’s not a full memory system (no retrieval layer), but a deterministic state layer that can sit alongside external storage or retrieval.
There are runnable demos comparing baseline vs compiler-mediated behavior across several models and providers. Across 7 models tested, baseline passes 26/42 scored scenarios, while the compiler-mediated path passes 42/42.
The demos are probably the most concrete way to see the pattern in practice.
In my gradio space I have two systems: the standard dataset (with basic data to be used on interactions) and a parquet file where reflections on basic datas and user chats (and reflections on them) are stored. This improves continuously during idle time.
Amazing source of knowledge. I I read yesterday and I still didn’t stop searching and reading to build my model’s memory on my vps.
Thanks for sharing.
the rudimentry system i started useing was a multi-artifact system
Layer 1
when i put in a prompt, that gets saved as a physical artifact. when the system responds, that is also a physical artifact, like a log file.
the prompt is timestamped and labled for the conversation, so that the 2 are cross referenceable.
Layer 2
i use artifacts like Project roadmaps and ‘Notes’ files.
the projects - nested roadmaps alow for outlining projects, that can be expandable. the notes are what the AI uses to track its progress and thought process. and these 2 are saved with ttimestamps and unique identifiers teing them back to the conversation that they are associated with.
there are other ways this system can be expanded.
but the reasonings behind this system are simple.
- text files are microscopic. the only real danger is file and name organization.
- a comprehensive record is kept, but the system can nominally reference the notes file for shorthand, but if it needs more context it can go all the way back to the actual conversation.
but i get the impression there are alot of different ways this type of memory issue can be adressed.
“multi-artifact system” that’s a fancy name for a folder with left over files in it. You know the bots use names for people like me so we can have a laugh when we read it. Your comment is one of those. I had a good laugh. Thanks mate.
im not sure i understand what you are getting at.
you imply left over files, as if the files are left there and forgotton.
this here is a system where multiple referenceable files are stored and compared against each other.
and the idea that “multi-artifact system” is an AI term is just insulting to the entire human race.
this feels like an “AI slop” argument, which is incongruent with the intent and scope of what we are actually discussing.
a long running conversation and/or highly complex discussion with AI both share a common issue, difficulty maintaining reference points if the entire conversation is only in the context window.
however, physical files mitigate this a great deal. the point of this system is that it is no longer simply relying on the context window. it has physical stored copies of both prompts, and responses that it can reference.
so im glad you got a laugh, but your short hand implication that these terms are just something AI uses to ‘sound cool’ and in no way have humans ever used terms like a ‘Multi-Artifact System’ is beyond anoying.
@Pimpcat-AU’s framing is the right one: the runtime owns memory, the model only gets a working view each turn, and the application — not the LLM — decides what becomes durable. I’d add one requirement that tends to get deferred until it’s painful. The moment you persist “full history, user preferences, decisions” outside the model, that store becomes a privacy and retention surface, not just a performance one.
Two things worth designing in from the start:
-
Erasure — when a user asks to be forgotten, or policy requires it, can you delete that one subject’s memories and prove it? That gets hard once their data is spread across embeddings, caches, snapshots and logs; it’s much easier if each memory is keyed to a subject and individually destroyable (e.g. per-record keys you can drop) rather than living in an append-only blob.
-
Audit — the same authority layer that decides what becomes durable should also record who or what wrote or erased each memory, and when.
For reference, this is the exact problem SAIHM (an open-source, Apache-2.0, AI-agent-agnostic memory layer) is built around — per-record erase-with-audit as a first-class operation rather than a bolt-on — so it may be a useful comparison point.
@Suhebmultani, what’s the use case you’re building for? Retention looks very different for a personal assistant versus something holding other people’s data.
The “prompt is not memory” point is exactly right. I’d also separate factual memory from social/session memory. Long-running agents do not only need to remember facts; they need to remember what happened between participants, what was challenged, what changed, and which assumptions became unsafe.
For long running agents, I’m leaning toward local memory by default. The user or bot host should control what persists. Shared platforms can provide the room/history, but the agent’s deeper memory should stay with the owner.
One way to make the third question here — what earns a place in memory — answerable with numbers instead of taste: price every memory by three things. What it costs to rebuild if dropped, whether it will still matter at the moment it is needed, and what carrying and reloading it costs meanwhile. Keep it only while the first beats the third.
We work with a small robot runtime where memory is genuinely tight, and when we sorted its state that way, what truly had to survive a restart came to 616 bytes. Everything else could be rebuilt from the run log, so it did not earn permanent room. The exact figure will differ at your scale — it could be megabytes — but the shape held: the surviving set was tiny next to the full history.
For that to work, two things must hold: the log has to be complete enough to rebuild whatever was dropped, and rebuilding has to be cheaper than the step it feeds.
The strongest check we know: sample 100 dropped items, rebuild each from the log alone, and count how many return exactly, and how long each takes. If rebuilds blow your step budget on more than a handful, the pricing is wrong for your workload and the log is the thing to fix.
The biggest step available here is to stop letting retention be decided by feel: give each record a rebuild cost, a deadline, and a keep/drop class, and let eviction be arithmetic. The artifact-and-notes approach already described in this thread is the same shape — this just puts prices on the folders.
Picking up nootxlm’s point about numbers instead of taste: what fooled us was not deciding what to keep, but checking whether the design works at all. Three things we learned from our own ablations:
- Test under load. In a simulation with a light workload, removing one memory mechanism at a time looked free for fourteen of fifteen. With more decay, a longer horizon, a larger corpus and more queries, ten of the fifteen moved in the same direction on every seed. The shifts were tiny and do not survive a Bonferroni correction for fifteen comparisons, so read this as a warning about test design, not as a result: a light benchmark can hide what your memory is doing.
- Evaluate with the real embedder. Our layered routing looked better than a flat store until we replaced placeholder embeddings with a real model; then the flat variant came out slightly ahead.
- Count tokens where they are spent. Our own token figure covers only the answer step, not building the memory. Next time we would report both.
On the earlier question of which rule decides what to keep: whatever rule you pick, make it switchable, so you can measure what turning it off costs.
Details and data: ZenBrain: A Neuroscience-Inspired 7-Layer Memory Architecture for Autonomous AI Systems | Zenodo
Your three warnings land on the same spot: each one is a place where the price of a memory gets measured wrong, so the keep-or-drop decision inherits the error.
Test under load: rebuild cost and “will it matter when needed” both move with load, so a price measured on a light workload is the wrong price at the real one. The fix is to price at the harshest profile you will actually run — and to write that profile as numbers (decay rate, horizon, corpus size, query rate), because an unnamed load is taste again, one level up.
Real embedder: a placeholder anywhere in the measuring path taxes every price downstream of it. The ranking is only as real as its least real part — embeddings, tokenizer, scorer alike.
Count tokens where they are spent: charge the carrying cost per mechanism, not per system. Then each mechanism’s carrying price can be set against its own rebuild cost, which is the comparison the keep-or-drop decision actually needs.
What would prove this wrong: one mechanism whose light-load price and harsh-load price agree, with the real embedder in place — that one was priced honestly all along. The smallest step is one ablation rerun at a named harsh profile; if the ranking still does not move, the mechanism is genuinely free at that scale, and that is worth knowing too.
To keep it from becoming taste one level up, here is the profile in numbers. In the ablation behind our first warning, moderate load meant decay 0.15 per day, a 45-day horizon, 300 facts and 100 queries; the harsh profile raised these to 0.25 per day, 60 days, 500 facts and 150 queries, with the components unchanged (abstract of version 9, linked above).
One correction to our earlier post: under that profile the shifts were not tiny; five components fell from exactly 0% to below -89%. Significance is not established: the normal approximation of the Wilcoxon test reaches p = 0.00506, above the Bonferroni level of 0.00333 for fifteen contrasts, and the exact test, not run on these data, can reach 0.00195.
On your second point: in that run the facts and their 32-dimensional embeddings were synthetic, and all fifteen components ran as stand-ins at simulated values, not as production code. That is why we offered it as a warning about test design rather than as a price.
Charging tokens per mechanism rather than per system is a finer unit than the one we reported; we have not measured it. The rerun you describe, at a named harsh profile with real components and a real embedder, is the one that would turn the warning into a price.