Lesson 11 of 33 · Part 1: API Basics

Streaming: The Typing Effect

Show the answer word by word as it is written, like ChatGPT does.

Last time: Our first API call: send one question with create(), wait, then print response.choices[0].message.content.
Today: Add stream=True and print the answer piece by piece while the AI writes it, like ChatGPT.
1. Set up
2. Ask with stream=True
3. Loop over chunks
4. Done
OpenAIgpt-4o-mini
Pixel
writing…
"Pixel"
" was"
" a"
" cleaning"
" robot"
" who"
" swept"
" an"
" art"
" museum"
" every"
" night"
"."
" It"
" began"
" copying"
" the"
" paintings"
" with"
" a"
" dusty"
" old"
" brush"
","
" and"
" night"
" after"
" night"
" its"
" w"
"obb"
"ly"
" lines"
" grew"
" smoother"
"."
" One"
" morning"
" the"
" guards"
" found"
" a"
" bright"
" sunset"
" on"
" an"
" eas"
"el"
","
" and"
" they"
" hung"
" Pixel"
"'s"
" first"
" painting"
" by"
" the"
" front"
" door"
"."
stream=True
Your laptop· terminal
$ python run.py part1/streaming.py
Asking the AI to write (streaming)...
Source Code
1# part1/streaming.py
2from openai import OpenAI
3client = OpenAI()
4
5print("Asking the AI to write (streaming)...")
6
7# stream=True: get the answer piece by piece
8stream = client.chat.completions.create(
9    model="gpt-4o-mini",
10    messages=[
11        {"role": "user",
12         "content": "Tell a 3-sentence robot story."}
13    ],
14    stream=True,
15)
16
17# Starts empty; every piece gets added to it
18full_story = ""
19
20# Each chunk carries a tiny new piece of the answer
21for chunk in stream:
22    piece = chunk.choices[0].delta.content
23    # Skip chunks with no text ("" or None)
24    if piece:
25        # end="": same line. flush=True: show now
26        print(piece, end="", flush=True)
27        full_story += piece
28
29print(f"\n\nDone! {len(full_story)} characters in total.")

No output yet...

← Prev
1/0
Next: Tokens & Cost →