Spaces:
Runtime error
Runtime error
| from typing import Any, Optional | |
| from smolagents.tools import Tool | |
| import duckduckgo_search | |
| class DuckDuckGoSearchTool(Tool): | |
| name = "web_search" | |
| description = "Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results." | |
| inputs = { | |
| 'query': { | |
| 'type': 'string', | |
| 'description': 'The search query to perform.' | |
| } | |
| } | |
| output_type = "string" | |
| def __init__(self, max_results=10, **kwargs): | |
| super().__init__() | |
| self.max_results = max_results | |
| try: | |
| from duckduckgo_search import DDGS | |
| except ImportError as e: | |
| raise ImportError( | |
| "You must install package `duckduckgo_search` to run this tool: for instance run `pip install duckduckgo-search`." | |
| ) from e | |
| self.ddgs = DDGS(**kwargs) | |
| def forward(self, query: str) -> str: | |
| results = list(self.ddgs.text(query, max_results=self.max_results)) | |
| if len(results) == 0: | |
| raise Exception("No results found! Try a less restrictive/shorter query.") | |
| # Print result structure for debugging | |
| if results: | |
| print("Result keys:", results[0].keys()) | |
| postprocessed_results = [] | |
| for result in results: | |
| title = result.get('title', '') | |
| url = result.get('link', '') or result.get('href', '') | |
| body = result.get('body', '') or result.get('snippet', '') | |
| postprocessed_results.append(f"[{title}]({url})\n{body}") | |
| return "## Search Results\n\n" + "\n\n".join(postprocessed_results) |