第 1 章 环境准备与首次跑通


文档摘要

第 1 章 环境准备与首次跑通 目标:5 分钟内完成安装,写入第一条记忆并成功检索。能跑通比读十页文档更重要。 1.1 环境要求 项目 | 要求 | 说明 Python | ≥ 3.13 | memU 使用新版 typing 与 asyncio 特性 API Key | OpenAI 或兼容端点 | 提取、摘要、embedding 均依赖 LLM 操作系统 | Windows / macOS / Linux | 本教程示例以通用 Python 为准 可选 | Docker | 运行 PostgreSQL + pgvector(见第 8 章) 检查 Python 版本: 1.

第 1 章 环境准备与首次跑通

目标:5 分钟内完成安装,写入第一条记忆并成功检索。能跑通比读十页文档更重要。

1.1 环境要求

项目 要求 说明
Python ≥ 3.13 memU 使用新版 typing 与 asyncio 特性
API Key OpenAI 或兼容端点 提取、摘要、embedding 均依赖 LLM
操作系统 Windows / macOS / Linux 本教程示例以通用 Python 为准
可选 Docker 运行 PostgreSQL + pgvector(见第 8 章)

检查 Python 版本:

python --version # 应输出 Python 3.13.x 或更高

1.2 安装 memU

方式一:PyPI 安装(推荐入门)

pip install memu-py

如需 PostgreSQL 支持:

pip install "memu-py[postgres]"

如需 LangGraph 集成:

pip install "memu-py[langgraph]"

方式二:从源码安装(进阶开发)

克隆官方仓库后,在项目根目录执行 uv syncmake install。适合需要修改 Pipeline 或贡献代码的开发者,详见第 10 章。

1.3 配置 API Key

memU 默认走 OpenAI 兼容接口。在终端设置环境变量:

# Linux / macOS export OPENAI_API_KEY=sk-your-key-here # Windows PowerShell $env:OPENAI_API_KEY="sk-your-key-here"

若使用国内模型(通义千问等),不必设置 OPENAI_API_KEY,而是在初始化时通过 llm_profiles 指定 base_urlapi_key,详见第 8 章。

1.4 最小可运行示例

下面是一个完整的「写入 + 检索」闭环。代码为概念性片段,不依赖特定本地路径。

import asyncio from memu import MemoryService # 一段模拟对话 JSON 的内容(实际使用时可以是本地路径或 HTTP URL) CONVERSATION = """ [ {"role": "user", "content": "我叫小明,喜欢简洁的技术文档,讨厌冗长的铺垫。"}, {"role": "assistant", "content": "好的,我会尽量简洁。"}, {"role": "user", "content": "我最近在学智能体记忆,用 memU 做实验。"} ] """ async def main(): # 1. 初始化服务(内存存储,适合本地实验) service = MemoryService( llm_profiles={ "default": { "api_key": "your_openai_api_key", "chat_model": "gpt-4o-mini", }, }, database_config={ "metadata_store": {"provider": "inmemory"}, }, retrieve_config={"method": "rag"}, ) # 2. 写入记忆 — 将对话作为 conversation 模态摄入 # resource_url 可以是本地路径、HTTP URL 或 blob 存储地址 result = await service.memorize( resource_url="https://example.com/demo-conversation.json", modality="conversation", user={"user_id": "xiaoming"}, ) print("=== memorize 返回 ===") print(f"来源 ID: {result['resource']['id']}") print(f"提取记忆条数: {len(result['items'])}") for item in result["items"]: print(f" [{item['memory_type']}] {item['summary'][:80]}") # 3. 检索记忆 context = await service.retrieve( queries=[{ "role": "user", "content": {"text": "这个用户有什么偏好?"}, }], where={"user_id": "xiaoming"}, ) print("\n=== retrieve 返回 ===") for item in context.get("items", []): print(f" → {item['summary']}") if __name__ == "__main__": asyncio.run(main())

预期现象

  • memorize 返回的 items 中应出现 memory_type=profile 的条目(如「用户喜欢简洁文档」)
  • retrieve 能召回与「偏好」相关的记忆项

1.5 理解返回结构(初识)

memorize() 成功后返回字典,核心字段:

{ "resource": { "id": "...", "modality": "conversation", "caption": "..." }, "items": [ { "id": "...", "memory_type": "profile", "summary": "..." }, { "id": "...", "memory_type": "event", "summary": "..." }, ], "categories": [ { "id": "...", "name": "user_preferences", "summary": "..." }, ], "relations": [ { "item_id": "...", "category_id": "..." }, ], }

retrieve() 返回字典,核心字段:

{ "needs_retrieval": True, "original_query": "...", "rewritten_query": "...", "categories": [...], "items": [...], "resources": [...], }

完整字段说明见第 3 章与附录 B。

1.6 云端快速体验(可选)

若不想自托管,可使用 memU Cloud

项目
Base URL https://api.memu.so
认证 Authorization: Bearer YOUR_API_KEY
写入 POST /api/v3/memory/memorize
状态 GET /api/v3/memory/memorize/status/{task_id}
检索 POST /api/v3/memory/retrieve

云端 API 为异步任务模式:提交 memorize 后轮询 status,完成后调用 retrieve。详细对接见第 9 章。

试用入口可在 memU 官方站点(memu.so)申请,具体以官方公告为准。

1.7 常见安装问题

现象 原因 处理
Python version 报错 版本低于 3.13 升级 Python 或使用 pyenv
No module named memu 包装名是 memu-py pip install memu-py
API 401 Key 无效或未设置 检查环境变量与 Profile 配置
asyncio 相关警告 在非 async 上下文调用 asyncio.run() 包裹

更多排查见附录 C。

1.8 本章小结

  • 安装:pip install memu-py,Python ≥ 3.13。
  • 最小闭环:MemoryServicememorize()retrieve()
  • 入门用 inmemory 存储即可;生产环境切换 Postgres,见第 8 章。

动手实验

  1. 按 1.4 节跑通示例,观察 memory_type 分布。
  2. retrieve_config 改为 {"method": "llm"},对比两种模式的返回差异(第 6 章会深入讲解)。
  3. where 中传入错误的 user_id,观察检索结果为空——理解作用域隔离的重要性。

下一章:第 2 章 — 智能体记忆核心概念(建立原理底座)。

回顾:第 0 章的学习路线 — 若时间紧,可 1 → 5 → 6 → 9 跳跃阅读。


发布者: 作者: 转发
评论区 (0)
U