Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -32,21 +32,25 @@ def ai_response(message, chat_history):
|
|
| 32 |
}
|
| 33 |
|
| 34 |
# 发送请求到第三方 API
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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():
|