arijit121 commited on
Commit
c765b20
·
1 Parent(s): 8c5c24b
Files changed (6) hide show
  1. README.md +22 -4
  2. agent.json +21 -22
  3. app.py +250 -52
  4. prompts.yaml +17 -24
  5. requirements.txt +2 -1
  6. tools/visit_webpage.py +4 -1
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
- title: First Agent Template
3
- emoji:
4
- colorFrom: pink
5
- colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 5.23.1
8
  app_file: app.py
@@ -13,6 +13,24 @@ tags:
13
  - smolagent
14
  - tool
15
  - agent-course
 
16
  ---
17
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: GAIA Agent
3
+ emoji: 🤖
4
+ colorFrom: blue
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 5.23.1
8
  app_file: app.py
 
13
  - smolagent
14
  - tool
15
  - agent-course
16
+ - gaia
17
  ---
18
 
19
+ # GAIA Benchmark Agent
20
+
21
+ A smolagents-based CodeAgent designed to pass the GAIA Level 1 benchmark for the HuggingFace Agents Course (Unit 4 Final Assignment).
22
+
23
+ ## Features
24
+ - **DuckDuckGo Web Search** — Real-time information retrieval
25
+ - **Webpage Visitor** — Deep-reads any URL as markdown
26
+ - **Code Execution** — Runs Python code for computation and reasoning
27
+ - **Planning** — Periodic re-planning for multi-step tasks
28
+ - **Exact Answer Extraction** — Outputs only the final answer value
29
+
30
+ ## Usage
31
+ 1. Log in with your HuggingFace account.
32
+ 2. Click **Run Evaluation & Submit All Answers**.
33
+ 3. Wait for the agent to process all 20 questions.
34
+ 4. View your score!
35
+
36
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
agent.json CHANGED
@@ -7,35 +7,20 @@
7
  "model": {
8
  "class": "HfApiModel",
9
  "data": {
10
- "max_tokens": 2096,
11
- "temperature": 0.5,
12
  "last_input_token_count": null,
13
  "last_output_token_count": null,
14
  "model_id": "Qwen/Qwen2.5-Coder-32B-Instruct",
15
  "custom_role_conversions": null
16
  }
17
  },
