Spaces:
Running
Running
hammaad-swe
commited on
Commit
·
11534de
1
Parent(s):
81917a3
feat: modularized code
Browse files- .gitignore +6 -0
- README.md +2 -2
- app.py +74 -131
- gaia_agent.py +33 -0
- logic.py +163 -0
- requirements.txt +4 -1
.gitignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.venv
|
2 |
+
.env
|
3 |
+
.vscode/
|
4 |
+
.idea/
|
5 |
+
.DS_Store
|
6 |
+
.gitattributes
|
README.md
CHANGED
@@ -1,5 +1,5 @@
|
|
1 |
---
|
2 |
-
title:
|
3 |
emoji: 🕵🏻♂️
|
4 |
colorFrom: indigo
|
5 |
colorTo: indigo
|
@@ -9,7 +9,7 @@ app_file: app.py
|
|
9 |
pinned: false
|
10 |
hf_oauth: true
|
11 |
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
|
12 |
-
hf_oauth_expiration_minutes:
|
13 |
---
|
14 |
|
15 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
1 |
---
|
2 |
+
title: GAIA - Agents Course Assignment
|
3 |
emoji: 🕵🏻♂️
|
4 |
colorFrom: indigo
|
5 |
colorTo: indigo
|
|
|
9 |
pinned: false
|
10 |
hf_oauth: true
|
11 |
# optional, default duration is 8 hours/480 minutes. Max duration is 30 days/43200 minutes.
|
12 |
+
hf_oauth_expiration_minutes: 567
|
13 |
---
|
14 |
|
15 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
CHANGED
@@ -1,160 +1,96 @@
|
|
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 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
13 |
-
class BasicAgent:
|
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 |
-
agent =
|
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 +98,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 +120,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 gaia_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(profile: gr.OAuthProfile | None):
|
13 |
+
"""Fetches all questions, runs the BasicAgent on them, submits all answers,
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
14 |
and displays the results.
|
|
|
|
|
|
|
15 |
|
16 |
+
Args:
|
17 |
+
profile: An optional gr.OAuthProfile object containing user information
|
18 |
+
if the user is logged in. If None, the user is not logged in.
|
19 |
+
|
20 |
+
Returns:
|
21 |
+
tuple[str, pd.DataFrame | None]: A tuple containing:
|
22 |
+
- A string representing the status of the run and submission process.
|
23 |
+
This could be a success message, an error message, or a message
|
24 |
+
indicating that no answers were produced.
|
25 |
+
- A pandas DataFrame containing the results log. This DataFrame will
|
26 |
+
be displayed in the Gradio interface. It can be None if an error
|
27 |
+
occurred before the agent was run.
|
28 |
+
"""
|
29 |
+
# 0. Get user details
|
30 |
+
space_id = os.getenv("SPACE_ID")
|
31 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
32 |
+
print(agent_code)
|
33 |
if profile:
|
34 |
+
username = f"{profile.username}"
|
35 |
print(f"User logged in: {username}")
|
36 |
else:
|
37 |
print("User not logged in.")
|
38 |
return "Please Login to Hugging Face with the button.", None
|
39 |
|
40 |
+
# 1. Instantiate Agent
|
|
|
|
|
|
|
|
|
41 |
try:
|
42 |
+
agent = gaia_agent.GaiaAgent()
|
43 |
except Exception as e:
|
44 |
print(f"Error instantiating agent: {e}")
|
45 |
return f"Error initializing agent: {e}", None
|
|
|
|
|
|
|
46 |
|
47 |
# 2. Fetch Questions
|
|
|
48 |
try:
|
49 |
+
questions_data = logic.fetch_all_questions()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
50 |
except Exception as e:
|
51 |
+
return str(e), None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
52 |
|
53 |
+
# 3. Run the Agent
|
54 |
+
results_log, answers_payload = logic.run_agent(agent, questions_data)
|
55 |
if not answers_payload:
|
56 |
print("Agent did not produce any answers to submit.")
|
57 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
58 |
|
59 |
+
# 4. Prepare & Submit Answers
|
60 |
+
submission_data = {
|
61 |
+
"username": username.strip(),
|
62 |
+
"agent_code": agent_code,
|
63 |
+
"answers": answers_payload,
|
64 |
+
}
|
65 |
+
print(
|
66 |
+
f"Agent finished. Submitting {len(answers_payload)} answers for user '"
|
67 |
+
f"{username}'..."
|
68 |
+
)
|
69 |
+
return logic.submit_answers(submission_data, results_log)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
70 |
|
71 |
|
72 |
# --- Build Gradio Interface using Blocks ---
|
73 |
+
with gr.Blocks() as gaia_ui:
|
74 |
gr.Markdown("# Basic Agent Evaluation Runner")
|
75 |
gr.Markdown(
|
76 |
"""
|
77 |
**Instructions:**
|
78 |
|
79 |
+
1. Please clone this space, then modify the code to define your agent's
|
80 |
+
logic, the tools, the necessary packages, etc ...
|
81 |
+
2. Log in to your Hugging Face account using the button below. This uses
|
82 |
+
your HF username for submission.
|
83 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your
|
84 |
+
agent, submit answers, and see the score.
|
85 |
|
86 |
---
|
87 |
**Disclaimers:**
|
88 |
+
Once clicking on the "submit button, it can take quite some time ( this is
|
89 |
+
the time for the agent to go through all the questions).
|
90 |
+
This space provides a basic setup and is intentionally sub-optimal to
|
91 |
+
encourage you to develop your own, more robust solution. For instance for the
|
92 |
+
delay process of the submit button, a solution could be to cache the answers
|
93 |
+
and submit in a separate action or even to answer the questions in async.
|
94 |
"""
|
95 |
)
|
96 |
|
|
|
98 |
|
99 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
100 |
|
101 |
+
status_output = gr.Textbox(
|
102 |
+
label="Run Status / Submission Result", lines=5, interactive=False
|
103 |
+
)
|
104 |
# Removed max_rows=10 from DataFrame constructor
|
105 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
106 |
|
107 |
run_button.click(
|
108 |
+
fn=run_and_submit_all, inputs=None, outputs=[status_output, results_table]
|
|
|
109 |
)
|
110 |
|
111 |
if __name__ == "__main__":
|
112 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
113 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
114 |
space_host_startup = os.getenv("SPACE_HOST")
|
115 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
116 |
|
117 |
if space_host_startup:
|
118 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
120 |
else:
|
121 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
122 |
|
123 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
124 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
125 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
126 |
+
print(
|
127 |
+
f" Repo Tree URL: https://huggingface.co/spaces/"
|
128 |
+
f"{space_id_startup}/tree/main"
|
129 |
+
)
|
130 |
else:
|
131 |
+
print(
|
132 |
+
"ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL "
|
133 |
+
"cannot be determined."
|
134 |
+
)
|
135 |
|
136 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
137 |
|
138 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
139 |
+
gaia_ui.launch(debug=True, share=False)
|
gaia_agent.py
ADDED
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
class GaiaAgent:
|
2 |
+
"""
|
3 |
+
A basic agent that receives a question and returns a fixed answer.
|
4 |
+
|
5 |
+
This class serves as a placeholder or a simple baseline agent for testing
|
6 |
+
and demonstration purposes. It does not perform any sophisticated
|
7 |
+
reasoning or information retrieval.
|
8 |
+
"""
|
9 |
+
|
10 |
+
def __init__(self):
|
11 |
+
"""
|
12 |
+
Initializes the GaiaAgent.
|
13 |
+
|
14 |
+
Currently, this constructor simply prints a message to the console.
|
15 |
+
In a more complex implementation, this method might load a model,
|
16 |
+
connect to a database, or perform other setup tasks.
|
17 |
+
"""
|
18 |
+
print("BasicAgent initialized.")
|
19 |
+
|
20 |
+
def __call__(self, question: str) -> str:
|
21 |
+
"""
|
22 |
+
Processes a question and returns a fixed answer.
|
23 |
+
|
24 |
+
Args:
|
25 |
+
question: The question to be processed.
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
A fixed string representing the agent's answer.
|
29 |
+
"""
|
30 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
31 |
+
fixed_answer = "This is a default answer."
|
32 |
+
print(f"Agent returning fixed answer: {fixed_answer}")
|
33 |
+
return fixed_answer
|
logic.py
ADDED
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Dict, List, Tuple
|
2 |
+
|
3 |
+
import pandas as pd
|
4 |
+
import requests
|
5 |
+
from gaia_agent import GaiaAgent
|
6 |
+
from pandas import DataFrame
|
7 |
+
|
8 |
+
# --- Constants ---
|
9 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
10 |
+
QUESTIONS_URL = f"{DEFAULT_API_URL}/questions"
|
11 |
+
SUBMIT_URL = f"{DEFAULT_API_URL}/submit"
|
12 |
+
|
13 |
+
|
14 |
+
# --- Helper Methods ---
|
15 |
+
def fetch_all_questions() -> Dict:
|
16 |
+
"""Fetches all questions from the specified API endpoint.
|
17 |
+
|
18 |
+
This function retrieves a list of questions from the API, handles potential errors
|
19 |
+
such as network issues, invalid responses, or empty question lists, and returns
|
20 |
+
the questions as a dictionary.
|
21 |
+
|
22 |
+
Returns:
|
23 |
+
Dict: A dictionary containing the questions data retrieved from the API.
|
24 |
+
|
25 |
+
Raises:
|
26 |
+
UserWarning: If there is an error fetching the questions, such as network issues,
|
27 |
+
invalid JSON response, or an empty question list. The exception message
|
28 |
+
provides details about the specific error encountered.
|
29 |
+
"""
|
30 |
+
print(f"Fetching questions from: {QUESTIONS_URL}")
|
31 |
+
response = requests.get(QUESTIONS_URL, timeout=15)
|
32 |
+
try:
|
33 |
+
response.raise_for_status()
|
34 |
+
questions_data = response.json()
|
35 |
+
if not questions_data:
|
36 |
+
print("Fetched questions list is empty.")
|
37 |
+
raise UserWarning("Fetched questions list is empty or invalid format.")
|
38 |
+
print(f"Fetched {len(questions_data)} questions.")
|
39 |
+
return questions_data
|
40 |
+
except requests.exceptions.RequestException as e:
|
41 |
+
print(f"Error fetching questions: {e}")
|
42 |
+
raise UserWarning(f"Error fetching questions: {e}")
|
43 |
+
except requests.exceptions.JSONDecodeError as e:
|
44 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
45 |
+
print(f"Response text: {response.text[:500]}")
|
46 |
+
raise UserWarning(f"Error decoding server response for questions: {e}")
|
47 |
+
except Exception as e:
|
48 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
49 |
+
raise UserWarning(f"An unexpected error occurred fetching questions: {e}")
|
50 |
+
|
51 |
+
|
52 |
+
def submit_answers(submission_data: dict, results_log: list) -> Tuple[str, DataFrame]:
|
53 |
+
"""Submits answers to the scoring API and returns the submission status and results.
|
54 |
+
|
55 |
+
This function sends the provided answers to the scoring API, handles potential errors
|
56 |
+
such as network issues, server errors, or invalid responses, and returns a status
|
57 |
+
message indicating the success or failure of the submission, along with a DataFrame
|
58 |
+
containing the results log.
|
59 |
+
|
60 |
+
Args:
|
61 |
+
submission_data (dict): A dictionary containing the answers to be submitted.
|
62 |
+
Expected to have a structure compatible with the scoring API.
|
63 |
+
results_log (list): A list of dictionaries containing the results log.
|
64 |
+
This log is converted to a Pandas DataFrame and returned.
|
65 |
+
|
66 |
+
Returns:
|
67 |
+
Tuple[str, DataFrame]: A tuple containing:
|
68 |
+
- A status message (str) indicating the submission status and any relevant
|
69 |
+
information or error messages.
|
70 |
+
- A Pandas DataFrame containing the results log.
|
71 |
+
|
72 |
+
"""
|
73 |
+
try:
|
74 |
+
response = requests.post(SUBMIT_URL, json=submission_data, timeout=60)
|
75 |
+
response.raise_for_status()
|
76 |
+
result_data = response.json()
|
77 |
+
final_status = (
|
78 |
+
f"Submission Successful!\n"
|
79 |
+
f"User: {result_data.get('username')}\n"
|
80 |
+
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
81 |
+
f"({result_data.get('correct_count', '?')}/"
|
82 |
+
f"{result_data.get('total_attempted', '?')} correct)\n"
|
83 |
+
f"Message: {result_data.get('message', 'No message received.')}"
|
84 |
+
)
|
85 |
+
print("Submission successful.")
|
86 |
+
results_df = pd.DataFrame(results_log)
|
87 |
+
return final_status, results_df
|
88 |
+
except requests.exceptions.HTTPError as e:
|
89 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
90 |
+
try:
|
91 |
+
error_json = e.response.json()
|
92 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
93 |
+
except requests.exceptions.JSONDecodeError:
|
94 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
95 |
+
status_message = f"Submission Failed: {error_detail}"
|
96 |
+
print(status_message)
|
97 |
+
results_df = pd.DataFrame(results_log)
|
98 |
+
return status_message, results_df
|
99 |
+
except requests.exceptions.Timeout:
|
100 |
+
status_message = "Submission Failed: The request timed out."
|
101 |
+
print(status_message)
|
102 |
+
results_df = pd.DataFrame(results_log)
|
103 |
+
return status_message, results_df
|
104 |
+
except requests.exceptions.RequestException as e:
|
105 |
+
status_message = f"Submission Failed: Network error - {e}"
|
106 |
+
print(status_message)
|
107 |
+
results_df = pd.DataFrame(results_log)
|
108 |
+
return status_message, results_df
|
109 |
+
except Exception as e:
|
110 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
111 |
+
print(status_message)
|
112 |
+
results_df = pd.DataFrame(results_log)
|
113 |
+
return status_message, results_df
|
114 |
+
|
115 |
+
|
116 |
+
def run_agent(agent: GaiaAgent,
|
117 |
+
questions_data: List[Dict]) -> Tuple[List[Dict], List[Dict]]:
|
118 |
+
"""Runs the agent on a list of questions and returns the results and answers.
|
119 |
+
|
120 |
+
This function iterates through a list of questions, runs the provided agent on each
|
121 |
+
question, and collects the results and answers. It handles potential errors during
|
122 |
+
agent execution and returns the results log and the answers payload.
|
123 |
+
|
124 |
+
Args:
|
125 |
+
agent (GaiaAgent): An instance of the GaiaAgent class, which is responsible for
|
126 |
+
generating answers to the questions.
|
127 |
+
questions_data (List[Dict]): A list of dictionaries, where each dictionary
|
128 |
+
represents a question and contains at least the 'task_id' and 'question' keys.
|
129 |
+
|
130 |
+
Returns:
|
131 |
+
Tuple[List[Dict], List[Dict]]: A tuple containing:
|
132 |
+
- A list of dictionaries representing the results log, where each dictionary
|
133 |
+
contains the 'Task ID', 'Question', and 'Submitted Answer'.
|
134 |
+
- A list of dictionaries representing the answers payload, where each dictionary
|
135 |
+
contains the 'task_id' and 'submitted_answer'.
|
136 |
+
"""
|
137 |
+
results_log = []
|
138 |
+
answers_payload = []
|
139 |
+
|
140 |
+
print(f"🚀 Running agent on {len(questions_data)} questions...")
|
141 |
+
for item in questions_data:
|
142 |
+
task_id = item.get("task_id")
|
143 |
+
question_text = item.get("question")
|
144 |
+
if not task_id or question_text is None:
|
145 |
+
print(f"⚠️ Skipping invalid item (missing task_id or question): {item}")
|
146 |
+
continue
|
147 |
+
try:
|
148 |
+
submitted_answer = agent(question_text)
|
149 |
+
answers_payload.append(
|
150 |
+
{"task_id": task_id, "submitted_answer": submitted_answer}
|
151 |
+
)
|
152 |
+
except Exception as e:
|
153 |
+
print(f"❌ Error running agent on task {task_id}: {e}")
|
154 |
+
submitted_answer = f"AGENT ERROR: {e}"
|
155 |
+
|
156 |
+
results_log.append(
|
157 |
+
{
|
158 |
+
"Task ID": task_id,
|
159 |
+
"Question": question_text,
|
160 |
+
"Submitted Answer": submitted_answer,
|
161 |
+
}
|
162 |
+
)
|
163 |
+
return results_log, answers_payload
|
requirements.txt
CHANGED
@@ -1,2 +1,5 @@
|
|
1 |
gradio
|
2 |
-
|
|
|
|
|
|
|
|
1 |
gradio
|
2 |
+
gradio[oauth]
|
3 |
+
requests
|
4 |
+
python-dotenv
|
5 |
+
pandas
|