Supermemory 学习教程

Supermemory 学习教程

从零开始掌握 Supermemory - AI 记忆引擎

教程日期:2026-03-27


目录

  1. 环境准备
  2. 快速开始
  3. 核心概念
  4. 记忆管理
  5. 用户画像
  6. 混合搜索
  7. 文件处理
  8. 连接器集成
  9. 框架集成
  10. MCP 集成
  11. 生产部署
  12. 最佳实践
  13. 常见问题

一、环境准备

1.1 前置知识

学习 Supermemory 前建议了解:

知识领域 重要程度 说明
TypeScript/JavaScript ⭐⭐⭐⭐ 主要开发语言
AI/LLM 基础 ⭐⭐⭐⭐ 理解大语言模型
API 调用 ⭐⭐⭐ REST API 使用
向量搜索概念 ⭐⭐⭐ 理解嵌入和相似度

1.2 安装 SDK

# Node.js / TypeScript
npm install supermemory

# 或使用 bun
bun add supermemory

# Python
pip install supermemory

1.3 获取 API Key

  1. 访问 https://console.supermemory.ai
  2. 注册/登录账户
  3. 在 Dashboard 创建 API Key
  4. API Key 格式: sm_...

1.4 环境变量配置

# .env
SUPERMEMORY_API_KEY=sm_your_api_key_here

1.5 验证安装

import Supermemory from "supermemory";

const client = new Supermemory();

// 测试连接
const profile = await client.profile({ containerTag: "test" });
console.log("Supermemory 连接成功!");

二、快速开始

2.1 存储第一条记忆

import Supermemory from "supermemory";

const client = new Supermemory();

// 存储用户偏好
await client.add({
  content: "用户喜欢使用 TypeScript 进行开发,偏好函数式编程风格",
  containerTag: "user_123",  // 用户唯一标识
});

console.log("记忆已存储!");

2.2 获取用户画像

// 获取用户画像 (~50ms)
const { profile } = await client.profile({
  containerTag: "user_123"
});

console.log("静态记忆:", profile.static);
// ["喜欢使用 TypeScript", "偏好函数式编程风格"]

console.log("动态记忆:", profile.dynamic);
// ["最近的上下文信息..."]

2.3 搜索记忆

// 搜索相关记忆
const results = await client.search.memories({
  q: "用户偏好什么编程语言?",
  containerTag: "user_123",
});

console.log(results);

2.4 完整示例

import Supermemory from "supermemory";

async function main() {
  const client = new Supermemory();

  // 1. 存储记忆
  await client.add({
    content: "用户是一名前端工程师,使用 React 和 TypeScript",
    containerTag: "user_abc",
  });

  // 2. 获取画像
  const { profile } = await client.profile({
    containerTag: "user_abc"
  });
  console.log("用户画像:", profile);

  // 3. 搜索
  const results = await client.search.memories({
    q: "技术栈",
    containerTag: "user_abc",
  });
  console.log("搜索结果:", results);
}

main();

三、核心概念

3.1 Memory vs RAG

┌─────────────────────────────────────────────────────────────────────┐
│                    Memory vs RAG 对比                                │
├─────────────────────────────────────────────────────────────────────┤
│                                                                     │
│   RAG (检索增强生成)                                                │
│   ┌─────────────────────────────────────────────────────────────┐  │
│   │ • 检索文档块                                                  │  │
│   │ • 无状态:所有人得到相同结果                                   │  │
│   │ • 不理解时间变化                                              │  │
│   │ • 例: 搜索 "API 文档" → 返回 API 文档                         │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
│   Memory (记忆)                                                     │
│   ┌─────────────────────────────────────────────────────────────┐  │
│   │ • 提取和追踪关于用户的事实                                    │  │
│   │ • 有状态:个性化结果                                          │  │
│   │ • 理解时间变化和矛盾                                          │  │
│   │ • 例: "我刚搬到旧金山" 取代 "我住在纽约"                       │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
│   Supermemory = RAG + Memory                                        │
│   ┌─────────────────────────────────────────────────────────────┐  │
│   │ 同时返回文档 (RAG) + 用户偏好 (Memory)                        │  │
│   └─────────────────────────────────────────────────────────────┘  │
│                                                                     │
└─────────────────────────────────────────────────────────────────────┘

3.2 Container Tag

Container Tag 是数据隔离的关键概念:

// 用户级别隔离
containerTag: "user_123"

// 项目级别隔离
containerTag: "project_abc"

// 会话级别隔离
containerTag: "session_xyz"

3.3 记忆类型

