modular-rag-langchain 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.
- modular_rag_langchain-0.1.0/PKG-INFO +83 -0
- modular_rag_langchain-0.1.0/README.md +63 -0
- modular_rag_langchain-0.1.0/langchain_modular_rag.py +380 -0
- modular_rag_langchain-0.1.0/modular_rag_langchain.egg-info/PKG-INFO +83 -0
- modular_rag_langchain-0.1.0/modular_rag_langchain.egg-info/SOURCES.txt +8 -0
- modular_rag_langchain-0.1.0/modular_rag_langchain.egg-info/dependency_links.txt +1 -0
- modular_rag_langchain-0.1.0/modular_rag_langchain.egg-info/requires.txt +14 -0
- modular_rag_langchain-0.1.0/modular_rag_langchain.egg-info/top_level.txt +1 -0
- modular_rag_langchain-0.1.0/pyproject.toml +28 -0
- modular_rag_langchain-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: modular-rag-langchain
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A modular RAG retrieval class based on LangChain and Chroma
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: chromadb
|
|
8
|
+
Requires-Dist: langchain-chroma
|
|
9
|
+
Requires-Dist: langchain-community
|
|
10
|
+
Requires-Dist: langchain-core
|
|
11
|
+
Requires-Dist: langchain-openai
|
|
12
|
+
Requires-Dist: langchain-classic
|
|
13
|
+
Requires-Dist: jieba
|
|
14
|
+
Requires-Dist: rank-bm25
|
|
15
|
+
Requires-Dist: python-dotenv
|
|
16
|
+
Requires-Dist: dashscope
|
|
17
|
+
Provides-Extra: publish
|
|
18
|
+
Requires-Dist: build; extra == "publish"
|
|
19
|
+
Requires-Dist: twine; extra == "publish"
|
|
20
|
+
|
|
21
|
+
# modular-rag-langchain
|
|
22
|
+
|
|
23
|
+
提供一个 `ModularRAG` 类,用于连接已有的 Chroma 知识库并执行在线检索。
|
|
24
|
+
|
|
25
|
+
Python 3.11 及以上。
|
|
26
|
+
|
|
27
|
+
## 安装
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install modular-rag-langchain
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## 使用
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from langchain_modular_rag import ModularRAG
|
|
37
|
+
|
|
38
|
+
rag = ModularRAG({
|
|
39
|
+
"persist_directory": "./chroma_db",
|
|
40
|
+
"collection_name": "study",
|
|
41
|
+
"embedding_model": "text-embedding-v4",
|
|
42
|
+
"top_k": 5,
|
|
43
|
+
"recall_top_k": 20,
|
|
44
|
+
"pre_retrieval": {
|
|
45
|
+
"enabled": False,
|
|
46
|
+
"rewrite_query": False,
|
|
47
|
+
"hyde": False,
|
|
48
|
+
"model": "qwen-plus",
|
|
49
|
+
},
|
|
50
|
+
"hybrid_retrieval": {
|
|
51
|
+
"enabled": True,
|
|
52
|
+
"weights": [0.5, 0.5],
|
|
53
|
+
},
|
|
54
|
+
"post_retrieval": {
|
|
55
|
+
"enabled": True,
|
|
56
|
+
"deduplicate": True,
|
|
57
|
+
"rerank": False,
|
|
58
|
+
"rerank_model": "qwen3-rerank",
|
|
59
|
+
"similarity_filter": False,
|
|
60
|
+
"similarity_threshold": 0.4,
|
|
61
|
+
"compress_context": False,
|
|
62
|
+
"llm_model": "qwen-plus",
|
|
63
|
+
"reorder": False,
|
|
64
|
+
},
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
results = rag.search("公司打卡时间?")
|
|
68
|
+
for document in results:
|
|
69
|
+
print(document.metadata)
|
|
70
|
+
print(document.page_content)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## 环境变量
|
|
74
|
+
|
|
75
|
+
需要配置通义 API Key:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
export DASHSCOPE_API_KEY="你的 API Key"
|
|
79
|
+
或
|
|
80
|
+
setx DASHSCOPE_API_KEY="你的 API Key"
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`persist_directory` 指向已经完成入库的 Chroma 数据库。这个包当前只提供在线检索,不包含你的个人知识库数据,也不会自动创建或导入知识库。
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
# modular-rag-langchain
|
|
2
|
+
|
|
3
|
+
提供一个 `ModularRAG` 类,用于连接已有的 Chroma 知识库并执行在线检索。
|
|
4
|
+
|
|
5
|
+
Python 3.11 及以上。
|
|
6
|
+
|
|
7
|
+
## 安装
|
|
8
|
+
|
|
9
|
+
```bash
|
|
10
|
+
pip install modular-rag-langchain
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## 使用
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from langchain_modular_rag import ModularRAG
|
|
17
|
+
|
|
18
|
+
rag = ModularRAG({
|
|
19
|
+
"persist_directory": "./chroma_db",
|
|
20
|
+
"collection_name": "study",
|
|
21
|
+
"embedding_model": "text-embedding-v4",
|
|
22
|
+
"top_k": 5,
|
|
23
|
+
"recall_top_k": 20,
|
|
24
|
+
"pre_retrieval": {
|
|
25
|
+
"enabled": False,
|
|
26
|
+
"rewrite_query": False,
|
|
27
|
+
"hyde": False,
|
|
28
|
+
"model": "qwen-plus",
|
|
29
|
+
},
|
|
30
|
+
"hybrid_retrieval": {
|
|
31
|
+
"enabled": True,
|
|
32
|
+
"weights": [0.5, 0.5],
|
|
33
|
+
},
|
|
34
|
+
"post_retrieval": {
|
|
35
|
+
"enabled": True,
|
|
36
|
+
"deduplicate": True,
|
|
37
|
+
"rerank": False,
|
|
38
|
+
"rerank_model": "qwen3-rerank",
|
|
39
|
+
"similarity_filter": False,
|
|
40
|
+
"similarity_threshold": 0.4,
|
|
41
|
+
"compress_context": False,
|
|
42
|
+
"llm_model": "qwen-plus",
|
|
43
|
+
"reorder": False,
|
|
44
|
+
},
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
results = rag.search("公司打卡时间?")
|
|
48
|
+
for document in results:
|
|
49
|
+
print(document.metadata)
|
|
50
|
+
print(document.page_content)
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## 环境变量
|
|
54
|
+
|
|
55
|
+
需要配置通义 API Key:
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
export DASHSCOPE_API_KEY="你的 API Key"
|
|
59
|
+
或
|
|
60
|
+
setx DASHSCOPE_API_KEY="你的 API Key"
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
`persist_directory` 指向已经完成入库的 Chroma 数据库。这个包当前只提供在线检索,不包含你的个人知识库数据,也不会自动创建或导入知识库。
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
# 封装一个类,包含配置型与各种优化的方法
|
|
2
|
+
# 设置一个大方法,将所有的优化方法都在这个大方法内执行
|
|
3
|
+
# 是否执行已经怎么执行(参数),由配置项控制
|
|
4
|
+
# 优化方法封装成静态方法 不依赖对象
|
|
5
|
+
import jieba
|
|
6
|
+
from langchain_community.retrievers import BM25Retriever
|
|
7
|
+
|
|
8
|
+
class ModularRAG():
|
|
9
|
+
def __init__(self, config):
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
from dotenv import load_dotenv
|
|
13
|
+
from langchain_chroma import Chroma
|
|
14
|
+
from langchain_community.embeddings import DashScopeEmbeddings
|
|
15
|
+
load_dotenv()
|
|
16
|
+
self.config = config
|
|
17
|
+
directory = config.get("persist_directory", "./chroma_db")
|
|
18
|
+
if not (Path(directory).expanduser() / "chroma.sqlite3").is_file():
|
|
19
|
+
raise FileNotFoundError(f"知识库不存在:{directory}")
|
|
20
|
+
self.embeddings = DashScopeEmbeddings(
|
|
21
|
+
model=config.get("embedding_model", "text-embedding-v4"),
|
|
22
|
+
dashscope_api_key=os.getenv("DASHSCOPE_API_KEY"),
|
|
23
|
+
)
|
|
24
|
+
self.db = Chroma(
|
|
25
|
+
collection_name=config.get("collection_name", "study"),
|
|
26
|
+
persist_directory=str(Path(directory).expanduser()),
|
|
27
|
+
embedding_function=self.embeddings
|
|
28
|
+
)
|
|
29
|
+
|
|
30
|
+
# 将所有优化的功能封装成方法
|
|
31
|
+
# 1. 查询前格式化
|
|
32
|
+
@staticmethod
|
|
33
|
+
def normalize_query(question):
|
|
34
|
+
# 去除多余的空格
|
|
35
|
+
import re
|
|
36
|
+
# 空格'\s+'
|
|
37
|
+
return re.sub(r'\s+', ' ', question).strip()
|
|
38
|
+
|
|
39
|
+
# 2. 查询前改写
|
|
40
|
+
@staticmethod
|
|
41
|
+
def rewrite_query(question, model='qwen3.8-max'):
|
|
42
|
+
import os
|
|
43
|
+
from dotenv import load_dotenv
|
|
44
|
+
from langchain_openai import ChatOpenAI
|
|
45
|
+
load_dotenv(override=True)
|
|
46
|
+
|
|
47
|
+
llm = ChatOpenAI(
|
|
48
|
+
model=model,
|
|
49
|
+
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
|
50
|
+
base_url=os.getenv("DASHSCOPE_BASE_URL"),
|
|
51
|
+
temperature=0.3
|
|
52
|
+
)
|
|
53
|
+
|
|
54
|
+
from langchain_core.messages import HumanMessage
|
|
55
|
+
from langchain_core.messages import SystemMessage
|
|
56
|
+
res = llm.invoke(
|
|
57
|
+
[
|
|
58
|
+
SystemMessage(content='把问题改写为适合知识库检索的独立查询。保留原意,不编造缺失上下文,只输出查询。'),
|
|
59
|
+
HumanMessage(content=question)
|
|
60
|
+
]
|
|
61
|
+
)
|
|
62
|
+
return res.content.strip()
|
|
63
|
+
|
|
64
|
+
# 3. 查询前假性答案
|
|
65
|
+
@staticmethod
|
|
66
|
+
def generate_hyde(question, model='qwen3.8-max'):
|
|
67
|
+
import os
|
|
68
|
+
from dotenv import load_dotenv
|
|
69
|
+
from langchain_openai import ChatOpenAI
|
|
70
|
+
load_dotenv(override=True)
|
|
71
|
+
|
|
72
|
+
llm = ChatOpenAI(
|
|
73
|
+
model=model,
|
|
74
|
+
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
|
75
|
+
base_url=os.getenv("DASHSCOPE_BASE_URL"),
|
|
76
|
+
temperature=0.3
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
from langchain_core.messages import HumanMessage
|
|
80
|
+
from langchain_core.messages import SystemMessage
|
|
81
|
+
res = llm.invoke(
|
|
82
|
+
[
|
|
83
|
+
SystemMessage(content='为问题生成约100字的假设性答案,用于语义检索。只输出假设答案,不将其视为事实证据。'),
|
|
84
|
+
HumanMessage(content=question)
|
|
85
|
+
]
|
|
86
|
+
)
|
|
87
|
+
return res.content.strip()
|
|
88
|
+
|
|
89
|
+
# 4. 向量检索器
|
|
90
|
+
# chroma对象(db)不确定,需要当作参数传入
|
|
91
|
+
@staticmethod
|
|
92
|
+
def vector_search(question, db, top_k=5):
|
|
93
|
+
# 封装检索器
|
|
94
|
+
retriever = db.as_retriever(search_kwargs={"k": top_k})
|
|
95
|
+
# 检索
|
|
96
|
+
documents = retriever.invoke(question)
|
|
97
|
+
# 需要在metadata元数据中 添加'chunk_id'
|
|
98
|
+
# 后续进行删除,修改等操作需要
|
|
99
|
+
for document in documents:
|
|
100
|
+
document.metadata['chunk_id'] = document.id
|
|
101
|
+
return documents
|
|
102
|
+
|
|
103
|
+
# 5. BM25检索 / 关键词检索 / 稀疏检索
|
|
104
|
+
@staticmethod
|
|
105
|
+
def bm25_search(question, documents, top_k=5):
|
|
106
|
+
import jieba
|
|
107
|
+
from langchain_community.retrievers import BM25Retriever
|
|
108
|
+
|
|
109
|
+
# 如果没有数据(documents为空),则返回空列表
|
|
110
|
+
if not documents:
|
|
111
|
+
return []
|
|
112
|
+
# bm25检索到的答案是列表,如果数据为空,就检索不到答案,一定返回空列表
|
|
113
|
+
|
|
114
|
+
# 封装bm5检索器
|
|
115
|
+
bm25_retriever = BM25Retriever.from_documents(
|
|
116
|
+
documents,
|
|
117
|
+
preprocess_func=lambda text: list(jieba.cut(text)),
|
|
118
|
+
k=top_k
|
|
119
|
+
)
|
|
120
|
+
return bm25_retriever.invoke(question)
|
|
121
|
+
|
|
122
|
+
# 6. 融合检索
|
|
123
|
+
@staticmethod
|
|
124
|
+
def rrf_fusion(question, vector_retriever, bm25_retriever, weights=None, rrf_k=60):
|
|
125
|
+
# 导包引入融合检索器
|
|
126
|
+
from langchain_classic.retrievers import EnsembleRetriever
|
|
127
|
+
|
|
128
|
+
# 实例化融合检索器
|
|
129
|
+
retriever = EnsembleRetriever(
|
|
130
|
+
retrievers=[vector_retriever, bm25_retriever],
|
|
131
|
+
weights=weights or [0.5, 0, 5],
|
|
132
|
+
c=rrf_k
|
|
133
|
+
)
|
|
134
|
+
return retriever.invoke(question)
|
|
135
|
+
|
|
136
|
+
# 7. 答案去重
|
|
137
|
+
@staticmethod
|
|
138
|
+
def deduplicate(documents):
|
|
139
|
+
seen = set() # 集合用来去重
|
|
140
|
+
results = [] # 用来装去重后的答案
|
|
141
|
+
for document in documents:
|
|
142
|
+
if document.page_content not in seen:
|
|
143
|
+
seen.add(document.page_content)
|
|
144
|
+
results.append(document)
|
|
145
|
+
return results
|
|
146
|
+
|
|
147
|
+
# 8. 重排序/精排
|
|
148
|
+
@staticmethod
|
|
149
|
+
def rerank_documents(question, documents, top_k=5, model='qwen3-rerank'):
|
|
150
|
+
# 导包
|
|
151
|
+
import os
|
|
152
|
+
from dotenv import load_dotenv
|
|
153
|
+
from langchain_community.document_compressors import DashScopeRerank
|
|
154
|
+
load_dotenv(override=True)
|
|
155
|
+
# 判空
|
|
156
|
+
if not documents:
|
|
157
|
+
return []
|
|
158
|
+
# 实例化 重排序大模型对象
|
|
159
|
+
reranker = DashScopeRerank(top_n=top_k)
|
|
160
|
+
reranker.model = model
|
|
161
|
+
|
|
162
|
+
return list(reranker.compress_documents(documents, question))
|
|
163
|
+
|
|
164
|
+
# 9. 相似度阈值筛选
|
|
165
|
+
@staticmethod
|
|
166
|
+
def similarity_filter(question: str, documents, embeddings, threshold=0.4):
|
|
167
|
+
import math # 引入数学模块
|
|
168
|
+
# 判空
|
|
169
|
+
if not documents:
|
|
170
|
+
return []
|
|
171
|
+
# 获取向量
|
|
172
|
+
# 把问题向量化 -- 单一文本 返回值是一组向量
|
|
173
|
+
query_vector = embeddings.embed_query(question)
|
|
174
|
+
# 把答案向量化 -- 文本列表 返回值是向量列表
|
|
175
|
+
vectors = embeddings.embed_documents([
|
|
176
|
+
document.page_content for document in documents
|
|
177
|
+
])
|
|
178
|
+
|
|
179
|
+
# 计算 问题向量的模长
|
|
180
|
+
query_norm = math.sqrt(sum(value * value for value in query_vector))
|
|
181
|
+
|
|
182
|
+
# 遍历答案 计算每一个答案和问题的相似度
|
|
183
|
+
results = []
|
|
184
|
+
for document, vector in zip(documents, vectors):
|
|
185
|
+
# vectors [[1,2,3,6,12,56....], [1,2,3,6,12,56....],...... ]
|
|
186
|
+
# vector 每一组向量
|
|
187
|
+
vector_norm = math.sqrt(sum(value * value for value in vector)) # 答案的模长
|
|
188
|
+
if query_norm == 0 or vector_norm == 0:
|
|
189
|
+
continue
|
|
190
|
+
similarity = sum(
|
|
191
|
+
query_value * value for query_value, value in zip(query_vector, vector)
|
|
192
|
+
# query_vector [1,2,3,4,5,6,7,99,88,77......] 问题向量
|
|
193
|
+
# vector [8,5,4,2,3,99,66,105,......] 答案的向量
|
|
194
|
+
) / (query_norm * vector_norm)
|
|
195
|
+
# 分子是 点积 分母是 模长的积 similarity就是余弦值
|
|
196
|
+
if similarity >= threshold: # 相似度大于阈值的答案才保留
|
|
197
|
+
result = document.model_copy(deep=True) # 深拷贝 隔绝后续操作对原数据的影响
|
|
198
|
+
result.metadata["cosine_similarity"] = similarity
|
|
199
|
+
results.append(result)
|
|
200
|
+
return results
|
|
201
|
+
|
|
202
|
+
# 10. 上下文压缩
|
|
203
|
+
@staticmethod
|
|
204
|
+
def compress_context(question, documents, model='qwen3.8-max'):
|
|
205
|
+
import os
|
|
206
|
+
from dotenv import load_dotenv
|
|
207
|
+
from langchain_openai import ChatOpenAI
|
|
208
|
+
from langchain_classic.retrievers.document_compressors import LLMChainExtractor
|
|
209
|
+
load_dotenv(override=True)
|
|
210
|
+
|
|
211
|
+
# 判空
|
|
212
|
+
if not documents:
|
|
213
|
+
return []
|
|
214
|
+
# 实例化大模型对象
|
|
215
|
+
llm = ChatOpenAI(
|
|
216
|
+
model=model,
|
|
217
|
+
api_key=os.getenv("DASHSCOPE_API_KEY"),
|
|
218
|
+
base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
|
|
219
|
+
temperature=0,
|
|
220
|
+
)
|
|
221
|
+
# 实例化压缩器(抽取相关句子)
|
|
222
|
+
compressor = LLMChainExtractor.from_llm(llm)
|
|
223
|
+
# 答案列表中的每一个答案都要压缩
|
|
224
|
+
return compressor.compress_documents(documents, question)
|
|
225
|
+
# compressor.compress_documents方法
|
|
226
|
+
|
|
227
|
+
# 参数1. Document列表 答案列表
|
|
228
|
+
# 参数2. 问题 要向着谁压缩
|
|
229
|
+
# 返回值: Document列表 压缩后的答案列表
|
|
230
|
+
# 功能: 抽取答案中与问题相关的句子 --- 压缩
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
# 11 长上下文重排
|
|
234
|
+
# 上下文过长时 大模型会以往上下文的中间内容
|
|
235
|
+
# 所以需要把得分高的答案 放到上下文的两边
|
|
236
|
+
@staticmethod
|
|
237
|
+
def reorder_documents(documents):
|
|
238
|
+
# 导包
|
|
239
|
+
from langchain_community.document_transformers import LongContextReorder
|
|
240
|
+
|
|
241
|
+
# 把顺序操作后的答案列表返回
|
|
242
|
+
return list(LongContextReorder().transform_documents(documents))
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
# 准备一个大方法,所有优化方法(11个静态方法)都在这个方法内执行
|
|
246
|
+
# 具体哪些方法执行以及怎么执行(参数),通过配置项进行判断
|
|
247
|
+
# 将来用户进行查询的时候,只要调用这个大方法即可
|
|
248
|
+
def search(self, question, top_k, filters=None):
|
|
249
|
+
from langchain_core.documents import Document
|
|
250
|
+
# 判断question是否为空
|
|
251
|
+
if not question:
|
|
252
|
+
raise ValueError('问题不能为空')
|
|
253
|
+
|
|
254
|
+
# limit = self.config.get("top_k", 5) if top_k is None else top_k
|
|
255
|
+
limit = top_k if top_k else self.config.get("top_k", 5) # 最终答案数
|
|
256
|
+
if not isinstance(limit, int) or limit <= 0:
|
|
257
|
+
raise ValueError('tok_k必须是正整数')
|
|
258
|
+
|
|
259
|
+
# 召回池大小 最初删选多少答案
|
|
260
|
+
count = max(self.config.get('recall_top_k',20),top_k)
|
|
261
|
+
# 简化操作
|
|
262
|
+
pre = self.config.get('pre_retrieval', {})
|
|
263
|
+
hybrid = self.config.get('hybrid_retrieval', {})
|
|
264
|
+
post = self.config.get('post_retrieval', {})
|
|
265
|
+
query = question
|
|
266
|
+
keyword_query = query # 针对BM25检索
|
|
267
|
+
dense_query = query # 假性答案 针对语义检索 默认值与原提示词相同(可能经过重写)
|
|
268
|
+
# 检索前优化
|
|
269
|
+
|
|
270
|
+
if pre.get('enable',False):
|
|
271
|
+
# 总开关一旦为True 格式化自动执行
|
|
272
|
+
query = self.normalize_query(query) #格式化
|
|
273
|
+
# 判断重写是否执行
|
|
274
|
+
if pre.get('rewrite_query', False):
|
|
275
|
+
query = self.rewrite_query(query,model = pre.get('model', 'qwen-3.8-flash'))
|
|
276
|
+
|
|
277
|
+
if pre.get('hyde',False):
|
|
278
|
+
dense_query = self.generate_hyde(query, model=pre.get('model', 'qwen-3.8-flash'))
|
|
279
|
+
|
|
280
|
+
#注: 假性答案 不能做BM25检索, 只能做语义检索
|
|
281
|
+
# 一旦经过假性答案处理,必须要把原提示词(可能经过重写)保留
|
|
282
|
+
# 在假性答案之前 维护两个变量
|
|
283
|
+
# keyword_query 用来保存原提示词 后续BM25检索 就用这个变量
|
|
284
|
+
# dense_query用来保存假性答案 默认值是原提示词 语义检索就用这个变量
|
|
285
|
+
|
|
286
|
+
# 检索中优化
|
|
287
|
+
|
|
288
|
+
# 汇总筛选条件
|
|
289
|
+
conditions = []
|
|
290
|
+
for condition in (self.config.get("filters"), filters):
|
|
291
|
+
if condition:
|
|
292
|
+
conditions.extend({key: value} for key, value in condition.items())
|
|
293
|
+
where = None
|
|
294
|
+
if len(conditions) == 1:
|
|
295
|
+
where = conditions[0]
|
|
296
|
+
elif len(conditions) > 1:
|
|
297
|
+
where = {"$and": conditions}
|
|
298
|
+
# 筛选数据
|
|
299
|
+
if hybrid.get('enable', False):
|
|
300
|
+
stored = self.db.get(where = where,include=['documents','metadatas'])
|
|
301
|
+
# 整合数据
|
|
302
|
+
corpus = []
|
|
303
|
+
for i,text in enumerate(stored["documents"] or []):
|
|
304
|
+
corpus.append(Document(
|
|
305
|
+
id=stored["ids"][i],
|
|
306
|
+
page_content=text,
|
|
307
|
+
metadata=stored["metadatas"][i] or {}
|
|
308
|
+
))
|
|
309
|
+
|
|
310
|
+
if not corpus:
|
|
311
|
+
return []
|
|
312
|
+
# 检索数据
|
|
313
|
+
# 检索器
|
|
314
|
+
# 语义检索器
|
|
315
|
+
vector_retriever = self.db.as_retriever(
|
|
316
|
+
search_kwargs = {"k": count}
|
|
317
|
+
)
|
|
318
|
+
# BM25检索器
|
|
319
|
+
bm25_retriever = BM25Retriever.from_documents(
|
|
320
|
+
corpus,
|
|
321
|
+
preprocess_func=lambda text: list(jieba.cut(text)),
|
|
322
|
+
k=count
|
|
323
|
+
)
|
|
324
|
+
documents = self.rrf_fusion(keyword_query,vector_retriever,bm25_retriever)
|
|
325
|
+
else:
|
|
326
|
+
# 融合检索未开启,只使用语义检索即可
|
|
327
|
+
documents = self.vector_search(dense_query,self.db,count)
|
|
328
|
+
|
|
329
|
+
# 检索后优化
|
|
330
|
+
if post.get('enable',False):
|
|
331
|
+
if post.get('deduplicate',False):
|
|
332
|
+
documents = self.deduplicate(documents)
|
|
333
|
+
if post.get('rerank',False):
|
|
334
|
+
documents = self.rerank_documents(query,documents,top_k=count,model=post.get('rerank_model','qwen3-rerank'))
|
|
335
|
+
# 问题: 重排的时候 为什么要保留所有答案,而不是保留最终答案数
|
|
336
|
+
# 答: 只要后续操作(相似度阈值筛选)还有可能改变答案数,则不要主动操作个数
|
|
337
|
+
if post.get('similarity_filter',False):
|
|
338
|
+
documents = self.similarity_filter(query,documents,self.embeddings,threshold=post.get('similarity_threshold',0.4))
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
# 至此后去操作不会再改变答案个数,所以我们需要对答案进行主动截断
|
|
342
|
+
# 更新 要保留的答案数
|
|
343
|
+
# 经过筛选 答案数可能不够 所以要更新\
|
|
344
|
+
limit = limit if len(documents)>=limit else len(documents)
|
|
345
|
+
documents = documents[:limit]
|
|
346
|
+
if post.get('enable',False):
|
|
347
|
+
if post.get('compress_context',False):
|
|
348
|
+
documents = self.compress_context(query,documents,model=post.get('llm_model','qwen3.8-flash'))
|
|
349
|
+
|
|
350
|
+
if post.get('reorder',False):
|
|
351
|
+
documents = self.reorder_documents(documents)
|
|
352
|
+
return documents
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
if __name__ == "__main__":
|
|
356
|
+
config = {
|
|
357
|
+
"persist_directory": "./chroma_db",
|
|
358
|
+
"collection_name": "study",
|
|
359
|
+
"embedding_model": "text-embedding-v4",
|
|
360
|
+
"top_k": 5,
|
|
361
|
+
"recall_top_k": 20,
|
|
362
|
+
"pre_retrieval": {
|
|
363
|
+
"enabled": True,
|
|
364
|
+
"rewrite_query": True,
|
|
365
|
+
"hyde": True,
|
|
366
|
+
"model": "qwen-plus",
|
|
367
|
+
},
|
|
368
|
+
"hybrid_retrieval": {"enabled": True},
|
|
369
|
+
"post_retrieval": {
|
|
370
|
+
"enabled": True,
|
|
371
|
+
"deduplicate": True,
|
|
372
|
+
"rerank": True,
|
|
373
|
+
"rerank_model": "qwen3-rerank",
|
|
374
|
+
"similarity_filter": True,
|
|
375
|
+
"similarity_threshold": 0.4,
|
|
376
|
+
"compress_context": True,
|
|
377
|
+
"llm_model": "qwen-plus",
|
|
378
|
+
"reorder": True,
|
|
379
|
+
},
|
|
380
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: modular-rag-langchain
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A modular RAG retrieval class based on LangChain and Chroma
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: chromadb
|
|
8
|
+
Requires-Dist: langchain-chroma
|
|
9
|
+
Requires-Dist: langchain-community
|
|
10
|
+
Requires-Dist: langchain-core
|
|
11
|
+
Requires-Dist: langchain-openai
|
|
12
|
+
Requires-Dist: langchain-classic
|
|
13
|
+
Requires-Dist: jieba
|
|
14
|
+
Requires-Dist: rank-bm25
|
|
15
|
+
Requires-Dist: python-dotenv
|
|
16
|
+
Requires-Dist: dashscope
|
|
17
|
+
Provides-Extra: publish
|
|
18
|
+
Requires-Dist: build; extra == "publish"
|
|
19
|
+
Requires-Dist: twine; extra == "publish"
|
|
20
|
+
|
|
21
|
+
# modular-rag-langchain
|
|
22
|
+
|
|
23
|
+
提供一个 `ModularRAG` 类,用于连接已有的 Chroma 知识库并执行在线检索。
|
|
24
|
+
|
|
25
|
+
Python 3.11 及以上。
|
|
26
|
+
|
|
27
|
+
## 安装
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
pip install modular-rag-langchain
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## 使用
|
|
34
|
+
|
|
35
|
+
```python
|
|
36
|
+
from langchain_modular_rag import ModularRAG
|
|
37
|
+
|
|
38
|
+
rag = ModularRAG({
|
|
39
|
+
"persist_directory": "./chroma_db",
|
|
40
|
+
"collection_name": "study",
|
|
41
|
+
"embedding_model": "text-embedding-v4",
|
|
42
|
+
"top_k": 5,
|
|
43
|
+
"recall_top_k": 20,
|
|
44
|
+
"pre_retrieval": {
|
|
45
|
+
"enabled": False,
|
|
46
|
+
"rewrite_query": False,
|
|
47
|
+
"hyde": False,
|
|
48
|
+
"model": "qwen-plus",
|
|
49
|
+
},
|
|
50
|
+
"hybrid_retrieval": {
|
|
51
|
+
"enabled": True,
|
|
52
|
+
"weights": [0.5, 0.5],
|
|
53
|
+
},
|
|
54
|
+
"post_retrieval": {
|
|
55
|
+
"enabled": True,
|
|
56
|
+
"deduplicate": True,
|
|
57
|
+
"rerank": False,
|
|
58
|
+
"rerank_model": "qwen3-rerank",
|
|
59
|
+
"similarity_filter": False,
|
|
60
|
+
"similarity_threshold": 0.4,
|
|
61
|
+
"compress_context": False,
|
|
62
|
+
"llm_model": "qwen-plus",
|
|
63
|
+
"reorder": False,
|
|
64
|
+
},
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
results = rag.search("公司打卡时间?")
|
|
68
|
+
for document in results:
|
|
69
|
+
print(document.metadata)
|
|
70
|
+
print(document.page_content)
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## 环境变量
|
|
74
|
+
|
|
75
|
+
需要配置通义 API Key:
|
|
76
|
+
|
|
77
|
+
```bash
|
|
78
|
+
export DASHSCOPE_API_KEY="你的 API Key"
|
|
79
|
+
或
|
|
80
|
+
setx DASHSCOPE_API_KEY="你的 API Key"
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
`persist_directory` 指向已经完成入库的 Chroma 数据库。这个包当前只提供在线检索,不包含你的个人知识库数据,也不会自动创建或导入知识库。
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
langchain_modular_rag.py
|
|
3
|
+
pyproject.toml
|
|
4
|
+
modular_rag_langchain.egg-info/PKG-INFO
|
|
5
|
+
modular_rag_langchain.egg-info/SOURCES.txt
|
|
6
|
+
modular_rag_langchain.egg-info/dependency_links.txt
|
|
7
|
+
modular_rag_langchain.egg-info/requires.txt
|
|
8
|
+
modular_rag_langchain.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
langchain_modular_rag
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "modular-rag-langchain"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "A modular RAG retrieval class based on LangChain and Chroma"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.11"
|
|
11
|
+
dependencies = [
|
|
12
|
+
"chromadb",
|
|
13
|
+
"langchain-chroma",
|
|
14
|
+
"langchain-community",
|
|
15
|
+
"langchain-core",
|
|
16
|
+
"langchain-openai",
|
|
17
|
+
"langchain-classic",
|
|
18
|
+
"jieba",
|
|
19
|
+
"rank-bm25",
|
|
20
|
+
"python-dotenv",
|
|
21
|
+
"dashscope",
|
|
22
|
+
]
|
|
23
|
+
|
|
24
|
+
[project.optional-dependencies]
|
|
25
|
+
publish = ["build", "twine"]
|
|
26
|
+
|
|
27
|
+
[tool.setuptools]
|
|
28
|
+
py-modules = ["langchain_modular_rag"]
|