├── .devcontainer └── devcontainer.json ├── .github ├── CODEOWNERS ├── ISSUE_TEMPLATE │ ├── bug_report.yml │ ├── config.yml │ └── feature_request.yml ├── pull_request_template.md └── workflows │ ├── ci.yml │ ├── create-releases.yml │ ├── publish-jsr.yml │ ├── publish-npm.yml │ └── release-doctor.yml ├── .gitignore ├── .prettierignore ├── .prettierrc.json ├── .release-please-manifest.json ├── .stats.yml ├── Brewfile ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── MIGRATION.md ├── README.md ├── SECURITY.md ├── api.md ├── azure.md ├── bin ├── check-release-environment ├── cli ├── migration-config.json ├── publish-jsr └── publish-npm ├── ecosystem-tests ├── browser-direct-import │ ├── .gitignore │ ├── package-lock.json │ ├── package.json │ ├── public │ │ ├── index.html │ │ └── index.js │ ├── src │ │ └── test.ts │ └── tsconfig.json ├── bun │ ├── .gitignore │ ├── README.md │ ├── bun.lockb │ ├── openai.test.ts │ ├── package.json │ ├── sample1.mp3 │ └── tsconfig.json ├── cli.ts ├── cloudflare-worker │ ├── .editorconfig │ ├── .prettierrc │ ├── jest.config.cjs │ ├── package-lock.json │ ├── package.json │ ├── src │ │ ├── uploadWebApiTestCases.ts │ │ └── worker.ts │ ├── tests │ │ └── test.js │ ├── tsconfig.check.json │ ├── tsconfig.json │ └── wrangler.toml ├── deno │ ├── deno.jsonc │ ├── deno.lock │ └── main_test.ts ├── node-js │ ├── package-lock.json │ ├── package.json │ └── test.js ├── node-ts-cjs-auto │ ├── jest.config.cjs │ ├── moduleResolution │ │ ├── node │ │ │ └── type-tests.ts │ │ └── nodenext │ │ │ └── type-tests.ts │ ├── package-lock.json │ ├── package.json │ ├── sample1.mp3 │ ├── tests │ │ └── test.ts │ ├── tsconfig.json │ └── tsconfig.nodenext.json ├── node-ts-cjs-web │ ├── jest.config.cjs │ ├── package-lock.json │ ├── package.json │ ├── sample1.mp3 │ ├── tests │ │ ├── test-jsdom.ts │ │ └── test-node.ts │ ├── tsconfig.json │ ├── tsconfig.nodenext.json │ └── types-test.ts ├── node-ts-cjs │ ├── jest.config.cjs │ ├── package-lock.json │ ├── package.json │ ├── sample1.mp3 │ ├── tests │ │ ├── test-jsdom.ts │ │ └── test-node.ts │ ├── tsconfig.json │ └── tsconfig.nodenext.json ├── node-ts-esm-auto │ ├── esnext-type-tests.ts │ ├── jest.config.cjs │ ├── package-lock.json │ ├── package.json │ ├── sample1.mp3 │ ├── tests │ │ └── test.ts │ └── tsconfig.json ├── node-ts-esm-web │ ├── jest.config.cjs │ ├── package-lock.json │ ├── package.json │ ├── sample1.mp3 │ ├── tests │ │ └── test.ts │ ├── tsconfig.json │ ├── tsconfig.noderesolution.json │ └── types-test.ts ├── node-ts-esm │ ├── iitm.js │ ├── jest.config.cjs │ ├── package-lock.json │ ├── package.json │ ├── sample1.mp3 │ ├── tests │ │ ├── test-esnext.ts │ │ └── test.ts │ ├── tsconfig.json │ └── tsconfig.noderesolution.json ├── node-ts4.5-jest28 │ ├── jest.config.cjs │ ├── package-lock.json │ ├── package.json │ ├── sample1.mp3 │ ├── tests │ │ └── test.ts │ └── tsconfig.json ├── proxy.ts ├── ts-browser-webpack │ ├── .babelrc │ ├── .gitignore │ ├── package-lock.json │ ├── package.json │ ├── public │ │ └── index.html │ ├── src │ │ ├── index.ts │ │ └── test.ts │ ├── tsconfig.json │ └── webpack.config.js └── vercel-edge │ ├── .gitignore │ ├── jest.config.cjs │ ├── next.config.js │ ├── package-lock.json │ ├── package.json │ ├── public │ └── favicon.ico │ ├── src │ ├── pages │ │ ├── _app.tsx │ │ ├── _document.tsx │ │ ├── ai-streaming.tsx │ │ ├── api │ │ │ ├── edge-test.ts │ │ │ ├── node-test.ts │ │ │ ├── query-params.ts │ │ │ ├── response.ts │ │ │ ├── streaming.ts │ │ │ ├── transcribe.ts │ │ │ └── vercel-ai-streaming.ts │ │ └── index.tsx │ └── uploadWebApiTestCases.ts │ ├── tests │ └── test.ts │ └── tsconfig.json ├── eslint.config.mjs ├── examples ├── .gitignore ├── .keep ├── assistant-stream-raw.ts ├── assistant-stream.ts ├── assistants.ts ├── audio.ts ├── azure │ ├── chat.ts │ └── realtime │ │ ├── websocket.ts │ │ └── ws.ts ├── chat-params-types.ts ├── demo.ts ├── errors.ts ├── fine-tuning-data.jsonl ├── fine-tuning.ts ├── function-call-diy.ts ├── function-call-stream-raw.ts ├── function-call-stream.ts ├── function-call.ts ├── logprobs.ts ├── package-lock.json ├── package.json ├── parsing-run-tools.ts ├── parsing-stream.ts ├── parsing-tools-stream.ts ├── parsing-tools.ts ├── parsing.ts ├── raw-response.ts ├── realtime │ ├── websocket.ts │ └── ws.ts ├── responses │ ├── stream.ts │ ├── stream_background.ts │ ├── streaming-tools.ts │ ├── structured-outputs-tools.ts │ └── structured-outputs.ts ├── speech-to-text.ts ├── stream-to-client-browser.ts ├── stream-to-client-express.ts ├── stream-to-client-next.ts ├── stream-to-client-raw.ts ├── stream.ts ├── text-to-speech.ts ├── tool-call-helpers-zod.ts ├── tool-call-helpers.ts ├── tool-calls-stream.ts ├── tsconfig.json ├── types.ts └── ui-generation.ts ├── helpers.md ├── jest.config.ts ├── jsr.json ├── jsr.json.orig ├── package.json ├── realtime.md ├── release-please-config.json ├── scripts ├── bootstrap ├── build ├── build-deno ├── format ├── lint ├── mock ├── test └── utils │ ├── attw-report.cjs │ ├── check-is-in-git-install.sh │ ├── check-version.cjs │ ├── convert-jsr-readme.cjs │ ├── fix-index-exports.cjs │ ├── git-swap.sh │ ├── make-dist-package-json.cjs │ ├── postprocess-files.cjs │ └── upload-artifact.sh ├── src ├── _vendor │ ├── partial-json-parser │ │ ├── README.md │ │ └── parser.ts │ └── zod-to-json-schema │ │ ├── LICENSE │ │ ├── Options.ts │ │ ├── README.md │ │ ├── Refs.ts │ │ ├── errorMessages.ts │ │ ├── index.ts │ │ ├── parseDef.ts │ │ ├── parsers │ │ ├── any.ts │ │ ├── array.ts │ │ ├── bigint.ts │ │ ├── boolean.ts │ │ ├── branded.ts │ │ ├── catch.ts │ │ ├── date.ts │ │ ├── default.ts │ │ ├── effects.ts │ │ ├── enum.ts │ │ ├── intersection.ts │ │ ├── literal.ts │ │ ├── map.ts │ │ ├── nativeEnum.ts │ │ ├── never.ts │ │ ├── null.ts │ │ ├── nullable.ts │ │ ├── number.ts │ │ ├── object.ts │ │ ├── optional.ts │ │ ├── pipeline.ts │ │ ├── promise.ts │ │ ├── readonly.ts │ │ ├── record.ts │ │ ├── set.ts │ │ ├── string.ts │ │ ├── tuple.ts │ │ ├── undefined.ts │ │ ├── union.ts │ │ └── unknown.ts │ │ ├── util.ts │ │ └── zodToJsonSchema.ts ├── api-promise.ts ├── azure.ts ├── beta │ └── realtime │ │ ├── index.ts │ │ ├── internal-base.ts │ │ ├── websocket.ts │ │ └── ws.ts ├── client.ts ├── core │ ├── README.md │ ├── api-promise.ts │ ├── error.ts │ ├── pagination.ts │ ├── resource.ts │ ├── streaming.ts │ └── uploads.ts ├── error.ts ├── helpers │ ├── audio.ts │ └── zod.ts ├── index.ts ├── internal │ ├── README.md │ ├── builtin-types.ts │ ├── decoders │ │ └── line.ts │ ├── detect-platform.ts │ ├── errors.ts │ ├── headers.ts │ ├── parse.ts │ ├── qs │ │ ├── LICENSE.md │ │ ├── README.md │ │ ├── formats.ts │ │ ├── index.ts │ │ ├── stringify.ts │ │ ├── types.ts │ │ └── utils.ts │ ├── request-options.ts │ ├── shim-types.d.ts │ ├── shims.ts │ ├── stream-utils.ts │ ├── to-file.ts │ ├── types.ts │ ├── uploads.ts │ ├── utils.ts │ └── utils │ │ ├── base64.ts │ │ ├── bytes.ts │ │ ├── env.ts │ │ ├── log.ts │ │ ├── path.ts │ │ ├── sleep.ts │ │ ├── uuid.ts │ │ └── values.ts ├── lib │ ├── .keep │ ├── AbstractChatCompletionRunner.ts │ ├── AssistantStream.ts │ ├── ChatCompletionRunner.ts │ ├── ChatCompletionStream.ts │ ├── ChatCompletionStreamingRunner.ts │ ├── EventEmitter.ts │ ├── EventStream.ts │ ├── ResponsesParser.ts │ ├── RunnableFunction.ts │ ├── Util.ts │ ├── chatCompletionUtils.ts │ ├── jsonschema.ts │ ├── parser.ts │ └── responses │ │ ├── EventTypes.ts │ │ └── ResponseStream.ts ├── pagination.ts ├── resource.ts ├── resources.ts ├── resources │ ├── audio.ts │ ├── audio │ │ ├── audio.ts │ │ ├── index.ts │ │ ├── speech.ts │ │ ├── transcriptions.ts │ │ └── translations.ts │ ├── batches.ts │ ├── beta.ts │ ├── beta │ │ ├── assistants.ts │ │ ├── beta.ts │ │ ├── index.ts │ │ ├── realtime.ts │ │ ├── realtime │ │ │ ├── index.ts │ │ │ ├── realtime.ts │ │ │ ├── sessions.ts │ │ │ └── transcription-sessions.ts │ │ ├── threads.ts │ │ └── threads │ │ │ ├── index.ts │ │ │ ├── messages.ts │ │ │ ├── runs.ts │ │ │ ├── runs │ │ │ ├── index.ts │ │ │ ├── runs.ts │ │ │ └── steps.ts │ │ │ └── threads.ts │ ├── chat.ts │ ├── chat │ │ ├── chat.ts │ │ ├── completions.ts │ │ ├── completions │ │ │ ├── completions.ts │ │ │ ├── index.ts │ │ │ └── messages.ts │ │ └── index.ts │ ├── completions.ts │ ├── containers.ts │ ├── containers │ │ ├── containers.ts │ │ ├── files.ts │ │ ├── files │ │ │ ├── content.ts │ │ │ ├── files.ts │ │ │ └── index.ts │ │ └── index.ts │ ├── embeddings.ts │ ├── evals.ts │ ├── evals │ │ ├── evals.ts │ │ ├── index.ts │ │ ├── runs.ts │ │ └── runs │ │ │ ├── index.ts │ │ │ ├── output-items.ts │ │ │ └── runs.ts │ ├── files.ts │ ├── fine-tuning.ts │ ├── fine-tuning │ │ ├── alpha.ts │ │ ├── alpha │ │ │ ├── alpha.ts │ │ │ ├── graders.ts │ │ │ └── index.ts │ │ ├── checkpoints.ts │ │ ├── checkpoints │ │ │ ├── checkpoints.ts │ │ │ ├── index.ts │ │ │ └── permissions.ts │ │ ├── fine-tuning.ts │ │ ├── index.ts │ │ ├── jobs.ts │ │ ├── jobs │ │ │ ├── checkpoints.ts │ │ │ ├── index.ts │ │ │ └── jobs.ts │ │ └── methods.ts │ ├── graders.ts │ ├── graders │ │ ├── grader-models.ts │ │ ├── graders.ts │ │ └── index.ts │ ├── images.ts │ ├── index.ts │ ├── models.ts │ ├── moderations.ts │ ├── responses.ts │ ├── responses │ │ ├── index.ts │ │ ├── input-items.ts │ │ └── responses.ts │ ├── shared.ts │ ├── uploads.ts │ ├── uploads │ │ ├── index.ts │ │ ├── parts.ts │ │ └── uploads.ts │ ├── vector-stores.ts │ └── vector-stores │ │ ├── file-batches.ts │ │ ├── files.ts │ │ ├── index.ts │ │ └── vector-stores.ts ├── streaming.ts ├── uploads.ts └── version.ts ├── tests ├── _vendor │ └── partial-json-parser │ │ └── partial-json-parsing.test.ts ├── api-resources │ ├── audio │ │ ├── speech.test.ts │ │ ├── transcriptions.test.ts │ │ └── translations.test.ts │ ├── batches.test.ts │ ├── beta │ │ ├── assistants.test.ts │ │ ├── realtime │ │ │ ├── sessions.test.ts │ │ │ └── transcription-sessions.test.ts │ │ └── threads │ │ │ ├── messages.test.ts │ │ │ ├── runs │ │ │ ├── runs.test.ts │ │ │ └── steps.test.ts │ │ │ └── threads.test.ts │ ├── chat │ │ └── completions │ │ │ ├── completions.test.ts │ │ │ └── messages.test.ts │ ├── completions.test.ts │ ├── containers │ │ ├── containers.test.ts │ │ └── files │ │ │ ├── content.test.ts │ │ │ └── files.test.ts │ ├── embeddings-base64-response.json │ ├── embeddings-float-response.json │ ├── embeddings.test.ts │ ├── evals │ │ ├── evals.test.ts │ │ └── runs │ │ │ ├── output-items.test.ts │ │ │ └── runs.test.ts │ ├── files.test.ts │ ├── fine-tuning │ │ ├── alpha │ │ │ └── graders.test.ts │ │ ├── checkpoints │ │ │ └── permissions.test.ts │ │ └── jobs │ │ │ ├── checkpoints.test.ts │ │ │ └── jobs.test.ts │ ├── images.test.ts │ ├── models.test.ts │ ├── moderations.test.ts │ ├── responses │ │ ├── input-items.test.ts │ │ └── responses.test.ts │ ├── uploads │ │ ├── parts.test.ts │ │ └── uploads.test.ts │ └── vector-stores │ │ ├── file-batches.test.ts │ │ ├── files.test.ts │ │ └── vector-stores.test.ts ├── base64.test.ts ├── buildHeaders.test.ts ├── form.test.ts ├── helpers │ └── zod.test.ts ├── index.test.ts ├── internal │ └── decoders │ │ └── line.test.ts ├── lib │ ├── ChatCompletionRunFunctions.test.ts │ ├── ChatCompletionStream.test.ts │ ├── __snapshots__ │ │ ├── ChatCompletionStream.test.ts.snap │ │ └── parser.test.ts.snap │ ├── azure.test.ts │ └── parser.test.ts ├── log.test.ts ├── path.test.ts ├── qs │ ├── empty-keys-cases.ts │ ├── stringify.test.ts │ └── utils.test.ts ├── responses.test.ts ├── streaming.test.ts ├── streaming │ └── assistants │ │ └── assistant.test.ts ├── stringifyQuery.test.ts ├── uploads.test.ts └── utils │ ├── mock-fetch.ts │ ├── mock-snapshots.ts │ └── typing.ts ├── tsc-multi.json ├── tsconfig.build.json ├── tsconfig.deno.json ├── tsconfig.dist-src.json ├── tsconfig.json └── yarn.lock /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 2 | // README at: https://github.com/devcontainers/templates/tree/main/src/debian 3 | { 4 | "name": "Development", 5 | "image": "mcr.microsoft.com/devcontainers/typescript-node:latest", 6 | "features": { 7 | "ghcr.io/devcontainers/features/node:1": {} 8 | }, 9 | "postCreateCommand": "yarn install", 10 | "customizations": { 11 | "vscode": { 12 | "extensions": ["esbenp.prettier-vscode"] 13 | } 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | # This file is used to automatically assign reviewers to PRs 2 | # For more information see: https://help.github.com/en/github/creating-cloning-and-archiving-repositories/about-code-owners 3 | 4 | * @openai/sdks-team 5 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/config.yml: -------------------------------------------------------------------------------- 1 | blank_issues_enabled: false 2 | contact_links: 3 | - name: OpenAI support 4 | url: https://help.openai.com/ 5 | about: | 6 | Please only file issues here that you believe represent actual bugs or feature requests for the OpenAI Node library. 7 | If you're having general trouble with the OpenAI API, please visit our help center to get support. 8 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.yml: -------------------------------------------------------------------------------- 1 | name: Feature request 2 | description: Suggest an idea for this library 3 | labels: ['feature-request'] 4 | body: 5 | - type: markdown 6 | attributes: 7 | value: | 8 | Thanks for taking the time to fill out this feature request! 9 | - type: checkboxes 10 | id: non_api 11 | attributes: 12 | label: Confirm this is a feature request for the Node library and not the underlying OpenAI API. 13 | description: Feature requests for the underlying OpenAI API should be reported on our [Developer Community](https://community.openai.com/c/api/7) 14 | options: 15 | - label: This is a feature request for the Node library 16 | required: true 17 | - type: textarea 18 | id: feature 19 | attributes: 20 | label: Describe the feature or improvement you're requesting 21 | description: A clear and concise description of what you want to happen. 22 | validations: 23 | required: true 24 | - type: textarea 25 | id: context 26 | attributes: 27 | label: Additional context 28 | description: Add any other context about the feature request here. 29 | -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | - [ ] I understand that this repository is auto-generated and my pull request may not be merged 7 | 8 | ## Changes being requested 9 | 10 | ## Additional context & links 11 | -------------------------------------------------------------------------------- /.github/workflows/create-releases.yml: -------------------------------------------------------------------------------- 1 | name: Create releases 2 | on: 3 | schedule: 4 | - cron: '0 5 * * *' # every day at 5am UTC 5 | push: 6 | branches: 7 | - master 8 | 9 | jobs: 10 | release: 11 | name: release 12 | if: github.ref == 'refs/heads/master' && github.repository == 'openai/openai-node' 13 | runs-on: ubuntu-latest 14 | environment: publish 15 | permissions: 16 | contents: read 17 | id-token: write 18 | 19 | steps: 20 | - uses: actions/checkout@v4 21 | 22 | - uses: stainless-api/trigger-release-please@v1 23 | id: release 24 | with: 25 | repo: ${{ github.event.repository.full_name }} 26 | stainless-api-key: ${{ secrets.STAINLESS_API_KEY }} 27 | 28 | - name: Set up Node 29 | if: ${{ steps.release.outputs.releases_created }} 30 | uses: actions/setup-node@v3 31 | with: 32 | node-version: '20' 33 | 34 | - name: Install dependencies 35 | if: ${{ steps.release.outputs.releases_created }} 36 | run: | 37 | yarn install 38 | 39 | - name: Publish to NPM 40 | if: ${{ steps.release.outputs.releases_created }} 41 | run: | 42 | bash ./bin/publish-npm 43 | env: 44 | NPM_TOKEN: ${{ secrets.OPENAI_NPM_TOKEN || secrets.NPM_TOKEN }} 45 | 46 | - name: Publish to JSR 47 | if: ${{ steps.release.outputs.releases_created }} 48 | run: | 49 | bash ./bin/publish-jsr 50 | -------------------------------------------------------------------------------- /.github/workflows/publish-jsr.yml: -------------------------------------------------------------------------------- 1 | # workflow for re-running publishing to JSR in case it fails for some reason 2 | # you can run this workflow by navigating to https://www.github.com/openai/openai-node/actions/workflows/publish-jsr.yml 3 | name: Publish JSR 4 | on: 5 | workflow_dispatch: 6 | 7 | jobs: 8 | publish: 9 | name: publish 10 | runs-on: ubuntu-latest 11 | permissions: 12 | contents: read 13 | id-token: write 14 | environment: publish 15 | 16 | steps: 17 | - uses: actions/checkout@v4 18 | 19 | - name: Set up Node 20 | uses: actions/setup-node@v3 21 | with: 22 | node-version: '20' 23 | 24 | - name: Install dependencies 25 | run: | 26 | yarn install 27 | 28 | - name: Publish to JSR 29 | run: | 30 | bash ./bin/publish-jsr 31 | -------------------------------------------------------------------------------- /.github/workflows/publish-npm.yml: -------------------------------------------------------------------------------- 1 | # workflow for re-running publishing to NPM in case it fails for some reason 2 | # you can run this workflow by navigating to https://www.github.com/openai/openai-node/actions/workflows/publish-npm.yml 3 | name: Publish NPM 4 | on: 5 | workflow_dispatch: 6 | 7 | jobs: 8 | publish: 9 | name: publish 10 | runs-on: ubuntu-latest 11 | environment: publish 12 | 13 | steps: 14 | - uses: actions/checkout@v4 15 | 16 | - name: Set up Node 17 | uses: actions/setup-node@v3 18 | with: 19 | node-version: '20' 20 | 21 | - name: Install dependencies 22 | run: | 23 | yarn install 24 | 25 | - name: Publish to NPM 26 | run: | 27 | bash ./bin/publish-npm 28 | env: 29 | NPM_TOKEN: ${{ secrets.OPENAI_NPM_TOKEN || secrets.NPM_TOKEN }} 30 | -------------------------------------------------------------------------------- /.github/workflows/release-doctor.yml: -------------------------------------------------------------------------------- 1 | name: Release Doctor 2 | on: 3 | push: 4 | branches: 5 | - master 6 | workflow_dispatch: 7 | 8 | jobs: 9 | release_doctor: 10 | name: release doctor 11 | runs-on: ubuntu-latest 12 | environment: publish 13 | if: github.repository == 'openai/openai-node' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch' || startsWith(github.head_ref, 'release-please') || github.head_ref == 'next') 14 | 15 | steps: 16 | - uses: actions/checkout@v4 17 | 18 | - name: Check release environment 19 | run: | 20 | bash ./bin/check-release-environment 21 | env: 22 | STAINLESS_API_KEY: ${{ secrets.STAINLESS_API_KEY }} 23 | NPM_TOKEN: ${{ secrets.OPENAI_NPM_TOKEN || secrets.NPM_TOKEN }} 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .prism.log 2 | node_modules 3 | yarn-error.log 4 | codegen.log 5 | Brewfile.lock.json 6 | dist 7 | dist-deno 8 | /*.tgz 9 | .idea/ 10 | tmp 11 | .pack 12 | ecosystem-tests/deno/package.json 13 | ecosystem-tests/*/openai.tgz 14 | .dev.vars 15 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | CHANGELOG.md 2 | /ecosystem-tests/*/** 3 | /node_modules 4 | /deno 5 | 6 | # don't format tsc output, will break source maps 7 | /dist 8 | -------------------------------------------------------------------------------- /.prettierrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "experimentalTernaries": true, 4 | "printWidth": 110, 5 | "singleQuote": true, 6 | "trailingComma": "all" 7 | } 8 | -------------------------------------------------------------------------------- /.release-please-manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | ".": "5.0.1" 3 | } 4 | -------------------------------------------------------------------------------- /.stats.yml: -------------------------------------------------------------------------------- 1 | configured_endpoints: 111 2 | openapi_spec_url: https://storage.googleapis.com/stainless-sdk-openapi-specs/openai%2Fopenai-d4bcffecf0cdadf746faa6708ed1ec81fac451f9b857deabbab26f0a343b9314.yml 3 | openapi_spec_hash: 7c54a18b4381248bda7cc34c52142615 4 | config_hash: e618aa8ff61aea826540916336de65a6 5 | -------------------------------------------------------------------------------- /Brewfile: -------------------------------------------------------------------------------- 1 | brew "node" 2 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Reporting Security Issues 4 | 5 | This SDK is generated by [Stainless Software Inc](http://stainless.com). Stainless takes security seriously, and encourages you to report any security vulnerability promptly so that appropriate action can be taken. 6 | 7 | To report a security issue, please contact the Stainless team at security@stainless.com. 8 | 9 | ## Responsible Disclosure 10 | 11 | We appreciate the efforts of security researchers and individuals who help us maintain the security of 12 | SDKs we generate. If you believe you have found a security vulnerability, please adhere to responsible 13 | disclosure practices by allowing us a reasonable amount of time to investigate and address the issue 14 | before making any information public. 15 | 16 | ## Reporting Non-SDK Related Security Issues 17 | 18 | If you encounter security issues that are not directly related to SDKs but pertain to the services 19 | or products provided by OpenAI, please follow the respective company's security reporting guidelines. 20 | 21 | ### OpenAI Terms and Policies 22 | 23 | Our Security Policy can be found at [Security Policy URL](https://openai.com/policies/coordinated-vulnerability-disclosure-policy). 24 | 25 | Please contact disclosure@openai.com for any questions or concerns regarding the security of our services. 26 | 27 | --- 28 | 29 | Thank you for helping us keep the SDKs and systems they interact with secure. 30 | -------------------------------------------------------------------------------- /bin/check-release-environment: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | errors=() 4 | 5 | if [ -z "${STAINLESS_API_KEY}" ]; then 6 | errors+=("The STAINLESS_API_KEY secret has not been set. Please contact Stainless for an API key & set it in your organization secrets on GitHub.") 7 | fi 8 | 9 | if [ -z "${NPM_TOKEN}" ]; then 10 | errors+=("The OPENAI_NPM_TOKEN secret has not been set. Please set it in either this repository's secrets or your organization secrets") 11 | fi 12 | 13 | lenErrors=${#errors[@]} 14 | 15 | if [[ lenErrors -gt 0 ]]; then 16 | echo -e "Found the following errors in the release environment:\n" 17 | 18 | for error in "${errors[@]}"; do 19 | echo -e "- $error\n" 20 | done 21 | 22 | exit 1 23 | fi 24 | 25 | echo "The environment is ready to push releases!" 26 | 27 | -------------------------------------------------------------------------------- /bin/cli: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | const { spawnSync } = require('child_process'); 4 | 5 | const commands = { 6 | migrate: { 7 | description: 'Run migrations to update to the latest major SDK version', 8 | fn: () => { 9 | const result = spawnSync( 10 | 'npx', 11 | [ 12 | '-y', 13 | 'https://github.com/stainless-api/migrate-ts/releases/download/0.0.3/stainless-api-migrate-0.0.3.tgz', 14 | '--migrationConfig', 15 | require.resolve('./migration-config.json'), 16 | ...process.argv.slice(3), 17 | ], 18 | { stdio: 'inherit' }, 19 | ); 20 | if (result.status !== 0) { 21 | process.exit(result.status); 22 | } 23 | }, 24 | }, 25 | }; 26 | 27 | function exitWithHelp() { 28 | console.log(`Usage: openai `); 29 | console.log(); 30 | console.log('Subcommands:'); 31 | 32 | for (const [name, info] of Object.entries(commands)) { 33 | console.log(` ${name} ${info.description}`); 34 | } 35 | 36 | console.log(); 37 | process.exit(1); 38 | } 39 | 40 | if (process.argv.length < 3) { 41 | exitWithHelp(); 42 | } 43 | 44 | const commandName = process.argv[2]; 45 | 46 | const command = commands[commandName]; 47 | if (!command) { 48 | console.log(`Unknown subcommand ${commandName}.`); 49 | exitWithHelp(); 50 | } 51 | 52 | command.fn(); 53 | -------------------------------------------------------------------------------- /bin/publish-jsr: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -eux 4 | 5 | # Build the project 6 | yarn build 7 | 8 | # Navigate to the dist directory 9 | cd dist-deno 10 | 11 | npx jsr publish ${JSR_TOKEN:+"--token=$JSR_TOKEN"} 12 | -------------------------------------------------------------------------------- /bin/publish-npm: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -eux 4 | 5 | npm config set '//registry.npmjs.org/:_authToken' "$NPM_TOKEN" 6 | 7 | yarn build 8 | cd dist 9 | 10 | # Get latest version from npm 11 | # 12 | # If the package doesn't exist, yarn will return 13 | # {"type":"error","data":"Received invalid response from npm."} 14 | # where .data.version doesn't exist so LAST_VERSION will be an empty string. 15 | LAST_VERSION="$(yarn info --json 2> /dev/null | jq -r '.data.version')" 16 | 17 | # Get current version from package.json 18 | VERSION="$(node -p "require('./package.json').version")" 19 | 20 | # Check if current version is pre-release (e.g. alpha / beta / rc) 21 | CURRENT_IS_PRERELEASE=false 22 | if [[ "$VERSION" =~ -([a-zA-Z]+) ]]; then 23 | CURRENT_IS_PRERELEASE=true 24 | CURRENT_TAG="${BASH_REMATCH[1]}" 25 | fi 26 | 27 | # Check if last version is a stable release 28 | LAST_IS_STABLE_RELEASE=true 29 | if [[ -z "$LAST_VERSION" || "$LAST_VERSION" =~ -([a-zA-Z]+) ]]; then 30 | LAST_IS_STABLE_RELEASE=false 31 | fi 32 | 33 | # Use a corresponding alpha/beta tag if there already is a stable release and we're publishing a prerelease. 34 | if $CURRENT_IS_PRERELEASE && $LAST_IS_STABLE_RELEASE; then 35 | TAG="$CURRENT_TAG" 36 | else 37 | TAG="latest" 38 | fi 39 | 40 | # Publish with the appropriate tag 41 | yarn publish --access public --tag "$TAG" 42 | -------------------------------------------------------------------------------- /ecosystem-tests/browser-direct-import/.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /dist 3 | -------------------------------------------------------------------------------- /ecosystem-tests/browser-direct-import/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "browser-direct-import", 3 | "version": "0.0.1", 4 | "private": true, 5 | "scripts": { 6 | "tsc": "tsc --noEmit", 7 | "test": "ts-node src/test.ts", 8 | "test:ci": "start-server-and-test serve http://localhost:8081 test", 9 | "serve": "sirv -q public --port 8081" 10 | }, 11 | "devDependencies": { 12 | "fastest-levenshtein": "^1.0.16", 13 | "puppeteer": "^23.4.0", 14 | "sirv-cli": "^3.0.0", 15 | "start-server-and-test": "^2.0.0", 16 | "ts-node": "^10.9.1", 17 | "typescript": "^4.7.4" 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ecosystem-tests/browser-direct-import/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Package in the Browser 6 | 7 | 8 |
Running tests...
9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /ecosystem-tests/browser-direct-import/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "strict": true, 5 | "noImplicitReturns": true, 6 | "removeComments": true, 7 | "preserveConstEnums": true, 8 | "sourceMap": true, 9 | "declaration": true, 10 | "skipLibCheck": false, 11 | "target": "es2015", 12 | "lib": ["es2017", "dom"], 13 | "outDir": "dist", 14 | "rootDir": "./", 15 | "baseUrl": ".", 16 | "paths": { 17 | "*": ["types/*"] 18 | } 19 | }, 20 | "include": ["src/**/*", "public/index.js"], 21 | "exclude": ["node_modules/*"] 22 | } 23 | -------------------------------------------------------------------------------- /ecosystem-tests/bun/README.md: -------------------------------------------------------------------------------- 1 | # openai-bun-test 2 | 3 | To install dependencies: 4 | 5 | ```bash 6 | bun install 7 | ``` 8 | 9 | To run: 10 | 11 | ```bash 12 | bun run index.ts 13 | ``` 14 | -------------------------------------------------------------------------------- /ecosystem-tests/bun/bun.lockb: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openai/openai-node/eebb832c8433696976375e7f1446070f2dc4d91a/ecosystem-tests/bun/bun.lockb -------------------------------------------------------------------------------- /ecosystem-tests/bun/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "openai-bun-test", 3 | "module": "index.ts", 4 | "type": "module", 5 | "engines": { 6 | "bun": ">=1.0.0" 7 | }, 8 | "scripts": { 9 | "tsc": "tsc" 10 | }, 11 | "devDependencies": { 12 | "fastest-levenshtein": "^1.0.16", 13 | "bun-types": "^1.2.14", 14 | "typescript": "5.8.3" 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /ecosystem-tests/bun/sample1.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openai/openai-node/eebb832c8433696976375e7f1446070f2dc4d91a/ecosystem-tests/bun/sample1.mp3 -------------------------------------------------------------------------------- /ecosystem-tests/bun/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["*.ts"], 3 | "compilerOptions": { 4 | "lib": ["ESNext"], 5 | "module": "esnext", 6 | "target": "esnext", 7 | "moduleResolution": "bundler", 8 | "moduleDetection": "force", 9 | "allowImportingTsExtensions": true, 10 | "strict": true, 11 | "downlevelIteration": true, 12 | "skipLibCheck": false, 13 | "jsx": "preserve", 14 | "allowSyntheticDefaultImports": true, 15 | "forceConsistentCasingInFileNames": true, 16 | "allowJs": true, 17 | "noEmit": true, 18 | "types": [ 19 | "bun-types" // add Bun global 20 | ] 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ecosystem-tests/cloudflare-worker/.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | indent_style = tab 6 | tab_width = 2 7 | end_of_line = lf 8 | charset = utf-8 9 | trim_trailing_whitespace = true 10 | insert_final_newline = true 11 | 12 | [*.yml] 13 | indent_style = space 14 | -------------------------------------------------------------------------------- /ecosystem-tests/cloudflare-worker/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 140, 3 | "singleQuote": true, 4 | "semi": true, 5 | "useTabs": true 6 | } 7 | -------------------------------------------------------------------------------- /ecosystem-tests/cloudflare-worker/jest.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | transform: {}, 4 | testEnvironment: 'node', 5 | testMatch: ['/tests/*.js'], 6 | watchPathIgnorePatterns: ['/node_modules/'], 7 | verbose: false, 8 | testTimeout: 60000, 9 | }; 10 | -------------------------------------------------------------------------------- /ecosystem-tests/cloudflare-worker/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "cfw", 3 | "version": "0.0.0", 4 | "private": true, 5 | "type": "module", 6 | "scripts": { 7 | "tsc": "tsc && tsc -p tsconfig.check.json", 8 | "deploy": "wrangler publish", 9 | "start": "wrangler dev", 10 | "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", 11 | "test:ci": "start-server-and-test start http://localhost:8787 test" 12 | }, 13 | "devDependencies": { 14 | "@cloudflare/workers-types": "^4.20250525.0", 15 | "fastest-levenshtein": "^1.0.16", 16 | "jest": "^29.5.0", 17 | "start-server-and-test": "^2.0.0", 18 | "ts-jest": "^29.1.0", 19 | "typescript": "5.8.3", 20 | "wrangler": "^3.74.0" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ecosystem-tests/cloudflare-worker/tests/test.js: -------------------------------------------------------------------------------- 1 | it( 2 | 'works', 3 | async () => { 4 | expect(await (await fetch('http://localhost:8787/test')).text()).toEqual('Passed!'); 5 | }, 6 | 3 * 60000 7 | ); 8 | -------------------------------------------------------------------------------- /ecosystem-tests/cloudflare-worker/tsconfig.check.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["src"], 4 | "exclude": ["tests", "jest.config.cjs"], 5 | "compilerOptions": { 6 | "skipLibCheck": true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /ecosystem-tests/cloudflare-worker/wrangler.toml: -------------------------------------------------------------------------------- 1 | name = "cfw" 2 | main = "src/worker.ts" 3 | compatibility_date = "2023-06-18" 4 | #node_compat = true 5 | 6 | # # KV Namespace binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/kv 7 | # [[kv_namespaces]] 8 | # binding = "MY_KV_NAMESPACE" 9 | # id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" 10 | 11 | # # Durable Object binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/durable-objects 12 | # [[durable_objects]] 13 | # binding = "MY_DURABLE_OBJECT" 14 | # class_name = "MyDurableObject" 15 | 16 | # # Bucket binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/kv#bucket 17 | # [[buckets]] 18 | # binding = "MY_BUCKET" 19 | # name = "my-bucket" 20 | # bucket_id = "yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy" 21 | 22 | # # Service binding - For more information: https://developers.cloudflare.com/workers/platform/services 23 | # [[routes]] 24 | # binding = "MY_SERVICE" 25 | # pattern = "/api/*" 26 | # script = "api.js" 27 | 28 | # # Queue binding - For more information: https://developers.cloudflare.com/workers/runtime-apis/queues 29 | # [[queues]] 30 | # binding = "MY_QUEUE" 31 | # name = "my-queue" 32 | # zone_id = "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz" 33 | 34 | # [env.production] 35 | # MY_VARIABLE = "production_value" 36 | 37 | # [env.staging] 38 | # MY_VARIABLE = "staging_value" 39 | 40 | # [env.shared] 41 | # SHARED_VARIABLE = "shared_value" 42 | 43 | [vars] 44 | -------------------------------------------------------------------------------- /ecosystem-tests/deno/deno.jsonc: -------------------------------------------------------------------------------- 1 | { 2 | "tasks": { 3 | "install": "deno install --node-modules-dir main_test.ts -f", 4 | "check": "deno lint && deno check main_test.ts", 5 | "test": "deno test --allow-env --allow-net --allow-read --node-modules-dir" 6 | }, 7 | "imports": { 8 | "openai": "../../deno/mod.ts", 9 | "openai/": "../../deno/" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /ecosystem-tests/node-js/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-js", 3 | "version": "1.0.0", 4 | "lockfileVersion": 3, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "node-js", 9 | "version": "1.0.0", 10 | "license": "ISC" 11 | } 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ecosystem-tests/node-js/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-js", 3 | "version": "1.0.0", 4 | "description": "", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "author": "", 10 | "license": "ISC" 11 | } 12 | -------------------------------------------------------------------------------- /ecosystem-tests/node-js/test.js: -------------------------------------------------------------------------------- 1 | const openaiKey = "a valid OpenAI key" 2 | const OpenAI = require('openai'); 3 | 4 | console.log(OpenAI) 5 | 6 | const openai = new OpenAI({ 7 | apiKey: openaiKey, 8 | }); 9 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-auto/jest.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | preset: 'ts-jest', 4 | testEnvironment: 'node', 5 | testMatch: ['/tests/*.ts'], 6 | watchPathIgnorePatterns: ['/node_modules/'], 7 | verbose: false, 8 | testTimeout: 60000, 9 | }; 10 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-auto/moduleResolution/node/type-tests.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | 3 | const client = new OpenAI(); 4 | 5 | async function typeTests() { 6 | const response = await client.audio.transcriptions 7 | .create({ 8 | file: 'test' as any, 9 | model: 'whisper-1', 10 | }) 11 | .asResponse(); 12 | response.body; 13 | } 14 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-auto/moduleResolution/nodenext/type-tests.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | 3 | async function typeTests(client: OpenAI) { 4 | const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [] }).asResponse(); 5 | const url: string = response.url; 6 | } 7 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-auto/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-ts-cjs-auto", 3 | "version": "0.0.1", 4 | "main": "index.js", 5 | "private": true, 6 | "scripts": { 7 | "tsc": "tsc && tsc -p tsconfig.nodenext.json", 8 | "test": "jest" 9 | }, 10 | "dependencies": { 11 | "formdata-node": "^4.4.1", 12 | "tsconfig-paths": "^4.0.0" 13 | }, 14 | "devDependencies": { 15 | "@types/node": "^20.4.2", 16 | "@types/ws": "^8.5.4", 17 | "fastest-levenshtein": "^1.0.16", 18 | "jest": "^28.1.3", 19 | "ts-jest": "^28.0.8", 20 | "typescript": "4.7.4" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-auto/sample1.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openai/openai-node/eebb832c8433696976375e7f1446070f2dc4d91a/ecosystem-tests/node-ts-cjs-auto/sample1.mp3 -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-auto/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*", "moduleResolution/node/*"], 3 | 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Projects */ 7 | "incremental": true, 8 | 9 | /* Language and Environment */ 10 | "target": "ES2015", 11 | "lib": ["ES2015"], 12 | "jsx": "react", 13 | 14 | /* Modules */ 15 | "module": "commonjs", 16 | "rootDir": "./", 17 | "moduleResolution": "node", 18 | "baseUrl": "./", 19 | "paths": { 20 | "~/*": ["*"] 21 | }, 22 | "resolveJsonModule": true, 23 | "composite": true, 24 | 25 | /* Emit */ 26 | "outDir": "node_modules", 27 | "noEmit": true, 28 | 29 | /* Interop Constraints */ 30 | "isolatedModules": true, 31 | "allowSyntheticDefaultImports": true, 32 | /* "esModuleInterop": true, */ 33 | "forceConsistentCasingInFileNames": true, 34 | "allowJs": true, 35 | "checkJs": true, 36 | 37 | /* Experimental Features */ 38 | "experimentalDecorators": true, 39 | 40 | /* Type Checking */ 41 | "strict": true, 42 | "noImplicitAny": true, 43 | "strictNullChecks": true, 44 | "strictFunctionTypes": true, 45 | "strictBindCallApply": true, 46 | "strictPropertyInitialization": true, 47 | "noImplicitThis": true, 48 | "alwaysStrict": true, 49 | "noUncheckedIndexedAccess": true, 50 | "noImplicitOverride": true, 51 | "noPropertyAccessFromIndexSignature": true, 52 | "skipLibCheck": false 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-auto/tsconfig.nodenext.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*", "moduleResolution/nodenext/*"], 3 | 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Projects */ 7 | "incremental": true, 8 | 9 | /* Language and Environment */ 10 | "target": "ES2015", 11 | "lib": ["ES2015"], 12 | "jsx": "react", 13 | 14 | /* Modules */ 15 | "module": "commonjs", 16 | "rootDir": "./", 17 | "moduleResolution": "NodeNext", 18 | "baseUrl": "./", 19 | "paths": { 20 | "~/*": ["*"] 21 | }, 22 | "resolveJsonModule": true, 23 | "composite": true, 24 | 25 | /* Emit */ 26 | "outDir": "node_modules", 27 | "noEmit": true, 28 | 29 | /* Interop Constraints */ 30 | "isolatedModules": true, 31 | "allowSyntheticDefaultImports": true, 32 | /* "esModuleInterop": true, */ 33 | "forceConsistentCasingInFileNames": true, 34 | "allowJs": true, 35 | "checkJs": true, 36 | 37 | /* Experimental Features */ 38 | "experimentalDecorators": true, 39 | 40 | /* Type Checking */ 41 | "strict": true, 42 | "noImplicitAny": true, 43 | "strictNullChecks": true, 44 | "strictFunctionTypes": true, 45 | "strictBindCallApply": true, 46 | "strictPropertyInitialization": true, 47 | "noImplicitThis": true, 48 | "alwaysStrict": true, 49 | "noUncheckedIndexedAccess": true, 50 | "noImplicitOverride": true, 51 | "noPropertyAccessFromIndexSignature": true, 52 | "skipLibCheck": false 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-web/jest.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | preset: 'ts-jest', 4 | testEnvironment: 'node', 5 | testMatch: ['/tests/*.ts'], 6 | watchPathIgnorePatterns: ['/node_modules/'], 7 | verbose: false, 8 | testTimeout: 60000, 9 | }; 10 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-web/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-ts-cjs-web", 3 | "version": "0.0.1", 4 | "main": "index.js", 5 | "private": true, 6 | "scripts": { 7 | "tsc": "tsc && tsc -p tsconfig.nodenext.json", 8 | "test": "jest" 9 | }, 10 | "dependencies": { 11 | "formdata-node": "^4.4.1", 12 | "tsconfig-paths": "^4.0.0" 13 | }, 14 | "devDependencies": { 15 | "jest-fixed-jsdom": "^0.0.9", 16 | "@types/node": "^18.0.0", 17 | "fastest-levenshtein": "^1.0.16", 18 | "jest": "^29.5.0", 19 | "ts-jest": "^29.1.0", 20 | "typescript": "4.7.4" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-web/sample1.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openai/openai-node/eebb832c8433696976375e7f1446070f2dc4d91a/ecosystem-tests/node-ts-cjs-web/sample1.mp3 -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-web/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts"], 3 | 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Projects */ 7 | "incremental": true, 8 | 9 | /* Language and Environment */ 10 | "target": "ES2022", 11 | "lib": ["ES2022", "DOM"], 12 | "jsx": "react", 13 | 14 | /* Modules */ 15 | "module": "commonjs", 16 | "rootDir": "./", 17 | "moduleResolution": "node", 18 | "baseUrl": "./", 19 | "paths": { 20 | "~/*": ["*"] 21 | }, 22 | "resolveJsonModule": true, 23 | "composite": true, 24 | 25 | /* Emit */ 26 | "outDir": "node_modules", 27 | "noEmit": true, 28 | 29 | /* Interop Constraints */ 30 | "isolatedModules": true, 31 | "allowSyntheticDefaultImports": true, 32 | /* "esModuleInterop": true, */ 33 | "forceConsistentCasingInFileNames": true, 34 | "allowJs": true, 35 | "checkJs": true, 36 | 37 | /* Experimental Features */ 38 | "experimentalDecorators": true, 39 | 40 | /* Type Checking */ 41 | "strict": true, 42 | "noImplicitAny": true, 43 | "strictNullChecks": true, 44 | "strictFunctionTypes": true, 45 | "strictBindCallApply": true, 46 | "strictPropertyInitialization": true, 47 | "noImplicitThis": true, 48 | "alwaysStrict": true, 49 | "noUncheckedIndexedAccess": true, 50 | "noImplicitOverride": true, 51 | "noPropertyAccessFromIndexSignature": true, 52 | "skipLibCheck": true 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-web/tsconfig.nodenext.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts"], 3 | 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Projects */ 7 | "incremental": true, 8 | 9 | /* Language and Environment */ 10 | "target": "ES2022", 11 | "lib": ["ES2022", "DOM"], 12 | "jsx": "react", 13 | 14 | /* Modules */ 15 | "module": "commonjs", 16 | "rootDir": "./", 17 | "moduleResolution": "NodeNext", 18 | "baseUrl": "./", 19 | "paths": { 20 | "~/*": ["*"] 21 | }, 22 | "resolveJsonModule": true, 23 | "composite": true, 24 | 25 | /* Emit */ 26 | "outDir": "node_modules", 27 | "noEmit": true, 28 | 29 | /* Interop Constraints */ 30 | "isolatedModules": true, 31 | "allowSyntheticDefaultImports": true, 32 | /* "esModuleInterop": true, */ 33 | "forceConsistentCasingInFileNames": true, 34 | "allowJs": true, 35 | "checkJs": true, 36 | 37 | /* Experimental Features */ 38 | "experimentalDecorators": true, 39 | 40 | /* Type Checking */ 41 | "strict": true, 42 | "noImplicitAny": true, 43 | "strictNullChecks": true, 44 | "strictFunctionTypes": true, 45 | "strictBindCallApply": true, 46 | "strictPropertyInitialization": true, 47 | "noImplicitThis": true, 48 | "alwaysStrict": true, 49 | "noUncheckedIndexedAccess": true, 50 | "noImplicitOverride": true, 51 | "noPropertyAccessFromIndexSignature": true, 52 | "skipLibCheck": true 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs-web/types-test.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | 3 | async function typeTests(client: OpenAI) { 4 | const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [] }).asResponse(); 5 | const url: string = response.url; 6 | } 7 | 8 | export {}; 9 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs/jest.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | preset: 'ts-jest', 4 | testEnvironment: 'node', 5 | testMatch: ['/tests/*.ts'], 6 | watchPathIgnorePatterns: ['/node_modules/'], 7 | verbose: false, 8 | testTimeout: 60000, 9 | }; 10 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-ts-cjs", 3 | "version": "0.0.1", 4 | "main": "index.js", 5 | "private": true, 6 | "scripts": { 7 | "tsc": "tsc && tsc -p tsconfig.nodenext.json", 8 | "test": "jest" 9 | }, 10 | "dependencies": { 11 | "formdata-node": "^4.4.1", 12 | "tsconfig-paths": "^4.0.0", 13 | "typescript": "^5.7.3", 14 | "undici": "^7.2.0" 15 | }, 16 | "devDependencies": { 17 | "@types/node": "^20.14.8", 18 | "@types/ws": "^8.5.4", 19 | "fastest-levenshtein": "^1.0.16", 20 | "jest": "^29.5.0", 21 | "jest-fixed-jsdom": "^0.0.9", 22 | "ts-jest": "^29.1.0" 23 | }, 24 | "type": "commonjs" 25 | } 26 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs/sample1.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openai/openai-node/eebb832c8433696976375e7f1446070f2dc4d91a/ecosystem-tests/node-ts-cjs/sample1.mp3 -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts"], 3 | "exclude": ["tests/*-shim-errors.ts"], 4 | 5 | "compilerOptions": { 6 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 7 | /* Projects */ 8 | "incremental": true, 9 | 10 | /* Language and Environment */ 11 | "target": "ES2015", 12 | "lib": ["ES2015", "DOM.AsyncIterable"], 13 | "jsx": "react", 14 | 15 | /* Modules */ 16 | "module": "commonjs", 17 | "rootDir": "./", 18 | "moduleResolution": "node", 19 | "baseUrl": "./", 20 | "paths": { 21 | "~/*": ["*"] 22 | }, 23 | "resolveJsonModule": true, 24 | "composite": true, 25 | 26 | /* Emit */ 27 | "outDir": "node_modules", 28 | "noEmit": true, 29 | 30 | /* Interop Constraints */ 31 | "isolatedModules": true, 32 | "allowSyntheticDefaultImports": true, 33 | /* "esModuleInterop": true, */ 34 | "forceConsistentCasingInFileNames": true, 35 | "allowJs": true, 36 | "checkJs": true, 37 | 38 | /* Experimental Features */ 39 | "experimentalDecorators": true, 40 | 41 | /* Type Checking */ 42 | "strict": true, 43 | "noImplicitAny": true, 44 | "strictNullChecks": true, 45 | "strictFunctionTypes": true, 46 | "strictBindCallApply": true, 47 | "strictPropertyInitialization": true, 48 | "noImplicitThis": true, 49 | "alwaysStrict": true, 50 | "noUncheckedIndexedAccess": true, 51 | "noImplicitOverride": true, 52 | "noPropertyAccessFromIndexSignature": true, 53 | "skipLibCheck": false 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-cjs/tsconfig.nodenext.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts"], 3 | "exclude": ["tests/*-shim-errors.ts"], 4 | 5 | "compilerOptions": { 6 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 7 | /* Projects */ 8 | "incremental": true, 9 | 10 | /* Language and Environment */ 11 | "target": "ES2015", 12 | "lib": ["ES2015", "DOM.AsyncIterable"], 13 | "jsx": "react", 14 | 15 | /* Modules */ 16 | "module": "NodeNext", 17 | "rootDir": "./", 18 | "moduleResolution": "NodeNext", 19 | "baseUrl": "./", 20 | "paths": { 21 | "~/*": ["*"] 22 | }, 23 | "resolveJsonModule": true, 24 | "composite": true, 25 | 26 | /* Emit */ 27 | "outDir": "node_modules", 28 | "noEmit": true, 29 | 30 | /* Interop Constraints */ 31 | "isolatedModules": true, 32 | "allowSyntheticDefaultImports": true, 33 | /* "esModuleInterop": true, */ 34 | "forceConsistentCasingInFileNames": true, 35 | "allowJs": true, 36 | "checkJs": true, 37 | 38 | /* Experimental Features */ 39 | "experimentalDecorators": true, 40 | 41 | /* Type Checking */ 42 | "strict": true, 43 | "noImplicitAny": true, 44 | "strictNullChecks": true, 45 | "strictFunctionTypes": true, 46 | "strictBindCallApply": true, 47 | "strictPropertyInitialization": true, 48 | "noImplicitThis": true, 49 | "alwaysStrict": true, 50 | "noUncheckedIndexedAccess": true, 51 | "noImplicitOverride": true, 52 | "noPropertyAccessFromIndexSignature": true, 53 | "skipLibCheck": false 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-auto/esnext-type-tests.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | 3 | async function typeTests(client: OpenAI) { 4 | const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [] }).asResponse(); 5 | const url: string = response.url; 6 | } 7 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-auto/jest.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | extensionsToTreatAsEsm: ['.ts'], 4 | moduleNameMapper: { 5 | '^(\\.{1,2}/.*)\\.js$': '$1', 6 | }, 7 | transform: { 8 | // '^.+\\.[tj]sx?$' to process js/ts with `ts-jest` 9 | // '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest` 10 | '^.+\\.tsx?$': [ 11 | 'ts-jest', 12 | { 13 | useESM: true, 14 | diagnostics: false, 15 | }, 16 | ], 17 | }, 18 | testEnvironment: 'node', 19 | testMatch: ['/tests/*.ts'], 20 | watchPathIgnorePatterns: ['/node_modules/'], 21 | verbose: false, 22 | testTimeout: 60000, 23 | }; 24 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-auto/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-ts-esm-auto", 3 | "version": "0.0.1", 4 | "main": "index.js", 5 | "type": "module", 6 | "private": true, 7 | "scripts": { 8 | "tsc": "tsc", 9 | "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" 10 | }, 11 | "dependencies": { 12 | "formdata-node": "^5.0.1" 13 | }, 14 | "devDependencies": { 15 | "@types/node": "^20.3.1", 16 | "fastest-levenshtein": "^1.0.16", 17 | "jest": "^29.5.0", 18 | "ts-jest": "^29.1.0", 19 | "ts-node": "^10.9.1", 20 | "typescript": "4.7.4" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-auto/sample1.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openai/openai-node/eebb832c8433696976375e7f1446070f2dc4d91a/ecosystem-tests/node-ts-esm-auto/sample1.mp3 -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-auto/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts", "*.ts"], 3 | 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Projects */ 7 | "incremental": true, 8 | 9 | /* Language and Environment */ 10 | "target": "ES2022", 11 | "lib": ["ES2022"], 12 | "jsx": "react", 13 | 14 | /* Modules */ 15 | "module": "ESNext", 16 | "rootDir": "./", 17 | "moduleResolution": "NodeNext", 18 | "baseUrl": "./", 19 | "paths": { 20 | "~/*": ["*"] 21 | }, 22 | "resolveJsonModule": true, 23 | "composite": true, 24 | 25 | /* Emit */ 26 | "outDir": "node_modules", 27 | "noEmit": true, 28 | 29 | /* Interop Constraints */ 30 | "isolatedModules": true, 31 | "allowSyntheticDefaultImports": true, 32 | /* "esModuleInterop": true, */ 33 | "forceConsistentCasingInFileNames": true, 34 | "allowJs": true, 35 | "checkJs": true, 36 | 37 | /* Experimental Features */ 38 | "experimentalDecorators": true, 39 | 40 | /* Type Checking */ 41 | "strict": true, 42 | "noImplicitAny": true, 43 | "strictNullChecks": true, 44 | "strictFunctionTypes": true, 45 | "strictBindCallApply": true, 46 | "strictPropertyInitialization": true, 47 | "noImplicitThis": true, 48 | "alwaysStrict": true, 49 | "noUncheckedIndexedAccess": true, 50 | "noImplicitOverride": true, 51 | "noPropertyAccessFromIndexSignature": true, 52 | "skipLibCheck": true 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-web/jest.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | extensionsToTreatAsEsm: ['.ts'], 4 | moduleNameMapper: { 5 | '^(\\.{1,2}/.*)\\.js$': '$1', 6 | }, 7 | transform: { 8 | // '^.+\\.[tj]sx?$' to process js/ts with `ts-jest` 9 | // '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest` 10 | '^.+\\.tsx?$': [ 11 | 'ts-jest', 12 | { 13 | useESM: true, 14 | diagnostics: false, 15 | }, 16 | ], 17 | }, 18 | testEnvironment: 'node', 19 | testMatch: ['/tests/*.ts'], 20 | watchPathIgnorePatterns: ['/node_modules/'], 21 | verbose: false, 22 | testTimeout: 60000, 23 | }; 24 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-web/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-ts-esm-web", 3 | "version": "0.0.1", 4 | "main": "index.js", 5 | "type": "module", 6 | "private": true, 7 | "scripts": { 8 | "tsc": "tsc && tsc -p tsconfig.noderesolution.json", 9 | "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js" 10 | }, 11 | "dependencies": { 12 | "formdata-node": "^5.0.1" 13 | }, 14 | "devDependencies": { 15 | "@types/node": "^20.3.1", 16 | "fastest-levenshtein": "^1.0.16", 17 | "jest": "^29.5.0", 18 | "ts-jest": "^29.1.0", 19 | "ts-node": "^10.9.1", 20 | "typescript": "4.7.4" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-web/sample1.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openai/openai-node/eebb832c8433696976375e7f1446070f2dc4d91a/ecosystem-tests/node-ts-esm-web/sample1.mp3 -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-web/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts"], 3 | 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Projects */ 7 | "incremental": true, 8 | 9 | /* Language and Environment */ 10 | "target": "ES2022", 11 | "lib": ["ES2022", "DOM"], 12 | "jsx": "react", 13 | 14 | /* Modules */ 15 | "module": "ESNext", 16 | "rootDir": "./", 17 | "moduleResolution": "NodeNext", 18 | "baseUrl": "./", 19 | "paths": { 20 | "~/*": ["*"] 21 | }, 22 | "resolveJsonModule": true, 23 | "composite": true, 24 | 25 | /* Emit */ 26 | "outDir": "node_modules", 27 | "noEmit": true, 28 | 29 | /* Interop Constraints */ 30 | "isolatedModules": true, 31 | "allowSyntheticDefaultImports": true, 32 | /* "esModuleInterop": true, */ 33 | "forceConsistentCasingInFileNames": true, 34 | "allowJs": true, 35 | "checkJs": true, 36 | 37 | /* Experimental Features */ 38 | "experimentalDecorators": true, 39 | 40 | /* Type Checking */ 41 | "strict": true, 42 | "noImplicitAny": true, 43 | "strictNullChecks": true, 44 | "strictFunctionTypes": true, 45 | "strictBindCallApply": true, 46 | "strictPropertyInitialization": true, 47 | "noImplicitThis": true, 48 | "alwaysStrict": true, 49 | "noUncheckedIndexedAccess": true, 50 | "noImplicitOverride": true, 51 | "noPropertyAccessFromIndexSignature": true, 52 | "skipLibCheck": true 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-web/tsconfig.noderesolution.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts"], 3 | 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Projects */ 7 | "incremental": true, 8 | 9 | /* Language and Environment */ 10 | "target": "ES2022", 11 | "lib": ["ES2022", "DOM"], 12 | "jsx": "react", 13 | 14 | /* Modules */ 15 | "module": "ESNext", 16 | "rootDir": "./", 17 | "moduleResolution": "node", 18 | "baseUrl": "./", 19 | "paths": { 20 | "~/*": ["*"] 21 | }, 22 | "resolveJsonModule": true, 23 | "composite": true, 24 | 25 | /* Emit */ 26 | "outDir": "node_modules", 27 | "noEmit": true, 28 | 29 | /* Interop Constraints */ 30 | "isolatedModules": true, 31 | "allowSyntheticDefaultImports": true, 32 | /* "esModuleInterop": true, */ 33 | "forceConsistentCasingInFileNames": true, 34 | "allowJs": true, 35 | "checkJs": true, 36 | 37 | /* Experimental Features */ 38 | "experimentalDecorators": true, 39 | 40 | /* Type Checking */ 41 | "strict": true, 42 | "noImplicitAny": true, 43 | "strictNullChecks": true, 44 | "strictFunctionTypes": true, 45 | "strictBindCallApply": true, 46 | "strictPropertyInitialization": true, 47 | "noImplicitThis": true, 48 | "alwaysStrict": true, 49 | "noUncheckedIndexedAccess": true, 50 | "noImplicitOverride": true, 51 | "noPropertyAccessFromIndexSignature": true, 52 | "skipLibCheck": true 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm-web/types-test.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | 3 | async function typeTests(client: OpenAI) { 4 | const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [] }).asResponse(); 5 | const url: string = response.url; 6 | } 7 | 8 | export {}; 9 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm/iitm.js: -------------------------------------------------------------------------------- 1 | import {register} from 'node:module' 2 | register('import-in-the-middle/hook.mjs', import.meta.url) -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm/jest.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | extensionsToTreatAsEsm: ['.ts'], 4 | moduleNameMapper: { 5 | '^(\\.{1,2}/.*)\\.js$': '$1', 6 | }, 7 | transform: { 8 | // '^.+\\.[tj]sx?$' to process js/ts with `ts-jest` 9 | // '^.+\\.m?[tj]sx?$' to process js/ts/mjs/mts with `ts-jest` 10 | '^.+\\.tsx?$': [ 11 | 'ts-jest', 12 | { 13 | useESM: true, 14 | diagnostics: false, 15 | }, 16 | ], 17 | }, 18 | testEnvironment: 'node', 19 | testMatch: ['/tests/*.ts'], 20 | watchPathIgnorePatterns: ['/node_modules/'], 21 | verbose: false, 22 | testTimeout: 60000, 23 | }; 24 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-ts-esm", 3 | "version": "0.0.1", 4 | "main": "index.js", 5 | "type": "module", 6 | "private": true, 7 | "scripts": { 8 | "tsc": "tsc && tsc -p tsconfig.noderesolution.json", 9 | "test": "node --import=./iitm.js --experimental-vm-modules node_modules/jest/bin/jest.js" 10 | }, 11 | "dependencies": { 12 | "formdata-node": "^5.0.1", 13 | "import-in-the-middle": "^1.11.2" 14 | }, 15 | "devDependencies": { 16 | "@types/node": "^20.3.1", 17 | "fastest-levenshtein": "^1.0.16", 18 | "jest": "^29.5.0", 19 | "ts-jest": "^29.1.0", 20 | "ts-node": "^10.9.1", 21 | "typescript": "4.7.4" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm/sample1.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openai/openai-node/eebb832c8433696976375e7f1446070f2dc4d91a/ecosystem-tests/node-ts-esm/sample1.mp3 -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts"], 3 | 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Projects */ 7 | "incremental": true, 8 | 9 | /* Language and Environment */ 10 | "target": "ES2022", 11 | "lib": ["ES2022"], 12 | "jsx": "react", 13 | 14 | /* Modules */ 15 | "module": "ESNext", 16 | "rootDir": "./", 17 | "moduleResolution": "NodeNext", 18 | "baseUrl": "./", 19 | "paths": { 20 | "~/*": ["*"] 21 | }, 22 | "resolveJsonModule": true, 23 | "composite": true, 24 | 25 | /* Emit */ 26 | "outDir": "node_modules", 27 | "noEmit": true, 28 | 29 | /* Interop Constraints */ 30 | "isolatedModules": true, 31 | "allowSyntheticDefaultImports": true, 32 | /* "esModuleInterop": true, */ 33 | "forceConsistentCasingInFileNames": true, 34 | "allowJs": true, 35 | "checkJs": true, 36 | 37 | /* Experimental Features */ 38 | "experimentalDecorators": true, 39 | 40 | /* Type Checking */ 41 | "strict": true, 42 | "noImplicitAny": true, 43 | "strictNullChecks": true, 44 | "strictFunctionTypes": true, 45 | "strictBindCallApply": true, 46 | "strictPropertyInitialization": true, 47 | "noImplicitThis": true, 48 | "alwaysStrict": true, 49 | "noUncheckedIndexedAccess": true, 50 | "noImplicitOverride": true, 51 | "noPropertyAccessFromIndexSignature": true, 52 | "skipLibCheck": true 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts-esm/tsconfig.noderesolution.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts"], 3 | "exclude": ["tests/*-esnext.ts"], 4 | 5 | "compilerOptions": { 6 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 7 | /* Projects */ 8 | "incremental": true, 9 | 10 | /* Language and Environment */ 11 | "target": "ES2022", 12 | "lib": ["ES2022"], 13 | "jsx": "react", 14 | 15 | /* Modules */ 16 | "module": "ESNext", 17 | "rootDir": "./", 18 | "moduleResolution": "node", 19 | "baseUrl": "./", 20 | "paths": { 21 | "~/*": ["*"] 22 | }, 23 | "resolveJsonModule": true, 24 | "composite": true, 25 | 26 | /* Emit */ 27 | "outDir": "node_modules", 28 | "noEmit": true, 29 | 30 | /* Interop Constraints */ 31 | "isolatedModules": true, 32 | "allowSyntheticDefaultImports": true, 33 | /* "esModuleInterop": true, */ 34 | "forceConsistentCasingInFileNames": true, 35 | "allowJs": true, 36 | "checkJs": true, 37 | 38 | /* Experimental Features */ 39 | "experimentalDecorators": true, 40 | 41 | /* Type Checking */ 42 | "strict": true, 43 | "noImplicitAny": true, 44 | "strictNullChecks": true, 45 | "strictFunctionTypes": true, 46 | "strictBindCallApply": true, 47 | "strictPropertyInitialization": true, 48 | "noImplicitThis": true, 49 | "alwaysStrict": true, 50 | "noUncheckedIndexedAccess": true, 51 | "noImplicitOverride": true, 52 | "noPropertyAccessFromIndexSignature": true, 53 | "skipLibCheck": true 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts4.5-jest28/jest.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | preset: 'ts-jest', 4 | testEnvironment: 'node', 5 | testMatch: ['/tests/*.ts'], 6 | watchPathIgnorePatterns: ['/node_modules/'], 7 | verbose: false, 8 | testTimeout: 60000, 9 | }; 10 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts4.5-jest28/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "node-ts4.5-jest27", 3 | "version": "0.0.1", 4 | "main": "index.js", 5 | "private": true, 6 | "scripts": { 7 | "tsc": "tsc", 8 | "test": "jest" 9 | }, 10 | "dependencies": { 11 | "formdata-node": "^4.4.1", 12 | "tsconfig-paths": "^4.0.0" 13 | }, 14 | "devDependencies": { 15 | "@types/node": "20.11.20", 16 | "@types/jest": "27.5.2", 17 | "@types/ws": "^8.5.4", 18 | "fastest-levenshtein": "^1.0.16", 19 | "jest": "28.1.3", 20 | "ts-jest": "^28.0.0", 21 | "typescript": "4.5.5" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ecosystem-tests/node-ts4.5-jest28/sample1.mp3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/openai/openai-node/eebb832c8433696976375e7f1446070f2dc4d91a/ecosystem-tests/node-ts4.5-jest28/sample1.mp3 -------------------------------------------------------------------------------- /ecosystem-tests/node-ts4.5-jest28/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["tests/*.ts"], 3 | 4 | "compilerOptions": { 5 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 6 | /* Projects */ 7 | "incremental": true, 8 | 9 | /* Language and Environment */ 10 | "target": "ES2015", 11 | "lib": ["ES2015"], 12 | "jsx": "react", 13 | 14 | /* Modules */ 15 | "module": "commonjs", 16 | "rootDir": "./", 17 | "moduleResolution": "node", 18 | "baseUrl": "./", 19 | "paths": { 20 | "~/*": ["*"] 21 | }, 22 | "resolveJsonModule": true, 23 | "composite": true, 24 | 25 | /* Emit */ 26 | "outDir": "node_modules", 27 | "noEmit": true, 28 | 29 | /* Interop Constraints */ 30 | "isolatedModules": true, 31 | "allowSyntheticDefaultImports": true, 32 | /* "esModuleInterop": true, */ 33 | "forceConsistentCasingInFileNames": true, 34 | "allowJs": true, 35 | "checkJs": true, 36 | 37 | /* Experimental Features */ 38 | "experimentalDecorators": true, 39 | 40 | /* Type Checking */ 41 | "strict": true, 42 | "noImplicitAny": true, 43 | "strictNullChecks": true, 44 | "strictFunctionTypes": true, 45 | "strictBindCallApply": true, 46 | "strictPropertyInitialization": true, 47 | "noImplicitThis": true, 48 | "alwaysStrict": true, 49 | "noUncheckedIndexedAccess": true, 50 | "noImplicitOverride": true, 51 | "noPropertyAccessFromIndexSignature": true, 52 | "skipLibCheck": false 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /ecosystem-tests/proxy.ts: -------------------------------------------------------------------------------- 1 | import { createServer } from 'http'; 2 | import { connect } from 'net'; 3 | 4 | async function startProxy() { 5 | const proxy = createServer((_req, res) => { 6 | res.end(); 7 | }); 8 | 9 | proxy.on('connect', (req, clientSocket, head) => { 10 | const serverSocket = connect(443, 'api.openai.com', () => { 11 | clientSocket.write( 12 | 'HTTP/1.1 200 Connection Established\r\n' + 'Proxy-agent: Node.js-Proxy\r\n' + '\r\n', 13 | ); 14 | serverSocket.write(head); 15 | serverSocket.pipe(clientSocket); 16 | clientSocket.pipe(serverSocket); 17 | }); 18 | }); 19 | 20 | await new Promise((resolve) => proxy.listen(0, '127.0.0.1', resolve)); 21 | 22 | console.log(proxy.address()!.toString()) 23 | 24 | return () => { 25 | proxy.close() 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ecosystem-tests/ts-browser-webpack/.babelrc: -------------------------------------------------------------------------------- 1 | { 2 | "presets": [ 3 | "@babel/preset-env", // Automatically determines the Babel plugins and polyfills you need based on your target environments 4 | "@babel/preset-typescript" // If you're using TypeScript, this preset will enable TypeScript transformation 5 | ], 6 | "plugins": [] 7 | } 8 | -------------------------------------------------------------------------------- /ecosystem-tests/ts-browser-webpack/.gitignore: -------------------------------------------------------------------------------- 1 | /node_modules 2 | /dist 3 | -------------------------------------------------------------------------------- /ecosystem-tests/ts-browser-webpack/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ts-browser-webpack", 3 | "version": "0.0.1", 4 | "private": true, 5 | "description": "ts-browser-webpack", 6 | "scripts": { 7 | "tsc": "tsc", 8 | "serve": "webpack serve", 9 | "build": "webpack", 10 | "test": "ts-node src/test.ts", 11 | "test:ci": "start-server-and-test serve http://localhost:8080 test" 12 | }, 13 | "devDependencies": { 14 | "@babel/core": "^7.21.0", 15 | "@babel/preset-env": "^7.21.0", 16 | "@babel/preset-typescript": "^7.21.0", 17 | "babel-loader": "^9.1.2", 18 | "fastest-levenshtein": "^1.0.16", 19 | "html-webpack-plugin": "^5.5.3", 20 | "puppeteer": "^23.4.0", 21 | "start-server-and-test": "^2.0.0", 22 | "ts-loader": "^9.4.3", 23 | "ts-node": "^10.9.1", 24 | "typescript": "^4.7.4", 25 | "webpack": "^5.87.0", 26 | "webpack-cli": "^5.0.2", 27 | "webpack-dev-server": "^4.15.1" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /ecosystem-tests/ts-browser-webpack/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Package in the Browser 6 | 7 | 8 |
Running tests...
9 | 10 | 11 | -------------------------------------------------------------------------------- /ecosystem-tests/ts-browser-webpack/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "strict": true, 5 | "noImplicitReturns": true, 6 | "removeComments": true, 7 | "preserveConstEnums": true, 8 | "sourceMap": true, 9 | "declaration": true, 10 | "skipLibCheck": false, 11 | "target": "es2015", 12 | "lib": ["es2017", "dom"], 13 | "outDir": "dist", 14 | "rootDir": "./", 15 | "baseUrl": ".", 16 | "paths": { 17 | "*": ["types/*"] 18 | } 19 | }, 20 | "include": ["src/**/*"], 21 | "exclude": ["node_modules/*"] 22 | } 23 | -------------------------------------------------------------------------------- /ecosystem-tests/ts-browser-webpack/webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | const HtmlWebpackPlugin = require('html-webpack-plugin'); 3 | 4 | const publicPath = path.resolve(__dirname, 'public'); 5 | const srcPath = path.resolve(__dirname, 'src'); 6 | const buildPath = path.resolve(__dirname, 'dist'); 7 | 8 | module.exports = { 9 | entry: path.join(srcPath, 'index.ts'), 10 | 11 | mode: 'development', 12 | 13 | output: { 14 | path: buildPath, 15 | filename: 'bundle.js', 16 | }, 17 | 18 | module: { 19 | rules: [ 20 | { 21 | test: /\.js$/, 22 | exclude: /node_modules/, 23 | loader: 'babel-loader', 24 | }, 25 | { 26 | test: /\.ts$/, 27 | exclude: /node_modules/, 28 | use: 'ts-loader', 29 | }, 30 | ], 31 | }, 32 | 33 | resolve: { 34 | extensions: ['.js', '.ts'], 35 | }, 36 | 37 | devtool: 'eval', 38 | 39 | plugins: [ 40 | new HtmlWebpackPlugin({ 41 | template: path.join(publicPath, 'index.html'), 42 | filename: 'index.html', 43 | }), 44 | ], 45 | 46 | devServer: { 47 | static: { 48 | directory: publicPath, 49 | }, 50 | compress: true, 51 | port: 8080, 52 | }, 53 | }; 54 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | /*.tgz 8 | 9 | # testing 10 | /coverage 11 | 12 | # next.js 13 | /.next/ 14 | /out/ 15 | 16 | # production 17 | /build 18 | 19 | # misc 20 | .DS_Store 21 | *.pem 22 | 23 | # debug 24 | npm-debug.log* 25 | yarn-debug.log* 26 | yarn-error.log* 27 | 28 | # local env files 29 | .env*.local 30 | 31 | # vercel 32 | .vercel 33 | 34 | # typescript 35 | *.tsbuildinfo 36 | next-env.d.ts 37 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/jest.config.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */ 2 | module.exports = { 3 | preset: 'ts-jest', 4 | testEnvironment: 'node', 5 | testMatch: ['/tests/*.ts'], 6 | watchPathIgnorePatterns: ['/node_modules/'], 7 | verbose: false, 8 | testTimeout: 60000, 9 | }; 10 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/next.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('next').NextConfig} */ 2 | const nextConfig = { 3 | reactStrictMode: true, 4 | }; 5 | 6 | module.exports = nextConfig; 7 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "vercel-edge", 3 | "version": "0.1.0", 4 | "private": true, 5 | "scripts": { 6 | "dev": "next dev", 7 | "build": "next build", 8 | "start": "next start", 9 | "lint": "next lint", 10 | "edge-runtime": "edge-runtime", 11 | "vercel": "vercel", 12 | "test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", 13 | "test:ci:dev": "start-server-and-test dev http://localhost:3000 test", 14 | "test:ci": "start-server-and-test start http://localhost:3000 test" 15 | }, 16 | "dependencies": { 17 | "ai": "2.1.34", 18 | "next": "^14.2.25", 19 | "react": "18.2.0", 20 | "react-dom": "18.2.0" 21 | }, 22 | "devDependencies": { 23 | "@types/node": "20.3.3", 24 | "@types/react": "18.2.74", 25 | "@types/react-dom": "18.2.23", 26 | "edge-runtime": "^2.4.3", 27 | "fastest-levenshtein": "^1.0.16", 28 | "jest": "^29.5.0", 29 | "start-server-and-test": "^2.0.0", 30 | "ts-jest": "^29.1.0", 31 | "typescript": "4.7.4", 32 | "vercel": "^31.0.0" 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/src/pages/_app.tsx: -------------------------------------------------------------------------------- 1 | import type { AppProps } from 'next/app'; 2 | 3 | export default function App({ Component, pageProps }: AppProps) { 4 | return ; 5 | } 6 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/src/pages/_document.tsx: -------------------------------------------------------------------------------- 1 | import { Html, Head, Main, NextScript } from 'next/document'; 2 | 3 | export default function Document() { 4 | return ( 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | ); 13 | } 14 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/src/pages/ai-streaming.tsx: -------------------------------------------------------------------------------- 1 | import { useChat } from 'ai/react'; 2 | 3 | export default function Chat() { 4 | const { messages, input, handleInputChange, handleSubmit } = useChat({ api: '/api/vercel-ai-streaming' }); 5 | console.log({ messages }); 6 | 7 | return ( 8 |
9 | {messages.map((m) => ( 10 |
11 | {m.role === 'user' ? 'User: ' : 'AI: '} 12 | {m.content} 13 |
14 | ))} 15 | 16 |
17 | 25 | 26 |
27 |
28 | ); 29 | } 30 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/src/pages/api/query-params.ts: -------------------------------------------------------------------------------- 1 | import { NextRequest, NextResponse } from 'next/server'; 2 | import OpenAI from 'openai'; 3 | 4 | export const config = { 5 | runtime: 'edge', 6 | unstable_allowDynamic: [ 7 | // This is currently required because `qs` uses `side-channel` which depends on this. 8 | // 9 | // Warning: Some features may be broken at runtime because of this. 10 | '/node_modules/function-bind/**', 11 | ], 12 | }; 13 | 14 | export default async (request: NextRequest) => { 15 | const openai = new OpenAI(); 16 | 17 | const result = await openai.beta.assistants.list({ limit: 10 }); 18 | 19 | return NextResponse.json(result); 20 | }; 21 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/src/pages/api/response.ts: -------------------------------------------------------------------------------- 1 | import { NextRequest, NextResponse } from 'next/server'; 2 | import OpenAI from 'openai'; 3 | 4 | export const config = { 5 | runtime: 'edge', 6 | unstable_allowDynamic: [ 7 | // This is currently required because `qs` uses `side-channel` which depends on this. 8 | // 9 | // Warning: Some features may be broken at runtime because of this. 10 | '/node_modules/function-bind/**', 11 | ], 12 | }; 13 | 14 | export default async (request: NextRequest) => { 15 | const openai = new OpenAI(); 16 | 17 | const result = await openai.completions.create({ 18 | prompt: 'Say this is a test', 19 | model: 'gpt-3.5-turbo-instruct', 20 | }); 21 | return NextResponse.json(result); 22 | }; 23 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/src/pages/api/streaming.ts: -------------------------------------------------------------------------------- 1 | import { NextRequest, NextResponse } from 'next/server'; 2 | import OpenAI from 'openai'; 3 | 4 | export const config = { 5 | runtime: 'edge', 6 | unstable_allowDynamic: [ 7 | // This is currently required because `qs` uses `side-channel` which depends on this. 8 | // 9 | // Warning: Some features may be broken at runtime because of this. 10 | '/node_modules/function-bind/**', 11 | ], 12 | }; 13 | 14 | export default async (request: NextRequest) => { 15 | const openai = new OpenAI(); 16 | 17 | const text: string[] = []; 18 | 19 | const stream = await openai.completions.create({ 20 | prompt: 'Say this is a test', 21 | model: 'gpt-3.5-turbo-instruct', 22 | stream: true, 23 | }); 24 | 25 | for await (const part of stream) { 26 | text.push(part.choices[0]?.text || ''); 27 | } 28 | 29 | return NextResponse.json({ text: text.join('') }); 30 | }; 31 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/src/pages/api/transcribe.ts: -------------------------------------------------------------------------------- 1 | import { NextRequest, NextResponse } from 'next/server'; 2 | import OpenAI, { toFile } from 'openai'; 3 | import { TranscriptionCreateParams } from 'openai/resources/audio'; 4 | 5 | export const config = { 6 | runtime: 'edge', 7 | unstable_allowDynamic: [ 8 | // This is currently required because `qs` uses `side-channel` which depends on this. 9 | // 10 | // Warning: Some features may be broken at runtime because of this. 11 | '/node_modules/function-bind/**', 12 | ], 13 | }; 14 | 15 | export default async (request: NextRequest) => { 16 | const openai = new OpenAI(); 17 | 18 | async function typeTests() { 19 | // @ts-expect-error this should error if the `Uploadable` type was resolved correctly 20 | await openai.audio.transcriptions.create({ file: { foo: true }, model: 'whisper-1' }); 21 | // @ts-expect-error this should error if the `Uploadable` type was resolved correctly 22 | await openai.audio.transcriptions.create({ file: null, model: 'whisper-1' }); 23 | // @ts-expect-error this should error if the `Uploadable` type was resolved correctly 24 | await openai.audio.transcriptions.create({ file: 'test', model: 'whisper-1' }); 25 | } 26 | 27 | const rsp = await fetch('https://audio-samples.github.io/samples/mp3/blizzard_biased/sample-1.mp3'); 28 | 29 | const params: TranscriptionCreateParams = { 30 | model: 'whisper-1', 31 | file: await toFile(rsp, 'sample-1.mp3'), 32 | }; 33 | const transcription = await openai.audio.transcriptions.create(params); 34 | 35 | return NextResponse.json(transcription); 36 | }; 37 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/src/pages/api/vercel-ai-streaming.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | import { OpenAIStream, StreamingTextResponse } from 'ai'; 3 | import { NextRequest } from 'next/server'; 4 | 5 | export const config = { 6 | runtime: 'edge', 7 | unstable_allowDynamic: [ 8 | // This is currently required because `qs` uses `side-channel` which depends on this. 9 | '/node_modules/function-bind/**', 10 | ], 11 | }; 12 | 13 | export default async (request: NextRequest) => { 14 | const openai = new OpenAI(); 15 | 16 | // Extract the `messages` from the body of the request 17 | const { messages } = await request.json(); 18 | 19 | // Ask OpenAI for a streaming chat completion given the prompt 20 | const streamResponse = await openai.chat.completions 21 | .create({ 22 | model: 'gpt-3.5-turbo', 23 | stream: true, 24 | messages, 25 | }) 26 | .asResponse(); 27 | 28 | const stream = OpenAIStream(streamResponse); 29 | 30 | // Respond with the stream 31 | return new StreamingTextResponse(stream); 32 | }; 33 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/src/pages/index.tsx: -------------------------------------------------------------------------------- 1 | import Head from 'next/head'; 2 | 3 | export default function Home() { 4 | return ( 5 | <> 6 | 7 | Vercel Edge Test 8 | 9 | 10 | 11 | 12 |
13 |
14 |

Hello, world!

15 |
16 |
17 | 18 | ); 19 | } 20 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/tests/test.ts: -------------------------------------------------------------------------------- 1 | const baseUrl = process.env.TEST_BASE_URL || 'http://localhost:3000'; 2 | console.log(baseUrl); 3 | 4 | it( 5 | 'node runtime', 6 | async () => { 7 | expect(await (await fetch(`${baseUrl}/api/node-test`)).text()).toEqual('Passed!'); 8 | }, 9 | 3 * 60000, 10 | ); 11 | 12 | it( 13 | 'edge runtime', 14 | async () => { 15 | expect(await (await fetch(`${baseUrl}/api/edge-test`)).text()).toEqual('Passed!'); 16 | }, 17 | 3 * 60000, 18 | ); 19 | 20 | // make isolatedModules happy 21 | export {}; 22 | -------------------------------------------------------------------------------- /ecosystem-tests/vercel-edge/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "lib": ["dom", "dom.iterable", "esnext"], 5 | "allowJs": true, 6 | "skipLibCheck": true, 7 | "strict": true, 8 | "forceConsistentCasingInFileNames": true, 9 | "noEmit": true, 10 | "esModuleInterop": true, 11 | "module": "esnext", 12 | "moduleResolution": "node", 13 | "resolveJsonModule": true, 14 | "isolatedModules": true, 15 | "jsx": "preserve", 16 | "incremental": true, 17 | "paths": { 18 | "~/*": ["./src/*"] 19 | } 20 | }, 21 | "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], 22 | "exclude": ["node_modules"] 23 | } 24 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | import tseslint from 'typescript-eslint'; 3 | import unusedImports from 'eslint-plugin-unused-imports'; 4 | import prettier from 'eslint-plugin-prettier'; 5 | 6 | export default tseslint.config( 7 | { 8 | languageOptions: { 9 | parser: tseslint.parser, 10 | parserOptions: { sourceType: 'module' }, 11 | }, 12 | files: ['**/*.ts', '**/*.mts', '**/*.cts', '**/*.js', '**/*.mjs', '**/*.cjs'], 13 | ignores: ['dist/**', 'ecosystem-tests/**'], 14 | plugins: { 15 | '@typescript-eslint': tseslint.plugin, 16 | 'unused-imports': unusedImports, 17 | prettier, 18 | }, 19 | rules: { 20 | 'no-unused-vars': 'off', 21 | 'prettier/prettier': 'error', 22 | 'unused-imports/no-unused-imports': 'error', 23 | 'no-restricted-imports': [ 24 | 'error', 25 | { 26 | patterns: [ 27 | { 28 | regex: '^openai(/.*)?', 29 | message: 'Use a relative import, not a package import.', 30 | }, 31 | ], 32 | }, 33 | ], 34 | }, 35 | }, 36 | { 37 | files: ['tests/**', 'examples/**'], 38 | rules: { 39 | 'no-restricted-imports': 'off', 40 | }, 41 | }, 42 | ); 43 | -------------------------------------------------------------------------------- /examples/.gitignore: -------------------------------------------------------------------------------- 1 | yarn.lock 2 | node_modules 3 | -------------------------------------------------------------------------------- /examples/.keep: -------------------------------------------------------------------------------- 1 | File generated from our OpenAPI spec by Stainless. 2 | 3 | This directory can be used to store example files demonstrating usage of this SDK. 4 | It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. 5 | -------------------------------------------------------------------------------- /examples/assistant-stream-raw.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const openai = new OpenAI(); 6 | 7 | async function main() { 8 | const assistant = await openai.beta.assistants.create({ 9 | model: 'gpt-4-1106-preview', 10 | name: 'Math Tutor', 11 | instructions: 'You are a personal math tutor. Write and run code to answer math questions.', 12 | }); 13 | 14 | const thread = await openai.beta.threads.create({ 15 | messages: [ 16 | { 17 | role: 'user', 18 | content: '"I need to solve the equation `3x + 11 = 14`. Can you help me?"', 19 | }, 20 | ], 21 | }); 22 | 23 | const stream = await openai.beta.threads.runs.create(thread.id, { 24 | assistant_id: assistant.id, 25 | additional_instructions: 'Please address the user as Jane Doe. The user has a premium account.', 26 | stream: true, 27 | }); 28 | 29 | for await (const event of stream) { 30 | if (event.event === 'thread.message.delta') { 31 | const chunk = event.data.delta.content?.[0]; 32 | if (chunk && 'text' in chunk && chunk.text.value) { 33 | process.stdout.write(chunk.text.value); 34 | } 35 | } 36 | } 37 | 38 | console.log(); 39 | } 40 | 41 | main(); 42 | -------------------------------------------------------------------------------- /examples/assistant-stream.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | /** 6 | * Example of streaming a response from an assistant 7 | */ 8 | 9 | const openai = new OpenAI(); 10 | 11 | async function main() { 12 | const assistant = await openai.beta.assistants.create({ 13 | model: 'gpt-4-1106-preview', 14 | name: 'Math Tutor', 15 | instructions: 'You are a personal math tutor. Write and run code to answer math questions.', 16 | }); 17 | 18 | let assistantId = assistant.id; 19 | console.log('Created Assistant with Id: ' + assistantId); 20 | 21 | const thread = await openai.beta.threads.create({ 22 | messages: [ 23 | { 24 | role: 'user', 25 | content: '"I need to solve the equation `3x + 11 = 14`. Can you help me?"', 26 | }, 27 | ], 28 | }); 29 | 30 | let threadId = thread.id; 31 | console.log('Created thread with Id: ' + threadId); 32 | 33 | const run = openai.beta.threads.runs 34 | .stream(threadId, { 35 | assistant_id: assistantId, 36 | }) 37 | //Subscribe to streaming events and log them 38 | .on('event', (event) => console.log(event)) 39 | .on('textDelta', (delta, snapshot) => console.log(snapshot)) 40 | .on('messageDelta', (delta, snapshot) => console.log(snapshot)) 41 | .on('run', (run) => console.log(run)) 42 | .on('connect', () => console.log()); 43 | const result = await run.finalRun(); 44 | console.log('Run Result' + result); 45 | } 46 | 47 | main(); 48 | -------------------------------------------------------------------------------- /examples/assistants.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | /** 6 | * Example of polling for a complete response from an assistant 7 | */ 8 | 9 | const openai = new OpenAI(); 10 | 11 | async function main() { 12 | const assistant = await openai.beta.assistants.create({ 13 | model: 'gpt-4-1106-preview', 14 | name: 'Math Tutor', 15 | instructions: 'You are a personal math tutor. Write and run code to answer math questions.', 16 | // tools = [], 17 | }); 18 | 19 | let assistantId = assistant.id; 20 | console.log('Created Assistant with Id: ' + assistantId); 21 | 22 | const thread = await openai.beta.threads.create({ 23 | messages: [ 24 | { 25 | role: 'user', 26 | content: '"I need to solve the equation `3x + 11 = 14`. Can you help me?"', 27 | }, 28 | ], 29 | }); 30 | 31 | let threadId = thread.id; 32 | console.log('Created thread with Id: ' + threadId); 33 | 34 | const run = await openai.beta.threads.runs.createAndPoll(thread.id, { 35 | assistant_id: assistantId, 36 | additional_instructions: 'Please address the user as Jane Doe. The user has a premium account.', 37 | }); 38 | 39 | console.log('Run finished with status: ' + run.status); 40 | 41 | if (run.status == 'completed') { 42 | const messages = await openai.beta.threads.messages.list(thread.id); 43 | for (const message of messages.getPaginatedItems()) { 44 | console.log(message); 45 | } 46 | } 47 | } 48 | 49 | main(); 50 | -------------------------------------------------------------------------------- /examples/azure/chat.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import { AzureOpenAI } from 'openai'; 4 | import { getBearerTokenProvider, DefaultAzureCredential } from '@azure/identity'; 5 | import 'dotenv/config'; 6 | 7 | // Corresponds to your Model deployment within your OpenAI resource, e.g. gpt-4-1106-preview 8 | // Navigate to the Azure OpenAI Studio to deploy a model. 9 | const deployment = 'gpt-4-1106-preview'; 10 | 11 | const credential = new DefaultAzureCredential(); 12 | const scope = 'https://cognitiveservices.azure.com/.default'; 13 | const azureADTokenProvider = getBearerTokenProvider(credential, scope); 14 | 15 | // Make sure to set AZURE_OPENAI_ENDPOINT with the endpoint of your Azure resource. 16 | // You can find it in the Azure Portal. 17 | const openai = new AzureOpenAI({ azureADTokenProvider, apiVersion: '2024-10-01-preview' }); 18 | 19 | async function main() { 20 | console.log('Non-streaming:'); 21 | const result = await openai.chat.completions.create({ 22 | model: deployment, 23 | messages: [{ role: 'user', content: 'Say hello!' }], 24 | }); 25 | console.log(result.choices[0]!.message?.content); 26 | 27 | console.log(); 28 | console.log('Streaming:'); 29 | const stream = await openai.chat.completions.create({ 30 | model: deployment, 31 | messages: [{ role: 'user', content: 'Say hello!' }], 32 | stream: true, 33 | }); 34 | 35 | for await (const part of stream) { 36 | process.stdout.write(part.choices[0]?.delta?.content ?? ''); 37 | } 38 | process.stdout.write('\n'); 39 | } 40 | 41 | main().catch((err) => { 42 | console.error(err); 43 | process.exit(1); 44 | }); 45 | -------------------------------------------------------------------------------- /examples/demo.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | // gets API Key from environment variable OPENAI_API_KEY 6 | const openai = new OpenAI(); 7 | 8 | async function main() { 9 | // Non-streaming: 10 | const completion = await openai.chat.completions.create({ 11 | model: 'gpt-4', 12 | messages: [{ role: 'user', content: 'Say this is a test' }], 13 | }); 14 | console.log(completion.choices[0]?.message?.content); 15 | 16 | // Streaming: 17 | const stream = await openai.chat.completions.create({ 18 | model: 'gpt-4', 19 | messages: [{ role: 'user', content: 'Say this is a test' }], 20 | stream: true, 21 | }); 22 | for await (const part of stream) { 23 | process.stdout.write(part.choices[0]?.delta?.content || ''); 24 | } 25 | process.stdout.write('\n'); 26 | } 27 | 28 | main(); 29 | -------------------------------------------------------------------------------- /examples/errors.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI, { NotFoundError } from 'openai'; 4 | 5 | // gets API Key from environment variable OPENAI_API_KEY 6 | const client = new OpenAI(); 7 | 8 | async function main() { 9 | try { 10 | await client.completions.create({ 11 | prompt: 'Say this is a test', 12 | model: 'unknown-model', 13 | }); 14 | } catch (err) { 15 | if (err instanceof NotFoundError) { 16 | console.log(`Caught NotFoundError!`); 17 | console.log(err); 18 | console.log(`message: `, err.message); 19 | console.log(`code: `, err.code); 20 | console.log(`type: `, err.type); 21 | console.log(`param: `, err.param); 22 | } else { 23 | console.log(`Raised unknown error`); 24 | throw err; 25 | } 26 | } 27 | } 28 | 29 | main(); 30 | -------------------------------------------------------------------------------- /examples/logprobs.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | // gets API Key from environment variable OPENAI_API_KEY 6 | const openai = new OpenAI(); 7 | 8 | async function main() { 9 | const stream = await openai.chat.completions 10 | .stream({ 11 | model: 'gpt-4', 12 | messages: [{ role: 'user', content: 'Say this is a test' }], 13 | stream: true, 14 | logprobs: true, 15 | }) 16 | .on('logprobs.content.delta', (logprob) => { 17 | console.log(logprob); 18 | }); 19 | 20 | console.dir(await stream.finalChatCompletion(), { depth: null }); 21 | } 22 | 23 | main(); 24 | -------------------------------------------------------------------------------- /examples/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "openai-examples", 3 | "version": "1.0.0", 4 | "description": "Usage examples for the OpenAI Node.js SDK.", 5 | "main": "index.js", 6 | "license": "MIT", 7 | "private": true, 8 | "dependencies": { 9 | "@azure/identity": "^4.2.0", 10 | "dotenv": "^16.4.7", 11 | "express": "^4.18.2", 12 | "next": "^14.2.25", 13 | "openai": "file:..", 14 | "zod-to-json-schema": "^3.21.4" 15 | }, 16 | "devDependencies": { 17 | "@types/body-parser": "^1.19.3", 18 | "@types/express": "^4.17.19", 19 | "@types/web": "^0.0.194" 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /examples/parsing-stream.ts: -------------------------------------------------------------------------------- 1 | import { zodResponseFormat } from 'openai/helpers/zod'; 2 | import OpenAI from 'openai/index'; 3 | import { z } from 'zod'; 4 | 5 | const Step = z.object({ 6 | explanation: z.string(), 7 | output: z.string(), 8 | }); 9 | 10 | const MathResponse = z.object({ 11 | steps: z.array(Step), 12 | final_answer: z.string(), 13 | }); 14 | 15 | async function main() { 16 | const client = new OpenAI(); 17 | 18 | const stream = client.chat.completions 19 | .stream({ 20 | model: 'gpt-4o-2024-08-06', 21 | messages: [ 22 | { 23 | role: 'user', 24 | content: `What's the weather like in SF?`, 25 | }, 26 | ], 27 | response_format: zodResponseFormat(MathResponse, 'math_response'), 28 | }) 29 | .on('refusal.delta', ({ delta }) => { 30 | process.stdout.write(delta); 31 | }) 32 | .on('refusal.done', () => console.log('\n\nrequest refused 😱')) 33 | .on('content.delta', ({ snapshot, parsed }) => { 34 | console.log('content:', snapshot); 35 | console.log('parsed:', parsed); 36 | console.log(); 37 | }) 38 | .on('content.done', (props) => { 39 | if (props.parsed) { 40 | console.log('\n\nfinished parsing!'); 41 | console.log(`answer: ${props.parsed.final_answer}`); 42 | } 43 | }); 44 | 45 | await stream.done(); 46 | 47 | const completion = await stream.finalChatCompletion(); 48 | 49 | console.dir(completion, { depth: 5 }); 50 | 51 | const message = completion.choices[0]?.message; 52 | if (message?.parsed) { 53 | console.log(message.parsed.steps); 54 | } 55 | } 56 | 57 | main(); 58 | -------------------------------------------------------------------------------- /examples/parsing-tools-stream.ts: -------------------------------------------------------------------------------- 1 | import { zodFunction } from 'openai/helpers/zod'; 2 | import OpenAI from 'openai/index'; 3 | import { z } from 'zod'; 4 | 5 | const GetWeatherArgs = z.object({ 6 | city: z.string(), 7 | country: z.string(), 8 | units: z.enum(['c', 'f']).default('c'), 9 | }); 10 | 11 | async function main() { 12 | const client = new OpenAI(); 13 | const refusal = process.argv.includes('refusal'); 14 | 15 | const stream = client.chat.completions 16 | .stream({ 17 | model: 'gpt-4o-2024-08-06', 18 | messages: [ 19 | { 20 | role: 'user', 21 | content: refusal ? 'How do I make anthrax?' : `What's the weather like in SF?`, 22 | }, 23 | ], 24 | tools: [zodFunction({ name: 'get_weather', parameters: GetWeatherArgs })], 25 | }) 26 | .on('tool_calls.function.arguments.delta', (props) => 27 | console.log('tool_calls.function.arguments.delta', props), 28 | ) 29 | .on('tool_calls.function.arguments.done', (props) => 30 | console.log('tool_calls.function.arguments.done', props), 31 | ) 32 | .on('refusal.delta', ({ delta }) => { 33 | process.stdout.write(delta); 34 | }) 35 | .on('refusal.done', () => console.log('\n\nrequest refused 😱')); 36 | 37 | const completion = await stream.finalChatCompletion(); 38 | 39 | console.log('final completion:'); 40 | console.dir(completion, { depth: 10 }); 41 | } 42 | 43 | main(); 44 | -------------------------------------------------------------------------------- /examples/parsing.ts: -------------------------------------------------------------------------------- 1 | import { zodResponseFormat } from 'openai/helpers/zod'; 2 | import OpenAI from 'openai/index'; 3 | import { z } from 'zod'; 4 | 5 | const Step = z.object({ 6 | explanation: z.string(), 7 | output: z.string(), 8 | }); 9 | 10 | const MathResponse = z.object({ 11 | steps: z.array(Step), 12 | final_answer: z.string(), 13 | }); 14 | 15 | async function main() { 16 | const client = new OpenAI(); 17 | 18 | const completion = await client.chat.completions.parse({ 19 | model: 'gpt-4o-2024-08-06', 20 | messages: [ 21 | { role: 'system', content: 'You are a helpful math tutor.' }, 22 | { role: 'user', content: 'solve 8x + 31 = 2' }, 23 | ], 24 | response_format: zodResponseFormat(MathResponse, 'math_response'), 25 | }); 26 | 27 | console.dir(completion, { depth: 5 }); 28 | 29 | const message = completion.choices[0]?.message; 30 | if (message?.parsed) { 31 | console.log(message.parsed.steps); 32 | console.log(`answer: ${message.parsed.final_answer}`); 33 | } 34 | } 35 | 36 | main(); 37 | -------------------------------------------------------------------------------- /examples/raw-response.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S yarn tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | // gets API Key from environment variable OPENAI_API_KEY 6 | const client = new OpenAI(); 7 | 8 | async function main() { 9 | // getting just raw Response: 10 | { 11 | const response = await client.completions 12 | .create({ 13 | prompt: 'Say this is a test', 14 | model: 'gpt-3.5-turbo-instruct', 15 | }) 16 | .asResponse(); 17 | console.log(`response headers: `, Object.fromEntries(response.headers.entries())); 18 | console.log(`response json: `, await response.json()); 19 | } 20 | 21 | // getting the usual return value plus raw Response: 22 | { 23 | const { data: completion, response } = await client.completions 24 | .create({ 25 | prompt: 'Say this is a test', 26 | model: 'gpt-3.5-turbo-instruct', 27 | }) 28 | .withResponse(); 29 | console.log(`response headers: `, Object.fromEntries(response.headers.entries())); 30 | console.log(`completion: `, completion); 31 | } 32 | } 33 | 34 | main().catch(console.error); 35 | -------------------------------------------------------------------------------- /examples/realtime/websocket.ts: -------------------------------------------------------------------------------- 1 | import { OpenAIRealtimeWebSocket } from 'openai/beta/realtime/websocket'; 2 | 3 | async function main() { 4 | const rt = new OpenAIRealtimeWebSocket({ model: 'gpt-4o-realtime-preview-2024-12-17' }); 5 | 6 | // access the underlying `ws.WebSocket` instance 7 | rt.socket.addEventListener('open', () => { 8 | console.log('Connection opened!'); 9 | rt.send({ 10 | type: 'session.update', 11 | session: { 12 | modalities: ['text'], 13 | model: 'gpt-4o-realtime-preview', 14 | }, 15 | }); 16 | 17 | rt.send({ 18 | type: 'conversation.item.create', 19 | item: { 20 | type: 'message', 21 | role: 'user', 22 | content: [{ type: 'input_text', text: 'Say a couple paragraphs!' }], 23 | }, 24 | }); 25 | 26 | rt.send({ type: 'response.create' }); 27 | }); 28 | 29 | rt.on('error', (err) => { 30 | // in a real world scenario this should be logged somewhere as you 31 | // likely want to continue processing events regardless of any errors 32 | throw err; 33 | }); 34 | 35 | rt.on('session.created', (event) => { 36 | console.log('session created!', event.session); 37 | console.log(); 38 | }); 39 | 40 | rt.on('response.text.delta', (event) => process.stdout.write(event.delta)); 41 | rt.on('response.text.done', () => console.log()); 42 | 43 | rt.on('response.done', () => rt.close()); 44 | 45 | rt.socket.addEventListener('close', () => console.log('\nConnection closed!')); 46 | } 47 | 48 | main(); 49 | -------------------------------------------------------------------------------- /examples/realtime/ws.ts: -------------------------------------------------------------------------------- 1 | import { OpenAIRealtimeWS } from 'openai/beta/realtime/ws'; 2 | 3 | async function main() { 4 | const rt = new OpenAIRealtimeWS({ model: 'gpt-4o-realtime-preview-2024-12-17' }); 5 | 6 | // access the underlying `ws.WebSocket` instance 7 | rt.socket.on('open', () => { 8 | console.log('Connection opened!'); 9 | rt.send({ 10 | type: 'session.update', 11 | session: { 12 | modalities: ['text'], 13 | model: 'gpt-4o-realtime-preview', 14 | }, 15 | }); 16 | 17 | rt.send({ 18 | type: 'conversation.item.create', 19 | item: { 20 | type: 'message', 21 | role: 'user', 22 | content: [{ type: 'input_text', text: 'Say a couple paragraphs!' }], 23 | }, 24 | }); 25 | 26 | rt.send({ type: 'response.create' }); 27 | }); 28 | 29 | rt.on('error', (err) => { 30 | // in a real world scenario this should be logged somewhere as you 31 | // likely want to continue processing events regardless of any errors 32 | throw err; 33 | }); 34 | 35 | rt.on('session.created', (event) => { 36 | console.log('session created!', event.session); 37 | console.log(); 38 | }); 39 | 40 | rt.on('response.text.delta', (event) => process.stdout.write(event.delta)); 41 | rt.on('response.text.done', () => console.log()); 42 | 43 | rt.on('response.done', () => rt.close()); 44 | 45 | rt.socket.on('close', () => console.log('\nConnection closed!')); 46 | } 47 | 48 | main(); 49 | -------------------------------------------------------------------------------- /examples/responses/stream.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const openai = new OpenAI(); 6 | 7 | async function main() { 8 | const runner = openai.responses 9 | .stream({ 10 | model: 'gpt-4o-2024-08-06', 11 | input: 'solve 8x + 31 = 2', 12 | }) 13 | .on('event', (event) => console.log(event)) 14 | .on('response.output_text.delta', (diff) => process.stdout.write(diff.delta)); 15 | 16 | for await (const event of runner) { 17 | console.log('event', event); 18 | } 19 | 20 | const result = await runner.finalResponse(); 21 | console.log(result); 22 | } 23 | 24 | main(); 25 | -------------------------------------------------------------------------------- /examples/responses/stream_background.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const openai = new OpenAI(); 6 | 7 | async function main() { 8 | const runner = openai.responses.stream({ 9 | model: 'gpt-4o-2024-08-06', 10 | input: 'solve 8x + 31 = 2', 11 | background: true, 12 | }); 13 | 14 | let id: string | null = null; 15 | 16 | for await (const event of runner) { 17 | if (event.type == 'response.created') { 18 | id = event.response.id; 19 | } 20 | 21 | console.log('event', event); 22 | if (event.sequence_number == 10) { 23 | break; 24 | } 25 | } 26 | 27 | console.log('Interrupted. Continuing...'); 28 | 29 | const runner2 = openai.responses.stream({ 30 | response_id: id!, 31 | starting_after: 10, 32 | }); 33 | 34 | for await (const event of runner2) { 35 | console.log('event', event); 36 | } 37 | 38 | const result = await runner2.finalResponse(); 39 | console.log(result); 40 | } 41 | 42 | main(); 43 | -------------------------------------------------------------------------------- /examples/responses/streaming-tools.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import { OpenAI } from 'openai'; 4 | import { zodResponsesFunction } from 'openai/helpers/zod'; 5 | import { z } from 'zod'; 6 | 7 | const Table = z.enum(['orders', 'customers', 'products']); 8 | const Column = z.enum([ 9 | 'id', 10 | 'status', 11 | 'expected_delivery_date', 12 | 'delivered_at', 13 | 'shipped_at', 14 | 'ordered_at', 15 | 'canceled_at', 16 | ]); 17 | const Operator = z.enum(['=', '>', '<', '<=', '>=', '!=']); 18 | const OrderBy = z.enum(['asc', 'desc']); 19 | const DynamicValue = z.object({ 20 | column_name: Column, 21 | }); 22 | 23 | const Condition = z.object({ 24 | column: Column, 25 | operator: Operator, 26 | value: z.union([z.string(), z.number(), DynamicValue]), 27 | }); 28 | 29 | const Query = z.object({ 30 | table_name: Table, 31 | columns: z.array(Column), 32 | conditions: z.array(Condition), 33 | order_by: OrderBy, 34 | }); 35 | 36 | async function main() { 37 | const client = new OpenAI(); 38 | 39 | const tool = zodResponsesFunction({ name: 'query', parameters: Query }); 40 | 41 | const stream = client.responses.stream({ 42 | model: 'gpt-4o-2024-08-06', 43 | input: 'look up all my orders in november of last year that were fulfilled but not delivered on time', 44 | tools: [tool], 45 | }); 46 | 47 | for await (const event of stream) { 48 | console.dir(event, { depth: 10 }); 49 | } 50 | } 51 | 52 | main(); 53 | -------------------------------------------------------------------------------- /examples/responses/structured-outputs-tools.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import { OpenAI } from 'openai'; 4 | import { zodResponsesFunction } from 'openai/helpers/zod'; 5 | import { z } from 'zod'; 6 | 7 | const Table = z.enum(['orders', 'customers', 'products']); 8 | const Column = z.enum([ 9 | 'id', 10 | 'status', 11 | 'expected_delivery_date', 12 | 'delivered_at', 13 | 'shipped_at', 14 | 'ordered_at', 15 | 'canceled_at', 16 | ]); 17 | const Operator = z.enum(['=', '>', '<', '<=', '>=', '!=']); 18 | const OrderBy = z.enum(['asc', 'desc']); 19 | const DynamicValue = z.object({ 20 | column_name: Column, 21 | }); 22 | 23 | const Condition = z.object({ 24 | column: Column, 25 | operator: Operator, 26 | value: z.union([z.string(), z.number(), DynamicValue]), 27 | }); 28 | 29 | const Query = z.object({ 30 | table_name: Table, 31 | columns: z.array(Column), 32 | conditions: z.array(Condition), 33 | order_by: OrderBy, 34 | }); 35 | 36 | async function main() { 37 | const client = new OpenAI(); 38 | 39 | const tool = zodResponsesFunction({ name: 'query', parameters: Query }); 40 | 41 | const rsp = await client.responses.parse({ 42 | model: 'gpt-4o-2024-08-06', 43 | input: 'look up all my orders in november of last year that were fulfilled but not delivered on time', 44 | tools: [tool], 45 | }); 46 | 47 | console.log(rsp); 48 | 49 | const functionCall = rsp.output[0]!; 50 | 51 | if (functionCall.type !== 'function_call') { 52 | throw new Error('Expected function call'); 53 | } 54 | 55 | const query = functionCall.parsed_arguments; 56 | 57 | console.log(query); 58 | } 59 | 60 | main(); 61 | -------------------------------------------------------------------------------- /examples/responses/structured-outputs.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import { OpenAI } from 'openai'; 4 | import { zodTextFormat } from 'openai/helpers/zod'; 5 | import { z } from 'zod'; 6 | 7 | const Step = z.object({ 8 | explanation: z.string(), 9 | output: z.string(), 10 | }); 11 | 12 | const MathResponse = z.object({ 13 | steps: z.array(Step), 14 | final_answer: z.string(), 15 | }); 16 | 17 | const client = new OpenAI(); 18 | 19 | async function main() { 20 | const rsp = await client.responses.parse({ 21 | input: 'solve 8x + 31 = 2', 22 | model: 'gpt-4o-2024-08-06', 23 | text: { 24 | format: zodTextFormat(MathResponse, 'math_response'), 25 | }, 26 | }); 27 | 28 | console.log(rsp.output_parsed); 29 | console.log('answer: ', rsp.output_parsed?.final_answer); 30 | } 31 | 32 | main().catch(console.error); 33 | -------------------------------------------------------------------------------- /examples/speech-to-text.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | import { recordAudio } from 'openai/helpers/audio'; 3 | 4 | const openai = new OpenAI(); 5 | 6 | async function main(): Promise { 7 | console.log('Recording for 5 seconds...'); 8 | const response = await recordAudio({ timeout: 5000, device: 4 }); 9 | 10 | console.log('Transcribing...'); 11 | const transcription = await openai.audio.transcriptions.create({ 12 | file: response, 13 | model: 'whisper-1', 14 | }); 15 | 16 | console.log(transcription.text); 17 | } 18 | 19 | main().catch(console.error); 20 | -------------------------------------------------------------------------------- /examples/stream-to-client-browser.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | /** 4 | * This file is intended be run from the command-line with Node 5 | * for easy demo purposes, but simulating use in the browser. 6 | * 7 | * To run it in a browser application, copy/paste it into a frontend application, 8 | * remove the 'node-fetch' import, and replace `process.stdout.write` with 9 | * a console.log or UI display. 10 | */ 11 | import { ChatCompletionStream } from 'openai/lib/ChatCompletionStream'; 12 | 13 | fetch('http://localhost:3000', { 14 | method: 'POST', 15 | body: 'Tell me why dogs are better than cats', 16 | headers: { 'Content-Type': 'text/plain' }, 17 | }).then(async (res) => { 18 | // @ts-ignore ReadableStream on different environments can be strange 19 | const runner = ChatCompletionStream.fromReadableStream(res.body); 20 | 21 | runner.on('content', (delta, snapshot) => { 22 | process.stdout.write(delta); 23 | // or, in a browser, you might display like this: 24 | // document.body.innerText += delta; // or: 25 | // document.body.innerText = snapshot; 26 | }); 27 | 28 | console.dir(await runner.finalChatCompletion(), { depth: null }); 29 | }); 30 | -------------------------------------------------------------------------------- /examples/stream-to-client-express.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | // This file demonstrates how to stream from the server the chunks as 4 | // a new-line separated JSON-encoded stream. 5 | 6 | import OpenAI from 'openai'; 7 | import express, { Request, Response } from 'express'; 8 | 9 | const openai = new OpenAI(); 10 | const app = express(); 11 | 12 | app.use(express.text()); 13 | 14 | // This endpoint can be called with: 15 | // 16 | // curl 127.0.0.1:3000 -N -X POST -H 'Content-Type: text/plain' \ 17 | // --data 'Can you explain why dogs are better than cats?' 18 | // 19 | // Or consumed with fetch: 20 | // 21 | // fetch('http://localhost:3000', { 22 | // method: 'POST', 23 | // body: 'Tell me why dogs are better than cats', 24 | // }).then(async res => { 25 | // const runner = ChatCompletionStreamingRunner.fromReadableStream(res) 26 | // }) 27 | // 28 | // See examples/stream-to-client-browser.ts for a more complete example. 29 | app.post('/', async (req: Request, res: Response) => { 30 | try { 31 | console.log('Received request:', req.body); 32 | 33 | const stream = openai.chat.completions.stream({ 34 | model: 'gpt-3.5-turbo', 35 | stream: true, 36 | messages: [{ role: 'user', content: req.body }], 37 | }); 38 | 39 | res.header('Content-Type', 'text/plain'); 40 | for await (const chunk of stream.toReadableStream()) { 41 | res.write(chunk); 42 | } 43 | 44 | res.end(); 45 | } catch (e) { 46 | console.error(e); 47 | } 48 | }); 49 | 50 | app.listen('3000', () => { 51 | console.log('Started proxy express server'); 52 | }); 53 | -------------------------------------------------------------------------------- /examples/stream-to-client-next.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | import type { NextApiRequest, NextApiResponse } from 'next'; 3 | 4 | // This file demonstrates how to stream from a Next.JS server as 5 | // a new-line separated JSON-encoded stream. This file cannot be run 6 | // without Next.JS scaffolding. 7 | 8 | export const runtime = 'edge'; 9 | 10 | // This endpoint can be called with: 11 | // 12 | // curl 127.0.0.1:3000 -N -X POST -H 'Content-Type: text/plain' \ 13 | // --data 'Can you explain why dogs are better than cats?' 14 | // 15 | // Or consumed with fetch: 16 | // 17 | // fetch('http://localhost:3000', { 18 | // method: 'POST', 19 | // body: 'Tell me why dogs are better than cats', 20 | // }).then(async res => { 21 | // const runner = ChatCompletionStreamingRunner.fromReadableStream(res) 22 | // }) 23 | // 24 | // See examples/stream-to-client-browser.ts for a more complete example. 25 | export default async function handler(req: NextApiRequest, res: NextApiResponse) { 26 | const openai = new OpenAI(); 27 | 28 | const stream = openai.chat.completions.stream({ 29 | model: 'gpt-3.5-turbo', 30 | stream: true, 31 | // @ts-ignore 32 | messages: [{ role: 'user', content: await req.text() }], 33 | }); 34 | 35 | return res.send(stream.toReadableStream()); 36 | // @ts-ignore -- Or, for the app router: 37 | return new Response(stream.toReadableStream()); 38 | } 39 | -------------------------------------------------------------------------------- /examples/stream-to-client-raw.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | // This file demonstrates how to stream from the server as a text/plain 4 | // response with express and the stream async iterator. 5 | 6 | import OpenAI from 'openai'; 7 | import express, { Request, Response } from 'express'; 8 | 9 | const openai = new OpenAI(); 10 | const app = express(); 11 | 12 | app.use(express.text()); 13 | 14 | // This endpoint can be called with: 15 | // 16 | // curl 127.0.0.1:3000 -N -X POST -H 'Content-Type: text/plain' \ 17 | // --data 'Can you explain why dogs are better than cats?' 18 | // 19 | // Or consumed with fetch: 20 | // 21 | // fetch('http://localhost:3000', { 22 | // method: 'POST', 23 | // body: 'Tell me why dogs are better than cats', 24 | // }).then(async res => { 25 | // const decoder = new TextDecoder(); 26 | // for await (const chunk of res.body) { 27 | // console.log(`chunk: ${decoder.decode(chunk)}`); 28 | // } 29 | // }) 30 | // 31 | app.post('/', async (req: Request, res: Response) => { 32 | try { 33 | console.log('Received request:', req.body); 34 | 35 | const stream = await openai.chat.completions.create({ 36 | model: 'gpt-3.5-turbo', 37 | stream: true, 38 | messages: [{ role: 'user', content: req.body }], 39 | }); 40 | 41 | res.header('Content-Type', 'text/plain'); 42 | 43 | // Sends each content stream chunk-by-chunk, such that the client 44 | // ultimately receives a single string. 45 | for await (const chunk of stream) { 46 | res.write(chunk.choices[0]?.delta.content || ''); 47 | } 48 | 49 | res.end(); 50 | } catch (e) { 51 | console.error(e); 52 | } 53 | }); 54 | 55 | app.listen('3000', () => { 56 | console.log('Started proxy express server'); 57 | }); 58 | -------------------------------------------------------------------------------- /examples/stream.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const openai = new OpenAI(); 6 | 7 | async function main() { 8 | const runner = openai.chat.completions 9 | .stream({ 10 | model: 'gpt-3.5-turbo', 11 | messages: [{ role: 'user', content: 'Say this is a test' }], 12 | }) 13 | .on('message', (msg) => console.log(msg)) 14 | .on('content', (diff) => process.stdout.write(diff)); 15 | 16 | for await (const chunk of runner) { 17 | console.log('chunk', chunk); 18 | } 19 | 20 | const result = await runner.finalChatCompletion(); 21 | console.log(result); 22 | } 23 | 24 | main(); 25 | -------------------------------------------------------------------------------- /examples/text-to-speech.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | import { playAudio } from 'openai/helpers/audio'; 3 | 4 | const openai = new OpenAI(); 5 | 6 | const exampleText = ` 7 | I see skies of blue and clouds of white 8 | The bright blessed days, the dark sacred nights 9 | And I think to myself 10 | What a wonderful world 11 | `.trim(); 12 | 13 | async function main(): Promise { 14 | const response = await openai.audio.speech.create({ 15 | model: 'tts-1', 16 | voice: 'nova', 17 | input: exampleText, 18 | }); 19 | 20 | await playAudio(response); 21 | } 22 | 23 | main().catch(console.error); 24 | -------------------------------------------------------------------------------- /examples/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json" 3 | } 4 | -------------------------------------------------------------------------------- /examples/types.ts: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env -S npm run tsn -T 2 | 3 | import OpenAI from 'openai'; 4 | 5 | // gets API Key from environment variable OPENAI_API_KEY 6 | const openai = new OpenAI(); 7 | 8 | async function main() { 9 | // Explicit non streaming params type: 10 | const params: OpenAI.Chat.ChatCompletionCreateParams = { 11 | model: 'gpt-4', 12 | messages: [{ role: 'user', content: 'Say this is a test!' }], 13 | }; 14 | const completion = await openai.chat.completions.create(params); 15 | console.log(completion.choices[0]?.message?.content); 16 | 17 | // Explicit streaming params type: 18 | const streaming_params: OpenAI.Chat.ChatCompletionCreateParams = { 19 | model: 'gpt-4', 20 | messages: [{ role: 'user', content: 'Say this is a test!' }], 21 | stream: true, 22 | }; 23 | 24 | const stream = await openai.chat.completions.create(streaming_params); 25 | for await (const chunk of stream) { 26 | process.stdout.write(chunk.choices[0]?.delta?.content || ''); 27 | } 28 | process.stdout.write('\n'); 29 | } 30 | 31 | main(); 32 | -------------------------------------------------------------------------------- /examples/ui-generation.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | import { z } from 'zod'; 3 | import { zodResponseFormat } from 'openai/helpers/zod'; 4 | 5 | const openai = new OpenAI(); 6 | 7 | // `z.lazy()` can't infer recursive types so we have to explicitly 8 | // define the type ourselves here 9 | interface UI { 10 | type: 'div' | 'button' | 'header' | 'section' | 'field' | 'form'; 11 | label: string; 12 | children: Array; 13 | attributes: { 14 | value: string; 15 | name: string; 16 | }[]; 17 | } 18 | 19 | const UISchema: z.ZodType = z.lazy(() => 20 | z.object({ 21 | type: z.enum(['div', 'button', 'header', 'section', 'field', 'form']), 22 | label: z.string(), 23 | children: z.array(UISchema), 24 | attributes: z.array( 25 | z.object({ 26 | name: z.string(), 27 | value: z.string(), 28 | }), 29 | ), 30 | }), 31 | ); 32 | 33 | async function main() { 34 | const completion = await openai.chat.completions.parse({ 35 | model: 'gpt-4o-2024-08-06', 36 | messages: [ 37 | { 38 | role: 'system', 39 | content: 'You are a UI generator AI. Convert the user input into a UI.', 40 | }, 41 | { role: 'user', content: 'Make a User Profile Form' }, 42 | ], 43 | response_format: zodResponseFormat(UISchema, 'ui'), 44 | }); 45 | 46 | const message = completion.choices[0]!.message; 47 | const ui = message.parsed; 48 | console.dir(ui, { depth: 10 }); 49 | } 50 | 51 | main(); 52 | -------------------------------------------------------------------------------- /jest.config.ts: -------------------------------------------------------------------------------- 1 | import type { JestConfigWithTsJest } from 'ts-jest'; 2 | 3 | const config: JestConfigWithTsJest = { 4 | preset: 'ts-jest/presets/default-esm', 5 | testEnvironment: 'node', 6 | transform: { 7 | '^.+\\.(t|j)sx?$': ['@swc/jest', { sourceMaps: 'inline' }], 8 | }, 9 | moduleNameMapper: { 10 | '^openai$': '/src/index.ts', 11 | '^openai/(.*)$': '/src/$1', 12 | }, 13 | modulePathIgnorePatterns: [ 14 | '/ecosystem-tests/', 15 | '/dist/', 16 | '/deno/', 17 | '/deno_tests/', 18 | ], 19 | testPathIgnorePatterns: ['scripts'], 20 | // prettierPath: require.resolve('prettier-2'), 21 | }; 22 | 23 | export default config; 24 | -------------------------------------------------------------------------------- /jsr.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@openai/openai", 3 | "version": "5.0.1", 4 | "exports": { 5 | ".": "./index.ts", 6 | "./helpers/zod": "./helpers/zod.ts", 7 | "./beta/realtime/websocket": "./beta/realtime/websocket.ts" 8 | }, 9 | "imports": { 10 | "zod": "npm:zod@3" 11 | }, 12 | "publish": { 13 | "exclude": [ 14 | "!." 15 | ] 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /jsr.json.orig: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@openai/openai", 3 | <<<<<<< HEAD 4 | "version": "4.87.4", 5 | "exports": { 6 | ".": "./index.ts", 7 | "./helpers/zod": "./helpers/zod.ts", 8 | "./beta/realtime/websocket": "./beta/realtime/websocket.ts" 9 | }, 10 | "imports": { 11 | "zod": "npm:zod@3" 12 | }, 13 | ||||||| parent of 0603bcac (chore(internal): version bump (#1393)) 14 | "version": "4.87.3", 15 | "exports": "./index.ts", 16 | ======= 17 | "version": "4.87.4", 18 | "exports": "./index.ts", 19 | >>>>>>> 0603bcac (chore(internal): version bump (#1393)) 20 | "publish": { 21 | "exclude": [ 22 | "!." 23 | ] 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /release-please-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "packages": { 3 | ".": {} 4 | }, 5 | "$schema": "https://raw.githubusercontent.com/stainless-api/release-please/main/schemas/config.json", 6 | "include-v-in-tag": true, 7 | "include-component-in-tag": false, 8 | "versioning": "prerelease", 9 | "prerelease": true, 10 | "bump-minor-pre-major": true, 11 | "bump-patch-for-minor-pre-major": false, 12 | "pull-request-header": "Automated Release PR", 13 | "pull-request-title-pattern": "release: ${version}", 14 | "changelog-sections": [ 15 | { 16 | "type": "feat", 17 | "section": "Features" 18 | }, 19 | { 20 | "type": "fix", 21 | "section": "Bug Fixes" 22 | }, 23 | { 24 | "type": "perf", 25 | "section": "Performance Improvements" 26 | }, 27 | { 28 | "type": "revert", 29 | "section": "Reverts" 30 | }, 31 | { 32 | "type": "chore", 33 | "section": "Chores" 34 | }, 35 | { 36 | "type": "docs", 37 | "section": "Documentation" 38 | }, 39 | { 40 | "type": "style", 41 | "section": "Styles" 42 | }, 43 | { 44 | "type": "refactor", 45 | "section": "Refactors" 46 | }, 47 | { 48 | "type": "test", 49 | "section": "Tests", 50 | "hidden": true 51 | }, 52 | { 53 | "type": "build", 54 | "section": "Build System" 55 | }, 56 | { 57 | "type": "ci", 58 | "section": "Continuous Integration", 59 | "hidden": true 60 | } 61 | ], 62 | "release-type": "node", 63 | "extra-files": [ 64 | "src/version.ts", 65 | "README.md", 66 | { 67 | "type": "json", 68 | "path": "jsr.json", 69 | "jsonpath": "$.version" 70 | } 71 | ] 72 | } 73 | -------------------------------------------------------------------------------- /scripts/bootstrap: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | if [ -f "Brewfile" ] && [ "$(uname -s)" = "Darwin" ] && [ "$SKIP_BREW" != "1" ]; then 8 | brew bundle check >/dev/null 2>&1 || { 9 | echo "==> Installing Homebrew dependencies…" 10 | brew bundle 11 | } 12 | fi 13 | 14 | echo "==> Installing Node dependencies…" 15 | 16 | PACKAGE_MANAGER=$(command -v yarn >/dev/null 2>&1 && echo "yarn" || echo "npm") 17 | 18 | $PACKAGE_MANAGER install 19 | 20 | cd "$(dirname "$0")/../examples" 21 | $PACKAGE_MANAGER install -------------------------------------------------------------------------------- /scripts/build-deno: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -exuo pipefail 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | rm -rf dist-deno; mkdir dist-deno 8 | cp -rp src/* jsr.json dist-deno 9 | 10 | for file in README.md LICENSE CHANGELOG.md; do 11 | if [ -e "${file}" ]; then cp "${file}" dist-deno; fi 12 | done 13 | 14 | node scripts/utils/convert-jsr-readme.cjs ./dist-deno/README.md 15 | -------------------------------------------------------------------------------- /scripts/format: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | echo "==> Running eslint --fix" 8 | ./node_modules/.bin/eslint --fix . 9 | 10 | echo "==> Running prettier --write" 11 | # format things eslint didn't 12 | ./node_modules/.bin/prettier --write --cache --cache-strategy metadata . '!**/dist' '!**/*.ts' '!**/*.mts' '!**/*.cts' '!**/*.js' '!**/*.mjs' '!**/*.cjs' 13 | -------------------------------------------------------------------------------- /scripts/lint: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | echo "==> Running eslint" 8 | ./node_modules/.bin/eslint . 9 | 10 | echo "==> Building" 11 | ./scripts/build 12 | 13 | echo "==> Checking types" 14 | ./node_modules/typescript/bin/tsc 15 | 16 | echo "==> Running Are The Types Wrong?" 17 | ./node_modules/.bin/attw --pack dist -f json >.attw.json || true 18 | node scripts/utils/attw-report.cjs 19 | 20 | echo "==> Running publint" 21 | ./node_modules/.bin/publint dist 22 | -------------------------------------------------------------------------------- /scripts/mock: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | if [[ -n "$1" && "$1" != '--'* ]]; then 8 | URL="$1" 9 | shift 10 | else 11 | URL="$(grep 'openapi_spec_url' .stats.yml | cut -d' ' -f2)" 12 | fi 13 | 14 | # Check if the URL is empty 15 | if [ -z "$URL" ]; then 16 | echo "Error: No OpenAPI spec path/url provided or found in .stats.yml" 17 | exit 1 18 | fi 19 | 20 | echo "==> Starting mock server with URL ${URL}" 21 | 22 | # Run prism mock on the given spec 23 | if [ "$1" == "--daemon" ]; then 24 | npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL" &> .prism.log & 25 | 26 | # Wait for server to come online 27 | echo -n "Waiting for server" 28 | while ! grep -q "✖ fatal\|Prism is listening" ".prism.log" ; do 29 | echo -n "." 30 | sleep 0.1 31 | done 32 | 33 | if grep -q "✖ fatal" ".prism.log"; then 34 | cat .prism.log 35 | exit 1 36 | fi 37 | 38 | echo 39 | else 40 | npm exec --package=@stainless-api/prism-cli@5.8.5 -- prism mock "$URL" 41 | fi 42 | -------------------------------------------------------------------------------- /scripts/test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -e 4 | 5 | cd "$(dirname "$0")/.." 6 | 7 | RED='\033[0;31m' 8 | GREEN='\033[0;32m' 9 | YELLOW='\033[0;33m' 10 | NC='\033[0m' # No Color 11 | 12 | function prism_is_running() { 13 | curl --silent "http://localhost:4010" >/dev/null 2>&1 14 | } 15 | 16 | kill_server_on_port() { 17 | pids=$(lsof -t -i tcp:"$1" || echo "") 18 | if [ "$pids" != "" ]; then 19 | kill "$pids" 20 | echo "Stopped $pids." 21 | fi 22 | } 23 | 24 | function is_overriding_api_base_url() { 25 | [ -n "$TEST_API_BASE_URL" ] 26 | } 27 | 28 | if ! is_overriding_api_base_url && ! prism_is_running ; then 29 | # When we exit this script, make sure to kill the background mock server process 30 | trap 'kill_server_on_port 4010' EXIT 31 | 32 | # Start the dev server 33 | ./scripts/mock --daemon 34 | fi 35 | 36 | if is_overriding_api_base_url ; then 37 | echo -e "${GREEN}✔ Running tests against ${TEST_API_BASE_URL}${NC}" 38 | echo 39 | elif ! prism_is_running ; then 40 | echo -e "${RED}ERROR:${NC} The test suite will not run without a mock Prism server" 41 | echo -e "running against your OpenAPI spec." 42 | echo 43 | echo -e "To run the server, pass in the path or url of your OpenAPI" 44 | echo -e "spec to the prism command:" 45 | echo 46 | echo -e " \$ ${YELLOW}npm exec --package=@stoplight/prism-cli@~5.3.2 -- prism mock path/to/your.openapi.yml${NC}" 47 | echo 48 | 49 | exit 1 50 | else 51 | echo -e "${GREEN}✔ Mock prism server is running with your OpenAPI spec${NC}" 52 | echo 53 | fi 54 | 55 | echo "==> Running tests" 56 | ./node_modules/.bin/jest "$@" 57 | -------------------------------------------------------------------------------- /scripts/utils/attw-report.cjs: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const problems = Object.values(JSON.parse(fs.readFileSync('.attw.json', 'utf-8')).problems) 3 | .flat() 4 | .filter( 5 | (problem) => 6 | !( 7 | // This is intentional, if the user specifies .mjs they get ESM. 8 | ( 9 | (problem.kind === 'CJSResolvesToESM' && problem.entrypoint.endsWith('.mjs')) || 10 | // This is intentional for backwards compat reasons. 11 | (problem.kind === 'MissingExportEquals' && problem.implementationFileName.endsWith('/index.js')) || 12 | // this is intentional, we deliberately attempt to import types that may not exist from parent node_modules 13 | // folders to better support various runtimes without triggering automatic type acquisition. 14 | (problem.kind === 'InternalResolutionError' && problem.moduleSpecifier.includes('node_modules')) 15 | ) 16 | ), 17 | ); 18 | fs.unlinkSync('.attw.json'); 19 | if (problems.length) { 20 | process.stdout.write('The types are wrong!\n' + JSON.stringify(problems, null, 2) + '\n'); 21 | process.exitCode = 1; 22 | } else { 23 | process.stdout.write('Types ok!\n'); 24 | } 25 | -------------------------------------------------------------------------------- /scripts/utils/check-is-in-git-install.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # Check if you happen to call prepare for a repository that's already in node_modules. 3 | [ "$(basename "$(dirname "$PWD")")" = 'node_modules' ] || 4 | # The name of the containing directory that 'npm` uses, which looks like 5 | # $HOME/.npm/_cacache/git-cloneXXXXXX 6 | [ "$(basename "$(dirname "$PWD")")" = 'tmp' ] || 7 | # The name of the containing directory that 'yarn` uses, which looks like 8 | # $(yarn cache dir)/.tmp/XXXXX 9 | [ "$(basename "$(dirname "$PWD")")" = '.tmp' ] 10 | -------------------------------------------------------------------------------- /scripts/utils/check-version.cjs: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | 4 | const main = () => { 5 | const pkg = require('../../package.json'); 6 | const version = pkg['version']; 7 | if (!version) throw 'The version property is not set in the package.json file'; 8 | if (typeof version !== 'string') { 9 | throw `Unexpected type for the package.json version field; got ${typeof version}, expected string`; 10 | } 11 | 12 | const versionFile = path.resolve(__dirname, '..', '..', 'src', 'version.ts'); 13 | const contents = fs.readFileSync(versionFile, 'utf8'); 14 | const output = contents.replace(/(export const VERSION = ')(.*)(')/g, `$1${version}$3`); 15 | fs.writeFileSync(versionFile, output); 16 | }; 17 | 18 | if (require.main === module) { 19 | main(); 20 | } 21 | -------------------------------------------------------------------------------- /scripts/utils/fix-index-exports.cjs: -------------------------------------------------------------------------------- 1 | const fs = require('fs'); 2 | const path = require('path'); 3 | 4 | const indexJs = 5 | process.env['DIST_PATH'] ? 6 | path.resolve(process.env['DIST_PATH'], 'index.js') 7 | : path.resolve(__dirname, '..', '..', 'dist', 'index.js'); 8 | 9 | let before = fs.readFileSync(indexJs, 'utf8'); 10 | let after = before.replace( 11 | /^(\s*Object\.defineProperty\s*\(exports,\s*["']__esModule["'].+)$/m, 12 | `exports = module.exports = function (...args) { 13 | return new exports.default(...args) 14 | } 15 | $1`.replace(/^ /gm, ''), 16 | ); 17 | fs.writeFileSync(indexJs, after, 'utf8'); 18 | -------------------------------------------------------------------------------- /scripts/utils/git-swap.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -exuo pipefail 3 | # the package is published to NPM from ./dist 4 | # we want the final file structure for git installs to match the npm installs, so we 5 | 6 | # delete everything except ./dist and ./node_modules 7 | find . -maxdepth 1 -mindepth 1 ! -name 'dist' ! -name 'node_modules' -exec rm -rf '{}' + 8 | 9 | # move everything from ./dist to . 10 | mv dist/* . 11 | 12 | # delete the now-empty ./dist 13 | rmdir dist 14 | -------------------------------------------------------------------------------- /scripts/utils/make-dist-package-json.cjs: -------------------------------------------------------------------------------- 1 | const pkgJson = require(process.env['PKG_JSON_PATH'] || '../../package.json'); 2 | 3 | function processExportMap(m) { 4 | for (const key in m) { 5 | const value = m[key]; 6 | if (typeof value === 'string') m[key] = value.replace(/^\.\/dist\//, './'); 7 | else processExportMap(value); 8 | } 9 | } 10 | processExportMap(pkgJson.exports); 11 | 12 | for (const key of ['types', 'main', 'module']) { 13 | if (typeof pkgJson[key] === 'string') pkgJson[key] = pkgJson[key].replace(/^(\.\/)?dist\//, './'); 14 | } 15 | 16 | delete pkgJson.devDependencies; 17 | delete pkgJson.scripts.prepack; 18 | delete pkgJson.scripts.prepublishOnly; 19 | delete pkgJson.scripts.prepare; 20 | 21 | console.log(JSON.stringify(pkgJson, null, 2)); 22 | -------------------------------------------------------------------------------- /scripts/utils/upload-artifact.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -exuo pipefail 3 | 4 | RESPONSE=$(curl -X POST "$URL" \ 5 | -H "Authorization: Bearer $AUTH" \ 6 | -H "Content-Type: application/json") 7 | 8 | SIGNED_URL=$(echo "$RESPONSE" | jq -r '.url') 9 | 10 | if [[ "$SIGNED_URL" == "null" ]]; then 11 | echo -e "\033[31mFailed to get signed URL.\033[0m" 12 | exit 1 13 | fi 14 | 15 | UPLOAD_RESPONSE=$(tar -cz dist | curl -v -X PUT \ 16 | -H "Content-Type: application/gzip" \ 17 | --data-binary @- "$SIGNED_URL" 2>&1) 18 | 19 | if echo "$UPLOAD_RESPONSE" | grep -q "HTTP/[0-9.]* 200"; then 20 | echo -e "\033[32mUploaded build to Stainless storage.\033[0m" 21 | echo -e "\033[32mInstallation: npm install 'https://pkg.stainless.com/s/openai-typescript/$SHA'\033[0m" 22 | else 23 | echo -e "\033[31mFailed to upload artifact.\033[0m" 24 | exit 1 25 | fi 26 | -------------------------------------------------------------------------------- /src/_vendor/partial-json-parser/README.md: -------------------------------------------------------------------------------- 1 | # Partial JSON Parser 2 | 3 | Vendored from https://www.npmjs.com/package/partial-json with some modifications 4 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/LICENSE: -------------------------------------------------------------------------------- 1 | ISC License 2 | 3 | Copyright (c) 2020, Stefan Terdell 4 | 5 | Permission to use, copy, modify, and/or distribute this software for any 6 | purpose with or without fee is hereby granted, provided that the above 7 | copyright notice and this permission notice appear in all copies. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 10 | WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 11 | MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 12 | ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 13 | WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 14 | ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 15 | OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 16 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/README.md: -------------------------------------------------------------------------------- 1 | # Zod to Json Schema 2 | 3 | Vendored version of https://github.com/StefanTerdell/zod-to-json-schema that has been updated to generate JSON Schemas that are compatible with OpenAI's [strict mode](https://platform.openai.com/docs/guides/structured-outputs/supported-schemas) 4 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/Refs.ts: -------------------------------------------------------------------------------- 1 | import type { ZodTypeDef } from 'zod'; 2 | import { getDefaultOptions, Options, Targets } from './Options'; 3 | import { JsonSchema7Type } from './parseDef'; 4 | import { zodDef } from './util'; 5 | 6 | export type Refs = { 7 | seen: Map; 8 | /** 9 | * Set of all the `$ref`s we created, e.g. `Set(['#/$defs/ui'])` 10 | * this notable does not include any `definitions` that were 11 | * explicitly given as an option. 12 | */ 13 | seenRefs: Set; 14 | currentPath: string[]; 15 | propertyPath: string[] | undefined; 16 | } & Options; 17 | 18 | export type Seen = { 19 | def: ZodTypeDef; 20 | path: string[]; 21 | jsonSchema: JsonSchema7Type | undefined; 22 | }; 23 | 24 | export const getRefs = (options?: string | Partial>): Refs => { 25 | const _options = getDefaultOptions(options); 26 | const currentPath = 27 | _options.name !== undefined ? 28 | [..._options.basePath, _options.definitionPath, _options.name] 29 | : _options.basePath; 30 | return { 31 | ..._options, 32 | currentPath: currentPath, 33 | propertyPath: undefined, 34 | seenRefs: new Set(), 35 | seen: new Map( 36 | Object.entries(_options.definitions).map(([name, def]) => [ 37 | zodDef(def), 38 | { 39 | def: zodDef(def), 40 | path: [..._options.basePath, _options.definitionPath, name], 41 | // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. 42 | jsonSchema: undefined, 43 | }, 44 | ]), 45 | ), 46 | }; 47 | }; 48 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/errorMessages.ts: -------------------------------------------------------------------------------- 1 | import { JsonSchema7TypeUnion } from './parseDef'; 2 | import { Refs } from './Refs'; 3 | 4 | export type ErrorMessages = Partial< 5 | Omit<{ [key in keyof T]: string }, OmitProperties | 'type' | 'errorMessages'> 6 | >; 7 | 8 | export function addErrorMessage }>( 9 | res: T, 10 | key: keyof T, 11 | errorMessage: string | undefined, 12 | refs: Refs, 13 | ) { 14 | if (!refs?.errorMessages) return; 15 | if (errorMessage) { 16 | res.errorMessage = { 17 | ...res.errorMessage, 18 | [key]: errorMessage, 19 | }; 20 | } 21 | } 22 | 23 | export function setResponseValueAndErrors< 24 | Json7Type extends JsonSchema7TypeUnion & { 25 | errorMessage?: ErrorMessages; 26 | }, 27 | Key extends keyof Omit, 28 | >(res: Json7Type, key: Key, value: Json7Type[Key], errorMessage: string | undefined, refs: Refs) { 29 | res[key] = value; 30 | addErrorMessage(res, key, errorMessage, refs); 31 | } 32 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/index.ts: -------------------------------------------------------------------------------- 1 | export * from './Options'; 2 | export * from './Refs'; 3 | export * from './errorMessages'; 4 | export * from './parseDef'; 5 | export * from './parsers/any'; 6 | export * from './parsers/array'; 7 | export * from './parsers/bigint'; 8 | export * from './parsers/boolean'; 9 | export * from './parsers/branded'; 10 | export * from './parsers/catch'; 11 | export * from './parsers/date'; 12 | export * from './parsers/default'; 13 | export * from './parsers/effects'; 14 | export * from './parsers/enum'; 15 | export * from './parsers/intersection'; 16 | export * from './parsers/literal'; 17 | export * from './parsers/map'; 18 | export * from './parsers/nativeEnum'; 19 | export * from './parsers/never'; 20 | export * from './parsers/null'; 21 | export * from './parsers/nullable'; 22 | export * from './parsers/number'; 23 | export * from './parsers/object'; 24 | export * from './parsers/optional'; 25 | export * from './parsers/pipeline'; 26 | export * from './parsers/promise'; 27 | export * from './parsers/readonly'; 28 | export * from './parsers/record'; 29 | export * from './parsers/set'; 30 | export * from './parsers/string'; 31 | export * from './parsers/tuple'; 32 | export * from './parsers/undefined'; 33 | export * from './parsers/union'; 34 | export * from './parsers/unknown'; 35 | export * from './zodToJsonSchema'; 36 | import { zodToJsonSchema } from './zodToJsonSchema'; 37 | export default zodToJsonSchema; 38 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/any.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7AnyType = {}; 2 | 3 | export function parseAnyDef(): JsonSchema7AnyType { 4 | return {}; 5 | } 6 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/array.ts: -------------------------------------------------------------------------------- 1 | import { ZodArrayDef, ZodFirstPartyTypeKind } from 'zod'; 2 | import { ErrorMessages, setResponseValueAndErrors } from '../errorMessages'; 3 | import { JsonSchema7Type, parseDef } from '../parseDef'; 4 | import { Refs } from '../Refs'; 5 | 6 | export type JsonSchema7ArrayType = { 7 | type: 'array'; 8 | items?: JsonSchema7Type | undefined; 9 | minItems?: number; 10 | maxItems?: number; 11 | errorMessages?: ErrorMessages; 12 | }; 13 | 14 | export function parseArrayDef(def: ZodArrayDef, refs: Refs) { 15 | const res: JsonSchema7ArrayType = { 16 | type: 'array', 17 | }; 18 | if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { 19 | res.items = parseDef(def.type._def, { 20 | ...refs, 21 | currentPath: [...refs.currentPath, 'items'], 22 | }); 23 | } 24 | 25 | if (def.minLength) { 26 | setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs); 27 | } 28 | if (def.maxLength) { 29 | setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs); 30 | } 31 | if (def.exactLength) { 32 | setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs); 33 | setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs); 34 | } 35 | return res; 36 | } 37 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/boolean.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7BooleanType = { 2 | type: 'boolean'; 3 | }; 4 | 5 | export function parseBooleanDef(): JsonSchema7BooleanType { 6 | return { 7 | type: 'boolean', 8 | }; 9 | } 10 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/branded.ts: -------------------------------------------------------------------------------- 1 | import { ZodBrandedDef } from 'zod'; 2 | import { parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | 5 | export function parseBrandedDef(_def: ZodBrandedDef, refs: Refs) { 6 | return parseDef(_def.type._def, refs); 7 | } 8 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/catch.ts: -------------------------------------------------------------------------------- 1 | import { ZodCatchDef } from 'zod'; 2 | import { parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | 5 | export const parseCatchDef = (def: ZodCatchDef, refs: Refs) => { 6 | return parseDef(def.innerType._def, refs); 7 | }; 8 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/default.ts: -------------------------------------------------------------------------------- 1 | import { ZodDefaultDef } from 'zod'; 2 | import { JsonSchema7Type, parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | 5 | export function parseDefaultDef(_def: ZodDefaultDef, refs: Refs): JsonSchema7Type & { default: any } { 6 | return { 7 | ...parseDef(_def.innerType._def, refs), 8 | default: _def.defaultValue(), 9 | }; 10 | } 11 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/effects.ts: -------------------------------------------------------------------------------- 1 | import { ZodEffectsDef } from 'zod'; 2 | import { JsonSchema7Type, parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | 5 | export function parseEffectsDef( 6 | _def: ZodEffectsDef, 7 | refs: Refs, 8 | forceResolution: boolean, 9 | ): JsonSchema7Type | undefined { 10 | return refs.effectStrategy === 'input' ? parseDef(_def.schema._def, refs, forceResolution) : {}; 11 | } 12 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/enum.ts: -------------------------------------------------------------------------------- 1 | import { ZodEnumDef } from 'zod'; 2 | 3 | export type JsonSchema7EnumType = { 4 | type: 'string'; 5 | enum: string[]; 6 | }; 7 | 8 | export function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType { 9 | return { 10 | type: 'string', 11 | enum: [...def.values], 12 | }; 13 | } 14 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/literal.ts: -------------------------------------------------------------------------------- 1 | import { ZodLiteralDef } from 'zod'; 2 | import { Refs } from '../Refs'; 3 | 4 | export type JsonSchema7LiteralType = 5 | | { 6 | type: 'string' | 'number' | 'integer' | 'boolean'; 7 | const: string | number | boolean; 8 | } 9 | | { 10 | type: 'object' | 'array'; 11 | }; 12 | 13 | export function parseLiteralDef(def: ZodLiteralDef, refs: Refs): JsonSchema7LiteralType { 14 | const parsedType = typeof def.value; 15 | if ( 16 | parsedType !== 'bigint' && 17 | parsedType !== 'number' && 18 | parsedType !== 'boolean' && 19 | parsedType !== 'string' 20 | ) { 21 | return { 22 | type: Array.isArray(def.value) ? 'array' : 'object', 23 | }; 24 | } 25 | 26 | if (refs.target === 'openApi3') { 27 | return { 28 | type: parsedType === 'bigint' ? 'integer' : parsedType, 29 | enum: [def.value], 30 | } as any; 31 | } 32 | 33 | return { 34 | type: parsedType === 'bigint' ? 'integer' : parsedType, 35 | const: def.value, 36 | }; 37 | } 38 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/map.ts: -------------------------------------------------------------------------------- 1 | import { ZodMapDef } from 'zod'; 2 | import { JsonSchema7Type, parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | import { JsonSchema7RecordType, parseRecordDef } from './record'; 5 | 6 | export type JsonSchema7MapType = { 7 | type: 'array'; 8 | maxItems: 125; 9 | items: { 10 | type: 'array'; 11 | items: [JsonSchema7Type, JsonSchema7Type]; 12 | minItems: 2; 13 | maxItems: 2; 14 | }; 15 | }; 16 | 17 | export function parseMapDef(def: ZodMapDef, refs: Refs): JsonSchema7MapType | JsonSchema7RecordType { 18 | if (refs.mapStrategy === 'record') { 19 | return parseRecordDef(def, refs); 20 | } 21 | 22 | const keys = 23 | parseDef(def.keyType._def, { 24 | ...refs, 25 | currentPath: [...refs.currentPath, 'items', 'items', '0'], 26 | }) || {}; 27 | const values = 28 | parseDef(def.valueType._def, { 29 | ...refs, 30 | currentPath: [...refs.currentPath, 'items', 'items', '1'], 31 | }) || {}; 32 | return { 33 | type: 'array', 34 | maxItems: 125, 35 | items: { 36 | type: 'array', 37 | items: [keys, values], 38 | minItems: 2, 39 | maxItems: 2, 40 | }, 41 | }; 42 | } 43 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/nativeEnum.ts: -------------------------------------------------------------------------------- 1 | import { ZodNativeEnumDef } from 'zod'; 2 | 3 | export type JsonSchema7NativeEnumType = { 4 | type: 'string' | 'number' | ['string', 'number']; 5 | enum: (string | number)[]; 6 | }; 7 | 8 | export function parseNativeEnumDef(def: ZodNativeEnumDef): JsonSchema7NativeEnumType { 9 | const object = def.values; 10 | const actualKeys = Object.keys(def.values).filter((key: string) => { 11 | return typeof object[object[key]!] !== 'number'; 12 | }); 13 | 14 | const actualValues = actualKeys.map((key: string) => object[key]!); 15 | 16 | const parsedTypes = Array.from(new Set(actualValues.map((values: string | number) => typeof values))); 17 | 18 | return { 19 | type: 20 | parsedTypes.length === 1 ? 21 | parsedTypes[0] === 'string' ? 22 | 'string' 23 | : 'number' 24 | : ['string', 'number'], 25 | enum: actualValues, 26 | }; 27 | } 28 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/never.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7NeverType = { 2 | not: {}; 3 | }; 4 | 5 | export function parseNeverDef(): JsonSchema7NeverType { 6 | return { 7 | not: {}, 8 | }; 9 | } 10 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/null.ts: -------------------------------------------------------------------------------- 1 | import { Refs } from '../Refs'; 2 | 3 | export type JsonSchema7NullType = { 4 | type: 'null'; 5 | }; 6 | 7 | export function parseNullDef(refs: Refs): JsonSchema7NullType { 8 | return refs.target === 'openApi3' ? 9 | ({ 10 | enum: ['null'], 11 | nullable: true, 12 | } as any) 13 | : { 14 | type: 'null', 15 | }; 16 | } 17 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/nullable.ts: -------------------------------------------------------------------------------- 1 | import { ZodNullableDef } from 'zod'; 2 | import { JsonSchema7Type, parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | import { JsonSchema7NullType } from './null'; 5 | import { primitiveMappings } from './union'; 6 | 7 | export type JsonSchema7NullableType = 8 | | { 9 | anyOf: [JsonSchema7Type, JsonSchema7NullType]; 10 | } 11 | | { 12 | type: [string, 'null']; 13 | }; 14 | 15 | export function parseNullableDef(def: ZodNullableDef, refs: Refs): JsonSchema7NullableType | undefined { 16 | if ( 17 | ['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) && 18 | (!def.innerType._def.checks || !def.innerType._def.checks.length) 19 | ) { 20 | if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') { 21 | return { 22 | type: primitiveMappings[def.innerType._def.typeName as keyof typeof primitiveMappings], 23 | nullable: true, 24 | } as any; 25 | } 26 | 27 | return { 28 | type: [primitiveMappings[def.innerType._def.typeName as keyof typeof primitiveMappings], 'null'], 29 | }; 30 | } 31 | 32 | if (refs.target === 'openApi3') { 33 | const base = parseDef(def.innerType._def, { 34 | ...refs, 35 | currentPath: [...refs.currentPath], 36 | }); 37 | 38 | if (base && '$ref' in base) return { allOf: [base], nullable: true } as any; 39 | 40 | return base && ({ ...base, nullable: true } as any); 41 | } 42 | 43 | const base = parseDef(def.innerType._def, { 44 | ...refs, 45 | currentPath: [...refs.currentPath, 'anyOf', '0'], 46 | }); 47 | 48 | return base && { anyOf: [base, { type: 'null' }] }; 49 | } 50 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/optional.ts: -------------------------------------------------------------------------------- 1 | import { ZodOptionalDef } from 'zod'; 2 | import { JsonSchema7Type, parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | 5 | export const parseOptionalDef = (def: ZodOptionalDef, refs: Refs): JsonSchema7Type | undefined => { 6 | if (refs.currentPath.toString() === refs.propertyPath?.toString()) { 7 | return parseDef(def.innerType._def, refs); 8 | } 9 | 10 | const innerSchema = parseDef(def.innerType._def, { 11 | ...refs, 12 | currentPath: [...refs.currentPath, 'anyOf', '1'], 13 | }); 14 | 15 | return innerSchema ? 16 | { 17 | anyOf: [ 18 | { 19 | not: {}, 20 | }, 21 | innerSchema, 22 | ], 23 | } 24 | : {}; 25 | }; 26 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/pipeline.ts: -------------------------------------------------------------------------------- 1 | import { ZodPipelineDef } from 'zod'; 2 | import { JsonSchema7Type, parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | import { JsonSchema7AllOfType } from './intersection'; 5 | 6 | export const parsePipelineDef = ( 7 | def: ZodPipelineDef, 8 | refs: Refs, 9 | ): JsonSchema7AllOfType | JsonSchema7Type | undefined => { 10 | if (refs.pipeStrategy === 'input') { 11 | return parseDef(def.in._def, refs); 12 | } else if (refs.pipeStrategy === 'output') { 13 | return parseDef(def.out._def, refs); 14 | } 15 | 16 | const a = parseDef(def.in._def, { 17 | ...refs, 18 | currentPath: [...refs.currentPath, 'allOf', '0'], 19 | }); 20 | const b = parseDef(def.out._def, { 21 | ...refs, 22 | currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'], 23 | }); 24 | 25 | return { 26 | allOf: [a, b].filter((x): x is JsonSchema7Type => x !== undefined), 27 | }; 28 | }; 29 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/promise.ts: -------------------------------------------------------------------------------- 1 | import { ZodPromiseDef } from 'zod'; 2 | import { JsonSchema7Type, parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | 5 | export function parsePromiseDef(def: ZodPromiseDef, refs: Refs): JsonSchema7Type | undefined { 6 | return parseDef(def.type._def, refs); 7 | } 8 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/readonly.ts: -------------------------------------------------------------------------------- 1 | import { ZodReadonlyDef } from 'zod'; 2 | import { parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | 5 | export const parseReadonlyDef = (def: ZodReadonlyDef, refs: Refs) => { 6 | return parseDef(def.innerType._def, refs); 7 | }; 8 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/set.ts: -------------------------------------------------------------------------------- 1 | import { ZodSetDef } from 'zod'; 2 | import { ErrorMessages, setResponseValueAndErrors } from '../errorMessages'; 3 | import { JsonSchema7Type, parseDef } from '../parseDef'; 4 | import { Refs } from '../Refs'; 5 | 6 | export type JsonSchema7SetType = { 7 | type: 'array'; 8 | uniqueItems: true; 9 | items?: JsonSchema7Type | undefined; 10 | minItems?: number; 11 | maxItems?: number; 12 | errorMessage?: ErrorMessages; 13 | }; 14 | 15 | export function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType { 16 | const items = parseDef(def.valueType._def, { 17 | ...refs, 18 | currentPath: [...refs.currentPath, 'items'], 19 | }); 20 | 21 | const schema: JsonSchema7SetType = { 22 | type: 'array', 23 | uniqueItems: true, 24 | items, 25 | }; 26 | 27 | if (def.minSize) { 28 | setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs); 29 | } 30 | 31 | if (def.maxSize) { 32 | setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs); 33 | } 34 | 35 | return schema; 36 | } 37 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/tuple.ts: -------------------------------------------------------------------------------- 1 | import { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod'; 2 | import { JsonSchema7Type, parseDef } from '../parseDef'; 3 | import { Refs } from '../Refs'; 4 | 5 | export type JsonSchema7TupleType = { 6 | type: 'array'; 7 | minItems: number; 8 | items: JsonSchema7Type[]; 9 | } & ( 10 | | { 11 | maxItems: number; 12 | } 13 | | { 14 | additionalItems?: JsonSchema7Type | undefined; 15 | } 16 | ); 17 | 18 | export function parseTupleDef( 19 | def: ZodTupleDef, 20 | refs: Refs, 21 | ): JsonSchema7TupleType { 22 | if (def.rest) { 23 | return { 24 | type: 'array', 25 | minItems: def.items.length, 26 | items: def.items 27 | .map((x, i) => 28 | parseDef(x._def, { 29 | ...refs, 30 | currentPath: [...refs.currentPath, 'items', `${i}`], 31 | }), 32 | ) 33 | .reduce((acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]), []), 34 | additionalItems: parseDef(def.rest._def, { 35 | ...refs, 36 | currentPath: [...refs.currentPath, 'additionalItems'], 37 | }), 38 | }; 39 | } else { 40 | return { 41 | type: 'array', 42 | minItems: def.items.length, 43 | maxItems: def.items.length, 44 | items: def.items 45 | .map((x, i) => 46 | parseDef(x._def, { 47 | ...refs, 48 | currentPath: [...refs.currentPath, 'items', `${i}`], 49 | }), 50 | ) 51 | .reduce((acc: JsonSchema7Type[], x) => (x === undefined ? acc : [...acc, x]), []), 52 | }; 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/undefined.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7UndefinedType = { 2 | not: {}; 3 | }; 4 | 5 | export function parseUndefinedDef(): JsonSchema7UndefinedType { 6 | return { 7 | not: {}, 8 | }; 9 | } 10 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/parsers/unknown.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7UnknownType = {}; 2 | 3 | export function parseUnknownDef(): JsonSchema7UnknownType { 4 | return {}; 5 | } 6 | -------------------------------------------------------------------------------- /src/_vendor/zod-to-json-schema/util.ts: -------------------------------------------------------------------------------- 1 | import type { ZodSchema, ZodTypeDef } from 'zod'; 2 | 3 | export const zodDef = (zodSchema: ZodSchema | ZodTypeDef): ZodTypeDef => { 4 | return '_def' in zodSchema ? zodSchema._def : zodSchema; 5 | }; 6 | 7 | export function isEmptyObj(obj: Object | null | undefined): boolean { 8 | if (!obj) return true; 9 | for (const _k in obj) return false; 10 | return true; 11 | } 12 | -------------------------------------------------------------------------------- /src/api-promise.ts: -------------------------------------------------------------------------------- 1 | /** @deprecated Import from ./core/api-promise instead */ 2 | export * from './core/api-promise'; 3 | -------------------------------------------------------------------------------- /src/beta/realtime/index.ts: -------------------------------------------------------------------------------- 1 | export { OpenAIRealtimeError } from './internal-base'; 2 | -------------------------------------------------------------------------------- /src/core/README.md: -------------------------------------------------------------------------------- 1 | # `core` 2 | 3 | This directory holds public modules implementing non-resource-specific SDK functionality. 4 | -------------------------------------------------------------------------------- /src/core/resource.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import type { OpenAI } from '../client'; 4 | 5 | export class APIResource { 6 | protected _client: OpenAI; 7 | 8 | constructor(client: OpenAI) { 9 | this._client = client; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /src/core/uploads.ts: -------------------------------------------------------------------------------- 1 | export { type Uploadable } from '../internal/uploads'; 2 | export { toFile, type ToFileInput } from '../internal/to-file'; 3 | -------------------------------------------------------------------------------- /src/error.ts: -------------------------------------------------------------------------------- 1 | /** @deprecated Import from ./core/error instead */ 2 | export * from './core/error'; 3 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { OpenAI as default } from './client'; 4 | 5 | export { type Uploadable, toFile } from './core/uploads'; 6 | export { APIPromise } from './core/api-promise'; 7 | export { OpenAI, type ClientOptions } from './client'; 8 | export { PagePromise } from './core/pagination'; 9 | export { 10 | OpenAIError, 11 | APIError, 12 | APIConnectionError, 13 | APIConnectionTimeoutError, 14 | APIUserAbortError, 15 | NotFoundError, 16 | ConflictError, 17 | RateLimitError, 18 | BadRequestError, 19 | AuthenticationError, 20 | InternalServerError, 21 | PermissionDeniedError, 22 | UnprocessableEntityError, 23 | } from './core/error'; 24 | 25 | export { AzureOpenAI } from './azure'; 26 | -------------------------------------------------------------------------------- /src/internal/README.md: -------------------------------------------------------------------------------- 1 | # `internal` 2 | 3 | The modules in this directory are not importable outside this package and will change between releases. 4 | -------------------------------------------------------------------------------- /src/internal/errors.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export function isAbortError(err: unknown) { 4 | return ( 5 | typeof err === 'object' && 6 | err !== null && 7 | // Spec-compliant fetch implementations 8 | (('name' in err && (err as any).name === 'AbortError') || 9 | // Expo fetch 10 | ('message' in err && String((err as any).message).includes('FetchRequestCanceledException'))) 11 | ); 12 | } 13 | 14 | export const castToError = (err: any): Error => { 15 | if (err instanceof Error) return err; 16 | if (typeof err === 'object' && err !== null) { 17 | try { 18 | if (Object.prototype.toString.call(err) === '[object Error]') { 19 | // @ts-ignore - not all envs have native support for cause yet 20 | const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); 21 | if (err.stack) error.stack = err.stack; 22 | // @ts-ignore - not all envs have native support for cause yet 23 | if (err.cause && !error.cause) error.cause = err.cause; 24 | if (err.name) error.name = err.name; 25 | return error; 26 | } 27 | } catch {} 28 | try { 29 | return new Error(JSON.stringify(err)); 30 | } catch {} 31 | } 32 | return new Error(err); 33 | }; 34 | -------------------------------------------------------------------------------- /src/internal/qs/LICENSE.md: -------------------------------------------------------------------------------- 1 | BSD 3-Clause License 2 | 3 | Copyright (c) 2014, Nathan LaFreniere and other [contributors](https://github.com/puruvj/neoqs/graphs/contributors) All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 6 | 7 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 8 | 9 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 10 | 11 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 12 | 13 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 14 | -------------------------------------------------------------------------------- /src/internal/qs/README.md: -------------------------------------------------------------------------------- 1 | # qs 2 | 3 | This is a vendored version of [neoqs](https://github.com/PuruVJ/neoqs) which is a TypeScript rewrite of [qs](https://github.com/ljharb/qs), a query string library. 4 | -------------------------------------------------------------------------------- /src/internal/qs/formats.ts: -------------------------------------------------------------------------------- 1 | import type { Format } from './types'; 2 | 3 | export const default_format: Format = 'RFC3986'; 4 | export const formatters: Record string> = { 5 | RFC1738: (v: PropertyKey) => String(v).replace(/%20/g, '+'), 6 | RFC3986: (v: PropertyKey) => String(v), 7 | }; 8 | export const RFC1738 = 'RFC1738'; 9 | export const RFC3986 = 'RFC3986'; 10 | -------------------------------------------------------------------------------- /src/internal/qs/index.ts: -------------------------------------------------------------------------------- 1 | import { default_format, formatters, RFC1738, RFC3986 } from './formats'; 2 | 3 | const formats = { 4 | formatters, 5 | RFC1738, 6 | RFC3986, 7 | default: default_format, 8 | }; 9 | 10 | export { stringify } from './stringify'; 11 | export { formats }; 12 | 13 | export type { DefaultDecoder, DefaultEncoder, Format, ParseOptions, StringifyOptions } from './types'; 14 | -------------------------------------------------------------------------------- /src/internal/request-options.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import { NullableHeaders } from './headers'; 4 | 5 | import type { BodyInit } from './builtin-types'; 6 | import { Stream } from '../core/streaming'; 7 | import type { HTTPMethod, MergedRequestInit } from './types'; 8 | import { type HeadersLike } from './headers'; 9 | 10 | export type FinalRequestOptions = RequestOptions & { method: HTTPMethod; path: string }; 11 | 12 | export type RequestOptions = { 13 | method?: HTTPMethod; 14 | path?: string; 15 | query?: object | undefined | null; 16 | body?: unknown; 17 | headers?: HeadersLike; 18 | maxRetries?: number; 19 | stream?: boolean | undefined; 20 | timeout?: number; 21 | fetchOptions?: MergedRequestInit; 22 | signal?: AbortSignal | undefined | null; 23 | idempotencyKey?: string; 24 | 25 | __metadata?: Record; 26 | __binaryResponse?: boolean | undefined; 27 | __streamClass?: typeof Stream; 28 | }; 29 | 30 | export type EncodedContent = { bodyHeaders: HeadersLike; body: BodyInit }; 31 | export type RequestEncoder = (request: { headers: NullableHeaders; body: unknown }) => EncodedContent; 32 | 33 | export const FallbackEncoder: RequestEncoder = ({ headers, body }) => { 34 | return { 35 | bodyHeaders: { 36 | 'content-type': 'application/json', 37 | }, 38 | body: JSON.stringify(body), 39 | }; 40 | }; 41 | -------------------------------------------------------------------------------- /src/internal/shim-types.d.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | /** 4 | * Shims for types that we can't always rely on being available globally. 5 | * 6 | * Note: these only exist at the type-level, there is no corresponding runtime 7 | * version for any of these symbols. 8 | */ 9 | 10 | /** 11 | * In order to properly access the global `NodeJS` type, if it's available, we 12 | * need to make use of declaration shadowing. Without this, any checks for the 13 | * presence of `NodeJS.ReadableStream` will fail. 14 | */ 15 | declare namespace NodeJS { 16 | interface ReadableStream {} 17 | } 18 | 19 | type HasProperties = keyof T extends never ? false : true; 20 | 21 | // @ts-ignore 22 | type _ReadableStream = 23 | // @ts-ignore 24 | HasProperties extends true ? NodeJS.ReadableStream : ReadableStream; 25 | 26 | // @ts-ignore 27 | declare const _ReadableStream: unknown extends typeof ReadableStream ? never : typeof ReadableStream; 28 | export { _ReadableStream as ReadableStream }; 29 | -------------------------------------------------------------------------------- /src/internal/stream-utils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Most browsers don't yet have async iterable support for ReadableStream, 3 | * and Node has a very different way of reading bytes from its "ReadableStream". 4 | * 5 | * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 6 | */ 7 | export function ReadableStreamToAsyncIterable(stream: any): AsyncIterableIterator { 8 | if (stream[Symbol.asyncIterator]) return stream; 9 | 10 | const reader = stream.getReader(); 11 | return { 12 | async next() { 13 | try { 14 | const result = await reader.read(); 15 | if (result?.done) reader.releaseLock(); // release lock when stream becomes closed 16 | return result; 17 | } catch (e) { 18 | reader.releaseLock(); // release lock when stream becomes errored 19 | throw e; 20 | } 21 | }, 22 | async return() { 23 | const cancelPromise = reader.cancel(); 24 | reader.releaseLock(); 25 | await cancelPromise; 26 | return { done: true, value: undefined }; 27 | }, 28 | [Symbol.asyncIterator]() { 29 | return this; 30 | }, 31 | }; 32 | } 33 | -------------------------------------------------------------------------------- /src/internal/utils.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './utils/values'; 4 | export * from './utils/base64'; 5 | export * from './utils/env'; 6 | export * from './utils/log'; 7 | export * from './utils/uuid'; 8 | export * from './utils/sleep'; 9 | -------------------------------------------------------------------------------- /src/internal/utils/bytes.ts: -------------------------------------------------------------------------------- 1 | export function concatBytes(buffers: Uint8Array[]): Uint8Array { 2 | let length = 0; 3 | for (const buffer of buffers) { 4 | length += buffer.length; 5 | } 6 | const output = new Uint8Array(length); 7 | let index = 0; 8 | for (const buffer of buffers) { 9 | output.set(buffer, index); 10 | index += buffer.length; 11 | } 12 | 13 | return output; 14 | } 15 | 16 | let encodeUTF8_: (str: string) => Uint8Array; 17 | export function encodeUTF8(str: string) { 18 | let encoder; 19 | return ( 20 | encodeUTF8_ ?? 21 | ((encoder = new (globalThis as any).TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))) 22 | )(str); 23 | } 24 | 25 | let decodeUTF8_: (bytes: Uint8Array) => string; 26 | export function decodeUTF8(bytes: Uint8Array) { 27 | let decoder; 28 | return ( 29 | decodeUTF8_ ?? 30 | ((decoder = new (globalThis as any).TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))) 31 | )(bytes); 32 | } 33 | -------------------------------------------------------------------------------- /src/internal/utils/env.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | /** 4 | * Read an environment variable. 5 | * 6 | * Trims beginning and trailing whitespace. 7 | * 8 | * Will return undefined if the environment variable doesn't exist or cannot be accessed. 9 | */ 10 | export const readEnv = (env: string): string | undefined => { 11 | if (typeof (globalThis as any).process !== 'undefined') { 12 | return (globalThis as any).process.env?.[env]?.trim() ?? undefined; 13 | } 14 | if (typeof (globalThis as any).Deno !== 'undefined') { 15 | return (globalThis as any).Deno.env?.get?.(env)?.trim(); 16 | } 17 | return undefined; 18 | }; 19 | -------------------------------------------------------------------------------- /src/internal/utils/sleep.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); 4 | -------------------------------------------------------------------------------- /src/internal/utils/uuid.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | /** 4 | * https://stackoverflow.com/a/2117523 5 | */ 6 | export let uuid4 = function () { 7 | const { crypto } = globalThis as any; 8 | if (crypto?.randomUUID) { 9 | uuid4 = crypto.randomUUID.bind(crypto); 10 | return crypto.randomUUID(); 11 | } 12 | const u8 = new Uint8Array(1); 13 | const randomByte = crypto ? () => crypto.getRandomValues(u8)[0]! : () => (Math.random() * 0xff) & 0xff; 14 | return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => 15 | (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16), 16 | ); 17 | }; 18 | -------------------------------------------------------------------------------- /src/lib/.keep: -------------------------------------------------------------------------------- 1 | File generated from our OpenAPI spec by Stainless. 2 | 3 | This directory can be used to store custom files to expand the SDK. 4 | It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. 5 | -------------------------------------------------------------------------------- /src/lib/Util.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Like `Promise.allSettled()` but throws an error if any promises are rejected. 3 | */ 4 | export const allSettledWithThrow = async (promises: Promise[]): Promise => { 5 | const results = await Promise.allSettled(promises); 6 | const rejected = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected'); 7 | if (rejected.length) { 8 | for (const result of rejected) { 9 | console.error(result.reason); 10 | } 11 | 12 | throw new Error(`${rejected.length} promise(s) failed - see the above errors`); 13 | } 14 | 15 | // Note: TS was complaining about using `.filter().map()` here for some reason 16 | const values: R[] = []; 17 | for (const result of results) { 18 | if (result.status === 'fulfilled') { 19 | values.push(result.value); 20 | } 21 | } 22 | return values; 23 | }; 24 | -------------------------------------------------------------------------------- /src/lib/chatCompletionUtils.ts: -------------------------------------------------------------------------------- 1 | import { 2 | type ChatCompletionAssistantMessageParam, 3 | type ChatCompletionMessageParam, 4 | type ChatCompletionToolMessageParam, 5 | } from '../resources'; 6 | 7 | export const isAssistantMessage = ( 8 | message: ChatCompletionMessageParam | null | undefined, 9 | ): message is ChatCompletionAssistantMessageParam => { 10 | return message?.role === 'assistant'; 11 | }; 12 | 13 | export const isToolMessage = ( 14 | message: ChatCompletionMessageParam | null | undefined, 15 | ): message is ChatCompletionToolMessageParam => { 16 | return message?.role === 'tool'; 17 | }; 18 | 19 | export function isPresent(obj: T | null | undefined): obj is T { 20 | return obj != null; 21 | } 22 | -------------------------------------------------------------------------------- /src/pagination.ts: -------------------------------------------------------------------------------- 1 | /** @deprecated Import from ./core/pagination instead */ 2 | export * from './core/pagination'; 3 | -------------------------------------------------------------------------------- /src/resource.ts: -------------------------------------------------------------------------------- 1 | /** @deprecated Import from ./core/resource instead */ 2 | export * from './core/resource'; 3 | -------------------------------------------------------------------------------- /src/resources.ts: -------------------------------------------------------------------------------- 1 | export * from './resources/index'; 2 | -------------------------------------------------------------------------------- /src/resources/audio.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './audio/index'; 4 | -------------------------------------------------------------------------------- /src/resources/audio/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { Audio, type AudioModel, type AudioResponseFormat } from './audio'; 4 | export { Speech, type SpeechModel, type SpeechCreateParams } from './speech'; 5 | export { 6 | Transcriptions, 7 | type Transcription, 8 | type TranscriptionInclude, 9 | type TranscriptionSegment, 10 | type TranscriptionStreamEvent, 11 | type TranscriptionTextDeltaEvent, 12 | type TranscriptionTextDoneEvent, 13 | type TranscriptionVerbose, 14 | type TranscriptionWord, 15 | type TranscriptionCreateResponse, 16 | type TranscriptionCreateParams, 17 | type TranscriptionCreateParamsNonStreaming, 18 | type TranscriptionCreateParamsStreaming, 19 | } from './transcriptions'; 20 | export { 21 | Translations, 22 | type Translation, 23 | type TranslationVerbose, 24 | type TranslationCreateResponse, 25 | type TranslationCreateParams, 26 | } from './translations'; 27 | -------------------------------------------------------------------------------- /src/resources/beta.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './beta/index'; 4 | -------------------------------------------------------------------------------- /src/resources/beta/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { 4 | Assistants, 5 | type Assistant, 6 | type AssistantDeleted, 7 | type AssistantStreamEvent, 8 | type AssistantTool, 9 | type CodeInterpreterTool, 10 | type FileSearchTool, 11 | type FunctionTool, 12 | type MessageStreamEvent, 13 | type RunStepStreamEvent, 14 | type RunStreamEvent, 15 | type ThreadStreamEvent, 16 | type AssistantCreateParams, 17 | type AssistantUpdateParams, 18 | type AssistantListParams, 19 | type AssistantsPage, 20 | } from './assistants'; 21 | export { Beta } from './beta'; 22 | export { Realtime } from './realtime/index'; 23 | export { 24 | Threads, 25 | type AssistantResponseFormatOption, 26 | type AssistantToolChoice, 27 | type AssistantToolChoiceFunction, 28 | type AssistantToolChoiceOption, 29 | type Thread, 30 | type ThreadDeleted, 31 | type ThreadCreateParams, 32 | type ThreadUpdateParams, 33 | type ThreadCreateAndRunParams, 34 | type ThreadCreateAndRunParamsNonStreaming, 35 | type ThreadCreateAndRunParamsStreaming, 36 | type ThreadCreateAndRunPollParams, 37 | type ThreadCreateAndRunStreamParams, 38 | } from './threads/index'; 39 | -------------------------------------------------------------------------------- /src/resources/beta/realtime.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './realtime/index'; 4 | -------------------------------------------------------------------------------- /src/resources/beta/realtime/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { Realtime } from './realtime'; 4 | export { Sessions, type Session, type SessionCreateResponse, type SessionCreateParams } from './sessions'; 5 | export { 6 | TranscriptionSessions, 7 | type TranscriptionSession, 8 | type TranscriptionSessionCreateParams, 9 | } from './transcription-sessions'; 10 | -------------------------------------------------------------------------------- /src/resources/beta/threads.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './threads/index'; 4 | -------------------------------------------------------------------------------- /src/resources/beta/threads/runs.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './runs/index'; 4 | -------------------------------------------------------------------------------- /src/resources/beta/threads/runs/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { 4 | Runs, 5 | type RequiredActionFunctionToolCall, 6 | type Run, 7 | type RunStatus, 8 | type RunCreateParams, 9 | type RunCreateParamsNonStreaming, 10 | type RunCreateParamsStreaming, 11 | type RunRetrieveParams, 12 | type RunUpdateParams, 13 | type RunListParams, 14 | type RunCancelParams, 15 | type RunSubmitToolOutputsParams, 16 | type RunSubmitToolOutputsParamsNonStreaming, 17 | type RunSubmitToolOutputsParamsStreaming, 18 | type RunsPage, 19 | type RunCreateAndPollParams, 20 | type RunCreateAndStreamParams, 21 | type RunStreamParams, 22 | type RunSubmitToolOutputsAndPollParams, 23 | type RunSubmitToolOutputsStreamParams, 24 | } from './runs'; 25 | export { 26 | Steps, 27 | type CodeInterpreterLogs, 28 | type CodeInterpreterOutputImage, 29 | type CodeInterpreterToolCall, 30 | type CodeInterpreterToolCallDelta, 31 | type FileSearchToolCall, 32 | type FileSearchToolCallDelta, 33 | type FunctionToolCall, 34 | type FunctionToolCallDelta, 35 | type MessageCreationStepDetails, 36 | type RunStep, 37 | type RunStepInclude, 38 | type RunStepDelta, 39 | type RunStepDeltaEvent, 40 | type RunStepDeltaMessageDelta, 41 | type ToolCall, 42 | type ToolCallDelta, 43 | type ToolCallDeltaObject, 44 | type ToolCallsStepDetails, 45 | type StepRetrieveParams, 46 | type StepListParams, 47 | type RunStepsPage, 48 | } from './steps'; 49 | -------------------------------------------------------------------------------- /src/resources/chat.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './chat/index'; 4 | -------------------------------------------------------------------------------- /src/resources/chat/completions.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './completions/index'; 4 | -------------------------------------------------------------------------------- /src/resources/chat/completions/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { 4 | Completions, 5 | type ChatCompletion, 6 | type ChatCompletionAssistantMessageParam, 7 | type ChatCompletionAudio, 8 | type ChatCompletionAudioParam, 9 | type ChatCompletionChunk, 10 | type ChatCompletionContentPart, 11 | type ChatCompletionContentPartImage, 12 | type ChatCompletionContentPartInputAudio, 13 | type ChatCompletionContentPartRefusal, 14 | type ChatCompletionContentPartText, 15 | type ChatCompletionDeleted, 16 | type ChatCompletionDeveloperMessageParam, 17 | type ChatCompletionFunctionCallOption, 18 | type ChatCompletionFunctionMessageParam, 19 | type ChatCompletionMessage, 20 | type ChatCompletionMessageParam, 21 | type ChatCompletionMessageToolCall, 22 | type ChatCompletionModality, 23 | type ChatCompletionNamedToolChoice, 24 | type ChatCompletionPredictionContent, 25 | type ChatCompletionRole, 26 | type ChatCompletionStoreMessage, 27 | type ChatCompletionStreamOptions, 28 | type ChatCompletionSystemMessageParam, 29 | type ChatCompletionTokenLogprob, 30 | type ChatCompletionTool, 31 | type ChatCompletionToolChoiceOption, 32 | type ChatCompletionToolMessageParam, 33 | type ChatCompletionUserMessageParam, 34 | type ChatCompletionCreateParams, 35 | type ChatCompletionCreateParamsNonStreaming, 36 | type ChatCompletionCreateParamsStreaming, 37 | type ChatCompletionUpdateParams, 38 | type ChatCompletionListParams, 39 | type ChatCompletionStoreMessagesPage, 40 | type ChatCompletionsPage, 41 | } from './completions'; 42 | export * from './completions'; 43 | export { Messages, type MessageListParams } from './messages'; 44 | -------------------------------------------------------------------------------- /src/resources/chat/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { Chat } from './chat'; 4 | export { 5 | Completions, 6 | type ChatCompletion, 7 | type ChatCompletionAssistantMessageParam, 8 | type ChatCompletionAudio, 9 | type ChatCompletionAudioParam, 10 | type ChatCompletionChunk, 11 | type ChatCompletionContentPart, 12 | type ChatCompletionContentPartImage, 13 | type ChatCompletionContentPartInputAudio, 14 | type ChatCompletionContentPartRefusal, 15 | type ChatCompletionContentPartText, 16 | type ChatCompletionDeleted, 17 | type ChatCompletionDeveloperMessageParam, 18 | type ChatCompletionFunctionCallOption, 19 | type ChatCompletionFunctionMessageParam, 20 | type ChatCompletionMessage, 21 | type ChatCompletionMessageParam, 22 | type ChatCompletionMessageToolCall, 23 | type ChatCompletionModality, 24 | type ChatCompletionNamedToolChoice, 25 | type ChatCompletionPredictionContent, 26 | type ChatCompletionRole, 27 | type ChatCompletionStoreMessage, 28 | type ChatCompletionStreamOptions, 29 | type ChatCompletionSystemMessageParam, 30 | type ChatCompletionTokenLogprob, 31 | type ChatCompletionTool, 32 | type ChatCompletionToolChoiceOption, 33 | type ChatCompletionToolMessageParam, 34 | type ChatCompletionUserMessageParam, 35 | type ChatCompletionCreateParams, 36 | type ChatCompletionCreateParamsNonStreaming, 37 | type ChatCompletionCreateParamsStreaming, 38 | type ChatCompletionUpdateParams, 39 | type ChatCompletionListParams, 40 | type ChatCompletionStoreMessagesPage, 41 | type ChatCompletionsPage, 42 | } from './completions/index'; 43 | -------------------------------------------------------------------------------- /src/resources/containers.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './containers/index'; 4 | -------------------------------------------------------------------------------- /src/resources/containers/files.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './files/index'; 4 | -------------------------------------------------------------------------------- /src/resources/containers/files/content.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import { APIResource } from '../../../core/resource'; 4 | import { APIPromise } from '../../../core/api-promise'; 5 | import { buildHeaders } from '../../../internal/headers'; 6 | import { RequestOptions } from '../../../internal/request-options'; 7 | import { path } from '../../../internal/utils/path'; 8 | 9 | export class Content extends APIResource { 10 | /** 11 | * Retrieve Container File Content 12 | */ 13 | retrieve(fileID: string, params: ContentRetrieveParams, options?: RequestOptions): APIPromise { 14 | const { container_id } = params; 15 | return this._client.get(path`/containers/${container_id}/files/${fileID}/content`, { 16 | ...options, 17 | headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), 18 | __binaryResponse: true, 19 | }); 20 | } 21 | } 22 | 23 | export interface ContentRetrieveParams { 24 | container_id: string; 25 | } 26 | 27 | export declare namespace Content { 28 | export { type ContentRetrieveParams as ContentRetrieveParams }; 29 | } 30 | -------------------------------------------------------------------------------- /src/resources/containers/files/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { Content, type ContentRetrieveParams } from './content'; 4 | export { 5 | Files, 6 | type FileCreateResponse, 7 | type FileRetrieveResponse, 8 | type FileListResponse, 9 | type FileCreateParams, 10 | type FileRetrieveParams, 11 | type FileListParams, 12 | type FileDeleteParams, 13 | type FileListResponsesPage, 14 | } from './files'; 15 | -------------------------------------------------------------------------------- /src/resources/containers/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { 4 | Containers, 5 | type ContainerCreateResponse, 6 | type ContainerRetrieveResponse, 7 | type ContainerListResponse, 8 | type ContainerCreateParams, 9 | type ContainerListParams, 10 | type ContainerListResponsesPage, 11 | } from './containers'; 12 | export { 13 | Files, 14 | type FileCreateResponse, 15 | type FileRetrieveResponse, 16 | type FileListResponse, 17 | type FileCreateParams, 18 | type FileRetrieveParams, 19 | type FileListParams, 20 | type FileDeleteParams, 21 | type FileListResponsesPage, 22 | } from './files/index'; 23 | -------------------------------------------------------------------------------- /src/resources/evals.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './evals/index'; 4 | -------------------------------------------------------------------------------- /src/resources/evals/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { 4 | Evals, 5 | type EvalCustomDataSourceConfig, 6 | type EvalStoredCompletionsDataSourceConfig, 7 | type EvalCreateResponse, 8 | type EvalRetrieveResponse, 9 | type EvalUpdateResponse, 10 | type EvalListResponse, 11 | type EvalDeleteResponse, 12 | type EvalCreateParams, 13 | type EvalUpdateParams, 14 | type EvalListParams, 15 | type EvalListResponsesPage, 16 | } from './evals'; 17 | export { 18 | Runs, 19 | type CreateEvalCompletionsRunDataSource, 20 | type CreateEvalJSONLRunDataSource, 21 | type EvalAPIError, 22 | type RunCreateResponse, 23 | type RunRetrieveResponse, 24 | type RunListResponse, 25 | type RunDeleteResponse, 26 | type RunCancelResponse, 27 | type RunCreateParams, 28 | type RunRetrieveParams, 29 | type RunListParams, 30 | type RunDeleteParams, 31 | type RunCancelParams, 32 | type RunListResponsesPage, 33 | } from './runs/index'; 34 | -------------------------------------------------------------------------------- /src/resources/evals/runs.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './runs/index'; 4 | -------------------------------------------------------------------------------- /src/resources/evals/runs/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { 4 | OutputItems, 5 | type OutputItemRetrieveResponse, 6 | type OutputItemListResponse, 7 | type OutputItemRetrieveParams, 8 | type OutputItemListParams, 9 | type OutputItemListResponsesPage, 10 | } from './output-items'; 11 | export { 12 | Runs, 13 | type CreateEvalCompletionsRunDataSource, 14 | type CreateEvalJSONLRunDataSource, 15 | type EvalAPIError, 16 | type RunCreateResponse, 17 | type RunRetrieveResponse, 18 | type RunListResponse, 19 | type RunDeleteResponse, 20 | type RunCancelResponse, 21 | type RunCreateParams, 22 | type RunRetrieveParams, 23 | type RunListParams, 24 | type RunDeleteParams, 25 | type RunCancelParams, 26 | type RunListResponsesPage, 27 | } from './runs'; 28 | -------------------------------------------------------------------------------- /src/resources/fine-tuning.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './fine-tuning/index'; 4 | -------------------------------------------------------------------------------- /src/resources/fine-tuning/alpha.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './alpha/index'; 4 | -------------------------------------------------------------------------------- /src/resources/fine-tuning/alpha/alpha.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import { APIResource } from '../../../core/resource'; 4 | import * as GradersAPI from './graders'; 5 | import { 6 | GraderRunParams, 7 | GraderRunResponse, 8 | GraderValidateParams, 9 | GraderValidateResponse, 10 | Graders, 11 | } from './graders'; 12 | 13 | export class Alpha extends APIResource { 14 | graders: GradersAPI.Graders = new GradersAPI.Graders(this._client); 15 | } 16 | 17 | Alpha.Graders = Graders; 18 | 19 | export declare namespace Alpha { 20 | export { 21 | Graders as Graders, 22 | type GraderRunResponse as GraderRunResponse, 23 | type GraderValidateResponse as GraderValidateResponse, 24 | type GraderRunParams as GraderRunParams, 25 | type GraderValidateParams as GraderValidateParams, 26 | }; 27 | } 28 | -------------------------------------------------------------------------------- /src/resources/fine-tuning/alpha/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { Alpha } from './alpha'; 4 | export { 5 | Graders, 6 | type GraderRunResponse, 7 | type GraderValidateResponse, 8 | type GraderRunParams, 9 | type GraderValidateParams, 10 | } from './graders'; 11 | -------------------------------------------------------------------------------- /src/resources/fine-tuning/checkpoints.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './checkpoints/index'; 4 | -------------------------------------------------------------------------------- /src/resources/fine-tuning/checkpoints/checkpoints.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import { APIResource } from '../../../core/resource'; 4 | import * as PermissionsAPI from './permissions'; 5 | import { 6 | PermissionCreateParams, 7 | PermissionCreateResponse, 8 | PermissionCreateResponsesPage, 9 | PermissionDeleteParams, 10 | PermissionDeleteResponse, 11 | PermissionRetrieveParams, 12 | PermissionRetrieveResponse, 13 | Permissions, 14 | } from './permissions'; 15 | 16 | export class Checkpoints extends APIResource { 17 | permissions: PermissionsAPI.Permissions = new PermissionsAPI.Permissions(this._client); 18 | } 19 | 20 | Checkpoints.Permissions = Permissions; 21 | 22 | export declare namespace Checkpoints { 23 | export { 24 | Permissions as Permissions, 25 | type PermissionCreateResponse as PermissionCreateResponse, 26 | type PermissionRetrieveResponse as PermissionRetrieveResponse, 27 | type PermissionDeleteResponse as PermissionDeleteResponse, 28 | type PermissionCreateResponsesPage as PermissionCreateResponsesPage, 29 | type PermissionCreateParams as PermissionCreateParams, 30 | type PermissionRetrieveParams as PermissionRetrieveParams, 31 | type PermissionDeleteParams as PermissionDeleteParams, 32 | }; 33 | } 34 | -------------------------------------------------------------------------------- /src/resources/fine-tuning/checkpoints/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { Checkpoints } from './checkpoints'; 4 | export { 5 | Permissions, 6 | type PermissionCreateResponse, 7 | type PermissionRetrieveResponse, 8 | type PermissionDeleteResponse, 9 | type PermissionCreateParams, 10 | type PermissionRetrieveParams, 11 | type PermissionDeleteParams, 12 | type PermissionCreateResponsesPage, 13 | } from './permissions'; 14 | -------------------------------------------------------------------------------- /src/resources/fine-tuning/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { Alpha } from './alpha/index'; 4 | export { Checkpoints } from './checkpoints/index'; 5 | export { FineTuning } from './fine-tuning'; 6 | export { 7 | Jobs, 8 | type FineTuningJob, 9 | type FineTuningJobEvent, 10 | type FineTuningJobWandbIntegration, 11 | type FineTuningJobWandbIntegrationObject, 12 | type FineTuningJobIntegration, 13 | type JobCreateParams, 14 | type JobListParams, 15 | type JobListEventsParams, 16 | type FineTuningJobsPage, 17 | type FineTuningJobEventsPage, 18 | } from './jobs/index'; 19 | export { 20 | Methods, 21 | type DpoHyperparameters, 22 | type DpoMethod, 23 | type ReinforcementHyperparameters, 24 | type ReinforcementMethod, 25 | type SupervisedHyperparameters, 26 | type SupervisedMethod, 27 | } from './methods'; 28 | -------------------------------------------------------------------------------- /src/resources/fine-tuning/jobs.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './jobs/index'; 4 | -------------------------------------------------------------------------------- /src/resources/fine-tuning/jobs/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { 4 | Checkpoints, 5 | type FineTuningJobCheckpoint, 6 | type CheckpointListParams, 7 | type FineTuningJobCheckpointsPage, 8 | } from './checkpoints'; 9 | export { 10 | Jobs, 11 | type FineTuningJob, 12 | type FineTuningJobEvent, 13 | type FineTuningJobWandbIntegration, 14 | type FineTuningJobWandbIntegrationObject, 15 | type FineTuningJobIntegration, 16 | type JobCreateParams, 17 | type JobListParams, 18 | type JobListEventsParams, 19 | type FineTuningJobsPage, 20 | type FineTuningJobEventsPage, 21 | } from './jobs'; 22 | -------------------------------------------------------------------------------- /src/resources/graders.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './graders/index'; 4 | -------------------------------------------------------------------------------- /src/resources/graders/graders.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import { APIResource } from '../../core/resource'; 4 | import * as GraderModelsAPI from './grader-models'; 5 | import { 6 | GraderModels, 7 | LabelModelGrader, 8 | MultiGrader, 9 | PythonGrader, 10 | ScoreModelGrader, 11 | StringCheckGrader, 12 | TextSimilarityGrader, 13 | } from './grader-models'; 14 | 15 | export class Graders extends APIResource { 16 | graderModels: GraderModelsAPI.GraderModels = new GraderModelsAPI.GraderModels(this._client); 17 | } 18 | 19 | Graders.GraderModels = GraderModels; 20 | 21 | export declare namespace Graders { 22 | export { 23 | GraderModels as GraderModels, 24 | type LabelModelGrader as LabelModelGrader, 25 | type MultiGrader as MultiGrader, 26 | type PythonGrader as PythonGrader, 27 | type ScoreModelGrader as ScoreModelGrader, 28 | type StringCheckGrader as StringCheckGrader, 29 | type TextSimilarityGrader as TextSimilarityGrader, 30 | }; 31 | } 32 | -------------------------------------------------------------------------------- /src/resources/graders/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { 4 | GraderModels, 5 | type LabelModelGrader, 6 | type MultiGrader, 7 | type PythonGrader, 8 | type ScoreModelGrader, 9 | type StringCheckGrader, 10 | type TextSimilarityGrader, 11 | } from './grader-models'; 12 | export { Graders } from './graders'; 13 | -------------------------------------------------------------------------------- /src/resources/responses.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './responses/index'; 4 | -------------------------------------------------------------------------------- /src/resources/responses/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { InputItems, type ResponseItemList, type InputItemListParams } from './input-items'; 4 | export { Responses } from './responses'; 5 | -------------------------------------------------------------------------------- /src/resources/uploads.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './uploads/index'; 4 | -------------------------------------------------------------------------------- /src/resources/uploads/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { Parts, type UploadPart, type PartCreateParams } from './parts'; 4 | export { Uploads, type Upload, type UploadCreateParams, type UploadCompleteParams } from './uploads'; 5 | -------------------------------------------------------------------------------- /src/resources/vector-stores.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export * from './vector-stores/index'; 4 | -------------------------------------------------------------------------------- /src/resources/vector-stores/index.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | export { 4 | FileBatches, 5 | type VectorStoreFileBatch, 6 | type FileBatchCreateParams, 7 | type FileBatchRetrieveParams, 8 | type FileBatchCancelParams, 9 | type FileBatchListFilesParams, 10 | } from './file-batches'; 11 | export { 12 | Files, 13 | type VectorStoreFile, 14 | type VectorStoreFileDeleted, 15 | type FileContentResponse, 16 | type FileCreateParams, 17 | type FileRetrieveParams, 18 | type FileUpdateParams, 19 | type FileListParams, 20 | type FileDeleteParams, 21 | type FileContentParams, 22 | type VectorStoreFilesPage, 23 | type FileContentResponsesPage, 24 | } from './files'; 25 | export { 26 | VectorStores, 27 | type AutoFileChunkingStrategyParam, 28 | type FileChunkingStrategy, 29 | type FileChunkingStrategyParam, 30 | type OtherFileChunkingStrategyObject, 31 | type StaticFileChunkingStrategy, 32 | type StaticFileChunkingStrategyObject, 33 | type StaticFileChunkingStrategyObjectParam, 34 | type VectorStore, 35 | type VectorStoreDeleted, 36 | type VectorStoreSearchResponse, 37 | type VectorStoreCreateParams, 38 | type VectorStoreUpdateParams, 39 | type VectorStoreListParams, 40 | type VectorStoreSearchParams, 41 | type VectorStoresPage, 42 | type VectorStoreSearchResponsesPage, 43 | } from './vector-stores'; 44 | -------------------------------------------------------------------------------- /src/streaming.ts: -------------------------------------------------------------------------------- 1 | /** @deprecated Import from ./core/streaming instead */ 2 | export * from './core/streaming'; 3 | -------------------------------------------------------------------------------- /src/uploads.ts: -------------------------------------------------------------------------------- 1 | /** @deprecated Import from ./core/uploads instead */ 2 | export * from './core/uploads'; 3 | -------------------------------------------------------------------------------- /src/version.ts: -------------------------------------------------------------------------------- 1 | export const VERSION = '5.0.1'; // x-release-please-version 2 | -------------------------------------------------------------------------------- /tests/api-resources/audio/speech.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource speech', () => { 11 | // binary tests are currently broken 12 | test.skip('create: required and optional params', async () => { 13 | const response = await client.audio.speech.create({ 14 | input: 'input', 15 | model: 'string', 16 | voice: 'ash', 17 | instructions: 'instructions', 18 | response_format: 'mp3', 19 | speed: 0.25, 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /tests/api-resources/audio/transcriptions.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI, { toFile } from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource transcriptions', () => { 11 | test('create: only required params', async () => { 12 | const responsePromise = client.audio.transcriptions.create({ 13 | file: await toFile(Buffer.from('# my file contents'), 'README.md'), 14 | model: 'gpt-4o-transcribe', 15 | }); 16 | const rawResponse = await responsePromise.asResponse(); 17 | expect(rawResponse).toBeInstanceOf(Response); 18 | const response = await responsePromise; 19 | expect(response).not.toBeInstanceOf(Response); 20 | const dataAndResponse = await responsePromise.withResponse(); 21 | expect(dataAndResponse.data).toBe(response); 22 | expect(dataAndResponse.response).toBe(rawResponse); 23 | }); 24 | 25 | test('create: required and optional params', async () => { 26 | const response = await client.audio.transcriptions.create({ 27 | file: await toFile(Buffer.from('# my file contents'), 'README.md'), 28 | model: 'gpt-4o-transcribe', 29 | chunking_strategy: 'auto', 30 | include: ['logprobs'], 31 | language: 'language', 32 | prompt: 'prompt', 33 | response_format: 'json', 34 | stream: false, 35 | temperature: 0, 36 | timestamp_granularities: ['word'], 37 | }); 38 | }); 39 | }); 40 | -------------------------------------------------------------------------------- /tests/api-resources/audio/translations.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI, { toFile } from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource translations', () => { 11 | test('create: only required params', async () => { 12 | const responsePromise = client.audio.translations.create({ 13 | file: await toFile(Buffer.from('# my file contents'), 'README.md'), 14 | model: 'whisper-1', 15 | }); 16 | const rawResponse = await responsePromise.asResponse(); 17 | expect(rawResponse).toBeInstanceOf(Response); 18 | const response = await responsePromise; 19 | expect(response).not.toBeInstanceOf(Response); 20 | const dataAndResponse = await responsePromise.withResponse(); 21 | expect(dataAndResponse.data).toBe(response); 22 | expect(dataAndResponse.response).toBe(rawResponse); 23 | }); 24 | 25 | test('create: required and optional params', async () => { 26 | const response = await client.audio.translations.create({ 27 | file: await toFile(Buffer.from('# my file contents'), 'README.md'), 28 | model: 'whisper-1', 29 | prompt: 'prompt', 30 | response_format: 'json', 31 | temperature: 0, 32 | }); 33 | }); 34 | }); 35 | -------------------------------------------------------------------------------- /tests/api-resources/beta/realtime/sessions.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource sessions', () => { 11 | test('create', async () => { 12 | const responsePromise = client.beta.realtime.sessions.create({}); 13 | const rawResponse = await responsePromise.asResponse(); 14 | expect(rawResponse).toBeInstanceOf(Response); 15 | const response = await responsePromise; 16 | expect(response).not.toBeInstanceOf(Response); 17 | const dataAndResponse = await responsePromise.withResponse(); 18 | expect(dataAndResponse.data).toBe(response); 19 | expect(dataAndResponse.response).toBe(rawResponse); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /tests/api-resources/beta/realtime/transcription-sessions.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource transcriptionSessions', () => { 11 | test('create', async () => { 12 | const responsePromise = client.beta.realtime.transcriptionSessions.create({}); 13 | const rawResponse = await responsePromise.asResponse(); 14 | expect(rawResponse).toBeInstanceOf(Response); 15 | const response = await responsePromise; 16 | expect(response).not.toBeInstanceOf(Response); 17 | const dataAndResponse = await responsePromise.withResponse(); 18 | expect(dataAndResponse.data).toBe(response); 19 | expect(dataAndResponse.response).toBe(rawResponse); 20 | }); 21 | }); 22 | -------------------------------------------------------------------------------- /tests/api-resources/chat/completions/messages.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource messages', () => { 11 | test('list', async () => { 12 | const responsePromise = client.chat.completions.messages.list('completion_id'); 13 | const rawResponse = await responsePromise.asResponse(); 14 | expect(rawResponse).toBeInstanceOf(Response); 15 | const response = await responsePromise; 16 | expect(response).not.toBeInstanceOf(Response); 17 | const dataAndResponse = await responsePromise.withResponse(); 18 | expect(dataAndResponse.data).toBe(response); 19 | expect(dataAndResponse.response).toBe(rawResponse); 20 | }); 21 | 22 | test('list: request options and params are passed correctly', async () => { 23 | // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error 24 | await expect( 25 | client.chat.completions.messages.list( 26 | 'completion_id', 27 | { after: 'after', limit: 0, order: 'asc' }, 28 | { path: '/_stainless_unknown_path' }, 29 | ), 30 | ).rejects.toThrow(OpenAI.NotFoundError); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /tests/api-resources/completions.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource completions', () => { 11 | test('create: only required params', async () => { 12 | const responsePromise = client.completions.create({ model: 'string', prompt: 'This is a test.' }); 13 | const rawResponse = await responsePromise.asResponse(); 14 | expect(rawResponse).toBeInstanceOf(Response); 15 | const response = await responsePromise; 16 | expect(response).not.toBeInstanceOf(Response); 17 | const dataAndResponse = await responsePromise.withResponse(); 18 | expect(dataAndResponse.data).toBe(response); 19 | expect(dataAndResponse.response).toBe(rawResponse); 20 | }); 21 | 22 | test('create: required and optional params', async () => { 23 | const response = await client.completions.create({ 24 | model: 'string', 25 | prompt: 'This is a test.', 26 | best_of: 0, 27 | echo: true, 28 | frequency_penalty: -2, 29 | logit_bias: { foo: 0 }, 30 | logprobs: 0, 31 | max_tokens: 16, 32 | n: 1, 33 | presence_penalty: -2, 34 | seed: 0, 35 | stop: '\n', 36 | stream: false, 37 | stream_options: { include_usage: true }, 38 | suffix: 'test.', 39 | temperature: 1, 40 | top_p: 1, 41 | user: 'user-1234', 42 | }); 43 | }); 44 | }); 45 | -------------------------------------------------------------------------------- /tests/api-resources/containers/files/content.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource content', () => { 11 | test('retrieve: required and optional params', async () => { 12 | const response = await client.containers.files.content.retrieve('file_id', { 13 | container_id: 'container_id', 14 | }); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /tests/api-resources/embeddings-base64-response.json: -------------------------------------------------------------------------------- 1 | {"object":"list","data":[{"object":"embedding","index":0,"embedding":"A1fLvaC4Bb0QB7w8yEvrPOm9Xj2r0yA8EW4sPRq75j3Fbiq81/chPumAGb0afqG8R6AFvpzsQT35SPO7Hi39PEMAir1lf0A92McfvRoVlLxQv9o9tHqIvQYlrL0fwlK8sufPPYz2gjzH5Ho93GebvN+eCTxjRjW8PJRKvXMtFD4+n3C9ByMPO39Gkjs1Jm49A1fLPdNXpjv8RLm92McfveKpLz01VNO9SUIevhAHvD0flG09+9srvW5j7Txp8dY8LW4Ju08bJb1GdL29g+aNPWlLBD1p8dY8LkCkvfPLtjxcBj4+1/ehPebv/bz/Ifo8SqkOvREFHzyAr588HbUPPbFS+r00gri825WAPQlcGj1qHZ+8o8EOPo880Tn5dli9zRUSPc2APD0b5RG9mhxEvTyUSj3FQMU95u/9vE20tD3wwBC94NmxvXSUhL3Ofh8904WLPRbeJb2Paja8BClmvhwgOj2e6Ic9em0LPdj1BD3lSau7dJQEPJi107yB6kc97sTKO6lAaD2YDwE9YDuPPSFVC735dtg9SK1IOysJNrwtQkE8BmJxPb2ZXT0hVYs9g+YNvLfuuz2nyhe9z7nHN5UVWDxea5E77F1avTIbyL256oG9ft+hPVWJAbwNoug82TCtvUrm072wgN86JPWGO3TRyTwOY4a8xJwPvkx5DL1f1B68RwkTvja7Q72BrQI9Pfs6PTdfeb3RxG09jJxVvfl22D3eCbQ9FbR6vTPtYrn0mzS+kqGkPDxXhbwyG8i98M9wveayuL1EpL88lNqvve3yL70RQmQ7VcZGPaPBjr1wyEA9fKaWOskMibwNomi8J9Rku9EeGz016Si8O1mivQ38lb0EgxO88P1VvcilmLuNA0a9lj8DvHCceD3lSSs9uFWsve6HBT6XEZ68ShS5PFJSE70dTIK86OvDvSNgsbzS8DU8bPz8PAuVpTxKQIE9/NmOPBhFFj7LsL67PJRKvIxu8LwSqVS8D8yTPSOOlj1g0gG8A+69vYz2AjxPhLK80fLSPbrL/LztWz09LAcZvqfKF73B/JO8lnzIvCk5OLxwMU69dmQCvQtp3bs6hwe9WZKKume4S7x3CLg9zK4hPLsjDT16P6a7MbTXPRp+IT0dtQ89GayGvcngwD2F8bO70R4bu8tFlDxcBr67xAWdvdnWfzzQTIC9zn6fPYSKwz3alx28h8GxPW74wj3eNxk+xUBFvIpjyj0WdRi9AkoIPXhvqLugx+U8F0ezvUlCHjx3NAC9uvlhPEOmXD36oAM9D56uvddgrz2giiC9GhWUvHrWGLv0yRk8fOPbvMc+KLs7//S8v5UjPJUV2D0KLjW6YKa5PDciNDuJznQ9USZLPQ=="}],"model":"text-embedding-3-large","usage":{"prompt_tokens":1,"total_tokens":1}} -------------------------------------------------------------------------------- /tests/api-resources/fine-tuning/jobs/checkpoints.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource checkpoints', () => { 11 | test('list', async () => { 12 | const responsePromise = client.fineTuning.jobs.checkpoints.list('ft-AF1WoRqd3aJAHsqc9NY7iL8F'); 13 | const rawResponse = await responsePromise.asResponse(); 14 | expect(rawResponse).toBeInstanceOf(Response); 15 | const response = await responsePromise; 16 | expect(response).not.toBeInstanceOf(Response); 17 | const dataAndResponse = await responsePromise.withResponse(); 18 | expect(dataAndResponse.data).toBe(response); 19 | expect(dataAndResponse.response).toBe(rawResponse); 20 | }); 21 | 22 | test('list: request options and params are passed correctly', async () => { 23 | // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error 24 | await expect( 25 | client.fineTuning.jobs.checkpoints.list( 26 | 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', 27 | { after: 'after', limit: 0 }, 28 | { path: '/_stainless_unknown_path' }, 29 | ), 30 | ).rejects.toThrow(OpenAI.NotFoundError); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /tests/api-resources/models.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource models', () => { 11 | test('retrieve', async () => { 12 | const responsePromise = client.models.retrieve('gpt-4o-mini'); 13 | const rawResponse = await responsePromise.asResponse(); 14 | expect(rawResponse).toBeInstanceOf(Response); 15 | const response = await responsePromise; 16 | expect(response).not.toBeInstanceOf(Response); 17 | const dataAndResponse = await responsePromise.withResponse(); 18 | expect(dataAndResponse.data).toBe(response); 19 | expect(dataAndResponse.response).toBe(rawResponse); 20 | }); 21 | 22 | test('list', async () => { 23 | const responsePromise = client.models.list(); 24 | const rawResponse = await responsePromise.asResponse(); 25 | expect(rawResponse).toBeInstanceOf(Response); 26 | const response = await responsePromise; 27 | expect(response).not.toBeInstanceOf(Response); 28 | const dataAndResponse = await responsePromise.withResponse(); 29 | expect(dataAndResponse.data).toBe(response); 30 | expect(dataAndResponse.response).toBe(rawResponse); 31 | }); 32 | 33 | test('delete', async () => { 34 | const responsePromise = client.models.delete('ft:gpt-4o-mini:acemeco:suffix:abc123'); 35 | const rawResponse = await responsePromise.asResponse(); 36 | expect(rawResponse).toBeInstanceOf(Response); 37 | const response = await responsePromise; 38 | expect(response).not.toBeInstanceOf(Response); 39 | const dataAndResponse = await responsePromise.withResponse(); 40 | expect(dataAndResponse.data).toBe(response); 41 | expect(dataAndResponse.response).toBe(rawResponse); 42 | }); 43 | }); 44 | -------------------------------------------------------------------------------- /tests/api-resources/moderations.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource moderations', () => { 11 | test('create: only required params', async () => { 12 | const responsePromise = client.moderations.create({ input: 'I want to kill them.' }); 13 | const rawResponse = await responsePromise.asResponse(); 14 | expect(rawResponse).toBeInstanceOf(Response); 15 | const response = await responsePromise; 16 | expect(response).not.toBeInstanceOf(Response); 17 | const dataAndResponse = await responsePromise.withResponse(); 18 | expect(dataAndResponse.data).toBe(response); 19 | expect(dataAndResponse.response).toBe(rawResponse); 20 | }); 21 | 22 | test('create: required and optional params', async () => { 23 | const response = await client.moderations.create({ input: 'I want to kill them.', model: 'string' }); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /tests/api-resources/responses/input-items.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource inputItems', () => { 11 | test('list', async () => { 12 | const responsePromise = client.responses.inputItems.list('response_id'); 13 | const rawResponse = await responsePromise.asResponse(); 14 | expect(rawResponse).toBeInstanceOf(Response); 15 | const response = await responsePromise; 16 | expect(response).not.toBeInstanceOf(Response); 17 | const dataAndResponse = await responsePromise.withResponse(); 18 | expect(dataAndResponse.data).toBe(response); 19 | expect(dataAndResponse.response).toBe(rawResponse); 20 | }); 21 | 22 | test('list: request options and params are passed correctly', async () => { 23 | // ensure the request options are being passed correctly by passing an invalid HTTP method in order to cause an error 24 | await expect( 25 | client.responses.inputItems.list( 26 | 'response_id', 27 | { after: 'after', before: 'before', include: ['file_search_call.results'], limit: 0, order: 'asc' }, 28 | { path: '/_stainless_unknown_path' }, 29 | ), 30 | ).rejects.toThrow(OpenAI.NotFoundError); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /tests/api-resources/uploads/parts.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import OpenAI, { toFile } from 'openai'; 4 | 5 | const client = new OpenAI({ 6 | apiKey: 'My API Key', 7 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 8 | }); 9 | 10 | describe('resource parts', () => { 11 | test('create: only required params', async () => { 12 | const responsePromise = client.uploads.parts.create('upload_abc123', { 13 | data: await toFile(Buffer.from('# my file contents'), 'README.md'), 14 | }); 15 | const rawResponse = await responsePromise.asResponse(); 16 | expect(rawResponse).toBeInstanceOf(Response); 17 | const response = await responsePromise; 18 | expect(response).not.toBeInstanceOf(Response); 19 | const dataAndResponse = await responsePromise.withResponse(); 20 | expect(dataAndResponse.data).toBe(response); 21 | expect(dataAndResponse.response).toBe(rawResponse); 22 | }); 23 | 24 | test('create: required and optional params', async () => { 25 | const response = await client.uploads.parts.create('upload_abc123', { 26 | data: await toFile(Buffer.from('# my file contents'), 'README.md'), 27 | }); 28 | }); 29 | }); 30 | -------------------------------------------------------------------------------- /tests/streaming/assistants/assistant.test.ts: -------------------------------------------------------------------------------- 1 | import OpenAI from 'openai'; 2 | import { AssistantStream } from 'openai/lib/AssistantStream'; 3 | 4 | const openai = new OpenAI({ 5 | apiKey: 'My API Key', 6 | baseURL: process.env['TEST_API_BASE_URL'] ?? 'http://127.0.0.1:4010', 7 | }); 8 | 9 | describe('assistant tests', () => { 10 | test('delta accumulation', () => { 11 | expect(AssistantStream.accumulateDelta({}, {})).toEqual({}); 12 | expect(AssistantStream.accumulateDelta({}, { a: 'apple' })).toEqual({ a: 'apple' }); 13 | 14 | // strings 15 | expect(AssistantStream.accumulateDelta({ a: 'foo' }, { a: ' bar' })).toEqual({ a: 'foo bar' }); 16 | 17 | // dictionaries 18 | expect(AssistantStream.accumulateDelta({ a: { foo: '1' } }, { a: { bar: '2' } })).toEqual({ 19 | a: { 20 | foo: '1', 21 | bar: '2', 22 | }, 23 | }); 24 | expect(AssistantStream.accumulateDelta({ a: { foo: 'hello,' } }, { a: { foo: ' world' } })).toEqual({ 25 | a: { foo: 'hello, world' }, 26 | }); 27 | 28 | expect(AssistantStream.accumulateDelta({}, { a: null })).toEqual({ a: null }); 29 | expect(AssistantStream.accumulateDelta({ a: null }, { a: 'apple' })).toEqual({ a: 'apple' }); 30 | expect(AssistantStream.accumulateDelta({ a: null }, { a: null })).toEqual({ a: null }); 31 | }); 32 | }); 33 | -------------------------------------------------------------------------------- /tests/stringifyQuery.test.ts: -------------------------------------------------------------------------------- 1 | // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. 2 | 3 | import { OpenAI } from 'openai'; 4 | 5 | const { stringifyQuery } = OpenAI.prototype as any; 6 | 7 | describe(stringifyQuery, () => { 8 | for (const [input, expected] of [ 9 | [{ a: '1', b: 2, c: true }, 'a=1&b=2&c=true'], 10 | [{ a: null, b: false, c: undefined }, 'a=&b=false'], 11 | [{ 'a/b': 1.28341 }, `${encodeURIComponent('a/b')}=1.28341`], 12 | [ 13 | { 'a/b': 'c/d', 'e=f': 'g&h' }, 14 | `${encodeURIComponent('a/b')}=${encodeURIComponent('c/d')}&${encodeURIComponent( 15 | 'e=f', 16 | )}=${encodeURIComponent('g&h')}`, 17 | ], 18 | ]) { 19 | it(`${JSON.stringify(input)} -> ${expected}`, () => { 20 | expect(stringifyQuery(input)).toEqual(expected); 21 | }); 22 | } 23 | }); 24 | -------------------------------------------------------------------------------- /tests/utils/typing.ts: -------------------------------------------------------------------------------- 1 | type Equal = (() => T extends X ? 1 : 2) extends () => T extends Y ? 1 : 2 ? true : false; 2 | 3 | export const expectType = (_expression: T): void => { 4 | return; 5 | }; 6 | 7 | export const compareType = (_expression: Equal): void => { 8 | return; 9 | }; 10 | -------------------------------------------------------------------------------- /tsc-multi.json: -------------------------------------------------------------------------------- 1 | { 2 | "targets": [ 3 | { "extname": ".js", "module": "commonjs", "shareHelpers": "internal/tslib.js" }, 4 | { "extname": ".mjs", "module": "esnext", "shareHelpers": "internal/tslib.mjs" } 5 | ], 6 | "projects": ["tsconfig.build.json"] 7 | } 8 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["dist/src"], 4 | "exclude": [], 5 | "compilerOptions": { 6 | "rootDir": "./dist/src", 7 | "paths": { 8 | "openai/*": ["dist/src/*"], 9 | "openai": ["dist/src/index.ts"] 10 | }, 11 | "noEmit": false, 12 | "declaration": true, 13 | "declarationMap": true, 14 | "outDir": "dist", 15 | "pretty": true, 16 | "sourceMap": true 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /tsconfig.deno.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "include": ["dist-deno"], 4 | "exclude": [], 5 | "compilerOptions": { 6 | "rootDir": "./dist-deno", 7 | "lib": ["es2020", "DOM"], 8 | "noEmit": true, 9 | "declaration": true, 10 | "declarationMap": true, 11 | "outDir": "dist-deno", 12 | "pretty": true, 13 | "sourceMap": true 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.dist-src.json: -------------------------------------------------------------------------------- 1 | { 2 | // this config is included in the published src directory to prevent TS errors 3 | // from appearing when users go to source, and VSCode opens the source .ts file 4 | // via declaration maps 5 | "include": ["index.ts"], 6 | "compilerOptions": { 7 | "target": "ES2015", 8 | "lib": ["DOM", "DOM.Iterable", "ES2018"], 9 | "moduleResolution": "node" 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src", "tests", "examples"], 3 | "exclude": [], 4 | "compilerOptions": { 5 | "target": "es2020", 6 | "lib": ["es2020"], 7 | "module": "commonjs", 8 | "moduleResolution": "node", 9 | "esModuleInterop": true, 10 | "baseUrl": "./", 11 | "paths": { 12 | "openai/*": ["src/*"], 13 | "openai": ["src/index.ts"] 14 | }, 15 | "noEmit": true, 16 | 17 | "resolveJsonModule": true, 18 | 19 | "forceConsistentCasingInFileNames": true, 20 | 21 | "strict": true, 22 | "noImplicitAny": true, 23 | "strictNullChecks": true, 24 | "strictFunctionTypes": true, 25 | "strictBindCallApply": true, 26 | "strictPropertyInitialization": true, 27 | "noImplicitThis": true, 28 | "noImplicitReturns": true, 29 | "alwaysStrict": true, 30 | "exactOptionalPropertyTypes": true, 31 | "noUncheckedIndexedAccess": true, 32 | "noImplicitOverride": true, 33 | "noPropertyAccessFromIndexSignature": true, 34 | "isolatedModules": true, 35 | 36 | "skipLibCheck": true 37 | } 38 | } 39 | --------------------------------------------------------------------------------