leonsimon23 commited on
Commit
bc49f0d
·
verified ·
1 Parent(s): 2d0ef85

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -123
app.py CHANGED
@@ -10,7 +10,20 @@ logging.basicConfig(level=logging.DEBUG)
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,14 +31,12 @@ class FastGPTChat:
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,7 +49,7 @@ class FastGPTChat:
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,9 +78,8 @@ class FastGPTChat:
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,18 +93,22 @@ class FastGPTChat:
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,128 +116,121 @@ def create_chat_interface():
102
  with gr.Blocks(
103
  title="AI用药咨询助手",
104
  css="""
105
- body {
106
- background-color: #F4F6F9;
107
- font-family: 'Inter', 'PingFang SC', sans-serif;
108
- }
109
- .container {
110
- max-width: 800px;
111
- margin: 2rem auto;
112
- padding: 1rem;
113
- box-sizing: border-box;
114
- }
115
- .title-container {
116
- text-align: center;
117
- margin-bottom: 1.5rem;
118
- }
119
- .title-container h1 {
120
- color: #2C3E50;
121
- font-size: 2.2rem;
122
- font-weight: 700;
123
- margin-bottom: 0.5rem;
124
- }
125
- .title-container h3 {
126
- color: #6B7280;
127
- font-size: 1rem;
128
- font-weight: 400;
129
  }
130
  .chat-container {
131
- background-color: white;
132
- border-radius: 16px;
133
- box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
134
- overflow: hidden;
135
- }
136
- .chatbot {
137
- height: 500px !important;
138
- background-color: #F9FAFB;
139
- padding: 1rem;
140
- overflow-y: auto;
141
- }
142
- .chatbot .user-message {
143
- background: linear-gradient(135deg, #3B82F6, #2563EB);
144
- color: white !important;
145
- border-radius: 16px 16px 4px 16px !important;
146
- align-self: flex-end !important;
147
- max-width: 80% !important;
148
- }
149
- .chatbot .bot-message {
150
- background: linear-gradient(135deg, #F3F4F6, #FFFFFF);
151
- color: #1F2937 !important;
152
- border: 1px solid #E5E7EB !important;
153
- border-radius: 16px 16px 16px 4px !important;
154
- align-self: flex-start !important;
155
- max-width: 80% !important;
156
- }
157
- .input-container {
158
- background: white;
159
- padding: 1rem;
160
- border-top: 1px solid #E5E7EB;
161
  }
162
  .message-box {
163
- border: 2px solid #E5E7EB !important;
164
- border-radius: 12px !important;
165
- padding: 0.75rem !important;
166
- font-size: 0.95rem !important;
167
- transition: all 0.3s ease !important;
168
- background: white !important;
169
  }
170
  .message-box:focus {
171
- border-color: #3B82F6 !important;
172
- box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.2) !important;
173
- }
174
- .button-container {
175
- display: flex;
176
- gap: 1rem;
177
- margin-top: 1rem;
178
  }
179
  .submit-btn {
180
- background: linear-gradient(135deg, #3B82F6, #2563EB) !important;
 
181
  color: white !important;
182
- padding: 0.75rem 1.5rem !important;
183
- border-radius: 12px !important;
184
- font-weight: 600 !important;
185
  transition: all 0.3s ease !important;
186
- flex: 1;
187
  }
188
  .submit-btn:hover {
 
189
  transform: translateY(-2px);
190
- box-shadow: 0 6px 16px rgba(59, 130, 246, 0.3) !important;
191
  }
192
  .clear-btn {
193
- background: #EF4444 !important;
 
194
  color: white !important;
195
- padding: 0.75rem 1.5rem !important;
196
- border-radius: 12px !important;
197
- font-weight: 600 !important;
198
  transition: all 0.3s ease !important;
 
199
  }
200
  .clear-btn:hover {
 
201
  transform: translateY(-2px);
202
- box-shadow: 0 6px 16px rgba(239, 68, 68, 0.3) !important;
203
  }
204
- @media (max-width: 600px) {
205
- .container {
206
- margin: 1rem;
207
- padding: 0.5rem;
208
- }
209
- .chatbot {
210
- height: 400px !important;
211
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  }
213
  """
214
  ) as interface:
215
  with gr.Column(elem_classes="container"):
216
- with gr.Column(elem_classes="title-container"):
217
- gr.Markdown(
218
- """
219
- # 🏥 AI用药咨询助手
220
- ### 您的专业用药咨询顾问,随时为您解答用药相关问题
221
- """
222
- )
223
 
224
  with gr.Column(elem_classes="chat-container"):
225
  chatbot = gr.Chatbot(
226
- height=600,
227
  container=False,
228
  elem_classes="chatbot",
229
  show_label=False,
@@ -231,27 +238,28 @@ def create_chat_interface():
231
  avatar_images=("👤", "🤖")
232
  )
233
 
234
- with gr.Column(elem_classes="input-container"):
235
- message = gr.Textbox(
236
- show_label=False,
237
- placeholder="请输入您的用药问题...",
238
- container=False,
239
- elem_classes="message-box",
240
- lines=1, # 减小输入框初始行数
241
- max_lines=5 # 设置最大行数
242
- )
243
-
244
- with gr.Row(elem_classes="button-container"):
245
  submit = gr.Button(
246
  "发送 💊",
247
  variant="primary",
248
  elem_classes="submit-btn"
249
  )
250
- clear = gr.Button(
251
- "清空对话 🗑️",
252
- variant="secondary",
253
- elem_classes="clear-btn"
254
- )
 
 
255
 
256
  # 设置事件处理
257
  submit_click = submit.click(
@@ -273,4 +281,4 @@ def create_chat_interface():
273
 
274
  if __name__ == "__main__":
275
  demo = create_chat_interface()
276
- demo.queue().launch(debug=True, server_name="0.0.0.0")
 
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
  "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
  })
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
  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
  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
  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
  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(
 
281
 
282
  if __name__ == "__main__":
283
  demo = create_chat_interface()
284
+ demo.launch(debug=True)