类型 描述 示例
Static 永久事实 偏好、姓名、职业
Dynamic 近期上下文 当前项目、最近兴趣

3.4 记忆生命周期

存储 → 提取 → 分类 → 检索 → 更新/遗忘
 │      │      │      │       │
 │      │      │      │       └─ 自动或手动删除过期信息
 │      │      │      └─ 搜索时检索相关记忆
 │      │      └─ 分类为 Static 或 Dynamic
 │      └─ 从内容中提取事实
 └─ 用户对话或文档

四、记忆管理

4.1 存储记忆

// 存储文本
await client.add({
  content: "用户的生日是 3 月 15 日",
  containerTag: "user_123",
});

// 存储 URL
await client.add({
  content: "https://docs.example.com/api-guide",
  containerTag: "user_123",
});

// 存储 HTML
await client.add({
  content: "<html><body>文档内容...</body></html>",
  containerTag: "user_123",
});

// 带元数据存储
await client.add({
  content: "用户偏好深色主题",
  containerTag: "user_123",
  metadata: {
    source: "settings",
    timestamp: new Date().toISOString(),
  },
});

4.2 批量存储

const memories = [
  "用户使用 VS Code 编辑器",
  "用户偏好 2 空格缩进",
  "用户使用 Git 进行版本控制",
];

await Promise.all(
  memories.map(content =>
    client.add({
      content,
      containerTag: "user_123",
    })
  )
);

4.3 遗忘记忆

// 遗忘过期信息
await client.memories.forget({
  containerTag: "user_123",
  memoryContent: "用户住在纽约",
  reason: "用户已搬到旧金山",
});

4.4 更新记忆

// 存储新信息会自动处理矛盾
await client.add({
  content: "用户现在住在旧金山",  // 自动取代 "住在纽约"
  containerTag: "user_123",
});

五、用户画像

5.1 获取画像

// 基本获取
const { profile } = await client.profile({
  containerTag: "user_123"
});

// 带查询的画像获取
const { profile, searchResults } = await client.profile({
  containerTag: "user_123",
  q: "编程偏好",
});

console.log("静态记忆:", profile.static);
console.log("动态记忆:", profile.dynamic);
console.log("搜索结果:", searchResults);

5.2 画像结构

interface ProfileResult {
  profile: {
    static: string[];   // 永久事实
    dynamic: string[];  // 近期上下文
  };
  searchResults?: SearchResult[];
}

5.3 画像更新

用户画像会在每次添加新记忆时自动更新:

// 添加新记忆
await client.add({
  content: "用户最近在学习 Rust",
  containerTag: "user_123",
});

// 动态记忆会自动更新
const { profile } = await client.profile({
  containerTag: "user_123"
});
// profile.dynamic 现在包含 "最近在学习 Rust"

六、混合搜索

6.1 基本搜索

// 搜索记忆
const results = await client.search.memories({
  q: "部署流程",
  containerTag: "user_123",
});

// 搜索文档
const docs = await client.search.documents({
  q: "API 文档",
  containerTag: "project_abc",
});

6.2 混合搜索

// RAG + Memory 组合搜索
const results = await client.search.memories({
  q: "如何配置项目?",
  containerTag: "user_123",
  searchMode: "hybrid",
});

// 返回:
// - 项目配置文档 (RAG)
// - 用户的配置偏好 (Memory)

6.3 搜索结果结构

interface SearchResult {
  id: string;
  content: string;
  score: number;
  metadata?: Record<string, any>;
  type: "memory" | "document";
}

6.4 搜索选项

const results = await client.search.memories({
  q: "React 组件",
  containerTag: "user_123",
  limit: 10,              // 结果数量
  threshold: 0.7,         // 相似度阈值
  metadata: {             // 元数据过滤
    type: "code",
  },
});

七、文件处理

7.1 上传文件

// 上传 PDF
const file = fs.readFileSync("./document.pdf");
await client.documents.uploadFile({
  file: new Blob([file], { type: "application/pdf" }),
  containerTags: ["project_abc"],
  metadata: {
    title: "项目需求文档",
    author: "张三",
  },
});

7.2 支持的文件类型

类型 处理方式
PDF 文本提取
图片 OCR 处理
视频 语音转录
代码 AST 感知分块
文本 直接处理

7.3 列出文档

const docs = await client.documents.list({
  containerTag: "project_abc",
  limit: 20,
  offset: 0,
});

for (const doc of docs.documents) {
  console.log(doc.id, doc.title, doc.createdAt);
}

7.4 删除文档

await client.documents.delete({
  documentId: "doc_123",
  containerTag: "project_abc",
});

