知识库 · AI 智能体
从零开始构建 AI 智能体记忆
本文从零构建AI智能体记忆系统,使用Python、Ollama、SQLite和嵌入模型。避免LangChain等框架,通过持久化存储实现记住用户、语义检索、记忆分类与注入上下文,帮助理解智能体记忆的底层原理。
从零开始构建 AI 智能体记忆
9月19日修改
Jaydeep · X · @_jaydeepkarale · 2026-09-17 21:45
📌 本文为转载,版权归原作者所有,全文以原文链接为准
这是关于智能体记忆的 7 篇系列文章中的第 3 篇。目标是先理解基础知识,然后通过实际构建具有记忆功能的智能体来应用它们。
今天,我们将构建一个记忆系统。
没有 LangChain。
没有 LangGraph。
没有托管记忆服务。
只有 Python、Ollama、SQLite、一个嵌入模型和一个 LLM。
到本文结束时,我们将拥有一个能够实现以下功能的智能体:
记住关于用户的有用信息
在对话结束后持久化这些记忆
在之后检索相关记忆
将这些记忆注入 LLM 的上下文中
决定哪些信息值得记住
分配记忆类型、重要性和置信度
执行语义记忆检索
该实现刻意保持简单。目标不是构建一个生产级的记忆数据库。目标是理解当智能体记住某些事情时实际发生了什么。
Building An Agent Without Memory(构建无记忆的智能体)
我们的第一个实现是
代码块
from ollama import chat
MODEL = "qwen3:4b"
def ask_agent(message: str) -> str:
response = chat(
model=MODEL,
messages=[
{"role": "user", "content": message}
],
)
return response.message.content
if __name__ == "__main__":
print("User: My name is Jaydeep.")
print("Agent:", ask_agent("My name is Jaydeep."))
print("\nUser: What's my name?")
print("Agent:", ask_agent("What's my name?"))现在如果我们运行这段代码,我们会看到以下结果
起初,这可能看起来令人惊讶。模型在第一个请求中显然理解了我的名字。但第二个请求是一个单独的 API 调用。
除非我们的应用程序将之前的对话发送回模型,否则模型无法将该信息作为上下文使用。
所以让我们添加对话历史,看看是否能解决这个问题。
代码块
from ollama import chat
MODEL = "qwen3:4b"
messages = []
def ask_agent(message: str) -> str:
messages.append(
{
"role": "user",
"content": message,
}
)
response = chat(
model=MODEL,
messages=messages,
)
messages.append(
{
"role": "assistant",
"content": response.message.content,
}
)
return response.message.content
if __name__ == "__main__":
print("User: My name is Jaydeep.")
print("Agent:", ask_agent("My name is Jaydeep."))
print("\nUser: What's my name?")
print("Agent:", ask_agent("What's my name?"))
现在输出看起来好多了,即它记住了我的名字
但这并不是记忆,我们是将整个对话历史作为上下文发送。
代码块
[
{
"role": "user",
"content": "My name is Jaydeep."
},
{
"role": "assistant",
"content": "Nice to meet you, Jaydeep!"
},
{
"role": "user",
"content": "What's my name?"
}
]如果我们清除 `messages = []`,该信息就会从我们的应用程序中消失。
这就是我们试图解决的问题。我们需要一些在当前对话之外仍然存在的东西。
这就是记忆的用武之地。
Give the agent a persistent memory(赋予智能体持久记忆)
对于此实现,我们将避免设置向量数据库的复杂性,而是使用 SQLite。SQLite 非常适合这个实验,因为它是 Python 内置的。
没有数据库服务器。没有 Docker 容器。没有单独的安装。
数据库只是一个文件 `agent_memory.db`
我们将从一个小的模式开始:
代码块
memories
--------------------------------
id
user_id
content
memory_type
created_at然后创建一个文件 memory. py
代码块
import sqlite3
from datetime import datetime
DB_NAME = "agent_memory.db"
def get_connection():
return sqlite3.connect(DB_NAME)
def init_db():
connection = get_connection()
connection.execute("""
CREATE TABLE IF NOT EXISTS memories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
content TEXT NOT NULL,
memory_type TEXT,
created_at TEXT NOT NULL
)
""")
connection.commit()
connection.close()当我们的应用程序启动时,我们调用 init_db (),SQLite 会创建数据库和表(如果它们尚不存在)。现在我们需要在 memory. py 中添加一种保存记忆的方法。
代码块
def save_memory(
user_id: str,
content: str,
memory_type: str = "semantic",
):
connection = get_connection()
connection.execute(
"""
INSERT INTO memories
(user_id, content, memory_type, created_at)
VALUES
(?, ?, ?, ?)
""",
(
user_id,
content,
memory_type,
datetime.now().isoformat(),
),
)
connection.commit()
connection.close()这里有几件事值得注意。
`user_id` 告诉我们这是谁的记忆。这很重要,因为一个真正的智能体会与多个用户交互,我们不希望一个用户的记忆出现在另一个用户的对话中。
`content` 是我们存储的实际记忆,而 `memory_type` 告诉我们它是哪种记忆。目前,我们默认为 `semantic`。
`created_at` 为我们提供了时间戳。当我们开始考虑过时或过期的记忆时,我们将需要时间戳。
现在,让我们手动保存一个记忆:
代码块
save_memory(
user_id="jaydeep",
content="User's name is Jaydeep",
memory_type="semantic",
)这可以通过使用一个桩来打印内存来验证
代码块
memories = get_memories("jaydeep")
for memory in memories:
print(memory)我们应该看到类似以下内容:
代码块
(1, "User's name is Jaydeep", "semantic", "2026-09-15T...")内存存在于对话之外。我们可以关闭应用程序,再次启动它,数据仍然存放在 agent_memory.db 中。
但这里有个问题。我们的智能体仍然不知道内存的存在。
数据库可以记住。大语言模型不能。
我们需要检索存储的内存并将其放回智能体的上下文中。这是下一步。
Retrieve Agent Memory(检索智能体内存)
我们已成功存储了一条内存,现在让我们检索它。
代码块
def get_memories(user_id: str):
connection = get_connection()
cursor = connection.execute(
"""
SELECT id, content, memory_type, created_at
FROM memories
WHERE user_id = ?
ORDER BY created_at
""",
(user_id,),
)
memories = cursor.fetchall()
connection.close()
return memories我们通过 `user_id` 进行过滤,因为内存属于特定用户。目前,我们返回该用户的所有内存。稍后,我们将用基于相关性的检索来替换它。
到目前为止,我们已经构建了持久化存储和检索。但我们仍然缺少最重要的部分。检索到的内存如何真正到达大语言模型?
Inject memory into the agent's context(将内存注入智能体的上下文)
我们现在可以从 SQLite 中检索内存。
但存储内存和检索内存并不会自动让智能体感知到它。大语言模型只知道我们发送给它的内容。因此,我们需要在向大语言模型发送请求之前,将检索到的内存添加到提示词中。
让我们首先将内存转换为简单的文本块:
代码块
memories = get_memories(USER_ID)
memory_context = "\n".join(
f"- {memory[1]}"
for memory in memories
)如果我们的数据库包含:
代码块
User's name is Jaydeep
User is a platform engineer
User works with Kubernetes那么 memory_context 变为:
代码块
- User's name is Jaydeep
- User is a platform engineer
- User works with Kubernetes我们现在可以在提示词中包含该信息:
代码块
prompt = f"""
You are a helpful AI assistant.
Here are some things you remember about the user:
{memory_context}
Use these memories when they are relevant.
User's current message:
What's my name?
"""这里重要的是,内存并不是在做任何神奇的事情。我们只是简单地从数据库中取出数据,并将其放入大语言模型的上下文中。
请求实际上变成:
代码块
System instructions
+
Relevant memories
+
Current user message
↓
LLM
↓
Response我们刚刚完成了内存循环的前半部分。
智能体现在可以:
存储信息
检索信息
将该信息注入未来的对话中
但仍有重大问题。我们在手动决定存储什么内容。这无法扩展。这是我们接下来要解决的问题。
Who decides what is worth remembering?(谁来决定哪些值得记住?)
考虑这些消息:
`我的名字是 Jaydeep。`
`今天天气怎么样?`
`我正在为后端工程面试做准备。`
`我更喜欢 FastAPI 而不是 Django。`
我们的应用程序应该存储所有内容吗?可能不需要。
有些信息可能在数周或数月后有用。有些信息仅与当前对话相关。而有些信息则完全没用。
因此,我们的系统需要另一个组件来回答:
这些信息值得记住吗?
这是大语言模型可以帮忙的地方。
我们不会盲目地保存每条用户消息,而是将消息传递给内存提取器。
流程现在变成:
大语言模型负责提出内存建议。我们的应用程序负责决定如何处理该建议。
我们不希望大语言模型直接向数据库写入任意数据。相反,我们会要求它返回结构化结果。
Build the Agent memory extractor(构建智能体内存提取器)
下一步合乎逻辑的做法是使用大语言模型分析用户消息,并决定哪些值得记住。
代码块
import json
from ollama import chat
MODEL = "qwen3:4b"
def extract_memory(user_message: str) -> dict:
prompt = f"""
You are the memory extraction component of an AI assistant.
Analyze the user's message and determine whether it contains
information that could be useful in future conversations.
Remember information such as:
- User identity
- Long-term goals
- Skills
- Occupation
- Preferences
- Long-term projects
- Important recurring activities
- Explicit requests to remember something
Do NOT remember:
- Greetings
- Casual conversation
- Questions
- Temporary information
- One-off actions
- General information about the world
A memory should represent information about the USER,
not information about the world in general.
Return ONLY valid JSON.
Schema:
{{
"should_remember": true,
"memory": "short factual statement",
"memory_type": "semantic",
"importance": 0.8,
"confidence": 0.95,
"reason": "short explanation"
}}
memory_type must be one of:
- semantic
- episodic
- procedural
importance must be between 0 and 1.
confidence must be between 0 and 1.
If nothing should be remembered:
{{
"should_remember": false,
"memory": "",
"memory_type": "semantic",
"importance": 0,
"confidence": 0,
"reason": "explanation"
}}
User message:
{user_message}
"""
response = chat(
model=MODEL,
messages=[
{
"role": "user",
"content": prompt,
}
],
format="json",
)
return json.loads(
response.message.content.strip()
)我们将在下一节中更多讨论重要性、置信度和 memory_type 。但现在,让我们测试这个提取。我们可以如下独立测试提取器。
代码块
result = extract_memory(
"I'm preparing for a backend engineering interview."
)
print(result)我们可能会得到类似以下内容:
代码块
{
"should_remember": true,
"memory": "User is preparing for a backend engineering interview.",
"memory_type": "semantic",
"importance": 0.9,
"confidence": 0.95,
"reason": "This is a long-term goal that may be useful in future conversations."
}对于临时性的或通用性的问题,不值得记住的,我们会得到类似这样的结果
代码块
result = extract_memory(
"What's the weather today?"
)
{
"should_remember": false,
"memory": "",
"memory_type": "semantic",
"importance": 0,
"confidence": 0,
"reason": "This is a temporary question."
}我们现在已经从把每条消息存储在数据库中,转向了更加复杂的由人工智能驱动的流程
代码块
Every message
↓
Memory Extractor
↓
Should this be remembered?
↓
Yes / No但还有一个问题:记忆有多重要?我们有多大把握正确提取了它?
Agent Memories Metadata(智能体记忆元数据)
到目前为止,记忆只是像 `User prefers FastAPI over Django` 这样的字符串。这对基本演示足够了,但随着系统的发展,我们需要更多关于记忆本身的信息。
在上一节中,我们看到模式稍微做了调整,加入了 memory_type、重要性和置信度。
所以我们可以这样表示一条记忆:
代码块
Memory:
User prefers FastAPI over Django.
Type:
semantic
Importance:
0.8
Confidence:
0.95为什么这些字段很重要?
考虑一个场景,我们有两条记忆。
记忆 1:用户的名字是 Jaydeep。
记忆 2:用户正在准备后端工程面试。
两条都是有效的记忆。但它们的实用性可能因查询而异。同样,以低置信度提取的记忆不应该与用户明确陈述的内容同等对待。
所以让我们扩展一下模式。
代码块
CREATE TABLE memories (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id TEXT NOT NULL,
content TEXT NOT NULL,
memory_type TEXT NOT NULL,
importance REAL DEFAULT 0.5,
confidence REAL DEFAULT 1.0,
embedding TEXT,
status TEXT DEFAULT 'active',
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
);我们的记忆现在有了更丰富的表示:
代码块
{
"content": "User prefers FastAPI over Django",
"type": "semantic",
"importance": 0.8,
"confidence": 0.95,
"status": "active"
}注意我们还添加了 `embedding`、`status` 和 `updated_at` 列
我们不会马上全部使用它们。
embedding 在我们实现语义检索时会变得重要。
status 最终会帮助我们处理不再活跃的记忆。
updated_at 在记忆随时间变化时会变得有用。
这就是我们简单的数据库开始变成一个记忆存储,而不仅仅是一张文本表的地方。
现在让我们更新 `save_memory()` 方法,使其接受额外的元数据
代码块
def save_memory(
user_id: str,
content: str,
memory_type: str,
importance: float = 0.5,
confidence: float = 1.0,
embedding=None,
):
connection = get_connection()
connection.execute(
"""
INSERT INTO memories (
user_id,
content,
memory_type,
importance,
confidence,
embedding,
status,
created_at,
updated_at
)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
""",
(
user_id,
content,
memory_type,
importance,
confidence,
json.dumps(embedding) if embedding else None,
"active",
datetime.now().isoformat(),
datetime.now().isoformat(),
),
)
connection.commit()
connection.close()仍然有一个很大的局限。我们目前是通过从 SQLite 中获取来检索记忆。如果我们只有十条记忆,那没问题。
当有一万条时会怎样?
我们不想把每条记忆都发送给大语言模型。我们需要找到与当前请求相关的记忆。这就是嵌入向量发挥作用的地方。
Generate embeddings for agent memories(为智能体记忆生成嵌入向量)
嵌入向量将文本转换为一个数字向量,捕捉其意义的各个方面。
例如:"User prefers FastAPI over Django" 会被转换成这样的向量:[0.12, -0.04, 0.87, ...]
实际的向量会包含更多维度。我们不需要理解每个单独的数字。重要的是语义上相似的文本往往会产生更接近的向量。
让我们创建一个文件 retrieval.py
代码块
from ollama import embed
EMBEDDING_MODEL = "nomic-embed-text"
def create_embedding(text: str) -> list[float]:
response = embed(
model=EMBEDDING_MODEL,
input=text,
)
return response.embeddings[0]
>> embedding = create_embedding( "User prefers FastAPI over Django")这给了我们记忆的向量表示。我们可以将该向量与记忆一起存储。对于这个项目,我们特意将其以 JSON 形式存储在 SQLite 中。
为什么不用向量数据库?因为在引入向量数据库之前,我们想了解它实际上在做什么。
Find similar memories(查找相似记忆)
假设我们有这些记忆:
代码块
User prefers FastAPI over Django.
User is preparing for backend engineering interviews.
User works with Kubernetes.
User's name is Jaydeep.现在用户问:我应该如何准备我的后端面试?
我们可以将查询与存储的每条记忆进行比较,计算它们在语义上的相似程度。为此,我们需要一个相似度函数。
一种常见的方法是余弦相似度。
代码块
import math
def cosine_similarity(
vector_a: list[float],
vector_b: list[float],
) -> float:
dot_product = sum(
a * b
for a, b in zip(vector_a, vector_b)
)
magnitude_a = math.sqrt(
sum(a * a for a in vector_a)
)
magnitude_b = math.sqrt(
sum(b * b for b in vector_b)
)
if magnitude_a == 0 or magnitude_b == 0:
return 0.0
return dot_product / (
magnitude_a * magnitude_b
)结果是相似度分数。例如,我们的查询可能会产生:
代码块
Memory Similarity
User is preparing for backend interviews 0.91
User prefers FastAPI over Django 0.84
User works with Kubernetes 0.62
User's name is Jaydeep 0.08我们现在可以检索最相关的记忆,而不是盲目地将所有内容传递给大语言模型。这将我们的检索流程从:
代码块
All memories
↓
LLM改为
代码块
Current query
↓
Create embedding
↓
Compare with stored embeddings
↓
Rank by similarity
↓
Top K memories
↓
LLM现在让我们更新 `retrieve_memories` 方法,计算余弦相似度以及一个自定义的评分公式来为每条记忆打分
代码块
import json
from memory import get_connection
def retrieve_memories(
user_id: str,
query: str,
top_k: int = 3,
):
query_embedding = create_embedding(query)
connection = get_connection()
cursor = connection.execute(
"""
SELECT
id,
content,
memory_type,
importance,
confidence,
embedding
FROM memories
WHERE user_id = ?
AND status = 'active'
AND embedding IS NOT NULL
""",
(user_id,),
)
memories = cursor.fetchall()
connection.close()
scored_memories = []
for memory in memories:
embedding = json.loads(memory[5])
similarity = cosine_similarity(
query_embedding,
embedding,
)
score = (
similarity * 0.7
+ memory[3] * 0.2
+ memory[4] * 0.1
)
scored_memories.append(
(score, memory)
)
scored_memories.sort(
key=lambda item: item[0],
reverse=True,
)
return scored_memories[:top_k]该公式不应被视为金科玉律,仅用于演示目的。每条记忆的评分公式是
代码块
Similarity → 70%
Importance → 20%
Confidence → 10%在生产系统中,这些权重需要根据实际的检索质量进行评估。重要的理念是,相关性并非仅由语义相似性决定。
一个记忆可能在语义上相关但重要性较低。另一个记忆可能极其重要,但与当前查询的相关性较弱。
我们的排名函数提供了一种简单的方式来结合这些信号。
Put the memory loop together(整合记忆循环)
至此,我们已经拥有了所有主要组成部分。当用户发送消息时,我们的系统现在可以执行两项操作。首先,它可以检索可能有助于回答当前请求的记忆。
其次,它可以分析新消息,以确定其是否应成为未来的记忆。
完整流程如下:
检索和提取是相互独立的。
检索回答的是:
哪些现有记忆对此请求有用?
提取回答的是:
这条新消息是否包含值得记住的内容?
这是两个不同的问题。将它们分开处理,使得系统更易于推理和理解。
Build the final agent(构建最终智能体)
现在我们可以将这些组件连接起来。
我们的 Agent 类需要做到:
接收用户消息
检索相关记忆
构建 LLM 上下文
生成响应
提取潜在的新记忆
在适当时保存它
代码块
class Agent:
def __init__(self, user_id: str):
self.user_id = user_id
self.messages = []
def chat(self, user_message: str):
memories = retrieve_memories(
self.user_id,
user_message,
top_k=3,
)
memory_context = "\n".join(
f"- {memory[1][1]}"
for memory in memories
)
if not memory_context:
memory_context = "No relevant memories."
prompt = f"""
You are a helpful AI assistant.
Relevant memories about the user:
{memory_context}
Use these memories when they are relevant.
Do not mention the memory system.
User's current message:
{user_message}
"""
self.messages.append({
"role": "user",
"content": prompt,
})
response = chat(
model="qwen3:4b",
messages=self.messages,
stream=True,
)
full_response = ""
print("Agent: ", end="", flush=True)
for chunk in response:
content = chunk.message.content
print(
content,
end="",
flush=True,
)
full_response += content
print()
self.messages.append({
"role": "assistant",
"content": full_response,
})
print(
"\n[Extracting memory...]",
flush=True,
)
memory_candidate = extract_memory(
user_message
)
print(
f"[Memory decision: "
f"{memory_candidate['should_remember']}]",
flush=True,
)
if memory_candidate["should_remember"]:
content = memory_candidate["memory"]
embedding = create_embedding(
content
)
save_memory(
user_id=self.user_id,
content=content,
memory_type=memory_candidate["memory_type"],
importance=memory_candidate["importance"],
confidence=memory_candidate["confidence"],
embedding=embedding,
)
print(
"[Memory saved]",
flush=True,
)
return full_response这个类内部有很多事情发生,但请注意,每一项职责都对应我们已构建的某个部分。
代码块
retrieve_memories()
↓
create_embedding()
↓
LLM response
↓
extract_memory()
↓
create_embedding()
↓
save_memory()Add the application entry point(添加应用程序入口点)
我们现在拥有记忆系统的所有独立组件:
代码块
agent.py
↓
Coordinates the agent
memory.py
↓
Stores and retrieves memories
retrieval.py
↓
Creates embeddings and finds relevant memories
extractor.py
↓
Decides what information is worth remembering我们还需要一些东西来将一切串联起来,并提供与智能体交互的界面。这就是 main.py 的作用。
代码块
from day3.agent import Agent
from day3.memory import init_db, get_memories
USER_ID = "jaydeep"
def print_memories():
memories = get_memories(USER_ID)
print("\n" + "=" * 60)
print("STORED MEMORIES")
print("=" * 60)
if not memories:
print("No memories stored.")
return
for memory in memories:
print(f"""
ID: {memory[0]}
Memory: {memory[1]}
Type: {memory[2]}
Importance: {memory[3]:.2f}
Confidence: {memory[4]:.2f}
Created: {memory[7]}
""")
def main():
init_db()
agent = Agent(USER_ID)
print("=" * 60)
print("AGENT MEMORY DEMO")
print("=" * 60)
print("""
Commands:
/memories - show stored memories
/exit - quit
""")
while True:
user_message = input("\nYou: ").strip()
if not user_message:
continue
if user_message == "/exit":
break
if user_message == "/memories":
print_memories()
continue
agent.chat(user_message)
if __name__ == "__main__":
main()这个文件里没有太多 AI 逻辑。这是有意为之。`main.py` 仅仅是我们应用程序的入口点。
应用程序启动时,首先调用 `init_db()`。这确保我们的 SQLite 数据库和 memories 表存在。然后我们为用户创建一个智能体
agent = Agent (USER_ID)
从那里,每条消息都被传递给:
agent.chat(user_message)
Agent 类负责处理我们之前构建的实际记忆生命周期。
我们还添加了两个简单命令:
/memories
/exit
/memories 让我们检查系统实际存储了什么。这在实验时特别有用,因为我们可以看到记忆提取器是否在做明智的决策。
此时,项目具有简单的结构:
代码块
agent_memory
├── main.py
├── agent.py
├── extractor.py
├── memory.py
└── retrieval.py
Each file has a focused responsibility.
main.py
↓
Application entry point
agent.py
↓
Agent orchestration
extractor.py
↓
Memory extraction
memory.py
↓
Persistent storage
retrieval.py
↓
Embeddings + semantic retrieval现在让我们运行 Agent Memory 代码,实时查看其运作
由于这是首次运行,我们没有存储的记忆
让我们添加一些智能体理想情况下应该记住的内容
正如我们所见,智能体决定 ' 我是一名后端工程师,正在转型为 AI 工程师 ' 值得存入记忆中。
The complete code(完整代码)
我们有意将本文中的代码聚焦于每个独立步骤,以便我们理解所发生的事情。
完整可运行的实现,包括 Python 文件、SQLite 记忆存储、Ollama 集成、记忆提取、嵌入和语义检索,均可在 GitHub 上获取。
克隆仓库并安装依赖:
代码块
uv sync确保 Ollama 已具备所需模型:
代码块
ollama pull qwen3:4b
ollama pull nomic-embed-text然后启动智能体:
代码块
uv run main.py所有内容均在本地运行,因此我们无需为此实验使用外部 LLM API。
Final thoughts(最终思考)
我们在这篇文章开头提出了一个简单的问题:
如何在智能体中真正构建记忆?
答案并不是简单的 “添加一个向量数据库”。
向量数据库只是系统的一部分。一个记忆系统需要回答一系列问题:
代码块
What should I remember?
↓
How should I represent it?
↓
Where should I store it?
↓
When should I retrieve it?
↓
How relevant is it?
↓
What should I inject into context?
↓
Is the memory still true?
↓
Should I update or forget it?今天,我们构建了该流程的第一版。它小到足以让人理解,但完整到足以展示幕后真正发生的事情。
而且我们发现了一个重要问题。存储很容易。在正确的时间找到正确的记忆则困难得多。
这正是我们接下来要探讨的方向…… 敬请期待第 4 天。