Lesson 03.07 · Phase 03 · The Agent Loop

Streaming an agent's steps

Token streaming shows one reply as it's written. An agent needs more: which step it's on, what it's calling, what came back. Make the loop yield events.

Learning objectives

  • Turn the agent loop into a generator of typed events (stepstart, text, toolcall, toolresult, final, error).
  • Merge streamed tool-call fragments into complete calls.
  • Render one event stream in several ways: a terminal view, Server-Sent Events for a browser, and timing metrics.
  • Support cancellation (the consumer stops reading) and turn stream failures into events instead of tracebacks.

An agent run takes seconds to minutes. Phase 0 · Lesson 6 streamed the tokens of one reply, which helps for the final answer. But most of an agent's time isn't spent writing the final answer. It's spent deciding on tool calls, waiting for tools, and reading results. A token stream shows nothing during any of that.

Loading the full lesson…