First_agent_template / tools /web_search.py
Realistvik0's picture
Update tools/web_search.py
86008b5 verified
Raw History Blame Contribute Delete
1.5 kB
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}"