Square CloudSquare Cloud

What is an OpenAI-compatible API?

An OpenAI-compatible API accepts the same endpoints and JSON format as the OpenAI API, such as chat completions. To switch providers, you change the base URL, the API key and the model name.

Updated 7 min read

Learning objectives

After reading this article you will be able to:

  • Understand what OpenAI compatibility guarantees and what it does not
  • Switch providers by changing base URL, key and model, with the SDK or plain HTTP
  • Know what to test before switching: models, parameters, tools, embeddings and errors
On this page

If you have ever called a language model from code, you probably used OpenAI's format: a list of messages with roles, a model field and a reply inside choices. The format became so common that other providers, local servers and gateways started accepting it. The same code can then talk to different models.

"Compatible" does not mean identical, though. Compatibility covers the format, and the details vary a lot. Knowing where the differences are saves you from the worst surprise: a parameter that raises no error and also does nothing.

What does OpenAI-compatible mean?#

An OpenAI-compatible API accepts the same routes, authentication and JSON format as the OpenAI API, so a client built for OpenAI works after changing only the address, the key and the model.

In practice, that usually means:

  • Routes relative to a base URL. On OpenAI, the base is https://api.openai.com/v1 and chat lives at POST /chat/completions. A compatible provider has its own base URL with the same routes after it. Many also offer /models and sometimes /embeddings.
  • Header authentication with Authorization: Bearer <key>.
  • The same request body: model, messages with the system, user, assistant and tool roles, and optional fields such as tools and stream.
  • The same response: the text in choices[0].message.content, the stop reason in finish_reason and the token count in usage.

Most of the time, "compatible" refers to the Chat Completions format. OpenAI itself recommends the Responses API for new projects and says Chat Completions remains supported. Do not assume a compatible provider accepts both.

How do you switch providers in practice?#

With the official SDK, switching is configuration, not code. The Python and Node.js SDKs read OPENAI_API_KEY and OPENAI_BASE_URL from the environment, so the same script talks to any provider (pip install openai):

python
import os

from openai import OpenAI

# Reads OPENAI_API_KEY and OPENAI_BASE_URL from the environment.
# Without OPENAI_BASE_URL, the SDK uses OpenAI itself.
client = OpenAI()

response = client.chat.completions.create(
    model=os.environ["OPENAI_MODEL"],
    messages=[
        {"role": "system", "content": "Answer in one sentence."},
        {"role": "user", "content": "What is an OpenAI-compatible API?"},
    ],
)
print(response.choices[0].message.content)
if response.usage:
    print(response.usage.total_tokens, "tokens")

What changes from one provider to another lives in .env:

bash
OPENAI_BASE_URL=https://api.example.com/v1
OPENAI_API_KEY=your-key-for-this-provider
OPENAI_MODEL=model-id-from-this-provider

Node.js works the same way: new OpenAI() reads the same variables, or you pass { baseURL, apiKey } to the constructor.

Without an SDK, it is a regular HTTP request. Set the base URL without a trailing slash:

bash
curl "$OPENAI_BASE_URL/chat/completions" \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "'"$OPENAI_MODEL"'",
    "messages": [{"role": "user", "content": "Say hi in one word."}]
  }'

The response looks like this, shortened:

json
{
  "object": "chat.completion",
  "model": "model-id",
  "choices": [
    {
      "index": 0,
      "message": { "role": "assistant", "content": "Hi!" },
      "finish_reason": "stop"
    }
  ],
  "usage": { "prompt_tokens": 12, "completion_tokens": 2, "total_tokens": 14 }
}

A few base URLs, as each provider documents them (check the current one before you use it):

Provider Base URL Note
OpenAI https://api.openai.com/v1 The SDK default
Anthropic https://api.anthropic.com/v1 Per Anthropic, the layer is meant to test and compare models, and is not considered a long-term production solution
Google (Gemini API) On the OpenAI compatibility page of the Gemini API docs The path includes the API version: copy the current value from the docs
Ollama (local) http://localhost:11434/v1 The client requires a key, but Ollama ignores it

What usually varies between providers?#

The format is the same; what each provider does with it is not. The differences below are documented by the providers themselves:

What changes Documented example How to protect yourself
Models Each provider has its own IDs; on local Ollama, the model must be pulled first Model in an environment variable; list what is available at /models
Parameters On Anthropic, seed, logprobs and presence_penalty are ignored and n must be 1; Ollama does not support tool_choice Read the support table and never assume a field took effect
Function calling On Anthropic, the tools' strict flag is ignored, so arguments may not follow the schema Validate arguments in your code before running anything
Structured output On Anthropic, response_format only accepts json_schema with strict: true; anything else returns a 400 Test the exact mode you use
Embeddings Ollama and Gemini offer /embeddings; not every provider does Treat embeddings as a separate choice
Inputs beyond text On Anthropic, audio and file inputs return a 400 Check before sending images, audio or PDFs
Errors and limits Anthropic keeps the error format, but the messages are not equivalent, and some rate limit headers have other names Handle errors by HTTP status and code, never by message text
Responses API Ollama implements /v1/responses, but without state For portability, stay on Chat Completions

