Carolzinha2010 commited on
Commit
c345b27
·
verified ·
1 Parent(s): 81917a3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -6
app.py CHANGED
@@ -3,6 +3,8 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
@@ -10,14 +12,113 @@ 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
  def run_and_submit_all( profile: gr.OAuthProfile | None):
23
  """
@@ -91,7 +192,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
91
  print("Agent did not produce any answers to submit.")
92
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
93
 
94
- # 4. Prepare Submission
95
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
96
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
97
  print(status_update)
@@ -138,6 +239,15 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
138
  print(status_message)
139
  results_df = pd.DataFrame(results_log)
140
  return status_message, results_df
 
 
 
 
 
 
 
 
 
141
 
142
 
143
  # --- Build Gradio Interface using Blocks ---
@@ -193,4 +303,5 @@ if __name__ == "__main__":
193
  print("-"*(60 + len(" App Starting ")) + "\n")
194
 
195
  print("Launching Gradio Interface for Basic Agent Evaluation...")
196
- demo.launch(debug=True, share=False)
 
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ from bs4 import BeautifulSoup
7
+ import requests
8
 
9
  # (Keep Constants as is)
10
  # --- Constants ---
 
12
 
13
  # --- Basic Agent Definition ---
14
  # ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
15
+
16
+
17
+ def web_search(query: str) -> list[dict]:
18
+ """
19
+ Performs a web search and returns relevant information.
20
+
21
+ Args:
22
+ query: The search query string.
23
+
24
+ Returns:
25
+ A list of dictionaries, where each dictionary represents a search result
26
+ with keys 'title', 'snippet', and 'url'. Returns an empty list if no
27
+ results are found or an error occurs.
28
+ """
29
+ search_url = f"https://www.google.com/search?q={requests.utils.quote(query)}"
30
+ headers = {
31
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36"
32
+ }
33
+ results = []
34
+
35
+ try:
36
+ response = requests.get(search_url, headers=headers, timeout=10)
37
+ response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
38
+
39
+ soup = BeautifulSoup(response.text, 'html.parser')
40
+
41
+ # Find search results - this is a basic example and might need adjustment
42
+ # based on Google's ever-changing HTML structure.
43
+ # 'div.tF2CMy' is a common class for result blocks as of certain dates.
44
+ search_results = soup.select('div.tF2CMy')
45
+
46
+ if not search_results:
47
+ # Fallback or alternative selectors if the primary one fails
48
+ search_results = soup.select('div.g') # Another common class
49
+
50
+ for result in search_results:
51
+ link = result.select_one('a')
52
+ title = result.select_one('h3')
53
+ snippet = result.select_one('span.aCOpNe') # Example snippet class
54
+
55
+ if link and title:
56
+ item = {
57
+ 'title': title.get_text(),
58
+ 'url': link['href'],
59
+ 'snippet': snippet.get_text() if snippet else 'No snippet available'
60
+ }
61
+ results.append(item)
62
+
63
+ except requests.exceptions.RequestException as e:
64
+ print(f"Error during web search request: {e}")
65
+ except Exception as e:
66
+ print(f"An unexpected error occurred during web search: {e}")
67
+
68
+ return results
69
+
70
+ # Example usage (optional, for testing)
71
+ # search_results = web_search("what is the capital of France?")
72
+ # for i, result in enumerate(search_results[:3]): # Print first 3 results
73
+ # print(f"--- Result {i+1} ---")
74
+ # print(f"Title: {result.get('title', 'N/A')}")
75
+ # print(f"URL: {result.get('url', 'N/A')}")
76
+ # print(f"Snippet: {result.get('snippet', 'N/A')}")
77
+ # print("-" * 10)
78
+
79
  class BasicAgent:
80
+ def __init__(self):
81
  print("BasicAgent initialized.")
82
+
83
  def __call__(self, question: str) -> str:
84
  print(f"Agent received question (first 50 chars): {question[:50]}...")
85
+
86
+ # Simple logic to determine if a web search is needed
87
+ question_lower = question.lower()
88
+ search_keywords = ["what is", "how to", "where is", "who is", "when did", "define", "explain", "tell me about"]
89
+ needs_search = any(keyword in question_lower for keyword in search_keywords) or "?" in question
90
+
91
+ if needs_search:
92
+ print(f"Question likely requires search. Searching for: {question}")
93
+ search_results = web_search(question) # Call the web_search function
94
+
95
+ if search_results:
96
+ # Process search results to formulate an answer
97
+ answer_parts = []
98
+ for i, result in enumerate(search_results[:3]): # Use top 3 results
99
+ if result.get('snippet'):
100
+ answer_parts.append(f"Snippet {i+1}: {result['snippet']}")
101
+ elif result.get('title'):
102
+ answer_parts.append(f"Result {i+1} Title: {result['title']}")
103
+
104
+
105
+ if answer_parts:
106
+ formulated_answer = "Based on web search:\n" + "\n".join(answer_parts)
107
+ print(f"Agent returning search-based answer: {formulated_answer[:100]}...")
108
+ return formulated_answer
109
+ else:
110
+ print("Web search returned results but no useful snippets/titles found.")
111
+ return "I couldn't find a specific answer from the web search results."
112
+
113
+ else:
114
+ print("Web search returned no results.")
115
+ return "I couldn't find any relevant information on the web for your question."
116
+ else:
117
+ # If no search is needed, return a default or simple response
118
+ print("Question does not appear to require search. Returning fixed answer.")
119
+ fixed_answer = "How can I help you?"
120
+ return fixed_answer
121
+
122
 
123
  def run_and_submit_all( profile: gr.OAuthProfile | None):
124
  """
 
192
  print("Agent did not produce any answers to submit.")
193
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
194
 
195
+ # 4. Prepare Submission
196
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
197
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
198
  print(status_update)
 
239
  print(status_message)
240
  results_df = pd.DataFrame(results_log)
241
  return status_message, results_df
242
+
243
+ def __init__(self):
244
+ print("BasicAgent initialized.")
245
+ def __call__(self, question: str) -> str:
246
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
247
+ fixed_answer = "How i can help you?"
248
+ print(f"Agent returning fixed answer: {fixed_answer}")
249
+ return fixed_answer
250
+
251
 
252
 
253
  # --- Build Gradio Interface using Blocks ---
 
303
  print("-"*(60 + len(" App Starting ")) + "\n")
304
 
305
  print("Launching Gradio Interface for Basic Agent Evaluation...")
306
+ demo.launch(debug=True, share=False)7
307
+