Short answer: Stream LLM responses to Next.js by sending the prompt in a POST request and returning a text/event-stream response from FastAPI. Use the browser’s fetch API to read the stream, and wire the Stop button to an AbortController . The server must also close the upstream provider stream. Start with a deterministic mock so you can see all three pieces work before adding a model.
Why use Server-Sent Events instead of WebSockets for LLM streaming?
A chat answer flows one way, from server to browser. SSE is plain HTTP and needs no connection state on the server. It usually passes through load balancers, but a proxy may buffer it, which is covered below. WebSockets earn their extra work when the browser also needs to push data during the response, such as live audio.
How do you stream an LLM response from FastAPI?
FastAPI 0.135.0 added EventSourceResponse and ServerSentEvent in fastapi.sse , and the example below uses them.…