StackPractices
intermediate By Mathias Paulenko

Stream LLM Output with Server-Sent Events (SSE)

Stream LLM responses to clients in real-time using Server-Sent Events with FastAPI, OpenAI streaming, and async generators for token-by-token output

Topics: ai api

Overview

Streaming LLM output improves perceived latency — users see tokens as they’re generated instead of waiting for the full response. Server-Sent Events (SSE) is the standard protocol for streaming from server to client over HTTP. Below: SSE streaming with FastAPI, the OpenAI streaming API, and async generators.

When to Use This

  • Chat interfaces where users expect real-time responses
  • Long-form generation where waiting for the full output feels slow
  • Progress or status feeds that push updates from server to client over plain HTTP
  • Any LLM application where perceived latency matters

Don’t use SSE when you need bidirectional messaging (use WebSocket instead) or when the response is consumed by a non-browser client that can just read a chunked HTTP body.

ApproachDirectionTransportAuto-reconnectBest for
SSE (EventSource)Server → clientPlain HTTPBuilt-inToken streaming, feeds, notifications
WebSocketBidirectionalws:// upgradeManualClient-initiated messages, interactive low-latency
HTTP pollingRepeated requestsPlain HTTPN/AInfrequent updates, legacy clients
fetch + ReadableStreamServer → clientPlain HTTPManualPOST bodies, non-browser clients

For the Node.js equivalent, see Server-Sent Events with Node.js and Express.

Prerequisites

  • Python 3.10+
  • fastapi, uvicorn, openai packages
  • An OpenAI API key

Solution

1. Install Dependencies

pip install fastapi uvicorn openai sse-starlette

2. SSE Streaming Endpoint with FastAPI

from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel
from openai import AsyncOpenAI
import json
import asyncio

app = FastAPI()
client = AsyncOpenAI()

class ChatRequest(BaseModel):
    message: str
    model: str = "gpt-4o-mini"

async def stream_openai_response(message: str, model: str):
    """Async generator that yields SSE-formatted chunks from OpenAI."""
    stream = await client.chat.completions.create(
        model=model,
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": message},
        ],
        stream=True,
    )

    async for chunk in stream:
        if chunk.choices[0].delta.content is not None:
            data = json.dumps({"token": chunk.choices[0].delta.content})
            yield f"data: {data}\n\n"

    # Send end event
    yield f"data: {json.dumps({'done': True})}\n\n"

@app.get("/api/chat/stream")
async def chat_stream(message: str, model: str = "gpt-4o-mini"):
    """SSE endpoint for streaming LLM responses."""
    return StreamingResponse(
        stream_openai_response(message, model),
        media_type="text/event-stream",
        headers={
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "X-Accel-Buffering": "no",  # Disable Nginx buffering
        },
    )

3. Client-Side JavaScript (EventSource)

<!DOCTYPE html>
<html>
<body>
  <div id="output"></div>
  <script>
    const message = "Explain SSE in one paragraph";
    const eventSource = new EventSource(
      `/api/chat/stream?message=${encodeURIComponent(message)}`
    );

    eventSource.onmessage = (event) => {
      const data = JSON.parse(event.data);
      if (data.done) {
        eventSource.close();
        return;
      }
      document.getElementById("output").textContent += data.token;
    };

    eventSource.onerror = (error) => {
      console.error("SSE error:", error);
      eventSource.close();
    };
  </script>
</body>
</html>

4. POST-Based SSE with fetch (for request bodies)

EventSource only supports GET, which is why the endpoint above reads message from the query string. For JSON bodies — conversation history, files, long prompts — keep the endpoint as POST and consume the stream with fetch and ReadableStream instead.

@app.post("/api/chat/stream-post")
async def chat_stream_post(request: ChatRequest):
    """SSE endpoint that accepts POST body."""
    return StreamingResponse(
        stream_openai_response(request.message, request.model),
        media_type="text/event-stream",
    )
