Streaming
The Linkora API allows streaming responses from *any model*. This is useful for building chat interfaces or other applications where the UI should update as the model generates the response.
To enable streaming, you can set the stream parameter to true in your request. The model will then stream the response to the client in chunks, rather than returning the entire response at once.
Here is an example of how to stream a response, and process it:
import { Linkora } from '@linkora/sdk';
const linkora = new Linkora({
apiKey: '<LINKORA_API_KEY>',
});
const question = 'How would you build the tallest building ever?';
const stream = await linkora.responses.send({
responsesRequest: {
model: 'openai/gpt-4o',
input: question,
stream: true,
},
});
if (!(stream instanceof ReadableStream)) {
throw new Error('Expected a streaming response');
}
for await (const event of stream) {
if (event.type === 'response.failed') {
throw new Error(event.response.error?.message ?? 'Response failed');
}
if (event.type === 'response.incomplete') {
throw new Error(
`Response incomplete: ${event.response.incompleteDetails?.reason ?? 'unknown reason'}`,
);
}
if (event.type === 'response.output_text.delta') {
console.log(event.delta);
}
// The final response.completed event includes usage stats
if (event.type === 'response.completed') {
console.log('Usage:', event.response.usage);
}
}Additional information
For SSE (Server-Sent Events) streams, Linkora occasionally sends comments to prevent connection timeouts. These comments look like:
: LINKORA PROCESSINGComment payload can be safely ignored per the SSE specs. However, you can use it to improve UX as needed, e.g. by showing a dynamic loading indicator.
: before calling JSON.parse. Passing a comment line like : LINKORA PROCESSING to JSON.parse throws, and unhandled it will crash your stream loop. The snippets above handle this.A spec-compliant parser such as eventsource-parser handles comments, multi-line data: fields, and buffering for you:
import { createParser } from 'eventsource-parser';
const response = await fetch('https://link-ora.net/api/v1/responses', {
method: 'POST',
headers: {
Authorization: `Bearer ${process.env.LINKORA_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
model: 'openai/gpt-4o',
input: 'Hello',
stream: true,
}),
});
// Errors that occur before streaming starts are plain JSON, not SSE
if (!response.ok) {
const error = await response.json();
throw new Error(error.error.message);
}
const parser = createParser({
onEvent(event) {
if (event.data === '[DONE]') return;
try {
const data = JSON.parse(event.data);
if (data.type === 'response.output_text.delta') {
console.log(data.delta);
}
} catch {
// Ignore invalid JSON
}
},
});
const reader = response.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
parser.feed(decoder.decode(value, { stream: true }));
}A parser only handles the SSE framing. Errors that occur mid-generation still arrive as regular data: events (a response.failed or error event). See Handling Errors During Streaming below.
The generation ID is returned in the X-Generation-Id response header for all endpoints (chat completions, completions, responses, and messages), which can be useful for debugging and correlating requests.
Some SSE client implementations might not parse the payload according to spec, which leads to an uncaught error when you JSON.stringify the non-JSON payloads. We recommend the following clients:
The final usage chunk (Chat Completions)
On the Chat Completions endpoint (/api/v1/chat/completions), every stream ends with an extra chunk that carries the usage object for the request, sent just before the [DONE] message. OpenAI's spec emits this chunk with an empty choices array, but many clients crash when accessing choices[0].delta on it, so Linkora intentionally deviates: the usage chunk contains one choice with a content-free delta that repeats the finish_reason (and native_finish_reason) of the stream.
data: {"id":"gen-abc123",...,"choices":[{"index":0,"delta":{"content":"","role":"assistant"},"finish_reason":"stop","native_finish_reason":"stop"}]}
data: {"id":"gen-abc123",...,"choices":[{"index":0,"delta":{"content":"","role":"assistant"},"finish_reason":"stop","native_finish_reason":"stop"}],"usage":{...}}
data: [DONE]This means the terminal finish_reason appears twice: once on the last content-bearing chunk and again on the usage chunk. Clients that validate streams should treat the usage chunk as an accounting frame rather than a second terminal event.
This shape is specific to Chat Completions. Other endpoints follow their own specs: the Responses API (/api/v1/responses) reports usage in the response.completed event, and the Messages API (/api/v1/messages) reports it in the message_delta event before message_stop.
Stream cancellation
Streaming requests can be cancelled by aborting the connection. For supported providers, this immediately stops model processing and billing.
Provider Support
To implement stream cancellation:
import { Linkora } from '@linkora/sdk';
import { RequestAbortedError } from '@linkora/sdk/models/errors';
const linkora = new Linkora({
apiKey: '<LINKORA_API_KEY>',
});
const controller = new AbortController();
try {
const stream = await linkora.responses.send({
responsesRequest: {
model: 'openai/gpt-4o',
input: 'Write a story',
stream: true,
},
}, {
signal: controller.signal,
});
if (!(stream instanceof ReadableStream)) {
throw new Error('Expected a streaming response');
}
for await (const event of stream) {
if (event.type === 'response.output_text.delta') {
console.log(event.delta);
}
}
} catch (error) {
// Aborting before the response arrives throws RequestAbortedError; aborting mid-stream throws AbortError.
if (error instanceof RequestAbortedError || (error instanceof Error && error.name === 'AbortError')) {
console.log('Stream cancelled');
} else {
throw error;
}
}
// To cancel the stream:
controller.abort();Handling errors during streaming
Linkora handles errors differently depending on when they occur during the streaming process:
Errors before the response is committed
If an error occurs before Linkora has committed the response, you get a standard JSON error response with the appropriate HTTP status code. That covers failures raised before the request reaches a provider, and provider failures visible at connection time such as a connection error or a non-2xx upstream status.
{
"error": {
"code": 400,
"message": "Invalid model specified"
}
}Common HTTP status codes include:
- 400: Bad Request (invalid parameters)
- 401: Unauthorized (invalid API key)
- 402: Payment Required (insufficient credits)
- 429: Too Many Requests (rate limited)
- 502: Bad Gateway (provider error)
- 503: Service Unavailable (no available providers)
Errors after the response is committed (mid-stream)
Once the provider has returned response headers, the 200 OK status is committed even if no token has been produced yet. Any error after that point arrives as an SSE event rather than as an HTTP status. The event shape depends on the API.
Responses API
The stream ends with a response.failed event. An abridged event looks like:
data: {"type":"response.failed","response":{"id":"gen-abc123", ... ,"status":"failed","output":[],"error":{"code":"server_error","message":"Provider disconnected unexpectedly"},"error_type":"provider_unavailable"},"sequence_number":12}Key characteristics of mid-stream errors:
- The error is in
response.error, andresponse.statusis"failed" - The canonical Linkora
error_typeis at the top level ofresponse(see Responses API error formats) - The stream schema also defines a plain
errorevent ({"type":"error","code":"...","message":"..."}). Linkora reports failures withresponse.failed, but handling both is safe - The HTTP status remains 200 OK since headers were already sent
- The stream is terminated after this event
- The error can be the first and only event in the stream, so treat a
200carrying aresponse.failedevent with no output as a failure, not a success
Chat Completions
The stream ends with a chunk that carries a top-level error:
data: {"id":"cmpl-abc123","object":"chat.completion.chunk","created":1234567890,"model":"openai/gpt-4o","provider":"openai","error":{"code":502,"message":"Provider disconnected unexpectedly"},"choices":[{"index":0,"delta":{"content":""},"finish_reason":"error"}]}Key characteristics of mid-stream errors:
- The error appears at the top level alongside standard response fields (id, object, created, etc.)
- A
choicesarray is included withfinish_reason: "error"to properly terminate the stream - The HTTP status remains 200 OK since headers were already sent
- The stream is terminated after this unified error event
- The error can be the first and only event in the stream, so treat a
200carrying anerrorchunk with no content as a failure, not a success
See Errors and debugging for the full error formats of both APIs.
Code examples
Here's how to properly handle both types of errors in your streaming implementation:
import { Linkora } from '@linkora/sdk';
const linkora = new Linkora({
apiKey: '<LINKORA_API_KEY>',
});
async function streamWithErrorHandling(prompt: string) {
try {
const stream = await linkora.responses.send({
responsesRequest: {
model: 'openai/gpt-4o',
input: prompt,
stream: true,
},
});
if (!(stream instanceof ReadableStream)) {
throw new Error('Expected a streaming response');
}
for await (const event of stream) {
// Check for mid-stream errors
if (event.type === 'response.failed') {
console.error(`Stream error: ${event.response.error?.message}`);
console.log('Stream terminated due to error');
return;
}
if (event.type === 'response.incomplete') {
console.error(
`Stream incomplete: ${event.response.incompleteDetails?.reason ?? 'unknown reason'}`,
);
return;
}
if (event.type === 'error') {
console.error(`Stream error: ${event.message}`);
return;
}
// Process normal content
if (event.type === 'response.output_text.delta') {
console.log(event.delta);
}
}
} catch (error) {
// Handle pre-stream errors
console.error(`Error: ${error instanceof Error ? error.message : String(error)}`);
}
}API-specific behavior
Different API endpoints may handle streaming errors slightly differently:
- Responses API: Upstream token-limit errors (such as
max_tokens_exceeded) end the stream with aresponse.incompleteevent (incomplete_details.reason: "max_output_tokens") rather than an error; other failures end withresponse.failed - Chat Completions API: Returns
ErrorResponsedirectly if no chunks were processed, or includes error information in the response if some chunks were processed; the same token-limit errors becomefinish_reason: "length"
