Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
O

openai-node

> AI 编程
Open source

Official JavaScript / TypeScript library for the OpenAI API

11.1K stars0 likes2 views
WebsiteGitHub

About

Official JavaScript / TypeScript library for the OpenAI API

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

bash
npm install openai

Installation with Deno

Deno can import the package directly from npm:

typescript
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.

typescript
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.

typescript
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.

…

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)

typescript
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)

typescript
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)

typescript
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

typescript
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):

typescript
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.

…

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).

typescript
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
…

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.

…

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.

…

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:

typescript
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:

javascript
// 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:

typescript
// 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.

Cancellation

Pass an AbortSignal in the request's signal option to cancel a request, including while its response body is being read.

When native signal composition is unavailable or incompatible with the supplied signal, the SDK shares one listener per caller signal and holds request callbacks weakly. Cleanup depends on garbage collection; keeping a raw response or its body alive can keep its cancellation subscription alive after consumption. Older runtimes without WeakRef or FinalizationRegistry keep the existing fallback, which can retain a listener for each successful request until the caller aborts.

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.

typescript
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:

typescript
const { data: stream, request_id } = await openai.responses
  .create({
    model: 'gpt-5.5',
    input: 'Say this is

Issues· 7 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptnodejsopenaitypescript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedOct 2, 2026
CategoryAI 编程
PricingOpen source

> Related tools

G
GitHub Copilot
GitHub 官方 AI 编程助手,覆盖补全、Chat 与 Agent 模式。
C
Cursor
AI 原生代码编辑器,对话改代码、多文件 Agent 与规则体系是其核心。
S
skills
Skills for Real Engineers. Straight from my .agents directory.