Team Ai
Apppublic

memoryoverflow/First_agent_template

sourceHugging Faceupdated 2y agoView on Hugging Face
0likes
web_search.py45 linesDownload Raw Back to tools
1from smolagents.tools import Tool2 3class DuckDuckGoSearchTool(Tool):4    name = "web_search"5    description = """Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results."""6    inputs = {7        "query": {"type": "string", "description": "The search query to perform."},8        "search_type": {"type": "string", "description": "The type of search: 'text' or 'image' (default: 'text').", "nullable": True}9    }10    output_type = "string"11 12    def __init__(self, max_results=10, **kwargs):13        super().__init__()14        self.max_results = max_results15        try:16            from duckduckgo_search import DDGS17        except ImportError as e:18            raise ImportError(19                "You must install package `duckduckgo_search` to run this tool: for instance run `pip install duckduckgo-search`."20            ) from e21        self.ddgs = DDGS(**kwargs)22 23    def forward(self, query: str, search_type="text") -> str:24        if search_type == "image":25            results = list(self.ddgs.images(query, max_results=self.max_results))26            if not results:27                return "no images found"28            return results29        30        results = self.ddgs.text(query, max_results=self.max_results)31        if len(results) == 0:32            raise Exception("No results found! Try a less restrictive/shorter query.")33        postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" for result in results]34        return "## Search Results\n\n" + "\n\n".join(postprocessed_results)35 36TOOL_MAPPING = {37    tool_class.name: tool_class38    for tool_class in [39        DuckDuckGoSearchTool,40    ]41}42 43__all__ = [44    "DuckDuckGoSearchTool"45]