
Mem0 Platform 快速上手用 mem0ai Python/TypeScript 客户端构建 AI Agent 记忆层【免费下载链接】embedchainThe Memory Layer for AI Agents - Drop-in memory infrastructure for AI agents and apps. Context that persists. Built for production.项目地址: https://gitcode.com/GitHub_Trending/em/embedchain本文基于仓库中 Mem0 Platform Quickstart 文档 展开覆盖从安装 SDK、配置 API Key到 Python 同步/异步客户端、TypeScript 客户端、cURL 直连 REST API 的完整快速上手路径。读完本篇你可以直接复制可运行的代码完成「添加记忆 → 检索记忆」的核心闭环并借助 mem0/client/main.py 等源码理解客户端的鉴权、参数校验与接口调用细节。一、文档定位与前置条件Quickstart 文档的核心目标是2 分钟内跑通 Mem0 Platform无需部署任何基础设施只需一个 API Key。它同时提供三种接入方式Python SDK、TypeScript/JavaScript SDK 和原生 cURL。环境要求Python 3.10 或 Node.js 18一个 Mem0 Platform API Key在 Mem0 Platform 控制台的 API Keys 页面创建Key 以m0-开头。这些前置条件与仓库声明一致pyproject.toml 中包名为mem0ai即pip install mem0ai的实际来源requires-python 3.10,4.0mem0 技能定义 的 compatibility 字段也明确「Requires Python 3.10 or Node.js 18, pip install mem0ai or npm install mem0ai, MEM0_API_KEY env var (Platform), and internet access to api.mem0.ai. Uses Mem0 v3 API」。两种接入形态的边界需要注意本仓库包含两种形态Platform托管服务本篇 Quickstart 的主题通过MemoryClient调用远端 APIAPI Key 以m0-开头OSS自托管直接实例化 mem0/memory/main.py 中的Memory类本地配置 LLM/Embedding/向量库。mem0/init.py 同时导出了MemoryClient/AsyncMemoryClientPlatform 客户端与Memory/AsyncMemoryOSS 客户端二者入口不同不要混用。二、Python 客户端安装与同步调用安装与鉴权配置pip install mem0ai export MEM0_API_KEYm0-your-api-key添加记忆与检索记忆from mem0 import MemoryClient client MemoryClient(api_keyyour-api-key) # Add a memory messages [ {role: user, content: Im a vegetarian and allergic to nuts.}, {role: assistant, content: Got it! Ill remember your dietary preferences.} ] client.add(messages, user_iduser123) # Search memories results client.search(What are my dietary restrictions?, filters{user_id: user123}) print(results)客户端初始化做了什么从源码 mem0/client/main.py 可以看到MemoryClient.__init__的关键行为API Key 回退机制self.api_key api_key or os.getenv(MEM0_API_KEY)L116即构造函数参数优先其次读取环境变量两者都缺省时抛出ValueError默认 Hosthost or https://api.mem0.aiL117这也是 Quickstart 中 cURL 示例使用的服务地址鉴权头每次请求携带Authorization: Token api_key与Mem0-User-IDAPI Key 的 MD5 摘要L126-L145HTTP 超时设置为 300 秒Key 校验构造完成后立即调用GET /v1/ping/验证 Key 有效性并从中解析出org_id与project_idL160-L181这些 ID 随后被注入请求参数用于组织/项目级别的隔离与配额管理。add()三种输入形态都会被归一化client.add()并不只接受消息列表。mem0/client/main.py 中str输入会被包装成[{role: user, content: ...}]dict输入会被包装成单条消息列表其他类型直接抛ValueError归一化后 POST 到POST /v3/memories/add/即 Quickstart cURL 示例中的添加记忆端点。平台侧负责从对话中抽取事实性记忆因此传入的是「对话消息」而非记忆文本本身。search()实体参数必须放进 filters这是 Quickstart 代码中最容易被忽略的一条约束client.search(query, filters{user_id: user123})。源码中定义了ENTITY_PARAMS frozenset({user_id, agent_id, app_id, run_id})L40search()与get_all()会检查并拒绝顶层传入这些参数L316-L322直接抛出ValueError提示改用filters{user_id: ...}。对应的行为测试见 tests/test_client.py 中的test_search_rejects_user_id_kwarg、test_search_rejects_agent_id_kwarg等用例。此外search()会对 query 做非空校验与首尾空白裁剪_validate_and_trim_search_queryL43-L49空字符串或纯空白会直接抛错请求体最终 POST 到/v3/memories/search/L329。方法可选参数类型化 options除**kwargs外各方法还支持 Pydantic 类型化 options提供 IDE 补全与运行时校验。核心字段可从 mem0/client/types.py 查到add 的AddMemoryOptionsL15-L38参数类型说明filtersdict实体 ID 过滤如{user_id: ...}metadatadict附加元数据inferbool是否从输入中抽取记忆custom_categorieslist自定义记忆分类custom_instructionsstr事实抽取的自定义指令timestampint记忆时间戳Unixexpiration_datestr过期日期YYYY-MM-DDsearch 的SearchMemoryOptionsL41-L62参数类型说明filtersdict检索过滤如{user_id: ...}top_kint返回结果数量rerankbool是否对结果重排thresholdfloat最小相似度分数阈值categorieslist按分类过滤show_expiredbool是否包含过期记忆latest_onlybool是否只返回最新版本记忆get_all()的GetAllMemoryOptions则支持page/page_size分页以及start_date/end_date时间范围过滤L65-L85page/page_size会落到 URL query 参数而非 JSON body 中这一行为在 tests/test_client.py 的test_get_all_page_size_alone_lands_in_query_params等用例中有专门验证。异步客户端在async/await环境FastAPI、LangChain 异步流等中使用AsyncMemoryClient其全部方法均为协程底层使用httpx.AsyncClientfrom mem0 import AsyncMemoryClient client AsyncMemoryClient(api_keyyour-api-key) await client.add(messages, user_iduser123) results await client.search(query, filters{user_id: user123})AsyncMemoryClient 与同步版本参数签名一致api_key/host/client构造时同样会完成 Key 校验分页参数行为也与同步版对齐见 tests/test_client.py 中的test_async_get_all_page_*系列用例。三、TypeScript / JavaScript 客户端安装与基础用法npm install mem0ai export MEM0_API_KEYm0-your-api-keyimport MemoryClient from mem0ai; const client new MemoryClient({ apiKey: your-api-key }); // Add a memory const messages [ {role: user, content: Im a vegetarian and allergic to nuts.}, {role: assistant, content: Got it! Ill remember your dietary preferences.} ]; await client.add(messages, { userId: user123 }); // Search memories const results await client.search(What are my dietary restrictions?, { filters: { user_id: user123 } }); console.log(results);源码实现要点TS 客户端实现位于 mem0-ts/src/client/mem0.tsMemoryClient为默认导出构造函数接收{ apiKey, host?, identityCacheMax? }host默认同样是https://api.mem0.aiHTTP 层基于 axios超时 60 秒L121-L146鉴权头与 Python 版一致Authorization: Token apiKey与 Python 版相同的「实体参数必须走 filters」约束同样存在rejectTopLevelEntityParams()会检查user_id/userIdsnake_case 与 camelCase 双写法L40-L68并在getAllL397与searchL425中被调用违规时抛出明确指向filters的错误信息。这说明两个 SDK 在参数契约上保持了对称add支持顶层/选项中的实体参数而search/getAll强制使用filters。四、cURL 直连 REST API不需要装 SDK 时可以直接调用 REST 端点。以下示例完整继承自 Quickstart 文档export MEM0_API_KEYm0-your-api-key # Add memory curl -X POST https://api.mem0.ai/v3/memories/add/ \ -H Authorization: Token $MEM0_API_KEY \ -H Content-Type: application/json \ -d { messages: [ {role: user, content: I am a vegetarian and allergic to nuts.}, {role: assistant, content: Got it! I will remember your dietary preferences.} ], user_id: user123 } # Search memories curl -X POST https://api.mem0.ai/v3/memories/search/ \ -H Authorization: Token $MEM0_API_KEY \ -H Content-Type: application/json \ -d { query: What are my dietary restrictions?, filters: {user_id: user123} }两个端点与 SDK 源码中的路径一一对应/v3/memories/add/mem0/client/main.py L217和/v3/memories/search/L329鉴权方式均为Token型 Bearer 头。v3 接口将实体参数user_id等放入filters的结构在 search 请求体中体现得最明显。五、响应结构与示例Quickstart 给出的搜索响应示例如下{ results: [ { id: 14e1b28a-2014-40ad-ac42-69c9ef42193d, memory: Allergic to nuts, user_id: user123, categories: [health], created_at: 2025-10-22T04:40:22.864647-07:00, score: 0.30 } ] }字段解读id记忆的唯一标识UUID后续get/update/delete/history都依赖它memory平台从对话中抽取出的事实陈述本例中从两轮对话抽取出「对坚果过敏」这一条user_id记忆归属的实体检索时通过filters隔离不同用户的记忆categories自动/自定义分类可用于SearchMemoryOptions.categories过滤score相似度得分可结合threshold参数做质量过滤created_at记忆创建时间ISO 8601 带时区。SDK 返回的即为此结构的 Python dict / JS 对象client.search(...)返回{results: [...]}遍历时使用results.get(results, [])即可。六、易错点与验证依据汇总易错点行为依据search()顶层传user_id等实体参数抛ValueError要求改用filtersmem0/client/main.py L316-L322、tests/test_client.pysearch()传入空 query 或纯空白抛ValueError正常 query 会先做 stripmem0/client/main.py L43-L49未提供 API Key 且无环境变量构造即抛ValueError(Mem0 API Key not provided...)mem0/client/main.py L122-L123add()传入非法类型抛ValueError仅接受 str/dict/list[dict]mem0/client/main.py L208-L213TS 端顶层传userId给search/getAll抛错提示使用filtersmem0-ts/src/client/mem0.ts L40-L68七、后续路径Quickstart 文档末尾指向了三份进阶参考已转换为仓库根相对路径SDK GuidePython 与 TypeScript 的完整方法清单API ReferenceREST 端点与记忆对象结构Integration PatternsLangChain、CrewAI、Vercel AI 等框架集成模式。配合源码文件 mem0/client/main.py、mem0/client/types.py、mem0-ts/src/client/mem0.ts 与测试 tests/test_client.py可以进一步核对任意方法的参数契约与请求路径。【免费下载链接】embedchainThe Memory Layer for AI Agents - Drop-in memory infrastructure for AI agents and apps. Context that persists. Built for production.项目地址: https://gitcode.com/GitHub_Trending/em/embedchain创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考