File size: 1,504 Bytes
fd18d93 8fe992b 86008b5 8fe992b 86008b5 8fe992b 86008b5 | 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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | from typing import Any, Optional
from smolagents.tools import Tool
from ddgs import DDGS
class DuckDuckGoSearchTool(Tool):
name = "web_search"
description = (
"Searches the web for relevant sources. "
"Returns titles, URLs, and snippets from search results."
)
inputs = {
"query": {
"type": "string",
"description": "The web search query.",
}
}
output_type = "string"
def __init__(self, max_results=10, **kwargs):
super().__init__()
self.max_results = max_results
self.ddgs = DDGS(**kwargs)
def forward(self, query: str) -> str:
try:
results = list(
self.ddgs.text(
query,
max_results=self.max_results,
)
)
if not results:
return (
f"No search results were returned for: {query}. "
"Try a broader or differently worded query."
)
formatted = []
for result in results:
title = result.get("title", "Untitled")
url = result.get("href", "")
body = result.get("body", "")
formatted.append(
f"[{title}]({url})\n{body}"
)
return "## Search Results\n\n" + "\n\n".join(formatted)
except Exception as e:
return f"Search failed for '{query}': {e}"
|