yoshizen commited on
Commit
a7acff6
·
verified ·
1 Parent(s): 643ee17

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +129 -446
app.py CHANGED
@@ -1,68 +1,59 @@
1
  """
2
- Улучшенный GAIA Agent с поддержкой кэширования ответов и исправленным полем agent_code
3
  """
4
 
5
-
6
  import os
7
  import json
8
- import time
9
- 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-small", 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:
@@ -72,449 +63,141 @@ class EnhancedGAIAAgent:
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"
198
- self.results_url = f"{api_url}/results"
199
- self.correct_answers = 0
200
- self.total_questions = 0
201
-
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): # Сообщение об ошибке
216
- return questions_data, None
217
 
218
- # Запускаем агента на всех вопросах
219
- results_log, answers_payload = self._run_agent_on_questions(agent, questions_data)
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
-
269
- print(f"Running agent on {len(questions_data)} questions...")
270
- for item in questions_data:
271
- task_id = item.get("task_id")
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({
289
- "task_id": task_id,
290
- "submitted_answer": submitted_answer
291
- })
292
 
293
- results_log.append({
294
- "Task ID": task_id,
295
- "Question": question_text,
296
- "Submitted Answer": submitted_answer,
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,
304
- "Submitted Answer": f"AGENT ERROR: {e}"
305
- })
306
 
307
- return results_log, answers_payload
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,
331
- headers={"Content-Type": "application/json"},
332
- timeout=30
333
- )
334
- response.raise_for_status()
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
454
- elapsed_time_str = f"{elapsed_time:.2f} seconds"
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():
494
- result_text = gr.Textbox(label="Result", lines=2)
495
- correct_answers = gr.Number(label="Correct Answers")
496
- total_questions = gr.Number(label="Total Questions")
497
- elapsed_time = gr.Textbox(label="Elapsed Time")
498
- results_url = gr.Textbox(label="Results URL")
499
- cache_status = gr.Textbox(label="Cache Status")
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,
507
- total_questions,
508
- elapsed_time,
509
- results_url,
510
- cache_status
511
- ]
512
- )
513
-
514
- return demo
515
-
 
516
 
517
  if __name__ == "__main__":
518
- # Создаем и запускаем Gradio интерфейс
519
- demo = create_gradio_interface()
520
- demo.launch(share=True)
 
1
  """
2
+ Приложение для отправки ответов на сервер GAIA
3
  """
4
 
 
5
  import os
6
  import json
 
 
7
  import requests
8
+ import time
9
+ from typing import Dict, Any, List, Optional
 
 
 
10
 
11
+ from enhanced_gaia_agent_v3 import EnhancedGAIAAgent
12
 
13
  # Константы
14
+ API_URL = "https://gaia-challenge.huggingface.co/api/submit"
15
+ CACHE_FILE = "submission_cache.json"
 
 
16
 
17
+ class GAIASubmitter:
18
  """
19
+ Класс для отправки ответов на сервер GAIA
20
  """
21
 
22
+ def __init__(self, username: str, agent_code: str, use_cache: bool = True):
23
  """
24
+ Инициализация отправителя
25
 
26
  Args:
27
+ username: Имя пользователя для отправки
28
+ agent_code: Код агента для отправки
29
  use_cache: Использовать ли кэширование ответов
30
  """
31
+ self.username = username
32
+ self.agent_code = agent_code
33
  self.use_cache = use_cache
34
  self.cache = self._load_cache() if use_cache else {}
35
 
36
+ # Инициализируем агента
37
+ print(f"Initializing agent for submission...")
38
+ self.agent = EnhancedGAIAAgent(use_cache=True)
39
+
40
+ def _load_cache(self) -> Dict[str, Any]:
 
 
 
41
  """
42
  Загружает кэш ответов из файла
43
 
44
  Returns:
45
+ Dict[str, Any]: Словарь с кэшированными ответами
46
  """
47
  if os.path.exists(CACHE_FILE):
48
  try:
49
  with open(CACHE_FILE, 'r', encoding='utf-8') as f:
50
+ print(f"Loading submission cache from {CACHE_FILE}")
51
  return json.load(f)
52
  except Exception as e:
53
+ print(f"Error loading submission cache: {e}")
54
  return {}
55
  else:
56
+ print(f"Submission cache file {CACHE_FILE} not found, creating new cache")
57
  return {}
58
 
59
  def _save_cache(self) -> None:
 
63
  try:
64
  with open(CACHE_FILE, 'w', encoding='utf-8') as f:
65
  json.dump(self.cache, f, ensure_ascii=False, indent=2)
66
+ print(f"Submission cache saved to {CACHE_FILE}")
67
  except Exception as e:
