Pacama95/chatbot_agent
0
1from typing import Any, Optional2from smolagents.tools import Tool3 4class DuckDuckGoSearchTool(Tool):5 name = "web_search"6 description = "Performs a duckduckgo web search based on your query (think a Google search) then returns the top search results."7 inputs = {'query': {'type': 'string', 'description': 'The search query to perform.'}}8 output_type = "string"9 10 def __init__(self, max_results=10, **kwargs):11 super().__init__()12 self.max_results = max_results13 try:14 from duckduckgo_search import DDGS15 except ImportError as e:16 raise ImportError(17 "You must install package `duckduckgo_search` to run this tool: for instance run `pip install duckduckgo-search`."18 ) from e19 self.ddgs = DDGS(**kwargs)20 21 def forward(self, query: str) -> str:22 results = self.ddgs.text(query, max_results=self.max_results)23 if len(results) == 0:24 raise Exception("No results found! Try a less restrictive/shorter query.")25 postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" for result in results]26 return "## Search Results\n\n" + "\n\n".join(postprocessed_results)27 