Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,270 +4,148 @@ import requests
|
|
| 4 |
import pandas as pd
|
| 5 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel
|
| 6 |
|
| 7 |
-
#
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
-
#
|
| 11 |
class BasicAgent:
|
| 12 |
def __init__(self):
|
| 13 |
-
print("
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
raise e
|
| 39 |
|
| 40 |
def __call__(self, question: str) -> str:
|
| 41 |
-
"
|
| 42 |
-
print(f"📝 Question: {question[:80]}...")
|
| 43 |
try:
|
| 44 |
-
# Run the agent
|
| 45 |
answer = self.agent.run(question)
|
| 46 |
-
|
| 47 |
-
print(f"✅ Answer: {answer_str[:80]}...")
|
| 48 |
-
return answer_str
|
| 49 |
except Exception as e:
|
| 50 |
-
|
| 51 |
-
print(f"❌ {error_msg}")
|
| 52 |
-
return error_msg
|
| 53 |
|
| 54 |
|
| 55 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 56 |
-
"""
|
| 57 |
-
|
| 58 |
-
"""
|
| 59 |
-
# Get Space ID
|
| 60 |
space_id = os.getenv("SPACE_ID")
|
| 61 |
-
|
| 62 |
-
# Check if
|
| 63 |
if profile:
|
| 64 |
-
username =
|
| 65 |
-
print(f"
|
| 66 |
else:
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 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 |
-
|
| 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 |
-
|
| 89 |
-
|
| 90 |
-
|
| 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 |
-
|
| 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 |
-
|
| 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 |
-
|
| 115 |
-
|
|
|
|
|
|
|
| 116 |
|
| 117 |
-
for
|
| 118 |
task_id = item.get("task_id")
|
| 119 |
-
|
| 120 |
|
| 121 |
-
if not task_id or
|
| 122 |
-
print(f"⚠️ Skipping invalid question")
|
| 123 |
continue
|
| 124 |
|
| 125 |
-
print(f"
|
| 126 |
|
| 127 |
try:
|
| 128 |
-
|
| 129 |
-
submitted_answer
|
| 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 |
-
|
| 145 |
-
|
| 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 |
-
|
| 163 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
"agent_code": agent_code,
|
| 165 |
-
"answers":
|
| 166 |
}
|
| 167 |
|
| 168 |
try:
|
| 169 |
-
response = requests.post(submit_url, json=
|
| 170 |
response.raise_for_status()
|
| 171 |
-
|
| 172 |
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
f"
|
| 176 |
-
f"
|
| 177 |
-
f"
|
| 178 |
-
f"
|
| 179 |
-
f"Message: {result_data.get('message', 'No message')}"
|
| 180 |
)
|
| 181 |
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
print("="*60)
|
| 185 |
-
|
| 186 |
-
results_df = pd.DataFrame(results_log)
|
| 187 |
-
return final_status, results_df
|
| 188 |
-
|
| 189 |
except Exception as e:
|
| 190 |
-
|
| 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 |
-
|
| 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 |
-
|
| 255 |
-
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import pandas as pd
|
| 5 |
from smolagents import CodeAgent, DuckDuckGoSearchTool, LiteLLMModel
|
| 6 |
|
| 7 |
+
# API URL for submission
|
| 8 |
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
+
# My agent class
|
| 11 |
class BasicAgent:
|
| 12 |
def __init__(self):
|
| 13 |
+
print("Starting agent...")
|
| 14 |
+
|
| 15 |
+
# Get my HF token
|
| 16 |
+
token = os.getenv("hf_token") # ← Changed to lowercase!
|
| 17 |
+
|
| 18 |
+
if not token:
|
| 19 |
+
raise Exception("Token not found! Check secrets.")
|
| 20 |
+
|
| 21 |
+
# Create the model
|
| 22 |
+
self.model = LiteLLMModel(
|
| 23 |
+
model_id="huggingface/meta-llama/Llama-3.2-3B-Instruct",
|
| 24 |
+
api_key=token
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
# Add web search
|
| 28 |
+
self.search_tool = DuckDuckGoSearchTool()
|
| 29 |
+
|
| 30 |
+
# Create agent
|
| 31 |
+
self.agent = CodeAgent(
|
| 32 |
+
tools=[self.search_tool],
|
| 33 |
+
model=self.model,
|
| 34 |
+
additional_authorized_imports=["requests", "pandas", "numpy", "openpyxl", "xlrd"]
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
print("Agent ready!")
|
|
|
|
| 38 |
|
| 39 |
def __call__(self, question: str) -> str:
|
| 40 |
+
print(f"Question: {question[:50]}...")
|
|
|
|
| 41 |
try:
|
|
|
|
| 42 |
answer = self.agent.run(question)
|
| 43 |
+
return str(answer)
|
|
|
|
|
|
|
| 44 |
except Exception as e:
|
| 45 |
+
return f"Error: {str(e)}"
|
|
|
|
|
|
|
| 46 |
|
| 47 |
|
| 48 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 49 |
+
"""Main function to run the evaluation"""
|
| 50 |
+
|
|
|
|
|
|
|
| 51 |
space_id = os.getenv("SPACE_ID")
|
| 52 |
+
|
| 53 |
+
# Check if logged in
|
| 54 |
if profile:
|
| 55 |
+
username = profile.username
|
| 56 |
+
print(f"Logged in as: {username}")
|
| 57 |
else:
|
| 58 |
+
return "Please login first!", None
|
| 59 |
+
|
| 60 |
+
# URLs
|
| 61 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 62 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 63 |
+
|
| 64 |
+
# Initialize agent
|
| 65 |
+
print("Creating agent...")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
try:
|
| 67 |
agent = BasicAgent()
|
| 68 |
except Exception as e:
|
| 69 |
+
return f"Error creating agent: {e}", None
|
|
|
|
|
|
|
| 70 |
|
|
|
|
| 71 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 72 |
+
|
| 73 |
+
# Get questions
|
| 74 |
+
print("Getting questions...")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
try:
|
| 76 |
response = requests.get(questions_url, timeout=15)
|
| 77 |
response.raise_for_status()
|
| 78 |
+
questions = response.json()
|
| 79 |
+
print(f"Got {len(questions)} questions")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
except Exception as e:
|
| 81 |
+
return f"Error getting questions: {e}", None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
|
| 83 |
+
# Answer questions
|
| 84 |
+
print("Answering questions...")
|
| 85 |
+
results = []
|
| 86 |
+
answers = []
|
| 87 |
|
| 88 |
+
for i, item in enumerate(questions):
|
| 89 |
task_id = item.get("task_id")
|
| 90 |
+
question = item.get("question")
|
| 91 |
|
| 92 |
+
if not task_id or not question:
|
|
|
|
| 93 |
continue
|
| 94 |
|
| 95 |
+
print(f"Question {i+1}/{len(questions)}")
|
| 96 |
|
| 97 |
try:
|
| 98 |
+
answer = agent(question)
|
| 99 |
+
answers.append({"task_id": task_id, "submitted_answer": answer})
|
| 100 |
+
results.append({"Task ID": task_id, "Question": question, "Submitted Answer": answer})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
except Exception as e:
|
| 102 |
+
print(f"Error on question {i+1}: {e}")
|
| 103 |
+
results.append({"Task ID": task_id, "Question": question, "Submitted Answer": f"Error: {e}"})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 104 |
|
| 105 |
+
if not answers:
|
| 106 |
+
return "No answers generated", pd.DataFrame(results)
|
| 107 |
+
|
| 108 |
+
# Submit
|
| 109 |
+
print(f"Submitting {len(answers)} answers...")
|
| 110 |
+
submission = {
|
| 111 |
+
"username": username,
|
| 112 |
"agent_code": agent_code,
|
| 113 |
+
"answers": answers
|
| 114 |
}
|
| 115 |
|
| 116 |
try:
|
| 117 |
+
response = requests.post(submit_url, json=submission, timeout=60)
|
| 118 |
response.raise_for_status()
|
| 119 |
+
result = response.json()
|
| 120 |
|
| 121 |
+
status = (
|
| 122 |
+
f"Submission successful!\n"
|
| 123 |
+
f"User: {result.get('username')}\n"
|
| 124 |
+
f"Score: {result.get('score')}%\n"
|
| 125 |
+
f"Correct: {result.get('correct_count')}/{result.get('total_attempted')}\n"
|
| 126 |
+
f"Message: {result.get('message')}"
|
|
|
|
| 127 |
)
|
| 128 |
|
| 129 |
+
return status, pd.DataFrame(results)
|
| 130 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
except Exception as e:
|
| 132 |
+
return f"Submission failed: {e}", pd.DataFrame(results)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 133 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 134 |
|
| 135 |
+
# Gradio UI
|
| 136 |
+
with gr.Blocks() as demo:
|
| 137 |
+
gr.Markdown("# My Agent Evaluation")
|
| 138 |
+
gr.Markdown("Login and click the button to run the evaluation.")
|
| 139 |
+
|
| 140 |
gr.LoginButton()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 141 |
|
| 142 |
+
run_btn = gr.Button("Run Evaluation & Submit")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
|
| 144 |
+
status = gr.Textbox(label="Status", lines=5)
|
| 145 |
+
table = gr.DataFrame(label="Results", wrap=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 146 |
|
| 147 |
+
run_btn.click(fn=run_and_submit_all, outputs=[status, table])
|
| 148 |
+
|
| 149 |
+
if __name__ == "__main__":
|
| 150 |
+
print("Starting app...")
|
| 151 |
+
demo.launch()
|