Agent memoryAgent memory

Memory không phải là một context to hơn. Agent memory is not a bigger context.

Model quên. Hệ thống nhớ. Nó nhớ bằng cách chọn: lấy gì từ kho ra, đưa gì vào context, và giữ lại gì sau mỗi lượt. Không phải chi tiết nào cũng là ký ức. The model forgets. The system remembers. It remembers by choosing: what to pull from storage, what to put in context, and what to keep after each run. Not every detail is a memory.

Chỉnh so với ảnh gốc: working memory không phải một kho lưu lâu dài. Nó chính là context của lượt đang chạy, nên sơ đồ bên cạnh vẽ nó thành khung context. Correction to the source image: working memory isn’t a long-term store. It is the context of the current run, so the diagram draws it as the context frame. Trang gộp hai ảnh: bốn kho và vòng đọc – ghi (HackProduct), cộng ba thứ khác hay được gọi là memory từ ảnh “7 loại” (Brij Kishore Pandey). This page merges two images: four stores and the read–write loop (HackProduct), plus three more things often called memory from the “7 types” image (Brij Kishore Pandey).

Agent memory read–write loop Three long-term stores feed a selective reader. Only three items reach the context window, which is the working memory. The agent acts on exactly those. A write gate saves a durable preference back to semantic memory and drops temporary state. Dashed lines are decisions made at run time. 01 stores Episodic Last trip: JFK +900 more Semantic Prefers aisle +900 more Procedural Travel policy +900 more 02 read search(“trip like last time”) 03 context = working memory “Plan my Austin → NYC trip like last time.” Last trip: JFK Prefers aisle Travel policy left out: hotel dates, home city, 14-day rule… 04 act search_flights() morning, aisle, JFK 05 write Worth saving? ✓ < 10 AM ✗ Price: $312 temporary state
Nét đứt là quyết định lúc chạy: lấy gì ra, và ghi gì lại. Nét xanh chạy ngược lên là write-back: chỉ sở thích bền vững được quay về kho. Dashed lines are run-time decisions: what to read, and what to write. The green line running back up is the write-back: only a durable preference returns to storage.

Chọn cái nàoWhich one

Hỏi lần lượt từ trên xuống. Dừng ở câu đầu tiên trả lời “có”. Ask from the top down. Stop at the first “yes”.

Tác vụ xong trong một phiên, hoặc thông tin cần nhớ vừa một trang giấy?Does the task finish in one session, or does what you need to know fit on one page?
Chưa cần memory. Dùng một file tĩnh viết tay nạp vào system prompt, cộng lịch sử phiên.No memory yet. Use a hand-written static file in the system prompt, plus session history.
Thông tin thay đổi theo giờ: giá, tồn kho, trạng thái?Does it change by the hour: price, stock, status?
Không lưu. Gọi tool lấy lại khi cần.Don’t store it. Re-fetch with a tool when needed.
Chỉ cần trong lượt chạy này?Only needed during this run?
Working. Giữ trong state, hết lượt thì bỏ.Working. Keep it in state, drop it at the end.
Là cách làm: quy tắc, quy trình, kỹ năng?Is it a how-to: a rule, procedure or skill?
Procedural. Agent đề xuất, người duyệt.Procedural. Agent proposes, a human approves.
Là điều đúng và ổn định về người dùng hay thế giới?Is it a stable truth about the user or the world?
Semantic. Ghi đè khi đổi, lưu kèm nguồn.Semantic. Overwrite on change, keep the source.
Là chuyện đã xảy ra và kết quả của nó?Is it something that happened, and how it turned out?
Episodic. Có dấu thời gian, cho phai dần.Episodic. Timestamped, allowed to fade.
Là tài liệu có sẵn, lớn hơn context, hay đổi?Is it existing documents, bigger than the context, changing often?
Retrieval. Vừa context thì cứ nhét thẳng vào prompt.Retrieval. If it fits in context, just put it in the prompt.
Cần hành động vào lúc khác, hoặc khi một điều kiện xảy ra?Does it need action later, or when a condition is met?
Prospective. Ghi vào scheduler thật, không phải dặn model.Prospective. Write to a real scheduler, not a note to the model.
Cần đổi hành vi ở mọi lần gọi, quy mô lớn, đã thử hết các cách trên?Need a behaviour change on every call, at scale, after trying all of the above?
Parametric. Fine-tune để dạy hành vi, không để nạp dữ kiện.Parametric. Fine-tune to teach behaviour, never to load facts.

