1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
| from typing import List, Dict, Any
from sentence_transformers import SentenceTransformer
import numpy as np
class EnterpriseRAG:
"""企业级RAG系统"""
def __init__(self, config: Dict[str, Any]):
# 配置
self.config = config
# 嵌入模型
self.embedder = SentenceTransformer(
config.get("embed_model", "sentence-transformers/all-MiniLM-L6-v2")
)
# 向量数据库
self.vector_db = self._init_vector_db(config.get("vector_db"))
# LLM客户端
self.llm = self._init_llm(config.get("llm"))
def _init_vector_db(self, db_config: Dict):
"""初始化向量数据库"""
db_type = db_config.get("type", "faiss")
if db_type == "faiss":
import faiss
dimension = self.embedder.get_sentence_embedding_dimension()
index = faiss.IndexFlatIP(dimension)
return {"type": "faiss", "index": index}
elif db_type == "pinecone":
import pinecone
pinecone.init(
api_key=db_config["api_key"],
environment=db_config["environment"]
)
return {"type": "pinecone"}
elif db_type == "milvus":
from pymilvus import connections, Collection
connections.connect(
alias="default",
host=db_config["host"],
port=db_config["port"]
)
return {"type": "milvus"}
def _init_llm(self, llm_config: Dict):
"""初始化LLM"""
provider = llm_config.get("provider", "anthropic")
if provider == "anthropic":
from anthropic import Anthropic
return Anthropic(api_key=llm_config["api_key"])
elif provider == "openai":
from openai import OpenAI
return OpenAI(api_key=llm_config["api_key"])
elif provider == "local":
# 使用本地模型
return None
def index_documents(self, documents: List[Dict[str, Any]]):
"""索引文档"""
# 提取文本
texts = [doc["content"] for doc in documents]
# 文本切分
chunks = self._chunk_texts(texts, chunk_size=500, overlap=50)
# 生成嵌入
embeddings = self.embedder.encode(
[chunk["text"] for chunk in chunks]
)
# 存储到向量数据库
self._store_embeddings(chunks, embeddings)
def _chunk_texts(
self,
texts: List[str],
chunk_size: int = 500,
overlap: int = 50
) -> List[Dict]:
"""文本切分"""
chunks = []
for idx, text in enumerate(texts):
# 按段落切分
paragraphs = text.split("\n\n")
current_chunk = ""
chunk_id = 0
for para in paragraphs:
if len(current_chunk) + len(para) > chunk_size:
if current_chunk:
chunks.append({
"text": current_chunk.strip(),
"doc_id": idx,
"chunk_id": chunk_id
})
chunk_id += 1
current_chunk = para[overlap:]
else:
current_chunk += "\n\n" + para
if current_chunk:
chunks.append({
"text": current_chunk.strip(),
"doc_id": idx,
"chunk_id": chunk_id
})
return chunks
def _store_embeddings(self, chunks: List[Dict], embeddings: np.ndarray):
"""存储嵌入"""
db_type = self.vector_db["type"]
if db_type == "faiss":
import faiss
# 归一化
faiss.normalize_L2(embeddings)
# 添加到索引
self.vector_db["index"].add(
embeddings.astype("float32")
)
# 存储元数据
if "metadata" not in self.vector_db:
self.vector_db["metadata"] = []
self.vector_db["metadata"].extend(chunks)
elif db_type == "pinecone":
import pinecone
index = pinecone.Index(self.vector_db["index_name"])
for i, (chunk, embedding) in enumerate(zip(chunks, embeddings)):
index.upsert([
(str(i), embedding.tolist(), {
"text": chunk["text"],
"doc_id": chunk["doc_id"]
})
])
def retrieve(self, query: str, top_k: int = 5) -> List[Dict]:
"""检索相关文档"""
# 生成查询嵌入
query_embedding = self.embedder.encode([query])
db_type = self.vector_db["type"]
if db_type == "faiss":
import faiss
# 归一化
faiss.normalize_L2(query_embedding)
# 搜索
scores, indices = self.vector_db["index"].search(
query_embedding.astype("float32"),
top_k
)
# 组装结果
results = []
for score, idx in zip(scores[0], indices[0]):
if idx < len(self.vector_db["metadata"]):
meta = self.vector_db["metadata"][idx]
results.append({
"text": meta["text"],
"score": float(score),
"doc_id": meta["doc_id"]
})
return results
elif db_type == "pinecone":
import pinecone
index = pinecone.Index(self.vector_db["index_name"])
query_result = index.query(
vector=query_embedding[0].tolist(),
top_k=top_k,
include_metadata=True
)
return [
{
"text": match["metadata"]["text"],
"score": match["score"],
"doc_id": match["metadata"]["doc_id"]
}
for match in query_result["matches"]
]
def generate(self, query: str, context: List[Dict]) -> str:
"""生成回答"""
# 构建提示
context_text = "\n\n".join([
f"[文档{i+1}] {doc['text']}"
for i, doc in enumerate(context)
])
prompt = f"""
基于以下文档回答问题。如果文档中没有相关信息,请明确说明。
{context_text}
问题:{query}
回答:
"""
# 调用LLM
if self.llm:
response = self.llm.messages.create(
model="claude-3-5-sonnet-20241022",
max_tokens=2048,
messages=[{"role": "user", "content": prompt}]
)
return response.content[0].text
else:
# 本地模型
pass
def ask(self, query: str, top_k: int = 5) -> Dict[str, Any]:
"""问答接口"""
# 检索
retrieved_docs = self.retrieve(query, top_k=top_k)
# 检查相关性
if retrieved_docs and retrieved_docs[0]["score"] < 0.5:
return {
"answer": "抱歉,我在知识库中没有找到相关信息。",
"sources": [],
"confidence": "low"
}
# 生成
answer = self.generate(query, retrieved_docs)
return {
"answer": answer,
"sources": [
{"doc_id": doc["doc_id"], "score": doc["score"]}
for doc in retrieved_docs
],
"confidence": "high" if retrieved_docs[0]["score"] > 0.7 else "medium"
}
|