Sub topic 11
Printing the reply as it streams in
A model can take several seconds to produce a long reply. If the program waits for the whole reply and then prints it, the terminal looks frozen. Streaming prints each piece of the reply as soon as the model produces it. This chapter changes the model call to stream, keeps the history correct while it does, and handles Ctrl+C in the middle of a reply.
This chapter assumes you have the chat loop, the message list, and the single complete(messages) function from the earlier chapters. It also assumes you can read Python generators (functions that use yield).
What streaming changes
With a plain call, complete(history) returns one string. With streaming, the provider sends the reply as a series of small chunks, often a few characters or a word or two each. The history rule stays the same: the assistant message is added to the history once, after the reply is finished. The chunks are only for display.
That gives the turn two jobs at once:
- Show each chunk immediately.
- Collect the chunks so you can join them into one message at the end.
| Step | Non-streaming | Streaming |
|---|---|---|
| Model function returns | one string | an iterator of strings |
| When the user sees text | after the whole reply | as each chunk arrives |
| What goes in history | the returned string | the joined chunks |
| Failure in the middle | no reply at all | a partial reply is possible |
The last row is the new problem. A streamed reply can fail halfway, so you must decide what a half-finished reply means for the history.
Keep the stream behind one function
Earlier you isolated the model call behind complete(). Do the same for streaming. Define a second function, complete_stream(messages), that is a generator and yields plain text strings. Everything provider-specific stays inside it.
For learning and testing, you can write a fake stream that needs no network. It splits a canned reply into words and pauses briefly between them:
import time
def fake_stream(messages):
"""Yield a reply word by word, like a real streaming model would."""
reply = f"I can see {len(messages)} messages in this conversation."
for word in reply.split(" "):
time.sleep(0.05)
yield word + " "Because it yields text with a trailing space on each word, the joined reply ends with a space. You will strip that before storing it.
Printing chunks as they arrive
Terminal output is usually buffered. Python holds text in memory until it sees a newline or the buffer fills. If you print chunks with print(chunk, end=""), you may see nothing until the end of the line. Call flush() after each write to push the text to the screen now.
import sys
def print_stream(chunks, out=sys.stdout):
"""Write each chunk to out right away and return the full text."""
parts = []
for chunk in chunks:
out.write(chunk)
out.flush()
parts.append(chunk)
out.write("\n")
out.flush()
return "".join(parts)The out parameter defaults to the real terminal. Tests can pass in an in-memory buffer instead, which is the same trick you used earlier by passing the model function in as an argument.
A streaming turn that keeps history valid
Now combine the streaming with the history rules from the error-handling chapter. The question is what to do in each failure case.
- The request fails before any text arrives. Remove the user message, as before, so the history still alternates correctly.
- The stream fails after some text arrived. The reply is incomplete and may be cut off mid-sentence. Remove the user message and drop the partial text.
- The user presses Ctrl+C during the reply. The user chose to stop. Keep the partial text, because they saw it and may refer to it. If nothing arrived yet, treat it like case 1.
import sys
def stream_turn(history, user_text, complete_stream, out=sys.stdout):
history.append({"role": "user", "content": user_text})
parts = []
try:
for chunk in complete_stream(history):
out.write(chunk)
out.flush()
parts.append(chunk)
except KeyboardInterrupt:
out.write("\n[interrupted]\n")
out.flush()
partial = "".join(parts).strip()
if partial:
history.append({"role": "assistant", "content": partial})
else:
history.pop()
return partial
except Exception:
history.pop()
raise
out.write("\n")
out.flush()
reply = "".join(parts).strip()
history.append({"role": "assistant", "content": reply})
return replyNotice that the KeyboardInterrupt branch does not re-raise. The turn ends cleanly and the main loop continues, so one Ctrl+C stops the reply without ending the program.
The sequence of a streamed turn
Wiring it into the loop
The main loop changes in one place: it calls stream_turn and no longer prints the reply itself, because the printing already happened. It prints the bot> prompt first so the streamed text appears after it.
def main():
history = [{"role": "system", "content": "You are a concise, helpful assistant."}]
while True:
try:
user_text = input("you> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not user_text:
continue
if user_text == "/quit":
break
print("bot> ", end="", flush=True)
try:
stream_turn(history, user_text, fake_stream)
except Exception as exc:
print(f"\n[error: {exc}]")
if __name__ == "__main__":
main()This block needs stream_turn and fake_stream from the earlier blocks in the same file. To use a real model, replace fake_stream with your own complete_stream. Nothing else changes.
Edge cases to know about
Chunks do not line up with words. A real model may split a word, or even a multi-byte character's worth of text, across chunks. Never print or process chunks as if each one were a word. Your provider's SDK normally hands you decoded text, so you only need to concatenate it.
Slow display is not a slow model. Streaming does not make the model finish sooner. It only makes the first words appear sooner. Total time is about the same.
Piped output. When output goes to a file or another program instead of a terminal, flushing on every chunk is slower but still correct. If you want it quieter in that case, check out.isatty() and skip the flush.
Trimming and saving. Streaming does not change them. The history holds complete message strings, so trim_history and save_history work as they did before. Save only after a turn has ended, so a file never contains a half-built reply.
Strip with care. The example strips the joined reply to remove the trailing space from the fake stream. A real reply may begin or end with meaningful whitespace only rarely, so stripping is usually safe. If you want exact text, store it unstripped and strip only for display.
Testing the streaming turn
Since stream_turn takes the stream function and the output target as arguments, you can test every case above with no network. A fake stream can raise at a chosen point.
import io
def stream_of(*pieces, then_raise=None):
def gen(messages):
for piece in pieces:
yield piece
if then_raise is not None:
raise then_raise
return gen
def test_chunks_are_joined_into_one_message():
history = [{"role": "system", "content": "s"}]
out = io.StringIO()
reply = stream_turn(history, "hi", stream_of("Hel", "lo"), out)
assert reply == "Hello"
assert history[-1] == {"role": "assistant", "content": "Hello"}
assert out.getvalue() == "Hello\n"
def test_interrupt_keeps_partial_reply():
history = [{"role": "system", "content": "s"}]
out = io.StringIO()
stream = stream_of("Par", then_raise=KeyboardInterrupt())
assert stream_turn(history, "hi", stream, out) == "Par"
assert history[-1]["content"] == "Par"
assert len(history) == 3
def test_error_mid_stream_discards_everything():
history = [{"role": "system", "content": "s"}]
stream = stream_of("Par", then_raise=RuntimeError("dropped"))
try:
stream_turn(history, "hi", stream, io.StringIO())
except RuntimeError:
pass
assert len(history) == 1Run these with pytest. The second test passes only because KeyboardInterrupt has its own handler.
Common mistakes
- Forgetting
flush(), so the text appears in bursts or all at once. - Adding the assistant message to the history inside the loop, one chunk at a time. The history then fills with fragments instead of one message per reply.
- Printing the reply a second time in
mainafterstream_turnalready printed it. - Catching only
Exceptionand leaving an unanswered user message after Ctrl+C.
Exercise
A user presses Ctrl+C after the bot has printed "The capital of Fra" and then the stream stops. Using the stream_turn above, what is in the history afterward, and why is the next request still valid? Name one change you would make if you wanted partial replies to be discarded instead.
Show answer
The history ends with the user message followed by an assistant message whose content is "The capital of Fra". The roles still alternate user, assistant, so the next request is valid. To discard partial replies, change the KeyboardInterrupt branch to call history.pop() always, instead of appending the partial text, so the user message is removed and the history returns to its state before the turn.
Exercise
Why does stream_turn append the assistant message once at the end, instead of appending each chunk as it arrives?
Show answer
The history must hold one complete message per reply, because the model expects whole messages in alternating roles. Appending chunks would create many tiny assistant messages, break the alternation, and leave a partly written message in the history if the stream failed. Collecting chunks in a local list and appending once also lets the code decide what to store after a failure.