Sub topic 9
Reading the stream from a Python client
A streaming endpoint is only useful if the caller reads it incrementally. This chapter builds a Python client with httpx that prints tokens as they arrive. It also shows how to parse the Server-Sent Events (SSE) framing correctly and how to handle the failures a client sees on a long-lived response.
Prerequisites
This chapter assumes you have these:
- You can read
async/awaitcode and async generators. - You know the SSE format from the earlier chapter:
event:anddata:lines, with a blank line ending each message. - The
/chatendpoint from the previous chapters is running onhttp://localhost:8000. httpxis installed (pip install httpx).
Why a normal request call is wrong here
With client.post(...), httpx reads the whole response body before it returns. Against a streaming endpoint, that means your program waits until the last token has been generated and then receives everything at once. The server streams correctly, but the client erases the benefit.
To read incrementally, use client.stream(...). It is an async context manager. It returns once the response headers arrive, and the body stays unread until you iterate over it.
The diagram below shows who does what, and when.
A minimal client
This version matches the shape of the server's output. It reads one line at a time and remembers the most recent event name.
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())Four details matter here:
resp.raise_for_status()runs before any reading. A422from request validation or a500before streaming starts arrives as a normal status code. Only failures after the first byte need the in-banderrorevent.aiter_lines()yields decoded text lines without the trailing newline. Blank lines come through as empty strings.flush=Truemakesprintwrite immediately. Without it, a terminal that buffers stdout can hide the streaming effect.json.loadsaccepts the leading space indata: {...}, so this works. It would not work for non-JSON payloads.
Parsing SSE properly
The minimal client works because our server always sends one event: line and one single-line data: line per message. It breaks on other valid SSE input. The format allows these cases:
- A message with no
event:line. Its type defaults tomessage. - A
datafield split over severaldata:lines. A reader joins them with\n. - Comment lines that start with
:. Servers use them as keep-alive pings. - A blank line as the only reliable end of a message.
The blank line is the key signal. The minimal client never uses it, so an event value from one message could leak into the next if a later message omitted its event: line. A sturdier parser collects fields and emits a message when it sees the blank line.
import asyncio
import json
import httpx
URL = "http://localhost:8000/chat"
async def stream_events(resp: httpx.Response):
"""Yield (event, data) pairs from an SSE response."""
event = "message"
data_lines: list[str] = []
async for line in resp.aiter_lines():
if line == "":
if data_lines:
yield event, json.loads("\n".join(data_lines))
event = "message"
data_lines = []
elif line.startswith(":"):
continue
elif line.startswith("event:"):
event = line[len("event:"):].strip()
elif line.startswith("data:"):
data_lines.append(line[len("data:"):].removeprefix(" "))
async def main():
timeout = httpx.Timeout(10.0, read=60.0)
finished = False
async with httpx.AsyncClient(timeout=timeout) as client:
try:
async with client.stream("POST", URL, json={"prompt": "Say hello"}) as resp:
resp.raise_for_status()
async for event, data in stream_events(resp):
if event == "token":
print(data["text"], end="", flush=True)
elif event == "done":
finished = True
elif event == "error":
print("\n[server error]", data["message"])
except httpx.HTTPStatusError as exc:
print(f"Request rejected: {exc.response.status_code}")
except httpx.HTTPError as exc:
print(f"\n[connection problem] {type(exc).__name__}")
print()
if not finished:
print("Stream ended without a done event; the output may be incomplete.")
asyncio.run(main())stream_events is a small async generator of its own. It turns a raw line stream into typed messages, so the rest of the program does not care about SSE details. It also works as a separate, testable function.
Per the SSE specification, a reader removes at most one space after the colon. removeprefix(" ") does that, and it matters if a token itself starts with a space. removeprefix needs Python 3.9 or later.
Timeouts on a long-lived response
httpx has four timeouts: connect, read, write, and pool. For streaming, the read timeout is the one to understand. It limits the wait for each chunk, not the total duration of the response. A stream that runs for five minutes is fine, as long as no gap between chunks exceeds the read timeout.
That gives you two reasonable choices:
| Setting | Behavior | When to use it |
|---|---|---|
| `timeout=None` | Never times out | Quick experiments only. A stalled server hangs the client forever. |
| `httpx.Timeout(10.0, read=60.0)` | 10 seconds to connect, 60 seconds of silence allowed | Normal client code. Set `read` above the model's longest expected pause before the first token. |
The first token often takes the longest, because the model must process the whole prompt. Keep that in mind when you choose read.
What failures look like to the client
A streaming response can fail in three different places. The client sees each one differently.
- Before the stream starts. The server returns a non-2xx status.
raise_for_status()raiseshttpx.HTTPStatusError. - After the stream starts, handled by the server. The server catches the exception and sends
event: error. Your loop sees anerrorevent, and the response still ends normally. - After the stream starts, not handled. The connection drops or the server process dies. The client does not get an event. It gets a transport exception such as
httpx.RemoteProtocolError(the chunked body ended early) orhttpx.ReadTimeout. Both are subclasses ofhttpx.HTTPError.
Cases 2 and 3 leave you with partial output. The finished flag in the client above handles this. A complete stream always ends with done, so a missing done is how you detect a truncated response. Do not infer success from the absence of an exception.
Stopping early
Leaving the async with client.stream(...) block closes the connection. The server's side of that connection then breaks, which is the disconnect signal the cancellation chapter uses to stop the model call. You can test this from the client:
import asyncio
import json
import httpx
async def first_words(limit: int = 5):
seen = 0
async with httpx.AsyncClient(timeout=httpx.Timeout(10.0, read=60.0)) as client:
async with client.stream(
"POST", "http://localhost:8000/chat", json={"prompt": "Tell a long story"}
) 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:") and event == "token":
print(json.loads(line[len("data:"):])["text"], end="", flush=True)
seen += 1
if seen >= limit:
break
print("\n[stopped early]")
asyncio.run(first_words())The break exits the async for, and the async with blocks then close the response and the client. Watch the server log while you run this. If your endpoint handles disconnects correctly, generation stops soon after the client leaves.
Common mistakes
- Using
client.postand expecting streaming. The output appears all at once at the end. - Forgetting
flush=True. Output seems buffered even though the network is streaming fine. - Not resetting the event name at each blank line. Messages without an
event:line inherit the previous type. - Calling
json.loadson a: keep-alivecomment or a blank line. Parse onlydata:lines. - Using
timeout=Nonein production code. One hung connection can block a task forever. - Reading
resp.textinside the stream block. That call reads the entire body and defeats incremental reading. Useaiter_lines()oraiter_text().
Exercise
A colleague's client uses async with httpx.AsyncClient() as c: r = await c.post(URL, json=body) and then loops over r.text.splitlines(). The server streams correctly, yet the user sees nothing for ten seconds and then the whole answer. What is wrong, and what two changes fix it?
Show answer
c.post reads the full body before it returns, so the loop only starts after the last token has arrived. Replace it with async with c.stream("POST", URL, json=body) as r: and iterate with async for line in r.aiter_lines():, so lines are processed as they arrive. Also call print(..., flush=True) (or otherwise flush output) so the terminal shows each token immediately. The client should also check for a done event, so it can tell a complete answer from a truncated one.
Exercise
Why does stream_events reset event and data_lines when it sees a blank line, instead of only reading event: and data: lines as they come?
Show answer
The blank line is the only marker that ends an SSE message. Collecting fields until then supports messages whose data spans several lines. It also stops an event name from one message from carrying over to the next message that has no event: line. The reset returns the parser to its starting state, with event type message and no data.