Integration Guides

OpenAI-Compatible API + AI SDK: Setup and Pitfalls (2026)

ROIBest AI

Two ways to point the AI SDK at an OpenAI-compatible API

The Vercel AI SDK (ai package, version 7 as of November 2026) talks to providers through provider packages. For any endpoint that speaks the OpenAI wire format, such as a gateway, DeepSeek, OpenRouter, vLLM, LM Studio or Ollama, you have two options:

Option

Package

Which OpenAI API it calls

Use it when

createOpenAICompatible

@ai-sdk/openai-compatible

Chat Completions (/chat/completions)

The endpoint is "OpenAI-compatible" but is not OpenAI itself. This is the right default.

createOpenAI with baseURL

@ai-sdk/openai

Responses API by default (openai('id')), Chat Completions with openai.chat('id')

The endpoint is a pass-through proxy in front of real OpenAI models and supports /responses.

The detail that trips most people: since AI SDK 5, the default openai('model-id') factory calls the Responses API. Most third-party servers only implement /v1/chat/completions, so swapping baseURL on the OpenAI provider and keeping openai('model-id') produces 404s or "unknown endpoint" errors. The AI SDK docs say this directly: if your base URL only supports Chat Completions, use openai.chat('model-id') or the OpenAI-compatible provider.

Install and create a provider

npm install ai @ai-sdk/openai-compatible zod
import { createOpenAICompatible } from '@ai-sdk/openai-compatible';

export const gateway = createOpenAICompatible({
  name: 'gateway',                       // also the key for providerOptions
  baseURL: 'https://api.example.com/v1', // include /v1 if the server expects it
  apiKey: process.env.GATEWAY_API_KEY,   // sent as Authorization: Bearer <key>
  includeUsage: true,                    // token usage in streaming responses
});

What each setting does, from the @ai-sdk/openai-compatible reference:

  • baseURL: the prefix the SDK appends /chat/completions, /embeddings or /completions to. Use the same value you would give the OpenAI Python SDK, normally ending in /v1.
  • apiKey: becomes the Authorization: Bearer header. Local servers that do not check keys can omit it.
  • headers and queryParams: extra headers (for example a project or tenant header) and query parameters (for example api-version on Azure-style endpoints) added to every request.
  • includeUsage: off by default. Turn it on if you track token cost, otherwise streamed calls return no usage.
  • supportsStructuredOutputs: set to true only if the server honours response_format with a JSON schema.
  • fetch: a custom fetch for logging, retries or tests.

Generate and stream text

import { generateText, streamText } from 'ai';
import { gateway } from './gateway';

const { text, usage } = await generateText({
  model: gateway('deepseek-chat'),
  prompt: 'Explain idempotency keys in two sentences.',
});

const result = streamText({
  model: gateway('deepseek-chat'),
  system: 'You are a concise assistant.',
  prompt: 'List three causes of HTTP 429.',
});
for await (const delta of result.textStream) process.stdout.write(delta);

The model ID is passed through unchanged, so use exactly the ID that the server lists at GET /v1/models. If you want editor autocompletion, createOpenAICompatible accepts type parameters for chat, completion, embedding and image model IDs.

Tool calling and structured output

Tool calling works the same way as with first-party providers, as long as the backend implements the tools and tool_calls fields:

import { generateText, tool, stepCountIs } from 'ai';
import { z } from 'zod';

const { text } = await generateText({
  model: gateway('qwen3-coder'),
  tools: {
    getOrder: tool({
      description: 'Look up an order by ID',
      inputSchema: z.object({ id: z.string() }),
      execute: async ({ id }) => ({ id, status: 'shipped' }),
    }),
  },
  stopWhen: stepCountIs(3),
  prompt: 'Where is order A-1042?',
});

For JSON output, the SDK uses response_format with a schema only when you set supportsStructuredOutputs: true. Leave it off for servers without JSON-schema support; the SDK then asks for plain JSON mode instead of sending the schema, and validates the result against your schema itself. If a model never calls tools or returns malformed arguments, the cause is usually the serving engine (for example, vLLM needs tool parsing enabled), not the SDK. Our OpenAI-compatible API response format guide covers which response_format modes servers accept.

