File size: 11,598 Bytes
f078f62
 
8b6df94
 
 
d68b105
 
8b6df94
 
 
f078f62
8b6df94
81e21fd
 
 
 
 
 
 
 
 
8b6df94
 
f078f62
81e21fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b6df94
81e21fd
 
 
 
 
 
 
 
 
 
 
 
 
 
8b6df94
 
 
f078f62
 
 
7e0e19c
 
f078f62
 
81e21fd
 
 
 
 
 
 
 
 
 
f078f62
d68b105
f078f62
 
 
 
 
 
81e21fd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f078f62
8b6df94
 
f078f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8b6df94
 
f078f62
8b6df94
f078f62
8b6df94
 
09ab61d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f078f62
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eac1fe8
685d9f9
 
 
eac1fe8
 
 
f078f62
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
import os

from smolagents import (
    CodeAgent,
    PythonInterpreterTool,
    GoogleSearchTool,
    VisitWebpageTool,
)
from models import select_model

from typing import Optional


from tools_smolagent_audio import transcribe_audio
from tools_smolagent_browser import (
    wiki_search,
    web_search,
    arxiv_search,
    website_scrape,
)
from tools_smolagent_doc import (
    save_and_read_file,
    download_file_from_url,
    extract_text_from_image,
    analyze_csv_file,
    analyze_excel_file,
    read_file,
)
from tools_smolagent_img import (
    analyze_image,
    transform_image,
    draw_on_image,
    generate_simple_image,
    combine_images,
)
from tools_smolagent_maths import (
    multiply,
    add,
    subtract,
    divide,
    modulus,
    power,
    # square_root,
)
from tools_smolagent_video import (
    review_youtube_video,
    use_vision_model,
    video_frames_to_images,
    transcribe_youtube,
)

# from tools import (
#     save_and_read_file,
#     analyze_excel_file,
#     analyze_csv_file,
#     download_file_from_url,
#     extract_text_from_image,
# )


