Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,42 +1,44 @@
|
|
1 |
import gradio as gr
|
2 |
-
import requests
|
3 |
import os
|
|
|
4 |
|
5 |
-
#
|
6 |
-
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
# 定义对话函数
|
10 |
def answer(question, history):
|
11 |
if history is None:
|
12 |
history = []
|
13 |
|
14 |
-
#
|
15 |
-
messages = [{
|
16 |
-
|
17 |
-
|
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 |
-
|
25 |
-
|
26 |
-
|
27 |
-
json={"messages": messages},
|
28 |
-
headers={"Authorization": f"Bearer {DEEPSEEK_API_KEY}"}
|
29 |
)
|
30 |
-
|
31 |
-
#
|
32 |
-
|
33 |
-
|
34 |
-
|
|
|
|
|
|
|
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()
|