All guides

Receive and assemble an OpenRouter streaming answer

Send a streaming Responses API request, read SSE lines safely, join text deltas into one answer, and handle errors and cancellation.

AINavWritten / Updated Sources checked
On this page

At a glance

Streaming suits chat interfaces: the page updates while the model is still generating. Reading is the hard part. Data arrives in chunks, an SSE line can be split in half, comment lines that are not JSON are mixed in, and errors can appear after an HTTP 200. This guide follows the official streaming documentation for the Responses endpoint and builds a reader that joins text, recognizes failures and can stop midway.

Workflow

  1. Request

    Set stream to true in the Responses request body.

  2. Read

    Buffer chunks, skip comment lines and parse only data: lines.

  3. Finish

    Confirm completion only after response.completed. Record response.failed, response.incomplete, error and intentional cancellation separately. If [DONE] or connection closure arrives without confirmed completion, retain assembled text as an unfinished record and do not deliver it as a successful answer.

Each stage cites official sources.

Before you start

  • An OpenRouter API key kept in an environment variable or server-side config, never in front-end code or screenshots.
  • A model ID you have confirmed is usable (the documentation example uses openai/gpt-4o; whether it fits your task is for you to decide).
  • TypeScript or Python HTTP code you can run, with a way to abort the connection when needed.

1. Write the streaming request

In a server-side script, send a POST to https://openrouter.ai/api/v1/responses. The headers carry Authorization: Bearer plus your key and Content-Type: application/json. The body has model, input and stream set to true. Start with a short synthetic input, never real customer data.

2. Check the HTTP status first

Before reading the stream, check that the response succeeded. The documentation says errors before streaming starts are plain JSON, not SSE, and lists common statuses of 400, 401, 402, 429, 502 and 503. Read error.message, log it and stop. Do not enter the stream loop.

3. Buffer and split by line

Append every chunk to a string buffer, look for a newline, and process only complete lines, leaving the remainder for the next chunk. Use streaming text decoding so multi-byte characters are not cut apart.

4. Skip comments, parse only data lines

A line starting with a colon is an SSE comment, such as : OPENROUTER PROCESSING. It prevents connection timeouts and is not JSON, so skip it (or use it to show a loading hint). For a line starting with data:, strip the prefix. If the rest is [DONE], finish; otherwise parse it as JSON and ignore lines that fail to parse. Confirm completion only after response.completed. Record response.failed, response.incomplete, error and intentional cancellation separately. If [DONE] or connection closure arrives without confirmed completion, retain assembled text as an unfinished record and do not deliver it as a successful answer.

5. Handle events by type and join text

For response.output_text.delta, append delta to the answer string. For response.failed, read response.error.message and report failure. For response.incomplete, read response.incomplete_details.reason (the path in raw HTTP events; the TypeScript SDK spells it response.incompleteDetails.reason) and mark the answer unfinished. For an error event, read message. The response.completed event carries usage, which you can record. Confirm completion only after response.completed. Record response.failed, response.incomplete, error and intentional cancellation separately. If [DONE] or connection closure arrives without confirmed completion, retain assembled text as an unfinished record and do not deliver it as a successful answer.

6. Cancel the connection when needed

When the user presses stop or leaves the page, abort the connection (AbortController with fetch, or close the response in Python). The documentation says supported providers stop processing and billing immediately, while unsupported providers and non-streaming requests keep generating and are billed for the full response. For fetch, catch AbortError and record cancellation. In Python, close the response without applying JavaScript exception names. This cancellation exercise uses fetch or Python; check the SDK documentation separately for TypeScript SDK cancellation exceptions.

Original example

Exercise goal: summarize a synthetic meeting note in two sentences and assemble the full text. Request body (original sample):

json
{
  "model": "openai/gpt-4o",
  "input": "Summarize this synthetic note in two sentences: review scheduled Tuesday, owner confirms test environment, docs added next week.",
  "stream": true
}

The reader would see lines like these (an illustration written from the documented event types, not real output): : OPENROUTER PROCESSING data: {"type":"response.output_text.delta","delta":"The review is "} data: {"type":"response.output_text.delta","delta":"on Tuesday."} data: {"type":"response.completed","response":{}} data: [DONE] Result: the first line starts with a colon and is skipped; the two deltas are appended to give "The review is on Tuesday."; [DONE] ends the loop. If a line with type response.failed appeared midway, you would flag the run as failed and display and record the error, retaining accumulated text only as partial output. Confirm completion only after response.completed. Record response.failed, response.incomplete, error and intentional cancellation separately. If [DONE] or connection closure arrives without confirmed completion, retain assembled text as an unfinished record and do not deliver it as a successful answer. On response.failed, mark the run failed, display and record the error, and keep accumulated text only as partial output. The empty response object in the illustration omits other fields of an actual event.

Completion checks

  • The displayed text equals all deltas added in arrival order, with nothing duplicated or missing.
  • Comment lines are skipped and never reach JSON parsing.
  • A response.failed, response.incomplete or error event is clearly shown as failed or unfinished. A 200 carrying only a failure event and no text still counts as a failure.
  • After pressing stop the connection really closes, and the cancellation is not shown as an error.
  • Confirm completion only after response.completed. Record response.failed, response.incomplete, error and intentional cancellation separately. If [DONE] or connection closure arrives without confirmed completion, retain assembled text as an unfinished record and do not deliver it as a successful answer.

Limits

  • Cancellation stops processing and billing immediately only for providers on the official supported list. Otherwise the full response is billed, so do not promise that stopping is free.
  • This guide covers Responses endpoint events only. Chat Completions adds a final usage chunk and reports errors as a chunk with finish_reason error, and Messages reports usage in message_delta. Each needs its own parsing.
  • Hand-written parsing handles only basic line splitting. For multi-line data: fields, the documentation recommends a spec-compliant parser such as eventsource-parser.

Verification scope

This guide is based on the official OpenRouter streaming documentation. We only read the documentation; we did not test login, installation of the SDK, product API execution, file upload or generated output. The event lines in the example are illustrative text, so test real responses and model availability yourself.

Article sources

Original editorial content; official descriptions and checking suggestions are distinguished.

  1. OpenRouter · Official sources
    View details