Streaming and Cancellation
Stream a model answer as server-sent events: read the raw event stream, use the SDK streaming helpers, cancel an in-flight request with asyncio, and relay a stream to a browser through FastAPI so that generation stops when the user leaves.
Contentsand lesson path
On this page
- The problem
- Step 1: Look at the raw stream
- Step 2: Stream with the SDK helpers
- Step 3: Parse server-sent events yourself
- Step 4: Cancel a request in flight
- Step 5: Relay to a browser and stop when it leaves
- Common mistakes
- Check your understanding
- Apply it
- Review prompt
Lessons of LLM API Integration
- Anatomy of a Request: Messages, Parameters and Media Concept · 15 min
- First Calls: Parameters, Usage, Images and Audio Worked example · 25 min
- Lab: Retries, Backoff and Timeouts Lab · 25 min
- Streaming and Cancellation Worked example · 20 min
- Lab: One Client for Hosted, Local and Mock Models Lab · 30 min
- Check: Diagnose Failing API Calls Knowledge check · 10 questions
What you will learn
- Stream a response to a client and cancel an in-flight request cleanly.
Prerequisites: Python Foundations, HTTP & APIs
01. The problem
The support assistant from lesson 2 works, but agents stare at a spinner while a long answer takes twenty seconds or more. Worse, an agent who sees the answer going wrong cannot stop it, so the model keeps generating, and billing, tokens nobody reads. You need:
- text on screen as soon as the model produces it, with the stop reason and usage still recorded at the end;
- a way to cancel a request that is in progress, which closes the upstream connection and frees your worker;
- a server endpoint that relays the stream to a browser and stops generating when the browser goes away.
You will build each piece against the stand-in from lesson 2, which streams one token every 50 milliseconds and prints a line when a client hangs up early. Keep it running in terminal 1, with the environment variables set in terminal 2.
02. Step 1: Look at the raw stream
Ask for a stream by adding "stream": true to the request body. curl -N prints the response as it arrives instead of buffering it, -d @- reads the body from the lines that follow, and the end of the command keeps the first eight lines, cut at 88 characters:
curl -sN http://127.0.0.1:8100/v1/messages -H "Content-Type: application/json" \
-d @- <<'EOF' | head -n 8 | cut -c 1-88
{"model": "m", "max_tokens": 50, "stream": true,
"messages": [{"role": "user", "content": "Hi"}]}
EOFevent: message_start
data: {"type":"message_start","message":{"id":"msg_fake_1","type":"message","role":"assi
event: content_block_start
data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}
event: content_block_delta
data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Fake"This is one long HTTP response with the content type text/event-stream. Each event is an event: line naming its type and a data: line of JSON, then a blank line. The Messages API sends them in a fixed order:
message_start, with the message id, the model and the input token count;content_block_start, then manycontent_block_deltaevents carrying a few characters each, thencontent_block_stop;message_delta, with the stop reason and the output token count (usage counts in this event are running totals);message_stop.
Real streams also carry ping events, and can carry an error event, such as overloaded_error, after the status 200 has been sent. Stream readers must skip unknown event types and treat error as a failure despite the 200. Chat completions stream data: lines only: each chunk carries new text in choices[0].delta.content, the last chunk with choices has the finish_reason, an extra chunk with usage follows if you ask for it, and data: [DONE] ends the stream.
03. Step 2: Stream with the SDK helpers
The anthropic SDK parses the events for you. messages.stream() is a context manager: text_stream yields only the text, and get_final_message() returns the same Message object a plain call would, with the stop reason and usage. The script also measures when the first text arrived:
import os
import time
import anthropic
from ask_claude import SYSTEM, history
client = anthropic.Anthropic()
started = time.monotonic()
first = None
with client.messages.stream(
model=os.environ['ANTHROPIC_MODEL'],
max_tokens=1000,
system=SYSTEM,
messages=history,
) as stream:
for text in stream.text_stream: # only the text deltas, as they arrive
first = first or time.monotonic() - started
print(text, end='', flush=True)
final = stream.get_final_message() # the same Message a plain call returns
usage = final.usage
print(f'\nfirst text after {first:.2f} s, complete after '
f'{time.monotonic() - started:.2f} s')
print(f'stop_reason={final.stop_reason}, usage: input_tokens={usage.input_tokens}, '
f'output_tokens={usage.output_tokens}')python stream_claude.pyFake reply to: What should we change first?
Received 3 message(s), 0 image(s), 0 document(s).
There is no model here; a real provider would answer the question.
first text after 0.10 s, complete after 2.24 s
stop_reason=end_turn, usage: input_tokens=37, output_tokens=43The first words arrived after a fraction of a second, while the whole answer took more than two. With the openai SDK, pass stream=True and iterate over the chunks. Usage only arrives if you request it with stream_options, in a final chunk that has no choices:
import os
import openai
from ask_claude import SYSTEM, history
client = openai.OpenAI()
stream = client.chat.completions.create(
model=os.environ['OPENAI_MODEL'],
messages=[{'role': 'system', 'content': SYSTEM}, *history],
max_completion_tokens=1000,
stream=True,
stream_options={'include_usage': True}, # adds a last chunk with usage
)
finish, usage = None, None
with stream: # closes the HTTP response even if the loop stops early
for chunk in stream:
if chunk.usage:
usage = chunk.usage # the final chunk has usage and no choices
if not chunk.choices:
continue
choice = chunk.choices[0]
print(choice.delta.content or '', end='', flush=True)
finish = choice.finish_reason or finish
print(f'\nfinish_reason={finish}, usage: prompt_tokens={usage.prompt_tokens}, '
f'completion_tokens={usage.completion_tokens}')python stream_compatible.pyFake reply to: What should we change first?
Received 4 message(s), 0 image(s), 0 document(s).
There is no model here; a real provider would answer the question.
finish_reason=stop, usage: prompt_tokens=37, completion_tokens=4304. Step 3: Parse server-sent events yourself
Sometimes there is no SDK: a language without one, a gateway with its own fields, or debugging where you want every event. The format is simple enough to read with httpx, line by line as the body arrives:
"""Stream from the Messages API with plain httpx: what the SDK does for you."""
import json
import os
import httpx
url = os.environ.get('ANTHROPIC_BASE_URL', 'https://api.anthropic.com') + '/v1/messages'
headers = {
'authorization': f"Bearer {os.environ['ANTHROPIC_API_KEY']}",
'anthropic-version': '2026-10-21',
}
body = {
'model': os.environ['ANTHROPIC_MODEL'],
'max_tokens': 1000,
'stream': True,
'messages': [{'role': 'user', 'content': 'Ping?'}],
}
with httpx.stream('POST', url, headers=headers, json=body, timeout=30.0) as response:
response.raise_for_status()
for line in response.iter_lines(): # SSE: "event: ..." and "data: ..." lines
if not line.startswith('data:'):
continue # skip event names and the blank line that ends each event
event = json.loads(line.removeprefix('data:'))
if event['type'] == 'content_block_delta':
print(event['delta'].get('text', ''), end='', flush=True)
elif event['type'] == 'message_delta':
print(f"\nstop: {event['delta']['stop_reason']}, "
f"output tokens: {event['usage']['output_tokens']}")
elif event['type'] == 'error': # errors can arrive mid-stream, after a 200
raise RuntimeError(event['error'])python raw_sse.pyFake reply to: Ping?
Received 1 message(s), 0 image(s), 0 document(s).
There is no model here; a real provider would answer the question.
stop: end_turn, output tokens: 39The script sends the headers the current SDK would, Authorization: Bearer with the key and anthropic-version, handles the three events it needs and skips the rest. It is deliberately minimal: a full SSE parser also joins multi-line data: fields and ignores comment lines starting with a colon. In production prefer the SDK, which does all this and turns error events into exceptions.
05. Step 4: Cancel a request in flight
In an async application each request runs in a task, and cancelling the task is how you stop it. cancel_stream.py starts an answer, cancels it after one second as if the user had pressed Stop, and then gives a second answer an overall deadline with asyncio.timeout:
import asyncio
import os
import anthropic
client = anthropic.AsyncAnthropic()
async def answer(question: str) -> None:
async with client.messages.stream(
model=os.environ['ANTHROPIC_MODEL'],
max_tokens=1000,
messages=[{'role': 'user', 'content': question}],
) as stream:
async for text in stream.text_stream:
print(text, end='', flush=True)
# Leaving the async with block, normally or by cancellation, closes the stream.
async def main() -> None:
task = asyncio.create_task(answer('Write a long essay about HTTP.'))
await asyncio.sleep(1.0) # the user presses Stop after one second
task.cancel()
try:
await task
except asyncio.CancelledError:
print('\n[stopped by the user]')
try: # a deadline for the whole answer, not just for each read
async with asyncio.timeout(1.5):
await answer('Another long essay, please.')
except TimeoutError:
print('\n[gave up after 1.5 s]')
asyncio.run(main())python cancel_stream.pyFake reply to: Write a long essay about HTTP.
Received 1 message(
[stopped by the user]
Fake reply to: Another long essay, please.
Received 1 message(s), 0 image(s), 0 document(s).
[gave up after 1.5 s]INFO: 127.0.0.1:33190 - "POST /v1/messages HTTP/1.1" 200 OK
fake: client left after 15 of 44 tokens
INFO: 127.0.0.1:37122 - "POST /v1/messages HTTP/1.1" 200 OK
fake: client left after 29 of 43 tokenstask.cancel() raises CancelledError inside answer where it waits for the next event. The exception leaves the async with block, the SDK closes the HTTP connection, and the stand-in notices part-way through its reply. What the provider does next is its own business. Anthropic's billing note says that if your client disconnects or times out in the middle of a request that was on track to succeed, that request is still charged, and neither Anthropic nor OpenAI documents how many output tokens a cancelled stream costs; gateways, proxies and local servers vary too. Cancel anyway, to free your worker and stop reading, and check the usage console for a cancelled request instead of assuming it was cheap.
The second answer shows why streams need their own deadline. The client timeout from lesson 3 limits each wait for data, and a stream sends data every few tokens, so a slow, endless stream never trips it. asyncio.timeout(1.5) limits the whole answer and cancels it the same way. In synchronous code, leaving the with client.messages.stream(...) block by break, return or an exception also closes the connection; with the openai SDK, use the stream as a context manager or call stream.close().
06. Step 5: Relay to a browser and stop when it leaves
Browsers must not call the model API directly, because that would expose your key. Your server calls the model and relays the stream. Save relay.py, a FastAPI app that re-sends each piece of text as a server-sent event and ends with a done event that carries the usage:
"""Relay a model's stream to a browser as server-sent events."""
import asyncio
import json
import os
import anthropic
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
app = FastAPI()
client = anthropic.AsyncAnthropic()
def sse(data: dict, event: str | None = None) -> str:
return (f'event: {event}\n' if event else '') + f'data: {json.dumps(data)}\n\n'
@app.get('/chat')
async def chat(q: str) -> StreamingResponse:
async def events():
try:
async with client.messages.stream(
model=os.environ['ANTHROPIC_MODEL'],
max_tokens=1000,
messages=[{'role': 'user', 'content': q}],
) as stream:
async for text in stream.text_stream:
yield sse({'text': text})
final = await stream.get_final_message()
usage = final.usage
yield sse({'input': usage.input_tokens, 'output': usage.output_tokens},
event='done')
except asyncio.CancelledError: # the browser went away mid-stream
print('relay: client disconnected, upstream stream closed', flush=True)
raise # always re-raise a cancellation
return StreamingResponse(events(), media_type='text/event-stream',
headers={'Cache-Control': 'no-cache'})Start it in a third terminal, with the virtual environment active and the same environment variables set:
uvicorn relay:app --port 8200INFO: Started server process [3965867]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://127.0.0.1:8200 (Press CTRL+C to quit)In terminal 2, read one whole answer, keeping the last five lines, and then a second one that you abandon after one second with --max-time 1, as a user closing the tab would:
curl -sN 'http://127.0.0.1:8200/chat?q=Ping%3F' | tail -n 5
curl -sN --max-time 1 'http://127.0.0.1:8200/chat?q=Ping%3F' > /dev/nulldata: {"text": "."}
event: done
data: {"input": 2, "output": 39}INFO: 127.0.0.1:60336 - "GET /chat?q=Ping%3F HTTP/1.1" 200 OK
relay: client disconnected, upstream stream closed
INFO: 127.0.0.1:37130 - "POST /v1/messages HTTP/1.1" 200 OK
fake: client left after 19 of 39 tokensWhen the client hung up, Starlette, the toolkit under FastAPI, cancelled the generator producing the response. The cancellation reached the async with block, which closed the upstream stream, so the stand-in stopped generating. The except block logs and re-raises, because swallowing CancelledError would leave the task running as if nothing had happened. Without async with, nothing is sure to close the upstream connection, and the provider may keep generating, and billing, to the end. A synchronous client in an async endpoint is worse: it blocks the event loop, and cancellation cannot interrupt it.
On the browser side, chat interfaces usually read the stream with fetch and stop it with an AbortController. This script does the same in Node.js 22, aborting after one second as a Stop button would:
// In a browser, controller.abort() runs when the user clicks Stop.
const controller = new AbortController();
setTimeout(() => controller.abort(), 1000);
try {
const response = await fetch('http://127.0.0.1:8200/chat?q=Ping%3F', {
signal: controller.signal,
});
const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
let buffer = '';
for (;;) {
const { value, done } = await reader.read();
if (done) break;
buffer += value;
const events = buffer.split('\n\n'); // an SSE event ends with a blank line
buffer = events.pop();
for (const event of events) {
const data = event.split('\n').find((line) => line.startsWith('data: '));
if (data && !event.startsWith('event: done')) {
process.stdout.write(JSON.parse(data.slice(6)).text);
}
}
}
} catch (err) {
if (err.name !== 'AbortError') throw err;
console.log('\n[stopped]');
}node stop-button.mjsFake reply to: Ping?
Received 1 message(s), 0 image(s)
[stopped]Terminals 3 and 1 show the same pair of lines as before: the abort closed the connection, the relay cancelled its upstream stream, and generation stopped. The built-in EventSource API also reads server-sent events, but only with GET requests, and it reconnects on its own when the stream ends, which would ask the question again; close it when the done event arrives.
07. Common mistakes
08. Check your understanding
09. Apply it
Add streaming to the practice project, which must stream output to the terminal:
- Write a
stream_answer(question, on_text)function that streams from your hosted provider, callson_textfor each piece of text, and returns the final stop reason and usage, which you log as in lesson 2. - Give it an overall deadline, and make Ctrl+C stop the stream cleanly: catch
KeyboardInterruptaround a synchronous stream, or cancel the task in an async one, and log how many output tokens had been produced when it stopped. - Put
relay.pybehind your own front end, or behind a reverse proxy such as nginx, and confirm that text still arrives word by word and that closing the browser tab produces the cancellation line in the relay log.
10. Review prompt
Without looking back, list the Messages API stream events in order and say which ones carry the text, the stop reason and the usage, and how a chat completions stream differs. Then write an async function that streams an answer with an overall deadline of ten seconds, and explain how cancelling its task stops generation at the provider.
References
- OpenAI API reference
- Claude docs: Streaming messages
- Claude Help Center: How do I pay for my Claude API usage?
- Claude docs: Python SDK
- OpenAI Python library
- MDN Web Docs: Using server-sent events
- HTML Living Standard: Server-sent events
- Python docs: Coroutines and tasks
- FastAPI: Custom response classes
- Starlette: Responses
- MDN Web Docs: AbortController
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.