Sborole commited on
Commit
66c2582
·
verified ·
1 Parent(s): 1f276a5

Update tools/WebSearchTool.py

Browse files
Files changed (1) hide show
  1. tools/WebSearchTool.py +46 -48
tools/WebSearchTool.py CHANGED
@@ -1,17 +1,19 @@
1
- import requests
2
- from smolagents import Tool
3
  import os
4
- import json
 
 
5
 
6
- class SerpApiSearchTool(Tool):
7
  """
8
- A reliable web search tool using the SerpApi service, which wraps major
9
- search engines (like Google) to provide structured results. This is ideal
10
- for high reliability when keyless options are unstable.
11
  """
12
- name = "serpapi_search"
13
- description = "Use the reliable SerpApi to fetch current information from Google Search results. Requires an API key."
14
-
 
 
 
15
  inputs = {
16
  "query": {"type": "string", "description": "The search term to look up."}
17
  }
@@ -19,63 +21,59 @@ class SerpApiSearchTool(Tool):
19
 
20
  def __init__(self, **kwargs):
21
  super().__init__(**kwargs)
22
- # Retrieve API key from environment variables
23
- self.api_key = os.getenv("SERPAPI_KEY")
24
- self.endpoint = "https://serpapi.com/search"
25
 
26
- if not self.api_key:
27
- raise ValueError("SERPAPI_API_KEY secret not found. You need a key from the SerpApi free tier.")
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  def forward(self, query: str) -> str:
30
  """
31
- Executes a SerpApi search query and formats the top results (up to 3).
32
-
33
  Args:
34
  query: The search term provided by the agent.
35
-
36
  Returns:
37
  A formatted string of search results, or an error message.
38
  """
39
- print(f"Executing SerpApi Search for: '{query}'")
40
-
41
- params = {
42
- "api_key": self.api_key,
43
- "q": query,
44
- "num": 3, # Request up to 3 results
45
- "engine": "google", # Use Google search engine
46
- }
47
-
48
  try:
49
- # Make the API request
50
- response = requests.get(self.endpoint, params=params, timeout=10)
51
- response.raise_for_status()
52
- data = response.json()
 
 
53
 
54
- # Extract the organic results
55
- organic_results = data.get('organic_results', [])
56
 
57
- if not organic_results:
58
- # Check for a knowledge panel or featured snippet as a fallback
59
- featured_snippet = data.get('knowledge_graph', {}).get('description')
60
- if featured_snippet:
61
- return f"RESULT 1 (Featured Snippet): '{query}'\nCONTENT: {featured_snippet}\nSOURCE: Knowledge Panel"
62
-
63
- # If nothing useful is found:
64
  return "XX record info: No results found."
65
 
66
  search_results = []
67
- # Process the top 3 organic results
68
- for i, item in enumerate(organic_results[:3]):
69
  search_results.append(
70
- f"RESULT {i+1}: '{item.get('title', 'N/A')}'\n"
71
- f"CONTENT: {item.get('snippet', 'No snippet available.')}\n"
72
- f"SOURCE: {item.get('link', 'N/A')}"
73
  )
74
 
75
  # Join the results with a clear separator
76
  return "\n\n---SEPARATOR---\n\n".join(search_results)
77
 
78
- except requests.exceptions.RequestException as e:
79
- return f"Error during SerpApi Search API Request: {e}"
80
  except Exception as e:
81
- return f"Error processing SerpApi results: {e}"
 
 
 
 
1
  import os
2
+ from smolagents import Tool
3
+ # We use googleapiclient for the official Google Custom Search API
4
+ from googleapiclient.discovery import build
5
 
6
+ class GoogleSearchTool(Tool):
7
  """
8
+ A tool to perform web search Google searches using the Custom Search Engine (CSE) API.
9
+ Use this tool first to get the necessary information for calculation or further tools.
 
10
  """
11
+ # Use a descriptive name to guide the agent
12
+ name = "google_search"
13
+ # Reverting to a proper, concise tool description.
14
+ description = "Use Google to find current information and general knowledge. Returns a snippet and URL."
15
+
16
+ # Define the required input structure for the agent framework
17
  inputs = {
18
  "query": {"type": "string", "description": "The search term to look up."}
19
  }
 
21
 
22
  def __init__(self, **kwargs):
23
  super().__init__(**kwargs)
 
 
 
24
 
25
+ # Retrieve credentials from environment variables
26
+ # NOTE: This requires GOOGLE_API_KEY (the developer key) and GOOGLE_CSE_ID (the ID of your search engine)
27
+ self.api_key = os.getenv("GOOGLE_API_KEY")
28
+ self.cse_id = os.getenv("GOOGLE_CSE_ID")
29
+
30
+ # Check for mandatory credentials
31
+ if not self.api_key or not self.cse_id:
32
+ raise ValueError("GOOGLE_API_KEY or GOOGLE_CSE_ID secret not found. Check environment variables.")
33
+
34
+ # Initialize the Google Custom Search service
35
+ # 'customsearch' is the API name, 'v1' is the version
36
+ self.service = build(
37
+ "customsearch", "v1", developerKey=self.api_key
38
+ )
39
 
40
  def forward(self, query: str) -> str:
41
  """
42
+ Executes a Google search query and formats the top results (up to 3).
43
+
44
  Args:
45
  query: The search term provided by the agent.
46
+
47
  Returns:
48
  A formatted string of search results, or an error message.
49
  """
50
+ print(f"Executing Google search for: '{query}'")
 
 
 
 
 
 
 
 
51
  try:
52
+ # Execute the search request for up to 3 results
53
+ res = self.service.cse().list(
54
+ q=query,
55
+ cx=self.cse_id,
56
+ num=3
57
+ ).execute()
58
 
59
+ items = res.get('items', [])
 
60
 
61
+ if not items:
62
+ # Return the specific failure message expected by the agent
 
 
 
 
 
63
  return "XX record info: No results found."
64
 
65
  search_results = []
66
+ for i, item in enumerate(items):
67
+ # Formatting the output for clarity (Title, Content, Source URL)
68
  search_results.append(
69
+ f"RESULT {i+1}: '{item.get('title')}'\n"
70
+ f"CONTENT: {item.get('snippet')}\n"
71
+ f"SOURCE: {item.get('link')}"
72
  )
73
 
74
  # Join the results with a clear separator
75
  return "\n\n---SEPARATOR---\n\n".join(search_results)
76
 
 
 
77
  except Exception as e:
78
+ # Provide an informative error message upon API failure
79
+ return f"Error during Google Search API call: {e}"