Yermek68 commited on
Commit
bc2af3d
·
verified ·
1 Parent(s): 8ca8c0d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +18 -13
app.py CHANGED
@@ -11,11 +11,11 @@ from core.learning import analyze_user_input, adapt_answer
11
  from core.model_selector import choose_model
12
 
13
  # ==============================
14
- # 🔐 Токен авторизации Hugging Face
15
  # ==============================
16
  HF_TOKEN = os.getenv("HF_TOKEN")
17
  if not HF_TOKEN:
18
- print("⚠️ Токен Hugging Face не найден. Добавь его в Settings → Secrets → HF_TOKEN")
19
 
20
  # ==============================
21
  # 📊 Инициализация панели и логов
@@ -25,18 +25,22 @@ LOG_FILE = "logs/history.csv"
25
  os.makedirs("logs", exist_ok=True)
26
 
27
  # ==============================
28
- # ⚙️ Основная логика агента
29
  # ==============================
30
  def generate_response(user_input):
31
  try:
32
  start = time.time()
33
 
34
- # 1️⃣ Анализируем запрос и выбираем модель
35
  prefs = analyze_user_input(user_input)
36
  model_id = choose_model(user_input)
37
 
38
- # 2️⃣ Подключаем официальный InferenceClient
39
- client = InferenceClient(model=model_id, token=HF_TOKEN)
 
 
 
 
40
 
41
  # 3️⃣ Генерация текста
42
  result = client.text_generation(
@@ -50,7 +54,7 @@ def generate_response(user_input):
50
  improved = improve_answer(result)
51
  personalized = adapt_answer(improved)
52
 
53
- # 5️⃣ Обновляем память и контекст
54
  update_memory(user_input, personalized)
55
  context = summarize_context()
56
 
@@ -58,14 +62,14 @@ def generate_response(user_input):
58
  response_time = round(time.time() - start, 2)
59
  dashboard.log_request(model_id, prefs["category"], response_time)
60
 
61
- # 7️⃣ Сохраняем историю в CSV
62
  log_entry = {
63
  "time": time.strftime("%Y-%m-%d %H:%M:%S"),
64
  "model": model_id,
65
  "category": prefs["category"],
66
  "response_time": response_time,
67
  "prompt": user_input,
68
- "response": personalized[:2000]
69
  }
70
  df = pd.DataFrame([log_entry])
71
  if os.path.exists(LOG_FILE):
@@ -73,7 +77,7 @@ def generate_response(user_input):
73
  else:
74
  df.to_csv(LOG_FILE, index=False)
75
 
76
- # 8️⃣ Финальный вывод
77
  summary = (
78
  f"🧠 **Модель:** `{model_id}`\n"
79
  f"🧩 **Тип запроса:** {prefs['category']}\n"
@@ -90,7 +94,7 @@ def generate_response(user_input):
90
 
91
 
92
  # ==============================
93
- # 📈 Отображение Dashboard
94
  # ==============================
95
  def show_dashboard():
96
  metrics_text, df = dashboard.dashboard_ui()
@@ -100,8 +104,8 @@ def show_dashboard():
100
  # ==============================
101
  # 🎨 Интерфейс Gradio
102
  # ==============================
103
- with gr.Blocks(title="Eroha AgentAPI v5.2Guru Edition", theme="soft") as app:
104
- gr.Markdown("# 🤖 Eroha AgentAPI v5.2 — Guru Edition")
105
  gr.Markdown("**Автоматический интеллект + самообучение + аналитика + кэширование истории** 🌱")
106
 
107
  with gr.Tab("💬 Agent Chat"):
@@ -120,3 +124,4 @@ with gr.Blocks(title="Eroha AgentAPI v5.2 — Guru Edition", theme="soft") as ap
120
  refresh.click(show_dashboard, outputs=[metrics, log_table])
121
 
122
  app.launch(server_name="0.0.0.0", server_port=7860)
 
 
11
  from core.model_selector import choose_model
12
 
13
  # ==============================
14
+ # 🔐 Токен Hugging Face
15
  # ==============================
16
  HF_TOKEN = os.getenv("HF_TOKEN")
17
  if not HF_TOKEN:
18
+ print("⚠️ Токен Hugging Face не найден. Добавь его в Settings → Variables and secrets → HF_TOKEN")
19
 
20
  # ==============================
21
  # 📊 Инициализация панели и логов
 
25
  os.makedirs("logs", exist_ok=True)
26
 
27
  # ==============================
28
+ # ⚙️ Основная функция агента
29
  # ==============================
30
  def generate_response(user_input):
31
  try:
32
  start = time.time()
33
 
34
+ # 1️⃣ Анализируем запрос
35
  prefs = analyze_user_input(user_input)
36
  model_id = choose_model(user_input)
37
 
38
+ # 2️⃣ Подключаем официальный Router API вручную
39
+ client = InferenceClient(
40
+ model=model_id,
41
+ token=HF_TOKEN,
42
+ api_url="https://router.huggingface.co" # 🔧 Новый API, без 410 ошибок
43
+ )
44
 
45
  # 3️⃣ Генерация текста
46
  result = client.text_generation(
 
54
  improved = improve_answer(result)
55
  personalized = adapt_answer(improved)
56
 
57
+ # 5️⃣ Обновляем память
58
  update_memory(user_input, personalized)
59
  context = summarize_context()
60
 
 
62
  response_time = round(time.time() - start, 2)
63
  dashboard.log_request(model_id, prefs["category"], response_time)
64
 
65
+ # 7️⃣ Логирование истории
66
  log_entry = {
67
  "time": time.strftime("%Y-%m-%d %H:%M:%S"),
68
  "model": model_id,
69
  "category": prefs["category"],
70
  "response_time": response_time,
71
  "prompt": user_input,
72
+ "response": personalized[:2000],
73
  }
74
  df = pd.DataFrame([log_entry])
75
  if os.path.exists(LOG_FILE):
 
77
  else:
78
  df.to_csv(LOG_FILE, index=False)
79
 
80
+ # 8️⃣ Формирование финального ответа
81
  summary = (
82
  f"🧠 **Модель:** `{model_id}`\n"
83
  f"🧩 **Тип запроса:** {prefs['category']}\n"
 
94
 
95
 
96
  # ==============================
97
+ # 📈 Dashboard отображение
98
  # ==============================
99
  def show_dashboard():
100
  metrics_text, df = dashboard.dashboard_ui()
 
104
  # ==============================
105
  # 🎨 Интерфейс Gradio
106
  # ==============================
107
+ with gr.Blocks(title="Eroha AgentAPI v5.3Router Fixed", theme="soft") as app:
108
+ gr.Markdown("# 🤖 Eroha AgentAPI v5.3 — Guru Edition (Router API Fixed)")
109
  gr.Markdown("**Автоматический интеллект + самообучение + аналитика + кэширование истории** 🌱")
110
 
111
  with gr.Tab("💬 Agent Chat"):
 
124
  refresh.click(show_dashboard, outputs=[metrics, log_table])
125
 
126
  app.launch(server_name="0.0.0.0", server_port=7860)
127
+