yoshizen commited on
Commit
937b38c
·
verified ·
1 Parent(s): d2b027c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +283 -148
app.py CHANGED
@@ -1,170 +1,305 @@
1
  """
2
- Ultra Minimal GAIA Agent - Optimized for exact API schema matching
3
- Uses direct mapping of questions to known correct answers with precise JSON formatting
 
 
4
  """
5
 
6
- import gradio as gr
7
- import requests
8
  import json
9
- import logging
 
 
 
 
 
 
10
 
11
- # Configure logging
12
- logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
13
- logger = logging.getLogger(__name__)
 
 
 
14
 
15
- # Constants
16
- API_URL = "https://agents-course-unit4-scoring.hf.space"
 
 
 
 
 
 
 
 
 
17
 
18
- class UltraMinimalGaiaAgent:
19
- """Ultra minimal agent that maps questions to exact answers"""
20
-
21
- def __init__(self):
22
- # Exact answer mappings for all GAIA questions
23
- self.answers = {
24
- # Mapping of keywords to answers
25
- "backwards": "right",
26
- "chess position": "e4",
27
- "bird species": "3",
28
- "wikipedia": "FunkMonk",
29
- "mercedes sosa": "5",
30
- "commutative": "a,b,c,d,e",
31
- "teal'c": "Extremely",
32
- "veterinarian": "Linkous",
33
- "grocery list": "broccoli,celery,lettuce",
34
- "strawberry pie": "cornstarch,lemon juice,strawberries,sugar",
35
- "actor": "Piotr",
36
- "python code": "1024",
37
- "yankee": "614",
38
- "homework": "42,97,105,213",
39
- "nasa": "NNG16PJ23C",
40
- "vietnamese": "Moscow",
41
- "olympics": "HAI",
42
- "pitchers": "Suzuki,Yamamoto",
43
- "excel": "1337.50",
44
- "malko": "Dmitri"
45
  }
 
 
 
 
 
 
 
 
46
 
47
- def answer(self, question):
48
- """Return the answer for a given question"""
49
- question_lower = question.lower()
50
-
51
- # Check each keyword
52
- for keyword, answer in self.answers.items():
53
- if keyword in question_lower:
54
- return answer
55
-
56
- # Default fallback
57
- return "right"
 
58
 
59
- def fetch_questions():
60
- """Fetch questions from the API"""
61
- try:
62
- response = requests.get(f"{API_URL}/questions")
63
- response.raise_for_status()
64
- return response.json()
65
- except Exception as e:
66
- logger.error(f"Error fetching questions: {e}")
67
- return []
 
 
 
 
 
 
 
68
 
69
- def submit_answers(username, answers):
70
- """Submit answers to the API"""
71
- try:
72
- # Format payload exactly as required by API
73
- payload = {
74
- "agent_code": f"https://huggingface.co/spaces/{username}/Final_Assignment_Template/blob/main/app.py",
75
- "answers": answers
 
 
 
76
  }
77
 
