Update app.py
Browse files
app.py
CHANGED
|
@@ -1,196 +1,116 @@
|
|
| 1 |
import os
|
| 2 |
-
import gradio as gr
|
| 3 |
import requests
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
|
| 7 |
-
# (Keep Constants as is)
|
| 8 |
-
# --- Constants ---
|
| 9 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 10 |
-
|
| 11 |
-
# --- Basic Agent Definition ---
|
| 12 |
-
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
| 13 |
-
class BasicAgent:
|
| 14 |
-
def __init__(self):
|
| 15 |
-
print("BasicAgent initialized.")
|
| 16 |
-
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
fixed_answer = "This is a default answer."
|
| 19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
-
return fixed_answer
|
| 21 |
|
| 22 |
-
|
|
|
|
|
|
|
| 23 |
"""
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
| 26 |
"""
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
-
# 1. Instantiate Agent ( modify this part to create your 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 |
-
# 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 |
-
# 2. Fetch Questions
|
| 52 |
-
print(f"Fetching questions from: {questions_url}")
|
| 53 |
-
try:
|
| 54 |
-
response = requests.get(questions_url, timeout=15)
|
| 55 |
-
response.raise_for_status()
|
| 56 |
-
questions_data = response.json()
|
| 57 |
-
if not questions_data:
|
| 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 |
-
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 |
-
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 |
-
print(f"An unexpected error occurred fetching questions: {e}")
|
| 70 |
-
return f"An unexpected error occurred fetching questions: {e}", None
|
| 71 |
-
|
| 72 |
-
# 3. Run your Agent
|
| 73 |
-
results_log = []
|
| 74 |
-
answers_payload = []
|
| 75 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 76 |
for item in questions_data:
|
| 77 |
-
task_id = item
|
| 78 |
-
question_text = item
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
try:
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
f"Message: {result_data.get('message', 'No message received.')}"
|
| 111 |
-
)
|
| 112 |
-
print("Submission successful.")
|
| 113 |
-
results_df = pd.DataFrame(results_log)
|
| 114 |
-
return final_status, results_df
|
| 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 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 138 |
-
print(status_message)
|
| 139 |
-
results_df = pd.DataFrame(results_log)
|
| 140 |
-
return status_message, results_df
|
| 141 |
-
|
| 142 |
|
| 143 |
-
#
|
| 144 |
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("#
|
| 146 |
-
gr.Markdown(
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
gr.LoginButton()
|
| 162 |
-
|
| 163 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
-
|
| 165 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
-
|
| 169 |
-
run_button.click(
|
| 170 |
-
fn=run_and_submit_all,
|
| 171 |
-
outputs=[status_output, results_table]
|
| 172 |
)
|
| 173 |
|
| 174 |
if __name__ == "__main__":
|
| 175 |
-
|
| 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") # 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 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 187 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 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 requests
|
| 3 |
+
import gradio as gr
|
| 4 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, HfApiModel, tool
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
+
# 1. Define any custom tools your agent might need
|
| 7 |
+
@tool
|
| 8 |
+
def get_file_content_tool(task_id: str) -> str:
|
| 9 |
"""
|
| 10 |
+
Downloads and inspects files associated with a specific task ID from the course API.
|
| 11 |
+
|
| 12 |
+
Args:
|
| 13 |
+
task_id: The ID of the task requiring a file.
|
| 14 |
"""
|
| 15 |
+
url = f"https://agents-course-unit4-eval.hf.space/files/{task_id}"
|
| 16 |
+
response = requests.get(url)
|
| 17 |
+
if response.status_code == 200:
|
| 18 |
+
filename = f"temp_{task_id}"
|
| 19 |
+
with open(filename, "wb") as f:
|
| 20 |
+
f.write(response.content)
|
| 21 |
+
return f"File downloaded successfully as {filename}. You can now inspect or process it."
|
| 22 |
+
return f"Failed to download file for task {task_id}"
|
| 23 |
+
|
| 24 |
+
# 2. Initialize the model and the agent
|
| 25 |
+
# Using a robust model via Hugging Face API model provider
|
| 26 |
+
model = HfApiModel(model_id="meta-llama/Llama-3.3-70B-Instruct")
|
| 27 |
+
|
| 28 |
+
agent = CodeAgent(
|
| 29 |
+
tools=[DuckDuckGoSearchTool(), get_file_content_tool],
|
| 30 |
+
model=model,
|
| 31 |
+
max_steps=6,
|
| 32 |
+
verbosity_level=1
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
# 3. Core function to run evaluation across questions
|
| 36 |
+
def run_evaluation(username):
|
| 37 |
+
if not username:
|
| 38 |
+
return "Please log in with your Hugging Face account first.", {}
|
| 39 |
+
|
| 40 |
+
api_base = "https://agents-course-unit4-eval.hf.space"
|
| 41 |
+
|
| 42 |
+
# Fetch questions
|
| 43 |
+
resp = requests.get(f"{api_base}/questions")
|
| 44 |
+
if resp.status_code != 200:
|
| 45 |
+
return f"Failed to fetch questions: {resp.text}", {}
|
| 46 |
+
|
| 47 |
+
questions_data = resp.json()
|
| 48 |
+
answers = []
|
| 49 |
+
log_output = ""
|
| 50 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
for item in questions_data:
|
| 52 |
+
task_id = item["task_id"]
|
| 53 |
+
question_text = item["question"]
|
| 54 |
+
|
| 55 |
+
log_output += f"\n--- Processing Task ID: {task_id} ---\nQuestion: {question_text}\n"
|
| 56 |
+
|
| 57 |
try:
|
| 58 |
+
# Run the agent on the question prompt
|
| 59 |
+
# Instruction reminder: Keep answers direct for exact match scoring!
|
| 60 |
+
prompt = f"{question_text}\nProvide ONLY the direct, final answer string with no conversational padding."
|
| 61 |
+
raw_answer = agent.run(prompt)
|
| 62 |
+
|
| 63 |
+
# Clean up output string format if needed
|
| 64 |
+
clean_answer = str(raw_answer).strip()
|
| 65 |
+
|
| 66 |
+
answers.append({
|
| 67 |
+
"task_id": task_id,
|
| 68 |
+
"submitted_answer": clean_answer
|
| 69 |
+
})
|
| 70 |
+
log_output += f"Answer: {clean_answer}\n"
|
| 71 |
except Exception as e:
|
| 72 |
+
log_output += f"Error executing task {task_id}: {str(e)}\n"
|
| 73 |
+
answers.append({
|
| 74 |
+
"task_id": task_id,
|
| 75 |
+
"submitted_answer": "Error"
|
| 76 |
+
})
|
| 77 |
+
|
| 78 |
+
# 4. Submit results to the API
|
| 79 |
+
code_link = f"https://huggingface.co/spaces/{username}/{os.environ.get('SPACE_TITLE', 'Final_Assignment_Template')}/tree/main"
|
| 80 |
+
|
| 81 |
+
payload = {
|
| 82 |
+
"username": username,
|
| 83 |
+
"agent_code": code_link,
|
| 84 |
+
"answers": answers
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
sub_resp = requests.post(f"{api_base}/submit", json=payload)
|
| 88 |
+
if sub_resp.status_code == 200:
|
| 89 |
+
result_json = sub_resp.json()
|
| 90 |
+
log_output += f"\nSubmission Successful! Response: {result_json}"
|
| 91 |
+
else:
|
| 92 |
+
log_output += f"\nSubmission Failed: {sub_resp.text}"
|
| 93 |
+
|
| 94 |
+
return log_output, answers
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
# 5. Build Gradio UI Wrapper (Matches the template structure)
|
| 97 |
with gr.Blocks() as demo:
|
| 98 |
+
gr.Markdown("# Custom Agent Evaluation Runner")
|
| 99 |
+
gr.Markdown("Click below to run your custom `smolagents` code against the Unit 4 benchmark questions and submit automatically.")
|
| 100 |
+
|
| 101 |
+
with gr.Row():
|
| 102 |
+
login_button = gr.LoginButton()
|
| 103 |
+
|
| 104 |
+
with gr.Row():
|
| 105 |
+
submit_btn = gr.Button("Run Evaluation & Submit All Answers")
|
| 106 |
+
|
| 107 |
+
output_box = gr.Textbox(label="Run Status / Submission Result", lines=15)
|
| 108 |
+
|
| 109 |
+
submit_btn.click(
|
| 110 |
+
fn=run_evaluation,
|
| 111 |
+
inputs=[login_button],
|
| 112 |
+
outputs=[output_box]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
)
|
| 114 |
|
| 115 |
if __name__ == "__main__":
|
| 116 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|