Sub topic 9
Reading the stream from a Python client
This chapter assumes you have the /chat endpoint from the previous chapters running. It also assumes you know async/await and have used httpx for ordinary requests. You will write a client that prints tokens as they arrive instead of waiting for the full reply.
Why a normal request call is the wrong tool
A call such as await client.post(...) waits until the whole response body has arrived, then returns it. Against a streaming endpoint, that throws away the benefit of streaming. The client sees nothing until generation finishes.
httpx has a separate streaming API. client.stream(...) returns once the response headers arrive. The body stays unread until you iterate over it.
The client
Install the library with pip install httpx, start the server with uvicorn main:app, and run this script.
import asyncio
import json
import httpx
async def main():
async with httpx.AsyncClient(timeout=None) as client:
async with client.stream(
"POST", "http://localhost:8000/chat", json={"prompt": "Say hello"}
) as resp:
resp.raise_for_status()
event = None
async for line in resp.aiter_lines():
if line.startswith("event:"):
event = line[len("event:"):].strip()
elif line.startswith("data:"):
data = json.loads(line[len("data:"):])
if event == "token":
print(data["text"], end="", flush=True)
elif event == "error":
print("\n[error]", data["message"])
print()
asyncio.run(main())How the parsing works
The server frames each message as an event: line, a data: line, and a blank line. The client reads these lines in order.
aiter_lines()yields one decoded line at a time, as soon as the line is complete. It buffers partial lines for you, so a token split across two network packets still arrives as one line.- An
event:line sets the current event name. The client remembers it in theeventvariable. - A
data:line carries a JSON payload.json.loadsaccepts the leading space after the colon, so you do not need to strip it. - The blank line between messages matches neither
ifbranch and is ignored. - For a
tokenevent, the client prints the text withend=""andflush=True. Withoutflush=True, Python may hold the output in its own buffer and the stream would look frozen.
The error branch matters. As covered in the error-handling chapter, a failure after the response has started cannot change the status code. It can only appear as an error event, so the client must look for it.
Choices and common errors
- Timeout.
timeout=Nonedisables all timeouts, which is convenient for a demo. The defaulthttpxtimeout is 5 seconds, and the read timeout applies between chunks. A slow model can trip it. In real code, set a finite connect timeout and a generous read timeout, for examplehttpx.Timeout(10.0, read=60.0). - Forgetting
raise_for_status(). Validation errors, such as an empty prompt, return a normal 422 response. Without the check, the loop finds no matching lines and the script finishes without output. - Using
client.postinstead ofclient.stream. The script appears to work, but all text arrives at once. - Output arriving in bursts. If the server code is correct but you still see bursts, a proxy is probably buffering the response. That is the subject of a later chapter.
Exercise
The client prints nothing and exits without an error when you send {"prompt": ""}. Why, and what one line fixes the silence?
Show answer
The server's Pydantic model requires min_length=1, so it returns a 422 response. That body has no event: or data: lines, so the loop prints nothing. Calling resp.raise_for_status() right after opening the stream raises an HTTPStatusError, which makes the failure visible.