CLAWIST.
📖 指南阅读时间 11 分钟••作者:Lin

使用 Claude 为 AI 聊天机器人构建记忆系统:超越上下文窗口

使用笔记本电脑和智能手机的人物——示意图

与 Claude 的每一次对话都是从零开始的。模型不会记得你之前的聊天内容、你的偏好,也不会记得你在数周的互动中积累起来的上下文。对许多应用来说,这是一个根本性的限制。

不过,你可以围绕 Claude 构建记忆系统,让你的聊天机器人能够回忆过去的对话、学习用户偏好,并在不同会话之间保持上下文。本指南将向你展示如何做到这一点。

记忆问题

Claude 的上下文窗口很大——最高可达 20 万个 token——但这并不是记忆。一旦对话结束,上下文中的所有内容都会消失。下一次对话将从零开始。

这会给以下场景带来问题:

  • 客户支持机器人 需要记住过去的工单
  • 个人助理 需要学习你的偏好
  • 教育工具 需要跟踪学习进度
  • 任何应用 只要连续性很重要

解决方案是构建外部记忆系统,用于存储、索引和检索相关信息,并在合适的时机将其注入 Claude 的上下文中。

记忆的类型

有效的聊天机器人记忆系统会实现多种类型的记忆:

短期记忆 保存当前的对话。这其实就是你已经在传给 Claude 的消息历史。

工作记忆 存储活跃的上下文——当前目标、近期决策、进行中的任务。它会在一个会话或项目内的多次对话之间持续保留。

长期记忆 记录应在数月之后仍能回忆起来的事实、偏好和重要事件。这需要持久化存储和智能检索。

情景记忆 记住特定的过去对话或事件。"还记得我们上周二讨论的营销策略吗?"

让我们逐一实现这些记忆类型。

短期记忆:对话历史

最简单的记忆就是你的消息数组。但即便如此,也有一些优化方法:

class ConversationMemory {
  constructor(maxMessages = 20) {
    this.messages = [];
    this.maxMessages = maxMessages;
  }
  
  addMessage(role, content) {
    this.messages.push({ role, content });
    
    // 使用滑动窗口,使其保持在上下文限制之内
    if (this.messages.length > this.maxMessages) {
      this.messages = this.messages.slice(-this.maxMessages);
    }
  }
  
  getContext() {
    return this.messages;
  }
}

对于较长的对话,应对较早的消息进行摘要,而不是直接丢弃:

async summarizeOlderMessages(messages) {
  const toSummarize = messages.slice(0, -10);
  const recent = messages.slice(-10);
  
  const summary = await anthropic.messages.create({
    model: "claude-haiku-3-20240307",
    max_tokens: 500,
    messages: [{
      role: "user",
      content: `Summarize this conversation in 2-3 sentences, 
                capturing key points and decisions: 
                ${JSON.stringify(toSummarize)}`
    }]
  });
  
  return [
    { role: "system", content: `Previous conversation summary: ${summary.content}` },
    ...recent
  ];
}

工作记忆:活跃上下文

工作记忆保存与当前任务或会话相关的信息。请以结构化的格式存储它:

class WorkingMemory {
  constructor() {
    this.context = {
      currentGoal: null,
      activeProject: null,
      recentDecisions: [],
      pendingTasks: [],
      lastUpdated: null
    };
  }
  
  update(key, value) {
    this.context[key] = value;
    this.context.lastUpdated = new Date().toISOString();
  }
  
  toPrompt() {
    return `Current context:
    - Goal: ${this.context.currentGoal || 'None set'}
    - Project: ${this.context.activeProject || 'None'}
    - Recent decisions: ${this.context.recentDecisions.join(', ') || 'None'}
    - Pending tasks: ${this.context.pendingTasks.join(', ') || 'None'}`;
  }
}

将此内容注入您的系统提示词,使 Claude 始终能够获取当前的工作上下文。

长期记忆:向量存储

长期记忆需要持久地存储信息,并根据语义相似度进行检索。向量数据库非常擅长这一点。

以下是使用 Pinecone 的完整实现:

import { Pinecone } from '@pinecone-database/pinecone';
import Anthropic from '@anthropic-ai/sdk';

class LongTermMemory {
  constructor(userId) {
    this.userId = userId;
    this.pinecone = new Pinecone();
    this.index = this.pinecone.index('chatbot-memory');
    this.anthropic = new Anthropic();
  }
  
  async store(content, metadata = {}) {
    // Generate embedding using an embedding model
    const embedding = await this.getEmbedding(content);
    
    await this.index.upsert([{
      id: `${this.userId}-${Date.now()}`,
      values: embedding,
      metadata: {
        userId: this.userId,
        content: content,
        timestamp: new Date().toISOString(),
        ...metadata
      }
    }]);
  }
  
  async recall(query, topK = 5) {
    const queryEmbedding = await this.getEmbedding(query);
    
    const results = await this.index.query({
      vector: queryEmbedding,
      topK: topK,
      filter: { userId: this.userId },
      includeMetadata: true
    });
    
    return results.matches.map(match => ({
      content: match.metadata.content,
      timestamp: match.metadata.timestamp,
      relevance: match.score
    }));
  }
  
