Yermek68 commited on
Commit
ae12180
·
verified ·
1 Parent(s): 106b57a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +49 -19
app.py CHANGED
@@ -1,21 +1,28 @@
1
  import gradio as gr
2
  import requests
 
 
3
  from core.intelligence import update_memory, summarize_context
4
  from core.selfcheck import evaluate_answer, improve_answer
5
  from core.learning import analyze_user_input, adapt_answer
6
- from core.model_selector import choose_model
7
 
8
- # Укажи токен, если хочешь иначе можно без него
9
- HEADERS = {"Authorization": "Bearer hf_your_token"} # можно удалить, если токен не используется
10
 
 
 
 
11
  def generate_response(user_input):
12
  try:
13
- # 1️⃣ Анализ стиля и выбор модели
 
 
14
  prefs = analyze_user_input(user_input)
15
  model_id = choose_model(user_input)
16
  api_url = f"https://api-inference.huggingface.co/models/{model_id}"
17
 
18
- # 2️⃣ Запрос к модели
19
  payload = {"inputs": user_input, "parameters": {"max_new_tokens": 600, "temperature": 0.7}}
20
  response = requests.post(api_url, headers=HEADERS, json=payload)
21
 
@@ -25,21 +32,27 @@ def generate_response(user_input):
25
  result = response.json()
26
  base_output = result[0]["generated_text"] if isinstance(result, list) else result
27
 
28
- # 3️⃣ Самоанализ и улучшение
29
  check = evaluate_answer(base_output)
30
  improved = improve_answer(base_output)
31
 
32
- # 4️⃣ Адаптация под пользователя
33
  personalized = adapt_answer(improved)
34
 
35
- # 5️⃣ Обновление памяти
36
  update_memory(user_input, personalized)
37
  context = summarize_context()
38
 
39
- # 6️⃣ Формирование вывода
 
 
 
 
40
  summary = (
41
  f"🧠 Модель: `{model_id}`\n"
42
- f"🧩 Самоанализ: {check['result']}\n"
 
 
43
  f"{'; '.join(check['feedback']) if check['feedback'] else '✅ Всё отлично'}\n\n"
44
  f"{context}"
45
  )
@@ -50,15 +63,32 @@ def generate_response(user_input):
50
  return f"❌ Ошибка: {str(e)}"
51
 
52
 
53
- # === Интерфейс ===
54
- with gr.Blocks(title="Eroha AgentAPI v5.0 — Auto Model Switch") as demo:
55
- gr.Markdown("# 🤖 Eroha AgentAPI v5.0 — Auto Model Switch + Self-Learning")
56
- gr.Markdown("Агент сам выбирает оптимальную модель Hugging Face и адаптирует ответы под твой стиль 🧠")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
 
58
- user_input = gr.Textbox(label="Введите запрос", placeholder="Например: объясни квантовую физику или напиши стих...")
59
- output_box = gr.Textbox(label="Ответ", lines=15)
60
- submit_btn = gr.Button("🚀 Запросить")
 
 
61
 
62
- submit_btn.click(fn=generate_response, inputs=user_input, outputs=output_box)
 
63
 
64
- demo.launch()
 
1
  import gradio as gr
2
  import requests
3
+ import time
4
+ from core.dashboard import ErohaDashboard
5
  from core.intelligence import update_memory, summarize_context
6
  from core.selfcheck import evaluate_answer, improve_answer
7
  from core.learning import analyze_user_input, adapt_answer
8
+ from core.model_selector import choose_model, select_model
9
 
10
+ # 🔐 Если токен есть, вставь сюда
11
+ HEADERS = {"Authorization": "Bearer hf_your_token"} # можно убрать, если не нужен
12
 
13
+ dashboard = ErohaDashboard()
14
+
15
+ # === 1️⃣ Основная функция агента ===
16
  def generate_response(user_input):
17
  try:
18
+ start = time.time()
19
+
20
+ # Анализ предпочтений и выбор модели
21
  prefs = analyze_user_input(user_input)
22
  model_id = choose_model(user_input)
23
  api_url = f"https://api-inference.huggingface.co/models/{model_id}"
24
 
25
+ # Запрос к API
26
  payload = {"inputs": user_input, "parameters": {"max_new_tokens": 600, "temperature": 0.7}}
27
  response = requests.post(api_url, headers=HEADERS, json=payload)
28
 
 
32
  result = response.json()
33
  base_output = result[0]["generated_text"] if isinstance(result, list) else result
34
 
35
+ # Самоанализ и улучшение
36
  check = evaluate_answer(base_output)
37
  improved = improve_answer(base_output)
38
 
39
+ # Адаптация под пользователя
40
  personalized = adapt_answer(improved)
41
 
42
+ # Обновление памяти
43
  update_memory(user_input, personalized)
44
  context = summarize_context()
45
 
46
+ # Метрики
47
+ response_time = round(time.time() - start, 2)
48
+ dashboard.log_request(model_id, prefs["category"], response_time)
49
+
50
+ # Формирование ответа
51
  summary = (
52
  f"🧠 Модель: `{model_id}`\n"
53
+ f"🧩 Тип запроса: {prefs['category']}\n"
54
+ f"⚡ Время отклика: {response_time} сек\n"
55
+ f"🔍 Самоанализ: {check['result']}\n"
56
  f"{'; '.join(check['feedback']) if check['feedback'] else '✅ Всё отлично'}\n\n"
57
  f"{context}"
58
  )
 
63
  return f"❌ Ошибка: {str(e)}"
64
 
65
 
66
+ # === 2️⃣ Функции Dashboard ===
67
+ def show_dashboard():
68
+ metrics_text, df = dashboard.dashboard_ui()
69
+ return metrics_text, df
70
+
71
+
72
+ # === 3️⃣ Интерфейс ===
73
+ with gr.Blocks(title="Eroha AgentAPI v5.0 — Guru Edition", theme="soft") as app:
74
+ gr.Markdown("# 🤖 Eroha AgentAPI v5.0 — Guru Edition")
75
+ gr.Markdown("*Автоматический интеллект + самообучение + аналитика 🧠*")
76
+
77
+ with gr.Tab("💬 Agent Chat"):
78
+ user_input = gr.Textbox(
79
+ label="Введите запрос",
80
+ placeholder="Например: Объясни, как работает квантовая суперпозиция или напиши код..."
81
+ )
82
+ output_box = gr.Textbox(label="Ответ", lines=15)
83
+ submit_btn = gr.Button("🚀 Отправить")
84
+ submit_btn.click(fn=generate_response, inputs=user_input, outputs=output_box)
85
 
86
+ with gr.Tab("📊 Dashboard"):
87
+ metrics = gr.Markdown(label="Общая статистика")
88
+ log_table = gr.Dataframe(headers=["time", "model", "type", "response_time"], label="История")
89
+ refresh = gr.Button("🔄 Обновить")
90
+ refresh.click(show_dashboard, outputs=[metrics, log_table])
91
 
92
+ # === 4️⃣ Запуск ===
93
+ app.launch(server_name="0.0.0.0", server_port=7860)
94