File size: 3,750 Bytes
4145939 43ef72c 4145939 2e1a1b2 43ef72c ababf7c 43ef72c 4145939 43ef72c ababf7c b365cdb ababf7c 43ef72c ababf7c 43ef72c ababf7c b365cdb 43ef72c b365cdb ababf7c 43ef72c 4e3871a 43ef72c 4e3871a 88f118c 4e3871a ababf7c 88f118c 4145939 ababf7c 43ef72c ababf7c 43ef72c 4e3871a 43ef72c b365cdb 43ef72c ababf7c 43ef72c b365cdb 43ef72c b365cdb 43ef72c 4e3871a b365cdb 43ef72c 903a112 ababf7c 903a112 ababf7c 903a112 ababf7c 4e3871a b365cdb 4e3871a 4145939 ababf7c 43ef72c ababf7c 88f118c 43ef72c ababf7c 4e3871a 43ef72c ababf7c 43ef72c 4145939 dc2732a 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 |
import gradio as gr
from openai import OpenAI
# Инициализация клиента DeepSeek
client = OpenAI(
api_key="sk-a02694cf3c8640c9ae60428ee2c5a62e", # <-- Замените на свой ключ
base_url="https://api.deepseek.com"
)
def chat_with_deepseek(user_message, history):
"""
user_message: текст, введённый пользователем (str).
history: список словарей [{"role": "user"/"assistant", "content": "..."}],
в формате, ожидаемом Chatbot(type="messages").
Возвращает (new_history, new_history, ""),
где третий элемент очищает поле ввода.
"""
# Преобразуем историю в формат messages для модели:
messages = []
for msg in history:
messages.append({"role": msg["role"], "content": msg["content"]})
# Добавляем текущее сообщение пользователя
messages.append({"role": "user", "content": user_message})
# Обращаемся к deepseek-reasoner
try:
response = client.chat.completions.create(
model="deepseek-reasoner",
messages=messages
)
assistant_content = response.choices[0].message.content
except Exception as e:
assistant_content = f"Ошибка при обращении к API: {e}"
# Формируем новое состояние истории
new_history = history + [
{"role": "user", "content": user_message},
{"role": "assistant", "content": assistant_content}
]
# Третий выход (пустая строка) очистит поле ввода
return new_history, new_history, ""
# Создаём 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: #000000 !important;
}
.block.block--main {
background-color: #000000 !important;
}
.gradio-container {
color: #ffffff !important;
}
#chatbot {
background-color: #111111 !important;
}
"""
) as demo:
# Заголовок
gr.HTML("""
<h1 style="text-align:center; color:#ffffff;">Чат с deepseek-reasoner</h1>
<p style="text-align:center; color:#cccccc;">
При нажатии Enter сообщение отправляется!
</p>
""")
# Чат (в формате "messages", чтобы избежать предупреждений Gradio)
chatbot = gr.Chatbot(
label="Диалог",
height=400,
type="messages",
elem_id="chatbot"
)
# Храним историю в стейте (пустой список по умолчанию)
state = gr.State([])
# Поле ввода: Enter => отправка, т.к. lines=1
msg = gr.Textbox(
label="Ваш вопрос",
placeholder="Введите сообщение и нажмите Enter для отправки",
lines=1, # Однострочное поле
)
# Привязываем отправку при нажатии Enter (submit)
msg.submit(
fn=chat_with_deepseek,
inputs=[msg, state],
outputs=[chatbot, state, msg], # msg = "" (очищается)
scroll_to_output=True
)
# Запуск
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)
|