MarcoXi commited on
Commit
c8c2297
·
verified ·
1 Parent(s): 7d13a58

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +27 -25
app.py CHANGED
@@ -1,42 +1,44 @@
1
  import gradio as gr
2
- import requests
3
  import os
 
4
 
5
- # 假设 DeepSeek-R1 的 API URL 和 API Key
6
- DEEPSEEK_API_URL = os.getenv("DEEPSEEK_API_URL", "https://dashscope.aliyuncs.com/compatible-mode/v1")
7
- DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
 
 
 
 
 
 
8
 
9
  # 定义对话函数
10
  def answer(question, history):
11
  if history is None:
12
  history = []
13
 
14
- # 组装对话历史
15
- messages = [{"role": "system", "content": "你是一个中国厨师,用中文回答做菜的问题。"}]
16
-
17
- for item in history:
18
- messages.append({"role": item["role"], "content": item["content"]})
19
-
20
- messages.append({"role": "user", "content": question})
21
-
22
- # 调用 DeepSeek-R1 API
23
  try:
24
- # 发送请求到 DeepSeek-R1 API
25
- response = requests.post(
26
- DEEPSEEK_API_URL,
27
- json={"messages": messages},
28
- headers={"Authorization": f"Bearer {DEEPSEEK_API_KEY}"}
29
  )
30
-
31
- # 解析 API 响应
32
- response_data = response.json()
33
- print("API 响应数据:", response_data) # 打印响应数据进行调试
34
- bot_response = response_data.get("choices")[0]["message"]["content"]
 
 
 
35
 
36
  # 更新历史记录
37
  history.append({"role": "user", "content": question})
38
  history.append({"role": "assistant", "content": bot_response})
39
-
40
  return history, history
41
 
42
  except Exception as e:
@@ -105,4 +107,4 @@ with gr.Blocks(css="""
105
 
106
  txt.submit(answer, [txt, state], [chatbot, state])
107
 
108
- demo.launch()
 
1
  import gradio as gr
 
2
  import os
3
+ from openai import OpenAI
4
 
5
+ # 读取环境变量
6
+ DASHSCOPE_API_KEY = os.getenv("DASHSCOPE_API_KEY") # 从环境变量读取 API Key
7
+ DASHSCOPE_API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
8
+
9
+ # 设置 DashScope API 客户端
10
+ client = OpenAI(
11
+ api_key=DASHSCOPE_API_KEY,
12
+ base_url=DASHSCOPE_API_URL
13
+ )
14
 
15
  # 定义对话函数
16
  def answer(question, history):
17
  if history is None:
18
  history = []
19
 
20
+ # 将历史记录与用户输入合并
21
+ messages = [{'role': 'user', 'content': question}]
22
+
23
+ # DashScope API 发送请求
 
 
 
 
 
24
  try:
25
+ completion = client.chat.completions.create(
26
+ model="deepseek-r1", # 使用 DeepSeek-R1 模型
27
+ messages=messages
 
 
28
  )
29
+
30
+ # 获取思考过程与最终答案
31
+ reasoning_content = completion.choices[0].message.get("reasoning_content", "没有思考过程")
32
+ bot_response = completion.choices[0].message["content"]
33
+
34
+ # 输出思考过程与最终答案(用于调试)
35
+ print("思考过程:", reasoning_content)
36
+ print("最终答案:", bot_response)
37
 
38
  # 更新历史记录
39
  history.append({"role": "user", "content": question})
40
  history.append({"role": "assistant", "content": bot_response})
41
+
42
  return history, history
43
 
44
  except Exception as e:
 
107
 
108
  txt.submit(answer, [txt, state], [chatbot, state])
109
 
110
+ demo.launch()