vortex123 commited on
Commit
4e3871a
·
verified ·
1 Parent(s): ff1324c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +48 -48
app.py CHANGED
@@ -1,60 +1,57 @@
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
- # Функция, которая будет вызываться при каждом новом сообщении
11
- # Она принимает текущее сообщение пользователя и "history" — историю чата
12
- # в формате Gradio (список кортежей).
13
  def chat_with_deepseek(user_message, history):
14
  """
15
- :param user_message: текст последнего сообщения от пользователя
16
- :param history: список кортежей ([(user_msg, bot_msg), ...]),
17
- где хранится вся история переписки
18
- :return: обновлённая история с добавленным ответом от deepseek-reasoner
19
  """
20
 
21
- # Преобразуем history из формата Gradio в формат messages для DeepSeek
22
  messages = []
23
- for user_msg, bot_msg in history:
24
- if user_msg:
25
- messages.append({"role": "user", "content": user_msg})
26
- if bot_msg:
27
- messages.append({"role": "assistant", "content": bot_msg})
28
-
29
- # Добавляем новое пользовательское сообщение
30
  messages.append({"role": "user", "content": user_message})
31
-
32
- # Обращаемся к deepseek-reasoner, передавая всю историю
33
  try:
34
  response = client.chat.completions.create(
35
  model="deepseek-reasoner",
36
  messages=messages
37
  )
38
- bot_reply = response.choices[0].message.content
39
  except Exception as e:
40
- bot_reply = f"Ошибка при обращении к API: {str(e)}"
 
 
 
 
 
 
 
41
 
42
- # Возвращаем историю, дополнив её ответом бота
43
- history.append((user_message, bot_reply))
44
- return history, history
45
 
46
- # Настраиваем интерфейс Gradio
47
- # - elem_id / css / theme позволяют стилизовать под "тёмный" чат
48
- # - "chatbot" виджет в Gradio уже отображает историю в виде «баблов»
49
  with gr.Blocks(
50
  theme=gr.themes.Base(
51
- primary_hue="slate", # оттенок для кнопок
52
- secondary_hue="blue", # оттенок для второстепенных элементов
53
- neutral_hue="slate",
54
  text_size="md",
55
  font=["Arial", "sans-serif"],
56
  ),
57
  css="""
 
58
  body {
59
  background-color: #111111 !important;
60
  }
@@ -64,44 +61,47 @@ with gr.Blocks(
64
  .gradio-container {
65
  color: #ffffff !important;
66
  }
67
- /* Дополнительные правки под темный фон */
68
- #chatbot {
69
- background-color: #222222 !important;
70
  }
71
  """) as demo:
72
 
73
  gr.Markdown(
74
- "<h1 style='text-align: center; color: #ffffff;'>Чат с deepseek-reasoner</h1>"
75
- "<p style='text-align: center; color: #bbbbbb;'>Тёмная тема, многошаговый диалог</p>"
76
  )
77
 
78
- # Компонент Chatbot для отображения диалога
79
- chatbot = gr.Chatbot(label="Диалог").style(height=400)
 
 
 
 
80
 
81
- # Поле для ввода текста
82
  msg = gr.Textbox(
83
  label="Ваш вопрос",
84
- placeholder="Напишите сообщение...",
85
  lines=3
86
  )
87
-
88
  # Кнопка отправки
89
  send_btn = gr.Button("Отправить", variant="primary")
90
 
91
- # state для хранения истории
92
- state = gr.State([]) # пустой список истории
 
93
 
94
- # Привязываем функцию chat_with_deepseek к нажатию кнопки "Отправить"
95
- # input: user_message (msg), history (state)
96
- # output: (chatbot, state) — обновлённая история чата
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
- # Также можно отправлять сообщение, нажав Enter в Textbox
105
  msg.submit(
106
  fn=chat_with_deepseek,
107
  inputs=[msg, state],
@@ -109,6 +109,6 @@ with gr.Blocks(
109
  scroll_to_output=True
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
+ # Функция обработки сообщения пользователя
 
 
11
  def chat_with_deepseek(user_message, history):
12
  """
13
+ user_message: текст последнего сообщения пользователя (str)
14
+ history: список словарей [{role:..., content:...}, ...]
15
+ Возвращает обновлённый history, дополненный сообщением от ассистента.
 
16
  """
17
 
18
+ # Собираем контекст для deepseek-reasoner
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",
30
  messages=messages
31
  )
32
+ assistant_content = response.choices[0].message.content
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
+ return new_history, new_history
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: #111111 !important;
57
  }
 
61
  .gradio-container {
62
  color: #ffffff !important;
63
  }
64
+ /* Фон самого чат-окна */
65
+ #chatbot {
66
+ background-color: #222222 !important;
67
  }
68
  """) as demo:
69
 
70
  gr.Markdown(
71
+ "<h1 style='text-align:center; color:#ffffff;'>Чат с deepseek-reasoner</h1>"
72
+ "<p style='text-align:center; color:#bbbbbb;'>Тёмная тема, многошаговый диалог</p>"
73
  )
74
 
75
+ # Chatbot в режиме 'messages', чтобы избежать предупреждения и работать с role/content
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=3
87
  )
88
+
89
  # Кнопка отправки
90
  send_btn = gr.Button("Отправить", variant="primary")
91
 
92
+ # Переменная состояний (история диалога) по умолчанию пустая
93
+ # Будет храниться в формате [{'role':'...', 'content':'...'}, ...]
94
+ state = gr.State([])
95
 
96
+ # Логика: при клике на кнопку вызываем chat_with_deepseek
 
 
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
+ # Также отправляем сообщение при нажатии Enter в msg
105
  msg.submit(
106
  fn=chat_with_deepseek,
107
  inputs=[msg, state],
 
109
  scroll_to_output=True
110
  )
111
 
112
+ # Запуск
113
  if __name__ == "__main__":
114
  demo.launch(server_name="0.0.0.0", server_port=7860)