File size: 1,463 Bytes
fd18d93
8fe992b
 
 
 
 
 
 
 
 
 
 
 
4dea240
 
8fe992b
4dea240
 
 
 
 
 
 
8fe992b
 
 
4dea240
8fe992b
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from typing import Any, Optional
from smolagents.tools import Tool

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:
            # Preferred package name (new)
            from ddgs import DDGS
        except ImportError as e:
            try:
                # Backward-compatible fallback (old package name)
                from duckduckgo_search import DDGS
            except ImportError as inner_e:
                raise ImportError(
                    "You must install package `ddgs` (or legacy `duckduckgo_search`) to run this tool: for instance run `pip install ddgs`."
                ) from inner_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.")
        postprocessed_results = [f"[{result['title']}]({result['href']})\n{result['body']}" for result in results]
        return "## Search Results\n\n" + "\n\n".join(postprocessed_results)