ragconfig 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.
- ragconfig-0.1.0/LICENSE +21 -0
- ragconfig-0.1.0/PKG-INFO +267 -0
- ragconfig-0.1.0/RAGConfig.py +173 -0
- ragconfig-0.1.0/README.md +236 -0
- ragconfig-0.1.0/pyproject.toml +56 -0
- ragconfig-0.1.0/ragconfig.egg-info/PKG-INFO +267 -0
- ragconfig-0.1.0/ragconfig.egg-info/SOURCES.txt +9 -0
- ragconfig-0.1.0/ragconfig.egg-info/dependency_links.txt +1 -0
- ragconfig-0.1.0/ragconfig.egg-info/requires.txt +10 -0
- ragconfig-0.1.0/ragconfig.egg-info/top_level.txt +1 -0
- ragconfig-0.1.0/setup.cfg +4 -0
ragconfig-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 RAGConfig 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.
|
ragconfig-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ragconfig
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Modular RAG enhancement toolkit built on LangChain: query rewriting, expansion, decomposition, routing, HyDE, hybrid search, rerank and contextual compression.
|
|
5
|
+
Author: RAGConfig contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: rag,retrieval-augmented-generation,langchain,llm,hybrid-search,rerank,hyde
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: langchain-classic<2.0.0,>=1.0.0
|
|
22
|
+
Requires-Dist: langchain-community<1.0.0,>=0.4.0
|
|
23
|
+
Requires-Dist: langchain-core<2.0.0,>=1.0.0
|
|
24
|
+
Requires-Dist: langchain-openai<2.0.0,>=1.0.0
|
|
25
|
+
Requires-Dist: dashscope>=1.20.0
|
|
26
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
29
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# RAGConfig
|
|
33
|
+
|
|
34
|
+
[](https://pypi.org/project/ragconfig/)
|
|
35
|
+
[](https://pypi.org/project/ragconfig/)
|
|
36
|
+
[](LICENSE)
|
|
37
|
+
|
|
38
|
+
基于 LangChain 的模块化 RAG 增强工具。它把常见的检索增强环节分别封装成独立方法,并提供一个统一的开关配置:**默认全部关闭,按需打开**。关闭时方法会原样返回输入,因此你可以在流水线里无条件调用,而不需要到处写 `if`。
|
|
39
|
+
|
|
40
|
+
`RAGConfig` 只负责“使用”依赖,不负责“创建”依赖:大模型、向量检索器、BM25 检索器都由你构造后注入。
|
|
41
|
+
|
|
42
|
+
## 功能一览
|
|
43
|
+
|
|
44
|
+
| 能力 | 方法 | 说明 |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| 查询改写 | `query_rewrite` | 把口语化问题改写成适合检索的查询 |
|
|
47
|
+
| 查询扩展 | `query_expand` | 生成多个语义相近、表达不同的查询 |
|
|
48
|
+
| 查询分解 | `query_decompose` | 把复杂问题拆成可独立检索的子问题 |
|
|
49
|
+
| 查询路由 | `query_router` | 判断问题应该查询哪个知识库 |
|
|
50
|
+
| HyDE | `hyde` | 先生成假设答案,再用它去检索 |
|
|
51
|
+
| 混合检索 | `hybrid_search` | BM25 + 向量检索加权融合 |
|
|
52
|
+
| 多路召回 | `multi_route` | 预留接口,当前版本尚未实现 |
|
|
53
|
+
| 重排序 | `rerank` | 使用 DashScope Rerank 对候选文档重新打分 |
|
|
54
|
+
| 上下文压缩 | `contextual_compression` | 相似度过滤 → LLM 抽取 → 长上下文重排 |
|
|
55
|
+
|
|
56
|
+
## 安装
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install ragconfig
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
> 项目名为 `ragconfig`,导入的模块名是 `RAGConfig`,类名也是 `RAGConfig`:
|
|
63
|
+
>
|
|
64
|
+
> ```python
|
|
65
|
+
> from RAGConfig import RAGConfig
|
|
66
|
+
> ```
|
|
67
|
+
|
|
68
|
+
要求 Python 3.10 及以上。
|
|
69
|
+
|
|
70
|
+
如果要从源码安装开发版本:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pip install -e .
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## 环境变量
|
|
77
|
+
|
|
78
|
+
重排序和上下文压缩会调用阿里云百炼(DashScope),需要配置:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
DASHSCOPE_API_KEY=sk-xxxxxxxxxxxxxxxx
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
本库**不会自动加载 `.env`**。请在应用入口自行调用 `load_dotenv()`,或直接在运行环境中设置变量。
|
|
85
|
+
|
|
86
|
+
## 快速开始
|
|
87
|
+
|
|
88
|
+
下面的示例额外使用了 `langchain-chroma`、`jieba` 和 `rank_bm25` 来搭建演示用检索器:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
pip install langchain-chroma jieba rank_bm25
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
import os
|
|
96
|
+
|
|
97
|
+
import jieba
|
|
98
|
+
from dotenv import load_dotenv
|
|
99
|
+
from langchain_chroma import Chroma
|
|
100
|
+
from langchain_community.embeddings import DashScopeEmbeddings
|
|
101
|
+
from langchain_community.retrievers import BM25Retriever
|
|
102
|
+
from langchain_core.documents import Document
|
|
103
|
+
from langchain_openai import ChatOpenAI
|
|
104
|
+
|
|
105
|
+
from RAGConfig import RAGConfig
|
|
106
|
+
|
|
107
|
+
load_dotenv()
|
|
108
|
+
|
|
109
|
+
# 1. 依赖:大模型 + 向量模型
|
|
110
|
+
llm = ChatOpenAI(
|
|
111
|
+
model="deepseek-flash",
|
|
112
|
+
api_key=os.getenv("DEEPSEEK_API_KEY"),
|
|
113
|
+
base_url=os.getenv("DEEPSEEK_BASE_URL"),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
embeddings = DashScopeEmbeddings(
|
|
117
|
+
model="text-embedding-v4",
|
|
118
|
+
dashscope_api_key=os.getenv("DASHSCOPE_API_KEY"),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
# 2. 知识库与两路检索器
|
|
122
|
+
docs = [
|
|
123
|
+
Document(page_content="500ml 便携保温杯,316 不锈钢内胆,保温 12 小时。",
|
|
124
|
+
metadata={"category": "产品规格"}),
|
|
125
|
+
Document(page_content="首次使用请用温水清洗,不可放入洗碗机,不可微波加热。",
|
|
126
|
+
metadata={"category": "使用与保养"}),
|
|
127
|
+
Document(page_content="支持 7 天无理由退换货,自购买之日起享受一年质保。",
|
|
128
|
+
metadata={"category": "售后政策"}),
|
|
129
|
+
]
|
|
130
|
+
|
|
131
|
+
store = Chroma.from_documents(docs, embeddings)
|
|
132
|
+
vector_retriever = store.as_retriever(search_kwargs={"k": 3})
|
|
133
|
+
|
|
134
|
+
bm25_retriever = BM25Retriever.from_documents(
|
|
135
|
+
docs,
|
|
136
|
+
preprocess_func=lambda text: list(jieba.cut(text)), # 中文必须先分词
|
|
137
|
+
k=3,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
# 3. 创建并开启需要的环节
|
|
141
|
+
rag = RAGConfig(
|
|
142
|
+
llm=llm,
|
|
143
|
+
vector_retriever=vector_retriever,
|
|
144
|
+
bm25_retriever=bm25_retriever,
|
|
145
|
+
embedding_model="text-embedding-v4",
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
rag.control(
|
|
149
|
+
enable_query_rewrite=True,
|
|
150
|
+
enable_hyde=True,
|
|
151
|
+
enable_hybrid_search=True,
|
|
152
|
+
enable_rerank=True,
|
|
153
|
+
enable_contextual_compression=True,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
# 4. 组装检索流水线
|
|
157
|
+
question = "保温杯能不能放进洗碗机清洗?"
|
|
158
|
+
|
|
159
|
+
query = rag.query_rewrite(question) # 改写口语化问题
|
|
160
|
+
query = rag.hyde(query) # 用假设答案增强语义
|
|
161
|
+
candidates = rag.hybrid_search(query) # BM25 + 向量融合召回
|
|
162
|
+
candidates = rag.rerank(query, candidates) # DashScope 精排(保留 top 3)
|
|
163
|
+
documents = rag.contextual_compression(query, candidates)
|
|
164
|
+
|
|
165
|
+
for doc in documents:
|
|
166
|
+
print("-", doc.page_content)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## 配置项
|
|
170
|
+
|
|
171
|
+
通过 `rag.control(**config)` 修改配置。键名不存在时会抛出 `ValueError`:
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
rag.control(enable_rerank=True) # 打开重排序
|
|
175
|
+
rag.control(enable_hyde=False) # 关闭 HyDE
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
| 配置键 | 默认值 | 作用 |
|
|
179
|
+
| --- | --- | --- |
|
|
180
|
+
| `enable_query_rewrite` | `False` | 查询改写 |
|
|
181
|
+
| `enable_query_expand` | `False` | 查询扩展 |
|
|
182
|
+
| `enable_query_decompose` | `False` | 查询分解 |
|
|
183
|
+
| `enable_query_router` | `False` | 查询路由(注意键名是 `router`) |
|
|
184
|
+
| `enable_hyde` | `False` | HyDE 假设答案 |
|
|
185
|
+
| `enable_hybrid_search` | `False` | 混合检索 |
|
|
186
|
+
| `enable_multi_route` | `False` | 多路召回(预留,当前无效果) |
|
|
187
|
+
| `enable_rerank` | `False` | 重排序 |
|
|
188
|
+
| `enable_contextual_compression` | `False` | 上下文压缩 |
|
|
189
|
+
|
|
190
|
+
未列出的增强参数(混合检索权重、重排序 `top_n`、压缩阈值等)当前版本固定在代码中,见下文“已知限制”。
|
|
191
|
+
|
|
192
|
+
## API 说明
|
|
193
|
+
|
|
194
|
+
所有方法的第一个参数都是查询字符串。开关关闭时,方法返回“未处理”的输入,方便串联调用。
|
|
195
|
+
|
|
196
|
+
| 方法 | 返回 | 开关关闭时 |
|
|
197
|
+
| --- | --- | --- |
|
|
198
|
+
| `query_rewrite(query)` | `str` | 返回原 `query` |
|
|
199
|
+
| `query_expand(query, expand_number=3)` | `list[str]` | 返回 `[query]` |
|
|
200
|
+
| `query_decompose(query)` | `list[str]` | 返回 `[query]` |
|
|
201
|
+
| `query_router(query, routers=None)` | `str` | 返回 `"default"` |
|
|
202
|
+
| `hyde(query)` | `str` | 返回原 `query` |
|
|
203
|
+
| `hybrid_search(query)` | `list[Document]` | 返回 `[]` |
|
|
204
|
+
| `multi_route(query)` | `list[Document]` | 返回 `[]`(预留接口) |
|
|
205
|
+
| `rerank(query, documents)` | `list[Document]` | 返回原 `documents` |
|
|
206
|
+
| `contextual_compression(query, documents)` | `list[Document]` | 返回原 `documents` |
|
|
207
|
+
|
|
208
|
+
### 构造参数
|
|
209
|
+
|
|
210
|
+
| 参数 | 默认值 | 用途 |
|
|
211
|
+
| --- | --- | --- |
|
|
212
|
+
| `llm` | 必填 | 查询改写、扩展、分解、路由、HyDE、压缩抽取 |
|
|
213
|
+
| `vector_retriever` | `None` | 向量检索器,混合检索的语义一路 |
|
|
214
|
+
| `bm25_retriever` | `None` | BM25 检索器,混合检索的关键词一路 |
|
|
215
|
+
| `embedding_model` | `"text-embedding-v4"` | 上下文压缩计算相似度时使用的向量模型 |
|
|
216
|
+
|
|
217
|
+
### 各环节细节
|
|
218
|
+
|
|
219
|
+
- **查询改写 / 扩展 / 分解 / HyDE**:使用注入的 `llm` 生成内容。扩展和分解要求模型输出 JSON 数组,建议使用指令遵循能力较好的模型。
|
|
220
|
+
- **查询路由**:`routers` 是候选知识库名称列表。模型输出不在候选列表中时回退为 `"default"`。
|
|
221
|
+
- **混合检索**:使用 `EnsembleRetriever` 融合 BM25 与向量检索,权重固定为 BM25 `0.4`、向量 `0.6`。两路检索器缺任意一个时返回 `[]`。
|
|
222
|
+
- **重排序**:调用 `DashScopeRerank`,模型为 `qwen3-rerank`,固定 `top_n=3`,需要 `DASHSCOPE_API_KEY`。
|
|
223
|
+
- **上下文压缩**:依次执行 `EmbeddingsFilter`(相似度阈值固定 `0.42`)→ `LLMChainExtractor`(用注入的 `llm` 抽取相关句)→ `LongContextReorder`(相关块放到首尾)。需要 `DASHSCOPE_API_KEY` 和注入的 `llm`。
|
|
224
|
+
- **多路召回**:`multi_route()` 目前是预留接口,固定返回空列表,请勿在正式流水线中依赖。
|
|
225
|
+
|
|
226
|
+
## 已知限制
|
|
227
|
+
|
|
228
|
+
1. `multi_route()` 尚未实现。
|
|
229
|
+
2. 混合检索权重、重排序 `top_n`、压缩相似度阈值目前是硬编码,不能通过 `control()` 调整。
|
|
230
|
+
3. 重排序和上下文压缩固定使用 DashScope,其他厂商的 reranker / embedding 需要自行改造。
|
|
231
|
+
4. `query_expand()` 和 `query_decompose()` 使用 `JsonOutputParser`,模型返回非法 JSON 时会抛异常。
|
|
232
|
+
5. BM25 处理中文时必须传入分词函数(如 `jieba.cut`),否则整句会被当作一个词,召回效果很差。
|
|
233
|
+
|
|
234
|
+
## 构建与发布
|
|
235
|
+
|
|
236
|
+
```bash
|
|
237
|
+
# 安装构建工具
|
|
238
|
+
pip install --upgrade build twine
|
|
239
|
+
|
|
240
|
+
# 构建 sdist 和 wheel
|
|
241
|
+
python -m build
|
|
242
|
+
|
|
243
|
+
# 检查元数据
|
|
244
|
+
python -m twine check dist/*
|
|
245
|
+
|
|
246
|
+
# 先发布到 TestPyPI 验证
|
|
247
|
+
python -m twine upload --repository testpypi dist/*
|
|
248
|
+
|
|
249
|
+
# 再发布到 PyPI
|
|
250
|
+
python -m twine upload dist/*
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
发布前请先把 `RAGConfig.py` 中的 `__version__` 升级;构建时版本号会从该属性读取。
|
|
254
|
+
|
|
255
|
+
## 项目结构
|
|
256
|
+
|
|
257
|
+
```text
|
|
258
|
+
RAGConfig/
|
|
259
|
+
├── RAGConfig.py # 模块源码
|
|
260
|
+
├── pyproject.toml # 构建与元数据配置
|
|
261
|
+
├── README.md
|
|
262
|
+
└── LICENSE
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
## License
|
|
266
|
+
|
|
267
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import os
|
|
2
|
+
|
|
3
|
+
from dotenv import load_dotenv
|
|
4
|
+
from langchain_classic.retrievers import EnsembleRetriever
|
|
5
|
+
from langchain_classic.retrievers.document_compressors import DocumentCompressorPipeline, EmbeddingsFilter, \
|
|
6
|
+
LLMChainExtractor
|
|
7
|
+
from langchain_community.document_compressors import DashScopeRerank
|
|
8
|
+
from langchain_community.document_transformers import LongContextReorder
|
|
9
|
+
from langchain_community.embeddings import DashScopeEmbeddings
|
|
10
|
+
from langchain_core.output_parsers import StrOutputParser, JsonOutputParser
|
|
11
|
+
from langchain_core.prompts import ChatPromptTemplate
|
|
12
|
+
from langchain_openai import ChatOpenAI
|
|
13
|
+
|
|
14
|
+
__version__ = "0.1.0"
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class RAGConfig:
|
|
18
|
+
"""RAG 基础配置"""
|
|
19
|
+
|
|
20
|
+
def __init__(self,llm,vector_retriever=None,bm25_retriever=None,embedding_model="text-embedding-v4"):
|
|
21
|
+
self.llm = llm
|
|
22
|
+
self.vector_retriever = vector_retriever
|
|
23
|
+
self.bm25_retriever = bm25_retriever
|
|
24
|
+
self.embedding_model=embedding_model
|
|
25
|
+
self.config = {
|
|
26
|
+
# 默认配置,全为关闭状态
|
|
27
|
+
"enable_query_rewrite": False,
|
|
28
|
+
"enable_query_expand": False,
|
|
29
|
+
"enable_query_decompose": False,
|
|
30
|
+
"enable_query_router": False,
|
|
31
|
+
"enable_hyde": False,
|
|
32
|
+
"enable_hybrid_search": False,
|
|
33
|
+
"enable_multi_route": False,
|
|
34
|
+
"enable_rerank": False,
|
|
35
|
+
"enable_contextual_compression": False,
|
|
36
|
+
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def control(self,**config):
|
|
41
|
+
for k,v in config.items():
|
|
42
|
+
if k not in self.config:
|
|
43
|
+
raise ValueError(f"未知的配置选项 {k}")
|
|
44
|
+
self.config[k] = v
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def query_rewrite(self,query):
|
|
49
|
+
"""查询改写:去掉用户的口语化"""
|
|
50
|
+
if not self.config["enable_query_rewrite"]:
|
|
51
|
+
return query
|
|
52
|
+
|
|
53
|
+
prompt = ChatPromptTemplate.from_template("""
|
|
54
|
+
你是一位专业的检索查询改写助手。请把用户的原始问题改写为一个清晰、独立、适合用于知识库检索的查询。
|
|
55
|
+
不做任何过多解释,直接输出改写后的查询。
|
|
56
|
+
原问题:{query}
|
|
57
|
+
""")
|
|
58
|
+
|
|
59
|
+
chain = prompt | self.llm | StrOutputParser()
|
|
60
|
+
|
|
61
|
+
return chain.invoke({"query":query}).strip()
|
|
62
|
+
|
|
63
|
+
def query_expand(self, query, expand_number = 3):
|
|
64
|
+
"""查询扩展:一个查询扩展成多个"""
|
|
65
|
+
if not self.config["enable_query_expand"]:
|
|
66
|
+
return [query]
|
|
67
|
+
|
|
68
|
+
prompt = ChatPromptTemplate.from_template("""
|
|
69
|
+
你是一位专业的检索查询扩展助手。请针对以下问题,生成 {expand_number} 个语义相近但表达方式不同的查询。
|
|
70
|
+
不做任何过多解释,以 JSON 数组的方式直接输出扩展后的查询。
|
|
71
|
+
原问题:{query}
|
|
72
|
+
""")
|
|
73
|
+
chain = prompt | self.llm | JsonOutputParser()
|
|
74
|
+
return chain.invoke({"query":query,"expand_number":expand_number})
|
|
75
|
+
|
|
76
|
+
def query_decompose(self, query):
|
|
77
|
+
"""查询分解:把复杂问题拆解成多个"""
|
|
78
|
+
if not self.config["enable_query_decompose"]:
|
|
79
|
+
return [query]
|
|
80
|
+
|
|
81
|
+
prompt = ChatPromptTemplate.from_template("""
|
|
82
|
+
你是一位查询分解助手。请把下面的复杂问题拆成若干个可以独立检索的子问题。
|
|
83
|
+
不做任何过多解释,以 JSON 数组的方式直接输出。
|
|
84
|
+
原问题:{query}
|
|
85
|
+
""")
|
|
86
|
+
chain = prompt | self.llm | JsonOutputParser()
|
|
87
|
+
return chain.invoke({"query":query})
|
|
88
|
+
|
|
89
|
+
def query_router(self, query , routers= None):
|
|
90
|
+
"""查询路由:判断问题应该查哪个知识库"""
|
|
91
|
+
if not self.config["enable_query_router"] or not routers:
|
|
92
|
+
return "default"
|
|
93
|
+
|
|
94
|
+
prompt = ChatPromptTemplate.from_template("""
|
|
95
|
+
你是一位查询路由助手。可选的知识库有:{routers}
|
|
96
|
+
请判断下面的问题应该查哪个知识库,只输出知识库名称,不要解释。
|
|
97
|
+
问题:{query}
|
|
98
|
+
""")
|
|
99
|
+
chain = prompt | self.llm | StrOutputParser()
|
|
100
|
+
result = chain.invoke({"routers": "、".join(routers), "query": query}).strip()
|
|
101
|
+
# 模型可能输出多余内容,不在候选里就回退到 default
|
|
102
|
+
return result if result in routers else "default"
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def hyde(self,query):
|
|
106
|
+
"""HyDE:先生成假设答案,再去做检索"""
|
|
107
|
+
if not self.config["enable_hyde"]:
|
|
108
|
+
return query
|
|
109
|
+
|
|
110
|
+
prompt = ChatPromptTemplate.from_template("""
|
|
111
|
+
你是一位知识库助手。请针对下面的问题写一段简洁、准确的假设性回答。
|
|
112
|
+
这段回答将用来检索相关文档,不需要说明它是假设。
|
|
113
|
+
问题:{query}
|
|
114
|
+
""")
|
|
115
|
+
chain = prompt | self.llm | StrOutputParser()
|
|
116
|
+
|
|
117
|
+
return chain.invoke({"query":query})
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def hybrid_search(self,query):
|
|
121
|
+
if not self.config["enable_hybrid_search"]:
|
|
122
|
+
return []
|
|
123
|
+
|
|
124
|
+
if self.vector_retriever is None or self.bm25_retriever is None:
|
|
125
|
+
return []
|
|
126
|
+
|
|
127
|
+
fused = EnsembleRetriever(
|
|
128
|
+
retrievers=[self.bm25_retriever, self.vector_retriever],
|
|
129
|
+
weights=[0.4, 0.6]
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
return fused.invoke(query)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def multi_route(self,query):
|
|
136
|
+
"""多路召回:合并不同数据源的结果"""
|
|
137
|
+
if not self.config["enable_multi_route"]:
|
|
138
|
+
return []
|
|
139
|
+
|
|
140
|
+
pass
|
|
141
|
+
return []
|
|
142
|
+
|
|
143
|
+
def rerank(self,query,documents):
|
|
144
|
+
"""重排序:对召回的结果从新打分"""
|
|
145
|
+
if not self.config["enable_rerank"]:
|
|
146
|
+
return documents
|
|
147
|
+
reranker = DashScopeRerank(top_n=3) # top_n=3:精排后只留分数最高的 3 条
|
|
148
|
+
reranker.model = "qwen3-rerank"
|
|
149
|
+
# 注意参数顺序:先文档列表,后查询
|
|
150
|
+
return reranker.compress_documents(documents, query)
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def contextual_compression(self,query,documents):
|
|
154
|
+
"""上下文压缩:过滤和抽取无关内容"""
|
|
155
|
+
if not self.config["enable_contextual_compression"]:
|
|
156
|
+
return documents
|
|
157
|
+
|
|
158
|
+
embeddings = DashScopeEmbeddings(
|
|
159
|
+
model=self.embedding_model, # 百炼向量模型
|
|
160
|
+
dashscope_api_key=os.getenv("DASHSCOPE_API_KEY")
|
|
161
|
+
) # 百炼密钥
|
|
162
|
+
|
|
163
|
+
# 压缩流水线:三件事按「先便宜后贵」排队,依次处理粗排结果
|
|
164
|
+
pipeline = DocumentCompressorPipeline(transformers=[
|
|
165
|
+
EmbeddingsFilter(embeddings=embeddings, similarity_threshold=0.42),
|
|
166
|
+
# ① 过滤:相似度低于阈值的整篇丢掉(不调模型,最便宜)
|
|
167
|
+
LLMChainExtractor.from_llm(self.llm),
|
|
168
|
+
# ② 抽取:LLM 精读,只留与问题相关的句子(一次模型调用,放后面)
|
|
169
|
+
LongContextReorder(),
|
|
170
|
+
# ③ 重排:相关块放首尾,防 LLM 中间遗忘(只换顺序)
|
|
171
|
+
])
|
|
172
|
+
# documents 是召回/重排后的 Document 列表,直接交给流水线压缩
|
|
173
|
+
return pipeline.compress_documents(documents, query)
|
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
# RAGConfig
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/ragconfig/)
|
|
4
|
+
[](https://pypi.org/project/ragconfig/)
|
|
5
|
+
[](LICENSE)
|
|
6
|
+
|
|
7
|
+
基于 LangChain 的模块化 RAG 增强工具。它把常见的检索增强环节分别封装成独立方法,并提供一个统一的开关配置:**默认全部关闭,按需打开**。关闭时方法会原样返回输入,因此你可以在流水线里无条件调用,而不需要到处写 `if`。
|
|
8
|
+
|
|
9
|
+
`RAGConfig` 只负责“使用”依赖,不负责“创建”依赖:大模型、向量检索器、BM25 检索器都由你构造后注入。
|
|
10
|
+
|
|
11
|
+
## 功能一览
|
|
12
|
+
|
|
13
|
+
| 能力 | 方法 | 说明 |
|
|
14
|
+
| --- | --- | --- |
|
|
15
|
+
| 查询改写 | `query_rewrite` | 把口语化问题改写成适合检索的查询 |
|
|
16
|
+
| 查询扩展 | `query_expand` | 生成多个语义相近、表达不同的查询 |
|
|
17
|
+
| 查询分解 | `query_decompose` | 把复杂问题拆成可独立检索的子问题 |
|
|
18
|
+
| 查询路由 | `query_router` | 判断问题应该查询哪个知识库 |
|
|
19
|
+
| HyDE | `hyde` | 先生成假设答案,再用它去检索 |
|
|
20
|
+
| 混合检索 | `hybrid_search` | BM25 + 向量检索加权融合 |
|
|
21
|
+
| 多路召回 | `multi_route` | 预留接口,当前版本尚未实现 |
|
|
22
|
+
| 重排序 | `rerank` | 使用 DashScope Rerank 对候选文档重新打分 |
|
|
23
|
+
| 上下文压缩 | `contextual_compression` | 相似度过滤 → LLM 抽取 → 长上下文重排 |
|
|
24
|
+
|
|
25
|
+
## 安装
|
|
26
|
+
|
|
27
|
+
```bash
|
|
28
|
+
pip install ragconfig
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
> 项目名为 `ragconfig`,导入的模块名是 `RAGConfig`,类名也是 `RAGConfig`:
|
|
32
|
+
>
|
|
33
|
+
> ```python
|
|
34
|
+
> from RAGConfig import RAGConfig
|
|
35
|
+
> ```
|
|
36
|
+
|
|
37
|
+
要求 Python 3.10 及以上。
|
|
38
|
+
|
|
39
|
+
如果要从源码安装开发版本:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
pip install -e .
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
## 环境变量
|
|
46
|
+
|
|
47
|
+
重排序和上下文压缩会调用阿里云百炼(DashScope),需要配置:
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
DASHSCOPE_API_KEY=sk-xxxxxxxxxxxxxxxx
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
本库**不会自动加载 `.env`**。请在应用入口自行调用 `load_dotenv()`,或直接在运行环境中设置变量。
|
|
54
|
+
|
|
55
|
+
## 快速开始
|
|
56
|
+
|
|
57
|
+
下面的示例额外使用了 `langchain-chroma`、`jieba` 和 `rank_bm25` 来搭建演示用检索器:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install langchain-chroma jieba rank_bm25
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
import os
|
|
65
|
+
|
|
66
|
+
import jieba
|
|
67
|
+
from dotenv import load_dotenv
|
|
68
|
+
from langchain_chroma import Chroma
|
|
69
|
+
from langchain_community.embeddings import DashScopeEmbeddings
|
|
70
|
+
from langchain_community.retrievers import BM25Retriever
|
|
71
|
+
from langchain_core.documents import Document
|
|
72
|
+
from langchain_openai import ChatOpenAI
|
|
73
|
+
|
|
74
|
+
from RAGConfig import RAGConfig
|
|
75
|
+
|
|
76
|
+
load_dotenv()
|
|
77
|
+
|
|
78
|
+
# 1. 依赖:大模型 + 向量模型
|
|
79
|
+
llm = ChatOpenAI(
|
|
80
|
+
model="deepseek-flash",
|
|
81
|
+
api_key=os.getenv("DEEPSEEK_API_KEY"),
|
|
82
|
+
base_url=os.getenv("DEEPSEEK_BASE_URL"),
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
embeddings = DashScopeEmbeddings(
|
|
86
|
+
model="text-embedding-v4",
|
|
87
|
+
dashscope_api_key=os.getenv("DASHSCOPE_API_KEY"),
|
|
88
|
+
)
|
|
89
|
+
|
|
90
|
+
# 2. 知识库与两路检索器
|
|
91
|
+
docs = [
|
|
92
|
+
Document(page_content="500ml 便携保温杯,316 不锈钢内胆,保温 12 小时。",
|
|
93
|
+
metadata={"category": "产品规格"}),
|
|
94
|
+
Document(page_content="首次使用请用温水清洗,不可放入洗碗机,不可微波加热。",
|
|
95
|
+
metadata={"category": "使用与保养"}),
|
|
96
|
+
Document(page_content="支持 7 天无理由退换货,自购买之日起享受一年质保。",
|
|
97
|
+
metadata={"category": "售后政策"}),
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
store = Chroma.from_documents(docs, embeddings)
|
|
101
|
+
vector_retriever = store.as_retriever(search_kwargs={"k": 3})
|
|
102
|
+
|
|
103
|
+
bm25_retriever = BM25Retriever.from_documents(
|
|
104
|
+
docs,
|
|
105
|
+
preprocess_func=lambda text: list(jieba.cut(text)), # 中文必须先分词
|
|
106
|
+
k=3,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
# 3. 创建并开启需要的环节
|
|
110
|
+
rag = RAGConfig(
|
|
111
|
+
llm=llm,
|
|
112
|
+
vector_retriever=vector_retriever,
|
|
113
|
+
bm25_retriever=bm25_retriever,
|
|
114
|
+
embedding_model="text-embedding-v4",
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
rag.control(
|
|
118
|
+
enable_query_rewrite=True,
|
|
119
|
+
enable_hyde=True,
|
|
120
|
+
enable_hybrid_search=True,
|
|
121
|
+
enable_rerank=True,
|
|
122
|
+
enable_contextual_compression=True,
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
# 4. 组装检索流水线
|
|
126
|
+
question = "保温杯能不能放进洗碗机清洗?"
|
|
127
|
+
|
|
128
|
+
query = rag.query_rewrite(question) # 改写口语化问题
|
|
129
|
+
query = rag.hyde(query) # 用假设答案增强语义
|
|
130
|
+
candidates = rag.hybrid_search(query) # BM25 + 向量融合召回
|
|
131
|
+
candidates = rag.rerank(query, candidates) # DashScope 精排(保留 top 3)
|
|
132
|
+
documents = rag.contextual_compression(query, candidates)
|
|
133
|
+
|
|
134
|
+
for doc in documents:
|
|
135
|
+
print("-", doc.page_content)
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
## 配置项
|
|
139
|
+
|
|
140
|
+
通过 `rag.control(**config)` 修改配置。键名不存在时会抛出 `ValueError`:
|
|
141
|
+
|
|
142
|
+
```python
|
|
143
|
+
rag.control(enable_rerank=True) # 打开重排序
|
|
144
|
+
rag.control(enable_hyde=False) # 关闭 HyDE
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
| 配置键 | 默认值 | 作用 |
|
|
148
|
+
| --- | --- | --- |
|
|
149
|
+
| `enable_query_rewrite` | `False` | 查询改写 |
|
|
150
|
+
| `enable_query_expand` | `False` | 查询扩展 |
|
|
151
|
+
| `enable_query_decompose` | `False` | 查询分解 |
|
|
152
|
+
| `enable_query_router` | `False` | 查询路由(注意键名是 `router`) |
|
|
153
|
+
| `enable_hyde` | `False` | HyDE 假设答案 |
|
|
154
|
+
| `enable_hybrid_search` | `False` | 混合检索 |
|
|
155
|
+
| `enable_multi_route` | `False` | 多路召回(预留,当前无效果) |
|
|
156
|
+
| `enable_rerank` | `False` | 重排序 |
|
|
157
|
+
| `enable_contextual_compression` | `False` | 上下文压缩 |
|
|
158
|
+
|
|
159
|
+
未列出的增强参数(混合检索权重、重排序 `top_n`、压缩阈值等)当前版本固定在代码中,见下文“已知限制”。
|
|
160
|
+
|
|
161
|
+
## API 说明
|
|
162
|
+
|
|
163
|
+
所有方法的第一个参数都是查询字符串。开关关闭时,方法返回“未处理”的输入,方便串联调用。
|
|
164
|
+
|
|
165
|
+
| 方法 | 返回 | 开关关闭时 |
|
|
166
|
+
| --- | --- | --- |
|
|
167
|
+
| `query_rewrite(query)` | `str` | 返回原 `query` |
|
|
168
|
+
| `query_expand(query, expand_number=3)` | `list[str]` | 返回 `[query]` |
|
|
169
|
+
| `query_decompose(query)` | `list[str]` | 返回 `[query]` |
|
|
170
|
+
| `query_router(query, routers=None)` | `str` | 返回 `"default"` |
|
|
171
|
+
| `hyde(query)` | `str` | 返回原 `query` |
|
|
172
|
+
| `hybrid_search(query)` | `list[Document]` | 返回 `[]` |
|
|
173
|
+
| `multi_route(query)` | `list[Document]` | 返回 `[]`(预留接口) |
|
|
174
|
+
| `rerank(query, documents)` | `list[Document]` | 返回原 `documents` |
|
|
175
|
+
| `contextual_compression(query, documents)` | `list[Document]` | 返回原 `documents` |
|
|
176
|
+
|
|
177
|
+
### 构造参数
|
|
178
|
+
|
|
179
|
+
| 参数 | 默认值 | 用途 |
|
|
180
|
+
| --- | --- | --- |
|
|
181
|
+
| `llm` | 必填 | 查询改写、扩展、分解、路由、HyDE、压缩抽取 |
|
|
182
|
+
| `vector_retriever` | `None` | 向量检索器,混合检索的语义一路 |
|
|
183
|
+
| `bm25_retriever` | `None` | BM25 检索器,混合检索的关键词一路 |
|
|
184
|
+
| `embedding_model` | `"text-embedding-v4"` | 上下文压缩计算相似度时使用的向量模型 |
|
|
185
|
+
|
|
186
|
+
### 各环节细节
|
|
187
|
+
|
|
188
|
+
- **查询改写 / 扩展 / 分解 / HyDE**:使用注入的 `llm` 生成内容。扩展和分解要求模型输出 JSON 数组,建议使用指令遵循能力较好的模型。
|
|
189
|
+
- **查询路由**:`routers` 是候选知识库名称列表。模型输出不在候选列表中时回退为 `"default"`。
|
|
190
|
+
- **混合检索**:使用 `EnsembleRetriever` 融合 BM25 与向量检索,权重固定为 BM25 `0.4`、向量 `0.6`。两路检索器缺任意一个时返回 `[]`。
|
|
191
|
+
- **重排序**:调用 `DashScopeRerank`,模型为 `qwen3-rerank`,固定 `top_n=3`,需要 `DASHSCOPE_API_KEY`。
|
|
192
|
+
- **上下文压缩**:依次执行 `EmbeddingsFilter`(相似度阈值固定 `0.42`)→ `LLMChainExtractor`(用注入的 `llm` 抽取相关句)→ `LongContextReorder`(相关块放到首尾)。需要 `DASHSCOPE_API_KEY` 和注入的 `llm`。
|
|
193
|
+
- **多路召回**:`multi_route()` 目前是预留接口,固定返回空列表,请勿在正式流水线中依赖。
|
|
194
|
+
|
|
195
|
+
## 已知限制
|
|
196
|
+
|
|
197
|
+
1. `multi_route()` 尚未实现。
|
|
198
|
+
2. 混合检索权重、重排序 `top_n`、压缩相似度阈值目前是硬编码,不能通过 `control()` 调整。
|
|
199
|
+
3. 重排序和上下文压缩固定使用 DashScope,其他厂商的 reranker / embedding 需要自行改造。
|
|
200
|
+
4. `query_expand()` 和 `query_decompose()` 使用 `JsonOutputParser`,模型返回非法 JSON 时会抛异常。
|
|
201
|
+
5. BM25 处理中文时必须传入分词函数(如 `jieba.cut`),否则整句会被当作一个词,召回效果很差。
|
|
202
|
+
|
|
203
|
+
## 构建与发布
|
|
204
|
+
|
|
205
|
+
```bash
|
|
206
|
+
# 安装构建工具
|
|
207
|
+
pip install --upgrade build twine
|
|
208
|
+
|
|
209
|
+
# 构建 sdist 和 wheel
|
|
210
|
+
python -m build
|
|
211
|
+
|
|
212
|
+
# 检查元数据
|
|
213
|
+
python -m twine check dist/*
|
|
214
|
+
|
|
215
|
+
# 先发布到 TestPyPI 验证
|
|
216
|
+
python -m twine upload --repository testpypi dist/*
|
|
217
|
+
|
|
218
|
+
# 再发布到 PyPI
|
|
219
|
+
python -m twine upload dist/*
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
发布前请先把 `RAGConfig.py` 中的 `__version__` 升级;构建时版本号会从该属性读取。
|
|
223
|
+
|
|
224
|
+
## 项目结构
|
|
225
|
+
|
|
226
|
+
```text
|
|
227
|
+
RAGConfig/
|
|
228
|
+
├── RAGConfig.py # 模块源码
|
|
229
|
+
├── pyproject.toml # 构建与元数据配置
|
|
230
|
+
├── README.md
|
|
231
|
+
└── LICENSE
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
## License
|
|
235
|
+
|
|
236
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "ragconfig"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Modular RAG enhancement toolkit built on LangChain: query rewriting, expansion, decomposition, routing, HyDE, hybrid search, rerank and contextual compression."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "RAGConfig contributors" },
|
|
15
|
+
]
|
|
16
|
+
keywords = [
|
|
17
|
+
"rag",
|
|
18
|
+
"retrieval-augmented-generation",
|
|
19
|
+
"langchain",
|
|
20
|
+
"llm",
|
|
21
|
+
"hybrid-search",
|
|
22
|
+
"rerank",
|
|
23
|
+
"hyde",
|
|
24
|
+
]
|
|
25
|
+
classifiers = [
|
|
26
|
+
"Development Status :: 3 - Alpha",
|
|
27
|
+
"Intended Audience :: Developers",
|
|
28
|
+
"Operating System :: OS Independent",
|
|
29
|
+
"Programming Language :: Python :: 3",
|
|
30
|
+
"Programming Language :: Python :: 3.10",
|
|
31
|
+
"Programming Language :: Python :: 3.11",
|
|
32
|
+
"Programming Language :: Python :: 3.12",
|
|
33
|
+
"Programming Language :: Python :: 3.13",
|
|
34
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
35
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
36
|
+
]
|
|
37
|
+
dependencies = [
|
|
38
|
+
"langchain-classic>=1.0.0,<2.0.0",
|
|
39
|
+
"langchain-community>=0.4.0,<1.0.0",
|
|
40
|
+
"langchain-core>=1.0.0,<2.0.0",
|
|
41
|
+
"langchain-openai>=1.0.0,<2.0.0",
|
|
42
|
+
"dashscope>=1.20.0",
|
|
43
|
+
"python-dotenv>=1.0.0",
|
|
44
|
+
]
|
|
45
|
+
|
|
46
|
+
[project.optional-dependencies]
|
|
47
|
+
dev = [
|
|
48
|
+
"build>=1.2",
|
|
49
|
+
"twine>=5.0",
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
[tool.setuptools]
|
|
53
|
+
py-modules = ["RAGConfig"]
|
|
54
|
+
|
|
55
|
+
[tool.setuptools.dynamic]
|
|
56
|
+
version = { attr = "RAGConfig.__version__" }
|
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ragconfig
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Modular RAG enhancement toolkit built on LangChain: query rewriting, expansion, decomposition, routing, HyDE, hybrid search, rerank and contextual compression.
|
|
5
|
+
Author: RAGConfig contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Keywords: rag,retrieval-augmented-generation,langchain,llm,hybrid-search,rerank,hyde
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: Operating System :: OS Independent
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
17
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
18
|
+
Requires-Python: >=3.10
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
License-File: LICENSE
|
|
21
|
+
Requires-Dist: langchain-classic<2.0.0,>=1.0.0
|
|
22
|
+
Requires-Dist: langchain-community<1.0.0,>=0.4.0
|
|
23
|
+
Requires-Dist: langchain-core<2.0.0,>=1.0.0
|
|
24
|
+
Requires-Dist: langchain-openai<2.0.0,>=1.0.0
|
|
25
|
+
Requires-Dist: dashscope>=1.20.0
|
|
26
|
+
Requires-Dist: python-dotenv>=1.0.0
|
|
27
|
+
Provides-Extra: dev
|
|
28
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
29
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
30
|
+
Dynamic: license-file
|
|
31
|
+
|
|
32
|
+
# RAGConfig
|
|
33
|
+
|
|
34
|
+
[](https://pypi.org/project/ragconfig/)
|
|
35
|
+
[](https://pypi.org/project/ragconfig/)
|
|
36
|
+
[](LICENSE)
|
|
37
|
+
|
|
38
|
+
基于 LangChain 的模块化 RAG 增强工具。它把常见的检索增强环节分别封装成独立方法,并提供一个统一的开关配置:**默认全部关闭,按需打开**。关闭时方法会原样返回输入,因此你可以在流水线里无条件调用,而不需要到处写 `if`。
|
|
39
|
+
|
|
40
|
+
`RAGConfig` 只负责“使用”依赖,不负责“创建”依赖:大模型、向量检索器、BM25 检索器都由你构造后注入。
|
|
41
|
+
|
|
42
|
+
## 功能一览
|
|
43
|
+
|
|
44
|
+
| 能力 | 方法 | 说明 |
|
|
45
|
+
| --- | --- | --- |
|
|
46
|
+
| 查询改写 | `query_rewrite` | 把口语化问题改写成适合检索的查询 |
|
|
47
|
+
| 查询扩展 | `query_expand` | 生成多个语义相近、表达不同的查询 |
|
|
48
|
+
| 查询分解 | `query_decompose` | 把复杂问题拆成可独立检索的子问题 |
|
|
49
|
+
| 查询路由 | `query_router` | 判断问题应该查询哪个知识库 |
|
|
50
|
+
| HyDE | `hyde` | 先生成假设答案,再用它去检索 |
|
|
51
|
+
| 混合检索 | `hybrid_search` | BM25 + 向量检索加权融合 |
|
|
52
|
+
| 多路召回 | `multi_route` | 预留接口,当前版本尚未实现 |
|
|
53
|
+
| 重排序 | `rerank` | 使用 DashScope Rerank 对候选文档重新打分 |
|
|
54
|
+
| 上下文压缩 | `contextual_compression` | 相似度过滤 → LLM 抽取 → 长上下文重排 |
|
|
55
|
+
|
|
56
|
+
## 安装
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pip install ragconfig
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
> 项目名为 `ragconfig`,导入的模块名是 `RAGConfig`,类名也是 `RAGConfig`:
|
|
63
|
+
>
|
|
64
|
+
> ```python
|
|
65
|
+
> from RAGConfig import RAGConfig
|
|
66
|
+
> ```
|
|
67
|
+
|
|
68
|
+
要求 Python 3.10 及以上。
|
|
69
|
+
|
|
70
|
+
如果要从源码安装开发版本:
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
pip install -e .
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
## 环境变量
|
|
77
|
+
|
|
78
|
+
重排序和上下文压缩会调用阿里云百炼(DashScope),需要配置:
|
|
79
|
+
|
|
80
|
+
```bash
|
|
81
|
+
DASHSCOPE_API_KEY=sk-xxxxxxxxxxxxxxxx
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
本库**不会自动加载 `.env`**。请在应用入口自行调用 `load_dotenv()`,或直接在运行环境中设置变量。
|
|
85
|
+
|
|
86
|
+
## 快速开始
|
|
87
|
+
|
|
88
|
+
下面的示例额外使用了 `langchain-chroma`、`jieba` 和 `rank_bm25` 来搭建演示用检索器:
|
|
89
|
+
|
|
90
|
+
```bash
|
|
91
|
+
pip install langchain-chroma jieba rank_bm25
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
import os
|
|
96
|
+
|
|
97
|
+
import jieba
|
|
98
|
+
from dotenv import load_dotenv
|
|
99
|
+
from langchain_chroma import Chroma
|
|
100
|
+
from langchain_community.embeddings import DashScopeEmbeddings
|
|
101
|
+
from langchain_community.retrievers import BM25Retriever
|
|
102
|
+
from langchain_core.documents import Document
|
|
103
|
+
from langchain_openai import ChatOpenAI
|
|
104
|
+
|
|
105
|
+
from RAGConfig import RAGConfig
|
|
106
|
+
|
|
107
|
+
load_dotenv()
|
|
108
|
+
|
|
109
|
+
# 1. 依赖:大模型 + 向量模型
|
|
110
|
+
llm = ChatOpenAI(
|
|
111
|
+
model="deepseek-flash",
|
|
112
|
+
api_key=os.getenv("DEEPSEEK_API_KEY"),
|
|
113
|
+
base_url=os.getenv("DEEPSEEK_BASE_URL"),
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
embeddings = DashScopeEmbeddings(
|
|
117
|
+
model="text-embedding-v4",
|
|
118
|
+
dashscope_api_key=os.getenv("DASHSCOPE_API_KEY"),
|
|
119
|
+
)
|
|
120
|
+
|
|
121
|
+
# 2. 知识库与两路检索器
|
|
122
|
+
docs = [
|
|
123
|
+
Document(page_content="500ml 便携保温杯,316 不锈钢内胆,保温 12 小时。",
|
|
124
|
+
metadata={"category": "产品规格"}),
|
|
125
|
+
Document(page_content="首次使用请用温水清洗,不可放入洗碗机,不可微波加热。",
|
|
126
|
+
metadata={"category": "使用与保养"}),
|
|
127
|
+
Document(page_content="支持 7 天无理由退换货,自购买之日起享受一年质保。",
|
|
128
|
+
metadata={"category": "售后政策"}),
|
|
129
|
+
]
|
|
130
|
+
|
|
131
|
+
store = Chroma.from_documents(docs, embeddings)
|
|
132
|
+
vector_retriever = store.as_retriever(search_kwargs={"k": 3})
|
|
133
|
+
|
|
134
|
+
bm25_retriever = BM25Retriever.from_documents(
|
|
135
|
+
docs,
|
|
136
|
+
preprocess_func=lambda text: list(jieba.cut(text)), # 中文必须先分词
|
|
137
|
+
k=3,
|
|
138
|
+
)
|
|
139
|
+
|
|
140
|
+
# 3. 创建并开启需要的环节
|
|
141
|
+
rag = RAGConfig(
|
|
142
|
+
llm=llm,
|
|
143
|
+
vector_retriever=vector_retriever,
|
|
144
|
+
bm25_retriever=bm25_retriever,
|
|
145
|
+
embedding_model="text-embedding-v4",
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
rag.control(
|
|
149
|
+
enable_query_rewrite=True,
|
|
150
|
+
enable_hyde=True,
|
|
151
|
+
enable_hybrid_search=True,
|
|
152
|
+
enable_rerank=True,
|
|
153
|
+
enable_contextual_compression=True,
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
# 4. 组装检索流水线
|
|
157
|
+
question = "保温杯能不能放进洗碗机清洗?"
|
|
158
|
+
|
|
159
|
+
query = rag.query_rewrite(question) # 改写口语化问题
|
|
160
|
+
query = rag.hyde(query) # 用假设答案增强语义
|
|
161
|
+
candidates = rag.hybrid_search(query) # BM25 + 向量融合召回
|
|
162
|
+
candidates = rag.rerank(query, candidates) # DashScope 精排(保留 top 3)
|
|
163
|
+
documents = rag.contextual_compression(query, candidates)
|
|
164
|
+
|
|
165
|
+
for doc in documents:
|
|
166
|
+
print("-", doc.page_content)
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
## 配置项
|
|
170
|
+
|
|
171
|
+
通过 `rag.control(**config)` 修改配置。键名不存在时会抛出 `ValueError`:
|
|
172
|
+
|
|
173
|
+
```python
|
|
174
|
+
rag.control(enable_rerank=True) # 打开重排序
|
|
175
|
+
rag.control(enable_hyde=False) # 关闭 HyDE
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
| 配置键 | 默认值 | 作用 |
|
|
179
|
+
| --- | --- | --- |
|
|
180
|
+
| `enable_query_rewrite` | `False` | 查询改写 |
|
|
181
|
+
| `enable_query_expand` | `False` | 查询扩展 |
|
|
182
|
+
| `enable_query_decompose` | `False` | 查询分解 |
|
|
183
|
+
| `enable_query_router` | `False` | 查询路由(注意键名是 `router`) |
|
|
184
|
+
| `enable_hyde` | `False` | HyDE 假设答案 |
|
|
185
|
+
| `enable_hybrid_search` | `False` | 混合检索 |
|
|
186
|
+
| `enable_multi_route` | `False` | 多路召回(预留,当前无效果) |
|
|
187
|
+
| `enable_rerank` | `False` | 重排序 |
|
|
188
|
+
| `enable_contextual_compression` | `False` | 上下文压缩 |
|
|
189
|
+
|
|
190
|
+
未列出的增强参数(混合检索权重、重排序 `top_n`、压缩阈值等)当前版本固定在代码中,见下文“已知限制”。
|
|
191
|
+
|
|
192
|
+
## API 说明
|
|
193
|
+
|
|
194
|
+
所有方法的第一个参数都是查询字符串。开关关闭时,方法返回“未处理”的输入,方便串联调用。
|
|
195
|
+
|
|
196
|
+
| 方法 | 返回 | 开关关闭时 |
|
|
197
|
+
| --- | --- | --- |
|
|
198
|
+
| `query_rewrite(query)` | `str` | 返回原 `query` |
|
|
199
|
+
| `query_expand(query, expand_number=3)` | `list[str]` | 返回 `[query]` |
|
|
200
|
+
| `query_decompose(query)` | `list[str]` | 返回 `[query]` |
|
|
201
|
+
| `query_router(query, routers=None)` | `str` | 返回 `"default"` |
|
|
202
|
+
| `hyde(query)` | `str` | 返回原 `query` |
|
|
203
|
+
| `hybrid_search(query)` | `list[Document]` | 返回 `[]` |
|
|
204
|
+
| `multi_route(query)` | `list[Document]` | 返回 `[]`(预留接口) |
|
|
205
|
+
| `rerank(query, documents)` | `list[Document]` | 返回原 `documents` |
|
|
206
|
+
| `contextual_compression(query, documents)` | `list[Document]` | 返回原 `documents` |
|
|
207
|
+
|
|
208
|
+
### 构造参数
|
|
209
|
+
|
|
210
|
+
| 参数 | 默认值 | 用途 |
|
|
211
|
+
| --- | --- | --- |
|
|
212
|
+
| `llm` | 必填 | 查询改写、扩展、分解、路由、HyDE、压缩抽取 |
|
|
213
|
+
| `vector_retriever` | `None` | 向量检索器,混合检索的语义一路 |
|
|
214
|
+
| `bm25_retriever` | `None` | BM25 检索器,混合检索的关键词一路 |
|
|
215
|
+
| `embedding_model` | `"text-embedding-v4"` | 上下文压缩计算相似度时使用的向量模型 |
|
|
216
|
+
|
|
217
|
+
### 各环节细节
|
|
218
|
+
|
|
219
|
+
- **查询改写 / 扩展 / 分解 / HyDE**:使用注入的 `llm` 生成内容。扩展和分解要求模型输出 JSON 数组,建议使用指令遵循能力较好的模型。
|
|
220
|
+
- **查询路由**:`routers` 是候选知识库名称列表。模型输出不在候选列表中时回退为 `"default"`。
|
|
221
|
+
- **混合检索**:使用 `EnsembleRetriever` 融合 BM25 与向量检索,权重固定为 BM25 `0.4`、向量 `0.6`。两路检索器缺任意一个时返回 `[]`。
|
|
222
|
+
- **重排序**:调用 `DashScopeRerank`,模型为 `qwen3-rerank`,固定 `top_n=3`,需要 `DASHSCOPE_API_KEY`。
|
|
223
|
+
- **上下文压缩**:依次执行 `EmbeddingsFilter`(相似度阈值固定 `0.42`)→ `LLMChainExtractor`(用注入的 `llm` 抽取相关句)→ `LongContextReorder`(相关块放到首尾)。需要 `DASHSCOPE_API_KEY` 和注入的 `llm`。
|
|
224
|
+
- **多路召回**:`multi_route()` 目前是预留接口,固定返回空列表,请勿在正式流水线中依赖。
|
|
225
|
+
|
|
226
|
+
## 已知限制
|
|
227
|
+
|
|
228
|
+
1. `multi_route()` 尚未实现。
|
|
229
|
+
2. 混合检索权重、重排序 `top_n`、压缩相似度阈值目前是硬编码,不能通过 `control()` 调整。
|
|
230
|
+
3. 重排序和上下文压缩固定使用 DashScope,其他厂商的 reranker / embedding 需要自行改造。
|
|
231
|
+
4. `query_expand()` 和 `query_decompose()` 使用 `JsonOutputParser`,模型返回非法 JSON 时会抛异常。
|
|
232
|
+
5. BM25 处理中文时必须传入分词函数(如 `jieba.cut`),否则整句会被当作一个词,召回效果很差。
|
|
233
|
+
|
|
234
|
+
## 构建与发布
|
|
235
|
+
|
|
236
|
+
```bash
|
|
237
|
+
# 安装构建工具
|
|
238
|
+
pip install --upgrade build twine
|
|
239
|
+
|
|
240
|
+
# 构建 sdist 和 wheel
|
|
241
|
+
python -m build
|
|
242
|
+
|
|
243
|
+
# 检查元数据
|
|
244
|
+
python -m twine check dist/*
|
|
245
|
+
|
|
246
|
+
# 先发布到 TestPyPI 验证
|
|
247
|
+
python -m twine upload --repository testpypi dist/*
|
|
248
|
+
|
|
249
|
+
# 再发布到 PyPI
|
|
250
|
+
python -m twine upload dist/*
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
发布前请先把 `RAGConfig.py` 中的 `__version__` 升级;构建时版本号会从该属性读取。
|
|
254
|
+
|
|
255
|
+
## 项目结构
|
|
256
|
+
|
|
257
|
+
```text
|
|
258
|
+
RAGConfig/
|
|
259
|
+
├── RAGConfig.py # 模块源码
|
|
260
|
+
├── pyproject.toml # 构建与元数据配置
|
|
261
|
+
├── README.md
|
|
262
|
+
└── LICENSE
|
|
263
|
+
```
|
|
264
|
+
|
|
265
|
+
## License
|
|
266
|
+
|
|
267
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
RAGConfig
|