Snaseem2026 commited on
Commit
64d5cdc
Β·
verified Β·
1 Parent(s): 9d6c66c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +156 -123
app.py CHANGED
@@ -2,66 +2,147 @@ import os
2
  import gradio as gr
3
  import requests
4
  import pandas as pd
5
- from smolagents import CodeAgent, DuckDuckGoSearchTool, VisitWebpageTool
6
- from smolagents.models import HfEngine
7
 
8
  # --- Constants ---
9
- DEFAULT_API_URL = "https://agents-course-unit4-scoring. hf.space"
10
 
11
- # --- Intelligent Agent with Tools ---
12
  class IntelligentAgent:
13
  def __init__(self):
14
- print("Initializing IntelligentAgent with tools...")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  try:
16
- # Initialize the model engine
17
- model = HfEngine(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
 
18
 
19
- # Initialize tools for web search and browsing
20
- search_tool = DuckDuckGoSearchTool()
21
- web_tool = VisitWebpageTool()
 
22
 
23
- # Create CodeAgent with tools
24
- self.agent = CodeAgent(
25
- tools=[search_tool, web_tool],
26
- model=model,
27
- max_steps=10,
28
- verbosity_level=1
29
- )
30
- print("Agent initialized successfully with search and web tools!")
31
  except Exception as e:
32
- print(f"Error initializing agent: {e}")
33
- self.agent = None
34
 
35
- def __call__(self, question: str) -> str:
36
- print(f"Agent received question: {question[:100]}...")
37
 
38
- if self. agent is None:
39
- return "Agent initialization failed."
 
 
 
 
 
 
 
 
 
 
40
 
41
- try:
42
- # Run the agent with the question
43
- result = self.agent. run(question)
44
- answer = str(result)
45
- print(f"Agent answer: {answer[: 200]}...")
46
- return answer
47
- except Exception as e:
48
- print(f"Error running agent: {e}")
49
- # Fallback: try to give a reasonable response
50
- return f"I encountered an error while processing this question."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  def run_and_submit_all(profile: gr.OAuthProfile | None):
53
  """
54
- Fetches all questions, runs the IntelligentAgent on them, submits all answers, and displays the results.
55
  """
56
  space_id = os.getenv("SPACE_ID")
57
 
58
- # Check if user is logged in
59
  if profile is None:
60
  print("User not logged in.")
61
  return "❌ Please login to Hugging Face using the button above.", None
62
 
63
  username = profile.username
64
- print(f"User logged in: {username}")
65
 
66
  api_url = DEFAULT_API_URL
67
  questions_url = f"{api_url}/questions"
@@ -71,53 +152,39 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
71
  print("Creating agent instance...")
72
  try:
73
  agent = IntelligentAgent()
74
- if agent. agent is None:
75
- return "❌ Failed to initialize agent. Please check logs.", None
76
  except Exception as e:
77
- print(f"Error instantiating agent: {e}")
78
  return f"Error initializing agent: {e}", None
79
 
80
- # Build agent code URL
81
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
82
  print(f"Agent code: {agent_code}")
83
 
84
  # 2. Fetch Questions
85
- print(f"Fetching questions from: {questions_url}")
86
  try:
87
  response = requests.get(questions_url, timeout=30)
88
  response.raise_for_status()
89
  questions_data = response.json()
90
  if not questions_data:
91
- print("Fetched questions list is empty.")
92
- return "Fetched questions list is empty or invalid format.", None
93
  print(f"βœ… Fetched {len(questions_data)} questions.")
94
- except requests.exceptions.RequestException as e:
95
- print(f"Error fetching questions: {e}")
96
- return f"Error fetching questions: {e}", None
97
- except requests.exceptions.JSONDecodeError as e:
98
- print(f"Error decoding JSON response from questions endpoint: {e}")
99
- print(f"Response text: {response. text[: 500]}")
100
- return f"Error decoding server response for questions: {e}", None
101
  except Exception as e:
102
- print(f"An unexpected error occurred fetching questions: {e}")
103
- return f"An unexpected error occurred fetching questions: {e}", None
104
 
105
- # 3. Run your Agent on each question
106
  results_log = []
107
  answers_payload = []
108
  print(f"\nπŸ€– Running agent on {len(questions_data)} questions...")
109
- print("=" * 60)
110
 
111
  for idx, item in enumerate(questions_data, 1):
112
  task_id = item.get("task_id")
113
  question_text = item.get("question")
114
 
115
  if not task_id or question_text is None:
116
- print(f"⚠️ Skipping item with missing task_id or question: {item}")
117
  continue
118
 
119
- print(f"\n[{idx}/{len(questions_data)}] Processing task: {task_id}")
120
- print(f"Question: {question_text[: 100]}...")
121
 
122
  try:
123
  answer = agent(question_text)
@@ -126,50 +193,34 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
126
  "submitted_answer": answer
127
  })