// Client-side fetch-based SSE
async function streamChat(message) {
  const response = await fetch("/api/chat/stream-post", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ message }),
  });

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
  let buffer = "";

  while (true) {
    const { done, value } = await reader.read();
    if (done) break;

    buffer += decoder.decode(value, { stream: true });
    const lines = buffer.split("\n\n");
    buffer = lines.pop(); // Keep incomplete chunk in buffer

    for (const line of lines) {
      if (line.startsWith("data: ")) {
        const data = JSON.parse(line.slice(6));
        if (data.done) return;
        console.log(data.token);
      }
    }
  }
}

5. Streaming with Conversation History

class ChatHistoryRequest(BaseModel):
    messages: list[dict]
    model: str = "gpt-4o-mini"

async def stream_with_history(messages: list[dict], model: str):
    """Stream response with full conversation history."""
    stream = await client.chat.completions.create(
        model=model,
        messages=messages,
        stream=True,
    )

    async for chunk in stream:
        content = chunk.choices[0].delta.content
        if content is not None:
            yield f"data: {json.dumps({'token': content})}\n\n"

    yield f"data: {json.dumps({'done': True})}\n\n"

@app.post("/api/chat/conversation")
async def chat_conversation(request: ChatHistoryRequest):
    return StreamingResponse(
        stream_with_history(request.messages, request.model),
        media_type="text/event-stream",
    )

6. Error Handling in Stream

async def stream_with_error_handling(message: str, model: str):
    """Stream with proper error handling."""
    try:
        stream = await client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": message}],
            stream=True,
        )

        async for chunk in stream:
            content = chunk.choices[0].delta.content
            if content is not None:
                yield f"data: {json.dumps({'token': content})}\n\n"

        yield f"data: {json.dumps({'done': True})}\n\n"

    except Exception as e:
        yield f"data: {json.dumps({'error': str(e)})}\n\n"

7. Client Disconnect and Keep-Alives

Proxies and load balancers drop idle connections — typically after 30–60 seconds without data. Send SSE comments as heartbeats between tokens, and stop consuming the OpenAI stream when the client goes away.

from fastapi import Request

async def stream_resilient(request: Request, message: str, model: str):
    """Stream with heartbeat comments and disconnect detection."""
    stream = await client.chat.completions.create(
        model=model,
        messages=[{"role": "user", "content": message}],
        stream=True,
    )

    try:
        async for chunk in stream:
            if await request.is_disconnected():
                await stream.close()
                return

            content = chunk.choices[0].delta.content
            if content is not None:
                yield f"data: {json.dumps({'token': content})}\n\n"
            else:
                yield ": ping\n\n"  # Comment heartbeat keeps proxies alive

        yield f"data: {json.dumps({'done': True})}\n\n"
    except asyncio.CancelledError:
        await stream.close()
        raise

request.is_disconnected() is FastAPI’s way to poll the client state inside a generator. Lines starting with : are SSE comments — invisible to EventSource handlers but enough to reset idle timeouts on Nginx, Cloudflare and most load balancers.

How It Works

  1. stream=True tells the OpenAI API to return chunks as they’re generated instead of waiting for the full response. Each chunk contains a delta with the new tokens.
  2. Async generator (async def + yield) produces chunks one at a time. FastAPI’s StreamingResponse consumes the generator and sends each chunk to the client immediately.
  3. SSE format — each event is data: {json}\n\n. The client splits the stream on those data: lines and processes each JSON payload as it arrives; a blank line terminates the event.
  4. EventSource is the browser’s built-in SSE client (see the MDN EventSource reference). It automatically reconnects on disconnection and parses the event stream.
  5. done event signals the client that the stream is complete, allowing it to close the connection and clean up.
sequenceDiagram diagram: participant C as Client (EventSource)

Variants

LangChain Streaming

from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

async def stream_langchain(message: str):
    """Stream using LangChain LCEL."""
    chain = (
        ChatPromptTemplate.from_template("{question}")
        | ChatOpenAI(model="gpt-4o-mini", streaming=True)
        | StrOutputParser()
    )

    async for chunk in chain.astream({"question": message}):
        yield f"data: {json.dumps({'token': chunk})}\n\n"

    yield f"data: {json.dumps({'done': True})}\n\n"

