leonsimon23 commited on
Commit
307fd4a
·
verified ·
1 Parent(s): 6e456bb

Create app_bak3.py

Browse files
Files changed (1) hide show
  1. app_bak3.py +284 -0
app_bak3.py ADDED
@@ -0,0 +1,284 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ import json
4
+ import uuid
5
+ import logging
6
+ import os
7
+
8
+ # 配置日志
9
+ logging.basicConfig(level=logging.DEBUG)
10
+ logger = logging.getLogger(__name__)
11
+
12
+ class FastGPTChat:
13
+ """
14
+ def __init__(self, api_key="",
15
+ system_prompt="我是一名AI用药咨询顾问,请向我提问有关用药的问题"):
16
+ self.api_key = api_key
17
+ self.base_url = "https://api.fastgpt.in/api"
18
+ self.system_prompt = system_prompt
19
+ self.headers = {
20
+ "Authorization": f"Bearer {api_key}",
21
+ "Content-Type": "application/json"
22
+ }
23
+ """
24
+
25
+ def __init__(self, system_prompt="我是一名AI用药咨询顾问,请向我提问有关用药的问题"):
26
+ # 从环境变量获取API密钥和基础URL
27
+ self.api_key = os.environ.get('FASTGPT_API_KEY')
28
+ self.base_url = os.environ.get('FASTGPT_BASE_URL', 'https://api.fastgpt.in/api')
29
+ self.system_prompt = system_prompt
30
+ self.headers = {
31
+ "Authorization": f"Bearer {self.api_key}",
32
+ "Content-Type": "application/json"
33
+ }
34
+
35
+
36
+
37
+ def chat(self, message, chat_history):
38
+ if not message.strip():
39
+ return "", chat_history
40
+
41
+ chat_id = str(uuid.uuid4())
42
+
43
+ # 构建消息历史,包含系统提示词
44
+ messages = []
45
+ if self.system_prompt:
46
+ messages.append({
47
+ "role": "system",
48
+ "content": self.system_prompt
49
+ })
50
+
51
+ # 添加聊天历史
52
+ for user_msg, bot_msg in chat_history:
53
+ messages.append({"role": "user", "content": user_msg})
54
+ messages.append({"role": "assistant", "content": bot_msg})
55
+
56
+ # 添加当前用户消息
57
+ messages.append({"role": "user", "content": message})
58
+
59
+ # 准备请求数据
60
+ data = {
61
+ "chatId": chat_id,
62
+ "stream": True,
63
+ "detail": True,
64
+ "model": "gpt-4o",
65
+ "messages": messages
66
+ }
67
+
68
+ try:
69
+ # 发送流式请求
70
+ response = requests.post(
71
+ f"{self.base_url}/v1/chat/completions",
72
+ headers=self.headers,
73
+ json=data,
74
+ stream=True,
75
+ timeout=30
76
+ )
77
+
78
+ if response.status_code != 200:
79
+ error_msg = f"API Error: Status {response.status_code}"
80
+ logger.error(error_msg)
81
+ chat_history.append((message, f"Error: {error_msg}"))
82
+ return "", chat_history
83
+
84
+ # 处理流式响应
85
+ full_response = ""
86
+ for line in response.iter_lines():
87
+ if line:
88
+ try:
89
+ line = line.decode('utf-8')
90
+ if line.startswith('data: '):
91
+ data = json.loads(line[6:])
92
+ if 'choices' in data and len(data['choices']) > 0:
93
+ content = data['choices'][0]['delta'].get('content', '')
94
+ if content:
95
+ full_response += content
96
+ # 更新聊天历史
97
+ if len(chat_history) > 0 and chat_history[-1][0] == message:
98
+ chat_history[-1] = (message, full_response)
99
+ else:
100
+ chat_history.append((message, full_response))
101
+ yield "", chat_history
102
+ except Exception as e:
103
+ logger.error(f"Error processing stream: {str(e)}")
104
+
105
+ return "", chat_history
106
+
107
+ except requests.exceptions.RequestException as e:
108
+ error_msg = f"Request failed: {str(e)}"
109
+ logger.error(error_msg)
110
+ chat_history.append((message, f"Error: {error_msg}"))
111
+ return "", chat_history
112
+
113
+ def create_chat_interface():
114
+ fastgpt_chat = FastGPTChat()
115
+
116
+ with gr.Blocks(
117
+ title="AI用药咨询助手",
118
+ css="""
119
+ .container { max-width: 800px; margin: auto; }
120
+ .chat-header {
121
+ text-align: center;
122
+ padding: 20px;
123
+ background: linear-gradient(135deg, #00b4d8, #0077b6);
124
+ color: white;
125
+ border-radius: 15px 15px 0 0;
126
+ margin-bottom: 20px;
127
+ }
128
+ .chat-container {
129
+ background-color: #ffffff;
130
+ border-radius: 15px;
131
+ padding: 20px;
132
+ box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
133
+ border: 1px solid #e0e0e0;
134
+ }
135
+ .message-box {
136
+ border: 2px solid #e0e0e0;
137
+ border-radius: 10px;
138
+ background-color: white;
139
+ transition: all 0.3s ease;
140
+ }
141
+ .message-box:focus {
142
+ border-color: #00b4d8;
143
+ box-shadow: 0 0 0 2px rgba(0, 180, 216, 0.2);
144
+ }
145
+ .submit-btn {
146
+ background-color: #00b4d8 !important;
147
+ border: none !important;
148
+ color: white !important;
149
+ padding: 10px 20px !important;
150
+ border-radius: 8px !important;
151
+ transition: all 0.3s ease !important;
152
+ font-weight: 600 !important;
153
+ }
154
+ .submit-btn:hover {
155
+ background-color: #0077b6 !important;
156
+ transform: translateY(-2px);
157
+ }
158
+ .clear-btn {
159
+ background-color: #ff4757 !important;
160
+ border: none !important;
161
+ color: white !important;
162
+ padding: 10px 20px !important;
163
+ border-radius: 8px !important;
164
+ transition: all 0.3s ease !important;
165
+ font-weight: 600 !important;
166
+ }
167
+ .clear-btn:hover {
168
+ background-color: #ff6b81 !important;
169
+ transform: translateY(-2px);
170
+ }
171
+ .chatbot {
172
+ background-color: #f8f9fa;
173
+ border-radius: 10px;
174
+ padding: 15px;
175
+ margin-bottom: 20px;
176
+ }
177
+ /* 移除消息背景的白色遮盖,优化对话样式 */
178
+ .chatbot > div {
179
+ background: transparent !important;
180
+ }
181
+ /* 用户消息样式 */
182
+ .chatbot .user-message {
183
+ background-color: #fce4ec !important;
184
+ border-radius: 15px 15px 2px 15px !important;
185
+ padding: 12px 18px !important;
186
+ margin: 8px 0 !important;
187
+ max-width: 85% !important;
188
+ float: right !important;
189
+ clear: both !important;
190
+ border: 1px solid #f48fb1 !important;
191
+ color: #1a1a1a !important;
192
+ font-size: 15px !important;
193
+ }
194
+ /* AI响应消息样式 */
195
+ .chatbot .bot-message {
196
+ background-color: #e8f5e9 !important;
197
+ border-radius: 15px 15px 15px 2px !important;
198
+ padding: 12px 18px !important;
199
+ margin: 8px 0 !important;
200
+ max-width: 85% !important;
201
+ float: left !important;
202
+ clear: both !important;
203
+ border: 1px solid #a5d6a7 !important;
204
+ color: #1a1a1a !important;
205
+ font-size: 15px !important;
206
+ }
207
+ /* 消息容器样式 */
208
+ .chatbot > div > div {
209
+ padding: 0 !important;
210
+ gap: 2rem !important;
211
+ }
212
+ /* 头像样式 */
213
+ .chatbot span.avatar {
214
+ padding: 8px !important;
215
+ margin: 8px !important;
216
+ }
217
+ /* 确保消息之间有适当的间距 */
218
+ .chatbot > div > div:not(:last-child) {
219
+ margin-bottom: 15px !important;
220
+ }
221
+ """
222
+ ) as interface:
223
+ with gr.Column(elem_classes="container"):
224
+ gr.Markdown(
225
+ """
226
+ # 🏥 AI用药咨询助手
227
+ ### 您的专业用药咨询顾问,随时为您解答用药相关问题
228
+ """
229
+ )
230
+
231
+ with gr.Column(elem_classes="chat-container"):
232
+ chatbot = gr.Chatbot(
233
+ height=500,
234
+ container=False,
235
+ elem_classes="chatbot",
236
+ show_label=False,
237
+ bubble_full_width=False,
238
+ avatar_images=("👤", "🤖")
239
+ )
240
+
241
+ with gr.Row(elem_id="input-container"):
242
+ with gr.Column(scale=8):
243
+ message = gr.Textbox(
244
+ show_label=False,
245
+ placeholder="请输入您的用药问题...",
246
+ container=False,
247
+ elem_classes="message-box",
248
+ lines=2
249
+ )
250
+ with gr.Column(scale=1, min_width=100):
251
+ submit = gr.Button(
252
+ "发送 💊",
253
+ variant="primary",
254
+ elem_classes="submit-btn"
255
+ )
256
+
257
+ with gr.Row(elem_id="control-container"):
258
+ clear = gr.Button(
259
+ "清空对话 🗑️",
260
+ variant="secondary",
261
+ elem_classes="clear-btn"
262
+ )
263
+
264
+ # 设置事件处理
265
+ submit_click = submit.click(
266
+ fastgpt_chat.chat,
267
+ inputs=[message, chatbot],
268
+ outputs=[message, chatbot],
269
+ api_name="chat"
270
+ )
271
+
272
+ message.submit(
273
+ fastgpt_chat.chat,
274
+ inputs=[message, chatbot],
275
+ outputs=[message, chatbot]
276
+ )
277
+
278
+ clear.click(lambda: None, None, chatbot, queue=False)
279
+
280
+ return interface
281
+
282
+ if __name__ == "__main__":
283
+ demo = create_chat_interface()
284
+ demo.launch(debug=True)