Sub topic 12
Relaying the stream through your own server
This chapter assumes you can read Python and JavaScript, know the Server-Sent Events (SSE) format, and have seen a streamed chat completion arrive as delta events. It also assumes you know basic asyncio and HTTP. Here you will put a server between the browser and the model API and forward the stream without breaking it.
Why put a server in the middle
A browser can't call the model API directly in most products, for these reasons:
- Secrets. The API key must never ship to the browser. Anyone who opens developer tools could copy it.
- Access control. Your server decides who may call the model, applies rate limits, and rejects oversized prompts.
- Accounting. Your server sees the final usage numbers and can record them per user.
- Persistence. Your server can save the finished message to a database.
- Stable contract. The browser talks to one event format that you control. You can change providers or model versions without touching the frontend.
The cost is that your server is now part of the streaming path. If it buffers, the user sees nothing until the model finishes. If it drops errors, the user sees a stalled answer.
The shape of a relay
A relay holds two HTTP connections open at once. It sends one streamed request upstream to the model API and returns one streamed response downstream to the browser. Each upstream event is read, optionally transformed, and written downstream as soon as it arrives.
Pass-through or re-encode
You have two options for what to send downstream.
| Approach | What the server does | Good for | Drawback |
|---|---|---|---|
| Pass-through | Copies upstream bytes to the client unchanged | Thin proxies, quick prototypes | The frontend depends on the provider's format. You can't easily inspect or save the text. |
| Re-encode | Parses each upstream event and emits your own events | Real products | You write and maintain a small parser and a mapping. |
This chapter uses re-encoding. Parsing lets you accumulate the text for storage, read the usage chunk, and translate errors into something the frontend understands.
A complete relay
The endpoint below uses FastAPI and httpx. It parses the provider's stream line by line, emits JSON events, and reports failures in the stream. Replace MODEL_NAME with a model you can use.
import json
import os
import httpx
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field
app = FastAPI()
API_URL = "https://api.openai.com/v1/chat/completions"
MODEL = "MODEL_NAME"
class ChatRequest(BaseModel):
prompt: str = Field(min_length=1, max_length=4000)
def sse(payload: dict) -> str:
# json.dumps escapes newlines, so each event stays on one data line.
return f"data: {json.dumps(payload)}\n\n"
async def relay(prompt: str):
body = {
"model": MODEL,
"messages": [{"role": "user", "content": prompt}],
"stream": True,
"stream_options": {"include_usage": True},
}
headers = {"Authorization": f"Bearer {os.environ['OPENAI_API_KEY']}"}
timeout = httpx.Timeout(10.0, read=60.0)
parts = []
finish_reason = None
usage = None
try:
async with httpx.AsyncClient(timeout=timeout) as client:
async with client.stream(
"POST", API_URL, json=body, headers=headers
) as upstream:
if upstream.status_code != 200:
yield sse({"type": "error", "status": upstream.status_code})
return
async for line in upstream.aiter_lines():
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
break
chunk = json.loads(data)
if chunk.get("usage"):
usage = chunk["usage"]
for choice in chunk.get("choices", []):
piece = choice["delta"].get("content")
if piece:
parts.append(piece)
yield sse({"type": "delta", "text": piece})
if choice.get("finish_reason"):
finish_reason = choice["finish_reason"]
yield sse({"type": "done", "finish_reason": finish_reason, "usage": usage})
except (httpx.HTTPError, json.JSONDecodeError):
yield sse({"type": "error", "status": 502})
finally:
# Runs on success, error, and client disconnect. Do not yield here.
full_text = "".join(parts)
print(f"saved {len(full_text)} characters, usage={usage}")
@app.post("/api/chat")
async def chat(request: ChatRequest):
return StreamingResponse(
relay(request.prompt),
media_type="text/event-stream",
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
)The browser function from the previous chapter reads this stream unchanged, because every event is one data: line. Its callback receives JSON strings, so it calls JSON.parse and switches on type.
What the code is doing
Line-based parsing
aiter_lines() buffers partial lines internally, so network chunk boundaries don't split a line. This relay depends on a provider detail: each event carries exactly one data: line. A provider that spreads one event over several data: lines needs the join logic from the parser you wrote earlier.
The generator owns both connections
Both async with blocks live inside the generator. When the generator finishes, raises, or is closed because the client disconnected, the context managers close the upstream connection. Closing it stops the provider from generating, so you stop paying for tokens nobody reads. Cancellation gets its own chapter. For now, keep the upstream request inside the generator.
Errors have no status code
The response headers, including 200 OK, are sent when the first byte goes out. After that you can't change the status. The error event is how the relay tells the browser that something went wrong. The frontend must treat a stream that ends without a done event as a failure, even though HTTP said 200.
Accumulate on the server too
The relay collects parts while it forwards. The finally block then has the text and usage available for storage. If the user cancels halfway, you still hold the partial text. Decide deliberately whether to save a partial message and how to mark it.
Keeping the stream unbuffered
A relay can still hide the stream if something between the model and the browser holds data back. Check these places:
- Your framework. Return a streaming response type, as above. Returning a list or joined string waits for everything.
- Compression middleware. Gzip middleware may collect data before it flushes. Exempt
text/event-streamresponses. - Reverse proxies. nginx buffers responses by default. The
X-Accel-Buffering: noheader turns that off per response. Other proxies and CDNs have their own settings. - Synchronous code in an async server. A blocking call inside an
async defhandler freezes the event loop and stalls every stream on that worker. Use async clients, or run blocking code in a thread.
Common mistakes
- Opening a new
AsyncClientper request is acceptable in a small example. In production, share one client so connections are reused. - Setting a single total timeout. A long answer is a long-lived request, so use a short connect timeout and a read timeout that applies between chunks.
- Using
GETwith the prompt in the URL. Prompts can be long and sensitive, so usePOSTand a JSON body. - Skipping input validation. Cap prompt length and require authentication before you open the upstream request. An unauthenticated streaming endpoint is an open tap on your bill.
- Yielding inside
finally. If the client has already gone, writing again raises errors and can hide the original problem.
Exercise
The relay has already sent the first delta when the provider connection times out. Why can't the server respond with a 504 status, and what should it do instead?
Show answer
HTTP status and headers are sent before the body, and the first delta has already been written, so the 200 status is final. The server should send an in-stream error event (for example type "error"), end the stream, and log the details. The client should treat a stream with no done event as incomplete.
Exercise
Why does the relay parse upstream events and re-emit its own, instead of copying bytes through?
Show answer
Parsing lets the server accumulate the full text for storage, read usage data from the final chunk, replace provider errors with a safe shape, and give the frontend a stable event format that does not change when the provider or model changes.