Update app.py
Browse files
app.py
CHANGED
@@ -1,23 +1,24 @@
|
|
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":
|
14 |
-
|
15 |
|
16 |
-
Возвращает (new_history, new_history, "")
|
17 |
-
- new_history — обновлённая история для Chatbot
|
18 |
-
- "" —
|
19 |
"""
|
20 |
-
|
|
|
21 |
messages = []
|
22 |
for msg in history:
|
23 |
messages.append({"role": msg["role"], "content": msg["content"]})
|
@@ -25,7 +26,7 @@ def chat_with_deepseek(user_message, history):
|
|
25 |
# Добавляем текущее сообщение пользователя
|
26 |
messages.append({"role": "user", "content": user_message})
|
27 |
|
28 |
-
#
|
29 |
try:
|
30 |
response = client.chat.completions.create(
|
31 |
model="deepseek-reasoner",
|
@@ -35,14 +36,16 @@ def chat_with_deepseek(user_message, history):
|
|
35 |
except Exception as e:
|
36 |
assistant_content = f"Ошибка при обращении к API: {e}"
|
37 |
|
38 |
-
#
|
39 |
new_history = history + [
|
40 |
{"role": "user", "content": user_message},
|
41 |
{"role": "assistant", "content": assistant_content}
|
42 |
]
|
43 |
-
|
|
|
44 |
|
45 |
with gr.Blocks(
|
|
|
46 |
theme=gr.themes.Base(
|
47 |
primary_hue="slate",
|
48 |
secondary_hue="blue",
|
@@ -50,8 +53,8 @@ with gr.Blocks(
|
|
50 |
text_size="md",
|
51 |
font=["Arial", "sans-serif"]
|
52 |
),
|
|
|
53 |
css="""
|
54 |
-
/* Фон приложения чёрный */
|
55 |
body {
|
56 |
background-color: #000000 !important;
|
57 |
}
|
@@ -61,23 +64,21 @@ with gr.Blocks(
|
|
61 |
.gradio-container {
|
62 |
color: #ffffff !important;
|
63 |
}
|
64 |
-
/* Фон области чата */
|
65 |
#chatbot {
|
66 |
background-color: #111111 !important;
|
67 |
}
|
68 |
"""
|
69 |
) as demo:
|
70 |
|
71 |
-
#
|
72 |
gr.HTML("""
|
73 |
<h1 style="text-align:center; color:#ffffff;">Чат с deepseek-reasoner</h1>
|
74 |
<p style="text-align:center; color:#cccccc;">
|
75 |
-
|
76 |
-
<strong>Ctrl+Enter</strong> — новая строка
|
77 |
</p>
|
78 |
""")
|
79 |
|
80 |
-
# Компонент
|
81 |
chatbot = gr.Chatbot(
|
82 |
label="Диалог",
|
83 |
height=400,
|
@@ -85,7 +86,7 @@ with gr.Blocks(
|
|
85 |
elem_id="chatbot"
|
86 |
)
|
87 |
|
88 |
-
#
|
89 |
msg = gr.Textbox(
|
90 |
label="Ваш вопрос",
|
91 |
placeholder="Введите сообщение...",
|
@@ -93,13 +94,17 @@ with gr.Blocks(
|
|
93 |
elem_id="user_input"
|
94 |
)
|
95 |
|
96 |
-
# Скрытая
|
97 |
-
hidden_send_btn = gr.Button(
|
|
|
|
|
|
|
|
|
98 |
|
99 |
-
# Состояние
|
100 |
state = gr.State([])
|
101 |
|
102 |
-
# При клике на кнопку
|
103 |
hidden_send_btn.click(
|
104 |
fn=chat_with_deepseek,
|
105 |
inputs=[msg, state],
|
@@ -107,7 +112,9 @@ with gr.Blocks(
|
|
107 |
scroll_to_output=True
|
108 |
)
|
109 |
|
110 |
-
# JS
|
|
|
|
|
111 |
custom_js = """
|
112 |
<script>
|
113 |
document.addEventListener('DOMContentLoaded', function() {
|
@@ -117,14 +124,17 @@ with gr.Blocks(
|
|
117 |
if (userInput && sendButton) {
|
118 |
userInput.addEventListener('keydown', function(e) {
|
119 |
if (e.key === 'Enter') {
|
|
|
120 |
if (e.ctrlKey) {
|
|
|
121 |
e.preventDefault();
|
122 |
const start = userInput.selectionStart;
|
123 |
const end = userInput.selectionEnd;
|
124 |
-
userInput.value = userInput.value.substring(0, start) + "\\n"
|
125 |
+ userInput.value.substring(end);
|
126 |
userInput.selectionStart = userInput.selectionEnd = start + 1;
|
127 |
} else {
|
|
|
128 |
e.preventDefault();
|
129 |
sendButton.click();
|
130 |
}
|
|
|
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":"user"|"assistant","content":"..."}],
|
14 |
+
формат Gradio Chatbot (type="messages").
|
15 |
|
16 |
+
Возвращает (new_history, new_history, ""):
|
17 |
+
- new_history — обновлённая история для Chatbot
|
18 |
+
- "" — чтобы очистить поле ввода
|
19 |
"""
|
20 |
+
|
21 |
+
# Преобразуем history в формат messages для DeepSeek
|
22 |
messages = []
|
23 |
for msg in history:
|
24 |
messages.append({"role": msg["role"], "content": msg["content"]})
|
|
|
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 |
+
return new_history, new_history, ""
|
46 |
|
47 |
with gr.Blocks(
|
48 |
+
# Тема Gradio:
|
49 |
theme=gr.themes.Base(
|
50 |
primary_hue="slate",
|
51 |
secondary_hue="blue",
|
|
|
53 |
text_size="md",
|
54 |
font=["Arial", "sans-serif"]
|
55 |
),
|
56 |
+
# CSS для чёрного оформления
|
57 |
css="""
|
|
|
58 |
body {
|
59 |
background-color: #000000 !important;
|
60 |
}
|
|
|
64 |
.gradio-container {
|
65 |
color: #ffffff !important;
|
66 |
}
|
|
|
67 |
#chatbot {
|
68 |
background-color: #111111 !important;
|
69 |
}
|
70 |
"""
|
71 |
) as demo:
|
72 |
|
73 |
+
# Шапка
|
74 |
gr.HTML("""
|
75 |
<h1 style="text-align:center; color:#ffffff;">Чат с deepseek-reasoner</h1>
|
76 |
<p style="text-align:center; color:#cccccc;">
|
77 |
+
<b>Enter</b> — отправить; <b>Ctrl+Enter</b> — новая строка.
|
|
|
78 |
</p>
|
79 |
""")
|
80 |
|
81 |
+
# Компонент чата, хранящего сообщения в формате "messages"
|
82 |
chatbot = gr.Chatbot(
|
83 |
label="Диалог",
|
84 |
height=400,
|
|
|
86 |
elem_id="chatbot"
|
87 |
)
|
88 |
|
89 |
+
# Текстовое поле (2 строки по умолчанию)
|
90 |
msg = gr.Textbox(
|
91 |
label="Ваш вопрос",
|
92 |
placeholder="Введите сообщение...",
|
|
|
94 |
elem_id="user_input"
|
95 |
)
|
96 |
|
97 |
+
# Скрытая кнопка (не показываем в UI), которую мы будем "нажимать" программно
|
98 |
+
hidden_send_btn = gr.Button(
|
99 |
+
"Скрытая кнопка",
|
100 |
+
visible=False,
|
101 |
+
elem_id="hidden_send_btn"
|
102 |
+
)
|
103 |
|
104 |
+
# Состояние для истории чата
|
105 |
state = gr.State([])
|
106 |
|
107 |
+
# При клике на кнопку (вызванной JS), отправляем сообщение
|
108 |
hidden_send_btn.click(
|
109 |
fn=chat_with_deepseek,
|
110 |
inputs=[msg, state],
|
|
|
112 |
scroll_to_output=True
|
113 |
)
|
114 |
|
115 |
+
# Подключаем JS, чтобы:
|
116 |
+
# - Enter => нажимать на скрытую кнопку (отправлять сообщение)
|
117 |
+
# - Ctrl+Enter => перенос строки
|
118 |
custom_js = """
|
119 |
<script>
|
120 |
document.addEventListener('DOMContentLoaded', function() {
|
|
|
124 |
if (userInput && sendButton) {
|
125 |
userInput.addEventListener('keydown', function(e) {
|
126 |
if (e.key === 'Enter') {
|
127 |
+
// Если нажали Enter
|
128 |
if (e.ctrlKey) {
|
129 |
+
// Ctrl+Enter => перенос строки
|
130 |
e.preventDefault();
|
131 |
const start = userInput.selectionStart;
|
132 |
const end = userInput.selectionEnd;
|
133 |
+
userInput.value = userInput.value.substring(0, start) + "\\n"
|
134 |
+ userInput.value.substring(end);
|
135 |
userInput.selectionStart = userInput.selectionEnd = start + 1;
|
136 |
} else {
|
137 |
+
// Enter => отправка
|
138 |
e.preventDefault();
|
139 |
sendButton.click();
|
140 |
}
|