Learn
Hardware & deployment

What is an OpenAI-compatible API endpoint?

The short answer

An OpenAI-compatible API accepts the same request and response shape as OpenAI's chat completions endpoint, usually at /v1/chat/completions with a messages array. Existing SDKs and tools can point at a different base URL, which makes switching between hosted providers and self-hosted servers a configuration change rather than a rewrite.

On this page

The contract, field by field

The endpoint is a POST to /v1/chat/completions with a bearer token in the Authorization header and a JSON body. The required fields are model and messages. Each message has a role, one of system, user, assistant or tool, and content that is usually a string but can be an array of typed parts when images or files are involved. Optional fields shape the generation: temperature and top_p for sampling, max_tokens or max_completion_tokens for length, stop for sequences that end generation, stream to switch to server-sent events, seed for reproducible sampling where supported, and n for multiple candidates.

The response carries an id, an object type, a created timestamp, the model that actually served the request, a choices array, and a usage block. Each choice contains an index, a message with role and content, an optional tool_calls array, and a finish_reason of stop, length, tool_calls or content_filter. The usage block reports prompt_tokens, completion_tokens and total_tokens, sometimes with detail objects for cached prompt tokens and reasoning tokens. Applications depend on those fields more than they realise: a billing system reads usage, an agent loop reads finish_reason to decide whether to continue, and a UI reads the model field to show which model answered.

Extensions beyond this core are where providers diverge. Tool definitions arrive in a tools array with JSON Schema parameters, and tool_choice selects automatic, required, none or a named function. response_format can request plain text, a JSON object, or a strict JSON schema. Some providers add reasoning controls, prompt caching hints, safety settings, or vendor-specific fields in an extra_body object. All of it is optional in the specification sense, which is exactly why the word compatible needs qualification.

Streaming is a separate protocol to implement

When stream is true, the server responds with content type text/event-stream and writes lines of the form data: followed by a JSON object, separated by blank lines. The first chunk typically carries the assistant role in a delta object, subsequent chunks carry fragments of content, and the final chunk carries a finish_reason. The stream ends with a literal data: [DONE] line. There is no Content-Length, no retry semantics and no way to change the HTTP status code after the first byte, so error handling has to happen inside the stream.

Three details break naive clients. First, network chunks do not align with event boundaries: a read can end in the middle of a JSON object, so the client must buffer until it sees the double newline before parsing. Second, token usage is absent from the stream unless you ask for it, and the way to ask differs; OpenAI accepts a stream_options object with include_usage, while some compatible servers always send usage and others never do. Third, tool calls stream as deltas indexed by position, with the function name arriving once and the arguments arriving as a series of string fragments that must be concatenated before parsing. Code that expects a complete tool call in one chunk works in testing and fails on longer arguments.

For a proxy or gateway in the middle, streaming also constrains buffering. Any component that accumulates the whole response before forwarding destroys the user experience, and compression can add latency if it holds bytes to fill a block. The path from model to browser should be flushed per event.

Errors are part of the interface

Compatible servers generally return an error object with a message, a type, an optional parameter name and a code. The status code tells you what to do. A 400 means the request is malformed or a parameter is unsupported and retrying will not help. A 401 means the key is missing or wrong, and a 403 means it is valid but not permitted for that model or region. A 404 usually means the model name is not deployed under that identifier. A 429 means rate limited or out of quota, and the two cases need different handling: one is retryable after a delay, the other requires a billing change. A 500 or 503 is the provider's problem and may be retryable with backoff.

Many compatible servers are less precise than this. Some return 400 for an expired key, some return 500 for a context-length overflow that should be a 400, and some return 200 with an error message in the content field. A production client needs a normalisation layer that inspects the body as well as the status, and a test suite that asserts the mapping rather than assuming it. If you run a gateway, this is one of the concrete pieces of value it should add.

Where compatibility actually breaks

  • Unsupported parameters are silently ignored by some servers and rejected with a 400 by others, so a temperature setting may simply not apply.
  • Some reasoning models reject max_tokens, non-default temperature and system messages, expecting max_completion_tokens and a developer role instead.
  • Tool calling differs on whether arguments are a JSON string or an object, whether parallel calls are allowed, and whether strict schema validation is enforced.
  • Structured output support ranges from full JSON Schema to a generic JSON mode that guarantees syntax but not shape.
  • Vision inputs differ on URL versus base64 data, on image size limits, and on how image tokens are counted against the context.
  • logprobs, top_logprobs, seed determinism and n greater than one are frequently accepted but ignored.
  • Usage accounting is missing in streams, missing entirely on some servers, or counts cached tokens differently.
  • Reasoning traces appear under vendor-specific fields such as reasoning_content, and dropping them changes multi-turn behaviour for some models.

Pointing an SDK at a different server

For the official Python and JavaScript SDKs, compatibility usually means setting a base URL and an API key. The base URL includes the version segment, so a self-hosted vLLM server is http://host:8000/v1, a local Ollama instance is http://localhost:11434/v1, and a hosted provider publishes its own. Azure OpenAI is the notable exception: the path includes the deployment name and an api-version query parameter, and authentication uses an api-key header rather than a bearer token, which is why Azure needs its own client class rather than a base URL swap.

Google's Gemini API exposes an OpenAI-compatible surface under a /v1beta/openai/ path, and several inference hosts, routers and Chinese model providers do the same. Anthropic's native API is a different shape, though a compatibility layer exists with a subset of features. The practical consequence is that base URL swapping gets you a working chat request in minutes and a working product only after you have tested the features you depend on.

