Gathering detailed insights and metrics for openai
Gathering detailed insights and metrics for openai
Gathering detailed insights and metrics for openai
Gathering detailed insights and metrics for openai
Official JavaScript / TypeScript library for the OpenAI API
npm install openai
Typescript
Module System
99.2
Supply Chain
99.7
Quality
99.6
Maintenance
100
Vulnerability
99.6
License
TypeScript (98.08%)
JavaScript (1.36%)
Shell (0.54%)
HTML (0.02%)
Total Downloads
214,365,509
Last Day
267,377
Last Week
4,265,152
Last Month
17,251,629
Last Year
138,540,957
Apache-2.0 License
9,405 Stars
1,204 Commits
1,136 Forks
140 Watchers
37 Branches
1,991 Contributors
Updated on Jul 01, 2025
Minified
Minified + Gzipped
Latest Version
5.8.2
Package Id
openai@5.8.2
Unpacked Size
5.36 MB
Size
839.69 kB
File Count
1,798
Published on
Jun 27, 2025
Cumulative downloads
Total Downloads
Last Day
3.4%
267,377
Compared to previous day
Last Week
-4.8%
4,265,152
Compared to previous week
Last Month
6.7%
17,251,629
Compared to previous month
Last Year
106.1%
138,540,957
Compared to previous year
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.
1npm install openai
1deno add jsr:@openai/openai 2npx 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:
1import OpenAI from 'jsr:@openai/openai';
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.
1import OpenAI from 'openai'; 2 3const client = new OpenAI({ 4 apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted 5}); 6 7const response = await client.responses.create({ 8 model: 'gpt-4o', 9 instructions: 'You are a coding assistant that talks like a pirate', 10 input: 'Are semicolons optional in JavaScript?', 11}); 12 13console.log(response.output_text);
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.
1import OpenAI from 'openai'; 2 3const client = new OpenAI({ 4 apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted 5}); 6 7const completion = await client.chat.completions.create({ 8 model: 'gpt-4o', 9 messages: [ 10 { role: 'developer', content: 'Talk like a pirate.' }, 11 { role: 'user', content: 'Are semicolons optional in JavaScript?' }, 12 ], 13}); 14 15console.log(completion.choices[0].message.content);
We provide support for streaming responses using Server Sent Events (SSE).
1import OpenAI from 'openai'; 2 3const client = new OpenAI(); 4 5const stream = await client.responses.create({ 6 model: 'gpt-4o', 7 input: 'Say "Sheep sleep deep" ten times fast!', 8 stream: true, 9}); 10 11for await (const event of stream) { 12 console.log(event); 13}
Request parameters that correspond to file uploads can be passed in many different forms:
File
(or an object with the same structure)fetch
Response
(or an object with the same structure)fs.ReadStream
toFile
helper1import fs from 'fs'; 2import OpenAI, { toFile } from 'openai'; 3 4const client = new OpenAI(); 5 6// If you have access to Node `fs` we recommend using `fs.createReadStream()`: 7await client.files.create({ file: fs.createReadStream('input.jsonl'), purpose: 'fine-tune' }); 8 9// Or if you have the web `File` API you can pass a `File` instance: 10await client.files.create({ file: new File(['my bytes'], 'input.jsonl'), purpose: 'fine-tune' }); 11 12// You can also pass a `fetch` `Response`: 13await client.files.create({ file: await fetch('https://somesite/input.jsonl'), purpose: 'fine-tune' }); 14 15// Finally, if none of the above are convenient, you can use our `toFile` helper: 16await client.files.create({ 17 file: await toFile(Buffer.from('my bytes'), 'input.jsonl'), 18 purpose: 'fine-tune', 19}); 20await client.files.create({ 21 file: await toFile(new Uint8Array([0, 1, 2]), 'input.jsonl'), 22 purpose: 'fine-tune', 23});
Verifying webhook signatures is optional but encouraged.
For more information about webhooks, see the API docs.
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.
1import { headers } from 'next/headers'; 2import OpenAI from 'openai'; 3 4const client = new OpenAI({ 5 webhookSecret: process.env.OPENAI_WEBHOOK_SECRET, // env var used by default; explicit here. 6}); 7 8export async function webhook(request: Request) { 9 const headersList = headers(); 10 const body = await request.text(); 11 12 try { 13 const event = client.webhooks.unwrap(body, headersList); 14 15 switch (event.type) { 16 case 'response.completed': 17 console.log('Response completed:', event.data); 18 break; 19 case 'response.failed': 20 console.log('Response failed:', event.data); 21 break; 22 default: 23 console.log('Unhandled event type:', event.type); 24 } 25 26 return Response.json({ message: 'ok' }); 27 } catch (error) { 28 console.error('Invalid webhook signature:', error); 29 return new Response('Invalid signature', { status: 400 }); 30 } 31}
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.
1import { headers } from 'next/headers'; 2import OpenAI from 'openai'; 3 4const client = new OpenAI({ 5 webhookSecret: process.env.OPENAI_WEBHOOK_SECRET, // env var used by default; explicit here. 6}); 7 8export async function webhook(request: Request) { 9 const headersList = headers(); 10 const body = await request.text(); 11 12 try { 13 client.webhooks.verifySignature(body, headersList); 14 15 // Parse the body after verification 16 const event = JSON.parse(body); 17 console.log('Verified event:', event); 18 19 return Response.json({ message: 'ok' }); 20 } catch (error) { 21 console.error('Invalid webhook signature:', error); 22 return new Response('Invalid signature', { status: 400 }); 23 } 24}
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:
1const job = await client.fineTuning.jobs 2 .create({ model: 'gpt-4o', training_file: 'file-abc123' }) 3 .catch(async (err) => { 4 if (err instanceof OpenAI.APIError) { 5 console.log(err.request_id); 6 console.log(err.status); // 400 7 console.log(err.name); // BadRequestError 8 console.log(err.headers); // {server: 'nginx', ...} 9 } else { 10 throw err; 11 } 12 });
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 |
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.
1const completion = await client.chat.completions.create({ 2 messages: [{ role: 'user', content: 'Say this is a test' }], 3 model: 'gpt-4o', 4}); 5console.log(completion._request_id); // req_123
You can also access the Request ID using the .withResponse()
method:
1const { data: stream, request_id } = await openai.chat.completions 2 .create({ 3 model: 'gpt-4', 4 messages: [{ role: 'user', content: 'Say this is a test' }], 5 stream: true, 6 }) 7 .withResponse();
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 through a WebSocket
connection.
1import { OpenAIRealtimeWebSocket } from 'openai/beta/realtime/websocket'; 2 3const rt = new OpenAIRealtimeWebSocket({ model: 'gpt-4o-realtime-preview-2024-12-17' }); 4 5rt.on('response.text.delta', (event) => process.stdout.write(event.delta));
For more information see realtime.md.
To use this library with Azure OpenAI, 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.
1import { AzureOpenAI } from 'openai'; 2import { getBearerTokenProvider, DefaultAzureCredential } from '@azure/identity'; 3 4const credential = new DefaultAzureCredential(); 5const scope = 'https://cognitiveservices.azure.com/.default'; 6const azureADTokenProvider = getBearerTokenProvider(credential, scope); 7 8const openai = new AzureOpenAI({ azureADTokenProvider }); 9 10const result = await openai.chat.completions.create({ 11 model: 'gpt-4o', 12 messages: [{ role: 'user', content: 'Say hello!' }], 13}); 14 15console.log(result.choices[0]!.message?.content);
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:
1// Configure the default for all requests: 2const client = new OpenAI({ 3 maxRetries: 0, // default is 2 4}); 5 6// Or, configure per-request: 7await client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I get the name of the current day in JavaScript?' }], model: 'gpt-4o' }, { 8 maxRetries: 5, 9});
Requests time out after 10 minutes by default. You can configure this with a timeout
option:
1// Configure the default for all requests: 2const client = new OpenAI({ 3 timeout: 20 * 1000, // 20 seconds (default is 10 minutes) 4}); 5 6// Override per-request: 7await client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I list all files in a directory using Python?' }], model: 'gpt-4o' }, { 8 timeout: 5 * 1000, 9});
On timeout, an APIConnectionTimeoutError
is thrown.
Note that requests which time out will be retried twice by default.
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.
1const response = await client.responses.create({ model: 'gpt-4o', input: 'testing 123' }); 2console.log(response._request_id); // req_123
You can also access the Request ID using the .withResponse()
method:
1const { data: stream, request_id } = await openai.responses 2 .create({ 3 model: 'gpt-4o', 4 input: 'Say this is a test', 5 stream: true, 6 }) 7 .withResponse();
List methods in the OpenAI API are paginated.
You can use the for await … of
syntax to iterate through items across all pages:
1async function fetchAllFineTuningJobs(params) { 2 const allFineTuningJobs = []; 3 // Automatically fetches more pages as needed. 4 for await (const fineTuningJob of client.fineTuning.jobs.list({ limit: 20 })) { 5 allFineTuningJobs.push(fineTuningJob); 6 } 7 return allFineTuningJobs; 8}
Alternatively, you can request a single page at a time:
1let page = await client.fineTuning.jobs.list({ limit: 20 }); 2for (const fineTuningJob of page.data) { 3 console.log(fineTuningJob); 4} 5 6// Convenience methods are provided for manually paginating: 7while (page.hasNextPage()) { 8 page = await page.getNextPage(); 9 // ... 10}
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 through a WebSocket
connection.
1import { OpenAIRealtimeWebSocket } from 'openai/beta/realtime/websocket'; 2 3const rt = new OpenAIRealtimeWebSocket({ model: 'gpt-4o-realtime-preview-2024-12-17' }); 4 5rt.on('response.text.delta', (event) => process.stdout.write(event.delta));
For more information see realtime.md.
To use this library with Azure OpenAI, 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.
1import { AzureOpenAI } from 'openai'; 2import { getBearerTokenProvider, DefaultAzureCredential } from '@azure/identity'; 3 4const credential = new DefaultAzureCredential(); 5const scope = 'https://cognitiveservices.azure.com/.default'; 6const azureADTokenProvider = getBearerTokenProvider(credential, scope); 7 8const openai = new AzureOpenAI({ 9 azureADTokenProvider, 10 apiVersion: '<The API version, e.g. 2024-10-01-preview>', 11}); 12 13const result = await openai.chat.completions.create({ 14 model: 'gpt-4o', 15 messages: [{ role: 'user', content: 'Say hello!' }], 16}); 17 18console.log(result.choices[0]!.message?.content);
For more information on support for the Azure API, see azure.md.
The "raw" Response
returned by fetch()
can be accessed through the .asResponse()
method on the APIPromise
type that all methods return.
This method returns as soon as the headers for a successful response are received and does not consume the response body, so you are free to write custom parsing or streaming logic.
You can also use the .withResponse()
method to get the raw Response
along with the parsed data.
Unlike .asResponse()
this method consumes the body, returning once it is parsed.
1const client = new OpenAI(); 2 3const httpResponse = await client.responses 4 .create({ model: 'gpt-4o', input: 'say this is a test.' }) 5 .asResponse(); 6 7// access the underlying web standard Response object 8console.log(httpResponse.headers.get('X-My-Header')); 9console.log(httpResponse.statusText); 10 11const { data: modelResponse, response: raw } = await client.responses 12 .create({ model: 'gpt-4o', input: 'say this is a test.' }) 13 .withResponse(); 14console.log(raw.headers.get('X-My-Header')); 15console.log(modelResponse);
[!IMPORTANT] All log messages are intended for debugging only. The format and content of log messages may change between releases.
The log level can be configured in two ways:
OPENAI_LOG
environment variablelogLevel
client option (overrides the environment variable if set)1import OpenAI from 'openai'; 2 3const client = new OpenAI({ 4 logLevel: 'debug', // Show all log messages 5});
Available log levels, from most to least verbose:
'debug'
- Show debug messages, info, warnings, and errors'info'
- Show info messages, warnings, and errors'warn'
- Show warnings and errors (default)'error'
- Show only errors'off'
- Disable all loggingAt the 'debug'
level, all HTTP requests and responses are logged, including headers and bodies.
Some authentication-related headers are redacted, but sensitive data in request and response bodies
may still be visible.
By default, this library logs to globalThis.console
. You can also provide a custom logger.
Most logging libraries are supported, including pino, winston, bunyan, consola, signale, and @std/log. If your logger doesn't work, please open an issue.
When providing a custom logger, the logLevel
option still controls which messages are emitted, messages
below the configured level will not be sent to your logger.
1import OpenAI from 'openai'; 2import pino from 'pino'; 3 4const logger = pino(); 5 6const client = new OpenAI({ 7 logger: logger.child({ name: 'OpenAI' }), 8 logLevel: 'debug', // Send all messages to pino, allowing it to filter 9});
This library is typed for convenient access to the documented API. If you need to access undocumented endpoints, params, or response properties, the library can still be used.
To make requests to undocumented endpoints, you can use client.get
, client.post
, and other HTTP verbs.
Options on the client, such as retries, will be respected when making these requests.
1await client.post('/some/path', { 2 body: { some_prop: 'foo' }, 3 query: { some_query_arg: 'bar' }, 4});
To make requests using undocumented parameters, you may use // @ts-expect-error
on the undocumented
parameter. This library doesn't validate at runtime that the request matches the type, so any extra values you
send will be sent as-is.
1client.chat.completions.create({ 2 // ... 3 // @ts-expect-error baz is not yet public 4 baz: 'undocumented option', 5});
For requests with the GET
verb, any extra params will be in the query, all other requests will send the
extra param in the body.
If you want to explicitly send an extra argument, you can do so with the query
, body
, and headers
request
options.
To access undocumented response properties, you may access the response object with // @ts-expect-error
on
the response object, or cast the response object to the requisite type. Like the request params, we do not
validate or strip extra properties from the response from the API.
If you want to use a different fetch
function, you can either polyfill the global:
1import fetch from 'my-fetch'; 2 3globalThis.fetch = fetch;
Or pass it to the client:
1import OpenAI from 'openai'; 2import fetch from 'my-fetch'; 3 4const client = new OpenAI({ fetch });
If you want to set custom fetch
options without overriding the fetch
function, you can provide a fetchOptions
object when instantiating the client or making a request. (Request-specific options override client options.)
1import OpenAI from 'openai'; 2 3const client = new OpenAI({ 4 fetchOptions: { 5 // `RequestInit` options 6 }, 7});
To modify proxy behavior, you can provide custom fetchOptions
that add runtime-specific proxy
options to requests:
Node [docs]
1import OpenAI from 'openai'; 2import * as undici from 'undici'; 3 4const proxyAgent = new undici.ProxyAgent('http://localhost:8888'); 5const client = new OpenAI({ 6 fetchOptions: { 7 dispatcher: proxyAgent, 8 }, 9});
Bun [docs]
1import OpenAI from 'openai'; 2 3const client = new OpenAI({ 4 fetchOptions: { 5 proxy: 'http://localhost:8888', 6 }, 7});
Deno [docs]
1import OpenAI from 'npm:openai';
2
3const httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });
4const client = new OpenAI({
5 fetchOptions: {
6 client: httpClient,
7 },
8});
This package generally follows SemVer conventions, though certain backwards-incompatible changes may be released as minor versions:
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
We are keen for your feedback; please open an issue with questions, bugs, or suggestions.
TypeScript >= 4.9 is supported.
The following runtimes are supported:
Node.js 20 LTS or later (non-EOL) versions.
Deno v1.28.0 or higher.
Bun 1.0 or later.
Cloudflare Workers.
Vercel Edge Runtime.
Jest 28 or greater with the "node"
environment ("jsdom"
is not supported at this time).
Nitro v2.6 or greater.
Web browsers: disabled by default to avoid exposing your secret API credentials. Enable browser support by explicitly setting dangerouslyAllowBrowser
to true'.
Enabling the dangerouslyAllowBrowser
option can be dangerous because it exposes your secret API credentials in the client-side code. Web browsers are inherently less secure than server environments,
any user with access to the browser can potentially inspect, extract, and misuse these credentials. This could lead to unauthorized access using your credentials and potentially compromise sensitive data or functionality.
In certain scenarios where enabling browser support might not pose significant risks:
Note that React Native is not supported at this time.
If you are interested in other runtime environments, please open or upvote an issue on GitHub.
No vulnerabilities found.
No security vulnerabilities found.
@langchain/openai
OpenAI integrations for LangChain.js
@azure/openai
A companion library to openai for Azure OpenAI.
@ai-sdk/openai
The **[OpenAI provider](https://ai-sdk.dev/providers/ai-sdk-providers/openai)** for the [AI SDK](https://ai-sdk.dev/docs) contains language model support for the OpenAI chat and completion APIs and embedding model support for the OpenAI embeddings API.
@ai-sdk/openai-compatible
This package provides a foundation for implementing providers that expose an OpenAI-compatible API.