18
- "prompt_templates": {
19
- "system_prompt": "You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.\nTo do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.\nTo solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.\n\nAt each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.\nThen in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.\nDuring each intermediate step, you can use 'print()' to save whatever important information you will then need.\nThese print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.\nIn the end you have to return a final answer using the `final_answer` tool.\n\nHere are a few examples using notional tools:\n---\nTask: \"Generate an image of the oldest person in this document.\"\n\nThought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.\nCode:\n```py\nanswer = document_qa(document=document, question=\"Who is the oldest person mentioned?\")\nprint(answer)\n```<end_code>\nObservation: \"The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland.\"\n\nThought: I will now generate an image showcasing the oldest person.\nCode:\n```py\nimage = image_generator(\"A portrait of John Doe, a 55-year-old man living in Canada.\")\nfinal_answer(image)\n```<end_code>\n\n---\nTask: \"What is the result of the following operation: 5 + 3 + 1294.678?\"\n\nThought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool\nCode:\n```py\nresult = 5 + 3 + 1294.678\nfinal_answer(result)\n```<end_code>\n\n---\nTask:\n\"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.\nYou have been provided with these additional arguments, that you can access using the keys as variables in your python code:\n{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}\"\n\nThought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.\nCode:\n```py\ntranslated_question = translator(question=question, src_lang=\"French\", tgt_lang=\"English\")\nprint(f\"The translated question is {translated_question}.\")\nanswer = image_qa(image=image, question=translated_question)\nfinal_answer(f\"The answer is {answer}\")\n```<end_code>\n\n---\nTask:\nIn a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.\nWhat does he say was the consequence of Einstein learning too much math on his creativity, in one word?\n\nThought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.\nCode:\n```py\npages = search(query=\"1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein\")\nprint(pages)\n```<end_code>\nObservation:\nNo result found for query \"1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein\".\n\nThought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.\nCode:\n```py\npages = search(query=\"1979 interview Stanislaus Ulam\")\nprint(pages)\n```<end_code>\nObservation:\nFound 6 pages:\n[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)\n\n[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)\n\n(truncated)\n\nThought: I will read the first 2 pages to know more.\nCode:\n```py\nfor url in [\"https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/\", \"https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/\"]:\n whole_page = visit_webpage(url)\n print(whole_page)\n print(\"\\n\" + \"=\"*80 + \"\\n\") # Print separator between pages\n```<end_code>\nObservation:\nManhattan Project Locations:\nLos Alamos, NM\nStanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at\n(truncated)\n\nThought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: \"He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity.\" Let's answer in one word.\nCode:\n```py\nfinal_answer(\"diminished\")\n```<end_code>\n\n---\nTask: \"Which city has the highest population: Guangzhou or Shanghai?\"\n\nThought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.\nCode:\n```py\nfor city in [\"Guangzhou\", \"Shanghai\"]:\n print(f\"Population {city}:\", search(f\"{city} population\")\n```<end_code>\nObservation:\nPopulation Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']\nPopulation Shanghai: '26 million (2019)'\n\nThought: Now I know that Shanghai has the highest population.\nCode:\n```py\nfinal_answer(\"Shanghai\")\n```<end_code>\n\n---\nTask: \"What is the current age of the pope, raised to the power 0.36?\"\n\nThought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.\nCode:\n```py\npope_age_wiki = wiki(query=\"current pope age\")\nprint(\"Pope age as per wikipedia:\", pope_age_wiki)\npope_age_search = web_search(query=\"current pope age\")\nprint(\"Pope age as per google search:\", pope_age_search)\n```<end_code>\nObservation:\nPope age: \"The pope Francis is currently 88 years old.\"\n\nThought: I know that the pope is 88 years old. Let's compute the result using python code.\nCode:\n```py\npope_current_age = 88 ** 0.36\nfinal_answer(pope_current_age)\n```<end_code>\n\nAbove example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:\n{%- for tool in tools.values() %}\n- {{ tool.name }}: {{ tool.description }}\n Takes inputs: {{tool.inputs}}\n Returns an output of type: {{tool.output_type}}\n{%- endfor %}\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task', a long string explaining your task.\nGiven that this team member is a real human, you should be very verbose in your task.\nHere is a list of the team members that you can call:\n{%- for agent in managed_agents.values() %}\n- {{ agent.name }}: {{ agent.description }}\n{%- endfor %}\n{%- else %}\n{%- endif %}\n\nHere are the rules you should always follow to solve your task:\n1. Always provide a 'Thought:' sequence, and a 'Code:\\n```py' sequence ending with '```<end_code>' sequence, else you will fail.\n2. Use only variables that you have defined!\n3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': \"What is the place where James Bond lives?\"})', but use the arguments directly as in 'answer = wiki(query=\"What is the place where James Bond lives?\")'.\n4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.\n5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.\n6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.\n7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.\n8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}\n9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.\n10. Don't give up! You're in charge of solving the task, not providing directions to solve it.\n\nNow Begin! If you solve the task correctly, you will receive a reward of $1,000,000.",
20
- "planning": {
21
- "initial_facts": "Below I will present you a task.\n\nYou will now build a comprehensive preparatory survey of which facts we have at our disposal and which ones we still need.\nTo do so, you will have to read the task and identify things that must be discovered in order to successfully complete it.\nDon't make any assumptions. For each item, provide a thorough reasoning. Here is how you will structure this survey:\n\n---\n### 1. Facts given in the task\nList here the specific facts given in the task that could help you (there might be nothing here).\n\n### 2. Facts to look up\nList here any facts that we may need to look up.\nAlso list where to find each of these, for instance a website, a file... - maybe the task contains some sources that you should re-use here.\n\n### 3. Facts to derive\nList here anything that we want to derive from the above by logical reasoning, for instance computation or simulation.\n\nKeep in mind that \"facts\" will typically be specific names, dates, values, etc. Your answer should use the below headings:\n### 1. Facts given in the task\n### 2. Facts to look up\n### 3. Facts to derive\nDo not add anything else.",
22
- "initial_plan": "You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.\n\nNow for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.\nThis plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.\nDo not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.\nAfter writing the final step of the plan, write the '\\n<end_plan>' tag and stop there.\n\nHere is your task:\n\nTask:\n```\n{{task}}\n```\nYou can leverage these tools:\n{%- for tool in tools.values() %}\n- {{ tool.name }}: {{ tool.description }}\n Takes inputs: {{tool.inputs}}\n Returns an output of type: {{tool.output_type}}\n{%- endfor %}\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'request', a long string explaining your request.\nGiven that this team member is a real human, you should be very verbose in your request.\nHere is a list of the team members that you can call:\n{%- for agent in managed_agents.values() %}\n- {{ agent.name }}: {{ agent.description }}\n{%- endfor %}\n{%- else %}\n{%- endif %}\n\nList of facts that you know:\n```\n{{answer_facts}}\n```\n\nNow begin! Write your plan below.",
23
- "update_facts_pre_messages": "You are a world expert at gathering known and unknown facts based on a conversation.\nBelow you will find a task, and a history of attempts made to solve the task. You will have to produce a list of these:\n### 1. Facts given in the task\n### 2. Facts that we have learned\n### 3. Facts still to look up\n### 4. Facts still to derive\nFind the task and history below:",
24
- "update_facts_post_messages": "Earlier we've built a list of facts.\nBut since in your previous steps you may have learned useful new facts or invalidated some false ones.\nPlease update your list of facts based on the previous history, and provide these headings:\n### 1. Facts given in the task\n### 2. Facts that we have learned\n### 3. Facts still to look up\n### 4. Facts still to derive\n\nNow write your new list of facts below.",
25
- "update_plan_pre_messages": "You are a world expert at making efficient plans to solve any task using a set of carefully crafted tools.\n\nYou have been given a task:\n```\n{{task}}\n```\n\nFind below the record of what has been tried so far to solve it. Then you will be asked to make an updated plan to solve the task.\nIf the previous tries so far have met some success, you can make an updated plan based on these actions.\nIf you are stalled, you can make a completely new plan starting from scratch.",
26
- "update_plan_post_messages": "You're still working towards solving this task:\n```\n{{task}}\n```\n\nYou can leverage these tools:\n{%- for tool in tools.values() %}\n- {{ tool.name }}: {{ tool.description }}\n Takes inputs: {{tool.inputs}}\n Returns an output of type: {{tool.output_type}}\n{%- endfor %}\n\n{%- if managed_agents and managed_agents.values() | list %}\nYou can also give tasks to team members.\nCalling a team member works the same as for calling a tool: simply, the only argument you can give in the call is 'task'.\nGiven that this team member is a real human, you should be very verbose in your task, it should be a long string providing informations as detailed as necessary.\nHere is a list of the team members that you can call:\n{%- for agent in managed_agents.values() %}\n- {{ agent.name }}: {{ agent.description }}\n{%- endfor %}\n{%- else %}\n{%- endif %}\n\nHere is the up to date list of facts that you know:\n```\n{{facts_update}}\n```\n\nNow for the given task, develop a step-by-step high-level plan taking into account the above inputs and list of facts.\nThis plan should involve individual tasks based on the available tools, that if executed correctly will yield the correct answer.\nBeware that you have {remaining_steps} steps remaining.\nDo not skip steps, do not add any superfluous steps. Only write the high-level plan, DO NOT DETAIL INDIVIDUAL TOOL CALLS.\nAfter writing the final step of the plan, write the '\\n<end_plan>' tag and stop there.\n\nNow write your new plan below."
27
- },
28
- "managed_agent": {
29
- "task": "You're a helpful agent named '{{name}}'.\nYou have been submitted this task by your manager.\n---\nTask:\n{{task}}\n---\nYou're helping your manager solve a wider task: so make sure to not provide a one-line answer, but give as much information as possible to give them a clear understanding of the answer.\n\nYour final_answer WILL HAVE to contain these parts:\n### 1. Task outcome (short version):\n### 2. Task outcome (extremely detailed version):\n### 3. Additional context (if relevant):\n\nPut all these in your final_answer tool, everything that you do not pass as an argument to final_answer will be lost.\nAnd even if your task resolution is not successful, please return as much context as possible, so that your manager can act upon this feedback.",
30
- "report": "Here is the final answer from your managed agent '{{name}}':\n{{final_answer}}"
31
- }
32
- },
33
- "max_steps": 6,
34
  "verbosity_level": 1,
