Commit
·
8aedee6
1
Parent(s):
81917a3
added gaia agent
Browse files- README.md +11 -2
- app.py +278 -101
- requirements.txt +8 -1
README.md
CHANGED
|
@@ -4,7 +4,6 @@ emoji: 🕵🏻♂️
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 5.25.2
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
hf_oauth: true
|
|
@@ -12,4 +11,14 @@ hf_oauth: true
|
|
| 12 |
hf_oauth_expiration_minutes: 480
|
| 13 |
---
|
| 14 |
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
colorFrom: indigo
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: gradio
|
|
|
|
| 7 |
app_file: app.py
|
| 8 |
pinned: false
|
| 9 |
hf_oauth: true
|
|
|
|
| 11 |
hf_oauth_expiration_minutes: 480
|
| 12 |
---
|
| 13 |
|
| 14 |
+
## ⚠️ Configuration Required
|
| 15 |
+
|
| 16 |
+
To run this space, you need to add your Hugging Face token to the space secrets. This is required for the agent to work.
|
| 17 |
+
|
| 18 |
+
1. Create a Hugging Face token with `read` access [here](https://huggingface.co/settings/tokens).
|
| 19 |
+
2. Go to your Space's **Settings** page.
|
| 20 |
+
3. Under **Secrets**, add a new secret.
|
| 21 |
+
- **Name:** `HF_TOKEN`
|
| 22 |
+
- **Value:** Paste your token here.
|
| 23 |
+
|
| 24 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
CHANGED
|
@@ -1,75 +1,283 @@
|
|
| 1 |
import os
|
| 2 |
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 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def __init__(self):
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
api_url = DEFAULT_API_URL
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
# 1. Instantiate Agent
|
| 42 |
try:
|
| 43 |
-
agent =
|
| 44 |
except Exception as e:
|
| 45 |
print(f"Error instantiating agent: {e}")
|
| 46 |
return f"Error initializing agent: {e}", None
|
| 47 |
-
|
| 48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 49 |
-
print(agent_code)
|
| 50 |
|
| 51 |
# 2. Fetch Questions
|
| 52 |
-
print(f"Fetching questions from: {questions_url}")
|
| 53 |
try:
|
| 54 |
response = requests.get(questions_url, timeout=15)
|
| 55 |
response.raise_for_status()
|
| 56 |
questions_data = response.json()
|
| 57 |
if not questions_data:
|
| 58 |
-
print("Fetched questions list is empty.")
|
| 59 |
return "Fetched questions list is empty or invalid format.", None
|
| 60 |
print(f"Fetched {len(questions_data)} questions.")
|
| 61 |
-
except requests.exceptions.RequestException as e:
|
| 62 |
-
print(f"Error fetching questions: {e}")
|
| 63 |
-
return f"Error fetching questions: {e}", None
|
| 64 |
-
except requests.exceptions.JSONDecodeError as e:
|
| 65 |
-
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 66 |
-
print(f"Response text: {response.text[:500]}")
|
| 67 |
-
return f"Error decoding server response for questions: {e}", None
|
| 68 |
except Exception as e:
|
| 69 |
-
|
| 70 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
|
| 72 |
-
# 3. Run
|
| 73 |
results_log = []
|
| 74 |
answers_payload = []
|
| 75 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
@@ -77,10 +285,9 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 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:
|
|
@@ -88,18 +295,14 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 88 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 89 |
|
| 90 |
if not answers_payload:
|
| 91 |
-
print("Agent did not produce any answers to submit.")
|
| 92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
|
| 94 |
-
# 4. Prepare
|
| 95 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
# 5. Submit
|
| 100 |
-
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 101 |
try:
|
| 102 |
-
response = requests.post(submit_url, json=submission_data, timeout=
|
| 103 |
response.raise_for_status()
|
| 104 |
result_data = response.json()
|
| 105 |
final_status = (
|
|
@@ -109,61 +312,42 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 109 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 110 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 111 |
)
|
| 112 |
-
print("Submission successful.")
|
| 113 |
results_df = pd.DataFrame(results_log)
|
| 114 |
return final_status, results_df
|
| 115 |
-
except requests.exceptions.HTTPError as e:
|
| 116 |
-
error_detail = f"Server responded with status {e.response.status_code}."
|
| 117 |
-
try:
|
| 118 |
-
error_json = e.response.json()
|
| 119 |
-
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 120 |
-
except requests.exceptions.JSONDecodeError:
|
| 121 |
-
error_detail += f" Response: {e.response.text[:500]}"
|
| 122 |
-
status_message = f"Submission Failed: {error_detail}"
|
| 123 |
-
print(status_message)
|
| 124 |
-
results_df = pd.DataFrame(results_log)
|
| 125 |
-
return status_message, results_df
|
| 126 |
-
except requests.exceptions.Timeout:
|
| 127 |
-
status_message = "Submission Failed: The request timed out."
|
| 128 |
-
print(status_message)
|
| 129 |
-
results_df = pd.DataFrame(results_log)
|
| 130 |
-
return status_message, results_df
|
| 131 |
except requests.exceptions.RequestException as e:
|
| 132 |
-
|
| 133 |
-
|
|
|
|
|
|
|
| 134 |
results_df = pd.DataFrame(results_log)
|
| 135 |
return status_message, results_df
|
| 136 |
except Exception as e:
|
| 137 |
status_message = f"An unexpected error occurred during submission: {e}"
|
| 138 |
-
print(status_message)
|
| 139 |
results_df = pd.DataFrame(results_log)
|
| 140 |
return status_message, results_df
|
| 141 |
|
| 142 |
|
| 143 |
-
# ---
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("#
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
**Instructions:**
|
| 149 |
|
| 150 |
-
1.
|
| 151 |
-
2. Log in to your Hugging Face account using the button below. This
|
| 152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
-
|
| 154 |
---
|
| 155 |
-
**
|
| 156 |
-
|
| 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 |
|
| 161 |
-
gr.
|
| 162 |
-
|
| 163 |
-
|
| 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(
|
|
@@ -173,24 +357,17 @@ with gr.Blocks() as demo:
|
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 179 |
-
|
| 180 |
-
if space_host_startup:
|
| 181 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
else:
|
| 184 |
-
print("
|
| 185 |
|
| 186 |
-
|
|
|
|
| 187 |
print(f"�� SPACE_ID found: {space_id_startup}")
|
| 188 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 190 |
else:
|
| 191 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?).
|
| 192 |
-
|
| 193 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
import re
|
| 6 |
+
import io
|
| 7 |
+
import contextlib
|
| 8 |
+
from huggingface_hub import InferenceClient
|
| 9 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
| 10 |
+
from PyPDF2 import PdfReader
|
| 11 |
+
from docx import Document
|
| 12 |
+
import json
|
| 13 |
|
|
|
|
| 14 |
# --- Constants ---
|
| 15 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 16 |
+
# A powerful, open-source model with function-calling capabilities
|
| 17 |
+
MODEL_ID = "NousResearch/Hermes-2-Pro-Mistral-7B"
|
| 18 |
+
# This prompt template is inspired by the ReAct framework and is tailored for tool use.
|
| 19 |
+
PROMPT_TEMPLATE = """<|im_start|>system
|
| 20 |
+
You are a helpful assistant designed to answer questions accurately. You have access to the following tools:
|
| 21 |
|
| 22 |
+
{tools_description}
|
| 23 |
+
|
| 24 |
+
To answer the question, you must follow this format, thinking step by step.
|
| 25 |
+
|
| 26 |
+
Thought: Your reasoning and plan for the next step. You can also write down observations here.
|
| 27 |
+
Action: The tool to use, in the format `tool_name(arg_name="value")`. The available tools are: {tool_names}.
|
| 28 |
+
Observation: The result from the tool.
|
| 29 |
+
... (this Thought/Action/Observation can repeat N times)
|
| 30 |
+
|
| 31 |
+
When you have the final answer, respond with:
|
| 32 |
+
Thought: I have now found the final answer.
|
| 33 |
+
Final Answer: The final answer.
|
| 34 |
+
|
| 35 |
+
Do not use a tool if you are not sure about the parameters. Do not make up file names.
|
| 36 |
+
Question: {question}<|im_end|>
|
| 37 |
+
<|im_start|>assistant
|
| 38 |
+
{scratchpad}"""
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# --- Tool Definitions ---
|
| 42 |
+
|
| 43 |
+
class WebSearchTool:
|
| 44 |
+
"""A tool to search the web for information."""
|
| 45 |
def __init__(self):
|
| 46 |
+
self.search = DuckDuckGoSearchRun()
|
| 47 |
+
|
| 48 |
+
def __call__(self, query: str):
|
| 49 |
+
"""
|
| 50 |
+
Searches the web for the given query.
|
| 51 |
+
Args:
|
| 52 |
+
query (str): The search query.
|
| 53 |
+
Returns:
|
| 54 |
+
str: The search results.
|
| 55 |
+
"""
|
| 56 |
+
print(f"--- Calling WebSearchTool with query: {query} ---")
|
| 57 |
+
try:
|
| 58 |
+
return self.search.run(query)
|
| 59 |
+
except Exception as e:
|
| 60 |
+
return f"Error during web search: {e}"
|
| 61 |
+
|
| 62 |
+
@property
|
| 63 |
+
def description(self):
|
| 64 |
+
return 'web_search(query: str) -> str - A tool to search the web for information. Use it to find up-to-date information or facts.'
|
| 65 |
+
|
| 66 |
+
class PythonREPLTool:
|
| 67 |
+
"""A tool to execute Python code."""
|
| 68 |
+
def __call__(self, code: str):
|
| 69 |
+
"""
|
| 70 |
+
Executes Python code and returns the output.
|
| 71 |
+
Args:
|
| 72 |
+
code (str): The Python code to execute.
|
| 73 |
+
Returns:
|
| 74 |
+
str: The output of the executed code.
|
| 75 |
+
"""
|
| 76 |
+
print(f"--- Calling PythonREPLTool with code: {code} ---")
|
| 77 |
+
if "os" in code or "sys" in code or "subprocess" in code:
|
| 78 |
+
return "Error: Use of os, sys, or subprocess is not allowed."
|
| 79 |
+
|
| 80 |
+
local_vars = {}
|
| 81 |
+
string_io = io.StringIO()
|
| 82 |
+
try:
|
| 83 |
+
with contextlib.redirect_stdout(string_io):
|
| 84 |
+
exec(code, {}, local_vars)
|
| 85 |
+
output = string_io.getvalue()
|
| 86 |
+
if not output and local_vars:
|
| 87 |
+
# If there was no print statement, return the value of the last variable
|
| 88 |
+
output = str(list(local_vars.values())[-1])
|
| 89 |
+
return output if output else "Code executed with no output."
|
| 90 |
+
except Exception as e:
|
| 91 |
+
return f"Error executing code: {e}"
|
| 92 |
+
|
| 93 |
+
@property
|
| 94 |
+
def description(self):
|
| 95 |
+
return 'python_repl(code: str) -> str - A Python REPL. Use it to perform calculations, data manipulation, etc. The result of the last line is returned.'
|
| 96 |
+
|
| 97 |
+
class FileReaderTool:
|
| 98 |
+
"""A tool to read the content of a file associated with a task."""
|
| 99 |
+
def __init__(self, api_url: str):
|
| 100 |
+
self.api_url = api_url
|
| 101 |
+
|
| 102 |
+
def __call__(self, task_id: str, file_name: str):
|
| 103 |
+
"""
|
| 104 |
+
Reads the content of a file.
|
| 105 |
+
Args:
|
| 106 |
+
task_id (str): The ID of the task the file is associated with.
|
| 107 |
+
file_name (str): The name of the file to read. The LLM must infer this from the question.
|
| 108 |
+
Returns:
|
| 109 |
+
str: The content of the file.
|
| 110 |
+
"""
|
| 111 |
+
print(f"--- Calling FileReaderTool for task_id: {task_id}, file_name: {file_name} ---")
|
| 112 |
+
file_url = f"{self.api_url}/files/{task_id}"
|
| 113 |
+
|
| 114 |
+
try:
|
| 115 |
+
response = requests.get(file_url, timeout=20)
|
| 116 |
+
response.raise_for_status()
|
| 117 |
+
|
| 118 |
+
content = ""
|
| 119 |
+
file_content = io.BytesIO(response.content)
|
| 120 |
+
|
| 121 |
+
if file_name.endswith('.pdf'):
|
| 122 |
+
pdf = PdfReader(file_content)
|
| 123 |
+
for page in pdf.pages:
|
| 124 |
+
content += page.extract_text() if page.extract_text() else ""
|
| 125 |
+
elif file_name.endswith('.docx'):
|
| 126 |
+
doc = Document(file_content)
|
| 127 |
+
for para in doc.paragraphs:
|
| 128 |
+
content += para.text + '\n'
|
| 129 |
+
elif file_name.endswith('.csv'):
|
| 130 |
+
df = pd.read_csv(file_content)
|
| 131 |
+
content = df.to_string()
|
| 132 |
+
elif file_name.endswith('.json'):
|
| 133 |
+
data = json.load(file_content)
|
| 134 |
+
content = json.dumps(data, indent=2)
|
| 135 |
+
elif file_name.endswith('.txt'):
|
| 136 |
+
content = file_content.read().decode('utf-8')
|
| 137 |
+
else:
|
| 138 |
+
return f"Error: Unsupported file type for '{file_name}'. Supported types: .pdf, .docx, .csv, .json, .txt."
|
| 139 |
+
|
| 140 |
+
return content if content else "File is empty."
|
| 141 |
+
|
| 142 |
+
except requests.exceptions.RequestException as e:
|
| 143 |
+
return f"Error downloading file: {e}"
|
| 144 |
+
except Exception as e:
|
| 145 |
+
return f"Error reading file '{file_name}': {e}"
|
| 146 |
+
|
| 147 |
+
@property
|
| 148 |
+
def description(self):
|
| 149 |
+
return 'file_reader(task_id: str, file_name: str) -> str - Reads the content of a file associated with the current task. Use the file name mentioned in the question.'
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
# --- GAIA Agent Definition ---
|
| 153 |
+
class GaiaAgent:
|
| 154 |
+
def __init__(self, hf_token: str, api_url: str, max_turns: int = 8):
|
| 155 |
+
print("GaiaAgent initializing...")
|
| 156 |
+
if not hf_token:
|
| 157 |
+
raise ValueError("Hugging Face token is required for the Inference API.")
|
| 158 |
+
|
| 159 |
+
self.llm_client = InferenceClient(model=MODEL_ID, token=hf_token)
|
| 160 |
+
self.max_turns = max_turns
|
| 161 |
+
|
| 162 |
+
# Initialize tools
|
| 163 |
+
self.tools = {
|
| 164 |
+
"web_search": WebSearchTool(),
|
| 165 |
+
"python_repl": PythonREPLTool(),
|
| 166 |
+
"file_reader": FileReaderTool(api_url=api_url),
|
| 167 |
+
}
|
| 168 |
+
self.tools_description = "\n".join([f"- `{tool.description}`" for tool in self.tools.values()])
|
| 169 |
+
self.tool_names = ", ".join(self.tools.keys())
|
| 170 |
+
print("GaiaAgent initialized successfully.")
|
| 171 |
+
|
| 172 |
+
def __call__(self, question: str, task_id: str) -> str:
|
| 173 |
+
print(f"\n--- Running agent on task {task_id} ---")
|
| 174 |
+
print(f"Question: {question[:100]}...")
|
| 175 |
+
|
| 176 |
+
scratchpad = ""
|
| 177 |
+
|
| 178 |
+
for turn in range(self.max_turns):
|
| 179 |
+
print(f"Turn {turn + 1}/{self.max_turns}")
|
| 180 |
+
|
| 181 |
+
# 1. Construct the prompt
|
| 182 |
+
prompt = PROMPT_TEMPLATE.format(
|
| 183 |
+
tools_description=self.tools_description,
|
| 184 |
+
tool_names=self.tool_names,
|
| 185 |
+
question=question,
|
| 186 |
+
scratchpad=scratchpad,
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
# 2. Call the LLM
|
| 190 |
+
try:
|
| 191 |
+
llm_output = self.llm_client.text_generation(
|
| 192 |
+
prompt, max_new_tokens=1024, stop_sequences=["<|im_end|>", "Observation:"], temperature=0.1
|
| 193 |
+
).strip()
|
| 194 |
+
except Exception as e:
|
| 195 |
+
print(f"LLM API call failed: {e}")
|
| 196 |
+
return f"Error: LLM call failed. {e}"
|
| 197 |
+
|
| 198 |
+
print(f"LLM Output:\n{llm_output}")
|
| 199 |
+
scratchpad += llm_output
|
| 200 |
+
|
| 201 |
+
# 3. Parse the output for Final Answer or Action
|
| 202 |
+
final_answer_match = re.search(r"Final Answer:\s*(.*)", scratchpad, re.DOTALL)
|
| 203 |
+
action_match = re.search(r"Action:\s*([a-zA-Z0-9_]+)\((.*)\)", llm_output)
|
| 204 |
+
|
| 205 |
+
if final_answer_match:
|
| 206 |
+
answer = final_answer_match.group(1).strip()
|
| 207 |
+
print(f"Final Answer Found: {answer}")
|
| 208 |
+
return answer
|
| 209 |
+
|
| 210 |
+
elif action_match:
|
| 211 |
+
tool_name = action_match.group(1).strip()
|
| 212 |
+
tool_args_str = action_match.group(2).strip()
|
| 213 |
+
|
| 214 |
+
if tool_name not in self.tools:
|
| 215 |
+
observation = f"Error: Unknown tool '{tool_name}'. Available tools: {self.tool_names}"
|
| 216 |
+
else:
|
| 217 |
+
try:
|
| 218 |
+
# Safely parse arguments
|
| 219 |
+
args_dict = eval(f"dict({tool_args_str})", {"__builtins__": None}, {})
|
| 220 |
+
|
| 221 |
+
if tool_name == 'file_reader':
|
| 222 |
+
args_dict['task_id'] = task_id
|
| 223 |
+
|
| 224 |
+
tool = self.tools[tool_name]
|
| 225 |
+
observation = tool(**args_dict)
|
| 226 |
+
except Exception as e:
|
| 227 |
+
observation = f"Error executing tool '{tool_name}': {e}"
|
| 228 |
+
|
| 229 |
+
print(f"Observation: {str(observation)[:200]}...")
|
| 230 |
+
scratchpad += f"\nObservation: {str(observation)}\n"
|
| 231 |
+
else:
|
| 232 |
+
print("No valid action or final answer found in LLM output. Continuing thought process.")
|
| 233 |
+
scratchpad += "\nObservation: No valid action taken. Please either use a tool with the correct format `Action: tool_name(arg_name=\"value\")` or provide the final answer in the format `Final Answer: your_answer`."
|
| 234 |
+
|
| 235 |
+
print("Agent reached max turns.")
|
| 236 |
+
return "Agent stopped after reaching maximum turns."
|
| 237 |
+
|
| 238 |
+
# --- Main Submission Logic ---
|
| 239 |
+
|
| 240 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 241 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 242 |
+
if not hf_token:
|
| 243 |
+
return "Error: `HF_TOKEN` environment variable not set. Please add it to your Space secrets.", None
|
| 244 |
+
|
| 245 |
+
space_id = os.getenv("SPACE_ID")
|
| 246 |
+
if not space_id:
|
| 247 |
+
return "Error: `SPACE_ID` environment variable not found. Are you running in a Hugging Face Space?", None
|
| 248 |
+
|
| 249 |
+
if not profile:
|
| 250 |
+
return "Please Login to Hugging Face with the button to submit.", None
|
| 251 |
+
|
| 252 |
+
username = profile.username
|
| 253 |
+
print(f"User logged in: {username}")
|
| 254 |
|
| 255 |
api_url = DEFAULT_API_URL
|
| 256 |
questions_url = f"{api_url}/questions"
|
| 257 |
submit_url = f"{api_url}/submit"
|
| 258 |
|
| 259 |
+
# 1. Instantiate Agent
|
| 260 |
try:
|
| 261 |
+
agent = GaiaAgent(hf_token=hf_token, api_url=api_url)
|
| 262 |
except Exception as e:
|
| 263 |
print(f"Error instantiating agent: {e}")
|
| 264 |
return f"Error initializing agent: {e}", None
|
| 265 |
+
|
| 266 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 267 |
+
print(f"Code link: {agent_code}")
|
| 268 |
|
| 269 |
# 2. Fetch Questions
|
|
|
|
| 270 |
try:
|
| 271 |
response = requests.get(questions_url, timeout=15)
|
| 272 |
response.raise_for_status()
|
| 273 |
questions_data = response.json()
|
| 274 |
if not questions_data:
|
|
|
|
| 275 |
return "Fetched questions list is empty or invalid format.", None
|
| 276 |
print(f"Fetched {len(questions_data)} questions.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 277 |
except Exception as e:
|
| 278 |
+
return f"Error fetching questions: {e}", None
|
|
|
|
| 279 |
|
| 280 |
+
# 3. Run Agent and Collect Answers
|
| 281 |
results_log = []
|
| 282 |
answers_payload = []
|
| 283 |
print(f"Running agent on {len(questions_data)} questions...")
|
|
|
|
| 285 |
task_id = item.get("task_id")
|
| 286 |
question_text = item.get("question")
|
| 287 |
if not task_id or question_text is None:
|
|
|
|
| 288 |
continue
|
| 289 |
try:
|
| 290 |
+
submitted_answer = agent(question_text, task_id)
|
| 291 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 292 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 293 |
except Exception as e:
|
|
|
|
| 295 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 296 |
|
| 297 |
if not answers_payload:
|
|
|
|
| 298 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 299 |
|
| 300 |
+
# 4. Prepare and 5. Submit
|
| 301 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 302 |
+
print(f"Submitting {len(answers_payload)} answers for user '{username}'...")
|
| 303 |
+
|
|
|
|
|
|
|
|
|
|
| 304 |
try:
|
| 305 |
+
response = requests.post(submit_url, json=submission_data, timeout=120)
|
| 306 |
response.raise_for_status()
|
| 307 |
result_data = response.json()
|
| 308 |
final_status = (
|
|
|
|
| 312 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 313 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 314 |
)
|
|
|
|
| 315 |
results_df = pd.DataFrame(results_log)
|
| 316 |
return final_status, results_df
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 317 |
except requests.exceptions.RequestException as e:
|
| 318 |
+
error_detail = "Network error or server responded with an error."
|
| 319 |
+
if e.response is not None:
|
| 320 |
+
error_detail = f"Server responded with status {e.response.status_code}. Response: {e.response.text[:500]}"
|
| 321 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 322 |
results_df = pd.DataFrame(results_log)
|
| 323 |
return status_message, results_df
|
| 324 |
except Exception as e:
|
| 325 |
status_message = f"An unexpected error occurred during submission: {e}"
|
|
|
|
| 326 |
results_df = pd.DataFrame(results_log)
|
| 327 |
return status_message, results_df
|
| 328 |
|
| 329 |
|
| 330 |
+
# --- Gradio Interface ---
|
| 331 |
with gr.Blocks() as demo:
|
| 332 |
+
gr.Markdown("# GAIA Agent Evaluation Runner")
|
| 333 |
gr.Markdown(
|
| 334 |
"""
|
| 335 |
**Instructions:**
|
| 336 |
|
| 337 |
+
1. **Add your HF Token**: Go to the 'Settings' tab of this Space and add a secret named `HF_TOKEN` with your Hugging Face read token.
|
| 338 |
+
2. **Login**: Log in to your Hugging Face account using the button below. This is required for submission.
|
| 339 |
+
3. **Run**: Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
|
|
|
| 340 |
---
|
| 341 |
+
**Disclaimer:**
|
| 342 |
+
This process can take several minutes as the agent processes each question. Please be patient.
|
|
|
|
| 343 |
"""
|
| 344 |
)
|
| 345 |
|
| 346 |
+
with gr.Row():
|
| 347 |
+
gr.LoginButton()
|
| 348 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 349 |
|
| 350 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 351 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 352 |
|
| 353 |
run_button.click(
|
|
|
|
| 357 |
|
| 358 |
if __name__ == "__main__":
|
| 359 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 360 |
+
if not os.getenv("HF_TOKEN"):
|
| 361 |
+
print("⚠️ WARNING: `HF_TOKEN` secret not found. The agent will not be able to run.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 362 |
else:
|
| 363 |
+
print("✅ `HF_TOKEN` secret found.")
|
| 364 |
|
| 365 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 366 |
+
if space_id_startup:
|
| 367 |
print(f"�� SPACE_ID found: {space_id_startup}")
|
|
|
|
|
|
|
| 368 |
else:
|
| 369 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?).")
|
| 370 |
+
|
| 371 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 372 |
+
print("Launching Gradio Interface for GAIA Agent Evaluation...")
|
| 373 |
+
demo.launch()
|
|
|
requirements.txt
CHANGED
|
@@ -1,2 +1,9 @@
|
|
| 1 |
gradio
|
| 2 |
-
requests
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
gradio
|
| 2 |
+
requests
|
| 3 |
+
huggingface-hub
|
| 4 |
+
langchain-community
|
| 5 |
+
duckduckgo-search
|
| 6 |
+
pypdf2
|
| 7 |
+
python-docx
|
| 8 |
+
pandas
|
| 9 |
+
openpyxl
|