Upload 6 files
Browse files- agent.py +156 -0
- app.py +76 -131
- gitattributes +35 -0
- logic.py +108 -0
- requirements.txt +9 -2
agent.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any, Dict, List, Optional
|
| 2 |
+
import torch
|
| 3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 4 |
+
from duckduckgo_search import DDGS
|
| 5 |
+
import re
|
| 6 |
+
import math
|
| 7 |
+
|
| 8 |
+
class WebSearchTool:
|
| 9 |
+
def __init__(self):
|
| 10 |
+
self.search = DDGS()
|
| 11 |
+
|
| 12 |
+
def run(self, query: str, max_results: int = 3) -> str:
|
| 13 |
+
"""Perform a web search and return formatted results."""
|
| 14 |
+
try:
|
| 15 |
+
results = list(self.search.text(query, max_results=max_results))
|
| 16 |
+
formatted_results = []
|
| 17 |
+
for r in results:
|
| 18 |
+
formatted_results.append(f"Title: {r['title']}\nSnippet: {r['body']}\nURL: {r['link']}\n")
|
| 19 |
+
return "\n".join(formatted_results)
|
| 20 |
+
except Exception as e:
|
| 21 |
+
return f"Error performing web search: {str(e)}"
|
| 22 |
+
|
| 23 |
+
class Calculator:
|
| 24 |
+
def run(self, expression: str) -> str:
|
| 25 |
+
"""Evaluate mathematical expressions safely."""
|
| 26 |
+
try:
|
| 27 |
+
# Remove any characters that aren't numbers, operators, or parentheses
|
| 28 |
+
cleaned = re.sub(r'[^0-9+\-*/().\ ]', '', expression)
|
| 29 |
+
# Evaluate the expression
|
| 30 |
+
result = eval(cleaned, {"__builtins__": {}}, {"math": math})
|
| 31 |
+
return str(result)
|
| 32 |
+
except Exception as e:
|
| 33 |
+
return f"Error in calculation: {str(e)}"
|
| 34 |
+
|
| 35 |
+
class GaiaAgent:
|
| 36 |
+
def __init__(self):
|
| 37 |
+
# Initialize Qwen-7B model
|
| 38 |
+
self.model_name = "Qwen/Qwen-7B"
|
| 39 |
+
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 40 |
+
self.model_name,
|
| 41 |
+
trust_remote_code=True
|
| 42 |
+
)
|
| 43 |
+
self.model = AutoModelForCausalLM.from_pretrained(
|
| 44 |
+
self.model_name,
|
| 45 |
+
device_map="auto",
|
| 46 |
+
trust_remote_code=True
|
| 47 |
+
).eval()
|
| 48 |
+
|
| 49 |
+
# Initialize tools
|
| 50 |
+
self.tools = {
|
| 51 |
+
"web_search": WebSearchTool(),
|
| 52 |
+
"calculator": Calculator()
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
# System prompt template
|
| 56 |
+
self.system_prompt = """You are a helpful AI assistant with access to the following tools:
|
| 57 |
+
1. web_search: Search the internet for current information
|
| 58 |
+
2. calculator: Perform mathematical calculations
|
| 59 |
+
|
| 60 |
+
To use a tool, respond with: <tool>tool_name|input</tool>
|
| 61 |
+
For example: <tool>calculator|2 + 2</tool> or <tool>web_search|latest news about AI</tool>
|
| 62 |
+
|
| 63 |
+
If you don't need any tools to answer, just provide your response directly.
|
| 64 |
+
Always explain your reasoning before using tools or providing final answers."""
|
| 65 |
+
|
| 66 |
+
def _generate_response(self, prompt: str, max_length: int = 2048) -> str:
|
| 67 |
+
"""Generate a response using the Qwen model."""
|
| 68 |
+
try:
|
| 69 |
+
input_ids = self.tokenizer.encode(prompt, return_tensors="pt").to(self.model.device)
|
| 70 |
+
|
| 71 |
+
with torch.no_grad():
|
| 72 |
+
outputs = self.model.generate(
|
| 73 |
+
input_ids,
|
| 74 |
+
max_length=max_length,
|
| 75 |
+
num_return_sequences=1,
|
| 76 |
+
temperature=0.7,
|
| 77 |
+
do_sample=True,
|
| 78 |
+
pad_token_id=self.tokenizer.pad_token_id
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 82 |
+
# Extract only the assistant's response
|
| 83 |
+
response = response.split(prompt)[-1].strip()
|
| 84 |
+
return response
|
| 85 |
+
except Exception as e:
|
| 86 |
+
return f"Error generating response: {str(e)}"
|
| 87 |
+
|
| 88 |
+
def _extract_tool_calls(self, response: str) -> List[Dict[str, str]]:
|
| 89 |
+
"""Extract tool calls from the response."""
|
| 90 |
+
tool_pattern = r'<tool>(.*?)\|(.*?)</tool>'
|
| 91 |
+
matches = re.finditer(tool_pattern, response)
|
| 92 |
+
tool_calls = []
|
| 93 |
+
|
| 94 |
+
for match in matches:
|
| 95 |
+
tool_name = match.group(1).strip()
|
| 96 |
+
tool_input = match.group(2).strip()
|
| 97 |
+
tool_calls.append({"name": tool_name, "input": tool_input})
|
| 98 |
+
|
| 99 |
+
return tool_calls
|
| 100 |
+
|
| 101 |
+
def _execute_tool_call(self, tool_call: Dict[str, str]) -> str:
|
| 102 |
+
"""Execute a single tool call and return the result."""
|
| 103 |
+
tool_name = tool_call["name"]
|
| 104 |
+
tool_input = tool_call["input"]
|
| 105 |
+
|
| 106 |
+
if tool_name not in self.tools:
|
| 107 |
+
return f"Error: Tool '{tool_name}' not found"
|
| 108 |
+
|
| 109 |
+
try:
|
| 110 |
+
result = self.tools[tool_name].run(tool_input)
|
| 111 |
+
return result
|
| 112 |
+
except Exception as e:
|
| 113 |
+
return f"Error executing {tool_name}: {str(e)}"
|
| 114 |
+
|
| 115 |
+
def process_question(self, question: str) -> str:
|
| 116 |
+
"""Process a single question and return the answer."""
|
| 117 |
+
# Construct the full prompt
|
| 118 |
+
full_prompt = f"{self.system_prompt}\n\nQuestion: {question}\n\nAnswer:"
|
| 119 |
+
|
| 120 |
+
# Get initial response
|
| 121 |
+
response = self._generate_response(full_prompt)
|
| 122 |
+
|
| 123 |
+
# Extract and execute any tool calls
|
| 124 |
+
tool_calls = self._extract_tool_calls(response)
|
| 125 |
+
|
| 126 |
+
if tool_calls:
|
| 127 |
+
# Execute each tool call and collect results
|
| 128 |
+
tool_results = []
|
| 129 |
+
for tool_call in tool_calls:
|
| 130 |
+
result = self._execute_tool_call(tool_call)
|
| 131 |
+
tool_results.append(f"Tool {tool_call['name']} result: {result}")
|
| 132 |
+
|
| 133 |
+
# Generate final response with tool results
|
| 134 |
+
tool_results_str = "\n".join(tool_results)
|
| 135 |
+
final_prompt = f"{full_prompt}\n{response}\n\nTool Results:\n{tool_results_str}\n\nFinal Answer:"
|
| 136 |
+
final_response = self._generate_response(final_prompt)
|
| 137 |
+
|
| 138 |
+
return final_response
|
| 139 |
+
|
| 140 |
+
return response
|
| 141 |
+
|
| 142 |
+
def get_answer(self, question_data: Dict[str, Any]) -> Optional[str]:
|
| 143 |
+
"""Process a question from the GAIA benchmark and return an answer."""
|
| 144 |
+
try:
|
| 145 |
+
# Extract the actual question from the question data
|
| 146 |
+
question = question_data.get("question", "")
|
| 147 |
+
if not question:
|
| 148 |
+
return None
|
| 149 |
+
|
| 150 |
+
# Process the question and get the answer
|
| 151 |
+
answer = self.process_question(question)
|
| 152 |
+
|
| 153 |
+
return answer
|
| 154 |
+
except Exception as e:
|
| 155 |
+
print(f"Error processing question: {str(e)}")
|
| 156 |
+
return None
|
app.py
CHANGED
|
@@ -1,160 +1,98 @@
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
-
import
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 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 ---
|
| 28 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
if profile:
|
| 31 |
-
username= f"{profile.username}"
|
| 32 |
print(f"User logged in: {username}")
|
| 33 |
else:
|
| 34 |
print("User not logged in.")
|
| 35 |
return "Please Login to Hugging Face with the button.", None
|
| 36 |
|
| 37 |
-
|
| 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 |
-
|
| 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 |
|
| 51 |
# 2. Fetch Questions
|
| 52 |
-
print(f"Fetching questions from: {questions_url}")
|
| 53 |
try:
|
| 54 |
-
|
| 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 your Agent
|
| 73 |
-
results_log = []
|
| 74 |
-
answers_payload = []
|
| 75 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 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}"})
|
| 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 = {
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
print(
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
final_status = (
|
| 106 |
-
f"Submission Successful!\n"
|
| 107 |
-
f"User: {result_data.get('username')}\n"
|
| 108 |
-
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 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 |
-
status_message = f"Submission Failed: Network error - {e}"
|
| 133 |
-
print(status_message)
|
| 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 |
# --- Build Gradio Interface using Blocks ---
|
| 144 |
-
with gr.Blocks() as
|
| 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
|
| 151 |
-
|
| 152 |
-
|
|
|
|
|
|
|
|
|
|
| 153 |
|
| 154 |
---
|
| 155 |
**Disclaimers:**
|
| 156 |
-
Once clicking on the "submit button, it can take quite some time ( this is
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
"""
|
| 159 |
)
|
| 160 |
|
|
@@ -162,20 +100,21 @@ with gr.Blocks() as demo:
|
|
| 162 |
|
| 163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
|
| 165 |
-
status_output = gr.Textbox(
|
|
|
|
|
|
|
| 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(
|
| 170 |
-
fn=run_and_submit_all,
|
| 171 |
-
outputs=[status_output, results_table]
|
| 172 |
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 176 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 177 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 178 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 179 |
|
| 180 |
if space_host_startup:
|
| 181 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
@@ -183,14 +122,20 @@ if __name__ == "__main__":
|
|
| 183 |
else:
|
| 184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
|
| 186 |
-
if space_id_startup:
|
| 187 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
-
print(
|
|
|
|
|
|
|
|
|
|
| 190 |
else:
|
| 191 |
-
print(
|
|
|
|
|
|
|
|
|
|
| 192 |
|
| 193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
|
| 195 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
-
|
|
|
|
| 1 |
import os
|
| 2 |
+
|
| 3 |
+
import agent
|
| 4 |
import gradio as gr
|
| 5 |
+
import logic
|
|
|
|
| 6 |
import pandas as pd
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
|
| 9 |
+
load_dotenv()
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def run_and_submit_all(
|
| 13 |
+
profile: gr.OAuthProfile | None,
|
| 14 |
+
) -> tuple[str, pd.DataFrame | None]:
|
| 15 |
+
"""Fetches all questions, runs the BasicAgent on them, submits all answers,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
and displays the results.
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
+
Args:
|
| 19 |
+
profile: An optional gr.OAuthProfile object containing user information
|
| 20 |
+
if the user is logged in. If None, the user is not logged in.
|
| 21 |
+
|
| 22 |
+
Returns:
|
| 23 |
+
tuple[str, pd.DataFrame | None]: A tuple containing:
|
| 24 |
+
- A string representing the status of the run and submission process.
|
| 25 |
+
This could be a success message, an error message, or a message
|
| 26 |
+
indicating that no answers were produced.
|
| 27 |
+
- A pandas DataFrame containing the results log. This DataFrame will
|
| 28 |
+
be displayed in the Gradio interface. It can be None if an error
|
| 29 |
+
occurred before the agent was run.
|
| 30 |
+
"""
|
| 31 |
+
# 0. Get user details
|
| 32 |
+
space_id = os.getenv("SPACE_ID")
|
| 33 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 34 |
+
print(agent_code)
|
| 35 |
if profile:
|
| 36 |
+
username = f"{profile.username}"
|
| 37 |
print(f"User logged in: {username}")
|
| 38 |
else:
|
| 39 |
print("User not logged in.")
|
| 40 |
return "Please Login to Hugging Face with the button.", None
|
| 41 |
|
| 42 |
+
# 1. Instantiate Agent
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
try:
|
| 44 |
+
gaia_agent = agent.GaiaAgent()
|
| 45 |
except Exception as e:
|
| 46 |
print(f"Error instantiating agent: {e}")
|
| 47 |
return f"Error initializing agent: {e}", None
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
# 2. Fetch Questions
|
|
|
|
| 50 |
try:
|
| 51 |
+
questions_data = logic.fetch_all_questions()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
except Exception as e:
|
| 53 |
+
return str(e), None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
|
| 55 |
+
# 3. Run the Agent
|
| 56 |
+
results_log, answers_payload = logic.run_agent(gaia_agent, questions_data)
|
| 57 |
if not answers_payload:
|
| 58 |
print("Agent did not produce any answers to submit.")
|
| 59 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 60 |
|
| 61 |
+
# 4. Prepare & Submit Answers
|
| 62 |
+
submission_data = {
|
| 63 |
+
"username": username.strip(),
|
| 64 |
+
"agent_code": agent_code,
|
| 65 |
+
"answers": answers_payload,
|
| 66 |
+
}
|
| 67 |
+
print(
|
| 68 |
+
f"Agent finished. Submitting {len(answers_payload)} answers for user '"
|
| 69 |
+
f"{username}'..."
|
| 70 |
+
)
|
| 71 |
+
return logic.submit_answers(submission_data, results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
|
| 73 |
|
| 74 |
# --- Build Gradio Interface using Blocks ---
|
| 75 |
+
with gr.Blocks() as gaia_ui:
|
| 76 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 77 |
gr.Markdown(
|
| 78 |
"""
|
| 79 |
**Instructions:**
|
| 80 |
|
| 81 |
+
1. Please clone this space, then modify the code to define your agent's
|
| 82 |
+
logic, the tools, the necessary packages, etc ...
|
| 83 |
+
2. Log in to your Hugging Face account using the button below. This uses
|
| 84 |
+
your HF username for submission.
|
| 85 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your
|
| 86 |
+
agent, submit answers, and see the score.
|
| 87 |
|
| 88 |
---
|
| 89 |
**Disclaimers:**
|
| 90 |
+
Once clicking on the "submit button, it can take quite some time ( this is
|
| 91 |
+
the time for the agent to go through all the questions).
|
| 92 |
+
This space provides a basic setup and is intentionally sub-optimal to
|
| 93 |
+
encourage you to develop your own, more robust solution. For instance for the
|
| 94 |
+
delay process of the submit button, a solution could be to cache the answers
|
| 95 |
+
and submit in a separate action or even to answer the questions in async.
|
| 96 |
"""
|
| 97 |
)
|
| 98 |
|
|
|
|
| 100 |
|
| 101 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 102 |
|
| 103 |
+
status_output = gr.Textbox(
|
| 104 |
+
label="Run Status / Submission Result", lines=5, interactive=False
|
| 105 |
+
)
|
| 106 |
# Removed max_rows=10 from DataFrame constructor
|
| 107 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 108 |
|
| 109 |
run_button.click(
|
| 110 |
+
fn=run_and_submit_all, inputs=None, outputs=[status_output, results_table]
|
|
|
|
| 111 |
)
|
| 112 |
|
| 113 |
if __name__ == "__main__":
|
| 114 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 115 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 116 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 117 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 118 |
|
| 119 |
if space_host_startup:
|
| 120 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 122 |
else:
|
| 123 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 124 |
|
| 125 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 126 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 127 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 128 |
+
print(
|
| 129 |
+
f" Repo Tree URL: https://huggingface.co/spaces/"
|
| 130 |
+
f"{space_id_startup}/tree/main"
|
| 131 |
+
)
|
| 132 |
else:
|
| 133 |
+
print(
|
| 134 |
+
"ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL "
|
| 135 |
+
"cannot be determined."
|
| 136 |
+
)
|
| 137 |
|
| 138 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 139 |
|
| 140 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 141 |
+
gaia_ui.launch(debug=True, share=True)
|
gitattributes
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
logic.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from typing import Any, Dict, List, Tuple
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import requests
|
| 5 |
+
|
| 6 |
+
def fetch_all_questions() -> List[Dict[str, Any]]:
|
| 7 |
+
"""Fetch all questions from the GAIA benchmark API."""
|
| 8 |
+
try:
|
| 9 |
+
# The actual endpoint will be provided by the GAIA benchmark
|
| 10 |
+
api_url = os.getenv("GAIA_API_URL", "")
|
| 11 |
+
if not api_url:
|
| 12 |
+
raise ValueError("GAIA_API_URL environment variable not set")
|
| 13 |
+
|
| 14 |
+
response = requests.get(f"{api_url}/questions")
|
| 15 |
+
response.raise_for_status()
|
| 16 |
+
|
| 17 |
+
questions = response.json()
|
| 18 |
+
return questions
|
| 19 |
+
except Exception as e:
|
| 20 |
+
raise Exception(f"Failed to fetch questions: {str(e)}")
|
| 21 |
+
|
| 22 |
+
def run_agent(agent: Any, questions: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
|
| 23 |
+
"""Run the agent on all questions and collect results.
|
| 24 |
+
|
| 25 |
+
Args:
|
| 26 |
+
agent: The GaiaAgent instance
|
| 27 |
+
questions: List of question data from the API
|
| 28 |
+
|
| 29 |
+
Returns:
|
| 30 |
+
Tuple containing:
|
| 31 |
+
- List of result logs for display
|
| 32 |
+
- List of answer payloads for submission
|
| 33 |
+
"""
|
| 34 |
+
results_log = []
|
| 35 |
+
answers_payload = []
|
| 36 |
+
|
| 37 |
+
for question in questions:
|
| 38 |
+
question_id = question.get("id", "unknown")
|
| 39 |
+
question_text = question.get("question", "")
|
| 40 |
+
|
| 41 |
+
try:
|
| 42 |
+
# Get answer from agent
|
| 43 |
+
answer = agent.get_answer(question)
|
| 44 |
+
|
| 45 |
+
# Log result
|
| 46 |
+
result_entry = {
|
| 47 |
+
"Question ID": question_id,
|
| 48 |
+
"Question": question_text,
|
| 49 |
+
"Answer": answer if answer else "No answer provided",
|
| 50 |
+
"Status": "Success" if answer else "Failed"
|
| 51 |
+
}
|
| 52 |
+
results_log.append(result_entry)
|
| 53 |
+
|
| 54 |
+
# Prepare submission payload if answer was generated
|
| 55 |
+
if answer:
|
| 56 |
+
answer_entry = {
|
| 57 |
+
"question_id": question_id,
|
| 58 |
+
"answer": answer
|
| 59 |
+
}
|
| 60 |
+
answers_payload.append(answer_entry)
|
| 61 |
+
|
| 62 |
+
except Exception as e:
|
| 63 |
+
# Log error
|
| 64 |
+
result_entry = {
|
| 65 |
+
"Question ID": question_id,
|
| 66 |
+
"Question": question_text,
|
| 67 |
+
"Answer": f"Error: {str(e)}",
|
| 68 |
+
"Status": "Failed"
|
| 69 |
+
}
|
| 70 |
+
results_log.append(result_entry)
|
| 71 |
+
|
| 72 |
+
return results_log, answers_payload
|
| 73 |
+
|
| 74 |
+
def submit_answers(submission_data: Dict[str, Any], results_log: List[Dict[str, Any]]) -> Tuple[str, pd.DataFrame]:
|
| 75 |
+
"""Submit answers to the GAIA benchmark API.
|
| 76 |
+
|
| 77 |
+
Args:
|
| 78 |
+
submission_data: Dictionary containing submission details
|
| 79 |
+
results_log: List of result logs for display
|
| 80 |
+
|
| 81 |
+
Returns:
|
| 82 |
+
Tuple containing:
|
| 83 |
+
- Status message string
|
| 84 |
+
- DataFrame of results for display
|
| 85 |
+
"""
|
| 86 |
+
try:
|
| 87 |
+
# The actual endpoint will be provided by the GAIA benchmark
|
| 88 |
+
api_url = os.getenv("GAIA_API_URL", "")
|
| 89 |
+
if not api_url:
|
| 90 |
+
raise ValueError("GAIA_API_URL environment variable not set")
|
| 91 |
+
|
| 92 |
+
# Submit answers
|
| 93 |
+
response = requests.post(
|
| 94 |
+
f"{api_url}/submit",
|
| 95 |
+
json=submission_data
|
| 96 |
+
)
|
| 97 |
+
response.raise_for_status()
|
| 98 |
+
|
| 99 |
+
# Create DataFrame for display
|
| 100 |
+
results_df = pd.DataFrame(results_log)
|
| 101 |
+
|
| 102 |
+
# Return success message and results
|
| 103 |
+
return "Answers submitted successfully!", results_df
|
| 104 |
+
|
| 105 |
+
except Exception as e:
|
| 106 |
+
# If submission fails, still show results but with error message
|
| 107 |
+
results_df = pd.DataFrame(results_log)
|
| 108 |
+
return f"Error submitting answers: {str(e)}", results_df
|
requirements.txt
CHANGED
|
@@ -1,2 +1,9 @@
|
|
| 1 |
-
gradio
|
| 2 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio==5.25.2
|
| 2 |
+
transformers
|
| 3 |
+
torch
|
| 4 |
+
accelerate
|
| 5 |
+
duckduckgo-search
|
| 6 |
+
python-dotenv
|
| 7 |
+
pandas
|
| 8 |
+
requests
|
| 9 |
+
numpy
|