Spaces:
Runtime error
Runtime error
Omachoko
commited on
Commit
·
2d95e30
1
Parent(s):
30baeaa
Integrate ModularGAIAAgent into evaluation runner architecture
Browse files
app.py
CHANGED
|
@@ -19,100 +19,85 @@ agent = ModularGAIAAgent()
|
|
| 19 |
# --- Constants ---
|
| 20 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 21 |
|
| 22 |
-
# ---
|
| 23 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 24 |
class BasicAgent:
|
| 25 |
def __init__(self):
|
| 26 |
print("BasicAgent (GAIA Modular Agent) initialized.")
|
| 27 |
self.agent = ModularGAIAAgent()
|
| 28 |
-
def __call__(self, question: str) -> str:
|
| 29 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 30 |
try:
|
| 31 |
-
answer, trace = self.agent.answer_question({"task_id": "manual", "question": question, "file_name":
|
| 32 |
print(f"Agent returning answer: {answer}")
|
| 33 |
return answer
|
| 34 |
except Exception as e:
|
| 35 |
print(f"Agent error: {e}")
|
| 36 |
return f"AGENT ERROR: {e}"
|
| 37 |
|
| 38 |
-
def run_and_submit_all(
|
| 39 |
"""
|
| 40 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 41 |
and displays the results.
|
| 42 |
"""
|
| 43 |
-
|
| 44 |
-
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 45 |
-
|
| 46 |
if profile:
|
| 47 |
-
username= f"{profile.username}"
|
| 48 |
print(f"User logged in: {username}")
|
| 49 |
else:
|
| 50 |
print("User not logged in.")
|
| 51 |
return "Please Login to Hugging Face with the button.", None
|
| 52 |
-
|
| 53 |
api_url = DEFAULT_API_URL
|
| 54 |
questions_url = f"{api_url}/questions"
|
| 55 |
submit_url = f"{api_url}/submit"
|
| 56 |
-
|
| 57 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 58 |
try:
|
| 59 |
agent = BasicAgent()
|
| 60 |
except Exception as e:
|
| 61 |
print(f"Error instantiating agent: {e}")
|
| 62 |
return f"Error initializing agent: {e}", None
|
| 63 |
-
# 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)
|
| 64 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 65 |
print(agent_code)
|
| 66 |
-
|
| 67 |
-
# 2. Fetch Questions
|
| 68 |
print(f"Fetching questions from: {questions_url}")
|
| 69 |
try:
|
| 70 |
response = requests.get(questions_url, timeout=15)
|
| 71 |
response.raise_for_status()
|
| 72 |
questions_data = response.json()
|
| 73 |
if not questions_data:
|
| 74 |
-
|
| 75 |
-
|
| 76 |
print(f"Fetched {len(questions_data)} questions.")
|
| 77 |
except requests.exceptions.RequestException as e:
|
| 78 |
print(f"Error fetching questions: {e}")
|
| 79 |
return f"Error fetching questions: {e}", None
|
| 80 |
except requests.exceptions.JSONDecodeError as e:
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
except Exception as e:
|
| 85 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 86 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 87 |
-
|
| 88 |
-
# 3. Run your Agent
|
| 89 |
results_log = []
|
| 90 |
answers_payload = []
|
| 91 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 92 |
for item in questions_data:
|
| 93 |
task_id = item.get("task_id")
|
| 94 |
question_text = item.get("question")
|
|
|
|
| 95 |
if not task_id or question_text is None:
|
| 96 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 97 |
continue
|
| 98 |
try:
|
| 99 |
-
submitted_answer = agent(question_text)
|
| 100 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 101 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 102 |
except Exception as e:
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
if not answers_payload:
|
| 107 |
print("Agent did not produce any answers to submit.")
|
| 108 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 109 |
-
|
| 110 |
-
# 4. Prepare Submission
|
| 111 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 112 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 113 |
print(status_update)
|
| 114 |
-
|
| 115 |
-
# 5. Submit
|
| 116 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 117 |
try:
|
| 118 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
@@ -123,8 +108,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 123 |
f"User: {result_data.get('username')}\n"
|
| 124 |
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 125 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 126 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 127 |
-
)
|
| 128 |
print("Submission successful.")
|
| 129 |
results_df = pd.DataFrame(results_log)
|
| 130 |
return final_status, results_df
|
|
@@ -155,75 +139,44 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 155 |
results_df = pd.DataFrame(results_log)
|
| 156 |
return status_message, results_df
|
| 157 |
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
"
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
)
|
| 169 |
-
|
| 170 |
-
def submit_answers(username, agent_code_url):
|
| 171 |
-
# Placeholder for submission logic
|
| 172 |
-
return f"Submission for {username} with code {agent_code_url} (not implemented in demo)"
|
| 173 |
-
|
| 174 |
-
def show_leaderboard():
|
| 175 |
-
# Placeholder for leaderboard logic
|
| 176 |
-
return "Leaderboard feature coming soon."
|
| 177 |
-
|
| 178 |
-
demo = gr.Blocks(title="GAIA Benchmark Agent", theme=gr.themes.Soft())
|
| 179 |
-
with demo:
|
| 180 |
-
gr.Markdown("""
|
| 181 |
-
# 🤖 GAIA Benchmark Agent
|
| 182 |
-
Multi-modal, multi-step reasoning agent for the Hugging Face GAIA benchmark.
|
| 183 |
-
""")
|
| 184 |
-
with gr.Tabs():
|
| 185 |
-
with gr.TabItem("API Q&A"):
|
| 186 |
-
api_btn = gr.Button("Run on API Questions", variant="primary")
|
| 187 |
-
api_output = gr.Textbox(label="Answers and Reasoning Trace", lines=20)
|
| 188 |
-
api_btn.click(run_api_questions, outputs=api_output)
|
| 189 |
-
with gr.TabItem("Manual Input"):
|
| 190 |
-
manual_q = gr.Textbox(label="Enter your question", lines=3)
|
| 191 |
-
manual_btn = gr.Button("Answer", variant="primary")
|
| 192 |
-
manual_a = gr.Textbox(label="Answer")
|
| 193 |
-
manual_trace = gr.Textbox(label="Reasoning Trace", lines=5)
|
| 194 |
-
manual_btn.click(run_manual_question, inputs=manual_q, outputs=[manual_a, manual_trace])
|
| 195 |
-
with gr.TabItem("Submission/Leaderboard"):
|
| 196 |
-
username = gr.Textbox(label="Hugging Face Username")
|
| 197 |
-
code_url = gr.Textbox(label="Agent Code URL")
|
| 198 |
-
submit_btn = gr.Button("Submit Answers", variant="primary")
|
| 199 |
-
submit_out = gr.Textbox(label="Submission Result")
|
| 200 |
-
submit_btn.click(submit_answers, inputs=[username, code_url], outputs=submit_out)
|
| 201 |
-
leaderboard_btn = gr.Button("Show Leaderboard")
|
| 202 |
-
leaderboard_out = gr.Textbox(label="Leaderboard")
|
| 203 |
-
leaderboard_btn.click(show_leaderboard, outputs=leaderboard_out)
|
| 204 |
-
with gr.TabItem("Agent Help"):
|
| 205 |
-
help_md = gr.Markdown(show_help())
|
| 206 |
|
| 207 |
if __name__ == "__main__":
|
| 208 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 209 |
-
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 210 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 211 |
-
space_id_startup = os.getenv("SPACE_ID")
|
| 212 |
-
|
| 213 |
if space_host_startup:
|
| 214 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 215 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 216 |
else:
|
| 217 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 218 |
-
|
| 219 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 220 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 221 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 222 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 223 |
else:
|
| 224 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 225 |
-
|
| 226 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 227 |
-
|
| 228 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 229 |
demo.launch(debug=True, share=False)
|
|
|
|
| 19 |
# --- Constants ---
|
| 20 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 21 |
|
| 22 |
+
# --- Advanced Modular Agent Integration ---
|
|
|
|
| 23 |
class BasicAgent:
|
| 24 |
def __init__(self):
|
| 25 |
print("BasicAgent (GAIA Modular Agent) initialized.")
|
| 26 |
self.agent = ModularGAIAAgent()
|
| 27 |
+
def __call__(self, question: str, file_name: str = "") -> str:
|
| 28 |
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 29 |
try:
|
| 30 |
+
answer, trace = self.agent.answer_question({"task_id": "manual", "question": question, "file_name": file_name})
|
| 31 |
print(f"Agent returning answer: {answer}")
|
| 32 |
return answer
|
| 33 |
except Exception as e:
|
| 34 |
print(f"Agent error: {e}")
|
| 35 |
return f"AGENT ERROR: {e}"
|
| 36 |
|
| 37 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 38 |
"""
|
| 39 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 40 |
and displays the results.
|
| 41 |
"""
|
| 42 |
+
space_id = os.getenv("SPACE_ID")
|
|
|
|
|
|
|
| 43 |
if profile:
|
| 44 |
+
username = f"{profile.username}"
|
| 45 |
print(f"User logged in: {username}")
|
| 46 |
else:
|
| 47 |
print("User not logged in.")
|
| 48 |
return "Please Login to Hugging Face with the button.", None
|
|
|
|
| 49 |
api_url = DEFAULT_API_URL
|
| 50 |
questions_url = f"{api_url}/questions"
|
| 51 |
submit_url = f"{api_url}/submit"
|
|
|
|
|
|
|
| 52 |
try:
|
| 53 |
agent = BasicAgent()
|
| 54 |
except Exception as e:
|
| 55 |
print(f"Error instantiating agent: {e}")
|
| 56 |
return f"Error initializing agent: {e}", None
|
|
|
|
| 57 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 58 |
print(agent_code)
|
|
|
|
|
|
|
| 59 |
print(f"Fetching questions from: {questions_url}")
|
| 60 |
try:
|
| 61 |
response = requests.get(questions_url, timeout=15)
|
| 62 |
response.raise_for_status()
|
| 63 |
questions_data = response.json()
|
| 64 |
if not questions_data:
|
| 65 |
+
print("Fetched questions list is empty.")
|
| 66 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 67 |
print(f"Fetched {len(questions_data)} questions.")
|
| 68 |
except requests.exceptions.RequestException as e:
|
| 69 |
print(f"Error fetching questions: {e}")
|
| 70 |
return f"Error fetching questions: {e}", None
|
| 71 |
except requests.exceptions.JSONDecodeError as e:
|
| 72 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 73 |
+
print(f"Response text: {response.text[:500]}")
|
| 74 |
+
return f"Error decoding server response for questions: {e}", None
|
| 75 |
except Exception as e:
|
| 76 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 77 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
|
|
|
|
| 78 |
results_log = []
|
| 79 |
answers_payload = []
|
| 80 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 81 |
for item in questions_data:
|
| 82 |
task_id = item.get("task_id")
|
| 83 |
question_text = item.get("question")
|
| 84 |
+
file_name = item.get("file_name", "")
|
| 85 |
if not task_id or question_text is None:
|
| 86 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 87 |
continue
|
| 88 |
try:
|
| 89 |
+
submitted_answer = agent(question_text, file_name)
|
| 90 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 91 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
| 92 |
except Exception as e:
|
| 93 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 94 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
|
| 95 |
if not answers_payload:
|
| 96 |
print("Agent did not produce any answers to submit.")
|
| 97 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
|
|
|
|
|
|
| 98 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 99 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 100 |
print(status_update)
|
|
|
|
|
|
|
| 101 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 102 |
try:
|
| 103 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
|
|
|
| 108 |
f"User: {result_data.get('username')}\n"
|
| 109 |
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 110 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 111 |
+
f"Message: {result_data.get('message', 'No message received.')}")
|
|
|
|
| 112 |
print("Submission successful.")
|
| 113 |
results_df = pd.DataFrame(results_log)
|
| 114 |
return final_status, results_df
|
|
|
|
| 139 |
results_df = pd.DataFrame(results_log)
|
| 140 |
return status_message, results_df
|
| 141 |
|
| 142 |
+
with gr.Blocks() as demo:
|
| 143 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 144 |
+
gr.Markdown(
|
| 145 |
+
"""
|
| 146 |
+
**Instructions:**
|
| 147 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 148 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 149 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 150 |
+
---
|
| 151 |
+
**Disclaimers:**
|
| 152 |
+
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).
|
| 153 |
+
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.
|
| 154 |
+
"""
|
| 155 |
+
)
|
| 156 |
+
gr.LoginButton()
|
| 157 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 158 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 159 |
+
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 160 |
+
run_button.click(
|
| 161 |
+
fn=run_and_submit_all,
|
| 162 |
+
outputs=[status_output, results_table]
|
| 163 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
if __name__ == "__main__":
|
| 166 |
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
|
|
|
| 167 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 168 |
+
space_id_startup = os.getenv("SPACE_ID")
|
|
|
|
| 169 |
if space_host_startup:
|
| 170 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 171 |
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 172 |
else:
|
| 173 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 174 |
+
if space_id_startup:
|
|
|
|
| 175 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 176 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 177 |
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 178 |
else:
|
| 179 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
|
|
|
| 180 |
print("-"*(60 + len(" App Starting ")) + "\n")
|
|
|
|
| 181 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 182 |
demo.launch(debug=True, share=False)
|