八、连接器集成

8.1 支持的连接器

连接器 功能 同步方式
Google Drive 文档同步 实时 Webhook
Gmail 邮件处理 实时 Webhook
Notion 页面同步 实时 Webhook
OneDrive 文档同步 实时 Webhook
GitHub 仓库内容 实时 Webhook
Web Crawler URL 抓取 按需

8.2 连接 Google Drive

// 通过 Dashboard 连接
// 1. 访问 https://console.supermemory.ai
// 2. 进入 Connectors 页面
// 3. 点击 Google Drive 连接
// 4. 授权访问

// API 验证连接状态
const connections = await client.connections.list();
console.log(connections);

8.3 连接 GitHub

// 连接 GitHub 仓库
// 1. 在 Dashboard 选择 GitHub 连接器
// 2. 选择要同步的仓库
// 3. 配置同步频率

// 文件将自动同步并索引

8.4 URL 抓取

// 抓取网页内容
await client.add({
  content: "https://docs.example.com/guide",
  containerTag: "project_abc",
});

九、框架集成

9.1 Vercel AI SDK

import { withSupermemory } from "@supermemory/tools/ai-sdk";
import { openai } from "@ai-sdk/openai";

// 包装模型,自动添加记忆能力
const modelWithMemory = withSupermemory(
  openai("gpt-4o"),
  "user_123",
  {
    mode: "full",        // "profile" | "query" | "full"
    addMemory: "always"  // "always" | "never"
  }
);

// 使用
const result = await generateText({
  model: modelWithMemory,
  prompt: "你还记得我的编程偏好吗?",
});

模式说明

模式 描述
profile 获取用户画像,不过滤查询
query 基于用户消息搜索记忆
full 组合 profile + query 结果

9.2 OpenAI SDK

import { withSupermemory } from "@supermemory/tools/openai";

const openaiWithMemory = withSupermemory("user-123", {
  conversationId: "conversation-456",
  mode: "full",
  addMemory: "always"
});

const completion = await openaiWithMemory.chat.completions.create({
  model: "gpt-4o-mini",
  messages: [
    { role: "user", content: "我之前说过我喜欢什么语言?" }
  ],
});

console.log(completion.choices[0].message.content);

9.3 LangChain

import { SupermemoryMemory } from "@supermemory/tools/langchain";

const memory = new SupermemoryMemory({
  containerTag: "user_123",
});

const chain = new ConversationChain({
  llm: new ChatOpenAI(),
  memory: memory,
});

9.4 Mastra

import { Agent } from "@mastra/core/agent";
import { withSupermemory } from "@supermemory/tools/mastra";
import { openai } from "@ai-sdk/openai";

const agent = new Agent(
  withSupermemory(
    {
      id: "personal-assistant",
      name: "Personal Assistant",
      model: openai("gpt-4o"),
    },
    "user-123",
    {
      mode: "full",
      addMemory: "always"
    }
  )
);

十、MCP 集成

10.1 安装 MCP 服务器

# Claude Desktop
npx -y install-mcp@latest https://mcp.supermemory.ai/mcp \
  --client claude --oauth=yes

# Cursor IDE
npx -y install-mcp@latest https://mcp.supermemory.ai/mcp \
  --client cursor --oauth=yes

# VS Code
npx -y install-mcp@latest https://mcp.supermemory.ai/mcp \
  --client vscode --oauth=yes

10.2 MCP 工具

工具 功能
memory 保存或遗忘信息
recall 搜索记忆
whoAmI 获取当前用户信息
listProjects 列出可用项目
memory-graph 可视化记忆图谱

10.3 在 Claude 中使用

用户: 记住我是一名前端工程师,使用 React

Claude (使用 memory 工具): 好的,我已经记录了这条信息。

用户: 我之前说我是什么职业?

Claude (使用 recall 工具): 你说你是一名前端工程师,使用 React。

10.4 MCP 配置文件

// Claude Desktop 配置
{
  "mcpServers": {
    "supermemory": {
      "command": "npx",
      "args": ["-y", "supermemory-mcp"],
      "env": {
        "SUPERMEMORY_API_KEY": "sm_..."
      }
    }
  }
}

十一、生产部署

11.1 环境变量

# .env.production
SUPERMEMORY_API_KEY=sm_production_key
SUPERMEMORY_BASE_URL=https://api.supermemory.ai

11.2 错误处理

import Supermemory from "supermemory";

const client = new Supermemory();

