Sborole commited on
Commit
7268fdf
·
verified ·
1 Parent(s): 26c231b

Update tools/WebSearchTool.py

Browse files
Files changed (1) hide show
  1. tools/WebSearchTool.py +37 -44
tools/WebSearchTool.py CHANGED
@@ -1,18 +1,15 @@
1
  import os
 
2
  from smolagents import Tool
3
- from googleapiclient.discovery import build
4
 
5
- class GoogleSearchTool(Tool):
6
  """
7
- A tool to perform web search Google searches using the Custom Search Engine (CSE) API.
8
- Use this tool first to get the necessary information for calculation or further tools.
9
  """
10
- # Use a descriptive name to guide the agent
11
- name = "google_search"
12
- # Update the description to reflect the new functionality
13
- description = "Use Google to find current information and general knowledge. Returns a snippet and URL."
14
-
15
- # Define the required input structure for the agent framework
16
  inputs = {
17
  "query": {"type": "string", "description": "The search term to look up."}
18
  }
@@ -20,62 +17,58 @@ class GoogleSearchTool(Tool):
20
 
21
  def __init__(self, **kwargs):
22
  super().__init__(**kwargs)
 
 
23
 
24
- # Retrieve credentials from environment variables
25
- self.api_key = os.getenv("GOOGLE_API_KEY")
26
- self.cse_id = os.getenv("GOOGLE_CSE_ID")
27
-
28
- # Check for mandatory credentials
29
- if not self.api_key or not self.cse_id:
30
- raise ValueError("GOOGLE_API_KEY or GOOGLE_CSE_ID secret not found. Check environment variables.")
31
-
32
- # Initialize the Google Custom Search service
33
- # 'customsearch' is the API name, 'v1' is the version
34
- self.service = build(
35
- "customsearch", "v1", developerKey=self.api_key
36
- )
37
 
38
  def forward(self, query: str) -> str:
39
  """
40
- Executes a Google search query and formats the top results (up to 3).
41
-
42
- The output is formatted to prioritize the Title and Snippet (informational content)
43
- over the URL to address the confusion that it was only returning links.
44
-
45
  Args:
46
  query: The search term provided by the agent.
47
-
48
  Returns:
49
  A formatted string of search results, or an error message.
50
  """
51
- print(f"Executing Google search for: '{query}'")
 
 
 
 
 
 
 
 
 
52
  try:
53
- # Execute the search request for up to 3 results
54
- res = self.service.cse().list(
55
- q=query,
56
- cx=self.cse_id,
57
- num=3
58
- ).execute()
59
 
60
- items = res.get('items', [])
 
61
 
62
  if not items:
63
  # Return the specific failure message expected by the agent
64
  return "XX record info: No results found."
65
 
66
  search_results = []
 
67
  for i, item in enumerate(items):
68
- # We've adjusted the format here to put the snippet first,
69
- # which is usually the most important information for the agent.
70
  search_results.append(
71
- f"RESULT {i+1}: '{item.get('title')}'\n"
72
- f"CONTENT: {item.get('snippet')}\n"
73
- f"SOURCE: {item.get('link')}" # The URL is now clearly labeled as the SOURCE
74
  )
75
 
76
  # Join the results with a clear separator
77
  return "\n\n---SEPARATOR---\n\n".join(search_results)
78
 
 
 
79
  except Exception as e:
80
- # Provide an informative error message upon API failure
81
- return f"Error during Google Search API call: {e}"
 
1
  import os
2
+ import requests
3
  from smolagents import Tool
 
4
 
5
+ class SerpApiSearchTool(Tool):
6
  """
7
+ A tool to perform web search using the SerpApi engine.
8
+ This tool should be used to find current information and general knowledge.
9
  """
10
+ name = "serpapi_search"
11
+ description = "Use SerpApi to find current information and general knowledge. Returns a snippet and URL."
12
+
 
 
 
13
  inputs = {
14
  "query": {"type": "string", "description": "The search term to look up."}
15
  }
 
17
 
18
  def __init__(self, **kwargs):
19
  super().__init__(**kwargs)
20
+ # Retrieve API key from environment variables
21
+ self.api_key = os.getenv("SERPAPI_KEY")
22
 
23
+ if not self.api_key:
24
+ raise ValueError("SERPAPI_KEY secret not found. Check environment variables.")
 
 
 
 
 
 
 
 
 
 
 
25
 
26
  def forward(self, query: str) -> str:
27
  """
28
+ Executes a SerpApi search query and formats the top results (up to 3).
29
+
 
 
 
30
  Args:
31
  query: The search term provided by the agent.
32
+
33
  Returns:
34
  A formatted string of search results, or an error message.
35
  """
36
+ print(f"Executing SerpApi search for: '{query}'")
37
+
38
+ search_url = "https://serpapi.com/search"
39
+ params = {
40
+ "q": query,
41
+ "engine": "google", # Use Google search engine via SerpApi
42
+ "api_key": self.api_key,
43
+ "num": 3,
44
+ }
45
+
46
  try:
47
+ # Make the API request
48
+ response = requests.get(search_url, params=params)
49
+ response.raise_for_status() # Raise an exception for bad status codes (4xx or 5xx)
50
+ data = response.json()
 
 
51
 
52
+ # Extract the organic results
53
+ items = data.get('organic_results', [])
54
 
55
  if not items:
56
  # Return the specific failure message expected by the agent
57
  return "XX record info: No results found."
58
 
59
  search_results = []
60
+ # Process the top 3 results (since 'num=3' was requested)
61
  for i, item in enumerate(items):
 
 
62
  search_results.append(
63
+ f"RESULT {i+1}: '{item.get('title', 'N/A')}'\n"
64
+ f"CONTENT: {item.get('snippet', 'No snippet available.')}\n"
65
+ f"SOURCE: {item.get('link', 'N/A')}"
66
  )
67
 
68
  # Join the results with a clear separator
69
  return "\n\n---SEPARATOR---\n\n".join(search_results)
70
 
71
+ except requests.exceptions.RequestException as e:
72
+ return f"Error during SerpApi Request: {e}"
73
  except Exception as e:
74
+ return f"Error processing SerpApi results: {e}"