Provider-specific parameters with providerOptions

Anything the SDK does not model, such as a thinking switch, top_k or a routing hint, goes through providerOptions, keyed by the provider name in camelCase:

await generateText({
  model: gateway('glm-4.6'),
  prompt: 'Summarise this changelog.',
  providerOptions: {
    gateway: {
      reasoningEffort: 'low',          // documented chat option
      thinking: { type: 'disabled' },  // passed through to the request body as-is
    },
  },
});

Unknown keys are copied into the JSON body, so this is how you reach vendor extensions without forking the provider. Note the camelCase rule: a provider named my-gateway is addressed as providerOptions.myGateway. The fields for turning reasoning on or off differ by vendor; see how to enable thinking on OpenAI-compatible APIs.

Local servers: Ollama, LM Studio, vLLM

Server

baseURL

Key

LM Studio

http://localhost:1234/v1

Not required

Ollama

http://localhost:11434/v1

Not checked; any value works

vLLM

http://localhost:8000/v1

Required only if started with --api-key

llama.cpp llama-server

http://localhost:8080/v1

Optional --api-key

const local = createOpenAICompatible({ name: 'local', baseURL: 'http://localhost:11434/v1' });

If your app runs in a browser or an edge function, localhost means the user's machine or the edge runtime, not your workstation. Call local servers from a Node.js route or server action. For setting up the server side, see our self-hosted OpenAI-compatible API guide.

Common errors and what they mean

Symptom

Likely cause

Fix

404 on /responses

Using @ai-sdk/openai with openai('id') against a Chat-Completions-only server

Switch to createOpenAICompatible or openai.chat('id')

404 on /v1/v1/chat/completions or missing /v1

baseURL path wrong

Set baseURL to the path just before /chat/completions

401

Key missing, or the server expects a different header

Check apiKey; use headers for api-key style auth

usage is empty when streaming

includeUsage is off, or the server ignores stream_options

Set includeUsage: true; some servers never report it

Schema errors on structured output

supportsStructuredOutputs set on a server without JSON-schema support

Turn it off and let the SDK validate

Tool calls returned as plain text

Model or engine does not support tool calling

Use a tool-capable model; enable the engine's tool parser

The general list of where "compatible" endpoints diverge from OpenAI is in OpenAI compatibility issues, and base URL mistakes are covered in OpenAI-compatible base URL.

FAQ

Does the Vercel AI SDK support OpenAI-compatible APIs?

Yes. The @ai-sdk/openai-compatible package and its createOpenAICompatible function connect the AI SDK to any server that implements the OpenAI Chat Completions, Embeddings or Completions endpoints, with streaming, tool calling and image inputs where the server supports them.

Should I use @ai-sdk/openai or @ai-sdk/openai-compatible?

Use @ai-sdk/openai-compatible for anything that is not OpenAI itself. @ai-sdk/openai defaults to the Responses API and adds OpenAI-only features, so it fits only real OpenAI or a proxy that forwards /responses.

How do I pass custom parameters such as top_k or thinking?

Put them under providerOptions.<providerName> in camelCase. Keys the SDK does not recognise are passed through into the request body unchanged.

Can I use the AI SDK with Ollama or LM Studio?

Yes. Create a provider with baseURL set to http://localhost:11434/v1 for Ollama or http://localhost:1234/v1 for LM Studio, and call it from server-side code.

Why is usage missing from streamed responses?

includeUsage defaults to off. Set it to true when creating the provider; if usage is still empty, the server does not return usage in streams.

The short version

Install @ai-sdk/openai-compatible, create a provider with name, baseURL and apiKey, and call generateText or streamText with the server's exact model ID. Turn on includeUsage if you track cost, set supportsStructuredOutputs only for servers with JSON-schema support, and put vendor-specific fields in providerOptions. Reach for @ai-sdk/openai only when the backend really supports the Responses API. For a broader explanation of the protocol, start with what an OpenAI-compatible API is.