AI Agent Memory That Actually Works: Persistent Memory, Context Compression, and Cutting Token Costs

An AI agent without memory restarts from zero on every task, repeating questions, mistakes, and expensive context. This guide shows a practical memory design — what to keep, where to keep it, how to retrieve only what matters, and how to compress the rest so long-running agents stay useful without burning tokens.
01 / Why agents forget
A language model does not remember your last session by itself. Everything it “knows” about a task has to fit inside the current context window: the system prompt, the conversation so far, tool results, and any files you load. When the session ends, that working context disappears. When the session gets long, older material is truncated or buried, and the agent starts contradicting decisions it made an hour earlier.
This is not a model-quality problem you can prompt your way out of. It is an architecture problem. The fix is an external memory the agent reads and writes deliberately — a small, curated store outside the model — plus clear rules for when to save, retrieve, and forget.
02 / Three kinds of memory
Most confusion about agent memory comes from mixing up three different things. Working memory is what is in the context window right now: the current request, the plan, and the last few tool results. Short-term or session memory survives within one job — a running summary, intermediate findings, and a to-do list — but is discarded or archived when the job ends. Long-term persistent memory survives across sessions: stable facts, preferences, decisions, and lessons that should still be true next week.

| Layer | Lives where | Typical contents | Lifetime |
|---|---|---|---|
| Working memory | Context window | Current request, active plan, recent tool output | Minutes, one conversation turn at a time |
| Short-term / session memory | Scratch notes for one job | Running summary, intermediate findings, open questions | One task or one session |
| Long-term persistent memory | External store the agent reads and writes | Preferences, confirmed facts, decisions, recurring procedures | Weeks to months, until reviewed or expired |
The practical rule is simple: promote information upward only when it earns it. A fact moves from working memory to session notes when the current job needs it again, and into long-term memory only when it is confirmed, reusable, and likely to matter in a future, different task.
03 / What to store — and what never to store
Store decisions and their reasons, stable preferences, confirmed facts about people, projects and systems, and procedures that worked. Store them as short, dated statements, not as raw transcripts. “On 2026-11-20 the team chose daily publishing at 09:00 because mornings performed best in their existing routine” is a memory. A full chat log is not — it is an archive nobody will retrieve cleanly.
Never store secrets or credentials, API keys, passwords, or one-time codes. Never store raw personal data — full addresses, ID numbers, payment details, or private messages — unless a task explicitly requires it and you have a protected place for it, which a plain memory file is not. And never store unverified model claims as facts: if the agent guessed it, label it as a guess or do not save it at all. A wrong memory is worse than no memory, because future sessions will trust it.
04 / Where to store it: three practical options
Start with the simplest store that works. Plain files — Markdown or YAML in a folder — are readable, editable, and easy to back up, and for a personal agent they are often enough. When the store grows and you need fast keyword lookup, SQLite with full-text search gives you structured queries and ranking on your own machine, with no server to run. Vector stores are the third step, useful when retrieval is by meaning rather than exact words, but they add moving parts and can return plausible-looking, irrelevant matches.
| Option | Pros | Cons | Best for |
|---|---|---|---|
| Files (Markdown / YAML) | Human-readable, easy to edit and back up, zero setup | Slow to search at scale, no ranking | Starting out, small curated memory |
| SQLite + full-text search | Fast keyword search, structured fields, runs locally | Less readable by eye, needs a small amount of code | Growing stores, dated and tagged facts |
| Vector store | Retrieves by meaning, handles paraphrases | Extra infrastructure, fuzzy matches need checking | Large document collections, semantic recall |
Whichever you choose, keep one memory entry small and self-contained, with a date and a source. Here is an illustrative structure:
---
type: preference
date: 2026-11-20
source: confirmed by the user
review_by: 2026-12-20
---
Prefers a concise summary over the raw transcript for weekly reports.05 / Retrieval rules: load less, but load the right thing
Memory only helps if retrieval is disciplined. The most common failure is loading everything “just in case”: the context fills with stale facts, the current task gets a smaller share of attention, and costs rise. Instead, retrieve by task. Before a job starts, search memory with the job’s key terms, load the few entries that match, and leave the rest in the store.
Use lazy loading throughout the job as well. Load a project’s background only at the step that needs it, and a person’s preferences only when writing to that person. Retrieval is cheap; a bloated prompt is expensive on every turn.
- Match first: search by topic, person, or project before loading anything.
- Cap the load: set a small limit on entries per task and raise it only when a step fails for missing context.
- Prefer recent and confirmed: when entries conflict, the newer, source-backed entry wins — and the conflict gets flagged.
06 / Context compression: keep the signal, drop the bulk
Even with good retrieval, a long job fills its own context. Compression is how you shrink it without losing the thread. The highest-value technique is summarizing completed steps: once a research phase is done, replace twenty tool results with a five-line summary of what was found and decided, and drop the raw output. The work is finished; only its conclusion needs to travel forward.

