Sub topic 12
Relaying the stream through your own server
This chapter assumes you can read the provider stream and parse SSE events from the earlier chapters. It also assumes basic FastAPI and async Python.
Why relay at all
Browsers should not call the model API directly, because that would expose your API key. Your server sits in the middle. It holds the key, adds authentication, rate limits and logging, and forwards the model's output to the browser as it arrives.
A minimal relay
The server consumes the provider stream with async for and yields one SSE event per delta. It encodes each delta as JSON, so tokens that contain newlines do not break the data: line.
import json
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from openai import AsyncOpenAI
from pydantic import BaseModel
app = FastAPI()
client = AsyncOpenAI()
class ChatRequest(BaseModel):
prompt: str
def sse(data: str, event: str | None = None) -> str:
head = f"event: {event}\n" if event else ""
return f"{head}data: {data}\n\n"
async def relay(prompt: str):
try:
stream = await client.chat.completions.create(
model="MODEL_NAME",
messages=[{"role": "user", "content": prompt}],
stream=True,
)
async with stream: # closes the upstream request if we stop early
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
piece = chunk.choices[0].delta.content
yield sse(json.dumps({"delta": piece}))
yield sse("[DONE]")
except Exception:
# Headers are already sent, so report the failure inside the stream.
yield sse(json.dumps({"message": "upstream failed"}), event="error")
@app.post("/api/chat")
async def chat(req: ChatRequest):
return StreamingResponse(
relay(req.prompt),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)Save this as app.py and run it with uvicorn app:app. Set OPENAI_API_KEY first.
What to get right
- Use an async client. A synchronous call inside an async endpoint blocks the event loop, so every other stream on that worker stalls.
- Forward as you read. Do not collect the deltas into a list and send them at the end. That removes the benefit of streaming.
- Send headers that prevent buffering.
Cache-Control: no-cachestops caches from holding the response.X-Accel-Buffering: notells nginx to pass bytes through immediately. - Report errors in the stream. After the first byte, the HTTP status is already
200. The relay can no longer change it, so it sends a namederrorevent for the client to handle. - Stop upstream work when the client leaves. When the browser disconnects, Starlette cancels the generator. The
async with streamblock then closes the provider connection, so you stop paying for tokens nobody reads.
Exercise
Why does the relay wrap each delta in json.dumps instead of writing data: {piece} directly?
Show answer
A token can contain a newline. Written raw, it would end the data: line early and corrupt the event. JSON encoding turns the newline into \n inside a string, so each event stays on one line and the client recovers the exact text with JSON.parse.