Velamuvi AIAcademy

Lesson 5 of 8 · Real-World Use

Streaming Responses

Stream AI answers as they're written: why streaming feels faster, how server-sent events deliver chunks, assembling deltas, and streaming with the SDKs.

  • 6 min read
  • Beginner
  • Reviewed
In this lesson you will learn
  • Why streaming makes AI apps feel much faster
  • How server-sent events deliver an answer in small pieces
  • How to assemble the pieces and get the final stop reason and usage
  • How to stream with an SDK, and what to watch out for

Waiting versus watching

A long answer can take 20 seconds or more to generate. Without streaming, the user stares at a spinner until the very last token is ready. With streaming, the first words appear in under a second and the rest flows in as it is written. The total time is the same, but the app feels far faster.

Server-sent events

AI APIs stream using server-sent events (SSE): the server keeps the HTTP connection open and sends a series of small text messages, each starting with data:, as tokens are generated.

Try it yourselfPython
import json

# What arrives over the network when streaming: server-sent events, one per line.
# (Simplified; each provider names its events a little differently.)
stream = """event: message_start
data: {"type": "message_start"}

event: text_delta
data: {"type": "text_delta", "text": "Rain"}

event: text_delta
data: {"type": "text_delta", "text": "bows form when"}

event: text_delta
data: {"type": "text_delta", "text": " sunlight is split"}

event: text_delta
data: {"type": "text_delta", "text": " by raindrops."}

event: message_stop
data: {"type": "message_stop", "stop_reason": "end_turn", "output_tokens": 11}
"""

full_text = ""
for line in stream.splitlines():
    if not line.startswith("data: "):
        continue                                  # skip event names and blank lines
    event = json.loads(line[len("data: "):])
    if event["type"] == "text_delta":
        full_text += event["text"]
        print("screen now shows:", full_text)     # a real app updates the page here
    elif event["type"] == "message_stop":
        print("done:", event["stop_reason"], "|", event["output_tokens"], "output tokens")

The pattern is always the same:

  1. A start event.
  2. Many delta events, each with a small piece of new text. Your app adds each one to what is already shown.
  3. A stop event with the stop reason and, usually, the final token usage.

Streaming with an SDK

SDKs handle the connection and event parsing for you. These run on your own computer with your key.

Anthropic:

import anthropic

client = anthropic.Anthropic()

with client.messages.stream(
    model="MODEL_NAME",
    max_tokens=500,
    messages=[{"role": "user", "content": "Explain how rainbows form."}],
) as stream:
    for text in stream.text_stream:
        print(text, end="", flush=True)    # print each piece without a new line

OpenAI:

from openai import OpenAI

client = OpenAI()

stream = client.responses.create(
    model="MODEL_NAME",
    input="Explain how rainbows form.",
    stream=True,
)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="", flush=True)

end="" stops print adding a new line after every piece, and flush=True shows each piece immediately instead of waiting for a buffer to fill.

Things to watch out for

  • Errors can happen mid-stream. The connection can drop or the provider can send an error event halfway through. Handle it: keep what was shown, tell the user, and offer to retry.
  • Usage arrives at the end. Token counts usually come in the final events. If the stream is cut off, you may not get them; log what you can.
  • Characters can be split. A chunk can end partway through a multi-byte character or a word. SDKs handle this; if you parse raw bytes yourself, decode carefully.
  • Structured output and streaming don't mix easily. Half a JSON object can't be parsed. Wait for the end, or use a streaming parser designed for it.

Common mistakes

Practice exercise

Assemble a streamed answer from its chunks, as a chat app does.

Your solutionPython
events = [
    {"type": "start"},
    {"type": "delta", "text": "Hel"},
    {"type": "delta", "text": "lo, "},
    {"type": "delta", "text": "world"},
    {"type": "delta", "text": "!"},
    {"type": "stop", "reason": "end_turn"},
]

# Join the text of every "delta" event, then print:
# Hello, world!
# Received 4 chunks, stopped because: end_turn
Knowledge check

What is the main benefit of streaming a long AI response to a user?

Summary

  • Streaming delivers output in pieces as it is generated, cutting the wait to the time to first token.
  • APIs stream with server-sent events: a start event, many deltas, then a stop event with the reason and usage.
  • Accumulate the deltas into the full text as you display them.
  • SDKs provide simple streaming helpers.
  • Handle mid-stream errors, and don't stream when a program needs the whole output at once.

Next: handling errors and retrying safely.

Finished reading? Tick it off to track your progress.