Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 5.7 — When a Stream Breaks Midway
LLM Engineering · Example 1 of 1

Detecting and handling a broken stream

Four scripted requests: a clean one, a drop that a retry fixes, two drops, and a stream that ends silently. Java uses an Iterator that throws, since its examples stay single-threaded.

A stream can end early with no error: the connection resets, a proxy times out, or the provider fails after sending some text. A reply is complete only when a finish reason arrived. Otherwise retry, show the partial text with a warning, and tell the user.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 5 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Write classify_ending(finish_reason, raised) that returns "broken: error" if raised is true, "broken: no finish reason" if finish_reason is None, and "complete" otherwise.

02

Write best_partial(texts) that returns the longest string in a list (the first one if tied), or an empty string for an empty list.

Explain it without notes

01

How do you decide whether a streamed reply is complete?

02

Describe three policies for a stream that breaks midway and when each fits.

03

Why does idempotency matter when retrying a stream?

Detecting and handling a broken stream
Sign in to run this example in your browser.

Expected output

request 1: complete after 1 attempt(s): Rain today
request 2: complete after 2 attempt(s): Rain today
request 3: PARTIAL (broken: connection reset), shown with a warning: Rain tod
request 4: PARTIAL (broken: ended without a finish reason), shown with a warning: Rain tod