# langgraph-memory-system **Repository Path**: yizhishui/langgraph-memory-system ## Basic Information - **Project Name**: langgraph-memory-system - **Description**: 学习Agent所用的 - **Primary Language**: Python - **License**: Apache-2.0 - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-03-25 - **Last Updated**: 2026-09-02 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # LangGraph Memory System 一个生产级的 LangGraph Agent 记忆系统,支持 PostgreSQL 存储、用户+Agent 双隔离、双写备份,以及完整的前后端实现。 ## 特性 - **🗄️ PostgreSQL 存储**: 可扩展的数据库后端,支持连接池 - **👥 用户+Agent 隔离**: 每个用户+Agent 组合都有独立的记忆空间 - **💾 双写备份**: 可选的 JSON 备份,用于灾难恢复 - **🔄 防抖更新**: 高效的批量更新,支持可配置延迟 - **🤖 LLM 驱动更新**: 使用 Qwen Plus(阿里云)进行智能记忆提取 - **📊 实时流式输出**: SSE (Server-Sent Events) 实现 AI 响应流式输出 - **🔌 WebSocket 状态推送**: 实时推送记忆更新、队列状态等后台事件 - **🎨 Vue 3 前端**: 现代化的聊天界面和记忆可视化 - **📈 监控**: 内置健康检查和 Prometheus 指标 - **🧪 完整测试**: 单元测试、集成测试和性能测试 ## 架构 ``` 用户对话 → LangGraph Agent → MemoryMiddleware ↓ 过滤消息 ↓ MemoryUpdateQueue (30秒防抖) ↓ MemoryUpdater (Qwen Plus) ↓ ┌────────────────────┴────────────────────┐ ↓ ↓ PostgreSQL 存储 JSON 备份 (user_id + agent_name) (灾难恢复) ↓ ┌───────┴────────┐ ↓ ↓ SSE 流式输出 WebSocket 状态 (AI 响应) (记忆更新等) ``` ### 混合通信架构 本项目采用 **SSE + WebSocket 混合架构**: | 通信方式 | 用途 | 优势 | |---------|------|------| | **SSE** | AI 响应流式输出 | 浏览器原生支持、自动重连、HTTP/2 多路复用 | | **WebSocket** | 状态事件推送 | 双向通信、实时后台事件 | ## 安装 ### 基础安装 ```bash # 克隆仓库 git clone https://github.com/yourusername/langgraph-memory-system.git cd langgraph-memory-system # 安装依赖 pip install -e ".[all]" # 复制环境模板 cp .env.example .env # 编辑 .env 配置 nano .env # 重要:配置阿里云 DashScope API Key # 在 .env 文件中设置: # OPENAI_API_KEY=sk-your-dashscope-api-key # OPENAI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 ``` ### PostgreSQL 设置 ```bash # 创建数据库 createdb memory # 运行迁移 psql -d memory -f migrations/001_init_memory.sql ``` ### 前端设置 ```bash cd web # 安装依赖 npm install # 复制环境模板 cp .env.example .env.local # 配置后端 URL # 在 web/.env.local 中设置: # VITE_API_URL=http://localhost:8000 # VITE_WS_URL=ws://localhost:8000 ``` ## 快速开始 ### 启动全栈应用 ```bash # 终端 1: 启动 FastAPI 后端 source .venv/bin/activate python scripts/run_api.py # 运行在 http://0.0.0.0:8000 # 终端 2: 启动 Vue 前端 cd web npm run dev # 运行在 http://localhost:5173 # 访问应用 # 前端界面: http://localhost:5173 # API 文档: http://localhost:8000/docs # 健康检查: http://localhost:8000/health ``` ### Python API 基本用法 ```python import asyncio from langchain_core.messages import HumanMessage from memory.factory import create_memory_system async def main(): # 创建记忆系统 middleware, queue_manager = await create_memory_system() # 启动后台处理 await queue_manager.start() # 包装你的 LangGraph Agent wrapped_agent = middleware.wrap(your_agent_graph) # 使用用户+Agent 隔离 result = await wrapped_agent.ainvoke( {"messages": [HumanMessage(content="你好!我是一名软件工程师。")]}, config={ "metadata": { "user_id": "user123", "agent_name": "assistant" }, "configurable": { "thread_id": "thread456" } } ) # 清理 await queue_manager.stop() asyncio.run(main()) ``` ### 前端使用 访问 http://localhost:5173 后: 1. **聊天界面**: 发送消息,AI 响应会实时流式显示 2. **记忆可视化**: 查看注入的记忆内容和更新状态 3. **连接状态**: 监控 SSE 和 WebSocket 连接状态 ### 配置 ```python from memory.config import MemoryConfig config = MemoryConfig( enabled=True, storage_type="dual_write", # 或 "postgres" postgres_connection_string="postgresql://user:pass@localhost:5432/memory", postgres_pool_size=10, json_backup_enabled=True, debounce_seconds=30, update_model="qwen-plus", # 阿里云 Qwen Plus 模型 injection_enabled=True, max_injection_tokens=2000, fact_confidence_threshold=0.7, max_facts=500, ) ``` ## 记忆结构 ```json { "version": "1.0", "lastUpdated": "2024-01-01T00:00:00Z", "user": { "workContext": { "summary": "在 TechCorp 工作的软件工程师", "updatedAt": "..." }, "personalContext": { "summary": "住在旧金山,喜欢徒步旅行", "updatedAt": "..." }, "topOfMind": { "summary": "正在准备会议演讲", "updatedAt": "..." } }, "history": { "recentMonths": { "summary": "开始新工作,学习了 Python", "updatedAt": "..." }, "earlierContext": { "summary": "之前在 StartupXYZ 工作", "updatedAt": "..." }, "longTermBackground": { "summary": "计算机科学学位,10年工作经验", "updatedAt": "..." } }, "facts": [ { "id": "fact_abc123", "content": "比起 JavaScript 更喜欢 Python", "category": "preference", "confidence": 0.9, "createdAt": "2024-01-01T00:00:00Z", "source": "thread456" } ] } ``` ## API 端点 ### REST API - `POST /api/v1/chat/send` - 发送消息(非流式) - `POST /api/v1/chat/stream` - 发送消息(SSE 流式输出) - `GET /api/v1/memory/current/{user_id}` - 获取当前记忆 - `POST /api/v1/memory/update` - 手动触发记忆更新 - `GET /api/v1/users/list` - 获取用户列表 - `GET /health` - 健康检查 - `GET /metrics` - Prometheus 指标 ### WebSocket - `WS /api/v1/chat/ws/{user_id}` - WebSocket 连接,接收状态事件 ### WebSocket 事件 - `memory_injected` - 记忆已注入到对话 - `memory_queued` - 消息已排队等待记忆更新 - `memory_updated` - 记忆已更新 - `error` - 错误通知 ## SSE 流式输出 ### SSE 事件类型 - `metadata` - 初始元数据(消息 ID、线程 ID、记忆注入状态) - `token` - AI 响应的内容块 - `done` - 流式完成信号 - `error` - 错误信息 ### 前端使用示例 ```typescript import { useSSE } from '@/composables/useSSE'; const { isStreaming, streamMessage } = useSSE(); // 开始流式接收 streamMessage( userId, message, // onChunk: 每个内容块的回调 (chunk: string) => { console.log('收到:', chunk); // 更新 UI }, // options { onSuccess: (messageId) => console.log('完成:', messageId), onError: (error) => console.error('错误:', error), onMemoryInjected: (preview) => console.log('记忆注入:', preview) } ); ``` ## 测试 ```bash # 运行所有测试 pytest tests/ -v # 运行特定测试类型 pytest tests/test_memory_storage.py -v # 单元测试 pytest tests/test_memory_integration.py -v # 集成测试 pytest tests/test_memory_performance.py -m performance -v # 性能测试 # 运行测试并生成覆盖率报告 pytest tests/ --cov=memory --cov-report=html ``` ## 监控 ### 健康检查 ```bash curl http://localhost:8000/health/memory ``` 响应: ```json { "status": "healthy", "timestamp": "2024-01-01T00:00:00Z", "config": { "enabled": true, "storage_type": "dual_write", "injection_enabled": true }, "storage": { "type": "postgres", "status": "connected" } } ``` ### Prometheus 指标 ```bash curl http://localhost:8000/metrics ``` 可用指标: - `memory_updates_total` - 记忆更新总数 - `memory_update_duration_seconds` - 更新耗时 - `memory_cache_hits_total` - 缓存命中数 - `memory_cache_misses_total` - 缓存未命中数 ## 存储后端 ### PostgreSQL(推荐) ```python config = MemoryConfig( storage_type="postgres", postgres_connection_string="postgresql://user:pass@host:5432/db", ) ``` **优点**: 可扩展、支持并发访问、生产就绪 **缺点**: 需要数据库设置 ### 双写(默认) ```python config = MemoryConfig( storage_type="dual_write", postgres_connection_string="postgresql://user:pass@host:5432/db", json_backup_enabled=True, ) ``` **优点**: 自动备份、灾难恢复 **缺点**: 写入较慢(双倍写入) ## 性能 | 指标 | 数值 | |------|------| | 并发更新 | >100/秒 | | 缓存命中率 | >90% | | 更新延迟 | <500ms (p95) | | 存储开销 | <10% | ## 配置选项 | 选项 | 默认值 | 说明 | |------|--------|------| | `enabled` | `true` | 记忆系统总开关 | | `storage_type` | `dual_write` | 后端类型:`postgres` 或 `dual_write` | | `postgres_pool_size` | `10` | 数据库连接池大小 | | `debounce_seconds` | `30` | 队列批量延迟 | | `update_model` | `qwen-plus` | 记忆更新 LLM(qwen-plus、qwen-turbo、qwen-max) | | `injection_enabled` | `true` | 是否将记忆注入到提示 | | `max_injection_tokens` | `2000` | 注入的最大 token 数 | | `fact_confidence_threshold` | `0.7` | 事实的最小置信度 | | `max_facts` | `500` | 最大存储事实数 | | `cache_ttl_seconds` | `30` | 缓存 TTL | ## 故障排查 ### 数据库连接失败 ```bash # 检查 PostgreSQL 是否运行 pg_isready -h localhost -p 5432 # 测试连接 psql -h localhost -U postgres -d memory ``` ### 记忆更新不工作 1. 检查日志:`tail -f logs/memory.log` 2. 验证配置:`curl http://localhost:8000/health/memory/config` 3. 手动测试:见 `examples/basic_usage.py` ### 性能问题 1. 增加连接池:`postgres_pool_size=20` 2. 减少防抖:`debounce_seconds=10` 3. 检查指标:`curl http://localhost:8000/metrics` ### SSE 连接失败 1. 检查后端是否运行:`curl http://localhost:8000/health` 2. 查看浏览器控制台是否有 `[SSE]` 日志 3. 在浏览器网络标签查找 `EventStream` 请求 4. 确保 `VITE_API_URL` 配置正确 ### WebSocket 连接失败 1. 测试 WebSocket 端点:`wscat -c ws://localhost:8000/api/v1/chat/ws/test_user` 2. 检查 CORS 配置 3. 确保 `VITE_WS_URL` 配置正确 ## 项目结构 ### 后端结构 ``` api/ # FastAPI 服务 ├── main.py # 应用入口 ├── config.py # API 配置 ├── state.py # 应用状态 ├── checkpoint.py # LangGraph 检查点 ├── routes/ # API 路由 │ ├── chat.py # 聊天端点(含 SSE) │ ├── memory.py # 记忆端点 │ ├── users.py # 用户管理 │ └── debug.py # 调试端点 ├── services/ # 业务逻辑 │ ├── chat_service.py # 聊天服务 │ ├── thread_service.py # 线程服务 │ └── agent_factory.py # Agent 工厂 ├── websocket/ # WebSocket │ └── manager.py # 连接管理器 └── models/ # Pydantic 模型 ├── chat.py # 聊天模型 ├── memory.py # 记忆模型 └── websocket.py # WebSocket 模型 memory/ # 内存存储核心 ├── config.py # 内存配置 ├── storage.py # 存储抽象 ├── factory.py # 系统工厂 ├── postgres_storage.py # PostgreSQL 存储 ├── json_storage.py # JSON 文件存储 ├── dual_write_storage.py # 双写存储 ├── middleware.py # 记忆中间件 ├── updater.py # LLM 更新器 ├── queue.py # 更新队列 └── prompts.py # 提示词 scripts/ # 脚本和工具 └── run_api.py # API 启动脚本 tests/ # 测试套件 ├── test_memory_storage.py # 存储测试 ├── test_memory_integration.py # 集成测试 ├── test_memory_performance.py # 性能测试 ├── test_fixes.py # 修复验证 └── verify_fixes.py # 验证脚本 migrations/ # 数据库迁移 ├── 001_init_memory.sql # 内存表初始化 └── 002_thread_metadata.sql # 线程元数据表 monitoring/ # 监控 └── health.py # 健康检查 docs/ # 项目文档 ├── ARCHITECTURE.md # 架构设计 ├── MEMORY_FLOW.md # 内存流程 ├── MEMORY_SYSTEM_DEEP_DIVE.md # 深度解析 ├── PROJECT_STRUCTURE.md # 项目结构 └── LangGraph_Memory_System_Interview_Questions.md # 面试题 ``` ### 前端结构 ``` web/ ├── src/ │ ├── main.ts # 应用入口 │ ├── App.vue # 根组件 │ ├── style.css # 全局样式 │ ├── components/ # Vue 组件 │ │ ├── Chat/ # 聊天 UI │ │ ├── Layout/ # 布局组件 │ │ ├── Memory/ # 记忆可视化 │ │ └── RealTime/ # 实时通信 │ ├── views/ # 页面视图 │ │ ├── ChatView.vue # 聊天页面 │ │ ├── MemoryView.vue # 记忆页面 │ │ ├── HomeView.vue # 首页 │ │ └── SettingsView.vue # 设置页面 │ ├── stores/ # Pinia 状态 │ │ ├── chat.ts # 聊天状态 │ │ ├── memory.ts # 记忆状态 │ │ ├── thread.ts # 线程状态 │ │ ├── user.ts # 用户状态 │ │ └── websocket.ts # WebSocket 状态 │ ├── composables/ # 组合式函数 │ │ ├── useSSE.ts # SSE 连接 │ │ └── useWebSocket.ts # WebSocket 连接 │ ├── router/ # 路由配置 │ │ └── index.ts │ ├── types/ # TypeScript 类型 │ │ ├── chat.ts │ │ ├── memory.ts │ │ ├── user.ts │ │ └── index.ts │ ├── api/ # API 调用 │ └── assets/ # 静态资源 ├── package.json ├── vite.config.ts └── tsconfig.json ``` 详细的目录说明请参考 [docs/PROJECT_STRUCTURE.md](docs/PROJECT_STRUCTURE.md) ## 贡献指南 1. Fork 本仓库 2. 创建特性分支 3. 为新功能添加测试 4. 确保所有测试通过 5. 提交 Pull Request ## 许可证 MIT License - 详见 LICENSE 文件 ## 致谢 - 使用 [LangGraph](https://github.com/langchain-ai/langgraph) 构建 - 使用阿里云 [Qwen](https://qwenlm.github.io/) 模型 - 灵感来自 [DeerFlow](https://github.com/princeton-std/DeerFlow) 记忆系统 ## 阿里云 DashScope 配置 本项目使用阿里云 DashScope 提供的 Qwen 模型。 ### 获取 API Key 1. 访问 [阿里云 DashScope 控制台](https://dashscope.console.aliyun.com/) 2. 开通服务并创建 API Key 3. 将 API Key 设置到环境变量: ```bash export OPENAI_API_KEY=sk-your-dashscope-api-key export OPENAI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 ``` ### 可用模型 - `qwen-plus`:推荐用于记忆更新(性价比高) - `qwen-turbo`:速度更快,成本更低 - `qwen-max`:最高准确度,成本较高 - `qwen-long`:支持长文本 ### 模型配置 在 `.env` 文件中配置: ```bash MEMORY_UPDATE_MODEL=qwen-plus OPENAI_API_KEY=sk-your-dashscope-api-key OPENAI_BASE_URL=https://dashscope.aliyuncs.com/compatible-mode/v1 ``` ## 路线图 - [ ] 支持更多存储后端(Redis、MongoDB) - [ ] 记忆版本控制和历史记录 - [ ] 多语言支持 - [ ] 移动端应用 - [ ] 更多 LLM 提供商支持 - [ ] 记忆可视化增强(图谱、时间线) - [ ] A/B 测试框架