File size: 4,595 Bytes
4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c 4145939 43ef72c |
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 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
import gradio as gr
from openai import OpenAI
# Инициализация клиента для DeepSeek (укажите ваш ключ!)
client = OpenAI(
api_key="sk-a02694cf3c8640c9ae60428ee2c5a62e", # <-- ЗАМЕНИТЕ на свой ключ
base_url="https://api.deepseek.com"
)
# Функция, которая будет вызываться при каждом новом сообщении
# Она принимает текущее сообщение пользователя и "history" — историю чата
# в формате Gradio (список кортежей).
def chat_with_deepseek(user_message, history):
"""
:param user_message: текст последнего сообщения от пользователя
:param history: список кортежей ([(user_msg, bot_msg), ...]),
где хранится вся история переписки
:return: обновлённая история с добавленным ответом от deepseek-reasoner
"""
# Преобразуем history из формата Gradio в формат messages для DeepSeek
messages = []
for user_msg, bot_msg in history:
if user_msg:
messages.append({"role": "user", "content": user_msg})
if bot_msg:
messages.append({"role": "assistant", "content": bot_msg})
# Добавляем новое пользовательское сообщение
messages.append({"role": "user", "content": user_message})
# Обращаемся к deepseek-reasoner, передавая всю историю
try:
response = client.chat.completions.create(
model="deepseek-reasoner",
messages=messages
)
bot_reply = response.choices[0].message.content
except Exception as e:
bot_reply = f"Ошибка при обращении к API: {str(e)}"
# Возвращаем историю, дополнив её ответом бота
history.append((user_message, bot_reply))
return history, history
# Настраиваем интерфейс Gradio
# - elem_id / css / theme позволяют стилизовать под "тёмный" чат
# - "chatbot" виджет в Gradio уже отображает историю в виде «баблов»
with gr.Blocks(
theme=gr.themes.Base(
primary_hue="slate", # оттенок для кнопок
secondary_hue="blue", # оттенок для второстепенных элементов
neutral_hue="slate",
text_size="md",
font=["Arial", "sans-serif"],
),
css="""
body {
background-color: #111111 !important;
}
.block.block--main {
background-color: #111111 !important;
}
.gradio-container {
color: #ffffff !important;
}
/* Дополнительные правки под темный фон */
#chatbot {
background-color: #222222 !important;
}
""") as demo:
gr.Markdown(
"<h1 style='text-align: center; color: #ffffff;'>Чат с deepseek-reasoner</h1>"
"<p style='text-align: center; color: #bbbbbb;'>Тёмная тема, многошаговый диалог</p>"
)
# Компонент Chatbot для отображения диалога
chatbot = gr.Chatbot(label="Диалог").style(height=400)
# Поле для ввода текста
msg = gr.Textbox(
label="Ваш вопрос",
placeholder="Напишите сообщение...",
lines=3
)
# Кнопка отправки
send_btn = gr.Button("Отправить", variant="primary")
# state для хранения истории
state = gr.State([]) # пустой список истории
# Привязываем функцию chat_with_deepseek к нажатию кнопки "Отправить"
# input: user_message (msg), history (state)
# output: (chatbot, state) — обновлённая история чата
send_btn.click(
fn=chat_with_deepseek,
inputs=[msg, state],
outputs=[chatbot, state],
scroll_to_output=True
)
# Также можно отправлять сообщение, нажав Enter в Textbox
msg.submit(
fn=chat_with_deepseek,
inputs=[msg, state],
outputs=[chatbot, state],
scroll_to_output=True
)
# Запуск
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)
|