35
  "grammar": null,
36
- "planning_interval": null,
37
- "name": null,
38
- "description": null,
39
  "authorized_imports": [
40
  "unicodedata",
41
  "stat",
@@ -48,6 +33,20 @@
48
  "queue",
49
  "time",
50
  "collections",
51
- "re"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  ]
53
  }
 
7
  "model": {
8
  "class": "HfApiModel",
9
  "data": {
10
+ "max_tokens": 4096,
11
+ "temperature": 0.1,
12
  "last_input_token_count": null,
13
  "last_output_token_count": null,
14
  "model_id": "Qwen/Qwen2.5-Coder-32B-Instruct",
15
  "custom_role_conversions": null
16
  }
17
  },
18
+ "max_steps": 12,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19
  "verbosity_level": 1,
20
  "grammar": null,
21
+ "planning_interval": 3,
22
+ "name": "gaia_agent",
23
+ "description": "An agent designed for GAIA benchmark question answering.",
24
  "authorized_imports": [
25
  "unicodedata",
26
  "stat",
 
33
  "queue",
34
  "time",
35
  "collections",
36
+ "re",
37
+ "json",
38
+ "os",
39
+ "sys",
40
+ "csv",
41
+ "string",
42
+ "hashlib",
43
+ "functools",
44
+ "operator",
45
+ "fractions",
46
+ "decimal",
47
+ "typing",
48
+ "io",
49
+ "base64",
50
+ "urllib"
51
  ]
