leonsimon23 commited on
Commit
96f5518
·
verified ·
1 Parent(s): dc1a05f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -15
app.py CHANGED
@@ -32,21 +32,25 @@ def ai_response(message, chat_history):
32
  }
33
 
34
  # 发送请求到第三方 API
35
- response = requests.post(API_BASE_URL, json=payload, headers=headers)
36
-
37
- if response.status_code == 200:
38
- # 获取 API 响应内容
39
- response_data = response.json()
40
- assistant_message = response_data['choices'][0]['message']['content']
41
-
42
- # 返回新的聊天记录,转换为符合 gr.Chatbot 期望的元组格式
43
- chat_history.append(("user", message))
44
- chat_history.append(("assistant", assistant_message))
45
-
46
- return chat_history
47
- else:
48
- # 如果请求失败,返回错误消息
49
- return chat_history + [("assistant", "Sorry, something went wrong with the API.")]
 
 
 
 
50
 
51
  # 创建 Gradio 应用
52
  def create_interface():
 
32
  }
33
 
34
  # 发送请求到第三方 API
35
+ try:
36
+ response = requests.post(API_BASE_URL, json=payload, headers=headers)
37
+ response.raise_for_status() # 如果响应状态码不是 2xx,会抛出异常
38
+ if response.status_code == 200:
39
+ # 获取 API 响应内容
40
+ response_data = response.json()
41
+ assistant_message = response_data['choices'][0]['message']['content']
42
+
43
+ # 返回新的聊天记录,转换为符合 gr.Chatbot 期望的元组格式
44
+ chat_history.append(("user", message))
45
+ chat_history.append(("assistant", assistant_message))
46
+
47
+ return chat_history
48
+ else:
49
+ # 如果请求失败,输出错误信息
50
+ return chat_history + [("assistant", f"API error: {response.status_code}, {response.text}")]
51
+ except requests.exceptions.RequestException as e:
52
+ # 捕获任何请求错误,并输出详细错误信息
53
+ return chat_history + [("assistant", f"Request failed: {str(e)}")]
54
 
55
  # 创建 Gradio 应用
56
  def create_interface():