Stone164 commited on
Commit
11cb3d3
·
verified ·
1 Parent(s): d4096ed

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -13
app.py CHANGED
@@ -2,34 +2,43 @@ import gradio as gr
2
  from openai import OpenAI
3
  import os
4
 
5
- # 简化版本的预测函数
6
  def predict(message, history):
7
  try:
8
  # 初始化OpenAI客户端
9
  api_key = os.environ.get("API_TOKEN")
10
  if not api_key:
11
- return "错误:API密钥未设置,请在Hugging Face Space设置中添加名为API_TOKEN的Secret。"
12
 
13
  client = OpenAI(api_key=api_key)
14
 
15
- # 构建消息
16
- messages = [
17
- {"role": "system", "content": "你是一个有用的AI助手。"},
18
- {"role": "user", "content": message}
19
- ]
20
 
21
- # 非流式调用,更简单更可靠
 
 
 
 
 
 
 
 
22
  response = client.chat.completions.create(
23
  model="gpt-4o",
24
  messages=messages,
25
  max_tokens=1000,
26
  temperature=0.7,
27
- stream=False # 关闭流式响应
28
  )
29
 
30
- return response.choices[0].message.content
 
 
 
31
  except Exception as e:
32
- return f"发生误: {str(e)}"
 
33
 
34
  # 创建简化版界面
35
  with gr.Blocks(css="""
@@ -53,9 +62,15 @@ with gr.Blocks(css="""
53
 
54
  chatbot = gr.Chatbot()
55
  msg = gr.Textbox(placeholder="输入你的问题...", show_label=False)
 
 
56
  send_btn = gr.Button("发送", elem_id="custom-send")
57
 
58
- send_btn.click(predict, [msg, chatbot], [chatbot])
59
- msg.submit(predict, [msg, chatbot], [chatbot])
 
 
 
 
60
 
61
  demo.launch()
 
2
  from openai import OpenAI
3
  import os
4
 
5
+ # 修复格式问题的预测函数
6
  def predict(message, history):
7
  try:
8
  # 初始化OpenAI客户端
9
  api_key = os.environ.get("API_TOKEN")
10
  if not api_key:
11
+ return history + [["错误:API密钥未设置", ""]]
12
 
13
  client = OpenAI(api_key=api_key)
14
 
15
+ # 构建消息列表,包含历史记录
16
+ messages = [{"role": "system", "content": "你是一个有用的AI助手。"}]
 
 
 
17
 
18
+ # 添加历史消息
19
+ for user_msg, bot_msg in history:
20
+ messages.append({"role": "user", "content": user_msg})
21
+ messages.append({"role": "assistant", "content": bot_msg})
22
+
23
+ # 添加当前用户消息
24
+ messages.append({"role": "user", "content": message})
25
+
26
+ # 非流式调用
27
  response = client.chat.completions.create(
28
  model="gpt-4o",
29
  messages=messages,
30
  max_tokens=1000,
31
  temperature=0.7,
32
+ stream=False
33
  )
34
 
35
+ bot_response = response.choices[0].message.content
36
+
37
+ # 返回新的历史记录,添加当前交互
38
+ return history + [[message, bot_response]]
39
  except Exception as e:
40
+ # 时也保持正确的格式
41
+ return history + [[message, f"发生错误: {str(e)}"]]
42
 
43
  # 创建简化版界面
44
  with gr.Blocks(css="""
 
62
 
63
  chatbot = gr.Chatbot()
64
  msg = gr.Textbox(placeholder="输入你的问题...", show_label=False)
65
+ clear = gr.Button("清除对话")
66
+
67
  send_btn = gr.Button("发送", elem_id="custom-send")
68
 
69
+ # 重要:正确处理输入和状态
70
+ msg.submit(predict, [msg, chatbot], [chatbot]).then(
71
+ lambda: "", None, msg)
72
+ send_btn.click(predict, [msg, chatbot], [chatbot]).then(
73
+ lambda: "", None, msg)
74
+ clear.click(lambda: None, None, chatbot)
75
 
76
  demo.launch()