Sub topic 11
Printing the reply as it streams in
This chapter assumes you have the chat loop, the message history, and a run_turn function that takes the model function as a parameter. You should also be comfortable with Python generators (functions that use yield).
Why stream
A model can take several seconds to produce a long reply. With a plain call, the terminal stays silent until the whole reply arrives. Most chat APIs can instead send the reply in small pieces, called chunks, as the model produces them. Printing each chunk on arrival makes the bot feel responsive, even though the total time is the same.
A streaming model function
The model function changes shape. Instead of returning one string, it becomes a generator that yields chunks. Keeping it behind one function means the rest of the program does not care which provider you use. The version below is a fake that you can run now. Replace its body with your provider's streaming call, and yield only the text of each chunk.
import sys
import time
def complete_stream(messages):
"""Yield the reply in pieces. Replace with your provider's streaming call."""
for piece in ("This ", "is ", "a ", "streamed ", "reply."):
time.sleep(0.2)
yield piecePrinting while collecting
The history must still hold the complete reply as one string. So the turn function does two jobs for each chunk: it prints the chunk, and it saves the chunk in a list. After the stream ends, it joins the list and appends one assistant message.
def run_turn_stream(history, user_text, stream, out=sys.stdout):
history.append({"role": "user", "content": user_text})
parts = []
try:
for chunk in stream(history):
parts.append(chunk)
out.write(chunk)
out.flush()
except BaseException:
history.pop()
out.write("\n")
raise
out.write("\n")
reply = "".join(parts)
history.append({"role": "assistant", "content": reply})
return reply
if __name__ == "__main__":
history = [{"role": "system", "content": "You are a concise, helpful assistant."}]
while True:
try:
text = input("you> ").strip()
except (EOFError, KeyboardInterrupt):
print()
break
if not text:
continue
if text == "/quit":
break
print("bot> ", end="")
try:
run_turn_stream(history, text, complete_stream)
except KeyboardInterrupt:
print("[interrupted]")
except Exception as exc:
print(f"[error: {exc}]")Three details matter here.
- Flushing. Terminal output is usually buffered until a newline. Without
out.flush(), the chunks would appear all at once at the end, which defeats the purpose. - The
outparameter. Like the model function, the output target is passed in. A test can supplyio.StringIO()and check what was printed. - Cleanup on failure. The
except BaseExceptionblock coversKeyboardInterrupt, which is not a subclass ofException. It removes the user message, so the history never ends with a user message that has no reply. It then re-raises, so the caller decides what to show.
Common errors
- Printing with
print(chunk)adds a newline after every chunk. Usewriteorprint(chunk, end="", flush=True). - Storing each chunk as its own assistant message. The history should hold one message per turn.
- Yielding the provider's chunk objects instead of text. Some chunks carry no text, for example the final one. Skip those before yielding.
- Forgetting the trailing newline, which leaves the next
you>prompt on the same line as the reply.
Exercise
A streaming reply fails halfway through with a network error. Using runturnstream as written, what do the history and the terminal contain afterward, and why is it done that way?
Show answer
The terminal shows the partial text that was already printed, followed by a newline, and the caller prints an error message. The history is unchanged from before the turn, because the except block pops the user message and nothing was appended for the assistant. This keeps the history valid, with no user message left without a reply, and the user can simply retype the question.