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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from langchain_community.document_loaders import TextLoader, DirectoryLoader
|
| 4 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 5 |
+
from langchain_community.vectorstores import FAISS
|
| 6 |
+
from langchain_openai import ChatOpenAI
|
| 7 |
+
from langchain.prompts import PromptTemplate
|
| 8 |
+
import numpy as np
|
| 9 |
+
import faiss
|
| 10 |
+
from collections import deque
|
| 11 |
+
from langchain_core.embeddings import Embeddings
|
| 12 |
+
import threading
|
| 13 |
+
import queue
|
| 14 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
| 15 |
+
from sentence_transformers import SentenceTransformer
|
| 16 |
+
import pickle
|
| 17 |
+
import torch
|
| 18 |
+
from langchain_core.documents import Document
|
| 19 |
+
import time
|
| 20 |
+
from tqdm import tqdm
|
| 21 |
+
from rank_bm25 import BM25Okapi # 确保正确导入
|
| 22 |
+
import jieba # 引入中文分词库
|
| 23 |
+
|
| 24 |
+
# 获取 OPENROUTER_API_KEY 环境变量
|
| 25 |
+
os.environ["OPENROUTER_API_KEY"] = os.getenv("OPENROUTER_API_KEY", "")
|
| 26 |
+
if not os.environ["OPENROUTER_API_KEY"]:
|
| 27 |
+
raise ValueError("OPENROUTER_API_KEY 未设置,请在环境变量中配置或在 .env 文件中添加")
|
| 28 |
+
|
| 29 |
+
# 自定义 SentenceTransformerEmbeddings 类(使用 BAAI/bge-m3 模型,适配 CPU)
|
| 30 |
+
class SentenceTransformerEmbeddings(Embeddings):
|
| 31 |
+
def __init__(self, model_name="BAAI/bge-m3"):
|
| 32 |
+
self.model = SentenceTransformer(model_name, device="cpu")
|
| 33 |
+
self.batch_size = 64
|
| 34 |
+
self.query_cache = {}
|
| 35 |
+
|
| 36 |
+
def embed_documents(self, texts):
|
| 37 |
+
total_chunks = len(texts)
|
| 38 |
+
embeddings_list = []
|
| 39 |
+
batch_size = 1000
|
| 40 |
+
|
| 41 |
+
print(f"开始生成嵌入(共 {total_chunks} 个分片,每批 {batch_size} 个分片)")
|
| 42 |
+
start_time = time.time()
|
| 43 |
+
with torch.no_grad():
|
| 44 |
+
for i in tqdm(range(0, total_chunks, batch_size), desc="生成嵌入进度"):
|
| 45 |
+
batch_start = i
|
| 46 |
+
batch_end = min(i + batch_size, total_chunks)
|
| 47 |
+
batch_texts = [text.page_content for text in texts[batch_start:batch_end]]
|
| 48 |
+
|
| 49 |
+
batch_start_time = time.time()
|
| 50 |
+
batch_emb = self.model.encode(
|
| 51 |
+
batch_texts,
|
| 52 |
+
normalize_embeddings=True,
|
| 53 |
+
batch_size=self.batch_size,
|
| 54 |
+
show_progress_bar=True
|
| 55 |
+
)
|
| 56 |
+
batch_time = time.time() - batch_start_time
|
| 57 |
+
|
| 58 |
+
if isinstance(batch_emb, torch.Tensor):
|
| 59 |
+
embeddings_list.append(batch_emb.cpu().numpy())
|
| 60 |
+
else:
|
| 61 |
+
embeddings_list.append(batch_emb)
|
| 62 |
+
print(f"完成批次 {i//batch_size + 1}/{total_chunks//batch_size + 1},处理了 {batch_end - batch_start} 个分片,耗时 {batch_time:.2f} 秒")
|
| 63 |
+
|
| 64 |
+
embeddings_array = np.vstack(embeddings_list)
|
| 65 |
+
total_time = time.time() - start_time
|
| 66 |
+
print(f"嵌入生成完成,总耗时 {total_time:.2f} 秒,平均每 1000 个分片耗时 {total_time/total_chunks*1000:.2f} 秒")
|
| 67 |
+
|
| 68 |
+
np.save("embeddings.npy", embeddings_array)
|
| 69 |
+
return embeddings_array
|
| 70 |
+
|
| 71 |
+
def embed_query(self, text):
|
| 72 |
+
if text in self.query_cache:
|
| 73 |
+
return self.query_cache[text]
|
| 74 |
+
with torch.no_grad():
|
| 75 |
+
emb = self.model.encode([text], normalize_embeddings=True, batch_size=1, show_progress_bar=False)[0]
|
| 76 |
+
self.query_cache[text] = emb
|
| 77 |
+
return emb
|
| 78 |
+
|
| 79 |
+
# 预计算分词结果
|
| 80 |
+
def preprocess_corpus(documents):
|
| 81 |
+
if not os.path.exists("tokenized_corpus.pkl"):
|
| 82 |
+
tokenized_corpus = [list(jieba.cut_for_search(doc.page_content)) for doc in documents] # 使用 cut_for_search 提高精度
|
| 83 |
+
with open("tokenized_corpus.pkl", "wb") as f:
|
| 84 |
+
pickle.dump(tokenized_corpus, f)
|
| 85 |
+
print(f"预计算分词结果,保存到 tokenized_corpus.pkl,共 {len(tokenized_corpus)} 个分片")
|
| 86 |
+
else:
|
| 87 |
+
with open("tokenized_corpus.pkl", "rb") as f:
|
| 88 |
+
tokenized_corpus = pickle.load(f)
|
| 89 |
+
print(f"加载已有分词结果,共 {len(tokenized_corpus)} 个分片")
|
| 90 |
+
return tokenized_corpus
|
| 91 |
+
|
| 92 |
+
# 按权重混合检索函数(优化得分和多样性)
|
| 93 |
+
def hybrid_retrieval(query, vector_store, documents, tokenized_corpus, top_n=15, bm25_weight=0.2, semantic_weight=0.8):
|
| 94 |
+
try:
|
| 95 |
+
if not documents or not query:
|
| 96 |
+
raise ValueError("查询或文档列表为空")
|
| 97 |
+
|
| 98 |
+
# 创建文档到 ID 的映射
|
| 99 |
+
doc_to_id = {id(doc): str(i) for i, doc in enumerate(documents)}
|
| 100 |
+
id_to_doc = {str(i): doc for i, doc in enumerate(documents)}
|
| 101 |
+
|
| 102 |
+
# 验证索引与文档一致性
|
| 103 |
+
index_ids = set(vector_store.index_to_docstore_id.values())
|
| 104 |
+
doc_ids = set(str(i) for i in range(len(documents)))
|
| 105 |
+
if index_ids != doc_ids:
|
| 106 |
+
print("警告:索引与文档 ID 不匹配!index_ids:", index_ids, "doc_ids:", doc_ids)
|
| 107 |
+
|
| 108 |
+
# 语义搜索(FAISS)
|
| 109 |
+
vector_store.index.hnsw.efSearch = 300
|
| 110 |
+
query_embedding = vector_store.embedding_function.embed_query(query)
|
| 111 |
+
D, I = vector_store.index.search(np.array([query_embedding]), min(top_n * 2, len(documents)))
|
| 112 |
+
print(f"FAISS 搜索结果 - 距离 (D): {D[0][:5]}... (前5个)")
|
| 113 |
+
print(f"FAISS 搜索结果 - 索引 (I): {I[0][:5]}... (前5个)")
|
| 114 |
+
semantic_results = []
|
| 115 |
+
if D.size > 0:
|
| 116 |
+
max_dist = np.max(D) if np.max(D) > 0 else 1.0
|
| 117 |
+
for idx, dist in zip(I[0], D[0]):
|
| 118 |
+
if idx == -1:
|
| 119 |
+
continue
|
| 120 |
+
doc_id = vector_store.index_to_docstore_id.get(idx)
|
| 121 |
+
if doc_id is None:
|
| 122 |
+
continue
|
| 123 |
+
doc = vector_store.docstore.search(doc_id)
|
| 124 |
+
if doc:
|
| 125 |
+
# 归一化距离为相似度(0到1,1为最相似),设置默认值
|
| 126 |
+
similarity = 1.0 - (dist / max_dist if max_dist > 0 else 0.5)
|
| 127 |
+
semantic_results.append((doc, similarity))
|
| 128 |
+
else:
|
| 129 |
+
print("警告:FAISS 距离数组为空,可能索引异常")
|
| 130 |
+
|
| 131 |
+
# 使用 doc_id 存储语义得分
|
| 132 |
+
semantic_scores = {}
|
| 133 |
+
for doc, score in semantic_results:
|
| 134 |
+
doc_id = doc_to_id.get(id(doc))
|
| 135 |
+
if doc_id is not None:
|
| 136 |
+
semantic_scores[doc_id] = score
|
| 137 |
+
print(f"语义得分 (semantic_scores): {dict(list(semantic_scores.items())[:5])}... (前5个)")
|
| 138 |
+
|
| 139 |
+
# 关键字搜索(BM25,使用预计算分词,调整参数)
|
| 140 |
+
tokenized_query = list(jieba.cut_for_search(query))
|
| 141 |
+
bm25 = BM25Okapi(tokenized_corpus, k1=1.5, b=0.75) # 调整 BM25 参数
|
| 142 |
+
bm25_scores = bm25.get_scores(tokenized_query)
|
| 143 |
+
print(f"BM25 得分 (bm25_scores): {bm25_scores[:5]}... (前5个)")
|
| 144 |
+
|
| 145 |
+
# 归一化 BM25 得分
|
| 146 |
+
max_bm25 = max(bm25_scores) if bm25_scores.size > 0 and max(bm25_scores) > 0 else 1.0
|
| 147 |
+
normalized_bm25_scores = bm25_scores / max_bm25 if max_bm25 > 0 else bm25_scores
|
| 148 |
+
print(f"归一化 BM25 得分 (normalized_bm25_scores): {normalized_bm25_scores[:5]}... (前5个)")
|
| 149 |
+
|
| 150 |
+
# 合并得分,仅对语义搜索结果进行 BM25 增强
|
| 151 |
+
combined_scores = {}
|
| 152 |
+
for i, (doc, _) in enumerate(semantic_results[:top_n * 2]): # 取前 top_n * 2 个语义结果
|
| 153 |
+
doc_id = doc_to_id.get(id(doc))
|
| 154 |
+
if doc_id is not None:
|
| 155 |
+
semantic_score = semantic_scores.get(doc_id, 0.0)
|
| 156 |
+
bm25_score = normalized_bm25_scores[int(doc_id)] if int(doc_id) < len(normalized_bm25_scores) else 0.0
|
| 157 |
+
combined_score = (bm25_weight * bm25_score) + (semantic_weight * semantic_score)
|
| 158 |
+
combined_scores[doc_id] = combined_score
|
| 159 |
+
|
| 160 |
+
# 填充剩余结果(若语义结果不足)
|
| 161 |
+
if len(combined_scores) < top_n:
|
| 162 |
+
for i in range(len(documents)):
|
| 163 |
+
doc_id = str(i)
|
| 164 |
+
if doc_id not in combined_scores:
|
| 165 |
+
semantic_score = semantic_scores.get(doc_id, 0.0)
|
| 166 |
+
bm25_score = normalized_bm25_scores[i] if i < len(normalized_bm25_scores) else 0.0
|
| 167 |
+
combined_score = (bm25_weight * bm25_score) + (semantic_weight * semantic_score)
|
| 168 |
+
combined_scores[doc_id] = combined_score
|
| 169 |
+
if len(combined_scores) >= top_n:
|
| 170 |
+
break
|
| 171 |
+
|
| 172 |
+
# 按组合得分排序
|
| 173 |
+
ranked_ids = sorted(combined_scores.items(), key=lambda x: x[1], reverse=True)[:top_n]
|
| 174 |
+
ranked_docs = [(id_to_doc[doc_id], score) for doc_id, score in ranked_ids]
|
| 175 |
+
|
| 176 |
+
print(f"Query: {query[:100]}... (长度: {len(query)})")
|
| 177 |
+
print(f"混合检索结果 (数量: {len(ranked_docs)}):")
|
| 178 |
+
for i, (doc, score) in enumerate(ranked_docs):
|
| 179 |
+
print(f" Doc {i}: {doc.page_content[:100]}... (来源: {doc.metadata.get('book', '未知来源')}, 得分: {score:.4f})")
|
| 180 |
+
|
| 181 |
+
return ranked_docs
|
| 182 |
+
|
| 183 |
+
except Exception as e:
|
| 184 |
+
error_msg = str(e)
|
| 185 |
+
print(f"错误详情: {error_msg}")
|
| 186 |
+
raise Exception(f"混合检索失败: {error_msg}")
|
| 187 |
+
|
| 188 |
+
# 构建 HNSW 索引
|
| 189 |
+
def build_hnsw_index(knowledge_base_path, index_path):
|
| 190 |
+
print("开始加载文档...")
|
| 191 |
+
start_time = time.time()
|
| 192 |
+
loader = DirectoryLoader(knowledge_base_path, glob="*.txt", loader_cls=lambda path: TextLoader(path, encoding="utf-8"), use_multithreading=False)
|
| 193 |
+
documents = loader.load()
|
| 194 |
+
load_time = time.time() - start_time
|
| 195 |
+
print(f"加载完成,共 {len(documents)} 个文档,耗时 {load_time:.2f} 秒")
|
| 196 |
+
|
| 197 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
|
| 198 |
+
if not os.path.exists("chunks.pkl"):
|
| 199 |
+
print("开始分片...")
|
| 200 |
+
start_time = time.time()
|
| 201 |
+
texts = []
|
| 202 |
+
total_chars = 0
|
| 203 |
+
total_bytes = 0
|
| 204 |
+
for i, doc in enumerate(documents):
|
| 205 |
+
doc_chunks = text_splitter.split_documents([doc])
|
| 206 |
+
for chunk in doc_chunks:
|
| 207 |
+
content = chunk.page_content
|
| 208 |
+
file_path = chunk.metadata.get("source", "")
|
| 209 |
+
book_name = os.path.basename(file_path).replace(".txt", "").replace("_", "·")
|
| 210 |
+
texts.append(Document(page_content=content, metadata={"book": book_name or "未知来源"}))
|
| 211 |
+
total_chars += len(content)
|
| 212 |
+
total_bytes += len(content.encode('utf-8'))
|
| 213 |
+
if i < 5:
|
| 214 |
+
print(f"文件 {i} 字符数: {len(doc.page_content)}, 字节数: {len(doc.page_content.encode('utf-8'))}, 来源: {file_path}")
|
| 215 |
+
if (i + 1) % 10 == 0:
|
| 216 |
+
print(f"分片进度: 已处理 {i + 1}/{len(documents)} 个文件,当前分片总数: {len(texts)}")
|
| 217 |
+
with open("chunks.pkl", "wb") as f:
|
| 218 |
+
pickle.dump(texts, f)
|
| 219 |
+
split_time = time.time() - start_time
|
| 220 |
+
print(f"分片完成,共 {len(texts)} 个 chunk,总字符数: {total_chars},总字节数: {total_bytes},耗时 {split_time:.2f} 秒")
|
| 221 |
+
else:
|
| 222 |
+
with open("chunks.pkl", "rb") as f:
|
| 223 |
+
texts = pickle.load(f)
|
| 224 |
+
print(f"加载已有分片,共 {len(texts)} 个 chunk")
|
| 225 |
+
|
| 226 |
+
if not os.path.exists("embeddings.npy"):
|
| 227 |
+
print("开始生成嵌入(使用 BAAI/bge-m3,CPU 模式,分批处理)...")
|
| 228 |
+
embeddings_array = embeddings.embed_documents(texts)
|
| 229 |
+
if os.path.exists("embeddings_temp.npy"):
|
| 230 |
+
os.remove("embeddings_temp.npy")
|
| 231 |
+
print(f"嵌入生成完成,维度: {embeddings_array.shape}")
|
| 232 |
+
else:
|
| 233 |
+
embeddings_array = np.load("embeddings.npy")
|
| 234 |
+
print(f"加载已有嵌入,维度: {embeddings_array.shape}")
|
| 235 |
+
|
| 236 |
+
dimension = embeddings_array.shape[1]
|
| 237 |
+
index = faiss.IndexHNSWFlat(dimension, 16)
|
| 238 |
+
index.hnsw.efConstruction = 100
|
| 239 |
+
print("开始构建 HNSW 索引...")
|
| 240 |
+
|
| 241 |
+
batch_size = 5000
|
| 242 |
+
total_vectors = embeddings_array.shape[0]
|
| 243 |
+
for i in range(0, total_vectors, batch_size):
|
| 244 |
+
batch = embeddings_array[i:i + batch_size]
|
| 245 |
+
index.add(batch)
|
| 246 |
+
print(f"索引构建进度: {min(i + batch_size, total_vectors)} / {total_vectors}")
|
| 247 |
+
|
| 248 |
+
text_embeddings = [(text.page_content, embeddings_array[i]) for i, text in enumerate(texts)]
|
| 249 |
+
vector_store = FAISS.from_embeddings(text_embeddings, embeddings, normalize_L2=True)
|
| 250 |
+
vector_store.index = index
|
| 251 |
+
vector_store.docstore._dict.clear()
|
| 252 |
+
vector_store.index_to_docstore_id.clear()
|
| 253 |
+
|
| 254 |
+
for i, text in enumerate(texts):
|
| 255 |
+
doc_id = str(i)
|
| 256 |
+
vector_store.docstore._dict[doc_id] = text
|
| 257 |
+
vector_store.index_to_docstore_id[i] = doc_id
|
| 258 |
+
|
| 259 |
+
print("开始保存索引...")
|
| 260 |
+
vector_store.save_local(index_path)
|
| 261 |
+
print(f"HNSW 索引已生成并保存到 '{index_path}'")
|
| 262 |
+
return vector_store, texts # 返回 vector_store 和分片文本
|
| 263 |
+
|
| 264 |
+
# 初始化嵌入模型
|
| 265 |
+
embeddings = SentenceTransformerEmbeddings(model_name="BAAI/bge-m3")
|
| 266 |
+
print("已初始化 BAAI/bge-m3 嵌入模型,用于知识库检索(CPU 模式)")
|
| 267 |
+
|
| 268 |
+
# 加载或生成索引
|
| 269 |
+
index_path = "faiss_index_hnsw_new"
|
| 270 |
+
knowledge_base_path = "knowledge_base"
|
| 271 |
+
|
| 272 |
+
if not os.path.exists(index_path):
|
| 273 |
+
if os.path.exists(knowledge_base_path):
|
| 274 |
+
print("检测到 knowledge_base,正在生成 HNSW 索引...")
|
| 275 |
+
vector_store, all_documents = build_hnsw_index(knowledge_base_path, index_path)
|
| 276 |
+
else:
|
| 277 |
+
raise FileNotFoundError("未找到 'knowledge_base',请提供知识库数据")
|
| 278 |
+
else:
|
| 279 |
+
vector_store = FAISS.load_local(index_path, embeddings=embeddings, allow_dangerous_deserialization=True)
|
| 280 |
+
vector_store.index.hnsw.efSearch = 300
|
| 281 |
+
print("已加载 HNSW 索引 'faiss_index_hnsw_new',efSearch 设置为 300")
|
| 282 |
+
with open("chunks.pkl", "rb") as f:
|
| 283 |
+
all_documents = pickle.load(f)
|
| 284 |
+
# 验证 all_documents 内容
|
| 285 |
+
book_counts = {}
|
| 286 |
+
for doc in all_documents:
|
| 287 |
+
book = doc.metadata.get("book", "未知来源")
|
| 288 |
+
book_counts[book] = book_counts.get(book, 0) + 1
|
| 289 |
+
print(f"all_documents 书籍分布: {book_counts}")
|
| 290 |
+
|
| 291 |
+
# 预计算分词结果
|
| 292 |
+
tokenized_corpus = preprocess_corpus(all_documents)
|
| 293 |
+
|
| 294 |
+
# 初始化 ChatOpenAI
|
| 295 |
+
llm = ChatOpenAI(
|
| 296 |
+
model="deepseek/deepseek-r1:free",
|
| 297 |
+
api_key=os.environ["OPENROUTER_API_KEY"],
|
| 298 |
+
base_url="https://openrouter.ai/api/v1",
|
| 299 |
+
timeout=60,
|
| 300 |
+
temperature=0.3,
|
| 301 |
+
max_tokens=130000,
|
| 302 |
+
streaming=True
|
| 303 |
+
)
|
| 304 |
+
|
| 305 |
+
# 定义提示词模板
|
| 306 |
+
prompt_template = PromptTemplate(
|
| 307 |
+
input_variables=["context", "question", "chat_history"],
|
| 308 |
+
template="""
|
| 309 |
+
你是一个研究李敖的专家,根据用户提出的问题{question}、最近10轮对话历史{chat_history}以及从李敖相关书籍和评论中检索的至少10篇文本内容{context}回答问题。
|
| 310 |
+
在回答时,请注意以下几点:
|
| 311 |
+
- 结合李敖的写作风格和思想,筛选出与问题和对话历史最相关的检��内容,避免无关信息。
|
| 312 |
+
- 必须在回答中引用至少10篇不同的文本内容,引用格式为[引用: 文本序号],例如[引用: 1][引用: 2],并确保每篇文本在回答中都有明确使用。
|
| 313 |
+
- 在回答的末尾,必须以“引用文献”标题列出所有引用的文本序号及其内容摘要(每篇不超过50字)以及具体的书目信息(例如书名和章节),格式为:
|
| 314 |
+
- 引用文献:
|
| 315 |
+
1. [文本 1] 摘要... 出自:书名,第X页/章节。
|
| 316 |
+
2. [文本 2] 摘要... 出自:书名,第X页/章节。
|
| 317 |
+
(依此类推,至少10篇)
|
| 318 |
+
- 如果问题涉及李敖对某人或某事的评价,优先引用李敖的直接言论或文字,并说明出处。
|
| 319 |
+
- 回答应结构化、分段落,确保逻辑清晰,语言生动,类似李敖的犀利风格。
|
| 320 |
+
- 如果检索内容和历史不足以直接回答问题,可根据李敖的性格和观点推测其可能的看法,但需说明这是推测。
|
| 321 |
+
- 只能基于提供的知识库内容{context}和对话历史{chat_history}回答,不得引入外部信息。
|
| 322 |
+
- 对于列举类问题,控制在10个要点以内,并优先提供最相关项。
|
| 323 |
+
- 如果回答较长,结构化分段总结,分点作答控制在8个点以内。
|
| 324 |
+
- 根据对话历史调整回答,避免重复或矛盾。
|
| 325 |
+
- 并非搜索结果的所有内容都与用户的问题密切相关,你需要结合问题,对搜索结果进行甄别、筛选。
|
| 326 |
+
- 对于列举类的问题(如列举所有航班信息),尽量将答案控制在10个要点以内,并告诉用户可以查看搜索来源、获得完整信息。优先提供信息完整、最相关的列举项;如非必要,不要主动告诉用户搜索结果未提供的内容。
|
| 327 |
+
- 对于创作类的问题(如写论文),请务必在正文的段落中引用对应的参考编号,例如[引用:3][引用:5],不能只在文章末尾引用。你需要解读并概括用户的题目要求,选择合适的格式,充分利用搜索结果并抽取重要信息,生成符合用户要求、极具思想深度、富有创造力与专业性的答案。你的创作篇幅需要尽可能延长,对于每一个要点的论述要推测用户的意图,给出尽可能多角度的回答要点,且务必信息量大、论述详尽。
|
| 328 |
+
- 如果回答很长,请尽量结构化、分段落总结。如果需要分点作答,尽量控制在8个点以内,并合并相关的内容。
|
| 329 |
+
- 对于客观类的问答,如果问题的答案非常简短,可以适当补充一到两句相关信息,以丰富内容。
|
| 330 |
+
- 你需要根据用户要求和回答内容选择合适、美观的回答格式,确保可读性强。
|
| 331 |
+
- 你的回答应该综合多个相关知识库内容来回答,不能重复引用一个知识库内容。
|
| 332 |
+
- 除非用户要求,否则你回答的语言需要和用户提问的语言保持一致。
|
| 333 |
+
"""
|
| 334 |
+
)
|
| 335 |
+
|
| 336 |
+
# 对话历史管理类
|
| 337 |
+
class ConversationHistory:
|
| 338 |
+
def __init__(self, max_length=10):
|
| 339 |
+
self.history = deque(maxlen=max_length)
|
| 340 |
+
|
| 341 |
+
def add_turn(self, question, answer):
|
| 342 |
+
self.history.append((question, answer))
|
| 343 |
+
|
| 344 |
+
def get_history(self):
|
| 345 |
+
return [(turn[0], turn[1]) for turn in self.history]
|
| 346 |
+
|
| 347 |
+
def clear(self):
|
| 348 |
+
self.history.clear()
|
| 349 |
+
|
| 350 |
+
# 用户会话状态类
|
| 351 |
+
class UserSession:
|
| 352 |
+
def __init__(self):
|
| 353 |
+
self.conversation = ConversationHistory()
|
| 354 |
+
self.output_queue = queue.Queue()
|
| 355 |
+
self.stop_flag = threading.Event()
|
| 356 |
+
|
| 357 |
+
# 生成回答的线程函数
|
| 358 |
+
def generate_answer_thread(question, session):
|
| 359 |
+
stop_flag = session.stop_flag
|
| 360 |
+
output_queue = session.output_queue
|
| 361 |
+
conversation = session.conversation
|
| 362 |
+
|
| 363 |
+
stop_flag.clear()
|
| 364 |
+
try:
|
| 365 |
+
history_list = conversation.get_history()
|
| 366 |
+
history_text = "\n".join([f"问: {q}\n答: {a}" for q, a in history_list]) if history_list else ""
|
| 367 |
+
query_with_context = f"{history_text}\n当前问题: {question}" if history_text else question
|
| 368 |
+
|
| 369 |
+
# 1. 使用 BAAI/bge-m3 生成查询嵌入
|
| 370 |
+
start_time = time.time()
|
| 371 |
+
query_embedding = embeddings.embed_query(query_with_context)
|
| 372 |
+
embed_time = time.time() - start_time
|
| 373 |
+
output_queue.put(f"嵌入耗时 (BAAI/bge-m3): {embed_time:.2f} 秒\n")
|
| 374 |
+
|
| 375 |
+
if stop_flag.is_set():
|
| 376 |
+
output_queue.put("生成已停止")
|
| 377 |
+
return
|
| 378 |
+
|
| 379 |
+
# 2. 使用混合检索(BM25 + FAISS)
|
| 380 |
+
start_time = time.time()
|
| 381 |
+
retrieved_docs_with_scores = hybrid_retrieval(
|
| 382 |
+
query_with_context,
|
| 383 |
+
vector_store,
|
| 384 |
+
all_documents,
|
| 385 |
+
tokenized_corpus,
|
| 386 |
+
top_n=15,
|
| 387 |
+
bm25_weight=0.2,
|
| 388 |
+
semantic_weight=0.8
|
| 389 |
+
)
|
| 390 |
+
retrieval_time = time.time() - start_time
|
| 391 |
+
output_queue.put(f"混合检索耗时: {retrieval_time:.2f} 秒\n")
|
| 392 |
+
|
| 393 |
+
if stop_flag.is_set():
|
| 394 |
+
output_queue.put("生成已停止")
|
| 395 |
+
return
|
| 396 |
+
|
| 397 |
+
# 调整 final_docs 数量,取前 10 篇
|
| 398 |
+
final_docs = [doc for doc, _ in retrieved_docs_with_scores][:10]
|
| 399 |
+
if len(final_docs) < 10:
|
| 400 |
+
output_queue.put(f"警告:仅检索到 {len(final_docs)} 篇文本,可能无法满足引用 10 篇的要求")
|
| 401 |
+
|
| 402 |
+
# 构造 context,包含文本内容和书目信息
|
| 403 |
+
context = "\n\n".join([f"[文本 {i+1}] {doc.page_content} (出处: {doc.metadata.get('book', '未知来源')})" for i, doc in enumerate(final_docs)])
|
| 404 |
+
chat_history = [HumanMessage(content=q) if i % 2 == 0 else AIMessage(content=a)
|
| 405 |
+
for i, (q, a) in enumerate(history_list)]
|
| 406 |
+
prompt = prompt_template.format(context=context, question=question, chat_history=history_text)
|
| 407 |
+
|
| 408 |
+
# 3. 使用 LLM 生成回答
|
| 409 |
+
answer = ""
|
| 410 |
+
start_time = time.time()
|
| 411 |
+
for chunk in llm.stream([HumanMessage(content=prompt)]):
|
| 412 |
+
if stop_flag.is_set():
|
| 413 |
+
output_queue.put(answer + "\n\n(生成已停止)")
|
| 414 |
+
return
|
| 415 |
+
answer += chunk.content
|
| 416 |
+
output_queue.put(answer)
|
| 417 |
+
llm_time = time.time() - start_time
|
| 418 |
+
output_queue.put(f"\nLLM 生成耗时: {llm_time:.2f} 秒")
|
| 419 |
+
|
| 420 |
+
conversation.add_turn(question, answer)
|
| 421 |
+
output_queue.put(answer)
|
| 422 |
+
|
| 423 |
+
except Exception as e:
|
| 424 |
+
output_queue.put(f"Error: {str(e)}")
|
| 425 |
+
|
| 426 |
+
# Gradio 接口函数
|
| 427 |
+
def answer_question(question, session_state):
|
| 428 |
+
if session_state is None:
|
| 429 |
+
session_state = UserSession()
|
| 430 |
+
|
| 431 |
+
thread = threading.Thread(target=generate_answer_thread, args=(question, session_state))
|
| 432 |
+
thread.start()
|
| 433 |
+
|
| 434 |
+
while thread.is_alive() or not session_state.output_queue.empty():
|
| 435 |
+
try:
|
| 436 |
+
output = session_state.output_queue.get(timeout=0.1)
|
| 437 |
+
yield output, session_state
|
| 438 |
+
except queue.Empty:
|
| 439 |
+
continue
|
| 440 |
+
|
| 441 |
+
while not session_state.output_queue.empty():
|
| 442 |
+
yield session_state.output_queue.get(), session_state
|
| 443 |
+
|
| 444 |
+
def stop_generation(session_state):
|
| 445 |
+
if session_state is not None:
|
| 446 |
+
session_state.stop_flag.set()
|
| 447 |
+
return "生成已停止,正在中止..."
|
| 448 |
+
|
| 449 |
+
def clear_conversation():
|
| 450 |
+
return "对话历史已清空,请开始新的对话。", UserSession()
|
| 451 |
+
|
| 452 |
+
# 创建 Gradio 界面
|
| 453 |
+
with gr.Blocks(title="AI李敖助手") as interface:
|
| 454 |
+
gr.Markdown("### AI李敖助手")
|
| 455 |
+
gr.Markdown("基于李敖163本相关书籍构建的知识库,支持上下文关联,记住最近10轮对话,输入问题以获取李敖风格的回答。")
|
| 456 |
+
|
| 457 |
+
session_state = gr.State(value=None)
|
| 458 |
+
|
| 459 |
+
with gr.Row():
|
| 460 |
+
with gr.Column(scale=3):
|
| 461 |
+
question_input = gr.Textbox(label="请输入您的问题", placeholder="输入您的问题...")
|
| 462 |
+
submit_button = gr.Button("提交")
|
| 463 |
+
with gr.Column(scale=1):
|
| 464 |
+
clear_button = gr.Button("新建对话")
|
| 465 |
+
stop_button = gr.Button("停止生成")
|
| 466 |
+
|
| 467 |
+
output_text = gr.Textbox(label="回答", interactive=False)
|
| 468 |
+
|
| 469 |
+
submit_button.click(fn=answer_question, inputs=[question_input, session_state], outputs=[output_text, session_state])
|
| 470 |
+
clear_button.click(fn=clear_conversation, inputs=None, outputs=[output_text, session_state])
|
| 471 |
+
stop_button.click(fn=stop_generation, inputs=[session_state], outputs=output_text)
|
| 472 |
+
|
| 473 |
+
# 启动应用
|
| 474 |
+
if __name__ == "__main__":
|
| 475 |
+
interface.launch(share=True)
|