openai/openai-node v6.31.0
Summary
OpenAI Node.js SDK v6.31.0 release - TypeScript/JavaScript library for accessing OpenAI's REST API with support for Chat Completions and Responses APIs, featuring workload identity authentication for cloud environments.
View Cached Full Text
Cached at: 04/20/26, 08:37 AM
openai/openai-node Source: https://github.com/openai/openai-node # OpenAI TypeScript and JavaScript API Library
npm bundle size JSR Version (https://jsr.io/@openai/openai) This library provides convenient access to the OpenAI REST API from TypeScript or JavaScript. It is generated from our OpenAPI specification (https://github.com/openai/openai-openapi) with Stainless (https://stainlessapi.com/). To learn how to use the OpenAI API, check out our API Reference (https://platform.openai.com/docs/api-reference) and Documentation (https://platform.openai.com/docs). ## Installation sh npm install openai ### Installation from JSR sh 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 (https://jsr.io/docs/using-packages#importing-with-jsr-specifiers) without an install step if you’re using the Deno JavaScript runtime: ts 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 (https://github.com/openai/openai-node/tree/master/examples). The primary API for interacting with OpenAI models is the Responses API (https://platform.openai.com/docs/api-reference/responses). You can generate text from the model with the code below. ts 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.2', instructions: 'You are a coding assistant that talks like a pirate', input: 'Are semicolons optional in JavaScript?', }); console.log(response.output_text); The previous standard (supported indefinitely) for generating text is the Chat Completions API (https://platform.openai.com/docs/api-reference/chat). You can use that API to generate text from the model with the code below. ts 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.2', messages: [ { role: 'developer', content: 'Talk like a pirate.' }, { role: 'user', content: 'Are semicolons optional in JavaScript?' }, ], }); console.log(completion.choices[0].message.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. ### Kubernetes (service account tokens) ts import OpenAI from 'openai'; import { k8sServiceAccountTokenProvider } from 'openai/auth'; const client = new OpenAI({ workloadIdentity: { clientId: 'your-client-id', identityProviderId: 'idp-123', serviceAccountId: 'sa-456', provider: k8sServiceAccountTokenProvider('/var/run/secrets/kubernetes.io/serviceaccount/token'), }, }); const response = await client.chat.completions.create({ model: 'gpt-4', messages: [{ role: 'user', content: 'Hello!' }], }); ### Azure (managed identity) ts import OpenAI from 'openai'; import { azureManagedIdentityTokenProvider } from 'openai/auth'; const client = new OpenAI({ workloadIdentity: { clientId: 'your-client-id', identityProviderId: 'idp-123', serviceAccountId: 'sa-456', provider: azureManagedIdentityTokenProvider(), }, }); ### GCP (compute engine metadata) ts import OpenAI from 'openai'; import { gcpIDTokenProvider } from 'openai/auth'; const client = new OpenAI({ workloadIdentity: { clientId: 'your-client-id', identityProviderId: 'idp-123', serviceAccountId: 'sa-456', provider: gcpIDTokenProvider(), }, }); ### Custom subject token provider ts import OpenAI from 'openai'; const client = new OpenAI({ workloadIdentity: { clientId: 'your-client-id', 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): ts import OpenAI from 'openai'; import { k8sServiceAccountTokenProvider } from 'openai/auth'; const client = new OpenAI({ workloadIdentity: { clientId: 'your-client-id', 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). ts import OpenAI from 'openai'; const client = new OpenAI(); const stream = await client.responses.create({ model: 'gpt-5.2', 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 ts 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 (https://platform.openai.com/docs/guides/webhooks). ### 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. ts 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. ts 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: ts 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 | ## Request IDs > For more information on debugging requests, see these docs (https://platform.openai.com/docs/api-reference/debugging-requests) 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. ts const completion = await client.chat.completions.create({ messages: [{ role: 'user', content: 'Say this is a test' }], model: 'gpt-5.2', }); console.log(completion._request_id); // req_123 You can also access the Request ID using the .withResponse() method: ts const { data: stream, request_id } = await openai.chat.completions .create({ model: 'gpt-5.2', messages: [{ role: 'user', content: 'Say this is a test' }], stream: true, }) .withResponse(); ## Realtime API The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as function calling (https://platform.openai.com/docs/guides/function-calling) through a WebSocket connection. ts import { OpenAIRealtimeWebSocket } from 'openai/realtime/websocket'; const rt = new OpenAIRealtimeWebSocket({ model: 'gpt-realtime' }); rt.on('response.text.delta', (event) => process.stdout.write(event.delta)); For more information see realtime.md. ## Microsoft Azure OpenAI To use this library with Azure OpenAI (https://learn.microsoft.com/azure/ai-services/openai/overview), use the AzureOpenAI class instead of the OpenAI class. > [!IMPORTANT] > The Azure API shape slightly differs from the core API shape which means that the static types for responses / params > won’t always be correct. ts import { AzureOpenAI } from 'openai'; import { getBearerTokenProvider, DefaultAzureCredential } from '@azure/identity'; const credential = new DefaultAzureCredential(); const scope = 'https://cognitiveservices.azure.com/.default'; const azureADTokenProvider = getBearerTokenProvider(credential, scope); const openai = new AzureOpenAI({ azureADTokenProvider }); const result = await openai.chat.completions.create({ model: 'gpt-5.2', messages: [{ role: 'user', content: 'Say hello!' }], }); console.log(result.choices[0]!.message?.content); ### 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: js // 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.2' }, { maxRetries: 5, }); ### Timeouts Requests time out after 10 minutes by default. You can configure this with a timeout option: ts // 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.2' }, { 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 (https://platform.openai.com/docs/api-reference/debugging-requests) 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. ts const response = await client.responses.create({ model: 'gpt-5.2', input: 'testing 123' }); console.log(response._request_id); // req_123 You can also access the Request ID using the .withResponse() method: ts const { data: stream, request_id } = await openai.responses .create({ model: 'gpt-5.2', 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 fetchAllFineTuningJobs(params) { const allFineTuningJobs = []; // Automatically fetches more pages as needed. for await (const fineTuningJob of client.fineTuning.jobs.list({ limit: 20 })) { allFineTuningJobs.push(fineTuningJob); } return allFineTuningJobs; } Alternatively, you can request a single page at a time: ts let page = await client.fineTuning.jobs.list({ limit: 20 }); for (const fineTuningJob of page.data) { console.log(fineTuningJob); } // Convenience methods are provided for manually paginating: while (page.hasNextPage()) { page = await page.getNextPage(); // ... } ## Realtime API The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as function calling (https://platform.openai.com/docs/guides/function-calling) through a WebSocket connection. ts import { OpenAIRealtimeWebSocket } from 'openai/realtime/websocket'; const rt = new OpenAIRealtimeWebSocket({ model: 'gpt-realtime' }); rt.on('response.text.delta', (event) => process.stdout.write(event.delta)); For more information see realtime.md. ## Microsoft Azure OpenAI To use this library with Azure OpenAI (https://learn.microsoft.com/azure/ai-services/openai/overview), use the AzureOpenAI class instead of the OpenAI class. > [!IMPORTANT] > The Azure API shape slightly differs from the core API shape which means that the static types for responses / params > won’t always be correct. ts import { AzureOpenAI } from 'openai'; import { getBearerTokenProvider, DefaultAzureCredential } from '@azure/identity'; const credential = new DefaultAzureCredential(); const scope = 'https://cognitiveservices.azure.com/.default'; const azureADTokenProvider = getBearerTokenProvider(credential, scope);
Similar Articles
openai/openai-node v6.33.0
OpenAI Node.js SDK v6.33.0 release providing TypeScript/JavaScript access to OpenAI APIs with support for the new Responses API and workload identity authentication across Kubernetes, Azure, and GCP.
openai/openai-node v6.36.0
OpenAI released version 6.36.0 of the openai-node library, which provides TypeScript and JavaScript access to the OpenAI REST API and introduces workload identity authentication features for secure cloud environments.
openai/openai-node v6.37.0
This article announces the release of openai-node v6.37.0, an update to the official TypeScript and JavaScript SDK for the OpenAI API, featuring examples of the new Responses API and workload identity authentication.
openai/openai-node v6.35.0
The OpenAI Node.js client library has been updated to version 6.35.0, adding support for workload identity authentication for secure cloud environments.
openai/openai-node v6.38.0
OpenAI's TypeScript and JavaScript API library v6.38.0 now supports workload identity authentication, allowing secure token-based access in cloud environments like Kubernetes, Azure, and GCP.