New Tool Radar

AI Concepts

How to Stream a Structured Model Response and Parse Its JSON Fields as They Arrive

Open a streaming structured response, parse each JSON field as it arrives, and handle an incomplete stream.

Schematic with three steps: Open the stream with the schema; Parse fields as they arrive; Handle an incomplete stream.

You can use streaming to process model responses or function call arguments as they are being generated, and parse them as structured data, so you do not have to wait for the entire response to complete before handling it. That is particularly useful if you would like to display JSON fields one by one, or handle function call arguments as soon as they are available. The SDKs should handle the streaming mechanics for you.

What you need

  • An SDK that supports streaming with Structured Outputs
  • A schema for the reply
  • A UI or handler that can show fields one by one

Step 1: Open the stream with the schema

Start a streaming call with the response format set to your schema, using the SDK streaming helper rather than hand-rolling the stream.

Step 2: Parse fields as they arrive

As each field completes, parse it and display it or pass it on. A field is not final until the stream completes, so hold any action that depends on the whole object.

Step 3: Handle an incomplete stream

If the stream ends early, treat the reply as incomplete and do not store partial data as if it were complete. Retry the call or ask the user to try again.

Worked example: synthetic streaming parse

The table below is a synthetic example. It shows the expected result of streaming a structured reply; no API call was made.

Stream stage Field available Action
Field 1 arrives name Displayed
Field 2 arrives date Displayed
Stream completes participants Object stored
Stream cut early Partial object Discarded, retried

Expected result (UNTESTED). fields display one by one as they arrive, the object is stored only when the stream completes, and a cut stream is discarded and retried. This check was not run live; the table shows the expected result for the synthetic example.

Limits

  • Rely on the SDKs to handle streaming with Structured Outputs; hand-rolled stream parsing is easy to get wrong.
  • A streamed field is not final until the stream completes.
  • Incomplete responses still need handling, even in a stream.
  • Streaming shows progress sooner, but it does not make the model faster or the answer more accurate.

Sources

See all