Streaming Claude Responses
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
Long answers take time to generate. Without streaming, your user stares at a spinner until the last token is ready. With streaming, text appears as it is produced, and long requests stop timing out. This lesson covers the event protocol, the Python and PHP SDK helpers, a Laravel endpoint, and the browser code that reads it.
Learning objectives
- Explain the stream's event order and which events carry text and usage.
- Stream with the Python and PHP SDKs.
- Expose a stream from Laravel as server-sent events and read it in JavaScript.
- Handle errors that arrive after the HTTP status is already 200.
Prerequisites
How streaming works
Set "stream": true and the API replies with server-sent events (SSE) instead of one JSON body. Each event has a name and JSON data. Anthropic documents this flow:
message_start: a message object with empty content.
- For each content block:
content_block_start, any number of content_block_delta events, then content_block_stop. The index matches the block's position in the final content array.
- One or more
message_delta events carrying top-level changes such as the stop_reason.
- A final
message_stop.
Text arrives in content_block_delta events whose delta.type is text_delta. Two details matter: the token counts in message_delta's usage are cumulative, not per event, and the API may add new event types, so unknown events must be ignored rather than treated as errors. Ping events also appear to keep connections alive.
Browser --POST /api/ask/stream--> Your back end --stream:true--> Claude API
Browser <--SSE: data {"t":"Hel"}-- Your back end <--SSE: text_delta-- Claude API
Python
The SDK's stream helper handles the events and exposes a plain iterator of text. After the loop you can fetch the fully assembled message, identical to what a non-streaming call returns:
import anthropic
client = anthropic.Anthropic()
with client.messages.stream(
model="claude-sonnet-5-5",
max_tokens=600,
messages=[{"role": "user", "content": "Write a short checklist for launching a website."}],
) as stream:
for text in stream.text_stream:
print(text, end="", flush=True)
# After the stream ends, the SDK has assembled the complete message for you.
final = stream.get_final_message()
print()
print(f"\nstop_reason={final.stop_reason} in={final.usage.input_tokens} out={final.usage.output_tokens}")
PHP
The PHP SDK's createStream() yields events. Streaming needs an HTTP client that returns the body incrementally; with Guzzle installed the SDK configures this for you. With a buffering client, every event arrives at once at the end:
<?php
require __DIR__.'/vendor/autoload.php';
use Anthropic\Client;
$client = new Client();
$stream = $client->messages->createStream(
maxTokens: 600,
messages: [['role' => 'user', 'content' => 'Write a short checklist for launching a website.']],
model: 'claude-sonnet-5-5',
);
foreach ($stream as $event) {
if ($event->type === 'content_block_delta' && $event->delta->type === 'text_delta') {
echo $event->delta->text;
flush();
}
if ($event->type === 'message_delta') {
$stop = $event->delta->stopReason;
$out = $event->usage->outputTokens; // cumulative, not per event
}
}
echo PHP_EOL, "stop_reason={$stop} output_tokens={$out}", PHP_EOL;
Laravel: a streaming endpoint
The browser should never hold your key, so your back end relays the stream. This assumes the ClaudeGateway from lesson 2.10; a minimal version that streams directly looks like this:
public function stream(Request $request): StreamedResponse
{
$data = $request->validate(['prompt' => ['required', 'string', 'max:4000']]);
return response()->stream(function () use ($data) {
try {
foreach ($this->claude->stream($data['prompt'], self::SYSTEM) as $fragment) {
echo 'data: '.json_encode(['t' => $fragment])."\n\n";
if (ob_get_level() > 0) {
ob_flush();
}
flush();
}
echo "event: done\ndata: {}\n\n";
} catch (\Throwable $e) {
// The 200 header has already gone out, so report failure in-band.
logger()->warning('Claude stream failed', ['class' => $e::class]);
echo "event: error\ndata: {\"message\":\"The assistant stopped unexpectedly.\"}\n\n";
}
if (ob_get_level() > 0) {
ob_flush();
}
flush();
}, 200, [
'Content-Type' => 'text/event-stream',
'Cache-Control' => 'no-cache',
'X-Accel-Buffering' => 'no', // tells nginx not to buffer the stream
]);
}
If your site sits behind a proxy or CDN that buffers responses, the text will still arrive all at once. Check proxy buffering before blaming your code. On shared hosting that cannot stream, fall back to a normal request.
JavaScript in the browser
EventSource cannot send a POST body, so use fetch and read the stream. This function handles events that are split across network chunks, surfaces in-band errors, and accepts an AbortSignal so a "Stop" button can cancel:
/**
* Read a server-sent-event stream from your own back end with fetch.
* (EventSource cannot send a POST body, so fetch + a stream reader is the usual choice.)
*/
export async function streamAnswer(
prompt: string,
onText: (fragment: string) => void,
signal?: AbortSignal,
): Promise<void> {
const response = await fetch('/api/ask/stream', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Accept: 'text/event-stream' },
body: JSON.stringify({ prompt }),
signal,
});
if (!response.ok || !response.body) {
throw new Error(`Request failed with status ${response.status}`);
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
buffer += decoder.decode(value, { stream: true });
// Events are separated by a blank line; keep any incomplete tail for the next chunk.
const events = buffer.split('\n\n');
buffer = events.pop() ?? '';
for (const raw of events) {
const name = /^event: (.+)$/m.exec(raw)?.[1] ?? 'message';
const data = /^data: (.*)$/m.exec(raw)?.[1] ?? '{}';
if (name === 'error') {
throw new Error(JSON.parse(data).message ?? 'The assistant stopped unexpectedly.');
}
if (name === 'done') {
return;
}
onText(JSON.parse(data).t as string);
}
}
}
In React, append each fragment to state inside onText.
Errors in the middle of a stream
An error can occur after the API has already returned 200. Anthropic documents an error event, for example overloaded_error, which corresponds to HTTP 529 in a non-streaming call. Handle it in three places: the SDK iterator (an exception), your relay (send an event: error as above) and the browser (show the partial text plus a retry option).
To recover a cut-off response on Claude 4.6 and later, the documentation's approach is to save what arrived, then send a new request with a user message containing the partial text and an instruction to continue from where it left off. Tool-use and thinking blocks cannot be recovered partially.
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A documentation site adds "Ask the docs". Answers average 300 tokens. Without streaming users waited about as long as the whole generation took; with streaming the first words appear almost immediately, even though total time is unchanged. The team also found long summaries no longer hit proxy timeouts, because bytes keep flowing.
Common errors and solutions
| Symptom | Cause | Fix |
| All text appears at once | Proxy, PHP output buffering or a non-streaming HTTP client. | Send X-Accel-Buffering: no, flush output, use Guzzle. |
| Half an event shows up as garbage | Parsing each network chunk as a complete event. | Buffer and split on blank lines, as in the TypeScript above. |
| Token counts look too large | Adding up every message_delta usage. | Usage there is cumulative; use the last value. |
| Code breaks when a new event type appears | Strict handling of known events only. | Ignore unknown events. |
| Users stay billed after leaving the page | Generation continues on the server. | Abort the upstream request when the client disconnects. |
Security considerations
- Keep the key on the server; the relay is the only place that talks to Claude.
- Validate and size-limit the prompt before opening a stream, and rate-limit the endpoint, because a stream holds a connection open.
- Never send raw upstream error text to the browser; send a safe message and log the details.
Performance and cost considerations
- Streaming improves perceived speed, not total generation time or price.
- Anthropic recommends streaming (or the Batch API) for long requests, especially those over 10 minutes, and the SDKs refuse non-streaming requests expected to exceed that timeout.
- Each open stream holds a PHP worker; size your worker pool for it.
Key takeaways
- Set
stream: true and read SSE events; text is in text_delta events.
- SDK helpers do the parsing;
get_final_message() gives the assembled message.
- Use
fetch with a stream reader in the browser and relay through your back end.
- Errors can arrive mid-stream after a 200; handle them in-band.
Lesson recap: stream events in order, relay through your back end, and handle errors in-band.
Knowledge check
- Which event type carries streamed text, and what is its
delta.type?
- Why are
message_delta token counts not added together?
- Why does your code need to ignore unknown event types?
- Why use
fetch instead of EventSource for this endpoint?
- A stream fails halfway. The HTTP status was 200. How do you tell the user?
Answers and explanations
content_block_delta with delta.type equal to text_delta.
- They are cumulative, so the latest value is already the total.
- Anthropic says new event types may be added, and unknown ones should be handled gracefully.
EventSource only makes GET requests, so it cannot send the prompt in a POST body.
- Send an in-band
error event, and have the browser show the partial text with a retry option.
Official references and further reading
Related tutorials