Supermemory SDK 实战指南:TypeScript 与 Python 全量 API 参考及 AI 框架集成

发布时间:2026/9/11 7:43:06
Supermemory SDK 实战指南:TypeScript 与 Python 全量 API 参考及 AI 框架集成 Supermemory SDK 实战指南TypeScript 与 Python 全量 API 参考及 AI 框架集成【免费下载链接】supermemoryMemory and context engine app that is extremely fast, scalable, and can be run fully locally. The Memory API for the AI era.项目地址: https://gitcode.com/GitHub_Trending/su/supermemory本篇技术指南以 Supermemory 官方 SDK 文档为主体完整覆盖 TypeScript 与 Python 两套 SDK 的安装、初始化、核心方法add / profile / search / documents与高级特性并深入讲解如何通过 Agent 工具、中间件与 Vercel AI SDK、LangChain、CrewAI 等主流框架集成持久化记忆。读完本文你将掌握为 AI 应用接入「写入记忆 → 检索上下文 → 个性化回复」完整闭环的全部 API 用法与工程最佳实践。Supermemory 是面向 AI Agent 的长期与短期记忆基础设施核心能力包括从对话/文档中抽取事实的 Memory API、静态事实 动态记忆组成的用户画像User Profiles、以及支持元数据过滤与混合检索的语义搜索RAG。其能力分层与整体概念可参考 skills/supermemory/SKILL.md 与 skills/supermemory/references/quickstart.md。安装 SDKSupermemory 原生提供 TypeScript 与 Python 两套 SDK另有一套面向 AI 框架的 Agent 工具包。TypeScript / JavaScriptnpm install supermemory # 或 yarn add supermemory # 或 pnpm add supermemory # Agent 工具与 Vercel AI SDK 中间件 npm install supermemory/tools其中supermemory/tools提供两大能力一组可供模型直接调用的记忆操作工具如searchMemories、addMemory以及可自动注入用户画像的withSupermemory中间件。仓库内 packages/tools/src/ai-sdk.ts 正是这些工具的实现其核心supermemoryTools()会返回 7 个工具。Pythonpip install supermemory # 需要 aiohttp 异步支持时 pip install supermemory[aiohttp] # OpenAI function tools 与中间件 pip install supermemory-openai-sdk其他 SDK 与集成更多 SDK、社区集成与框架专属指南可在官方文档站 discovery 页面找到。初始化客户端TypeScriptimport { Supermemory } from supermemory; const client new Supermemory({ apiKey: process.env.SUPERMEMORY_API_KEY, // 可选设置了环境变量后可省略 baseURL: https://api.supermemory.ai // 可选默认即此地址 });Pythonimport os from supermemory import Supermemory # 同步客户端 client Supermemory( api_keyos.environ[SUPERMEMORY_API_KEY], # 可选设置了环境变量后可省略 base_urlhttps://api.supermemory.ai # 可选默认即此地址 ) # 异步客户端 from supermemory import AsyncSupermemory async_client AsyncSupermemory( api_keyos.environ[SUPERMEMORY_API_KEY] )从源码结构看API 客户端基于https://api.supermemory.ai这一默认 baseURL 构造packages/lib/api.ts 中的 fetch 实例同样以https://api.supermemory.ai/v3为基准说明两套客户端与服务端端点一一对应。核心方法add()—— 存储记忆将内容提交给 Supermemory 进行处理与记忆抽取。注意add()不读取本地文件路径上传本地文件应使用client.documents.uploadFile({ file })TypeScript或client.documents.upload_file(file...)Pythonfilepath仅是元数据并非文件上传。TypeScriptawait client.add({ content: string, // 必填纯文本或 URL 字符串 containerTag?: string, // 可选隔离标识符用户/项目 ID entityContext?: string, // 可选引导记忆抽取的上下文 customId?: string, // 可选你的自定义标识符 metadata?: Recordstring, any // 可选自定义键值对 });Pythonclient.add( contentstr, # 必填纯文本或 URL 字符串 container_tagstr, # 可选隔离标识符 entity_contextstr, # 可选引导记忆抽取的上下文 custom_idstr, # 可选你的自定义标识符 metadatadict # 可选自定义键值对 )content支持的范围很广可以是任意纯文本也可以是网页、PDF、图片、视频等 URL系统会根据 URL 响应格式自动检测内容类型——这一点在 packages/validation/api.ts 的content字段 openapi 描述中有明确说明。另外metadata的键必须是字符串且大小写敏感值只能是字符串、数字或布尔值不允许嵌套对象。示例写入文本内容await client.add({ content: User prefers dark mode and TypeScript over JavaScript, containerTag: user_123, metadata: { source: preferences, timestamp: new Date().toISOString() } });示例写入 URL 交给后台处理await client.add({ content: https://example.com/blog/article, containerTag: knowledge_base, entityContext: technical documentation, metadata: { type: documentation, category: api } });示例携带自定义 IDawait client.add({ content: Project requirements document..., containerTag: project_abc, customId: requirements_v1, metadata: { version: 1.0, author: johnexample.com } });customId可以来自你数据库中的主键用于唯一标识这条记忆也便于后续按 ID 精确引用或实现幂等写入。profile()—— 获取用户上下文获取个性化上下文包含静态画像数据与相关的动态记忆。TypeScriptconst response await client.profile({ containerTag: string, // 必填用户/项目标识符 q?: string, // 可选查询词传入后返回搜索结果 threshold?: number // 可选相关度阈值0-1默认 0.5 }); // 返回结构 // { // profile: { // static: string[], // 长期稳定的事实 // dynamic: string[] // 动态记忆近期上下文 // }, // searchResults?: { // 仅当传入 q 参数时返回 // results: Array{ // 搜索结果 // id: string, // memory?: string, // similarity: number, // metadata: object | null // }, // total: number, // timing: number // } // }Pythonresponse client.profile( container_tagstr, # 必填用户/项目标识符 qstr, # 可选查询词传入后返回搜索结果 thresholdfloat # 可选相关度阈值0-1默认 0.5 ) # 返回 ProfileResponse 模型 # response.profile.static / response.profile.dynamic # response.search_results.results # 仅当传入 q 时存在从底层实现看profile()对应/v4/profile端点当传入q时请求体为{ q, containerTag, include: [static, dynamic] }否则只传{ containerTag, include: [static, dynamic] }实现见 packages/tools/src/shared/memory-client.ts。这也解释了为什么只有传入q时才会附带searchResults。示例获取用户画像const response await client.profile({ containerTag: user_123, q: What are the users preferences and settings? }); console.log(response.profile.static); // [User John Doe, Prefers dark mode, ...] console.log(response.profile.dynamic); // [Recently mentioned..., Last conversation...] console.log(response.searchResults); // 查询对应的搜索结果传入 q 时才有示例不检索、只取已存记忆const response await client.profile({ containerTag: user_456 // 不传 q 只返回 profile.static 与 profile.dynamic }); console.log(response.profile.static); // 所有静态事实 console.log(response.profile.dynamic); // 近期动态记忆 // response.searchResults 为 undefinedsearch()—— 语义搜索跨记忆执行语义检索。注意版本差异client.search()是当前 TypeScript v4 调用方式Python 对应client.search.memories()同样走 v4 端点而 TypeScript 的client.search.documents()是旧的 v3 文档响应接口。TypeScriptconst response await client.search({ q: string, // 必填查询词 containerTag?: string, // 可选按容器标签过滤 limit?: number, // 可选最大结果数默认 10最大 100 threshold?: number, // 可选相似度阈值0-1默认 0.6 searchMode?: memories | hybrid | documents, // 可选memories默认、hybrid记忆文档块、documents仅块 filters?: FilterObject // 可选高级过滤 }); // 返回结构 // { // results: Array{ // id: string, // memory?: string, // 记忆内容记忆类结果 // chunk?: string, // 块内容hybrid 模式下的文档块 // metadata: object | null, // updatedAt: string, // similarity: number, // version?: number | null // }, // total: number, // timing: number // 搜索耗时毫秒 // }Pythonresponse client.search.memories( qstr, # 必填查询词 container_tagstr, # 可选按容器标签过滤 thresholdfloat, # 可选相似度阈值0-1默认 0.6 limitint, # 可选最大结果数默认 10最大 100 search_modestr, # 可选memories默认、hybrid 或 documents filtersdict # 可选高级过滤 ) # 返回 SearchMemoriesResponse 模型 # response.results, response.total, response.timingv4 搜索的默认阈值与上限在服务端 schema 中有明确约束threshold默认0.6、取值范围[0, 1]limit必须在1~100之间默认 10见 packages/validation/api.ts 中的Searchv4RequestSchema。同时v4 的搜索结果还支持context字段携带updates / extends / derives三种关系的父/子记忆packages/validation/api.ts这印证了记忆以知识图谱关系组织的设计。示例基础语义搜索const response await client.search({ q: How do I authenticate users?, containerTag: documentation, limit: 10 }); response.results.forEach(result { console.log(Similarity: ${result.similarity}); console.log(Content: ${result.memory ?? result.chunk}); });示例RAG 场景的混合搜索记忆 源文档块const response await client.search({ q: authentication methods, containerTag: docs, searchMode: hybrid, // 同时返回抽取的记忆与文档块 threshold: 0.3, limit: 10 });示例带元数据过滤的搜索const response await client.search({ q: authentication methods, containerTag: docs, threshold: 0.3, filters: { AND: [ { key: type, value: tutorial }, { key: category, value: security } ] } });示例在指定文件路径内搜索const response await client.search({ q: rate limiting configuration, containerTag: specific_project, filepath: /docs/api.md });过滤器的完整结构AND/OR组合、negate取反、numericOperator数值比较等在 packages/validation/api.ts 的SearchFiltersSchema中亦有体现。documents.list()—— 列出文档获取已存储的源文档支持过滤与分页。TypeScriptconst docs await client.documents.list({ containerTags?: string[], // 可选按一个或多个容器过滤 limit?: number, // 可选每页条数默认 10 page?: number, // 可选页码从 1 开始默认 1 includeContent?: boolean, // 可选是否包含源内容默认 false sort?: createdAt | updatedAt, order?: asc | desc }); // 返回结构 // { // memories: Array{ // id: string, // status: string, // metadata: object, // createdAt: string, // content?: string // 仅当 includeContenttrue // }, // pagination: { currentPage, totalItems, totalPages, limit? } // }Pythondocs client.documents.list( container_tags[str], # 可选按一个或多个容器过滤 limitint, # 可选每页条数默认 10 pageint, # 可选页码从 1 开始默认 1 include_contentbool # 可选是否包含源内容默认 False )服务端的列表接口同样支持sortcreatedAt/updatedAt与orderasc/desc参数默认按createdAt降序见 packages/validation/api.ts。示例列出某用户的全部文档const docs await client.documents.list({ containerTags: [user_123], limit: 50 }); docs.memories.forEach(doc { console.log(${doc.id}: ${doc.status}); });示例分页遍历const page1 await client.documents.list({ limit: 20, page: 1 }); const page2 await client.documents.list({ limit: 20, page: 2 });documents.delete()—— 删除文档永久删除某个源文档从该源抽取出的记忆会被「软遗忘」不再出现在画像或搜索结果中。TypeScriptawait client.documents.delete(documentId);Pythonclient.documents.delete(document_id)示例await client.documents.delete(doc_abc123);这里需要区分两种删除语义详见 skills/supermemory/SKILL.md 中的 Removing information 章节memoryForget软删除仅让某条抽取出的画像事实不再出现在 profile / search 中源文档保留删除粒度是记忆 ID 或精确内容匹配。documents.delete()硬删除永久移除底层源文档同时软遗忘其抽取出的记忆删除粒度是文档 ID来自documents.list()。切勿混淆 IDmemoryId≠documentId。混合检索结果中只有包含memory的条目才有可遗忘的记忆 ID包含chunk的条目是块 IDstatic/dynamic 画像条目是纯文本需要借助带查询的 profile 搜索结果来获得 ID。高级特性元数据过滤写入时附带丰富元数据检索时即可做精确过滤await client.add({ content: Product review of iPhone 15, containerTag: reviews, metadata: { product: iPhone 15, rating: 4.5, verified: true, tags: [smartphone, apple, 2024] } }); // 带元数据过滤的搜索 const results await client.search({ q: phone reviews, containerTag: reviews, filters: { AND: [ { key: rating, value: 4.0, filterType: numeric, numericOperator: }, { key: verified, value: true }, { key: tags, value: apple, filterType: array_contains } ] } });元数据过滤支持字符串精确匹配、numeric数值比较配合numericOperator、array_contains数组包含等过滤类型并且可以用negate取反packages/validation/api.ts。用实体上下文Entity Context提升抽取质量提供上下文可以引导 Supermemory 理解「该抽取什么、优先什么」await client.add({ content: User mentioned preferring React over Vue, containerTag: user_123, entityContext: This is a conversation about frontend framework preferences });在服务端 schema 中entityContext的上限为 1500 字符packages/validation/api.ts用于指导该容器标签下的记忆抽取方向。容器标签Container Tag模式容器标签是隔离记忆的标识符相同containerTag的记忆被归组可被独立检索。典型用法包括用户 ID、项目 ID、会话 ID、组织 ID 等。以下是几种常用模式按用户隔离const userId user_123; await client.add({ content: ..., containerTag: userId }); const context await client.profile({ containerTag: userId, q: ... });多租户应用const orgTag org_${organizationId}; const userTag org_${organizationId}_user_${userId}; // 组织级共享知识 await client.add({ content: ..., containerTag: orgTag }); // 组织内的用户专属 await client.add({ content: ..., containerTag: userTag });按项目组织const projectTag project_${projectId}; await client.add({ content: Project requirements..., containerTag: projectTag, metadata: { type: requirements, version: 1.0 } });与 AI 框架集成Vercel AI SDKAgent 工具supermemory/tools/ai-sdk/supermemory/ai-sdk对于需要模型显式决定何时调用记忆操作的场景直接使用 7 个工具而非手写 SDK 调用import { generateText, stepCountIs } from ai import { openai } from ai-sdk/openai import { supermemoryTools } from supermemory/tools/ai-sdk const allTools supermemoryTools(process.env.SUPERMEMORY_API_KEY!, { containerTags: [user_123], }) // 只挑选允许 Agent 调用的操作 const tools { searchMemories: allTools.searchMemories, addMemory: allTools.addMemory, getProfile: allTools.getProfile, documentList: allTools.documentList, documentAdd: allTools.documentAdd, } const { text } await generateText({ model: openai(gpt-4o), tools, stopWhen: stepCountIs(5), prompt: What do you remember about my coffee preferences?, })完整的 7 个工具为searchMemories、addMemory、getProfile、documentList、documentAdd、documentDelete、memoryForget。各工具职责与选用时机可参考下表工具使用时机searchMemories回答前主动做混合检索记忆 源文档块不限于用户明确说「搜索」时addMemory存储用户陈述的单条可泛化事实getProfile加载静态 动态画像传query可将搜索结果聚焦到当前话题documentList浏览已存源文档会话、URL、文件返回文档 IDdocumentAdd摄入原始内容文本、对话记录、URL、笔记走后台处理自动抽取记忆适合大批量内容而非单条事实documentDelete永久删除源文档并软遗忘其记忆memoryForget按记忆 ID 或精确内容软删除某条已学到的画像事实searchMemories用于针对性混合召回getProfile用于获取宽泛的静态/动态用户上下文documentList、documentAdd、documentDelete负责源文档生命周期管理。supermemoryTools()的实现细节见 packages/tools/src/ai-sdk.ts每个工具内部都封装了对应的 SDK 调用如searchMemories实际以searchMode: hybrid调用client.search()见 packages/tools/src/ai-sdk.ts。多容器标签时的行为如果配置了多个容器标签searchMemories、getProfile、memoryForget会使用第一个标签因为 v4 记忆操作是单空间single-space的而 add、list、delete 操作在支持的情况下使用更广的配置范围。安全提示supermemoryTools()聚合结果包含破坏性操作documentDelete、memoryForget。只应暴露 Agent 被授权执行的操作删除类工具务必仅在获得授权并要求用户确认时开放。stopWhen允许模型消费工具结果后产出最终回答而不是在第一次工具调用后就立即停止。中间件withSupermemory不需要工具调用、希望「自动注入画像 自动保存会话」时使用withSupermemoryimport { withSupermemory } from supermemory/tools/ai-sdk import { openai } from ai-sdk/openai const modelWithMemory withSupermemory(openai(gpt-4o), { containerTag: user_123, customId: conversation_456, })从源码结构看该中间件内部复用supermemoryProfileSearch获取画像与检索结果并支持通过 prompt 模板将记忆格式化为 Markdown 注入系统提示词packages/tools/src/shared/memory-client.ts 的buildMemoriesText负责拉取 → 去重 → 格式化整条链路。手动 SDK 集成import { Supermemory } from supermemory; import { openai } from ai-sdk/openai; import { generateText } from ai; const memory new Supermemory(); async function chat(userId: string, message: string) { // 1. 获取上下文 const context await memory.profile({ containerTag: userId, q: message }); const profileText [ ...context.profile.static, ...context.profile.dynamic, ].join(\n); const searchText JSON.stringify(context.searchResults?.results ?? []); // 2. 携带上下文生成回复 const { text } await generateText({ model: openai(gpt-4), system: User Profile:\n${profileText}\n\nRelevant Context:\n${searchText}, prompt: message }); // 3. 存储会话 await memory.add({ content: User: ${message}\nAssistant: ${text}, containerTag: userId }); return text; }这个「取上下文 → 注入提示 → 存回对话」三步模式是整个 SDK 集成的通用工作流skills/supermemory/references/quickstart.md 的 Core Workflow Pattern 一节有相同阐述。LangChainimport { Supermemory } from supermemory; import { ChatOpenAI } from langchain/openai; import { HumanMessage, SystemMessage } from langchain/core/messages; const memory new Supermemory(); const llm new ChatOpenAI({ model: gpt-4 }); async function chatWithMemory(userId: string, userMessage: string) { // 检索上下文 const context await memory.profile({ containerTag: userId, q: userMessage }); // 构造带上下文的消息 const messages [ new SystemMessage(Context: ${JSON.stringify(context)}), new HumanMessage(userMessage) ]; const response await llm.invoke(messages); // 存储交互 await memory.add({ content: ${userMessage}\n${response.content}, containerTag: userId }); return response.content; }CrewAIfrom supermemory import Supermemory from crewai import Agent, Task, Crew memory Supermemory() def create_memory_enhanced_agent(user_id: str): # 获取用户上下文 context memory.profile( container_taguser_id, quser preferences and history ) profile_text \n.join( (context.profile.static or []) (context.profile.dynamic or []) ) search_text \n.join( result.memory for result in (context.search_results.results if context.search_results else []) if result.memory ) agent Agent( rolePersonal Assistant, goalHelp the user with personalized assistance, backstoryfUser Context:\n{profile_text}\n\nRelevant memories:\n{search_text}, verboseTrue ) return agent面向 OpenAI 的 Python 工具除 CrewAI 外supermemory-openai-sdk还提供与 OpenAI function calling 兼容的 7 个工具定义。典型用法是构造SupermemoryTools后通过get_tool_definitions()拿到全部定义再在传给模型前过滤掉破坏性工具import os from supermemory_openai import SupermemoryTools tools SupermemoryTools( os.environ[SUPERMEMORY_API_KEY], {container_tags: [user_123]}, ) definitions tools.get_tool_definitions() # 全部 7 个工具如果模型不应调用document_delete或memory_forget务必先过滤definitions再传给模型。TypeScript 侧对应的 7 个 OpenAI 函数 schema含各参数类型、默认值与必填约束实现在 packages/tools/src/openai/tools.ts。最佳实践1. 保持容器标签一致始终使用同一套容器标签格式避免同一实体出现多种写法// 好统一格式 const tag user_${userId}; // 避免不一致 // 有时用 user_123 // 有时用 123标签不一致会导致同一用户的记忆被分散到多个空间画像与检索都会失真。2. 富元数据写入时添加元数据便于后续过滤与组织await client.add({ content: ..., containerTag: user_123, metadata: { source: chat, timestamp: new Date().toISOString(), conversationId: conv_456, topics: [programming, typescript] } });3. 有意义的自定义 ID利用customId实现幂等写入与精确引用await client.add({ content: ..., customId: feedback_${userId}_${Date.now()}, containerTag: feedback });4. 合理的阈值设置从 v4 搜索默认值0.6起步根据检索质量再调整0.3-0.5召回更广适合探索发现场景0.5-0.7精度与召回均衡0.6为默认值0.7-1.0高精度结果更少但更相关需要提醒的是profile()的默认阈值是0.5而search()的默认阈值是0.6两者不同按需分别调节。5. 错误处理始终优雅处理异常try { await client.add({ content: ..., containerTag: user_123 }); } catch (error) { if (error.status 401) { console.error(Invalid API key); } else if (error.status 429) { console.error(Rate limit exceeded); } else { console.error(Failed to add memory:, error.message); } }常见状态码包括401API Key 无效与429触发限流搜索无结果时优先排查降低threshold、确认containerTag与写入时一致、等待内容处理完成大 PDF 约 1-2 分钟视频约 5-10 分钟。命名约定速查概念TypeScriptcamelCasePythonsnake_case容器标签containerTagcontainer_tag实体上下文entityContextentity_context自定义 IDcustomIdcustom_id阈值thresholdthreshold查询词qq性能建议批量操作需要连续写入多个文档时可快速连续调用add()或使用服务端批处理端点/documents/batch单次支持 1~600 条见 packages/lib/api.ts。异步优先始终使用 async 操作避免阻塞主流程Python 侧有aiohttp扩展可安装AsyncSupermemory。分页文档列表较大时用limit与从 1 开始的page参数分页拉取。缓存短时间内多次调用时可对profile()结果做短期缓存工具层已内置缓存与去重逻辑见 packages/tools/src/shared/。场景选型总结聊天机器人使用中间件withSupermemory/with_supermemory自动注入上下文或把工具交给模型实现显式记忆控制。知识库RAG用add()/documentAdd摄入文本或 URL本地文件走 SDK 的文件上传方法再用searchMemories的 hybrid 模式做检索。任务型助手组合getProfile与searchMemories实现上下文感知的任务完成。客户支持索引文档与工单按客户维度检索相关知识。信息移除纠正单个错误事实用memoryForget删除整段对话或文件用documentDelete用户意图模糊时先searchMemories拿到memoryId再memoryForget。完整的端点级参考、知识图谱架构说明与更多实战用例可继续阅读本仓库下的 skills/supermemory/references/api-reference.md、skills/supermemory/references/architecture.md 与 skills/supermemory/references/use-cases.md。【免费下载链接】supermemoryMemory and context engine app that is extremely fast, scalable, and can be run fully locally. The Memory API for the AI era.项目地址: https://gitcode.com/GitHub_Trending/su/supermemory创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考