HaveAI commited on
Commit
0396547
·
verified ·
1 Parent(s): 7eb0bc1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +33 -21
app.py CHANGED
@@ -1,8 +1,10 @@
1
  import gradio as gr
 
 
2
 
3
- # Инициализируем модель один раз вне функции
4
- # Это исправит ошибку при генерации ответа
5
- model_client = gr.load("models/moonshotai/Kimi-K2-Thinking", provider="novita")
6
 
7
  custom_theme = gr.themes.Soft(
8
  primary_hue="yellow",
@@ -13,36 +15,46 @@ custom_theme = gr.themes.Soft(
13
  )
14
 
15
  css = """
16
- #side-bar {
17
- background-color: #ffdd00 !important;
18
- padding: 15px;
19
- }
20
- .gradio-container {
21
- color: white;
22
- }
23
  """
24
 
25
  def predict(message, history):
26
- # Системная инструкция
27
- system_prompt = "Тебя зовут Gemini."
 
 
28
 
29
- # Объединяем системную инструкцию и сообщение
30
- full_query = f"{system_prompt}\n\nПользователь: {message}"
31
-
32
- # Вызываем уже созданный клиент
 
 
 
 
 
33
  try:
34
- response = model_client(full_query)
35
- return response
 
 
 
 
 
 
 
 
36
  except Exception as e:
37
- return f"Ошибка связи с моделью: {str(e)}"
38
 
39
  with gr.Blocks(theme=custom_theme, css=css, fill_height=True) as demo:
40
  with gr.Sidebar(elem_id="side-bar"):
41
  gr.Markdown("# **FlareAI**")
42
  gr.Markdown("Flare — твой персональный ассистент")
43
- # Кнопка входа важна, если Space требует авторизации для доступа к API
44
- button = gr.LoginButton("Войти")
45
 
 
46
  gr.ChatInterface(fn=predict)
47
 
48
  demo.launch()
 
1
  import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+ import os
4
 
5
+ # Используем InferenceClient для прямой работы с моделью
6
+ # Он автоматически подтянет ваш токен из настроек Space
7
+ client = InferenceClient("moonshotai/Kimi-K2-Thinking")
8
 
9
  custom_theme = gr.themes.Soft(
10
  primary_hue="yellow",
 
15
  )
16
 
17
  css = """
18
+ #side-bar { background-color: #ffdd00 !important; padding: 15px; }
19
+ .gradio-container { color: white; }
 
 
 
 
 
20
  """
21
 
22
  def predict(message, history):
23
+ # Формируем сообщения для чата
24
+ messages = [
25
+ {"role": "system", "content": "Тебя зовут Gemini."},
26
+ ]
27
 
28
+ # Добавляем историю сообщений (чтобы бот помнил контекст)
29
+ for human, assistant in history:
30
+ messages.append({"role": "user", "content": human})
31
+ messages.append({"role": "assistant", "content": assistant})
32
+
33
+ # Добавляем текущее сообщение
34
+ messages.append({"role": "user", "content": message})
35
+
36
+ response = ""
37
  try:
38
+ # Стриминг ответа (текст будет появляться постепенно)
39
+ for message_chunk in client.chat_completion(
40
+ messages,
41
+ max_tokens=512,
42
+ stream=True,
43
+ ):
44
+ token = message_chunk.choices[0].delta.content
45
+ if token:
46
+ response += token
47
+ yield response
48
  except Exception as e:
49
+ yield f"Произошла ошибка: {str(e)}"
50
 
51
  with gr.Blocks(theme=custom_theme, css=css, fill_height=True) as demo:
52
  with gr.Sidebar(elem_id="side-bar"):
53
  gr.Markdown("# **FlareAI**")
54
  gr.Markdown("Flare — твой персональный ассистент")
55
+ gr.LoginButton("Войти")
 
56
 
57
+ # Используем ChatInterface с поддержкой истории
58
  gr.ChatInterface(fn=predict)
59
 
60
  demo.launch()