Ir para o conteúdo

Lição 6 · Generating Text

Streaming Responses

Stream OpenAI API output with stream=True, handle typed events such as text deltas and completion, relay them to browsers and cope with broken streams.

A normal request waits until the whole reply is ready. For a long answer, the user may stare at a blank screen for a while. With streaming, the API sends the reply in small pieces while it is being generated. The total work is similar, but the first words appear much sooner, so the app feels faster.

In this lesson you read the event stream, build the final text from pieces, and handle the cases where a stream does not end well.

Turn on streaming

Add stream=True. Instead of one response object, you get a sequence of events that you loop over.

Python
# Read-only
stream = client.responses.create(
    model="gpt-6.2-sol",
    input="Explain DNS to a beginner.",
    stream=True,
)

for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)
    elif event.type == "response.completed":
        print("\n[done]")
    elif event.type in ("response.incomplete", "response.failed"):
        print("\n[not completed]", event.response.status)
    elif event.type == "error":
        print("\n[stream error]", event)

Each event has a type. These are good ones to know first.

Event type When it arrives
response.created The response has started
response.output_text.delta A new piece of text, in delta
response.completed The response finished
response.incomplete The response stopped early, for example at the output token limit
response.failed The response failed
error Something went wrong in the stream

There are more types, for example for output items, refusals and function call arguments. A robust program handles the events it needs and ignores types it does not know, because new ones can appear.

Simulate a stream

This stand-in yields hand-written events. It lets you practice the handling logic without a model.

Python Stand-in: consume a stream of events

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The second run returns half a sentence. The important detail is the finished flag: text is complete only when the stream says so. If the connection drops, you may get no error event at all. The loop simply ends or raises an exception. In both cases, the flag stays false.

What to do with a partial reply

Decide this in advance. Reasonable choices are:

  • Show the partial text with a clear "reply interrupted" note and a retry button.
  • Throw it away and retry the whole request.
  • For automated jobs, never use partial text. Treat the run as failed.

Do not save a partial reply as if it were final, and do not act on it. Half of a sentence such as "do not delete" can mean the opposite of the full one.

Sending the stream to a browser

Your browser code must not hold the API key, so the stream passes through your server. A common method is server-sent events (SSE): your server keeps the HTTP response open and writes one small message for each text piece.

Python
# Read-only: the idea, using a generator your web framework can stream
import json

def sse_lines(stream):
    for event in stream:
        if event.type == "response.output_text.delta":
            yield "data: " + json.dumps({"delta": event.delta}) + "\n\n"
        elif event.type == "response.completed":
            yield "data: " + json.dumps({"done": True}) + "\n\n"

In the browser, add each piece with textContent, not innerHTML. Model output is untrusted text. If you render Markdown, use a library that sanitizes HTML.

JavaScript
// Read-only: append text safely
answerElement.textContent += message.delta;

Also think about your proxy or hosting platform. Some buffer responses, so the user receives everything at once at the end. If streaming works locally but not in production, check buffering and time limits.

Cancel and clean up

A user may close the tab or press Stop. Your server should notice the disconnect and close the upstream stream, so you stop paying for output nobody will read. Check how your SDK and framework signal cancellation.

For very long tasks, streaming may be the wrong tool. Batch and background jobs covers requests that run without a user waiting.

Streaming and checks

Streaming changes when you can check output. If you filter or moderate the full reply before showing it, you cannot also show each piece immediately. When you request inline moderation scores, they arrive only after the whole output has been generated. For sensitive apps, consider waiting for the full reply, or showing it in larger checked chunks.

Structured data has a similar issue. A half-finished JSON object does not parse. Collect all pieces, confirm completion, then parse. See structured outputs.

Measure what users feel

Two numbers help you judge a streaming app:

  • Time to first text: how long until the first delta.
  • Total time: how long until completion.

Log both with your response ID. A change in prompt, model or reasoning effort can move them in different directions. A model that thinks longer may start later even if it writes at the same speed.

Show a "working" state between sending the request and receiving the first delta. Reasoning and tool use can create a noticeable pause before any text appears.

Should you stream at all?

Stream when a person is watching and the answer is long enough that waiting feels slow. Do not stream just because you can. For background jobs, short labels and structured data that your program must validate, a normal request is simpler and has fewer failure paths.

Keep the interface calm

Updating the page for every tiny delta can make it flicker or waste work, especially when you re-render Markdown each time. Collect pieces for a few tens of milliseconds and then draw once. Screen readers can also struggle with constantly changing text, so consider announcing the answer when it is complete. Give users a visible Stop button, and keep the text they have already received readable after they press it.

Test with a slow network as well as a fast one, and test what happens when you cut the connection in the middle.

Common mistakes

  • Assuming each delta is a whole word or sentence. Pieces can split anywhere, so join them before you search or parse.
  • Saving the reply to your database when the loop ends, without checking that the completion event arrived.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Which event carries a new piece of text?

    The delta field of that event holds the new text.
  2. 2. How should your code treat an event type it does not recognize?

    New event types can be added, so unrelated ones should not break your program.
  3. 3. When is streamed text known to be complete?

    Punctuation proves nothing. Wait for the completion signal.
  4. 4. What is the safest way to add plain model text to a web page?

    textContent shows the characters as text and does not interpret them as HTML or code.

Summary

  • stream=True returns typed events as the reply is generated.
  • Join text deltas, and rely on the completion event to know the reply is whole.
  • Plan for errors and dropped connections.
  • Relay streams through your server and render them as untrusted text.
  • Parse structured data and run full checks only after completion.

Next: Models and Reasoning Effort

Seu progresso fica salvo neste navegador. Não precisa de conta.