# Build Agents that never forget
**作者**: Akshay
**日期**: 2026-04-13T17:36:17.000Z
**来源**: [https://x.com/akshay_pachaar/status/2043745099792953508](https://x.com/akshay_pachaar/status/2043745099792953508)
---

A first-principles walk through agent memory: from Python lists to markdown files to vector search to graph-vector hybrids, and finally, a clean, open-source solution for all of this.

An LLM is stateless by design. Every API call starts fresh. The "memory" you feel when chatting with ChatGPT is an illusion created by re-sending the entire conversation history with every request.
That trick works for casual chat. It falls apart the moment you try to build a real agent.
Here are 7 failure modes show up the instant you skip memory:
Context amnesia: the agent asks for information you already gave it
Zero personalization: every interaction feels generic
Multi-step task failure: intermediate state silently drops mid-task
Repeated mistakes: no episodic recall means the same errors, forever
No knowledge accumulation: every session starts from scratch
Hallucination from gaps: when context overflows, the model invents
Identity collapse: no continuity, no trust
The obvious response is "throw more context at it." That's why 128K and 200K token windows feel like they should solve everything.
They don't.
Accuracy drops over 30% when relevant information sits in the middle of a long context. This is the well-documented "lost in the middle" effect.
Context is a shared budget: system prompts, retrieved docs, conversation history, and output all fight for the same tokens.
Even at 100K tokens, the absence of persistence, prioritization, and salience makes raw context length insufficient.

Memory isn't about cramming more text into the prompt. It's about structuring what the agent remembers so it can find what matters.
## The cognitive science frame that actually helps
Lilian Weng's 2023 formulation has become the default framework:
Agent = LLM + Memory + Planning + Tool Use.
The four co-equal pillars.
Her taxonomy borrows from cognitive science, where human memory splits into three systems:
- Sensory memory captures raw perceptual input and holds it for a fraction of a second. Only the portions you pay attention to get passed forward.
- Working memory is where active thinking happens. It holds roughly 7±2 items at a time (Miller's 1956 finding). Lose focus, and the contents disappear.
- Long-term memory is durable storage with no practical capacity limit. Retrieval is the bottleneck: you can store millions of things and still fail to recall the one you need.
Each maps directly to a component in modern agent architectures:

Long-term memory itself splits further:
- Episodic: specific past events ("on Tuesday, the PostgreSQL cluster went down")
- Semantic: facts and concepts ("PostgreSQL is a relational database")
- Procedural: skills and workflows ("when a user asks for a refund, first check the purchase date")
The bridge between episodic and semantic is memory consolidation: repeated specific events distilling into general knowledge. An agent that notices "users consistently prefer executive summaries" across dozens of interactions should turn that into a reusable rule. Without consolidation, your agent replays individual events rather than learning from them.

## The minimal agent, and what breaks first
Strip away the frameworks and an agent is a loop: perceive, think, act.
Tell it "I have 4 apples," then ask "I ate one, how many left?" and it has no idea what apples you're talking about. Each call exists in isolation.
## Layer 1: The Python list
The first fix everyone reaches for:
Multi-turn works now. The apples question gets answered correctly because the full conversation re-ships with every call.
Two problems show up fast:
- The list grows unbounded. Around turn 200, you hit the context ceiling and the oldest messages silently drop. The user's name from turn 1 disappears long before yesterday's throwaway joke. No prioritization, just strict chronological order.
- Everything lives in RAM. The moment the Python process ends, your agent has no idea who you are.
## Layer 2: Markdown files for persistence
The next move is writing memory to disk. Markdown is a natural fit: human-readable, Git-friendly, and the agent can read it back as plain text. Claude Code uses exactly this pattern with CLAUDE.md and MEMORY.md files.
Persistence is solved. Restart the script, and the conversation is still on disk. You could also maintain a separate facts file that the agent extracts over time:
You can open the file in any editor, see exactly what the agent knows, and fix it by hand. Genuinely useful for prototyping.
With 4 facts, this works perfectly. Load the entire file into context and the LLM handles any question about Sarah, her company, or her industry.
Now fast-forward three months. Your agent has 2,000 extracted facts and 200 conversation logs. That's 500K+ tokens of markdown on disk, and your context window is 128K.
You can no longer load everything. You need to selectively retrieve only the facts relevant to the current query. With flat files, your only option is keyword search:
At small scale, markdown files work. At real scale, they force keyword retrieval, and keywords can't handle synonyms, paraphrases, or connections across facts.
The information is on disk. But you can't load all of it, and keyword search is too brittle to find the right pieces.
If you've used OpenClaw, you've seen this play out. It stores memory as markdown checkpoint files, and over weeks of daily use, earlier facts quietly slip away as context accumulates and gets compacted. The storage is there. The retrieval isn't.
Storage without intelligent retrieval is a library with no catalog.
## Layer 3: Vector search and the wall it hits
Bolt on embeddings. Chunk your markdown, embed the chunks, search by cosine similarity. Now "database" matches "PostgreSQL" because their vectors live close together in embedding space. The synonym problem dissolves.
Then you hit a new wall. Consider these three facts in your vector DB:
User asks: "Was Alice's project affected by Tuesday's outage?"
The query mentions Alice and Tuesday's outage, so vector search ranks the first and third facts high. But the critical bridge, "Project Atlas uses PostgreSQL," mentions neither Alice nor Tuesday. It's the connecting piece, and it's the one that won't surface.
Each fact is an isolated point in embedding space. The connective tissue linking them is invisible to vectors.

This isn't an edge case. It's the normal shape of real-world questions. Business knowledge is inherently relational: people belong to teams, teams own projects, projects depend on systems, systems have incidents. Any question that crosses two or more hops exceeds what flat vector retrieval can answer.
## The capability matrix
Each layer fixes the previous pain but reveals a deeper one:

You need persistence, semantic understanding, and relational reasoning in a single memory layer.
Building this yourself means gluing together a vector database, a graph database, a relational store, an entity extractor, a deduplication pipeline, and an edge-weighting system. That's weeks of infrastructure work before you write a single line of agent logic.
I've been using a solution that fills this gap cleanly. It's fully open-source, handles all three storage paradigms under one roof, and you can get it running in minutes. Let's talk about Cognee.
Cognee: three stores, one engine, four calls
Cognee is an open-source knowledge engine built for agent memory. It combines vector search with knowledge graphs and a relational provenance layer into a single system.
The entire API surface is four async calls:
Behind those four calls sits a three-store architecture.

Why three stores and not one ?
Each store captures a dimension of knowledge the others can't:
- Relational store → provenance: where data came from, when it was ingested, who has access
- Vector store → semantics: what content means, what it's similar to
- Graph store → relationships: how entities connect, what causes what, who reports to whom
Flatten any of these and you lose information that matters for retrieval accuracy.
The default stack is SQLite + LanceDB + Kuzu, entirely embedded and file-based. pip install cognee plus an LLM API key and you're running.
No Docker, no external services.
For production, swap SQLite for Postgres, LanceDB for Qdrant/Pinecone/pgvector, and Kuzu for Neo4j/FalkorDB/Neptune.
Same four-call API either way.
## What cognify actually does?
cognee.cognify() runs a multi-stage pipeline that converts raw text into structured, interconnected knowledge:
Document classification by type and domain
Permission checking for multi-tenant access control
Chunk extraction that respects paragraph structure (not fixed-size cuts)
Entity and relationship extraction via LLM, with automatic deduplication through content hashing
Summary generation for efficient retrieval
Dual indexing into the vector store (embeddings) and graph store (edges)
The deduplication step matters more than it sounds. If the same entity shows up across 50 documents, Cognee merges it into a single graph node with 50 inbound edges. Your agent no longer sees "Alice" as 50 different strangers. And the pipeline is incremental by default: only new or updated files get reprocessed.

Every graph node has a corresponding embedding. This dual representation is the core trick: enter through vectors (find semantically similar content) and exit through the graph (follow relationships to connected entities), or the reverse. That's what makes multi-hop queries work without sacrificing semantic search.
## Memify: memory that learns
memify() is what separates Cognee from every "ingest and search" tool. It runs an RL-inspired optimization pass over the graph:
- Strengthening useful paths that led to good retrieval
- Pruning stale nodes that haven't been touched
- Auto-tuning edge weights based on real usage
- Adding derived facts by identifying implicit relationships
A customer support agent's graph naturally strengthens paths through product docs and refund policies while letting rarely-queried HR edges decay. The graph develops its own sense of relevance over time.

## Fourteen retrieval modes
Cognee ships 14 search modes. The ones you'll actually reach for:

Building a real agent with Cognee memory
Here's the complete pattern wiring Cognee into the perceive-think-act loop:
The memory cycle: ingest, extract, store, retrieve, respond, store again. Each turn enriches the knowledge graph, and incremental processing means you only pay to index new content.
Session memory handles pronoun resolution automatically:
Multi-tenancy is built in at the graph level with per-dataset permissions (read, write, delete, share). Not namespace separation, actual graph-level isolation.
## The practical path forward
If you're building an agent today, the real starting question is: "what does my agent need to remember, and what kind of questions will it answer?"
If your queries only need similarity search ("find conversations like this one"), vector-only memory works. The moment queries cross entity boundaries ("Was Alice's project affected by Tuesday's outage?"), you need graph traversal.
You can wire together separate vector, graph, and relational stores yourself. Teams that go this route typically burn weeks on infrastructure for a memory layer that still doesn't learn from its own usage.
Cognee collapses that into four API calls. Embedded defaults get you running in minutes. Swappable backends (Postgres, Qdrant, Neo4j) take you to production without changing your agent code.
Intelligence requires structure, not just storage. The three storage paradigms (relational, vector, graph) aren't competing options. They're complementary layers of the same memory system. Treating them that way is what turns a stateless LLM wrapper into something that actually learns.
What's the next thing you'd want your agent to remember tomorrow that it forgot today? Start there.
👉 Check out Cognee on GitHub →, give it a star, and try wiring it into your next agent.
Four async calls, a pip install, and you're running.
That's a wrap!
If you enjoyed reading this:
Find me →@akshay_pachaar ✔️
Every day, I share tutorials and insights on AI, Machine Learning, and vibe coding best practices.
## 相关链接
- [Akshay](https://x.com/akshay_pachaar)
- [@akshay_pachaar](https://x.com/akshay_pachaar)
- [287K](https://x.com/akshay_pachaar/status/2043745099792953508/analytics)
- [Miller's 1956 finding](https://pmc.ncbi.nlm.nih.gov/articles/PMC4486516/)
- [Cognee: three stores, one engine, four calls](https://github.com/topoteretes/cognee)
- [Cognee](https://github.com/topoteretes/cognee)
- [Cognee collapses that into four API calls](https://github.com/topoteretes/cognee)
- [Check out Cognee on GitHub →](https://github.com/topoteretes/cognee)
- [@akshay_pachaar](https://x.com/@akshay_pachaar)
- [Upgrade to Premium](https://x.com/i/premium_sign_up)
- [1:36 AM · Apr 14, 2026](https://x.com/akshay_pachaar/status/2043745099792953508)
- [287.3K Views](https://x.com/akshay_pachaar/status/2043745099792953508/analytics)
- [View quotes](https://x.com/akshay_pachaar/status/2043745099792953508/quotes)
---
*导出时间: 2026/4/16 17:09:31*
---
## 中文翻译
# 构建永不遗忘的智能体
**作者**: Akshay
**日期**: 2026-04-13T17:36:17.000Z
**来源**: [https://x.com/akshay_pachaar/status/2043745099792953508](https://x.com/akshay_pachaar/status/2043745099792953508)
---

从第一性原理出发,带你走一遍智能体记忆:从 Python 列表到 Markdown 文件,再到向量搜索,再到图-向量混合,最后是一种干净的开源解决方案,可以搞定这一切。

LLM 在设计上就是无状态的。每次 API 调用都是从零开始。你在与 ChatGPT 聊天时感受到的“记忆”,其实是一种错觉——通过在每次请求时重新发送完整的对话历史来实现的。
这个技巧对日常聊天够用了。但一旦你试图构建一个真正的智能体,它就彻底失效了。
以下是一旦忽略记忆就会立刻出现的 7 种失败模式:
上下文失忆:智能体会向你索要你已经提供过的信息
零个性化:每次交互都千篇一律
多步任务失败:中间状态在任务进行中悄然丢失
重复犯错:没有情景记忆,意味着同样的错误永远重演
无法积累知识:每次会话都从零开始
因信息缺失而产生幻觉:当上下文溢出时,模型开始编造
身份崩塌:没有连续性,就没有信任
显而易见的应对方案是“给它更多上下文”。这也是为什么 128K 和 200K 的 token 窗口让人觉得应该能解决所有问题。
它们解决不了。
当相关信息位于长上下文中间时,准确率会下降超过 30%。这就是有据可查的“迷失在中间”效应。
上下文是一个共享预算:系统提示词、检索到的文档、对话历史和输出都要争夺同一批 token。
即使有 100K token,由于缺乏持久化、优先级排序和显著性判断,单纯的上下文长度依然不够。

记忆不是往提示词里塞更多文本,而是对智能体记住的内容进行结构化,让它能找到真正重要的东西。
## 真正有用的认知科学框架
Lilian Weng 在 2023 年提出的表述已成为默认框架:
智能体 = LLM + 记忆 + 规划 + 工具使用。
四根同等重要的支柱。
她的分类借鉴了认知科学,其中人类记忆分为三个系统:
- 感觉记忆捕捉原始的感知输入,并将其保持不到一秒。只有你注意到的部分才会被传递下去。
- 工作记忆是活跃思维发生的地方。它一次大约能容纳 7±2 个项目(Miller 1956 年的发现)。一旦分心,内容就消失了。
- 长期记忆是持久存储,没有实际的容量限制。检索才是瓶颈:你可以存储数百万条信息,却仍然无法回忆起你需要的那一条。
每一个都直接对应现代智能体架构中的一个组件:

长期记忆本身还可以进一步细分:
- 情景记忆:具体的过往事件(“周二,PostgreSQL 集群宕机了”)
- 语义记忆:事实和概念(“PostgreSQL 是一个关系型数据库”)
- 程序性记忆:技能和工作流(“当用户要求退款时,先检查购买日期”)
情景记忆与语义记忆之间的桥梁是记忆固化:反复出现的具体事件提炼成通用知识。如果一个智能体在几十次交互中注意到“用户始终偏好执行摘要”,它应该把这一点转化为一条可复用的规则。没有固化,你的智能体只会重放一个个事件,而无法从中学习。

## 最简智能体,以及最先崩坏的东西
抛开所有框架,智能体就是一个循环:感知、思考、行动。
告诉它“我有 4 个苹果”,然后问“我吃了一个,还剩几个?”,它根本不知道你在说哪些苹果。每次调用都是孤立存在的。
## 第一层:Python 列表
每个人首先想到的修复方案:
现在多轮对话可以工作了。苹果问题能得到正确回答,因为每次调用都会重新发送完整的对话历史。
但两个问题很快浮现:
- 列表会无限增长。大约到第 200 轮时,你会撞上上下文上限,最早的消息被悄然丢弃。第 1 轮里用户的名字,早在昨天那句随口的玩笑之前就消失了。没有任何优先级,只有严格的时间顺序。
- 一切都存在 RAM 里。Python 进程一结束,你的智能体就完全不认识你了。
## 第二层:用 Markdown 文件实现持久化
下一步是把记忆写入磁盘。Markdown 是天然的契合选择:人类可读、对 Git 友好,而且智能体可以把它当纯文本读回来。Claude Code 使用的正是这种模式,通过 CLAUDE.md 和 MEMORY.md 文件。
持久化问题解决了。重启脚本,对话依然在磁盘上。你还可以维护一个单独的事实文件,让智能体随时间逐步抽取信息:
你可以在任何编辑器中打开这个文件,确切地看到智能体知道什么,并手动修正。这对原型开发确实很有用。
只有 4 条事实时,这完美工作。把整个文件加载进上下文,LLM 能回答关于 Sarah、她的公司或她所在行业的任何问题。
现在快进三个月。你的智能体积累了 2,000 条抽取的事实和 200 份对话日志。磁盘上有超过 500K token 的 Markdown,而你的上下文窗口只有 128K。
你已经无法加载全部内容。你需要有选择地只检索与当前查询相关的事实。对于扁平文件,你唯一的选择就是关键词搜索:
在小规模下,Markdown 文件很好用。但在真实规模下,它们迫使你使用关键词检索,而关键词无法处理同义词、改写或事实之间的关联。
信息就在磁盘上。但你无法全部加载,而关键词搜索又太脆弱,找不到正确的片段。
如果你用过 OpenClaw,你一定见过这种情形。它把记忆存储为 Markdown 检查点文件,随着每天使用数周后,早期的信息在上下文不断积累并被压缩时悄然溜走。存储在那里,检索却不在。
没有智能检索的存储,就像一座没有目录的图书馆。
## 第三层:向量搜索及其撞上的墙
再加上嵌入(embeddings)。把你的 Markdown 分块,对每个块做嵌入,用余弦相似度搜索。现在"database"能匹配到"PostgreSQL"了,因为它们的向量在嵌入空间中距离很近。同义词问题就此化解。
然后你又会撞上新的墙。看看向量数据库中的这三条事实:
用户提问:"Alice 的项目受周二故障的影响了吗?"
查询提到了 Alice 和周二的故障,所以向量搜索会把第一条和第三条事实排在前面。但关键的桥梁——"Project Atlas 使用 PostgreSQL"——既没提到 Alice 也没提到周二。它才是连接性的关键环节,却恰恰是不会浮现的那一条。
每条事实都是嵌入空间中的一个孤立点。连接它们的组织结构对向量来说是不可见的。

这并不是边缘案例。它就是现实世界问题的常态形态。业务知识天生就是关系型的:人属于团队,团队负责项目,项目依赖系统,系统会发生事故。任何跨越两个或更多跳数的问题都超出了扁平向量检索能回答的范围。
## 能力矩阵
每一层都修复了上一层的痛点,但暴露出更深的一层:

你需要在一个记忆层中同时具备持久化、语义理解和关系推理能力。
自己动手构建意味着要把向量数据库、图数据库、关系型存储、实体提取器、去重流水线和边权重系统拼接在一起。在你写下第一行智能体逻辑之前,就得先做几周的基础设施工作。
我一直在用一个能干净利落填补这一空白的解决方案。它完全开源,在同一屋檐下处理所有三种存储范式,而且几分钟就能跑起来。让我们来聊聊 Cognee。
Cognee:三个存储,一个引擎,四次调用
Cognee 是一个为智能体记忆打造的开源知识引擎。它将向量搜索、知识图谱和关系型数据溯源层组合成一个单一系统。
整个 API 只有四个异步调用:
在这四次调用背后是一个三存储架构。

为什么是三个存储而不是一个?
每个存储捕捉的都是其他存储无法覆盖的一个知识维度:
- 关系型存储 → 溯源:数据从哪来、何时被摄入、谁能访问
- 向量存储 → 语义:内容是什么意思、与什么相似
- 图存储 → 关系:实体之间如何连接、什么导致什么、谁向谁汇报
把其中任何一个压平,你都会丢失对检索准确性至关重要的信息。
默认技术栈是 SQLite + LanceDB + Kuzu,完全嵌入式且基于文件。`pip install cognee`,再加一个 LLM API 密钥,你就可以运行了。
不需要 Docker,不需要外部服务。
在生产环境中,可以把 SQLite 换成 Postgres,LanceDB 换成 Qdrant/Pinecone/pgvector,Kuzu 换成 Neo4j/FalkorDB/Neptune。
无论哪种方式,都是同样的四次调用 API。
## cognify 到底做了什么?
cognee.cognify() 运行一个多阶段流水线,把原始文本转化为结构化、相互连接的知识:
- 按类型和领域对文档进行分类
- 针对多租户访问控制进行权限检查
- 尊重段落结构的分块提取(而非固定大小切割)
- 通过 LLM 进行实体和关系提取,并通过内容哈希自动去重
- 生成摘要以实现高效检索
- 双重索引:写入向量存储(嵌入)和图存储(边)
去重这一步比听起来更重要。如果同一个实体出现在 50 个文档中,Cognee 会把它合并成一个带有 50 条入边的图节点。你的智能体不会再把"Alice"看成 50 个不同的陌生人。而且流水线默认是增量的:只有新增或更新的文件才会被重新处理。

每个图节点都有对应的嵌入。这种双重表示是核心技巧:从向量进入(找到语义相似的内容),再从图退出(沿着关系找到相连的实体),或者反过来。这正是多跳查询能够在不牺牲语义搜索的前提下得以实现的原因。
## Memify:会学习的记忆
memify() 是 Cognee 与所有"摄入即搜索"工具的区别所在。它在图上运行一轮受强化学习启发的优化:
- 强化那些带来良好检索结果的有用路径
- 剪除长期未被触碰的陈旧节点
- 根据真实使用情况自动调整边权重
- 通过识别隐式关系来添加推导出的事实
一个客服智能体的图会自然地强化穿过产品文档和退款政策的路径,同时让很少被查询的 HR 边逐渐衰减。这张图会随着时间推移发展出自己对相关性的感知。

## 十四种检索模式
Cognee 内置了 14 种搜索模式。你真正会用到的有:

用 Cognee 记忆构建一个真正的智能体
下面是把 Cognee 接入感知-思考-行动循环的完整模式:
记忆循环:摄入、提取、存储、检索、响应、再次存储。每一轮对话都在丰富知识图谱,而增量处理意味着你只需为新内容支付索引成本。
会话记忆自动处理代词消解:
多租户在图层面内置支持,配有按数据集划分的权限(读、写、删除、分享)。不是命名空间隔离,而是真正的图级隔离。
## 切实可行的前进路径
如果你今天正在构建智能体,真正该问的起点问题是:"我的智能体需要记住什么,以及它要回答什么样的问题?"
如果你的查询只需要相似度搜索("找到与此类似的对话"),纯向量记忆就够了。一旦查询跨越实体边界("Alice 的项目受周二故障的影响了吗?"),你就需要图遍历了。
你可以自己将独立的向量、图和关系型存储拼接起来。选择这条路线的团队通常要为这个记忆层的基础设施耗费数周时间,而它依然无法从自身的使用中学习。
Cognee 将这一切压缩为四次 API 调用。内置默认配置让你几分钟内即可运行起来。可替换的后端(Postgres、Qdrant、Neo4j)让你无需更改智能体代码即可进入生产环境。
智能需要结构,而不仅仅是存储。三种存储范式(关系型、向量、图)并不是相互竞争的选项,它们是同一个记忆系统的互补层次。以这种方式对待它们,才能把一个无状态的 LLM 包装器变成真正能学习的东西。
明天你最希望你的智能体记住而今天却遗忘了的东西是什么?从这里开始。
👉 前往 GitHub 查看 Cognee →,给它点个星,并尝试将它接入你的下一个智能体。
四次异步调用,一条 pip install 命令,你就可以运行了。
本期就到这里!
如果你喜欢这篇文章:
关注我 →@akshay_pachaar ✔️
每天,我都会分享有关 AI、机器学习和氛围编程最佳实践的教程与见解。
## 相关链接
- [Akshay](https://x.com/akshay_pachaar)
- [@akshay_pachaar](https://x.com/akshay_pachaar)
- [287K](https://x.com/akshay_pachaar/status/2043745099792953508/analytics)
- [Miller 1956 年的发现](https://pmc.ncbi.nlm.nih.gov/articles/PMC4486516/)
- [Cognee:三个存储,一个引擎,四次调用](https://github.com/topoteretes/cognee)
- [Cognee](https://github.com/topoteretes/cognee)
- [Cognee 将这一切压缩为四次 API 调用](https://github.com/topoteretes/cognee)
- [前往 GitHub 查看 Cognee →](https://github.com/topoteretes/cognee)
- [@akshay_pachaar](https://x.com/@akshay_pachaar)
- [升级到 Premium](https://x.com/i/premium_sign_up)
- [2026年4月14日 凌晨1:36](https://x.com/akshay_pachaar/status/2043745099792953508)
- [287.3K 次浏览](https://x.com/akshay_pachaar/status/2043745099792953508/analytics)
- [查看引用](https://x.com/akshay_pachaar/status/2043745099792953508/quotes)
---
*导出时间: 2026/4/16 17:09:31*