LlamaIndex Documentation

LlamaIndex Documentation

🚀 LlamaIndex MCP 演示

本仓库展示了如何借助 LlamaCloud 创建 MCP 服务器,以及如何将 LlamaIndex 用作 MCP 客户端。通过这些操作,你可以利用 RAG(检索增强生成)为 Claude 等客户端提供实时私人信息,以更精准地回答问题。

🚀 快速开始

✨ 使用 LlamaCloud 作为 MCP 服务器

📦 安装指南

设置您的 LlamaCloud 索引
  1. 获取 LlamaCloud 账户。
  2. 在 UI 中创建一个新的索引,并选择任意数据源。在此示例中,我们使用了 Google Drive 并提供了一部分 LlamaIndex 文档作为数据源。若仅用于测试,也可直接上传文档到索引。
  3. LlamaCloud UI 获取一个 API 密钥。
设置您的 MCP 服务器
  1. 克隆此仓库。
  2. 创建一个 .env 文件并添加两个环境变量:
    • LLAMA_CLOUD_API_KEY - 上一步获取的 API 密钥。
    • OPENAI_API_KEY - 您的 OpenAI API 密钥。

💻 使用示例

运行 MCP 服务器

运行以下命令以启动 MCP 服务器:

uvicorn mcp_server:app --reload

✨ 使用 LlamaIndex 作为 MCP 客户端

💻 使用示例

基础用法

mcp_http_server.py 中,您可以找到以下代码:

from fastapi import FastAPI
import asyncio
from mcp_core.mcp_client import BasicMCPClient
from mcp_core.tool_spec import McpToolSpec
from langchain.agents import FunctionAgent
from langchain.llms import OpenAI

mcp = FastAPI(title="LlamaIndex MCP 服务器")

async def main():
await mcp.startup()
asyncio.create_task(mcp.run_sse_async())

if __name__ == "__main__":
asyncio.run(main())
高级用法

获取工具规范

mcp_client = BasicMCPClient("http://localhost:8000/sse")
mcp_tool_spec = McpToolSpec(
client=mcp_client,
allowed_tools=["tool1", "tool2"],
)

tools = mcp_tool_spec.to_tool_list()

创建代理并回答问题

llm = OpenAI(model="gpt-4o-mini")

agent = FunctionAgent(
tools=tools,
llm=llm,
system_prompt="您是一个知道如何在 LlamaIndex 中构建代理的智能体。",
)

async def run_agent():
response = await agent.run("如何在 LlamaIndex 中创建一个代理?")
print(response)

if __name__ == "__main__":
asyncio.run(run_agent())

你已完成所有设置!现在可以使用代理从您的 LlamaCloud 索引中获取信息了。

  • 0 关注
  • 0 收藏,19 浏览
  • system 提出于 2025-09-18 15:18

相似服务问题

相关AI产品