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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""GAIA level-1 agent for the Hugging Face Agents Course (Unit 4 final assignment).
|
| 2 |
+
|
| 3 |
+
Built on smolagents' CodeAgent. The LLM backend goes through LiteLLM, so any
|
| 4 |
+
provider works by setting MODEL_ID and that provider's API key env var, e.g.
|
| 5 |
+
MODEL_ID=anthropic/claude-sonnet-5-5 + ANTHROPIC_API_KEY
|
| 6 |
+
MODEL_ID=gemini/gemini-2.5-flash + GEMINI_API_KEY
|
| 7 |
+
MODEL_ID=openai/gpt-4.1 + OPENAI_API_KEY
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
import base64
|
| 11 |
+
import io
|
| 12 |
+
import mimetypes
|
| 13 |
+
import os
|
| 14 |
+
import re
|
| 15 |
+
import tempfile
|
| 16 |
+
|
| 17 |
+
import requests
|
| 18 |
+
from dotenv import load_dotenv
|
| 19 |
+
from smolagents import (
|
| 20 |
+
CodeAgent,
|
| 21 |
+
DuckDuckGoSearchTool,
|
| 22 |
+
LiteLLMModel,
|
| 23 |
+
VisitWebpageTool,
|
| 24 |
+
WikipediaSearchTool,
|
| 25 |
+
tool,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
load_dotenv()
|
| 29 |
+
|
| 30 |
+
API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 31 |
+
MODEL_ID = os.getenv("MODEL_ID", "anthropic/claude-sonnet-5-5")
|
| 32 |
+
FILES_DIR = os.path.join(tempfile.gettempdir(), "gaia_files")
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def download_task_file(task_id: str, file_name: str) -> str | None:
|
| 36 |
+
"""Download the attachment for a task and return its local path."""
|
| 37 |
+
if not file_name:
|
| 38 |
+
return None
|
| 39 |
+
os.makedirs(FILES_DIR, exist_ok=True)
|
| 40 |
+
path = os.path.join(FILES_DIR, file_name)
|
| 41 |
+
if not os.path.exists(path):
|
| 42 |
+
resp = requests.get(f"{API_URL}/files/{task_id}", timeout=60)
|
| 43 |
+
resp.raise_for_status()
|
| 44 |
+
with open(path, "wb") as f:
|
| 45 |
+
f.write(resp.content)
|
| 46 |
+
return path
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _llm_text(messages: list[dict]) -> str:
|
| 50 |
+
import litellm
|
| 51 |
+
|
| 52 |
+
resp = litellm.completion(model=MODEL_ID, messages=messages)
|
| 53 |
+
return resp.choices[0].message.content
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
@tool
|
| 57 |
+
def analyze_image(image_path: str, question: str) -> str:
|
| 58 |
+
"""Look at a local image file with a vision model and answer a question about it.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
image_path: Local path to the image (png, jpg, ...).
|
| 62 |
+
question: What you want to know about the image. Be specific.
|
| 63 |
+
"""
|
| 64 |
+
mime = mimetypes.guess_type(image_path)[0] or "image/png"
|
| 65 |
+
with open(image_path, "rb") as f:
|
| 66 |
+
b64 = base64.b64encode(f.read()).decode()
|
| 67 |
+
return _llm_text([
|
| 68 |
+
{
|
| 69 |
+
"role": "user",
|
| 70 |
+
"content": [
|
| 71 |
+
{"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}},
|
| 72 |
+
{"type": "text", "text": question},
|
| 73 |
+
],
|
| 74 |
+
}
|
| 75 |
+
])
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
@tool
|
| 79 |
+
def transcribe_audio(audio_path: str) -> str:
|
| 80 |
+
"""Transcribe a local audio file (mp3, wav, ...) to text with Whisper.
|
| 81 |
+
|
| 82 |
+
Args:
|
| 83 |
+
audio_path: Local path to the audio file.
|
| 84 |
+
"""
|
| 85 |
+
import whisper # openai-whisper, runs locally on CPU
|
| 86 |
+
|
| 87 |
+
model = whisper.load_model(os.getenv("WHISPER_MODEL", "small"))
|
| 88 |
+
return model.transcribe(audio_path)["text"]
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@tool
|
| 92 |
+
def youtube_transcript(url: str) -> str:
|
| 93 |
+
"""Fetch the spoken transcript (captions) of a YouTube video.
|
| 94 |
+
|
| 95 |
+
Args:
|
| 96 |
+
url: The YouTube video URL.
|
| 97 |
+
"""
|
| 98 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
| 99 |
+
|
| 100 |
+
m = re.search(r"(?:v=|youtu\.be/)([\w-]{11})", url)
|
| 101 |
+
if not m:
|
| 102 |
+
return "Could not parse a video id from the URL."
|
| 103 |
+
try:
|
| 104 |
+
fetched = YouTubeTranscriptApi().fetch(m.group(1))
|
| 105 |
+
return "\n".join(f"[{s.start:.0f}s] {s.text}" for s in fetched)
|
| 106 |
+
except Exception as e:
|
| 107 |
+
return f"Transcript unavailable: {e}"
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@tool
|
| 111 |
+
def read_excel(path: str) -> str:
|
| 112 |
+
"""Read every sheet of an Excel/CSV file and return it as text tables.
|
| 113 |
+
|
| 114 |
+
Args:
|
| 115 |
+
path: Local path to the .xlsx / .xls / .csv file.
|
| 116 |
+
"""
|
| 117 |
+
import pandas as pd
|
| 118 |
+
|
| 119 |
+
if path.lower().endswith(".csv"):
|
| 120 |
+
return pd.read_csv(path).to_string()
|
| 121 |
+
sheets = pd.read_excel(path, sheet_name=None)
|
| 122 |
+
return "\n\n".join(f"## Sheet: {name}\n{df.to_string()}" for name, df in sheets.items())
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@tool
|
| 126 |
+
def read_text_file(path: str) -> str:
|
| 127 |
+
"""Read a local text/code file and return its content.
|
| 128 |
+
|
| 129 |
+
Args:
|
| 130 |
+
path: Local path to the file.
|
| 131 |
+
"""
|
| 132 |
+
with open(path, encoding="utf-8", errors="replace") as f:
|
| 133 |
+
return f.read()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
SYSTEM_HINT = """You are a precise research assistant solving a GAIA benchmark question.
|
| 137 |
+
Use the tools to look things up and verify; do not guess when you can check.
|
| 138 |
+
Rules for the final answer (it is graded by EXACT MATCH):
|
| 139 |
+
- Call final_answer() with ONLY the answer: no explanation, no units unless asked, no "FINAL ANSWER" prefix.
|
| 140 |
+
- A number: plain digits, no thousands separators, no $ or % unless asked.
|
| 141 |
+
- A string: as few words as possible, no articles, no abbreviations unless asked.
|
| 142 |
+
- A list: comma-separated, following any ordering/format the question asks for.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
class GaiaAgent:
|
| 147 |
+
def __init__(self):
|
| 148 |
+
model = LiteLLMModel(model_id=MODEL_ID)
|
| 149 |
+
self.agent = CodeAgent(
|
| 150 |
+
model=model,
|
| 151 |
+
tools=[
|
| 152 |
+
DuckDuckGoSearchTool(max_results=8),
|
| 153 |
+
VisitWebpageTool(max_output_length=60000),
|
| 154 |
+
WikipediaSearchTool(user_agent="gaia-agent (hf agents course)"),
|
| 155 |
+
youtube_transcript,
|
| 156 |
+
analyze_image,
|
| 157 |
+
transcribe_audio,
|
| 158 |
+
read_excel,
|
| 159 |
+
read_text_file,
|
| 160 |
+
],
|
| 161 |
+
additional_authorized_imports=[
|
| 162 |
+
"pandas", "numpy", "json", "re", "math", "datetime", "collections",
|
| 163 |
+
"itertools", "statistics", "requests", "bs4", "subprocess", "os",
|
| 164 |
+
],
|
| 165 |
+
max_steps=15,
|
| 166 |
+
verbosity_level=1,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
def __call__(self, question: str, file_path: str | None = None) -> str:
|
| 170 |
+
prompt = SYSTEM_HINT + "\nQuestion:\n" + question
|
| 171 |
+
if file_path:
|
| 172 |
+
prompt += f"\n\nThe attached file is available locally at: {file_path}"
|
| 173 |
+
answer = str(self.agent.run(prompt)).strip()
|
| 174 |
+
return re.sub(r"^\s*FINAL ANSWER:\s*", "", answer, flags=re.I).strip()
|
app.py
ADDED
|
@@ -0,0 +1,188 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from agent import GaiaAgent, download_task_file
|
| 12 |
+
|
| 13 |
+
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 14 |
+
"""
|
| 15 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 16 |
+
and displays the results.
|
| 17 |
+
"""
|
| 18 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 19 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 20 |
+
|
| 21 |
+
if profile:
|
| 22 |
+
username= f"{profile.username}"
|
| 23 |
+
print(f"User logged in: {username}")
|
| 24 |
+
else:
|
| 25 |
+
print("User not logged in.")
|
| 26 |
+
return "Please Login to Hugging Face with the button.", None
|
| 27 |
+
|
| 28 |
+
api_url = DEFAULT_API_URL
|
| 29 |
+
questions_url = f"{api_url}/questions"
|
| 30 |
+
submit_url = f"{api_url}/submit"
|
| 31 |
+
|
| 32 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 33 |
+
try:
|
| 34 |
+
agent = GaiaAgent()
|
| 35 |
+
except Exception as e:
|
| 36 |
+
print(f"Error instantiating agent: {e}")
|
| 37 |
+
return f"Error initializing agent: {e}", None
|
| 38 |
+
# 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)
|
| 39 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 40 |
+
print(agent_code)
|
| 41 |
+
|
| 42 |
+
# 2. Fetch Questions
|
| 43 |
+
print(f"Fetching questions from: {questions_url}")
|
| 44 |
+
try:
|
| 45 |
+
response = requests.get(questions_url, timeout=15)
|
| 46 |
+
response.raise_for_status()
|
| 47 |
+
questions_data = response.json()
|
| 48 |
+
if not questions_data:
|
| 49 |
+
print("Fetched questions list is empty.")
|
| 50 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 51 |
+
print(f"Fetched {len(questions_data)} questions.")
|
| 52 |
+
except requests.exceptions.RequestException as e:
|
| 53 |
+
print(f"Error fetching questions: {e}")
|
| 54 |
+
return f"Error fetching questions: {e}", None
|
| 55 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 56 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 57 |
+
print(f"Response text: {response.text[:500]}")
|
| 58 |
+
return f"Error decoding server response for questions: {e}", None
|
| 59 |
+
except Exception as e:
|
| 60 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 61 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 62 |
+
|
| 63 |
+
# 3. Run your Agent
|
| 64 |
+
results_log = []
|
| 65 |
+
answers_payload = []
|
| 66 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 67 |
+
for item in questions_data:
|
| 68 |
+
task_id = item.get("task_id")
|
| 69 |
+
question_text = item.get("question")
|
| 70 |
+
if not task_id or question_text is None:
|
| 71 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 72 |
+
continue
|
| 73 |
+
try:
|
| 74 |
+
file_path = download_task_file(task_id, item.get("file_name", ""))
|
| 75 |
+
submitted_answer = agent(question_text, file_path)
|
| 76 |
+
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 77 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 78 |
+
except Exception as e:
|
| 79 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 80 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
| 81 |
+
|
| 82 |
+
if not answers_payload:
|
| 83 |
+
print("Agent did not produce any answers to submit.")
|
| 84 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 85 |
+
|
| 86 |
+
# 4. Prepare Submission
|
| 87 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 88 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 89 |
+
print(status_update)
|
| 90 |
+
|
| 91 |
+
# 5. Submit
|
| 92 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 93 |
+
try:
|
| 94 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 95 |
+
response.raise_for_status()
|
| 96 |
+
result_data = response.json()
|
| 97 |
+
final_status = (
|
| 98 |
+
f"Submission Successful!\n"
|
| 99 |
+
f"User: {result_data.get('username')}\n"
|
| 100 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 101 |
+
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 102 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
| 103 |
+
)
|
| 104 |
+
print("Submission successful.")
|
| 105 |
+
results_df = pd.DataFrame(results_log)
|
| 106 |
+
return final_status, results_df
|
| 107 |
+
except requests.exceptions.HTTPError as e:
|
| 108 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 109 |
+
try:
|
| 110 |
+
error_json = e.response.json()
|
| 111 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 112 |
+
except requests.exceptions.JSONDecodeError:
|
| 113 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 114 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 115 |
+
print(status_message)
|
| 116 |
+
results_df = pd.DataFrame(results_log)
|
| 117 |
+
return status_message, results_df
|
| 118 |
+
except requests.exceptions.Timeout:
|
| 119 |
+
status_message = "Submission Failed: The request timed out."
|
| 120 |
+
print(status_message)
|
| 121 |
+
results_df = pd.DataFrame(results_log)
|
| 122 |
+
return status_message, results_df
|
| 123 |
+
except requests.exceptions.RequestException as e:
|
| 124 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 125 |
+
print(status_message)
|
| 126 |
+
results_df = pd.DataFrame(results_log)
|
| 127 |
+
return status_message, results_df
|
| 128 |
+
except Exception as e:
|
| 129 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 130 |
+
print(status_message)
|
| 131 |
+
results_df = pd.DataFrame(results_log)
|
| 132 |
+
return status_message, results_df
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# --- Build Gradio Interface using Blocks ---
|
| 136 |
+
with gr.Blocks() as demo:
|
| 137 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 138 |
+
gr.Markdown(
|
| 139 |
+
"""
|
| 140 |
+
**Instructions:**
|
| 141 |
+
|
| 142 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 143 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 144 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 145 |
+
|
| 146 |
+
---
|
| 147 |
+
**Disclaimers:**
|
| 148 |
+
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).
|
| 149 |
+
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.
|
| 150 |
+
"""
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
gr.LoginButton()
|
| 154 |
+
|
| 155 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 156 |
+
|
| 157 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 158 |
+
# Removed max_rows=10 from DataFrame constructor
|
| 159 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 160 |
+
|
| 161 |
+
run_button.click(
|
| 162 |
+
fn=run_and_submit_all,
|
| 163 |
+
outputs=[status_output, results_table]
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 168 |
+
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 169 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 170 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 171 |
+
|
| 172 |
+
if space_host_startup:
|
| 173 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 174 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 175 |
+
else:
|
| 176 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 177 |
+
|
| 178 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 179 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 180 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 181 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 182 |
+
else:
|
| 183 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 184 |
+
|
| 185 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 186 |
+
|
| 187 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 188 |
+
demo.launch(debug=True, share=False)
|
requirements.txt
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
requests
|
| 3 |
+
pandas
|
| 4 |
+
openpyxl
|
| 5 |
+
smolagents[litellm]
|
| 6 |
+
ddgs
|
| 7 |
+
wikipedia-api
|
| 8 |
+
markdownify
|
| 9 |
+
youtube-transcript-api
|
| 10 |
+
openai-whisper
|
| 11 |
+
python-dotenv
|
run_local.py
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run the agent locally on all questions, cache answers, and optionally submit.
|
| 2 |
+
|
| 3 |
+
python run_local.py # answer every question not yet cached
|
| 4 |
+
python run_local.py --only 3 11 # (re)answer specific question indexes
|
| 5 |
+
python run_local.py --submit # submit cached answers
|
| 6 |
+
|
| 7 |
+
Submitting through the API needs no Gradio login: the scoring server only takes
|
| 8 |
+
the username, the public Space code link, and the answers.
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
import requests
|
| 16 |
+
|
| 17 |
+
from agent import API_URL, GaiaAgent, download_task_file
|
| 18 |
+
|
| 19 |
+
USERNAME = os.getenv("HF_USERNAME", "2tyoon")
|
| 20 |
+
SPACE_ID = os.getenv("SPACE_ID", f"{USERNAME}/Final_Assignment_Agent")
|
| 21 |
+
CACHE = "answers.json"
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def load_cache() -> dict:
|
| 25 |
+
if os.path.exists(CACHE):
|
| 26 |
+
with open(CACHE, encoding="utf-8") as f:
|
| 27 |
+
return json.load(f)
|
| 28 |
+
return {}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def save_cache(cache: dict) -> None:
|
| 32 |
+
with open(CACHE, "w", encoding="utf-8") as f:
|
| 33 |
+
json.dump(cache, f, ensure_ascii=False, indent=2)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main() -> None:
|
| 37 |
+
parser = argparse.ArgumentParser()
|
| 38 |
+
parser.add_argument("--only", type=int, nargs="*")
|
| 39 |
+
parser.add_argument("--submit", action="store_true")
|
| 40 |
+
args = parser.parse_args()
|
| 41 |
+
|
| 42 |
+
questions = requests.get(f"{API_URL}/questions", timeout=30).json()
|
| 43 |
+
cache = load_cache()
|
| 44 |
+
|
| 45 |
+
if args.submit:
|
| 46 |
+
payload = {
|
| 47 |
+
"username": USERNAME,
|
| 48 |
+
"agent_code": f"https://huggingface.co/spaces/{SPACE_ID}/tree/main",
|
| 49 |
+
"answers": [
|
| 50 |
+
{"task_id": q["task_id"], "submitted_answer": cache[q["task_id"]]}
|
| 51 |
+
for q in questions
|
| 52 |
+
if q["task_id"] in cache
|
| 53 |
+
],
|
| 54 |
+
}
|
| 55 |
+
resp = requests.post(f"{API_URL}/submit", json=payload, timeout=120)
|
| 56 |
+
print(resp.status_code, json.dumps(resp.json(), ensure_ascii=False, indent=2))
|
| 57 |
+
return
|
| 58 |
+
|
| 59 |
+
agent = GaiaAgent()
|
| 60 |
+
for i, q in enumerate(questions):
|
| 61 |
+
if args.only is not None and i not in args.only:
|
| 62 |
+
continue
|
| 63 |
+
if args.only is None and q["task_id"] in cache:
|
| 64 |
+
continue
|
| 65 |
+
print(f"\n===== [{i}] {q['question'][:120]}")
|
| 66 |
+
try:
|
| 67 |
+
file_path = download_task_file(q["task_id"], q.get("file_name", ""))
|
| 68 |
+
answer = agent(q["question"], file_path)
|
| 69 |
+
except Exception as e:
|
| 70 |
+
print(f"!! error: {e}")
|
| 71 |
+
continue
|
| 72 |
+
print(f"===== [{i}] ANSWER: {answer}")
|
| 73 |
+
cache[q["task_id"]] = answer
|
| 74 |
+
save_cache(cache)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
main()
|