OpenClaw 向量记忆实现方案
根据调研结果,我为你整理了 在 OpenClaw 中实现向量记忆的完整方案:
🧠 OpenClaw 向量记忆实现方案
📋 方案总览
| 方案 | 难度 | 成本 | 推荐度 | 适用场景 |
|---|---|---|---|---|
| 方案 A:ChromaDB 本地方案 | ⭐⭐ | 免费 | ⭐⭐⭐⭐⭐ | 个人使用,隐私优先 |
| 方案 B:Qdrant 本地/云端 | ⭐⭐⭐ | 免费/付费 | ⭐⭐⭐⭐ | 生产环境,高性能 |
| 方案 C:LangChain + 任意向量库 | ⭐⭐⭐ | 取决于选型 | ⭐⭐⭐⭐ | 需要完整 RAG 管道 |
| 方案 D:LlamaIndex 方案 | ⭐⭐⭐⭐ | 取决于选型 | ⭐⭐⭐ | 复杂索引需求 方案 A:ChromaDB 本地方案 ⭐ 强烈推荐最适合 OpenClaw 个人助手的方案 优势 |
- ✅ 完全本地运行,隐私安全
- ✅ 零配置,开箱即用
- ✅ Python 原生支持
- ✅ 轻量级,资源占用低
- ✅ 支持持久化存储
- 架构设计
- OpenClaw Memory System
- │
- ├── 现有记忆 (MEMORY.md + memory/*.md)
- │ └── 语义搜索 (memory_search)
- │
- └── 向量记忆系统 (新增)
- ├── ChromaDB (向量存储)
- ├── Sentence Transformers (Embedding 模型)
- └── 向量记忆技能 (vector-memory skill)
- 实现步骤
- 1️⃣ 创建技能目录结构
- skills/vector-memory/
- ├── SKILL.md # 技能说明
- ├── package.json # NPM 配置
- └── scripts/
- ├── init.py # 初始化数据库
- ├── store.py # 存储记忆
- ├── search.py # 向量搜索
- └── migrate.py # 迁移现有记忆
- 2️⃣ 安装依赖
- pip install chromadb sentence-transformers
- 3️⃣ 核心代码示例初始化数据库 (init.py):
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import chromadb
- from chromadb.config import Settings
- import os
- # 数据库路径 (OpenClaw workspace)
- db_path = os.path.expanduser("~/.openclaw/workspace/memory/vector_db")
- # 创建持久化客户端
- client = chromadb.PersistentClient(path=db_path)
- # 创建记忆集合
- memory_collection = client.get_or_create_collection(
- name="openclaw_memory",
- metadata={"description": "OpenClaw 向量记忆"}
- )
- print(f"✅ 向量数据库初始化完成:{db_path}")
存储记忆 (store.py): - #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import chromadb
- from sentence_transformers import SentenceTransformer
- import os
- import json
- from datetime import datetime
- # 配置
- db_path = os.path.expanduser("~/.openclaw/workspace/memory/vector_db")
- model_name = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
- # 初始化
- client = chromadb.PersistentClient(path=db_path)
- collection = client.get_or_create_collection(name="openclaw_memory")
- embedder = SentenceTransformer(model_name)
- def store_memory(text, metadata=None):
- """存储记忆到向量数据库"""
- # 生成嵌入向量
- embedding = embedder.encode(text)
- # 生成唯一 ID
- memory_id = f"mem_{datetime.now().strftime('%Y%m%d%H%M%S')}_{hash(text) % 10000}"
- # 默认元数据
- if metadata is None:
- metadata = {}
- metadata['created_at'] = datetime.now().isoformat()
- metadata['type'] = metadata.get('type', 'general')
- # 存储
- collection.upsert(
- ids=[memory_id],
- embeddings=[embedding.tolist()],
- metadatas=[metadata],
- documents=[text]
- )
- return memory_id
- # 示例
- if __name__ == "__main__":
- mem_id = store_memory(
- "用户喜欢现代感、科技感的设计风格,特别是玻璃拟态 (glassmorphism)",
- metadata={"type": "user_preference", "category": "design"}
- )
- print(f"✅ 记忆已存储:{mem_id}")
向量搜索 (search.py): - #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- import chromadb
- from sentence_transformers import SentenceTransformer
- import os
- import json
- # 配置
- db_path = os.path.expanduser("~/.openclaw/workspace/memory/vector_db")
- model_name = "sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
- # 初始化
- client = chromadb.PersistentClient(path=db_path)
- collection = client.get_or_create_collection(name="openclaw_memory")
- embedder = SentenceTransformer(model_name)
- def search_memories(query, n_results=5, filter_type=None):
- """搜索相关记忆"""
- # 生成查询向量
- query_embedding = embedder.encode(query)
- # 构建过滤器
- where_filter = None
- if filter_type:
- where_filter = {"type": filter_type}
- # 搜索
- results = collection.query(
- query_embeddings=[query_embedding.tolist()],
- n_results=n_results,
- where=where_filter,
- include=["documents", "metadatas", "distances"]
- )
- # 格式化输出
- memories = []
- if results['documents'] and results['documents'][0]:
- for i, doc in enumerate(results['documents'][0]):
- memories.append({
- 'content': doc,
- 'metadata': results['metadatas'][0][i],
- 'distance': results['distances'][0][i]
- })
- return memories
- # 示例
- if __name__ == "__main__":
- query = "用户喜欢什么设计风格?"
- results = search_memories(query, n_results=3)
- print(f"🔍 搜索结果:{len(results)} 条相关记忆\n")
- for i, mem in enumerate(results, 1):
- print(f"{i}. {mem['content']}")
- print(f" 相似度:{1 - mem['distance']:.4f}")
- print(f" 元数据:{mem['metadata']}\n")
- 4️⃣ 集成到 OpenClaw创建新工具函数 (memory_vector.py):
- # 添加到 OpenClaw 工具系统
- def memory_vector_store(text, metadata=None):
- """向量记忆存储工具"""
- # 调用 store.py
- pass
- def memory_vector_search(query, n_results=5):
- """向量记忆搜索工具"""
- # 调用 search.py
- pass
修改 memory_search 技能: - ## 增强版 memory_search
- 优先级:
- 1. 先搜索向量记忆 (语义相似度)
- 2. 再搜索文本记忆 (关键词匹配)
- 3. 合并结果,去重排序
- 方案 B:Qdrant 方案 (高性能)
- 优势
- ✅ 支持混合搜索 (向量 + 关键词)
- ✅ 支持过滤和聚合
- ✅ 可本地运行,也可云端部署
- ✅ 性能优秀,适合大规模数据
- 快速开始
- # Docker 运行 Qdrant
- docker run -p 6333:6333 -p 6334:6334 \
- -v qdrant_storage:/qdrant/storage \
- qdrant/qdrant
- from qdrant_client import QdrantClient
- from qdrant_client.models import Distance, VectorParams, PointStruct
- # 连接
- client = QdrantClient(host="localhost", port=6333)
- # 创建集合
- client.create_collection(
- collection_name="openclaw_memory",
- vectors_config=VectorParams(size=384, distance=Distance.COSINE),
- )
- # 存储记忆
- client.upsert(
- collection_name="openclaw_memory",
- points=[
- PointStruct(
- id=1,
- vector=embedding,
- payload={"text": "记忆内容", "type": "preference"}
- )
- ]
- )
- 方案 C:LangChain + 向量库 (完整 RAG)
- 优势
- ✅ 完整的 RAG 管道
- ✅ 支持 1000+ 向量库集成
- ✅ 内置记忆管理工具
- 架构
- from langchain_community.vectorstores import Chroma
- from langchain_community.embeddings import HuggingFaceEmbeddings
- from langchain.text_splitter import RecursiveCharacterTextSplitter
- from langchain.chains import RetrievalQA
- # 初始化
- embeddings = HuggingFaceEmbeddings(
- model_name="sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2"
- )
- vectorstore = Chroma(
- persist_directory="./memory/vector_db",
- embedding_function=embeddings
- )
- # 创建检索链
- qa_chain = RetrievalQA.from_chain_type(
- llm=your_llm,
- retriever=vectorstore.as_retriever()
- )
- # 查询
- result = qa_chain("用户的设计偏好是什么?")
- 方案 D:混合记忆系统 (终极方案)结合 OpenClaw 现有记忆和向量记忆:
- ┌─────────────────────────────────────────────┐
- │ OpenClaw 记忆系统 │
- ├─────────────────────────────────────────────┤
- │ ┌─────────────┐ ┌──────────────┐ │
- │ │ 文本记忆 │ │ 向量记忆 │ │
- │ │ MEMORY.md │ │ ChromaDB │ │
- │ │ memory/*.md │ │ (语义搜索) │ │
- │ └──────┬──────┘ └──────┬───────┘ │
- │ │ │ │
- │ └────────┬─────────┘ │
- │ ▼ │
- │ ┌───────────────┐ │
- │ │ 记忆路由器 │ │
- │ │ (智能选择) │ │
- │ └───────────────┘ │
- │ │ │
- │ ┌────────┴────────┐ │
- │ ▼ ▼ │
- │ ┌─────────────┐ ┌──────────────┐ │
- │ │ memory_get │ │ vector_search│ │
- │ └─────────────┘ └──────────────┘ │
- └─────────────────────────────────────────────┘
- 📊 方案对比
| 特性 | ChromaDB | Qdrant | LangChain | 混合方案 |
|---|---|---|---|---|
| 部署难度 | ⭐ | ⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| 性能 | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐ |
| 隐私 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| 成本 | 免费 | 免费/付费 | 免费 | 免费 |
| 推荐度 | ⭐⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |

发表评论 (审核通过后显示评论):