UNPKG

@gongfu/memory

Version:

Intelligent memory layer for Gongfu using mem0

482 lines (407 loc) 10.1 kB
# @gongfu/memory 智能记忆层,基于 [mem0](https://mem0.ai) 为 Gongfu 提供持久化、个性化的 AI 记忆能力。 ## 🌟 特性 - **🧠 智能记忆管理**:自动学习和记住用户偏好、项目模式和历史经验 - **🔍 语义搜索**:基于向量数据库的相似性搜索,智能检索相关记忆 - **👤 多级别隔离**:支持用户级、项目级、全局级的记忆隔离 - **🚀 高性能**:缓存优化、批量处理、异步操作 - **🔒 隐私保护**:本地加密存储,用户完全控制数据 - **🎯 场景适配**:任务管理、Agent 推荐、工作流优化等多场景支持 ## 📦 安装 ```bash # 使用 pnpm pnpm add @gongfu/memory # 使用 npm npm install @gongfu/memory # 使用 yarn yarn add @gongfu/memory ``` ## 🚀 快速开始 ### 基础使用 ```typescript import { MemoryClient } from '@gongfu/memory' // 初始化客户端 const memory = new MemoryClient({ apiKey: process.env.OPENAI_API_KEY, userId: 'user123', config: { vector_store: { provider: 'qdrant', config: { collection_name: 'gongfu_memories', host: 'localhost', port: 6333 } } } }) // 添加记忆 await memory.add('用户偏好使用 TypeScript 进行开发') await memory.add('通常在早上 9-11 点效率最高', { category: 'work_pattern' }) // 搜索记忆 const results = await memory.search('开发语言偏好') console.log(results) // [{ memory: '用户偏好使用 TypeScript 进行开发', score: 0.92 }] // 更新记忆 await memory.update('memory_id', '用户偏好使用 TypeScript 和 React') // 删除记忆 await memory.delete('memory_id') ``` ### 任务记忆管理 ```typescript import { TaskMemoryAdapter } from '@gongfu/memory/adapters' const taskMemory = new TaskMemoryAdapter({ userId: 'user123', projectId: 'project456' }) // 学习任务模式 await taskMemory.learnTaskPattern({ task: { name: '实现用户认证', type: 'feature', priority: 'high', estimatedTime: '3d', actualTime: '2.5d', tags: ['auth', 'security'] }, outcome: { status: 'completed', quality: 'excellent', challenges: ['JWT 实现复杂'] } }) // 获取任务建议 const suggestion = await taskMemory.suggestTask('实现登录功能') console.log(suggestion) /* { estimatedTime: '2-3d', suggestedPriority: 'high', suggestedTags: ['auth', 'security'], similarTasks: [...], tips: ['注意 JWT 实现的复杂性'], confidence: 0.85 } */ // 获取相似历史任务 const similarTasks = await taskMemory.findSimilarTasks({ name: '实现 OAuth 登录', type: 'feature' }) ``` ### Agent 记忆管理 ```typescript import { AgentMemoryAdapter } from '@gongfu/memory/adapters' const agentMemory = new AgentMemoryAdapter({ userId: 'user123' }) // 记录 Agent 使用反馈 await agentMemory.recordUsage({ agentId: 'developer-agent', taskType: 'feature', performance: { speed: 'fast', quality: 'high', accuracy: 0.95 }, userSatisfaction: 5 }) // 获取个性化 Agent 推荐 const recommendations = await agentMemory.recommendAgents({ taskType: 'feature', complexity: 'high', techStack: ['typescript', 'react'] }) console.log(recommendations) /* [ { agentId: 'developer-agent', score: 0.95, reason: '历史表现优秀' }, { agentId: 'architect-agent', score: 0.80, reason: '擅长复杂功能设计' } ] */ // 学习 Agent 协作模式 await agentMemory.learnCollaborationPattern({ agents: ['developer-agent', 'reviewer-agent'], taskType: 'feature', outcome: 'success', pattern: 'sequential' }) ``` ### 用户偏好记忆 ```typescript import { UserPreferenceAdapter } from '@gongfu/memory/adapters' const preferences = new UserPreferenceAdapter({ userId: 'user123' }) // 记录用户偏好 await preferences.recordPreference({ category: 'coding_style', preference: { language: 'TypeScript', framework: 'React', testingLibrary: 'Vitest', lintingRules: 'strict' } }) // 记录工作模式 await preferences.recordWorkPattern({ productiveHours: ['9:00-11:00', '14:00-16:00'], preferredTaskTypes: ['feature', 'optimization'], breakFrequency: '每2小时休息10分钟' }) // 获取个性化建议 const suggestions = await preferences.getPersonalizedSuggestions({ context: 'task_scheduling', currentTime: '09:30' }) console.log(suggestions) /* { recommendation: '现在是您的高效时段,建议处理复杂功能开发', taskTypes: ['feature', 'refactor'], estimatedProductivity: 0.9 } */ ``` ## 🏗️ 架构设计 ### 核心组件 ``` @gongfu/memory/ ├── MemoryClient # mem0 客户端封装 ├── adapters/ # 场景适配器 │ ├── TaskMemoryAdapter # 任务记忆管理 │ ├── AgentMemoryAdapter # Agent 记忆管理 │ └── UserPreferenceAdapter # 用户偏好管理 ├── utils/ # 工具函数 │ ├── embedding.ts # 向量嵌入工具 │ ├── similarity.ts # 相似度计算 │ └── cache.ts # 缓存管理 └── types/ # 类型定义 ``` ### 数据模型 ```typescript // 记忆条目 interface MemoryEntry { id: string content: string embedding?: number[] metadata: { userId: string projectId?: string category?: string tags?: string[] timestamp: Date ttl?: number // 生存时间(秒) } score?: number // 相关性分数 } // 任务记忆 interface TaskMemory { taskPattern: { type: string estimatedTime: string actualTime?: string complexity: 'low' | 'medium' | 'high' successRate: number } commonTags: string[] dependencies: string[] challenges: string[] bestPractices: string[] } // Agent 记忆 interface AgentMemory { agentId: string performance: { taskTypes: Record<string, PerformanceMetrics> overallScore: number specialties: string[] } collaborationPatterns: CollaborationPattern[] userFeedback: Feedback[] } ``` ## 🔧 高级配置 ### 向量数据库配置 支持多种向量数据库后端: ```typescript // Qdrant (默认) const memory = new MemoryClient({ config: { vector_store: { provider: 'qdrant', config: { host: 'localhost', port: 6333, collection_name: 'gongfu_memories' } } } }) // ChromaDB const memory = new MemoryClient({ config: { vector_store: { provider: 'chroma', config: { collection_name: 'gongfu_memories', persist_directory: './chroma_db' } } } }) // In-Memory (开发测试) const memory = new MemoryClient({ config: { vector_store: { provider: 'in_memory' } } }) ``` ### LLM 配置 ```typescript const memory = new MemoryClient({ config: { llm: { provider: 'openai', config: { model: 'gpt-4o-mini', temperature: 0.1, max_tokens: 500 } }, embedder: { provider: 'openai', config: { model: 'text-embedding-3-small' } } } }) ``` ### 记忆生命周期管理 ```typescript // 设置记忆过期时间 await memory.add('临时偏好设置', { ttl: 86400 // 24小时后过期 }) // 记忆衰减策略 const memory = new MemoryClient({ config: { retention: { strategy: 'decay', // 'decay' | 'fixed' | 'adaptive' decayRate: 0.1, // 每天衰减 10% minScore: 0.3 // 分数低于 0.3 自动删除 } } }) // 记忆容量限制 const memory = new MemoryClient({ config: { capacity: { maxEntries: 10000, // 最大记忆条数 maxSizePerUser: '100MB', // 每用户最大存储 evictionPolicy: 'LRU' // 'LRU' | 'LFU' | 'FIFO' } } }) ``` ## 🔐 隐私和安全 ### 数据加密 ```typescript const memory = new MemoryClient({ config: { encryption: { enabled: true, algorithm: 'aes-256-gcm', keyDerivation: 'pbkdf2' } } }) ``` ### 数据导出和清除 ```typescript // 导出用户所有记忆 const memories = await memory.exportUserMemories('user123') fs.writeFileSync('user_memories.json', JSON.stringify(memories)) // 清除用户记忆 await memory.clearUserMemories('user123') // 清除项目记忆 await memory.clearProjectMemories('project456') // 选择性清除 await memory.clearMemories({ userId: 'user123', category: 'work_pattern', olderThan: '30d' }) ``` ## 📊 性能优化 ### 批量操作 ```typescript // 批量添加记忆 await memory.batchAdd([ { content: '偏好 1', metadata: { category: 'preference' } }, { content: '偏好 2', metadata: { category: 'preference' } }, { content: '偏好 3', metadata: { category: 'preference' } } ]) // 批量搜索 const results = await memory.batchSearch([ 'TypeScript 最佳实践', 'React 性能优化', '测试策略' ]) ``` ### 缓存策略 ```typescript const memory = new MemoryClient({ config: { cache: { enabled: true, ttl: 300, // 5分钟缓存 maxSize: '50MB', strategy: 'LRU' } } }) // 预热缓存 await memory.warmCache({ userId: 'user123', categories: ['preference', 'work_pattern'] }) ``` ## 🧪 测试 ```typescript import { MemoryClient } from '@gongfu/memory' import { MockVectorStore } from '@gongfu/memory/testing' // 使用 Mock 向量存储进行测试 const memory = new MemoryClient({ config: { vector_store: { provider: 'mock', config: { store: new MockVectorStore() } } } }) // 测试记忆添加 test('should add and retrieve memory', async () => { await memory.add('test memory') const results = await memory.search('test') expect(results[0].content).toBe('test memory') }) ``` ## 🚧 路线图 - [ ] 支持更多向量数据库(Pinecone, Weaviate) - [ ] 图数据库集成(记忆关系网络) - [ ] 实时记忆同步 - [ ] 记忆可视化界面 - [ ] 跨项目记忆迁移 - [ ] 记忆模板系统 - [ ] AI 驱动的记忆整理 - [ ] 记忆版本控制 ## 📄 许可证 MIT © Gongfu Team