Lightrag的安装部署使用
ollama和lightrag包地址在结尾一、前置安装工作python安装tar -zxvf Python-3.11.9.tgz cd Python-3.11.9 ./configure --prefix/usr/local/python311 make make install ln -s /usr/local/python311/bin/python3.11 /usr/bin/python311 ln -s /usr/local/python311/bin/pip3.11 /usr/bin/pip311升级pippip311 install --upgrade pipgit安装yum install -y git二、Ollama安装迅雷下载https://github.com/ollama/ollama/releases/download/v0.3.12/ollama-linux-amd64.tgz启动OLLAMA_HOST0.0.0.0 ollama serve ollama list NAME ID SIZE MODIFIED拉取千问模型ollama pull qwen2:0.5b ollama pull nomic-embed-text ollama list NAME ID SIZE MODIFIED nomic-embed-text:latest 0a109f422b47 274 MB 2 hours ago qwen2:0.5b 6f48b936a09f 352 MB 2 hours ago三、LightRAG安装下载https://github.com/HKUDS/LightRAG下载好LightRAG-main.zip上传到/root目录下# 创建并进入目录 mkdir -p /root/LightRAG cd /root/LightRAG # 解压 unzip /root/LightRAG-main.zip # 将解压后的所有文件包括隐藏文件移动到当前目录 mv LightRAG-main/* LightRAG-main/.[!.]* . 2/dev/null # 删除空的文件夹和原始的 ZIP 文件 rmdir LightRAG-main 2/dev/null rm /root/LightRAG-main.zip # 创建虚拟环境 python3.11 -m venv venv # 激活虚拟环境 source venv/bin/activate安装核心依赖配置pip国内镜像源# 配置 pip 使用清华源永久生效 pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple # 验证配置 pip config list # 以可编辑模式安装 LightRAG 核心 pip install -e . # 安装 Ollama 相关的额外依赖 pip install ollama requests numpy aiohttp # 验证 (venv) [rootlightrag LightRAG]# python -c from lightrag import LightRAG; print(✅ LightRAG 核心已成功安装并可以导 入) ✅ LightRAG 核心已成功安装并可以导入 四、测试通行ollama启动OLLAMA_HOST127.0.0.1:6006 ollama serve跑lightrag官方测试用例失败(venv) [rootlightrag examples]# python lightrag_ollama_demo.py LightRAG compatible demo log file: /root/LightRAG/examples/lightrag_ollama_demo.log An error occurred: No module named _sqlite3 Traceback (most recent call last): File /root/LightRAG/examples/lightrag_ollama_demo.py, line 218, in module asyncio.run(main()) File /usr/local/python311/lib/python3.11/asyncio/runners.py, line 190, in run return runner.run(main) ^^^^^^^^^^^^^^^^ File /usr/local/python311/lib/python3.11/asyncio/runners.py, line 118, in run return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File /usr/local/python311/lib/python3.11/asyncio/base_events.py, line 654, in run_until_complete return future.result() ^^^^^^^^^^^^^^^ File /root/LightRAG/examples/lightrag_ollama_demo.py, line 210, in main if rag: ^^^ UnboundLocalError: cannot access local variable rag where it is not associated with a value退出虚拟环境deactivate重新编译Python加上 sqlite3 组件# 安装 sqlite3 依赖 yum install -y sqlite-devel cd /data/Python-3.11.9 ./configure --enable-loadable-sqlite-extensions --prefix/usr/local/python311 make -j$(nproc) make install重新构建虚拟环境cd /root/LightRAG rm -rf venv python311 -m venv venv source venv/bin/activate pip install . -i https://pypi.tuna.tsinghua.edu.cn/simple (venv) [rootlightrag LightRAG]# python -c import sqlite3; print(✅ 安装成功) ✅ 安装成功跑官方测试用例(venv) [rootlightrag LightRAG]# cd examples/ (venv) [rootlightrag examples]# python lightrag_ollama_demo.py LightRAG compatible demo log file: /root/LightRAG/examples/lightrag_ollama_demo.log INFO: [] Created new empty graph file: ./dickens/graph_chunk_entity_relation.graphml INFO:nano-vectordb:Init {embedding_dim: 1024, metric: cosine, storage_file: ./dickens/vdb_entities.json} 0 data INFO:nano-vectordb:Init {embedding_dim: 1024, metric: cosine, storage_file: ./dickens/vdb_relationships.json} 0 data INFO:nano-vectordb:Init {embedding_dim: 1024, metric: cosine, storage_file: ./dickens/vdb_chunks.json} 0 data INFO: [] Process 1814492 KV load full_docs with 0 records INFO: [] Process 1814492 KV load text_chunks with 0 records INFO: [] Process 1814492 KV load full_entities with 0 records INFO: [] Process 1814492 KV load full_relations with 0 records INFO: [] Process 1814492 KV load entity_chunks with 0 records INFO: [] Process 1814492 KV load relation_chunks with 0 records INFO: [] Process 1814492 KV load llm_response_cache with 0 records INFO: [] Process 1814492 doc status load doc_status with 0 records INFO: Embedding func: 8 new workers initialized (Timeouts: Func: 30s, Worker: 60s, Health Check: 75s) WARNING: Embedding func: Worker timeout for task 140388521705728_12014196.785028914 after 60s An error occurred: Embedding func: Worker execution timeout after 60s INFO: Successfully finalized 12 storages Done!查看ollama是否运行ps aux | grep ollama网页测试创建个本地的html文件!DOCTYPE html html langzh-CN head meta charsetUTF-8 meta nameviewport contentwidthdevice-width, initial-scale1.0 titleLightRAG 知识库问答/title style *{margin:0;padding:0;box-sizing:border-box;font-family:system-ui, sans-serif} body{background:#f0f2f5;padding:20px;max-width:900px;margin:0 auto} .title{text-align:center;margin:20px 0;color:#333} .chat{background:#fff;border-radius:12px;height:650px;overflow-y:auto;padding:20px;box-shadow:0 2px 10px #00000010;margin-bottom:15px} .msg{margin-bottom:16px;max-width:75%;line-height:1.6} .user{margin-left:auto;background:#009fdf;color:#fff;padding:10px 14px;border-radius:14px 14px 4px 14px} .bot{background:#f1f3f5;color:#333;padding:10px 14px;border-radius:14px 14px 14px 4px} .input-box{display:flex;gap:10px} #question{flex:1;padding:14px;border:1px solid #ddd;border-radius:10px;font-size:15px} #send{padding:14px 24px;background:#009fdf;color:#fff;border:none;border-radius:10px;font-size:15px;cursor:pointer} #send:disabled{background:#999;cursor:not-allowed} .loading{color:#666;font-style:italic} /style /head body h2 classtitle LightRAG 智能问答10.10.100.25/h2 div classchat idchat/div div classinput-box input typetext idquestion placeholder输入问题... button idsend发送/button /div script const chat document.getElementById(chat) const question document.getElementById(question) const send document.getElementById(send) // 你的服务器地址 const API_URL http://10.10.100.25:9632/api/query function addMsg(text, type) { const div document.createElement(div) div.className msg type div.textContent text chat.appendChild(div) chat.scrollTop chat.scrollHeight return div } async function sendMsg() { const q question.value.trim() if (!q) return question.value send.disabled true addMsg(q, user) const load addMsg(正在思考中..., bot) try { const res await fetch(API_URL, { method: POST, headers: { Content-Type: application/json }, body: JSON.stringify({ query: q }) }) const data await res.json() chat.removeChild(load) addMsg(data.response || 未获取到回答, bot) } catch (e) { chat.removeChild(load) addMsg(❌ 连接失败请检查\n1. LightRAG 是否运行\n2. 服务IP10.10.100.25:9632\n3. 防火墙是否开放端口, bot) } finally { send.disabled false } } send.onclick sendMsg question.addEventListener(keypress, e e.key Enter sendMsg()) /script /body /html服务器创建api.py(venv) [rootlightrag LightRAG]# cat api.py EOF from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import httpx app FastAPI() app.add_middleware( CORSMiddleware, allow_origins[*], allow_methods[*], allow_headers[*], ) app.post(/api/query) async def query(data: dict): try: async with httpx.AsyncClient(timeouthttpx.Timeout(120.0)) as client: resp await client.post( http://127.0.0.1:11434/api/generate, json{ model: qwen2.5:3b, # 这里改成你真实存在的模型 prompt: data[query], stream: False } ) r resp.json() return {response: r.get(response, 无返回)} except Exception as e: return {response: f错误{str(e)}} if __name__ __main__: import uvicorn uvicorn.run(app, host0.0.0.0, port9632) EOF[rootlightrag ~]# cd /root/LightRAG/ [rootlightrag LightRAG]# source venv/bin/activate (venv) [rootlightrag LightRAG]# python api.py INFO: Started server process [1836731] INFO: Waiting for application startup. INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:9632 (Press CTRLC to quit) INFO: 10.254.254.3:54350 - OPTIONS /api/query HTTP/1.1 200 OK INFO: 10.254.254.3:54350 - POST /api/query HTTP/1.1 200 OK INFO: 10.254.254.3:54356 - GET / HTTP/1.1 404 Not Found INFO: 10.254.254.3:54356 - GET / HTTP/1.1 404 Not Found INFO: 10.254.254.3:54356 - GET / HTTP/1.1 404 Not Found INFO: 10.254.254.3:54351 - OPTIONS /api/query HTTP/1.1 200 OK INFO: 10.254.254.3:54351 - POST /api/query HTTP/1.1 200 OK五、开放API安装api依赖[rootlightrag LightRAG]# source venv/bin/activate (venv) [rootlightrag LightRAG]# pip install lightrag-hku[api] fastapi uvicorn python-multipart python-docx官方自带api服务启动# 进入LightRAG根目录 cd /root/LightRAG # 启动官方API服务加载data目录文档 python -m lightrag.api.lightrag_server --host 0.0.0.0 --port 9633 --working-dir ./data报错 storage[embedding_dim] self.embedding_dim AssertionError: Embedding dim mismatch, expected: 1024, but loaded: 768 解决 删除旧的向量库图谱缓存 # 只删向量库报错根源 rm -rf ./data/vdb_*.json # 只删图谱缓存 rm -f ./data/graph_chunk_entity_relation.graphml # 删除 kv 缓存 rm -f ./data/kv_*.json # 重新启动 nohup python -m lightrag.api.lightrag_server --host 0.0.0.0 --port 9633 --working-dir ./data lightrag.log 21 Starting Uvicorn server in single-process mode on 0.0.0.0:9633 INFO: Started server process [1911007] INFO: Waiting for application startup. INFO: [] Process 1911007 KV load full_docs with 0 records INFO: [] Process 1911007 KV load text_chunks with 0 records INFO: [] Process 1911007 KV load full_entities with 0 records INFO: [] Process 1911007 KV load full_relations with 0 records INFO: [] Process 1911007 KV load entity_chunks with 0 records INFO: [] Process 1911007 KV load relation_chunks with 0 records INFO: [] Process 1911007 KV load llm_response_cache with 0 records INFO: [] Process 1911007 doc status load doc_status with 0 records Server is ready to accept connections! INFO: Application startup complete. INFO: Uvicorn running on http://0.0.0.0:9633 (Press CTRLC to quit) 访问http://10.10.100.25:9633/docs可打开自动生成的Swagger接口文档直接在线调试所有接口。目前可被其他系统对接可创建文档可问答可吐图谱问题lightrag强制使用mxbai-embed-large模型但当前并没有所以需要下载[rootlightrag ~]# ollama pull mxbai-embed-large [rootlightrag ~]# ollama pull qwen2.5:0.5b修改环境变量(venv) [rootlightrag LightRAG]# cp env.example .env (venv) [rootlightrag LightRAG]# vi .env LLM_TYPEollama OLLAMA_API_BASEhttp://127.0.0.1:11434/v1 LLM_MODELqwen2.5:0.5b EMBEDDING_MODELmxbai-embed-large # 存储 STORAGE_DIR./data # 核心把超时时间调到最大 EMBEDDING_TIMEOUT600 LLM_TIMEOUT600 MAX_WORKERS1 ASYNC_TIMEOUT600重启服务[rootlightrag data]# pkill -f ollama [rootlightrag data]# nohup ollama serve /dev/null 21 [1] 1918038 (venv) [rootlightrag LightRAG]# rm -rf data/ (venv) [rootlightrag LightRAG]# mkdir -p data (venv) [rootlightrag LightRAG]# pkill -f lightrag (venv) [rootlightrag LightRAG]# nohup python -m lightrag.api.lightrag_server --host 0.0.0.0 --port 9633 --working-dir ./data lightrag.log 21 测试1(venv) [rootlightrag LightRAG]# curl -X POST http://127.0.0.1:9633/documents/text \ -H Content-Type: application/json \ -d {text:员工手册上班时间9:00-18:00午休1小时请假需要提前一天申请。} (venv) [rootlightrag LightRAG]# curl -X POST http://127.0.0.1:9633/query -H Content-Type:application/json -d {query:上班时间是几点,mode:naive,only_need_context:false,stream:false} {response:下班时间是几点,references:[]}(venv) [rootlightrag LightRAG]# curl -X POST http://127.0.0.1:9633/querry:上班,mode:naive,only_need_context:false,stream:false} {response:是的用户询问是否上班了。请问您目前的工作地点或计划工作的时间是什么时候呢,references:[]}(venv) [rootry:午休几点,mode:naive,only_need_context:false,stream:false}lication/json -d {quer {response:Document Chunk 2 提供了答案“上班时间9:00-18:00午休1小时请假需要提前一天申请。”,references:[]}(venvry:请假需要提前多久申请,mode:naive,only_need_context:false,stream:false}ation/json -d {quer {response:员工手册上班时间9:00-18:00午休1小时请假需要提前一天申请。,references:[]}(venv) [rootlightrag Lighry:上班时间,mode:naive,only_need_context:false,stream:false}r {response:是的上班时间是从9:00到18:00。请提前一天申请休假。,references:[]}(venv) [rootlightrag LightRAG]#六、对外api服务方式适用场景说明直接调用 RESTful API通用系统对接如你的业务后端、脚本或任何支持 HTTP 请求的服务。通过发送POST请求到 LightRAG 服务的特定端口如http://your-server:9633来操作。通过 MCP 协议需要将 LightRAG 作为工具集成到支持 MCP 的 AI 应用如 Claude Desktop 等。通过 MCP 服务器作为中间件提供更标准化的工具接口适合 AI 智能体场景 -1-2。1、restful直接发送post请求到端口例如curl -X POST http://127.0.0.1:9633/documents/text \ -H Content-Type: application/json \ -d {text:员工手册上班时间9:00-18:00午休1小时请假需要提前一天申请。}mcp协议2、mcp┌─────────────────────────────────────────────────────────────────────────────┐ │ Windows 本地 │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ Claude Code │ │ │ │ (MCP 客户端 - HTTP 模式) │ │ │ └─────────────────────────────────┬───────────────────────────────────┘ │ │ │ HTTP 请求 │ │ ▼ http://10.10.100.25:3000/mcp │ └────────────────────────────────────┼────────────────────────────────────────┘ │ │ 网络直连同一内网 ▼ ┌─────────────────────────────────────────────────────────────────────────────┐ │ Linux 服务器 (10.10.100.25) │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ mcp-proxy (端口 3000) │ │ │ │ HTTP → stdio 桥接服务 │ │ │ └─────────────────────────────────┬───────────────────────────────────┘ │ │ │ stdio 通信 │ │ ▼ │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ mcp-lightrag (stdio 模式) │ │ │ │ MCP 服务端 │ │ │ └─────────────────────────────────┬───────────────────────────────────┘ │ │ │ HTTP API 调用 │ │ ▼ http://localhost:9633 │ │ ┌─────────────────────────────────────────────────────────────────────┐ │ │ │ LightRAG Server (端口 9633) │ │ │ │ 知识库服务 │ │ │ └─────────────────────────────────────────────────────────────────────┘ │ └─────────────────────────────────────────────────────────────────────────────┘1、各组件说明组件运行位置端口作用Claude CodeWindows-MCP 客户端发起查询请求mcp-proxyLinux3000HTTP → stdio 桥接器mcp-lightragLinux- (stdio)MCP 服务端处理协议请求LightRAG ServerLinux9633实际的知识库 API 服务在 Linux 服务器上启动一个 MCP 服务暴露 LightRAG 的 HTTP API在 Windows 本地通过 Claude Code 命令添加这个远程 MCP 服务地址2、服务器配置# 1. 进入 LightRAG 的虚拟环境 cd /root/LightRAG source venv/bin/activate # 2. 启动 LightRAG API 服务后台运行 nohup python -m lightrag.api.lightrag_server \ --host 0.0.0.0 \ --port 9633 \ --working-dir ./data \ lightrag.log 21 # 3. 安装 mcp 库和 fastmcpHTTP 传输支持 pip install mcp fastmcp pip install mcp-lightrag # 4. 启动mcp桥接服务 venv) [rootlightrag LightRAG]# nohup npx mcp-proxy --port 3000 --host 0.0.0.0 -- /root/LightRAG/venv/bin/mcp-lightrag --host localhost --port 9633 mcp-proxy.log 21 # 5. 验证服务状态 ss -tlnp | grep 3000 LISTEN 0 511 0.0.0.0:3000 0.0.0.0:* users:((node,pid1979784,fd21)) curl http://localhost:3000/mcp No sessionId(venv) 3、windows配置编辑C:\Users\Administrator\.claude.json添加 MCP 服务器配置{ mcpServers: { lightrag: { type: http, url: http://10.10.100.25:3000/mcp } }, enabledMcpjsonServers: [lightrag] }打开powershell进入claude code╭─── Claude Code v2.1.62 ──────────────────────────────────────────────────────────────────────────────────────────────╮│ │ Tips for getting started ││ Welcome back! │ Run /init to create a CLAUDE.md file with instructions for Claude ││ │ Note: You have launched claude in your home directory. For the bes…││ │ ─────────────────────────────────────────────────────────────────── ││ ▐▛███▜▌ │ Recent activity ││ ▝▜█████▛▘ │ No recent activity ││ ▘▘ ▝▝ │ ││ MiniMax-M2.5-highspeed · API Usage Billing │ ││ C:\Users\Administrator │ │╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯/model to try Opus 4.6/mcp ╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮│ Lightrag MCP Server ││ ││ Status: √ connected ││ Auth: √ authenticated ││ URL: http://10.10.100.25:3000/mcp ││ Config location: C:\Users\Administrator.claude.json ││ Capabilities: tools ││ Tools: 18 tools ││ ncel ││ 1. View tools ││ 2. Re-authenticate ││ 3. Clear authentication ││ 4. Reconnect ││ 5. Disable4、测试帮我查询lightrag知识库有什么文档 · Incubating… ● Tool use● lightrag - list_all_docs (MCP)P) ●⎿ Running…c he system. WARNING: Can be slow if there are many documents. Use ⎿ { status: success, T response: DocsStatusesResponse(statusesDocsStatusesResponseStatuses(additional_properties{processed:… 23 lines (ctrlo to expand) ● 知识库中有 4 个文档其中包含转正条件的是 员工手册/试用期管理 相关的文档。让我查询具体内容。 Tool uselightrag - query_knowledge_graph (MCP)(limit:o5,tprompt:条转正条件是什么试用期考核的评分标准是什么) ●⎿ Running…k o u r on ⎿ { status: error, response: null,… 2 lines (ctrlo to expand) ●EElightrag - query_knowledge_graph (MCP)(prompt: 转正条件是什么试用期考核的评分标准是什么)●⎿ Running… ⎿ {status: error, T response: null, … 2 lines (ctrlo to expand) ●F知识库中已有关于员工手册的信息。根据文档内容转正条件如下试用期约定及管理1. 合同约定公司与员工签订劳动合同时可约定试用期具体以劳动合同为准。 2. 试用期要求员工应严格遵守公司规章制度按录用条件和岗位职责完成工作。部门负责人有权随时考核评估员工是否符合录用条件。 2. 考核内容试用期考核主要包括三个维度 - 工作能力考核 - 工作态度考核 - 工作业绩考核各岗位具体考核指标、权重与衡量标准以岗位要求为准4. 试用期考核流程主要为中期考核和转正考核 - 中期考核满分100分部门考核得分80分以上为合格 - 转正考核需达到转正标准 5. 转正条件总结员工需通过试用期中期考核和转正考核满足录用条件后方可转正。知识库中共有 4份文档员工手册、行政管理制度、公司管理制度、试用期约定及管理2026-04-21更新。通过网盘分享的文件LightRAG链接: https://pan.baidu.com/s/14fL6t-ph9PJJdfxSdKaqRA?pwdnegx 提取码: negx--来自百度网盘超级会员v10的分享