Update app.py
#448
by dharshini3 - opened
app.py
CHANGED
|
@@ -1,196 +1,221 @@
|
|
| 1 |
import os
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
-
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
|
| 11 |
-
|
| 12 |
-
# -----
|
|
|
|
|
|
|
|
|
|
| 13 |
class BasicAgent:
|
| 14 |
def __init__(self):
|
| 15 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
|
| 30 |
if profile:
|
| 31 |
-
username=
|
| 32 |
-
print(f"
|
| 33 |
else:
|
| 34 |
-
|
| 35 |
-
return "Please Login to Hugging Face with the button.", None
|
| 36 |
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
submit_url = f"{api_url}/submit"
|
| 40 |
|
| 41 |
-
# 1. Instantiate Agent ( modify this part to create your agent)
|
| 42 |
try:
|
| 43 |
agent = BasicAgent()
|
| 44 |
except Exception as e:
|
| 45 |
-
|
| 46 |
-
|
| 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 |
-
#
|
| 52 |
-
|
|
|
|
|
|
|
| 53 |
try:
|
| 54 |
-
response = requests.get(questions_url, timeout=
|
| 55 |
response.raise_for_status()
|
|
|
|
| 56 |
questions_data = response.json()
|
| 57 |
-
|
| 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 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
# 3. Run your Agent
|
| 73 |
results_log = []
|
| 74 |
answers_payload = []
|
| 75 |
-
|
| 76 |
for item in questions_data:
|
|
|
|
| 77 |
task_id = item.get("task_id")
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
continue
|
|
|
|
| 82 |
try:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
response.raise_for_status()
|
| 104 |
-
|
| 105 |
-
|
|
|
|
|
|
|
| 106 |
f"Submission Successful!\n"
|
| 107 |
-
f"User: {
|
| 108 |
-
f"Overall Score: {
|
| 109 |
-
f"
|
| 110 |
-
f"Message: {
|
| 111 |
)
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 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 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
|
|
|
| 141 |
|
| 142 |
|
| 143 |
-
# ---
|
|
|
|
|
|
|
|
|
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 146 |
-
gr.Markdown(
|
| 147 |
-
"""
|
| 148 |
-
**Instructions:**
|
| 149 |
|
| 150 |
-
|
| 151 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
| 158 |
"""
|
| 159 |
)
|
| 160 |
|
| 161 |
gr.LoginButton()
|
| 162 |
|
| 163 |
-
run_button = gr.Button(
|
|
|
|
|
|
|
| 164 |
|
| 165 |
-
status_output = gr.Textbox(
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
run_button.click(
|
| 170 |
fn=run_and_submit_all,
|
| 171 |
-
outputs=[
|
|
|
|
|
|
|
|
|
|
| 172 |
)
|
| 173 |
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 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 |
-
|
| 187 |
-
|
| 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 gradio as gr
|
| 3 |
import requests
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
|
| 6 |
+
from smolagents import CodeAgent, InferenceClientModel, WebSearchTool
|
| 7 |
+
|
| 8 |
+
# --------------------------------------------------
|
| 9 |
+
# Constants
|
| 10 |
+
# --------------------------------------------------
|
| 11 |
+
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
|
| 14 |
+
|
| 15 |
+
# --------------------------------------------------
|
| 16 |
+
# Agent Definition
|
| 17 |
+
# --------------------------------------------------
|
| 18 |
+
|
| 19 |
class BasicAgent:
|
| 20 |
def __init__(self):
|
| 21 |
+
print("Initializing Agent...")
|
| 22 |
+
|
| 23 |
+
self.model = InferenceClientModel(
|
| 24 |
+
token=os.getenv("HF_TOKEN")
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
self.agent = CodeAgent(
|
| 28 |
+
tools=[WebSearchTool()],
|
| 29 |
+
model=self.model,
|
| 30 |
+
max_steps=5
|
| 31 |
+
)
|
| 32 |
+
|
| 33 |
+
print("Agent initialized successfully.")
|
| 34 |
+
|
| 35 |
def __call__(self, question: str) -> str:
|
| 36 |
+
try:
|
| 37 |
+
print(f"Question: {question[:100]}")
|
| 38 |
+
|
| 39 |
+
answer = self.agent.run(question)
|
| 40 |
+
|
| 41 |
+
print(f"Answer: {answer}")
|
| 42 |
+
|
| 43 |
+
return str(answer)
|
| 44 |
+
|
| 45 |
+
except Exception as e:
|
| 46 |
+
print(f"Agent Error: {e}")
|
| 47 |
+
return f"Error: {e}"
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# --------------------------------------------------
|
| 51 |
+
# Evaluation Runner
|
| 52 |
+
# --------------------------------------------------
|
| 53 |
+
|
| 54 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 55 |
+
|
| 56 |
+
space_id = os.getenv("SPACE_ID")
|
| 57 |
|
| 58 |
if profile:
|
| 59 |
+
username = profile.username
|
| 60 |
+
print(f"Logged in as: {username}")
|
| 61 |
else:
|
| 62 |
+
return "Please Login to Hugging Face first.", None
|
|
|
|
| 63 |
|
| 64 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 65 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
|
|
|
| 66 |
|
|
|
|
| 67 |
try:
|
| 68 |
agent = BasicAgent()
|
| 69 |
except Exception as e:
|
| 70 |
+
return f"Error creating agent: {e}", None
|
| 71 |
+
|
|
|
|
| 72 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
|
|
|
| 73 |
|
| 74 |
+
# ----------------------------------------------
|
| 75 |
+
# Fetch Questions
|
| 76 |
+
# ----------------------------------------------
|
| 77 |
+
|
| 78 |
try:
|
| 79 |
+
response = requests.get(questions_url, timeout=30)
|
| 80 |
response.raise_for_status()
|
| 81 |
+
|
| 82 |
questions_data = response.json()
|
| 83 |
+
|
|
|
|
|
|
|
| 84 |
print(f"Fetched {len(questions_data)} questions.")
|
| 85 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
+
return f"Error fetching questions: {e}", None
|
| 88 |
+
|
| 89 |
+
# ----------------------------------------------
|
| 90 |
+
# Run Agent
|
| 91 |
+
# ----------------------------------------------
|
| 92 |
|
|
|
|
| 93 |
results_log = []
|
| 94 |
answers_payload = []
|
| 95 |
+
|
| 96 |
for item in questions_data:
|
| 97 |
+
|
| 98 |
task_id = item.get("task_id")
|
| 99 |
+
question = item.get("question")
|
| 100 |
+
|
| 101 |
+
if not task_id or not question:
|
| 102 |
continue
|
| 103 |
+
|
| 104 |
try:
|
| 105 |
+
answer = agent(question)
|
| 106 |
+
|
| 107 |
+
answers_payload.append(
|
| 108 |
+
{
|
| 109 |
+
"task_id": task_id,
|
| 110 |
+
"submitted_answer": str(answer)
|
| 111 |
+
}
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
results_log.append(
|
| 115 |
+
{
|
| 116 |
+
"Task ID": task_id,
|
| 117 |
+
"Question": question,
|
| 118 |
+
"Submitted Answer": answer
|
| 119 |
+
}
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
except Exception as e:
|
|
|
|
|
|
|
| 123 |
|
| 124 |
+
results_log.append(
|
| 125 |
+
{
|
| 126 |
+
"Task ID": task_id,
|
| 127 |
+
"Question": question,
|
| 128 |
+
"Submitted Answer": f"ERROR: {e}"
|
| 129 |
+
}
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
if len(answers_payload) == 0:
|
| 133 |
+
return "No answers generated.", pd.DataFrame(results_log)
|
| 134 |
|
| 135 |
+
# ----------------------------------------------
|
| 136 |
+
# Submit Answers
|
| 137 |
+
# ----------------------------------------------
|
| 138 |
+
|
| 139 |
+
submission_data = {
|
| 140 |
+
"username": username,
|
| 141 |
+
"agent_code": agent_code,
|
| 142 |
+
"answers": answers_payload
|
| 143 |
+
}
|
| 144 |
|
|
|
|
|
|
|
| 145 |
try:
|
| 146 |
+
|
| 147 |
+
response = requests.post(
|
| 148 |
+
submit_url,
|
| 149 |
+
json=submission_data,
|
| 150 |
+
timeout=120
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
response.raise_for_status()
|
| 154 |
+
|
| 155 |
+
result = response.json()
|
| 156 |
+
|
| 157 |
+
status = (
|
| 158 |
f"Submission Successful!\n"
|
| 159 |
+
f"User: {result.get('username')}\n"
|
| 160 |
+
f"Overall Score: {result.get('score')}%\n"
|
| 161 |
+
f"Correct Answers: {result.get('correct_count')}/{result.get('total_attempted')}\n"
|
| 162 |
+
f"Message: {result.get('message')}"
|
| 163 |
)
|
| 164 |
+
|
| 165 |
+
return status, pd.DataFrame(results_log)
|
| 166 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
except Exception as e:
|
| 168 |
+
|
| 169 |
+
return (
|
| 170 |
+
f"Submission Failed: {e}",
|
| 171 |
+
pd.DataFrame(results_log)
|
| 172 |
+
)
|
| 173 |
|
| 174 |
|
| 175 |
+
# --------------------------------------------------
|
| 176 |
+
# UI
|
| 177 |
+
# --------------------------------------------------
|
| 178 |
+
|
| 179 |
with gr.Blocks() as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
|
| 181 |
+
gr.Markdown("# Hugging Face Agents Course - Final Assignment")
|
|
|
|
|
|
|
| 182 |
|
| 183 |
+
gr.Markdown(
|
| 184 |
+
"""
|
| 185 |
+
1. Login with Hugging Face
|
| 186 |
+
2. Click the evaluation button
|
| 187 |
+
3. Wait for all questions to finish
|
| 188 |
+
4. Answers will be submitted automatically
|
| 189 |
"""
|
| 190 |
)
|
| 191 |
|
| 192 |
gr.LoginButton()
|
| 193 |
|
| 194 |
+
run_button = gr.Button(
|
| 195 |
+
"Run Evaluation & Submit All Answers"
|
| 196 |
+
)
|
| 197 |
|
| 198 |
+
status_output = gr.Textbox(
|
| 199 |
+
label="Run Status / Submission Result",
|
| 200 |
+
lines=8
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
results_table = gr.DataFrame(
|
| 204 |
+
label="Questions and Agent Answers",
|
| 205 |
+
wrap=True
|
| 206 |
+
)
|
| 207 |
|
| 208 |
run_button.click(
|
| 209 |
fn=run_and_submit_all,
|
| 210 |
+
outputs=[
|
| 211 |
+
status_output,
|
| 212 |
+
results_table
|
| 213 |
+
]
|
| 214 |
)
|
| 215 |
|
| 216 |
+
# --------------------------------------------------
|
| 217 |
+
# Launch
|
| 218 |
+
# --------------------------------------------------
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 219 |
|
| 220 |
+
if __name__ == "__main__":
|
| 221 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|