gov-modular-rag 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- gov_modular_rag-0.1.0/LICENSE +21 -0
- gov_modular_rag-0.1.0/PKG-INFO +203 -0
- gov_modular_rag-0.1.0/README.md +180 -0
- gov_modular_rag-0.1.0/gov_modular_rag.egg-info/PKG-INFO +203 -0
- gov_modular_rag-0.1.0/gov_modular_rag.egg-info/SOURCES.txt +9 -0
- gov_modular_rag-0.1.0/gov_modular_rag.egg-info/dependency_links.txt +1 -0
- gov_modular_rag-0.1.0/gov_modular_rag.egg-info/requires.txt +13 -0
- gov_modular_rag-0.1.0/gov_modular_rag.egg-info/top_level.txt +1 -0
- gov_modular_rag-0.1.0/gov_modular_rag.py +435 -0
- gov_modular_rag-0.1.0/pyproject.toml +29 -0
- gov_modular_rag-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 gov-modular-rag contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gov-modular-rag
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A configurable modular RAG retrieval layer for existing Chroma knowledge bases
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Keywords: rag,langchain,chroma,retrieval,government
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: chromadb
|
|
11
|
+
Requires-Dist: langchain-chroma
|
|
12
|
+
Requires-Dist: langchain-community
|
|
13
|
+
Requires-Dist: langchain-core
|
|
14
|
+
Requires-Dist: langchain-openai
|
|
15
|
+
Requires-Dist: jieba
|
|
16
|
+
Requires-Dist: rank-bm25
|
|
17
|
+
Requires-Dist: python-dotenv
|
|
18
|
+
Requires-Dist: dashscope
|
|
19
|
+
Provides-Extra: publish
|
|
20
|
+
Requires-Dist: build; extra == "publish"
|
|
21
|
+
Requires-Dist: twine; extra == "publish"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# gov-modular-rag
|
|
25
|
+
|
|
26
|
+
一个面向政务问答场景的模块化 RAG 检索包:连接**已经建好的 Chroma 知识库**,提供向量检索、BM25 混合检索、RRF 融合、去重、相似度过滤、重排和上下文压缩。
|
|
27
|
+
|
|
28
|
+
> 说明:教程中的 `langchain-modular-rag` 已由其他作者发布到 PyPI;本项目使用 `gov-modular-rag`,避免同名冲突。
|
|
29
|
+
>
|
|
30
|
+
> 本包只做在线检索,不包含你的知识库数据,也不会自动创建或导入知识库。
|
|
31
|
+
|
|
32
|
+
## 安装
|
|
33
|
+
|
|
34
|
+
从源码目录安装:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install -e .
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
发布到 PyPI 后可以这样安装:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install gov-modular-rag
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Python 3.11 及以上。
|
|
47
|
+
|
|
48
|
+
## 准备知识库
|
|
49
|
+
|
|
50
|
+
先准备一个 Chroma 持久化目录。下面是最小入库示例:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from langchain_chroma import Chroma
|
|
54
|
+
from langchain_community.embeddings import DashScopeEmbeddings
|
|
55
|
+
from langchain_core.documents import Document
|
|
56
|
+
|
|
57
|
+
embeddings = DashScopeEmbeddings(model="text-embedding-v4")
|
|
58
|
+
|
|
59
|
+
docs = [
|
|
60
|
+
Document(
|
|
61
|
+
page_content="社保卡丢失后,先挂失,再携带身份证到社保卡服务窗口补换。",
|
|
62
|
+
metadata={"title": "社保卡补换", "chunk_id": "policy-1"},
|
|
63
|
+
),
|
|
64
|
+
Document(
|
|
65
|
+
page_content="租房提取公积金需要身份证、银行卡、租赁合同或租房发票。",
|
|
66
|
+
metadata={"title": "公积金租房提取", "chunk_id": "policy-2"},
|
|
67
|
+
),
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
Chroma.from_documents(
|
|
71
|
+
documents=docs,
|
|
72
|
+
embedding=embeddings,
|
|
73
|
+
ids=[doc.metadata["chunk_id"] for doc in docs],
|
|
74
|
+
persist_directory="./chroma_db",
|
|
75
|
+
collection_name="study",
|
|
76
|
+
)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## 使用
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from gov_modular_rag import ModularRAG
|
|
83
|
+
|
|
84
|
+
rag = ModularRAG({
|
|
85
|
+
"persist_directory": "./chroma_db",
|
|
86
|
+
"collection_name": "study",
|
|
87
|
+
"embedding_model": "text-embedding-v4",
|
|
88
|
+
"top_k": 5,
|
|
89
|
+
"recall_top_k": 20,
|
|
90
|
+
"pre_retrieval": {
|
|
91
|
+
"enabled": False,
|
|
92
|
+
"rewrite_query": False,
|
|
93
|
+
"hyde": False,
|
|
94
|
+
"model": "qwen-plus",
|
|
95
|
+
},
|
|
96
|
+
"hybrid_retrieval": {
|
|
97
|
+
"enabled": True,
|
|
98
|
+
"weights": [0.5, 0.5],
|
|
99
|
+
},
|
|
100
|
+
"post_retrieval": {
|
|
101
|
+
"enabled": True,
|
|
102
|
+
"deduplicate": True,
|
|
103
|
+
"rerank": False,
|
|
104
|
+
"rerank_model": "qwen3-rerank",
|
|
105
|
+
"similarity_filter": False,
|
|
106
|
+
"similarity_threshold": 0.4,
|
|
107
|
+
"compress_context": False,
|
|
108
|
+
"llm_model": "qwen-plus",
|
|
109
|
+
"reorder": False,
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
results = rag.search("公司打卡时间?")
|
|
114
|
+
for document in results:
|
|
115
|
+
print(document.metadata)
|
|
116
|
+
print(document.page_content)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`search()` 返回 `list[Document]`,可以直接拿来拼 Prompt:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
context = "\n\n".join(
|
|
123
|
+
f"[{i}] {doc.page_content}"
|
|
124
|
+
for i, doc in enumerate(results, start=1)
|
|
125
|
+
)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## 配置说明
|
|
129
|
+
|
|
130
|
+
| 参数 | 默认值 | 作用 |
|
|
131
|
+
| --- | --- | --- |
|
|
132
|
+
| `persist_directory` | 必填 | 已有 Chroma 持久化目录 |
|
|
133
|
+
| `collection_name` | `study` | Chroma 集合名 |
|
|
134
|
+
| `embedding_model` | `text-embedding-v4` | 通义向量模型 |
|
|
135
|
+
| `top_k` | `5` | 最终返回条数 |
|
|
136
|
+
| `recall_top_k` | `20` | 向量/BM25 每路召回条数 |
|
|
137
|
+
| `pre_retrieval.enabled` | `False` | 是否启用查询预处理 |
|
|
138
|
+
| `pre_retrieval.rewrite_query` | `False` | 是否做查询改写 |
|
|
139
|
+
| `pre_retrieval.hyde` | `False` | 是否生成 HyDE 假设答案 |
|
|
140
|
+
| `pre_retrieval.model` | `qwen-plus` | 改写/HyDE 使用的模型 |
|
|
141
|
+
| `hybrid_retrieval.enabled` | `True` | 是否启用向量 + BM25 混合检索 |
|
|
142
|
+
| `hybrid_retrieval.weights` | `[0.5, 0.5]` | 两路 RRF 权重 |
|
|
143
|
+
| `post_retrieval.enabled` | `True` | 是否启用后处理 |
|
|
144
|
+
| `post_retrieval.deduplicate` | `True` | 按 chunk_id 和正文去重 |
|
|
145
|
+
| `post_retrieval.similarity_filter` | `False` | 是否按余弦相似度过滤 |
|
|
146
|
+
| `post_retrieval.similarity_threshold` | `0.4` | 相似度阈值 |
|
|
147
|
+
| `post_retrieval.rerank` | `False` | 是否调用 DashScope 重排 |
|
|
148
|
+
| `post_retrieval.rerank_model` | `qwen3-rerank` | 重排模型 |
|
|
149
|
+
| `post_retrieval.compress_context` | `False` | 是否用 LLM 抽取相关句 |
|
|
150
|
+
| `post_retrieval.llm_model` | `qwen-plus` | 压缩使用的模型 |
|
|
151
|
+
| `post_retrieval.reorder` | `False` | 是否按余弦相似度重排 |
|
|
152
|
+
|
|
153
|
+
预处理、重排和压缩都会产生额外的大模型调用,第一次调试建议先保持关闭。
|
|
154
|
+
|
|
155
|
+
## 环境变量
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
# Windows PowerShell
|
|
159
|
+
$env:DASHSCOPE_API_KEY="你的 API Key"
|
|
160
|
+
|
|
161
|
+
# macOS / Linux
|
|
162
|
+
export DASHSCOPE_API_KEY="你的 API Key"
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
代码也支持 `DASHSCOPE_BASE_URL`;不设置时默认使用:
|
|
166
|
+
|
|
167
|
+
```text
|
|
168
|
+
https://dashscope.aliyuncs.com/compatible-mode/v1
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## 说明与限制
|
|
172
|
+
|
|
173
|
+
- 只读取已有 Chroma 库;如果集合为空,`search()` 会返回空列表。
|
|
174
|
+
- BM25 语料在第一次检索时从 Chroma 读取并缓存;知识库更新后调用 `rag.refresh()`。
|
|
175
|
+
- 混合检索使用 RRF 排名融合,分数是排名分,不是余弦相似度。
|
|
176
|
+
- `rerank`、`compress_context`、`rewrite_query`、`hyde` 需要可用的通义 API Key。
|
|
177
|
+
- 当前不包含文档切分和自动入库;入库请参考上面的“准备知识库”。
|
|
178
|
+
|
|
179
|
+
## 本地构建
|
|
180
|
+
|
|
181
|
+
```bash
|
|
182
|
+
pip install build twine
|
|
183
|
+
python -m build
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
构建完成后会在 `dist/` 下生成:
|
|
187
|
+
|
|
188
|
+
- `gov_modular_rag-0.1.0-py3-none-any.whl`
|
|
189
|
+
- `gov_modular_rag-0.1.0.tar.gz`
|
|
190
|
+
|
|
191
|
+
## 发布到 PyPI
|
|
192
|
+
|
|
193
|
+
先注册 PyPI 账号并创建 API Token,然后执行:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
twine upload dist/*
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
用户名填 `__token__`,密码填 PyPI Token。
|
|
200
|
+
|
|
201
|
+
## License
|
|
202
|
+
|
|
203
|
+
MIT
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
# gov-modular-rag
|
|
2
|
+
|
|
3
|
+
一个面向政务问答场景的模块化 RAG 检索包:连接**已经建好的 Chroma 知识库**,提供向量检索、BM25 混合检索、RRF 融合、去重、相似度过滤、重排和上下文压缩。
|
|
4
|
+
|
|
5
|
+
> 说明:教程中的 `langchain-modular-rag` 已由其他作者发布到 PyPI;本项目使用 `gov-modular-rag`,避免同名冲突。
|
|
6
|
+
>
|
|
7
|
+
> 本包只做在线检索,不包含你的知识库数据,也不会自动创建或导入知识库。
|
|
8
|
+
|
|
9
|
+
## 安装
|
|
10
|
+
|
|
11
|
+
从源码目录安装:
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install -e .
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
发布到 PyPI 后可以这样安装:
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
pip install gov-modular-rag
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Python 3.11 及以上。
|
|
24
|
+
|
|
25
|
+
## 准备知识库
|
|
26
|
+
|
|
27
|
+
先准备一个 Chroma 持久化目录。下面是最小入库示例:
|
|
28
|
+
|
|
29
|
+
```python
|
|
30
|
+
from langchain_chroma import Chroma
|
|
31
|
+
from langchain_community.embeddings import DashScopeEmbeddings
|
|
32
|
+
from langchain_core.documents import Document
|
|
33
|
+
|
|
34
|
+
embeddings = DashScopeEmbeddings(model="text-embedding-v4")
|
|
35
|
+
|
|
36
|
+
docs = [
|
|
37
|
+
Document(
|
|
38
|
+
page_content="社保卡丢失后,先挂失,再携带身份证到社保卡服务窗口补换。",
|
|
39
|
+
metadata={"title": "社保卡补换", "chunk_id": "policy-1"},
|
|
40
|
+
),
|
|
41
|
+
Document(
|
|
42
|
+
page_content="租房提取公积金需要身份证、银行卡、租赁合同或租房发票。",
|
|
43
|
+
metadata={"title": "公积金租房提取", "chunk_id": "policy-2"},
|
|
44
|
+
),
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
Chroma.from_documents(
|
|
48
|
+
documents=docs,
|
|
49
|
+
embedding=embeddings,
|
|
50
|
+
ids=[doc.metadata["chunk_id"] for doc in docs],
|
|
51
|
+
persist_directory="./chroma_db",
|
|
52
|
+
collection_name="study",
|
|
53
|
+
)
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## 使用
|
|
57
|
+
|
|
58
|
+
```python
|
|
59
|
+
from gov_modular_rag import ModularRAG
|
|
60
|
+
|
|
61
|
+
rag = ModularRAG({
|
|
62
|
+
"persist_directory": "./chroma_db",
|
|
63
|
+
"collection_name": "study",
|
|
64
|
+
"embedding_model": "text-embedding-v4",
|
|
65
|
+
"top_k": 5,
|
|
66
|
+
"recall_top_k": 20,
|
|
67
|
+
"pre_retrieval": {
|
|
68
|
+
"enabled": False,
|
|
69
|
+
"rewrite_query": False,
|
|
70
|
+
"hyde": False,
|
|
71
|
+
"model": "qwen-plus",
|
|
72
|
+
},
|
|
73
|
+
"hybrid_retrieval": {
|
|
74
|
+
"enabled": True,
|
|
75
|
+
"weights": [0.5, 0.5],
|
|
76
|
+
},
|
|
77
|
+
"post_retrieval": {
|
|
78
|
+
"enabled": True,
|
|
79
|
+
"deduplicate": True,
|
|
80
|
+
"rerank": False,
|
|
81
|
+
"rerank_model": "qwen3-rerank",
|
|
82
|
+
"similarity_filter": False,
|
|
83
|
+
"similarity_threshold": 0.4,
|
|
84
|
+
"compress_context": False,
|
|
85
|
+
"llm_model": "qwen-plus",
|
|
86
|
+
"reorder": False,
|
|
87
|
+
},
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
results = rag.search("公司打卡时间?")
|
|
91
|
+
for document in results:
|
|
92
|
+
print(document.metadata)
|
|
93
|
+
print(document.page_content)
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
`search()` 返回 `list[Document]`,可以直接拿来拼 Prompt:
|
|
97
|
+
|
|
98
|
+
```python
|
|
99
|
+
context = "\n\n".join(
|
|
100
|
+
f"[{i}] {doc.page_content}"
|
|
101
|
+
for i, doc in enumerate(results, start=1)
|
|
102
|
+
)
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
## 配置说明
|
|
106
|
+
|
|
107
|
+
| 参数 | 默认值 | 作用 |
|
|
108
|
+
| --- | --- | --- |
|
|
109
|
+
| `persist_directory` | 必填 | 已有 Chroma 持久化目录 |
|
|
110
|
+
| `collection_name` | `study` | Chroma 集合名 |
|
|
111
|
+
| `embedding_model` | `text-embedding-v4` | 通义向量模型 |
|
|
112
|
+
| `top_k` | `5` | 最终返回条数 |
|
|
113
|
+
| `recall_top_k` | `20` | 向量/BM25 每路召回条数 |
|
|
114
|
+
| `pre_retrieval.enabled` | `False` | 是否启用查询预处理 |
|
|
115
|
+
| `pre_retrieval.rewrite_query` | `False` | 是否做查询改写 |
|
|
116
|
+
| `pre_retrieval.hyde` | `False` | 是否生成 HyDE 假设答案 |
|
|
117
|
+
| `pre_retrieval.model` | `qwen-plus` | 改写/HyDE 使用的模型 |
|
|
118
|
+
| `hybrid_retrieval.enabled` | `True` | 是否启用向量 + BM25 混合检索 |
|
|
119
|
+
| `hybrid_retrieval.weights` | `[0.5, 0.5]` | 两路 RRF 权重 |
|
|
120
|
+
| `post_retrieval.enabled` | `True` | 是否启用后处理 |
|
|
121
|
+
| `post_retrieval.deduplicate` | `True` | 按 chunk_id 和正文去重 |
|
|
122
|
+
| `post_retrieval.similarity_filter` | `False` | 是否按余弦相似度过滤 |
|
|
123
|
+
| `post_retrieval.similarity_threshold` | `0.4` | 相似度阈值 |
|
|
124
|
+
| `post_retrieval.rerank` | `False` | 是否调用 DashScope 重排 |
|
|
125
|
+
| `post_retrieval.rerank_model` | `qwen3-rerank` | 重排模型 |
|
|
126
|
+
| `post_retrieval.compress_context` | `False` | 是否用 LLM 抽取相关句 |
|
|
127
|
+
| `post_retrieval.llm_model` | `qwen-plus` | 压缩使用的模型 |
|
|
128
|
+
| `post_retrieval.reorder` | `False` | 是否按余弦相似度重排 |
|
|
129
|
+
|
|
130
|
+
预处理、重排和压缩都会产生额外的大模型调用,第一次调试建议先保持关闭。
|
|
131
|
+
|
|
132
|
+
## 环境变量
|
|
133
|
+
|
|
134
|
+
```bash
|
|
135
|
+
# Windows PowerShell
|
|
136
|
+
$env:DASHSCOPE_API_KEY="你的 API Key"
|
|
137
|
+
|
|
138
|
+
# macOS / Linux
|
|
139
|
+
export DASHSCOPE_API_KEY="你的 API Key"
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
代码也支持 `DASHSCOPE_BASE_URL`;不设置时默认使用:
|
|
143
|
+
|
|
144
|
+
```text
|
|
145
|
+
https://dashscope.aliyuncs.com/compatible-mode/v1
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
## 说明与限制
|
|
149
|
+
|
|
150
|
+
- 只读取已有 Chroma 库;如果集合为空,`search()` 会返回空列表。
|
|
151
|
+
- BM25 语料在第一次检索时从 Chroma 读取并缓存;知识库更新后调用 `rag.refresh()`。
|
|
152
|
+
- 混合检索使用 RRF 排名融合,分数是排名分,不是余弦相似度。
|
|
153
|
+
- `rerank`、`compress_context`、`rewrite_query`、`hyde` 需要可用的通义 API Key。
|
|
154
|
+
- 当前不包含文档切分和自动入库;入库请参考上面的“准备知识库”。
|
|
155
|
+
|
|
156
|
+
## 本地构建
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
pip install build twine
|
|
160
|
+
python -m build
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
构建完成后会在 `dist/` 下生成:
|
|
164
|
+
|
|
165
|
+
- `gov_modular_rag-0.1.0-py3-none-any.whl`
|
|
166
|
+
- `gov_modular_rag-0.1.0.tar.gz`
|
|
167
|
+
|
|
168
|
+
## 发布到 PyPI
|
|
169
|
+
|
|
170
|
+
先注册 PyPI 账号并创建 API Token,然后执行:
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
twine upload dist/*
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
用户名填 `__token__`,密码填 PyPI Token。
|
|
177
|
+
|
|
178
|
+
## License
|
|
179
|
+
|
|
180
|
+
MIT
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gov-modular-rag
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A configurable modular RAG retrieval layer for existing Chroma knowledge bases
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Keywords: rag,langchain,chroma,retrieval,government
|
|
7
|
+
Requires-Python: >=3.11
|
|
8
|
+
Description-Content-Type: text/markdown
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Requires-Dist: chromadb
|
|
11
|
+
Requires-Dist: langchain-chroma
|
|
12
|
+
Requires-Dist: langchain-community
|
|
13
|
+
Requires-Dist: langchain-core
|
|
14
|
+
Requires-Dist: langchain-openai
|
|
15
|
+
Requires-Dist: jieba
|
|
16
|
+
Requires-Dist: rank-bm25
|
|
17
|
+
Requires-Dist: python-dotenv
|
|
18
|
+
Requires-Dist: dashscope
|
|
19
|
+
Provides-Extra: publish
|
|
20
|
+
Requires-Dist: build; extra == "publish"
|
|
21
|
+
Requires-Dist: twine; extra == "publish"
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
|
|
24
|
+
# gov-modular-rag
|
|
25
|
+
|
|
26
|
+
一个面向政务问答场景的模块化 RAG 检索包:连接**已经建好的 Chroma 知识库**,提供向量检索、BM25 混合检索、RRF 融合、去重、相似度过滤、重排和上下文压缩。
|
|
27
|
+
|
|
28
|
+
> 说明:教程中的 `langchain-modular-rag` 已由其他作者发布到 PyPI;本项目使用 `gov-modular-rag`,避免同名冲突。
|
|
29
|
+
>
|
|
30
|
+
> 本包只做在线检索,不包含你的知识库数据,也不会自动创建或导入知识库。
|
|
31
|
+
|
|
32
|
+
## 安装
|
|
33
|
+
|
|
34
|
+
从源码目录安装:
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install -e .
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
发布到 PyPI 后可以这样安装:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install gov-modular-rag
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
Python 3.11 及以上。
|
|
47
|
+
|
|
48
|
+
## 准备知识库
|
|
49
|
+
|
|
50
|
+
先准备一个 Chroma 持久化目录。下面是最小入库示例:
|
|
51
|
+
|
|
52
|
+
```python
|
|
53
|
+
from langchain_chroma import Chroma
|
|
54
|
+
from langchain_community.embeddings import DashScopeEmbeddings
|
|
55
|
+
from langchain_core.documents import Document
|
|
56
|
+
|
|
57
|
+
embeddings = DashScopeEmbeddings(model="text-embedding-v4")
|
|
58
|
+
|
|
59
|
+
docs = [
|
|
60
|
+
Document(
|
|
61
|
+
page_content="社保卡丢失后,先挂失,再携带身份证到社保卡服务窗口补换。",
|
|
62
|
+
metadata={"title": "社保卡补换", "chunk_id": "policy-1"},
|
|
63
|
+
),
|
|
64
|
+
Document(
|
|
65
|
+
page_content="租房提取公积金需要身份证、银行卡、租赁合同或租房发票。",
|
|
66
|
+
metadata={"title": "公积金租房提取", "chunk_id": "policy-2"},
|
|
67
|
+
),
|
|
68
|
+
]
|
|
69
|
+
|
|
70
|
+
Chroma.from_documents(
|
|
71
|
+
documents=docs,
|
|
72
|
+
embedding=embeddings,
|
|
73
|
+
ids=[doc.metadata["chunk_id"] for doc in docs],
|
|
74
|
+
persist_directory="./chroma_db",
|
|
75
|
+
collection_name="study",
|
|
76
|
+
)
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## 使用
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from gov_modular_rag import ModularRAG
|
|
83
|
+
|
|
84
|
+
rag = ModularRAG({
|
|
85
|
+
"persist_directory": "./chroma_db",
|
|
86
|
+
"collection_name": "study",
|
|
87
|
+
"embedding_model": "text-embedding-v4",
|
|
88
|
+
"top_k": 5,
|
|
89
|
+
"recall_top_k": 20,
|
|
90
|
+
"pre_retrieval": {
|
|
91
|
+
"enabled": False,
|
|
92
|
+
"rewrite_query": False,
|
|
93
|
+
"hyde": False,
|
|
94
|
+
"model": "qwen-plus",
|
|
95
|
+
},
|
|
96
|
+
"hybrid_retrieval": {
|
|
97
|
+
"enabled": True,
|
|
98
|
+
"weights": [0.5, 0.5],
|
|
99
|
+
},
|
|
100
|
+
"post_retrieval": {
|
|
101
|
+
"enabled": True,
|
|
102
|
+
"deduplicate": True,
|
|
103
|
+
"rerank": False,
|
|
104
|
+
"rerank_model": "qwen3-rerank",
|
|
105
|
+
"similarity_filter": False,
|
|
106
|
+
"similarity_threshold": 0.4,
|
|
107
|
+
"compress_context": False,
|
|
108
|
+
"llm_model": "qwen-plus",
|
|
109
|
+
"reorder": False,
|
|
110
|
+
},
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
results = rag.search("公司打卡时间?")
|
|
114
|
+
for document in results:
|
|
115
|
+
print(document.metadata)
|
|
116
|
+
print(document.page_content)
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`search()` 返回 `list[Document]`,可以直接拿来拼 Prompt:
|
|
120
|
+
|
|
121
|
+
```python
|
|
122
|
+
context = "\n\n".join(
|
|
123
|
+
f"[{i}] {doc.page_content}"
|
|
124
|
+
for i, doc in enumerate(results, start=1)
|
|
125
|
+
)
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
## 配置说明
|
|
129
|
+
|
|
130
|
+
| 参数 | 默认值 | 作用 |
|
|
131
|
+
| --- | --- | --- |
|
|
132
|
+
| `persist_directory` | 必填 | 已有 Chroma 持久化目录 |
|
|
133
|
+
| `collection_name` | `study` | Chroma 集合名 |
|
|
134
|
+
| `embedding_model` | `text-embedding-v4` | 通义向量模型 |
|
|
135
|
+
| `top_k` | `5` | 最终返回条数 |
|
|
136
|
+
| `recall_top_k` | `20` | 向量/BM25 每路召回条数 |
|
|
137
|
+
| `pre_retrieval.enabled` | `False` | 是否启用查询预处理 |
|
|
138
|
+
| `pre_retrieval.rewrite_query` | `False` | 是否做查询改写 |
|
|
139
|
+
| `pre_retrieval.hyde` | `False` | 是否生成 HyDE 假设答案 |
|
|
140
|
+
| `pre_retrieval.model` | `qwen-plus` | 改写/HyDE 使用的模型 |
|
|
141
|
+
| `hybrid_retrieval.enabled` | `True` | 是否启用向量 + BM25 混合检索 |
|
|
142
|
+
| `hybrid_retrieval.weights` | `[0.5, 0.5]` | 两路 RRF 权重 |
|
|
143
|
+
| `post_retrieval.enabled` | `True` | 是否启用后处理 |
|
|
144
|
+
| `post_retrieval.deduplicate` | `True` | 按 chunk_id 和正文去重 |
|
|
145
|
+
| `post_retrieval.similarity_filter` | `False` | 是否按余弦相似度过滤 |
|
|
146
|
+
| `post_retrieval.similarity_threshold` | `0.4` | 相似度阈值 |
|
|
147
|
+
| `post_retrieval.rerank` | `False` | 是否调用 DashScope 重排 |
|
|
148
|
+
| `post_retrieval.rerank_model` | `qwen3-rerank` | 重排模型 |
|
|
149
|
+
| `post_retrieval.compress_context` | `False` | 是否用 LLM 抽取相关句 |
|
|
150
|
+
| `post_retrieval.llm_model` | `qwen-plus` | 压缩使用的模型 |
|
|
151
|
+
| `post_retrieval.reorder` | `False` | 是否按余弦相似度重排 |
|
|
152
|
+
|
|
153
|
+
预处理、重排和压缩都会产生额外的大模型调用,第一次调试建议先保持关闭。
|
|
154
|
+
|
|
155
|
+
## 环境变量
|
|
156
|
+
|
|
157
|
+
```bash
|
|
158
|
+
# Windows PowerShell
|
|
159
|
+
$env:DASHSCOPE_API_KEY="你的 API Key"
|
|
160
|
+
|
|
161
|
+
# macOS / Linux
|
|
162
|
+
export DASHSCOPE_API_KEY="你的 API Key"
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
代码也支持 `DASHSCOPE_BASE_URL`;不设置时默认使用:
|
|
166
|
+
|
|
167
|
+
```text
|
|
168
|
+
https://dashscope.aliyuncs.com/compatible-mode/v1
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
## 说明与限制
|
|
172
|
+
|
|
173
|
+
- 只读取已有 Chroma 库;如果集合为空,`search()` 会返回空列表。
|
|
174
|
+
- BM25 语料在第一次检索时从 Chroma 读取并缓存;知识库更新后调用 `rag.refresh()`。
|
|
175
|
+
- 混合检索使用 RRF 排名融合,分数是排名分,不是余弦相似度。
|
|
176
|
+
- `rerank`、`compress_context`、`rewrite_query`、`hyde` 需要可用的通义 API Key。
|
|
177
|
+
- 当前不包含文档切分和自动入库;入库请参考上面的“准备知识库”。
|
|
178
|
+
|
|
179
|
+
## 本地构建
|
|
180
|
+
|
|
181
|
+
```bash
|
|
182
|
+
pip install build twine
|
|
183
|
+
python -m build
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
构建完成后会在 `dist/` 下生成:
|
|
187
|
+
|
|
188
|
+
- `gov_modular_rag-0.1.0-py3-none-any.whl`
|
|
189
|
+
- `gov_modular_rag-0.1.0.tar.gz`
|
|
190
|
+
|
|
191
|
+
## 发布到 PyPI
|
|
192
|
+
|
|
193
|
+
先注册 PyPI 账号并创建 API Token,然后执行:
|
|
194
|
+
|
|
195
|
+
```bash
|
|
196
|
+
twine upload dist/*
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
用户名填 `__token__`,密码填 PyPI Token。
|
|
200
|
+
|
|
201
|
+
## License
|
|
202
|
+
|
|
203
|
+
MIT
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gov_modular_rag
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""A small, configurable RAG retrieval layer for an existing Chroma store.
|
|
3
|
+
|
|
4
|
+
This module is intentionally independent from the author's course files. It
|
|
5
|
+
only performs online retrieval: it never creates or imports a knowledge base.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import hashlib
|
|
11
|
+
import logging
|
|
12
|
+
import math
|
|
13
|
+
import os
|
|
14
|
+
import re
|
|
15
|
+
from copy import deepcopy
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import Any
|
|
18
|
+
|
|
19
|
+
import jieba
|
|
20
|
+
from dotenv import load_dotenv
|
|
21
|
+
from langchain_chroma import Chroma
|
|
22
|
+
from langchain_community.embeddings import DashScopeEmbeddings
|
|
23
|
+
from langchain_core.documents import Document
|
|
24
|
+
from langchain_core.messages import HumanMessage, SystemMessage
|
|
25
|
+
from langchain_openai import ChatOpenAI
|
|
26
|
+
|
|
27
|
+
try: # Keep jieba's normal startup logs out of library users' consoles.
|
|
28
|
+
jieba.setLogLevel(logging.ERROR)
|
|
29
|
+
except AttributeError: # pragma: no cover - compatibility with old jieba
|
|
30
|
+
pass
|
|
31
|
+
|
|
32
|
+
__all__ = ["ModularRAG"]
|
|
33
|
+
__version__ = "0.1.0"
|
|
34
|
+
|
|
35
|
+
_DEFAULT_CONFIG: dict[str, Any] = {
|
|
36
|
+
"persist_directory": "",
|
|
37
|
+
"collection_name": "study",
|
|
38
|
+
"embedding_model": "text-embedding-v4",
|
|
39
|
+
"top_k": 5,
|
|
40
|
+
"recall_top_k": 20,
|
|
41
|
+
"pre_retrieval": {
|
|
42
|
+
"enabled": False,
|
|
43
|
+
"rewrite_query": False,
|
|
44
|
+
"hyde": False,
|
|
45
|
+
"model": "qwen-plus",
|
|
46
|
+
},
|
|
47
|
+
"hybrid_retrieval": {
|
|
48
|
+
"enabled": True,
|
|
49
|
+
"weights": [0.5, 0.5],
|
|
50
|
+
},
|
|
51
|
+
"post_retrieval": {
|
|
52
|
+
"enabled": True,
|
|
53
|
+
"deduplicate": True,
|
|
54
|
+
"rerank": False,
|
|
55
|
+
"rerank_model": "qwen3-rerank",
|
|
56
|
+
"similarity_filter": False,
|
|
57
|
+
"similarity_threshold": 0.4,
|
|
58
|
+
"compress_context": False,
|
|
59
|
+
"llm_model": "qwen-plus",
|
|
60
|
+
"reorder": False,
|
|
61
|
+
},
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
_DASHSCOPE_BASE_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:
|
|
68
|
+
"""Merge nested config dictionaries without mutating the defaults."""
|
|
69
|
+
result = deepcopy(base)
|
|
70
|
+
for key, value in override.items():
|
|
71
|
+
if isinstance(value, dict) and isinstance(result.get(key), dict):
|
|
72
|
+
result[key] = _deep_merge(result[key], value)
|
|
73
|
+
else:
|
|
74
|
+
result[key] = deepcopy(value)
|
|
75
|
+
return result
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _text_key(text: str) -> str:
|
|
79
|
+
return hashlib.sha1(text.encode("utf-8")).hexdigest()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _doc_key(doc: Document) -> str:
|
|
83
|
+
value = (doc.metadata or {}).get("chunk_id")
|
|
84
|
+
return str(value) if value else _text_key(doc.page_content)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _copy_doc(doc: Document, *, metadata: dict[str, Any] | None = None) -> Document:
|
|
88
|
+
return Document(
|
|
89
|
+
page_content=doc.page_content,
|
|
90
|
+
metadata=metadata if metadata is not None else dict(doc.metadata or {}),
|
|
91
|
+
id=getattr(doc, "id", None),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
class ModularRAG:
|
|
96
|
+
"""Connect to an existing Chroma collection and run a modular RAG pipeline.
|
|
97
|
+
|
|
98
|
+
Parameters
|
|
99
|
+
----------
|
|
100
|
+
config:
|
|
101
|
+
Configuration dictionary. The accepted keys and defaults match the
|
|
102
|
+
README. Only ``persist_directory`` is required.
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(self, config: dict[str, Any]) -> None:
|
|
106
|
+
if not isinstance(config, dict):
|
|
107
|
+
raise TypeError("config 必须是字典")
|
|
108
|
+
self.config = _deep_merge(_DEFAULT_CONFIG, config)
|
|
109
|
+
load_dotenv(override=False)
|
|
110
|
+
# 安装后的包不在项目目录里,额外读取当前工作目录的 .env,
|
|
111
|
+
# 方便从项目根目录直接运行示例。
|
|
112
|
+
load_dotenv(dotenv_path=Path.cwd() / ".env", override=False)
|
|
113
|
+
|
|
114
|
+
persist_directory = str(self.config.get("persist_directory") or "").strip()
|
|
115
|
+
if not persist_directory:
|
|
116
|
+
raise ValueError("config['persist_directory'] 不能为空")
|
|
117
|
+
path = Path(persist_directory).expanduser()
|
|
118
|
+
if not path.exists():
|
|
119
|
+
raise FileNotFoundError(f"Chroma 目录不存在: {path}")
|
|
120
|
+
self.persist_directory = str(path)
|
|
121
|
+
|
|
122
|
+
if not os.getenv("DASHSCOPE_API_KEY"):
|
|
123
|
+
raise RuntimeError("没有找到 DASHSCOPE_API_KEY,请先配置环境变量")
|
|
124
|
+
|
|
125
|
+
self.collection_name = str(
|
|
126
|
+
self.config.get("collection_name") or "study"
|
|
127
|
+
).strip()
|
|
128
|
+
self.embedding_model = str(
|
|
129
|
+
self.config.get("embedding_model") or "text-embedding-v4"
|
|
130
|
+
).strip()
|
|
131
|
+
self.top_k = max(0, int(self.config.get("top_k", 5)))
|
|
132
|
+
self.recall_top_k = max(1, int(self.config.get("recall_top_k", 20)))
|
|
133
|
+
|
|
134
|
+
self.embeddings = DashScopeEmbeddings(model=self.embedding_model)
|
|
135
|
+
self.db = Chroma(
|
|
136
|
+
persist_directory=self.persist_directory,
|
|
137
|
+
collection_name=self.collection_name,
|
|
138
|
+
embedding_function=self.embeddings,
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
self._all_docs: list[Document] | None = None
|
|
142
|
+
self._bm25 = None
|
|
143
|
+
self._llm_cache: dict[str, ChatOpenAI] = {}
|
|
144
|
+
|
|
145
|
+
# ------------------------------------------------------------------
|
|
146
|
+
# Public API
|
|
147
|
+
# ------------------------------------------------------------------
|
|
148
|
+
def search(self, question: str) -> list[Document]:
|
|
149
|
+
"""Retrieve the most relevant documents for one question."""
|
|
150
|
+
if not isinstance(question, str):
|
|
151
|
+
raise TypeError("question 必须是字符串")
|
|
152
|
+
question = question.strip()
|
|
153
|
+
if not question or self.top_k == 0:
|
|
154
|
+
return []
|
|
155
|
+
|
|
156
|
+
query = re.sub(r"\s+", " ", question).strip()
|
|
157
|
+
search_query = query
|
|
158
|
+
pre = self.config["pre_retrieval"]
|
|
159
|
+
if pre.get("enabled"):
|
|
160
|
+
if pre.get("rewrite_query"):
|
|
161
|
+
query = self._rewrite(query, str(pre.get("model") or "qwen-plus"))
|
|
162
|
+
search_query = query
|
|
163
|
+
if pre.get("hyde"):
|
|
164
|
+
search_query = self._hyde(
|
|
165
|
+
query, str(pre.get("model") or "qwen-plus")
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
vector_docs = self._vector_search(search_query, self.recall_top_k)
|
|
169
|
+
hybrid = self.config["hybrid_retrieval"]
|
|
170
|
+
if hybrid.get("enabled"):
|
|
171
|
+
bm25_docs = self._bm25_search(query, self.recall_top_k)
|
|
172
|
+
weights = hybrid.get("weights") or [0.5, 0.5]
|
|
173
|
+
docs = self._rrf(vector_docs, bm25_docs, weights=weights)
|
|
174
|
+
else:
|
|
175
|
+
docs = vector_docs
|
|
176
|
+
|
|
177
|
+
post = self.config["post_retrieval"]
|
|
178
|
+
if post.get("enabled"):
|
|
179
|
+
if post.get("deduplicate"):
|
|
180
|
+
docs = self._deduplicate(docs)
|
|
181
|
+
if post.get("similarity_filter"):
|
|
182
|
+
docs = self._similarity_filter(
|
|
183
|
+
query,
|
|
184
|
+
docs,
|
|
185
|
+
threshold=float(post.get("similarity_threshold", 0.4)),
|
|
186
|
+
)
|
|
187
|
+
if post.get("rerank"):
|
|
188
|
+
docs = self._rerank(
|
|
189
|
+
query,
|
|
190
|
+
docs,
|
|
191
|
+
top_k=self.top_k,
|
|
192
|
+
model=str(post.get("rerank_model") or "qwen3-rerank"),
|
|
193
|
+
)
|
|
194
|
+
if post.get("compress_context"):
|
|
195
|
+
docs = self._compress_context(
|
|
196
|
+
query,
|
|
197
|
+
docs,
|
|
198
|
+
model=str(post.get("llm_model") or "qwen-plus"),
|
|
199
|
+
)
|
|
200
|
+
if post.get("reorder"):
|
|
201
|
+
docs = self._reorder(docs)
|
|
202
|
+
|
|
203
|
+
return docs[: self.top_k]
|
|
204
|
+
|
|
205
|
+
def refresh(self) -> None:
|
|
206
|
+
"""Forget the cached BM25 corpus after the collection has changed."""
|
|
207
|
+
self._all_docs = None
|
|
208
|
+
self._bm25 = None
|
|
209
|
+
|
|
210
|
+
# ------------------------------------------------------------------
|
|
211
|
+
# Retrieval primitives
|
|
212
|
+
# ------------------------------------------------------------------
|
|
213
|
+
def _vector_search(self, question: str, top_k: int) -> list[Document]:
|
|
214
|
+
results = self.db.similarity_search_with_score(question, k=top_k)
|
|
215
|
+
docs: list[Document] = []
|
|
216
|
+
for doc, distance in results:
|
|
217
|
+
metadata = dict(doc.metadata or {})
|
|
218
|
+
metadata.setdefault("chunk_id", _text_key(doc.page_content))
|
|
219
|
+
metadata["vector_distance"] = float(distance)
|
|
220
|
+
docs.append(_copy_doc(doc, metadata=metadata))
|
|
221
|
+
return docs
|
|
222
|
+
|
|
223
|
+
def _all_documents(self) -> list[Document]:
|
|
224
|
+
if self._all_docs is not None:
|
|
225
|
+
return self._all_docs
|
|
226
|
+
data = self.db.get(include=["documents", "metadatas"])
|
|
227
|
+
texts = data.get("documents") or []
|
|
228
|
+
metadatas = data.get("metadatas") or []
|
|
229
|
+
ids = data.get("ids") or []
|
|
230
|
+
docs: list[Document] = []
|
|
231
|
+
for index, text in enumerate(texts):
|
|
232
|
+
if not text:
|
|
233
|
+
continue
|
|
234
|
+
metadata = dict(metadatas[index] or {}) if index < len(metadatas) else {}
|
|
235
|
+
metadata.setdefault(
|
|
236
|
+
"chunk_id",
|
|
237
|
+
ids[index] if index < len(ids) and ids[index] else _text_key(text),
|
|
238
|
+
)
|
|
239
|
+
docs.append(Document(page_content=text, metadata=metadata))
|
|
240
|
+
self._all_docs = docs
|
|
241
|
+
return docs
|
|
242
|
+
|
|
243
|
+
def _bm25_search(self, question: str, top_k: int) -> list[Document]:
|
|
244
|
+
documents = self._all_documents()
|
|
245
|
+
if not documents:
|
|
246
|
+
return []
|
|
247
|
+
from langchain_community.retrievers import BM25Retriever
|
|
248
|
+
|
|
249
|
+
k = max(1, min(top_k, len(documents)))
|
|
250
|
+
if self._bm25 is None:
|
|
251
|
+
self._bm25 = BM25Retriever.from_documents(
|
|
252
|
+
documents,
|
|
253
|
+
preprocess_func=lambda text: list(jieba.cut(text)),
|
|
254
|
+
k=k,
|
|
255
|
+
)
|
|
256
|
+
else:
|
|
257
|
+
self._bm25.k = k
|
|
258
|
+
return list(self._bm25.invoke(question))
|
|
259
|
+
|
|
260
|
+
@staticmethod
|
|
261
|
+
def _rrf(
|
|
262
|
+
vector_docs: list[Document],
|
|
263
|
+
bm25_docs: list[Document],
|
|
264
|
+
*,
|
|
265
|
+
weights: list[float] | None = None,
|
|
266
|
+
rrf_k: int = 60,
|
|
267
|
+
) -> list[Document]:
|
|
268
|
+
weights = list(weights or [0.5, 0.5])
|
|
269
|
+
if len(weights) != 2:
|
|
270
|
+
weights = [0.5, 0.5]
|
|
271
|
+
scores: dict[str, float] = {}
|
|
272
|
+
docs_by_key: dict[str, Document] = {}
|
|
273
|
+
for docs, weight in zip((vector_docs, bm25_docs), weights):
|
|
274
|
+
for rank, doc in enumerate(docs):
|
|
275
|
+
key = _doc_key(doc)
|
|
276
|
+
docs_by_key.setdefault(key, _copy_doc(doc))
|
|
277
|
+
scores[key] = scores.get(key, 0.0) + float(weight) / (
|
|
278
|
+
rrf_k + rank + 1
|
|
279
|
+
)
|
|
280
|
+
return [
|
|
281
|
+
docs_by_key[key]
|
|
282
|
+
for key in sorted(scores, key=lambda item: scores[item], reverse=True)
|
|
283
|
+
]
|
|
284
|
+
|
|
285
|
+
# ------------------------------------------------------------------
|
|
286
|
+
# Post retrieval
|
|
287
|
+
# ------------------------------------------------------------------
|
|
288
|
+
@staticmethod
|
|
289
|
+
def _deduplicate(docs: list[Document]) -> list[Document]:
|
|
290
|
+
seen_keys: set[str] = set()
|
|
291
|
+
seen_texts: set[str] = set()
|
|
292
|
+
result: list[Document] = []
|
|
293
|
+
for doc in docs:
|
|
294
|
+
key = _doc_key(doc)
|
|
295
|
+
text_key = _text_key(doc.page_content)
|
|
296
|
+
if key in seen_keys or text_key in seen_texts:
|
|
297
|
+
continue
|
|
298
|
+
seen_keys.add(key)
|
|
299
|
+
seen_texts.add(text_key)
|
|
300
|
+
result.append(doc)
|
|
301
|
+
return result
|
|
302
|
+
|
|
303
|
+
def _similarity_filter(
|
|
304
|
+
self,
|
|
305
|
+
question: str,
|
|
306
|
+
docs: list[Document],
|
|
307
|
+
*,
|
|
308
|
+
threshold: float,
|
|
309
|
+
) -> list[Document]:
|
|
310
|
+
if not docs:
|
|
311
|
+
return []
|
|
312
|
+
query_vector = self.embeddings.embed_query(question)
|
|
313
|
+
doc_vectors = self.embeddings.embed_documents(
|
|
314
|
+
[doc.page_content for doc in docs]
|
|
315
|
+
)
|
|
316
|
+
query_norm = math.sqrt(sum(value * value for value in query_vector))
|
|
317
|
+
if query_norm == 0:
|
|
318
|
+
return []
|
|
319
|
+
result: list[Document] = []
|
|
320
|
+
for doc, vector in zip(docs, doc_vectors):
|
|
321
|
+
norm = math.sqrt(sum(value * value for value in vector))
|
|
322
|
+
if norm == 0:
|
|
323
|
+
continue
|
|
324
|
+
similarity = sum(
|
|
325
|
+
query_value * value
|
|
326
|
+
for query_value, value in zip(query_vector, vector)
|
|
327
|
+
) / (query_norm * norm)
|
|
328
|
+
if similarity >= threshold:
|
|
329
|
+
metadata = dict(doc.metadata or {})
|
|
330
|
+
metadata["cosine_similarity"] = similarity
|
|
331
|
+
result.append(_copy_doc(doc, metadata=metadata))
|
|
332
|
+
return result
|
|
333
|
+
|
|
334
|
+
def _rerank(
|
|
335
|
+
self,
|
|
336
|
+
question: str,
|
|
337
|
+
docs: list[Document],
|
|
338
|
+
*,
|
|
339
|
+
top_k: int,
|
|
340
|
+
model: str,
|
|
341
|
+
) -> list[Document]:
|
|
342
|
+
if not docs:
|
|
343
|
+
return []
|
|
344
|
+
from langchain_community.document_compressors import DashScopeRerank
|
|
345
|
+
|
|
346
|
+
reranker = DashScopeRerank(
|
|
347
|
+
top_n=max(1, min(top_k, len(docs))),
|
|
348
|
+
model=model,
|
|
349
|
+
)
|
|
350
|
+
return list(reranker.compress_documents(docs, question))
|
|
351
|
+
|
|
352
|
+
def _compress_context(
|
|
353
|
+
self,
|
|
354
|
+
question: str,
|
|
355
|
+
docs: list[Document],
|
|
356
|
+
*,
|
|
357
|
+
model: str,
|
|
358
|
+
) -> list[Document]:
|
|
359
|
+
if not docs:
|
|
360
|
+
return []
|
|
361
|
+
llm = self._get_llm(model)
|
|
362
|
+
result: list[Document] = []
|
|
363
|
+
for doc in docs:
|
|
364
|
+
response = llm.invoke(
|
|
365
|
+
[
|
|
366
|
+
SystemMessage(
|
|
367
|
+
content=(
|
|
368
|
+
"从给定资料中抽取与问题直接相关的事实、条件或步骤。"
|
|
369
|
+
"不要补充资料外的事实;只输出抽取内容,没有相关内容就输出空字符串。"
|
|
370
|
+
)
|
|
371
|
+
),
|
|
372
|
+
HumanMessage(content=f"问题:{question}\n资料:{doc.page_content}"),
|
|
373
|
+
]
|
|
374
|
+
)
|
|
375
|
+
content = str(response.content or "").strip()
|
|
376
|
+
if content:
|
|
377
|
+
result.append(
|
|
378
|
+
Document(
|
|
379
|
+
page_content=content,
|
|
380
|
+
metadata=dict(doc.metadata or {}),
|
|
381
|
+
)
|
|
382
|
+
)
|
|
383
|
+
return result
|
|
384
|
+
|
|
385
|
+
@staticmethod
|
|
386
|
+
def _reorder(docs: list[Document]) -> list[Document]:
|
|
387
|
+
if not any("cosine_similarity" in (doc.metadata or {}) for doc in docs):
|
|
388
|
+
return docs
|
|
389
|
+
return sorted(
|
|
390
|
+
docs,
|
|
391
|
+
key=lambda doc: float((doc.metadata or {}).get("cosine_similarity", 0)),
|
|
392
|
+
reverse=True,
|
|
393
|
+
)
|
|
394
|
+
|
|
395
|
+
# ------------------------------------------------------------------
|
|
396
|
+
# Optional LLM preprocessing
|
|
397
|
+
# ------------------------------------------------------------------
|
|
398
|
+
def _get_llm(self, model: str) -> ChatOpenAI:
|
|
399
|
+
if model not in self._llm_cache:
|
|
400
|
+
self._llm_cache[model] = ChatOpenAI(
|
|
401
|
+
model=model,
|
|
402
|
+
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
|
403
|
+
base_url=os.getenv("DASHSCOPE_BASE_URL") or _DASHSCOPE_BASE_URL,
|
|
404
|
+
temperature=0,
|
|
405
|
+
timeout=90,
|
|
406
|
+
)
|
|
407
|
+
return self._llm_cache[model]
|
|
408
|
+
|
|
409
|
+
def _rewrite(self, question: str, model: str) -> str:
|
|
410
|
+
response = self._get_llm(model).invoke(
|
|
411
|
+
[
|
|
412
|
+
SystemMessage(
|
|
413
|
+
content=(
|
|
414
|
+
"把问题改写为适合知识库检索的独立查询。保留原意,"
|
|
415
|
+
"不要编造缺失上下文,只输出改写后的查询。"
|
|
416
|
+
)
|
|
417
|
+
),
|
|
418
|
+
HumanMessage(content=question),
|
|
419
|
+
]
|
|
420
|
+
)
|
|
421
|
+
return str(response.content or "").strip() or question
|
|
422
|
+
|
|
423
|
+
def _hyde(self, question: str, model: str) -> str:
|
|
424
|
+
response = self._get_llm(model).invoke(
|
|
425
|
+
[
|
|
426
|
+
SystemMessage(
|
|
427
|
+
content=(
|
|
428
|
+
"为问题生成约 100 字的假设性答案,用于语义检索。"
|
|
429
|
+
"只输出假设答案,不要把它当作事实证据。"
|
|
430
|
+
)
|
|
431
|
+
),
|
|
432
|
+
HumanMessage(content=question),
|
|
433
|
+
]
|
|
434
|
+
)
|
|
435
|
+
return str(response.content or "").strip() or question
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "gov-modular-rag"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A configurable modular RAG retrieval layer for existing Chroma knowledge bases"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
keywords = ["rag", "langchain", "chroma", "retrieval", "government"]
|
|
13
|
+
dependencies = [
|
|
14
|
+
"chromadb",
|
|
15
|
+
"langchain-chroma",
|
|
16
|
+
"langchain-community",
|
|
17
|
+
"langchain-core",
|
|
18
|
+
"langchain-openai",
|
|
19
|
+
"jieba",
|
|
20
|
+
"rank-bm25",
|
|
21
|
+
"python-dotenv",
|
|
22
|
+
"dashscope",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.optional-dependencies]
|
|
26
|
+
publish = ["build", "twine"]
|
|
27
|
+
|
|
28
|
+
[tool.setuptools]
|
|
29
|
+
py-modules = ["gov_modular_rag"]
|