关于 conversation-memory
为 LLM 对话设计持久记忆系统的技能,覆盖短期、长期和实体记忆的存储、检索与整合。适合构建对话式 AI 的开发者,并强调用户隔离、记忆清理和相关性筛选等实现注意事项。
主要功能
- 01短期、长期与实体记忆模式
- 02记忆持久化和检索策略
- 03按上下文检索相关记忆
- 04记忆整合与生命周期管理
- 05用户隔离和隐私风险检查
适用场景
- 01为对话式 AI 设计分层记忆
- 02让 LLM 在提示词中使用相关历史
- 03规划记忆清理和跨用户隔离
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ sickn33/ agentic-awesome-skills --skill conversation-memory安装后在 Claude Code 中输入/conversation-memory确认已加载。
详细介绍
对话记忆
用于 LLM 对话的持久化记忆系统,包括短期、长期和基于实体的记忆
能力
- 短期记忆
- 长期记忆
- 实体记忆
- 记忆持久化
- 记忆检索
- 记忆整合
前置条件
- 知识:LLM 对话模式、数据库基础知识、键值存储
- 建议技能:上下文窗口管理、RAG 实现
范围
- 不涵盖:知识图谱构建、语义搜索实现、数据库管理
- 边界:重点关注 LLM 的记忆模式,涵盖存储和检索策略
生态系统
主要工具
- Mem0 - AI 应用的记忆层
- LangChain Memory - LangChain 中的记忆工具
- Redis - 用于会话记忆的内存数据存储 示例是架构草图,其中的存储、构造函数和辅助方法由应用程序负责。每个存储都必须预先限定到经过身份验证的租户/用户;最后的隔离示例并非可选项。仅持久化用户/产品记忆策略允许的信息;排除凭据,对每一层应用保留/删除策略,并保留来源/时间/置信度及更正记录。提取/生成的文本是不可信证据,绝不是指令或已验证事实。名称相同的实体不一定是同一个人:合并前先解析身份,绝不可在没有证据的情况下赋予经过校准的 0.9 置信度。草图中声明的 LONG_TERM_MAX 并未实际强制执行:在投入生产前实现有界淘汰。
模式
分层记忆系统
针对不同用途使用不同记忆层
使用场景:构建任何对话式 AI
interface MemorySystem {
// Buffer: Current conversation (in context)
buffer: ConversationBuffer;
// Short-term: Recent interactions (session)
shortTerm: ShortTermMemory;
// Long-term: Persistent across sessions
longTerm: LongTermMemory;
// Entity: Facts about people, places, things
entity: EntityMemory;
}
class TieredMemory implements MemorySystem {
async addMessage(message: Message): Promise<void> {
// Always add to buffer
this.buffer.add(message);
// Extract entities
const entities = await extractEntities(message);
for (const entity of entities) {
await this.entity.upsert(entity);
}
// Check for memorable content
if (await isMemoryWorthy(message)) {
await this.shortTerm.add({
content: message.content,
timestamp: Date.now(),
importance: await scoreImportance(message)
});
}
}
async consolidate(): Promise<void> {
// Move important short-term to long-term
const memories = await this.shortTerm.getOld(24 * 60 * 60 * 1000);
for (const memory of memories) {
if (memory.importance > 0.7 || memory.referenced > 2) {
await this.longTerm.add(memory);
}
await this.shortTerm.remove(memory.id);
}
}
async buildContext(query: string): Promise<string> {
const parts: string[] = [];
// Relevant long-term memories
const longTermRelevant = await this.longTerm.search(query, 3);
if (longTermRelevant.length) {
parts.push('## Relevant Memories\n' +
longTermRelevant.map(m => `- ${m.content}`).join('\n'));
}
// Relevant entities
const entities = await this.entity.getRelevant(query);
if (entities.length) {
parts.push('## Known Entities\n' +
entities.map(e => `- ${e.name}: ${e.facts.map(f => f.content).join(', ')}`).join('\n'));
}
// Recent conversation
const recent = this.buffer.getRecent(10);
parts.push('## Recent Conversation\n' + formatMessages(recent));
return parts.join('\n\n');
}
}
实体记忆
存储并更新有关实体的事实
使用场景:需要记住有关人物、地点、事物的详细信息
interface Entity {
id: string;
name: string;
type: 'person' | 'place' | 'thing' | 'concept';
facts: Fact[];
lastMentioned: number;
mentionCount: number;
}
interface Fact {
content: string;
confidence: number;
source: string; // Which message this came from
timestamp: number;
}
class EntityMemory {
async extractAndStore(message: Message): Promise<void> {
// Use LLM to extract entities and facts
const extraction = await llm.complete(`
Extract entities and facts from this message.
Return JSON: { "entities": [
{ "name": "...", "type": "...", "facts": ["..."] }
]}
Message: "${message.content}"
`);
const { entities } = JSON.parse(extraction);
for (const entity of entities) {
await this.upsert(entity, message.id);
}
}
async upsert(entity: ExtractedEntity, sourceId: string): Promise<void> {
const existing = await this.store.get(entity.name.toLowerCase());
if (existing) {
// Merge facts, avoiding duplicates
for (const fact of entity.facts) {
if (!this.hasSimilarFact(existing.facts, fact)) {
existing.facts.push({
content: fact,
confidence: 0.9,
source: sourceId,
timestamp: Date.now()
});
}
}
existing.lastMentioned = Date.now();
existing.mentionCount++;
await this.store.set(entity.name.toLowerCase(), existing);
} else {
// Create new entity
await this.store.set(entity.name.toLowerCase(), {
id: generateId(),
name: entity.name,
type: entity.type,
facts: entity.facts.map(f => ({
content: f,
confidence: 0.9,
source: sourceId,
timestamp: Date.now()
})),
lastMentioned: Date.now(),
mentionCount: 1
});
}
}
}
记忆感知式提示
在提示词中加入相关记忆
使用场景:在带有记忆上下文的情况下调用 LLM
async function promptWithMemory(
query: string,
memory: MemorySystem,
systemPrompt: string
): Promise<string> {
// Retrieve relevant memories
const relevantMemories = await memory.longTerm.search(query, 5);
const entities = await memory.entity.getRelevant(query);
const recentContext = memory.buffer.getRecent(5);
// Build memory-augmented prompt
const prompt = `
${systemPrompt}
## User Context
${entities.length ? `Known about user:\n${entities.map(e =>
`- ${e.name}: ${e.facts.map(f => f.content).join('; ')}`
).join('\n')}` : ''}
${relevantMemories.length ? `Relevant past interactions:\n${relevantMemories.map(m =>
`- [${formatDate(m.timestamp)}] ${m.content}`
).join('\n')}` : ''}
## Recent Conversation
${formatMessages(recentContext)}
## Current Query
${query}
`.trim();
const response = await llm.complete(prompt);
// Do not promote generated assistant claims into user facts.
// Persist only authorized source messages through the application memory policy.
return response;
}
易错之处
记忆存储无限增长,导致系统变慢
严重程度:高
情况:系统随时间推移变慢,成本上升
症状:
- 记忆检索缓慢
- 存储成本高
- 延迟随时间不断增加
问题原因: 每条消息都被存储为记忆。 没有清理或整合。 需要从数百万条记录中检索。
建议的修复方法:
// Implement memory lifecycle management
class ManagedMemory {
// Limits
private readonly SHORT_TERM_MAX = 100;
private readonly LONG_TERM_MAX = 10000;
private readonly CONSOLIDATION_INTERVAL = 24 * 60 * 60 * 1000;
async add(memory: Memory): Promise<void> {
// Score importance before storing
const score = await this.scoreImportance(memory);
if (score < 0.3) return; // Don't store low-importance
memory.importance = score;
await this.shortTerm.add(memory);
// Check limits
await this.enforceShortTermLimit();
}
async enforceShortTermLimit(): Promise<void> {
const count = await this.shortTerm.count();
if (count > this.SHORT_TERM_MAX) {
// Consolidate: move important to long-term, delete rest
const memories = await this.shortTerm.getAll();
memories.sort((a, b) => b.importance - a.importance);
const toKeep = memories.slice(0, this.SHORT_TERM_MAX * 0.7);
const toConsolidate = memories.slice(this.SHORT_TERM_MAX * 0.7);
for (const m of toConsolidate) {
if (m.importance > 0.7) {
await this.longTerm.add(m);
}
await this.shortTerm.remove(m.id);
}
}
}
async scoreImportance(memory: Memory): Promise<number> {
const factors = {
hasUserPreference: /prefer|like|don't like|hate|love/i.test(memory.content) ? 0.3 : 0,
hasDecision: /decided|chose|will do|won't do/i.test(memory.content) ? 0.3 : 0,
hasFactAboutUser: /my|I am|I have|I work/i.test(memory.content) ? 0.2 : 0,
length: memory.content.length > 100 ? 0.1 : 0,
userMessage: memory.role === 'user' ? 0.1 : 0,
};
return Object.values(factors).reduce((a, b) => a + b, 0);
}
}
检索到的记忆与当前查询无关
严重程度:高
情况:记忆被加入上下文,却没有帮助
症状:
- 上下文中的记忆似乎毫无关联
- 用户询问已经存入记忆的内容
- 无关上下文造成困惑
问题原因: 仅使用简单的关键词匹配。 没有相关性评分。 加入所有检索到的记忆。
建议的修复方法:
// Intelligent memory retrieval
async function retrieveRelevant(
query: string,
memories: MemoryStore,
maxResults: number = 5
): Promise<Memory[]> {
// 1. Semantic search
const candidates = await memories.semanticSearch(query, maxResults * 3);
// 2. Score relevance with context
const scored = await Promise.all(candidates.map(async (m) => {
const relevanceScore = await llm.complete(`
Rate 0-1 how relevant this memory is to the query.
Query: "${query}"
Memory: "${m.content}"
Return just the number.
`);
const score = Number(relevanceScore.trim());
return { ...m, relevance: Number.isFinite(score) && score >= 0 && score <= 1 ? score : 0 };
}));
// 3. Filter low relevance
const relevant = scored.filter(m => m.relevance > 0.5);
// 4. Sort and limit
return relevant
.sort((a, b) => b.relevance - a.relevance)
.slice(0, maxResults);
}
一个用户可以访问另一个用户的记忆
严重程度:严重
情况:用户看到其他用户会话中的信息
症状:
- 用户看到其他用户的信息
- 收到隐私投诉
- 违反合规要求
问题原因: 记忆存储中没有用户隔离。 共享记忆命名空间。 跨用户检索。
建议的修复方法:
// Strict user isolation in memory
class IsolatedMemory {
private getKey(userId: string, memoryId: string): string {
// Namespace all keys by user
return `user:${encodeURIComponent(userId)}:memory:${encodeURIComponent(memoryId)}`;
}
async add(userId: string, memory: Memory): Promise<void> {
// Validate userId is authenticated
if (requireAuthenticatedUserId() !== userId) {
throw new Error('Invalid user ID');
}
const key = this.getKey(userId, memory.id);
memory.userId = userId; // Tag with user
await this.store.set(key, memory);
}
async search(userId: string, query: string): Promise<Memory[]> {
// CRITICAL: Filter by user in query
return await this.store.search({
query,
filter: { userId: userId }, // Mandatory filter
limit: 10
});
}
async delete(userId: string, memoryId: string): Promise<void> {
const memory = await this.get(userId, memoryId);
// Verify ownership before delete
if (!memory || memory.userId !== userId) {
throw new Error('Access denied');
}
await this.store.delete(this.getKey(userId, memoryId));
}
// Scoped export (not proof of legal compliance)
async exportUserData(userId: string): Promise<Memory[]> {
return await this.store.getAll({ userId });
}
// Scoped deletion (also address backups, indexes, caches and retention policy)
async deleteUserData(userId: string): Promise<void> {
const memories = await this.exportUserData(userId);
for (const m of memories) {
await this.store.delete(this.getKey(userId, m.id));
}
}
}
验证检查
记忆中没有用户隔离
严重程度:严重
消息:记忆操作未进行用户隔离。存在隐私漏洞。
修复操作:在所有记忆操作中加入 userId,检索时按用户筛选
没有重要性筛选
严重程度:警告
消息:未进行重要性筛选便存储记忆。可能导致记忆膨胀。
修复操作:存储前评估重要性,筛除不重要的内容
存储记忆但不检索
严重程度:警告
消息:存储了记忆,但没有检索逻辑。记忆将无法发挥作用。
修复操作:实现记忆检索并将其纳入提示词
未清理记忆
严重程度:信息
消息:没有记忆清理机制。存储量将无限增长。
修复操作:根据存储时间/重要性实现记忆整合和清理
协作
委派触发条件
- context window|token -> context-window-management(需要优化上下文)
- rag|retrieval|vector -> rag-implementation(需要检索系统)
- cache|caching -> prompt-caching(需要缓存策略)
完整记忆系统
技能:conversation-memory、context-window-management、rag-implementation
工作流:
1. Design memory tiers
2. Implement storage and retrieval
3. Integrate with context management
4. Add consolidation and cleanup
相关技能
配合使用效果良好:context-window-management、rag-implementation、prompt-caching、llm-npc-dialogue
适用场景
- 用户提及或暗示:对话记忆
- 用户提及或暗示:记住
- 用户提及或暗示:记忆持久化
- 用户提及或暗示:长期记忆
- 用户提及或暗示:聊天记录
限制
- 仅当任务明确符合上述范围时,才使用此技能。
- 不要将输出视为特定环境验证、测试或专家评审的替代品。
- 如果缺少必要的输入、权限、安全边界或成功标准,请停止并请求澄清。