OpenAI SDK with Vertex AI in Node.js
Vertex AI has an OpenAI-compatible Chat Completions endpoint, so you can call Gemini (and OpenAI's open-weight gpt-oss models) with the official openai npm package. Set baseURL to your project's endpoints/openapi URL, pass a Google Cloud access token as apiKey, and change the model name to something like google/gemini-3.5-flash. Everything else in your Node.js code stays the same.
This guide is for Node.js teams who already have OpenAI code and want to run it on Google Cloud, or who want to compare both providers without maintaining two SDKs. If you are still choosing a provider, read OpenAI vs Vertex AI for Production SaaS first. If you have never touched Vertex AI, start with Vertex AI Setup for Node.js Apps.
Naming note: Google now documents Vertex AI's generative features under the name Gemini Enterprise Agent Platform. The API host is still
aiplatform.googleapis.com, and everything below works the same under either name.
What Is the Vertex AI OpenAI-Compatible Endpoint?
The OpenAI-compatible endpoint is a translation layer that accepts requests in OpenAI's Chat Completions format and runs them on models hosted in Vertex AI. It is not a proxy to OpenAI. Your prompts never leave Google Cloud, billing goes to your Google Cloud project, and IAM controls who can call it.
There are three things it changes compared with calling api.openai.com:
| Setting | OpenAI | Vertex AI (OpenAI-compatible) |
|---|---|---|
| Base URL | https://api.openai.com/v1 | https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi |
| API key | sk-... OpenAI key | Google Cloud OAuth access token (expires after 1 hour) |
| Model name | gpt-4.1-mini | google/gemini-3.5-flash, openai/gpt-oss-120b-maas |
Only the Chat Completions API is covered. The Responses API, Assistants, and file APIs are OpenAI products and do not exist on Vertex AI.
Can You Use OpenAI Models on Vertex AI?
Partly. This is the most common confusion behind searches like "openai models on vertex ai".
- OpenAI's proprietary GPT models are not on Vertex AI. If you need those, you call OpenAI (or Azure OpenAI) directly.
- OpenAI's open-weight gpt-oss models are on Vertex AI as a managed "model as a service" (MaaS) offering in Model Garden. The model ID in Google's docs is
openai/gpt-oss-120b-maas. - Gemini models use the
google/prefix, for examplegoogle/gemini-3.5-flashorgoogle/gemini-3.1-pro-preview.
So "OpenAI on Vertex" really means two things: the OpenAI SDK and request format work with any supported model, and one family of OpenAI models (gpt-oss) is hosted there.
Prerequisites
- A Google Cloud project with billing enabled.
- The Vertex AI API enabled:
gcloud services enable aiplatform.googleapis.com --project=YOUR_PROJECT_ID
- The
roles/aiplatform.userIAM role on the account or service account that will make calls. - Application Default Credentials (ADC) on your machine:
gcloud auth application-default login
- Node.js 20 or later and two packages:
npm install openai google-auth-library
For gpt-oss you also need to enable the model on its Model Garden page. Google's docs list roles/consumerprocurement.entitlementManager as an extra role for that step, because partner models go through a marketplace entitlement.
Calling Gemini with the OpenAI SDK in Node.js
The key detail is authentication. The endpoint does not accept API keys of any kind, only a short-lived OAuth access token. Current versions of the openai package accept an async function for apiKey, which the SDK calls before each request. Combined with google-auth-library, which caches the token and refreshes it before it expires, you get a client that keeps working past the one-hour mark.
// vertex-openai.js import OpenAI from 'openai'; import { GoogleAuth } from 'google-auth-library'; const PROJECT_ID = process.env.GOOGLE_CLOUD_PROJECT; const LOCATION = 'global'; const auth = new GoogleAuth({ scopes: ['https://www.googleapis.com/auth/cloud-platform'], }); export const vertex = new OpenAI({ baseURL: `https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/endpoints/openapi`, // Called before each request. google-auth-library returns a cached token // and refreshes it automatically when it is close to expiry. apiKey: async () => { const client = await auth.getClient(); const { token } = await client.getAccessToken(); return token; }, }); const completion = await vertex.chat.completions.create({ model: 'google/gemini-3.5-flash', messages: [ { role: 'system', content: 'You are a concise assistant for a SaaS help desk.' }, { role: 'user', content: 'Explain what a webhook is in two sentences.' }, ], max_tokens: 200, }); console.log(completion.choices[0].message.content);
If you are on an older openai version that only takes a string, create the client per request with a fresh token instead. Do not fetch one token at startup and reuse it: your app will start returning 401 errors exactly one hour after each deploy, which is a confusing bug to chase.
Global vs regional endpoints
The example uses the global location, which Google recommends for availability. If you need data residency, use a regional host instead:
https://us-central1-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/us-central1/endpoints/openapi
Two things to know. First, Google's own samples mix v1 and v1beta1 in these URLs; v1 worked for the features in this post, but if a newer feature returns 404, try v1beta1. Second, some organizations block the global endpoint with the constraints/gcp.restrictEndpointUsage org policy. If global calls fail with a policy error, switch to a region.
Streaming Responses
Streaming works exactly like OpenAI, with server-sent events ending in data: [DONE]:
const stream = await vertex.chat.completions.create({ model: 'google/gemini-3.5-flash', messages: [{ role: 'user', content: 'Write a 3-step onboarding checklist.' }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content ?? ''); }
Tool Calling (Function Calling)
Tools use the standard OpenAI shape. tool_choice accepts none, auto and required:
const tools = [ { type: 'function', function: { name: 'get_invoice_status', description: 'Look up the payment status of an invoice by its ID', parameters: { type: 'object', properties: { invoiceId: { type: 'string' } }, required: ['invoiceId'], }, }, }, ]; const res = await vertex.chat.completions.create({ model: 'google/gemini-3.5-flash', messages: [{ role: 'user', content: 'Has invoice INV-1042 been paid?' }], tools, tool_choice: 'auto', }); const call = res.choices[0].message.tool_calls?.[0]; if (call) { const args = JSON.parse(call.function.arguments); console.log(call.function.name, args); // get_invoice_status { invoiceId: 'INV-1042' } }
Google's docs note that tool parameters are interpreted with the OpenAPI schema subset, not full JSON Schema. Keep schemas flat and simple (type, properties, required, enum, description). The same rule applies to the patterns in MCP Explained: AI Agents Meet Your Tools, where tools also need small, well-described schemas.
Structured JSON Output
response_format supports text, json_object and json_schema:
const res = await vertex.chat.completions.create({ model: 'google/gemini-3.5-flash', messages: [{ role: 'user', content: 'Extract: "Call Priya on Friday about the Q3 renewal"' }], response_format: { type: 'json_schema', json_schema: { name: 'task', schema: { type: 'object', properties: { person: { type: 'string' }, day: { type: 'string' }, topic: { type: 'string' }, }, required: ['person', 'day', 'topic'], }, }, }, }); const task = JSON.parse(res.choices[0].message.content);
Fully recursive schemas are not supported. Validate the parsed result with Zod before trusting it; TypeScript for AI Applications in Node.js shows that pattern end to end.
Gemini-Specific Features: reasoning_effort and extra_body
The compatibility layer maps OpenAI's reasoning_effort to Gemini thinking budgets. Per Google's docs, low maps to 1,024 thinking tokens, medium to 8,192 and high to 24,576 (Gemini 3 models map it to a thinking level instead).
For features OpenAI has no field for, Vertex AI reads a google object inside extra_body. With the Node SDK, you pass extra fields directly in the request body:
const res = await vertex.chat.completions.create({ model: 'google/gemini-3.5-flash', messages: [{ role: 'user', content: 'Plan a database migration in 5 steps.' }], // Gemini-only options. Use either this or reasoning_effort, not both. // In TypeScript, add // @ts-expect-error above this line (not in the OpenAI types). extra_body: { google: { thinking_config: { include_thoughts: false, thinking_budget: 4096 }, }, }, });
Google lists safety_settings, cached_content, thinking_config and media_resolution among the supported extra_body.google keys. If you find yourself needing several of them, that is the signal to switch that code path to @google/genai.
Supported and Ignored Parameters
| Parameter | Supported on Vertex AI |
|---|---|
messages, model, max_tokens / max_completion_tokens | Yes |
temperature, top_p, n, stop, seed | Yes |
frequency_penalty, presence_penalty | Yes |
stream | Yes |
tools, tool_choice | Yes |
response_format (text, json_object, json_schema) | Yes |
reasoning_effort | Yes (mapped to thinking budget) |
Images (image_url with gs:// or data URI), input_audio | Yes |
logprobs, logit_bias | Not listed, ignored |
| Responses API, Assistants, Files, fine-tuning | No |
The important line in Google's docs: unsupported parameters are ignored, not rejected. If your OpenAI code depends on logprobs for confidence scores, it will silently get nothing back. Test every parameter you rely on.
Calling gpt-oss Through the Same Client
Once gpt-oss is enabled in Model Garden, it is just another model name on the same endpoint:
const res = await vertex.chat.completions.create({ model: 'openai/gpt-oss-120b-maas', messages: [{ role: 'user', content: 'Summarize the CAP theorem in one paragraph.' }], max_tokens: 400, });
This makes a cheap A/B test possible: same client, same prompts, swap the model string, and compare quality and cost on your real traffic. For cost tracking per model, see How to Cut Your AI API Costs.
When to Use the OpenAI SDK vs @google/genai
| Situation | Use |
|---|---|
| Existing OpenAI codebase, want Gemini as a second provider | OpenAI SDK + Vertex endpoint |
| Gateway or framework that only speaks the OpenAI format | OpenAI SDK + Vertex endpoint |
| A/B testing Gemini against gpt-oss or OpenAI | OpenAI SDK + Vertex endpoint |
| New Gemini-first product | @google/genai |
| Context caching, grounding with Google Search, image or video generation | @google/genai |
The compatibility layer is the fastest way to get Gemini into an OpenAI codebase. It is not the best long-term interface for a Gemini-heavy product, because every Gemini-only feature becomes an extra_body escape hatch. Many teams use both: the OpenAI SDK for shared chat logic, @google/genai for the Google-specific paths.
Production Checklist
- Use the async
apiKeyfunction (or a per-request client) so tokens refresh. Never hard-code a token. - Run on a service account, not your user credentials. On Cloud Run, attach a service account with
roles/aiplatform.userand ADC picks it up with no key file. Deploy Node.js AI Apps to Cloud Run covers that setup. - Pin model IDs in config, not code, so you can roll forward when Google retires a version.
- Handle 429s with exponential backoff. The OpenAI SDK retries twice by default; raise
maxRetriesfor batch jobs. - Test ignored parameters. Anything not on Google's list does nothing.
Frequently Asked Questions
Does Vertex AI support the OpenAI API?
Yes. Vertex AI (now documented as Gemini Enterprise Agent Platform) exposes an OpenAI-compatible Chat Completions endpoint. Point the official OpenAI SDK at https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi, pass a Google Cloud access token as the API key, and use model names like google/gemini-3.5-flash. Streaming, tool calls, JSON output and images are supported.
Can I use OpenAI's GPT models on Vertex AI?
Not the proprietary GPT models. Vertex AI does not host OpenAI's closed models. Model Garden offers OpenAI's open-weight gpt-oss family as a managed API, for example openai/gpt-oss-120b-maas, which you call through the same OpenAI-compatible endpoint after enabling it.
What API key do I use with the OpenAI SDK on Vertex AI?
Not an OpenAI key and not a Gemini API key. The endpoint only accepts Google Cloud authentication, so apiKey is an OAuth access token from Application Default Credentials. Tokens expire after one hour by default, so production code must refresh them; google-auth-library does this for you.
Which OpenAI parameters does Vertex AI ignore?
The common Chat Completions parameters are supported: messages, model, max_tokens, temperature, top_p, n, stop, seed, stream, tools, tool_choice, response_format, reasoning_effort and the penalty parameters. Anything not on Google's list, such as logprobs or logit_bias, is silently ignored rather than rejected.
Should I use the OpenAI SDK or @google/genai for Gemini on Vertex AI?
Use the OpenAI SDK when you already have OpenAI code, want to A/B test providers, or route through an OpenAI-format gateway. Use @google/genai for new Gemini-first code, because it exposes every Gemini feature without extra_body workarounds.