import gradio as gr import os from openai import OpenAI # 读取环境变量 DASHSCOPE_API_KEY = os.getenv("DASHSCOPE_API_KEY") # 从环境变量读取 API Key DASHSCOPE_API_URL = "https://dashscope.aliyuncs.com/compatible-mode/v1" # 设置 DashScope API 客户端 client = OpenAI( api_key=DASHSCOPE_API_KEY, base_url=DASHSCOPE_API_URL ) # 定义对话函数 def answer(question, history): if history is None: history = [] # 将历史记录与用户输入合并 messages = [{'role': 'user', 'content': question}] # 向 DashScope API 发送请求 try: completion = client.chat.completions.create( model="deepseek-r1", # 使用 DeepSeek-R1 模型 messages=messages ) # 获取思考过程与最终答案 reasoning_content = completion.choices[0].message.get("reasoning_content", "没有思考过程") bot_response = completion.choices[0].message["content"] # 输出思考过程与最终答案(用于调试) print("思考过程:", reasoning_content) print("最终答案:", bot_response) # 更新历史记录 history.append({"role": "user", "content": question}) history.append({"role": "assistant", "content": bot_response}) return history, history except Exception as e: print("API 请求失败:", e) return history, history # 返回空的 history # 创建 Gradio 界面 with gr.Blocks(css=""" #chatbot { height: 400px; background-color: #f7f7f7; border-radius: 10px; padding: 20px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); } .gradio-container { background-color: #212121; border-radius: 20px; padding: 40px; } .gr-button { background-color: #4CAF50; color: white; border-radius: 10px; padding: 10px 20px; border: none; font-weight: bold; } .gr-button:hover { background-color: #45a049; } .gr-chatbot { font-family: 'Arial', sans-serif; height: 400px; } .chatbot-message { margin: 10px; padding: 10px; border-radius: 15px; 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: 10px; width: 100%; } .gradio-container .gr-chatbot .overflow-y-auto { max-height: 500px; } """) 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()