128
  results_log.append((task_id, question_text[:50], answer[:100]))
129
- print(f"βœ… Answer generated: {answer[:100]}...")
130
- except Exception as e:
131
- print(f"❌ Error running agent on question {task_id}: {e}")
132
- error_answer = "I apologize, but I encountered an error processing this question."
133
- answers_payload. append({
134
  "task_id": task_id,
135
- "submitted_answer": error_answer
136
  })
137
- results_log. append((task_id, question_text[:50], f"Error: {e}"))
138
-
139
- print("\n" + "=" * 60)
140
- print(f"βœ… Completed processing all questions!")
141
 
142
  # 4. Submit answers
143
- print(f"\nπŸ“€ Submitting {len(answers_payload)} answers to {submit_url}...")
144
  try:
145
  payload = {
146
  "username": username,
147
  "answers": answers_payload,
148
- "agent_code": agent_code
149
  }
150
 
151
- submit_response = requests.post(
152
- submit_url,
153
- json=payload,
154
- timeout=60
155
- )
156
- submit_response. raise_for_status()
157
- submission_result = submit_response. json()
158
- print(f"βœ… Submission successful: {submission_result}")
159
- except requests.exceptions.HTTPError as e:
160
- print(f"❌ HTTP Error submitting answers: {e}")
161
- print(f"Response text: {submit_response. text[:500]}")
162
- return f"Error submitting answers: {e}\n\nResponse: {submit_response.text[:200]}", None
163
  except Exception as e:
164
- print(f"❌ Error submitting answers: {e}")
165
  return f"Error submitting answers: {e}", None
166
 
167
  # Display results
168
  results_df = pd.DataFrame(results_log, columns=["task_id", "question", "answer"])
169
-
170
- # Extract score from submission result
171
  score = submission_result.get('score', 'N/A')
172
- total_questions = len(answers_payload)
173
 
174
  result_message = f"""
175
  ## πŸŽ‰ Submission Successful!
@@ -177,62 +228,44 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
177
  ### πŸ“Š Your Results:
178
  - **Score:** {score}
179
  - **Username:** {username}
180
- - **Questions Answered:** {total_questions}
181
 
182
  ### πŸ† Score Breakdown:
183
  - βœ… **Pass Threshold:** 30%
184
  - πŸ“ˆ **Your Score:** {score}
185
 
186
- {f"πŸŽ“ **Congratulations! You passed Unit 4! **" if isinstance(score, (int, float)) and score >= 30 else "πŸ“š Keep improving your agent to reach 30%! "}
187
 
188
  ### πŸ”— Links:
189
- - [View Your Agent Code]({agent_code})
190
  - [Course Unit 4](https://huggingface.co/learn/agents-course/en/unit4/hands-on)
191
-
192
- ---
193
- *Agent powered by smolagents with DuckDuckGo Search & Web Browsing*
194
  """
195
 
196
  return result_message, results_df
197
 