Mẹo phân loại: bỏ hết ngày tháng khỏi câu. Vẫn đúng là semantic; mất nghĩa là episodic; bắt đầu bằng “luôn”, “không bao giờ”, “khi X thì Y” là procedural. Quick test: strip every date from the sentence. Still true means semantic; meaningless means episodic; starting with “always”, “never” or “when X, do Y” means procedural.

Bốn kho nhớFour stores

Mỗi kho trả lời một câu hỏi khác nhau. Màu trên tab là loại kho, giữ nguyên ở mọi nơi trên trang. Each store answers a different question. The tab colour marks the store type and stays the same everywhere on this page.

W

Working

đang làm gì · một lượtwhat am I doing · one run
[system][memory][chat][tool results][notes]
└──── context window, hữu hạn / finite ────┘

Trạng thái của lượt đang chạy: yêu cầu, kế hoạch, kết quả tool. Về kỹ thuật là context window cộng state của vòng lặp agent.The state of the current run: request, plan, tool results. Technically, the context window plus the agent loop’s state.

Dùng choUse for
So sánh chuyến bay cho chuyến này, danh sách file đã sửa trong phiên, form nhiều bước.Comparing flights for this trip, files edited this session, multi-step forms.
ĐượcGain
Không cần hạ tầng, truy cập tức thì, luôn mới, tự dọn khi hết lượt.No infrastructure, instant access, always fresh, cleans itself up.
MấtLose
Mất sạch khi kết thúc hoặc crash; bị trần context chặn; tóm tắt thì mất chi tiết.Gone at the end or on a crash; capped by context; summaries lose detail.

Đổi khả năng nhớ qua phiên lấy tốc độ, độ tươi và sự đơn giản.Trades cross-session recall for speed, freshness and simplicity.

Dấu hiệu:Sign: xong việc mà vứt đi cũng không ai tiếc.nobody would miss it once the task is done.

E

Episodic

đã xảy ra gì · thángwhat happened · months
03-02 │ Austin→NYC │ JFK 8:05, aisle │ ✓
05-17 │ Austin→SFO │ 6:00 AM         │ ✗ too early

Nhật ký có thời gian: bối cảnh, hành động, kết quả, phản hồi. Truy xuất tập tương tự để làm few-shot từ chính lịch sử người dùng.A timestamped log: situation, action, outcome, feedback. Similar episodes are retrieved as few-shot examples from the user’s own history.

Dùng choUse for
“Đặt như lần trước”, ticket cũ của cùng khách, lần trước sửa lỗi build thế nào.“Book it like last time”, a customer’s past tickets, how this build error was fixed before.
ĐượcGain
Học từ kết quả thật không cần fine-tune; kiểm toán được; nguyên liệu cho semantic.Learns from real outcomes without fine-tuning; auditable; feeds semantic facts.
MấtLose
Phình không giới hạn; dễ lấy nhầm tiền lệ; khái quát từ một lần; nhiều dữ liệu cá nhân nhất.Grows unbounded; wrong precedents; generalizing from one case; the most personal data.

Đổi dung lượng và độ phức tạp truy xuất lấy khả năng học từ lịch sử thật.Trades storage and retrieval complexity for learning from real history.

Dấu hiệu:Sign: câu hỏi có “lần trước”, “như hôm đó”.the request says “last time” or “like that day”.

S

Semantic

