Spaces:
Runtime error
Runtime error
Update evaluation_app.py
Browse files- evaluation_app.py +150 -128
evaluation_app.py
CHANGED
|
@@ -1,6 +1,7 @@
|
|
| 1 |
-
"""
|
| 2 |
|
| 3 |
import os
|
|
|
|
| 4 |
import gradio as gr
|
| 5 |
import requests
|
| 6 |
import pandas as pd
|
|
@@ -8,143 +9,113 @@ import time
|
|
| 8 |
from langchain_core.messages import HumanMessage
|
| 9 |
from agent import build_graph
|
| 10 |
|
|
|
|
| 11 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 12 |
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
| 16 |
def __init__(self):
|
| 17 |
-
print("
|
| 18 |
self.graph = build_graph()
|
| 19 |
-
|
| 20 |
-
def __call__(self, question: str) -> str:
|
| 21 |
-
print(f"Agent received question: {question[:50]}...")
|
| 22 |
-
|
| 23 |
-
# Create a focused prompt
|
| 24 |
-
focused_prompt = f"""Answer this question directly and concisely.
|
| 25 |
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
Answer:"""
|
| 35 |
-
|
| 36 |
-
try:
|
| 37 |
-
# Wrap the question in a HumanMessage
|
| 38 |
-
messages = [HumanMessage(content=focused_prompt)]
|
| 39 |
-
result = self.graph.invoke({"messages": messages}, {"recursion_limit": 5})
|
| 40 |
-
|
| 41 |
-
answer = result['messages'][-1].content
|
| 42 |
-
print(f"Raw agent response: {answer[:100]}...")
|
| 43 |
-
|
| 44 |
-
# Extract final answer properly
|
| 45 |
-
if "FINAL ANSWER:" in answer:
|
| 46 |
-
final_part = answer.split("FINAL ANSWER:")[-1].strip()
|
| 47 |
-
# Clean up the final answer
|
| 48 |
-
final_part = final_part.replace("</function>", "").replace("<function>", "").strip()
|
| 49 |
-
if final_part:
|
| 50 |
-
return final_part
|
| 51 |
-
|
| 52 |
-
# If no FINAL ANSWER found, extract the last meaningful line
|
| 53 |
-
lines = answer.strip().split('\n')
|
| 54 |
-
for line in reversed(lines):
|
| 55 |
-
line = line.strip()
|
| 56 |
-
if line and not line.startswith('<') and not line.startswith('Error'):
|
| 57 |
-
return line
|
| 58 |
-
|
| 59 |
-
return answer.strip()[:100] # Fallback
|
| 60 |
-
|
| 61 |
-
except Exception as e:
|
| 62 |
-
print(f"Error in agent call: {e}")
|
| 63 |
-
return f"Error: {str(e)[:50]}"
|
| 64 |
-
|
| 65 |
-
def run_evaluation(username: str):
|
| 66 |
-
"""Runs the GAIA evaluation with proper error handling."""
|
| 67 |
-
|
| 68 |
-
if not username or username.strip() == "":
|
| 69 |
-
return "Please enter your Hugging Face username.", None
|
| 70 |
-
|
| 71 |
-
# Get space info automatically
|
| 72 |
-
space_id = os.getenv("SPACE_ID")
|
| 73 |
-
if not space_id:
|
| 74 |
-
return "Error: SPACE_ID not found.", None
|
| 75 |
-
|
| 76 |
-
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 77 |
api_url = DEFAULT_API_URL
|
| 78 |
questions_url = f"{api_url}/questions"
|
| 79 |
submit_url = f"{api_url}/submit"
|
| 80 |
-
|
| 81 |
-
#
|
| 82 |
try:
|
| 83 |
-
agent =
|
| 84 |
except Exception as e:
|
|
|
|
| 85 |
return f"Error initializing agent: {e}", None
|
| 86 |
-
|
| 87 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
try:
|
| 89 |
response = requests.get(questions_url, timeout=15)
|
| 90 |
response.raise_for_status()
|
| 91 |
questions_data = response.json()
|
| 92 |
-
|
| 93 |
if not questions_data:
|
| 94 |
-
|
| 95 |
-
|
| 96 |
print(f"Fetched {len(questions_data)} questions.")
|
| 97 |
-
except
|
|
|
|
| 98 |
return f"Error fetching questions: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
-
# Run
|
| 101 |
results_log = []
|
| 102 |
answers_payload = []
|
| 103 |
-
|
| 104 |
-
|
|
|
|
| 105 |
task_id = item.get("task_id")
|
| 106 |
question_text = item.get("question")
|
| 107 |
-
|
| 108 |
if not task_id or question_text is None:
|
|
|
|
| 109 |
continue
|
| 110 |
-
|
| 111 |
-
print(f"Processing question {i+1}/{len(questions_data)}: {task_id}")
|
| 112 |
-
|
| 113 |
-
# Shorter delay to speed up
|
| 114 |
-
time.sleep(5)
|
| 115 |
-
|
| 116 |
try:
|
| 117 |
submitted_answer = agent(question_text)
|
| 118 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 119 |
-
results_log.append({
|
| 120 |
-
"Task ID": task_id,
|
| 121 |
-
"Question": question_text[:80] + "...",
|
| 122 |
-
"Submitted Answer": submitted_answer
|
| 123 |
-
})
|
| 124 |
-
print(f"Answer: {submitted_answer}")
|
| 125 |
except Exception as e:
|
| 126 |
-
|
| 127 |
-
results_log.append({
|
| 128 |
-
"Task ID": task_id,
|
| 129 |
-
"Question": question_text[:80] + "...",
|
| 130 |
-
"Submitted Answer": error_msg
|
| 131 |
-
})
|
| 132 |
|
| 133 |
if not answers_payload:
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
|
|
|
| 143 |
try:
|
| 144 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 145 |
response.raise_for_status()
|
| 146 |
result_data = response.json()
|
| 147 |
-
|
| 148 |
final_status = (
|
| 149 |
f"Submission Successful!\n"
|
| 150 |
f"User: {result_data.get('username')}\n"
|
|
@@ -152,42 +123,93 @@ def run_evaluation(username: str):
|
|
| 152 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 153 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 154 |
)
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
except Exception as e:
|
| 159 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
-
# Gradio Interface
|
| 162 |
with gr.Blocks() as demo:
|
| 163 |
-
gr.Markdown("#
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
)
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
|
|
|
|
|
|
| 183 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
|
|
|
| 184 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 185 |
-
|
| 186 |
run_button.click(
|
| 187 |
-
fn=
|
| 188 |
-
inputs=[username_input],
|
| 189 |
outputs=[status_output, results_table]
|
| 190 |
)
|
| 191 |
|
| 192 |
if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 193 |
demo.launch(debug=True, share=False)
|
|
|
|
| 1 |
+
""" Basic Agent Evaluation Runner"""
|
| 2 |
|
| 3 |
import os
|
| 4 |
+
import inspect
|
| 5 |
import gradio as gr
|
| 6 |
import requests
|
| 7 |
import pandas as pd
|
|
|
|
| 9 |
from langchain_core.messages import HumanMessage
|
| 10 |
from agent import build_graph
|
| 11 |
|
| 12 |
+
# --- Constants ---
|
| 13 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 14 |
|
| 15 |
+
# --- Basic Agent Definition ---
|
| 16 |
+
# ----- THIS IS WHERE YOU CAN BUILD WHAT YOU WANT ------
|
| 17 |
+
|
| 18 |
+
class BasicAgent:
|
| 19 |
+
"""A langgraph agent."""
|
| 20 |
+
|
| 21 |
def __init__(self):
|
| 22 |
+
print("BasicAgent initialized.")
|
| 23 |
self.graph = build_graph()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
def __call__(self, question: str) -> str:
|
| 26 |
+
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 27 |
+
# Wrap the question in a HumanMessage from langchain_core
|
| 28 |
+
messages = [HumanMessage(content=question)]
|
| 29 |
+
messages = self.graph.invoke({"messages": messages})
|
| 30 |
+
answer = messages['messages'][-1].content
|
| 31 |
+
return answer[14:]
|
| 32 |
|
| 33 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 34 |
+
"""
|
| 35 |
+
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 36 |
+
and displays the results.
|
| 37 |
+
"""
|
| 38 |
+
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 39 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 40 |
+
|
| 41 |
+
if profile:
|
| 42 |
+
username = f"{profile.username}"
|
| 43 |
+
print(f"User logged in: {username}")
|
| 44 |
+
else:
|
| 45 |
+
print("User not logged in.")
|
| 46 |
+
return "Please Login to Hugging Face with the button.", None
|
| 47 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
api_url = DEFAULT_API_URL
|
| 49 |
questions_url = f"{api_url}/questions"
|
| 50 |
submit_url = f"{api_url}/submit"
|
| 51 |
+
|
| 52 |
+
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 53 |
try:
|
| 54 |
+
agent = BasicAgent()
|
| 55 |
except Exception as e:
|
| 56 |
+
print(f"Error instantiating agent: {e}")
|
| 57 |
return f"Error initializing agent: {e}", None
|
| 58 |
+
|
| 59 |
+
# Link to code repository on Hugging Face Spaces
|
| 60 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 61 |
+
print(agent_code)
|
| 62 |
+
|
| 63 |
+
# 2. Fetch Questions
|
| 64 |
+
print(f"Fetching questions from: {questions_url}")
|
| 65 |
try:
|
| 66 |
response = requests.get(questions_url, timeout=15)
|
| 67 |
response.raise_for_status()
|
| 68 |
questions_data = response.json()
|
|
|
|
| 69 |
if not questions_data:
|
| 70 |
+
print("Fetched questions list is empty.")
|
| 71 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 72 |
print(f"Fetched {len(questions_data)} questions.")
|
| 73 |
+
except requests.exceptions.RequestException as e:
|
| 74 |
+
print(f"Error fetching questions: {e}")
|
| 75 |
return f"Error fetching questions: {e}", None
|
| 76 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 77 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 78 |
+
print(f"Response text: {response.text[:500]}")
|
| 79 |
+
return f"Error decoding server response for questions: {e}", None
|
| 80 |
+
except Exception as e:
|
| 81 |
+
print(f"An unexpected error occurred fetching questions: {e}")
|
| 82 |
+
return f"An unexpected error occurred fetching questions: {e}", None
|
| 83 |
|
| 84 |
+
# 3. Run your Agent
|
| 85 |
results_log = []
|
| 86 |
answers_payload = []
|
| 87 |
+
|
| 88 |
+
print(f"Running agent on {len(questions_data)} questions...")
|
| 89 |
+
for item in questions_data:
|
| 90 |
task_id = item.get("task_id")
|
| 91 |
question_text = item.get("question")
|
|
|
|
| 92 |
if not task_id or question_text is None:
|
| 93 |
+
print(f"Skipping item with missing task_id or question: {item}")
|
| 94 |
continue
|
| 95 |
+
time.sleep(30) # Delay to avoid API rate limit or syncing issues
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
try:
|
| 97 |
submitted_answer = agent(question_text)
|
| 98 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
| 99 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
except Exception as e:
|
| 101 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 102 |
+
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
if not answers_payload:
|
| 105 |
+
print("Agent did not produce any answers to submit.")
|
| 106 |
+
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 107 |
+
|
| 108 |
+
# 4. Prepare Submission
|
| 109 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
| 110 |
+
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 111 |
+
print(status_update)
|
| 112 |
+
|
| 113 |
+
# 5. Submit
|
| 114 |
+
print(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
| 115 |
try:
|
| 116 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 117 |
response.raise_for_status()
|
| 118 |
result_data = response.json()
|
|
|
|
| 119 |
final_status = (
|
| 120 |
f"Submission Successful!\n"
|
| 121 |
f"User: {result_data.get('username')}\n"
|
|
|
|
| 123 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
| 124 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 125 |
)
|
| 126 |
+
print("Submission successful.")
|
| 127 |
+
results_df = pd.DataFrame(results_log)
|
| 128 |
+
return final_status, results_df
|
| 129 |
+
except requests.exceptions.HTTPError as e:
|
| 130 |
+
error_detail = f"Server responded with status {e.response.status_code}."
|
| 131 |
+
try:
|
| 132 |
+
error_json = e.response.json()
|
| 133 |
+
error_detail += f" Detail: {error_json.get('detail', e.response.text)}"
|
| 134 |
+
except requests.exceptions.JSONDecodeError:
|
| 135 |
+
error_detail += f" Response: {e.response.text[:500]}"
|
| 136 |
+
status_message = f"Submission Failed: {error_detail}"
|
| 137 |
+
print(status_message)
|
| 138 |
+
results_df = pd.DataFrame(results_log)
|
| 139 |
+
return status_message, results_df
|
| 140 |
+
except requests.exceptions.Timeout:
|
| 141 |
+
status_message = "Submission Failed: The request timed out."
|
| 142 |
+
print(status_message)
|
| 143 |
+
results_df = pd.DataFrame(results_log)
|
| 144 |
+
return status_message, results_df
|
| 145 |
+
except requests.exceptions.RequestException as e:
|
| 146 |
+
status_message = f"Submission Failed: Network error - {e}"
|
| 147 |
+
print(status_message)
|
| 148 |
+
results_df = pd.DataFrame(results_log)
|
| 149 |
+
return status_message, results_df
|
| 150 |
except Exception as e:
|
| 151 |
+
status_message = f"An unexpected error occurred during submission: {e}"
|
| 152 |
+
print(status_message)
|
| 153 |
+
results_df = pd.DataFrame(results_log)
|
| 154 |
+
return status_message, results_df
|
| 155 |
+
|
| 156 |
+
# --- Build Gradio Interface using Blocks ---
|
| 157 |
|
|
|
|
| 158 |
with gr.Blocks() as demo:
|
| 159 |
+
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 160 |
+
|
| 161 |
+
gr.Markdown(
|
| 162 |
+
"""
|
| 163 |
+
**Instructions:**
|
| 164 |
+
|
| 165 |
+
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 166 |
+
|
| 167 |
+
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 168 |
+
|
| 169 |
+
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 170 |
+
|
| 171 |
+
---
|
| 172 |
+
|
| 173 |
+
**Disclaimers:**
|
| 174 |
+
|
| 175 |
+
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).
|
| 176 |
+
|
| 177 |
+
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 separate action or even to answer the questions in async.
|
| 178 |
+
|
| 179 |
+
"""
|
| 180 |
)
|
| 181 |
+
|
| 182 |
+
gr.LoginButton()
|
| 183 |
+
|
| 184 |
+
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 185 |
+
|
| 186 |
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 187 |
+
|
| 188 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 189 |
+
|
| 190 |
run_button.click(
|
| 191 |
+
fn=run_and_submit_all,
|
|
|
|
| 192 |
outputs=[status_output, results_table]
|
| 193 |
)
|
| 194 |
|
| 195 |
if __name__ == "__main__":
|
| 196 |
+
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 197 |
+
space_host_startup = os.getenv("SPACE_HOST")
|
| 198 |
+
space_id_startup = os.getenv("SPACE_ID")
|
| 199 |
+
|
| 200 |
+
if space_host_startup:
|
| 201 |
+
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 202 |
+
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 203 |
+
else:
|
| 204 |
+
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 205 |
+
|
| 206 |
+
if space_id_startup:
|
| 207 |
+
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 208 |
+
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 209 |
+
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 210 |
+
else:
|
| 211 |
+
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 212 |
+
|
| 213 |
+
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 214 |
+
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 215 |
demo.launch(debug=True, share=False)
|