yoshizen commited on
Commit
71c05d4
·
verified ·
1 Parent(s): d55317d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -325
app.py CHANGED
@@ -1,8 +1,3 @@
1
- """
2
- Улучшенный GAIA Agent с поддержкой кэширования ответов и исправленным полем agent_code
3
- """
4
-
5
-
6
  import os
7
  import json
8
  import time
@@ -10,188 +5,18 @@ import torch
10
  import requests
11
  import gradio as gr
12
  import pandas as pd
13
- from huggingface_hub import login
14
  from typing import List, Dict, Any, Optional, Union, Callable, Tuple
15
- from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
16
-
17
 
18
  # Константы
19
- CACHE_FILE = "gaia_answers_cache.json"
20
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
21
- MAX_RETRIES = 3 # Максимальное количество попыток отправки
22
- RETRY_DELAY = 5 # Секунды ожидания между попытками
23
-
24
- class EnhancedGAIAAgent:
25
- """
26
- Улучшенный агент для Hugging Face GAIA с поддержкой кэширования ответов
27
- """
28
-
29
- def __init__(self, model_name="google/flan-t5-base", use_cache=True):
30
- """
31
- Инициализация агента с моделью и кэшем
32
-
33
- Args:
34
- model_name: Название модели для загрузки
35
- use_cache: Использовать ли кэширование ответов
36
- """
37
- print(f"Initializing EnhancedGAIAAgent with model: {model_name}")
38
- self.model_name = model_name
39
- self.use_cache = use_cache
40
- self.cache = self._load_cache() if use_cache else {}
41
-
42
- # Загружаем модель и токенизатор
43
- print("Loading tokenizer...")
44
- self.tokenizer = AutoTokenizer.from_pretrained(model_name)
45
- print("Loading model...")
46
- self.model = AutoModelForSeq2SeqLM.from_pretrained(model_name)
47
- print("Model and tokenizer loaded successfully")
48
-
49
- def _load_cache(self) -> Dict[str, str]:
50
- """
51
- Загружает кэш ответов из файла
52
-
53
- Returns:
54
- Dict[str, str]: Словарь с кэшированными ответами
55
- """
56
- if os.path.exists(CACHE_FILE):
57
- try:
58
- with open(CACHE_FILE, 'r', encoding='utf-8') as f:
59
- print(f"Loading cache from {CACHE_FILE}")
60
- return json.load(f)
61
- except Exception as e:
62
- print(f"Error loading cache: {e}")
63
- return {}
64
- else:
65
- print(f"Cache file {CACHE_FILE} not found, creating new cache")
66
- return {}
67
-
68
- def _save_cache(self) -> None:
69
- """
70
- Сохраняет кэш ответов в файл
71
- """
72
- try:
73
- with open(CACHE_FILE, 'w', encoding='utf-8') as f:
74
- json.dump(self.cache, f, ensure_ascii=False, indent=2)
75
- print(f"Cache saved to {CACHE_FILE}")
76
- except Exception as e:
77
- print(f"Error saving cache: {e}")
78
-
79
- def _classify_question(self, question: str) -> str:
80
- """
81
- Классифицирует вопрос по типу для лучшего форматирования ответа
82
-
83
- Args:
84
- question: Текст вопроса
85
-
86
- Returns:
87
- str: Тип вопроса (factual, calculation, list, date_time, etc.)
88
- """
89
- # Простая эвристическая классификация
90
- question_lower = question.lower()
91
-
92
- if any(word in question_lower for word in ["calculate", "sum", "product", "divide", "multiply", "add", "subtract", "how many"]):
93
- return "calculation"
94
- elif any(word in question_lower for word in ["list", "enumerate", "items", "elements"]):
95
- return "list"
96
- elif any(word in question_lower for word in ["date", "time", "day", "month", "year", "when"]):
97
- return "date_time"
98
- else:
99
- return "factual"
100
-
101
- def _format_answer(self, raw_answer: str, question_type: str) -> str:
102
- """
103
- Форматирует ответ в соответствии с типом вопроса
104
-
105
- Args:
106
- raw_answer: Необработанный ответ от модели
107
- question_type: Тип вопроса
108
-
109
- Returns:
110
- str: Отформатированный ответ
111
- """
112
- # Удаляем лишние пробелы и переносы строк
113
- answer = raw_answer.strip()
114
-
115
- # Удаляем префиксы, которые часто добавляет модель
116
- prefixes = ["Answer:", "The answer is:", "I think", "I believe", "According to", "Based on"]
117
- for prefix in prefixes:
118
- if answer.startswith(prefix):
119
- answer = answer[len(prefix):].strip()
120
-
121
- # Специфическ��е форматирование в зависимости от типа вопроса
122
- if question_type == "calculation":
123
- # Для числовых ответов удаляем лишний текст
124
- # Оставляем только числа, если они есть
125
- import re
126
- numbers = re.findall(r'-?\d+\.?\d*', answer)
127
- if numbers:
128
- answer = numbers[0]
129
- elif question_type == "list":
130
- # Для списков убеждаемся, что элементы разделены запятыми
131
- if "," not in answer and " " in answer:
132
- items = [item.strip() for item in answer.split() if item.strip()]
133
- answer = ", ".join(items)
134
-
135
- return answer
136
-
137
- def __call__(self, question: str, task_id: Optional[str] = None) -> str:
138
- """
139
- Обрабатывает вопрос и возвращает ответ
140
-
141
- Args:
142
- question: Текст вопроса
143
- task_id: Идентификатор задачи (опционально)
144
-
145
- Returns:
146
- str: Ответ в формате JSON с ключом final_answer
147
- """
148
- # Создаем ключ для кэша (используем task_id, если доступен)
149
- cache_key = task_id if task_id else question
150
-
151
- # Проверяем наличие ответа в кэше
152
- if self.use_cache and cache_key in self.cache:
153
- print(f"Cache hit for question: {question[:50]}...")
154
- return self.cache[cache_key]
155
-
156
- # Классифицируем вопрос
157
- question_type = self._classify_question(question)
158
- print(f"Processing question: {question[:100]}...")
159
- print(f"Classified as: {question_type}")
160
-
161
- try:
162
- # Генерируем ответ с помощью модели
163
- inputs = self.tokenizer(question, return_tensors="pt")
164
- outputs = self.model.generate(**inputs, max_length=100)
165
- raw_answer = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
166
-
167
- # Форматируем ответ
168
- formatted_answer = self._format_answer(raw_answer, question_type)
169
-
170
- # Формируем JSON-ответ
171
- result = {"final_answer": formatted_answer}
172
- json_response = json.dumps(result)
173
-
174
- # Сохраняем в кэш
175
- if self.use_cache:
176
- self.cache[cache_key] = json_response
177
- self._save_cache()
178
-
179
- return json_response
180
-
181
- except Exception as e:
182
- error_msg = f"Error generating answer: {e}"
183
- print(error_msg)
184
- return json.dumps({"final_answer": f"AGENT ERROR: {e}"})
185
-
186
 
