Update app.py
Browse files
app.py
CHANGED
|
@@ -1,109 +1,170 @@
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import json
|
| 4 |
-
|
|
|
|
| 5 |
|
| 6 |
-
# --- CONFIGURATION ---
|
| 7 |
API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 8 |
-
# Ensure your space code link looks exactly like this (.../tree/main)
|
| 9 |
-
HF_USERNAME = "your_hf_username"
|
| 10 |
-
CODE_LINK = f"https://huggingface.co/spaces/{HF_USERNAME}/Final_Assignment_Template/tree/main"
|
| 11 |
|
| 12 |
-
#
|
| 13 |
search_tool = DuckDuckGoSearchTool()
|
| 14 |
agent = CodeAgent(
|
| 15 |
-
model=
|
| 16 |
tools=[search_tool],
|
| 17 |
-
additional_authorized_imports=["pandas", "numpy", "requests", "bs4", "openpyxl", "pypdf"]
|
| 18 |
)
|
| 19 |
|
| 20 |
-
def
|
| 21 |
-
"""
|
| 22 |
-
|
|
|
|
| 23 |
response.raise_for_status()
|
| 24 |
-
return response.json()
|
| 25 |
|
| 26 |
-
def
|
| 27 |
-
"""Downloads an evaluation
|
| 28 |
if not file_name:
|
| 29 |
return None
|
| 30 |
|
| 31 |
-
|
| 32 |
-
os.makedirs(
|
|
|
|
| 33 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
url = f"{API_BASE_URL}/files/{task_id}"
|
| 35 |
response = requests.get(url, stream=True)
|
| 36 |
|
| 37 |
if response.status_code == 200:
|
| 38 |
-
with open(
|
| 39 |
for chunk in response.iter_content(chunk_size=8192):
|
| 40 |
-
|
| 41 |
-
print(f"π₯
|
| 42 |
-
return
|
| 43 |
else:
|
| 44 |
-
print(f"
|
| 45 |
return None
|
| 46 |
|
| 47 |
-
def
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
"
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
"only the raw value matching the requested format."
|
| 57 |
-
)
|
| 58 |
-
|
| 59 |
-
for item in questions:
|
| 60 |
-
task_id = item['task_id']
|
| 61 |
-
raw_question = item['question']
|
| 62 |
-
# Level 1 items occasionally reference attached data sheets
|
| 63 |
-
file_name = item.get('file_name', None)
|
| 64 |
-
|
| 65 |
-
print(f"\nπ Processing Task ID: {task_id}")
|
| 66 |
|
| 67 |
-
#
|
| 68 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
|
|
|
|
|
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
try:
|
| 77 |
-
# Execute agent reasoning loop
|
| 78 |
-
raw_output = agent.run(full_prompt)
|
| 79 |
-
final_answer = str(raw_output).strip()
|
| 80 |
|
| 81 |
-
#
|
| 82 |
-
|
| 83 |
-
final_answer = final_answer.lower().split("the answer is")[-1].strip(" :.`\"")
|
| 84 |
-
|
| 85 |
-
print(f"π― Cleaned Agent Result: '{final_answer}'")
|
| 86 |
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
"
|
| 90 |
-
|
|
|
|
| 91 |
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
|
| 109 |
-
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import requests
|
| 3 |
import json
|
| 4 |
+
import gradio as ui
|
| 5 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel
|
| 6 |
|
| 7 |
+
# --- SCORING CONFIGURATION ---
|
| 8 |
API_BASE_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
+
# Initialize core agent dependencies
|
| 11 |
search_tool = DuckDuckGoSearchTool()
|
| 12 |
agent = CodeAgent(
|
| 13 |
+
model=HfApiModel(), # Serverless inference engine
|
| 14 |
tools=[search_tool],
|
| 15 |
+
additional_authorized_imports=["pandas", "numpy", "requests", "bs4", "openpyxl", "pypdf", "PIL"]
|
| 16 |
)
|
| 17 |
|
| 18 |
+
def fetch_evaluation_questions():
|
| 19 |
+
"""Fetches the 20 level 1 filtered validation questions from the course API."""
|
| 20 |
+
url = f"{API_BASE_URL}/questions"
|
| 21 |
+
response = requests.get(url)
|
| 22 |
response.raise_for_status()
|
| 23 |
+
return response.json()
|
| 24 |
|
| 25 |
+
def download_task_file(task_id: str, file_name: str):
|
| 26 |
+
"""Downloads an evaluation asset if present and maps it to a local workspace path."""
|
| 27 |
if not file_name:
|
| 28 |
return None
|
| 29 |
|
| 30 |
+
local_directory = "./downloads"
|
| 31 |
+
os.makedirs(local_directory, exist_ok=True)
|
| 32 |
+
local_file_path = os.path.join(local_directory, f"{task_id}_{file_name}")
|
| 33 |
|
| 34 |
+
# Don't re-download if file already exists locally
|
| 35 |
+
if os.path.exists(local_file_path):
|
| 36 |
+
return local_file_path
|
| 37 |
+
|
| 38 |
url = f"{API_BASE_URL}/files/{task_id}"
|
| 39 |
response = requests.get(url, stream=True)
|
| 40 |
|
| 41 |
if response.status_code == 200:
|
| 42 |
+
with open(local_file_path, 'wb') as file:
|
| 43 |
for chunk in response.iter_content(chunk_size=8192):
|
| 44 |
+
file.write(chunk)
|
| 45 |
+
print(f"π₯ Asset downloaded successfully for Task {task_id} -> {local_file_path}")
|
| 46 |
+
return local_file_path
|
| 47 |
else:
|
| 48 |
+
print(f"βΉοΈ No download asset found or status code error for Task {task_id}: {response.status_code}")
|
| 49 |
return None
|
| 50 |
|
| 51 |
+
def process_agent_evaluation(hf_username: str, profile_code_url: str, progress=ui.Progress()):
|
| 52 |
+
"""Iterates through all evaluation steps, manages files, runs agent queries, and returns results."""
|
| 53 |
+
if not hf_username.strip() or not profile_code_url.strip():
|
| 54 |
+
return "β Error: Please fill in both your Hugging Face Username and your Public Space Code Link before submitting."
|
| 55 |
+
|
| 56 |
+
try:
|
| 57 |
+
progress(0, desc="Fetching GAIA evaluation questions...")
|
| 58 |
+
questions = fetch_evaluation_questions()
|
| 59 |
+
submitted_answers = []
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
+
# Strict context formatting boundary to prevent verbose conversational leaks
|
| 62 |
+
formatting_instructions = (
|
| 63 |
+
"\n\nCRITICAL OUTCOME INSTRUCTION: Output ONLY the literal final string answer. "
|
| 64 |
+
"Do NOT prefix with 'FINAL ANSWER:', do NOT use markdown code blocks for text, "
|
| 65 |
+
"and do NOT include conversational explanations. Your complete response must contain "
|
| 66 |
+
"only the raw value matching the requested format."
|
| 67 |
+
)
|
| 68 |
|
| 69 |
+
total_questions = len(questions)
|
| 70 |
+
for index, item in enumerate(questions):
|
| 71 |
+
task_id = item['task_id']
|
| 72 |
+
raw_question = item['question']
|
| 73 |
+
file_name = item.get('file_name', None)
|
| 74 |
|
| 75 |
+
progress((index / total_questions), desc=f"Evaluating Task {index + 1}/{total_questions} (ID: {task_id})...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
|
| 77 |
+
# Look up and handle data attachments
|
| 78 |
+
local_file_path = download_task_file(task_id, file_name)
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
full_prompt = raw_question
|
| 81 |
+
if local_file_path:
|
| 82 |
+
full_prompt += f"\nNote: The file provided for this task has been downloaded locally to: {local_file_path}"
|
| 83 |
+
|
| 84 |
+
full_prompt += formatting_instructions
|
| 85 |
|
| 86 |
+
try:
|
| 87 |
+
# Fire up the agent loop
|
| 88 |
+
raw_output = agent.run(full_prompt)
|
| 89 |
+
final_answer = str(raw_output).strip()
|
| 90 |
+
|
| 91 |
+
# Cleanup parser fallback if agent leaked phrases
|
| 92 |
+
if "the answer is" in final_answer.lower():
|
| 93 |
+
final_answer = final_answer.lower().split("the answer is")[-1].strip(" :.`\"*")
|
| 94 |
+
|
| 95 |
+
submitted_answers.append({
|
| 96 |
+
"task_id": task_id,
|
| 97 |
+
"submitted_answer": final_answer
|
| 98 |
+
})
|
| 99 |
+
print(f"β
Clean Answer Logged [{task_id}]: {final_answer}")
|
| 100 |
+
|
| 101 |
+
except Exception as e:
|
| 102 |
+
print(f"β Execution crash on task {task_id}: {e}")
|
| 103 |
+
submitted_answers.append({
|
| 104 |
+
"task_id": task_id,
|
| 105 |
+
"submitted_answer": "ERROR_FALLBACK"
|
| 106 |
+
})
|
| 107 |
+
|
| 108 |
+
# --- POST SUBMISSION PAYLOAD ---
|
| 109 |
+
progress(0.95, desc="Transmitting data package to student leaderboard...")
|
| 110 |
+
payload = {
|
| 111 |
+
"username": hf_username.strip(),
|
| 112 |
+
"agent_code": profile_code_url.strip(),
|
| 113 |
+
"answers": submitted_answers
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
headers = {"Content-Type": "application/json"}
|
| 117 |
+
submit_url = f"{API_BASE_URL}/submit"
|
| 118 |
+
|
| 119 |
+
response = requests.post(submit_url, json=payload, headers=headers)
|
| 120 |
+
|
| 121 |
+
if response.status_code == 200:
|
| 122 |
+
result_data = response.json()
|
| 123 |
+
score = result_data.get("score", 0)
|
| 124 |
+
percentage = score * 100
|
| 125 |
|
| 126 |
+
status_summary = (
|
| 127 |
+
f"### π Evaluation Complete!\n\n"
|
| 128 |
+
f"**π Final Score:** {percentage:.1f}% ({int(score * total_questions)} / {total_questions} Correct)\n\n"
|
| 129 |
+
f"**π¬ API Server Response:** {result_data.get('message', 'Submission saved successfully!')}\n\n"
|
| 130 |
+
f"Check your standing on the leaderboard right now!"
|
| 131 |
+
)
|
| 132 |
+
return status_summary
|
| 133 |
+
else:
|
| 134 |
+
return f"β Submission Error (HTTP {response.status_code}): {response.text}"
|
| 135 |
+
|
| 136 |
+
except Exception as general_error:
|
| 137 |
+
return f"β A structural runtime execution crash occurred: {str(general_error)}"
|
| 138 |
+
|
| 139 |
+
# --- GRADIO WEB USER INTERFACE ---
|
| 140 |
+
with ui.Blocks(theme=ui.themes.Soft()) as interface:
|
| 141 |
+
ui.Markdown("# π Unit 4: GAIA Benchmark Agent Certification Engine")
|
| 142 |
+
ui.Markdown(
|
| 143 |
+
"Welcome! This portal coordinates your custom `smolagents` architecture against the "
|
| 144 |
+
"20 curated Level-1 GAIA tasks. Fill in your identification markers below to run evaluation and sync metrics."
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
with ui.Row():
|
| 148 |
+
input_username = ui.Textbox(
|
| 149 |
+
label="Hugging Face Username",
|
| 150 |
+
placeholder="e.g., dev_pioneer",
|
| 151 |
+
lines=1
|
| 152 |
+
)
|
| 153 |
+
input_code_link = ui.Textbox(
|
| 154 |
+
label="Public Space Repository Link (agent_code URL)",
|
| 155 |
+
placeholder="https://huggingface.co/spaces/your_username/your_space/tree/main",
|
| 156 |
+
lines=1
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
evaluate_button = ui.Button("π Start Evaluation & Submit Answers", variant="primary")
|
| 160 |
|
| 161 |
+
output_display = ui.Markdown(value="π‘ Provide your workspace metrics above and click run to engage the loop.")
|
| 162 |
+
|
| 163 |
+
evaluate_button.click(
|
| 164 |
+
fn=process_agent_evaluation,
|
| 165 |
+
inputs=[input_username, input_code_link],
|
| 166 |
+
outputs=output_display
|
| 167 |
+
)
|
| 168 |
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
interface.launch()
|