{"id":13432983,"url":"https://github.com/openai/openai-node","last_synced_at":"2026-04-08T23:03:05.516Z","repository":{"id":42698326,"uuid":"438419937","full_name":"openai/openai-node","owner":"openai","description":"Official JavaScript / TypeScript library for the OpenAI API","archived":false,"fork":false,"pushed_at":"2025-05-05T08:34:15.000Z","size":5567,"stargazers_count":9134,"open_issues_count":98,"forks_count":1059,"subscribers_count":134,"default_branch":"master","last_synced_at":"2025-05-05T16:05:59.269Z","etag":null,"topics":["nodejs","openai","typescript"],"latest_commit_sha":null,"homepage":"https://www.npmjs.com/package/openai","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/openai.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2021-12-14T22:32:58.000Z","updated_at":"2025-05-05T13:56:15.000Z","dependencies_parsed_at":"2023-10-16T20:09:40.579Z","dependency_job_id":"1672f332-e749-479c-9d23-d51a80844c68","html_url":"https://github.com/openai/openai-node","commit_stats":{"total_commits":32,"total_committers":6,"mean_commits":5.333333333333333,"dds":0.5625,"last_synced_commit":"0363de20747e272a92e41da4a4c4293104aa9461"},"previous_names":[],"tags_count":252,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2Fopenai-node","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2Fopenai-node/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2Fopenai-node/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/openai%2Fopenai-node/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/openai","download_url":"https://codeload.github.com/openai/openai-node/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253103574,"owners_count":21854693,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["nodejs","openai","typescript"],"created_at":"2024-07-31T02:01:19.363Z","updated_at":"2026-02-24T05:29:59.753Z","avatar_url":"https://github.com/openai.png","language":"TypeScript","readme":"# OpenAI TypeScript and JavaScript API Library\n\n[![NPM version](\u003chttps://img.shields.io/npm/v/openai.svg?label=npm%20(stable)\u003e)](https://npmjs.org/package/openai) ![npm bundle size](https://img.shields.io/bundlephobia/minzip/openai) [![JSR Version](https://jsr.io/badges/@openai/openai)](https://jsr.io/@openai/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) with [Stainless](https://stainlessapi.com/).\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 from JSR\n\n```sh\ndeno add jsr:@openai/openai\nnpx jsr add @openai/openai\n```\n\nThese 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:\n\n```ts\nimport OpenAI from 'jsr:@openai/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/master/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.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://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.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## 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// 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\n## Webhook Verification\n\nVerifying webhook signatures is _optional but encouraged_.\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 = 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/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 = headers();\n  const body = await request.text();\n\n  try {\n    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\u003c!-- prettier-ignore --\u003e\n```ts\nconst job = await client.fineTuning.jobs\n  .create({ model: 'gpt-4o', training_file: 'file-abc123' })\n  .catch(async (err) =\u003e {\n    if (err instanceof OpenAI.APIError) {\n      console.log(err.request_id);\n      console.log(err.status); // 400\n      console.log(err.name); // BadRequestError\n      console.log(err.headers); // {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| \u003e=500       | `InternalServerError`      |\n| N/A         | `APIConnectionError`       |\n\n## Request IDs\n\n\u003e 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 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); // 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://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' });\n\nrt.on('response.text.delta', (event) =\u003e 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://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI`\nclass instead of the `OpenAI` class.\n\n\u003e [!IMPORTANT]\n\u003e The Azure API shape slightly differs from the core API shape which means that the static types for responses / params\n\u003e 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({ 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 \u003e=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 --\u003e\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.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 --\u003e\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.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\u003e 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.2', 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.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  // 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' });\n\nrt.on('response.text.delta', (event) =\u003e 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://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI`\nclass instead of the `OpenAI` class.\n\n\u003e [!IMPORTANT]\n\u003e The Azure API shape slightly differs from the core API shape which means that the static types for responses / params\n\u003e 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: '\u003cThe API version, e.g. 2024-10-01-preview\u003e',\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 --\u003e\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// 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\u003e [!IMPORTANT]\n\u003e All log messages are intended for debugging only. The format and content of log messages\n\u003e 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), [signale](https://www.npmjs.com/package/signale), and [@std/log](https://jsr.io/@std/log). 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\u003cimg src=\"https://raw.githubusercontent.com/stainless-api/sdk-assets/refs/heads/main/node.svg\" align=\"top\" width=\"18\" height=\"21\"\u003e **Node** \u003csup\u003e[[docs](https://github.com/nodejs/undici/blob/main/docs/docs/api/ProxyAgent.md#example---proxyagent-with-fetch)]\u003c/sup\u003e\n\n```ts\nimport OpenAI from 'openai';\nimport * as undici from 'undici';\n\nconst proxyAgent = new undici.ProxyAgent('http://localhost:8888');\nconst client = new OpenAI({\n  fetchOptions: {\n    dispatcher: proxyAgent,\n  },\n});\n```\n\n\u003cimg src=\"https://raw.githubusercontent.com/stainless-api/sdk-assets/refs/heads/main/bun.svg\" align=\"top\" width=\"18\" height=\"21\"\u003e **Bun** \u003csup\u003e[[docs](https://bun.sh/guides/http/proxy)]\u003c/sup\u003e\n\n```ts\nimport OpenAI from 'openai';\n\nconst client = new OpenAI({\n  fetchOptions: {\n    proxy: 'http://localhost:8888',\n  },\n});\n```\n\n\u003cimg src=\"https://raw.githubusercontent.com/stainless-api/sdk-assets/refs/heads/main/deno.svg\" align=\"top\" width=\"18\" height=\"21\"\u003e **Deno** \u003csup\u003e[[docs](https://docs.deno.com/api/deno/~/Deno.createHttpClient)]\u003c/sup\u003e\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## 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 \u003e= 4.9 is supported.\n\nThe following runtimes are supported:\n\n- Node.js 20 LTS or later ([non-EOL](https://endoflife.date/nodejs)) 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\u003e\n    \u003csummary\u003eMore explanation\u003c/summary\u003e\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/details\u003e\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](./CONTRIBUTING.md).\n","funding_links":[],"categories":["TypeScript","SDK","Repository","JavaScript SDKs for general AI APIs","Openai","A01_文本生成_文本对话","Repos","APIs \u0026 SDKs","Libraries \u0026 SDKs"],"sub_categories":["Other","GPT","大语言对话模型及数据","Official SDKs"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenai%2Fopenai-node","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fopenai%2Fopenai-node","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fopenai%2Fopenai-node/lists"}