MCPcopy Index your code
hub / github.com/openai/openai-node

github.com/openai/openai-node @v6.45.0

repository ↗ · DeepWiki ↗ · release v6.45.0 ↗ · + Follow
2,969 symbols 6,097 edges 520 files 343 documented · 12% updated 10d agov6.45.0 · 2026-06-24★ 11,013113 open issues
README

OpenAI TypeScript and JavaScript API Library

NPM version npm bundle size JSR Version

This library provides convenient access to the OpenAI REST API from TypeScript or JavaScript.

It is generated from our OpenAPI specification with Stainless.

To learn how to use the OpenAI API, check out our API Reference and Documentation.

Installation

npm install openai

Installation from JSR

deno add jsr:@openai/openai
npx jsr add @openai/openai

These commands will make the module importable from the @openai/openai scope. You can also import directly from JSR without an install step if you're using the Deno JavaScript runtime:

import OpenAI from 'jsr:@openai/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',
          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.

The required fields are identityProviderId, serviceAccountId, and provider.

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 token refresh buffer (default is 1200 seconds (20 minutes) before expiration):

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,
  },
});

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 helper
import fs from 'fs';
import OpenAI, { toFile } 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',
});

Webhook Verification

Verifying webhook signatures is optional but encouraged.

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 = headers();
  const body = await request.text();

  try {
    const event = 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 = headers();
  const body = await request.text();

  try {
    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.request_id);
      console.log(err.status); // 400
      console.log(err.name); // BadRequestError
      console.log(err.headers); // {server: 'nginx', ...}
    } else {
      throw err;
    }
  });

Error codes are as follows:

Status Code Error Type
400 BadRequestError
401 AuthenticationError
403 PermissionDeniedError
404 NotFoundError
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:

// Configure the default for all requests:
const client = new OpenAI({
  maxRetries: 0, // default is 2
});

// Or, configure per-request:
await client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I get the name of the current day in JavaScript?' }], model: 'gpt-5.5' }, {
  maxRetries: 5,
});

Timeouts

Requests time out after 10 minutes by default. You can configure this with a timeout option:

// Configure the default for all requests:
const client = new OpenAI({
  timeout: 20 * 1000, // 20 seconds (default is 10 minutes)
});

// Override per-request:
await client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I list all files in a directory using Python?' }], model: 'gpt-5.5' }, {
  timeout: 5 * 1000,
});

On timeout, an APIConnectionTimeoutError is thrown.

Note that requests which time out will be retried twice by default.

Request IDs

For more information on debugging requests, see these docs

All object responses in the SDK provide a _request_id property which is added from the x-request-id response header so that you can quickly log failing requests and report them back to OpenAI.

const response = await client.responses.create({ model: 'gpt-5.5', input: 'testing 123' });
console.log(response._request_id); // req_123

You can also access the Request ID using the .withResponse() method:

const { data: stream, request_id } = await openai.responses
  .create({
    model: 'gpt-5.5',
    input: 'Say this is a test',
    stream: true,
  })
  .withResponse();

Auto-pagination

List methods in the OpenAI API are paginated. You can use the for await … of syntax to iterate through items across all pages:

```ts async function fetchAllFineT

Extension points exported contracts — how you extend this code

BedrockRequestAuth (Interface)
(no doc) [6 implementers]
src/internal/bedrock.ts
ChatCompletionRunnerContext (Interface)
(no doc) [1 implementers]
src/lib/AbstractChatCompletionRunner.ts
RunOpts (Interface)
(no doc)
ecosystem-tests/cli.ts
Matchers (Interface)
(no doc)
ecosystem-tests/node-ts4.5-jest28/tests/test.ts
Matchers (Interface)
(no doc)
ecosystem-tests/node-ts-esm-auto/tests/test.ts
Env (Interface)
(no doc)
ecosystem-tests/cloudflare-worker/src/worker.ts
Matchers (Interface)
(no doc)
ecosystem-tests/node-ts-cjs-auto/tests/test.ts
Matchers (Interface)
(no doc)
ecosystem-tests/node-ts-esm/tests/test.ts

Core symbols most depended-on inside this repo

expect
called by 2412
ecosystem-tests/ts-browser-webpack/src/index.ts
create
called by 383
src/resources/files.ts
asResponse
called by 296
src/core/api-promise.ts
stringify
called by 267
src/internal/qs/stringify.ts
withResponse
called by 264
src/core/api-promise.ts
get
called by 187
src/client.ts
on
called by 161
src/internal/ws-adapter.ts
post
called by 111
src/client.ts

Shape

Interface 1,402
Method 625
Function 622
Class 320

Languages

TypeScript100%

Modules by API surface

src/resources/responses/responses.ts230 symbols
src/resources/realtime/realtime.ts143 symbols
src/resources/beta/realtime/realtime.ts74 symbols
src/resources/chat/completions/completions.ts73 symbols
src/resources/admin/organization/audit-logs.ts69 symbols
src/resources/admin/organization/usage.ts48 symbols
src/resources/beta/assistants.ts47 symbols
src/core/error.ts47 symbols
src/resources/beta/chatkit/threads.ts44 symbols
src/resources/beta/threads/messages.ts41 symbols
src/lib/ChatCompletionStream.ts40 symbols
src/core/pagination.ts40 symbols

Dependencies from manifests, versioned

@arethetypeswrong/cli0.18.3 · 1×
@aws-sdk/credential-provider-node3.972.47 · 1×
@azure/identity4.2.0 · 1×
@babel/core7.21.0 · 1×
@babel/preset-env7.21.0 · 1×
@babel/preset-typescript7.21.0 · 1×
@cloudflare/workers-types4.20250525.0 · 1×
@smithy/hash-node4.3.5 · 1×
@smithy/protocol-http5.4.5 · 1×
@smithy/signature-v45.4.5 · 1×
@swc/core1.3.102 · 1×
@swc/jest0.2.29 · 1×

For agents

$ claude mcp add openai-node \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact