khojoii's picture
use username instead of oauth
f9ec52b
Raw
History Blame Contribute Delete
6.16 kB
import os
import gradio as gr
import requests
import pandas as pd
from agent import create_agent, _clean_answer, build_question_prompt
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
def run_and_submit_all(username: str):
space_id = os.getenv("SPACE_ID")
if not username or not username.strip():
return "Please enter your Hugging Face username.", None
username = username.strip()
print(f"User: {username}")
api_url = DEFAULT_API_URL
questions_url = f"{api_url}/questions"
submit_url = f"{api_url}/submit"
try:
agent = create_agent()
except Exception as e:
print(f"Error instantiating agent: {e}")
return f"Error initializing agent: {e}", None
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
print(f"Agent code URL: {agent_code}")
print(f"Fetching questions from: {questions_url}")
try:
response = requests.get(questions_url, timeout=15)
response.raise_for_status()
questions_data = response.json()
if not questions_data:
print("Fetched questions list is empty.")
return "Fetched questions list is empty or invalid format.", None
print(f"Fetched {len(questions_data)} questions.")
except requests.exceptions.RequestException as e:
return f"Error fetching questions: {e}", None
except requests.exceptions.JSONDecodeError as e:
return f"Error decoding server response for questions: {e}", None
except Exception as e:
return f"An unexpected error occurred fetching questions: {e}", None
results_log = []
answers_payload = []
print(f"Running agent on {len(questions_data)} questions...")
for item in questions_data:
task_id = item.get("task_id")
question_text = item.get("question")
if not task_id or question_text is None:
print(f"Skipping item with missing task_id or question: {item}")
continue
prompt = build_question_prompt(item)
try:
raw_output = agent.run(prompt)
answer = _clean_answer(raw_output)
print(f"Task {task_id}: raw={raw_output!r} cleaned={answer!r}")
except Exception as e:
print(f"Error running agent on task {task_id}: {e}")
answer = f"AGENT ERROR: {e}"
answers_payload.append({"task_id": task_id, "submitted_answer": answer})
results_log.append({
"Task ID": task_id,
"Question": question_text,
"Submitted Answer": answer,
})
if not answers_payload:
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
submission_data = {
"username": username,
"agent_code": agent_code,
"answers": answers_payload,
}
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
print(status_update)
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
try:
response = requests.post(submit_url, json=submission_data, timeout=60)
response.raise_for_status()
result_data = response.json()
final_status = (
f"Submission Successful!\n"
f"User: {result_data.get('username')}\n"
f"Overall Score: {result_data.get('score', 'N/A')}% "
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
f"Message: {result_data.get('message', 'No message received.')}"
)
print("Submission successful.")
results_df = pd.DataFrame(results_log)
return final_status, results_df
except requests.exceptions.HTTPError as e:
error_detail = f"Server responded with status {e.response.status_code}."
try:
error_json = e.response.json()
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
except requests.exceptions.JSONDecodeError:
error_detail += f" Response: {e.response.text[:500]}"
return f"Submission Failed: {error_detail}", pd.DataFrame(results_log)
except requests.exceptions.Timeout:
return "Submission Failed: The request timed out.", pd.DataFrame(results_log)
except requests.exceptions.RequestException as e:
return f"Submission Failed: Network error - {e}", pd.DataFrame(results_log)
except Exception as e:
return f"An unexpected error occurred during submission: {e}", pd.DataFrame(results_log)
with gr.Blocks() as demo:
gr.Markdown("# GAIA Benchmark Agent Runner")
gr.Markdown(
"""
**Instructions:**
1. Enter your Hugging Face username below.
2. Click **Run Evaluation & Submit All Answers** to run the agent on all questions and submit.
3. Results and a per-question breakdown will appear below.
---
**Note:** Running all questions takes several minutes. Each question triggers multi-step reasoning.
"""
)
username_input = gr.Textbox(label="Hugging Face Username", placeholder="e.g. john_doe")
run_button = gr.Button("Run Evaluation & Submit All Answers")
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
run_button.click(
fn=run_and_submit_all,
inputs=[username_input],
outputs=[status_output, results_table],
)
if __name__ == "__main__":
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
space_host = os.getenv("SPACE_HOST")
space_id = os.getenv("SPACE_ID")
if space_host:
print(f"SPACE_HOST: {space_host}")
print(f" Runtime URL: https://{space_host}.hf.space")
else:
print("SPACE_HOST not found (running locally?).")
if space_id:
print(f"SPACE_ID: {space_id}")
print(f" Repo URL: https://huggingface.co/spaces/{space_id}/tree/main")
else:
print("SPACE_ID not found (running locally?).")
print("-" * 60 + "\n")
demo.launch(debug=True, share=False)