| | #!/usr/bin/env -S uv run --script | | | # /// script |
| | # requires-python = ">=3.14" |
| | # dependencies = [ |
| | # "httpx>=0.29", |
| | # "openai>=3.62", |
| | # "pydantic>=2.14", |
| | # "strands-agents[openai]>=1.68", |
| | # ] |
| | # /// |
| | """Summarize the most controversial stories on the Hacker News front page. |
| | The run follows observe -> decide -> apply -> report: |
| | - observe: fetch the front page and the comments of each story as State. |
| | - decide: GPT-6 Luna (Decisions API) scores how heated each discussion is and |
| | returns a Plan with the top stories. Changes nothing. |
| | - apply: a Strands agent on GPT-6.1 Terra reads the picked threads through the |
| | hn_comments tool and returns a Result holding the plan and digest. |
| | - report: print the result. |
| | Every function gets its dependencies as keyword arguments. main() is the |
| | composition root: it builds the clients, the tool and the agent, and wires |
| | them together. |
| | Run it with uv, which reads the inline metadata above (PEP 723), creates an |
| | isolated environment and installs the dependencies on first run: |
| | export OPENAI_API_KEY=sk-... |
| | uv run agent.py |
| | Or run it directly, through the shebang: |
| | chmod +x agent.py |
| | ./agent.py |
| | For repeatable installs, lock the dependencies next to the script. uv picks up |
| | agent.py.lock automatically on later runs: |
| | uv lock --script agent.py |
| | """ |
| | import asyncio |
| | import os |
| | import sys |
| | from dataclasses import asdict, dataclass |
| | from html.parser import HTMLParser |
| | from typing import Protocol, TextIO |
| | import httpx |
| | from openai import AsyncOpenAI |
| | from pydantic import BaseModel |
| | from strands import Agent, tool |
| | from strands.models.openai_responses import OpenAIResponsesModel |
| | HN_API = "https://hn.algolia.com/api/v1" |
| | SUMMARY_MODEL = "gpt-6.1-terra" |
| | DECISION_MODEL = "gpt-6-luna" |
| | FRONT_PAGE_SIZE = 30 | | | COMMENTS_PER_STORY = 50 | | | MAX_COMMENT_CHARS = 600 | | | TOP_N = 5 | | | CONTROVERSY_LEVELS = [ | | | { | | | "label": "Calm", | | | "description": "Commenters mostly agree or just share information.", | | | }, | | | { | | | "label": "Mixed", | | | "description": "Some disagreement, but the tone stays friendly.", | | | }, | | | { | | | "label": "Heated", | | | "description": "Clear camps argue, with sharp pushback.", | | | }, | | | { | | | "label": "Flame war", | | | "description": "Hostile, polarized arguing dominates the thread.", | | | }, | | | ] | | | SYSTEM_PROMPT = """\ | | | You summarize Hacker News discussions for a busy reader. | | | Read each story's comments with the hn_comments tool before you write about it. | | | """ | | | SUMMARY_PROMPT = """\ | | | Summarize these stories, in this order: | | | {stories} | | | For each one, write one sentence on what it's about. Then write two sentences | | | on what commenters disagree about and the mood of the thread. | | | """ | | | # --------------------------------------------------------------------------- | | | # Data |
| | # --------------------------------------------------------------------------- |
| | @dataclass(frozen=True) |
| | class Story: | | | """A front-page story and the comments observe read for it.""" | | | id: str | | | title: str | | | comments: list[str] | | | @property |
| | def url(self) -> str: |
| | return f"https://news.ycombinator.com/item?id={self.id}" |
| | @dataclass(frozen=True) |
| | class State: | | | """The current state observe hands to decide.""" |
| | stories: list[Story] |
| | @dataclass(frozen=True) |
| | class Verdict: | | | """Luna's controversy reading for one story.""" | | | story: Story | | | # Probability-weighted level index, from 0 (calm) to the top level. | | | score: float | | | # The single most likely level, like "Heated". | | | level: str | | | confidence: float | | | @dataclass(frozen=True) | | | class Plan: | | | """What decide hands to apply: the stories to summarize, most controversial first.""" | | | picks: list[Verdict] | | | # The highest level index, so a score can be shown as "2.3 / 3". | | | max_score: int |
| | def verdict_for(self, *, story_id: str) -> Verdict: |
| | return next(v for v in self.picks if v.story.id == story_id) |
| | class StorySummary(BaseModel): |
| | story_id: str | | | title: str | | | # One sentence on what the story is about. | | | about: str | | | # Two sentences on the disagreement and the mood of the thread. | | | debate: str |
| | class Digest(BaseModel): |
| | stories: list[StorySummary] |
| | @dataclass(frozen=True) |
| | class Result: | | | """What apply hands to report: the plan and the digest built from it.""" | | | plan: Plan | | | digest: Digest | | | class FetchComments(Protocol): | | | """Fetches up to N comments of one story. The hn_comments tool has this signature.""" |
| | async def __call__(self, *, story_id: str, limit: int = 50) -> list[str]: ... |
| | # --------------------------------------------------------------------------- |
| | # Tools |
| | # --------------------------------------------------------------------------- |
| | def make_hn_comments(*, http: httpx.AsyncClient, max_comment_chars: int): |
| | """Build the hn_comments tool around an injected HTTP client.""" |
| | @tool |
| | async def hn_comments(*, story_id: str, limit: int = 50) -> list[str]: |
| | """Return up to limit comments on a Hacker News story, replies included, in thread order. |
| | Args: |
| | story_id: The Hacker News item ID of the story. |
| | limit: The maximum number of comments to return. |
| | """ |
| | resp = await http.get(f"/items/{story_id}") |
| | resp.raise_for_status() |
| | story = resp.json() |
| | # Walk the comment tree depth-first, so each reply stays next to its parent. |
| | comments = [] |
| | stack = list(reversed(story["children"])) |
| | while stack and len(comments) < limit: |
| | node = stack.pop() |
| | if node.get("text"): |
| | comments.append( | | | strip_html(text=node["text"], max_chars=max_comment_chars) | | | ) | | | stack.extend(reversed(node["children"])) | | | return comments | | | return hn_comments | | | class TextExtractor(HTMLParser): | | | """Collect the text of an HTML fragment. Entities are decoded for us.""" |
| | def __init__(self) -> None: |
| | super().__init__(convert_charrefs=True) |
| | self.parts: list[str] = [] |
| | def handle_data(self, data: str) -> None: |
| | self.parts.append(data) |
| | def strip_html(*, text: str, max_chars: int) -> str: |
| | parser = TextExtractor() |
| | parser.feed(text) |
| | parser.close() |
| | # HN separates paragraphs with bare <p> tags, so join the parts with spaces. |
| | text = " ".join(" ".join(parser.parts).split()) |
| | return text[:max_chars] |
| | # --------------------------------------------------------------------------- |
| | # Observe, decide, apply, report | | | # --------------------------------------------------------------------------- | | | async def observe( | | | *, | | | http: httpx.AsyncClient, | | | fetch_comments: FetchComments, | | | front_page_size: int, | | | comments_per_story: int, |
| | ) -> State: |
| | resp = await http.get( |
| | "/search", | | | params={"tags": "front_page", "hitsPerPage": front_page_size}, | | | ) |
| | resp.raise_for_status() |
| | hits = resp.json()["hits"] |
| | async with asyncio.TaskGroup() as tg: |
| | tasks = [ |
| | tg.create_task( | | | fetch_comments(story_id=hit["objectID"], limit=comments_per_story) | | | ) | | | for hit in hits | | | ] |
| | stories = [ |
| | Story(id=hit["objectID"], title=hit["title"], comments=task.result()) |
| | for hit, task in zip(hits, tasks) | | | ] | | | return State(stories=stories) | | | async def decide( | | | *, | | | state: State, | | | openai: AsyncOpenAI, | | | model: str, | | | levels: list[dict], | | | top_n: int, | | | ) -> Plan: | | | # One Decisions request. All stories are the shared input, | | | # and each story gets its own score question. | | | questions = [ | | | { | | | "type": "score", | | | "name": story.id, | | | "instructions": ( | | | f"How controversial is the discussion on story {story.id} " | | | f"({story.title!r}), judging by how much commenters disagree " | | | "and how heated the mood is?" | | | ), | | | "levels": levels, | | | } | | | for story in state.stories | | | ] | | | response = await openai.decisions.create( | | | model=model, | | | input=[ | | | { | | | "role": "user", | | | "content": [ | | | { | | | "type": "input_text", | | | "text": "Hacker News front page stories with their comments.", | | | }, | | | { | | | "type": "input_json", | | | "data": [asdict(story) for story in state.stories], | | | }, | | | ], | | | } | | | ], | | | questions=questions, | | | ) |
| | stories_by_id = {story.id: story for story in state.stories} |
| | verdicts = [] |
| | for answer in response.answers: | | | # Luna can refuse a question. Those stories just don't get ranked. | | | if answer.type != "score": | | | continue | | | likeliest = max(answer.probabilities, key=lambda p: p.probability) | | | verdicts.append( | | | Verdict( | | | story=stories_by_id[answer.name], | | | score=answer.score, | | | level=likeliest.label, | | | confidence=answer.confidence, | | | ) | | | ) |
| | verdicts.sort(key=lambda v: v.score, reverse=True) |
| | return Plan(picks=verdicts[:top_n], max_score=len(levels) - 1) |
| | async def apply(*, plan: Plan, agent: Agent, prompt: str) -> Result: |
| | stories = "\n".join(f"- {v.story.id}: {v.story.title}" for v in plan.picks) |
| | response = await agent.invoke_async( | | | prompt.format(stories=stories), | | | structured_output_model=Digest, | | | ) |
| | return Result(plan=plan, digest=response.structured_output) |
| | def report(*, result: Result, out: TextIO) -> None: |
| | plan = result.plan | | | digest = result.digest | | | print( | | | f"# Most controversial on Hacker News right now (top {len(digest.stories)})", | | | file=out, | | | ) |
| | print(file=out) |
| | for rank, summary in enumerate(digest.stories, start=1): |
| | verdict = plan.verdict_for(story_id=summary.story_id) |
| | print(f"## {rank}. {verdict.story.title}", file=out) |
| | print( |
| | f"Controversy: {verdict.level}, {verdict.score:.2f} / {plan.max_score} " |
| | f"(confidence {verdict.confidence:.2f})", |
| | file=out, | | | ) |
| | print(verdict.story.url, file=out) |
| | print(file=out) |
| | print(summary.about, summary.debate, file=out) |
| | print(file=out) |
| | async def reconcile( | | | *, | | | http: httpx.AsyncClient, | | | openai: AsyncOpenAI, | | | agent: Agent, | | | fetch_comments: FetchComments, | | | out: TextIO, | | | decision_model: str, | | | controversy_levels: list[dict], | | | summary_prompt: str, | | | front_page_size: int, | | | comments_per_story: int, | | | top_n: int, |
| | ) -> None: |
| | state = await observe( |
| | http=http, | | | fetch_comments=fetch_comments, | | | front_page_size=front_page_size, | | | comments_per_story=comments_per_story, | | | ) | | | plan = await decide( # returns data, changes nothing | | | state=state, | | | openai=openai, | | | model=decision_model, | | | levels=controversy_levels, | | | top_n=top_n, | | | ) |
| | result = await apply(plan=plan, agent=agent, prompt=summary_prompt) |
| | report(result=result, out=out) |
| | # --------------------------------------------------------------------------- |
| | # Composition root |
| | # --------------------------------------------------------------------------- |
| | async def main() -> None: |
| | api_key = os.environ.get("OPENAI_API_KEY", "").strip() |
| | if not api_key: | | | sys.exit("error: OPENAI_API_KEY is not set") | | | async with ( |
| | httpx.AsyncClient(base_url=HN_API, timeout=20) as http, |
| | AsyncOpenAI(api_key=api_key) as openai, |
| | ): |
| | hn_comments = make_hn_comments(http=http, max_comment_chars=MAX_COMMENT_CHARS) |
| | agent = Agent( |
| | model=OpenAIResponsesModel(client=openai, model_id=SUMMARY_MODEL), |
| | tools=[hn_comments], |
| | system_prompt=SYSTEM_PROMPT, | | | callback_handler=None, | | | ) | | | await reconcile( | | | http=http, | | | openai=openai, | | | agent=agent, | | | fetch_comments=hn_comments, | | | out=sys.stdout, | | | decision_model=DECISION_MODEL, | | | controversy_levels=CONTROVERSY_LEVELS, | | | summary_prompt=SUMMARY_PROMPT, | | | front_page_size=FRONT_PAGE_SIZE, | | | comments_per_story=COMMENTS_PER_STORY, | | | top_n=TOP_N, | | | ) |
| | if __name__ == "__main__": |
| | asyncio.run(main()) |