mobrobro commited on
Commit
72b86d4
·
verified ·
1 Parent(s): d8d1a61

Upload 3 files

Browse files
Files changed (3) hide show
  1. app.py +5 -404
  2. run.py +125 -0
  3. run_gaia.py +277 -0
app.py CHANGED
@@ -1,410 +1,11 @@
1
- import os
2
- import gradio as gr
3
- import requests
4
- import inspect
5
- import pandas as pd
6
- import sys
7
- from pathlib import Path
8
 
9
- # Add your agent's code to the path
10
- sys.path.append(str(Path(__file__).parent.absolute()))
11
 
12
- # Import your agent components
13
- from dotenv import load_dotenv
14
- from huggingface_hub import login
15
- from scripts.text_inspector_tool import TextInspectorTool
16
- from scripts.text_web_browser import (
17
- ArchiveSearchTool,
18
- FinderTool,
19
- FindNextTool,
20
- PageDownTool,
21
- PageUpTool,
22
- SimpleTextBrowser,
23
- VisitTool,
24
- )
25
- from scripts.visual_qa import visualizer
26
- from scripts.reformulator import prepare_response
27
 
28
- from smolagents import (
29
- CodeAgent,
30
- GoogleSearchTool,
31
- LiteLLMModel,
32
- ToolCallingAgent,
33
- )
34
 
