First_agent_template / tools /fetch_news.py
l3xv's picture
implement pink glasses
53b1f1e
import re
from smolagents.tools import Tool
class FetchNewsTool(Tool):
"""
A tool that searches for the latest English news using DuckDuckGo.
"""
name = "fetch_news"
description = "Finds the latest English news using DuckDuckGo"
inputs = {}
output_type = "string"
def __init__(self, max_results=5, **kwargs):
super().__init__()
self.max_results = max_results
try:
from duckduckgo_search import DDGS
except ImportError as e:
raise ImportError(
"You must install package `duckduckgo_search` to run this tool: "
"for instance run `pip install duckduckgo-search`."
) from e
# Create a DuckDuckGoSearch instance with any kwargs needed
self.ddgs = DDGS(**kwargs)
def forward(self) -> str:
"""
1) Perform a DuckDuckGo search on 'latest news'.
2) Format each result with a "Headline #: ..." prefix.
3) Return all the headlines as one string, separated by newlines.
"""
results = self.ddgs.news("latest news", max_results=self.max_results)
if not results:
return "No results found, or unable to retrieve news at this time."
headlines = []
for i, item in enumerate(results, start=1):
snippet = f"{item['body']}"
headlines.append(snippet)
return " ".join(headlines)
# Example usage:
if __name__ == "__main__":
news = FetchNewsTool()
print(news.forward())