Frameworks add another layer of assumption. LangChain, LlamaIndex and most agent libraries have an OpenAI integration that accepts a base URL, but they may also call endpoints your server does not implement, such as the models list, files, or batches. A missing /v1/models endpoint is a common reason a framework refuses to start against an otherwise functional server, even though chat works fine.

A contract test for any new endpoint

  • Send a plain chat request with a system and a user message, and confirm the response has choices, a finish_reason and a usage block.
  • Stream the same request and confirm delta chunks assemble into the same text, and that the terminating marker is handled.
  • Request a tool call with two functions and verify the arguments parse as JSON and the call index is stable across chunks.
  • Request a strict JSON schema output and validate three responses against the schema, not just one.
  • Send a prompt just under and just over the advertised context limit and confirm the error is a 400 with a useful message.
  • Check the token counts against the provider's tokenizer endpoint, or against a local tokenizer, for both prompt and completion.
  • Send an invalid key and an unroutable model name and confirm the error codes match what your retry logic expects.
  • Run a multi-turn conversation and confirm the assistant's prior tool calls and reasoning fields round-trip correctly.

Tokens, cost and why the numbers disagree

Token counts are model-specific, and a tokeniser built for OpenAI models will be wrong for Llama, Qwen or Mistral by ten to thirty percent depending on the text. English prose is close enough that the error hides; code, JSON, Indic scripts and other non-Latin text diverge sharply because the vocabulary was trained on different data. Use the server's own tokenize endpoint when it offers one, or load the model's tokeniser locally, and never estimate cost for a non-OpenAI model with a general-purpose tokeniser.

Prompt caching complicates the arithmetic further. Providers that support it report cached tokens separately, usually at a discount, and the cache only hits when the prefix is byte-identical, so a timestamp at the top of your system prompt silently disables it. Reasoning models report reasoning tokens inside completion tokens, which means a short visible answer can bill like a long one. If you are forecasting spend, measure on real traffic for a week rather than extrapolating from tokeniser output.

Versioning, aliases and the deprecation trap

Most providers offer both a stable alias and dated snapshots. The alias points at whatever is current, which means your product's behaviour changes when the provider upgrades it; the snapshot is pinned but eventually retired. The safe pattern is to pin the snapshot in production, keep the alias in staging, and run your evaluation suite against the alias monthly so you learn about drift before the retirement notice arrives. Record the resolved model name from the response, not the name you requested, because that is the only reliable record of what actually answered.

Self-hosted servers invert the problem: the model does not change unless you change it, but the server software does. A vLLM upgrade can change the chat template handling, the default sampling behaviour or the tool-call parser. Pin the image tag, keep the previous deployment warm, and re-run the contract test after every upgrade. The failure is rarely a crash; it is a subtle change in formatting that breaks a parser downstream.

Multimodal inputs and structured outputs

Vision support is expressed as content parts: a message whose content is an array containing a text part and one or more image parts, each with either a URL or a base64 data URI and an optional detail level. The compatibility problem is that image tokenisation is architecture-specific. A 1024 by 1024 image can cost a few hundred tokens on one model and well over a thousand on another, so a request that fits comfortably in a 32K context on the primary model can overflow on the fallback. Providers also differ on whether remote URLs are fetched server-side, which is a security decision as much as a feature one, since a URL fetch from the provider's network is an outbound request you did not make.

Structured output has two implementations that look identical from the client side. The first is prompt-based JSON mode, which guarantees parseable syntax but not the schema you asked for. The second is constrained decoding, where a grammar derived from your JSON Schema masks invalid tokens at each step, which guarantees the shape but can degrade quality if the schema forces unusual token sequences. OpenAI's strict schema mode, vLLM's guided decoding and llama.cpp's grammars all sit in the second category with different levels of support for unions, recursion and optional fields. Test the schema features you actually use, especially nested objects and enums, rather than assuming a simple object test generalises.

The rest of the surface: embeddings and moderation

Most compatible servers also implement /v1/embeddings, which takes a model and either a string or an array of strings and returns a data array of embedding objects with an index and a float array, plus a usage block. Two details cause silent bugs. Some servers return unnormalised vectors and others return unit-length vectors, so cosine similarity computed with a dot product gives different results depending on the provider. And the dimensions parameter is not universally supported; a model that outputs 1,536 dimensions cannot be truncated to 512 on the server unless it was trained for that, and truncating client-side without renormalising changes retrieval quality.

Moderation endpoints are implemented far less consistently, and many self-hosted servers omit them entirely. If your product relies on a moderation call before generation, that dependency has to be part of the compatibility test rather than an assumption. The same applies to files, batches and fine-tuning endpoints: the chat surface is the part everyone implements, and the rest is optional.

Common mistakes

  • Assuming the usage block exists in streaming responses, then billing zero tokens for every streamed request.
  • Parsing server-sent events by splitting on newlines without handling a JSON object cut across two network reads.
  • Treating a 429 from a quota exhaustion the same as a rate limit and retrying forever.
  • Switching the base URL and assuming tool calling, JSON mode and vision still work unchanged.
  • Sending max_tokens to a reasoning model that only accepts max_completion_tokens.
  • Leaving a timestamp or request ID at the top of a system prompt, which defeats prompt caching on every call.
  • Testing with English prose and shipping to users who write in a language the tokeniser handles very differently.
  • Hard-coding a provider's error strings instead of its status codes, then breaking on the next provider update.
Page feedback

Was this helpful?

A quick signal helps improve these notes.

Report a mistake Straight to the lab inbox

Put it to work

See the models, datasets and gateway this lab runs.