Spaces:
Sleeping
Sleeping
Create news.py
Browse files- tools/news.py +29 -0
tools/news.py
ADDED
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Optional
|
2 |
+
from smolagents.tools import Tool
|
3 |
+
|
4 |
+
class News(Tool):
|
5 |
+
name = "News"
|
6 |
+
description = "Fetches the latest NYTimes RSS feed and returns the headlines of the most recent 5 stories."
|
7 |
+
inputs = {} # This tool does not require any inputs.
|
8 |
+
output_type = "string"
|
9 |
+
|
10 |
+
def __init__(self, feed_url: str = "https://rss.nytimes.com/services/xml/rss/nyt/HomePage.xml", max_results: int = 5, **kwargs):
|
11 |
+
super().__init__()
|
12 |
+
self.feed_url = feed_url
|
13 |
+
self.max_results = max_results
|
14 |
+
try:
|
15 |
+
import feedparser
|
16 |
+
except ImportError as e:
|
17 |
+
raise ImportError(
|
18 |
+
"You must install package `feedparser` to run this tool: for instance run `pip install feedparser`."
|
19 |
+
) from e
|
20 |
+
self.feedparser = feedparser
|
21 |
+
|
22 |
+
def forward(self) -> str:
|
23 |
+
feed = self.feedparser.parse(self.feed_url)
|
24 |
+
if not feed.entries:
|
25 |
+
raise Exception("No entries found in the feed.")
|
26 |
+
latest_entries = feed.entries[:self.max_results]
|
27 |
+
headlines = [entry.title for entry in latest_entries]
|
28 |
+
result = "## NYTimes Latest Headlines\n\n" + "\n".join(f"- {headline}" for headline in headlines)
|
29 |
+
return result
|