class BasicAgent:
    def __init__(
        self,
        verbose=False,
        name_model_provider="openrouter",
        name_model="llama4",
    ):
        self.verbose = verbose
        # tools = [
        #     GoogleSearchTool(provider="serper"),
        #     PythonInterpreterTool(),
        #     VisitWebpageTool(),
        #     save_and_read_file,
        #     analyze_excel_file,
        #     analyze_csv_file,
        #     download_file_from_url,
        #     extract_text_from_image,
        # ]
        tools = [
            GoogleSearchTool(provider="serper"),
            PythonInterpreterTool(),
            save_and_read_file,
            analyze_excel_file,
            analyze_csv_file,
            download_file_from_url,
            extract_text_from_image,
            read_file,
            transcribe_audio,
            wiki_search,
            # web_search,
            arxiv_search,
            website_scrape,
            analyze_image,
            transform_image,
            draw_on_image,
            generate_simple_image,
            combine_images,
            multiply,
            add,
            subtract,
            divide,
            modulus,
            power,
            # square_root,
            review_youtube_video,
            use_vision_model,
            video_frames_to_images,
            transcribe_youtube,
        ]
        self.agent = CodeAgent(
            tools=tools,
            model=select_model(name_model_provider, name_model),
            additional_authorized_imports=[
                "pandas",
                "numpy",
                "datetime",
                "json",
                "re",
                "math",
                "os",
                "requests",
                "csv",
                "urllib",
                "io",
                "cv2",
            ],
            executor_type="local",
            executor_kwargs={},
            verbosity_level=0,
        )
        print("BasicAgent initialized.")

    def __call__(self, question: str) -> str:
        """
        Process a GAIA benchmark question and return the answer

        Args:
            question: The question to answer
            task_file_path: Optional path to a file associated with the question

        Returns:
            The answer to the question
        """
        try:
            if self.verbose:
                print(f"Processing question: {question}")

            # Create a context with file information if available
            context = question
            if question.startswith(".") or ".rewsna eht sa" in question:
                context = f""" This question appears to be in reversed text. Here's the reversed version: {question[::-1]} Now answer the question above. Remember to format your answer exactly as requested. """

            # Add a prompt to ensure precise answers

            full_prompt = f"""{context}. When answering, provide ONLY the precise answer requested. Do not include explanations, steps, reasoning, or additional text. Be direct and specific. GAIA benchmark requires exact matching answers. For example, if asked "What is the capital of France?", respond simply with "Paris"."""

            # rules = "When answering, your answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, do not include brackets and apply the above rules depending of whether the element to be put in the list is a number or a string."

            # full_prompt = f"""{context}. {rules}"""

            # Run the agent with the question
            answer = self.agent.run(full_prompt)

            # Clean up the answer to ensure it's in the expected format
            # Remove common prefixes that models often add
            answer = self._clean_answer(answer)

            if self.verbose:
                print(f"Generated answer: {answer}")

            return answer

        except Exception as e:
            error_msg = f"Error answering question: {e}"
            if self.verbose:
                print(error_msg)
            return error_msg

    def answer_question(
        self, question: str, task_file_path: Optional[str] = None
    ) -> str:
        """
        Process a GAIA benchmark question and return the answer

        Args:
            question: The question to answer
            task_file_path: Optional path to a file associated with the question

        Returns:
            The answer to the question
        """
        try:
            if self.verbose:
                print(f"Processing question: {question}")
                if task_file_path:
                    print(f"With associated file: {task_file_path}")

            # Create a context with file information if available
            context = question
            file_content = None

            # If there's a file, read it and include its content in the context
            if task_file_path:
                try:
                    with open(task_file_path, "r") as f:
                        file_content = f.read()

                    # Determine file type from extension
                    file_ext = os.path.splitext(task_file_path)[1].lower()

                    context = f""" Question: {question} This question has an associated file. Here is the file content: ```{file_ext} {file_content}```Analyze the file content above to answer the question."""

                except Exception as file_e:
                    context = f""" Question: {question} This question has an associated file at path: {task_file_path}. However, there was an error reading the file: {file_e}. You can still try to answer the question based on the information provided."""

            # Check for special cases that need specific formatting
            # Reversed text questions
            if question.startswith(".") or ".rewsna eht sa" in question:
                context = f""" This question appears to be in reversed text. Here's the reversed version: {question[::-1]} Now answer the question above. Remember to format your answer exactly as requested. """

            # Add a prompt to ensure precise answers

            full_prompt = f"""{context}. When answering, provide ONLY the precise answer requested. Do not include explanations, steps, reasoning, or additional text. Be direct and specific. GAIA benchmark requires exact matching answers. For example, if asked "What is the capital of France?", respond simply with "Paris"."""

            # rules = "When answering, your answer should be a number OR as few words as possible OR a comma separated list of numbers and/or strings. If you are asked for a number, don't use comma to write your number neither use units such as $ or percent sign unless specified otherwise. If you are asked for a string, don't use articles, neither abbreviations (e.g. for cities), and write the digits in plain text unless specified otherwise. If you are asked for a comma separated list, do not include brackets and apply the above rules depending of whether the element to be put in the list is a number or a string."

            # full_prompt = f"""{context}. {rules}"""

            # Run the agent with the question
            answer = self.agent.run(full_prompt)

            # Clean up the answer to ensure it's in the expected format
            # Remove common prefixes that models often add
            answer = self._clean_answer(answer)

            if self.verbose:
                print(f"Generated answer: {answer}")

            return answer

        except Exception as e:
            error_msg = f"Error answering question: {e}"
            if self.verbose:
                print(error_msg)
            return error_msg

    def _clean_answer(self, answer: any) -> str:
        """
        Clean up the answer to remove common prefixes and formatting
        that models often add but that can cause exact match failures.

        Args:
            answer: The raw answer from the model

        Returns:
            The cleaned answer as a string
        """
        # Convert non-string types to strings
        if not isinstance(answer, str):
            # Handle numeric types (float, int)
            if isinstance(answer, float):
                # Format floating point numbers properly
                # Check if it's an integer value in float form (e.g., 12.0)
                if answer.is_integer():
                    formatted_answer = str(int(answer))
                else:
                    # For currency values that might need formatting
                    if abs(answer) >= 1000:
                        formatted_answer = f"${answer:,.2f}"
                    else:
                        formatted_answer = str(answer)
                return formatted_answer
            elif isinstance(answer, int):
                return str(answer)
            else:
                # For any other type
                return str(answer)

        # Now we know answer is a string, so we can safely use string methods
        # Normalize whitespace
        answer = answer.strip()

        # Remove common prefixes and formatting that models add
        prefixes_to_remove = [
            "The answer is ",
            "Answer: ",
            "Final answer: ",
            "The result is ",
            "To answer this question: ",
            "Based on the information provided, ",
            "According to the information: ",
        ]

        for prefix in prefixes_to_remove:
            if answer.startswith(prefix):
                answer = answer[len(prefix) :].strip()

        # Remove quotes if they wrap the entire answer
        if (answer.startswith('"') and answer.endswith('"')) or (
            answer.startswith("'") and answer.endswith("'")
        ):
            answer = answer[1:-1].strip()

        stuff_to_remove = "Stdout:"
        if answer.startswith(stuff_to_remove):
            answer = answer[len(stuff_to_remove) :].strip()

        stuff_to_remove_bis = "Output: "
        if answer.startswith(stuff_to_remove_bis):
            answer = answer[len(stuff_to_remove_bis) :].strip()
        return answer