Skip to main content
Blog · Analysis

AI Gateway Streaming: What Breaks OpenAI-Compatible Clients

Vishal Vishwakarma11 min read

Streaming has quietly become the default way to serve a language model. A chat interface that waits for the whole answer feels broken, so nearly every application asks for the answer as server-sent events (SSE) and draws each token as it arrives, and the OpenAI chat completion chunk has become the shape the whole ecosystem parses. AI gateways, proxies and routers sit in the middle of that stream, and most of them have something of their own to say while it runs: which model was chosen, what the request cost, which guardrail fired, whether a fallback was taken.

The practical question for AI gateway streaming is where a gateway can put that information in an OpenAI-compatible stream without breaking the clients downstream, and we had our own answer wrong. Inferbase sends a routing event before the first token and a usage event after the last. While testing the Vercel AI SDK against it, we found that every stream finished with finishReason: "error", although the text arrived intact. So we measured the general case: one streamed answer, an extra event added four different ways, and ten client setups reading each one.

Why the information travels inside the stream

A gateway has two obvious alternatives to the stream itself, and both fall short for this kind of information. Response headers leave before the first token, so they can carry what is known at the start, such as the model that was chosen, but not what is only known at the end: the cost, the token count, or the fact that the first provider failed mid-answer and a fallback finished it. HTTP trailers would fit that timing, but browsers' Fetch API does not expose them, and most client libraries never read them.

A separate lookup endpoint works for logging after the fact, and we offer one, but it costs the caller a second request and leaves the streaming code unaware of what happened. For anything an application wants while the answer is being drawn, the stream is the only channel that arrives at the right moment, which is why gateways keep putting events into it and why the format of those events matters.

Four ways an AI gateway can add an event to a stream

An SSE stream is a sequence of blocks separated by blank lines. A block can carry data: lines, an optional event: name, or comment lines that begin with a colon. That gives a gateway four places to put its own information.

A data frame with no choices, which is what our gateway sent:

data: {"object": "gateway.routing", "model": "example-model", "task": "general"}

The same frame with an empty choices array, the shape OpenAI itself uses for the usage chunk at the end of a stream when a request sets stream_options.include_usage:

data: {"object": "gateway.routing", "model": "example-model", "task": "general", "choices": []}

An SSE comment, which the specification says clients ignore:

: gateway.routing {"model": "example-model", "task": "general"}

A named event, which the specification routes to a listener for that event name:

event: gateway.routing
data: {"object": "gateway.routing", "model": "example-model", "task": "general"}

We built a small mock server that streams the answer "Hello there." as three ordinary chunks, with the extra event sent once before the first chunk and once after the last, in each of these four forms, plus a control stream with nothing extra. Each client streamed from each variant. A run passed when the full text arrived, no error was raised and the stream finished normally.

The clients are the ones most applications reach an OpenAI-compatible API through: the official Python and Node SDKs, the Vercel AI SDK through both its OpenAI-compatible provider and its OpenAI provider, LangChain's ChatOpenAI, LiteLLM used as a client, the Dify plugin SDK that model plugins for Dify are built on, and the Goose agent. For the two OpenAI SDKs we ran two loops, one that checks choices before reading it and one that does not, because the difference turned out to matter more than the SDK.

The results

Client (version)No choiceschoices: []SSE commentNamed event
OpenAI Python SDK 3.60.0, loop checks choicespasspasspasspass
OpenAI Node SDK 7.65.0, loop checks choicespasspasspasspass
OpenAI Python SDK, loop reads choices[0]TypeErrorIndexErrorpassTypeError
OpenAI Node SDK, loop reads choices[0]TypeErrorTypeErrorpassTypeError
Vercel AI SDK 7.0.185, @ai-sdk/openai-compatible 3.0.97finishes with errorpasspassfinishes with error
Vercel AI SDK 7.0.185, @ai-sdk/openai 4.0.126 (chat)finishes with errorpasspassfinishes with error
LangChain ChatOpenAI (langchain-openai 1.8.5)passpasspasspass
LiteLLM 1.111.1 as a clientpasspasspasspass
Dify plugin SDK 0.11.1 (OpenAI-compatible model)passpasspasspass
Goose 1.61.1 (OpenAI engine)passpasspasspass

The control stream passed for every client. Two of the four forms broke something, and they broke different things for different reasons.

What breaks, and why

The Vercel AI SDK validates every frame it reads against the chat completion chunk schema, and in that schema choices is required. A frame without it fails validation, the SDK emits an error part into the stream and marks the step's finish reason as error. Against our own gateway the validation error named the problem precisely: expected array, received undefined at the path choices.

Everything else still flows, which is exactly why the problem is easy to miss. In our mock the text was complete and the usage was counted, so a script that only prints textStream looks perfectly healthy. useChat, and anything else that reads the finish reason or the error parts, reports a failed response on every message instead.

The named event was the more surprising result. In our runs neither the OpenAI SDKs nor the AI SDK set the block aside because of its event: name; each parsed its data: line as one more chunk. A named event therefore arrived exactly like a data frame without choices, and it failed in exactly the same places. The SSE specification gives event names a meaning, but the clients most applications use do not act on it.

The naive loop deserves its own note. Most quickstarts read the stream like this:

