from typing import Any from smolagents.tools import Tool from duckduckgo_search import DDGS import re class DuckDuckGoSearchTool(Tool): name = "web_search" description = "Performs a web search and returns the top results." inputs = {'query': {'type': 'string', 'description': 'The search query'}} output_type = "string" def __init__(self, max_results=5, **kwargs): self.max_results = max_results self.ddgs = DDGS() super().__init__() def forward(self, query: str) -> str: if not query or len(query.strip()) < 3: return "Error: Search query too short" try: results = self.ddgs.text(query, max_results=self.max_results) if not results: return "No results found" formatted = [f"[{r['title']}]({r['href']})\n{r['body']}" for r in results] return "## Search Results\n\n" + "\n\n".join(formatted) except Exception as e: return f"Search failed: {str(e)}"