yoshizen commited on
Commit
e06c6cc
·
verified ·
1 Parent(s): a6b5f2c

Delete app.py

Browse files
Files changed (1) hide show
  1. app.py +0 -305
app.py DELETED
@@ -1,305 +0,0 @@
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.image_processor = ImageProcessor()
154
- self.web_search = WebSearchTool()
155
- self.response_formatter = GAIAResponseFormatter()
156
- self.tools = self._register_tools()
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}")