Skip to content
Solo build2026

Agent Harness

Streaming agent runtime behind the portfolio guide

Last updated
Oct 2026
Primary language
Python
https://github.com/rk4rohankumar/learn-ai
Agent Harness preview

Overview

A from-scratch harness for running LLM agents, with no framework underneath. A FastAPI service owns the generation loop: it streams typed events to a Next.js client over SSE, executes registered tools between model turns, and lets the client cancel a generation while it is still running. Conversations and generations persist through SQLAlchemy, so a session resumes with its full tool history. The LLM layer is provider-neutral, with an Anthropic adapter and a deterministic mock. A separate stateless endpoint now powers the portfolio guide, with answers grounded in verified public notes.

Role
Solo build
Year
2026
Stack
PythonFastAPISQLAlchemyPostgreSQLAnthropic APINext.jsTypeScriptServer-Sent Events

Architecture

persistNext.js clientrenders typed eventsFastAPISSE · cancel mid-streamGenerationRunnermodel ↔ tool loop, max 10LLM adapterAnthropic · mockToolRegistrystatus · timing · errorsPostgreSQLprompts rebuilt from stateVisitor endpointstateless · the guide
Agent Harness: the streamed generation loop and what it persists

The problem

Agent frameworks hide the loop that matters: when the model asks for a tool, what runs, what gets persisted, and what happens when the user cancels halfway through a stream. I wanted every one of those seams visible and testable.

Decisions

  1. 01

    A capped async-generator loop instead of a framework

    GenerationRunner streams the model, detects tool calls, executes them through a ToolRegistry, submits the results and repeats, with a hard cap of 10 iterations so a confused model cannot spin forever.

  2. 02

    Prompts rebuilt from persisted state

    PromptBuilder derives every prompt purely from what is stored in PostgreSQL, so a run is replayable and a session resumes after a restart with its full tool history.

  3. 03

    Cancellation that cannot corrupt state

    Single-writer status columns, throttled cancel polling and partial-output persistence on client disconnect: a cancelled generation stops cleanly and keeps what it had already produced.

The hard part

Cancelling a stream without corrupting it

Cancellation looks like one button, but a generation is three things happening at once: the model is streaming tokens, a tool may be running between turns, and all of it is being written to PostgreSQL so the conversation can resume later. A cancel that lands in the wrong place leaves a generation marked as streaming forever, or a reply persisted as if it belonged to a finished turn. The problem was to let a cancel arrive at any moment and still end with a database that tells the truth.

The rule that made it tractable: a cancel is a request, not a status. The cancel endpoint writes exactly one column, a cancel-requested timestamp, and never touches the generation’s status. Only the runner writes status. Every column has a single writer, so two code paths can never fight over the same row, and the first timestamp wins, so repeated clicks are harmless. The endpoint answers from the status it finds: accepted if the run is still live, already finished if it is not.

The runner reads that timestamp through a throttled poller rather than on every token. Mid-stream it checks about twice a second, with a targeted single-column query instead of the ORM’s cached object, because the identity map would happily return the stale value it loaded when the run began. At the cheap, rare boundaries, the start of a model turn and the moment before the run is declared complete, it bypasses the throttle and asks again. Once the poller has seen a cancel it never un-sees it. That final forced check narrows the window in which a cancel and a completion can cross; a cancel that arrives after it loses, which is the right outcome, because the generation really did finish.

When a cancel wins, the runner stops the provider stream, persists whatever text had already arrived as the partial reply, marks the generation cancelled with its stop reason and token counts, and emits a typed cancelled event so the client’s tool-call cards and event inspector settle on the same state as the database. The implicit case gets the same treatment. If the client simply disconnects, a closed tab or a dropped connection, the response task is cancelled at the current yield and the handler walks the same terminal path without emitting anything, because nobody is listening. The variables that path needs are hoisted above the try block for exactly that reason, and the terminal write is committed on its own so a later rollback cannot undo it. The deterministic mock provider makes the whole sequence reproducible without an API key.

Outcome

A three-layer typed event stream (provider → application → wire), per-run telemetry for first-token latency, token usage and stop reason, and a Next.js client with live tool-call cards and a raw event inspector.

Status

In development since July 2026; public repository. The deterministic mock provider makes the whole loop testable without an API key.

Screenshots

Agent Harness chat: a weather tool call answered three times, then a fourth generation cancelled mid-stream; the raw SSE event log alongside shows text deltas, tool_started, tool_finished, done and cancelled events
Agent Harness chat: a weather tool call answered three times, then a fourth generation cancelled mid-stream; the raw SSE event log alongside shows text deltas, tool_started, tool_finished, done and cancelled events
Agent Harness with the conversation sidebar open: a resumed conversation replays its earlier tool result and follow-up, the event log listing conversation, tool_started, tool_finished, text and done events
Agent Harness with the conversation sidebar open: a resumed conversation replays its earlier tool result and follow-up, the event log listing conversation, tool_started, tool_finished, text and done events
Tool-calling demo from the repository README: the assistant calls a tool mid-answer and the inspector shows the typed events as they stream
Tool-calling demo from the repository README: the assistant calls a tool mid-answer and the inspector shows the typed events as they stream

What it does

  • Generation runner drives the model ↔ tool loop until the model stops, capped at 10 iterations
  • Tool registry returns structured executions with status, timing and errors
  • Typed SSE event stream: text deltas, tool started/finished, completed, cancelled
  • Conversations and generations persisted; sessions resume with full tool history
  • Stateless visitor endpoint for the portfolio guide with curated public portfolio context and streamed replies

Built with

PythonFastAPISQLAlchemyPostgreSQLAnthropic APINext.jsTypeScriptServer-Sent Events

Language mix

  • Python59.0%
  • TypeScript27.9%
  • HTML11.6%
  • CSS0.7%
  • JavaScript0.7%

Sourced from the repository on GitHub.