35
- # --- Constants ---
36
- DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
37
-
38
- # GAIA system prompt for exact answer format
39
- GAIA_SYSTEM_PROMPT = """You are a general AI assistant. I will ask you a question. Report your thoughts, and finish your answer with the following template: FINAL ANSWER: [YOUR FINAL ANSWER]. YOUR FINAL 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, apply the above rules depending of whether the element to be put in the list is a number or a string."""
40
-
41
- # --- Smolagent Implementation ---
42
- load_dotenv(override=True)
43
-
44
- # Try to login with HF token from env or secrets
45
- try:
46
- hf_token = os.getenv("HF_TOKEN")
47
- if hf_token:
48
- login(hf_token)
49
- print("Successfully logged in to Hugging Face")
50
- else:
51
- print("No HF_TOKEN found in environment")
52
- except Exception as e:
53
- print(f"Error logging in to Hugging Face: {e}")
54
-
55
- # Custom settings for your agent
56
- custom_role_conversions = {"tool-call": "assistant", "tool-response": "user"}
57
- user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
58
-
59
- BROWSER_CONFIG = {
60
- "viewport_size": 1024 * 5,
61
- "downloads_folder": "downloads_folder",
62
- "request_kwargs": {
63
- "headers": {"User-Agent": user_agent},
64
- "timeout": 300,
65
- },
66
- "serpapi_key": os.getenv("SERPAPI_API_KEY"),
67
- }
68
-
69
- # Create downloads folder if it doesn't exist
70
- os.makedirs(f"./{BROWSER_CONFIG['downloads_folder']}", exist_ok=True)
71
-
72
- class SmolaAgent:
73
- def __init__(self):
74
- print("Initializing SmolaAgent...")
75
-
76
- # Initialize model
77
- model_id = "o1" # You can adjust this or make it configurable
78
- model_params = {
79
- "model_id": model_id,
80
- "custom_role_conversions": custom_role_conversions,
81
- "max_completion_tokens": 8192,
82
- }
83
- if model_id == "o1":
84
- model_params["reasoning_effort"] = "high"
85
-
86
- self.model = LiteLLMModel(**model_params)
87
-
88
- # Create agent with tools
89
- text_limit = 100000
90
- browser = SimpleTextBrowser(**BROWSER_CONFIG)
91
- WEB_TOOLS = [
92
- GoogleSearchTool(provider="serper"),
93
- VisitTool(browser),
94
- PageUpTool(browser),
95
- PageDownTool(browser),
96
- FinderTool(browser),
97
- FindNextTool(browser),
98
- ArchiveSearchTool(browser),
99
- TextInspectorTool(self.model, text_limit),
100
- ]
101
-
102
- # Create text webbrowser agent
103
- self.text_webbrowser_agent = ToolCallingAgent(
104
- model=self.model,
105
- tools=WEB_TOOLS,
106
- max_steps=20,
107
- verbosity_level=2,
108
- planning_interval=4,
109
- name="search_agent",
110
- description="""A team member that will search the internet to answer your question.
111
- Ask him for all your questions that require browsing the web.
112
- Provide him as much context as possible, in particular if you need to search on a specific timeframe!
113
- And don't hesitate to provide him with a complex search task, like finding a difference between two webpages.
114
- Your request must be a real sentence, not a google search! Like "Find me this information (...)" rather than a few keywords.
115
- """,
116
- provide_run_summary=True,
117
- )
118
-
119
- self.text_webbrowser_agent.prompt_templates["managed_agent"]["task"] += """You can navigate to .txt online files.
120
- If a non-html page is in another format, especially .pdf or a Youtube video, use tool 'inspect_file_as_text' to inspect it.
121
- Additionally, if after some searching you find out that you need more information to answer the question, you can use `final_answer` with your request for clarification as argument to request for more information."""
122
-
123
- # Create manager agent
124
- self.manager_agent = CodeAgent(
125
- model=self.model,
126
- tools=[visualizer, TextInspectorTool(self.model, text_limit)],
127
- max_steps=12,
128
- verbosity_level=2,
129
- additional_authorized_imports=["*"],
130
- planning_interval=4,
131
- managed_agents=[self.text_webbrowser_agent],
132
- )
133
-
134
- print("SmolaAgent initialized successfully.")
135
-
136
- def __call__(self, question: str) -> str:
137
- print(f"Agent received question: {question[:50]}...")
138
-
139
- # Include the GAIA system prompt in the question to ensure proper answer format
140
- augmented_question = f"""You have one question to answer. It is paramount that you provide a correct answer.
141
- Give it all you can: I know for a fact that you have access to all the relevant tools to solve it and find the correct answer (the answer does exist). Failure or 'I cannot answer' or 'None found' will not be tolerated, success will be rewarded.
142
- Run verification steps if that's needed, you must make sure you find the correct answer!
143
-
144
- {GAIA_SYSTEM_PROMPT}
145
-
146
- Here is the task:
147
- {question}"""
148
-
149
- try:
150
- # Run the agent
151
- result = self.manager_agent.run(augmented_question)
152
-
153
- # Use reformulator to get properly formatted final answer
154
- agent_memory = self.manager_agent.write_memory_to_messages()
155
-
156
- # Add the GAIA system prompt to the reformulation to ensure correct format
157
- for message in agent_memory:
158
- if message.get("role") == "system" and message.get("content"):
159
- if isinstance(message["content"], list):
160
- for content_item in message["content"]:
161
- if content_item.get("type") == "text":
162
- content_item["text"] = GAIA_SYSTEM_PROMPT + "\n\n" + content_item["text"]
163
- else:
164
- message["content"] = GAIA_SYSTEM_PROMPT + "\n\n" + message["content"]
165
- break
166
-
167
- final_answer = prepare_response(augmented_question, agent_memory, self.model)
168
-
169
- print(f"Agent returning answer: {final_answer}")
170
- return final_answer
171
-
172
- except Exception as e:
173
- print(f"Error running agent: {e}")
174
- return "FINAL ANSWER: Unable to determine"
175
-
176
- # Function to extract the exact answer from agent response
177
- def extract_final_answer(agent_response):
178
- if "FINAL ANSWER:" in agent_response:
179
- answer = agent_response.split("FINAL ANSWER:")[1].strip()
180
-
181
- # Additional cleaning to ensure exact match
182
- # Remove any trailing punctuation
183
- answer = answer.rstrip('.,!?;:')
184
-
185
- # Clean numbers (remove commas and units)
186
- # This is a simple example - you might need more sophisticated cleaning
187
- words = answer.split()
188
- for i, word in enumerate(words):
189
- # Try to convert to a number to remove commas and format correctly
190
- try:
191
- num = float(word.replace(',', '').replace('$', '').replace('%', ''))
192
- # Convert to int if it's a whole number
193
- words[i] = str(int(num)) if num.is_integer() else str(num)
194
- except (ValueError, AttributeError):
195
- # Not a number, leave as is
196
- pass
197
-
198
- return ' '.join(words)
199
-
200
- return "Unable to determine"
201
-
202
- # Replace BasicAgent with your SmolaAgent in the run_and_submit_all function
203
- def run_and_submit_all(profile: gr.OAuthProfile | None):
204
- """
205
- Fetches all questions, runs the SmolaAgent on them, submits all answers,
206
- and displays the results.
207
- """
208
- # --- Determine HF Space Runtime URL and Repo URL ---
209
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
210
-
211
- if profile:
212
- username= f"{profile.username}"
213
- print(f"User logged in: {username}")
214
- else:
215
- print("User not logged in.")
216
- return "Please Login to Hugging Face with the button.", None
217
-
218
- api_url = DEFAULT_API_URL
219
- questions_url = f"{api_url}/questions"
220
- submit_url = f"{api_url}/submit"
221
-
222
- # 1. Instantiate Agent
223
- try:
224
- agent = SmolaAgent()
225
- except Exception as e:
226
- print(f"Error instantiating agent: {e}")
227
- return f"Error initializing agent: {e}", None
228
-
229
- # In the case of an app running as a hugging Face space, this link points toward your codebase
230
- agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
231
- print(agent_code)
232
-
233
- # 2. Fetch Questions
234
- print(f"Fetching questions from: {questions_url}")
235
- try:
236
- response = requests.get(questions_url, timeout=15)
237
- response.raise_for_status()
238
- questions_data = response.json()
239
- if not questions_data:
240
- print("Fetched questions list is empty.")
241
- return "Fetched questions list is empty or invalid format.", None
242
- print(f"Fetched {len(questions_data)} questions.")
243
- except requests.exceptions.RequestException as e:
244
- print(f"Error fetching questions: {e}")
245
- return f"Error fetching questions: {e}", None
246
- except requests.exceptions.JSONDecodeError as e:
247
- print(f"Error decoding JSON response from questions endpoint: {e}")
248
- print(f"Response text: {response.text[:500]}")
249
- return f"Error decoding server response for questions: {e}", None
250
- except Exception as e:
251
- print(f"An unexpected error occurred fetching questions: {e}")
252
- return f"An unexpected error occurred fetching questions: {e}", None
253
-
254
- # 3. Run your Agent
255
- results_log = []
256
- answers_payload = []
257
- print(f"Running agent on {len(questions_data)} questions...")
258
- for item in questions_data:
259
- task_id = item.get("task_id")
260
- question_text = item.get("question")
261
-
262
- # Check if there are files associated with this task
263
- try:
264
- files_url = f"{api_url}/files/{task_id}"
265
- files_response = requests.get(files_url, timeout=15)
266
- if files_response.status_code == 200:
267
- # Save the file and provide its path to the agent
268
- # This depends on what format the files are returned in
269
- print(f"Task {task_id} has associated files")
270
- # Handle files if needed
271
- except Exception as e:
272
- print(f"Error checking for files for task {task_id}: {e}")
273
- # Continue even if file check fails
274
-
275
- if not task_id or question_text is None:
276
- print(f"Skipping item with missing task_id or question: {item}")
277
- continue
278
-
279
- try:
280
- # Get full agent response
281
- full_response = agent(question_text)
282
-
283
- # Extract just the final answer part for submission
284
- submitted_answer = extract_final_answer(full_response)
285
-
286
- # Add to submission payload
287
- answers_payload.append({
288
- "task_id": task_id,
289
- "submitted_answer": submitted_answer,
290
- "reasoning_trace": full_response # Optional: include full reasoning
291
- })
292
-
293
- # Log for display
294
- results_log.append({
295
- "Task ID": task_id,
296
- "Question": question_text,
297
- "Submitted Answer": submitted_answer,
298
- "Full Response": full_response
299
- })
300
-
301
- print(f"Processed task {task_id}, answer: {submitted_answer}")
302
-
303
- except Exception as e:
304
- print(f"Error running agent on task {task_id}: {e}")
305
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
306
-
307
- if not answers_payload:
308
- print("Agent did not produce any answers to submit.")
309
- return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
310
-
311
- # 4. Prepare Submission
312
- submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
313
- status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
314
- print(status_update)
315
-
316
- # 5. Submit
317
- print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
318
- try:
319
- response = requests.post(submit_url, json=submission_data, timeout=60)
320
- response.raise_for_status()
321
- result_data = response.json()
322
- final_status = (
323
- f"Submission Successful!\n"
324
- f"User: {result_data.get('username')}\n"
325
- f"Overall Score: {result_data.get('score', 'N/A')}% "
326
- f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
327
- f"Message: {result_data.get('message', 'No message received.')}"
328
- )
329
- print("Submission successful.")
330
- results_df = pd.DataFrame(results_log)
331
- return final_status, results_df
332
- except requests.exceptions.HTTPError as e:
333
- error_detail = f"Server responded with status {e.response.status_code}."
334
- try:
335
- error_json = e.response.json()
336
- error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
337
- except requests.exceptions.JSONDecodeError:
338
- error_detail += f" Response: {e.response.text[:500]}"
339
- status_message = f"Submission Failed: {error_detail}"
340
- print(status_message)
341
- results_df = pd.DataFrame(results_log)
342
- return status_message, results_df
343
- except requests.exceptions.Timeout:
344
- status_message = "Submission Failed: The request timed out."
345
- print(status_message)
346
- results_df = pd.DataFrame(results_log)
347
- return status_message, results_df
348
- except requests.exceptions.RequestException as e:
349
- status_message = f"Submission Failed: Network error - {e}"
350
- print(status_message)
351
- results_df = pd.DataFrame(results_log)
352
- return status_message, results_df
353
- except Exception as e:
354
- status_message = f"An unexpected error occurred during submission: {e}"
355
- print(status_message)
356
- results_df = pd.DataFrame(results_log)
357
- return status_message, results_df
358
-
359
- # --- Build Gradio Interface using Blocks ---
360
- with gr.Blocks() as demo:
361
- gr.Markdown("# Smolagent GAIA Evaluation Runner")
362
- gr.Markdown(
363
- """
364
- **Instructions:**
365
- 1. Log in to your Hugging Face account using the button below.
366
- 2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
367
- ---
368
- **Note:** This process will take some time as the agent processes each question. The agent is specifically configured to
369
- format answers according to the GAIA benchmark requirements:
370
- - Numbers: No commas, no units
371
- - Strings: No articles, no abbreviations
372
- - Lists: Comma-separated values following the above rules
373
- """
374
- )
375
-
376
- gr.LoginButton()
377
-
378
- run_button = gr.Button("Run Evaluation & Submit All Answers")
379
-
380
- status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
381
- results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
382
-
383
- run_button.click(
384
- fn=run_and_submit_all,
385
- outputs=[status_output, results_table]
386
- )
387
 
