aihuashanying commited on
Commit
3f79fdf
·
1 Parent(s): d5b9fa8

Upload 2 files

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