Skip to content

Streaming

Set "stream": true (Gemini: call streamGenerateContent) and the response is sent as it is generated. Response headers include Content-Type: text/event-stream, Cache-Control: no-cache and X-Accel-Buffering: no, so proxies that honour them do not buffer.

Dialect Stream Last events
OpenAI Chat data: {chunk} lines A chunk with choices: [] and usage (with usage.cost), then data: [DONE]. The usage chunk is always sent, whether or not the request has stream_options.include_usage.
OpenAI Responses Typed events (response.output_text.delta, …) response.completed (or response.incomplete) with response.usage.cost.
Anthropic message_start, content_block_*, message_delta, message_stop message_delta carries the final usage, including cost.
Gemini A JSON array of GenerateContentResponse objects, or SSE with ?alt=sse The last object carries usageMetadata, including cost.

The cost in a stream is the amount charged for the whole request. Read it from the last event that carries usage: a provider may send usage earlier in the stream (Anthropic does in message_start), and the cost on those earlier events is only what the request had cost up to that point.

import os
from openai import OpenAI
client = OpenAI(base_url="https://api.test.whocare.xyz/v1", api_key=os.environ["GATEWAY_API_KEY"])
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Count from one to five."}],
stream=True,
)
cost = None
for chunk in stream:
if chunk.choices and chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="", flush=True)
if chunk.usage:
cost = chunk.usage.model_extra["cost"]
print()
print("cost (USD):", cost)
import OpenAI from "openai";
const client = new OpenAI({
baseURL: "https://api.test.whocare.xyz/v1",
apiKey: process.env.GATEWAY_API_KEY,
});
const stream = await client.chat.completions.create({
model: "gpt-4o-mini",
messages: [{ role: "user", content: "Count from one to five." }],
stream: true,
});
let cost;
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content;
if (delta) process.stdout.write(delta);
if (chunk.usage) cost = chunk.usage.cost;
}
console.log("\ncost (USD):", cost);
Terminal window
# -N turns off curl's own buffering so events print as they arrive.
curl -N https://api.test.whocare.xyz/v1/messages \
-H "x-api-key: $GATEWAY_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "Content-Type: application/json" \
-d '{
"model": "claude-sonnet-5-5",
"max_tokens": 64,
"stream": true,
"messages": [{"role": "user", "content": "Count from one to five."}]
}'
Terminal window
curl -N "https://api.test.whocare.xyz/v1beta/models/gemini-2.5-flash:streamGenerateContent?alt=sse" \
-H "x-goog-api-key: $GATEWAY_API_KEY" \
-H "Content-Type: application/json" \
-d '{"contents": [{"role": "user", "parts": [{"text": "Count from one to five."}]}]}'

Failures before the first byte are retried for you

Section titled “Failures before the first byte are retried for you”

The gateway does not send anything to you until the provider has produced content (or finished). Until then, a failed attempt (a 5xx, a timeout, a stream that breaks, a provider-side rate limit) is retried on the next provider, up to 3 attempts per request by default, and you see only the final outcome. X-Gateway-Attempts tells you how many attempts it took.

Two timers apply to a stream before it starts:

  • If the provider sends no body byte within 60 seconds of the attempt (default), the attempt fails and the next provider is tried.
  • If the provider sends only metadata for 10 seconds after its headers, the gateway starts your response anyway so that you receive those frames.

Once the response has started there is no retry: the status line is already sent.

An error after the response started is delivered in the stream, in the dialect’s own error shape, and the stream ends:

  • OpenAI Chat: a data: line holding {"error": {...}}, then data: [DONE].
  • Anthropic: an event: error event.
  • Gemini: an error object in the stream.

The request is billed for what was delivered, with status: partial in /v1/generation. Your client should treat a stream that ended without its normal final event as failed, keep the text it already has, and decide whether to ask again.

If the balance can no longer cover the request while it streams, the gateway cuts the stream and bills what was delivered (status: partial). In the OpenAI, Anthropic and Gemini formats it normally ends the response with a length stop (finish_reason: "length", stop_reason: "max_tokens", MAX_TOKENS); when the provider’s own bytes are being forwarded unchanged, it ends with an insufficient_balance error event instead. Treat a length stop on a response that is shorter than your max_tokens as a sign to check your balance.

If your client disconnects after the provider has started answering, the gateway does not cancel the provider. It keeps reading the stream (output discarded) for up to 60 seconds by default, to learn the real usage:

  • If the provider finishes in that time, you are billed the provider’s final usage, which can be more than the text your client had read.
  • If it does not, or the provider reports no usage, you are billed for the text read so far, counted by the gateway’s own estimate (usage_estimated: true in /v1/generation).

At least the input side is billed even if no text had been delivered yet. The request is recorded with status: canceled. A non-streaming request whose client disconnects after the provider answered is read to the end and billed in full. If you disconnect before the provider has answered at all, nothing is billed.

A non-streaming response sends nothing until generation is complete. For requests that can run for minutes (long reasoning, large outputs), prefer streaming where the model supports it: a proxy or load balancer in front of the gateway may close a connection that stays silent for too long.

The server stops a stream if the provider is silent between chunks for 120 seconds (default). A non-streaming request that is still waiting for the provider after 10 minutes (default) ends with 504 upstream_timeout and is not retried.