R1 / app.py
vortex123's picture
Update app.py
88f118c verified
raw
history blame
5.34 kB
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: строка, введённая пользователем.
history: список словарей [{"role":"user"|"assistant","content":"..."}],
формат Gradio Chatbot (type="messages").
Возвращает (new_history, new_history, ""):
- new_history — обновлённая история для Chatbot
- "" — чтобы очистить поле ввода
"""
# Преобразуем history в формат messages для DeepSeek
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, ""
with gr.Blocks(
# Тема Gradio:
theme=gr.themes.Base(
primary_hue="slate",
secondary_hue="blue",
neutral_hue="slate",
text_size="md",
font=["Arial", "sans-serif"]
),
# CSS для чёрного оформления
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;">
<b>Enter</b> — отправить; <b>Ctrl+Enter</b> — новая строка.
</p>
""")
# Компонент чата, хранящего сообщения в формате "messages"
chatbot = gr.Chatbot(
label="Диалог",
height=400,
type="messages",
elem_id="chatbot"
)
# Текстовое поле (2 строки по умолчанию)
msg = gr.Textbox(
label="Ваш вопрос",
placeholder="Введите сообщение...",
lines=2,
elem_id="user_input"
)
# Скрытая кнопка (не показываем в UI), которую мы будем "нажимать" программно
hidden_send_btn = gr.Button(
"Скрытая кнопка",
visible=False,
elem_id="hidden_send_btn"
)
# Состояние для истории чата
state = gr.State([])
# При клике на кнопку (вызванной JS), отправляем сообщение
hidden_send_btn.click(
fn=chat_with_deepseek,
inputs=[msg, state],
outputs=[chatbot, state, msg],
scroll_to_output=True
)
# Подключаем JS, чтобы:
# - Enter => нажимать на скрытую кнопку (отправлять сообщение)
# - Ctrl+Enter => перенос строки
custom_js = """
<script>
document.addEventListener('DOMContentLoaded', function() {
const userInput = document.querySelector('#user_input textarea');
const sendButton = document.querySelector('#hidden_send_btn button');
if (userInput && sendButton) {
userInput.addEventListener('keydown', function(e) {
if (e.key === 'Enter') {
// Если нажали Enter
if (e.ctrlKey) {
// Ctrl+Enter => перенос строки
e.preventDefault();
const start = userInput.selectionStart;
const end = userInput.selectionEnd;
userInput.value = userInput.value.substring(0, start) + "\\n"
+ userInput.value.substring(end);
userInput.selectionStart = userInput.selectionEnd = start + 1;
} else {
// Enter => отправка
e.preventDefault();
sendButton.click();
}
}
});
}
});
</script>
"""
gr.HTML(custom_js)
# Запуск
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860)