{"name":"openai","version":"2.0.2","keywords":["openai","open","ai","gpt-3","gpt3"],"author":{"name":"OpenAI"},"license":"MIT","_id":"openai@2.0.2","maintainers":[{"name":"dschnurr","email":"schnurr@gmail.com"},{"name":"jeevnayak","email":"jeev.nayak@gmail.com"},{"name":"knight-oai","email":"knight@openai.com"},{"name":"mario-oai","email":"mario@openai.com"}],"homepage":"https://github.com/openai/openai-node#readme","bugs":{"url":"https://github.com/openai/openai-node/issues"},"dist":{"shasum":"c0508552e06c269ffcb503a2e204a924b17d2e9d","tarball":"http://registry-npm.ywwl.com/openai/download/openai-2.0.2.tgz","fileCount":22,"integrity":"sha512-JyvCwi3/yj8OTm7Qbj3RGj8KpCzOQ+Vq6Sn3MqaqFmhGQxTW0LS98YPLwDqK6MRPVGdbx3++cjXDzQ+kqaB6uA==","signatures":[{"sig":"MEYCIQDMPqO17LyMu3HDbqrkRZl+hfGVXgsRtK4TgztYBmiYKQIhAM4e/mhlgS680qcpB7PqUr5vzzwXBw2e4/IRxeu+HuvK","keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA"}],"unpackedSize":319131,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJh8IymCRA9TVsSAnZWagAAwaQP/2t2VvNSQb8+hw850IMG\nptWD7reJ/poTAa5sgWYcvmikcyda7nn0JEmQA1/QV3qvapQpOZbCSHIqrsRw\nmP0TdgZZjuqxKmXHL7yYxorNmdG2wDQe/pEe1f2tycT8aBvLS+tE1K6NG7Cs\nb6Ma6Qx/efIgrM45Z7JK1evVr4alG4m7oTUdMHYaNx7uSYi/S20Xj3D0hhKX\nFOBNRApSd22PFhJEVyY9VzWuEI8BgywleN8MwDf+A2Ta3HjrlVlqpM1JPgn9\nYyGnnfmglVGuZShAuKIhyVg4f1a4iTm9NEe98OGpwfVzM/Db//NNWoBSE26U\nzvnZUa84V1q65FKpQkmhi6Bgr7RlbhFyXQMQTbQ278K3RO9WlWcpVgGL/w14\nNmu3jSWiQUHnJY5a6AQPEmSxHc67OLRnac7aBmLQos3c8KpGNX/mOzXb+Mgo\nhjBszWsLH4BSKsc9Na0ZCyJPcKA8zm5h5+C495q+Z9RA9fx8grvXg2waMb5U\n+bje6BKFAAV9109MX6TMp/CLiJZ/pppV65cEaWDmf4LlQTGTX7A/gohNxgHX\nYTgDq+toSx+W55kfdmgAoheCUnT4vPayi1+4B+lUVh0FJo+Wrc7+1W1+pCea\nZC6Wp6uIddaaeGUM3SaLKGGeL2OpHrsnIevdtXNDIVhp45JvPIB0SDcaiLf9\nJc+Y\r\n=MdJr\r\n-----END PGP SIGNATURE-----\r\n","size":33923,"noattachment":false,"key":"/openai/-/openai-2.0.2.tgz"},"main":"./dist/index.js","types":"./dist/index.d.ts","gitHead":"95e1f257c76f874bd61fd2059e670144b230fa9d","scripts":{"build":"tsc --outDir dist/"},"_npmUser":{"name":"jeevnayak","email":"jeev.nayak@gmail.com"},"repository":{"url":"git+ssh://git@github.com/openai/openai-node.git","type":"git"},"_npmVersion":"8.1.0","description":"Node.js library for the OpenAI API","directories":{},"_nodeVersion":"16.13.0","dependencies":{"axios":"^0.25.0","form-data":"^4.0.0"},"_hasShrinkwrap":false,"devDependencies":{"typescript":"^3.6.4","@types/node":"^12.11.5"},"_npmOperationalInternal":{"tmp":"tmp/openai_2.0.2_1643154598288_0.6968267335135794","host":"s3://npm-registry-packages"},"readme":"# OpenAI TypeScript and JavaScript API Library\n\n[![NPM version](<https://img.shields.io/npm/v/openai.svg?label=npm%20(stable)>)](https://npmjs.org/package/openai) ![npm bundle size](https://img.shields.io/bundlephobia/minzip/openai)\n\nThis library provides convenient access to the OpenAI REST API from TypeScript or JavaScript.\n\nIt is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi).\n\nTo 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).\n\n## Installation\n\n```sh\nnpm install openai\n```\n\n### Installation with Deno\n\nDeno can import the package directly from npm:\n\n```ts\nimport OpenAI from 'npm:openai';\n```\n\n## Usage\n\nThe full API of this library can be found in [api.md file](api.md) along with many [code examples](https://github.com/openai/openai-node/tree/main/examples).\n\nThe 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.\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted\n});\n\nconst response = await client.responses.create({\n  model: 'gpt-5.5',\n  instructions: 'You are a coding assistant that talks like a pirate',\n  input: 'Are semicolons optional in JavaScript?',\n});\n\nconsole.log(response.output_text);\n```\n\n### Multi-turn conversations\n\nWhen you manage Responses API conversation history manually, preserve output items in order. Filtering\n`response.output` to messages can drop required reasoning or tool-call items and cause the next request to\nfail.\n\nUse the SDK's `toResponseInputItems()` helper to normalize all replayable output items before adding them to\nthe next request. For simple continuation, you can pass `previous_response_id` instead.\n\nSee the [manual conversation state example](examples/responses/manual-conversation-state.ts) and\n[conversation state guide](https://developers.openai.com/api/docs/guides/conversation-state).\n\nThe 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.\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted\n});\n\nconst completion = await client.chat.completions.create({\n  model: 'gpt-5.5',\n  messages: [\n    { role: 'developer', content: 'Talk like a pirate.' },\n    { role: 'user', content: 'Are semicolons optional in JavaScript?' },\n  ],\n});\n\nconsole.log(completion.choices[0].message.content);\n```\n\n## Vision\n\nUse the Responses API to analyze images and generate text about visual content.\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  apiKey: process.env['OPENAI_API_KEY'], // This is the default and can be omitted\n});\n\nconst response = await client.responses.create({\n  model: 'gpt-5.5',\n  input: [\n    {\n      role: 'user',\n      content: [\n        { type: 'input_text', text: 'What is in this image?' },\n        {\n          type: 'input_image',\n          detail: 'auto',\n          image_url:\n            'https://api.nga.gov/iiif/a2e6da57-3cd1-4235-b20e-95dcaefed6c8/full/!800,800/0/default.jpg',\n        },\n      ],\n    },\n  ],\n});\n\nconsole.log(response.output_text);\n```\n\n## Workload Identity Authentication\n\nFor 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.\n\nThe `workloadIdentity` parameter is mutually exclusive with `apiKey`.\n\nFor 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.\n\n### Kubernetes (service account tokens)\n\n```ts\nimport OpenAI from 'openai';\nimport { k8sServiceAccountTokenProvider } from 'openai/auth';\n\nconst client = new OpenAI({\n  workloadIdentity: {\n    identityProviderId: 'idp-123',\n    serviceAccountId: 'sa-456',\n    provider: k8sServiceAccountTokenProvider('/var/run/secrets/kubernetes.io/serviceaccount/token'),\n  },\n});\n\nconst response = await client.chat.completions.create({\n  model: 'gpt-5.5',\n  messages: [{ role: 'user', content: 'Hello!' }],\n});\n```\n\n### Azure (managed identity)\n\n```ts\nimport OpenAI from 'openai';\nimport { azureManagedIdentityTokenProvider } from 'openai/auth';\n\nconst client = new OpenAI({\n  workloadIdentity: {\n    identityProviderId: 'idp-123',\n    serviceAccountId: 'sa-456',\n    provider: azureManagedIdentityTokenProvider(),\n  },\n});\n```\n\n### GCP (compute engine metadata)\n\n```ts\nimport OpenAI from 'openai';\nimport { gcpIDTokenProvider } from 'openai/auth';\n\nconst client = new OpenAI({\n  workloadIdentity: {\n    identityProviderId: 'idp-123',\n    serviceAccountId: 'sa-456',\n    provider: gcpIDTokenProvider(),\n  },\n});\n```\n\n### Custom subject token provider\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  workloadIdentity: {\n    identityProviderId: 'idp-123',\n    serviceAccountId: 'sa-456',\n    provider: {\n      tokenType: 'jwt',\n      getToken: async () => {\n        return 'your-jwt-token';\n      },\n    },\n  },\n});\n```\n\nYou 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):\n\n```ts\nimport OpenAI from 'openai';\nimport { k8sServiceAccountTokenProvider } from 'openai/auth';\n\nconst client = new OpenAI({\n  workloadIdentity: {\n    identityProviderId: 'idp-123',\n    serviceAccountId: 'sa-456',\n    provider: k8sServiceAccountTokenProvider('/var/token'),\n    refreshBufferSeconds: 120.0,\n  },\n});\n```\n\n### X.509 client certificates\n\nApplications 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.\n\n```ts\nimport OpenAI from 'openai';\nimport { workloadIdentity } from 'openai/auth/x509-transport';\n\nconst credential = workloadIdentity.fromX509({\n  certificateChain: process.env['OPENAI_X509_CLIENT_CERTIFICATE_CHAIN_PEM']!,\n  privateKey: process.env['OPENAI_X509_CLIENT_PRIVATE_KEY_PEM']!,\n  identityProviderId: process.env['OPENAI_X509_IDENTITY_PROVIDER_ID']!,\n  serviceAccountId: process.env['OPENAI_X509_SERVICE_ACCOUNT_ID']!,\n});\n\ntry {\n  const client = new OpenAI({\n    credential,\n    project: process.env['OPENAI_X509_PROJECT_ID'] ?? null,\n  });\n\n  console.log((await client.models.list()).data.length);\n} finally {\n  await credential.close();\n}\n```\n\nThe 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](./examples/mtls/README.md#x509-workload-identity-nodejs).\n\n## Streaming responses\n\nWe provide support for streaming responses using Server-Sent Events (SSE).\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI();\n\nconst stream = await client.responses.create({\n  model: 'gpt-5.5',\n  input: 'Say \"Sheep sleep deep\" ten times fast!',\n  stream: true,\n});\n\nfor await (const event of stream) {\n  console.log(event);\n}\n```\n\n## File uploads\n\nRequest parameters that correspond to file uploads can be passed in many different forms:\n\n- `File` (or an object with the same structure)\n- a `fetch` `Response` (or an object with the same structure)\n- an `fs.ReadStream`\n- the return value of our `toFile` or `toStreamingFile` helpers\n\n```ts\nimport fs from 'fs';\nimport OpenAI, { toFile, toStreamingFile } from 'openai';\n\nconst client = new OpenAI();\n\n// If you have access to Node `fs` we recommend using `fs.createReadStream()`:\nawait client.files.create({ file: fs.createReadStream('input.jsonl'), purpose: 'fine-tune' });\n\n// Or if you have the web `File` API you can pass a `File` instance:\nawait client.files.create({ file: new File(['my bytes'], 'input.jsonl'), purpose: 'fine-tune' });\n\n// You can also pass a `fetch` `Response`:\nawait client.files.create({\n  file: await fetch('https://somesite/input.jsonl'),\n  purpose: 'fine-tune',\n});\n\n// Finally, if none of the above are convenient, you can use our `toFile` helper:\nawait client.files.create({\n  file: await toFile(Buffer.from('my bytes'), 'input.jsonl'),\n  purpose: 'fine-tune',\n});\nawait client.files.create({\n  file: await toFile(new Uint8Array([0, 1, 2]), 'input.jsonl'),\n  purpose: 'fine-tune',\n});\n\n// `toFile()` creates a web File, so it must buffer stream inputs before sending them.\n// Use `toStreamingFile()` to stream an arbitrary web, Node, or cloud-storage stream directly:\nawait client.files.create({\n  file: toStreamingFile(myReadableStream, 'input.jsonl', { type: 'application/jsonl' }),\n  purpose: 'fine-tune',\n});\n```\n\n## Webhook Verification\n\nVerifying webhook signatures is _optional but encouraged_.\n\nWebhook verification is asynchronous. Always `await` `unwrap()` or `verifySignature()` before trusting\nthe event.\n\nFor more information about webhooks, see [the API docs](https://platform.openai.com/docs/guides/webhooks).\n\n### Parsing webhook payloads\n\nFor 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.\n\nNote 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.\n\n```ts\nimport { headers } from 'next/headers';\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  webhookSecret: process.env.OPENAI_WEBHOOK_SECRET, // env var used by default; explicit here.\n});\n\nexport async function webhook(request: Request) {\n  const headersList = await headers();\n  const body = await request.text();\n\n  try {\n    const event = await client.webhooks.unwrap(body, headersList);\n\n    switch (event.type) {\n      case 'response.completed':\n        console.log('Response completed:', event.data);\n        break;\n      case 'response.failed':\n        console.log('Response failed:', event.data);\n        break;\n      default:\n        console.log('Unhandled event type:', event.type);\n    }\n\n    return Response.json({ message: 'ok' });\n  } catch (error) {\n    console.error('Invalid webhook signature:', error);\n    return new Response('Invalid signature', { status: 400 });\n  }\n}\n```\n\n### Verifying webhook payloads directly\n\nIn 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.\n\nNote 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.\n\n```ts\nimport { headers } from 'next/headers';\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  webhookSecret: process.env.OPENAI_WEBHOOK_SECRET, // env var used by default; explicit here.\n});\n\nexport async function webhook(request: Request) {\n  const headersList = await headers();\n  const body = await request.text();\n\n  try {\n    await client.webhooks.verifySignature(body, headersList);\n\n    // Parse the body after verification\n    const event = JSON.parse(body);\n    console.log('Verified event:', event);\n\n    return Response.json({ message: 'ok' });\n  } catch (error) {\n    console.error('Invalid webhook signature:', error);\n    return new Response('Invalid signature', { status: 400 });\n  }\n}\n```\n\n## Handling errors\n\nWhen the library is unable to connect to the API,\nor if the API returns a non-success status code (i.e., 4xx or 5xx response),\na subclass of `APIError` will be thrown:\n\n<!-- prettier-ignore -->\n```ts\nconst job = await client.fineTuning.jobs\n  .create({ model: 'gpt-4o', training_file: 'file-abc123' })\n  .catch(async (err) => {\n    if (err instanceof OpenAI.APIError) {\n      console.log(err.requestID);\n      console.log(err.status); // 400\n      console.log(err instanceof OpenAI.BadRequestError); // true for an HTTP 400 response\n      console.log(err.headers); // response Headers\n    } else {\n      throw err;\n    }\n  });\n```\n\nError codes are as follows:\n\n| Status Code | Error Type                 |\n| ----------- | -------------------------- |\n| 400         | `BadRequestError`          |\n| 401         | `AuthenticationError`      |\n| 403         | `PermissionDeniedError`    |\n| 404         | `NotFoundError`            |\n| 409         | `ConflictError`            |\n| 422         | `UnprocessableEntityError` |\n| 429         | `RateLimitError`           |\n| >=500       | `InternalServerError`      |\n| N/A         | `APIConnectionError`       |\n\n### Retries\n\nCertain errors will be automatically retried 2 times by default, with a short exponential backoff.\nConnection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,\n429 Rate Limit, and >=500 Internal errors will all be retried by default.\n\nYou can use the `maxRetries` option to configure or disable this:\n\n<!-- prettier-ignore -->\n```js\n// Configure the default for all requests:\nconst client = new OpenAI({\n  maxRetries: 0, // default is 2\n});\n\n// Or, configure per-request:\nawait client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I get the name of the current day in JavaScript?' }], model: 'gpt-5.5' }, {\n  maxRetries: 5,\n});\n```\n\n### Timeouts\n\nRequests time out after 10 minutes by default. You can configure this with a `timeout` option:\n\n<!-- prettier-ignore -->\n```ts\n// Configure the default for all requests:\nconst client = new OpenAI({\n  timeout: 20 * 1000, // 20 seconds (default is 10 minutes)\n});\n\n// Override per-request:\nawait client.chat.completions.create({ messages: [{ role: 'user', content: 'How can I list all files in a directory using Python?' }], model: 'gpt-5.5' }, {\n  timeout: 5 * 1000,\n});\n```\n\nOn timeout, an `APIConnectionTimeoutError` is thrown.\n\nNote that requests which time out will be [retried twice by default](#retries).\n\n## Request IDs\n\n> For more information on debugging requests, see [these docs](https://platform.openai.com/docs/api-reference/debugging-requests)\n\nAll 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.\n\n```ts\nconst response = await client.responses.create({ model: 'gpt-5.5', input: 'testing 123' });\nconsole.log(response._request_id); // req_123\n```\n\nYou can also access the Request ID using the `.withResponse()` method:\n\n```ts\nconst { data: stream, request_id } = await openai.responses\n  .create({\n    model: 'gpt-5.5',\n    input: 'Say this is a test',\n    stream: true,\n  })\n  .withResponse();\n```\n\n## Auto-pagination\n\nList methods in the OpenAI API are paginated.\nYou can use the `for await … of` syntax to iterate through items across all pages:\n\n```ts\nasync function fetchAllFineTuningJobs(params) {\n  const allFineTuningJobs = [];\n  // Automatically fetches more pages as needed.\n  for await (const fineTuningJob of client.fineTuning.jobs.list({ limit: 20 })) {\n    allFineTuningJobs.push(fineTuningJob);\n  }\n  return allFineTuningJobs;\n}\n```\n\nAlternatively, you can request a single page at a time:\n\n```ts\nlet page = await client.fineTuning.jobs.list({ limit: 20 });\nfor (const fineTuningJob of page.data) {\n  console.log(fineTuningJob);\n}\n\n// Convenience methods are provided for manually paginating:\nwhile (page.hasNextPage()) {\n  page = await page.getNextPage();\n  // ...\n}\n```\n\n## Realtime API\n\nThe 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.\n\n```ts\nimport { OpenAIRealtimeWebSocket } from 'openai/realtime/websocket';\n\nconst rt = new OpenAIRealtimeWebSocket({ model: 'gpt-realtime-2' });\n\nrt.on('response.output_text.delta', (event) => process.stdout.write(event.delta));\n```\n\nFor more information see [docs/realtime.md](docs/realtime.md).\n\n## Microsoft Azure OpenAI\n\nTo use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI`\nclass instead of the `OpenAI` class.\n\n> [!IMPORTANT]\n> The Azure API shape slightly differs from the core API shape which means that the static types for responses / params\n> won't always be correct.\n\n```ts\nimport { AzureOpenAI } from 'openai';\nimport { getBearerTokenProvider, DefaultAzureCredential } from '@azure/identity';\n\nconst credential = new DefaultAzureCredential();\nconst scope = 'https://cognitiveservices.azure.com/.default';\nconst azureADTokenProvider = getBearerTokenProvider(credential, scope);\n\nconst openai = new AzureOpenAI({\n  azureADTokenProvider,\n  apiVersion: '<The API version, e.g. 2024-10-01-preview>',\n});\n\nconst result = await openai.chat.completions.create({\n  model: 'gpt-5.5',\n  messages: [{ role: 'user', content: 'Say hello!' }],\n});\n\nconsole.log(result.choices[0]!.message?.content);\n```\n\nFor more information on support for the Azure API, see [docs/azure.md](docs/azure.md).\n\n## Amazon Bedrock\n\nTo use this library with [Amazon Bedrock's OpenAI-compatible API](https://docs.aws.amazon.com/bedrock/latest/userguide/models-api-compatibility.html), configure the standard `OpenAI` client with the Bedrock provider:\n\n```ts\nimport OpenAI from 'openai';\nimport { bedrock } from 'openai/providers/bedrock/aws';\n\nconst client = new OpenAI({\n  provider: bedrock({ region: 'us-west-2' }),\n});\n\nconst response = await client.responses.create({\n  model: 'openai.gpt-5.4',\n  input: 'Say hello!',\n});\n\nconsole.log(response.output_text);\n```\n\nUse a model that [supports the Responses API](https://docs.aws.amazon.com/bedrock/latest/userguide/models-api-compatibility.html). A model returned by the Models API may support a different Bedrock inference API instead.\n\nThis uses the regional `https://bedrock-mantle.<region>.api.aws/openai/v1` endpoint. The region can also come from `AWS_REGION` or `AWS_DEFAULT_REGION`, and `AWS_BEDROCK_BASE_URL` can override the endpoint.\n\nThe AWS entrypoint uses the standard AWS credential chain by default. It also accepts a named profile, static credentials, or a custom credential provider. Install its peer dependencies before importing it:\n\n```bash\nnpm install @aws-sdk/credential-provider-node @smithy/hash-node @smithy/signature-v4\n```\n\nThe AWS entrypoint uses normal static imports so bundlers and serverless packagers can trace these dependencies. If one is missing, importing `openai/providers/bedrock/aws` fails immediately with the runtime's normal module-not-found error, for example:\n\n```text\nCannot find module '@aws-sdk/credential-provider-node'\n```\n\nFor Bedrock API key authentication, import `bedrock` from `openai/providers/bedrock` instead. That entrypoint has no AWS dependencies and works in browser-compatible runtimes when `dangerouslyAllowBrowser` is enabled. SigV4 authentication is supported in Node.js and compatible server runtimes and requires replayable request bodies. The legacy, bearer-only `BedrockOpenAI` class remains available for compatibility.\n\nFor more information on support for Amazon Bedrock, see [docs/bedrock.md](docs/bedrock.md).\n\n## Advanced Usage\n\n### Accessing raw Response data (e.g., headers)\n\nThe \"raw\" `Response` returned by `fetch()` can be accessed through the `.asResponse()` method on the `APIPromise` type that all methods return.\nThis 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.\n\nYou can also use the `.withResponse()` method to get the raw `Response` along with the parsed data.\nUnlike `.asResponse()` this method consumes the body, returning once it is parsed.\n\n<!-- prettier-ignore -->\n```ts\nconst client = new OpenAI();\n\nconst httpResponse = await client.responses\n  .create({ model: 'gpt-5.5', input: 'say this is a test.' })\n  .asResponse();\n\n// access the underlying web standard Response object\nconsole.log(httpResponse.headers.get('X-My-Header'));\nconsole.log(httpResponse.statusText);\n\nconst { data: modelResponse, response: raw } = await client.responses\n  .create({ model: 'gpt-5.5', input: 'say this is a test.' })\n  .withResponse();\nconsole.log(raw.headers.get('X-My-Header'));\nconsole.log(modelResponse);\n```\n\n### Logging\n\n> [!IMPORTANT]\n> All log messages are intended for debugging only. The format and content of log messages\n> may change between releases.\n\n#### Log levels\n\nThe log level can be configured in two ways:\n\n1. Via the `OPENAI_LOG` environment variable\n2. Using the `logLevel` client option (overrides the environment variable if set)\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  logLevel: 'debug', // Show all log messages\n});\n```\n\nAvailable log levels, from most to least verbose:\n\n- `'debug'` - Show debug messages, info, warnings, and errors\n- `'info'` - Show info messages, warnings, and errors\n- `'warn'` - Show warnings and errors (default)\n- `'error'` - Show only errors\n- `'off'` - Disable all logging\n\nAt the `'debug'` level, all HTTP requests and responses are logged, including headers and bodies.\nSome authentication-related headers are redacted, but sensitive data in request and response bodies\nmay still be visible.\n\n#### Custom logger\n\nBy default, this library logs to `globalThis.console`. You can also provide a custom logger.\nMost logging libraries are supported, including [pino](https://www.npmjs.com/package/pino), [winston](https://www.npmjs.com/package/winston), [bunyan](https://www.npmjs.com/package/bunyan), [consola](https://www.npmjs.com/package/consola), and [signale](https://www.npmjs.com/package/signale). If your logger doesn't work, please open an issue.\n\nWhen providing a custom logger, the `logLevel` option still controls which messages are emitted, messages\nbelow the configured level will not be sent to your logger.\n\n```ts\nimport OpenAI from 'openai';\nimport pino from 'pino';\n\nconst logger = pino();\n\nconst client = new OpenAI({\n  logger: logger.child({ name: 'OpenAI' }),\n  logLevel: 'debug', // Send all messages to pino, allowing it to filter\n});\n```\n\n### Making custom/undocumented requests\n\nThis library is typed for convenient access to the documented API. If you need to access undocumented\nendpoints, params, or response properties, the library can still be used.\n\n#### Undocumented endpoints\n\nTo make requests to undocumented endpoints, you can use `client.get`, `client.post`, and other HTTP verbs.\nOptions on the client, such as retries, will be respected when making these requests.\n\n```ts\nawait client.post('/some/path', {\n  body: { some_prop: 'foo' },\n  query: { some_query_arg: 'bar' },\n});\n```\n\n#### Undocumented request params\n\nTo make requests using undocumented parameters, you may use `// @ts-expect-error` on the undocumented\nparameter. This library doesn't validate at runtime that the request matches the type, so any extra values you\nsend will be sent as-is.\n\n```ts\nclient.chat.completions.create({\n  // ...\n  // @ts-expect-error baz is not yet public\n  baz: 'undocumented option',\n});\n```\n\nFor requests with the `GET` verb, any extra params will be in the query, all other requests will send the\nextra param in the body.\n\nIf you want to explicitly send an extra argument, you can do so with the `query`, `body`, and `headers` request\noptions.\n\n#### Undocumented response properties\n\nTo access undocumented response properties, you may access the response object with `// @ts-expect-error` on\nthe response object, or cast the response object to the requisite type. Like the request params, we do not\nvalidate or strip extra properties from the response from the API.\n\n### Customizing the fetch client\n\nIf you want to use a different `fetch` function, you can either polyfill the global:\n\n```ts\nimport fetch from 'my-fetch';\n\nglobalThis.fetch = fetch;\n```\n\nOr pass it to the client:\n\n```ts\nimport OpenAI from 'openai';\nimport fetch from 'my-fetch';\n\nconst client = new OpenAI({ fetch });\n```\n\n### Fetch options\n\nIf 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.)\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  fetchOptions: {\n    // `RequestInit` options\n  },\n});\n```\n\n#### Configuring proxies\n\nTo modify proxy behavior, you can provide custom `fetchOptions` that add runtime-specific proxy\noptions to requests:\n\n**Node** <sup>[[docs](https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md#example---proxyagent-with-fetch)]</sup>\n\n```ts\nimport OpenAI from 'openai';\nimport { fetch, ProxyAgent } from 'undici';\n\nconst proxyAgent = new ProxyAgent('http://localhost:8888');\nconst client = new OpenAI({\n  fetch,\n  fetchOptions: {\n    dispatcher: proxyAgent,\n  },\n});\n```\n\nUndici-specific options like `dispatcher` must be paired with the matching `fetch` implementation.\n\n**Bun** <sup>[[docs](https://bun.sh/guides/http/proxy)]</sup>\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  fetchOptions: {\n    proxy: 'http://localhost:8888',\n  },\n});\n```\n\n**Deno** <sup>[[docs](https://docs.deno.com/api/deno/~/Deno.createHttpClient)]</sup>\n\n```ts\nimport OpenAI from 'npm:openai';\n\nconst httpClient = Deno.createHttpClient({ proxy: { url: 'http://localhost:8888' } });\nconst client = new OpenAI({\n  fetchOptions: {\n    client: httpClient,\n  },\n});\n```\n\n### Mutual TLS\n\nThe API mTLS beta combines your API key with a client certificate. For enrollment, certificate requirements, activation, and supported endpoints, see the [OpenAI Mutual TLS Beta Program](https://help.openai.com/en/articles/10876024-openai-mutual-tls-beta-program). Configure mTLS on your runtime's HTTP transport, then pass that transport to the SDK with `fetch` and `fetchOptions`. Set `baseURL` to the mTLS endpoint explicitly:\n\n```ts\nimport { readFile } from 'node:fs/promises';\nimport { Agent, fetch as undiciFetch } from 'undici';\nimport OpenAI from 'openai';\n\nconst dispatcher = new Agent({\n  connect: {\n    // One PEM chain: leaf certificate first, then required intermediates.\n    cert: await readFile('/path/to/client-cert-chain.pem'),\n    key: await readFile('/path/to/client-key.pem'),\n  },\n});\n\nconst client = new OpenAI({\n  apiKey: process.env['OPENAI_API_KEY'],\n  baseURL: 'https://mtls.api.openai.com/v1',\n  fetch: undiciFetch,\n  fetchOptions: {\n    dispatcher,\n    redirect: 'manual',\n  },\n});\n```\n\nUse `https://mtls-eu.api.openai.com/v1` for EU Data Residency. The example uses manual redirects so the certificate-bearing transport does not automatically follow a redirect to another host. Close transports your application creates when they are no longer needed.\n\nSee the runnable [Node.js, Deno, and Bun mTLS examples](./examples/mtls/README.md) for certificate-chain setup, optional Node.js encrypted-key support, and runtime-specific transport cleanup.\n\n## Frequently Asked Questions\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:\n\n1. Changes that only affect static types, without breaking runtime behavior.\n2. Changes to library internals which are technically public but not intended or documented for external use. _(Please open a GitHub issue to let us know if you are relying on such internals.)_\n3. Changes that we do not expect to impact the vast majority of users in practice.\n\nWe take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.\n\nWe are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-node/issues) with questions, bugs, or suggestions.\n\n## Requirements\n\nTypeScript >= 4.9 is supported.\n\nThe following runtimes are supported:\n\n- Node.js 22 and 24 LTS. Node.js 22 is the minimum supported version.\n- Deno v1.28.0 or higher.\n- Bun 1.0 or later.\n- Cloudflare Workers.\n- Vercel Edge Runtime.\n- Jest 28 or greater with the `\"node\"` environment (`\"jsdom\"` is not supported at this time).\n- Nitro v2.6 or greater.\n- Web browsers: disabled by default to avoid exposing your secret API credentials. Enable browser support by explicitly setting `dangerouslyAllowBrowser` to `true`.\n  <details>\n    <summary>More explanation</summary>\n\n  ### Why is this dangerous?\n\n  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,\n  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.\n\n  ### When might this not be dangerous?\n\n  In certain scenarios where enabling browser support might not pose significant risks:\n\n  - Internal Tools: If the application is used solely within a controlled internal environment where the users are trusted, the risk of credential exposure can be mitigated.\n  - Public APIs with Limited Scope: If your API has very limited scope and the exposed credentials do not grant access to sensitive data or critical operations, the potential impact of exposure is reduced.\n  - Development or debugging purpose: Enabling this feature temporarily might be acceptable, provided the credentials are short-lived, aren't also used in production environments, or are frequently rotated.\n\n</details>\n\nNote that React Native is not supported at this time.\n\nIf you are interested in other runtime environments, please open or upvote an issue on GitHub.\n\nNode.js 20 reached end of life on April 30, 2026 and is no longer supported.\nPreviously published SDK releases remain available, but receive no guaranteed\nfixes or security backports for unsupported Node.js versions. See the\n[Node.js version support policy](https://github.com/openai/openai-node/blob/main/NODE_VERSION_POLICY.md)\nfor lifecycle, deprecation, and release rules.\n\n## Contributing\n\nSee [the contributing documentation](./.github/CONTRIBUTING.md).\n","publish_time":1643154598460,"_cnpm_publish_time":1643154598460,"dist-tags":{"alpha":"5.0.0-alpha.0","beta":"5.0.0-beta.0","latest":"7.53.0","next":"4.0.0-beta.12"}}