misayafff-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.
@@ -0,0 +1,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: misayafff-modular-rag
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
+ # langchain-modular-rag
22
+
23
+ 提供一个 `ModularRAG` 类,用于连接已有的 Chroma 知识库并执行在线检索。
24
+
25
+ Python 3.11 及以上。
26
+
27
+ ## 安装
28
+
29
+ ```bash
30
+ pip install langchain-modular-rag
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
+ # langchain-modular-rag
2
+
3
+ 提供一个 `ModularRAG` 类,用于连接已有的 Chroma 知识库并执行在线检索。
4
+
5
+ Python 3.11 及以上。
6
+
7
+ ## 安装
8
+
9
+ ```bash
10
+ pip install langchain-modular-rag
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,83 @@
1
+ Metadata-Version: 2.4
2
+ Name: misayafff-modular-rag
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
+ # langchain-modular-rag
22
+
23
+ 提供一个 `ModularRAG` 类,用于连接已有的 Chroma 知识库并执行在线检索。
24
+
25
+ Python 3.11 及以上。
26
+
27
+ ## 安装
28
+
29
+ ```bash
30
+ pip install langchain-modular-rag
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
+ misayafff_modular_rag.py
3
+ pyproject.toml
4
+ misayafff_modular_rag.egg-info/PKG-INFO
5
+ misayafff_modular_rag.egg-info/SOURCES.txt
6
+ misayafff_modular_rag.egg-info/dependency_links.txt
7
+ misayafff_modular_rag.egg-info/requires.txt
8
+ misayafff_modular_rag.egg-info/top_level.txt
@@ -0,0 +1,14 @@
1
+ chromadb
2
+ langchain-chroma
3
+ langchain-community
4
+ langchain-core
5
+ langchain-openai
6
+ langchain-classic
7
+ jieba
8
+ rank-bm25
9
+ python-dotenv
10
+ dashscope
11
+
12
+ [publish]
13
+ build
14
+ twine
@@ -0,0 +1 @@
1
+ misayafff_modular_rag
@@ -0,0 +1,299 @@
1
+ class ModularRAG:
2
+ def __init__(self, config: dict):
3
+ import os
4
+ from pathlib import Path
5
+ from dotenv import load_dotenv
6
+ from langchain_chroma import Chroma
7
+ from langchain_community.embeddings import DashScopeEmbeddings
8
+
9
+ load_dotenv()
10
+ self.config = config
11
+ directory = config.get("persist_directory", "./chroma_db")
12
+ if not (Path(directory).expanduser() / "chroma.sqlite3").is_file():
13
+ raise FileNotFoundError(f"知识库不存在:{directory}")
14
+ self.embeddings = DashScopeEmbeddings(
15
+ model=config.get("embedding_model", "text-embedding-v4"),
16
+ dashscope_api_key=os.getenv("DASHSCOPE_API_KEY"),
17
+ )
18
+ self.db = Chroma(
19
+ collection_name=config.get("collection_name", "study"),
20
+ persist_directory=str(Path(directory).expanduser()),
21
+ embedding_function=self.embeddings,
22
+ create_collection_if_not_exists=False,
23
+ )
24
+
25
+ def search(self, question: str, top_k=None, filters=None):
26
+ from langchain_core.documents import Document
27
+
28
+ if not question.strip():
29
+ raise ValueError("问题不能为空")
30
+ limit = self.config.get("top_k", 5) if top_k is None else top_k
31
+ if not isinstance(limit, int) or limit <= 0:
32
+ raise ValueError("top_k 必须是正整数")
33
+ count = max(self.config.get("recall_top_k", 20), limit)
34
+ pre = self.config.get("pre_retrieval", {})
35
+ hybrid = self.config.get("hybrid_retrieval", {})
36
+ post = self.config.get("post_retrieval", {})
37
+
38
+ query = question
39
+ if pre.get("enabled", False):
40
+ query = self.normalize_query(query)
41
+ if pre.get("rewrite_query", False):
42
+ query = self.rewrite_query(query, model=pre.get("model", "qwen-plus"))
43
+ keyword_query = query
44
+ dense_query = query
45
+ if pre.get("enabled", False) and pre.get("hyde", False):
46
+ dense_query = self.generate_hyde(query, model=pre.get("model", "qwen-plus"))
47
+
48
+ conditions = []
49
+ for condition in (self.config.get("filters"), filters):
50
+ if condition:
51
+ conditions.extend({key: value} for key, value in condition.items())
52
+ where = None
53
+ if len(conditions) == 1:
54
+ where = conditions[0]
55
+ elif len(conditions) > 1:
56
+ where = {"$and": conditions}
57
+
58
+ if hybrid.get("enabled", False):
59
+ import jieba
60
+ from langchain_community.retrievers import BM25Retriever
61
+ from langchain_core.runnables import RunnableLambda
62
+
63
+ stored = self.db.get(where=where, include=["documents", "metadatas"])
64
+ corpus = []
65
+ for index, text in enumerate(stored["documents"] or []):
66
+ corpus.append(Document(
67
+ id=stored["ids"][index],
68
+ page_content=text,
69
+ metadata=stored["metadatas"][index] or {},
70
+ ))
71
+ if not corpus:
72
+ return []
73
+ vector_retriever = self.db.as_retriever(
74
+ search_type="similarity",
75
+ search_kwargs={"k": count, "filter": where},
76
+ )
77
+ if dense_query != keyword_query:
78
+ vector_retriever = (
79
+ RunnableLambda(lambda incoming_query: dense_query) | vector_retriever
80
+ )
81
+ bm25_retriever = BM25Retriever.from_documents(
82
+ corpus,
83
+ preprocess_func=lambda text: list(jieba.cut(text)),
84
+ k=count,
85
+ )
86
+ documents = self.rrf_fusion(
87
+ keyword_query, vector_retriever, bm25_retriever,
88
+ weights=hybrid.get("weights", [0.5, 0.5]),
89
+ )
90
+ else:
91
+ documents = self.vector_search(dense_query, self.db, count, where)
92
+
93
+ if post.get("enabled", False):
94
+ if post.get("deduplicate", True):
95
+ documents = self.deduplicate(documents)
96
+ if post.get("rerank", False):
97
+ documents = self.rerank_documents(
98
+ question, documents, top_k=len(documents),
99
+ model=post.get("rerank_model", "qwen3-rerank"),
100
+ )
101
+ if post.get("similarity_filter", False):
102
+ documents = self.similarity_filter(
103
+ question, documents, self.embeddings,
104
+ threshold=post.get("similarity_threshold", 0.4),
105
+ )
106
+
107
+ documents = documents[:limit]
108
+ for rank, document in enumerate(documents, start=1):
109
+ document.metadata["retrieval_rank"] = rank
110
+
111
+ if post.get("enabled", False):
112
+ if post.get("compress_context", False):
113
+ documents = self.compress_context(
114
+ question, documents, model=post.get("llm_model", "qwen-plus")
115
+ )
116
+ if post.get("reorder", False):
117
+ documents = self.reorder_documents(documents)
118
+ for position, document in enumerate(documents, start=1):
119
+ document.metadata["context_position"] = position
120
+ return documents
121
+
122
+ @staticmethod
123
+ # ==================== 1. 归一化查询词:移除所有空格并首尾去空格 ====================
124
+ def normalize_query(question: str):
125
+ import re
126
+ return re.sub(r"\s+", " ", question).strip() # 移除所有空格并首尾去空格
127
+
128
+ @staticmethod
129
+ # ==================== 2. 改写查询词:根据模型提示改写为适合知识库检索的独立查询 ====================
130
+ def rewrite_query(question: str, model="qwen-plus"):
131
+ import os
132
+ from dotenv import load_dotenv
133
+ from langchain_openai import ChatOpenAI
134
+
135
+ load_dotenv()
136
+ llm = ChatOpenAI(
137
+ model=model,
138
+ api_key=os.getenv("DASHSCOPE_API_KEY"),
139
+ base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
140
+ temperature=0,
141
+ )
142
+ response = llm.invoke([
143
+ ("system", "把问题改写为适合知识库检索的独立查询。保留原意,不编造缺失上下文,只输出查询。"),
144
+ ("human", question),
145
+ ])
146
+ return response.content.strip()
147
+
148
+ @staticmethod
149
+ # ==================== 3. 生成假设性答案:根据模型提示生成约100字的假设性答案 ====================
150
+ def generate_hyde(question: str, model="qwen-plus"):
151
+ import os
152
+ from dotenv import load_dotenv
153
+ from langchain_openai import ChatOpenAI
154
+
155
+ load_dotenv()
156
+ llm = ChatOpenAI(
157
+ model=model,
158
+ api_key=os.getenv("DASHSCOPE_API_KEY"),
159
+ base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
160
+ temperature=0,
161
+ )
162
+ response = llm.invoke([
163
+ ("system", "为问题生成约100字的假设性答案,用于语义检索。只输出假设答案,不将其视为事实证据。"),
164
+ ("human", question),
165
+ ])
166
+ return response.content.strip()
167
+
168
+ @staticmethod
169
+ # ==================== 4. 稠密:向量检索召回文档 ====================
170
+ def vector_search(question: str, db, top_k=5, filters=None):
171
+ retriever = db.as_retriever(
172
+ search_type="similarity",
173
+ search_kwargs={"k": top_k, "filter": filters},
174
+ )
175
+ documents = retriever.invoke(question)
176
+ for document in documents:
177
+ document.metadata["chunk_id"] = document.id
178
+ return documents
179
+
180
+ @staticmethod
181
+ # ==================== 5. 稀疏:BM25检索召回文档 ====================
182
+ def bm25_search(question: str, documents, top_k=5):
183
+ import jieba
184
+ from langchain_community.retrievers import BM25Retriever
185
+
186
+ if not documents:
187
+ return []
188
+ bm25_retriever = BM25Retriever.from_documents(
189
+ documents,
190
+ preprocess_func=lambda text: list(jieba.cut(text)),
191
+ k=top_k,
192
+ )
193
+ return bm25_retriever.invoke(question)
194
+
195
+ @staticmethod
196
+ # ==================== 6. RRF融合召回文档 ====================
197
+ def rrf_fusion(question: str, vector_retriever, bm25_retriever, weights=None, rrf_k=60):
198
+ from langchain_classic.retrievers import EnsembleRetriever
199
+
200
+ retriever = EnsembleRetriever(
201
+ retrievers=[vector_retriever, bm25_retriever],
202
+ weights=weights or [0.5, 0.5],
203
+ c=rrf_k,
204
+ )
205
+ return retriever.invoke(question)
206
+
207
+ @staticmethod
208
+ # ==================== 7. 去重:根据文档内容去重 ====================
209
+ def deduplicate(documents):
210
+ seen = set()
211
+ results = []
212
+ for document in documents:
213
+ if document.page_content not in seen:
214
+ seen.add(document.page_content)
215
+ results.append(document)
216
+ return results
217
+
218
+ from langchain_core.documents import Document
219
+
220
+ @staticmethod
221
+ # ==================== 8. 重排:根据模型提示重排召回文档 ====================
222
+ def rerank_documents(question: str, documents, top_k=5, model="qwen3-rerank"):
223
+ import os
224
+ from dotenv import load_dotenv
225
+ from langchain_community.document_compressors import DashScopeRerank
226
+
227
+ if not documents:
228
+ return []
229
+ load_dotenv()
230
+ reranker = DashScopeRerank(
231
+ model=model,
232
+ dashscope_api_key=os.getenv("DASHSCOPE_API_KEY"),
233
+ top_n=top_k,
234
+ )
235
+ return list(reranker.compress_documents(documents, question))
236
+
237
+ @staticmethod
238
+ # ==================== 9. 筛选:根据文档相似度筛选出相关文档 ====================
239
+ def similarity_filter(question: str, documents, embeddings, threshold=0.4):
240
+ import math
241
+
242
+ if not documents:
243
+ return []
244
+ query_vector = embeddings.embed_query(question)
245
+ vectors = embeddings.embed_documents([
246
+ document.page_content for document in documents
247
+ ])
248
+ query_norm = math.sqrt(sum(value * value for value in query_vector))
249
+
250
+ results = []
251
+ for document, vector in zip(documents, vectors):
252
+ vector_norm = math.sqrt(sum(value * value for value in vector))
253
+ if query_norm == 0 or vector_norm == 0:
254
+ continue
255
+ similarity = sum(
256
+ query_value * value for query_value, value in zip(query_vector, vector)
257
+ ) / (query_norm * vector_norm)
258
+ if similarity >= threshold:
259
+ result = document.model_copy(deep=True)
260
+ result.metadata["cosine_similarity"] = similarity
261
+ results.append(result)
262
+ return results
263
+
264
+ @staticmethod
265
+ # ==================== 10. 压缩:根据模型提示压缩文档上下文 ====================
266
+ def compress_context(question: str, documents, model="qwen-plus"):
267
+ import os
268
+ from dotenv import load_dotenv
269
+ from langchain_openai import ChatOpenAI
270
+ from langchain_classic.retrievers.document_compressors import LLMChainExtractor
271
+
272
+ if not documents:
273
+ return []
274
+ load_dotenv()
275
+ llm = ChatOpenAI(
276
+ model=model,
277
+ api_key=os.getenv("DASHSCOPE_API_KEY"),
278
+ base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
279
+ temperature=0,
280
+ )
281
+ compressor = LLMChainExtractor.from_llm(llm)
282
+ results = []
283
+ for document in documents:
284
+ is_table = (
285
+ document.metadata.get("content_type") == "table"
286
+ or "<table" in document.page_content.lower()
287
+ )
288
+ if is_table:
289
+ results.append(document)
290
+ else:
291
+ results.extend(compressor.compress_documents([document], question))
292
+ return results
293
+
294
+ @staticmethod
295
+ # ==================== 11. 压缩:根据模型提示压缩文档上下文 ====================
296
+ def reorder_documents(documents):
297
+ from langchain_community.document_transformers import LongContextReorder
298
+
299
+ return list(LongContextReorder().transform_documents(documents))
@@ -0,0 +1,28 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "misayafff-modular-rag"
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 = ["misayafff_modular_rag"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+