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