R1 / app.py
vortex123's picture
Update app.py
ababf7c verified
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)