async function safeAdd(content: string, containerTag: string) {
  try {
    await client.add({ content, containerTag });
  } catch (error) {
    if (error.status === 429) {
      // 速率限制
      console.log("速率限制,等待重试...");
      await new Promise(r => setTimeout(r, 1000));
      return safeAdd(content, containerTag);
    }
    throw error;
  }
}

11.3 批量操作

// 使用队列处理大量数据
import { Queue } from "bullmq";

const queue = new Queue("memory-import");

async function batchAdd(items: string[], containerTag: string) {
  const jobs = items.map(content => ({
    name: "add-memory",
    data: { content, containerTag }
  }));

  await queue.addBulk(jobs);
}

11.4 缓存策略

// 缓存用户画像
const profileCache = new Map<string, any>();

async function getCachedProfile(containerTag: string) {
  if (profileCache.has(containerTag)) {
    return profileCache.get(containerTag);
  }

  const { profile } = await client.profile({ containerTag });
  profileCache.set(containerTag, profile);

  // 5 分钟后过期
  setTimeout(() => profileCache.delete(containerTag), 5 * 60 * 1000);

  return profile;
}

十二、最佳实践

12.1 容器标签设计

// 好的做法:清晰的层级结构
const userTag = `user:${userId}`;
const projectTag = `project:${projectId}`;
const sessionTag = `session:${sessionId}`;

// 不好的做法:混乱的标签
const badTag = "user123_project456_session789";

12.2 记忆内容格式

// 好的做法:清晰、结构化的内容
await client.add({
  content: "用户偏好:编程语言 = TypeScript,编辑器 = VS Code,主题 = 深色",
  containerTag: "user_123",
});

// 不好的做法:模糊、不完整的内容
await client.add({
  content: "用户说了一些偏好",
  containerTag: "user_123",
});

12.3 定期清理

// 设置定期清理任务
import { CronJob } from "cron";

const cleanupJob = new CronJob("0 0 * * *", async () => {
  // 清理过期的动态记忆
  await cleanupOldMemories();
});

cleanupJob.start();

12.4 监控使用

// 记录 API 使用情况
import { metrics } from "./metrics";

async function monitoredAdd(params: AddParams) {
  const start = Date.now();
  try {
    const result = await client.add(params);
    metrics.increment("supermemory.add.success");
    return result;
  } catch (error) {
    metrics.increment("supermemory.add.error");
    throw error;
  } finally {
    metrics.timing("supermemory.add.latency", Date.now() - start);
  }
}

十三、常见问题

13.1 安装问题

Q: 安装失败,提示网络错误

# 使用国内镜像
npm install supermemory --registry=https://registry.npmmirror.com

Q: API Key 无效

# 检查 API Key 格式
# 正确格式: sm_...

# 检查环境变量
echo $SUPERMEMORY_API_KEY

13.2 使用问题

Q: 记忆没有被存储

// 确保使用正确的 containerTag
await client.add({
  content: "内容",
  containerTag: "user_123",  // 必须指定
});

// 检查返回结果
const result = await client.add({ ... });
console.log(result);

Q: 搜索结果不准确

// 尝试混合搜索模式
const results = await client.search.memories({
  q: "查询内容",
  containerTag: "user_123",
  searchMode: "hybrid",  // 使用混合模式
  threshold: 0.5,        // 降低阈值
});

Q: 画像返回空

// 检查 containerTag 是否正确
const { profile } = await client.profile({
  containerTag: "user_123"
});

// 确保之前有存储记忆
await client.add({
  content: "测试记忆",
  containerTag: "user_123",
});

13.3 性能问题

Q: 响应速度慢

// 使用缓存
const cachedProfile = await getCachedProfile("user_123");

// 减少不必要的搜索
// 只在需要时调用 profile

// 使用正确的搜索模式
// "profile" 比 "full" 更快

Q: 大量数据导入慢

// 使用批量操作
const promises = items.map(item =>
  client.add({
    content: item.content,
    containerTag: item.tag,
  })
);

await Promise.all(promises);

参考资源

官方资源

  • GitHub: https://github.com/supermemoryai/supermemory
  • 文档: https://supermemory.ai/docs
  • 快速开始: https://supermemory.ai/docs/quickstart
  • API 参考: https://supermemory.ai/docs/api

SDK

  • npm: https://www.npmjs.com/package/supermemory
  • PyPI: https://pypi.org/project/supermemory/

社区

  • Discord: https://supermemory.link/discord
  • Twitter: https://twitter.com/supermemory

Dashboard

  • Console: https://console.supermemory.ai
  • Web App: https://app.supermemory.ai

教程生成时间:2026-03-27