mobrobro commited on
Commit
1868b08
·
verified ·
1 Parent(s): 81917a3

Revised app.py

Browse files
Files changed (1) hide show
  1. app.py +243 -29
app.py CHANGED
@@ -3,25 +3,206 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
- # (Keep Constants as is)
8
  # --- Constants ---
9
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
10
 
11
- # --- Basic Agent Definition ---
12
- # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
13
- class BasicAgent:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14
  def __init__(self):
15
- print("BasicAgent initialized.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  def __call__(self, question: str) -> str:
17
- print(f"Agent received question (first 50 chars): {question[:50]}...")
18
- fixed_answer = "This is a default answer."
19
- print(f"Agent returning fixed answer: {fixed_answer}")
20
- return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- def run_and_submit_all( profile: gr.OAuthProfile | None):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  """
24
- Fetches all questions, runs the BasicAgent on them, submits all answers,
25
  and displays the results.
26
  """
27
  # --- Determine HF Space Runtime URL and Repo URL ---
@@ -38,13 +219,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
38
  questions_url = f"{api_url}/questions"
39
  submit_url = f"{api_url}/submit"
40
 
41
- # 1. Instantiate Agent ( modify this part to create your agent)
42
  try:
43
- agent = BasicAgent()
44
  except Exception as e:
45
  print(f"Error instantiating agent: {e}")
46
  return f"Error initializing agent: {e}", None
47
- # In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
 
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  print(agent_code)
50
 
@@ -76,13 +258,48 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
76
  for item in questions_data:
77
  task_id = item.get("task_id")
78
  question_text = item.get("question")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
79
  if not task_id or question_text is None:
80
  print(f"Skipping item with missing task_id or question: {item}")
81
  continue
 
82
  try:
83
- submitted_answer = agent(question_text)
84
- answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
85
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  except Exception as e:
87
  print(f"Error running agent on task {task_id}: {e}")
88
  results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
@@ -139,22 +356,20 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
139
  results_df = pd.DataFrame(results_log)
140
  return status_message, results_df
141
 
142
-
143
  # --- Build Gradio Interface using Blocks ---
144
  with gr.Blocks() as demo:
145
- gr.Markdown("# Basic Agent Evaluation Runner")
146
  gr.Markdown(
147
  """
148
  **Instructions:**
149
-
150
- 1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
151
- 2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
152
- 3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
153
-
154
  ---
155
- **Disclaimers:**
156
- Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
157
- This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
 
 
158
  """
159
  )
160
 
@@ -163,7 +378,6 @@ with gr.Blocks() as demo:
163
  run_button = gr.Button("Run Evaluation & Submit All Answers")
164
 
165
  status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
166
- # Removed max_rows=10 from DataFrame constructor
167
  results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
168
 
169
  run_button.click(
@@ -192,5 +406,5 @@ if __name__ == "__main__":
192
 
193
  print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
- print("Launching Gradio Interface for Basic Agent Evaluation...")
196
  demo.launch(debug=True, share=False)
 
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 ---
 
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
 
 
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}"})
 
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
 
 
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(
 
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)