Two rows deserve attention. Embeddings do not mix across models: vectors from one model cannot be compared with another's, so switching embedding providers means regenerating everything (see what embeddings are). And function calling is the backbone of an AI agent: if the provider does not follow the schema strictly, your code has to validate every call.

Why do so many APIs adopt this format?#

Because the ecosystem already exists. OpenAI maintains official SDKs in several languages, and many AI frameworks and tools accept a configurable base URL. A provider that speaks this format gets all of that at once, and developers switch models without rewriting the integration.

It also makes local development easier. You can test against a model on your own machine and point to a cloud API in production by changing only variables. The trade-offs of each side are in local LLM vs API.

How do you test a provider before switching?#

Before you touch production, run this checklist against the new provider:

  1. A simple call. The script above, checking content, finish_reason and usage.
  2. Streaming. With stream: true, the reply arrives as server-sent events: each event is a chat.completion.chunk with the partial text in delta, and the stream ends with the line data: [DONE]. Details in how to stream AI responses.
  3. A full tool call round trip. The model asks for the tool, you return the result in a role: "tool" message with the tool_call_id, and it finishes the answer.
  4. Errors. A wrong key should return 401. In the SDK, error classes come from the HTTP status (AuthenticationError for 401, RateLimitError for 429), so the handling works with any provider that uses the same status codes. See how to handle 429 in 429 errors from AI APIs and context overflow in context_length_exceeded.
  5. Quality. Run your product's real questions. A prompt heavily tuned for one model may perform worse on another, and Anthropic recommends reworking prompts when you switch.

To pick which model to try, see which AI model to choose for your chatbot.

When is the native API the better choice?#

When you need a feature the OpenAI format has no place for. Anthropic, for example, recommends its native API for the full feature set and names PDF processing, citations, thinking and prompt caching. Google exposes Gemini-specific features through the compatibility layer in an extra field, extra_body, which is already provider-specific code.

The rule of thumb: use compatibility to get started, compare models and keep switching cheap. When one provider becomes central to your product, check whether its native API offers something you are leaving on the table.

How to do this on Square Cloud#

The Square Cloud AI Gateway is an OpenAI-compatible API for using cubic, the platform's AI model, in your own products. To point this article's Python script at it, set:

bash
OPENAI_BASE_URL=https://api.squarecloud.app/v2/ai
OPENAI_API_KEY=your-api-key-with-the-ai-chat-scope
OPENAI_MODEL=cubic

The key is an account API key with the ai:chat scope. For typed decisions (yes or no, a choice between options, a score on a scale), the cubic-decision model answers at POST /v2/ai/decisions.

Against the table of differences, the gateway looks like this: function calling in the OpenAI format (up to 32 tools), built-in web search, reasoning_effort and streaming with stream: true in the chat.completion.chunk format. It takes text only, with no image, audio or file input, and it does not generate embeddings: code that calls /embeddings needs another provider for that part. It keeps no state, so you send the history with every request (up to 500 messages). Errors follow the OpenAI format, with codes such as rate_limit_exceeded, daily_limit_reached, concurrent_limit_reached and context_length_exceeded.

The gateway comes with the Standard plan and up (from R$44.99 a month), at no extra cost within the plan's limits: up to 2.5 million tokens a day and a context of up to 64k tokens on Standard, up to 5 million and 128k on Pro. Beyond that, there are AI credit packs. Billing is in Brazilian reais, with a Brazilian invoice. See the details on AI Gateway.

AI

Host AI apps in always-on containers

OpenAI-compatible API

FAQs

Do I have to use the OpenAI SDK to call a compatible API?

No. Under the hood it is HTTP with JSON, so any HTTP client works. The SDK helps with types, retries, streaming and error classes mapped to HTTP status codes.

Does an OpenAI-compatible API use OpenAI's models?

Not necessarily. Compatible describes the request format, not the model. Each provider serves its own models under its own names, and you change the model value when you switch providers.

Why did a parameter have no effect on another provider?

Because many compatibility layers silently ignore the fields they do not support. Anthropic, for example, documents that most unsupported fields are ignored without an error. Check the provider's support table before you rely on a parameter.

Can I run an OpenAI-compatible API on my own computer?

Yes. Ollama, for example, exposes a compatible API at http://localhost:11434/v1. The SDK requires an API key, but Ollama ignores it, so any value works.

Next articleHow to build a RAG chatbot with PostgreSQL and pgvectorBuild a RAG chatbot with PostgreSQL and pgvector: chunk your documents, create embeddings and an HNSW index, search by distance and answer with sources.