Final_Assignment_Template / web_search.py
Realistvik0's picture
Create web_search.py
b8fcd64 verified
Raw History Blame
1.43 kB
from smolagents import Tool
from ddgs import DDGS
class WebSearchTool(Tool):
name = "web_search"
description = (
"Searches the web for relevant information. "
"Use this to find sources, facts, dates, statistics, "
"and other information needed to answer the question. "
"Search results include titles, URLs, and snippets."
)
inputs = {
"query": {
"type": "string",
"description": "The search query to run.",
}
}
output_type = "string"
def __init__(self, max_results=8):
super().__init__()
self.max_results = max_results
def forward(self, query: str) -> str:
try:
results = list(
DDGS().text(
query,
max_results=self.max_results,
)
)
if not results:
return "No search results found."
output = []
for result in results:
title = result.get("title", "Untitled")
url = result.get("href", "")
body = result.get("body", "")
output.append(
f"TITLE: {title}\n"
f"URL: {url}\n"
f"SNIPPET: {body}"
)
return "\n\n".join(output)
except Exception as e:
return f"Search failed: {e}"