First_agent_template / tools /web_search.py
rnrahate007's picture
Update tools/web_search.py
a8fc2f1 verified
Raw
History Blame Contribute Delete
1.97 kB
from typing import List
from smolagents.tools import Tool
class DuckDuckGoSearchTool(Tool):
"""
Performs a DuckDuckGo web search and returns formatted search results.
"""
name = "web_search"
description = (
"Searches the web using DuckDuckGo and returns the most relevant "
"search results. Use this whenever factual or current information "
"is required."
)
inputs = {
"query": {
"type": "string",
"description": "Search query."
}
}
output_type = "string"
def __init__(self, max_results: int = 5):
super().__init__()
self.max_results = max_results
try:
from ddgs import DDGS
self.ddgs = DDGS()
except ImportError as e:
raise ImportError(
"Install ddgs using:\n\npip install ddgs"
) from e
def forward(self, query: str) -> str:
queries = [
query,
query + " wikipedia",
query + " official",
query.replace("-", " "),
]
seen = set()
formatted = []
for q in queries:
try:
results = list(
self.ddgs.text(
q,
max_results=3
)
)
except Exception:
continue
for result in results:
url = result.get("href", "")
if url in seen:
continue
seen.add(url)
title = result.get("title", "No title")
snippet = result.get("body", "")
formatted.append(
f"""
Title:
{title}
URL:
{url}
Snippet:
{snippet}
"""
)
if len(formatted) >= 5:
break
if not formatted:
return "No useful search results were found."
return "\n".join(formatted[:5])