Spaces:
Sleeping
Sleeping
File size: 1,735 Bytes
adf4599 8fe992b 2b5d52f 7c6e2dd 8fe992b adf4599 8fe992b 7c6e2dd adf4599 2b5d52f 73f6a3d 8fe992b 2b5d52f 8fe992b adf4599 5feb0eb adf4599 5feb0eb 2b5d52f 5feb0eb adf4599 5feb0eb adf4599 185a3f4 adf4599 185a3f4 adf4599 185a3f4 adf4599 5feb0eb 54c64a8 2b5d52f 7c6e2dd |
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 |
from typing import Any
from smolagents.tools import Tool
from ddgs import DDGS
import json
class DuckDuckGoSearchTool(Tool):
name = "web_search"
description = "Performs a DuckDuckGo web search based on your query and returns an array of {title, url, snippet}"
inputs: dict[str, dict[str, Any]] = {
"query": {"type": "string", "description": "The search query to perform."}
}
output_type = "string" # switched to "json" as this smolagents version supports it
def __init__(self, max_results: int = 10, **kwargs: Any) -> None:
super().__init__()
self.max_results = max_results
self.ddgs = DDGS(**kwargs)
def forward(self, query: str) -> list[dict[str, str]]:
q = (query or "").strip()
if not q:
raise ValueError("Query must be a non-empty string.")
items = list(
self.ddgs.text(
keywords=q,
region="wt-wt",
safesearch="moderate",
timelimit=None,
max_results=self.max_results,
)
)
if not items:
raise RuntimeError("No results found. Try a broader/simpler query.")
results: list[dict[str, str]] = []
for it in items:
href = (it.get("href") or "").strip()
if not href:
continue
results.append(
{
"title": str(it.get("title", "")),
"url": href,
"snippet": str(it.get("body", "")),
}
)
if not results:
raise RuntimeError("Results were returned but none contained valid URLs.")
return json.dumps(results)
|