AI 助手记忆模式:构建持久化上下文系统

构建高效 AI 助手最大的挑战之一就是管理记忆。人类可以自然地记住对话并随着时间不断学习,而 AI 模型每次交互都是从零开始。实现强大的记忆系统,可以将一个基础的聊天机器人转变为真正智能的助手,使其理解上下文、记住偏好,并在过往交互的基础上不断进步。
本指南将探讨为 AI 助手构建记忆系统的模式和技术,并提供针对 Claude 和 OpenClaw 的实用实现。
理解 AI 记忆的挑战
像 Claude 这样的大型语言模型存在一个根本性限制:上下文窗口。虽然现代模型支持很大的上下文窗口(200K+ tokens),但仍然有限。更重要的是,除非明确保存,否则会话之间不会保留任何内容。
上下文窗口问题
上下文窗口就像模型的短期记忆。AI 在对话期间所知道的一切都必须放入这个窗口中,包括:
- 系统提示词
- 对话历史
- 相关文档或数据
- 工具定义和结果
随着对话越来越长,你将面临艰难的选择:截断历史(丢失上下文)、进行摘要(丢失细节),或有选择地包含信息(可能影响相关性)。
会话隔离
每次对 Claude 的 API 调用都是无状态的。除非你在请求中明确包含历史记录,否则模型不会记住之前的对话。这意味着:
- 用户偏好在会话之间会被遗忘
- 已学到的模式不会保留
- 每次都必须重新建立关系
解决方案:显式记忆系统
要创建具有真正记忆的 AI 助手,我们必须构建显式系统来:
- 在对话过程中捕获重要信息
- 将其持久化存储在模型之外
- 在需要时检索相关记忆
- 将其注入到未来的对话中
让我们来探讨实现这一目标的模式。
记忆架构层次
有效的 AI 记忆系统通常具有多个层次,每个层次服务于不同的目的。
工作记忆
工作记忆保存与当前对话相关的信息。它是临时的,但对于维持连贯的多轮对话至关重要。
interface WorkingMemory {
conversationId: string;
messages: Message[];
activeContext: string[];
pendingActions: Action[];
scratchpad: Record<string, unknown>;
}
class WorkingMemoryManager {
private memory: Map<string, WorkingMemory> = new Map();
createSession(conversationId: string): WorkingMemory {
const session: WorkingMemory = {
conversationId,
messages: [],
activeContext: [],
pendingActions: [],
scratchpad: {}
};
this.memory.set(conversationId, session);
return session;
}
addMessage(conversationId: string, message: Message): void {
const session = this.memory.get(conversationId);
if (session) {
session.messages.push(message);
this.pruneIfNeeded(session);
}
}
private pruneIfNeeded(session: WorkingMemory): void {
const MAX_MESSAGES = 50;
if (session.messages.length > MAX_MESSAGES) {
// Keep system messages and recent messages
const systemMessages = session.messages.filter(m => m.role === 'system');
const recentMessages = session.messages.slice(-MAX_MESSAGES + systemMessages.length);
session.messages = [...systemMessages, ...recentMessages];
}
}
}
短期记忆
短期记忆可以跨会话保留,但生命周期有限。它适用于:
- 近期的用户偏好
- 正在进行的任务和项目
- 临时笔记和提醒
interface ShortTermMemory {
userId: string;
entries: MemoryEntry[];
expiresAt: Date;
}
interface MemoryEntry {
id: string;
content: string;
type: 'preference' | 'task' | 'note' | 'context';
createdAt: Date;
accessedAt: Date;
importance: number;
}
class ShortTermMemoryStore {
private store: Map<string, ShortTermMemory> = new Map();
async addEntry(userId: string, entry: Omit<MemoryEntry, 'id' | 'createdAt' | 'accessedAt'>): Promise<string> {
const memory = this.store.get(userId) || this.createMemory(userId);
const fullEntry: MemoryEntry = {
...entry,
id: generateId(),
createdAt: new Date(),
accessedAt: new Date()
};
memory.entries.push(fullEntry);
this.enforceLimit(memory);
return fullEntry.id;
}
async getRelevant(userId: string, query: string, limit: number = 10): Promise<MemoryEntry[]> {
const memory = this.store.get(userId);
if (!memory) return [];
// 根据相关性和时效性为条目打分
const scored = memory.entries.map(entry => ({
entry,
score: this.calculateRelevance(entry, query)
}));
scored.sort((a, b) => b.score - a.score);
// 更新被检索条目的访问时间
const results = scored.slice(0, limit).map(s => s.entry);
results.forEach(entry => entry.accessedAt = new Date());
return results;
}
private calculateRelevance(entry: MemoryEntry, query: string): number {
let score = 0;
// 文本相似度(简化版)
const queryWords = query.toLowerCase().split(/\s+/);
const entryWords = entry.content.toLowerCase().split(/\s+/);
const overlap = queryWords.filter(w => entryWords.includes(w)).length;
score += overlap * 10;
// 时效性加分
const hoursSinceAccess = (Date.now() - entry.accessedAt.getTime()) / (1000 * 60 * 60);
score += Math.max(0, 50 - hoursSinceAccess);
// 重要性乘数
score *= entry.importance;
return score;
}
private enforceLimit(memory: ShortTermMemory): void {
const MAX_ENTRIES = 100;
if (memory.entries.length > MAX_ENTRIES) {
// 移除最不重要、最旧的条目
memory.entries.sort((a, b) => {
const aScore = a.importance + (a.accessedAt.getTime() / 1e12);
const bScore = b.importance + (b.accessedAt.getTime() / 1e12);
return bScore - aScore;
});
memory.entries = memory.entries.slice(0, MAX_ENTRIES);
}
}
}
长期记忆
长期记忆可以无限期地存储信息,它是真正具备持久性的助手的基础:
- 用户档案和偏好
- 历史对话(摘要)
- 已学习的事实和关系
- 技能和流程
interface LongTermMemory {
userId: string;
profile: UserProfile;
facts: Fact[];
conversations: ConversationSummary[];
relationships: Relationship[];
}
interface Fact {
id: string;
subject: string;
predicate: string;
object: string;
confidence: number;
source: string;
createdAt: Date;
updatedAt: Date;
}
interface ConversationSummary {
id: string;
date: Date;
topics: string[];
keyPoints: string[];
decisions: string[];
followUps: string[];
}
class LongTermMemoryStore {
private db: Database;
async storeFact(userId: string, fact: Omit<Fact, 'id' | 'createdAt' | 'updatedAt'>): Promise<void> {
const existing = await this.findExistingFact(userId, fact);
if (existing) {
// 更新置信度和时间戳
await this.db.facts.update(existing.id, {
confidence: Math.min(1, existing.confidence + 0.1),
updatedAt: new Date()
});
} else {
await this.db.facts.insert({
...fact,
id: generateId(),
userId,
createdAt: new Date(),
updatedAt: new Date()
});
}
}
async queryFacts(userId: string, query: string): Promise<Fact[]> {
// 使用基于嵌入向量的搜索进行语义匹配
const embedding = await this.getEmbedding(query);
return this.db.facts.vectorSearch({
userId,
embedding,
limit: 20,
minConfidence: 0.5
});
}
async summarizeConversation(conversation: Message[]): Promise<ConversationSummary> {
// 使用 Claude 生成摘要
const summaryPrompt = `Summarize this conversation, extracting:
1. Main topics discussed
2. Key points and information shared
3. Decisions made
4. Follow-up actions needed
Conversation:
${conversation.map(m => `${m.role}: ${m.content}`).join('\n')}`;
const summary = await claude.complete(summaryPrompt);
return JSON.parse(summary);
}
}
记忆检索策略
如果无法有效检索,存储记忆就毫无意义。难点在于在正确的时间找到正确的记忆。
基于关键词的检索
最简单的方法是将当前查询与已存储的记忆进行关键词匹配:
function keywordRetrieval(query: string, memories: MemoryEntry[]): MemoryEntry[] {
const queryTokens = tokenize(query.toLowerCase());
return memories
.map(memory => {
const memoryTokens = tokenize(memory.content.toLowerCase());
const overlap = queryTokens.filter(t => memoryTokens.includes(t));
return { memory, score: overlap.length / queryTokens.length };
})
.filter(result => result.score > 0.1)
.sort((a, b) => b.score - a.score)
.map(result => result.memory);
}
基于嵌入向量的语义检索
为了获得更好的语义匹配效果,请使用嵌入向量:
import { EmbeddingModel } from './embeddings';
class SemanticMemoryRetriever {
private embedder: EmbeddingModel;
private vectorStore: VectorStore;
async indexMemory(memory: MemoryEntry): Promise<void> {
const embedding = await this.embedder.embed(memory.content);
await this.vectorStore.insert({
id: memory.id,
vector: embedding,
metadata: {
type: memory.type,
createdAt: memory.createdAt
}
});
}
async retrieve(query: string, options: RetrievalOptions = {}): Promise<MemoryEntry[]> {
const queryEmbedding = await this.embedder.embed(query);
const results = await this.vectorStore.search({
vector: queryEmbedding,
limit: options.limit || 10,
threshold: options.threshold || 0.7,
filter: options.filter
});
return results.map(r => this.loadMemory(r.id));
}
}
混合检索
结合多种策略以获得最佳结果:
class HybridRetriever {
async retrieve(query: string, memories: MemoryEntry[]): Promise<MemoryEntry[]> {
// 从多种策略中获取结果
const keywordResults = await this.keywordRetrieval(query, memories);
const semanticResults = await this.semanticRetrieval(query);
const recencyResults = await this.recencyRetrieval(memories);
// 合并并去重
const combined = new Map<string, { memory: MemoryEntry; score: number }>();
keywordResults.forEach((m, i) => {
const existing = combined.get(m.id);
const score = (keywordResults.length - i) / keywordResults.length;
if (!existing || existing.score < score) {
combined.set(m.id, { memory: m, score });
}
});
semanticResults.forEach((m, i) => {
const existing = combined.get(m.id);
const score = (semanticResults.length - i) / semanticResults.length;
if (existing) {
existing.score += score * 0.5;
} else {
combined.set(m.id, { memory: m, score: score * 0.5 });
}
});
// 按综合得分排序
return Array.from(combined.values())
.sort((a, b) => b.score - a.score)
.map(r => r.memory);
}
}
记忆注入模式
检索到相关记忆后,您需要将它们有效地注入到对话中。
系统提示词注入
将记忆包含在系统提示词中:
function buildSystemPrompt(basePrompt: string, memories: MemoryEntry[]): string {
const memorySection = memories.length > 0
? `\n\n## Relevant Memories\n${memories.map(m => `- ${m.content}`).join('\n')}`
: '';
return basePrompt + memorySection;
}
上下文窗口管理
谨慎管理放入上下文窗口的内容:
class ContextWindowManager {
private readonly maxTokens: number;
private readonly reservedForResponse: number = 4000;
constructor(maxTokens: number = 200000) {
this.maxTokens = maxTokens;
}
buildContext(components: ContextComponent[]): string {
const availableTokens = this.maxTokens - this.reservedForResponse;
// 按优先级排序
const sorted = [...components].sort((a, b) => b.priority - a.priority);
let usedTokens = 0;
const included: ContextComponent[] = [];
for (const component of sorted) {
const tokens = this.countTokens(component.content);
if (usedTokens + tokens <= availableTokens) {
included.push(component);
usedTokens += tokens;
} else if (component.required) {
// 尝试对放不下的必需组件进行摘要
const summarized = this.summarize(component.content, availableTokens - usedTokens);
included.push({ ...component, content: summarized });
usedTokens += this.countTokens(summarized);
}
}
return included.map(c => c.content).join('\n\n');
}
}
对话摘要
当历史记录过长时,对较早的消息进行摘要:
class ConversationCompressor {
async compress(messages: Message[], targetTokens: number): Promise<Message[]> {
const currentTokens = this.countTokens(messages);
if (currentTokens <= targetTokens) {
return messages;
}
// 保持最近的消息完整
const recentCount = Math.min(10, messages.length);
const recentMessages = messages.slice(-recentCount);
const olderMessages = messages.slice(0, -recentCount);
// 对较早的消息进行摘要
const summary = await this.summarize(olderMessages);
return [
{
role: 'system',
content: `[Previous conversation summary: ${summary}]`
},
...recentMessages
];
}
private async summarize(messages: Message[]): Promise<string> {
const prompt = `Summarize this conversation concisely, preserving:
- Key decisions and agreements
- Important facts mentioned
- Unresolved questions or tasks
${messages.map(m => `${m.role}: ${m.content}`).join('\n')}`;
return claude.complete(prompt);
}
}
OpenClaw 记忆实现
OpenClaw 通过其文件系统为记忆提供内置支持。以下是如何有效利用它的方法。
记忆文件
OpenClaw 使用 markdown 文件进行持久化记忆:
<!-- memory/MEMORY.md -->
# 长期记忆
## 用户档案
- 姓名:John Smith
- 时区:America/New_York
- 偏好:偏好简洁的回复,注重技术深度
## 关键事实
- 在 TechCorp 担任高级工程师
- 主要项目:电商平台迁移
- 相比 JavaScript 更喜欢 Python
## 近期决策
- 2026-02-15:决定为新数据库使用 PostgreSQL
- 2026-02-18:已安排周五进行代码评审
每日记忆文件
追踪日常上下文:
<!-- memory/2026-02-20.md -->
# 2026年2月20日
## 上午会话
- 评审了拉取请求 #234
- 讨论了支付模块的 API 设计
- 用户提到截止日期是 3 月 1 日
## 任务
- [ ] 跟进支付服务商的选择
- [x] 发送文档链接
## 备注
- 用户似乎对截止日期感到压力很大
- 本周更倾向于较短的会议
记忆更新模式
让 AI 维护自己的记忆:
const memoryUpdatePrompt = `每次对话结束后,更新你的记忆文件:
1. 如果了解到关于用户的新信息,请将其添加到 MEMORY.md
2. 如果有任务或后续事项,请将其添加到今天的每日文件中
3. 如果用户表达了偏好,请记录下来
请有所选择——只存储在未来对话中有用的信息。`;
高级记忆模式
情景记忆
存储特定的事件和经历:
interface Episode {
id: string;
timestamp: Date;
participants: string[];
location?: string;
event: string;
outcome: string;
emotions?: string[];
importance: number;
}
class EpisodicMemory {
async recordEpisode(episode: Episode): Promise<void> {
await this.store.insert(episode);
// 从情景中提取事实
const facts = await this.extractFacts(episode);
for (const fact of facts) {
await this.factStore.storeFact(fact);
}
}
async recall(cue: string): Promise<Episode[]> {
// 查找与线索匹配的情景
const embedding = await this.embed(cue);
return this.store.vectorSearch({
embedding,
limit: 5
});
}
}
程序性记忆
记住如何做事:
interface Procedure {
id: string;
name: string;
description: string;
steps: string[];
prerequisites: string[];
successRate: number;
lastUsed: Date;
}
class ProceduralMemory {
async learnProcedure(name: string, steps: string[]): Promise<void> {
const existing = await this.find(name);
if (existing) {
// 用新步骤更新,同时保留有效的部分
existing.steps = this.mergeSteps(existing.steps, steps);
existing.lastUsed = new Date();
await this.store.update(existing);
} else {
await this.store.insert({
id: generateId(),
name,
description: await this.generateDescription(steps),
steps,
prerequisites: await this.inferPrerequisites(steps),
successRate: 1.0,
lastUsed: new Date()
});
}
}
async execute(name: string): Promise<ProcedureResult> {
const procedure = await this.find(name);
if (!procedure) throw new Error(`Unknown procedure: ${name}`);
const result = await this.runSteps(procedure.steps);
// 更新成功率
procedure.successRate = procedure.successRate * 0.9 + (result.success ? 0.1 : 0);
await this.store.update(procedure);
return result;
}
}
联想记忆
在记忆之间建立联系:
interface Association {
sourceId: string;
targetId: string;
type: 'causal' | 'temporal' | 'semantic' | 'emotional';
strength: number;
}
class AssociativeMemory {
async associate(memory1: string, memory2: string, type: Association['type']): Promise<void> {
const existing = await this.findAssociation(memory1, memory2);
if (existing) {
existing.strength = Math.min(1, existing.strength + 0.1);
await this.store.update(existing);
} else {
await this.store.insert({
sourceId: memory1,
targetId: memory2,
type,
strength: 0.5
});
}
}
async spread(startMemoryId: string, depth: number = 2): Promise<Memory[]> {
const visited = new Set<string>();
const results: Memory[] = [];
async function explore(memoryId: string, currentDepth: number): Promise<void> {
if (currentDepth > depth || visited.has(memoryId)) return;
visited.add(memoryId);
const memory = await this.loadMemory(memoryId);
results.push(memory);
const associations = await this.getAssociations(memoryId);
const strongAssociations = associations.filter(a => a.strength > 0.3);
for (const assoc of strongAssociations) {
await explore(assoc.targetId, currentDepth + 1);
}
}
await explore(startMemoryId, 0);
return results;
}
}
记忆衰减与遗忘
并非所有记忆都应永久保留。实现遗忘机制可以获得更好的性能:
class MemoryDecay {
async applyDecay(memories: MemoryEntry[]): Promise<void> {
const now = new Date();
for (const memory of memories) {
const daysSinceAccess = (now.getTime() - memory.accessedAt.getTime()) / (1000 * 60 * 60 * 24);
// 基于时间和重要性的指数衰减
const decayRate = 0.95;
const importanceBonus = memory.importance * 0.1;
const decayFactor = Math.pow(decayRate, daysSinceAccess) + importanceBonus;
memory.importance *= decayFactor;
// 移除低于阈值的记忆
if (memory.importance < 0.1) {
await this.archive(memory);
}
}
}
async consolidate(): Promise<void> {
// 定期合并相似的记忆
const allMemories = await this.store.getAll();
const clusters = await this.clusterSimilar(allMemories);
for (const cluster of clusters) {
if (cluster.length > 1) {
const merged = await this.mergeMemories(cluster);
await this.store.replace(cluster.map(m => m.id), merged);
}
}
}
}
结论
为 AI 助手构建有效的记忆系统,需要跨多个层次进行周全的架构设计。从维持对话连贯性的工作记忆,到保存用户偏好和已学事实的长期存储,每一层都发挥着至关重要的作用。
需要记住的关键原则:
- 为记忆分层 - 不同类型的信息需要不同的存储和检索模式
- 智能检索 - 使用结合关键词、语义和时效性的混合方法
- 谨慎管理上下文 - 上下文窗口是宝贵的空间
- 让记忆衰减 - 并非所有内容都需要永远记住
- 建立关联 - 相互关联的记忆比孤立的事实更有用
借助这些模式,您可以构建真正能够学习和记忆的 AI 助手,随着时间推移创造更自然、更有效的交互。
更多文章
终极 OpenClaw AWS 设置指南

在 AWS 上设置 OpenClaw 的权威指南。包括竞价实例配置、成本优化和分步说明。
在 OpenClaw 中使用工具链构建 AI 工作流
掌握工具链与函数调用的串联技巧,构建强大的多步骤 AI 自动化工作流——从数据提取到内容生成和部署。
自托管AI助手成本优化指南:低预算运行 Claude
降低自托管AI助手API成本的实用策略——智能模型路由、缓存、批处理,以及针对 OpenClaw 的优化,让您以更低的成本运行 Claude。