Ollama Streaming (Local LLM)

import httpx

async def stream_ollama(message: str, model: str = "llama3"):
    """Stream from a local Ollama instance."""
    async with httpx.AsyncClient() as http_client:
        async with http_client.stream(
            "POST",
            "http://localhost:11434/api/generate",
            json={"model": model, "prompt": message, "stream": True},
        ) as response:
            async for line in response.aiter_lines():
                data = json.loads(line)
                if data.get("response"):
                    yield f"data: {json.dumps({'token': data['response']})}\n\n"
                if data.get("done"):
                    yield f"data: {json.dumps({'done': True})}\n\n"
                    break

Backpressure Handling

async def stream_with_backpressure(message: str, model: str):
    """Stream with backpressure — slow down if client can't keep up."""
    queue = asyncio.Queue(maxsize=10)
    producer_done = asyncio.Event()

    async def producer():
        stream = await client.chat.completions.create(
            model=model,
            messages=[{"role": "user", "content": message}],
            stream=True,
        )
        async for chunk in stream:
            content = chunk.choices[0].delta.content
            if content:
                await queue.put(content)  # Blocks if queue is full
        producer_done.set()

    asyncio.create_task(producer())

    while not (producer_done.is_set() and queue.empty()):
        try:
            token = await asyncio.wait_for(queue.get(), timeout=30)
            yield f"data: {json.dumps({'token': token})}\n\n"
        except asyncio.TimeoutError:
            yield f"data: {json.dumps({'error': 'timeout'})}\n\n"
            break

    yield f"data: {json.dumps({'done': True})}\n\n"

Best Practices

  • Set X-Accel-Buffering: no — prevents Nginx from buffering the stream, which breaks real-time delivery
  • Handle client disconnection — poll request.is_disconnected() inside the generator and close the OpenAI stream when the client goes away
  • Send heartbeats between tokens — SSE comment lines (: ping) keep proxies from killing idle connections
  • Send a done event — lets the client know the stream is complete vs. an error
  • Use POST for request bodies — EventSource only supports GET; use fetch with ReadableStream for POST

For a deeper guide, see Complete Guide to OpenAI API Mastery. For the streaming parameters, see the OpenAI streaming documentation.

Common Mistakes

  • Not setting media_type="text/event-stream" — the browser won’t parse SSE without the correct content type
  • Buffering in a reverse proxy — Nginx and Cloudflare buffer responses by default; disable buffering for SSE endpoints
  • Not handling delta.content being None — the first and last chunks may have None content (role and finish reason)
  • Using EventSource for POST — EventSource only supports GET; use fetch with streaming for POST requests

Frequently Asked Questions

SSE vs. WebSocket — which should I use for LLM streaming?

SSE is simpler and sufficient for server-to-client streaming (which is all LLM streaming needs). Use WebSocket if you need bidirectional communication.

Does streaming reduce total latency?

No — the total time to generate the full response is the same. Streaming reduces perceived latency by showing tokens as they arrive.

Can I stream with function calling?

Yes. OpenAI streams function call arguments as deltas. You need to accumulate the chunks and parse the complete JSON at the end.

How do I handle rate limits during streaming?

Streaming responses count as one API call. Implement retry with exponential backoff on 429 errors before starting the stream.

Does EventSource reconnect automatically?

Yes. It retries the connection after a drop and sends a Last-Event-ID header with the last received event. If you emit id: fields in your events, the server can resume from that point.

Why does my stream arrive all at once instead of token by token?

Something is buffering it — usually a reverse proxy. Set X-Accel-Buffering: no on Nginx, check that your CDN doesn't buffer text/event-stream, and confirm FastAPI isn't behind middleware that awaits the full body.

How do I authenticate an SSE endpoint?

EventSource can't set custom headers, so use a cookie-based session or a short-lived token in the query string. With fetch-based streaming you can send Authorization headers normally.