Three more techniques stack on top. Prune tool results as they arrive: keep the lines that answer the question, not the whole page. Use terse output formats for intermediate work — short lists and tables instead of full sentences — when no human will read that step. And cache stable context: instructions, style guides, and project background that do not change during a job should be stated once, in a fixed place, rather than repeated and re-derived in every turn.
- Summarize completed steps into decisions and findings.
- Prune tool output to the relevant lines immediately.
- Shorten intermediate output; save full prose for deliverables.
- Cache stable background once, in one place.
07 / A worked cost example (illustrative numbers only)
The numbers below are a worked example with simple round figures, invented for the calculation. They are not any provider’s real pricing, and they are not benchmark results. The point is the shape of the saving, which you can re-run with your own actual rates.
Example calculation. Suppose an agent runs 20 turns on a long task, and suppose the illustrative price is $1 per 100,000 input tokens. Without memory discipline, imagine it carries 50,000 tokens of background and raw tool output on every turn: 20 × 50,000 = 1,000,000 input tokens, costing 1,000,000 ÷ 100,000 × $1 = $10 in this example. With curated memory and compression, imagine it carries 15,000 relevant tokens per turn instead: 20 × 15,000 = 300,000 tokens, costing $3 on the same made-up rate. The illustrative saving is $7 of $10 — not because the model got cheaper, but because 70% of what it was re-reading every turn was bulk it never needed.
Treat any such estimate as a planning sketch, not a promise. Measure your own before-and-after token counts on one recurring job; that single honest measurement is worth more than any generic percentage.
08 / Memory hygiene: review, expire, correct
Memory rots. Preferences change, projects end, and a fact that was true in October misleads in December. Build a small hygiene routine instead of trusting the store forever. On a regular cadence — monthly is a sensible default for a personal agent — review entries that affect upcoming work, delete what is no longer true, and add a review date to anything time-sensitive when you first save it.
Correction matters as much as deletion. When a memory turns out to be wrong, replace it with the corrected fact and note that it was corrected, so the agent does not “rediscover” the old version from an archive. And when two entries conflict, resolve the conflict at review time rather than leaving the agent to guess which one a future task should trust.
09 / Starter checklist
You do not need a platform to start. A folder, a few rules, and a monthly review will take a personal agent most of the way. Use this checklist to set up the first version in an afternoon, then improve it only where real tasks show friction.
- Separate working, session, and long-term memory — and promote facts upward only when confirmed and reusable.
- Store short, dated, source-backed statements; never store secrets, raw personal data, or unverified claims as facts.
- Start with Markdown files; move to SQLite full-text search or a vector store only when retrieval actually hurts.
- Retrieve by task, load lazily, and cap how much memory any single job pulls in.
- Compress as you go: summarize finished steps, prune tool output, shorten intermediate formats, cache stable context.
- Run your own before-and-after token count on one recurring job, using your real rates.
- Review monthly: delete the stale, correct the wrong, resolve conflicts, and refresh review dates.
Done well, memory is invisible: the agent stops asking what it already knows, stops repeating finished work, and spends its context — and your budget — on the task in front of it. That is what makes an agent feel like a teammate instead of a chatbox with amnesia.
