PebllaRyan commited on
Commit
d97bbdd
·
verified ·
1 Parent(s): 656f58a

Upload 2 files

Browse files
Files changed (2) hide show
  1. app_gradio.py +294 -0
  2. requirements.txt +17 -0
app_gradio.py ADDED
@@ -0,0 +1,294 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ########################################
2
+ # 0) 安装/导入依赖
3
+ ########################################
4
+ # 请先 pip3 install openai gradio langchain text2vec
5
+
6
+ from openai import OpenAI
7
+ import gradio as gr
8
+ import csv
9
+ from datetime import datetime
10
+ import torch
11
+ from langchain.vectorstores import FAISS
12
+ from langchain_huggingface import HuggingFaceEmbeddings
13
+
14
+ ########################################
15
+ # 1) 初始化 DeepSeek 客户端 & 向量检索 Embeddings
16
+ ########################################
17
+
18
+ # 使用 DeepSeek 提供的 OpenAI 兼容API
19
+ # 注意这里要填上你的 API Key
20
+ client = OpenAI(api_key="sk-feb7676c40b2486581c12e7ab60d7966", base_url="https://api.deepseek.com")
21
+
22
+ device = "cuda" if torch.cuda.is_available() else "cpu"
23
+
24
+ embeddings = HuggingFaceEmbeddings(
25
+ model_name="shibing624/text2vec-base-chinese",
26
+ model_kwargs={"device": device}
27
+ )
28
+
29
+ ########################################
30
+ # 2) 向量检索逻辑
31
+ ########################################
32
+
33
+ def load_vectorstore(index_path: str, embed_obj) -> FAISS:
34
+ """加载 FAISS 索引"""
35
+ return FAISS.load_local(
36
+ index_path,
37
+ embed_obj,
38
+ allow_dangerous_deserialization=True
39
+ )
40
+
41
+ def build_prompt_for_chatgpt(query, cs_docs, hc_docs, ic_docs):
42
+ """
43
+ 根据检索到的三类文档(CS/HC/IC),构造对大模型的提示 Prompt。
44
+ """
45
+ # 组装 Customer Success
46
+ cs_context = []
47
+ for i, doc in enumerate(cs_docs, start=1):
48
+ cs_context.append(f"[CS Doc {i}]\n{doc.page_content}\n")
49
+
50
+ # 组装 Help Center
51
+ hc_context = []
52
+ for i, doc in enumerate(hc_docs, start=1):
53
+ link = doc.metadata.get("链接", "无链接")
54
+ hc_context.append(f"[HC Doc {i}]\n链接: {link}\n{doc.page_content}\n")
55
+
56
+ # 组装 IC
57
+ ic_context = []
58
+ for i, doc in enumerate(ic_docs, start=1):
59
+ link = doc.metadata.get("链接", "无链接")
60
+ ic_context.append(f"[IC Doc {i}]\n链接: {link}\n{doc.page_content}\n")
61
+
62
+ prompt = f"""\
63
+ 请根据以下文档,回答用户的问题。如果无法从文档中找到答案,请说明你无法回答。
64
+
65
+ 用户问题:{query}
66
+
67
+ ======================
68
+ 【Customer Success - Top {len(cs_docs)}】
69
+ {''.join(cs_context)}
70
+
71
+ 【Help Center - Top {len(hc_docs)}】
72
+ {''.join(hc_context)}
73
+
74
+ 【IC - Top {len(ic_docs)}】
75
+ {''.join(ic_context)}
76
+ ======================
77
+
78
+ 请根据helpcenter链接查询help center内容给出准确答案
79
+
80
+ 请给出简洁、准确、机构清晰且包含必要细节的回答,并尽量引用help center链接,但不需要表明来自哪个文档:
81
+ """
82
+ return prompt
83
+
84
+ def combined_search(query, cs_index_path, hc_index_path, ic_index_path,
85
+ cs_k=3, hc_k=2, ic_k=3):
86
+ """
87
+ - 分别加载 CS、HC、IC 的向量索引
88
+ - 分别检索 query
89
+ - 将检索到的文档传递给 build_prompt_for_chatgpt,返回 Prompt
90
+ """
91
+ cs_vectorstore = load_vectorstore(cs_index_path, embeddings)
92
+ hc_vectorstore = load_vectorstore(hc_index_path, embeddings)
93
+ ic_vectorstore = load_vectorstore(ic_index_path, embeddings)
94
+
95
+ cs_docs = cs_vectorstore.similarity_search(query, k=cs_k)
96
+ hc_docs = hc_vectorstore.similarity_search(query, k=hc_k)
97
+ ic_docs = ic_vectorstore.similarity_search(query, k=ic_k)
98
+
99
+ prompt = build_prompt_for_chatgpt(query, cs_docs, hc_docs, ic_docs)
100
+ return cs_docs, hc_docs, ic_docs, prompt
101
+
102
+ ########################################
103
+ # 3) 调用 DeepSeek "deepseek-reasoner" 生成答案
104
+ ########################################
105
+
106
+ def generate_answer_with_deepseek(prompt_text):
107
+ """
108
+ 用 DeepSeek 的 “deepseek-reasoner” 模型生成答案。
109
+ 你给出的示例是通过 `client.chat.completions.create()`.
110
+ """
111
+ # 参考你给的代码,构造 messages
112
+ messages = [
113
+ {"role": "system", "content": "You are a helpful assistant"},
114
+ {"role": "user", "content": prompt_text},
115
+ ]
116
+
117
+ response = client.chat.completions.create(
118
+ model="deepseek-reasoner",
119
+ messages=messages,
120
+ stream=False
121
+ )
122
+
123
+ # 取回答文本
124
+ return response.choices[0].message.content
125
+
126
+ ########################################
127
+ # 4) Gradio 接口函数 - 检索并直接调 DeepSeek
128
+ ########################################
129
+
130
+ def run_search_and_answer(user_query, store_name):
131
+ """
132
+ 1) 检索出文档(cs_docs / hc_docs / ic_docs)
133
+ 2) 生成 Prompt
134
+ 3) 调用 DeepSeek 模型生成答案
135
+ 4) 返回给 Gradio 界面
136
+ """
137
+ cs_index_path = "CS_faiss_index"
138
+ hc_index_path = "HC_faiss_index"
139
+ ic_index_path = "IC_faiss_index"
140
+
141
+ # 做检索 + 构造 prompt
142
+ cs_docs, hc_docs, ic_docs, prompt_text = combined_search(
143
+ query=user_query,
144
+ cs_index_path=cs_index_path,
145
+ hc_index_path=hc_index_path,
146
+ ic_index_path=ic_index_path,
147
+ cs_k=5,
148
+ hc_k=2,
149
+ ic_k=5
150
+ )
151
+
152
+ # 生成 DeepSeek 回答
153
+ deepseek_answer = generate_answer_with_deepseek(prompt_text)
154
+
155
+ # 拼出检索到的简要结果,返回给前端查看
156
+ cs_result = "\n".join([
157
+ f"{doc.page_content[:60]}... (Link: {doc.metadata.get('link', '无链接')})"
158
+ for i, doc in enumerate(cs_docs, start=1)
159
+ ])
160
+
161
+ hc_result_list = []
162
+ hc_links = []
163
+ for i, doc in enumerate(hc_docs, start=1):
164
+ snippet = doc.page_content[:60]
165
+ link = doc.metadata.get('链接', '无链接')
166
+ hc_result_list.append(f"{snippet}... (Link: {link})")
167
+ hc_links.append(link)
168
+ hc_result = "\n".join(hc_result_list)
169
+
170
+ ic_result = "\n".join([
171
+ f"{doc.page_content[:60]}... (Link: {doc.metadata.get('链接', '无链接')})"
172
+ for i, doc in enumerate(ic_docs, start=1)
173
+ ])
174
+
175
+ doc_summary = (
176
+ "=== Customer Success Docs ===\n"
177
+ f"{cs_result}\n\n"
178
+ "=== Help Center Docs ===\n"
179
+ f"{hc_result}\n\n"
180
+ "=== IC Docs ===\n"
181
+ f"{ic_result}\n"
182
+ )
183
+
184
+ # 合并多个 Help Center 链接为一个字符串,用分号隔开
185
+ links_str = "; ".join(hc_links)
186
+
187
+ # 把检索结果、最终 Prompt、DeepSeek答案、HC链接 一并返回
188
+ return doc_summary, prompt_text, deepseek_answer, links_str
189
+
190
+ ########################################
191
+ # 5) 记录反馈
192
+ ########################################
193
+ def record_feedback(user_query, final_answer, feedback_choice, improved_answer, store_name, links_str):
194
+ """
195
+ 将用户这次交互的信息存储到 CSV:
196
+ - 如果用户选择“好”,就存原来的 final_answer
197
+ - 如果用户选择“不好”,就存 improved_answer
198
+ - 还要记录:问题产生时间(精确到小时) + 店铺名称 + Help Center链接
199
+ """
200
+ if not user_query.strip():
201
+ return "没有检测到问题内容,无法记录。"
202
+
203
+ # 判断用户评价
204
+ if feedback_choice == "好":
205
+ used_answer = final_answer
206
+ else:
207
+ # 如果用户选择“不好”,但又没给改进后的答案
208
+ if not improved_answer.strip():
209
+ return "你选择了“不好”,请填写改进后的答案。"
210
+ used_answer = improved_answer
211
+
212
+ # 生成时间戳(精确到小时)
213
+ current_time = datetime.now().strftime("%Y-%m-%d %H:00:00")
214
+
215
+ # 写入 CSV
216
+ with open("feedback.csv", "a", encoding="utf-8", newline="") as f:
217
+ writer = csv.writer(f)
218
+ writer.writerow([
219
+ current_time, # 问题产生时间(到小时)
220
+ store_name, # 店铺名称
221
+ user_query, # 用户问题
222
+ feedback_choice, # 好/不好
223
+ used_answer, # 最终答案(可能是原回答,也可能是改进后答案)
224
+ links_str # help center链接(用分号隔开)
225
+ ])
226
+
227
+ return "已记录到 feedback.csv,谢谢你的反馈!"
228
+
229
+ ########################################
230
+ # 6) 搭建 Gradio UI
231
+ ########################################
232
+ with gr.Blocks() as demo:
233
+ gr.Markdown("## Peblla 智能知识库助手 - 整合DeepSeek示例")
234
+
235
+ # 店铺名称
236
+ store_name_box = gr.Textbox(label="店铺名称", placeholder="可选:你在哪个店铺遇到了问题?")
237
+
238
+ # 用户输入问题
239
+ user_query_box = gr.Textbox(label="问题", lines=2)
240
+
241
+ # 点击按钮进行检索 + DeepSeek回答
242
+ btn_search = gr.Button("提交问题")
243
+
244
+ # 显示检索结果、Prompt、DeepSeek的回答
245
+ doc_result_box = gr.Textbox(label="检索到的文档(简要)", interactive=False, lines=6)
246
+ prompt_box = gr.Textbox(label="生成的 Prompt", interactive=False, lines=6, visible=False)
247
+ deepseek_answer_box = gr.Textbox(label="DeepSeek 回答", interactive=False, lines=6)
248
+
249
+ # 隐藏组件,用于存储检索到的 HC 链接字符串
250
+ hc_links_box = gr.Textbox(visible=False)
251
+
252
+ gr.Markdown("---")
253
+
254
+ # 用户对 DeepSeek 的回答做出评价
255
+ feedback_choice = gr.Radio(
256
+ choices=["好", "不好"],
257
+ label="回答质量如何?",
258
+ value=None
259
+ )
260
+
261
+ improved_answer_box = gr.Textbox(
262
+ label="如果选择“不好”,请在这里输入改进后的答案",
263
+ lines=5
264
+ )
265
+
266
+ btn_feedback = gr.Button("提交反馈")
267
+ feedback_result = gr.Markdown()
268
+
269
+ # 当“提交问题”按钮被点击时,执行 run_search_and_answer
270
+ btn_search.click(
271
+ fn=run_search_and_answer,
272
+ inputs=[user_query_box, store_name_box],
273
+ outputs=[doc_result_box, prompt_box, deepseek_answer_box, hc_links_box]
274
+ )
275
+
276
+ # 当“提交反馈”按钮被点击时,执行 record_feedback
277
+ btn_feedback.click(
278
+ fn=record_feedback,
279
+ inputs=[
280
+ user_query_box, # user_query
281
+ deepseek_answer_box, # final_answer (此处是 deepseek 生成的答案)
282
+ feedback_choice, # feedback_choice
283
+ improved_answer_box, # improved_answer
284
+ store_name_box, # store_name
285
+ hc_links_box # links_str
286
+ ],
287
+ outputs=[feedback_result]
288
+ )
289
+
290
+ demo.launch(
291
+ server_name="0.0.0.0",
292
+ server_port=7860,
293
+ share=True
294
+ )
requirements.txt ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 核心依赖
2
+ pandas==1.5.3
3
+ numpy==1.24.3
4
+ torch==2.0.1
5
+
6
+ # LangChain + FAISS
7
+ langchain==0.0.146
8
+ faiss-cpu==1.7.3
9
+
10
+ # 如果你用 faiss-gpu 而非 CPU,请改为 faiss-gpu
11
+ # faiss-gpu==1.7.3
12
+
13
+ # 用于 HuggingFaceEmbeddings 依赖
14
+ transformers==4.28.0
15
+
16
+ # Gradio 做前端可视化
17
+ gradio==3.27.0