198
- # --- Gradio UI Setup ---
199
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
200
- gr.Markdown("""
201
  # πŸ€– Intelligent Agent - Unit 4 Final Assignment
202
 
203
- This agent uses **smolagents** with:
204
- - πŸ” **DuckDuckGo Search** - for finding information on the web
205
- - 🌐 **Web Page Visitor** - for reading webpage content
206
- - 🧠 **Code Agent** - for reasoning and executing Python code
207
 
208
  ## πŸ“‹ Instructions:
209
- 1. βœ… Click "Sign in with Hugging Face" below
210
- 2. πŸš€ Click "Run Evaluation & Submit All Answers"
211
- 3. ⏳ Wait for your score (this may take a few minutes)
212
 
213
- **Target:** Get 30% or higher to pass Unit 4!
214
  """)
215
 
216
- with gr.Row():
217
- gr.LoginButton()
218
-
219
- with gr.Row():
220
- submit_button = gr.Button(
221
- "πŸš€ Run Evaluation & Submit All Answers",
222
- variant="primary",
223
- size="lg"
224
- )
225
-
226
- with gr.Row():
227
- output_text = gr. Markdown()
228
-
229
- with gr.Row():
230
- output_table = gr.Dataframe(label="πŸ“ Detailed Results", wrap=True)
231
-
232
- submit_button.click(
233
- run_and_submit_all,
234
- inputs=None,
235
- outputs=[output_text, output_table]
236
- )
237
 
238
  demo.launch()
 
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
+ # --- Intelligent Agent with Web Search ---
10
  class IntelligentAgent:
11
  def __init__(self):
12
+ print("Initializing IntelligentAgent...")
13
+ self.search_tool = self._create_search_function()
14
+
15
+ def _create_search_function(self):
16
+ """Create a simple DuckDuckGo search function"""
17
+ try:
18
+ from duckduckgo_search import DDGS
19
+ return DDGS()
20
+ except:
21
+ return None
22
+
23
+ def search_web(self, query: str, max_results: int = 5) -> str:
24
+ """Search the web using DuckDuckGo"""
25
+ if self.search_tool is None:
26
+ return "Search unavailable"
27
+
28
  try:
29
+ results = list(self.search_tool. text(query, max_results=max_results))
30
+ if not results:
31
+ return "No results found"
32
 
33
+ # Format results
34
+ formatted = []
35
+ for i, r in enumerate(results[: max_results], 1):
36
+ formatted.append(f"{i}. {r. get('title', 'N/A')}: {r.get('body', 'N/A')}")
37
 
38
+ return "\n\n".join(formatted)
 
 
 
 
 
 
 
39
  except Exception as e:
40
+ print(f"Search error: {e}")
41
+ return "Search failed"
42
 
43
+ def __call__(self, question: str) -> str:
44
+ print(f"Processing question: {question[:100]}...")
45
 
46
+ # For questions that likely need web search
47
+ if any(keyword in question.lower() for keyword in ['current', 'latest', 'recent', 'today', 'now', '2024', '2025', '2026']):
48
+ print("Searching web for current information...")
49
+ search_results = self.search_web(question, max_results=3)
50
+
51
+ # Try to extract relevant answer from search results
52
+ if search_results and search_results != "No results found":
53
+ # Return first meaningful snippet
54
+ lines = search_results.split('\n')
55
+ for line in lines:
56
+ if len(line) > 20:
57
+ return line[:500]
58
 