for chunk in stream:
    print(chunk.choices[0].delta.content or "", end="")

That loop fails on any frame without a first choice, including the empty-choices frame that passed every library. It also fails on a plain OpenAI-shaped stream with nothing extra in it, as soon as the request sets stream_options: {"include_usage": true}: the final usage chunk has choices: [] by design, and our control run raised an IndexError on it.

Code that reads streams from more than one source should therefore check that choices is non-empty, and that single check made every variant safe for both OpenAI SDKs. The fault in the naive loop belongs to the loop, not to the gateway, but a gateway that wants to be a drop-in replacement inherits the code its callers already have.

The four tolerant clients each pass over what they do not recognize. LangChain skips a chunk whose choices is empty or missing, Dify's plugin SDK continues past any frame without choices, and LiteLLM passed every variant as well. Goose's OpenAI engine goes further and treats a frame with no choices key as metadata on purpose; a comment in its parser notes that gateways interleave such frames with real chunks, and that failing on them "kills the whole turn on an otherwise healthy stream".

Reading gateway events from the client

A gateway event is only useful if an application can read it, and the empty-choices form keeps that possible in every client we tested. In Python, the guarded loop needs one more branch to pick the event up by its object value:

for chunk in stream:
    if not chunk.choices:
        if chunk.object == "gateway.routing":
            routing = chunk.model_extra
        continue
    print(chunk.choices[0].delta.content or "", end="")

The OpenAI SDKs keep the fields they do not model on the chunk (in model_extra in Python, as plain properties in Node), so nothing the gateway sends is lost on the way through. The AI SDK hides raw chunks from application code, but its OpenAI-compatible provider accepts a metadata extractor that sees every parsed frame and returns what it finds on providerMetadata:

const provider = createOpenAICompatible({
  name: 'gateway',
  baseURL: 'https://gateway.example.com/v1',
  apiKey: process.env.GATEWAY_API_KEY,
  metadataExtractor: {
    extractMetadata: async ({ parsedBody }) => ({ gateway: { routing: parsedBody.routing ?? null } }),
    createStreamExtractor: () => {
      let routing = null
      return {
        processChunk: (chunk) => { if (chunk?.object === 'gateway.routing') routing = chunk },
        buildMetadata: () => ({ gateway: { routing } }),
      }
    },
  },
})

A comment line offers no such path. Every client strips it before application code runs, which is the right outcome for a keep-alive and the wrong one for anything a caller wants to log.

What an AI gateway should send

  1. Send information a client may read as a data frame with "choices": []. It passed every library in the table, because OpenAI's own usage chunk already has that shape and every client has to handle it. Keep a distinctive object value so clients that want the event can match on it.
  2. Send information no client needs as an SSE comment. Keep-alives and processing notices fit here; OpenRouter, for instance, documents its "OPENROUTER PROCESSING" keep-alive as a comment line. Every client dropped comments before they reached the caller, so nothing breaks, and nothing can be read.
  3. Do not use named events for chat completion streams. The clients we tested ignore the name and parse the data as a chunk, so a named event is the bare frame under another label.
  4. Never send a data frame without choices. It is the form that breaks the AI SDK, and the AI SDK is one of the most common ways to build a chat interface on an OpenAI-compatible API.

The non-streamed side is easier. A chat completion with an extra top-level field, such as a routing object, passed both OpenAI SDKs, both AI SDK providers, LangChain and LiteLLM in the same mock, because each reads the fields it knows and leaves the rest alone.

How we changed Inferbase

Our routing event and usage event were bare data frames, the first column of the table. As of December 1, 2026 both carry "choices": [], as do the status and media events a stream sends when a chat request asks for an image or speech. Clients that know the events still match on their object value, and the routing decision now reaches AI SDK applications through a metadata extractor instead of failing their streams. The Vercel AI SDK guide shows how to read it, and client compatibility lists what a stream from Inferbase contains.

Method and data

The mock server streamed "Hello there." as three chat completion chunks (role and first word, second word, finish with stop), with the gateway event sent before the first chunk and after the finish chunk, then [DONE]. When a request set stream_options.include_usage, a usage chunk with choices: [] came before [DONE], as OpenAI sends it. The five variants differed only in how the two gateway events were written. Each client streamed once per variant on December 1, 2026, with the versions listed in the table and a current release of each; a run passed when the full text arrived, no exception was raised, no error part was emitted and the finish reason, where the client exposes one, was stop. The two OpenAI SDK rows that check choices iterate over chunk.choices and skip a chunk without one; the two that do not read chunk.choices[0] directly. The AI SDK results against Inferbase itself, before and after the change, were measured on the same day with the same package versions. Like our provider parameter report, this is a measurement of behavior at one point in time; client libraries change their parsers between releases, so the versions in the table are part of the result.

Frequently asked questions

OpenAI-compatible APIstreamingAI gatewayVercel AI SDKserver-sent events

Have thoughts on this article?

We would love to hear your feedback, questions, or experience with these topics. Reach out on social media or drop us a message.

Related Articles

Stay up to date

Get notified when we publish new articles on AI model selection, cost optimization, and infrastructure planning.

Put intelligence in the middle.

Start on the free plan with 5,000 requests a month, no card required.