Update app.py
Browse files
app.py
CHANGED
@@ -1,29 +1,32 @@
|
|
1 |
import gradio as gr
|
2 |
from openai import OpenAI
|
3 |
|
4 |
-
# Инициализация клиента
|
5 |
client = OpenAI(
|
6 |
-
api_key="sk-a02694cf3c8640c9ae60428ee2c5a62e", #
|
7 |
base_url="https://api.deepseek.com"
|
8 |
)
|
9 |
|
10 |
-
# Функция обработки сообщения пользователя
|
11 |
def chat_with_deepseek(user_message, history):
|
12 |
"""
|
13 |
-
user_message:
|
14 |
-
history: список словарей [{role
|
15 |
-
|
|
|
|
|
|
|
|
|
16 |
"""
|
17 |
|
18 |
-
#
|
19 |
messages = []
|
20 |
for item in history:
|
21 |
messages.append({"role": item["role"], "content": item["content"]})
|
22 |
|
23 |
-
# Добавляем
|
24 |
messages.append({"role": "user", "content": user_message})
|
25 |
-
|
26 |
-
# Вызываем deepseek-reasoner
|
27 |
try:
|
28 |
response = client.chat.completions.create(
|
29 |
model="deepseek-reasoner",
|
@@ -33,82 +36,121 @@ def chat_with_deepseek(user_message, history):
|
|
33 |
except Exception as e:
|
34 |
assistant_content = f"Ошибка при обращении к API: {e}"
|
35 |
|
36 |
-
#
|
37 |
new_history = history + [
|
38 |
{"role": "user", "content": user_message},
|
39 |
{"role": "assistant", "content": assistant_content}
|
40 |
]
|
41 |
-
|
42 |
-
|
|
|
|
|
|
|
43 |
|
44 |
-
# Создаём Gradio-приложение
|
45 |
with gr.Blocks(
|
46 |
theme=gr.themes.Base(
|
47 |
primary_hue="slate",
|
48 |
secondary_hue="blue",
|
49 |
neutral_hue="slate",
|
50 |
text_size="md",
|
51 |
-
font=["Arial", "sans-serif"]
|
52 |
),
|
53 |
css="""
|
54 |
-
/*
|
55 |
body {
|
56 |
-
background-color: #
|
57 |
}
|
58 |
.block.block--main {
|
59 |
-
background-color: #
|
60 |
}
|
61 |
.gradio-container {
|
62 |
color: #ffffff !important;
|
63 |
}
|
64 |
-
/* Фон
|
65 |
#chatbot {
|
66 |
-
background-color: #
|
67 |
}
|
68 |
-
"""
|
|
|
69 |
|
70 |
gr.Markdown(
|
71 |
"<h1 style='text-align:center; color:#ffffff;'>Чат с deepseek-reasoner</h1>"
|
72 |
-
"<p style='text-align:center; color:#bbbbbb;'
|
73 |
)
|
74 |
|
75 |
-
#
|
76 |
chatbot = gr.Chatbot(
|
77 |
label="Диалог",
|
78 |
height=400,
|
79 |
-
type="messages"
|
|
|
80 |
)
|
81 |
|
82 |
-
# Поле ввода
|
83 |
msg = gr.Textbox(
|
84 |
label="Ваш вопрос",
|
85 |
placeholder="Введите сообщение...",
|
86 |
-
lines=
|
|
|
87 |
)
|
88 |
|
89 |
-
# Кнопка
|
90 |
-
send_btn = gr.Button("Отправить", variant="primary")
|
91 |
|
92 |
-
#
|
93 |
-
#
|
94 |
state = gr.State([])
|
95 |
|
96 |
-
#
|
97 |
send_btn.click(
|
98 |
fn=chat_with_deepseek,
|
99 |
inputs=[msg, state],
|
100 |
-
outputs=[chatbot, state],
|
101 |
scroll_to_output=True
|
102 |
)
|
103 |
|
104 |
-
#
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
111 |
|
112 |
-
# Запуск
|
113 |
if __name__ == "__main__":
|
114 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|
|
|
1 |
import gradio as gr
|
2 |
from openai import OpenAI
|
3 |
|
4 |
+
# Инициализация клиента DeepSeek
|
5 |
client = OpenAI(
|
6 |
+
api_key="sk-a02694cf3c8640c9ae60428ee2c5a62e", # ЗАМЕНИТЕ на свой ключ
|
7 |
base_url="https://api.deepseek.com"
|
8 |
)
|
9 |
|
|
|
10 |
def chat_with_deepseek(user_message, history):
|
11 |
"""
|
12 |
+
user_message: строка, введённая пользователем.
|
13 |
+
history: список словарей формата [{"role": ..., "content": ...}, ...]
|
14 |
+
(в формате для Gradio Chatbot c type="messages").
|
15 |
+
|
16 |
+
Возвращает (new_history, new_history, ""), где:
|
17 |
+
- new_history — обновлённая история для Chatbot
|
18 |
+
- "" — чтобы очистить поле ввода.
|
19 |
"""
|
20 |
|
21 |
+
# Преобразуем history в messages для DeepSeek (по сути — то же самое, но на всякий случай)
|
22 |
messages = []
|
23 |
for item in history:
|
24 |
messages.append({"role": item["role"], "content": item["content"]})
|
25 |
|
26 |
+
# Добавляем текущее сообщение пользователя
|
27 |
messages.append({"role": "user", "content": user_message})
|
28 |
+
|
29 |
+
# Вызываем модель deepseek-reasoner
|
30 |
try:
|
31 |
response = client.chat.completions.create(
|
32 |
model="deepseek-reasoner",
|
|
|
36 |
except Exception as e:
|
37 |
assistant_content = f"Ошибка при обращении к API: {e}"
|
38 |
|
39 |
+
# Формируем новое состояние истории
|
40 |
new_history = history + [
|
41 |
{"role": "user", "content": user_message},
|
42 |
{"role": "assistant", "content": assistant_content}
|
43 |
]
|
44 |
+
# Возвращаем:
|
45 |
+
# 1) обновлённый чат для Chatbot,
|
46 |
+
# 2) обновлённый state,
|
47 |
+
# 3) пустую строку для очистки поля ввода
|
48 |
+
return new_history, new_history, ""
|
49 |
|
|
|
50 |
with gr.Blocks(
|
51 |
theme=gr.themes.Base(
|
52 |
primary_hue="slate",
|
53 |
secondary_hue="blue",
|
54 |
neutral_hue="slate",
|
55 |
text_size="md",
|
56 |
+
font=["Arial", "sans-serif"]
|
57 |
),
|
58 |
css="""
|
59 |
+
/* Чёрный фон для всего приложения */
|
60 |
body {
|
61 |
+
background-color: #000000 !important;
|
62 |
}
|
63 |
.block.block--main {
|
64 |
+
background-color: #000000 !important;
|
65 |
}
|
66 |
.gradio-container {
|
67 |
color: #ffffff !important;
|
68 |
}
|
69 |
+
/* Фон области чата */
|
70 |
#chatbot {
|
71 |
+
background-color: #111111 !important;
|
72 |
}
|
73 |
+
"""
|
74 |
+
) as demo:
|
75 |
|
76 |
gr.Markdown(
|
77 |
"<h1 style='text-align:center; color:#ffffff;'>Чат с deepseek-reasoner</h1>"
|
78 |
+
"<p style='text-align:center; color:#bbbbbb;'>Нажмите Enter, чтобы отправить; Ctrl+Enter для новой строки</p>"
|
79 |
)
|
80 |
|
81 |
+
# Компонент чата в «сообщениях» (OpenAI-стиле)
|
82 |
chatbot = gr.Chatbot(
|
83 |
label="Диалог",
|
84 |
height=400,
|
85 |
+
type="messages",
|
86 |
+
elem_id="chatbot"
|
87 |
)
|
88 |
|
89 |
+
# Поле ввода
|
90 |
msg = gr.Textbox(
|
91 |
label="Ваш вопрос",
|
92 |
placeholder="Введите сообщение...",
|
93 |
+
lines=2, # можно увеличить
|
94 |
+
elem_id="user_input"
|
95 |
)
|
96 |
|
97 |
+
# Кнопка "Отправить"
|
98 |
+
send_btn = gr.Button("Отправить", variant="primary", elem_id="send_button")
|
99 |
|
100 |
+
# Gradio-хранилище истории
|
101 |
+
# (по умолчанию пустой список [{"role": "...", "content": "..."}])
|
102 |
state = gr.State([])
|
103 |
|
104 |
+
# При клике на кнопку: вызываем функцию, обновляем чат и очищаем поле ввода
|
105 |
send_btn.click(
|
106 |
fn=chat_with_deepseek,
|
107 |
inputs=[msg, state],
|
108 |
+
outputs=[chatbot, state, msg],
|
109 |
scroll_to_output=True
|
110 |
)
|
111 |
|
112 |
+
# Здесь мы не используем msg.submit(...), так как будем обрабатывать Enter
|
113 |
+
# через JavaScript (чтобы Ctrl+Enter давал перенос строки).
|
114 |
+
|
115 |
+
# Подключаем JS-код, который перехватывает Enter и Ctrl+Enter
|
116 |
+
# - Enter => отправка (нажатие на send_button)
|
117 |
+
# - Ctrl+Enter => вставка новой строки
|
118 |
+
custom_js = """
|
119 |
+
<script>
|
120 |
+
document.addEventListener('DOMContentLoaded', function() {
|
121 |
+
// Ищем textarea внутри элемента #user_input
|
122 |
+
const userInput = document.querySelector('#user_input textarea');
|
123 |
+
// Ищем кнопку внутри #send_button
|
124 |
+
const sendButton = document.querySelector('#send_button button');
|
125 |
+
|
126 |
+
if (userInput && sendButton) {
|
127 |
+
userInput.addEventListener('keydown', function(e) {
|
128 |
+
if (e.key === 'Enter') {
|
129 |
+
if (e.ctrlKey) {
|
130 |
+
// Ctrl+Enter => вставляем новую строку
|
131 |
+
e.preventDefault();
|
132 |
+
const start = userInput.selectionStart;
|
133 |
+
const end = userInput.selectionEnd;
|
134 |
+
userInput.value = userInput.value.substring(0, start)
|
135 |
+
+ "\\n"
|
136 |
+
+ userInput.value.substring(end);
|
137 |
+
// Устанавливаем курсор ниже
|
138 |
+
userInput.selectionStart = userInput.selectionEnd = start + 1;
|
139 |
+
} else {
|
140 |
+
// Просто Enter => отправляем
|
141 |
+
e.preventDefault();
|
142 |
+
sendButton.click();
|
143 |
+
}
|
144 |
+
}
|
145 |
+
});
|
146 |
+
}
|
147 |
+
});
|
148 |
+
</script>
|
149 |
+
"""
|
150 |
+
|
151 |
+
# Добавляем HTML-блок с нашим кастомным JS
|
152 |
+
gr.HTML(custom_js)
|
153 |
|
154 |
+
# Запуск приложения
|
155 |
if __name__ == "__main__":
|
156 |
demo.launch(server_name="0.0.0.0", server_port=7860)
|