Spaces:
Runtime error
Runtime error
Update tools/WebSearchTool.py
Browse files- 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
|
| 6 |
"""
|
| 7 |
-
A tool to perform web search
|
| 8 |
-
|
| 9 |
"""
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 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 |
-
|
| 25 |
-
|
| 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
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
try:
|
| 53 |
-
#
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
num=3
|
| 58 |
-
).execute()
|
| 59 |
|
| 60 |
-
|
|
|
|
| 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')}"
|
| 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 |
-
|
| 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}"
|
|
|