[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"project-10138":3},{"id":4,"name":5,"fullName":6,"owner":7,"repo":5,"description":8,"homepage":9,"htmlUrl":10,"language":11,"languages":10,"totalLinesOfCode":10,"stars":12,"forks":13,"watchers":14,"openIssues":15,"contributorsCount":16,"subscribersCount":16,"size":16,"stars1d":16,"stars7d":17,"stars30d":18,"stars90d":16,"forks30d":16,"starsTrendScore":19,"compositeScore":20,"rankGlobal":10,"rankLanguage":10,"license":21,"archived":22,"fork":22,"defaultBranch":23,"hasWiki":22,"hasPages":22,"topics":24,"createdAt":10,"pushedAt":10,"updatedAt":27,"readmeContent":28,"aiSummary":29,"trendingCount":16,"starSnapshotCount":16,"syncStatus":30,"lastSyncTime":31,"discoverSource":32},10138,"openai-node","openai\u002Fopenai-node","openai","Official JavaScript \u002F TypeScript library for the OpenAI API","https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fopenai",null,"TypeScript",10965,1516,155,126,0,21,70,12,44.54,"Apache License 2.0",false,"master",[25,7,26],"nodejs","typescript","2026-06-12 02:02:17","# OpenAI TypeScript and JavaScript API Library\n\n[![NPM version](\u003Chttps:\u002F\u002Fimg.shields.io\u002Fnpm\u002Fv\u002Fopenai.svg?label=npm%20(stable)>)](https:\u002F\u002Fnpmjs.org\u002Fpackage\u002Fopenai) ![npm bundle size](https:\u002F\u002Fimg.shields.io\u002Fbundlephobia\u002Fminzip\u002Fopenai) [![JSR Version](https:\u002F\u002Fjsr.io\u002Fbadges\u002F@openai\u002Fopenai)](https:\u002F\u002Fjsr.io\u002F@openai\u002Fopenai)\n\nThis library provides convenient access to the OpenAI REST API from TypeScript or JavaScript.\n\nIt is generated from our [OpenAPI specification](https:\u002F\u002Fgithub.com\u002Fopenai\u002Fopenai-openapi) with [Stainless](https:\u002F\u002Fstainlessapi.com\u002F).\n\nTo learn how to use the OpenAI API, check out our [API Reference](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference) and [Documentation](https:\u002F\u002Fplatform.openai.com\u002Fdocs).\n\n## Installation\n\n```sh\nnpm install openai\n```\n\n### Installation from JSR\n\n```sh\ndeno add jsr:@openai\u002Fopenai\nnpx jsr add @openai\u002Fopenai\n```\n\nThese commands will make the module importable from the `@openai\u002Fopenai` scope. You can also [import directly from JSR](https:\u002F\u002Fjsr.io\u002Fdocs\u002Fusing-packages#importing-with-jsr-specifiers) without an install step if you're using the Deno JavaScript runtime:\n\n```ts\nimport OpenAI from 'jsr:@openai\u002Fopenai';\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:\u002F\u002Fgithub.com\u002Fopenai\u002Fopenai-node\u002Ftree\u002Fmaster\u002Fexamples).\n\nThe primary API for interacting with OpenAI models is the [Responses API](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fresponses). 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'], \u002F\u002F This is the default and can be omitted\n});\n\nconst response = await client.responses.create({\n  model: 'gpt-5.2',\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\nThe previous standard (supported indefinitely) for generating text is the [Chat Completions API](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fchat). 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'], \u002F\u002F This is the default and can be omitted\n});\n\nconst completion = await client.chat.completions.create({\n  model: 'gpt-5.2',\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## 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\n### Kubernetes (service account tokens)\n\n```ts\nimport OpenAI from 'openai';\nimport { k8sServiceAccountTokenProvider } from 'openai\u002Fauth';\n\nconst client = new OpenAI({\n  workloadIdentity: {\n    clientId: 'your-client-id',\n    identityProviderId: 'idp-123',\n    serviceAccountId: 'sa-456',\n    provider: k8sServiceAccountTokenProvider('\u002Fvar\u002Frun\u002Fsecrets\u002Fkubernetes.io\u002Fserviceaccount\u002Ftoken'),\n  },\n});\n\nconst response = await client.chat.completions.create({\n  model: 'gpt-4',\n  messages: [{ role: 'user', content: 'Hello!' }],\n});\n```\n\n### Azure (managed identity)\n\n```ts\nimport OpenAI from 'openai';\nimport { azureManagedIdentityTokenProvider } from 'openai\u002Fauth';\n\nconst client = new OpenAI({\n  workloadIdentity: {\n    clientId: 'your-client-id',\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\u002Fauth';\n\nconst client = new OpenAI({\n  workloadIdentity: {\n    clientId: 'your-client-id',\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    clientId: 'your-client-id',\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 token refresh buffer (default is 1200 seconds (20 minutes) before expiration):\n\n```ts\nimport OpenAI from 'openai';\nimport { k8sServiceAccountTokenProvider } from 'openai\u002Fauth';\n\nconst client = new OpenAI({\n  workloadIdentity: {\n    clientId: 'your-client-id',\n    identityProviderId: 'idp-123',\n    serviceAccountId: 'sa-456',\n    provider: k8sServiceAccountTokenProvider('\u002Fvar\u002Ftoken'),\n    refreshBufferSeconds: 120.0,\n  },\n});\n```\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.2',\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` helper\n\n```ts\nimport fs from 'fs';\nimport OpenAI, { toFile } from 'openai';\n\nconst client = new OpenAI();\n\n\u002F\u002F 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\u002F\u002F 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\u002F\u002F You can also pass a `fetch` `Response`:\nawait client.files.create({\n  file: await fetch('https:\u002F\u002Fsomesite\u002Finput.jsonl'),\n  purpose: 'fine-tune',\n});\n\n\u002F\u002F 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\n## Webhook Verification\n\nVerifying webhook signatures is _optional but encouraged_.\n\nFor more information about webhooks, see [the API docs](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Fwebhooks).\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\u002Fheaders';\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  webhookSecret: process.env.OPENAI_WEBHOOK_SECRET, \u002F\u002F env var used by default; explicit here.\n});\n\nexport async function webhook(request: Request) {\n  const headersList = headers();\n  const body = await request.text();\n\n  try {\n    const event = 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\u002Fheaders';\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  webhookSecret: process.env.OPENAI_WEBHOOK_SECRET, \u002F\u002F env var used by default; explicit here.\n});\n\nexport async function webhook(request: Request) {\n  const headersList = headers();\n  const body = await request.text();\n\n  try {\n    client.webhooks.verifySignature(body, headersList);\n\n    \u002F\u002F 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\u003C!-- 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.request_id);\n      console.log(err.status); \u002F\u002F 400\n      console.log(err.name); \u002F\u002F BadRequestError\n      console.log(err.headers); \u002F\u002F {server: 'nginx', ...}\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| 422         | `UnprocessableEntityError` |\n| 429         | `RateLimitError`           |\n| >=500       | `InternalServerError`      |\n| N\u002FA         | `APIConnectionError`       |\n\n## Request IDs\n\n> For more information on debugging requests, see [these docs](https:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fdebugging-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 completion = await client.chat.completions.create({\n  messages: [{ role: 'user', content: 'Say this is a test' }],\n  model: 'gpt-5.2',\n});\nconsole.log(completion._request_id); \u002F\u002F 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.chat.completions\n  .create({\n    model: 'gpt-5.2',\n    messages: [{ role: 'user', content: 'Say this is a test' }],\n    stream: true,\n  })\n  .withResponse();\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:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Ffunction-calling) through a `WebSocket` connection.\n\n```ts\nimport { OpenAIRealtimeWebSocket } from 'openai\u002Frealtime\u002Fwebsocket';\n\nconst rt = new OpenAIRealtimeWebSocket({ model: 'gpt-realtime' });\n\nrt.on('response.text.delta', (event) => process.stdout.write(event.delta));\n```\n\nFor more information see [realtime.md](realtime.md).\n\n## Microsoft Azure OpenAI\n\nTo use this library with [Azure OpenAI](https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fai-services\u002Fopenai\u002Foverview), 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 \u002F params\n> won't always be correct.\n\n```ts\nimport { AzureOpenAI } from 'openai';\nimport { getBearerTokenProvider, DefaultAzureCredential } from '@azure\u002Fidentity';\n\nconst credential = new DefaultAzureCredential();\nconst scope = 'https:\u002F\u002Fcognitiveservices.azure.com\u002F.default';\nconst azureADTokenProvider = getBearerTokenProvider(credential, scope);\n\nconst openai = new AzureOpenAI({ azureADTokenProvider });\n\nconst result = await openai.chat.completions.create({\n  model: 'gpt-5.2',\n  messages: [{ role: 'user', content: 'Say hello!' }],\n});\n\nconsole.log(result.choices[0]!.message?.content);\n```\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\u003C!-- prettier-ignore -->\n```js\n\u002F\u002F Configure the default for all requests:\nconst client = new OpenAI({\n  maxRetries: 0, \u002F\u002F default is 2\n});\n\n\u002F\u002F 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.2' }, {\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\u003C!-- prettier-ignore -->\n```ts\n\u002F\u002F Configure the default for all requests:\nconst client = new OpenAI({\n  timeout: 20 * 1000, \u002F\u002F 20 seconds (default is 10 minutes)\n});\n\n\u002F\u002F 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.2' }, {\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:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fapi-reference\u002Fdebugging-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.2', input: 'testing 123' });\nconsole.log(response._request_id); \u002F\u002F 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.2',\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  \u002F\u002F 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\u002F\u002F Convenience methods are provided for manually paginating:\nwhile (page.hasNextPage()) {\n  page = await page.getNextPage();\n  \u002F\u002F ...\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:\u002F\u002Fplatform.openai.com\u002Fdocs\u002Fguides\u002Ffunction-calling) through a `WebSocket` connection.\n\n```ts\nimport { OpenAIRealtimeWebSocket } from 'openai\u002Frealtime\u002Fwebsocket';\n\nconst rt = new OpenAIRealtimeWebSocket({ model: 'gpt-realtime' });\n\nrt.on('response.text.delta', (event) => process.stdout.write(event.delta));\n```\n\nFor more information see [realtime.md](realtime.md).\n\n## Microsoft Azure OpenAI\n\nTo use this library with [Azure OpenAI](https:\u002F\u002Flearn.microsoft.com\u002Fazure\u002Fai-services\u002Fopenai\u002Foverview), 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 \u002F params\n> won't always be correct.\n\n```ts\nimport { AzureOpenAI } from 'openai';\nimport { getBearerTokenProvider, DefaultAzureCredential } from '@azure\u002Fidentity';\n\nconst credential = new DefaultAzureCredential();\nconst scope = 'https:\u002F\u002Fcognitiveservices.azure.com\u002F.default';\nconst azureADTokenProvider = getBearerTokenProvider(credential, scope);\n\nconst openai = new AzureOpenAI({\n  azureADTokenProvider,\n  apiVersion: '\u003CThe API version, e.g. 2024-10-01-preview>',\n});\n\nconst result = await openai.chat.completions.create({\n  model: 'gpt-5.2',\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 [azure.md](azure.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\u003C!-- prettier-ignore -->\n```ts\nconst client = new OpenAI();\n\nconst httpResponse = await client.responses\n  .create({ model: 'gpt-5.2', input: 'say this is a test.' })\n  .asResponse();\n\n\u002F\u002F 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.2', 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', \u002F\u002F 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:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fpino), [winston](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fwinston), [bunyan](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fbunyan), [consola](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fconsola), [signale](https:\u002F\u002Fwww.npmjs.com\u002Fpackage\u002Fsignale), and [@std\u002Flog](https:\u002F\u002Fjsr.io\u002F@std\u002Flog). 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', \u002F\u002F Send all messages to pino, allowing it to filter\n});\n```\n\n### Making custom\u002Fundocumented 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('\u002Fsome\u002Fpath', {\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 `\u002F\u002F @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  \u002F\u002F ...\n  \u002F\u002F @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 `\u002F\u002F @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    \u002F\u002F `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\u003Cimg src=\"https:\u002F\u002Fraw.githubusercontent.com\u002Fstainless-api\u002Fsdk-assets\u002Frefs\u002Fheads\u002Fmain\u002Fnode.svg\" align=\"top\" width=\"18\" height=\"21\"> **Node** \u003Csup>[[docs](https:\u002F\u002Fgithub.com\u002Fnodejs\u002Fundici\u002Fblob\u002Fmain\u002Fdocs\u002Fdocs\u002Fapi\u002FProxyAgent.md#example---proxyagent-with-fetch)]\u003C\u002Fsup>\n\n```ts\nimport OpenAI from 'openai';\nimport * as undici from 'undici';\n\nconst proxyAgent = new undici.ProxyAgent('http:\u002F\u002Flocalhost:8888');\nconst client = new OpenAI({\n  fetchOptions: {\n    dispatcher: proxyAgent,\n  },\n});\n```\n\n\u003Cimg src=\"https:\u002F\u002Fraw.githubusercontent.com\u002Fstainless-api\u002Fsdk-assets\u002Frefs\u002Fheads\u002Fmain\u002Fbun.svg\" align=\"top\" width=\"18\" height=\"21\"> **Bun** \u003Csup>[[docs](https:\u002F\u002Fbun.sh\u002Fguides\u002Fhttp\u002Fproxy)]\u003C\u002Fsup>\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  fetchOptions: {\n    proxy: 'http:\u002F\u002Flocalhost:8888',\n  },\n});\n```\n\n\u003Cimg src=\"https:\u002F\u002Fraw.githubusercontent.com\u002Fstainless-api\u002Fsdk-assets\u002Frefs\u002Fheads\u002Fmain\u002Fdeno.svg\" align=\"top\" width=\"18\" height=\"21\"> **Deno** \u003Csup>[[docs](https:\u002F\u002Fdocs.deno.com\u002Fapi\u002Fdeno\u002F~\u002FDeno.createHttpClient)]\u003C\u002Fsup>\n\n```ts\nimport OpenAI from 'npm:openai';\n\nconst httpClient = Deno.createHttpClient({ proxy: { url: 'http:\u002F\u002Flocalhost:8888' } });\nconst client = new OpenAI({\n  fetchOptions: {\n    client: httpClient,\n  },\n});\n```\n\n## Frequently Asked Questions\n\n## Semantic versioning\n\nThis package generally follows [SemVer](https:\u002F\u002Fsemver.org\u002Fspec\u002Fv2.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:\u002F\u002Fwww.github.com\u002Fopenai\u002Fopenai-node\u002Fissues) with questions, bugs, or suggestions.\n\n## Requirements\n\nTypeScript >= 4.9 is supported.\n\nThe following runtimes are supported:\n\n- Node.js 20 LTS or later ([non-EOL](https:\u002F\u002Fendoflife.date\u002Fnodejs)) versions.\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  \u003Cdetails>\n    \u003Csummary>More explanation\u003C\u002Fsummary>\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\u003C\u002Fdetails>\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\n## Contributing\n\nSee [the contributing documentation](.\u002FCONTRIBUTING.md).\n","openai-node 是 OpenAI 官方提供的用于访问其 API 的 JavaScript\u002FTypeScript 库。该项目通过 TypeScript 实现，支持 Node.js 环境，提供了一种便捷的方式来调用 OpenAI 的各种服务，包括但不限于文本生成、代码辅助等。它基于 OpenAPI 规范自动生成，并使用了 Stainless 工具以确保高质量的代码实现。此外，该库还支持多种安装方式，如 npm 和 JSR，方便开发者集成到自己的项目中。特别适合需要利用 AI 技术进行自然语言处理或创建智能助手的应用场景。",2,"2026-06-11 03:26:49","top_topic"]