The pattern
Three things every Python Ollama streaming client gets right:
timeout=None— first-token latency on a cold model can be tens of seconds. The default httpx timeout will kill your stream mid-warm-up. Set it to None and rely on the server.iter_lines()— let the HTTP client buffer until newlines, then yield complete lines. Don't read raw bytes and reassemble lines yourself.flush=Truewhen printing tokens — otherwise stdio buffers swallow the streaming feel.
Where this fits in production
This is the building block for streaming endpoints in your own backend. cwkPippa's Ollama vessel uses this exact pattern — stream NDJSON from Ollama, transform each chunk into a universal StreamChunk, write it to JSONL ground truth, then yield it to the frontend.
Common mistakes
- Forgetting
timeout=None. Default timeouts kill you on cold starts. - Buffering by character instead of by line.
iter_text()chunks at network boundaries;iter_lines()handles the boundary problem for you. - Not handling the empty final chunk.
done: truearrives with empty content. Break before printing.