π What is Streaming?
Streaming is the process of displaying AI-generated content as it's being created, rather than waiting for the full response to be ready.
β³ Without Streaming
π€ User sends request
β
π§ Model thinks...
β
β
Model finishes entire response
β
π User finally sees output
The user stares at a blank screen until everything is complete. π
β‘ With Streaming
π€ User sends request
β
π Model starts generating
β
π€ Token 1 appears
π€ Token 2 appears
π€ Token 3 appears
...
The response gradually appears on screen, creating the familiar β¨οΈ typewriter effect β just like you see in ChatGPT! β¨
π€ Why Does Streaming Work?
LLMs naturally produce text one token at a time πͺ. For example:
π€ User: Tell me about React
π€ Model generates:
React
React is
React is a
React is a JavaScript
React is a JavaScript library
...
Since the model is already working incrementally under the hood π§, it makes perfect sense to show the output incrementally too β no waiting required! π
βοΈ Lets add streaming in our create_brochure function
βΆοΈ Create a new code cell and run it: ( In same File - part4.ipynb)
def stream_brochure(company_name, url):
stream = openai.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": brochure_system_prompt},
{"role": "user", "content": get_brochure_user_prompt(company_name, url)}
],
stream=True
)
response = ""
display_handle = display(Markdown(""), display_id=True)
for chunk in stream:
response += chunk.choices[0].delta.content or ''
update_display(Markdown(response), display_id=display_handle.display_id)This function generates a company brochure using AI, word by word, and displays it in real time.
1οΈβ£ Send a request to GPT
stream = openai.chat.completions.create(..., stream=True)
Asks GPT-4 to write a brochure, with stream=True so it sends back the response chunk by chunk instead of all at once.
2οΈβ£ Set up a live display
response = ""
display_handle = display(Markdown(""), display_id=True)
Creates an empty placeholder on screen, ready to be updated.
Part | Meaning |
|---|---|
| Creates an empty markdown display |
| Gives it a unique ID so we can find it later |
| Stores that ID/reference for future use |
3οΈβ£ Build the response live
for chunk in stream:
response += chunk.choices[0].delta.content or ''
update_display(Markdown(response), display_id=...)
Each chunk = a few new words. They get added to the response and the display refreshes instantly β creating the β¨οΈ typewriter effect.
Chunk 1: "Hello"
Response: "Hello"
Chunk 2: " World"
Response: "Hello World"
Part | Meaning |
|---|---|
| The new content to show |
| Finds the same whiteboard using its name tag |
| Erases & rewrites the whiteboard with new content |
π§ In One Line:
Send prompt β receive words one by one β keep updating the screen until the brochure is complete.
βΆοΈ Create a new code cell and run it:
stream_brochure("Codeveda", "<https://codeveda.dev>")