68
+ print(f"Error saving submission cache: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
 
70
+ def submit_answers(self, questions: List[Dict[str, str]]) -> Dict[str, Any]:
71
  """
72
+ Отправляет ответы на сервер GAIA
73
 
74
  Args:
75
+ questions: Список вопросов для ответа
 
76
 
77
  Returns:
78
+ Dict[str, Any]: Ответ сервера
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  """
80
+ # Подготавливаем ответы
81
+ answers = {}
 
 
82
 
83
+ print(f"Processing {len(questions)} questions...")
84
+ for i, question in enumerate(questions):
85
+ task_id = question["task_id"]
86
+ question_text = question["question"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
 
88
+ print(f"Question {i+1}/{len(questions)}: {task_id} - {question_text[:50]}...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
 
90
+ # Получаем ответ от агента
91
  try:
92
+ json_response = self.agent(question_text, task_id)
 
 
 
93
  response_obj = json.loads(json_response)
94
+ answer = response_obj.get("final_answer", "")
95
 
96
+ print(f"Answer: {answer}")
97
+ answers[task_id] = answer
 
 
 
 
 
98
 
 
 
 
 
 
 
99
  except Exception as e:
100
+ print(f"Error processing question {task_id}: {e}")
101
+ answers[task_id] = f"ERROR: {e}"
 
 
 
 
102
 
103
+ # Подготавливаем данные для отправки
 
 
 
 
 
 
 
104
  submission_data = {
105
+ "username": self.username,
106
+ "agent_code": self.agent_code,
107
+ "answers": answers
108
  }
109
 
110
+ # Сохраняем данные для отладки
111
+ with open("submission_data.json", 'w', encoding='utf-8') as f:
112
+ json.dump(submission_data, f, ensure_ascii=False, indent=2)
113
+ print("Submission data saved to submission_data.json")
114
 
115
+ # Проверяем наличие ответа в кэше
116
+ cache_key = json.dumps(submission_data)
117
+ if self.use_cache and cache_key in self.cache:
118
+ print("Using cached submission response")
119
+ return self.cache[cache_key]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
 
121
+ # Отправляем запрос на сервер
122
+ print(f"Submitting answers to {API_URL}...")
 
 
 
123
  try:
124
+ response = requests.post(API_URL, json=submission_data)
125
+
126
+ # Сохраняем ответ для отладки
127
+ with open("response_content.txt", 'w', encoding='utf-8') as f:
128
+ f.write(response.text)
129
+ print("Response content saved to response_content.txt")
130
 
131
+ # Проверяем статус ответа
132
  if response.status_code == 200:
133
+ print("Submission successful!")
134
+ result = response.json()
135
+
136
+ # Сохраняем результат для отладки
137
+ with open("results_response.txt", 'w', encoding='utf-8') as f:
138
+ json.dump(result, f, ensure_ascii=False, indent=2)
139
+ print("Results saved to results_response.txt")
140
+
141
+ # Сохраняем в кэш
142
+ if self.use_cache:
143
+ self.cache[cache_key] = result
144
+ self._save_cache()
145
+
146
+ return result
147
  else:
148
+ error_msg = f"Submission failed with status code {response.status_code}: {response.text}"
149
+ print(error_msg)
150
+ return {"error": error_msg}
151
+
152
  except Exception as e:
153
+ error_msg = f"Error during submission: {e}"
154
+ print(error_msg)
155
+ return {"error": error_msg}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
156
 
157
+ def main():
158
  """
159
+ Основная функция для отправки ответов
160
  """
161
+ # Получаем имя пользователя из аргументов командной строки или запрашиваем у пользователя
162
+ import sys
163
+ if len(sys.argv) > 1:
164
+ username = sys.argv[1]
165
+ else:
166
+ username = input("Enter your username: ")
167
+
168
+ # Код агента для отправки
169
+ agent_code = "enhanced_gaia_agent_v3"
170
+
171
+ # Создаем отправителя
172
+ submitter = GAIASubmitter(username, agent_code, use_cache=True)
173
+
174
+ # Загружаем вопросы из файла
175
+ try:
176
+ with open("questions.json", 'r', encoding='utf-8') as f:
177
+ questions = json.load(f)
178
+ print(f"Loaded {len(questions)} questions from questions.json")
179
+ except FileNotFoundError:
180
+ print("Questions file not found, using sample questions")
181
+ # Используем примеры вопросов
182
+ from test_samples.sample_questions import get_sample_questions
183
+ questions = get_sample_questions()
184
+
185
+ # Отправляем ответы
186
+ result = submitter.submit_answers(questions)
187
+
188
+ # Выводим результат
189
+ print("\n=== Submission Result ===")
190
+ if "error" in result:
191
+ print(f"Error: {result['error']}")
192
+ else:
193
+ print(f"Score: {result.get('score', 'N/A')}")
194
+ print(f"Message: {result.get('message', 'No message')}")
195
+
196
+ # Выводим детальные результаты, если есть
197
+ if "details" in result:
198
+ print("\nDetails:")
199
+ for task_id, detail in result["details"].items():
200
+ print(f"- {task_id}: {detail}")
201
 
202
  if __name__ == "__main__":
203
+ main()