59
+ # Basic knowledge-based responses
60
+ question_lower = question.lower()
61
+
62
+ # Geography
63
+ if "capital" in question_lower:
64
+ capitals = {
65
+ "france": "Paris", "germany": "Berlin", "italy": "Rome",
66
+ "spain": "Madrid", "japan": "Tokyo", "china": "Beijing",
67
+ "india": "New Delhi", "brazil": "BrasΓ­lia", "canada": "Ottawa",
68
+ "australia": "Canberra", "russia": "Moscow", "uk": "London",
69
+ "united kingdom": "London", "usa": "Washington, D.C.",
70
+ "united states": "Washington, D.C.", "mexico": "Mexico City"
71
+ }
72
+ for country, capital in capitals.items():
73
+ if country in question_lower:
74
+ return capital
75
+
76
+ # Companies and CEOs
77
+ if "ceo" in question_lower or "chief executive" in question_lower:
78
+ ceos = {
79
+ "tesla": "Elon Musk", "spacex": "Elon Musk", "apple": "Tim Cook",
80
+ "microsoft": "Satya Nadella", "google": "Sundar Pichai",
81
+ "amazon": "Andy Jassy", "meta": "Mark Zuckerberg",
82
+ "facebook": "Mark Zuckerberg", "nvidia": "Jensen Huang"
83
+ }
84
+ for company, ceo in ceos.items():
85
+ if company in question_lower:
86
+ return ceo
87
+
88
+ # Historical dates
89
+ if "when" in question_lower or "what year" in question_lower:
90
+ events = {
91
+ "world war 2": "1939-1945", "world war ii": "1939-1945", "wwii": "1939-1945",
92
+ "world war 1": "1914-1918", "world war i": "1914-1918", "wwi": "1914-1918",
93
+ "moon landing": "1969", "first moon landing": "1969",
94
+ "declared independence": "1776", "independence america": "1776"
95
+ }
96
+ for event, date in events.items():
97
+ if event in question_lower:
98
+ return date
99
+
100
+ # Counting questions
101
+ if "how many" in question_lower:
102
+ counts = {
103
+ "planets": "8", "continents": "7", "oceans": "5",
104
+ "days in a week": "7", "months": "12", "states in usa": "50",
105
+ "states in us": "50"
106
+ }
107
+ for thing, count in counts.items():
108
+ if thing in question_lower:
109
+ return count
110
+
111
+ # Math questions
112
+ if any(op in question for op in ['+', '-', '*', '/', 'Γ—', 'Γ·']):
113
+ try:
114
+ # Simple eval for basic math (be careful with this in production!)
115
+ result = eval(question. replace('Γ—', '*').replace('Γ·', '/'))
116
+ return str(result)
117
+ except:
118
+ pass
119
+
120
+ # Try web search as fallback
121
+ print("Using web search as fallback...")
122
+ search_results = self.search_web(question, max_results=3)
123
+ if search_results and "No results found" not in search_results:
124
+ # Extract first meaningful content
125
+ lines = search_results.split('\n')
126
+ for line in lines:
127
+ if len(line. strip()) > 30:
128
+ # Return cleaned up snippet
129
+ return line. strip()[:500]
130
+
131
+ # Final fallback
132
+ return "I don't have enough information to answer this question accurately."
133
 
134
  def run_and_submit_all(profile: gr.OAuthProfile | None):
135
  """
136
+ Fetches all questions, runs the IntelligentAgent on them, submits all answers, and displays the results.
137
  """
138
  space_id = os.getenv("SPACE_ID")
139
 
 
140
  if profile is None:
141
  print("User not logged in.")
142
  return "❌ Please login to Hugging Face using the button above.", None
143
 
144
  username = profile.username
145
+ print(f"User logged in: {username}")
146
 
147
  api_url = DEFAULT_API_URL
148
  questions_url = f"{api_url}/questions"
 
152
  print("Creating agent instance...")
153
  try:
154
  agent = IntelligentAgent()
 
 
155
  except Exception as e:
156
+ print(f"Error instantiating agent: {e}")
157
  return f"Error initializing agent: {e}", None
158
 
 
159
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
160
  print(f"Agent code: {agent_code}")
161
 
162
  # 2. Fetch Questions
163
+ print(f"Fetching questions from: {questions_url}")
164
  try:
165
  response = requests.get(questions_url, timeout=30)
166
  response.raise_for_status()
167
  questions_data = response.json()
168
  if not questions_data:
169
+ return "Fetched questions list is empty.", None
 
170
  print(f"βœ… Fetched {len(questions_data)} questions.")
 
 
 
 
 
 
 
171
  except Exception as e:
172
+ print(f"Error fetching questions: {e}")
173
+ return f"Error fetching questions: {e}", None
174
 