187
  class EvaluationRunner:
188
- """
189
- Обрабатывает процесс оценки: получение вопросов, запуск агента,
190
- и отправку ответов на сервер оценки.
191
- """
192
 
193
  def __init__(self, api_url=DEFAULT_API_URL):
194
- """Инициализация с API endpoints."""
195
  self.api_url = api_url
196
  self.questions_url = f"{api_url}/questions"
197
  self.submit_url = f"{api_url}/submit"
@@ -202,14 +27,7 @@ class EvaluationRunner:
202
  def run_evaluation(self,
203
  agent: Callable[[str], str],
204
  username: str,
205
- agent_code_url: str) -> tuple[str, pd.DataFrame]:
206
- """
207
- Запускает полный процесс оценки:
208
- 1. Получает вопросы
209
- 2. Запускает агента на всех вопросах
210
- 3. Отправляет ответы
211
- 4. Возвращает результаты
212
- """
213
  # Получаем вопросы
214
  questions_data = self._fetch_questions()
215
  if isinstance(questions_data, str): # Сообщение об ошибке
@@ -220,49 +38,34 @@ class EvaluationRunner:
220
  if not answers_payload:
221
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
222
 
223
- # Отправляем ответы с логикой повторных попыток
224
- submission_result = self._submit_answers(username, agent_code_url, answers_payload)
 
 
 
 
225
 
226
- # Возвращаем результаты
227
  return submission_result, pd.DataFrame(results_log)
228
 
229
  def _fetch_questions(self) -> Union[List[Dict[str, Any]], str]:
230
- """Получает вопросы с сервера оценки."""
231
- print(f"Fetching questions from: {self.questions_url}")
232
  try:
233
  response = requests.get(self.questions_url, timeout=15)
234
  response.raise_for_status()
235
  questions_data = response.json()
236
 
237
  if not questions_data:
238
- error_msg = "Fetched questions list is empty or invalid format."
239
- print(error_msg)
240
- return error_msg
241
 
242
  self.total_questions = len(questions_data)
243
  print(f"Successfully fetched {self.total_questions} questions.")
244
  return questions_data
245
 
246
- except requests.exceptions.RequestException as e:
247
- error_msg = f"Error fetching questions: {e}"
248
- print(error_msg)
249
- return error_msg
250
-
251
- except requests.exceptions.JSONDecodeError as e:
252
- error_msg = f"Error decoding JSON response from questions endpoint: {e}"
253
- print(error_msg)
254
- print(f"Response text: {response.text[:500]}")
255
- return error_msg
256
-
257
  except Exception as e:
258
- error_msg = f"An unexpected error occurred fetching questions: {e}"
259
- print(error_msg)
260
- return error_msg
261
 
262
  def _run_agent_on_questions(self,
263
  agent: Any,
264
  questions_data: List[Dict[str, Any]]) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
265
- """Запускает агента на всех вопросах и собирает результаты."""
266
  results_log = []
267
  answers_payload = []
268
 
@@ -272,17 +75,11 @@ class EvaluationRunner:
272
  question_text = item.get("question")
273
 
274
  if not task_id or question_text is None:
275
- print(f"Skipping item with missing task_id or question: {item}")
276
  continue
277
 
278
  try:
279
- # Вызываем агента с task_id для правильного форматирования
280
  json_response = agent(question_text, task_id)
281
-
282
- # Парсим JSON-ответ
283
  response_obj = json.loads(json_response)
284
-
285
- # Извлекаем final_answer для отправки
286
  submitted_answer = response_obj.get("final_answer", "")
287
 
288
  answers_payload.append({
@@ -297,7 +94,6 @@ class EvaluationRunner:
297
  "Full Response": json_response
298
  })
299
  except Exception as e:
300
- print(f"Error running agent on task {task_id}: {e}")
301
  results_log.append({
302
  "Task ID": task_id,
303
  "Question": question_text,
@@ -308,23 +104,19 @@ class EvaluationRunner:
308
 
309
  def _submit_answers(self,
310
  username: str,
311
- agent_code_url: str,
312
  answers_payload: List[Dict[str, Any]]) -> str:
313
- """Отправляет ответы на сервер оценки."""
314
- # ИСПРАВЛЕНО: Используем agent_code вместо agent_code_url
315
  submission_data = {
316
  "username": username.strip(),
317
- "agent_code": agent_code_url.strip(), # Имя переменной осталось прежним, но поле изменено
318
  "answers": answers_payload
319
  }
320
 
321
  print(f"Submitting {len(answers_payload)} answers to: {self.submit_url}")
322
- max_retries = MAX_RETRIES
323
- retry_delay = RETRY_DELAY
324
 
325
- for attempt in range(1, max_retries + 1):
326
  try:
327
- print(f"Submission attempt {attempt} of {max_retries}...")
328
  response = requests.post(
329
  self.submit_url,
330
  json=submission_data,
@@ -335,119 +127,56 @@ class EvaluationRunner:
335
 
336
  try:
337
  result = response.json()
338
- score = result.get("score")
339
- max_score = result.get("max_score")
340
-
341
- if score is not None and max_score is not None:
342
- self.correct_answers = score # Обновляем счетчик правильных ответов
343
- return f"Evaluation complete! Score: {score}/{max_score}"
344
- else:
345
- print(f"Received N/A results. Waiting {retry_delay} seconds before retry...")
346
- time.sleep(retry_delay)
347
- continue
348
-
349
- except requests.exceptions.JSONDecodeError:
350
- print(f"Submission attempt {attempt}: Response was not JSON. Response: {response.text}")
351
- if attempt < max_retries:
352
- print(f"Waiting {retry_delay} seconds before retry...")
353
- time.sleep(retry_delay)
354
- else:
355
- return f"Submission successful, but response was not JSON. Response: {response.text}"
356
 
357
- except requests.exceptions.RequestException as e:
358
  print(f"Submission attempt {attempt} failed: {e}")
359
- if attempt < max_retries:
360
- print(f"Waiting {retry_delay} seconds before retry...")
361
- time.sleep(retry_delay)
362
- else:
363
- return f"Error submitting answers after {max_retries} attempts: {e}"
364
 
365
- # Если мы здесь, все попытки не удались, но не вызвали исключений
366
- return "Submission Successful, but results are pending!"
367
 
368
  def _check_results(self, username: str) -> None:
369
- """Проверяет результаты для подсчета правильных ответов."""
370
  try:
371
  results_url = f"{self.results_url}?username={username}"
372
- print(f"Checking results at: {results_url}")
373
-
374
  response = requests.get(results_url, timeout=15)
375
  if response.status_code == 200:
376
- try:
377
- data = response.json()
378
- if isinstance(data, dict):
379
- score = data.get("score")
380
- if score is not None:
381
- self.correct_answers = int(score)
382
- print(f"✓ Correct answers: {self.correct_answers}/{self.total_questions}")
383
- else:
384
- print("Score information not available in results")
385
- else:
386
- print("Results data is not in expected format")
387
- except:
388
- print("Could not parse results JSON")
389
- else:
390
- print(f"Could not fetch results, status code: {response.status_code}")
391
  except Exception as e:
392
  print(f"Error checking results: {e}")
393
 
394
  def get_correct_answers_count(self) -> int:
395
- """Возвращает количество правильных ответов."""
396
  return self.correct_answers
397
 
398
  def get_total_questions_count(self) -> int:
399
- """Возвращает общее количество вопросов."""
400
  return self.total_questions
401
 
402
  def print_evaluation_summary(self, username: str) -> None:
403
- """Выводит сводку результатов оценки."""
404
  print("\n===== EVALUATION SUMMARY =====")
405
  print(f"User: {username}")
406
  print(f"Overall Score: {self.correct_answers}/{self.total_questions}")
407
- print(f"Correct Answers: {self.correct_answers}")
408
- print(f"Total Questions: {self.total_questions}")
409
- print(f"Accuracy: {(self.correct_answers / self.total_questions * 100) if self.total_questions > 0 else 0:.1f}%")
410
  print("=============================\n")
411
 
412
 
413
  def run_evaluation(username: str,
414
- agent_code_url: str,
415
- model_name: str = "google/flan-t5-small",
416
- use_cache: bool = True) -> Tuple[str, int, int, str, str, str]:
417
- """
418
- Запускает полный процесс оценки с поддержкой кэширования
419
-
420
- Args:
421
- username: Имя пользователя Hugging Face
422
- agent_code_url: URL кода агента (или код агента)
423
- model_name: Название модели для использования
424
- use_cache: Использовать ли кэширование ответов
425
-
426
- Returns:
427
- Tuple[str, int, int, str, str, str]: Кортеж и�� 6 значений:
428
- - result_text: Текстовый результат оценки
429
- - correct_answers: Количество правильных ответов
430
- - total_questions: Общее количество вопросов
431
- - elapsed_time: Время выполнения
432
- - results_url: URL для проверки результатов
433
- - cache_status: Статус кэширования
434
- """
435
  start_time = time.time()
436
 
437
- # Инициализируем агента с поддержкой кэширования
438
  agent = EnhancedGAIAAgent(model_name=model_name, use_cache=use_cache)
439
 
440
- # Инициализируем runner с исправленным полем agent_code
441
  runner = EvaluationRunner(api_url=DEFAULT_API_URL)
442
 
443
  # Запускаем оценку
444
- result, results_log = runner.run_evaluation(agent, username, agent_code_url)
445
-
446
- # Проверяем результаты
447
- runner._check_results(username)
448
-
449
- # Выводим сводку
450
- runner.print_evaluation_summary(username)
451
 
452
  # Вычисляем время выполнения
453
  elapsed_time = time.time() - start_time
@@ -455,39 +184,32 @@ def run_evaluation(username: str,
455
 
456
  # Формируем URL результатов
457
  results_url = f"{DEFAULT_API_URL}/results?username={username}"
458
-
459
- # Формируем статус кэширования
460
  cache_status = "Cache enabled and used" if use_cache else "Cache disabled"
461
 
462
- # ИСПРАВЛЕНО: Возвращаем 6 отдельных значений вместо словаря
463
  return (
464
- result, # result_text
465
- runner.get_correct_answers_count(), # correct_answers
466
- runner.get_total_questions_count(), # total_questions
467
- elapsed_time_str, # elapsed_time
468
- results_url, # results_url
469
- cache_status # cache_status
470
  )
471
 
472
 
473
  def create_gradio_interface():
474
- """
475
- Создает Gradio интерфейс для запуска оценки
476
- """
477
  with gr.Blocks(title="GAIA Agent Evaluation") as demo:
478
- gr.Markdown("# GAIA Agent Evaluation with Caching")
479
 
480
  with gr.Row():
481
  with gr.Column():
482
  username = gr.Textbox(label="Hugging Face Username")
483
- agent_code_url = gr.Textbox(label="Agent Code URL or Code", lines=10)
484
  model_name = gr.Dropdown(
485
  label="Model",
486
  choices=["google/flan-t5-small", "google/flan-t5-base", "google/flan-t5-large"],
487
- value="google/flan-t5-small"
488
  )
489
- use_cache = gr.Checkbox(label="Use Answer Cache", value=True)
490
-
491
  run_button = gr.Button("Run Evaluation & Submit All Answers")
492
 
493
  with gr.Column():
@@ -500,7 +222,7 @@ def create_gradio_interface():
500
 
501
  run_button.click(
502
  fn=run_evaluation,
503
- inputs=[username, agent_code_url, model_name, use_cache],
504
  outputs=[
505
  result_text,
506
  correct_answers,
@@ -515,6 +237,5 @@ def create_gradio_interface():
515
 
516
 
517
  if __name__ == "__main__":
518
- # Создаем и запускаем Gradio интерфейс
519
  demo = create_gradio_interface()
520
- demo.launch(share=True)
 
 
 
 
 
 
1
  import os
2
  import json
3
  import time
 
5
  import requests
6
  import gradio as gr
7
  import pandas as pd
 
8
  from typing import List, Dict, Any, Optional, Union, Callable, Tuple
9
+ from agent import EnhancedGAIAAgent # Импорт из отдельного файла
 
10
 
11
  # Константы
 
12
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
13
+ MAX_RETRIES = 3
14
+ RETRY_DELAY = 5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
 
16
  class EvaluationRunner:
17
+ """Обрабатывает процесс оценки: получение вопросов, запуск агента, отправку ответов"""
 
 
 
18
 
19
  def __init__(self, api_url=DEFAULT_API_URL):
 
20
  self.api_url = api_url
21
  self.questions_url = f"{api_url}/questions"
22
  self.submit_url = f"{api_url}/submit"
 
27
  def run_evaluation(self,
28
  agent: Callable[[str], str],
29
  username: str,
30
+ agent_code: str) -> tuple[str, pd.DataFrame]:
 
 
 
 
 
 
 
31
  # Получаем вопросы
32
  questions_data = self._fetch_questions()
33
  if isinstance(questions_data, str): # Сообщение об ошибке
 
38
  if not answers_payload:
39
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
40
 
41
+ # Отправляем ответы
42
+ submission_result = self._submit_answers(username, agent_code, answers_payload)
43
+
44
+ # Проверяем результаты
45
+ self._check_results(username)
46
+ self.print_evaluation_summary(username)
47
 
 
48
  return submission_result, pd.DataFrame(results_log)
49
 
50
  def _fetch_questions(self) -> Union[List[Dict[str, Any]], str]:
 
 
51
  try:
52
  response = requests.get(self.questions_url, timeout=15)
53
  response.raise_for_status()
54
  questions_data = response.json()
55
 
56
  if not questions_data:
57
+ return "Fetched questions list is empty or invalid format."
 
 
58
 
59
  self.total_questions = len(questions_data)
60
  print(f"Successfully fetched {self.total_questions} questions.")
61
  return questions_data
62
 
 
 
 
 
 
 
 
 
 
 
 
63
  except Exception as e:
64
+ return f"Error fetching questions: {e}"
 
 
65
 
66
  def _run_agent_on_questions(self,
67
  agent: Any,
68
  questions_data: List[Dict[str, Any]]) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
 
69
  results_log = []
70
  answers_payload = []
71
 
 
75
  question_text = item.get("question")
76
 
77
  if not task_id or question_text is None:
 
78
  continue
79
 
80
  try:
 
81
  json_response = agent(question_text, task_id)
 
 
82
  response_obj = json.loads(json_response)
 
 
83
  submitted_answer = response_obj.get("final_answer", "")
84
 
85
  answers_payload.append({
 
94
  "Full Response": json_response
95
  })
96
  except Exception as e:
 
97
  results_log.append({
98
  "Task ID": task_id,
99
  "Question": question_text,
 
104
 
105
  def _submit_answers(self,
106
  username: str,
107
+ agent_code: str,
108
  answers_payload: List[Dict[str, Any]]) -> str:
 
 
109
  submission_data = {
110
  "username": username.strip(),
111
+ "agent_code": agent_code.strip(), # Ключевое исправление: agent_code вместо agent_code_url
112
  "answers": answers_payload
113
  }
114
 
115
  print(f"Submitting {len(answers_payload)} answers to: {self.submit_url}")
116
+ print("Submission data:", json.dumps(submission_data, indent=2))
 
117
 
118
+ for attempt in range(1, MAX_RETRIES + 1):
119
  try:
 
120
  response = requests.post(
121
  self.submit_url,
122
  json=submission_data,
 
127
 
128
  try:
129
  result = response.json()
130
+ if "message" in result:
131
+ return result["message"]
132
+ return "Evaluation submitted successfully"
133
+ except:
134
+ return f"Submission successful, but response was not JSON: {response.text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
135
 
136
+ except Exception as e:
137
  print(f"Submission attempt {attempt} failed: {e}")
138
+ time.sleep(RETRY_DELAY)
 
 
 
 
139
 
140
+ return "Error submitting answers after multiple attempts"
 
141
 
142
  def _check_results(self, username: str) -> None:
 
143
  try:
144
  results_url = f"{self.results_url}?username={username}"
 
 
145
  response = requests.get(results_url, timeout=15)
146
  if response.status_code == 200:
147
+ data = response.json()
148
+ if isinstance(data, dict) and "score" in data:
149
+ self.correct_answers = int(data["score"])
 
 
 
 
 
 
 
 
 
 
 
 
150
  except Exception as e:
151
  print(f"Error checking results: {e}")
152
 
153
  def get_correct_answers_count(self) -> int:
 
154
  return self.correct_answers
155
 
156
  def get_total_questions_count(self) -> int:
 
157
  return self.total_questions
158
 
159
  def print_evaluation_summary(self, username: str) -> None:
 
160
  print("\n===== EVALUATION SUMMARY =====")
161
  print(f"User: {username}")
162
  print(f"Overall Score: {self.correct_answers}/{self.total_questions}")
 
 
 
163
  print("=============================\n")
164
 
165
 
166
  def run_evaluation(username: str,
167
+ agent_code: str, # Исправлено имя параметра
168
+ model_name: str = "google/flan-t5-base",
169
+ use_cache: bool = False) -> Tuple[str, int, int, str, str, str]: # Кэш отключен по умолчанию
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
170
  start_time = time.time()
171
 
172
+ # Инициализируем агента
173
  agent = EnhancedGAIAAgent(model_name=model_name, use_cache=use_cache)
174
 
175
+ # Инициализируем runner
176
  runner = EvaluationRunner(api_url=DEFAULT_API_URL)
177
 
178
  # Запускаем оценку
179
+ result, results_log = runner.run_evaluation(agent, username, agent_code)
 
 
 
 
 
 
180
 
181
  # Вычисляем время выполнения
182
  elapsed_time = time.time() - start_time
 
184
 
185
  # Формируем URL результатов
186
  results_url = f"{DEFAULT_API_URL}/results?username={username}"
 
 
187
  cache_status = "Cache enabled and used" if use_cache else "Cache disabled"
188
 
 
189
  return (
190
+ result,
191
+ runner.get_correct_answers_count(),
192
+ runner.get_total_questions_count(),
193
+ elapsed_time_str,
194
+ results_url,
195
+ cache_status
196
  )
197
 
198
 
199
  def create_gradio_interface():
 
 
 
200
  with gr.Blocks(title="GAIA Agent Evaluation") as demo:
201
+ gr.Markdown("# GAIA Agent Evaluation")
202
 
203
  with gr.Row():
204
  with gr.Column():
205
  username = gr.Textbox(label="Hugging Face Username")
206
+ agent_code = gr.Textbox(label="Agent Code", lines=2, placeholder="Your agent code here")
207
  model_name = gr.Dropdown(
208
  label="Model",
209
  choices=["google/flan-t5-small", "google/flan-t5-base", "google/flan-t5-large"],
210
+ value="google/flan-t5-base"
211
  )
212
+ use_cache = gr.Checkbox(label="Use Answer Cache", value=False)
 
213
  run_button = gr.Button("Run Evaluation & Submit All Answers")
214
 
215
  with gr.Column():
 
222
 
223
  run_button.click(
224
  fn=run_evaluation,
225
+ inputs=[username, agent_code, model_name, use_cache],
226
  outputs=[
227
  result_text,
228
  correct_answers,
 
237
 
238
 
239
  if __name__ == "__main__":
 
240
  demo = create_gradio_interface()
241
+ demo.launch(share=True)