方寸 Portal

AI Engineer Portal

Your personal operating system for career transition.

Private mode

Exercise

Stream LLM responses with progress callbacks

Stream LLM Responses with Progress Callbacks

Streaming is the single highest-impact UX improvement you can make to an LLM feature. Without streaming, a user waits 5–10 seconds in silence before seeing any output. With streaming, text starts appearing within 300ms. The engineering is not hard, but handling streaming correctly — accumulating partial results, handling errors mid-stream, reporting progress — requires care.

What you are building

Build a stream_response function that:

  1. Accepts an Anthropic client, messages, model, and an optional on_chunk callback
  2. Streams the response using client.messages.stream()
  3. Calls on_chunk(text_delta: str, accumulated: str) after each text delta
  4. Handles StopReason variants: end_turn (normal), max_tokens (response was cut off), stop_sequence
  5. Returns a StreamResult with: the complete accumulated text, stop reason, total input/output tokens, and whether an error occurred mid-stream
  6. If a StreamError occurs mid-stream, calls on_chunk("[STREAM_ERROR]", accumulated_so_far) and returns a partial result with error=True

Also build a StreamBuffer class that implements on_chunk as a method and stores chunks for consumers that cannot process them live (e.g., testing, batch processing).

Why streaming matters in production

Streaming changes the user experience from "waiting" to "reading." Users tolerate 10+ seconds of generation if text is appearing. The same generation with no streaming feels broken at 5 seconds. Additionally, streaming lets you implement early-stop behavior: if the user navigates away or presses escape, you cancel the stream rather than completing a full (expensive) generation.

Llm Foundations / medium / Step 6 of 6

Practice stage

General drill

Hint

Keep the solution explicit and reviewable.

Next drill

This is the end of the current mini-sequence.

Success criteria

Make the solution explicit, debuggable, and easy to explain.

Review checklist

Review where the boundary is, what gets validated, and what would be hard to debug later.

Practice

Generate a variation

Generate a new exercise variation to deepen understanding or practice a related concept.

Attempt history

Recent submissions

Before you submit, decide what a strong answer should make obvious to the reviewer.

No attempts yet.