Skip to main content

AI and machine learning · Intermediate · 22 min

Stream LLM answers to a web page through FastAPI

By Padding · Updated 18 Nov 2026
Python 3.15 (python:3.15-slim) · FastAPI 0.165.0 · uvicorn 0.54.0 · anthropic SDK 2.14.0 · Claude Opus 5.5

You will have a FastAPI endpoint that relays a Claude stream to a web page as server-sent events, ends with the stop reason and token counts, closes the upstream call when the reader leaves, turns API failures into an error event and passes through Nginx without buffering.

On this page

A chat answer from a large language model can take ten or twenty seconds to finish. If your web page waits for the whole thing, the reader stares at a spinner and wonders whether anything is happening. If the page shows words as the model writes them, the reader starts reading within a second or two. Most chat products do this, and so can yours.

The model's API already streams. The job is to relay that stream through your own server to the browser, because the browser must never hold your API key. In this tutorial you build that relay with FastAPI. The server receives a question, opens a streaming call to Claude with Anthropic's Python SDK, and passes each piece of text on as a server-sent event. The page reads those events with fetch and shows them as they arrive.

A relay that works on a good day is the easy part. This one also handles the three things that go wrong in production:

  • The reader leaves. They close the tab, press Stop, or their phone loses signal. Your server should stop the upstream call instead of reading an answer nobody will see.
  • The API fails part-way. The HTTP status 200 has already gone to the browser, so an error has to travel as an event the page understands.
  • A proxy holds the stream back. Nginx buffers responses by default, which turns a smooth stream into one late burst.

If you have not used the SDK's streaming helper yet, start with stream Claude responses in Python. For the generic server-sent events format, reconnection and Last-Event-ID, see stream live updates with server-sent events. This tutorial covers what changes when an LLM sits at the other end.

Step 1 · Create the project and load your key

Make a demo folder and add the three packages at exact versions, so the code below behaves as described:

Bash
mkdir -p ~/stream-demo
cd ~/stream-demo
uv init --no-package
uv add fastapi==0.165.0 uvicorn==0.54.0 anthropic==2.14.0

FastAPI gives you the routes and request validation. Uvicorn is the server that runs the app. anthropic is the official SDK, which reads your key from the ANTHROPIC_API_KEY environment variable. Load the key file into this terminal. set -a exports every variable the file defines, so the key never appears in your shell history:

Bash
set -a
. ~/.config/llm-demo/env
set +a

Run those three lines again in every new terminal you use for this tutorial.

Check it worked

Bash
uv run python -c "import fastapi, uvicorn, anthropic; print(fastapi.__version__, uvicorn.__version__, anthropic.__version__)"
test -n "$ANTHROPIC_API_KEY" && echo "key is set"

The output is 0.165.0 0.54.0 2.14.0 and then key is set.

Step 2 · Write the streaming endpoint

Create app.py. Read it through once; the notes after it explain the parts that matter:

Bash
cd ~/stream-demo
cat > app.py <<'PY'
import asyncio
import json
import logging
import os
from pathlib import Path

import anthropic
import anyio
from fastapi import FastAPI
from fastapi.responses import FileResponse, StreamingResponse
from pydantic import BaseModel, Field

MODEL = "claude-opus-5-5"
# Room for the model's thinking as well as the answer: both count toward max_tokens.
MAX_TOKENS = int(os.environ.get("MAX_TOKENS", "16000"))
SYSTEM = "You answer questions from people learning web development. Be clear and brief."
PAGE = Path(__file__).parent / "index.html"
FRIENDLY = {
    "overloaded_error": "The model is busy right now. Try again in a minute.",
    "rate_limit_error": "Too many questions at once. Try again in a minute.",
}

log = logging.getLogger("uvicorn.error")
client = anthropic.AsyncAnthropic()  # reads ANTHROPIC_API_KEY from the environment
app = FastAPI()


class Question(BaseModel):
    question: str = Field(min_length=1, max_length=4000)


