File size: 1,053 Bytes
8070b95
8fe992b
e82bf33
8070b95
8fe992b
 
 
e82bf33
 
8fe992b
 
8070b95
8fe992b
e82bf33
8070b95
8fe992b
 
8070b95
 
 
 
e82bf33
8070b95
 
 
 
 
 
 
 
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
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)}"