Spaces:
Runtime error
Runtime error
File size: 1,527 Bytes
53b1f1e |
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 |
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())
|