HaveAI commited on
Commit
2cd32e2
·
verified ·
1 Parent(s): 1615469

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +23 -33
app.py CHANGED
@@ -1,53 +1,43 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- # Прямое подключение к API
5
- # Если у тебя в Settings добавлен HF_TOKEN, клиент подтянет его сам
6
- client = InferenceClient("moonshotai/Kimi-K2-Thinking")
7
 
 
 
8
  def predict(message, history):
9
- # Формируем промпт так, как любят современные модели
10
- messages = [{"role": "system", "content": "Тебя зовут Flare."}]
 
11
 
12
- for val in history:
13
- if val[0]: messages.append({"role": "user", "content": val[0]})
14
- if val[1]: messages.append({"role": "assistant", "content": val[1]})
15
-
16
- messages.append({"role": "user", "content": message})
17
-
18
- response = ""
19
  try:
20
- # Прямой вызов без посредников
21
- for msg in client.chat_completion(messages, max_tokens=1024, stream=True):
22
- token = msg.choices[0].delta.content
23
- if token:
24
- response += token
25
- yield response
 
 
26
  except Exception as e:
27
- yield f"Упс! Проблема с подключением: {str(e)}"
28
 
29
- # Настройка стиля
30
  custom_theme = gr.themes.Soft(
31
  primary_hue="yellow",
32
  secondary_hue="blue",
33
  ).set(
34
  body_background_fill="#0057b7",
35
  block_background_fill="#ffdd00",
36
- button_primary_background_fill="#ffdd00",
37
- block_label_text_color="#000000"
38
  )
39
 
40
- css = """
41
- .gradio-container { background-color: #0057b7 !important; }
42
- #side-info { background-color: #ffdd00; padding: 10px; border-radius: 8px; color: black; }
43
- """
44
-
45
- with gr.Blocks(theme=custom_theme, css=css, fill_height=True) as demo:
46
- with gr.Sidebar(elem_id="side-info"):
47
  gr.Markdown("# **FlareAI**")
48
- gr.Markdown("Flare — твой персональный ассистент")
49
- gr.LoginButton("Войти в HF")
50
 
 
51
  gr.ChatInterface(fn=predict)
52
 
 
53
  demo.launch()
 
1
  import gradio as gr
 
 
 
 
 
2
 
3
+ # Самый простой и надежный способ вызова модели в Hugging Face Spaces
4
+ # Мы используем встроенный метод загрузки, который сам следит за сессиями
5
  def predict(message, history):
6
+ # Системный промпт приклеиваем к сообщению
7
+ # В этой модели это самый стабильный способ сохранить личность
8
+ prompt = f"System: Тебя зовут Gemini. Всегда представляйся как Gemini.\nUser: {message}"
9
 
10
+ # Прямой вызов через интерфейс API
11
+ # Если будет ошибка "list indices", мы её перехватим заранее
 
 
 
 
 
12
  try:
13
+ model = gr.load("models/moonshotai/Kimi-K2-Thinking", provider="novita")
14
+ response = model(prompt)
15
+
16
+ # Безопасное извлечение текста
17
+ if isinstance(response, list) and len(response) > 0:
18
+ res = response[0]
19
+ return res.get("generated_text", str(res)) if isinstance(res, dict) else str(res)
20
+ return str(response)
21
  except Exception as e:
22
+ return f"Сервер временно занят. Подожди 10 секунд и попробуй снова. (Ошибка: {str(e)})"
23
 
24
+ # Твой сине-желтый дизайн
25
  custom_theme = gr.themes.Soft(
26
  primary_hue="yellow",
27
  secondary_hue="blue",
28
  ).set(
29
  body_background_fill="#0057b7",
30
  block_background_fill="#ffdd00",
 
 
31
  )
32
 
33
+ with gr.Blocks(theme=custom_theme, fill_height=True) as demo:
34
+ with gr.Sidebar():
 
 
 
 
 
35
  gr.Markdown("# **FlareAI**")
36
+ gr.Markdown("Твой ассистент Gemini")
37
+ gr.LoginButton("Войти")
38
 
39
+ # Используем простую версию чата без сложных настроек
40
  gr.ChatInterface(fn=predict)
41
 
42
+ # Запускаем без лишних параметров, чтобы не было конфликтов с браузером
43
  demo.launch()