-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathhackernews.py
More file actions
executable file
·284 lines (217 loc) · 9.26 KB
/
Copy pathhackernews.py
File metadata and controls
executable file
·284 lines (217 loc) · 9.26 KB
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
from autohive_integrations_sdk import (
ActionError,
Integration,
ExecutionContext,
ActionHandler,
ActionResult,
)
from typing import Dict, Any, List, Optional
from datetime import datetime, timezone
import asyncio
hackernews = Integration.load()
BASE_URL = "https://hacker-news.firebaseio.com/v0"
HN_ITEM_URL = "https://news.ycombinator.com/item?id="
HN_USER_URL = "https://news.ycombinator.com/user?id="
async def fetch_json(context: ExecutionContext, url: str) -> Optional[Any]:
"""Fetch JSON from a URL, returning None on error."""
try:
response = await context.fetch(url, method="GET")
return response.data
except Exception:
return None
async def fetch_item(context: ExecutionContext, item_id: int) -> Optional[Dict[str, Any]]:
"""Fetch a single item by ID."""
return await fetch_json(context, f"{BASE_URL}/item/{item_id}.json")
async def fetch_items_batch(context: ExecutionContext, item_ids: List[int]) -> List[Dict[str, Any]]:
"""Fetch multiple items concurrently."""
tasks = [fetch_item(context, item_id) for item_id in item_ids]
results = await asyncio.gather(*tasks)
return [item for item in results if item is not None]
def format_item(item: Dict[str, Any]) -> Dict[str, Any]:
"""Format an item for LLM-friendly output."""
formatted = {
"id": item.get("id"),
"title": item.get("title"),
"type": item.get("type"),
"by": item.get("by"),
"score": item.get("score", 0),
"descendants": item.get("descendants", 0),
"hn_url": f"{HN_ITEM_URL}{item.get('id')}",
}
if item.get("time"):
formatted["time"] = datetime.fromtimestamp(item["time"], tz=timezone.utc).isoformat()
if item.get("url"):
formatted["url"] = item["url"]
if item.get("text"):
formatted["text"] = item["text"]
return formatted
def format_comment(item: Dict[str, Any], replies: List[Dict[str, Any]] = None) -> Optional[Dict[str, Any]]:
"""Format a comment for LLM-friendly output."""
if item.get("deleted") or item.get("dead"):
return None
formatted = {
"id": item.get("id"),
"by": item.get("by", "[deleted]"),
"text": item.get("text", ""),
}
if item.get("time"):
formatted["time"] = datetime.fromtimestamp(item["time"], tz=timezone.utc).isoformat()
if replies:
formatted["replies"] = replies
return formatted
async def fetch_comments_recursive(
context: ExecutionContext,
comment_ids: List[int],
limit: int,
current_depth: int,
max_depth: int,
) -> List[Dict[str, Any]]:
"""Recursively fetch comments up to a certain depth."""
if not comment_ids or current_depth > max_depth:
return []
limited_ids = comment_ids[:limit] if current_depth == 1 else comment_ids[:10]
comments = await fetch_items_batch(context, limited_ids)
result = []
for comment in comments:
if comment.get("deleted") or comment.get("dead"):
continue
replies = []
if current_depth < max_depth and comment.get("kids"):
replies = await fetch_comments_recursive(context, comment["kids"], limit, current_depth + 1, max_depth)
formatted = format_comment(comment, replies if replies else None)
if formatted:
result.append(formatted)
return result
async def fetch_stories_list(
context: ExecutionContext, endpoint: str, limit: int, output_key: str = "stories"
) -> Dict[str, Any]:
"""Generic function to fetch a list of stories from an endpoint."""
story_ids = await fetch_json(context, f"{BASE_URL}/{endpoint}.json")
if not story_ids:
return {
output_key: [],
"fetched_at": datetime.now(timezone.utc).isoformat(),
"count": 0,
}
limited_ids = story_ids[: min(limit, 100)]
items = await fetch_items_batch(context, limited_ids)
formatted_items = []
for item in items:
if item:
formatted_items.append(format_item(item))
return {
output_key: formatted_items,
"fetched_at": datetime.now(timezone.utc).isoformat(),
"count": len(formatted_items),
}
@hackernews.action("get_top_stories")
class GetTopStoriesAction(ActionHandler):
"""Fetch top stories from Hacker News."""
async def execute(self, inputs: Dict[str, Any], context: ExecutionContext) -> ActionResult:
try:
limit = inputs.get("limit", 30)
result = await fetch_stories_list(context, "topstories", limit)
return ActionResult(data=result, cost_usd=0.0)
except Exception as e:
return ActionError(message=str(e))
@hackernews.action("get_best_stories")
class GetBestStoriesAction(ActionHandler):
"""Fetch best stories from Hacker News."""
async def execute(self, inputs: Dict[str, Any], context: ExecutionContext) -> ActionResult:
try:
limit = inputs.get("limit", 30)
result = await fetch_stories_list(context, "beststories", limit)
return ActionResult(data=result, cost_usd=0.0)
except Exception as e:
return ActionError(message=str(e))
@hackernews.action("get_new_stories")
class GetNewStoriesAction(ActionHandler):
"""Fetch newest stories from Hacker News."""
async def execute(self, inputs: Dict[str, Any], context: ExecutionContext) -> ActionResult:
try:
limit = inputs.get("limit", 30)
result = await fetch_stories_list(context, "newstories", limit)
return ActionResult(data=result, cost_usd=0.0)
except Exception as e:
return ActionError(message=str(e))
@hackernews.action("get_ask_hn_stories")
class GetAskHNStoriesAction(ActionHandler):
"""Fetch Ask HN stories."""
async def execute(self, inputs: Dict[str, Any], context: ExecutionContext) -> ActionResult:
try:
limit = inputs.get("limit", 30)
result = await fetch_stories_list(context, "askstories", limit)
return ActionResult(data=result, cost_usd=0.0)
except Exception as e:
return ActionError(message=str(e))
@hackernews.action("get_show_hn_stories")
class GetShowHNStoriesAction(ActionHandler):
"""Fetch Show HN stories."""
async def execute(self, inputs: Dict[str, Any], context: ExecutionContext) -> ActionResult:
try:
limit = inputs.get("limit", 30)
result = await fetch_stories_list(context, "showstories", limit)
return ActionResult(data=result, cost_usd=0.0)
except Exception as e:
return ActionError(message=str(e))
@hackernews.action("get_job_stories")
class GetJobStoriesAction(ActionHandler):
"""Fetch job postings from Hacker News."""
async def execute(self, inputs: Dict[str, Any], context: ExecutionContext) -> ActionResult:
try:
limit = inputs.get("limit", 30)
result = await fetch_stories_list(context, "jobstories", limit, output_key="jobs")
return ActionResult(data=result, cost_usd=0.0)
except Exception as e:
return ActionError(message=str(e))
@hackernews.action("get_story_with_comments")
class GetStoryWithCommentsAction(ActionHandler):
"""Fetch a story with its comments."""
async def execute(self, inputs: Dict[str, Any], context: ExecutionContext) -> ActionResult:
try:
story_id = inputs["story_id"]
comment_limit = inputs.get("comment_limit", 20)
comment_depth = inputs.get("comment_depth", 2)
story = await fetch_item(context, story_id)
if not story:
return ActionError(message=f"Story with ID {story_id} not found")
comments = []
if story.get("kids"):
comments = await fetch_comments_recursive(
context,
story["kids"],
comment_limit,
current_depth=1,
max_depth=comment_depth,
)
return ActionResult(
data={
"story": format_item(story),
"comments": comments,
"fetched_at": datetime.now(timezone.utc).isoformat(),
},
cost_usd=0.0,
)
except Exception as e:
return ActionError(message=str(e))
@hackernews.action("get_user_profile")
class GetUserProfileAction(ActionHandler):
"""Fetch a user's public profile."""
async def execute(self, inputs: Dict[str, Any], context: ExecutionContext) -> ActionResult:
try:
username = inputs["username"]
user = await fetch_json(context, f"{BASE_URL}/user/{username}.json")
if not user:
return ActionError(message=f"User '{username}' not found")
result = {
"id": user.get("id"),
"karma": user.get("karma", 0),
"profile_url": f"{HN_USER_URL}{username}",
}
if user.get("created"):
result["created"] = datetime.fromtimestamp(user["created"], tz=timezone.utc).isoformat()
if user.get("about"):
result["about"] = user["about"]
return ActionResult(data=result, cost_usd=0.0)
except Exception as e:
return ActionError(message=str(e))