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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +142 -131
app.py CHANGED
@@ -10,20 +10,7 @@ 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
@@ -31,12 +18,14 @@ class FastGPTChat:
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
 
@@ -49,7 +38,7 @@ class FastGPTChat:
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
 
@@ -78,8 +67,9 @@ class FastGPTChat:
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 = ""
@@ -93,22 +83,18 @@ class FastGPTChat:
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()
@@ -116,121 +102,148 @@ def create_chat_interface():
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,
@@ -238,28 +251,26 @@ def create_chat_interface():
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(
 
10
  logger = logging.getLogger(__name__)
11
 
12
  class FastGPTChat:
 
 
 
 
 
 
 
 
 
 
 
 
13
  def __init__(self, system_prompt="我是一名AI用药咨询顾问,请向我提问有关用药的问题"):
 
14
  self.api_key = os.environ.get('FASTGPT_API_KEY')
15
  self.base_url = os.environ.get('FASTGPT_BASE_URL', 'https://api.fastgpt.in/api')
16
  self.system_prompt = system_prompt
 
18
  "Authorization": f"Bearer {self.api_key}",
19
  "Content-Type": "application/json"
20
  }
 
 
21
 
22
  def chat(self, message, chat_history):
23
  if not message.strip():
24
  return "", chat_history
25
+
26
+ # 立即添加用户消息到聊天历史
27
+ chat_history.append((message, ""))
28
+ yield "", chat_history
29
 
30
  chat_id = str(uuid.uuid4())
31
 
 
38
  })
39
 
40
  # 添加聊天历史
41
+ for user_msg, bot_msg in chat_history[:-1]: # 不包含最新消息
42
  messages.append({"role": "user", "content": user_msg})
43
  messages.append({"role": "assistant", "content": bot_msg})
44
 
 
67
  if response.status_code != 200:
68
  error_msg = f"API Error: Status {response.status_code}"
69
  logger.error(error_msg)
70
+ chat_history[-1] = (message, f"Error: {error_msg}")
71
+ yield "", chat_history
72
+ return
73
 
74
  # 处理流式响应
75
  full_response = ""
 
83
  content = data['choices'][0]['delta'].get('content', '')
84
  if content:
85
  full_response += content
86
+ chat_history[-1] = (message, full_response)
 
 
 
 
87
  yield "", chat_history
88
  except Exception as e:
89
  logger.error(f"Error processing stream: {str(e)}")
90
 
91
+ yield "", chat_history
92
 
93
  except requests.exceptions.RequestException as e:
94
  error_msg = f"Request failed: {str(e)}"
95
  logger.error(error_msg)
96
+ chat_history[-1] = (message, f"Error: {error_msg}")
97
+ yield "", chat_history
98
 
99
  def create_chat_interface():
100
  fastgpt_chat = FastGPTChat()
 