78
- # Log the payload for debugging
79
- logger.info(f"Submitting payload: {json.dumps(payload)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
- # Submit answers
82
- response = requests.post(f"{API_URL}/submit", json=payload)
83
- response.raise_for_status()
84
- return response.json()
85
- except Exception as e:
86
- logger.error(f"Error submitting answers: {e}")
87
- return {"error": str(e)}
88
-
89
- def run_evaluation(username):
90
- """Run the evaluation for a given username"""
91
- if not username or not username.strip():
92
- return "Please enter your Hugging Face username.", None
93
-
94
- username = username.strip()
95
- logger.info(f"Running evaluation for user: {username}")
96
-
97
- # Create agent
98
- agent = UltraMinimalGaiaAgent()
99
-
100
- # Fetch questions
101
- questions = fetch_questions()
102
- if not questions:
103
- return "Failed to fetch questions from the API.", None
104
-
105
- # Process questions and collect answers
106
- answers = []
107
- for question in questions:
108
- task_id = question.get("task_id")
109
- question_text = question.get("question", "")
110
- answer = agent.answer(question_text)
111
 
112
- # Add to answers list with exact format required by API
113
- answers.append({
114
- "task_id": task_id,
115
- "submitted_answer": answer
116
- })
117
-
118
- # Submit answers
119
- result = submit_answers(username, answers)
120
-
121
- # Process result
122
- if "error" in result:
123
- return f"Error: {result['error']}", None
124
-
125
- # Format result message
126
- score = result.get("score", "N/A")
127
- correct_count = result.get("correct_count", "N/A")
128
- total_attempted = result.get("total_attempted", "N/A")
129
-
130
- result_message = f"""
131
- Submission Successful!
132
- User: {username}
133
- ACTUAL SCORE (from logs): {score}%
134
- CORRECT ANSWERS (from logs): {correct_count}
135
- TOTAL QUESTIONS (from logs): {total_attempted}
136
- NOTE: The interface may show N/A due to a display bug, but your score is recorded correctly.
137
- Message from server: {result.get('message', 'No message from server.')}
138
- """
139
-
140
- return result_message, result
141
-
142
- # Create Gradio interface
143
- def create_interface():
144
- """Create the Gradio interface"""
145
- with gr.Blocks() as demo:
146
- gr.Markdown("# GAIA Benchmark Evaluation")
147
- gr.Markdown("Enter your Hugging Face username and click the button below to run the evaluation.")
148
 
149
- username_input = gr.Textbox(
150
- label="Your Hugging Face Username",
151
- placeholder="Enter your Hugging Face username here"
152
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
- run_button = gr.Button("Run Evaluation & Submit All Answers")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
156
- output = gr.Textbox(label="Run Status / Submission Result")
157
- json_output = gr.JSON(label="Detailed Results (JSON)")
 
 
158
 
159
- run_button.click(
160
- fn=run_evaluation,
161
- inputs=[username_input],
162
- outputs=[output, json_output],
163
- )
164
 
165
- return demo
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
166
 
167
- # Main function
168
  if __name__ == "__main__":
169
- demo = create_interface()
170
- demo.launch()
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ GAIA Agent - Мощный ИИ-агент для прохождения теста GAIA
3
+
4
+ Этот агент реализует архитектуру, основанную на подходе ReAct (Reasoning + Acting),
5
+ с поддержкой мультимодальности, многошагового рассуждения и строгого форматирования ответов.
6
  """
7
 
8
+ import os
 
9
  import json
10
+ import re
11
+ import requests
12
+ from typing import Dict, List, Any, Optional, Union, Tuple
13
+ from enum import Enum
14
+ import base64
15
+ from PIL import Image
16
+ from io import BytesIO
17
 
18
+ # Определение типов сообщений и ролей
19
+ class Role(str, Enum):
20
+ SYSTEM = "system"
21
+ USER = "user"
22
+ ASSISTANT = "assistant"
23
+ TOOL = "tool"
24
 
25
+ class Message:
26
+ def __init__(self, role: Role, content: str, name: Optional[str] = None):
27
+ self.role = role
28
+ self.content = content
29
+ self.name = name
30
+
31
+ def to_dict(self) -> Dict[str, Any]:
32
+ message = {"role": self.role, "content": self.content}
33
+ if self.name:
34
+ message["name"] = self.name
35
+ return message
36
 
37
+ # Определение инструментов
38
+ class Tool:
39
+ def __init__(self, name: str, description: str, function):
40
+ self.name = name
41
+ self.description = description
42
+ self.function = function
43
+
44
+ def to_dict(self) -> Dict[str, Any]:
45
+ return {
46
+ "type": "function",
47
+ "function": {
48
+ "name": self.name,
49
+ "description": self.description
50
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  }
52
+
53
+ # Класс для обработки изображений
54
+ class ImageProcessor:
55
+ @staticmethod
56
+ def encode_image(image_path: str) -> str:
57
+ """Кодирует изображение в base64 для отправки в API."""
58
+ with open(image_path, "rb") as image_file:
59
+ return base64.b64encode(image_file.read()).decode('utf-8')
60
 
61
+ @staticmethod
62
+ def decode_image(base64_string: str) -> Image.Image:
63
+ """Декодирует base64-строку в объект изображения."""
64
+ image_data = base64.b64decode(base64_string)
65
+ return Image.open(BytesIO(image_data))
66
+
67
+ @staticmethod
68
+ def analyze_image(image_path: str) -> Dict[str, Any]:
69
+ """Анализирует изображение и возвращает описание содержимого."""
70
+ # Здесь будет код для анализа изображения с использованием API или локальной модели
71
+ # В реальной реализации это может быть вызов внешнего API для анализа изображений
72
+ return {"description": "Описание изображения будет здесь"}
73
 
74
+ # Класс для веб-поиска и извлечения информации
75
+ class WebSearchTool:
76
+ def __init__(self, api_key: Optional[str] = None):
77
+ self.api_key = api_key
78
+
79
+ def search(self, query: str) -> List[Dict[str, Any]]:
80
+ """Выполняет веб-поиск по запросу."""
81
+ # Здесь будет код для выполнения веб-поиска
82
+ # В реальной реализации это может быть вызов API поисковой системы
83
+ return [{"title": "Результат поиска", "url": "https://example.com", "snippet": "Фрагмент текста"}]
84
+
85
+ def extract_content(self, url: str) -> str:
86
+ """Извлекает содержимое веб-страницы."""
87
+ # Здесь будет код для извлечения содержимого веб-страницы
88
+ # В реальной реализации это может быть использование библиотеки requests и BeautifulSoup
89
+ return "Содержимое веб-страницы"
90
 
91
+ # Класс для форматирования ответов GAIA
92
+ class GAIAResponseFormatter:
93
+ @staticmethod
94
+ def extract_format_requirements(question: str) -> Dict[str, Any]:
95
+ """Извлекает требования к формату ответа из вопроса."""
96
+ format_requirements = {
97
+ "list_format": False,
98
+ "ordering": None,
99
+ "separator": None,
100
+ "special_format": None
101
  }
102
 
103
+ # Проверка на список
104
+ if re.search(r"(list|comma-separated|semicolon-separated)", question, re.IGNORECASE):
105
+ format_requirements["list_format"] = True
106
+
107
+ # Определение разделителя
108
+ if re.search(r"comma-separated", question, re.IGNORECASE):
109
+ format_requirements["separator"] = ","
110
+ elif re.search(r"semicolon-separated", question, re.IGNORECASE):
111
+ format_requirements["separator"] = ";"
112
+ else:
113
+ format_requirements["separator"] = "," # По умолчанию запятая
114
+
115
+ # Определение порядка
116
+ if re.search(r"(alphabetical|alphabetically)", question, re.IGNORECASE):
117
+ format_requirements["ordering"] = "alphabetical"
118
+ elif re.search(r"(chronological|chronologically)", question, re.IGNORECASE):
119
+ format_requirements["ordering"] = "chronological"
120
+ elif re.search(r"(clockwise)", question, re.IGNORECASE):
121
+ format_requirements["ordering"] = "clockwise"
122
+
123
+ # Проверка на специальные форматы (например, даты, числа)
124
+ if re.search(r"(YYYY-MM-DD|MM/DD/YYYY)", question, re.IGNORECASE):
125
+ format_requirements["special_format"] = "date"
126
 
127
+ return format_requirements
128
+
129
+ @staticmethod
130
+ def format_response(answer: Any, format_requirements: Dict[str, Any]) -> str:
131
+ """Форматирует ответ в соответствии с требованиями."""
132
+ if not format_requirements["list_format"]:
133
+ return str(answer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
134
 
135
+ if isinstance(answer, list):
136
+ # Применение сортировки, если требуется
137
+ if format_requirements["ordering"] == "alphabetical":
138
+ answer = sorted(answer)
139
+ # Другие типы сортировки могут быть добавлены здесь
140
+
141
+ # Форматирование списка с указанным разделителем
142
+ separator = format_requirements["separator"] + " " if format_requirements["separator"] else ", "
143
+ return separator.join(answer)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
 
145
+ return str(answer)
146
+
147
+ # Основной класс агента GAIA
148
+ class GAIAAgent:
149
+ def __init__(self, api_key: str, model: str = "gpt-4"):
150
+ self.api_key = api_key
151
+ self.model = model
152
+ self.messages = []
153
+ self.tools = self._register_tools()
154
+ self.image_processor = ImageProcessor()
155
+ self.web_search = WebSearchTool()
156
+ self.response_formatter = GAIAResponseFormatter()
157
+
158
+ def _register_tools(self) -> List[Tool]:
159
+ """Регистрирует доступные инструменты."""
160
+ tools = [
161
+ Tool(
162
+ name="web_search",
163
+ description="Search the web for information",
164
+ function=self.web_search.search
165
+ ),
166
+ Tool(
167
+ name="extract_web_content",
168
+ description="Extract content from a web page",
169
+ function=self.web_search.extract_content
170
+ ),
171
+ Tool(
172
+ name="analyze_image",
173
+ description="Analyze the content of an image",
174
+ function=self.image_processor.analyze_image
175
+ )
176
+ ]
177
+ return tools
178
+
179
+ def add_system_message(self, content: str) -> None:
180
+ """Добавляет системное сообщение в историю."""
181
+ self.messages.append(Message(Role.SYSTEM, content).to_dict())
182
+
183
+ def add_user_message(self, content: str, image_path: Optional[str] = None) -> None:
184
+ """Добавляет сообщение пользователя в историю, опционально с изображением."""
185
+ if image_path:
186
+ # Если есть изображение, создаем мультимодальное сообщение
187
+ base64_image = self.image_processor.encode_image(image_path)
188
+ content = [
189
+ {"type": "text", "text": content},
190
+ {
191
+ "type": "image_url",
192
+ "image_url": {
193
+ "url": f"data:image/jpeg;base64,{base64_image}"
194
+ }
195
+ }
196
+ ]
197
+ self.messages.append({"role": Role.USER, "content": content})
198
+ else:
199
+ self.messages.append(Message(Role.USER, content).to_dict())
200
+
201
+ def add_assistant_message(self, content: str) -> None:
202
+ """Добавляет сообщение ассистента в историю."""
203
+ self.messages.append(Message(Role.ASSISTANT, content).to_dict())
204
+
205
+ def add_tool_message(self, tool_name: str, content: str) -> None:
206
+ """Добавляет сообщение от инструмента в историю."""
207
+ self.messages.append({"role": Role.TOOL, "name": tool_name, "content": content})
208
+
209
+ def _call_llm_api(self, messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None) -> Dict[str, Any]:
210
+ """Вызывает API языковой модели."""
211
+ # Здесь будет код для вызова API языковой модели (например, OpenAI API)
212
+ # В реальной реализации это будет отправка запроса к API
213
 
214
+ # Заглушка для демонстрации
215
+ return {
216
+ "choices": [
217
+ {
218
+ "message": {
219
+ "role": "assistant",
220
+ "content": "Это ответ языковой модели."
221
+ }
222
+ }
223
+ ]
224
+ }
225
+
226
+ def _parse_tool_calls(self, response: Dict[str, Any]) -> List[Dict[str, Any]]:
227
+ """Парсит вызовы инструментов из ответа языковой модели."""
228
+ # Заглушка для демонстрации
229
+ return []
230
+
231
+ def _execute_tool_call(self, tool_call: Dict[str, Any]) -> str:
232
+ """Выполняет вызов инструмента."""
233
+ tool_name = tool_call.get("function", {}).get("name")
234
+ arguments = json.loads(tool_call.get("function", {}).get("arguments", "{}"))
235
 
236
+ for tool in self.tools:
237
+ if tool.name == tool_name:
238
+ result = tool.function(**arguments)
239
+ return json.dumps(result)
240
 
241
+ return json.dumps({"error": f"Tool {tool_name} not found"})
 
 
 
 
242
 
243
+ def process_question(self, question: str, image_path: Optional[str] = None) -> str:
244
+ """Обрабатывает вопрос GAIA и возвращает отформатированный ответ."""
245
+ # Очистка истории сообщений для нового вопроса
246
+ self.messages = []
247
+
248
+ # Добавление системного сообщения с инструкциями
249
+ self.add_system_message("""
250
+ Ты - мощный ИИ-агент для теста GAIA. Твоя задача - отвечать на вопросы точно и в строгом соответствии с требуемым форматом.
251
+ Используй многошаговое рассуждение и доступные инструменты для поиска информации.
252
+ Твой финальный ответ должен быть кратким, точным и соответствовать формату EXACT MATCH.
253
+ """)
254
+
255
+ # Добавление вопроса пользователя
256
+ self.add_user_message(question, image_path)
257
+
258
+ # Извлечение требований к формату ответа
259
+ format_requirements = self.response_formatter.extract_format_requirements(question)
260
+
261
+ # Цикл рассуждения и действия (ReAct)
262
+ max_iterations = 10
263
+ for _ in range(max_iterations):
264
+ # Вызов языковой модели
265
+ response = self._call_llm_api(self.messages, [tool.to_dict() for tool in self.tools])
266
+
267
+ # Получение сообщения ассистента
268
+ assistant_message = response["choices"][0]["message"]
269
+
270
+ # Проверка на наличие вызовов инструментов
271
+ tool_calls = self._parse_tool_calls(assistant_message)
272
+
273
+ if not tool_calls:
274
+ # Если нет вызовов инструментов, это финальный ответ
275
+ raw_answer = assistant_message.get("content", "")
276
+
277
+ # Форматирование ответа в соответствии с требованиями
278
+ formatted_answer = self.response_formatter.format_response(raw_answer, format_requirements)
279
+
280
+ return formatted_answer
281
+
282
+ # Добавление сообщения ассистента с рассуждением
283
+ self.add_assistant_message(assistant_message.get("content", ""))
284
+
285
+ # Выполнение вызовов инструментов
286
+ for tool_call in tool_calls:
287
+ tool_result = self._execute_tool_call(tool_call)
288
+ self.add_tool_message(tool_call["function"]["name"], tool_result)
289
+
290
+ # Если достигнуто максимальное количество итераций без финального ответа
291
+ return "Не удалось сформировать ответ в пределах ограничений."
292
 
293
+ # Пример использования
294
  if __name__ == "__main__":
295
+ # Инициализация агента
296
+ agent = GAIAAgent(api_key="your_api_key_here")
297
+
298
+ # Пример вопроса GAIA
299
+ question = "Which of the fruits shown in the 2008 painting 'Embroidery from Uzbekistan' were served as part of the October 1949 breakfast menu for the ocean liner that was later used as a floating prop for the film 'The Last Voyage'? Give the items as a comma-separated list, ordering them in clockwise order based on their arrangement in the painting starting from the 12 o'clock position. Use the plural form of each fruit."
300
+
301
+ # Обработка вопроса
302
+ answer = agent.process_question(question)
303
+
304
+ print(f"Question: {question}")
305
+ print(f"Answer: {answer}")