OpenAI TypeScript and JavaScript API Library
This library provides convenient access to the OpenAI REST API from TypeScript or JavaScript.
It is generated from our OpenAPI specification.
To learn how to use the OpenAI API, check out our API Reference and Documentation.
Installation
npm install openai
Installation with Deno
Deno can import the package directly from npm:
import OpenAI from 'npm:openai';
Usage
The full API of this library can be found in api.md file along with many code examples.
The primary API for interacting with OpenAI models is the Responses API. You can generate text from the model with the code below.
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
});
const response = await client.responses.create({
model: 'gpt-5.5',
instructions: 'You are a coding assistant that talks like a pirate',
input: 'Are semicolons optional in JavaScript?',
});
console.log(response.output_text);
Multi-turn conversations
When you manage Responses API conversation history manually, preserve output items in order. Filtering
response.output to messages can drop required reasoning or tool-call items and cause the next request to
fail.
Use the SDK's toResponseInputItems() helper to normalize all replayable output items before adding them to
the next request. For simple continuation, you can pass previous_response_id instead.
See the manual conversation state example and
conversation state guide.
The previous standard (supported indefinitely) for generating text is the Chat Completions API. You can use that API to generate text from the model with the code below.
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
});
const completion = await client.chat.completions.create({
model: 'gpt-5.5',
messages: [
{ role: 'developer', content: 'Talk like a pirate.' },
{ role: 'user', content: 'Are semicolons optional in JavaScript?' },
],
});
console.log(completion.choices[0].message.content);
Vision
Use the Responses API to analyze images and generate text about visual content.
import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted
});
const response = await client.responses.create({
model: 'gpt-5.5',
input: [
{
role: 'user',
content: [
{ type: 'input_text', text: 'What is in this image?' },
{
type: 'input_image',
detail: 'auto',
image_url:
'https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg',
},
],
},
],
});
console.log(response.output_text);
Workload Identity Authentication
For secure, automated environments like cloud-managed Kubernetes, Azure, and GCP, you can use workload identity authentication with short-lived tokens from cloud identity providers instead of long-lived API keys.
The workloadIdentity parameter is mutually exclusive with apiKey.
For subject-token workload identity, the required fields are identityProviderId, serviceAccountId, and provider. X.509 workload identity instead uses an enrolled client certificate and its separately configured transport.
Kubernetes (service account tokens)
import OpenAI from 'openai';
import { k8sServiceAccountTokenProvider } from 'openai/auth';
const client = new OpenAI({
workloadIdentity: {
identityProviderId: 'idp-123',
serviceAccountId: 'sa-456',
provider: k8sServiceAccountTokenProvider('/var/run/secrets/kubernetes.io/serviceaccount/token'),
},
});
const response = await client.chat.completions.create({
model: 'gpt-5.5',
messages: [{ role: 'user', content: 'Hello!' }],
});
Azure (managed identity)
import OpenAI from 'openai';
import { azureManagedIdentityTokenProvider } from 'openai/auth';
const client = new OpenAI({
workloadIdentity: {
identityProviderId: 'idp-123',
serviceAccountId: 'sa-456',
provider: azureManagedIdentityTokenProvider(),
},
});
GCP (compute engine metadata)
import OpenAI from 'openai';
import { gcpIDTokenProvider } from 'openai/auth';
const client = new OpenAI({
workloadIdentity: {
identityProviderId: 'idp-123',
serviceAccountId: 'sa-456',
provider: gcpIDTokenProvider(),
},
});
Custom subject token provider
import OpenAI from 'openai';
const client = new OpenAI({
workloadIdentity: {
identityProviderId: 'idp-123',
serviceAccountId: 'sa-456',
provider: {
tokenType: 'jwt',
getToken: async () => {
return 'your-jwt-token';
},
},
},
});
You can also customize the subject-token refresh buffer (default is 1200 seconds (20 minutes) before expiration; the effective buffer is capped at half of the actual token lifetime):
import OpenAI from 'openai';
import { k8sServiceAccountTokenProvider } from 'openai/auth';
const client = new OpenAI({
workloadIdentity: {
identityProviderId: 'idp-123',
serviceAccountId: 'sa-456',
provider: k8sServiceAccountTokenProvider('/var/token'),
refreshBufferSeconds: 120.0,
},
});
X.509 client certificates
Applications enrolled for X.509 workload identity can authenticate using a certificate-backed credential instead of a subject-token provider or API key. This Node.js-only integration requires the optional undici peer and currently supports only the global https://mtls.api.openai.com/v1 API endpoint.
import OpenAI from 'openai';
import { workloadIdentity } from 'openai/auth/x509-transport';
const credential = workloadIdentity.fromX509({
certificateChain: process.env['OPENAI_X509_CLIENT_CERTIFICATE_CHAIN_PEM']!,
privateKey: process.env['OPENAI_X509_CLIENT_PRIVATE_KEY_PEM']!,
identityProviderId: process.env['OPENAI_X509_IDENTITY_PROVIDER_ID']!,
serviceAccountId: process.env['OPENAI_X509_SERVICE_ACCOUNT_ID']!,
});
try {
const client = new OpenAI({
credential,
project: process.env['OPENAI_X509_PROJECT_ID'] ?? null,
});
console.log((await client.models.list()).data.length);
} finally {
await credential.close();
}
The SDK owns the credential's verified TLS transport, caches short-lived tokens in memory, isolates certificate generations, and bounds retries and cancellation. Set refreshBufferSeconds on the credential to configure proactive refresh; it defaults to 1,200 seconds (20 minutes) and is capped at half of the token's lifetime. For CONNECT proxies, encrypted private keys, live verification, and certificate rotation, see the X.509 workload-identity example.
Streaming responses
We provide support for streaming responses using Server-Sent Events (SSE).
import OpenAI from 'openai';
const client = new OpenAI();
const stream = await client.responses.create({
model: 'gpt-5.5',
input: 'Say "Sheep sleep deep" ten times fast!',
stream: true,
});
for await (const event of stream) {
console.log(event);
}
File uploads
Request parameters that correspond to file uploads can be passed in many different forms:
File (or an object with the same structure)
- a
fetch Response (or an object with the same structure)
- an
fs.ReadStream
- the return value of our
toFile or toStreamingFile helpers
import fs from 'fs';
import OpenAI, { toFile, toStreamingFile } from 'openai';
const client = new OpenAI();
// If you have access to Node `fs` we recommend using `fs.createReadStream()`:
await client.files.create({ file: fs.createReadStream('input.jsonl'), purpose: 'fine-tune' });
// Or if you have the web `File` API you can pass a `File` instance:
await client.files.create({ file: new File(['my bytes'], 'input.jsonl'), purpose: 'fine-tune' });
// You can also pass a `fetch` `Response`:
await client.files.create({
file: await fetch('https://somesite/input.jsonl'),
purpose: 'fine-tune',
});
// Finally, if none of the above are convenient, you can use our `toFile` helper:
await client.files.create({
file: await toFile(Buffer.from('my bytes'), 'input.jsonl'),
purpose: 'fine-tune',
});
await client.files.create({
file: await toFile(new Uint8Array([0, 1, 2]), 'input.jsonl'),
purpose: 'fine-tune',
});
// `toFile()` creates a web File, so it must buffer stream inputs before sending them.
// Use `toStreamingFile()` to stream an arbitrary web, Node, or cloud-storage stream directly:
await client.files.create({
file: toStreamingFile(myReadableStream, 'input.jsonl', { type: 'application/jsonl' }),
purpose: 'fine-tune',
});
Webhook Verification
Verifying webhook signatures is optional but encouraged.
Webhook verification is asynchronous. Always await unwrap() or verifySignature() before trusting
the event.
For more information about webhooks, see the API docs.
Parsing webhook payloads
For most use cases, you will likely want to verify the webhook and parse the payload at the same time. To achieve this, we provide the method client.webhooks.unwrap(), which parses a webhook request and verifies that it was sent by OpenAI. This method will throw an error if the signature is invalid.
Note that the body parameter must be the raw JSON string sent from the server (do not parse it first). The .unwrap() method will parse this JSON for you into an event object after verifying the webhook was sent from OpenAI.
import { headers } from 'next/headers';
import OpenAI from 'openai';
const client = new OpenAI({
webhookSecret: process.env.OPENAI_WEBHOOK_SECRET, // env var used by default; explicit here.
});
export async function webhook(request: Request) {
const headersList = await headers();
const body = await request.text();
try {
const event = await client.webhooks.unwrap(body, headersList);
switch (event.type) {
case 'response.completed':
console.log('Response completed:', event.data);
break;
case 'response.failed':
console.log('Response failed:', event.data);
break;
default:
console.log('Unhandled event type:', event.type);
}
return Response.json({ message: 'ok' });
} catch (error) {
console.error('Invalid webhook signature:', error);
return new Response('Invalid signature', { status: 400 });
}
}
Verifying webhook payloads directly
In some cases, you may want to verify the webhook separately from parsing the payload. If you prefer to handle these steps separately, we provide the method client.webhooks.verifySignature() to only verify the signature of a webhook request. Like .unwrap(), this method will throw an error if the signature is invalid.
Note that the body parameter must be the raw JSON string sent from the server (do not parse it first). You will then need to parse the body after verifying the signature.
import { headers } from 'next/headers';
import OpenAI from 'openai';
const client = new OpenAI({
webhookSecret: process.env.OPENAI_WEBHOOK_SECRET, // env var used by default; explicit here.
});
export async function webhook(request: Request) {
const headersList = await headers();
const body = await request.text();
try {
await client.webhooks.verifySignature(body, headersList);
// Parse the body after verification
const event = JSON.parse(body);
console.log('Verified event:', event);
return Response.json({ message: 'ok' });
} catch (error) {
console.error('Invalid webhook signature:', error);
return new Response('Invalid signature', { status: 400 });
}
}
Handling errors
When the library is unable to connect to the API,
or if the API returns a non-success status code (i.e., 4xx or 5xx response),
a subclass of APIError will be thrown:
const job = await client.fineTuning.jobs
.create({ model: 'gpt-4o', training_file: 'file-abc123' })
.catch(async (err) => {
if (err instanceof OpenAI.APIError) {
console.log(err.requestID);
console.log(err.status); // 400
console.log(err instanceof OpenAI.BadRequestError); // true for an HTTP 400 response
console.log(err.headers); // response Headers
} else {
throw err;
}
});
Error codes are as follows:
| Status Code |
Error Type |
| 400 |
BadRequestError |
| 401 |
AuthenticationError |
| 403 |
PermissionDeniedError |
| 404 |
NotFoundError |
| 409 |
ConflictError |
| 422 |
UnprocessableEntityError |
| 429 |
RateLimitError |
| >=500 |
InternalServerError |
| N/A |
APIConnectionError |
Retries
Certain errors will be automatically retried 2 times by default, with a short exponential backoff.
Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,
429 Rate Limit, and >=500 Internal errors will all be retried by default.
You can use the maxRetries option to configure or disable this: