langchain-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.
- langchain_modular_rag-0.1.0/PKG-INFO +85 -0
- langchain_modular_rag-0.1.0/README.md +65 -0
- langchain_modular_rag-0.1.0/langchain_modular_rag.egg-info/PKG-INFO +85 -0
- langchain_modular_rag-0.1.0/langchain_modular_rag.egg-info/SOURCES.txt +8 -0
- langchain_modular_rag-0.1.0/langchain_modular_rag.egg-info/dependency_links.txt +1 -0
- langchain_modular_rag-0.1.0/langchain_modular_rag.egg-info/requires.txt +14 -0
- langchain_modular_rag-0.1.0/langchain_modular_rag.egg-info/top_level.txt +1 -0
- langchain_modular_rag-0.1.0/langchain_modular_rag.py +299 -0
- langchain_modular_rag-0.1.0/pyproject.toml +28 -0
- langchain_modular_rag-0.1.0/setup.cfg +4 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langchain-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
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install langchain-modular-rag
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
## 使用
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from langchain_modular_rag import ModularRAG
|
|
39
|
+
|
|
40
|
+
rag = ModularRAG({
|
|
41
|
+
"persist_directory": "./chroma_db",
|
|
42
|
+
"collection_name": "study",
|
|
43
|
+
"embedding_model": "text-embedding-v4",
|
|
44
|
+
"top_k": 5,
|
|
45
|
+
"recall_top_k": 20,
|
|
46
|
+
"pre_retrieval": {
|
|
47
|
+
"enabled": False,
|
|
48
|
+
"rewrite_query": False,
|
|
49
|
+
"hyde": False,
|
|
50
|
+
"model": "qwen-plus",
|
|
51
|
+
},
|
|
52
|
+
"hybrid_retrieval": {
|
|
53
|
+
"enabled": True,
|
|
54
|
+
"weights": [0.5, 0.5],
|
|
55
|
+
},
|
|
56
|
+
"post_retrieval": {
|
|
57
|
+
"enabled": True,
|
|
58
|
+
"deduplicate": True,
|
|
59
|
+
"rerank": False,
|
|
60
|
+
"rerank_model": "qwen3-rerank",
|
|
61
|
+
"similarity_filter": False,
|
|
62
|
+
"similarity_threshold": 0.4,
|
|
63
|
+
"compress_context": False,
|
|
64
|
+
"llm_model": "qwen-plus",
|
|
65
|
+
"reorder": False,
|
|
66
|
+
},
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
results = rag.search("公司打卡时间?")
|
|
70
|
+
for document in results:
|
|
71
|
+
print(document.metadata)
|
|
72
|
+
print(document.page_content)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## 环境变量
|
|
76
|
+
|
|
77
|
+
需要配置通义 API Key:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
export DASHSCOPE_API_KEY="你的 API Key"
|
|
81
|
+
或
|
|
82
|
+
setx DASHSCOPE_API_KEY="你的 API Key"
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`persist_directory` 指向已经完成入库的 Chroma 数据库。这个包当前只提供在线检索,不包含你的个人知识库数据,也不会自动创建或导入知识库。
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
# langchain-modular-rag
|
|
2
|
+
|
|
3
|
+
提供一个 `ModularRAG` 类,用于连接已有的 Chroma 知识库并执行在线检索。
|
|
4
|
+
|
|
5
|
+
Python 3.11 及以上。
|
|
6
|
+
|
|
7
|
+
## 安装
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install langchain-modular-rag
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
## 使用
|
|
16
|
+
|
|
17
|
+
```python
|
|
18
|
+
from langchain_modular_rag import ModularRAG
|
|
19
|
+
|
|
20
|
+
rag = ModularRAG({
|
|
21
|
+
"persist_directory": "./chroma_db",
|
|
22
|
+
"collection_name": "study",
|
|
23
|
+
"embedding_model": "text-embedding-v4",
|
|
24
|
+
"top_k": 5,
|
|
25
|
+
"recall_top_k": 20,
|
|
26
|
+
"pre_retrieval": {
|
|
27
|
+
"enabled": False,
|
|
28
|
+
"rewrite_query": False,
|
|
29
|
+
"hyde": False,
|
|
30
|
+
"model": "qwen-plus",
|
|
31
|
+
},
|
|
32
|
+
"hybrid_retrieval": {
|
|
33
|
+
"enabled": True,
|
|
34
|
+
"weights": [0.5, 0.5],
|
|
35
|
+
},
|
|
36
|
+
"post_retrieval": {
|
|
37
|
+
"enabled": True,
|
|
38
|
+
"deduplicate": True,
|
|
39
|
+
"rerank": False,
|
|
40
|
+
"rerank_model": "qwen3-rerank",
|
|
41
|
+
"similarity_filter": False,
|
|
42
|
+
"similarity_threshold": 0.4,
|
|
43
|
+
"compress_context": False,
|
|
44
|
+
"llm_model": "qwen-plus",
|
|
45
|
+
"reorder": False,
|
|
46
|
+
},
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
results = rag.search("公司打卡时间?")
|
|
50
|
+
for document in results:
|
|
51
|
+
print(document.metadata)
|
|
52
|
+
print(document.page_content)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## 环境变量
|
|
56
|
+
|
|
57
|
+
需要配置通义 API Key:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
export DASHSCOPE_API_KEY="你的 API Key"
|
|
61
|
+
或
|
|
62
|
+
setx DASHSCOPE_API_KEY="你的 API Key"
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
`persist_directory` 指向已经完成入库的 Chroma 数据库。这个包当前只提供在线检索,不包含你的个人知识库数据,也不会自动创建或导入知识库。
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: langchain-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
|
+
|
|
30
|
+
```bash
|
|
31
|
+
pip install langchain-modular-rag
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
## 使用
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
from langchain_modular_rag import ModularRAG
|
|
39
|
+
|
|
40
|
+
rag = ModularRAG({
|
|
41
|
+
"persist_directory": "./chroma_db",
|
|
42
|
+
"collection_name": "study",
|
|
43
|
+
"embedding_model": "text-embedding-v4",
|
|
44
|
+
"top_k": 5,
|
|
45
|
+
"recall_top_k": 20,
|
|
46
|
+
"pre_retrieval": {
|
|
47
|
+
"enabled": False,
|
|
48
|
+
"rewrite_query": False,
|
|
49
|
+
"hyde": False,
|
|
50
|
+
"model": "qwen-plus",
|
|
51
|
+
},
|
|
52
|
+
"hybrid_retrieval": {
|
|
53
|
+
"enabled": True,
|
|
54
|
+
"weights": [0.5, 0.5],
|
|
55
|
+
},
|
|
56
|
+
"post_retrieval": {
|
|
57
|
+
"enabled": True,
|
|
58
|
+
"deduplicate": True,
|
|
59
|
+
"rerank": False,
|
|
60
|
+
"rerank_model": "qwen3-rerank",
|
|
61
|
+
"similarity_filter": False,
|
|
62
|
+
"similarity_threshold": 0.4,
|
|
63
|
+
"compress_context": False,
|
|
64
|
+
"llm_model": "qwen-plus",
|
|
65
|
+
"reorder": False,
|
|
66
|
+
},
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
results = rag.search("公司打卡时间?")
|
|
70
|
+
for document in results:
|
|
71
|
+
print(document.metadata)
|
|
72
|
+
print(document.page_content)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
## 环境变量
|
|
76
|
+
|
|
77
|
+
需要配置通义 API Key:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
export DASHSCOPE_API_KEY="你的 API Key"
|
|
81
|
+
或
|
|
82
|
+
setx DASHSCOPE_API_KEY="你的 API Key"
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
`persist_directory` 指向已经完成入库的 Chroma 数据库。这个包当前只提供在线检索,不包含你的个人知识库数据,也不会自动创建或导入知识库。
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
README.md
|
|
2
|
+
langchain_modular_rag.py
|
|
3
|
+
pyproject.toml
|
|
4
|
+
langchain_modular_rag.egg-info/PKG-INFO
|
|
5
|
+
langchain_modular_rag.egg-info/SOURCES.txt
|
|
6
|
+
langchain_modular_rag.egg-info/dependency_links.txt
|
|
7
|
+
langchain_modular_rag.egg-info/requires.txt
|
|
8
|
+
langchain_modular_rag.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
langchain_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 = "langchain-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 = ["langchain_modular_rag"]
|