def sse(event: str, data: dict) -> str:
    """Format one server-sent event: a name line, a data line, a blank line."""
    return f"event: {event}\ndata: {json.dumps(data)}\n\n"


async def relay(question: str):
    chunks = 0
    try:
        async with client.messages.stream(
            model=MODEL,
            max_tokens=MAX_TOKENS,
            system=SYSTEM,
            output_config={"effort": "low"},
            messages=[{"role": "user", "content": question}],
        ) as stream:
            try:
                async for text in stream.text_stream:
                    chunks += 1
                    yield sse("delta", {"text": text})
            except (asyncio.CancelledError, GeneratorExit):
                # The browser has gone. Close the upstream stream inside a shielded
                # scope, so the cancellation cannot interrupt the clean-up.
                with anyio.CancelScope(shield=True):
                    await stream.close()
                log.info("browser left after %d chunks; upstream stream closed", chunks)
                raise
            final = await stream.get_final_message()
    except anthropic.APIStatusError as err:
        log.warning("API error after %d chunks: %s", chunks, err.type)
        message = FRIENDLY.get(err.type, "Something went wrong while answering. Try again.")
        yield sse("error", {"type": err.type or "api_error", "message": message})
        return
    except anthropic.APIConnectionError:
        log.warning("could not reach the API after %d chunks", chunks)
        yield sse("error", {"type": "connection_error", "message": "The model service could not be reached. Try again."})
        return
    yield sse("done", {
        "stop_reason": final.stop_reason,
        "input_tokens": final.usage.input_tokens,
        "output_tokens": final.usage.output_tokens,
    })


@app.get("/")
async def page():
    return FileResponse(PAGE)


@app.post("/ask")
async def ask(q: Question):
    return StreamingResponse(
        relay(q.question),
        media_type="text/event-stream",
        headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
    )
PY

What each part does:

  • AsyncAnthropic and async with client.messages.stream(...). The async client lets one Uvicorn process relay many answers at once, because waiting for the next token does not block other requests. text_stream yields only the text pieces. Claude Opus 5.5 always thinks before it answers, and those thinking blocks arrive with empty text by default, so text_stream skips them. That thinking is why the first word can take a moment. output_config={"effort": "low"} asks for less thinking, which suits short chat answers.
  • sse(). A server-sent event is plain text: an event: line naming it, a data: line holding it, and a blank line to end it. The page gets three kinds: delta for each piece of text, done when the answer is complete, and error.
  • The done event. get_final_message() returns the whole message once the stream ends. Its stop_reason says why the model stopped (end_turn, max_tokens or refusal), and usage gives the token counts you are billed for. Output tokens include the thinking you never see.
  • except (asyncio.CancelledError, GeneratorExit). When the browser disconnects, Starlette, the toolkit under FastAPI, cancels the generator. The handler closes the upstream stream and logs it, then re-raises so the cancellation finishes normally.
  • except anthropic.APIStatusError. The SDK raises this for an error response when the call opens, and also for an error event that arrives part-way through a stream. Either way, the browser already has status 200, so the error goes out as an event. err.type is the API's error type, such as overloaded_error. The friendly text is what a reader sees; the type is for your page's logic and your logs.
  • The headers. Cache-Control: no-cache stops caches holding on to the stream. X-Accel-Buffering: no tells Nginx not to buffer this response.
  • Question. Pydantic rejects an empty or very long question with a 422 before any tokens are spent.

FastAPI 0.165 also ships EventSourceResponse and ServerSentEvent in fastapi.sse, which format events for you when a route yields them. The hand-written sse() function keeps the wire format visible here, and it works the same way.

Check it worked

Bash
cd ~/stream-demo
uv run python -c "import app; print(app.MODEL, app.MAX_TOKENS)"

The output is claude-opus-5-5 16000. An ImportError or SyntaxError here means the file was not copied in full.

Step 3 · Start the server and read the stream with curl

In your second terminal, load the key and start the app:

Bash
cd ~/stream-demo
set -a
. ~/.config/llm-demo/env
set +a
uv run uvicorn app:app --host 127.0.0.1 --port 8000

