Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,196 +1,153 @@
|
|
| 1 |
import os
|
| 2 |
-
import
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
# --- Constants ---
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 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 |
-
|
| 25 |
-
|
| 26 |
"""
|
| 27 |
-
#
|
| 28 |
-
|
|
|
|
|
|
|
| 29 |
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
else:
|
| 34 |
-
print("User not logged in.")
|
| 35 |
-
return "Please Login to Hugging Face with the button.", None
|
| 36 |
-
|
| 37 |
-
api_url = DEFAULT_API_URL
|
| 38 |
-
questions_url = f"{api_url}/questions"
|
| 39 |
-
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
# 1
|
|
|
|
| 42 |
try:
|
| 43 |
-
agent =
|
| 44 |
except Exception as e:
|
| 45 |
-
|
| 46 |
-
return
|
| 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
|
| 52 |
-
|
|
|
|
| 53 |
try:
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 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
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
answers_payload = []
|
| 75 |
-
|
| 76 |
-
for item in questions_data:
|
| 77 |
task_id = item.get("task_id")
|
| 78 |
-
|
| 79 |
-
if not task_id or
|
| 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 |
-
|
| 91 |
-
|
| 92 |
-
|
|
|
|
|
|
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 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=60)
|
| 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"
|
| 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 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
)
|
| 160 |
|
| 161 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
|
| 163 |
-
|
|
|
|
| 164 |
|
| 165 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
|
| 169 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
fn=run_and_submit_all,
|
| 171 |
-
|
|
|
|
|
|
|
| 172 |
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
|
| 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") # Get SPACE_ID at startup
|
| 179 |
-
|
| 180 |
-
if space_host_startup:
|
| 181 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
-
else:
|
| 184 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
-
|
| 186 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 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 environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
-
|
| 193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
-
|
| 195 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
-
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
import os
|
| 2 |
+
import json
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
+
import gradio as gr
|
| 6 |
+
|
| 7 |
+
from agents.agent import GaiaAgent
|
| 8 |
+
from agents.router import route_task, profiles
|
| 9 |
|
| 10 |
+
# ————— Constants —————
|
|
|
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
+
def run_and_submit_all(
|
| 14 |
+
profile: gr.OAuthProfile | None,
|
| 15 |
+
temperature: float,
|
| 16 |
+
num_chains: int
|
| 17 |
+
):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
"""
|
| 19 |
+
Generator function for streaming UI updates.
|
| 20 |
+
Yields (status_message, results_dataframe, submission_file_path)
|
| 21 |
"""
|
| 22 |
+
# 0) Check login
|
| 23 |
+
if profile is None:
|
| 24 |
+
yield "❌ Please log in to Hugging Face to submit.", pd.DataFrame(), None
|
| 25 |
+
return
|
| 26 |
|
| 27 |
+
username = profile.username.strip()
|
| 28 |
+
space_id = os.getenv("SPACE_ID", "")
|
| 29 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
+
# 1) Instantiate your real GaiaAgent
|
| 32 |
+
yield "🔄 Initializing GaiaAgent...", pd.DataFrame(), None
|
| 33 |
try:
|
| 34 |
+
agent = GaiaAgent()
|
| 35 |
except Exception as e:
|
| 36 |
+
yield f"❌ Error initializing agent: {e}", pd.DataFrame(), None
|
| 37 |
+
return
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
# 2) Fetch GAIA questions
|
| 40 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 41 |
+
yield f"🔄 Fetching questions from {questions_url}...", pd.DataFrame(), None
|
| 42 |
try:
|
| 43 |
+
resp = requests.get(questions_url, timeout=15)
|
| 44 |
+
resp.raise_for_status()
|
| 45 |
+
questions = resp.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 46 |
except Exception as e:
|
| 47 |
+
yield f"❌ Error fetching questions: {e}", pd.DataFrame(), None
|
| 48 |
+
return
|
| 49 |
|
| 50 |
+
total = len(questions)
|
| 51 |
+
if total == 0:
|
| 52 |
+
yield "❌ No questions received from server.", pd.DataFrame(), None
|
| 53 |
+
return
|
| 54 |
+
yield f"✅ Loaded {total} questions. Starting evaluation…", pd.DataFrame(), None
|
| 55 |
+
|
| 56 |
+
# 3) Run agent on each question, streaming progress
|
| 57 |
+
results = []
|
| 58 |
answers_payload = []
|
| 59 |
+
for idx, item in enumerate(questions, start=1):
|
|
|
|
| 60 |
task_id = item.get("task_id")
|
| 61 |
+
prompt = item.get("question", "")
|
| 62 |
+
if not task_id or not prompt:
|
|
|
|
| 63 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
|
| 65 |
+
kind = route_task(prompt)
|
| 66 |
+
# Merge router profile + UI overrides
|
| 67 |
+
profile_params = profiles.get(kind, {}).copy()
|
| 68 |
+
profile_params["temperature"] = temperature
|
| 69 |
+
profile_params["num_samples"] = num_chains
|
| 70 |
|
| 71 |
+
yield (
|
| 72 |
+
f"🧠 [{idx}/{total}] Task {task_id} ({kind})…",
|
| 73 |
+
pd.DataFrame(results),
|
| 74 |
+
None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
try:
|
| 78 |
+
answer = agent.run(prompt, profile=profile_params)
|
| 79 |
+
except Exception as e:
|
| 80 |
+
answer = f"AGENT ERROR: {e}"
|
| 81 |
+
|
| 82 |
+
results.append({
|
| 83 |
+
"Task ID": task_id,
|
| 84 |
+
"Question": prompt,
|
| 85 |
+
"Answer": answer
|
| 86 |
+
})
|
| 87 |
+
answers_payload.append({
|
| 88 |
+
"task_id": task_id,
|
| 89 |
+
"submitted_answer": answer
|
| 90 |
+
})
|
| 91 |
+
|
| 92 |
+
# 4) Write out submission.json
|
| 93 |
+
submission = {
|
| 94 |
+
"username": username,
|
| 95 |
+
"agent_code": agent_code,
|
| 96 |
+
"answers": answers_payload
|
| 97 |
+
}
|
| 98 |
+
submission_path = "submission.json"
|
| 99 |
+
with open(submission_path, "w") as f:
|
| 100 |
+
json.dump(submission, f, indent=2)
|
| 101 |
+
|
| 102 |
+
yield (
|
| 103 |
+
f"💾 Built submission.json ({len(answers_payload)} answers). Now submitting…",
|
| 104 |
+
pd.DataFrame(results),
|
| 105 |
+
None
|
| 106 |
)
|
| 107 |
|
| 108 |
+
# 5) POST to scoring endpoint
|
| 109 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 110 |
+
try:
|
| 111 |
+
resp = requests.post(submit_url, json=submission, timeout=60)
|
| 112 |
+
resp.raise_for_status()
|
| 113 |
+
data = resp.json()
|
| 114 |
+
final_msg = (
|
| 115 |
+
f"✅ Submission Successful!\n"
|
| 116 |
+
f"Score: {data.get('score')}% "
|
| 117 |
+
f"({data.get('correct_count')}/{data.get('total_attempted')})\n"
|
| 118 |
+
f"{data.get('message','')}"
|
| 119 |
+
)
|
| 120 |
+
except Exception as e:
|
| 121 |
+
final_msg = f"❌ Submission Failed: {e}"
|
| 122 |
|
| 123 |
+
# Final yield includes the download link for submission.json
|
| 124 |
+
yield final_msg, pd.DataFrame(results), submission_path
|
| 125 |
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
# ————— Gradio UI —————
|
| 128 |
+
with gr.Blocks() as demo:
|
| 129 |
+
gr.Markdown("# GAIA Benchmark Agent Runner\n"
|
| 130 |
+
"Customize hyperparameters, run your agent end-to-end, and submit for scoring.")
|
| 131 |
+
|
| 132 |
+
with gr.Row():
|
| 133 |
+
login_btn = gr.LoginButton()
|
| 134 |
+
temp_slider = gr.Slider(0.0, 1.0, value=0.2, step=0.05,
|
| 135 |
+
label="Temperature")
|
| 136 |
+
chains_slider = gr.Slider(1, 10, value=5, step=1,
|
| 137 |
+
label="Self-Consistency Chains")
|
| 138 |
+
|
| 139 |
+
run_btn = gr.Button("▶️ Run & Submit All Answers")
|
| 140 |
+
status_box = gr.Textbox(label="Status / Final Result", lines=4)
|
| 141 |
+
results_table = gr.DataFrame(headers=["Task ID", "Question", "Answer"],
|
| 142 |
+
label="Detailed Results")
|
| 143 |
+
download_btn = gr.File(label="Download submission.json")
|
| 144 |
+
|
| 145 |
+
run_btn.click(
|
| 146 |
fn=run_and_submit_all,
|
| 147 |
+
inputs=[login_btn, temp_slider, chains_slider],
|
| 148 |
+
outputs=[status_box, results_table, download_btn],
|
| 149 |
+
streaming=True
|
| 150 |
)
|
| 151 |
|
| 152 |
if __name__ == "__main__":
|
| 153 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|