  async getEmbedding(text) {
    // Use OpenAI's embedding model or similar
    const response = await fetch('https://api.openai.com/v1/embeddings', {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.OPENAI_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: 'text-embedding-3-small',
        input: text
      })
    });
    
    const data = await response.json();
    return data.data[0].embedding;
  }
}

自动提取记忆

无需手动决定要记住什么——让 Claude 自动提取重要信息:

async extractMemories(conversation) {
  const response = await anthropic.messages.create({
    model: "claude-sonnet-4-20250514",
    max_tokens: 1000,
    messages: [{
      role: "user",
      content: `Analyze this conversation and extract any facts, preferences, 
                or important information worth remembering about the user.
                
                Format as JSON: { "memories": [{ "type": "fact|preference|event", 
                "content": "...", "importance": 1-10 }] }
                
                Conversation: ${JSON.stringify(conversation)}`
    }]
  });
  
  const memories = JSON.parse(response.content);
  
  for (const memory of memories.memories) {
    if (memory.importance >= 7) {
      await this.longTermMemory.store(memory.content, {
        type: memory.type,
        importance: memory.importance
      });
    }
  }
}

在每次对话结束后运行此功能,以逐步建立用户的记忆档案。

情景记忆:对话归档

有时您需要回想具体的过往对话,而不仅仅是从中提取的事实:

class EpisodicMemory {
  constructor(userId) {
    this.userId = userId;
    this.db = new Database('episodes.db');
  }
  
  async storeEpisode(conversation, summary) {
    await this.db.insert('episodes', {
      userId: this.userId,
      timestamp: new Date().toISOString(),
      summary: summary,
      fullConversation: JSON.stringify(conversation),
      embedding: await this.getEmbedding(summary)
    });
  }
  
  async recallEpisode(query) {
    // Semantic search over episode summaries
    const episodes = await this.db.query(`
      SELECT summary, timestamp, fullConversation
      FROM episodes
      WHERE userId = ?
      ORDER BY vector_distance(embedding, ?) ASC
      LIMIT 3
    `, [this.userId, await this.getEmbedding(query)]);
    
    return episodes;
  }
}

整合应用

以下展示了所有记忆系统如何在一个完整的聊天机器人中协同工作:

class MemoryEnhancedChatbot {
  constructor(userId) {
    this.conversation = new ConversationMemory();
    this.working = new WorkingMemory();
    this.longTerm = new LongTermMemory(userId);
    this.episodic = new EpisodicMemory(userId);
    this.anthropic = new Anthropic();
  }
  
  async chat(userMessage) {
    // Add to conversation memory
    this.conversation.addMessage('user', userMessage);
    
    // Retrieve relevant long-term memories
    const memories = await this.longTerm.recall(userMessage);
    
    // Build context-enhanced prompt
    const systemPrompt = `You are a helpful assistant with memory.
    
    ${this.working.toPrompt()}
    
    Relevant memories about this user:
    ${memories.map(m => `- ${m.content}`).join('\n')}`;
    
    // Get response from Claude
    const response = await this.anthropic.messages.create({
      model: "claude-sonnet-4-20250514",
      max_tokens: 1024,
      system: systemPrompt,
      messages: this.conversation.getContext()
    });
    
    // Store response in conversation memory
    const assistantMessage = response.content[0].text;
    this.conversation.addMessage('assistant', assistantMessage);
    
    // Extract and store new memories (async, don't block)
    this.extractMemories(this.conversation.messages.slice(-4));
    
    return assistantMessage;
  }
}

记忆维护

长期记忆需要维护:

衰减旧记忆。 随着时间推移降低记忆的重要性评分,并删除低于阈值的记忆。

合并重复内容。 当相似的记忆不断积累时,将它们合并为单一且更强的记忆。

尊重隐私。 让用户可以查看、编辑和删除自己的记忆。将记忆管理功能内置到您的界面中。

async consolidateMemories() {
  const allMemories = await this.longTerm.getAllMemories();
  
  // Cluster similar memories
  const clusters = await this.clusterBySimilarity(allMemories);
  
  for (const cluster of clusters) {
    if (cluster.length > 1) {
      // Merge cluster into single memory
      const merged = await this.mergeMemories(cluster);
      await this.longTerm.store(merged);
      
      // Delete originals
      for (const memory of cluster) {
        await this.longTerm.delete(memory.id);
      }
    }
  }
}

生产环境注意事项

为真实用户构建记忆系统时:

  • 加密存储的记忆 使用用户专属密钥
  • 实施 GDPR 合规——用户可以导出和删除自己的数据
  • 设置记忆配额 以防止存储空间膨胀
  • 缓存频繁的召回结果 以减轻数据库负载
  • 测试召回质量 使用多样化的查询

在 AI 聊天机器人中构建记忆功能,可以将它们从无状态的工具转变为能与用户共同成长的持久型助手。从简单的对话历史开始,为关键事实添加长期存储,并随着应用的成熟逐步发展为完整的情景记忆。

最终成果是一个不仅会回应,还会记住的 AI。