Uvicorn prints a line like Uvicorn running on http://127.0.0.1:8000. Back in the first terminal, ask a question. --json sends the body as JSON, and -N turns off curl's own buffering, so each event prints the moment it arrives:

Bash
curl -sN --json '{"question": "Why do chat apps show answers word by word?"}' http://127.0.0.1:8000/ask

Now look at the response headers, and at what happens to a request the model should never see:

Bash
curl -s -D - -o /dev/null --json '{"question": "Hi"}' http://127.0.0.1:8000/ask
curl -s -o /dev/null -w '%{http_code}\n' --json '{"question": ""}' http://127.0.0.1:8000/ask

Check it worked

The first command prints a run of event: delta blocks, each with a data: line holding a few words, and ends with one done event such as:

Text
event: done
data: {"stop_reason": "end_turn", "input_tokens": 31, "output_tokens": 412}

Your wording and counts differ on every run. The headers include content-type: text/event-stream; charset=utf-8, cache-control: no-cache and x-accel-buffering: no. The empty question prints 422: validation errors still get a proper status code, because they happen before the stream starts.

Step 4 · Build the page that reads the stream

Browsers have a built-in reader for server-sent events, EventSource, but it can only make GET requests and cannot send a body. A question can be long, and it does not belong in a URL that ends up in server logs, so the page uses fetch with POST and reads the response body as it arrives. Create index.html next to app.py:

Bash
cd ~/stream-demo
cat > index.html <<'HTML'
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Ask the model</title>
  <style>
    body { font-family: system-ui, sans-serif; max-width: 40rem; margin: 2rem auto; padding: 0 1rem; line-height: 1.5; }
    textarea { width: 100%; font: inherit; box-sizing: border-box; }
    #answer { white-space: pre-wrap; min-height: 4rem; border-left: 3px solid #9ba1ac; padding-left: 0.75rem; }
    #status { color: #2a2d33; }
  </style>
</head>
<body>
  <h1>Ask the model</h1>
  <form id="ask">
    <label for="question">Your question</label>
    <textarea id="question" name="question" rows="3" maxlength="4000" required></textarea>
    <p>
      <button type="submit" id="send">Ask</button>
      <button type="button" id="stop" disabled>Stop</button>
    </p>
  </form>
  <div id="answer" aria-live="polite"></div>
  <p id="statusLine" role="status"></p>

  <script>
    const form = document.querySelector('#ask');
    const answer = document.querySelector('#answer');
    const statusLine = document.querySelector('#statusLine');
    const sendButton = document.querySelector('#send');
    const stopButton = document.querySelector('#stop');
    let controller = null;

    function handle(name, data) {
      if (name === 'delta') {
        answer.textContent += data.text;
      } else if (name === 'done') {
        if (!answer.textContent) answer.textContent = '(No answer text came back.)';
        let note = '';
        if (data.stop_reason === 'max_tokens') note = ' The answer was cut short by the length limit.';
        if (data.stop_reason === 'refusal') note = ' The model declined to answer this question.';
        statusLine.textContent = `Finished: ${data.input_tokens} tokens in, ${data.output_tokens} out.${note}`;
      } else if (name === 'error') {
        statusLine.textContent = data.message;
      }
    }

    function parseEvent(block) {
      let name = 'message';
      const lines = [];
      for (const line of block.split('\n')) {
        if (line.startsWith('event:')) name = line.slice(6).trim();
        else if (line.startsWith('data:')) lines.push(line.slice(5).trimStart());
      }
      if (lines.length) handle(name, JSON.parse(lines.join('\n')));
    }

    form.addEventListener('submit', async (event) => {
      event.preventDefault();
      answer.textContent = '';
      answer.setAttribute('aria-busy', 'true');
      statusLine.textContent = 'Waiting for the first words...';
      controller = new AbortController();
      sendButton.disabled = true;
      stopButton.disabled = false;
      try {
        const response = await fetch('/ask', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ question: form.question.value }),
          signal: controller.signal,
        });
        if (!response.ok) {
          statusLine.textContent = `The server could not take that question (status ${response.status}).`;
          return;
        }
        statusLine.textContent = 'Answering...';
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';
        for (;;) {
          const { value, done } = await reader.read();
          if (done) break;
          // stream: true keeps a character split across two chunks intact.
          buffer += decoder.decode(value, { stream: true });
          let end;
          while ((end = buffer.indexOf('\n\n')) !== -1) {
            parseEvent(buffer.slice(0, end));
            buffer = buffer.slice(end + 2);
          }
        }
      } catch (error) {
        statusLine.textContent = error.name === 'AbortError'
          ? 'Stopped.'
          : 'The connection dropped before the answer finished. Try again.';
      } finally {
        answer.setAttribute('aria-busy', 'false');
        sendButton.disabled = false;
        stopButton.disabled = true;
        controller = null;
      }
    });

    stopButton.addEventListener('click', () => controller?.abort());
  </script>
