Update app.py
Browse files
app.py
CHANGED
|
@@ -4,31 +4,112 @@ 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 |
class BasicAgent:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
def __init__(self):
|
| 15 |
-
print("BasicAgent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"Agent received question (first
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 25 |
and displays the results.
|
| 26 |
"""
|
| 27 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 28 |
-
space_id = os.getenv("SPACE_ID")
|
| 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,15 +119,17 @@ 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}")
|
|
@@ -55,16 +138,16 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 55 |
response.raise_for_status()
|
| 56 |
questions_data = response.json()
|
| 57 |
if not questions_data:
|
| 58 |
-
|
| 59 |
-
|
| 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 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
except Exception as e:
|
| 69 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 70 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
@@ -81,19 +164,39 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 81 |
continue
|
| 82 |
try:
|
| 83 |
submitted_answer = agent(question_text)
|
| 84 |
-
answers_payload.append(
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
if not answers_payload:
|
| 91 |
print("Agent did not produce any answers to submit.")
|
| 92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
|
| 94 |
-
# 4. Prepare Submission
|
| 95 |
-
submission_data = {
|
| 96 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
print(status_update)
|
| 98 |
|
| 99 |
# 5. Submit
|
|
@@ -142,19 +245,20 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
| 142 |
|
| 143 |
# --- Build Gradio Interface using Blocks ---
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 146 |
gr.Markdown(
|
| 147 |
"""
|
| 148 |
**Instructions:**
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
---
|
| 155 |
-
**
|
| 156 |
-
|
| 157 |
-
|
|
|
|
|
|
|
| 158 |
"""
|
| 159 |
)
|
| 160 |
|
|
@@ -162,20 +266,24 @@ with gr.Blocks() as demo:
|
|
| 162 |
|
| 163 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
|
| 165 |
-
status_output = gr.Textbox(
|
| 166 |
-
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
run_button.click(
|
| 170 |
fn=run_and_submit_all,
|
| 171 |
-
outputs=[status_output, results_table]
|
| 172 |
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
print("\n" + "-"*30 + " App Starting " + "-"*30)
|
| 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}")
|
|
@@ -183,14 +291,16 @@ if __name__ == "__main__":
|
|
| 183 |
else:
|
| 184 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 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(
|
|
|
|
|
|
|
| 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)
|
|
|
|
| 4 |
import inspect
|
| 5 |
import pandas as pd
|
| 6 |
|
| 7 |
+
# 🔹 NOVO: imports do smolagents
|
| 8 |
+
from smolagents import CodeAgent, InferenceClientModel
|
| 9 |
+
|
| 10 |
# --- Constants ---
|
| 11 |
+
# (mantido como no template)
|
| 12 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 13 |
|
| 14 |
+
|
| 15 |
+
# =========================================================
|
| 16 |
+
# Helper: limpeza de resposta para EXACT MATCH
|
| 17 |
+
# =========================================================
|
| 18 |
+
def clean_answer(text: str) -> str:
|
| 19 |
+
"""
|
| 20 |
+
Limpa a saída do modelo para ficar mais adequada ao EXACT MATCH.
|
| 21 |
+
Remove prefixos como 'Answer:', 'Final answer:' etc.,
|
| 22 |
+
aspas externas e ponto final solto.
|
| 23 |
+
"""
|
| 24 |
+
if text is None:
|
| 25 |
+
return ""
|
| 26 |
+
|
| 27 |
+
ans = str(text).strip()
|
| 28 |
+
|
| 29 |
+
# remove prefixos comuns
|
| 30 |
+
prefixes = [
|
| 31 |
+
"answer:", "resposta:", "final answer:", "final:", "ans:", "a:",
|
| 32 |
+
"the answer is", "the final answer is",
|
| 33 |
+
]
|
| 34 |
+
lower = ans.lower()
|
| 35 |
+
for p in prefixes:
|
| 36 |
+
if lower.startswith(p):
|
| 37 |
+
ans = ans[len(p):].strip()
|
| 38 |
+
break
|
| 39 |
+
|
| 40 |
+
# remove ponto final se não parecer número decimal
|
| 41 |
+
if ans.endswith(".") and not ans.replace(".", "", 1).isdigit():
|
| 42 |
+
ans = ans[:-1].strip()
|
| 43 |
+
|
| 44 |
+
# remove aspas externas
|
| 45 |
+
if len(ans) > 1 and ans[0] == ans[-1] and ans[0] in ["'", '"']:
|
| 46 |
+
ans = ans[1:-1].strip()
|
| 47 |
+
|
| 48 |
+
return ans
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# =========================================================
|
| 52 |
+
# Basic Agent Definition – AGORA usando smolagents
|
| 53 |
+
# =========================================================
|
| 54 |
+
|
| 55 |
+
SYSTEM_PROMPT = (
|
| 56 |
+
"You are an exam-taking assistant.\n"
|
| 57 |
+
"For each question, reply with ONLY the final answer, with no explanation, "
|
| 58 |
+
"no reasoning, no extra words, no quotes, and no labels like 'Final answer'.\n"
|
| 59 |
+
"If the answer is a number, output just the number. "
|
| 60 |
+
"If it is a word or short phrase, output just that.\n"
|
| 61 |
+
"Your output will be compared to the ground truth using EXACT MATCH."
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
class BasicAgent:
|
| 66 |
+
"""
|
| 67 |
+
Agente simples baseado em smolagents:
|
| 68 |
+
- Usa InferenceClientModel (Inference API da Hugging Face)
|
| 69 |
+
- Não utiliza tools adicionais
|
| 70 |
+
- Retorna uma string já limpa para EXACT MATCH
|
| 71 |
+
"""
|
| 72 |
+
|
| 73 |
def __init__(self):
|
| 74 |
+
print("Initializing smolagents BasicAgent...")
|
| 75 |
+
|
| 76 |
+
# Modelo remoto via Inference API (utiliza HF_TOKEN configurado no Space)
|
| 77 |
+
self.model = InferenceClientModel()
|
| 78 |
+
|
| 79 |
+
# CodeAgent sem ferramentas (agente simples)
|
| 80 |
+
self.agent = CodeAgent(
|
| 81 |
+
model=self.model,
|
| 82 |
+
tools=[], # agente simples: sem tools
|
| 83 |
+
max_steps=1, # sem tools, 1 passo é suficiente
|
| 84 |
+
system_prompt=SYSTEM_PROMPT,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
def __call__(self, question: str) -> str:
|
| 88 |
+
print(f"Agent received question (first 80 chars): {question[:80]}...")
|
| 89 |
+
try:
|
| 90 |
+
raw_answer = self.agent.run(question)
|
| 91 |
+
fixed_answer = clean_answer(raw_answer)
|
| 92 |
+
print(f"Agent returning cleaned answer: {fixed_answer}")
|
| 93 |
+
return fixed_answer
|
| 94 |
+
except Exception as e:
|
| 95 |
+
print(f"Error inside BasicAgent.__call__: {e}")
|
| 96 |
+
# Em caso de erro, devolve string vazia (melhor do que quebrar tudo)
|
| 97 |
+
return ""
|
| 98 |
+
|
| 99 |
|
| 100 |
+
# =========================================================
|
| 101 |
+
# Runner + submit (mantido do template, só usando BasicAgent novo)
|
| 102 |
+
# =========================================================
|
| 103 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 104 |
"""
|
| 105 |
Fetches all questions, runs the BasicAgent on them, submits all answers,
|
| 106 |
and displays the results.
|
| 107 |
"""
|
| 108 |
# --- Determine HF Space Runtime URL and Repo URL ---
|
| 109 |
+
space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
|
| 110 |
|
| 111 |
if profile:
|
| 112 |
+
username = f"{profile.username}"
|
| 113 |
print(f"User logged in: {username}")
|
| 114 |
else:
|
| 115 |
print("User not logged in.")
|
|
|
|
| 119 |
questions_url = f"{api_url}/questions"
|
| 120 |
submit_url = f"{api_url}/submit"
|
| 121 |
|
| 122 |
+
# 1. Instantiate Agent (agora nosso agente smolagents)
|
| 123 |
try:
|
| 124 |
agent = BasicAgent()
|
| 125 |
except Exception as e:
|
| 126 |
print(f"Error instantiating agent: {e}")
|
| 127 |
return f"Error initializing agent: {e}", None
|
| 128 |
+
|
| 129 |
+
# In the case of an app running as a hugging Face space, this link points toward your codebase
|
| 130 |
+
# (useful for others so please keep it public)
|
| 131 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 132 |
+
print(f"Agent code URL: {agent_code}")
|
| 133 |
|
| 134 |
# 2. Fetch Questions
|
| 135 |
print(f"Fetching questions from: {questions_url}")
|
|
|
|
| 138 |
response.raise_for_status()
|
| 139 |
questions_data = response.json()
|
| 140 |
if not questions_data:
|
| 141 |
+
print("Fetched questions list is empty.")
|
| 142 |
+
return "Fetched questions list is empty or invalid format.", None
|
| 143 |
print(f"Fetched {len(questions_data)} questions.")
|
| 144 |
except requests.exceptions.RequestException as e:
|
| 145 |
print(f"Error fetching questions: {e}")
|
| 146 |
return f"Error fetching questions: {e}", None
|
| 147 |
except requests.exceptions.JSONDecodeError as e:
|
| 148 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 149 |
+
print(f"Response text: {response.text[:500]}")
|
| 150 |
+
return f"Error decoding server response for questions: {e}", None
|
| 151 |
except Exception as e:
|
| 152 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 153 |
return f"An unexpected error occurred fetching questions: {e}", None
|
|
|
|
| 164 |
continue
|
| 165 |
try:
|
| 166 |
submitted_answer = agent(question_text)
|
| 167 |
+
answers_payload.append(
|
| 168 |
+
{"task_id": task_id, "submitted_answer": submitted_answer}
|
| 169 |
+
)
|
| 170 |
+
results_log.append(
|
| 171 |
+
{
|
| 172 |
+
"Task ID": task_id,
|
| 173 |
+
"Question": question_text,
|
| 174 |
+
"Submitted Answer": submitted_answer,
|
| 175 |
+
}
|
| 176 |
+
)
|
| 177 |
except Exception as e:
|
| 178 |
+
print(f"Error running agent on task {task_id}: {e}")
|
| 179 |
+
results_log.append(
|
| 180 |
+
{
|
| 181 |
+
"Task ID": task_id,
|
| 182 |
+
"Question": question_text,
|
| 183 |
+
"Submitted Answer": f"AGENT ERROR: {e}",
|
| 184 |
+
}
|
| 185 |
+
)
|
| 186 |
|
| 187 |
if not answers_payload:
|
| 188 |
print("Agent did not produce any answers to submit.")
|
| 189 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 190 |
|
| 191 |
+
# 4. Prepare Submission
|
| 192 |
+
submission_data = {
|
| 193 |
+
"username": username.strip(),
|
| 194 |
+
"agent_code": agent_code,
|
| 195 |
+
"answers": answers_payload,
|
| 196 |
+
}
|
| 197 |
+
status_update = (
|
| 198 |
+
f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 199 |
+
)
|
| 200 |
print(status_update)
|
| 201 |
|
| 202 |
# 5. Submit
|
|
|
|
| 245 |
|
| 246 |
# --- Build Gradio Interface using Blocks ---
|
| 247 |
with gr.Blocks() as demo:
|
| 248 |
+
gr.Markdown("# Basic Agent Evaluation Runner (smolagents)")
|
| 249 |
gr.Markdown(
|
| 250 |
"""
|
| 251 |
**Instructions:**
|
| 252 |
+
1. This space uses a simple agent built with `smolagents` + `InferenceClientModel`.
|
| 253 |
+
2. Log in to your Hugging Face account using the button below.
|
| 254 |
+
3. Click **'Run Evaluation & Submit All Answers'** to fetch questions,
|
| 255 |
+
run the agent, submit answers, and see your score.
|
|
|
|
| 256 |
---
|
| 257 |
+
**Notes:**
|
| 258 |
+
- The correction on the server uses EXACT MATCH, so the agent is prompted
|
| 259 |
+
to output only the final answer (sem 'FINAL ANSWER', sem explicações).
|
| 260 |
+
- This template is intentionally simples; você pode adicionar tools,
|
| 261 |
+
melhorar o prompt, etc., se quiser subir seu score.
|
| 262 |
"""
|
| 263 |
)
|
| 264 |
|
|
|
|
| 266 |
|
| 267 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 268 |
|
| 269 |
+
status_output = gr.Textbox(
|
| 270 |
+
label="Run Status / Submission Result", lines=5, interactive=False
|
| 271 |
+
)
|
| 272 |
+
results_table = gr.DataFrame(
|
| 273 |
+
label="Questions and Agent Answers",
|
| 274 |
+
wrap=True,
|
| 275 |
+
)
|
| 276 |
|
| 277 |
run_button.click(
|
| 278 |
fn=run_and_submit_all,
|
| 279 |
+
outputs=[status_output, results_table],
|
| 280 |
)
|
| 281 |
|
| 282 |
if __name__ == "__main__":
|
| 283 |
+
print("\n" + "-" * 30 + " App Starting " + "-" * 30)
|
| 284 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
| 285 |
space_host_startup = os.getenv("SPACE_HOST")
|
| 286 |
+
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
| 287 |
|
| 288 |
if space_host_startup:
|
| 289 |
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
|
|
|
| 291 |
else:
|
| 292 |
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 293 |
|
| 294 |
+
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 295 |
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 296 |
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 297 |
+
print(
|
| 298 |
+
f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main"
|
| 299 |
+
)
|
| 300 |
else:
|
| 301 |
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 302 |
|
| 303 |
+
print("-" * (60 + len(" App Starting ")) + "\n")
|
| 304 |
|
| 305 |
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 306 |
demo.launch(debug=True, share=False)
|