|
import gradio as gr |
|
from openai import OpenAI |
|
|
|
|
|
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 = [] |
|
for msg in history: |
|
messages.append({"role": msg["role"], "content": msg["content"]}) |
|
|
|
messages.append({"role": "user", "content": user_message}) |
|
|
|
|
|
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( |
|
|
|
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> |
|
""") |
|
|
|
|
|
chatbot = gr.Chatbot( |
|
label="Диалог", |
|
height=400, |
|
type="messages", |
|
elem_id="chatbot" |
|
) |
|
|
|
|
|
state = gr.State([]) |
|
|
|
|
|
msg = gr.Textbox( |
|
label="Ваш вопрос", |
|
placeholder="Введите сообщение и нажмите Enter для отправки", |
|
lines=1, |
|
) |
|
|
|
|
|
msg.submit( |
|
fn=chat_with_deepseek, |
|
inputs=[msg, state], |
|
outputs=[chatbot, state, msg], |
|
scroll_to_output=True |
|
) |
|
|
|
|
|
if __name__ == "__main__": |
|
demo.launch(server_name="0.0.0.0", server_port=7860) |
|
|