</body>
</html>
HTML

The parts worth copying into your own front end:

  • Splitting on a blank line. Network chunks do not line up with events: one chunk can hold half an event or three of them. The page keeps a buffer and only parses up to each \n\n, which is where an event ends.
  • TextDecoder with stream: true. A character such as é or ọ takes more than one byte in UTF-8 and can be split across chunks. Stream mode holds the partial bytes until the rest arrives, so answers in Yoruba, Amharic or French come through intact.
  • textContent, never innerHTML. The model's text can contain anything, including markup. Writing it as text means it can never run as code in your page.
  • aria-busy and role="status". Screen readers wait while the answer is being written instead of reading every few words, and the status line announces when it finishes.
  • The Stop button. controller.abort() closes the connection. On the server this is the same disconnect as a closed tab, so the upstream call stops too.

Check it worked

Open http://127.0.0.1:8000 in your browser, type a question and press Ask. The status line changes to Answering... and words appear in the answer box a few at a time, without a reload. When the answer ends, the status line shows the token counts, for example Finished: 31 tokens in, 412 out. If nothing appears until the very end, check in the developer tools Network tab that /ask answers with Content-Type: text/event-stream.

Step 5 · Stop the upstream call when the reader leaves

Ask for something long, and press Ctrl+C after a few lines have printed:

Bash
curl -N --json '{"question": "Write a long essay on the history of HTTP."}' http://127.0.0.1:8000/ask

When curl exits, it closes its connection. Uvicorn notices and tells Starlette, which cancels the relay generator wherever it is waiting. The except block in relay closes the SDK stream, which closes the connection to the API. Nothing is left reading an answer that nobody will see.

This matters more than it seems. Readers on mobile data close tabs, lose signal in a lift or run out of prepaid data in the middle of an answer. Without this, each of those leaves your server holding an open API connection until the model finishes, and a busy app can run out of connections. The cut-off also stops your server spending effort on the rest of the answer. Do not count on it to reduce the bill, though: you pay for the tokens the model generated, and some of those may be produced after you hang up.

Check it worked

In the second terminal, Uvicorn prints a line such as:

Text
INFO:     browser left after 14 chunks; upstream stream closed

The number depends on when you pressed Ctrl+C. Try the same from the page: ask for a long essay, then press Stop. The page says Stopped. and the same log line appears.

Step 6 · Turn API errors into an error event

Errors in a streaming endpoint come in two kinds. Some arrive when the call opens: a wrong key, a rate limit or an invalid request. The SDK already retries rate limits and server errors twice before it gives up. Others arrive in the middle of the stream: the API's streaming documentation shows an overloaded_error event arriving after the response has started, with no retry possible because part of the answer has already been sent. In both cases your page has already received status 200.

You can see the first kind without waiting for an outage. Start a second copy of the app on port 8001 with a key that is deliberately wrong. In the second terminal, press Ctrl+C to stop the app, then run:

Bash
ANTHROPIC_API_KEY=not-a-real-key uv run uvicorn app:app --host 127.0.0.1 --port 8001

