I split a model reply into chunks, receive them one at a time, and print each as it arrives, accumulating them into a complete message.
chunks = ["Hello", ", ", "this ", "reply ", "is ", "streamed ", "in ", "parts."]
buffer = ""
print("Streaming responses")
print("Chunks received: %d" % len(chunks))
for c in chunks:
buffer += c
print("Received chunk: %r" % c)
print("Full message reconstructed: %s" % buffer)
Before you run it, say out loud what it will print. Then open the answer.
What it prints
Streaming responses
Chunks received: 8
Received chunk: 'Hello'
Received chunk: ', '
Received chunk: 'this '
Received chunk: 'reply '
Received chunk: 'is '
Received chunk: 'streamed '
Received chunk: 'in '
Received chunk: 'parts.'
Full message reconstructed: Hello, this reply is streamed in parts.
Each chunk is just a tiny piece with no words on either side, so the browser is responsible for gluing them back in order. If one chunk is dropped, a word silently disappears from the middle.