Stream it
Stream an answer so customers see it as it’s written, and handle an error that arrives after the stream has started.
Long answers take a few seconds, and your shop’s customers stare at an empty box until the whole reply is done. Streaming sends the answer in small pieces as the model writes it, so the first words show up almost at once.
Add "stream": true to the request body. The response comes back as server-sent events (SSE): lines that start with data: , each holding a JSON chunk with the next piece of text in choices[0].delta.content. The last line is data: [DONE].
: OPENROUTER PROCESSING
data: {"choices":[{"delta":{"content":"Yes, we"},"finish_reason":null}]}
data: {"choices":[{"delta":{"content":" ship to Canada."},"finish_reason":null}]}
data: {"choices":[{"delta":{},"finish_reason":"stop"}],"usage":{"total_tokens":33,"cost":0.0000123}}
data: [DONE]Check your understanding
A streamed answer stops halfway. The HTTP status was 200. The last chunk has an error field and "finish_reason": "error". What happened?
SSE lines that start with a colon are comments that keep the connection open. Skip them. The final chunk carries usage, so the cost from the last lesson is still there at the end. The streaming docs have parsers for several languages, and the official SDKs handle all of this for you.
Apply it
A customer closes the chat window while a long answer is still streaming. Your server keeps reading until the model finishes. Is that a problem?
It can be: you may pay for tokens no one will read. Abort the request when the customer leaves, for example with an AbortController in JavaScript. For providers that support it, closing the connection stops the model and the billing for the rest of the answer.
The streaming docs list which providers support cancellation.
Takeaway
Streaming shows the answer as it’s written. Read delta.content from each chunk, skip comment lines, stop at [DONE], and check every chunk for an error, because a 200 at the start doesn’t promise a complete answer.