Spaces:
Build error
Build error
| import os | |
| from smolagents.tools import Tool | |
| from serpapi import GoogleSearch | |
| from dotenv import load_dotenv | |
| class GoogleSearchTool(Tool): | |
| name = "google_search" | |
| description = "Perform a Google search and return the top 5 results as a string." | |
| inputs = {'query': {'type': 'string', 'description': 'The search query to perform.'}} | |
| output_type = "string" | |
| def __init__(self): | |
| super().__init__() | |
| load_dotenv() | |
| self.api_key = os.getenv("SERPAPI_API_KEY") | |
| if not self.api_key: | |
| raise ValueError("SerpAPI key is missing. Set 'SERPAPI_API_KEY' in environment variables.") | |
| def forward(self, query: str) -> str: | |
| params = { | |
| "q": query, | |
| "api_key": self.api_key, | |
| "num": 5 | |
| } | |
| search = GoogleSearch(params) | |
| results = search.get_dict().get("organic_results", []) | |
| if not results: | |
| return f"No search results found for '{query}'." | |
| formatted_results = [] | |
| for idx, result in enumerate(results): | |
| title = result.get("title", "No title") | |
| link = result.get("link", "No link") | |
| snippet = result.get("snippet", "No description available.") | |
| formatted_results.append(f"{idx+1}. {title}\n {snippet}\n {link}") | |
| return "\n\n".join(formatted_results) | |