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