điều gì đúng · đến khi bị thaywhat’s true · until replaced
user:42 ─ prefers ─► aisle   (src ep#118)
user:42 ─ home ────► Austin
user:42 ─ flies ───► < 10:00  (confirmed)

Sự thật ổn định, không gắn với một sự kiện. Lưu thành profile, danh sách fact hoặc graph; fact mâu thuẫn thì ghi đè, không để song song.Stable facts not tied to one event. Stored as a profile, fact list or graph; conflicting facts overwrite rather than coexist.

Dùng choUse for
Tên, múi giờ, sở thích; “repo này dùng pnpm”; dị ứng, hạn mức chi.Name, time zone, preferences; “this repo uses pnpm”; allergies, spending limits.
ĐượcGain
Một dòng thay mười tập; truy xuất theo khoá rẻ, gần như không trượt; người dùng xem và sửa được.One line replaces ten episodes; cheap key lookup that rarely misses; users can review it.
MấtLose
Lỗi thời âm thầm; suy luận sai thành “sự thật”; thiếu nguồn thì khó gỡ.Goes stale silently; bad inferences become “facts”; unsourced facts are hard to remove.

Đổi bối cảnh của từng sự kiện lấy một bản tóm lược gọn, rẻ, dùng lại được.Trades per-event context for a compact, cheap, reusable summary.

Dấu hiệu:Sign: bỏ ngày tháng đi câu vẫn đúng.still true with every date removed.

P

Procedural

làm thế nào · đến khi được sửahow to · until changed
system prompt ─┐
policies.md ───┼─► mọi lượt / every turn
skills/*.md ───┘   (+ agent code = hard form)

Quy tắc, chính sách, quy trình, kỹ năng. System prompt và mã agent là dạng cứng; file quy tắc và thư viện kỹ năng là dạng cập nhật được.Rules, policies, procedures, skills. The system prompt and agent code are the hard form; rule files and skill libraries are the updatable form.

Dùng choUse for
Đặt vé trước 14 ngày, coding convention, cách deploy, không gửi email khi chưa xác nhận.Book 14 days ahead, coding conventions, how to deploy, no external email without confirmation.
ĐượcGain
Viết một lần, nhất quán mọi lượt; đổi hành vi không cần fine-tune; quản lý bằng git.Write once, consistent every turn; changes behaviour without fine-tuning; lives in git.
MấtLose
Một quy tắc sai lặp lại ở mọi lượt; là bề mặt tấn công (memory poisoning); quy tắc chồng chéo dần.One wrong rule repeats every turn; an attack surface (memory poisoning); rules pile up and conflict.

Đổi sự linh hoạt theo từng tình huống lấy hành vi nhất quán, dự đoán được.Trades case-by-case flexibility for consistent, predictable behaviour.

Dấu hiệu:Sign: câu bắt đầu bằng “luôn”, “không bao giờ”.the sentence starts with “always” or “never”.

Ba thứ khác cũng gọi là memoryThree more things called memory

Không phải kho agent ghi trong lúc hội thoại: một cái là đường truy cập, một cái nằm trong trọng số, một cái nằm trong scheduler. Not stores the agent writes during a conversation: one is an access path, one lives in the weights, one lives in a scheduler.

R

Retrieval

tài liệu có sẵn · theo nguồnexisting documents · follows source
query ─▶ embed ─▶ top-k ─▶ rerank ─▶ prompt
            vector DB / BM25 / SQL

Đường truy cập, không phải nơi lưu: lấy đoạn tài liệu liên quan (wiki, chính sách, bảng giá) đưa vào context khi cần.An access path, not a store: pulls relevant passages (wikis, policies, price lists) into context when needed.

Dùng choUse for
Hỏi đáp trên kho tài liệu lớn hơn context nhiều lần, nội dung đổi hằng tuần, cần trích dẫn nguồn, phân quyền theo tài liệu.Q&A over a corpus many times the context size, content that changes weekly, answers needing citations, per-document permissions.
ĐượcGain
Cập nhật chỉ cần re-index; truy được nguồn; mở rộng gần như không giới hạn.Updates only need reindexing; answers are traceable; scales almost without limit.
MấtLose
Tìm trượt thì trả lời sai mà model không biết; câu hỏi “liệt kê tất cả” gần như không giải được; thêm một hệ thống phải vận hành.A retrieval miss means a wrong answer the model can’t see; “list every…” questions barely work; one more system to run.

Đổi độ phức tạp vận hành và rủi ro tìm trượt lấy tri thức không giới hạn, luôn cập nhật.Trades operational complexity and miss risk for unlimited, always-current knowledge.

Dấu hiệu:Sign: kho tài liệu lớn hơn context nhiều lần.the corpus is many times the context size.

P

Parametric

trọng số · đến khi huấn luyện lạiweights · until retrained
training data ──▶ [ weights ] 🔒 ──▶ every answer
        update = retrain / fine-tune

Tri thức và hành vi nén vào trọng số lúc huấn luyện. Không được “tra cứu” mà ảnh hưởng ngầm lên mọi đầu ra.Knowledge and behaviour compressed into the weights during training. Not looked up; it shapes every output implicitly.

Dùng choUse for
Kiến thức chung (đã có sẵn); ép giọng văn, định dạng ở quy mô lớn; distillation cho một task hẹp lặp hàng triệu lần.General knowledge (already there); enforcing tone or format at scale; distilling a narrow task repeated millions of times.
ĐượcGain
Không tốn token context, không độ trễ truy xuất; hành vi đã fine-tune ổn định hơn chỉ dẫn trong prompt.No context tokens, no retrieval latency; fine-tuned behaviour is steadier than prompt instructions.
MấtLose
Đóng băng tại ngày cắt dữ liệu; không truy được nguồn; fine-tune để nạp dữ kiện cho kết quả kém; làm lại khi model nền nâng cấp.Frozen at the cutoff; no sources; fine-tuning facts in works poorly; redo it whenever the base model is upgraded.

Đổi khả năng cập nhật và truy nguồn lấy suy luận nhanh, rẻ.Trades updatability and traceability for fast, cheap inference.

Dấu hiệu:Sign: prompt dài chỉ để ép giọng văn, và lưu lượng gọi rất lớn.a long prompt exists only to enforce tone, at huge volume.

F

Prospective

scheduler · đến khi thực thischeduler · until executed
agent: "follow up in 3 days" ─▶ scheduler
  (time passes, model not running)
scheduler fires ─▶ wake agent ─▶ act

Nhớ phải làm một việc vào lúc khác hoặc khi điều kiện xảy ra. Model chỉ ghi lời hẹn; scheduler, cron, hàng đợi mới giữ lời hẹn.Remembering to act at a later time or when a condition is met. The model records the promise; a scheduler, cron or queue keeps it.

Dùng choUse for
Theo dõi khách sau N ngày, báo cáo buổi sáng, phản ứng khi build lỗi, task phải chờ phê duyệt.Following up after N days, morning reports, reacting to a failed build, tasks waiting on approval.
ĐượcGain
Agent chuyển từ thụ động sang chủ động; hạ tầng scheduler đã trưởng thành; người dùng xem và huỷ được lời hẹn.Turns the agent proactive; scheduler infrastructure is mature; users can view and cancel commitments.
MấtLose
Không có scheduler thì không tồn tại; ngữ cảnh lúc hẹn có thể đã cũ lúc thực thi; hành động khi không ai giám sát.No scheduler, no memory; context saved at scheduling time may be stale when it runs; acts while nobody watches.

Đổi rủi ro hành động không giám sát lấy khả năng chủ động theo thời gian.Trades the risk of unsupervised action for the ability to act over time.

Dấu hiệu:Sign: người dùng nói “nhắc tôi”, “tuần sau kiểm tra lại”.the user says “remind me” or “check again next week”.

Vòng đọc – ghiThe read–write loop

Kho chỉ là nơi chứa. Giá trị nằm ở ba quyết định theo đúng thứ tự trong ảnh: lấy gì ra, ghép thế nào, giữ lại gì. Stores are just containers. The value lies in three decisions, in the image’s order: what to pull, how to assemble, what to keep.

02

Đọc (truy xuất)Read (retrieval)

query ─► filter user ─► keyword+vector
      ─► rank: relevant × recent × important
      ─► cut to token budget

Quyết định thứ gì từ kho được vào context ở lượt này. Không lấy ra được thì coi như chưa từng nhớ.Decides what from storage enters context this turn. If it isn’t retrieved, it was never remembered.

Dùng choUse for
Kho lớn hơn vài trăm mục, trợ lý nhiều người dùng, agent dùng nhiều tháng.Stores beyond a few hundred items, multi-user assistants, agents used for months.
ĐượcGain
Context nhỏ, rẻ, tập trung; kho lớn tuỳ ý; log được để gỡ lỗi.Small, cheap, focused context; store can grow freely; loggable for debugging.
MấtLose
Giống về vector chưa chắc liên quan; thêm độ trễ; lấy nhầm user là sự cố bảo mật.Vector similarity isn’t relevance; added latency; the wrong user’s memory is a security incident.

Đổi khả năng “thấy hết” lấy một context nhỏ, rẻ và sắc nét.Trades “seeing everything” for a small, cheap, sharp context.

Dấu hiệu:Sign: kho đã lớn hơn ngân sách context bạn chịu dành cho nó.the store has outgrown the context budget you’ll give it.

03

Context (lắp ráp)Context (assembly)

[procedural]  tĩnh, cache được / static, cacheable
[semantic]    fact về user / user facts
[episodic]    1–3 tập / episodes
[chat + request]

Thứ duy nhất model thấy. Agent trong ảnh chọn chuyến sáng, ghế lối đi, JFK vì chỉ được đưa đúng ba điều đó.The only thing the model sees. The agent in the image picks morning, aisle, JFK because it was given exactly those three things.

Dùng choUse for
Debug câu trả lời “đúng nhưng thiếu”, quy tắc bị “quên”, chi phí token tăng vô ích.Debugging “right but incomplete” answers, “forgotten” rules, rising token bills.
ĐượcGain
Một điểm kiểm soát; nhãn nguồn giúp cân nặng nhẹ; cấu trúc ổn định thì cache trúng.One control point; source labels set priority; stable structure keeps the cache warm.
MấtLose
Context dài thì sót phần giữa; memory sai được tin như thật; có thể mang prompt injection.Long contexts lose the middle; wrong memories are trusted; can carry prompt injection.

Đổi độ đầy đủ lấy sự tập trung: mỗi dòng thêm vào chiếm chỗ của một dòng khác.Trades completeness for focus: every line added takes another’s place.

Dấu hiệu:Sign: agent làm sai điều bạn chắc chắn đã lưu.the agent gets wrong something you know was stored.

05

Cổng ghiWrite gate

Flights < 10 AM   ─┐          ┌─► ✓ semantic
Price today $312  ─┼─► worth? ─┤
Loading status…  ─┘          └─► ✗ drop

Quyết định điều gì được giữ và vào kho nào. Chạy nền, thao tác ADD / UPDATE / DELETE / NOOP so với cái đã có. Trạng thái nhất thời không bao giờ thành ký ức.Decides what is kept and where. Runs in the background as ADD / UPDATE / DELETE / NOOP against what exists. Temporary state never becomes a memory.

Dùng choUse for
Mọi hệ thống ghi memory tự động, trợ lý cá nhân dài hạn.Any system that writes memory automatically; long-lived personal assistants.
ĐượcGain
Kho sạch, truy xuất chính xác; giá cũ không bị dùng lại; ít dữ liệu cá nhân thừa.Clean store, accurate retrieval; no stale prices reused; less surplus personal data.
MấtLose
Quá chặt thì sót, quá lỏng thì rác; thêm một lần gọi LLM; bước trích xuất cũng suy diễn sai được.Too strict misses, too loose fills with junk; one more LLM call; extraction can infer wrongly.

Đổi khả năng “nhớ mọi thứ” lấy một kho nhỏ nhưng đáng tin.Trades “remember everything” for a small store you can trust.

Dấu hiệu:Sign: kho tăng nhanh mà câu trả lời không tốt lên.the store grows fast while answers don’t improve.

Bảng đánh đổiTrade-off table

Các trục là những câu hỏi thật khi thiết kế: sống bao lâu, ghi bao nhiêu, hỏng kiểu gì, lan xa đến đâu.The axes are the real design questions: how long it lives, how often it’s written, how it fails, how far an error spreads.

Working Episodic Semantic Procedural
Vòng đờiLifetime Một lượtOne run Tháng, phai dầnMonths, fading Đến khi bị thayUntil replaced Đến khi sửa có chủ đíchUntil deliberately changed
Tần suất ghiWrites Liên tụcConstant Mỗi phiênEvery session Thỉnh thoảngOccasional HiếmRare
Cách lấy raRetrieval Có sẵn trong contextAlready in context Độ giống + độ gần đâySimilarity + recency Theo khoá hoặc ngữ nghĩaBy key or meaning Luôn nạp hoặc theo triggerAlways, or on trigger
Kiểu hỏngFailure Tràn contextContext overflow Nhầm tiền lệWrong precedent Fact lỗi thờiStale fact Lỗi lặp mọi lượtError every turn
Phạm vi khi saiBlast radius Một lượtOne run Một quyết địnhOne decision Nhiều lượtMany turns Mọi lượtEvery turn
Ai nên ghiWho writes Agent Agent, tự độngAgent, automatically Agent, có xác nhậnAgent, with confirmation Người duyệtHuman-approved

Càng sang phải: ghi càng hiếm, sống càng lâu, sai càng đắt. Mức kiểm soát khi ghi phải tăng theo đúng chiều đó.Moving right: rarer writes, longer life, costlier mistakes. Write-time control must rise in the same direction.

Anti-patterns

Những lỗi phổ biến nhất khi đưa memory vào agent thật.The most common mistakes when shipping agent memory.

Coi context window lớn là memoryTreating a big context window as memory
Đắt, chậm, vẫn mất khi hết phiên, sót phần giữa.Expensive, slow, still lost at session end, misses the middle.
Lưu ngoài, truy xuất có chọn lọc.Store externally, retrieve selectively.
Lưu mọi thứ “biết đâu cần”Saving everything “just in case”
Kho phình, truy xuất nhiễu, rủi ro dữ liệu cá nhân.Bloated store, noisy retrieval, privacy risk.
Cổng ghi có tiêu chí rõ và TTL.A write gate with clear criteria and TTLs.
Lưu trạng thái nhất thờiStoring transient state
Lần sau dùng giá cũ như sự thật.Old prices get used as fact next time.
Gọi tool lấy lại; chỉ lưu sở thích và quy tắc.Re-fetch via tool; store only preferences and rules.
Chỉ append, không xử lý fact cũAppend-only facts
Hai sự thật mâu thuẫn cùng tồn tại, model tự chọn.Two contradictory truths coexist; the model picks one.
UPDATE/DELETE, lưu thời điểm, bản mới thắng.UPDATE/DELETE, timestamps, newest wins.
Agent tự sửa proceduralAgent edits procedural memory unreviewed
Một lỗi hay một injection lặp lại ở mọi lượt.One bug or injection repeats every turn.
Agent đề xuất, người duyệt, có rollback.Agent proposes, human approves, with rollback.
Chỉ dùng vector searchVector search only
Hỏng với tên riêng, mã đơn, con số.Fails on names, order IDs, numbers.
Hybrid: keyword + vector + lọc metadata.Hybrid: keyword + vector + metadata filters.
Lọc theo user bằng promptFiltering by user in the prompt
Rò memory giữa các người dùng.Memory leaks between users.
Lọc cứng theo user/tenant ở tầng dữ liệu.Hard filter on user/tenant at the data layer.
Người dùng không xem, xoá được memoryUsers can’t see or delete memory
Mất niềm tin, vi phạm quyền về dữ liệu.Lost trust, data-rights violations.
Trang quản lý memory và lệnh “quên”.A memory page and a “forget” command.
Vector DB cho vài chục tài liệuA vector DB for a few dozen documents
Thêm hạ tầng, thêm lỗi tìm trượt, không được gì.Extra infrastructure, extra misses, no gain.
Nhét thẳng vào prompt, dùng prompt caching.Put them in the prompt with prompt caching.
Fine-tune để nạp tài liệu nội bộFine-tuning to load internal docs
Model học dữ kiện mới kém, không truy được nguồn.Models learn new facts poorly, with no citations.
Dùng retrieval; fine-tune chỉ để dạy hành vi.Use retrieval; fine-tune only for behaviour.
Dặn model “nhớ nhắc tôi” mà không có scheduler“Remind me” with no scheduler
Không ai thức dậy để nhắc.Nothing wakes up to remind anyone.
Ghi vào hệ thống lịch thật.Write to a real scheduling system.

Ba câu cần nhớThree things to remember