Stream LLM output through FastAPI without buffering it away

A generator can yield promptly while the client still displays everything at the end. Verify the whole delivery path, including server scheduling, event framing, proxy buffering and the client's read method. Start with a deterministic local stream so provider latency cannot obscure the diagnosis.

Prove local progressive delivery

Use Python 3.14 and install fastapi==0.165.0 and uvicorn==0.54.0 in an isolated environment. Save this application as app.py.

Python
import asyncio
import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse

app = FastAPI()

def sse(event, value):
    return f"event: {event}\ndata: {json.dumps(value)}\n\n"

async def events():
    for text in ("One ", "piece ", "at a time."):
        yield sse("delta", {"text": text})
        await asyncio.sleep(0.3)
    yield sse("done", {})

@app.get("/stream")
async def stream():
    return StreamingResponse(
        events(),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )

Run python -m uvicorn app:app --host 127.0.0.1 --port 8000. In another terminal run curl -N http://127.0.0.1:8000/stream. On Windows PowerShell, use curl.exe if curl resolves to a shell alias. Expect three delta events separated by roughly 0.3 seconds, followed by done. The timing is illustrative, not a real-time guarantee.

The generator uses await asyncio.sleep, which yields control to the event loop. time.sleep inside this async generator would block the loop. StreamingResponse accepts an iterator or async iterator, but it does not make arbitrary blocking work asynchronous. FastAPI streaming documentation .

Each server-sent event ends with a blank line. JSON encoding keeps embedded newlines within a data value from breaking that framing. A network read may contain half an event or several events. A client must parse the event stream rather than assume one read equals one token. Server-sent events standard .

Replace the local producer with provider deltas

Install openai==3.58.0, configure OPENAI_API_KEY, and set OPENAI_MODEL to an available Responses model. Replace only the events function and add these imports. This producer makes a billable provider request when /stream is called.

Python
import os
from openai import AsyncOpenAI, APIError

async def events():
    try:
        async with AsyncOpenAI(timeout=30.0, max_retries=0) as client:
            async with client.responses.stream(
                model=os.environ["OPENAI_MODEL"],
                input="Explain what a CSV file is in two sentences.",
                store=False,
            ) as upstream:
                async for event in upstream:
                    if event.type == "response.output_text.delta":
                        yield sse("delta", {"text": event.delta})
                final = await upstream.get_final_response()
                if final.status != "completed":
                    yield sse("error", {"message": "Generation did not complete"})
                    return
                if any(
                    part.type == "refusal"
                    for item in final.output if item.type == "message"
                    for part in item.content
                ):
                    yield sse("error", {"message": "No answer was provided"})
                    return
                yield sse("done", {})
    except (APIError, RuntimeError):
        yield sse("error", {"message": "Generation failed"})

The context managers close upstream resources when iteration exits, including cancellation. Do not swallow cancellation or reconnect automatically and concatenate a second generation onto a partial first answer. The simplified endpoint uses a fixed prompt and needs authentication and request limits before public deployment. Keep the API key on the server. OpenAI streaming guide , Python SDK .

Locate remaining buffering

Compare direct loopback delivery with delivery through the reverse proxy. Nginx can honor X-Accel-Buffering: no, unless its configuration disables that behavior. Other proxies and compression middleware have their own controls. Avoid disabling buffering globally just to fix one streaming route. Nginx buffering reference .

Use an event-stream parser or incremental browser reader. Calling response.text() waits for the whole body. Once headers have been sent, a later generation failure cannot change the original HTTP status, which is why this protocol includes an explicit error event.

The local stream was checked over loopback for progressive arrival. Provider events were checked with mocks. No live model stream or production proxy was tested.

Question provenance

This article addresses FastAPI StreamingResponse not streaming with generator function , asked by Robert Ritz on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored. No answer text or code is reproduced.

Author: Herman Schoenfeld