📚 OpenClaw + LlamaIndex 集成指南
想让你的Agent拥有"记忆"?LlamaIndex + OpenClaw = 超级RAG Agent。从文档检索到知识库问答,一篇搞定。
🎯 为什么需要 LlamaIndex?
OpenClaw原生的 web-search 和 web-fetch 可以搜索互联网,但如果你需要:
- 📖 检索本地文档(PDF、Word、Markdown)
- 🏢 查询企业知识库
- 🔍 在海量数据中精准搜索
- 💬 基于文档的问答
那就需要 LlamaIndex 来增强你的Agent!
🏗️ 架构设计
┌─────────────────────────────────────────┐
│ OpenClaw Agent │
│ ┌─────────────────────────────────┐ │
│ │ LlamaIndex MCP Server │ │
│ │ ┌───────┐ ┌───────┐ ┌──────┐ │ │
│ │ │ Query │ │ Index │ │ Chat │ │ │
│ │ │ Engine│ │ Build │ │ Eng. │ │ │
│ │ └───┬───┘ └───┬───┘ └──┬───┘ │ │
│ │ │ │ │ │ │
│ │ ┌───┴─────────┴────────┴───┐ │ │
│ │ │ Vector Store │ │ │
│ │ │ ChromaDB / Pinecone │ │ │
│ │ └──────────────────────────┘ │ │
│ └─────────────────────────────────┘ │
│ │
│ Tools: web-search, file-manager, ... │
└─────────────────────────────────────────┘
🚀 快速开始
步骤1:安装依赖
# 安装LlamaIndex
pip install llama-index llama-index-vector-stores-chroma
# 安装OpenClaw MCP支持
npm install -g @anthropic/mcp-server-llamaindex
步骤2:创建MCP Server
# llamaindex_mcp_server.py
from mcp.server import Server
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
from llama_index.vector_stores.chroma import ChromaVectorStore
import chromadb
# 初始化ChromaDB
chroma_client = chromadb.PersistentClient(path="./chroma_db")
chroma_collection = chroma_client.get_or_create_collection("my_docs")
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
# 创建MCP Server
server = Server("llamaindex")
@server.tool()
def index_documents(directory: str) -> str:
"""索引目录中的文档"""
documents = SimpleDirectoryReader(directory).load_data()
index = VectorStoreIndex.from_documents(
documents, vector_store=vector_store
)
return f"已索引 {len(documents)} 个文档"
@server.tool()
def query_knowledge_base(query: str) -> str:
"""查询知识库"""
index = VectorStoreIndex.from_vector_store(vector_store)
query_engine = index.as_query_engine()
response = query_engine.query(query)
return str(response)
@server.tool()
def search_documents(query: str, top_k: int = 5) -> str:
"""搜索相关文档片段"""
index = VectorStoreIndex.from_vector_store(vector_store)
retriever = index.as_retriever(similarity_top_k=top_k)
nodes = retriever.retrieve(query)
results = []
for node in nodes:
results.append(f"[相关度: {node.score:.2f}]\n{node.text}")
return "\n---\n".join(results)
if __name__ == "__main__":
server.run()
步骤3:配置OpenClaw
# 在 openclaw.json 中添加MCP配置
{
"mcpServers": {
"llamaindex": {
"command": "python",
"args": ["llamaindex_mcp_server.py"],
"env": {}
}
}
}
步骤4:使用
# 现在你可以直接对Agent说:
# "索引 /path/to/documents 目录下的所有文档"
# Agent会调用 index_documents 工具
# "查询知识库:OpenClaw的安装步骤是什么?"
# Agent会调用 query_knowledge_base 工具
# "搜索与'Agent安全'相关的文档"
# Agent会调用 search_documents 工具
💡 最佳实践
1. 文档预处理
# 使用LlamaIndex的转换器优化文档
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.extractors import TitleExtractor
# 配置转换管道
transformations = [
SentenceSplitter(chunk_size=512, chunk_overlap=20),
TitleExtractor(),
]
# 索引时自动应用
index = VectorStoreIndex.from_documents(
documents,
transformations=transformations,
vector_store=vector_store
)
2. 混合检索
# 结合向量检索和关键词检索
from llama_index.core.retrievers import QueryFusionRetriever
from llama_index.retrievers.bm25 import BM25Retriever
# 创建混合检索器
retriever = QueryFusionRetriever(
retrievers=[vector_retriever, bm25_retriever],
num_queries=1,
use_async=True
)
3. 缓存优化
# 使用缓存避免重复计算
from llama_index.core.storage.docstore import SimpleDocumentStore
from llama_index.core.storage.index_store import SimpleIndexStore
# 持久化存储
storage_context = StorageContext.from_defaults(
docstore=SimpleDocumentStore.from_persist_dir("./storage"),
vector_store=vector_store,
index_store=SimpleIndexStore.from_persist_dir("./storage")
)
🔗 相关资源