102
  with gr.Blocks(
103
  title="AI用药咨询助手",
104
  css="""
105
+ /* 整体容器样式 */
106
+ .container {
107
+ width: 80%;
108
+ margin: auto;
109
+ padding: 2rem;
110
+ box-sizing: border-box;
111
+ }
112
+
113
+ /* 标题区域样式 */
114
+ .title-container {
115
+ text-align: center;
116
+ margin-bottom: 2rem;
117
+ }
118
+
119
+ .title-container h1 {
120
+ color: #2C3E50;
121
+ font-size: 2.5rem;
122
+ margin-bottom: 0.5rem;
123
+ }
124
+
125
+ .title-container h3 {
126
+ color: #7F8C8D;
127
+ font-size: 1.2rem;
128
+ font-weight: normal;
129
  }
130
+
131
+ /* 聊天容器样式 */
132
  .chat-container {
133
+ background-color: #FFFFFF;
134
+ border-radius: 20px;
135
+ box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
136
+ padding: 2rem;
137
+ margin-bottom: 2rem;
138
  }
139
+
140
+ /* 聊天框样式 */
141
+ .chatbot {
142
+ background-color: #F8F9FA;
143
+ border-radius: 15px;
144
+ padding: 1.5rem;
145
+ margin-bottom: 1.5rem;
146
+ height: 600px !important;
147
+ overflow-y: auto;
148
+ }
149
+
150
+ /* 消息样式 */
151
+ .chatbot .user-message {
152
+ background: linear-gradient(135deg, #6366F1, #4F46E5);
153
+ color: white !important;
154
+ border-radius: 18px 18px 4px 18px !important;
155
+ padding: 1rem 1.5rem !important;
156
+ margin: 1rem 0 !important;
157
+ max-width: 80% !important;
158
+ float: right !important;
159
+ clear: both !important;
160
+ box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2) !important;
161
+ }
162
+
163
+ .chatbot .bot-message {
164
+ background: white !important;
165
+ border: 1px solid #E5E7EB !important;
166
+ color: #1F2937 !important;
167
+ border-radius: 18px 18px 18px 4px !important;
168
+ padding: 1rem 1.5rem !important;
169
+ margin: 1rem 0 !important;
170
+ max-width: 80% !important;
171
+ float: left !important;
172
+ clear: both !important;
173
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05) !important;
174
+ }
175
+
176
+ /* 输入区域样式 */
177
+ .input-container {
178
+ background: white;
179
+ padding: 1.5rem;
180
+ border-radius: 15px;
181
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
182
+ }
183
+
184
  .message-box {
185
+ border: 2px solid #E5E7EB !important;
186
+ border-radius: 12px !important;
187
+ padding: 1rem !important;
188
+ font-size: 1rem !important;
189
+ transition: all 0.3s ease !important;
190
+ background: white !important;
191
  }
192
+
193
  .message-box:focus {
194
+ border-color: #6366F1 !important;
195
+ box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.2) !important;
196
  }
197
+
198
+ /* 按钮样式 */
199
+ .button-container {
200
+ display: flex;
201
+ gap: 1rem;
202
+ margin-top: 1rem;
203
+ }
204
+
205
  .submit-btn {
206
+ background: linear-gradient(135deg, #6366F1, #4F46E5) !important;
 
207
  color: white !important;
208
+ padding: 0.75rem 1.5rem !important;
209
+ border-radius: 12px !important;
 
210
  font-weight: 600 !important;
211
+ transition: all 0.3s ease !important;
212
+ flex: 1;
213
  }
214
+
215
  .submit-btn:hover {
 
216
  transform: translateY(-2px);
217
+ box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3) !important;
218
  }
219
+
220
  .clear-btn {
221
+ background: #EF4444 !important;
 
222
  color: white !important;
223
+ padding: 0.75rem 1.5rem !important;
224
+ border-radius: 12px !important;
 
225
  font-weight: 600 !important;
226
+ transition: all 0.3s ease !important;
227
  }
228
+
229
  .clear-btn:hover {
 
230
  transform: translateY(-2px);
231
+ box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3) !important;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
232
  }
233
  """
234
  ) as interface:
235
  with gr.Column(elem_classes="container"):
236
+ with gr.Column(elem_classes="title-container"):
237
+ gr.Markdown(
238
+ """
239
+ # 🏥 AI用药咨询助手
240
+ ### 您的专业用药咨询顾问,随时为您解答用药相关问题
241
+ """
242
+ )
243
 
244
  with gr.Column(elem_classes="chat-container"):
245
  chatbot = gr.Chatbot(
246
+ height=600,
247
  container=False,
248
  elem_classes="chatbot",
249
  show_label=False,
 
251
  avatar_images=("👤", "🤖")
252
  )
253
 
254
+ with gr.Column(elem_classes="input-container"):
255
+ message = gr.Textbox(
256
+ show_label=False,
257
+ placeholder="请输入您的用药问题...",
258
+ container=False,
259
+ elem_classes="message-box",
260
+ lines=3
261
+ )
262
+
263
+ with gr.Row(elem_classes="button-container"):
264
  submit = gr.Button(
265
  "发送 💊",
266
  variant="primary",
267
  elem_classes="submit-btn"
268
  )
269
+ clear = gr.Button(
270
+ "清空对话 🗑️",
271
+ variant="secondary",
272
+ elem_classes="clear-btn"
273
+ )
 
 
274
 
275
  # 设置事件处理
276
  submit_click = submit.click(