Spaces:
Sleeping
Sleeping
Update app.py
#1
by
olcapone
- opened
app.py
CHANGED
|
@@ -1,25 +1,13 @@
|
|
| 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 |
-
# ----- 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.
|
|
@@ -28,7 +16,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 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.")
|
|
@@ -38,20 +26,21 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 38 |
questions_url = f"{api_url}/questions"
|
| 39 |
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
# 1. Instantiate Agent
|
| 42 |
try:
|
| 43 |
agent = BasicAgent()
|
| 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=
|
| 55 |
response.raise_for_status()
|
| 56 |
questions_data = response.json()
|
| 57 |
if not questions_data:
|
|
@@ -73,12 +62,22 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 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})
|
|
@@ -99,11 +98,11 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 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 = (
|
| 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"
|
|
@@ -119,78 +118,112 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 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 demo:
|
| 145 |
-
gr.Markdown("#
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
|
|
|
|
|
|
| 148 |
**Instructions:**
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
**Disclaimers:**
|
| 156 |
-
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).
|
| 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 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
print("\n" + "
|
|
|
|
|
|
|
|
|
|
| 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}")
|
| 182 |
-
print(f" Runtime URL
|
| 183 |
else:
|
| 184 |
-
print("βΉοΈ
|
| 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(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 190 |
else:
|
| 191 |
-
print("βΉοΈ SPACE_ID
|
| 192 |
-
|
| 193 |
-
print("
|
| 194 |
-
|
| 195 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
from agent import BasicAgent
|
| 6 |
|
|
|
|
| 7 |
# --- Constants ---
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
"""
|
| 12 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 13 |
and displays the results.
|
|
|
|
| 16 |
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 17 |
|
| 18 |
if profile:
|
| 19 |
+
username = f"{profile.username}"
|
| 20 |
print(f"User logged in: {username}")
|
| 21 |
else:
|
| 22 |
print("User not logged in.")
|
|
|
|
| 26 |
questions_url = f"{api_url}/questions"
|
| 27 |
submit_url = f"{api_url}/submit"
|
| 28 |
|
| 29 |
+
# 1. Instantiate Agent
|
| 30 |
try:
|
| 31 |
agent = BasicAgent()
|
| 32 |
except Exception as e:
|
| 33 |
print(f"Error instantiating agent: {e}")
|
| 34 |
return f"Error initializing agent: {e}", None
|
| 35 |
+
|
| 36 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase
|
| 37 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 38 |
print(agent_code)
|
| 39 |
|
| 40 |
# 2. Fetch Questions
|
| 41 |
print(f"Fetching questions from: {questions_url}")
|
| 42 |
try:
|
| 43 |
+
response = requests.get(questions_url, timeout=30)
|
| 44 |
response.raise_for_status()
|
| 45 |
questions_data = response.json()
|
| 46 |
if not questions_data:
|
|
|
|
| 62 |
results_log = []
|
| 63 |
answers_payload = []
|
| 64 |
print(f"Running agent on {len(questions_data)} questions...")
|
| 65 |
+
|
| 66 |
+
# Progress tracking
|
| 67 |
+
progress_count = 0
|
| 68 |
+
total_questions = len(questions_data)
|
| 69 |
+
|
| 70 |
for item in questions_data:
|
| 71 |
task_id = item.get("task_id")
|
| 72 |
question_text = item.get("question")
|
| 73 |
if not task_id or question_text is None:
|
| 74 |
print(f"Skipping item with missing task_id or question: {item}")
|
| 75 |
continue
|
| 76 |
+
|
| 77 |
+
# Update progress
|
| 78 |
+
progress_count += 1
|
| 79 |
+
print(f"Processing question {progress_count}/{total_questions}")
|
| 80 |
+
|
| 81 |
try:
|
| 82 |
submitted_answer = agent(question_text)
|
| 83 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
|
|
|
| 98 |
# 5. Submit
|
| 99 |
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 100 |
try:
|
| 101 |
+
response = requests.post(submit_url, json=submission_data, timeout=120)
|
| 102 |
response.raise_for_status()
|
| 103 |
result_data = response.json()
|
| 104 |
final_status = (
|
| 105 |
+
f"β
Submission Successful!\n"
|
| 106 |
f"User: {result_data.get('username')}\n"
|
| 107 |
f"Overall Score: {result_data.get('score', 'N/A')}% "
|
| 108 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
|
|
|
| 118 |
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 119 |
except requests.exceptions.JSONDecodeError:
|
| 120 |
error_detail += f" Response: {e.response.text[:500]}"
|
| 121 |
+
status_message = f"β Submission Failed: {error_detail}"
|
| 122 |
print(status_message)
|
| 123 |
results_df = pd.DataFrame(results_log)
|
| 124 |
return status_message, results_df
|
| 125 |
except requests.exceptions.Timeout:
|
| 126 |
+
status_message = "β Submission Failed: The request timed out. Please try again."
|
| 127 |
print(status_message)
|
| 128 |
results_df = pd.DataFrame(results_log)
|
| 129 |
return status_message, results_df
|
| 130 |
except requests.exceptions.RequestException as e:
|
| 131 |
+
status_message = f"β Submission Failed: Network error - {e}"
|
| 132 |
print(status_message)
|
| 133 |
results_df = pd.DataFrame(results_log)
|
| 134 |
return status_message, results_df
|
| 135 |
except Exception as e:
|
| 136 |
+
status_message = f"β An unexpected error occurred during submission: {e}"
|
| 137 |
print(status_message)
|
| 138 |
results_df = pd.DataFrame(results_log)
|
| 139 |
return status_message, results_df
|
| 140 |
|
| 141 |
+
def test_agent(question: str, provider: str):
|
| 142 |
+
"""Test the agent with a single question."""
|
| 143 |
+
try:
|
| 144 |
+
agent = BasicAgent(provider=provider)
|
| 145 |
+
answer = agent(question)
|
| 146 |
+
return f"Question: {question}\nAnswer: {answer}"
|
| 147 |
+
except Exception as e:
|
| 148 |
+
return f"Error testing agent: {e}"
|
| 149 |
|
| 150 |
# --- Build Gradio Interface using Blocks ---
|
| 151 |
+
with gr.Blocks(title="GAIA Agent Evaluator") as demo:
|
| 152 |
+
gr.Markdown("# π€ GAIA Agent Evaluator")
|
| 153 |
gr.Markdown(
|
| 154 |
"""
|
| 155 |
+
This interface allows you to evaluate your agent against the GAIA benchmark questions.
|
| 156 |
+
|
| 157 |
**Instructions:**
|
| 158 |
+
1. Log in to your Hugging Face account using the button below
|
| 159 |
+
2. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, and submit answers
|
| 160 |
+
3. View your results and score in the output panel
|
| 161 |
+
|
| 162 |
+
**For Testing:**
|
| 163 |
+
Use the test section below to verify your agent works correctly with sample questions.
|
|
|
|
|
|
|
|
|
|
| 164 |
"""
|
| 165 |
)
|
| 166 |
+
|
| 167 |
+
with gr.Tab("Evaluation"):
|
| 168 |
+
gr.Markdown("## π Run Full Evaluation")
|
| 169 |
+
gr.LoginButton()
|
| 170 |
+
|
| 171 |
+
with gr.Row():
|
| 172 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers", variant="primary")
|
| 173 |
+
|
| 174 |
+
status_output = gr.Textbox(label="π Status / Submission Result", lines=8, interactive=False)
|
| 175 |
+
results_table = gr.DataFrame(label="π Questions and Agent Answers", wrap=True)
|
| 176 |
+
|
| 177 |
+
run_button.click(
|
| 178 |
+
fn=run_and_submit_all,
|
| 179 |
+
outputs=[status_output, results_table]
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
with gr.Tab("Testing"):
|
| 183 |
+
gr.Markdown("## π§ͺ Test Your Agent")
|
| 184 |
+
with gr.Row():
|
| 185 |
+
with gr.Column():
|
| 186 |
+
test_question = gr.Textbox(
|
| 187 |
+
label="Question",
|
| 188 |
+
placeholder="Enter a test question...",
|
| 189 |
+
value="What is 2+2?"
|
| 190 |
+
)
|
| 191 |
+
provider_choice = gr.Radio(
|
| 192 |
+
choices=["groq", "hf"],
|
| 193 |
+
value="groq",
|
| 194 |
+
label="Provider"
|
| 195 |
+
)
|
| 196 |
+
test_button = gr.Button("Test Agent")
|
| 197 |
+
with gr.Column():
|
| 198 |
+
test_output = gr.Textbox(label="Agent Response", lines=10, interactive=False)
|
| 199 |
+
|
| 200 |
+
test_button.click(
|
| 201 |
+
fn=test_agent,
|
| 202 |
+
inputs=[test_question, provider_choice],
|
| 203 |
+
outputs=test_output
|
| 204 |
+
)
|
| 205 |
|
| 206 |
if __name__ == "__main__":
|
| 207 |
+
print("\n" + "="*50)
|
| 208 |
+
print("π GAIA Agent Evaluator Starting")
|
| 209 |
+
print("="*50)
|
| 210 |
+
|
| 211 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 212 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 213 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 214 |
+
|
| 215 |
if space_host_startup:
|
| 216 |
print(f"β
SPACE_HOST found: {space_host_startup}")
|
| 217 |
+
print(f" Runtime URL: https://{space_host_startup}.hf.space")
|
| 218 |
else:
|
| 219 |
+
print("βΉοΈ Running locally (SPACE_HOST not found)")
|
| 220 |
+
|
| 221 |
+
if space_id_startup:
|
| 222 |
print(f"β
SPACE_ID found: {space_id_startup}")
|
| 223 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
|
|
|
| 224 |
else:
|
| 225 |
+
print("βΉοΈ SPACE_ID not found (Repo URL cannot be determined)")
|
| 226 |
+
|
| 227 |
+
print("="*50)
|
| 228 |
+
print("Launching Gradio Interface...")
|
|
|
|
| 229 |
demo.launch(debug=True, share=False)
|