AI Engineer Portal
Your personal operating system for career transition.
Exercise
Build a streaming response accumulator for LLM output
Build a Streaming Response Accumulator for LLM Output
Most production LLM APIs support streaming: instead of waiting for the full response, you receive tokens as they are generated. Streaming dramatically reduces time-to-first-token and lets you forward partial output to users in real time. But streaming also means your application needs to handle partial data, detect stream completion, and produce a coherent final result.
What to build
Implement a StreamAccumulator class that processes a stream of token chunks:
-
__init__()— initialize internal state. -
feed(chunk: str | None) -> None— accept one chunk.Noneis the sentinel that signals end-of-stream. -
is_complete() -> bool— returnTrueafter aNonesentinel has been received. -
full_text() -> str— return the concatenation of all received chunks (excluding the sentinel). RaiseRuntimeErrorif the stream is not yet complete. -
chunk_count() -> int— return the number of non-sentinel chunks received. -
extract_json() -> dict | None— after the stream is complete, try to parse the full text as JSON. Return the parsed dict on success,Noneon failure. This is useful for tool call responses that stream as JSON.
Also implement simulate_stream(text: str, chunk_size: int = 5) -> list[str | None] — a helper that splits a text into chunks of chunk_size characters and appends a None sentinel. This simulates a provider stream for testing.
Why this matters
In a FastAPI streaming endpoint, you forward chunks to a client as they arrive. In a background job, you accumulate the full text and then validate it. The StreamAccumulator makes both use cases clean without duplicating the concatenation logic.
Constraints
full_text()must raiseRuntimeErrorif called before the sentinel arrives.feed(None)called multiple times should be idempotent (still just marks as complete).- Do not assume chunks are single tokens — they can be multi-character strings.
Data Transformation / medium / Step 13 of 16
Transform and summarize data safely
Think like an evaluation or trace pipeline: group clearly, preserve the data story, and make edge cases visible instead of clever.
- - Handles missing or noisy records predictably
- - Produces summary output that is easy to inspect
- - Would be safe to rerun in a script workflow
- - Do grouped metrics stay readable?
- - Would malformed rows be debuggable?
- - Did I choose names that explain the transformation?
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.