import gradio as gr import requests import os # 假设 DeepSeek-R1 的 API URL 和 API Key DEEPSEEK_API_URL = os.getenv("DEEPSEEK_API_URL", "https://api.deepseek.com/v1/chat") DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY") # 定义对话函数 def answer(question, history): if history is None: history = [] # 组装对话历史 messages = [{"role": "system", "content": "你是一个中国厨师,用中文回答做菜的问题。"}] for item in history: messages.append({"role": item["role"], "content": item["content"]}) messages.append({"role": "user", "content": question}) # 调用 DeepSeek-R1 API response = requests.post( DEEPSEEK_API_URL, json={"messages": messages}, headers={"Authorization": f"Bearer {DEEPSEEK_API_KEY}"} ) response_data = response.json() bot_response = response_data.get("choices")[0]["message"]["content"] # 更新历史记录 history.append({"role": "user", "content": question}) history.append({"role": "assistant", "content": bot_response}) return 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; } .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()