Update app.py
Browse files
app.py
CHANGED
|
@@ -2,62 +2,55 @@ import os
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
|
|
|
| 5 |
|
| 6 |
# --- Constants ---
|
| 7 |
-
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 8 |
|
| 9 |
-
# ---
|
| 10 |
-
class
|
| 11 |
def __init__(self):
|
| 12 |
-
print("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
def __call__(self, question:
|
| 15 |
-
print(f"Agent received question
|
| 16 |
-
|
| 17 |
-
# Basic intelligent response system
|
| 18 |
-
question_lower = question.lower()
|
| 19 |
-
|
| 20 |
-
# Try to provide context-aware answers
|
| 21 |
-
if "capital" in question_lower:
|
| 22 |
-
if "france" in question_lower:
|
| 23 |
-
return "Paris"
|
| 24 |
-
elif "germany" in question_lower:
|
| 25 |
-
return "Berlin"
|
| 26 |
-
elif "italy" in question_lower:
|
| 27 |
-
return "Rome"
|
| 28 |
-
elif "spain" in question_lower:
|
| 29 |
-
return "Madrid"
|
| 30 |
-
elif "japan" in question_lower:
|
| 31 |
-
return "Tokyo"
|
| 32 |
-
|
| 33 |
-
if "who" in question_lower and "ceo" in question_lower:
|
| 34 |
-
if "tesla" in question_lower or "spacex" in question_lower:
|
| 35 |
-
return "Elon Musk"
|
| 36 |
-
elif "apple" in question_lower:
|
| 37 |
-
return "Tim Cook"
|
| 38 |
-
elif "microsoft" in question_lower:
|
| 39 |
-
return "Satya Nadella"
|
| 40 |
-
|
| 41 |
-
if "what year" in question_lower or "when" in question_lower:
|
| 42 |
-
if "world war 2" in question_lower or "wwii" in question_lower:
|
| 43 |
-
return "1939-1945"
|
| 44 |
-
elif "world war 1" in question_lower or "wwi" in question_lower:
|
| 45 |
-
return "1914-1918"
|
| 46 |
|
| 47 |
-
if
|
| 48 |
-
|
| 49 |
-
return "8"
|
| 50 |
-
elif "continents" in question_lower:
|
| 51 |
-
return "7"
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 57 |
|
| 58 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 59 |
"""
|
| 60 |
-
Fetches all questions, runs the
|
| 61 |
"""
|
| 62 |
space_id = os.getenv("SPACE_ID")
|
| 63 |
|
|
@@ -74,132 +67,167 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 74 |
submit_url = f"{api_url}/submit"
|
| 75 |
|
| 76 |
# 1. Instantiate Agent
|
| 77 |
-
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
| 79 |
except Exception as e:
|
| 80 |
print(f"Error instantiating agent: {e}")
|
| 81 |
return f"Error initializing agent: {e}", None
|
| 82 |
|
| 83 |
# Build agent code URL
|
| 84 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 85 |
-
print(f"Agent code:
|
| 86 |
|
| 87 |
# 2. Fetch Questions
|
| 88 |
-
print(f"Fetching questions from:
|
| 89 |
try:
|
| 90 |
-
response = requests.get(questions_url, timeout=
|
| 91 |
response.raise_for_status()
|
| 92 |
questions_data = response.json()
|
| 93 |
if not questions_data:
|
| 94 |
print("Fetched questions list is empty.")
|
| 95 |
return "Fetched questions list is empty or invalid format.", None
|
| 96 |
-
print(f"Fetched {len(questions_data)} questions.")
|
| 97 |
-
except requests.
|
| 98 |
print(f"Error fetching questions: {e}")
|
| 99 |
return f"Error fetching questions: {e}", None
|
| 100 |
-
except requests.
|
| 101 |
-
print(f"Error decoding JSON response from questions endpoint:
|
| 102 |
print(f"Response text: {response.text[: 500]}")
|
| 103 |
return f"Error decoding server response for questions: {e}", None
|
| 104 |
except Exception as e:
|
| 105 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 106 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 107 |
|
| 108 |
-
# 3. Run your Agent
|
| 109 |
results_log = []
|
| 110 |
answers_payload = []
|
| 111 |
-
print(f"Running agent on {len(questions_data)} questions...")
|
| 112 |
-
|
|
|
|
|
|
|
| 113 |
task_id = item.get("task_id")
|
| 114 |
question_text = item.get("question")
|
| 115 |
-
|
| 116 |
-
|
|
|
|
| 117 |
continue
|
| 118 |
|
|
|
|
|
|
|
|
|
|
| 119 |
try:
|
| 120 |
answer = agent(question_text)
|
| 121 |
-
|
| 122 |
-
answers_payload. append({
|
| 123 |
"task_id": task_id,
|
| 124 |
"submitted_answer": answer
|
| 125 |
})
|
| 126 |
-
results_log.append((task_id, question_text[: 50], answer[:
|
|
|
|
| 127 |
except Exception as e:
|
| 128 |
-
print(f"Error running agent on question {task_id}: {e}")
|
|
|
|
| 129 |
answers_payload.append({
|
| 130 |
"task_id": task_id,
|
| 131 |
-
"submitted_answer":
|
| 132 |
})
|
| 133 |
results_log.append((task_id, question_text[: 50], f"Error: {e}"))
|
| 134 |
|
| 135 |
-
|
| 136 |
-
print(f"
|
|
|
|
|
|
|
|
|
|
| 137 |
try:
|
| 138 |
-
# Correct payload format
|
| 139 |
payload = {
|
| 140 |
"username": username,
|
| 141 |
"answers": answers_payload,
|
| 142 |
"agent_code": agent_code
|
| 143 |
}
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
submit_response = requests. post(
|
| 148 |
submit_url,
|
| 149 |
json=payload,
|
| 150 |
-
timeout=
|
| 151 |
)
|
| 152 |
submit_response.raise_for_status()
|
| 153 |
submission_result = submit_response.json()
|
| 154 |
-
print(f"Submission successful: {submission_result}")
|
| 155 |
except requests.exceptions.HTTPError as e:
|
| 156 |
-
print(f"HTTP Error submitting answers: {e}")
|
| 157 |
-
print(f"Response text: {submit_response.text[:
|
| 158 |
return f"Error submitting answers: {e}\n\nResponse: {submit_response.text[:200]}", None
|
| 159 |
-
except Exception as e:
|
| 160 |
-
print(f"Error submitting answers: {e}")
|
| 161 |
return f"Error submitting answers: {e}", None
|
| 162 |
|
| 163 |
# Display results
|
| 164 |
-
results_df = pd.
|
| 165 |
|
| 166 |
# Extract score from submission result
|
| 167 |
score = submission_result.get('score', 'N/A')
|
|
|
|
|
|
|
| 168 |
result_message = f"""
|
| 169 |
-
##
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 170 |
|
| 171 |
-
|
|
|
|
|
|
|
| 172 |
|
| 173 |
-
**
|
| 174 |
|
| 175 |
-
|
|
|
|
|
|
|
| 176 |
|
| 177 |
-
|
|
|
|
| 178 |
"""
|
| 179 |
|
| 180 |
return result_message, results_df
|
| 181 |
|
| 182 |
# --- Gradio UI Setup ---
|
| 183 |
-
with gr.Blocks() as demo:
|
| 184 |
gr.Markdown("""
|
| 185 |
-
# π€ Agent
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
-
|
| 188 |
-
1. Click
|
| 189 |
-
2.
|
| 190 |
-
3. Wait for your score
|
|
|
|
|
|
|
| 191 |
""")
|
| 192 |
|
| 193 |
with gr.Row():
|
| 194 |
gr.LoginButton()
|
| 195 |
|
| 196 |
with gr.Row():
|
| 197 |
-
submit_button = gr.Button(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
# The profile is automatically injected when using gr.LoginButton()
|
| 203 |
submit_button.click(
|
| 204 |
run_and_submit_all,
|
| 205 |
inputs=None,
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
import requests
|
| 4 |
import pandas as pd
|
| 5 |
+
from smolagents import CodeAgent, HfApiModel, DuckDuckGoSearchTool, VisitWebpageTool
|
| 6 |
|
| 7 |
# --- Constants ---
|
| 8 |
+
DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
| 9 |
|
| 10 |
+
# --- Intelligent Agent with Tools ---
|
| 11 |
+
class IntelligentAgent:
|
| 12 |
def __init__(self):
|
| 13 |
+
print("Initializing IntelligentAgent with tools...")
|
| 14 |
+
try:
|
| 15 |
+
# Initialize the model (uses Qwen model on HF Inference)
|
| 16 |
+
model = HfApiModel()
|
| 17 |
+
|
| 18 |
+
# Initialize tools for web search and browsing
|
| 19 |
+
search_tool = DuckDuckGoSearchTool()
|
| 20 |
+
web_tool = VisitWebpageTool()
|
| 21 |
+
|
| 22 |
+
# Create CodeAgent with tools
|
| 23 |
+
self.agent = CodeAgent(
|
| 24 |
+
tools=[search_tool, web_tool],
|
| 25 |
+
model=model,
|
| 26 |
+
max_steps=10,
|
| 27 |
+
verbosity_level=1
|
| 28 |
+
)
|
| 29 |
+
print("Agent initialized successfully with search and web tools!")
|
| 30 |
+
except Exception as e:
|
| 31 |
+
print(f"Error initializing agent: {e}")
|
| 32 |
+
self.agent = None
|
| 33 |
|
| 34 |
+
def __call__(self, question: str) -> str:
|
| 35 |
+
print(f"Agent received question: {question[:100]}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
if self.agent is None:
|
| 38 |
+
return "Agent initialization failed."
|
|
|
|
|
|
|
|
|
|
| 39 |
|
| 40 |
+
try:
|
| 41 |
+
# Run the agent with the question
|
| 42 |
+
result = self.agent. run(question)
|
| 43 |
+
answer = str(result)
|
| 44 |
+
print(f"Agent answer: {answer[:200]}...")
|
| 45 |
+
return answer
|
| 46 |
+
except Exception as e:
|
| 47 |
+
print(f"Error running agent: {e}")
|
| 48 |
+
# Fallback: try to give a reasonable response
|
| 49 |
+
return f"I encountered an error while processing this question. Error: {str(e)}"
|
| 50 |
|
| 51 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 52 |
"""
|
| 53 |
+
Fetches all questions, runs the IntelligentAgent on them, submits all answers, and displays the results.
|
| 54 |
"""
|
| 55 |
space_id = os.getenv("SPACE_ID")
|
| 56 |
|
|
|
|
| 67 |
submit_url = f"{api_url}/submit"
|
| 68 |
|
| 69 |
# 1. Instantiate Agent
|
| 70 |
+
print("Creating agent instance...")
|
| 71 |
+
try:
|
| 72 |
+
agent = IntelligentAgent()
|
| 73 |
+
if agent. agent is None:
|
| 74 |
+
return "β Failed to initialize agent. Please check logs.", None
|
| 75 |
except Exception as e:
|
| 76 |
print(f"Error instantiating agent: {e}")
|
| 77 |
return f"Error initializing agent: {e}", None
|
| 78 |
|
| 79 |
# Build agent code URL
|
| 80 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
| 81 |
+
print(f"Agent code: {agent_code}")
|
| 82 |
|
| 83 |
# 2. Fetch Questions
|
| 84 |
+
print(f"Fetching questions from: {questions_url}")
|
| 85 |
try:
|
| 86 |
+
response = requests.get(questions_url, timeout=30)
|
| 87 |
response.raise_for_status()
|
| 88 |
questions_data = response.json()
|
| 89 |
if not questions_data:
|
| 90 |
print("Fetched questions list is empty.")
|
| 91 |
return "Fetched questions list is empty or invalid format.", None
|
| 92 |
+
print(f"β
Fetched {len(questions_data)} questions.")
|
| 93 |
+
except requests.exceptions.RequestException as e:
|
| 94 |
print(f"Error fetching questions: {e}")
|
| 95 |
return f"Error fetching questions: {e}", None
|
| 96 |
+
except requests.exceptions.JSONDecodeError as e:
|
| 97 |
+
print(f"Error decoding JSON response from questions endpoint: {e}")
|
| 98 |
print(f"Response text: {response.text[: 500]}")
|
| 99 |
return f"Error decoding server response for questions: {e}", None
|
| 100 |
except Exception as e:
|
| 101 |
print(f"An unexpected error occurred fetching questions: {e}")
|
| 102 |
return f"An unexpected error occurred fetching questions: {e}", None
|
| 103 |
|
| 104 |
+
# 3. Run your Agent on each question
|
| 105 |
results_log = []
|
| 106 |
answers_payload = []
|
| 107 |
+
print(f"\nπ€ Running agent on {len(questions_data)} questions...")
|
| 108 |
+
print("=" * 60)
|
| 109 |
+
|
| 110 |
+
for idx, item in enumerate(questions_data, 1):
|
| 111 |
task_id = item.get("task_id")
|
| 112 |
question_text = item.get("question")
|
| 113 |
+
|
| 114 |
+
if not task_id or question_text is None:
|
| 115 |
+
print(f"β οΈ Skipping item with missing task_id or question: {item}")
|
| 116 |
continue
|
| 117 |
|
| 118 |
+
print(f"\n[{idx}/{len(questions_data)}] Processing task: {task_id}")
|
| 119 |
+
print(f"Question: {question_text[: 100]}...")
|
| 120 |
+
|
| 121 |
try:
|
| 122 |
answer = agent(question_text)
|
| 123 |
+
answers_payload.append({
|
|
|
|
| 124 |
"task_id": task_id,
|
| 125 |
"submitted_answer": answer
|
| 126 |
})
|
| 127 |
+
results_log.append((task_id, question_text[: 50], answer[:100]))
|
| 128 |
+
print(f"β
Answer generated: {answer[:100]}...")
|
| 129 |
except Exception as e:
|
| 130 |
+
print(f"β Error running agent on question {task_id}: {e}")
|
| 131 |
+
error_answer = "I apologize, but I encountered an error processing this question."
|
| 132 |
answers_payload.append({
|
| 133 |
"task_id": task_id,
|
| 134 |
+
"submitted_answer": error_answer
|
| 135 |
})
|
| 136 |
results_log.append((task_id, question_text[: 50], f"Error: {e}"))
|
| 137 |
|
| 138 |
+
print("\n" + "=" * 60)
|
| 139 |
+
print(f"β
Completed processing all questions!")
|
| 140 |
+
|
| 141 |
+
# 4. Submit answers
|
| 142 |
+
print(f"\nπ€ Submitting {len(answers_payload)} answers to {submit_url}...")
|
| 143 |
try:
|
|
|
|
| 144 |
payload = {
|
| 145 |
"username": username,
|
| 146 |
"answers": answers_payload,
|
| 147 |
"agent_code": agent_code
|
| 148 |
}
|
| 149 |
|
| 150 |
+
submit_response = requests.post(
|
|
|
|
|
|
|
| 151 |
submit_url,
|
| 152 |
json=payload,
|
| 153 |
+
timeout=60
|
| 154 |
)
|
| 155 |
submit_response.raise_for_status()
|
| 156 |
submission_result = submit_response.json()
|
| 157 |
+
print(f"β
Submission successful: {submission_result}")
|
| 158 |
except requests.exceptions.HTTPError as e:
|
| 159 |
+
print(f"β HTTP Error submitting answers: {e}")
|
| 160 |
+
print(f"Response text: {submit_response.text[:500]}")
|
| 161 |
return f"Error submitting answers: {e}\n\nResponse: {submit_response.text[:200]}", None
|
| 162 |
+
except Exception as e:
|
| 163 |
+
print(f"β Error submitting answers: {e}")
|
| 164 |
return f"Error submitting answers: {e}", None
|
| 165 |
|
| 166 |
# Display results
|
| 167 |
+
results_df = pd.DataFrame(results_log, columns=["task_id", "question", "answer"])
|
| 168 |
|
| 169 |
# Extract score from submission result
|
| 170 |
score = submission_result.get('score', 'N/A')
|
| 171 |
+
total_questions = len(answers_payload)
|
| 172 |
+
|
| 173 |
result_message = f"""
|
| 174 |
+
## π Submission Successful!
|
| 175 |
+
|
| 176 |
+
### π Your Results:
|
| 177 |
+
- **Score:** {score}
|
| 178 |
+
- **Username:** {username}
|
| 179 |
+
- **Questions Answered:** {total_questions}
|
| 180 |
|
| 181 |
+
### π Score Breakdown:
|
| 182 |
+
- β
**Pass Threshold:** 30%
|
| 183 |
+
- π **Your Score:** {score}
|
| 184 |
|
| 185 |
+
{f"π **Congratulations! You passed Unit 4! **" if isinstance(score, (int, float)) and score >= 30 else "π Keep improving your agent to reach 30%! "}
|
| 186 |
|
| 187 |
+
### π Links:
|
| 188 |
+
- [View Your Agent Code]({agent_code})
|
| 189 |
+
- [Course Unit 4](https://huggingface.co/learn/agents-course/en/unit4/hands-on)
|
| 190 |
|
| 191 |
+
---
|
| 192 |
+
*Agent powered by smolagents with DuckDuckGo Search & Web Browsing*
|
| 193 |
"""
|
| 194 |
|
| 195 |
return result_message, results_df
|
| 196 |
|
| 197 |
# --- Gradio UI Setup ---
|
| 198 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 199 |
gr.Markdown("""
|
| 200 |
+
# π€ Intelligent Agent - Unit 4 Final Assignment
|
| 201 |
+
|
| 202 |
+
This agent uses **smolagents** with:
|
| 203 |
+
- π **DuckDuckGo Search** - for finding information on the web
|
| 204 |
+
- π **Web Page Visitor** - for reading webpage content
|
| 205 |
+
- π§ **Code Agent** - for reasoning and executing Python code
|
| 206 |
|
| 207 |
+
## π Instructions:
|
| 208 |
+
1. β
Click "Sign in with Hugging Face" below
|
| 209 |
+
2. π Click "Run Evaluation & Submit All Answers"
|
| 210 |
+
3. β³ Wait for your score (this may take a few minutes)
|
| 211 |
+
|
| 212 |
+
**Target:** Get 30% or higher to pass Unit 4!
|
| 213 |
""")
|
| 214 |
|
| 215 |
with gr.Row():
|
| 216 |
gr.LoginButton()
|
| 217 |
|
| 218 |
with gr.Row():
|
| 219 |
+
submit_button = gr.Button(
|
| 220 |
+
"π Run Evaluation & Submit All Answers",
|
| 221 |
+
variant="primary",
|
| 222 |
+
size="lg"
|
| 223 |
+
)
|
| 224 |
|
| 225 |
+
with gr.Row():
|
| 226 |
+
output_text = gr.Markdown()
|
| 227 |
+
|
| 228 |
+
with gr.Row():
|
| 229 |
+
output_table = gr. Dataframe(label="π Detailed Results", wrap=True)
|
| 230 |
|
|
|
|
| 231 |
submit_button.click(
|
| 232 |
run_and_submit_all,
|
| 233 |
inputs=None,
|