175
+ # 3. Run Agent
176
  results_log = []
177
  answers_payload = []
178
  print(f"\nπŸ€– Running agent on {len(questions_data)} questions...")
 
179
 
180
  for idx, item in enumerate(questions_data, 1):
181
  task_id = item.get("task_id")
182
  question_text = item.get("question")
183
 
184
  if not task_id or question_text is None:
 
185
  continue
186
 
187
+ print(f"\n[{idx}/{len(questions_data)}] Task: {task_id}")
 
188
 
189
  try:
190
  answer = agent(question_text)
 
193
  "submitted_answer": answer
194
  })
195
  results_log.append((task_id, question_text[:50], answer[:100]))
196
+ print(f"βœ… Answer: {answer[:100]}")
197
+ except Exception as e:
198
+ print(f"❌ Error: {e}")
199
+ answers_payload.append({
 
200
  "task_id": task_id,
201
+ "submitted_answer": "Error processing question"
202
  })
 
 
 
 
203
 
204
  # 4. Submit answers
205
+ print(f"\nπŸ“€ Submitting {len(answers_payload)} answers...")
206
  try:
207
  payload = {
208
  "username": username,
209
  "answers": answers_payload,
210
+ "agent_code": agent_code
211
  }
212
 
213
+ submit_response = requests. post(submit_url, json=payload, timeout=60)
214
+ submit_response.raise_for_status()
215
+ submission_result = submit_response.json()
216
+ print(f"βœ… Submission successful: {submission_result}")
 
 
 
 
 
 
 
 
217
  except Exception as e:
218
+ print(f"❌ Error submitting: {e}")
219
  return f"Error submitting answers: {e}", None
220
 
221
  # Display results
222
  results_df = pd.DataFrame(results_log, columns=["task_id", "question", "answer"])
 
 
223
  score = submission_result.get('score', 'N/A')
 
224
 
225
  result_message = f"""
226
  ## πŸŽ‰ Submission Successful!
 
228
  ### πŸ“Š Your Results:
229
  - **Score:** {score}
230
  - **Username:** {username}
231
+ - **Questions Answered:** {len(answers_payload)}
232
 
233
  ### πŸ† Score Breakdown:
234
  - βœ… **Pass Threshold:** 30%
235
  - πŸ“ˆ **Your Score:** {score}
236
 
237
+ {f"πŸŽ“ **Congratulations! You passed Unit 4! **" if isinstance(score, (int, float)) and score >= 30 else "πŸ“š Keep improving to reach 30%! "}
238
 
239
  ### πŸ”— Links:
240
+ - [View Your Code]({agent_code})
241
  - [Course Unit 4](https://huggingface.co/learn/agents-course/en/unit4/hands-on)
 
 
 
242
  """
243
 
244
  return result_message, results_df
245
 
246
+ # --- Gradio UI ---
247
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
248
+ gr. Markdown("""
249
  # πŸ€– Intelligent Agent - Unit 4 Final Assignment
250
 
251
+ This agent uses:
252
+ - πŸ” **DuckDuckGo Search** for web information
253
+ - 🧠 **Knowledge Base** for common questions
254
+ - 🎯 **Smart fallbacks** for better coverage
255
 
256
  ## πŸ“‹ Instructions:
257
+ 1. βœ… Sign in with Hugging Face
258
+ 2. πŸš€ Click "Run Evaluation & Submit"
259
+ 3. ⏳ Wait for your score
260
 
261
+ **Target:** 30% or higher to pass!
262
  """)
263
 
264
+ gr.LoginButton()
265
+ submit_button = gr.Button("πŸš€ Run Evaluation & Submit All Answers", variant="primary", size="lg")
266
+ output_text = gr.Markdown()
267
+ output_table = gr. Dataframe(label="πŸ“ Results", wrap=True)
268
+
269
+ submit_button.click(run_and_submit_all, inputs=None, outputs=[output_text, output_table])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
270
 
271
  demo.launch()