52
  }
app.py CHANGED
@@ -1,69 +1,267 @@
1
- from smolagents import CodeAgent,DuckDuckGoSearchTool, HfApiModel,load_tool,tool
2
- import datetime
 
 
3
  import requests
4
- import pytz
 
 
 
 
 
5
  import yaml
 
6
  from tools.final_answer import FinalAnswerTool
 
 
7
 
8
- from Gradio_UI import GradioUI
 
9
 
10
- # Below is an example of a tool that does nothing. Amaze us with your creativity !
11
- @tool
12
- def my_custom_tool(arg1:str, arg2:int)-> str: #it's import to specify the return type
13
- #Keep this format for the description / args / args description but feel free to modify the tool
14
- """A tool that does nothing yet
15
- Args:
16
- arg1: the first argument
17
- arg2: the second argument
18
- """
19
- return "What magic will you build ?"
20
 
21
- @tool
22
- def get_current_time_in_timezone(timezone: str) -> str:
23
- """A tool that fetches the current local time in a specified timezone.
24
- Args:
25
- timezone: A string representing a valid timezone (e.g., 'America/New_York').
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  try:
28
- # Create timezone object
29
- tz = pytz.timezone(timezone)
30
- # Get current time in that timezone
31
- local_time = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M:%S")
32
- return f"The current local time in {timezone} is: {local_time}"
33
  except Exception as e:
34
- return f"Error fetching time for timezone '{timezone}': {str(e)}"
 
35
 
 
 
36
 
37
- final_answer = FinalAnswerTool()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # If the agent does not answer, the model is overloaded, please use another model or the following Hugging Face Endpoint that also contains qwen2.5 coder:
40
- # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
- model = HfApiModel(
43
- max_tokens=2096,
44
- temperature=0.5,
45
- model_id='Qwen/Qwen2.5-Coder-32B-Instruct',# it is possible that this model may be overloaded
46
- custom_role_conversions=None,
47
- )
48
 
 
 
 
 
 
 
 
 
49
 
50
- # Import tool from Hub
51
- image_generation_tool = load_tool("agents-course/text-to-image", trust_remote_code=True)
52
-
53
- with open("prompts.yaml", 'r') as stream:
54
- prompt_templates = yaml.safe_load(stream)
55
-
56
- agent = CodeAgent(
57
- model=model,
58
- tools=[final_answer], ## add your tools here (don't remove final answer)
59
- max_steps=6,
60
- verbosity_level=1,
61
- grammar=None,
62
- planning_interval=None,
63
- name=None,
64
- description=None,
65
- prompt_templates=prompt_templates
66
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
 
 
 
 
68
 
69
- GradioUI(agent).launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """GAIA Benchmark Evaluation Runner — smolagents CodeAgent"""
2
+ import os
3
+ import re
4
+ import gradio as gr
5
  import requests
6
+ import pandas as pd
7
+ from smolagents import (
8
+ CodeAgent,
9
+ HfApiModel,
10
+ DuckDuckGoSearchTool,
11
+ )
12
  import yaml
13
+
14
  from tools.final_answer import FinalAnswerTool
15
+ from tools.visit_webpage import VisitWebpageTool
16
+ from tools.web_search import DuckDuckGoSearchTool as CustomSearchTool
17
 
18
+ # --- Constants ---
19
+ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
20
 
 
 
 
 
 
 
 
 
 
 
21
 
22
+ def build_agent():
23
+ """Build a smolagents CodeAgent equipped for GAIA benchmark tasks."""
24
+
25
+ # Model — Use the HF Inference API (free tier)
26
+ # Fallback endpoint if the main model is overloaded:
27
+ # model_id='https://pflgm2locj2t89co.us-east-1.aws.endpoints.huggingface.cloud'
28
+ model = HfApiModel(
29
+ max_tokens=4096,
30
+ temperature=0.1,
31
+ model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
32
+ custom_role_conversions=None,
33
+ )
34
+
35
+ # Tools
36
+ final_answer = FinalAnswerTool()
37
+ visit_webpage = VisitWebpageTool()
38
+ search_tool = CustomSearchTool(max_results=5)
39
+
40
+ # Load prompt templates
41
+ with open("prompts.yaml", "r") as stream:
42
+ prompt_templates = yaml.safe_load(stream)
43
+
44
+ agent = CodeAgent(
45
+ model=model,
46
+ tools=[search_tool, visit_webpage, final_answer],
47
+ max_steps=12,
48
+ verbosity_level=1,
49
+ grammar=None,
50
+ planning_interval=3,
51
+ name="gaia_agent",
52
+ description="An agent designed for GAIA benchmark question answering.",
53
+ prompt_templates=prompt_templates,
54
+ )
55
+ return agent
56
+
57
+
58
+ def extract_answer(raw_answer: str) -> str:
59
+ """Clean agent output to extract only the final answer value."""
60
+ if raw_answer is None:
61
+ return ""
62
+ answer = str(raw_answer).strip()
63
+
64
+ # Remove common prefixes the agent might include
65
+ prefixes = [
66
+ "FINAL ANSWER:",
67
+ "Final Answer:",
68
+ "final answer:",
69
+ "The final answer is:",
70
+ "The answer is:",
71
+ "Answer:",
72
+ ]
73
+ for prefix in prefixes:
74
+ if answer.startswith(prefix):
75
+ answer = answer[len(prefix):].strip()
76
+
77
+ # Remove surrounding quotes if present
78
+ if (answer.startswith('"') and answer.endswith('"')) or \
79
+ (answer.startswith("'") and answer.endswith("'")):
80
+ answer = answer[1:-1].strip()
81
+
82
+ return answer
83
+
84
+
85
+ def run_and_submit_all(profile: gr.OAuthProfile | None):
86
+ """
87
+ Fetches all questions, runs the agent on them, submits all answers,
88
+ and displays the results.
89
  """
90
+ space_id = os.getenv("SPACE_ID")
91
+
92
+ if profile:
93
+ username = f"{profile.username}"
94
+ print(f"User logged in: {username}")
95
+ else:
96
+ print("User not logged in.")
97
+ return "Please Login to Hugging Face with the button.", None
98
+
99
+ api_url = DEFAULT_API_URL
100
+ questions_url = f"{api_url}/questions"
101
+ submit_url = f"{api_url}/submit"
102
+
103
+ # 1. Instantiate Agent
104
  try:
105
+ agent = build_agent()
 
 
 
 
106
  except Exception as e:
107
+ print(f"Error instantiating agent: {e}")
108
+ return f"Error initializing agent: {e}", None
109
 
110
+ agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
111
+ print(f"Agent code URL: {agent_code}")
112
 
113
+ # 2. Fetch Questions
114
+ print(f"Fetching questions from: {questions_url}")
115
+ try:
116
+ response = requests.get(questions_url, timeout=15)
117
+ response.raise_for_status()
118
+ questions_data = response.json()
119
+ if not questions_data:
120
+ print("Fetched questions list is empty.")
121
+ return "Fetched questions list is empty or invalid format.", None
122
+ print(f"Fetched {len(questions_data)} questions.")
123
+ except requests.exceptions.RequestException as e:
124
+ print(f"Error fetching questions: {e}")
125
+ return f"Error fetching questions: {e}", None
126
+ except requests.exceptions.JSONDecodeError as e:
127
+ print(f"Error decoding JSON response: {e}")
128
+ return f"Error decoding server response: {e}", None
129
+ except Exception as e:
130
+ print(f"An unexpected error occurred fetching questions: {e}")
131
+ return f"An unexpected error occurred: {e}", None
132
 
133
+ # 3. Run Agent on each question
134
+ results_log = []
135
+ answers_payload = []
136
+ print(f"Running agent on {len(questions_data)} questions...")
137
+ for i, item in enumerate(questions_data):
138
+ task_id = item.get("task_id")
139
+ question_text = item.get("question")
140
+ if not task_id or question_text is None:
141
+ print(f"Skipping item with missing task_id or question: {item}")
142
+ continue
143
+ try:
144
+ print(f"\n{'='*60}")
145
+ print(f"Question {i+1}/{len(questions_data)} (task_id: {task_id})")
146
+ print(f"Q: {question_text[:100]}...")
147
+ raw_answer = agent.run(question_text)
148
+ submitted_answer = extract_answer(raw_answer)
149
+ print(f"A: {submitted_answer}")
150
+ answers_payload.append({
151
+ "task_id": task_id,
152
+ "submitted_answer": submitted_answer,
153
+ })
154
+ results_log.append({
155
+ "Task ID": task_id,
156
+ "Question": question_text,
157
+ "Submitted Answer": submitted_answer,
158
+ })
159
+ except Exception as e:
160
+ print(f"Error running agent on task {task_id}: {e}")
161
+ results_log.append({
162
+ "Task ID": task_id,
163
+ "Question": question_text,
164
+ "Submitted Answer": f"AGENT ERROR: {e}",
165
+ })
166
 
167
+ if not answers_payload:
168
+ print("Agent did not produce any answers to submit.")
169
+ return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
 
 
 
170
 
171
+ # 4. Prepare Submission
172
+ submission_data = {
173
+ "username": username.strip(),
174
+ "agent_code": agent_code,
175
+ "answers": answers_payload,
176
+ }
177
+ status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
178
+ print(status_update)
179
 
180
+ # 5. Submit
181
+ print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
182
+ try:
183
+ response = requests.post(submit_url, json=submission_data, timeout=120)
184
+ response.raise_for_status()
185
+ result_data = response.json()
186
+ final_status = (
187
+ f"Submission Successful!\n"
188
+ f"User: {result_data.get('username')}\n"
189
+ f"Overall Score: {result_data.get('score', 'N/A')}% "
190
+ f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
191
+ f"Message: {result_data.get('message', 'No message received.')}"
192
+ )
193
+ print("Submission successful.")
194
+ results_df = pd.DataFrame(results_log)
195
+ return final_status, results_df
196
+ except requests.exceptions.HTTPError as e:
197
+ error_detail = f"Server responded with status {e.response.status_code}."
198
+ try:
199
+ error_json = e.response.json()
200
+ error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
201
+ except requests.exceptions.JSONDecodeError:
202
+ error_detail += f" Response: {e.response.text[:500]}"
203
+ status_message = f"Submission Failed: {error_detail}"
204
+ print(status_message)
205
+ results_df = pd.DataFrame(results_log)
206
+ return status_message, results_df
207
+ except requests.exceptions.Timeout:
208
+ status_message = "Submission Failed: The request timed out."
209
+ print(status_message)
210
+ results_df = pd.DataFrame(results_log)
211
+ return status_message, results_df
212
+ except requests.exceptions.RequestException as e:
213
+ status_message = f"Submission Failed: Network error - {e}"
214
+ print(status_message)
215
+ results_df = pd.DataFrame(results_log)
216
+ return status_message, results_df
217
+ except Exception as e:
218
+ status_message = f"An unexpected error occurred during submission: {e}"
219
+ print(status_message)
220
+ results_df = pd.DataFrame(results_log)
221
+ return status_message, results_df
222
+
223
+
224
+ # --- Build Gradio Interface ---
225
+ with gr.Blocks() as demo:
226
+ gr.Markdown("# GAIA Benchmark Agent Evaluation")
227
+ gr.Markdown(
228
+ """
229
+ **Instructions:**
230
+ 1. Log in to your Hugging Face account using the button below.
231
+ 2. Click 'Run Evaluation & Submit All Answers' to fetch questions,
232
+ run the agent, submit answers, and see the score.
233
+
234
+ ---
235
+ **Note:** This may take several minutes as the agent processes all questions.
236
+ """
237
+ )
238
+
239
+ gr.LoginButton()
240
+
241
+ run_button = gr.Button("Run Evaluation & Submit All Answers")
242
+
243
+ status_output = gr.Textbox(
244
+ label="Run Status / Submission Result", lines=5, interactive=False
245
+ )
246
+ results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
247
 
248
+ run_button.click(
249
+ fn=run_and_submit_all,
250
+ outputs=[status_output, results_table],
251
+ )
252
 
253
+ if __name__ == "__main__":
254
+ print("\n" + "-" * 30 + " App Starting " + "-" * 30)
255
+ space_host = os.getenv("SPACE_HOST")
256
+ space_id = os.getenv("SPACE_ID")
257
+ if space_host:
258
+ print(f"✅ SPACE_HOST: {space_host}")
259
+ else:
260
+ print("ℹ️ SPACE_HOST not found (running locally?).")
261
+ if space_id:
262
+ print(f"✅ SPACE_ID: {space_id}")
263
+ else:
264
+ print("ℹ️ SPACE_ID not found (running locally?).")
265
+ print("-" * (60 + len(" App Starting ")) + "\n")
266
+ print("Launching Gradio Interface for GAIA Evaluation...")
267
+ demo.launch(debug=True, share=False)
prompts.yaml CHANGED
@@ -9,6 +9,15 @@
9
  These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
10
  In the end you have to return a final answer using the `final_answer` tool.
11
 
 
 
 
 
 
 
 
 
 
12
  Here are a few examples using notional tools:
13
  ---
14
  Task: "Generate an image of the oldest person in this document."
@@ -38,21 +47,6 @@
38
  final_answer(result)
39
  ```<end_code>
40
 
41
- ---
42
- Task:
43
- "Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
44
- You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
45
- {'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"
46
-
47
- Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
48
- Code:
49
- ```py
50
- translated_question = translator(question=question, src_lang="French", tgt_lang="English")
51
- print(f"The translated question is {translated_question}.")
52
- answer = image_qa(image=image, question=translated_question)
53
- final_answer(f"The answer is {answer}")
54
- ```<end_code>
55
-
56
  ---
57
  Task:
58
  In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
@@ -61,7 +55,7 @@
61
  Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
62
  Code:
63
  ```py
64
- pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
65
  print(pages)
66
  ```<end_code>
67
  Observation:
@@ -70,7 +64,7 @@
70
  Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
71
  Code:
72
  ```py
73
- pages = search(query="1979 interview Stanislaus Ulam")
74
  print(pages)
75
  ```<end_code>
76
  Observation:
@@ -104,11 +98,11 @@
104
  ---
105
  Task: "Which city has the highest population: Guangzhou or Shanghai?"
106
 
107
- Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
108
  Code:
109
  ```py
110
  for city in ["Guangzhou", "Shanghai"]:
111
- print(f"Population {city}:", search(f"{city} population")
112
  ```<end_code>
113
  Observation:
114
  Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
@@ -123,13 +117,11 @@
123
  ---
124
  Task: "What is the current age of the pope, raised to the power 0.36?"
125
 
126
- Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
127
  Code:
128
  ```py
129
- pope_age_wiki = wiki(query="current pope age")
130
- print("Pope age as per wikipedia:", pope_age_wiki)
131
  pope_age_search = web_search(query="current pope age")
132
- print("Pope age as per google search:", pope_age_search)
133
  ```<end_code>
134
  Observation:
135
  Pope age: "The pope Francis is currently 88 years old."
@@ -163,13 +155,14 @@
163
  1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
164
  2. Use only variables that you have defined!
165
  3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
166
- 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
167
  5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
168
  6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
169
  7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
170
  8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
171
  9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
172
  10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
 
173
 
174
  Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
175
  "planning":
 
9
  These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
10
  In the end you have to return a final answer using the `final_answer` tool.
11
 
12
+ CRITICAL RULES FOR YOUR FINAL ANSWER:
13
+ - Your final answer must be ONLY the exact answer value — no extra words, no explanations, no prefixes.
14
+ - Do NOT include phrases like "The answer is", "FINAL ANSWER:", or any other conversational text.
15
+ - If the answer is a number, return just the number.
16
+ - If the answer is a name, return just the name.
17
+ - If the answer is a list, return items separated by commas.
18
+ - If asked for a specific format, follow that format exactly.
19
+ - Strip any trailing periods, spaces, or unnecessary punctuation.
20
+
21
  Here are a few examples using notional tools:
22
  ---
23
  Task: "Generate an image of the oldest person in this document."
 
47
  final_answer(result)
48
  ```<end_code>
49
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
  ---
51
  Task:
52
  In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
 
55
  Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
56
  Code:
57
  ```py
58
+ pages = web_search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
59
  print(pages)
60
  ```<end_code>
61
  Observation:
 
64
  Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
65
  Code:
66
  ```py
67
+ pages = web_search(query="1979 interview Stanislaus Ulam")
68
  print(pages)
69
  ```<end_code>
70
  Observation:
 
98
  ---
99
  Task: "Which city has the highest population: Guangzhou or Shanghai?"
100
 
101
+ Thought: I need to get the populations for both cities and compare them: I will use the tool `web_search` to get the population of both cities.
102
  Code:
103
  ```py
104
  for city in ["Guangzhou", "Shanghai"]:
105
+ print(f"Population {city}:", web_search(query=f"{city} population"))
106
  ```<end_code>
107
  Observation:
108
  Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
 
117
  ---
118
  Task: "What is the current age of the pope, raised to the power 0.36?"
119
 
120
+ Thought: I will use the tool `web_search` to get the age of the pope, then compute the result.
121
  Code:
122
  ```py
 
 
123
  pope_age_search = web_search(query="current pope age")
124
+ print("Pope age:", pope_age_search)
125
  ```<end_code>
126
  Observation:
127
  Pope age: "The pope Francis is currently 88 years old."
 
155
  1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
156
  2. Use only variables that you have defined!
157
  3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
158
+ 4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to web_search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
159
  5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
160
  6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
161
  7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
162
  8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
163
  9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
164
  10. Don't give up! You're in charge of solving the task, not providing directions to solve it.
165
+ 11. REMEMBER: Your final_answer must contain ONLY the answer value. No explanations. No extra text.
166
 
167
  Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
168
  "planning":
requirements.txt CHANGED
@@ -1,5 +1,6 @@
1
  markdownify
2
- smolagents==1.13.0
3
  requests
4
  duckduckgo_search
5
  pandas
 
 
1
  markdownify
2
+ smolagents[gradio]
3
  requests
4
  duckduckgo_search
5
  pandas
6
+ pyyaml
tools/visit_webpage.py CHANGED
@@ -1,4 +1,5 @@
1
  from typing import Any, Optional
 
2
  from smolagents.tools import Tool
3
  import requests
4
  import markdownify
@@ -23,7 +24,9 @@ class VisitWebpageTool(Tool):
23
  ) from e
24
  try:
25
  # Send a GET request to the URL with a 20-second timeout
26
- response = requests.get(url, timeout=20)
 
 
27
  response.raise_for_status() # Raise an exception for bad status codes
28
 
29
  # Convert the HTML content to Markdown
 
1
  from typing import Any, Optional
2
+ import re
3
  from smolagents.tools import Tool
4
  import requests
5
  import markdownify
 
24
  ) from e
25
  try:
26
  # Send a GET request to the URL with a 20-second timeout
27
+ response = requests.get(url, timeout=20, headers={
28
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
29
+ })
30
  response.raise_for_status() # Raise an exception for bad status codes
31
 
32
  # Convert the HTML content to Markdown