File size: 2,612 Bytes
cb162de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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()