yangdx
commited on
Commit
·
11c7a1e
1
Parent(s):
721ab34
Add chinese version of README
Browse files- Add introduction of graph visualization in LightRAG Server
- README-zh.md +1380 -0
- README.assets/b2aaf634151b4706892693ffb43d9093.png +3 -0
- README.assets/iShot_2025-03-23_12.40.08.png +3 -0
- README.md +54 -225
- lightrag/api/README-zh.md +559 -0
README-zh.md
CHANGED
@@ -0,0 +1,1380 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# LightRAG: Simple and Fast Retrieval-Augmented Generation
|
2 |
+
|
3 |
+
<img src="./README.assets/b2aaf634151b4706892693ffb43d9093.png" width="800" alt="LightRAG Diagram">
|
4 |
+
|
5 |
+
## 🎉 新闻
|
6 |
+
|
7 |
+
- [X] [2025.03.18]🎯📢LightRAG现已支持引文功能。
|
8 |
+
- [X] [2025.02.05]🎯📢我们团队发布了[VideoRAG](https://github.com/HKUDS/VideoRAG),用于理解超长上下文视频。
|
9 |
+
- [X] [2025.01.13]🎯📢我们团队发布了[MiniRAG](https://github.com/HKUDS/MiniRAG),使用小型模型简化RAG。
|
10 |
+
- [X] [2025.01.06]🎯📢现在您可以[使用PostgreSQL进行存储](#using-postgresql-for-storage)。
|
11 |
+
- [X] [2024.12.31]🎯📢LightRAG现在支持[通过文档ID删除](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#delete)。
|
12 |
+
- [X] [2024.11.25]🎯📢LightRAG现在支持无缝集成[自定义知识图谱](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#insert-custom-kg),使用户能够用自己的领域专业知识增强系统。
|
13 |
+
- [X] [2024.11.19]🎯📢LightRAG的综合指南现已在[LearnOpenCV](https://learnopencv.com/lightrag)上发布。非常感谢博客作者。
|
14 |
+
- [X] [2024.11.12]🎯📢LightRAG现在支持[Oracle Database 23ai的所有存储类型(KV、向量和图)](https://github.com/HKUDS/LightRAG/blob/main/examples/lightrag_oracle_demo.py)。
|
15 |
+
- [X] [2024.11.11]🎯📢LightRAG现在支持[通过实体名称删除实体](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#delete)。
|
16 |
+
- [X] [2024.11.09]🎯📢推出[LightRAG Gui](https://lightrag-gui.streamlit.app),允许您插入、查询、可视化和下载LightRAG知识。
|
17 |
+
- [X] [2024.11.04]🎯📢现在您可以[使用Neo4J进行存储](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#using-neo4j-for-storage)。
|
18 |
+
- [X] [2024.10.29]🎯📢LightRAG现在通过`textract`支持多种文件类型,包括PDF、DOC、PPT和CSV。
|
19 |
+
- [X] [2024.10.20]🎯📢我们为LightRAG添加了一个新功能:图形可视化。
|
20 |
+
- [X] [2024.10.18]🎯📢我们添加了[LightRAG介绍视频](https://youtu.be/oageL-1I0GE)的链接。感谢作者!
|
21 |
+
- [X] [2024.10.17]🎯📢我们创建了一个[Discord频道](https://discord.gg/yF2MmDJyGJ)!欢迎加入分享和讨论!🎉🎉
|
22 |
+
- [X] [2024.10.16]🎯📢LightRAG现在支持[Ollama模型](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
|
23 |
+
- [X] [2024.10.15]🎯📢LightRAG现在支持[Hugging Face模型](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
|
24 |
+
|
25 |
+
<details>
|
26 |
+
<summary style="font-size: 1.4em; font-weight: bold; cursor: pointer; display: list-item;">
|
27 |
+
算法流程图
|
28 |
+
</summary>
|
29 |
+
|
30 |
+

|
31 |
+
*图1:LightRAG索引流程图 - 图片来源:[Source](https://learnopencv.com/lightrag/)*
|
32 |
+

|
33 |
+
*图2:LightRAG检索和查询流程图 - 图片来源:[Source](https://learnopencv.com/lightrag/)*
|
34 |
+
|
35 |
+
</details>
|
36 |
+
|
37 |
+
## 安装
|
38 |
+
|
39 |
+
### 安装LightRAG核心
|
40 |
+
|
41 |
+
* 从源代码安装(推荐)
|
42 |
+
|
43 |
+
```bash
|
44 |
+
cd LightRAG
|
45 |
+
pip install -e .
|
46 |
+
```
|
47 |
+
|
48 |
+
* 从PyPI安装
|
49 |
+
|
50 |
+
```bash
|
51 |
+
pip install lightrag-hku
|
52 |
+
```
|
53 |
+
|
54 |
+
### 安装LightRAG服务器
|
55 |
+
|
56 |
+
LightRAG服务器旨在提供Web UI和API支持。Web UI便于文档索引、知识图谱探索和简单的RAG查询界面。LightRAG服务器还提供兼容Ollama的接口,旨在将LightRAG模拟为Ollama聊天模型。这使得AI聊天机器人(如Open WebUI)可以轻松访问LightRAG。
|
57 |
+
|
58 |
+
* 从PyPI安装
|
59 |
+
|
60 |
+
```bash
|
61 |
+
pip install "lightrag-hku[api]"
|
62 |
+
```
|
63 |
+
|
64 |
+
* 从源代码安装
|
65 |
+
|
66 |
+
```bash
|
67 |
+
# 如有必要,创建Python虚拟环境
|
68 |
+
# 以可编辑模式安装并支持API
|
69 |
+
pip install -e ".[api]"
|
70 |
+
```
|
71 |
+
|
72 |
+
**有关LightRAG服务器的更多信息,请参阅[LightRAG服务器](./lightrag/api/README.md)。**
|
73 |
+
|
74 |
+
## 快速开始
|
75 |
+
|
76 |
+
* [视频演示](https://www.youtube.com/watch?v=g21royNJ4fw)展示如何在本地运行LightRAG。
|
77 |
+
* 所有代码都可以在`examples`中找到。
|
78 |
+
* 如果使用OpenAI模型,请在环境中设置OpenAI API密钥:`export OPENAI_API_KEY="sk-..."`。
|
79 |
+
* 下载演示文本"狄更斯的圣诞颂歌":
|
80 |
+
|
81 |
+
```bash
|
82 |
+
curl https://raw.githubusercontent.com/gusye1234/nano-graphrag/main/tests/mock_data.txt > ./book.txt
|
83 |
+
```
|
84 |
+
|
85 |
+
## 查询
|
86 |
+
|
87 |
+
使用以下Python代码片段(在脚本中)初始化LightRAG并执行查询:
|
88 |
+
|
89 |
+
```python
|
90 |
+
import os
|
91 |
+
import asyncio
|
92 |
+
from lightrag import LightRAG, QueryParam
|
93 |
+
from lightrag.llm.openai import gpt_4o_mini_complete, gpt_4o_complete, openai_embed
|
94 |
+
from lightrag.kg.shared_storage import initialize_pipeline_status
|
95 |
+
from lightrag.utils import setup_logger
|
96 |
+
|
97 |
+
setup_logger("lightrag", level="INFO")
|
98 |
+
|
99 |
+
async def initialize_rag():
|
100 |
+
rag = LightRAG(
|
101 |
+
working_dir="your/path",
|
102 |
+
embedding_func=openai_embed,
|
103 |
+
llm_model_func=gpt_4o_mini_complete
|
104 |
+
)
|
105 |
+
|
106 |
+
await rag.initialize_storages()
|
107 |
+
await initialize_pipeline_status()
|
108 |
+
|
109 |
+
return rag
|
110 |
+
|
111 |
+
def main():
|
112 |
+
# 初始化RAG实例
|
113 |
+
rag = asyncio.run(initialize_rag())
|
114 |
+
# 插入文本
|
115 |
+
rag.insert("Your text")
|
116 |
+
|
117 |
+
# 执行朴素搜索
|
118 |
+
mode="naive"
|
119 |
+
# 执行本地搜索
|
120 |
+
mode="local"
|
121 |
+
# 执行全局搜索
|
122 |
+
mode="global"
|
123 |
+
# 执行混合搜索
|
124 |
+
mode="hybrid"
|
125 |
+
# 混合模式集成知识图谱和向量检索
|
126 |
+
mode="mix"
|
127 |
+
|
128 |
+
rag.query(
|
129 |
+
"这个故事的主要主题是什么?",
|
130 |
+
param=QueryParam(mode=mode)
|
131 |
+
)
|
132 |
+
|
133 |
+
if __name__ == "__main__":
|
134 |
+
main()
|
135 |
+
```
|
136 |
+
|
137 |
+
### 查询参数
|
138 |
+
|
139 |
+
```python
|
140 |
+
class QueryParam:
|
141 |
+
mode: Literal["local", "global", "hybrid", "naive", "mix"] = "global"
|
142 |
+
"""指定检索模式:
|
143 |
+
- "local":专注于上下文相关信息。
|
144 |
+
- "global":利用全局知识。
|
145 |
+
- "hybrid":结合本地和全局检索方法。
|
146 |
+
- "naive":执行基本搜索,不使用高级技术。
|
147 |
+
- "mix":集成知识图谱和向量检索。混合模式结合知识图谱和向量搜索:
|
148 |
+
- 同时使用结构化(KG)和非结构化(向量)信息
|
149 |
+
- 通过分析关系和上下文提供全面的答案
|
150 |
+
- 通过HTML img标签支持图像内容
|
151 |
+
- 允许通过top_k参数控制检索深度
|
152 |
+
"""
|
153 |
+
only_need_context: bool = False
|
154 |
+
"""如果为True,仅返回检索到的上下文而不生成响应。"""
|
155 |
+
response_type: str = "Multiple Paragraphs"
|
156 |
+
"""定义响应格式。示例:'Multiple Paragraphs'(多段落), 'Single Paragraph'(单段落), 'Bullet Points'(要点列表)。"""
|
157 |
+
top_k: int = 60
|
158 |
+
"""要检索的顶部项目数量。在'local'模式下代表实体,在'global'模式下代表关系。"""
|
159 |
+
max_token_for_text_unit: int = 4000
|
160 |
+
"""每个检索文本块允许的最大令牌数。"""
|
161 |
+
max_token_for_global_context: int = 4000
|
162 |
+
"""全局检索中关系描述的最大令牌分配。"""
|
163 |
+
max_token_for_local_context: int = 4000
|
164 |
+
"""本地检索中实体描述的最大令牌分配。"""
|
165 |
+
ids: list[str] | None = None # 仅支持PG向量数据库
|
166 |
+
"""用于过滤RAG的ID列表。"""
|
167 |
+
...
|
168 |
+
```
|
169 |
+
|
170 |
+
> top_k的默认值可以通过环境变量TOP_K更改。
|
171 |
+
|
172 |
+
<details>
|
173 |
+
<summary> <b>使用类OpenAI的API</b> </summary>
|
174 |
+
|
175 |
+
* LightRAG还支持类OpenAI的聊天/嵌入API:
|
176 |
+
|
177 |
+
```python
|
178 |
+
async def llm_model_func(
|
179 |
+
prompt, system_prompt=None, history_messages=[], keyword_extraction=False, **kwargs
|
180 |
+
) -> str:
|
181 |
+
return await openai_complete_if_cache(
|
182 |
+
"solar-mini",
|
183 |
+
prompt,
|
184 |
+
system_prompt=system_prompt,
|
185 |
+
history_messages=history_messages,
|
186 |
+
api_key=os.getenv("UPSTAGE_API_KEY"),
|
187 |
+
base_url="https://api.upstage.ai/v1/solar",
|
188 |
+
**kwargs
|
189 |
+
)
|
190 |
+
|
191 |
+
async def embedding_func(texts: list[str]) -> np.ndarray:
|
192 |
+
return await openai_embed(
|
193 |
+
texts,
|
194 |
+
model="solar-embedding-1-large-query",
|
195 |
+
api_key=os.getenv("UPSTAGE_API_KEY"),
|
196 |
+
base_url="https://api.upstage.ai/v1/solar"
|
197 |
+
)
|
198 |
+
|
199 |
+
async def initialize_rag():
|
200 |
+
rag = LightRAG(
|
201 |
+
working_dir=WORKING_DIR,
|
202 |
+
llm_model_func=llm_model_func,
|
203 |
+
embedding_func=EmbeddingFunc(
|
204 |
+
embedding_dim=4096,
|
205 |
+
max_token_size=8192,
|
206 |
+
func=embedding_func
|
207 |
+
)
|
208 |
+
)
|
209 |
+
|
210 |
+
await rag.initialize_storages()
|
211 |
+
await initialize_pipeline_status()
|
212 |
+
|
213 |
+
return rag
|
214 |
+
```
|
215 |
+
|
216 |
+
</details>
|
217 |
+
|
218 |
+
<details>
|
219 |
+
<summary> <b>使用Hugging Face模型</b> </summary>
|
220 |
+
|
221 |
+
* 如果您想使用Hugging Face模型,只需要按如下方式设置LightRAG:
|
222 |
+
|
223 |
+
参见`lightrag_hf_demo.py`
|
224 |
+
|
225 |
+
```python
|
226 |
+
# 使用Hugging Face模型初始化LightRAG
|
227 |
+
rag = LightRAG(
|
228 |
+
working_dir=WORKING_DIR,
|
229 |
+
llm_model_func=hf_model_complete, # 使用Hugging Face模型进行文本生成
|
230 |
+
llm_model_name='meta-llama/Llama-3.1-8B-Instruct', # Hugging Face的模型名称
|
231 |
+
# 使用Hugging Face嵌入函数
|
232 |
+
embedding_func=EmbeddingFunc(
|
233 |
+
embedding_dim=384,
|
234 |
+
max_token_size=5000,
|
235 |
+
func=lambda texts: hf_embed(
|
236 |
+
texts,
|
237 |
+
tokenizer=AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2"),
|
238 |
+
embed_model=AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
|
239 |
+
)
|
240 |
+
),
|
241 |
+
)
|
242 |
+
```
|
243 |
+
|
244 |
+
</details>
|
245 |
+
|
246 |
+
<details>
|
247 |
+
<summary> <b>使用Ollama模型</b> </summary>
|
248 |
+
|
249 |
+
### 概述
|
250 |
+
|
251 |
+
如果您想使用Ollama模型,您需要拉取计划使用的模型和嵌入模型,例如`nomic-embed-text`。
|
252 |
+
|
253 |
+
然后您只需要按如下方式设置LightRAG:
|
254 |
+
|
255 |
+
```python
|
256 |
+
# 使用Ollama模型初始化LightRAG
|
257 |
+
rag = LightRAG(
|
258 |
+
working_dir=WORKING_DIR,
|
259 |
+
llm_model_func=ollama_model_complete, # 使用Ollama模型进行文本生成
|
260 |
+
llm_model_name='your_model_name', # 您的模型名称
|
261 |
+
# 使用Ollama嵌入函数
|
262 |
+
embedding_func=EmbeddingFunc(
|
263 |
+
embedding_dim=768,
|
264 |
+
max_token_size=8192,
|
265 |
+
func=lambda texts: ollama_embed(
|
266 |
+
texts,
|
267 |
+
embed_model="nomic-embed-text"
|
268 |
+
)
|
269 |
+
),
|
270 |
+
)
|
271 |
+
```
|
272 |
+
|
273 |
+
### 增加上下文大小
|
274 |
+
|
275 |
+
为了使LightRAG��常工作,上下文应至少为32k令牌。默认情况下,Ollama模型的上下文大小为8k。您可以通过以下两种方式之一实现这一点:
|
276 |
+
|
277 |
+
#### 在Modelfile中增加`num_ctx`参数。
|
278 |
+
|
279 |
+
1. 拉取模型:
|
280 |
+
|
281 |
+
```bash
|
282 |
+
ollama pull qwen2
|
283 |
+
```
|
284 |
+
|
285 |
+
2. 显示模型文件:
|
286 |
+
|
287 |
+
```bash
|
288 |
+
ollama show --modelfile qwen2 > Modelfile
|
289 |
+
```
|
290 |
+
|
291 |
+
3. 编辑Modelfile,添加以下行:
|
292 |
+
|
293 |
+
```bash
|
294 |
+
PARAMETER num_ctx 32768
|
295 |
+
```
|
296 |
+
|
297 |
+
4. 创建修改后的模型:
|
298 |
+
|
299 |
+
```bash
|
300 |
+
ollama create -f Modelfile qwen2m
|
301 |
+
```
|
302 |
+
|
303 |
+
#### 通过Ollama API设置`num_ctx`。
|
304 |
+
|
305 |
+
您可以使用`llm_model_kwargs`参数配置ollama:
|
306 |
+
|
307 |
+
```python
|
308 |
+
rag = LightRAG(
|
309 |
+
working_dir=WORKING_DIR,
|
310 |
+
llm_model_func=ollama_model_complete, # 使用Ollama模型进行文本生成
|
311 |
+
llm_model_name='your_model_name', # 您的模型名称
|
312 |
+
llm_model_kwargs={"options": {"num_ctx": 32768}},
|
313 |
+
# 使用Ollama嵌入函数
|
314 |
+
embedding_func=EmbeddingFunc(
|
315 |
+
embedding_dim=768,
|
316 |
+
max_token_size=8192,
|
317 |
+
func=lambda texts: ollama_embedding(
|
318 |
+
texts,
|
319 |
+
embed_model="nomic-embed-text"
|
320 |
+
)
|
321 |
+
),
|
322 |
+
)
|
323 |
+
```
|
324 |
+
|
325 |
+
#### 低RAM GPU
|
326 |
+
|
327 |
+
为了在低RAM GPU上运行此实验,您应该选择小型模型并调整上下文窗口(增加上下文会增加内存消耗)。例如,在6Gb RAM的改装挖矿GPU上运行这个ollama示例需要将上下文大小设置为26k,同时使用`gemma2:2b`。它能够在`book.txt`中找到197个实体和19个关系。
|
328 |
+
|
329 |
+
</details>
|
330 |
+
<details>
|
331 |
+
<summary> <b>LlamaIndex</b> </summary>
|
332 |
+
|
333 |
+
LightRAG支持与LlamaIndex集成。
|
334 |
+
|
335 |
+
1. **LlamaIndex** (`llm/llama_index_impl.py`):
|
336 |
+
- 通过LlamaIndex与OpenAI和其他提供商集成
|
337 |
+
- 详细设置和示例请参见[LlamaIndex文档](lightrag/llm/Readme.md)
|
338 |
+
|
339 |
+
### 使用示例
|
340 |
+
|
341 |
+
```python
|
342 |
+
# 使用LlamaIndex直接访问OpenAI
|
343 |
+
import asyncio
|
344 |
+
from lightrag import LightRAG
|
345 |
+
from lightrag.llm.llama_index_impl import llama_index_complete_if_cache, llama_index_embed
|
346 |
+
from llama_index.embeddings.openai import OpenAIEmbedding
|
347 |
+
from llama_index.llms.openai import OpenAI
|
348 |
+
from lightrag.kg.shared_storage import initialize_pipeline_status
|
349 |
+
from lightrag.utils import setup_logger
|
350 |
+
|
351 |
+
# 为LightRAG设置日志处理程序
|
352 |
+
setup_logger("lightrag", level="INFO")
|
353 |
+
|
354 |
+
async def initialize_rag():
|
355 |
+
rag = LightRAG(
|
356 |
+
working_dir="your/path",
|
357 |
+
llm_model_func=llama_index_complete_if_cache, # LlamaIndex兼容的完成函数
|
358 |
+
embedding_func=EmbeddingFunc( # LlamaIndex兼容的嵌入函数
|
359 |
+
embedding_dim=1536,
|
360 |
+
max_token_size=8192,
|
361 |
+
func=lambda texts: llama_index_embed(texts, embed_model=embed_model)
|
362 |
+
),
|
363 |
+
)
|
364 |
+
|
365 |
+
await rag.initialize_storages()
|
366 |
+
await initialize_pipeline_status()
|
367 |
+
|
368 |
+
return rag
|
369 |
+
|
370 |
+
def main():
|
371 |
+
# 初始化RAG实例
|
372 |
+
rag = asyncio.run(initialize_rag())
|
373 |
+
|
374 |
+
with open("./book.txt", "r", encoding="utf-8") as f:
|
375 |
+
rag.insert(f.read())
|
376 |
+
|
377 |
+
# 执行朴素搜索
|
378 |
+
print(
|
379 |
+
rag.query("这个故事的主要主题是什么?", param=QueryParam(mode="naive"))
|
380 |
+
)
|
381 |
+
|
382 |
+
# 执行本地搜索
|
383 |
+
print(
|
384 |
+
rag.query("这个故事的主要主题是什么?", param=QueryParam(mode="local"))
|
385 |
+
)
|
386 |
+
|
387 |
+
# 执行全局搜索
|
388 |
+
print(
|
389 |
+
rag.query("这个故事的主要主题是什么?", param=QueryParam(mode="global"))
|
390 |
+
)
|
391 |
+
|
392 |
+
# 执行混合搜索
|
393 |
+
print(
|
394 |
+
rag.query("这个故事的主要主题是什么?", param=QueryParam(mode="hybrid"))
|
395 |
+
)
|
396 |
+
|
397 |
+
if __name__ == "__main__":
|
398 |
+
main()
|
399 |
+
```
|
400 |
+
|
401 |
+
#### 详细文档和示例,请参见:
|
402 |
+
|
403 |
+
- [LlamaIndex文档](lightrag/llm/Readme.md)
|
404 |
+
- [直接OpenAI示例](examples/lightrag_llamaindex_direct_demo.py)
|
405 |
+
- [LiteLLM代理示例](examples/lightrag_llamaindex_litellm_demo.py)
|
406 |
+
|
407 |
+
</details>
|
408 |
+
<details>
|
409 |
+
<summary> <b>对话历史支持</b> </summary>
|
410 |
+
|
411 |
+
LightRAG现在通过对话历史功能支持多轮对话。以下是使用方法:
|
412 |
+
|
413 |
+
```python
|
414 |
+
# 创建对话历史
|
415 |
+
conversation_history = [
|
416 |
+
{"role": "user", "content": "主角对圣诞节的态度是什么?"},
|
417 |
+
{"role": "assistant", "content": "在故事开始时,埃比尼泽·斯克鲁奇对圣诞节持非常消极的态度..."},
|
418 |
+
{"role": "user", "content": "他的态度是如何改变的?"}
|
419 |
+
]
|
420 |
+
|
421 |
+
# 创建带有对话历史的查询参数
|
422 |
+
query_param = QueryParam(
|
423 |
+
mode="mix", # 或其他模式:"local"、"global"、"hybrid"
|
424 |
+
conversation_history=conversation_history, # 添加对话历史
|
425 |
+
history_turns=3 # 考虑最近的对话轮数
|
426 |
+
)
|
427 |
+
|
428 |
+
# 进行考虑对话历史的查询
|
429 |
+
response = rag.query(
|
430 |
+
"是什么导致了他性格的这种变化?",
|
431 |
+
param=query_param
|
432 |
+
)
|
433 |
+
```
|
434 |
+
|
435 |
+
</details>
|
436 |
+
|
437 |
+
<details>
|
438 |
+
<summary> <b>自定义提示支持</b> </summary>
|
439 |
+
|
440 |
+
LightRAG现在支持自定义提示,以便对系统行为进行精细控制。以下是使用方法:
|
441 |
+
|
442 |
+
```python
|
443 |
+
# 创建查询参数
|
444 |
+
query_param = QueryParam(
|
445 |
+
mode="hybrid", # 或其他模式:"local"、"global"、"hybrid"、"mix"和"naive"
|
446 |
+
)
|
447 |
+
|
448 |
+
# 示例1:使用默认系统提示
|
449 |
+
response_default = rag.query(
|
450 |
+
"可再生能源的主要好处是什么?",
|
451 |
+
param=query_param
|
452 |
+
)
|
453 |
+
print(response_default)
|
454 |
+
|
455 |
+
# 示例2:使用自定义提示
|
456 |
+
custom_prompt = """
|
457 |
+
您是环境科学领域的专家助手。请提供详细且结构化的答案,并附带示例。
|
458 |
+
---对话历史---
|
459 |
+
{history}
|
460 |
+
|
461 |
+
---知识库---
|
462 |
+
{context_data}
|
463 |
+
|
464 |
+
---响应规则---
|
465 |
+
|
466 |
+
- 目标格式和长度:{response_type}
|
467 |
+
"""
|
468 |
+
response_custom = rag.query(
|
469 |
+
"可再生能源的主要好处是什么?",
|
470 |
+
param=query_param,
|
471 |
+
system_prompt=custom_prompt # 传递自定义提示
|
472 |
+
)
|
473 |
+
print(response_custom)
|
474 |
+
```
|
475 |
+
|
476 |
+
</details>
|
477 |
+
|
478 |
+
<details>
|
479 |
+
<summary> <b>独立关键词提取</b> </summary>
|
480 |
+
|
481 |
+
我们引入了新函数`query_with_separate_keyword_extraction`来增强关键词提取功能。该函数将关键词提取过程与用户提示分开,专注于查询以提高提取关键词的相关性。
|
482 |
+
|
483 |
+
##### 工作原理
|
484 |
+
|
485 |
+
该函数将输入分为两部分:
|
486 |
+
|
487 |
+
- `用户查询`
|
488 |
+
- `提示`
|
489 |
+
|
490 |
+
然后仅对`用户查询`执行关键词提取。这种分离确保提取过程是集中和相关的,不受`提示`中任何额外语言的影响。它还允许`提示`纯粹用于响应格式化,保持用户原始问题的意图和清晰度。
|
491 |
+
|
492 |
+
##### 使用示例
|
493 |
+
|
494 |
+
这个`示例`展示了如何为教育内容定制函数,专注于为高年级学生提供详细解释。
|
495 |
+
|
496 |
+
```python
|
497 |
+
rag.query_with_separate_keyword_extraction(
|
498 |
+
query="解释重力定律",
|
499 |
+
prompt="提供适合学习物理的高中生的详细解释。",
|
500 |
+
param=QueryParam(mode="hybrid")
|
501 |
+
)
|
502 |
+
```
|
503 |
+
|
504 |
+
</details>
|
505 |
+
|
506 |
+
<details>
|
507 |
+
<summary> <b>插入自定义KG</b> </summary>
|
508 |
+
|
509 |
+
```python
|
510 |
+
custom_kg = {
|
511 |
+
"chunks": [
|
512 |
+
{
|
513 |
+
"content": "Alice和Bob正在合作进行量子计算研究。",
|
514 |
+
"source_id": "doc-1"
|
515 |
+
}
|
516 |
+
],
|
517 |
+
"entities": [
|
518 |
+
{
|
519 |
+
"entity_name": "Alice",
|
520 |
+
"entity_type": "person",
|
521 |
+
"description": "Alice是一位专门研究量子物理的研究员。",
|
522 |
+
"source_id": "doc-1"
|
523 |
+
},
|
524 |
+
{
|
525 |
+
"entity_name": "Bob",
|
526 |
+
"entity_type": "person",
|
527 |
+
"description": "Bob是一位数学家。",
|
528 |
+
"source_id": "doc-1"
|
529 |
+
},
|
530 |
+
{
|
531 |
+
"entity_name": "量子计算",
|
532 |
+
"entity_type": "technology",
|
533 |
+
"description": "量子计算利用量子力学现象进行计算。",
|
534 |
+
"source_id": "doc-1"
|
535 |
+
}
|
536 |
+
],
|
537 |
+
"relationships": [
|
538 |
+
{
|
539 |
+
"src_id": "Alice",
|
540 |
+
"tgt_id": "Bob",
|
541 |
+
"description": "Alice和Bob是研究伙伴。",
|
542 |
+
"keywords": "合作 研究",
|
543 |
+
"weight": 1.0,
|
544 |
+
"source_id": "doc-1"
|
545 |
+
},
|
546 |
+
{
|
547 |
+
"src_id": "Alice",
|
548 |
+
"tgt_id": "量子计算",
|
549 |
+
"description": "Alice进行量子计算研究。",
|
550 |
+
"keywords": "研究 专业",
|
551 |
+
"weight": 1.0,
|
552 |
+
"source_id": "doc-1"
|
553 |
+
},
|
554 |
+
{
|
555 |
+
"src_id": "Bob",
|
556 |
+
"tgt_id": "量子计算",
|
557 |
+
"description": "Bob研究量子计算。",
|
558 |
+
"keywords": "研究 应用",
|
559 |
+
"weight": 1.0,
|
560 |
+
"source_id": "doc-1"
|
561 |
+
}
|
562 |
+
]
|
563 |
+
}
|
564 |
+
|
565 |
+
rag.insert_custom_kg(custom_kg)
|
566 |
+
```
|
567 |
+
|
568 |
+
</details>
|
569 |
+
|
570 |
+
## 插入
|
571 |
+
|
572 |
+
#### 基本插入
|
573 |
+
|
574 |
+
```python
|
575 |
+
# 基本插入
|
576 |
+
rag.insert("文本")
|
577 |
+
```
|
578 |
+
|
579 |
+
<details>
|
580 |
+
<summary> <b> 批量插入 </b></summary>
|
581 |
+
|
582 |
+
```python
|
583 |
+
# 基本批量插入:一次插入多个文本
|
584 |
+
rag.insert(["文本1", "文本2",...])
|
585 |
+
|
586 |
+
# 带有自定义批量大小配置的批量插入
|
587 |
+
rag = LightRAG(
|
588 |
+
working_dir=WORKING_DIR,
|
589 |
+
addon_params={
|
590 |
+
"insert_batch_size": 4 # 每批处理4个文档
|
591 |
+
}
|
592 |
+
)
|
593 |
+
|
594 |
+
rag.insert(["文本1", "文本2", "文本3", ...]) # 文档将以4个为一批进行处理
|
595 |
+
```
|
596 |
+
|
597 |
+
`addon_params`中的`insert_batch_size`参数控制插入过程中每批处理的文档数量。这对于以下情况很有用:
|
598 |
+
|
599 |
+
- 管理大型文档集合的内存使用
|
600 |
+
- 优化处理速度
|
601 |
+
- 提供更好的进度跟踪
|
602 |
+
- 如果未指定,默认值为10
|
603 |
+
|
604 |
+
</details>
|
605 |
+
|
606 |
+
<details>
|
607 |
+
<summary> <b> 带ID插入 </b></summary>
|
608 |
+
|
609 |
+
如果您想为文档提供自己的ID,文档数量和ID数量必须相同。
|
610 |
+
|
611 |
+
```python
|
612 |
+
# 插入单个文本,并为其提供ID
|
613 |
+
rag.insert("文本1", ids=["文本1的ID"])
|
614 |
+
|
615 |
+
# 插入多个文本,并为它们提供ID
|
616 |
+
rag.insert(["文本1", "文本2",...], ids=["文本1的ID", "文本2的ID"])
|
617 |
+
```
|
618 |
+
|
619 |
+
</details>
|
620 |
+
|
621 |
+
<details>
|
622 |
+
<summary><b>使用管道插入</b></summary>
|
623 |
+
|
624 |
+
`apipeline_enqueue_documents`和`apipeline_process_enqueue_documents`函数允许您对文档进行增量插入到图中。
|
625 |
+
|
626 |
+
这对于需要在后台处理文档的场景很有用,同时仍允许主线程继续执行。
|
627 |
+
|
628 |
+
并使用例程处理新文档。
|
629 |
+
|
630 |
+
```python
|
631 |
+
rag = LightRAG(..)
|
632 |
+
|
633 |
+
await rag.apipeline_enqueue_documents(input)
|
634 |
+
# 您的循环例程
|
635 |
+
await rag.apipeline_process_enqueue_documents(input)
|
636 |
+
```
|
637 |
+
|
638 |
+
</details>
|
639 |
+
|
640 |
+
<details>
|
641 |
+
<summary><b>插入多文件类型支持</b></summary>
|
642 |
+
|
643 |
+
`textract`支持读取TXT、DOCX、PPTX、CSV和PDF等文件类型。
|
644 |
+
|
645 |
+
```python
|
646 |
+
import textract
|
647 |
+
|
648 |
+
file_path = 'TEXT.pdf'
|
649 |
+
text_content = textract.process(file_path)
|
650 |
+
|
651 |
+
rag.insert(text_content.decode('utf-8'))
|
652 |
+
```
|
653 |
+
|
654 |
+
</details>
|
655 |
+
|
656 |
+
<details>
|
657 |
+
<summary><b>引文功能</b></summary>
|
658 |
+
|
659 |
+
通过提供文件路径,系统确保可以将来源追溯到其原始文档。
|
660 |
+
|
661 |
+
```python
|
662 |
+
# 定义文档及其文件路径
|
663 |
+
documents = ["文档内容1", "文档内容2"]
|
664 |
+
file_paths = ["path/to/doc1.txt", "path/to/doc2.txt"]
|
665 |
+
|
666 |
+
# 插入带有文件路径的文档
|
667 |
+
rag.insert(documents, file_paths=file_paths)
|
668 |
+
```
|
669 |
+
|
670 |
+
</details>
|
671 |
+
|
672 |
+
## 存储
|
673 |
+
|
674 |
+
<details>
|
675 |
+
<summary> <b>使用Neo4J进行存储</b> </summary>
|
676 |
+
|
677 |
+
* 对于生产级场景,您很可能想要利用企业级解决方案
|
678 |
+
* 进行KG存储。推荐在Docker中运行Neo4J以进行无缝本地测试。
|
679 |
+
* 参见:https://hub.docker.com/_/neo4j
|
680 |
+
|
681 |
+
```python
|
682 |
+
export NEO4J_URI="neo4j://localhost:7687"
|
683 |
+
export NEO4J_USERNAME="neo4j"
|
684 |
+
export NEO4J_PASSWORD="password"
|
685 |
+
|
686 |
+
# 为LightRAG设置日志记录器
|
687 |
+
setup_logger("lightrag", level="INFO")
|
688 |
+
|
689 |
+
# 当您启动项目时,请确保通过指定kg="Neo4JStorage"来覆盖默认的KG:NetworkX。
|
690 |
+
|
691 |
+
# 注意:默认设置使用NetworkX
|
692 |
+
# 使用Neo4J实现初始化LightRAG。
|
693 |
+
async def initialize_rag():
|
694 |
+
rag = LightRAG(
|
695 |
+
working_dir=WORKING_DIR,
|
696 |
+
llm_model_func=gpt_4o_mini_complete, # 使用gpt_4o_mini_complete LLM模型
|
697 |
+
graph_storage="Neo4JStorage", #<-----------覆盖KG默认值
|
698 |
+
)
|
699 |
+
|
700 |
+
# 初始化数据库连接
|
701 |
+
await rag.initialize_storages()
|
702 |
+
# 初始化文档处理的管道状态
|
703 |
+
await initialize_pipeline_status()
|
704 |
+
|
705 |
+
return rag
|
706 |
+
```
|
707 |
+
|
708 |
+
参见test_neo4j.py获取工作示例。
|
709 |
+
|
710 |
+
</details>
|
711 |
+
|
712 |
+
<details>
|
713 |
+
<summary> <b>使用Faiss进行存储</b> </summary>
|
714 |
+
|
715 |
+
- 安装所需依赖:
|
716 |
+
|
717 |
+
```
|
718 |
+
pip install faiss-cpu
|
719 |
+
```
|
720 |
+
|
721 |
+
如果您有GPU支持,也可以安装`faiss-gpu`。
|
722 |
+
|
723 |
+
- 这里我们使用`sentence-transformers`,但您也可以使用维度为`3072`的`OpenAIEmbedding`模型。
|
724 |
+
|
725 |
+
```python
|
726 |
+
async def embedding_func(texts: list[str]) -> np.ndarray:
|
727 |
+
model = SentenceTransformer('all-MiniLM-L6-v2')
|
728 |
+
embeddings = model.encode(texts, convert_to_numpy=True)
|
729 |
+
return embeddings
|
730 |
+
|
731 |
+
# 使用LLM模型函数和嵌入函数初始化LightRAG
|
732 |
+
rag = LightRAG(
|
733 |
+
working_dir=WORKING_DIR,
|
734 |
+
llm_model_func=llm_model_func,
|
735 |
+
embedding_func=EmbeddingFunc(
|
736 |
+
embedding_dim=384,
|
737 |
+
max_token_size=8192,
|
738 |
+
func=embedding_func,
|
739 |
+
),
|
740 |
+
vector_storage="FaissVectorDBStorage",
|
741 |
+
vector_db_storage_cls_kwargs={
|
742 |
+
"cosine_better_than_threshold": 0.3 # 您期望的阈值
|
743 |
+
}
|
744 |
+
)
|
745 |
+
```
|
746 |
+
|
747 |
+
</details>
|
748 |
+
|
749 |
+
<details>
|
750 |
+
<summary> <b>使用PostgreSQL进行存储</b> </summary>
|
751 |
+
|
752 |
+
对于生产级场景,您很可能想要利用企业级解决方案。PostgreSQL可以为您提供一站式解决方案,作为KV存储、向量数据库(pgvector)和图数据库(apache AGE)。
|
753 |
+
|
754 |
+
* PostgreSQL很轻量,整个二进制发行版包括所有必要的插件可以压缩到40MB:参考[Windows发布版](https://github.com/ShanGor/apache-age-windows/releases/tag/PG17%2Fv1.5.0-rc0),它在Linux/Mac上也很容易安装。
|
755 |
+
* 如果您是初学者并想避免麻烦,推荐使用docker,请从这个镜像开始(请务必阅读概述):https://hub.docker.com/r/shangor/postgres-for-rag
|
756 |
+
* 如何开始?参考:[examples/lightrag_zhipu_postgres_demo.py](https://github.com/HKUDS/LightRAG/blob/main/examples/lightrag_zhipu_postgres_demo.py)
|
757 |
+
* 为AGE创建索引示例:(如有必要,将下面的`dickens`改为您的图名)
|
758 |
+
```sql
|
759 |
+
load 'age';
|
760 |
+
SET search_path = ag_catalog, "$user", public;
|
761 |
+
CREATE INDEX CONCURRENTLY entity_p_idx ON dickens."Entity" (id);
|
762 |
+
CREATE INDEX CONCURRENTLY vertex_p_idx ON dickens."_ag_label_vertex" (id);
|
763 |
+
CREATE INDEX CONCURRENTLY directed_p_idx ON dickens."DIRECTED" (id);
|
764 |
+
CREATE INDEX CONCURRENTLY directed_eid_idx ON dickens."DIRECTED" (end_id);
|
765 |
+
CREATE INDEX CONCURRENTLY directed_sid_idx ON dickens."DIRECTED" (start_id);
|
766 |
+
CREATE INDEX CONCURRENTLY directed_seid_idx ON dickens."DIRECTED" (start_id,end_id);
|
767 |
+
CREATE INDEX CONCURRENTLY edge_p_idx ON dickens."_ag_label_edge" (id);
|
768 |
+
CREATE INDEX CONCURRENTLY edge_sid_idx ON dickens."_ag_label_edge" (start_id);
|
769 |
+
CREATE INDEX CONCURRENTLY edge_eid_idx ON dickens."_ag_label_edge" (end_id);
|
770 |
+
CREATE INDEX CONCURRENTLY edge_seid_idx ON dickens."_ag_label_edge" (start_id,end_id);
|
771 |
+
create INDEX CONCURRENTLY vertex_idx_node_id ON dickens."_ag_label_vertex" (ag_catalog.agtype_access_operator(properties, '"node_id"'::agtype));
|
772 |
+
create INDEX CONCURRENTLY entity_idx_node_id ON dickens."Entity" (ag_catalog.agtype_access_operator(properties, '"node_id"'::agtype));
|
773 |
+
CREATE INDEX CONCURRENTLY entity_node_id_gin_idx ON dickens."Entity" using gin(properties);
|
774 |
+
ALTER TABLE dickens."DIRECTED" CLUSTER ON directed_sid_idx;
|
775 |
+
|
776 |
+
-- 如有必要可以删除
|
777 |
+
drop INDEX entity_p_idx;
|
778 |
+
drop INDEX vertex_p_idx;
|
779 |
+
drop INDEX directed_p_idx;
|
780 |
+
drop INDEX directed_eid_idx;
|
781 |
+
drop INDEX directed_sid_idx;
|
782 |
+
drop INDEX directed_seid_idx;
|
783 |
+
drop INDEX edge_p_idx;
|
784 |
+
drop INDEX edge_sid_idx;
|
785 |
+
drop INDEX edge_eid_idx;
|
786 |
+
drop INDEX edge_seid_idx;
|
787 |
+
drop INDEX vertex_idx_node_id;
|
788 |
+
drop INDEX entity_idx_node_id;
|
789 |
+
drop INDEX entity_node_id_gin_idx;
|
790 |
+
```
|
791 |
+
* Apache AGE的已知问题:发布版本存在以下问题:
|
792 |
+
> 您可能会发现节点/边的属性是空的。
|
793 |
+
> 这是发布版本的已知问题:https://github.com/apache/age/pull/1721
|
794 |
+
>
|
795 |
+
> 您可以从源代码编译AGE来修复它。
|
796 |
+
>
|
797 |
+
|
798 |
+
## 删除
|
799 |
+
|
800 |
+
```python
|
801 |
+
# 删除实体:通过实体名称删除实体
|
802 |
+
rag.delete_by_entity("Project Gutenberg")
|
803 |
+
|
804 |
+
# 删除文档:通过文档ID删除与文档相关的实体和关系
|
805 |
+
rag.delete_by_doc_id("doc_id")
|
806 |
+
```
|
807 |
+
|
808 |
+
## 编辑实体和关系
|
809 |
+
|
810 |
+
LightRAG现在支持全面的知识图谱管理功能,允许您在知识图谱中创建、编辑和删除实体和关系。
|
811 |
+
|
812 |
+
<details>
|
813 |
+
<summary> <b>创建实体和关系</b> </summary>
|
814 |
+
|
815 |
+
```python
|
816 |
+
# 创建新实体
|
817 |
+
entity = rag.create_entity("Google", {
|
818 |
+
"description": "Google是一家专注于互联网相关服务和产品的跨国科技公司。",
|
819 |
+
"entity_type": "company"
|
820 |
+
})
|
821 |
+
|
822 |
+
# 创建另一个实体
|
823 |
+
product = rag.create_entity("Gmail", {
|
824 |
+
"description": "Gmail是由Google开发的电子邮件服务。",
|
825 |
+
"entity_type": "product"
|
826 |
+
})
|
827 |
+
|
828 |
+
# 创建实体之间的关系
|
829 |
+
relation = rag.create_relation("Google", "Gmail", {
|
830 |
+
"description": "Google开发和运营Gmail。",
|
831 |
+
"keywords": "开发 运营 服务",
|
832 |
+
"weight": 2.0
|
833 |
+
})
|
834 |
+
```
|
835 |
+
|
836 |
+
</details>
|
837 |
+
|
838 |
+
<details>
|
839 |
+
<summary> <b>编辑实体和关系</b> </summary>
|
840 |
+
|
841 |
+
```python
|
842 |
+
# 编辑现有实体
|
843 |
+
updated_entity = rag.edit_entity("Google", {
|
844 |
+
"description": "Google是Alphabet Inc.的子公司,成立于1998年。",
|
845 |
+
"entity_type": "tech_company"
|
846 |
+
})
|
847 |
+
|
848 |
+
# 重命名实体(所有关系都会正确迁移)
|
849 |
+
renamed_entity = rag.edit_entity("Gmail", {
|
850 |
+
"entity_name": "Google Mail",
|
851 |
+
"description": "Google Mail(前身为Gmail)是一项电子邮件服务。"
|
852 |
+
})
|
853 |
+
|
854 |
+
# 编辑实体之间的关系
|
855 |
+
updated_relation = rag.edit_relation("Google", "Google Mail", {
|
856 |
+
"description": "Google创建并维护Google Mail服务。",
|
857 |
+
"keywords": "创建 维护 电子邮件服务",
|
858 |
+
"weight": 3.0
|
859 |
+
})
|
860 |
+
```
|
861 |
+
|
862 |
+
</details>
|
863 |
+
|
864 |
+
所有操作都有同步和异步版本。异步版本带有前缀"a"(例如,`acreate_entity`,`aedit_relation`)。
|
865 |
+
|
866 |
+
#### 实体操作
|
867 |
+
|
868 |
+
- **create_entity**:创建具有指定属性的新实体
|
869 |
+
- **edit_entity**:更新现有实体的属性或重命名它
|
870 |
+
|
871 |
+
#### 关系操作
|
872 |
+
|
873 |
+
- **create_relation**:在现有实体之间创建新关系
|
874 |
+
- **edit_relation**:更新现有关系的属性
|
875 |
+
|
876 |
+
这些操作在图数据库和向量数据库组件之间保持数据一致性,确保您的知识图谱保持连贯。
|
877 |
+
|
878 |
+
## 数据导出功能
|
879 |
+
|
880 |
+
## 概述
|
881 |
+
|
882 |
+
LightRAG允许您以各种格式导出知识图谱数据,用于分析、共享和备份目的。系统支持导出实体、关系和关系数据。
|
883 |
+
|
884 |
+
## 导出功能
|
885 |
+
|
886 |
+
### 基本用法
|
887 |
+
|
888 |
+
```python
|
889 |
+
# 基本CSV导出(默认格式)
|
890 |
+
rag.export_data("knowledge_graph.csv")
|
891 |
+
|
892 |
+
# 指定任意格式
|
893 |
+
rag.export_data("output.xlsx", file_format="excel")
|
894 |
+
```
|
895 |
+
|
896 |
+
### 支持的不同文件格式
|
897 |
+
|
898 |
+
```python
|
899 |
+
# 以CSV格式导出数据
|
900 |
+
rag.export_data("graph_data.csv", file_format="csv")
|
901 |
+
|
902 |
+
# 导出数据到Excel表格
|
903 |
+
rag.export_data("graph_data.xlsx", file_format="excel")
|
904 |
+
|
905 |
+
# 以markdown格式导出数据
|
906 |
+
rag.export_data("graph_data.md", file_format="md")
|
907 |
+
|
908 |
+
# 导出数据为文本
|
909 |
+
rag.export_data("graph_data.txt", file_format="txt")
|
910 |
+
```
|
911 |
+
|
912 |
+
## 附加选项
|
913 |
+
|
914 |
+
在导出中包含向量嵌入(可选):
|
915 |
+
|
916 |
+
```python
|
917 |
+
rag.export_data("complete_data.csv", include_vector_data=True)
|
918 |
+
```
|
919 |
+
|
920 |
+
## 导出数据包括
|
921 |
+
|
922 |
+
所有导出包括:
|
923 |
+
|
924 |
+
* 实体信息(名称、ID、元数据)
|
925 |
+
* 关系数据(实体之间的连接)
|
926 |
+
* 来自向量数据库的关系信息
|
927 |
+
|
928 |
+
## 实体合并
|
929 |
+
|
930 |
+
<details>
|
931 |
+
<summary> <b>合并实体及其关系</b> </summary>
|
932 |
+
|
933 |
+
LightRAG现在支持将多个实体合并为单个实体,自动处理所有关系:
|
934 |
+
|
935 |
+
```python
|
936 |
+
# 基本实体合并
|
937 |
+
rag.merge_entities(
|
938 |
+
source_entities=["人工智能", "AI", "机器智能"],
|
939 |
+
target_entity="AI技术"
|
940 |
+
)
|
941 |
+
```
|
942 |
+
|
943 |
+
使用自定义合并策略:
|
944 |
+
|
945 |
+
```python
|
946 |
+
# 为不同字段定义自定义合并策略
|
947 |
+
rag.merge_entities(
|
948 |
+
source_entities=["约翰·史密斯", "史密斯博士", "J·史密斯"],
|
949 |
+
target_entity="约翰·史密斯",
|
950 |
+
merge_strategy={
|
951 |
+
"description": "concatenate", # 组合所有描述
|
952 |
+
"entity_type": "keep_first", # 保留第一个实体的类型
|
953 |
+
"source_id": "join_unique" # 组合所有唯一的源ID
|
954 |
+
}
|
955 |
+
)
|
956 |
+
```
|
957 |
+
|
958 |
+
使用自定义目标实体数据:
|
959 |
+
|
960 |
+
```python
|
961 |
+
# 为合并后的实体指定确切值
|
962 |
+
rag.merge_entities(
|
963 |
+
source_entities=["纽约", "NYC", "大苹果"],
|
964 |
+
target_entity="纽约市",
|
965 |
+
target_entity_data={
|
966 |
+
"entity_type": "LOCATION",
|
967 |
+
"description": "纽约市是美国人口最多的城市。",
|
968 |
+
}
|
969 |
+
)
|
970 |
+
```
|
971 |
+
|
972 |
+
结合两种方法的高级用法:
|
973 |
+
|
974 |
+
```python
|
975 |
+
# 使用策略和自定义数据合并公司实体
|
976 |
+
rag.merge_entities(
|
977 |
+
source_entities=["微软公司", "Microsoft Corporation", "MSFT"],
|
978 |
+
target_entity="微软",
|
979 |
+
merge_strategy={
|
980 |
+
"description": "concatenate", # 组合所有描述
|
981 |
+
"source_id": "join_unique" # 组合源ID
|
982 |
+
},
|
983 |
+
target_entity_data={
|
984 |
+
"entity_type": "ORGANIZATION",
|
985 |
+
}
|
986 |
+
)
|
987 |
+
```
|
988 |
+
|
989 |
+
合并实体时:
|
990 |
+
|
991 |
+
* 所有来自源实体的关系都会重定向到目标实体
|
992 |
+
* 重复的关系会被智能合并
|
993 |
+
* 防止自我关系(循环)
|
994 |
+
* 合并后删除源实体
|
995 |
+
* 保留关系权重和属性
|
996 |
+
|
997 |
+
</details>
|
998 |
+
|
999 |
+
## 缓存
|
1000 |
+
|
1001 |
+
<details>
|
1002 |
+
<summary> <b>清除缓存</b> </summary>
|
1003 |
+
|
1004 |
+
您可以使用不同模式清除LLM响应缓存:
|
1005 |
+
|
1006 |
+
```python
|
1007 |
+
# 清除所有缓存
|
1008 |
+
await rag.aclear_cache()
|
1009 |
+
|
1010 |
+
# 清除本地模式缓存
|
1011 |
+
await rag.aclear_cache(modes=["local"])
|
1012 |
+
|
1013 |
+
# 清除提取缓存
|
1014 |
+
await rag.aclear_cache(modes=["default"])
|
1015 |
+
|
1016 |
+
# 清除多个模式
|
1017 |
+
await rag.aclear_cache(modes=["local", "global", "hybrid"])
|
1018 |
+
|
1019 |
+
# 同步版本
|
1020 |
+
rag.clear_cache(modes=["local"])
|
1021 |
+
```
|
1022 |
+
|
1023 |
+
有效的模式包括:
|
1024 |
+
|
1025 |
+
- `"default"`:提取缓存
|
1026 |
+
- `"naive"`:朴素搜索缓存
|
1027 |
+
- `"local"`:本地搜索缓存
|
1028 |
+
- `"global"`:全局搜索缓存
|
1029 |
+
- `"hybrid"`:混合搜索缓存
|
1030 |
+
- `"mix"`:混合搜索缓存
|
1031 |
+
|
1032 |
+
</details>
|
1033 |
+
|
1034 |
+
## LightRAG初始化参数
|
1035 |
+
|
1036 |
+
<details>
|
1037 |
+
<summary> 参数 </summary>
|
1038 |
+
|
1039 |
+
| **参数** | **类型** | **说明** | **默认值** |
|
1040 |
+
|--------------|----------|-----------------|-------------|
|
1041 |
+
| **working_dir** | `str` | 存储缓存的目录 | `lightrag_cache+timestamp` |
|
1042 |
+
| **kv_storage** | `str` | 文档和文本块的存储类型。支持的类型:`JsonKVStorage`、`OracleKVStorage` | `JsonKVStorage` |
|
1043 |
+
| **vector_storage** | `str` | 嵌入向量的存储类型。支持的类型:`NanoVectorDBStorage`、`OracleVectorDBStorage` | `NanoVectorDBStorage` |
|
1044 |
+
| **graph_storage** | `str` | 图边和节点的存储类型。支持的类型:`NetworkXStorage`、`Neo4JStorage`、`OracleGraphStorage` | `NetworkXStorage` |
|
1045 |
+
| **chunk_token_size** | `int` | 拆分文档时每个块的最大令牌大小 | `1200` |
|
1046 |
+
| **chunk_overlap_token_size** | `int` | 拆分文档时两个块之间的重叠令牌大小 | `100` |
|
1047 |
+
| **tiktoken_model_name** | `str` | 用于计算令牌数的Tiktoken编码器的模型名称 | `gpt-4o-mini` |
|
1048 |
+
| **entity_extract_max_gleaning** | `int` | 实体提取过程中的循环次数,附加历史消息 | `1` |
|
1049 |
+
| **entity_summary_to_max_tokens** | `int` | 每个实体摘要的最大令牌大小 | `500` |
|
1050 |
+
| **node_embedding_algorithm** | `str` | 节点嵌入算法(当前未使用) | `node2vec` |
|
1051 |
+
| **node2vec_params** | `dict` | 节点嵌入的参数 | `{"dimensions": 1536,"num_walks": 10,"walk_length": 40,"window_size": 2,"iterations": 3,"random_seed": 3,}` |
|
1052 |
+
| **embedding_func** | `EmbeddingFunc` | 从文本生成嵌入向量的函数 | `openai_embed` |
|
1053 |
+
| **embedding_batch_num** | `int` | 嵌入过程的最大批量大小(每批发送多个文本) | `32` |
|
1054 |
+
| **embedding_func_max_async** | `int` | 最大并发异步嵌入进程数 | `16` |
|
1055 |
+
| **llm_model_func** | `callable` | LLM生成的函数 | `gpt_4o_mini_complete` |
|
1056 |
+
| **llm_model_name** | `str` | 用于生成的LLM模型名称 | `meta-llama/Llama-3.2-1B-Instruct` |
|
1057 |
+
| **llm_model_max_token_size** | `int` | LLM生成的最大令牌大小(影响实体关系摘要) | `32768`(默认值由环境变量MAX_TOKENS更改) |
|
1058 |
+
| **llm_model_max_async** | `int` | 最大并发异步LLM进程数 | `4`(默认值由环境变量MAX_ASYNC更改) |
|
1059 |
+
| **llm_model_kwargs** | `dict` | LLM生成的附加参数 | |
|
1060 |
+
| **vector_db_storage_cls_kwargs** | `dict` | 向量数据库的附加参数,如设置节点和关系检索的阈值 | cosine_better_than_threshold: 0.2(默认值由环境变量COSINE_THRESHOLD更改) |
|
1061 |
+
| **enable_llm_cache** | `bool` | 如果为`TRUE`,将LLM结果存储在缓存中;重复的提示返回缓存的响应 | `TRUE` |
|
1062 |
+
| **enable_llm_cache_for_entity_extract** | `bool` | 如果为`TRUE`,将实体提取的LLM结果存储在缓存中;适合初学者调试应用程序 | `TRUE` |
|
1063 |
+
| **addon_params** | `dict` | 附加参数,例如`{"example_number": 1, "language": "Simplified Chinese", "entity_types": ["organization", "person", "geo", "event"], "insert_batch_size": 10}`:设置示例限制、输出语言和文档处理的批量大小 | `example_number: 所有示例, language: English, insert_batch_size: 10` |
|
1064 |
+
| **convert_response_to_json_func** | `callable` | 未使用 | `convert_response_to_json` |
|
1065 |
+
| **embedding_cache_config** | `dict` | 问答缓存的配置。包含三个参数:`enabled`:布尔值,启用/禁用缓存查找功能。启用时,系统将在生成新答案之前检查缓存的响应。`similarity_threshold`:浮点值(0-1),相似度阈值。当新问题与缓存问题的相似度超过此阈值时,将直接返回缓存的答案而不调用LLM。`use_llm_check`:布尔值,启用/禁用LLM相似度验证。启用时,在返回缓存答案之前,将使用LLM作为二次检查来验证问题之间的相似度。 | 默认:`{"enabled": False, "similarity_threshold": 0.95, "use_llm_check": False}` |
|
1066 |
+
|
1067 |
+
</details>
|
1068 |
+
|
1069 |
+
## 错误处理
|
1070 |
+
|
1071 |
+
<details>
|
1072 |
+
<summary>点击查看错误处理详情</summary>
|
1073 |
+
|
1074 |
+
API包括全面的错误处理:
|
1075 |
+
|
1076 |
+
- 文件未找到错误(404)
|
1077 |
+
- 处理错误(500)
|
1078 |
+
- 支持多种文件编码(UTF-8和GBK)
|
1079 |
+
|
1080 |
+
</details>
|
1081 |
+
|
1082 |
+
## API
|
1083 |
+
|
1084 |
+
LightRag可以安装API支持,以提供Fast api接口来执行数据上传和索引/Rag操作/重新扫描输入文件夹等。
|
1085 |
+
|
1086 |
+
[LightRag API](lightrag/api/README.md)
|
1087 |
+
|
1088 |
+
## 图形可视化
|
1089 |
+
|
1090 |
+
LightRAG服务器提供全面的知识图谱可视化功能。它支持各种重力布局、节点查询、子图过滤等。**有关LightRAG服务器的更多信息,请参阅[LightRAG服务器](./lightrag/api/README.md)。**
|
1091 |
+
|
1092 |
+

|
1093 |
+
|
1094 |
+
## 评估
|
1095 |
+
|
1096 |
+
### 数据集
|
1097 |
+
|
1098 |
+
LightRAG使用的数据集可以从[TommyChien/UltraDomain](https://huggingface.co/datasets/TommyChien/UltraDomain)下载。
|
1099 |
+
|
1100 |
+
### 生成查询
|
1101 |
+
|
1102 |
+
LightRAG使用以下提示生成高级查询,相应的代码在`example/generate_query.py`中。
|
1103 |
+
|
1104 |
+
<details>
|
1105 |
+
<summary> 提示 </summary>
|
1106 |
+
|
1107 |
+
```python
|
1108 |
+
给定以下数据集描述:
|
1109 |
+
|
1110 |
+
{description}
|
1111 |
+
|
1112 |
+
请识别5个可能会使用此数据集的潜在用户。对于每个用户,列出他们会使用此数据集执行的5个任务。然后,对于每个(用户,任务)组合,生成5个需要对整个数据集有高级理解的问题。
|
1113 |
+
|
1114 |
+
按以下结构输出结果:
|
1115 |
+
- 用户1:[用户描述]
|
1116 |
+
- 任务1:[任务描述]
|
1117 |
+
- 问题1:
|
1118 |
+
- 问题2:
|
1119 |
+
- 问题3:
|
1120 |
+
- 问题4:
|
1121 |
+
- 问题5:
|
1122 |
+
- 任务2:[任务描述]
|
1123 |
+
...
|
1124 |
+
- 任务5:[任务描述]
|
1125 |
+
- 用户2:[用户描述]
|
1126 |
+
...
|
1127 |
+
- 用户5:[用户描述]
|
1128 |
+
...
|
1129 |
+
```
|
1130 |
+
|
1131 |
+
</details>
|
1132 |
+
|
1133 |
+
### 批量评估
|
1134 |
+
|
1135 |
+
为了评估两个RAG系统在高级查询上的性能,LightRAG使用以下提示,具体代码可在`example/batch_eval.py`中找到。
|
1136 |
+
|
1137 |
+
<details>
|
1138 |
+
<summary> 提示 </summary>
|
1139 |
+
|
1140 |
+
```python
|
1141 |
+
---角色---
|
1142 |
+
您是一位专家,负责根据三个标准评估同一问题的两个答案:**全面性**、**多样性**和**赋能性**。
|
1143 |
+
---目标---
|
1144 |
+
您将根据三个标准评估同一问题的两个答案:**全面性**、**多样性**和**赋能性**。
|
1145 |
+
|
1146 |
+
- **全面性**:答案提供了多少细节来涵盖问题的所有方面和细节?
|
1147 |
+
- **多样性**:答案在提供关于问题的不同视角和见解方面有多丰富多样?
|
1148 |
+
- **赋能性**:答案在多大程度上帮助读者理解并对主题做出明智判断?
|
1149 |
+
|
1150 |
+
对于每个标准,选择更好的答案(答案1或答案2)并解释原因。然后,根据这三个类别选择总体赢家。
|
1151 |
+
|
1152 |
+
这是问题:
|
1153 |
+
{query}
|
1154 |
+
|
1155 |
+
这是两个答案:
|
1156 |
+
|
1157 |
+
**答案1:**
|
1158 |
+
{answer1}
|
1159 |
+
|
1160 |
+
**答案2:**
|
1161 |
+
{answer2}
|
1162 |
+
|
1163 |
+
使用上述三个标准评估两个答案,并为每个标准提供详细解释。
|
1164 |
+
|
1165 |
+
以下列JSON格式输出您的评估:
|
1166 |
+
|
1167 |
+
{{
|
1168 |
+
"全面性": {{
|
1169 |
+
"获胜者": "[答案1或答案2]",
|
1170 |
+
"解释": "[在此提供解释]"
|
1171 |
+
}},
|
1172 |
+
"赋能性": {{
|
1173 |
+
"获胜者": "[答案1或答案2]",
|
1174 |
+
"解释": "[在此提供解释]"
|
1175 |
+
}},
|
1176 |
+
"总体获胜者": {{
|
1177 |
+
"获胜者": "[答案1或答案2]",
|
1178 |
+
"解释": "[根据三个标准总结为什么这个答案是总体获胜者]"
|
1179 |
+
}}
|
1180 |
+
}}
|
1181 |
+
```
|
1182 |
+
|
1183 |
+
</details>
|
1184 |
+
|
1185 |
+
### 总体性能表
|
1186 |
+
|
1187 |
+
| |**农业**| |**计算机科学**| |**法律**| |**混合**| |
|
1188 |
+
|----------------------|---------------|------------|------|------------|---------|------------|-------|------------|
|
1189 |
+
| |NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|
|
1190 |
+
|**全面性**|32.4%|**67.6%**|38.4%|**61.6%**|16.4%|**83.6%**|38.8%|**61.2%**|
|
1191 |
+
|**多样性**|23.6%|**76.4%**|38.0%|**62.0%**|13.6%|**86.4%**|32.4%|**67.6%**|
|
1192 |
+
|**赋能性**|32.4%|**67.6%**|38.8%|**61.2%**|16.4%|**83.6%**|42.8%|**57.2%**|
|
1193 |
+
|**总体**|32.4%|**67.6%**|38.8%|**61.2%**|15.2%|**84.8%**|40.0%|**60.0%**|
|
1194 |
+
| |RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|
|
1195 |
+
|**全面性**|31.6%|**68.4%**|38.8%|**61.2%**|15.2%|**84.8%**|39.2%|**60.8%**|
|
1196 |
+
|**多样性**|29.2%|**70.8%**|39.2%|**60.8%**|11.6%|**88.4%**|30.8%|**69.2%**|
|
1197 |
+
|**赋能性**|31.6%|**68.4%**|36.4%|**63.6%**|15.2%|**84.8%**|42.4%|**57.6%**|
|
1198 |
+
|**总体**|32.4%|**67.6%**|38.0%|**62.0%**|14.4%|**85.6%**|40.0%|**60.0%**|
|
1199 |
+
| |HyDE|**LightRAG**|HyDE|**LightRAG**|HyDE|**LightRAG**|HyDE|**LightRAG**|
|
1200 |
+
|**全面性**|26.0%|**74.0%**|41.6%|**58.4%**|26.8%|**73.2%**|40.4%|**59.6%**|
|
1201 |
+
|**多样性**|24.0%|**76.0%**|38.8%|**61.2%**|20.0%|**80.0%**|32.4%|**67.6%**|
|
1202 |
+
|**赋能性**|25.2%|**74.8%**|40.8%|**59.2%**|26.0%|**74.0%**|46.0%|**54.0%**|
|
1203 |
+
|**总体**|24.8%|**75.2%**|41.6%|**58.4%**|26.4%|**73.6%**|42.4%|**57.6%**|
|
1204 |
+
| |GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|
|
1205 |
+
|**全面性**|45.6%|**54.4%**|48.4%|**51.6%**|48.4%|**51.6%**|**50.4%**|49.6%|
|
1206 |
+
|**多样性**|22.8%|**77.2%**|40.8%|**59.2%**|26.4%|**73.6%**|36.0%|**64.0%**|
|
1207 |
+
|**赋能性**|41.2%|**58.8%**|45.2%|**54.8%**|43.6%|**56.4%**|**50.8%**|49.2%|
|
1208 |
+
|**总体**|45.2%|**54.8%**|48.0%|**52.0%**|47.2%|**52.8%**|**50.4%**|49.6%|
|
1209 |
+
|
1210 |
+
## 复现
|
1211 |
+
|
1212 |
+
所有代码都可以在`./reproduce`目录中找到。
|
1213 |
+
|
1214 |
+
### 步骤0 提取唯一上下文
|
1215 |
+
|
1216 |
+
首先,我们需要提取数据集中的唯一上下文。
|
1217 |
+
|
1218 |
+
<details>
|
1219 |
+
<summary> 代码 </summary>
|
1220 |
+
|
1221 |
+
```python
|
1222 |
+
def extract_unique_contexts(input_directory, output_directory):
|
1223 |
+
|
1224 |
+
os.makedirs(output_directory, exist_ok=True)
|
1225 |
+
|
1226 |
+
jsonl_files = glob.glob(os.path.join(input_directory, '*.jsonl'))
|
1227 |
+
print(f"找到{len(jsonl_files)}个JSONL文件。")
|
1228 |
+
|
1229 |
+
for file_path in jsonl_files:
|
1230 |
+
filename = os.path.basename(file_path)
|
1231 |
+
name, ext = os.path.splitext(filename)
|
1232 |
+
output_filename = f"{name}_unique_contexts.json"
|
1233 |
+
output_path = os.path.join(output_directory, output_filename)
|
1234 |
+
|
1235 |
+
unique_contexts_dict = {}
|
1236 |
+
|
1237 |
+
print(f"处理文件:{filename}")
|
1238 |
+
|
1239 |
+
try:
|
1240 |
+
with open(file_path, 'r', encoding='utf-8') as infile:
|
1241 |
+
for line_number, line in enumerate(infile, start=1):
|
1242 |
+
line = line.strip()
|
1243 |
+
if not line:
|
1244 |
+
continue
|
1245 |
+
try:
|
1246 |
+
json_obj = json.loads(line)
|
1247 |
+
context = json_obj.get('context')
|
1248 |
+
if context and context not in unique_contexts_dict:
|
1249 |
+
unique_contexts_dict[context] = None
|
1250 |
+
except json.JSONDecodeError as e:
|
1251 |
+
print(f"文件{filename}第{line_number}行JSON解码错误:{e}")
|
1252 |
+
except FileNotFoundError:
|
1253 |
+
print(f"未找到文件:{filename}")
|
1254 |
+
continue
|
1255 |
+
except Exception as e:
|
1256 |
+
print(f"处理文件{filename}时发生错误:{e}")
|
1257 |
+
continue
|
1258 |
+
|
1259 |
+
unique_contexts_list = list(unique_contexts_dict.keys())
|
1260 |
+
print(f"文件{filename}中有{len(unique_contexts_list)}个唯一的`context`条目。")
|
1261 |
+
|
1262 |
+
try:
|
1263 |
+
with open(output_path, 'w', encoding='utf-8') as outfile:
|
1264 |
+
json.dump(unique_contexts_list, outfile, ensure_ascii=False, indent=4)
|
1265 |
+
print(f"唯一的`context`条目已保存到:{output_filename}")
|
1266 |
+
except Exception as e:
|
1267 |
+
print(f"保存到文件{output_filename}时发生错误:{e}")
|
1268 |
+
|
1269 |
+
print("所有文件已处理完成。")
|
1270 |
+
|
1271 |
+
```
|
1272 |
+
|
1273 |
+
</details>
|
1274 |
+
|
1275 |
+
### 步骤1 插入上下文
|
1276 |
+
|
1277 |
+
对于提取的上下文,我们将它们插入到LightRAG系统中。
|
1278 |
+
|
1279 |
+
<details>
|
1280 |
+
<summary> 代码 </summary>
|
1281 |
+
|
1282 |
+
```python
|
1283 |
+
def insert_text(rag, file_path):
|
1284 |
+
with open(file_path, mode='r') as f:
|
1285 |
+
unique_contexts = json.load(f)
|
1286 |
+
|
1287 |
+
retries = 0
|
1288 |
+
max_retries = 3
|
1289 |
+
while retries < max_retries:
|
1290 |
+
try:
|
1291 |
+
rag.insert(unique_contexts)
|
1292 |
+
break
|
1293 |
+
except Exception as e:
|
1294 |
+
retries += 1
|
1295 |
+
print(f"插入失败,重试({retries}/{max_retries}),错误:{e}")
|
1296 |
+
time.sleep(10)
|
1297 |
+
if retries == max_retries:
|
1298 |
+
print("超过最大重试次数后插入失败")
|
1299 |
+
```
|
1300 |
+
|
1301 |
+
</details>
|
1302 |
+
|
1303 |
+
### 步骤2 生成查询
|
1304 |
+
|
1305 |
+
我们从数据集中每个上下文的前半部分和后半部分提取令牌,然后将它们组合为数据集描述以生成查询。
|
1306 |
+
|
1307 |
+
<details>
|
1308 |
+
<summary> 代码 </summary>
|
1309 |
+
|
1310 |
+
```python
|
1311 |
+
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
|
1312 |
+
|
1313 |
+
def get_summary(context, tot_tokens=2000):
|
1314 |
+
tokens = tokenizer.tokenize(context)
|
1315 |
+
half_tokens = tot_tokens // 2
|
1316 |
+
|
1317 |
+
start_tokens = tokens[1000:1000 + half_tokens]
|
1318 |
+
end_tokens = tokens[-(1000 + half_tokens):1000]
|
1319 |
+
|
1320 |
+
summary_tokens = start_tokens + end_tokens
|
1321 |
+
summary = tokenizer.convert_tokens_to_string(summary_tokens)
|
1322 |
+
|
1323 |
+
return summary
|
1324 |
+
```
|
1325 |
+
|
1326 |
+
</details>
|
1327 |
+
|
1328 |
+
### 步骤3 查询
|
1329 |
+
|
1330 |
+
对于步骤2中生成的查询,我们将提取它们并查询LightRAG。
|
1331 |
+
|
1332 |
+
<details>
|
1333 |
+
<summary> 代码 </summary>
|
1334 |
+
|
1335 |
+
```python
|
1336 |
+
def extract_queries(file_path):
|
1337 |
+
with open(file_path, 'r') as f:
|
1338 |
+
data = f.read()
|
1339 |
+
|
1340 |
+
data = data.replace('**', '')
|
1341 |
+
|
1342 |
+
queries = re.findall(r'- Question \d+: (.+)', data)
|
1343 |
+
|
1344 |
+
return queries
|
1345 |
+
```
|
1346 |
+
|
1347 |
+
</details>
|
1348 |
+
|
1349 |
+
## Star历史
|
1350 |
+
|
1351 |
+
<a href="https://star-history.com/#HKUDS/LightRAG&Date">
|
1352 |
+
<picture>
|
1353 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=HKUDS/LightRAG&type=Date&theme=dark" />
|
1354 |
+
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=HKUDS/LightRAG&type=Date" />
|
1355 |
+
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=HKUDS/LightRAG&type=Date" />
|
1356 |
+
</picture>
|
1357 |
+
</a>
|
1358 |
+
|
1359 |
+
## 贡献
|
1360 |
+
|
1361 |
+
感谢所有贡献者!
|
1362 |
+
|
1363 |
+
<a href="https://github.com/HKUDS/LightRAG/graphs/contributors">
|
1364 |
+
<img src="https://contrib.rocks/image?repo=HKUDS/LightRAG" />
|
1365 |
+
</a>
|
1366 |
+
|
1367 |
+
## 🌟引用
|
1368 |
+
|
1369 |
+
```python
|
1370 |
+
@article{guo2024lightrag,
|
1371 |
+
title={LightRAG: Simple and Fast Retrieval-Augmented Generation},
|
1372 |
+
author={Zirui Guo and Lianghao Xia and Yanhua Yu and Tu Ao and Chao Huang},
|
1373 |
+
year={2024},
|
1374 |
+
eprint={2410.05779},
|
1375 |
+
archivePrefix={arXiv},
|
1376 |
+
primaryClass={cs.IR}
|
1377 |
+
}
|
1378 |
+
```
|
1379 |
+
|
1380 |
+
**感谢您对我们工作的关注!**
|
README.assets/b2aaf634151b4706892693ffb43d9093.png
ADDED
![]() |
Git LFS Details
|
README.assets/iShot_2025-03-23_12.40.08.png
ADDED
![]() |
Git LFS Details
|
README.md
CHANGED
@@ -28,22 +28,10 @@
|
|
28 |
</tr>
|
29 |
</table>
|
30 |
|
31 |
-
<div align="center">
|
32 |
-
This repository hosts the code of LightRAG. The structure of this code is based on <a href="https://github.com/gusye1234/nano-graphrag">nano-graphrag</a>.
|
33 |
-
|
34 |
-
<img src="https://i-blog.csdnimg.cn/direct/b2aaf634151b4706892693ffb43d9093.png" width="800" alt="LightRAG Diagram">
|
35 |
-
</div>
|
36 |
-
</div>
|
37 |
-
</br>
|
38 |
-
|
39 |
-
|
40 |
-
|
41 |
|
|
|
42 |
|
43 |
-
|
44 |
-
<summary style="font-size: 1.4em; font-weight: bold; cursor: pointer; display: list-item;">
|
45 |
-
🎉 News
|
46 |
-
</summary>
|
47 |
|
48 |
- [X] [2025.03.18]🎯📢LightRAG now supports citation functionality.
|
49 |
- [X] [2025.02.05]🎯📢Our team has released [VideoRAG](https://github.com/HKUDS/VideoRAG) understanding extremely long-context videos.
|
@@ -63,8 +51,6 @@ This repository hosts the code of LightRAG. The structure of this code is based
|
|
63 |
- [X] [2024.10.16]🎯📢LightRAG now supports [Ollama models](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
|
64 |
- [X] [2024.10.15]🎯📢LightRAG now supports [Hugging Face models](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
|
65 |
|
66 |
-
</details>
|
67 |
-
|
68 |
<details>
|
69 |
<summary style="font-size: 1.4em; font-weight: bold; cursor: pointer; display: list-item;">
|
70 |
Algorithm Flowchart
|
@@ -779,7 +765,7 @@ For production level scenarios you will most likely want to leverage an enterpri
|
|
779 |
create INDEX CONCURRENTLY entity_idx_node_id ON dickens."Entity" (ag_catalog.agtype_access_operator(properties, '"node_id"'::agtype));
|
780 |
CREATE INDEX CONCURRENTLY entity_node_id_gin_idx ON dickens."Entity" using gin(properties);
|
781 |
ALTER TABLE dickens."DIRECTED" CLUSTER ON directed_sid_idx;
|
782 |
-
|
783 |
-- drop if necessary
|
784 |
drop INDEX entity_p_idx;
|
785 |
drop INDEX vertex_p_idx;
|
@@ -1081,33 +1067,33 @@ Valid modes are:
|
|
1081 |
<details>
|
1082 |
<summary> Parameters </summary>
|
1083 |
|
1084 |
-
| **Parameter**
|
1085 |
-
|
1086 |
-
| **
|
1087 |
-
| **
|
1088 |
-
| **
|
1089 |
-
| **
|
1090 |
-
| **
|
1091 |
-
| **
|
1092 |
-
| **
|
1093 |
-
| **
|
1094 |
-
| **
|
1095 |
-
| **
|
1096 |
-
| **
|
1097 |
-
| **
|
1098 |
-
| **
|
1099 |
-
| **
|
1100 |
-
| **
|
1101 |
-
| **
|
1102 |
-
| **
|
1103 |
-
| **
|
1104 |
-
| **
|
1105 |
-
| **
|
1106 |
-
| **
|
1107 |
-
| **
|
1108 |
-
| **
|
1109 |
-
| **
|
1110 |
-
| **
|
1111 |
|
1112 |
</details>
|
1113 |
|
@@ -1132,166 +1118,9 @@ LightRag can be installed with API support to serve a Fast api interface to perf
|
|
1132 |
|
1133 |
## Graph Visualization
|
1134 |
|
1135 |
-
|
1136 |
-
<summary> <b>Graph visualization with html</b> </summary>
|
1137 |
-
|
1138 |
-
* The following code can be found in `examples/graph_visual_with_html.py`
|
1139 |
-
|
1140 |
-
```python
|
1141 |
-
import networkx as nx
|
1142 |
-
from pyvis.network import Network
|
1143 |
-
|
1144 |
-
# Load the GraphML file
|
1145 |
-
G = nx.read_graphml('./dickens/graph_chunk_entity_relation.graphml')
|
1146 |
-
|
1147 |
-
# Create a Pyvis network
|
1148 |
-
net = Network(notebook=True)
|
1149 |
-
|
1150 |
-
# Convert NetworkX graph to Pyvis network
|
1151 |
-
net.from_nx(G)
|
1152 |
-
|
1153 |
-
# Save and display the network
|
1154 |
-
net.show('knowledge_graph.html')
|
1155 |
-
```
|
1156 |
-
|
1157 |
-
</details>
|
1158 |
-
|
1159 |
-
<details>
|
1160 |
-
<summary> <b>Graph visualization with Neo4</b> </summary>
|
1161 |
-
|
1162 |
-
* The following code can be found in `examples/graph_visual_with_neo4j.py`
|
1163 |
|
1164 |
-
|
1165 |
-
import os
|
1166 |
-
import json
|
1167 |
-
from lightrag.utils import xml_to_json
|
1168 |
-
from neo4j import GraphDatabase
|
1169 |
-
|
1170 |
-
# Constants
|
1171 |
-
WORKING_DIR = "./dickens"
|
1172 |
-
BATCH_SIZE_NODES = 500
|
1173 |
-
BATCH_SIZE_EDGES = 100
|
1174 |
-
|
1175 |
-
# Neo4j connection credentials
|
1176 |
-
NEO4J_URI = "bolt://localhost:7687"
|
1177 |
-
NEO4J_USERNAME = "neo4j"
|
1178 |
-
NEO4J_PASSWORD = "your_password"
|
1179 |
-
|
1180 |
-
def convert_xml_to_json(xml_path, output_path):
|
1181 |
-
"""Converts XML file to JSON and saves the output."""
|
1182 |
-
if not os.path.exists(xml_path):
|
1183 |
-
print(f"Error: File not found - {xml_path}")
|
1184 |
-
return None
|
1185 |
-
|
1186 |
-
json_data = xml_to_json(xml_path)
|
1187 |
-
if json_data:
|
1188 |
-
with open(output_path, 'w', encoding='utf-8') as f:
|
1189 |
-
json.dump(json_data, f, ensure_ascii=False, indent=2)
|
1190 |
-
print(f"JSON file created: {output_path}")
|
1191 |
-
return json_data
|
1192 |
-
else:
|
1193 |
-
print("Failed to create JSON data")
|
1194 |
-
return None
|
1195 |
-
|
1196 |
-
def process_in_batches(tx, query, data, batch_size):
|
1197 |
-
"""Process data in batches and execute the given query."""
|
1198 |
-
for i in range(0, len(data), batch_size):
|
1199 |
-
batch = data[i:i + batch_size]
|
1200 |
-
tx.run(query, {"nodes": batch} if "nodes" in query else {"edges": batch})
|
1201 |
-
|
1202 |
-
def main():
|
1203 |
-
# Paths
|
1204 |
-
xml_file = os.path.join(WORKING_DIR, 'graph_chunk_entity_relation.graphml')
|
1205 |
-
json_file = os.path.join(WORKING_DIR, 'graph_data.json')
|
1206 |
-
|
1207 |
-
# Convert XML to JSON
|
1208 |
-
json_data = convert_xml_to_json(xml_file, json_file)
|
1209 |
-
if json_data is None:
|
1210 |
-
return
|
1211 |
-
|
1212 |
-
# Load nodes and edges
|
1213 |
-
nodes = json_data.get('nodes', [])
|
1214 |
-
edges = json_data.get('edges', [])
|
1215 |
-
|
1216 |
-
# Neo4j queries
|
1217 |
-
create_nodes_query = """
|
1218 |
-
UNWIND $nodes AS node
|
1219 |
-
MERGE (e:Entity {id: node.id})
|
1220 |
-
SET e.entity_type = node.entity_type,
|
1221 |
-
e.description = node.description,
|
1222 |
-
e.source_id = node.source_id,
|
1223 |
-
e.displayName = node.id
|
1224 |
-
REMOVE e:Entity
|
1225 |
-
WITH e, node
|
1226 |
-
CALL apoc.create.addLabels(e, [node.entity_type]) YIELD node AS labeledNode
|
1227 |
-
RETURN count(*)
|
1228 |
-
"""
|
1229 |
-
|
1230 |
-
create_edges_query = """
|
1231 |
-
UNWIND $edges AS edge
|
1232 |
-
MATCH (source {id: edge.source})
|
1233 |
-
MATCH (target {id: edge.target})
|
1234 |
-
WITH source, target, edge,
|
1235 |
-
CASE
|
1236 |
-
WHEN edge.keywords CONTAINS 'lead' THEN 'lead'
|
1237 |
-
WHEN edge.keywords CONTAINS 'participate' THEN 'participate'
|
1238 |
-
WHEN edge.keywords CONTAINS 'uses' THEN 'uses'
|
1239 |
-
WHEN edge.keywords CONTAINS 'located' THEN 'located'
|
1240 |
-
WHEN edge.keywords CONTAINS 'occurs' THEN 'occurs'
|
1241 |
-
ELSE REPLACE(SPLIT(edge.keywords, ',')[0], '\"', '')
|
1242 |
-
END AS relType
|
1243 |
-
CALL apoc.create.relationship(source, relType, {
|
1244 |
-
weight: edge.weight,
|
1245 |
-
description: edge.description,
|
1246 |
-
keywords: edge.keywords,
|
1247 |
-
source_id: edge.source_id
|
1248 |
-
}, target) YIELD rel
|
1249 |
-
RETURN count(*)
|
1250 |
-
"""
|
1251 |
-
|
1252 |
-
set_displayname_and_labels_query = """
|
1253 |
-
MATCH (n)
|
1254 |
-
SET n.displayName = n.id
|
1255 |
-
WITH n
|
1256 |
-
CALL apoc.create.setLabels(n, [n.entity_type]) YIELD node
|
1257 |
-
RETURN count(*)
|
1258 |
-
"""
|
1259 |
-
|
1260 |
-
# Create a Neo4j driver
|
1261 |
-
driver = GraphDatabase.driver(NEO4J_URI, auth=(NEO4J_USERNAME, NEO4J_PASSWORD))
|
1262 |
-
|
1263 |
-
try:
|
1264 |
-
# Execute queries in batches
|
1265 |
-
with driver.session() as session:
|
1266 |
-
# Insert nodes in batches
|
1267 |
-
session.execute_write(process_in_batches, create_nodes_query, nodes, BATCH_SIZE_NODES)
|
1268 |
-
|
1269 |
-
# Insert edges in batches
|
1270 |
-
session.execute_write(process_in_batches, create_edges_query, edges, BATCH_SIZE_EDGES)
|
1271 |
-
|
1272 |
-
# Set displayName and labels
|
1273 |
-
session.run(set_displayname_and_labels_query)
|
1274 |
-
|
1275 |
-
except Exception as e:
|
1276 |
-
print(f"Error occurred: {e}")
|
1277 |
-
|
1278 |
-
finally:
|
1279 |
-
driver.close()
|
1280 |
-
|
1281 |
-
if __name__ == "__main__":
|
1282 |
-
main()
|
1283 |
-
```
|
1284 |
-
|
1285 |
-
</details>
|
1286 |
-
|
1287 |
-
<details>
|
1288 |
-
<summary> <b>Graphml 3d visualizer</b> </summary>
|
1289 |
-
|
1290 |
-
LightRag can be installed with Tools support to add extra tools like the graphml 3d visualizer.
|
1291 |
-
|
1292 |
-
[LightRag Visualizer](lightrag/tools/lightrag_visualizer/README.md)
|
1293 |
-
|
1294 |
-
</details>
|
1295 |
|
1296 |
## Evaluation
|
1297 |
|
@@ -1386,28 +1215,28 @@ Output your evaluation in the following JSON format:
|
|
1386 |
|
1387 |
### Overall Performance Table
|
1388 |
|
1389 |
-
|
|
1390 |
-
|
1391 |
-
|
|
1392 |
-
|
1393 |
-
|
1394 |
-
|
1395 |
-
|
1396 |
-
|
|
1397 |
-
|
1398 |
-
|
1399 |
-
|
1400 |
-
|
1401 |
-
|
|
1402 |
-
|
1403 |
-
|
1404 |
-
|
1405 |
-
|
1406 |
-
|
|
1407 |
-
|
1408 |
-
|
1409 |
-
|
1410 |
-
|
1411 |
|
1412 |
## Reproduce
|
1413 |
|
|
|
28 |
</tr>
|
29 |
</table>
|
30 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
31 |
|
32 |
+
<img src="./README.assets/b2aaf634151b4706892693ffb43d9093.png" width="800" alt="LightRAG Diagram">
|
33 |
|
34 |
+
## 🎉 News
|
|
|
|
|
|
|
35 |
|
36 |
- [X] [2025.03.18]🎯📢LightRAG now supports citation functionality.
|
37 |
- [X] [2025.02.05]🎯📢Our team has released [VideoRAG](https://github.com/HKUDS/VideoRAG) understanding extremely long-context videos.
|
|
|
51 |
- [X] [2024.10.16]🎯📢LightRAG now supports [Ollama models](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
|
52 |
- [X] [2024.10.15]🎯📢LightRAG now supports [Hugging Face models](https://github.com/HKUDS/LightRAG?tab=readme-ov-file#quick-start)!
|
53 |
|
|
|
|
|
54 |
<details>
|
55 |
<summary style="font-size: 1.4em; font-weight: bold; cursor: pointer; display: list-item;">
|
56 |
Algorithm Flowchart
|
|
|
765 |
create INDEX CONCURRENTLY entity_idx_node_id ON dickens."Entity" (ag_catalog.agtype_access_operator(properties, '"node_id"'::agtype));
|
766 |
CREATE INDEX CONCURRENTLY entity_node_id_gin_idx ON dickens."Entity" using gin(properties);
|
767 |
ALTER TABLE dickens."DIRECTED" CLUSTER ON directed_sid_idx;
|
768 |
+
|
769 |
-- drop if necessary
|
770 |
drop INDEX entity_p_idx;
|
771 |
drop INDEX vertex_p_idx;
|
|
|
1067 |
<details>
|
1068 |
<summary> Parameters </summary>
|
1069 |
|
1070 |
+
| **Parameter** | **Type** | **Explanation** | **Default** |
|
1071 |
+
|--------------|----------|-----------------|-------------|
|
1072 |
+
| **working_dir** | `str` | Directory where the cache will be stored | `lightrag_cache+timestamp` |
|
1073 |
+
| **kv_storage** | `str` | Storage type for documents and text chunks. Supported types: `JsonKVStorage`, `OracleKVStorage` | `JsonKVStorage` |
|
1074 |
+
| **vector_storage** | `str` | Storage type for embedding vectors. Supported types: `NanoVectorDBStorage`, `OracleVectorDBStorage` | `NanoVectorDBStorage` |
|
1075 |
+
| **graph_storage** | `str` | Storage type for graph edges and nodes. Supported types: `NetworkXStorage`, `Neo4JStorage`, `OracleGraphStorage` | `NetworkXStorage` |
|
1076 |
+
| **chunk_token_size** | `int` | Maximum token size per chunk when splitting documents | `1200` |
|
1077 |
+
| **chunk_overlap_token_size** | `int` | Overlap token size between two chunks when splitting documents | `100` |
|
1078 |
+
| **tiktoken_model_name** | `str` | Model name for the Tiktoken encoder used to calculate token numbers | `gpt-4o-mini` |
|
1079 |
+
| **entity_extract_max_gleaning** | `int` | Number of loops in the entity extraction process, appending history messages | `1` |
|
1080 |
+
| **entity_summary_to_max_tokens** | `int` | Maximum token size for each entity summary | `500` |
|
1081 |
+
| **node_embedding_algorithm** | `str` | Algorithm for node embedding (currently not used) | `node2vec` |
|
1082 |
+
| **node2vec_params** | `dict` | Parameters for node embedding | `{"dimensions": 1536,"num_walks": 10,"walk_length": 40,"window_size": 2,"iterations": 3,"random_seed": 3,}` |
|
1083 |
+
| **embedding_func** | `EmbeddingFunc` | Function to generate embedding vectors from text | `openai_embed` |
|
1084 |
+
| **embedding_batch_num** | `int` | Maximum batch size for embedding processes (multiple texts sent per batch) | `32` |
|
1085 |
+
| **embedding_func_max_async** | `int` | Maximum number of concurrent asynchronous embedding processes | `16` |
|
1086 |
+
| **llm_model_func** | `callable` | Function for LLM generation | `gpt_4o_mini_complete` |
|
1087 |
+
| **llm_model_name** | `str` | LLM model name for generation | `meta-llama/Llama-3.2-1B-Instruct` |
|
1088 |
+
| **llm_model_max_token_size** | `int` | Maximum token size for LLM generation (affects entity relation summaries) | `32768`(default value changed by env var MAX_TOKENS) |
|
1089 |
+
| **llm_model_max_async** | `int` | Maximum number of concurrent asynchronous LLM processes | `4`(default value changed by env var MAX_ASYNC) |
|
1090 |
+
| **llm_model_kwargs** | `dict` | Additional parameters for LLM generation | |
|
1091 |
+
| **vector_db_storage_cls_kwargs** | `dict` | Additional parameters for vector database, like setting the threshold for nodes and relations retrieval | cosine_better_than_threshold: 0.2(default value changed by env var COSINE_THRESHOLD) |
|
1092 |
+
| **enable_llm_cache** | `bool` | If `TRUE`, stores LLM results in cache; repeated prompts return cached responses | `TRUE` |
|
1093 |
+
| **enable_llm_cache_for_entity_extract** | `bool` | If `TRUE`, stores LLM results in cache for entity extraction; Good for beginners to debug your application | `TRUE` |
|
1094 |
+
| **addon_params** | `dict` | Additional parameters, e.g., `{"example_number": 1, "language": "Simplified Chinese", "entity_types": ["organization", "person", "geo", "event"], "insert_batch_size": 10}`: sets example limit, output language, and batch size for document processing | `example_number: all examples, language: English, insert_batch_size: 10` |
|
1095 |
+
| **convert_response_to_json_func** | `callable` | Not used | `convert_response_to_json` |
|
1096 |
+
| **embedding_cache_config** | `dict` | Configuration for question-answer caching. Contains three parameters: `enabled`: Boolean value to enable/disable cache lookup functionality. When enabled, the system will check cached responses before generating new answers. `similarity_threshold`: Float value (0-1), similarity threshold. When a new question's similarity with a cached question exceeds this threshold, the cached answer will be returned directly without calling the LLM. `use_llm_check`: Boolean value to enable/disable LLM similarity verification. When enabled, LLM will be used as a secondary check to verify the similarity between questions before returning cached answers. | Default: `{"enabled": False, "similarity_threshold": 0.95, "use_llm_check": False}` |
|
1097 |
|
1098 |
</details>
|
1099 |
|
|
|
1118 |
|
1119 |
## Graph Visualization
|
1120 |
|
1121 |
+
The LightRAG Server offers a comprehensive knowledge graph visualization feature. It supports various gravity layouts, node queries, subgraph filtering, and more. **For more information about LightRAG Server, please refer to [LightRAG Server](./lightrag/api/README.md).**
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1122 |
|
1123 |
+

|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1124 |
|
1125 |
## Evaluation
|
1126 |
|
|
|
1215 |
|
1216 |
### Overall Performance Table
|
1217 |
|
1218 |
+
| |**Agriculture**| |**CS**| |**Legal**| |**Mix**| |
|
1219 |
+
|----------------------|---------------|------------|------|------------|---------|------------|-------|------------|
|
1220 |
+
| |NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|NaiveRAG|**LightRAG**|
|
1221 |
+
|**Comprehensiveness**|32.4%|**67.6%**|38.4%|**61.6%**|16.4%|**83.6%**|38.8%|**61.2%**|
|
1222 |
+
|**Diversity**|23.6%|**76.4%**|38.0%|**62.0%**|13.6%|**86.4%**|32.4%|**67.6%**|
|
1223 |
+
|**Empowerment**|32.4%|**67.6%**|38.8%|**61.2%**|16.4%|**83.6%**|42.8%|**57.2%**|
|
1224 |
+
|**Overall**|32.4%|**67.6%**|38.8%|**61.2%**|15.2%|**84.8%**|40.0%|**60.0%**|
|
1225 |
+
| |RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|RQ-RAG|**LightRAG**|
|
1226 |
+
|**Comprehensiveness**|31.6%|**68.4%**|38.8%|**61.2%**|15.2%|**84.8%**|39.2%|**60.8%**|
|
1227 |
+
|**Diversity**|29.2%|**70.8%**|39.2%|**60.8%**|11.6%|**88.4%**|30.8%|**69.2%**|
|
1228 |
+
|**Empowerment**|31.6%|**68.4%**|36.4%|**63.6%**|15.2%|**84.8%**|42.4%|**57.6%**|
|
1229 |
+
|**Overall**|32.4%|**67.6%**|38.0%|**62.0%**|14.4%|**85.6%**|40.0%|**60.0%**|
|
1230 |
+
| |HyDE|**LightRAG**|HyDE|**LightRAG**|HyDE|**LightRAG**|HyDE|**LightRAG**|
|
1231 |
+
|**Comprehensiveness**|26.0%|**74.0%**|41.6%|**58.4%**|26.8%|**73.2%**|40.4%|**59.6%**|
|
1232 |
+
|**Diversity**|24.0%|**76.0%**|38.8%|**61.2%**|20.0%|**80.0%**|32.4%|**67.6%**|
|
1233 |
+
|**Empowerment**|25.2%|**74.8%**|40.8%|**59.2%**|26.0%|**74.0%**|46.0%|**54.0%**|
|
1234 |
+
|**Overall**|24.8%|**75.2%**|41.6%|**58.4%**|26.4%|**73.6%**|42.4%|**57.6%**|
|
1235 |
+
| |GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|GraphRAG|**LightRAG**|
|
1236 |
+
|**Comprehensiveness**|45.6%|**54.4%**|48.4%|**51.6%**|48.4%|**51.6%**|**50.4%**|49.6%|
|
1237 |
+
|**Diversity**|22.8%|**77.2%**|40.8%|**59.2%**|26.4%|**73.6%**|36.0%|**64.0%**|
|
1238 |
+
|**Empowerment**|41.2%|**58.8%**|45.2%|**54.8%**|43.6%|**56.4%**|**50.8%**|49.2%|
|
1239 |
+
|**Overall**|45.2%|**54.8%**|48.0%|**52.0%**|47.2%|**52.8%**|**50.4%**|49.6%|
|
1240 |
|
1241 |
## Reproduce
|
1242 |
|
lightrag/api/README-zh.md
ADDED
@@ -0,0 +1,559 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# LightRAG 服务器和 Web 界面
|
2 |
+
|
3 |
+
LightRAG 服务器旨在提供 Web 界面和 API 支持。Web 界面便于文档索引、知识图谱探索和简单的 RAG 查询界面。LightRAG 服务器还提供了与 Ollama 兼容的接口,旨在将 LightRAG 模拟为 Ollama 聊天模型。这使得 AI 聊天机器人(如 Open WebUI)可以轻松访问 LightRAG。
|
4 |
+
|
5 |
+

|
6 |
+
|
7 |
+

|
8 |
+
|
9 |
+

|
10 |
+
|
11 |
+
## 入门指南
|
12 |
+
|
13 |
+
### 安装
|
14 |
+
|
15 |
+
* 从 PyPI 安装
|
16 |
+
|
17 |
+
```bash
|
18 |
+
pip install "lightrag-hku[api]"
|
19 |
+
```
|
20 |
+
|
21 |
+
* 从源代码安装
|
22 |
+
|
23 |
+
```bash
|
24 |
+
# 克隆仓库
|
25 |
+
git clone https://github.com/HKUDS/lightrag.git
|
26 |
+
|
27 |
+
# 切换到仓库目录
|
28 |
+
cd lightrag
|
29 |
+
|
30 |
+
# 如有必要,创建 Python 虚拟环境
|
31 |
+
# 以可编辑模式安装并支持 API
|
32 |
+
pip install -e ".[api]"
|
33 |
+
```
|
34 |
+
|
35 |
+
### 启动 LightRAG 服务器前的准备
|
36 |
+
|
37 |
+
LightRAG 需要同时集成 LLM(大型语言模型)和嵌入模型以有效执行文档索引和查询操作。在首次部署 LightRAG 服务器之前,必须配置 LLM 和嵌入模型的设置。LightRAG 支持绑定到各种 LLM/嵌入后端:
|
38 |
+
|
39 |
+
* ollama
|
40 |
+
* lollms
|
41 |
+
* openai 或 openai 兼容
|
42 |
+
* azure_openai
|
43 |
+
|
44 |
+
建议使用环境变量来配置 LightRAG 服务器。项目根目录中有一个名为 `env.example` 的示例环境变量文件。请将此文件复制到启动目录并重命名为 `.env`。之后,您可以在 `.env` 文件中修改与 LLM 和嵌入模型相关的参数。需要注意的是,LightRAG 服务器每次启动时都会将 `.env` 中的环境变量加载到系统环境变量中。由于 LightRAG 服务器会优先使用系统环境变量中的设置,如果您在通过命令行启动 LightRAG 服务器后修改了 `.env` 文件,则需要执行 `source .env` 使新设置生效。
|
45 |
+
|
46 |
+
以下是 LLM 和嵌入模型的一些常见设置示例:
|
47 |
+
|
48 |
+
* OpenAI LLM + Ollama 嵌入
|
49 |
+
|
50 |
+
```
|
51 |
+
LLM_BINDING=openai
|
52 |
+
LLM_MODEL=gpt-4o
|
53 |
+
LLM_BINDING_HOST=https://api.openai.com/v1
|
54 |
+
LLM_BINDING_API_KEY=your_api_key
|
55 |
+
MAX_TOKENS=32768 # 发送给 LLM 的最大 token 数(小于模型上下文大小)
|
56 |
+
|
57 |
+
EMBEDDING_BINDING=ollama
|
58 |
+
EMBEDDING_BINDING_HOST=http://localhost:11434
|
59 |
+
EMBEDDING_MODEL=bge-m3:latest
|
60 |
+
EMBEDDING_DIM=1024
|
61 |
+
# EMBEDDING_BINDING_API_KEY=your_api_key
|
62 |
+
```
|
63 |
+
|
64 |
+
* Ollama LLM + Ollama 嵌入
|
65 |
+
|
66 |
+
```
|
67 |
+
LLM_BINDING=ollama
|
68 |
+
LLM_MODEL=mistral-nemo:latest
|
69 |
+
LLM_BINDING_HOST=http://localhost:11434
|
70 |
+
# LLM_BINDING_API_KEY=your_api_key
|
71 |
+
MAX_TOKENS=8192 # 发送给 LLM 的最大 token 数(基于您的 Ollama 服务器容量)
|
72 |
+
|
73 |
+
EMBEDDING_BINDING=ollama
|
74 |
+
EMBEDDING_BINDING_HOST=http://localhost:11434
|
75 |
+
EMBEDDING_MODEL=bge-m3:latest
|
76 |
+
EMBEDDING_DIM=1024
|
77 |
+
# EMBEDDING_BINDING_API_KEY=your_api_key
|
78 |
+
```
|
79 |
+
|
80 |
+
### 启动 LightRAG 服务器
|
81 |
+
|
82 |
+
LightRAG 服务器支持两种运行模式:
|
83 |
+
* 简单高效的 Uvicorn 模式
|
84 |
+
|
85 |
+
```
|
86 |
+
lightrag-server
|
87 |
+
```
|
88 |
+
* 多进程 Gunicorn + Uvicorn 模式(生产模式,不支持 Windows 环境)
|
89 |
+
|
90 |
+
```
|
91 |
+
lightrag-gunicorn --workers 4
|
92 |
+
```
|
93 |
+
`.env` 文件必须放在启动目录中。启动时,LightRAG 服务器将创建一个文档目录(默认为 `./inputs`)和一个数据目录(默认为 `./rag_storage`)。这允许您从不同目录启动多个 LightRAG 服务器实例,每个实例配置为监听不同的网络端口。
|
94 |
+
|
95 |
+
以下是一些常用的启动参数:
|
96 |
+
|
97 |
+
- `--host`:服务器监听地址(默认:0.0.0.0)
|
98 |
+
- `--port`:服务器监听端口(默认:9621)
|
99 |
+
- `--timeout`:LLM 请求超时时间(默认:150 秒)
|
100 |
+
- `--log-level`:日志级别(默认:INFO)
|
101 |
+
- --input-dir:指定要扫描文档的目录(默认:./input)
|
102 |
+
|
103 |
+
### 启动时自动扫描
|
104 |
+
|
105 |
+
当使用 `--auto-scan-at-startup` 参数启动任何服务器时,系统将自动:
|
106 |
+
|
107 |
+
1. 扫描输入目录中的新文件
|
108 |
+
2. 为尚未在数据库中的新文档建立索引
|
109 |
+
3. 使所有内容立即可用于 RAG 查询
|
110 |
+
|
111 |
+
> `--input-dir` 参数指定要扫描的输入目录。您可以从 webui 触发输入目录扫描。
|
112 |
+
|
113 |
+
### Gunicorn + Uvicorn 的多工作进程
|
114 |
+
|
115 |
+
LightRAG 服务器可以在 `Gunicorn + Uvicorn` 预加载模式下运行。Gunicorn 的多工作进程(多进程)功能可以防止文档索引任务阻塞 RAG 查询。使用 CPU 密集型文档提取工具(如 docling)在纯 Uvicorn 模式下可能会导致整个系统被阻塞。
|
116 |
+
|
117 |
+
虽然 LightRAG 服务器使用一个工作进程来处理文档索引流程,但通过 Uvicorn 的异步任务支持,可以并行处理多个文件。文档索引速度的瓶颈主要在于 LLM。如果您的 LLM 支持高并发,您可以通过增加 LLM 的并发级别来加速文档索引。以下是几个与并发处理相关的环境变量及其默认值:
|
118 |
+
|
119 |
+
```
|
120 |
+
WORKERS=2 # 工作进程数,不大于 (2 x 核心数) + 1
|
121 |
+
MAX_PARALLEL_INSERT=2 # 一批中并行处理的文件数
|
122 |
+
MAX_ASYNC=4 # LLM 的最大并发请求数
|
123 |
+
```
|
124 |
+
|
125 |
+
### 将 Lightrag 安装为 Linux 服务
|
126 |
+
|
127 |
+
从示例文件 `lightrag.sevice.example` 创建您的服务文件 `lightrag.sevice`。修改服务文件中的 WorkingDirectory 和 ExecStart:
|
128 |
+
|
129 |
+
```text
|
130 |
+
Description=LightRAG Ollama Service
|
131 |
+
WorkingDirectory=<lightrag 安装目录>
|
132 |
+
ExecStart=<lightrag 安装目录>/lightrag/api/lightrag-api
|
133 |
+
```
|
134 |
+
|
135 |
+
修改您的服务启动脚本:`lightrag-api`。根据需要更改 python 虚拟环境激活命令:
|
136 |
+
|
137 |
+
```shell
|
138 |
+
#!/bin/bash
|
139 |
+
|
140 |
+
# 您的 python 虚拟环境激活命令
|
141 |
+
source /home/netman/lightrag-xyj/venv/bin/activate
|
142 |
+
# 启动 lightrag api 服务器
|
143 |
+
lightrag-server
|
144 |
+
```
|
145 |
+
|
146 |
+
安装 LightRAG 服务。如果您的系统是 Ubuntu,以下命令将生效:
|
147 |
+
|
148 |
+
```shell
|
149 |
+
sudo cp lightrag.service /etc/systemd/system/
|
150 |
+
sudo systemctl daemon-reload
|
151 |
+
sudo systemctl start lightrag.service
|
152 |
+
sudo systemctl status lightrag.service
|
153 |
+
sudo systemctl enable lightrag.service
|
154 |
+
```
|
155 |
+
|
156 |
+
## Ollama 模拟
|
157 |
+
|
158 |
+
我们为 LightRAG 提供了 Ollama 兼容接口,旨在将 LightRAG 模拟为 Ollama 聊天模型。这使得支持 Ollama 的 AI 聊天前端(如 Open WebUI)可以轻松访问 LightRAG。
|
159 |
+
|
160 |
+
### 将 Open WebUI 连接到 LightRAG
|
161 |
+
|
162 |
+
启动 lightrag-server 后,您可以在 Open WebUI 管理面板中添加 Ollama 类型的连接。然后,一个名为 lightrag:latest 的模型将出现在 Open WebUI 的模型管理界面中。用户随后可以通过聊天界面向 LightRAG 发送查询。对于这种用例,最好将 LightRAG 安装为服务。
|
163 |
+
|
164 |
+
Open WebUI 使用 LLM 来执行会话标题和会话关键词生成任务。因此,Ollama 聊天补全 API 会检测并将 OpenWebUI 会话相关请求直接转发给底层 LLM。Open WebUI 的截图:
|
165 |
+
|
166 |
+

|
167 |
+
|
168 |
+
### 在聊天中选择查询模式
|
169 |
+
|
170 |
+
查询字符串中的查询前缀可以决定使用哪种 LightRAG 查询模式来生成响应。支持的前缀包括:
|
171 |
+
|
172 |
+
```
|
173 |
+
/local
|
174 |
+
/global
|
175 |
+
/hybrid
|
176 |
+
/naive
|
177 |
+
/mix
|
178 |
+
/bypass
|
179 |
+
```
|
180 |
+
|
181 |
+
例如,聊天消息 "/mix 唐僧有几个徒弟" 将触发 LightRAG 的混合模式查询。没有查询前缀的聊天消息默认会触发混合模式查询。
|
182 |
+
|
183 |
+
"/bypass" 不是 LightRAG 查询模式,它会告诉 API 服务器将查询连同聊天历史直接传递给底层 LLM。因此用户可以使用 LLM 基于聊天历史回答问题。如果您使用 Open WebUI 作为前端,您可以直接切换到普通 LLM 模型,而不是使用 /bypass 前缀。
|
184 |
+
|
185 |
+
## API 密钥和认证
|
186 |
+
|
187 |
+
默认情况下,LightRAG 服务器可以在没有任何认证的情况下访问。我们可以使用 API 密钥或账户凭证配置服务器以确保其安全。
|
188 |
+
|
189 |
+
* API 密钥
|
190 |
+
|
191 |
+
```
|
192 |
+
LIGHTRAG_API_KEY=your-secure-api-key-here
|
193 |
+
WHITELIST_PATHS=/health,/api/*
|
194 |
+
```
|
195 |
+
|
196 |
+
> 健康检查和 Ollama 模拟端点默认不进行 API 密钥检查。
|
197 |
+
|
198 |
+
* 账户凭证(Web 界面需要登录后才能访问)
|
199 |
+
|
200 |
+
LightRAG API 服务器使用基于 HS256 算法的 JWT 认证。要启用安全访问控制,需要以下环境变量:
|
201 |
+
|
202 |
+
```bash
|
203 |
+
# JWT 认证
|
204 |
+
AUTH_USERNAME=admin # 登录名
|
205 |
+
AUTH_PASSWORD=admin123 # 密码
|
206 |
+
TOKEN_SECRET=your-key # JWT 密钥
|
207 |
+
TOKEN_EXPIRE_HOURS=4 # 过期时间
|
208 |
+
```
|
209 |
+
|
210 |
+
> 目前仅支持配置一个管理员账户和密码。尚未开发和实现完整的账户系统。
|
211 |
+
|
212 |
+
如果未配置账户凭证,Web 界面将以访客身份访问系统。因此,即使仅配置了 API 密钥,所有 API 仍然可以通过访客账户访问,这仍然不安全。因此,要保护 API,需要同时配置这两种认证方法。
|
213 |
+
|
214 |
+
## Azure OpenAI 后端配置
|
215 |
+
|
216 |
+
可以使用以下 Azure CLI 命令创建 Azure OpenAI API(您需要先从 [https://docs.microsoft.com/en-us/cli/azure/install-azure-cli](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli) 安装 Azure CLI):
|
217 |
+
|
218 |
+
```bash
|
219 |
+
# 根据需要更改资源组名称、位置和 OpenAI 资源名称
|
220 |
+
RESOURCE_GROUP_NAME=LightRAG
|
221 |
+
LOCATION=swedencentral
|
222 |
+
RESOURCE_NAME=LightRAG-OpenAI
|
223 |
+
|
224 |
+
az login
|
225 |
+
az group create --name $RESOURCE_GROUP_NAME --location $LOCATION
|
226 |
+
az cognitiveservices account create --name $RESOURCE_NAME --resource-group $RESOURCE_GROUP_NAME --kind OpenAI --sku S0 --location swedencentral
|
227 |
+
az cognitiveservices account deployment create --resource-group $RESOURCE_GROUP_NAME --model-format OpenAI --name $RESOURCE_NAME --deployment-name gpt-4o --model-name gpt-4o --model-version "2024-08-06" --sku-capacity 100 --sku-name "Standard"
|
228 |
+
az cognitiveservices account deployment create --resource-group $RESOURCE_GROUP_NAME --model-format OpenAI --name $RESOURCE_NAME --deployment-name text-embedding-3-large --model-name text-embedding-3-large --model-version "1" --sku-capacity 80 --sku-name "Standard"
|
229 |
+
az cognitiveservices account show --name $RESOURCE_NAME --resource-group $RESOURCE_GROUP_NAME --query "properties.endpoint"
|
230 |
+
az cognitiveservices account keys list --name $RESOURCE_NAME -g $RESOURCE_GROUP_NAME
|
231 |
+
```
|
232 |
+
|
233 |
+
最后一个命令的输出将提供 OpenAI API 的端点和密钥。您可以使用这些值在 `.env` 文件中设置环境变量。
|
234 |
+
|
235 |
+
```
|
236 |
+
# .env 中的 Azure OpenAI 配置
|
237 |
+
LLM_BINDING=azure_openai
|
238 |
+
LLM_BINDING_HOST=your-azure-endpoint
|
239 |
+
LLM_MODEL=your-model-deployment-name
|
240 |
+
LLM_BINDING_API_KEY=your-azure-api-key
|
241 |
+
AZURE_OPENAI_API_VERSION=2024-08-01-preview # 可选,默认为最新版本
|
242 |
+
EMBEDDING_BINDING=azure_openai # 如果使用 Azure OpenAI 进行嵌入
|
243 |
+
EMBEDDING_MODEL=your-embedding-deployment-name
|
244 |
+
```
|
245 |
+
|
246 |
+
## LightRAG 服务器详细配置
|
247 |
+
|
248 |
+
API 服务器可以通过三种方式配置(优先级从高到低):
|
249 |
+
|
250 |
+
* 命令行参数
|
251 |
+
* 环境变量或 .env 文件
|
252 |
+
* Config.ini(仅用于存储配置)
|
253 |
+
|
254 |
+
大多数配置都有默认设置,详细信息请查看示例文件:`.env.example`。数据存储配置也可以通过 config.ini 设置。为方便起见,提供了示例文件 `config.ini.example`。
|
255 |
+
|
256 |
+
### 支持的 LLM 和嵌入后端
|
257 |
+
|
258 |
+
LightRAG 支持绑定到各种 LLM/嵌入后端:
|
259 |
+
|
260 |
+
* ollama
|
261 |
+
* lollms
|
262 |
+
* openai 和 openai 兼容
|
263 |
+
* azure_openai
|
264 |
+
|
265 |
+
使用环境变量 `LLM_BINDING` 或 CLI 参数 `--llm-binding` 选择 LLM 后端类型。使用环境变量 `EMBEDDING_BINDING` 或 CLI 参数 `--embedding-binding` 选择嵌入后端类型。
|
266 |
+
|
267 |
+
### 实体提取配置
|
268 |
+
* ENABLE_LLM_CACHE_FOR_EXTRACT:为实体提取启用 LLM 缓存(默认:true)
|
269 |
+
|
270 |
+
在测试环境中将 `ENABLE_LLM_CACHE_FOR_EXTRACT` 设置为 true 以减少 LLM 调用成本是很常见的做法。
|
271 |
+
|
272 |
+
### 支持的存储类型
|
273 |
+
|
274 |
+
LightRAG 使用 4 种类型的存储用于不同目的:
|
275 |
+
|
276 |
+
* KV_STORAGE:llm 响应缓存、文本块、文档信息
|
277 |
+
* VECTOR_STORAGE:实体向量、关系向量、块向量
|
278 |
+
* GRAPH_STORAGE:实体关系图
|
279 |
+
* DOC_STATUS_STORAGE:文档索引状态
|
280 |
+
|
281 |
+
每种存储类型都有几种实现:
|
282 |
+
|
283 |
+
* KV_STORAGE 支持的实现名称
|
284 |
+
|
285 |
+
```
|
286 |
+
JsonKVStorage JsonFile(默认)
|
287 |
+
MongoKVStorage MogonDB
|
288 |
+
RedisKVStorage Redis
|
289 |
+
TiDBKVStorage TiDB
|
290 |
+
PGKVStorage Postgres
|
291 |
+
OracleKVStorage Oracle
|
292 |
+
```
|
293 |
+
|
294 |
+
* GRAPH_STORAGE 支持的实现名称
|
295 |
+
|
296 |
+
```
|
297 |
+
NetworkXStorage NetworkX(默认)
|
298 |
+
Neo4JStorage Neo4J
|
299 |
+
MongoGraphStorage MongoDB
|
300 |
+
TiDBGraphStorage TiDB
|
301 |
+
AGEStorage AGE
|
302 |
+
GremlinStorage Gremlin
|
303 |
+
PGGraphStorage Postgres
|
304 |
+
OracleGraphStorage Postgres
|
305 |
+
```
|
306 |
+
|
307 |
+
* VECTOR_STORAGE 支持的实现名称
|
308 |
+
|
309 |
+
```
|
310 |
+
NanoVectorDBStorage NanoVector(默认)
|
311 |
+
MilvusVectorDBStorge Milvus
|
312 |
+
ChromaVectorDBStorage Chroma
|
313 |
+
TiDBVectorDBStorage TiDB
|
314 |
+
PGVectorStorage Postgres
|
315 |
+
FaissVectorDBStorage Faiss
|
316 |
+
QdrantVectorDBStorage Qdrant
|
317 |
+
OracleVectorDBStorage Oracle
|
318 |
+
MongoVectorDBStorage MongoDB
|
319 |
+
```
|
320 |
+
|
321 |
+
* DOC_STATUS_STORAGE 支持的实现名称
|
322 |
+
|
323 |
+
```
|
324 |
+
JsonDocStatusStorage JsonFile(默认)
|
325 |
+
PGDocStatusStorage Postgres
|
326 |
+
MongoDocStatusStorage MongoDB
|
327 |
+
```
|
328 |
+
|
329 |
+
### 如何选择存储实现
|
330 |
+
|
331 |
+
您可以通过环境变量选择存储实现。在首次启动 API 服务器之前,您可以将以下环境变量设置为特定的存储实现名称:
|
332 |
+
|
333 |
+
```
|
334 |
+
LIGHTRAG_KV_STORAGE=PGKVStorage
|
335 |
+
LIGHTRAG_VECTOR_STORAGE=PGVectorStorage
|
336 |
+
LIGHTRAG_GRAPH_STORAGE=PGGraphStorage
|
337 |
+
LIGHTRAG_DOC_STATUS_STORAGE=PGDocStatusStorage
|
338 |
+
```
|
339 |
+
|
340 |
+
在向 LightRAG 添加文档后,您不能更改存储实现选择。目前尚不支持从一个存储实现迁移到另一个存储实现。更多信息请阅读示例 env 文件或 config.ini 文件。
|
341 |
+
|
342 |
+
### LightRag API 服务器命令行选项
|
343 |
+
|
344 |
+
| 参数 | 默认值 | 描述 |
|
345 |
+
|-----------|---------|-------------|
|
346 |
+
| --host | 0.0.0.0 | 服务器主机 |
|
347 |
+
| --port | 9621 | 服务器端口 |
|
348 |
+
| --working-dir | ./rag_storage | RAG 存储的工作目录 |
|
349 |
+
| --input-dir | ./inputs | 包含输入文档的目录 |
|
350 |
+
| --max-async | 4 | 最大异步操作数 |
|
351 |
+
| --max-tokens | 32768 | 最大 token 大小 |
|
352 |
+
| --timeout | 150 | 超时时间(秒)。None 表示无限超时(不推荐) |
|
353 |
+
| --log-level | INFO | 日志级别(DEBUG、INFO、WARNING、ERROR、CRITICAL) |
|
354 |
+
| --verbose | - | 详细调试输出(True、False) |
|
355 |
+
| --key | None | 用于认证的 API 密钥。保护 lightrag 服务器免受未授权访问 |
|
356 |
+
| --ssl | False | 启用 HTTPS |
|
357 |
+
| --ssl-certfile | None | SSL 证书文件路径(如果启用 --ssl 则必需) |
|
358 |
+
| --ssl-keyfile | None | SSL 私钥文件路径(如果启用 --ssl 则必需) |
|
359 |
+
| --top-k | 50 | 要检索的 top-k 项目数;在"local"模式下对应实体,在"global"模式下对应关系。 |
|
360 |
+
| --cosine-threshold | 0.4 | 节点和关系检索的余弦阈值,与 top-k 一起控制节点和关系的检索。 |
|
361 |
+
| --llm-binding | ollama | LLM 绑定类型(lollms、ollama、openai、openai-ollama、azure_openai) |
|
362 |
+
| --embedding-binding | ollama | 嵌入绑定类型(lollms、ollama、openai、azure_openai) |
|
363 |
+
| auto-scan-at-startup | - | 扫描输入目录中的新文件并开始索引 |
|
364 |
+
|
365 |
+
### 使用示例
|
366 |
+
|
367 |
+
#### 使用 ollama 默认本地服务器作为 llm 和嵌入后端运行 Lightrag 服务器
|
368 |
+
|
369 |
+
Ollama 是 llm 和嵌入的默认后端,因此默认情况下您可以不带参数运行 lightrag-server,将使用默认值。确保已安装 ollama 并且正在运行,且默认模型已安装在 ollama 上。
|
370 |
+
|
371 |
+
```bash
|
372 |
+
# 使用 ollama 运行 lightrag,llm 使用 mistral-nemo:latest,嵌入使用 bge-m3:latest
|
373 |
+
lightrag-server
|
374 |
+
|
375 |
+
# 使用认证密钥
|
376 |
+
lightrag-server --key my-key
|
377 |
+
```
|
378 |
+
|
379 |
+
#### 使用 lollms 默认本地服务器作为 llm 和嵌入后端运行 Lightrag 服务器
|
380 |
+
|
381 |
+
```bash
|
382 |
+
# 使用 lollms 运行 lightrag,llm 使用 mistral-nemo:latest,嵌入使用 bge-m3:latest
|
383 |
+
# 在 .env 或 config.ini 中配置 LLM_BINDING=lollms 和 EMBEDDING_BINDING=lollms
|
384 |
+
lightrag-server
|
385 |
+
|
386 |
+
# 使用认证密钥
|
387 |
+
lightrag-server --key my-key
|
388 |
+
```
|
389 |
+
|
390 |
+
#### 使用 openai 服务器作为 llm 和嵌入后端运行 Lightrag 服务器
|
391 |
+
|
392 |
+
```bash
|
393 |
+
# 使用 openai 运行 lightrag,llm 使用 GPT-4o-mini,嵌入使用 text-embedding-3-small
|
394 |
+
# 在 .env 或 config.ini 中配置:
|
395 |
+
# LLM_BINDING=openai
|
396 |
+
# LLM_MODEL=GPT-4o-mini
|
397 |
+
# EMBEDDING_BINDING=openai
|
398 |
+
# EMBEDDING_MODEL=text-embedding-3-small
|
399 |
+
lightrag-server
|
400 |
+
|
401 |
+
# 使用认证密钥
|
402 |
+
lightrag-server --key my-key
|
403 |
+
```
|
404 |
+
|
405 |
+
#### 使用 azure openai 服务器作为 llm 和嵌入后端运行 Lightrag 服务器
|
406 |
+
|
407 |
+
```bash
|
408 |
+
# 使用 azure_openai 运行 lightrag
|
409 |
+
# 在 .env 或 config.ini 中配置:
|
410 |
+
# LLM_BINDING=azure_openai
|
411 |
+
# LLM_MODEL=your-model
|
412 |
+
# EMBEDDING_BINDING=azure_openai
|
413 |
+
# EMBEDDING_MODEL=your-embedding-model
|
414 |
+
lightrag-server
|
415 |
+
|
416 |
+
# 使用认证密钥
|
417 |
+
lightrag-server --key my-key
|
418 |
+
```
|
419 |
+
|
420 |
+
**重要说明:**
|
421 |
+
- 对于 LoLLMs:确保指定的模型已安装在您的 LoLLMs 实例中
|
422 |
+
- 对于 Ollama:确保指定的模型已安装在您的 Ollama 实例中
|
423 |
+
- 对于 OpenAI:确保您已设置 OPENAI_API_KEY 环境变量
|
424 |
+
- 对于 Azure OpenAI:按照先决条件部分所述构建和配置您的服务器
|
425 |
+
|
426 |
+
要获取任何服务器的帮助,使用 --help 标志:
|
427 |
+
```bash
|
428 |
+
lightrag-server --help
|
429 |
+
```
|
430 |
+
|
431 |
+
注意:如果您不需要 API 功能,可以使用以下命令安装不带 API 支持的基本包:
|
432 |
+
```bash
|
433 |
+
pip install lightrag-hku
|
434 |
+
```
|
435 |
+
|
436 |
+
## API 端点
|
437 |
+
|
438 |
+
所有服务器(LoLLMs、Ollama、OpenAI 和 Azure OpenAI)都为 RAG 功能提供相同的 REST API 端点。当 API 服务器运行时,访问:
|
439 |
+
|
440 |
+
- Swagger UI:http://localhost:9621/docs
|
441 |
+
- ReDoc:http://localhost:9621/redoc
|
442 |
+
|
443 |
+
您可以使用提供的 curl 命令或通过 Swagger UI 界面测试 API 端点。确保:
|
444 |
+
|
445 |
+
1. 启动适当的后端服务(LoLLMs、Ollama 或 OpenAI)
|
446 |
+
2. 启动 RAG 服务器
|
447 |
+
3. 使用文档管理端点上传一些文档
|
448 |
+
4. 使用查询端点查询系统
|
449 |
+
5. 如果在输入目录中放入新文件,触发文档扫描
|
450 |
+
|
451 |
+
### 查询端点
|
452 |
+
|
453 |
+
#### POST /query
|
454 |
+
使用不同搜索模式查询 RAG 系统。
|
455 |
+
|
456 |
+
```bash
|
457 |
+
curl -X POST "http://localhost:9621/query" \
|
458 |
+
-H "Content-Type: application/json" \
|
459 |
+
-d '{"query": "您的问题", "mode": "hybrid", ""}'
|
460 |
+
```
|
461 |
+
|
462 |
+
#### POST /query/stream
|
463 |
+
从 RAG 系统流式获取响应。
|
464 |
+
|
465 |
+
```bash
|
466 |
+
curl -X POST "http://localhost:9621/query/stream" \
|
467 |
+
-H "Content-Type: application/json" \
|
468 |
+
-d '{"query": "您的问题", "mode": "hybrid"}'
|
469 |
+
```
|
470 |
+
|
471 |
+
### 文档管理端点
|
472 |
+
|
473 |
+
#### POST /documents/text
|
474 |
+
直接将文本插入 RAG 系统。
|
475 |
+
|
476 |
+
```bash
|
477 |
+
curl -X POST "http://localhost:9621/documents/text" \
|
478 |
+
-H "Content-Type: application/json" \
|
479 |
+
-d '{"text": "您的文本内容", "description": "可选描述"}'
|
480 |
+
```
|
481 |
+
|
482 |
+
#### POST /documents/file
|
483 |
+
向 RAG 系统上传单个文件。
|
484 |
+
|
485 |
+
```bash
|
486 |
+
curl -X POST "http://localhost:9621/documents/file" \
|
487 |
+
-F "file=@/path/to/your/document.txt" \
|
488 |
+
-F "description=可选描述"
|
489 |
+
```
|
490 |
+
|
491 |
+
#### POST /documents/batch
|
492 |
+
一次上传多个文件。
|
493 |
+
|
494 |
+
```bash
|
495 |
+
curl -X POST "http://localhost:9621/documents/batch" \
|
496 |
+
-F "files=@/path/to/doc1.txt" \
|
497 |
+
-F "files=@/path/to/doc2.txt"
|
498 |
+
```
|
499 |
+
|
500 |
+
#### POST /documents/scan
|
501 |
+
|
502 |
+
触发输入目录中新文件的文档扫描。
|
503 |
+
|
504 |
+
```bash
|
505 |
+
curl -X POST "http://localhost:9621/documents/scan" --max-time 1800
|
506 |
+
```
|
507 |
+
|
508 |
+
> 根据所有新文件的预计索引时间调整 max-time。
|
509 |
+
|
510 |
+
#### DELETE /documents
|
511 |
+
|
512 |
+
从 RAG 系统中清除所有文档。
|
513 |
+
|
514 |
+
```bash
|
515 |
+
curl -X DELETE "http://localhost:9621/documents"
|
516 |
+
```
|
517 |
+
|
518 |
+
### Ollama 模拟端点
|
519 |
+
|
520 |
+
#### GET /api/version
|
521 |
+
|
522 |
+
获取 Ollama 版本信息。
|
523 |
+
|
524 |
+
```bash
|
525 |
+
curl http://localhost:9621/api/version
|
526 |
+
```
|
527 |
+
|
528 |
+
#### GET /api/tags
|
529 |
+
|
530 |
+
获取 Ollama 可用模型。
|
531 |
+
|
532 |
+
```bash
|
533 |
+
curl http://localhost:9621/api/tags
|
534 |
+
```
|
535 |
+
|
536 |
+
#### POST /api/chat
|
537 |
+
|
538 |
+
处理聊天补全请求。通过根据查询前缀选择查询模式将用户查询路由到 LightRAG。检测并将 OpenWebUI 会话相关请求(用于元数据生成任务)直接转发给底层 LLM。
|
539 |
+
|
540 |
+
```shell
|
541 |
+
curl -N -X POST http://localhost:9621/api/chat -H "Content-Type: application/json" -d \
|
542 |
+
'{"model":"lightrag:latest","messages":[{"role":"user","content":"猪八戒是谁"}],"stream":true}'
|
543 |
+
```
|
544 |
+
|
545 |
+
> 有关 Ollama API 的更多信息,请访问:[Ollama API 文档](https://github.com/ollama/ollama/blob/main/docs/api.md)
|
546 |
+
|
547 |
+
#### POST /api/generate
|
548 |
+
|
549 |
+
处理生成补全请求。为了兼容性目的,该请求不由 LightRAG 处理,而是由底层 LLM 模型处理。
|
550 |
+
|
551 |
+
### 实用工具端点
|
552 |
+
|
553 |
+
#### GET /health
|
554 |
+
检查��务器健康状况和配置。
|
555 |
+
|
556 |
+
```bash
|
557 |
+
curl "http://localhost:9621/health"
|
558 |
+
|
559 |
+
```
|