Sub topic 13
Letting users stop generation
This chapter assumes you can read the fetch streaming client and the FastAPI relay from earlier chapters. It also assumes you know basic asyncio and promises.
Why stopping needs work
A user who sees a wrong answer forming wants to press Stop. Hiding the text is not enough. The model keeps generating, and you keep paying for tokens nobody reads. A real stop has to travel from the button back to the model API.
Cancelling in the browser
Pass an AbortController signal to fetch. Calling abort() closes the connection. The pending reader.read() then rejects with an error named AbortError. This is an expected outcome, so don't treat it as a failure.
const controller = new AbortController();
let text = "";
async function run() {
try {
await streamCompletion(
"/api/chat",
{ prompt: "Hello" },
(data) => { text += data; },
controller.signal
);
} catch (err) {
if (err.name !== "AbortError") throw err;
}
console.log("Final text:", text);
}
document.querySelector("#stop").addEventListener("click", () => controller.abort());
run();An AbortController works once. Create a new one for each request.
Cancelling on the server
If your backend relays the stream, closing the browser connection does not stop the provider by itself. The relay must close its upstream request. Starlette cancels the response generator when the client disconnects, so a finally block is a reliable place to clean up.
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
async def relay(prompt: str):
stream = await client.chat.completions.create(
model="MODEL_NAME",
messages=[{"role": "user", "content": prompt}],
stream=True,
)
try:
async for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
piece = chunk.choices[0].delta.content
yield f"data: {json.dumps({'delta': piece})}\n\n"
yield "data: [DONE]\n\n"
finally:
await stream.close() # stops the upstream request
@app.post("/api/chat")
async def chat(req: ChatRequest):
return StreamingResponse(relay(req.prompt), media_type="text/event-stream")Without the finally block, the upstream stream can stay open until the model finishes. You would pay for the whole answer.
What to do with the partial text
- Keep what has arrived and show it as a normal message. Many apps label it as stopped.
- Add the partial text to the conversation history if the user may continue. Otherwise the next request lacks context.
- Expect no
finish_reasonand possibly no usage data. Providers often skip the final usage chunk when you disconnect, so billing figures can differ from your own counts. - Flip the button back from Stop to Send in a
finallyblock, so it resets whether the stream ended, failed or was aborted.
Common errors
| Symptom | Likely cause |
|---|---|
| Stop hides text but costs keep rising | The relay never closes the upstream stream |
| Console shows an uncaught `AbortError` | The catch block does not filter by `err.name` |
| Second request fails instantly | The aborted controller was reused |
Exercise
A user clicks Stop. The browser stops showing text, but your provider dashboard shows the full response was billed. Where is the most likely bug, and how do you fix it?
Show answer
The relay server did not close its upstream request when the browser disconnected. Wrap the upstream iteration in try/finally and close the upstream stream in the finally block, so a client disconnect cancels generation at the provider.