388
  if __name__ == "__main__":
389
- print("\n" + "-"*30 + " App Starting " + "-"*30)
390
- # Check for SPACE_HOST and SPACE_ID at startup for information
391
- space_host_startup = os.getenv("SPACE_HOST")
392
- space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
393
-
394
- if space_host_startup:
395
- print(f"✅ SPACE_HOST found: {space_host_startup}")
396
- print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
397
- else:
398
- print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
399
-
400
- if space_id_startup: # Print repo URLs if SPACE_ID is found
401
- print(f"✅ SPACE_ID found: {space_id_startup}")
402
- print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
403
- print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
404
- else:
405
- print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
406
-
407
- print("-"*(60 + len(" App Starting ")) + "\n")
408
-
409
- print("Launching Gradio Interface for Smolagent GAIA Evaluation...")
410
- demo.launch(debug=True, share=False)
 
1
+ from run import create_agent
 
 
 
 
 
 
2
 
3
+ from smolagents.gradio_ui import GradioUI
 
4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
+ agent = create_agent()
 
 
 
 
 
7
 
8
+ demo = GradioUI(agent)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  if __name__ == "__main__":
11
+ demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
run.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import os
3
+ import threading
4
+
5
+ from dotenv import load_dotenv
6
+ from huggingface_hub import login
7
+ from scripts.text_inspector_tool import TextInspectorTool
8
+ from scripts.text_web_browser import (
9
+ ArchiveSearchTool,
10
+ FinderTool,
11
+ FindNextTool,
12
+ PageDownTool,
13
+ PageUpTool,
14
+ SimpleTextBrowser,
15
+ VisitTool,
16
+ )
17
+ from scripts.visual_qa import visualizer
18
+
19
+ from smolagents import (
20
+ CodeAgent,
21
+ GoogleSearchTool,
22
+ # InferenceClientModel,
23
+ LiteLLMModel,
24
+ ToolCallingAgent,
25
+ )
26
+
27
+
28
+ load_dotenv(override=True)
29
+ login(os.getenv("HF_TOKEN"))
30
+
31
+ append_answer_lock = threading.Lock()
32
+
33
+
34
+ def parse_args():
35
+ parser = argparse.ArgumentParser()
36
+ parser.add_argument(
37
+ "question", type=str, help="for example: 'How many studio albums did Mercedes Sosa release before 2007?'"
38
+ )
39
+ parser.add_argument("--model-id", type=str, default="o1")
40
+ return parser.parse_args()
41
+
42
+
43
+ custom_role_conversions = {"tool-call": "assistant", "tool-response": "user"}
44
+
45
+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
46
+
47
+ BROWSER_CONFIG = {
48
+ "viewport_size": 1024 * 5,
49
+ "downloads_folder": "downloads_folder",
50
+ "request_kwargs": {
51
+ "headers": {"User-Agent": user_agent},
52
+ "timeout": 300,
53
+ },
54
+ "serpapi_key": os.getenv("SERPAPI_API_KEY"),
55
+ }
56
+
57
+ os.makedirs(f"./{BROWSER_CONFIG['downloads_folder']}", exist_ok=True)
58
+
59
+
60
+ def create_agent(model_id="o1"):
61
+ model_params = {
62
+ "model_id": model_id,
63
+ "custom_role_conversions": custom_role_conversions,
64
+ "max_completion_tokens": 8192,
65
+ }
66
+ if model_id == "o1":
67
+ model_params["reasoning_effort"] = "high"
68
+ model = LiteLLMModel(**model_params)
69
+
70
+ text_limit = 100000
71
+ browser = SimpleTextBrowser(**BROWSER_CONFIG)
72
+ WEB_TOOLS = [
73
+ GoogleSearchTool(provider="serper"),
74
+ VisitTool(browser),
75
+ PageUpTool(browser),
76
+ PageDownTool(browser),
77
+ FinderTool(browser),
78
+ FindNextTool(browser),
79
+ ArchiveSearchTool(browser),
80
+ TextInspectorTool(model, text_limit),
81
+ ]
82
+ text_webbrowser_agent = ToolCallingAgent(
83
+ model=model,
84
+ tools=WEB_TOOLS,
85
+ max_steps=20,
86
+ verbosity_level=2,
87
+ planning_interval=4,
88
+ name="search_agent",
89
+ description="""A team member that will search the internet to answer your question.
90
+ Ask him for all your questions that require browsing the web.
91
+ Provide him as much context as possible, in particular if you need to search on a specific timeframe!
92
+ And don't hesitate to provide him with a complex search task, like finding a difference between two webpages.
93
+ Your request must be a real sentence, not a google search! Like "Find me this information (...)" rather than a few keywords.
94
+ """,
95
+ provide_run_summary=True,
96
+ )
97
+ text_webbrowser_agent.prompt_templates["managed_agent"]["task"] += """You can navigate to .txt online files.
98
+ If a non-html page is in another format, especially .pdf or a Youtube video, use tool 'inspect_file_as_text' to inspect it.
99
+ Additionally, if after some searching you find out that you need more information to answer the question, you can use `final_answer` with your request for clarification as argument to request for more information."""
100
+
101
+ manager_agent = CodeAgent(
102
+ model=model,
103
+ tools=[visualizer, TextInspectorTool(model, text_limit)],
104
+ max_steps=12,
105
+ verbosity_level=2,
106
+ additional_authorized_imports=["*"],
107
+ planning_interval=4,
108
+ managed_agents=[text_webbrowser_agent],
109
+ )
110
+
111
+ return manager_agent
112
+
113
+
114
+ def main():
115
+ args = parse_args()
116
+
117
+ agent = create_agent(model_id=args.model_id)
118
+
119
+ answer = agent.run(args.question)
120
+
121
+ print(f"Got this answer: {answer}")
122
+
123
+
124
+ if __name__ == "__main__":
125
+ main()
run_gaia.py ADDED
@@ -0,0 +1,277 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # EXAMPLE COMMAND: python examples/open_deep_research/run_gaia.py --concurrency 32 --run-name generate-traces-03-apr-noplanning --model-id gpt-4o
2
+ import argparse
3
+ import json
4
+ import os
5
+ import threading
6
+ from concurrent.futures import ThreadPoolExecutor, as_completed
7
+ from datetime import datetime
8
+ from pathlib import Path
9
+
10
+ import datasets
11
+ import pandas as pd
12
+ from dotenv import load_dotenv
13
+ from huggingface_hub import login
14
+ from scripts.reformulator import prepare_response
15
+ from scripts.run_agents import (
16
+ get_single_file_description,
17
+ get_zip_description,
18
+ )
19
+ from scripts.text_inspector_tool import TextInspectorTool
20
+ from scripts.text_web_browser import (
21
+ ArchiveSearchTool,
22
+ FinderTool,
23
+ FindNextTool,
24
+ PageDownTool,
25
+ PageUpTool,
26
+ SimpleTextBrowser,
27
+ VisitTool,
28
+ )
29
+ from scripts.visual_qa import visualizer
30
+ from tqdm import tqdm
31
+
32
+ from smolagents import (
33
+ CodeAgent,
34
+ GoogleSearchTool,
35
+ LiteLLMModel,
36
+ Model,
37
+ ToolCallingAgent,
38
+ )
39
+
40
+
41
+ load_dotenv(override=True)
42
+ login(os.getenv("HF_TOKEN"))
43
+
44
+ append_answer_lock = threading.Lock()
45
+
46
+
47
+ def parse_args():
48
+ parser = argparse.ArgumentParser()
49
+ parser.add_argument("--concurrency", type=int, default=8)
50
+ parser.add_argument("--model-id", type=str, default="o1")
51
+ parser.add_argument("--run-name", type=str, required=True)
52
+ return parser.parse_args()
53
+
54
+
55
+ ### IMPORTANT: EVALUATION SWITCHES
56
+
57
+ print("Make sure you deactivated Tailscale VPN, else some URLs will be blocked!")
58
+
59
+ USE_OPEN_MODELS = False
60
+
61
+ SET = "validation"
62
+
63
+ custom_role_conversions = {"tool-call": "assistant", "tool-response": "user"}
64
+
65
+ ### LOAD EVALUATION DATASET
66
+
67
+ eval_ds = datasets.load_dataset("gaia-benchmark/GAIA", "2023_all")[SET]
68
+ eval_ds = eval_ds.rename_columns({"Question": "question", "Final answer": "true_answer", "Level": "task"})
69
+
70
+
71
+ def preprocess_file_paths(row):
72
+ if len(row["file_name"]) > 0:
73
+ row["file_name"] = f"data/gaia/{SET}/" + row["file_name"]
74
+ return row
75
+
76
+
77
+ eval_ds = eval_ds.map(preprocess_file_paths)
78
+ eval_df = pd.DataFrame(eval_ds)
79
+ print("Loaded evaluation dataset:")
80
+ print(eval_df["task"].value_counts())
81
+
82
+ user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36 Edg/119.0.0.0"
83
+
84
+ BROWSER_CONFIG = {
85
+ "viewport_size": 1024 * 5,
86
+ "downloads_folder": "downloads_folder",
87
+ "request_kwargs": {
88
+ "headers": {"User-Agent": user_agent},
89
+ "timeout": 300,
90
+ },
91
+ "serpapi_key": os.getenv("SERPAPI_API_KEY"),
92
+ }
93
+
94
+ os.makedirs(f"./{BROWSER_CONFIG['downloads_folder']}", exist_ok=True)
95
+
96
+
97
+ def create_agent_team(model: Model):
98
+ text_limit = 100000
99
+ ti_tool = TextInspectorTool(model, text_limit)
100
+
101
+ browser = SimpleTextBrowser(**BROWSER_CONFIG)
102
+
103
+ WEB_TOOLS = [
104
+ GoogleSearchTool(provider="serper"),
105
+ VisitTool(browser),
106
+ PageUpTool(browser),
107
+ PageDownTool(browser),
108
+ FinderTool(browser),
109
+ FindNextTool(browser),
110
+ ArchiveSearchTool(browser),
111
+ TextInspectorTool(model, text_limit),
112
+ ]
113
+
114
+ text_webbrowser_agent = ToolCallingAgent(
115
+ model=model,
116
+ tools=WEB_TOOLS,
117
+ max_steps=20,
118
+ verbosity_level=2,
119
+ planning_interval=4,
120
+ name="search_agent",
121
+ description="""A team member that will search the internet to answer your question.
122
+ Ask him for all your questions that require browsing the web.
123
+ Provide him as much context as possible, in particular if you need to search on a specific timeframe!
124
+ And don't hesitate to provide him with a complex search task, like finding a difference between two webpages.
125
+ Your request must be a real sentence, not a google search! Like "Find me this information (...)" rather than a few keywords.
126
+ """,
127
+ provide_run_summary=True,
128
+ )
129
+ text_webbrowser_agent.prompt_templates["managed_agent"]["task"] += """You can navigate to .txt online files.
130
+ If a non-html page is in another format, especially .pdf or a Youtube video, use tool 'inspect_file_as_text' to inspect it.
131
+ Additionally, if after some searching you find out that you need more information to answer the question, you can use `final_answer` with your request for clarification as argument to request for more information."""
132
+
133
+ manager_agent = CodeAgent(
134
+ model=model,
135
+ tools=[visualizer, ti_tool],
136
+ max_steps=12,
137
+ verbosity_level=2,
138
+ additional_authorized_imports=["*"],
139
+ planning_interval=4,
140
+ managed_agents=[text_webbrowser_agent],
141
+ )
142
+ return manager_agent
143
+
144
+
145
+ def append_answer(entry: dict, jsonl_file: str) -> None:
146
+ jsonl_file = Path(jsonl_file)
147
+ jsonl_file.parent.mkdir(parents=True, exist_ok=True)
148
+ with append_answer_lock, open(jsonl_file, "a", encoding="utf-8") as fp:
149
+ fp.write(json.dumps(entry) + "\n")
150
+ assert os.path.exists(jsonl_file), "File not found!"
151
+ print("Answer exported to file:", jsonl_file.resolve())
152
+
153
+
154
+ def answer_single_question(example, model_id, answers_file, visual_inspection_tool):
155
+ model_params = {
156
+ "model_id": model_id,
157
+ "custom_role_conversions": custom_role_conversions,
158
+ }
159
+ if model_id == "o1":
160
+ model_params["reasoning_effort"] = "high"
161
+ model_params["max_completion_tokens"] = 8192
162
+ else:
163
+ model_params["max_tokens"] = 4096
164
+ model = LiteLLMModel(**model_params)
165
+ # model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct", provider="together", max_tokens=4096)
166
+ document_inspection_tool = TextInspectorTool(model, 100000)
167
+
168
+ agent = create_agent_team(model)
169
+
170
+ augmented_question = """You have one question to answer. It is paramount that you provide a correct answer.
171
+ Give it all you can: I know for a fact that you have access to all the relevant tools to solve it and find the correct answer (the answer does exist). Failure or 'I cannot answer' or 'None found' will not be tolerated, success will be rewarded.
172
+ Run verification steps if that's needed, you must make sure you find the correct answer!
173
+ Here is the task:
174
+ """ + example["question"]
175
+
176
+ if example["file_name"]:
177
+ if ".zip" in example["file_name"]:
178
+ prompt_use_files = "\n\nTo solve the task above, you will have to use these attached files:\n"
179
+ prompt_use_files += get_zip_description(
180
+ example["file_name"], example["question"], visual_inspection_tool, document_inspection_tool
181
+ )
182
+ else:
183
+ prompt_use_files = "\n\nTo solve the task above, you will have to use this attached file:"
184
+ prompt_use_files += get_single_file_description(
185
+ example["file_name"], example["question"], visual_inspection_tool, document_inspection_tool
186
+ )
187
+ augmented_question += prompt_use_files
188
+
189
+ start_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
190
+ try:
191
+ # Run agent 🚀
192
+ final_result = agent.run(augmented_question)
193
+
194
+ agent_memory = agent.write_memory_to_messages()
195
+
196
+ final_result = prepare_response(augmented_question, agent_memory, reformulation_model=model)
197
+
198
+ output = str(final_result)
199
+ for memory_step in agent.memory.steps:
200
+ memory_step.model_input_messages = None
201
+ intermediate_steps = agent_memory
202
+
203
+ # Check for parsing errors which indicate the LLM failed to follow the required format
204
+ parsing_error = True if any(["AgentParsingError" in step for step in intermediate_steps]) else False
205
+
206
+ # check if iteration limit exceeded
207
+ iteration_limit_exceeded = True if "Agent stopped due to iteration limit or time limit." in output else False
208
+ raised_exception = False
209
+
210
+ except Exception as e:
211
+ print("Error on ", augmented_question, e)
212
+ output = None
213
+ intermediate_steps = []
214
+ parsing_error = False
215
+ iteration_limit_exceeded = False
216
+ exception = e
217
+ raised_exception = True
218
+ end_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
219
+ token_counts_manager = agent.monitor.get_total_token_counts()
220
+ token_counts_web = list(agent.managed_agents.values())[0].monitor.get_total_token_counts()
221
+ total_token_counts = {
222
+ "input": token_counts_manager["input"] + token_counts_web["input"],
223
+ "output": token_counts_manager["output"] + token_counts_web["output"],
224
+ }
225
+ annotated_example = {
226
+ "agent_name": model.model_id,
227
+ "question": example["question"],
228
+ "augmented_question": augmented_question,
229
+ "prediction": output,
230
+ "intermediate_steps": intermediate_steps,
231
+ "parsing_error": parsing_error,
232
+ "iteration_limit_exceeded": iteration_limit_exceeded,
233
+ "agent_error": str(exception) if raised_exception else None,
234
+ "task": example["task"],
235
+ "task_id": example["task_id"],
236
+ "true_answer": example["true_answer"],
237
+ "start_time": start_time,
238
+ "end_time": end_time,
239
+ "token_counts": total_token_counts,
240
+ }
241
+ append_answer(annotated_example, answers_file)
242
+
243
+
244
+ def get_examples_to_answer(answers_file, eval_ds) -> list[dict]:
245
+ print(f"Loading answers from {answers_file}...")
246
+ try:
247
+ done_questions = pd.read_json(answers_file, lines=True)["question"].tolist()
248
+ print(f"Found {len(done_questions)} previous results!")
249
+ except Exception as e:
250
+ print("Error when loading records: ", e)
251
+ print("No usable records! ▶️ Starting new.")
252
+ done_questions = []
253
+ return [line for line in eval_ds.to_list() if line["question"] not in done_questions]
254
+
255
+
256
+ def main():
257
+ args = parse_args()
258
+ print(f"Starting run with arguments: {args}")
259
+
260
+ answers_file = f"output/{SET}/{args.run_name}.jsonl"
261
+ tasks_to_run = get_examples_to_answer(answers_file, eval_ds)
262
+
263
+ with ThreadPoolExecutor(max_workers=args.concurrency) as exe:
264
+ futures = [
265
+ exe.submit(answer_single_question, example, args.model_id, answers_file, visualizer)
266
+ for example in tasks_to_run
267
+ ]
268
+ for f in tqdm(as_completed(futures), total=len(tasks_to_run), desc="Processing tasks"):
269
+ f.result()
270
+
271
+ # for example in tasks_to_run:
272
+ # answer_single_question(example, args.model_id, answers_file, visualizer)
273
+ print("All tasks processed.")
274
+
275
+
276
+ if __name__ == "__main__":
277
+ main()