AI Engineer Portal
Your personal operating system for career transition.
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:
- Accepts an Anthropic client, messages, model, and an optional
on_chunkcallback - Streams the response using
client.messages.stream() - Calls
on_chunk(text_delta: str, accumulated: str)after each text delta - Handles
StopReasonvariants:end_turn(normal),max_tokens(response was cut off),stop_sequence - Returns a
StreamResultwith: the complete accumulated text, stop reason, total input/output tokens, and whether an error occurred mid-stream - If a
StreamErroroccurs mid-stream, callson_chunk("[STREAM_ERROR]", accumulated_so_far)and returns a partial result witherror=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
General drill
Keep the solution explicit and reviewable.
This is the end of the current mini-sequence.
Make the solution explicit, debuggable, and easy to explain.
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.