Ask it a question, and check the status code it sends:

Bash
curl -sN --json '{"question": "Hello?"}' http://127.0.0.1:8001/ask
curl -s -o /dev/null -w '%{http_code}\n' --json '{"question": "Hello?"}' http://127.0.0.1:8001/ask

The SDK handles a mid-stream error the same way: when an error event arrives on the upstream stream, text_stream raises APIStatusError, and the except block in relay sends your own error event after whatever text has already gone out. The page then shows the partial answer with The model is busy right now. Try again in a minute. under it, which is more honest than pretending the half-answer is complete.

Check it worked

The first command prints one event and no text:

Text
event: error
data: {"type": "authentication_error", "message": "Something went wrong while answering. Try again."}

The second prints 200. That is the reason the error has to be an event: the status line went out before the API answered. The second terminal shows API error after 0 chunks: authentication_error, which is the line to alert on, since it means your server's key is wrong. Press Ctrl+C to stop this copy.

Step 7 · Show when an answer was cut short

max_tokens caps the whole reply, and the model's thinking counts toward it. If the cap is too low, the answer stops part-way, or thinking uses all of it and no text arrives at all. The done event tells the page which happened. Start a copy on port 8002 with a deliberately tiny cap:

Bash
MAX_TOKENS=50 uv run uvicorn app:app --host 127.0.0.1 --port 8002
Bash
curl -sN --json '{"question": "Compare three ways to store sessions in a web app."}' http://127.0.0.1:8002/ask

Check it worked

The stream ends with a done event whose stop_reason is max_tokens and whose output_tokens is 50. There may be a few delta events before it, or none if thinking used the whole cap. Open http://127.0.0.1:8002 and ask the same question: the page shows any partial text, or (No answer text came back.), with The answer was cut short by the length limit. in the status line. Press Ctrl+C to stop this copy, and start the normal one on port 8000 again for the next step. In your own app, keep the cap high enough for thinking plus a full answer, and watch for max_tokens in your logs.

Step 8 · Put the endpoint behind Nginx without buffering

Nginx buffers proxied responses by default: it collects what your app sends before passing it on. For a page that is right; for a stream it means the reader sees nothing, then the whole answer at once. The X-Accel-Buffering: no header your app sends already turns buffering off for /ask. Set it in Nginx as well, so the stream still works if a later change drops the header.

If your app is not behind Nginx yet, set up a reverse proxy first, as in put a Node app behind an Nginx reverse proxy; the Nginx side is the same for Uvicorn on port 8000. Then add this block inside the same server block, above the general location /:

Nginx
location /ask {
    proxy_pass http://127.0.0.1:8000;
    proxy_http_version 1.1;
    proxy_set_header Connection '';
    proxy_set_header Host $host;
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 300s;
    gzip off;
}
  • proxy_buffering off passes each event on as soon as Uvicorn writes it.
  • proxy_read_timeout 300s raises the 60-second default. That default counts the time between two reads, and a model that thinks for a long time before its first word can go quiet for longer than you expect.
  • gzip off stops compression from holding bytes back until it has a block worth compressing.

Test the configuration and reload Nginx:

Bash
sudo nginx -t
sudo systemctl reload nginx

Check it worked

sudo nginx -t reports that the syntax is ok and the test is successful. From your laptop, run the curl command from the third step against https://your-domain.example/ask, replacing the domain with yours. The delta events print a few at a time, as they did on port 8000, not all together at the end.

Step 9 · Stop the servers and clean up

Press Ctrl+C in the second terminal to stop Uvicorn, then remove the demo folder. The key file stays, because the other LLM tutorials load it:

Bash
cd ~
rm -rf ~/stream-demo

If you added the /ask location to a real Nginx site for this tutorial, remove it and reload Nginx.

Check it worked

curl http://127.0.0.1:8000/ask reports that it failed to connect, and ls ~/stream-demo reports that there is no such file or directory.

Next steps

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

AI-Integrated Solutions

Get new tutorials

New tutorials, about twice a month.