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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import requests
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel
|
| 6 |
|
| 7 |
+
# --- Constants ---
|
| 8 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
+
# --- Agent Definition ---
|
| 11 |
+
class BasicAgent:
|
| 12 |
+
def __init__(self):
|
| 13 |
+
print("Initializing smolagents CodeAgent...")
|
| 14 |
+
try:
|
| 15 |
+
# Create model - using FREE Llama model
|
| 16 |
+
self.model = LiteLLMModel(
|
| 17 |
+
model_id="huggingface/meta-llama/Llama-3.2-3B-Instruct"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
# Create search tool
|
| 21 |
+
self.search_tool = DuckDuckGoSearchTool()
|
| 22 |
+
|
| 23 |
+
# Create agent with tools
|
| 24 |
+
self.agent = CodeAgent(
|
| 25 |
+
tools=[self.search_tool],
|
| 26 |
+
model=self.model,
|
| 27 |
+
additional_authorized_imports=[
|
| 28 |
+
"requests",
|
| 29 |
+
"pandas",
|
| 30 |
+
"numpy",
|
| 31 |
+
"openpyxl",
|
| 32 |
+
"xlrd"
|
| 33 |
+
]
|
| 34 |
+
)
|
| 35 |
+
print("β
Agent initialized successfully!")
|
| 36 |
+
except Exception as e:
|
| 37 |
+
print(f"β Error initializing agent: {e}")
|
| 38 |
+
raise e
|
| 39 |
+
|
| 40 |
+
def __call__(self, question: str) -> str:
|
| 41 |
+
"""Run agent on a question and return the answer"""
|
| 42 |
+
print(f"π Question: {question[:80]}...")
|
| 43 |
+
try:
|
| 44 |
+
# Run the agent
|
| 45 |
+
answer = self.agent.run(question)
|
| 46 |
+
answer_str = str(answer)
|
| 47 |
+
print(f"β
Answer: {answer_str[:80]}...")
|
| 48 |
+
return answer_str
|
| 49 |
+
except Exception as e:
|
| 50 |
+
error_msg = f"Error: {str(e)}"
|
| 51 |
+
print(f"β {error_msg}")
|
| 52 |
+
return error_msg
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 56 |
+
"""
|
| 57 |
+
Fetches questions, runs agent, submits answers, returns results.
|
| 58 |
+
"""
|
| 59 |
+
# Get Space ID
|
| 60 |
+
space_id = os.getenv("SPACE_ID")
|
| 61 |
+
|
| 62 |
+
# Check if user is logged in
|
| 63 |
+
if profile:
|
| 64 |
+
username = f"{profile.username}"
|
| 65 |
+
print(f"π€ User logged in: {username}")
|
| 66 |
+
else:
|
| 67 |
+
print("β οΈ User not logged in")
|
| 68 |
+
return "Please Login to Hugging Face with the button above.", None
|
| 69 |
+
|
| 70 |
+
# API endpoints
|
| 71 |
+
api_url = DEFAULT_API_URL
|
| 72 |
+
questions_url = f"{api_url}/questions"
|
| 73 |
+
submit_url = f"{api_url}/submit"
|
| 74 |
+
|
| 75 |
+
# 1. Initialize Agent
|
| 76 |
+
print("\n" + "="*60)
|
| 77 |
+
print("π€ INITIALIZING AGENT")
|
| 78 |
+
print("="*60)
|
| 79 |
+
try:
|
| 80 |
+
agent = BasicAgent()
|
| 81 |
+
except Exception as e:
|
| 82 |
+
error_msg = f"Error initializing agent: {e}"
|
| 83 |
+
print(f"β {error_msg}")
|
| 84 |
+
return error_msg, None
|
| 85 |
+
|
| 86 |
+
# Code URL for submission
|
| 87 |
+
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 88 |
+
print(f"π Code URL: {agent_code}")
|
| 89 |
+
|
| 90 |
+
# 2. Fetch Questions
|
| 91 |
+
print("\n" + "="*60)
|
| 92 |
+
print("π₯ FETCHING QUESTIONS")
|
| 93 |
+
print("="*60)
|
| 94 |
+
print(f"URL: {questions_url}")
|
| 95 |
+
try:
|
| 96 |
+
response = requests.get(questions_url, timeout=15)
|
| 97 |
+
response.raise_for_status()
|
| 98 |
+
questions_data = response.json()
|
| 99 |
+
|
| 100 |
+
if not questions_data:
|
| 101 |
+
return "No questions received from server.", None
|
| 102 |
+
|
| 103 |
+
print(f"β
Fetched {len(questions_data)} questions")
|
| 104 |
+
except Exception as e:
|
| 105 |
+
error_msg = f"Error fetching questions: {e}"
|
| 106 |
+
print(f"β {error_msg}")
|
| 107 |
+
return error_msg, None
|
| 108 |
+
|
| 109 |
+
# 3. Run Agent on Questions
|
| 110 |
+
print("\n" + "="*60)
|
| 111 |
+
print("π RUNNING AGENT ON QUESTIONS")
|
| 112 |
+
print("="*60)
|
| 113 |
+
|
| 114 |
+
results_log = []
|
| 115 |
+
answers_payload = []
|
| 116 |
+
|
| 117 |
+
for idx, item in enumerate(questions_data, 1):
|
| 118 |
+
task_id = item.get("task_id")
|
| 119 |
+
question_text = item.get("question")
|
| 120 |
+
|
| 121 |
+
if not task_id or question_text is None:
|
| 122 |
+
print(f"β οΈ Skipping invalid question")
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
print(f"\n[{idx}/{len(questions_data)}] Task ID: {task_id}")
|
| 126 |
+
|
| 127 |
+
try:
|
| 128 |
+
# Run agent
|
| 129 |
+
submitted_answer = agent(question_text)
|
| 130 |
+
|
| 131 |
+
# Store answer
|
| 132 |
+
answers_payload.append({
|
| 133 |
+
"task_id": task_id,
|
| 134 |
+
"submitted_answer": submitted_answer
|
| 135 |
+
})
|
| 136 |
+
|
| 137 |
+
results_log.append({
|
| 138 |
+
"Task ID": task_id,
|
| 139 |
+
"Question": question_text,
|
| 140 |
+
"Submitted Answer": submitted_answer
|
| 141 |
+
})
|
| 142 |
+
|
| 143 |
+
except Exception as e:
|
| 144 |
+
error_answer = f"AGENT ERROR: {e}"
|
| 145 |
+
print(f"β Error: {e}")
|
| 146 |
+
|
| 147 |
+
results_log.append({
|
| 148 |
+
"Task ID": task_id,
|
| 149 |
+
"Question": question_text,
|
| 150 |
+
"Submitted Answer": error_answer
|
| 151 |
+
})
|
| 152 |
+
|
| 153 |
+
if not answers_payload:
|
| 154 |
+
return "Agent did not produce any answers.", pd.DataFrame(results_log)
|
| 155 |
+
|
| 156 |
+
# 4. Submit Answers
|
| 157 |
+
print("\n" + "="*60)
|
| 158 |
+
print("π€ SUBMITTING ANSWERS")
|
| 159 |
+
print("="*60)
|
| 160 |
+
print(f"Submitting {len(answers_payload)} answers for user: {username}")
|
| 161 |
+
|
| 162 |
+
submission_data = {
|
| 163 |
+
"username": username.strip(),
|
| 164 |
+
"agent_code": agent_code,
|
| 165 |
+
"answers": answers_payload
|
| 166 |
+
}
|
| 167 |
+
|
| 168 |
+
try:
|
| 169 |
+
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 170 |
+
response.raise_for_status()
|
| 171 |
+
result_data = response.json()
|
| 172 |
+
|
| 173 |
+
# Format success message
|
| 174 |
+
final_status = (
|
| 175 |
+
f"β
Submission Successful!\n\n"
|
| 176 |
+
f"User: {result_data.get('username')}\n"
|
| 177 |
+
f"Score: {result_data.get('score', 'N/A')}%\n"
|
| 178 |
+
f"Correct: {result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')}\n"
|
| 179 |
+
f"Message: {result_data.get('message', 'No message')}"
|
| 180 |
+
)
|
| 181 |
+
|
| 182 |
+
print("="*60)
|
| 183 |
+
print(final_status)
|
| 184 |
+
print("="*60)
|
| 185 |
+
|
| 186 |
+
results_df = pd.DataFrame(results_log)
|
| 187 |
+
return final_status, results_df
|
| 188 |
+
|
| 189 |
+
except Exception as e:
|
| 190 |
+
error_msg = f"β Submission Failed: {e}"
|
| 191 |
+
print(error_msg)
|
| 192 |
+
results_df = pd.DataFrame(results_log)
|
| 193 |
+
return error_msg, results_df
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# --- Gradio Interface ---
|
| 197 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 198 |
+
gr.Markdown("# π€ smolagents Exam Runner")
|
| 199 |
+
gr.Markdown(
|
| 200 |
+
"""
|
| 201 |
+
### Instructions:
|
| 202 |
+
1. **Log in** with your Hugging Face account (button below)
|
| 203 |
+
2. **Click** "Run Evaluation & Submit All Answers"
|
| 204 |
+
3. **Wait** - This takes several minutes as the agent answers each question
|
| 205 |
+
4. **View** your score and answers
|
| 206 |
+
|
| 207 |
+
---
|
| 208 |
+
|
| 209 |
+
β οΈ **Note:** The agent uses web search and code execution to answer questions.
|
| 210 |
+
This may take 5-10 minutes to complete all questions.
|
| 211 |
+
"""
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
gr.LoginButton()
|
| 215 |
+
|
| 216 |
+
run_button = gr.Button(
|
| 217 |
+
"π Run Evaluation & Submit All Answers",
|
| 218 |
+
variant="primary",
|
| 219 |
+
size="lg"
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
status_output = gr.Textbox(
|
| 223 |
+
label="π Status & Results",
|
| 224 |
+
lines=10,
|
| 225 |
+
interactive=False
|
| 226 |
+
)
|
| 227 |
+
|
| 228 |
+
results_table = gr.DataFrame(
|
| 229 |
+
label="π Questions and Agent Answers",
|
| 230 |
+
wrap=True
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
run_button.click(
|
| 234 |
+
fn=run_and_submit_all,
|
| 235 |
+
outputs=[status_output, results_table]
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
gr.Markdown(
|
| 239 |
+
"""
|
| 240 |
+
---
|
| 241 |
+
**Tips:**
|
| 242 |
+
- The agent searches the web for answers
|
| 243 |
+
- Some questions require data analysis or file processing
|
| 244 |
+
- Answers are submitted automatically after completion
|
| 245 |
+
"""
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
if __name__ == "__main__":
|
| 250 |
+
print("\n" + "="*70)
|
| 251 |
+
print(" " * 20 + "π SMOLAGENTS EXAM RUNNER")
|
| 252 |
+
print("="*70)
|
| 253 |
+
|
| 254 |
+
# Check environment variables
|
| 255 |
+
space_host = os.getenv("SPACE_HOST")
|
| 256 |
+
space_id = os.getenv("SPACE_ID")
|
| 257 |
+
|
| 258 |
+
if space_host:
|
| 259 |
+
print(f"β
SPACE_HOST: {space_host}")
|
| 260 |
+
print(f" Runtime URL: https://{space_host}.hf.space")
|
| 261 |
+
else:
|
| 262 |
+
print("βΉοΈ SPACE_HOST not found (running locally?)")
|
| 263 |
+
|
| 264 |
+
if space_id:
|
| 265 |
+
print(f"β
SPACE_ID: {space_id}")
|
| 266 |
+
print(f" Repo: https://huggingface.co/spaces/{space_id}")
|
| 267 |
+
else:
|
| 268 |
+
print("βΉοΈ SPACE_ID not found (running locally?)")
|
| 269 |
+
|
| 270 |
+
print("="*70 + "\n")
|
| 271 |
+
print("π¬ Launching Gradio Interface...\n")
|
| 272 |
+
|
| 273 |
+
demo.launch(debug=True, share=False)
|