deepseek-r1 / app.py
MarcoXi's picture
Update app.py
c0b418a verified
import gradio as gr
import os
import requests
# 从环境变量中读取 API 密钥
DASHSCOPE_API_KEY = os.getenv("DASHSCOPE_API_KEY")
DASHSCOPE_API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1"
# 设置 DeepSeek API 客户端
class DeepSeekClient:
def __init__(self, api_key, base_url):
self.api_key = api_key
self.base_url = base_url
def chat(self, question):
headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json",
}
data = {
"model": "deepseek-r1", # 使用 DeepSeek 模型
"messages": [{"role": "user", "content": question}],
}
try:
response = requests.post(
f"{self.base_url}/chat/completions",
headers=headers,
json=data
)
response.raise_for_status()
result = response.json()
# 获取思考过程和最终答案
reasoning_content = result["choices"][0].get("reasoning_content", "没有思考过程")
bot_response = result["choices"][0]["message"]["content"]
return bot_response, reasoning_content
except Exception as e:
return f"Error: {e}", None
# 创建 DeepSeek 客户端
client = DeepSeekClient(api_key=DASHSCOPE_API_KEY, base_url=DASHSCOPE_API_URL)
# 定义聊天函数
def answer(question, history):
if history is None:
history = []
# 获取模型响应
bot_response, reasoning_content = client.chat(question)
# 输出思考过程与最终答案(用于调试)
print("思考过程:", reasoning_content)
print("最终答案:", bot_response)
# 更新历史记录
history.append({"role": "user", "content": question})
history.append({"role": "assistant", "content": bot_response})
return history, history
# 创建 Gradio 界面
with gr.Blocks(css="""
/* 修改布局适应手机端 */
.gradio-container {
background-color: #f0f0f0;
border-radius: 15px;
padding: 20px;
max-width: 500px;
margin: auto;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.gr-button {
background-color: #4CAF50;
color: white;
border-radius: 10px;
padding: 12px 25px;
border: none;
font-weight: bold;
}
.gr-button:hover {
background-color: #45a049;
}
.gr-chatbot {
font-family: 'Arial', sans-serif;
height: 300px;
max-height: 300px;
overflow-y: auto;
padding: 10px;
margin-bottom: 20px;
background-color: #ffffff;
border-radius: 15px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.chatbot-message {
margin: 10px;
padding: 10px;
border-radius: 12px;
background-color: #e1f5fe;
}
.user-message {
background-color: #a5d6a7;
color: #ffffff;
}
.assistant-message {
background-color: #e3f2fd;
color: #000000;
}
input[type="text"] {
font-size: 16px;
border-radius: 10px;
padding: 12px;
width: 100%;
background-color: #f9f9f9;
margin-top: 10px;
}
/* 手机端优化:输入框宽度和响应式设计 */
@media (max-width: 600px) {
.gradio-container {
padding: 15px;
width: 90%;
}
.gr-button {
padding: 10px 20px;
}
}
""") as demo:
chatbot = gr.Chatbot(elem_id="chatbot", type="messages") # 使用 Gradio 的聊天组件
state = gr.State([])
with gr.Row():
txt = gr.Textbox(placeholder="请输入您的问题并按回车发送", lines=1)
txt.submit(answer, [txt, state], [chatbot, state])
demo.launch()