├── .eslintrc.cjs ├── .github ├── actions │ └── install-node-pnpm │ │ └── action.yml └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── .prettierignore ├── .prettierrc ├── extract-types.mjs ├── license ├── openai-types ├── _shims │ ├── MultipartBody.d.ts │ ├── auto │ │ ├── runtime-bun.d.ts │ │ ├── runtime-node.d.ts │ │ ├── runtime.d.ts │ │ ├── types-node.d.ts │ │ └── types.d.ts │ ├── bun-runtime.d.ts │ ├── index.d.ts │ ├── manual-types.d.ts │ ├── node-runtime.d.ts │ ├── node-types.d.ts │ ├── registry.d.ts │ ├── web-runtime.d.ts │ └── web-types.d.ts ├── _vendor │ ├── partial-json-parser │ │ └── parser.d.ts │ └── zod-to-json-schema │ │ ├── Options.d.ts │ │ ├── Refs.d.ts │ │ ├── errorMessages.d.ts │ │ ├── index.d.ts │ │ ├── parseDef.d.ts │ │ ├── parsers │ │ ├── any.d.ts │ │ ├── array.d.ts │ │ ├── bigint.d.ts │ │ ├── boolean.d.ts │ │ ├── branded.d.ts │ │ ├── catch.d.ts │ │ ├── date.d.ts │ │ ├── default.d.ts │ │ ├── effects.d.ts │ │ ├── enum.d.ts │ │ ├── intersection.d.ts │ │ ├── literal.d.ts │ │ ├── map.d.ts │ │ ├── nativeEnum.d.ts │ │ ├── never.d.ts │ │ ├── null.d.ts │ │ ├── nullable.d.ts │ │ ├── number.d.ts │ │ ├── object.d.ts │ │ ├── optional.d.ts │ │ ├── pipeline.d.ts │ │ ├── promise.d.ts │ │ ├── readonly.d.ts │ │ ├── record.d.ts │ │ ├── set.d.ts │ │ ├── string.d.ts │ │ ├── tuple.d.ts │ │ ├── undefined.d.ts │ │ ├── union.d.ts │ │ └── unknown.d.ts │ │ ├── util.d.ts │ │ └── zodToJsonSchema.d.ts ├── core.d.ts ├── error.d.ts ├── helpers │ └── zod.d.ts ├── index.d.ts ├── internal │ ├── decoders │ │ └── line.d.ts │ └── qs │ │ ├── formats.d.ts │ │ ├── index.d.ts │ │ ├── stringify.d.ts │ │ ├── types.d.ts │ │ └── utils.d.ts ├── lib │ ├── AbstractChatCompletionRunner.d.ts │ ├── AssistantStream.d.ts │ ├── ChatCompletionRunner.d.ts │ ├── ChatCompletionStream.d.ts │ ├── ChatCompletionStreamingRunner.d.ts │ ├── EventStream.d.ts │ ├── RunnableFunction.d.ts │ ├── Util.d.ts │ ├── chatCompletionUtils.d.ts │ ├── jsonschema.d.ts │ └── parser.d.ts ├── pagination.d.ts ├── resource.d.ts ├── resources │ ├── audio │ │ ├── audio.d.ts │ │ ├── index.d.ts │ │ ├── speech.d.ts │ │ ├── transcriptions.d.ts │ │ └── translations.d.ts │ ├── batches.d.ts │ ├── beta │ │ ├── assistants.d.ts │ │ ├── beta.d.ts │ │ ├── chat │ │ │ ├── chat.d.ts │ │ │ ├── completions.d.ts │ │ │ └── index.d.ts │ │ ├── index.d.ts │ │ ├── threads │ │ │ ├── index.d.ts │ │ │ ├── messages.d.ts │ │ │ ├── runs │ │ │ │ ├── index.d.ts │ │ │ │ ├── runs.d.ts │ │ │ │ └── steps.d.ts │ │ │ └── threads.d.ts │ │ └── vector-stores │ │ │ ├── file-batches.d.ts │ │ │ ├── files.d.ts │ │ │ ├── index.d.ts │ │ │ └── vector-stores.d.ts │ ├── chat │ │ ├── chat.d.ts │ │ ├── completions.d.ts │ │ └── index.d.ts │ ├── completions.d.ts │ ├── embeddings.d.ts │ ├── files.d.ts │ ├── fine-tuning │ │ ├── fine-tuning.d.ts │ │ ├── index.d.ts │ │ └── jobs │ │ │ ├── checkpoints.d.ts │ │ │ ├── index.d.ts │ │ │ └── jobs.d.ts │ ├── images.d.ts │ ├── index.d.ts │ ├── models.d.ts │ ├── moderations.d.ts │ ├── shared.d.ts │ └── uploads │ │ ├── index.d.ts │ │ ├── parts.d.ts │ │ └── uploads.d.ts ├── shims │ ├── node.d.ts │ └── web.d.ts ├── src │ └── _shims │ │ ├── auto │ │ └── types.d.ts │ │ ├── index.d.ts │ │ ├── manual-types.d.ts │ │ ├── node-types.d.ts │ │ └── web-types.d.ts ├── streaming.d.ts ├── uploads.d.ts └── version.d.ts ├── package.json ├── pnpm-lock.yaml ├── readme.md ├── src ├── errors.ts ├── fetch-api.ts ├── index.ts ├── openai-client.ts ├── streaming.ts └── types.ts ├── tsconfig.dist.json └── tsconfig.json /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | /** @type {import('eslint').Linter.Config} */ 2 | module.exports = { 3 | extends: ['@dexaai/eslint-config/node'], 4 | ignorePatterns: ['openai-types/', 'dist/', 'node_modules/'], 5 | rules: { 6 | '@typescript-eslint/ban-ts-comment': 'off', 7 | 'no-process-env': 'off', 8 | 'no-console': 'off', 9 | 'prefer-const': 'off', 10 | }, 11 | }; 12 | -------------------------------------------------------------------------------- /.github/actions/install-node-pnpm/action.yml: -------------------------------------------------------------------------------- 1 | name: 'Install Node and pnpm' 2 | description: 'Install Node and pnpm with caching for fast install' 3 | 4 | inputs: 5 | node-version: 6 | description: 'The version of Node to install' 7 | default: '20' 8 | required: false 9 | 10 | runs: 11 | using: 'composite' 12 | steps: 13 | - name: Install Node 14 | uses: actions/setup-node@v4 15 | with: 16 | node-version: ${{ inputs.node-version }} 17 | 18 | - name: Install pnpm 19 | uses: pnpm/action-setup@v4 20 | id: pnpm-install 21 | with: 22 | run_install: false 23 | 24 | - name: Get pnpm store directory 25 | id: pnpm-cache 26 | shell: bash 27 | run: | 28 | echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT 29 | 30 | - name: Setup pnpm cache 31 | uses: actions/cache@v4 32 | with: 33 | path: ${{ steps.pnpm-cache.outputs.STORE_PATH }} 34 | key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} 35 | restore-keys: | 36 | ${{ runner.os }}-pnpm-store- 37 | 38 | # Run install with optional filter if present 39 | - name: Install pnpm dependencies 40 | shell: bash 41 | run: pnpm install --frozen-lockfile 42 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | 9 | jobs: 10 | types: 11 | name: Types 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v4 15 | - uses: ./.github/actions/install-node-pnpm 16 | - run: pnpm run typecheck 17 | 18 | lint: 19 | name: Lint 20 | runs-on: ubuntu-latest 21 | steps: 22 | - uses: actions/checkout@v4 23 | - uses: ./.github/actions/install-node-pnpm 24 | - run: pnpm run lint 25 | 26 | format: 27 | name: Format 28 | runs-on: ubuntu-latest 29 | steps: 30 | - uses: actions/checkout@v4 31 | - uses: ./.github/actions/install-node-pnpm 32 | - run: pnpm run format 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | .env 4 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | enable-pre-post-scripts=true 2 | -------------------------------------------------------------------------------- /.prettierignore: -------------------------------------------------------------------------------- 1 | openai-types 2 | dist 3 | pnpm-lock.yaml 4 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "es5" 4 | } 5 | -------------------------------------------------------------------------------- /extract-types.mjs: -------------------------------------------------------------------------------- 1 | import fs from 'node:fs'; 2 | import path from 'node:path'; 3 | 4 | /** 5 | * This is used to extract the type declarations from the openai Node.js 6 | * package. Doing this allows it to be a devDependency instead of a dependency, 7 | * which greatly reduces the size of the final bundle. 8 | */ 9 | function extractTypes(srcDir, destDir) { 10 | if (!fs.existsSync(destDir)) { 11 | fs.mkdirSync(destDir, { recursive: true }); 12 | } 13 | 14 | const entries = fs.readdirSync(srcDir, { withFileTypes: true }); 15 | 16 | for (const entry of entries) { 17 | const srcPath = path.join(srcDir, entry.name); 18 | const destPath = path.join(destDir, entry.name); 19 | 20 | if (entry.isDirectory()) { 21 | extractTypes(srcPath, destPath); 22 | } else if (entry.isFile() && entry.name.endsWith('.d.ts')) { 23 | const depth = Math.max(0, destPath.split('/').length - 2); 24 | const relativePath = depth > 0 ? '../'.repeat(depth) : './'; 25 | 26 | // OpenAI has some absolute package imports, so switch them to use relative imports. 27 | const content = fs 28 | .readFileSync(srcPath, 'utf8') 29 | .replaceAll(/'openai\/([^'.]*)'/g, `'${relativePath}$1.js'`); 30 | fs.writeFileSync(destPath, content); 31 | console.log(destPath); 32 | } 33 | } 34 | } 35 | 36 | extractTypes('node_modules/openai', 'openai-types'); 37 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Dexa 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /openai-types/_shims/MultipartBody.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | export declare class MultipartBody { 5 | body: any; 6 | constructor(body: any); 7 | get [Symbol.toStringTag](): string; 8 | } 9 | //# sourceMappingURL=MultipartBody.d.ts.map -------------------------------------------------------------------------------- /openai-types/_shims/auto/runtime-bun.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | export * from "../bun-runtime.js"; 5 | //# sourceMappingURL=runtime-bun.d.ts.map -------------------------------------------------------------------------------- /openai-types/_shims/auto/runtime-node.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | export * from "../node-runtime.js"; 5 | //# sourceMappingURL=runtime-node.d.ts.map -------------------------------------------------------------------------------- /openai-types/_shims/auto/runtime.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | export * from "../web-runtime.js"; 5 | //# sourceMappingURL=runtime.d.ts.map -------------------------------------------------------------------------------- /openai-types/_shims/auto/types-node.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | export * from "../node-types.js"; 5 | //# sourceMappingURL=types-node.d.ts.map -------------------------------------------------------------------------------- /openai-types/_shims/auto/types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | export type Agent = any; 5 | 6 | // @ts-ignore 7 | declare const _fetch: unknown extends typeof fetch ? never : typeof fetch; 8 | export { _fetch as fetch }; 9 | 10 | // @ts-ignore 11 | type _Request = unknown extends Request ? never : Request; 12 | export { _Request as Request }; 13 | 14 | // @ts-ignore 15 | type _RequestInfo = unknown extends RequestInfo ? never : RequestInfo; 16 | export { type _RequestInfo as RequestInfo }; 17 | 18 | // @ts-ignore 19 | type _RequestInit = unknown extends RequestInit ? never : RequestInit; 20 | export { type _RequestInit as RequestInit }; 21 | 22 | // @ts-ignore 23 | type _Response = unknown extends Response ? never : Response; 24 | export { _Response as Response }; 25 | 26 | // @ts-ignore 27 | type _ResponseInit = unknown extends ResponseInit ? never : ResponseInit; 28 | export { type _ResponseInit as ResponseInit }; 29 | 30 | // @ts-ignore 31 | type _ResponseType = unknown extends ResponseType ? never : ResponseType; 32 | export { type _ResponseType as ResponseType }; 33 | 34 | // @ts-ignore 35 | type _BodyInit = unknown extends BodyInit ? never : BodyInit; 36 | export { type _BodyInit as BodyInit }; 37 | 38 | // @ts-ignore 39 | type _Headers = unknown extends Headers ? never : Headers; 40 | export { _Headers as Headers }; 41 | 42 | // @ts-ignore 43 | type _HeadersInit = unknown extends HeadersInit ? never : HeadersInit; 44 | export { type _HeadersInit as HeadersInit }; 45 | 46 | type EndingType = 'native' | 'transparent'; 47 | 48 | export interface BlobPropertyBag { 49 | endings?: EndingType; 50 | type?: string; 51 | } 52 | 53 | export interface FilePropertyBag extends BlobPropertyBag { 54 | lastModified?: number; 55 | } 56 | 57 | export type FileFromPathOptions = Omit; 58 | 59 | // @ts-ignore 60 | type _FormData = unknown extends FormData ? never : FormData; 61 | // @ts-ignore 62 | declare const _FormData: unknown extends typeof FormData ? never : typeof FormData; 63 | export { _FormData as FormData }; 64 | 65 | // @ts-ignore 66 | type _File = unknown extends File ? never : File; 67 | // @ts-ignore 68 | declare const _File: unknown extends typeof File ? never : typeof File; 69 | export { _File as File }; 70 | 71 | // @ts-ignore 72 | type _Blob = unknown extends Blob ? never : Blob; 73 | // @ts-ignore 74 | declare const _Blob: unknown extends typeof Blob ? never : typeof Blob; 75 | export { _Blob as Blob }; 76 | 77 | export declare class Readable { 78 | readable: boolean; 79 | readonly readableEnded: boolean; 80 | readonly readableFlowing: boolean | null; 81 | readonly readableHighWaterMark: number; 82 | readonly readableLength: number; 83 | readonly readableObjectMode: boolean; 84 | destroyed: boolean; 85 | read(size?: number): any; 86 | pause(): this; 87 | resume(): this; 88 | isPaused(): boolean; 89 | destroy(error?: Error): this; 90 | [Symbol.asyncIterator](): AsyncIterableIterator; 91 | } 92 | 93 | export declare class FsReadStream extends Readable { 94 | path: {}; // node type is string | Buffer 95 | } 96 | 97 | // @ts-ignore 98 | type _ReadableStream = unknown extends ReadableStream ? never : ReadableStream; 99 | // @ts-ignore 100 | declare const _ReadableStream: unknown extends typeof ReadableStream ? never : typeof ReadableStream; 101 | export { _ReadableStream as ReadableStream }; 102 | -------------------------------------------------------------------------------- /openai-types/_shims/bun-runtime.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | import { type Shims } from "./registry.js"; 5 | export declare function getRuntime(): Shims; 6 | //# sourceMappingURL=bun-runtime.d.ts.map -------------------------------------------------------------------------------- /openai-types/_shims/index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | import { manual } from "./manual-types.js"; 5 | import * as auto from '../_shims/auto/types.js'; 6 | import { type RequestOptions } from "../core.js"; 7 | 8 | type SelectType = unknown extends Manual ? Auto : Manual; 9 | 10 | export const kind: string; 11 | 12 | // @ts-ignore 13 | export type Agent = SelectType; 14 | 15 | // @ts-ignore 16 | export const fetch: SelectType; 17 | 18 | // @ts-ignore 19 | export type Request = SelectType; 20 | // @ts-ignore 21 | export type RequestInfo = SelectType; 22 | // @ts-ignore 23 | export type RequestInit = SelectType; 24 | 25 | // @ts-ignore 26 | export type Response = SelectType; 27 | // @ts-ignore 28 | export type ResponseInit = SelectType; 29 | // @ts-ignore 30 | export type ResponseType = SelectType; 31 | // @ts-ignore 32 | export type BodyInit = SelectType; 33 | // @ts-ignore 34 | export type Headers = SelectType; 35 | // @ts-ignore 36 | export const Headers: SelectType; 37 | // @ts-ignore 38 | export type HeadersInit = SelectType; 39 | 40 | // @ts-ignore 41 | export type BlobPropertyBag = SelectType; 42 | // @ts-ignore 43 | export type FilePropertyBag = SelectType; 44 | // @ts-ignore 45 | export type FileFromPathOptions = SelectType; 46 | // @ts-ignore 47 | export type FormData = SelectType; 48 | // @ts-ignore 49 | export const FormData: SelectType; 50 | // @ts-ignore 51 | export type File = SelectType; 52 | // @ts-ignore 53 | export const File: SelectType; 54 | // @ts-ignore 55 | export type Blob = SelectType; 56 | // @ts-ignore 57 | export const Blob: SelectType; 58 | 59 | // @ts-ignore 60 | export type Readable = SelectType; 61 | // @ts-ignore 62 | export type FsReadStream = SelectType; 63 | // @ts-ignore 64 | export type ReadableStream = SelectType; 65 | // @ts-ignore 66 | export const ReadableStream: SelectType; 67 | 68 | export function getMultipartRequestOptions>( 69 | form: FormData, 70 | opts: RequestOptions, 71 | ): Promise>; 72 | 73 | export function getDefaultAgent(url: string): any; 74 | 75 | // @ts-ignore 76 | export type FileFromPathOptions = SelectType; 77 | 78 | export function fileFromPath(path: string, options?: FileFromPathOptions): Promise; 79 | export function fileFromPath(path: string, filename?: string, options?: FileFromPathOptions): Promise; 80 | 81 | export function isFsReadStream(value: any): value is FsReadStream; 82 | -------------------------------------------------------------------------------- /openai-types/_shims/manual-types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | /** 5 | * Types will get added to this namespace when you import one of the following: 6 | * 7 | * import '../shims/node.js' 8 | * import '../shims/web.js' 9 | * 10 | * Importing more than one will cause type and runtime errors. 11 | */ 12 | export namespace manual {} 13 | -------------------------------------------------------------------------------- /openai-types/_shims/node-runtime.d.ts: -------------------------------------------------------------------------------- 1 | import { type Shims } from "./registry.js"; 2 | export declare function getRuntime(): Shims; 3 | //# sourceMappingURL=node-runtime.d.ts.map -------------------------------------------------------------------------------- /openai-types/_shims/node-types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | import * as nf from 'node-fetch'; 5 | import * as fd from 'formdata-node'; 6 | 7 | export { type Agent } from 'node:http'; 8 | export { type Readable } from 'node:stream'; 9 | export { type ReadStream as FsReadStream } from 'node:fs'; 10 | export { ReadableStream } from 'node:stream/web'; 11 | 12 | export const fetch: typeof nf.default; 13 | 14 | export type Request = nf.Request; 15 | export type RequestInfo = nf.RequestInfo; 16 | export type RequestInit = nf.RequestInit; 17 | 18 | export type Response = nf.Response; 19 | export type ResponseInit = nf.ResponseInit; 20 | export type ResponseType = nf.ResponseType; 21 | export type BodyInit = nf.BodyInit; 22 | export type Headers = nf.Headers; 23 | export type HeadersInit = nf.HeadersInit; 24 | 25 | type EndingType = 'native' | 'transparent'; 26 | export interface BlobPropertyBag { 27 | endings?: EndingType; 28 | type?: string; 29 | } 30 | 31 | export interface FilePropertyBag extends BlobPropertyBag { 32 | lastModified?: number; 33 | } 34 | 35 | export type FileFromPathOptions = Omit; 36 | 37 | export type FormData = fd.FormData; 38 | export const FormData: typeof fd.FormData; 39 | export type File = fd.File; 40 | export const File: typeof fd.File; 41 | export type Blob = fd.Blob; 42 | export const Blob: typeof fd.Blob; 43 | -------------------------------------------------------------------------------- /openai-types/_shims/registry.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | import { type RequestOptions } from "../core.js"; 5 | export interface Shims { 6 | kind: string; 7 | fetch: any; 8 | Request: any; 9 | Response: any; 10 | Headers: any; 11 | FormData: any; 12 | Blob: any; 13 | File: any; 14 | ReadableStream: any; 15 | getMultipartRequestOptions: >(form: Shims['FormData'], opts: RequestOptions) => Promise>; 16 | getDefaultAgent: (url: string) => any; 17 | fileFromPath: ((path: string, filename?: string, options?: {}) => Promise) | ((path: string, options?: {}) => Promise); 18 | isFsReadStream: (value: any) => boolean; 19 | } 20 | export declare let auto: boolean; 21 | export declare let kind: Shims['kind'] | undefined; 22 | export declare let fetch: Shims['fetch'] | undefined; 23 | export declare let Request: Shims['Request'] | undefined; 24 | export declare let Response: Shims['Response'] | undefined; 25 | export declare let Headers: Shims['Headers'] | undefined; 26 | export declare let FormData: Shims['FormData'] | undefined; 27 | export declare let Blob: Shims['Blob'] | undefined; 28 | export declare let File: Shims['File'] | undefined; 29 | export declare let ReadableStream: Shims['ReadableStream'] | undefined; 30 | export declare let getMultipartRequestOptions: Shims['getMultipartRequestOptions'] | undefined; 31 | export declare let getDefaultAgent: Shims['getDefaultAgent'] | undefined; 32 | export declare let fileFromPath: Shims['fileFromPath'] | undefined; 33 | export declare let isFsReadStream: Shims['isFsReadStream'] | undefined; 34 | export declare function setShims(shims: Shims, options?: { 35 | auto: boolean; 36 | }): void; 37 | //# sourceMappingURL=registry.d.ts.map -------------------------------------------------------------------------------- /openai-types/_shims/web-runtime.d.ts: -------------------------------------------------------------------------------- 1 | import { type Shims } from "./registry.js"; 2 | export declare function getRuntime({ manuallyImported }?: { 3 | manuallyImported?: boolean; 4 | }): Shims; 5 | //# sourceMappingURL=web-runtime.d.ts.map -------------------------------------------------------------------------------- /openai-types/_shims/web-types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | export type Agent = any; 5 | 6 | declare const _fetch: typeof fetch; 7 | export { _fetch as fetch }; 8 | 9 | type _Request = Request; 10 | export { _Request as Request }; 11 | 12 | type _RequestInfo = RequestInfo; 13 | export { type _RequestInfo as RequestInfo }; 14 | 15 | type _RequestInit = RequestInit; 16 | export { type _RequestInit as RequestInit }; 17 | 18 | type _Response = Response; 19 | export { _Response as Response }; 20 | 21 | type _ResponseInit = ResponseInit; 22 | export { type _ResponseInit as ResponseInit }; 23 | 24 | type _ResponseType = ResponseType; 25 | export { type _ResponseType as ResponseType }; 26 | 27 | type _BodyInit = BodyInit; 28 | export { type _BodyInit as BodyInit }; 29 | 30 | type _Headers = Headers; 31 | export { _Headers as Headers }; 32 | 33 | type _HeadersInit = HeadersInit; 34 | export { type _HeadersInit as HeadersInit }; 35 | 36 | type EndingType = 'native' | 'transparent'; 37 | 38 | export interface BlobPropertyBag { 39 | endings?: EndingType; 40 | type?: string; 41 | } 42 | 43 | export interface FilePropertyBag extends BlobPropertyBag { 44 | lastModified?: number; 45 | } 46 | 47 | export type FileFromPathOptions = Omit; 48 | 49 | type _FormData = FormData; 50 | declare const _FormData: typeof FormData; 51 | export { _FormData as FormData }; 52 | 53 | type _File = File; 54 | declare const _File: typeof File; 55 | export { _File as File }; 56 | 57 | type _Blob = Blob; 58 | declare const _Blob: typeof Blob; 59 | export { _Blob as Blob }; 60 | 61 | export declare class Readable { 62 | readable: boolean; 63 | readonly readableEnded: boolean; 64 | readonly readableFlowing: boolean | null; 65 | readonly readableHighWaterMark: number; 66 | readonly readableLength: number; 67 | readonly readableObjectMode: boolean; 68 | destroyed: boolean; 69 | read(size?: number): any; 70 | pause(): this; 71 | resume(): this; 72 | isPaused(): boolean; 73 | destroy(error?: Error): this; 74 | [Symbol.asyncIterator](): AsyncIterableIterator; 75 | } 76 | 77 | export declare class FsReadStream extends Readable { 78 | path: {}; // node type is string | Buffer 79 | } 80 | 81 | type _ReadableStream = ReadableStream; 82 | declare const _ReadableStream: typeof ReadableStream; 83 | export { _ReadableStream as ReadableStream }; 84 | -------------------------------------------------------------------------------- /openai-types/_vendor/partial-json-parser/parser.d.ts: -------------------------------------------------------------------------------- 1 | declare class PartialJSON extends Error { 2 | } 3 | declare class MalformedJSON extends Error { 4 | } 5 | declare const partialParse: (input: string) => any; 6 | export { partialParse, PartialJSON, MalformedJSON }; 7 | //# sourceMappingURL=parser.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/Options.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodSchema, ZodTypeDef } from 'zod'; 2 | import { Refs, Seen } from "./Refs.js"; 3 | import { JsonSchema7Type } from "./parseDef.js"; 4 | export type Targets = 'jsonSchema7' | 'jsonSchema2019-09' | 'openApi3'; 5 | export type DateStrategy = 'format:date-time' | 'format:date' | 'string' | 'integer'; 6 | export declare const ignoreOverride: unique symbol; 7 | export type Options = { 8 | name: string | undefined; 9 | $refStrategy: 'root' | 'relative' | 'none' | 'seen' | 'extract-to-root'; 10 | basePath: string[]; 11 | effectStrategy: 'input' | 'any'; 12 | pipeStrategy: 'input' | 'output' | 'all'; 13 | dateStrategy: DateStrategy | DateStrategy[]; 14 | mapStrategy: 'entries' | 'record'; 15 | removeAdditionalStrategy: 'passthrough' | 'strict'; 16 | nullableStrategy: 'from-target' | 'property'; 17 | target: Target; 18 | strictUnions: boolean; 19 | definitionPath: string; 20 | definitions: Record; 21 | errorMessages: boolean; 22 | markdownDescription: boolean; 23 | patternStrategy: 'escape' | 'preserve'; 24 | applyRegexFlags: boolean; 25 | emailStrategy: 'format:email' | 'format:idn-email' | 'pattern:zod'; 26 | base64Strategy: 'format:binary' | 'contentEncoding:base64' | 'pattern:zod'; 27 | nameStrategy: 'ref' | 'duplicate-ref' | 'title'; 28 | override?: (def: ZodTypeDef, refs: Refs, seen: Seen | undefined, forceResolution?: boolean) => JsonSchema7Type | undefined | typeof ignoreOverride; 29 | openaiStrictMode?: boolean; 30 | }; 31 | export declare const getDefaultOptions: (options: string | Partial> | undefined) => Options; 32 | //# sourceMappingURL=Options.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/Refs.d.ts: -------------------------------------------------------------------------------- 1 | import type { ZodTypeDef } from 'zod'; 2 | import { Options, Targets } from "./Options.js"; 3 | import { JsonSchema7Type } from "./parseDef.js"; 4 | export type Refs = { 5 | seen: Map; 6 | /** 7 | * Set of all the `$ref`s we created, e.g. `Set(['#/$defs/ui'])` 8 | * this notable does not include any `definitions` that were 9 | * explicitly given as an option. 10 | */ 11 | seenRefs: Set; 12 | currentPath: string[]; 13 | propertyPath: string[] | undefined; 14 | } & Options; 15 | export type Seen = { 16 | def: ZodTypeDef; 17 | path: string[]; 18 | jsonSchema: JsonSchema7Type | undefined; 19 | }; 20 | export declare const getRefs: (options?: string | Partial>) => Refs; 21 | //# sourceMappingURL=Refs.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/errorMessages.d.ts: -------------------------------------------------------------------------------- 1 | import { JsonSchema7TypeUnion } from "./parseDef.js"; 2 | import { Refs } from "./Refs.js"; 3 | export type ErrorMessages = Partial>; 6 | export declare function addErrorMessage; 8 | }>(res: T, key: keyof T, errorMessage: string | undefined, refs: Refs): void; 9 | export declare function setResponseValueAndErrors; 11 | }, Key extends keyof Omit>(res: Json7Type, key: Key, value: Json7Type[Key], errorMessage: string | undefined, refs: Refs): void; 12 | //# sourceMappingURL=errorMessages.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/index.d.ts: -------------------------------------------------------------------------------- 1 | export * from "./Options.js"; 2 | export * from "./Refs.js"; 3 | export * from "./errorMessages.js"; 4 | export * from "./parseDef.js"; 5 | export * from "./parsers/any.js"; 6 | export * from "./parsers/array.js"; 7 | export * from "./parsers/bigint.js"; 8 | export * from "./parsers/boolean.js"; 9 | export * from "./parsers/branded.js"; 10 | export * from "./parsers/catch.js"; 11 | export * from "./parsers/date.js"; 12 | export * from "./parsers/default.js"; 13 | export * from "./parsers/effects.js"; 14 | export * from "./parsers/enum.js"; 15 | export * from "./parsers/intersection.js"; 16 | export * from "./parsers/literal.js"; 17 | export * from "./parsers/map.js"; 18 | export * from "./parsers/nativeEnum.js"; 19 | export * from "./parsers/never.js"; 20 | export * from "./parsers/null.js"; 21 | export * from "./parsers/nullable.js"; 22 | export * from "./parsers/number.js"; 23 | export * from "./parsers/object.js"; 24 | export * from "./parsers/optional.js"; 25 | export * from "./parsers/pipeline.js"; 26 | export * from "./parsers/promise.js"; 27 | export * from "./parsers/readonly.js"; 28 | export * from "./parsers/record.js"; 29 | export * from "./parsers/set.js"; 30 | export * from "./parsers/string.js"; 31 | export * from "./parsers/tuple.js"; 32 | export * from "./parsers/undefined.js"; 33 | export * from "./parsers/union.js"; 34 | export * from "./parsers/unknown.js"; 35 | export * from "./zodToJsonSchema.js"; 36 | import { zodToJsonSchema } from "./zodToJsonSchema.js"; 37 | export default zodToJsonSchema; 38 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parseDef.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodTypeDef } from 'zod'; 2 | import { JsonSchema7AnyType } from "./parsers/any.js"; 3 | import { JsonSchema7ArrayType } from "./parsers/array.js"; 4 | import { JsonSchema7BigintType } from "./parsers/bigint.js"; 5 | import { JsonSchema7BooleanType } from "./parsers/boolean.js"; 6 | import { JsonSchema7DateType } from "./parsers/date.js"; 7 | import { JsonSchema7EnumType } from "./parsers/enum.js"; 8 | import { JsonSchema7AllOfType } from "./parsers/intersection.js"; 9 | import { JsonSchema7LiteralType } from "./parsers/literal.js"; 10 | import { JsonSchema7MapType } from "./parsers/map.js"; 11 | import { JsonSchema7NativeEnumType } from "./parsers/nativeEnum.js"; 12 | import { JsonSchema7NeverType } from "./parsers/never.js"; 13 | import { JsonSchema7NullType } from "./parsers/null.js"; 14 | import { JsonSchema7NullableType } from "./parsers/nullable.js"; 15 | import { JsonSchema7NumberType } from "./parsers/number.js"; 16 | import { JsonSchema7ObjectType } from "./parsers/object.js"; 17 | import { JsonSchema7RecordType } from "./parsers/record.js"; 18 | import { JsonSchema7SetType } from "./parsers/set.js"; 19 | import { JsonSchema7StringType } from "./parsers/string.js"; 20 | import { JsonSchema7TupleType } from "./parsers/tuple.js"; 21 | import { JsonSchema7UndefinedType } from "./parsers/undefined.js"; 22 | import { JsonSchema7UnionType } from "./parsers/union.js"; 23 | import { JsonSchema7UnknownType } from "./parsers/unknown.js"; 24 | import { Refs } from "./Refs.js"; 25 | type JsonSchema7RefType = { 26 | $ref: string; 27 | }; 28 | type JsonSchema7Meta = { 29 | title?: string; 30 | default?: any; 31 | description?: string; 32 | markdownDescription?: string; 33 | }; 34 | export type JsonSchema7TypeUnion = JsonSchema7StringType | JsonSchema7ArrayType | JsonSchema7NumberType | JsonSchema7BigintType | JsonSchema7BooleanType | JsonSchema7DateType | JsonSchema7EnumType | JsonSchema7LiteralType | JsonSchema7NativeEnumType | JsonSchema7NullType | JsonSchema7NumberType | JsonSchema7ObjectType | JsonSchema7RecordType | JsonSchema7TupleType | JsonSchema7UnionType | JsonSchema7UndefinedType | JsonSchema7RefType | JsonSchema7NeverType | JsonSchema7MapType | JsonSchema7AnyType | JsonSchema7NullableType | JsonSchema7AllOfType | JsonSchema7UnknownType | JsonSchema7SetType; 35 | export type JsonSchema7Type = JsonSchema7TypeUnion & JsonSchema7Meta; 36 | export declare function parseDef(def: ZodTypeDef, refs: Refs, forceResolution?: boolean): JsonSchema7Type | undefined; 37 | export {}; 38 | //# sourceMappingURL=parseDef.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/any.d.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7AnyType = {}; 2 | export declare function parseAnyDef(): JsonSchema7AnyType; 3 | //# sourceMappingURL=any.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/array.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodArrayDef } from 'zod'; 2 | import { ErrorMessages } from "../errorMessages.js"; 3 | import { JsonSchema7Type } from "../parseDef.js"; 4 | import { Refs } from "../Refs.js"; 5 | export type JsonSchema7ArrayType = { 6 | type: 'array'; 7 | items?: JsonSchema7Type | undefined; 8 | minItems?: number; 9 | maxItems?: number; 10 | errorMessages?: ErrorMessages; 11 | }; 12 | export declare function parseArrayDef(def: ZodArrayDef, refs: Refs): JsonSchema7ArrayType; 13 | //# sourceMappingURL=array.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/bigint.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodBigIntDef } from 'zod'; 2 | import { Refs } from "../Refs.js"; 3 | import { ErrorMessages } from "../errorMessages.js"; 4 | export type JsonSchema7BigintType = { 5 | type: 'integer'; 6 | format: 'int64'; 7 | minimum?: BigInt; 8 | exclusiveMinimum?: BigInt; 9 | maximum?: BigInt; 10 | exclusiveMaximum?: BigInt; 11 | multipleOf?: BigInt; 12 | errorMessage?: ErrorMessages; 13 | }; 14 | export declare function parseBigintDef(def: ZodBigIntDef, refs: Refs): JsonSchema7BigintType; 15 | //# sourceMappingURL=bigint.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/boolean.d.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7BooleanType = { 2 | type: 'boolean'; 3 | }; 4 | export declare function parseBooleanDef(): JsonSchema7BooleanType; 5 | //# sourceMappingURL=boolean.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/branded.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodBrandedDef } from 'zod'; 2 | import { Refs } from "../Refs.js"; 3 | export declare function parseBrandedDef(_def: ZodBrandedDef, refs: Refs): import("../parseDef").JsonSchema7Type | undefined; 4 | //# sourceMappingURL=branded.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/catch.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodCatchDef } from 'zod'; 2 | import { Refs } from "../Refs.js"; 3 | export declare const parseCatchDef: (def: ZodCatchDef, refs: Refs) => import("../parseDef").JsonSchema7Type | undefined; 4 | //# sourceMappingURL=catch.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/date.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodDateDef } from 'zod'; 2 | import { Refs } from "../Refs.js"; 3 | import { ErrorMessages } from "../errorMessages.js"; 4 | import { JsonSchema7NumberType } from "./number.js"; 5 | import { DateStrategy } from "../Options.js"; 6 | export type JsonSchema7DateType = { 7 | type: 'integer' | 'string'; 8 | format: 'unix-time' | 'date-time' | 'date'; 9 | minimum?: number; 10 | maximum?: number; 11 | errorMessage?: ErrorMessages; 12 | } | { 13 | anyOf: JsonSchema7DateType[]; 14 | }; 15 | export declare function parseDateDef(def: ZodDateDef, refs: Refs, overrideDateStrategy?: DateStrategy): JsonSchema7DateType; 16 | //# sourceMappingURL=date.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/default.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodDefaultDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | export declare function parseDefaultDef(_def: ZodDefaultDef, refs: Refs): JsonSchema7Type & { 5 | default: any; 6 | }; 7 | //# sourceMappingURL=default.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/effects.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodEffectsDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | export declare function parseEffectsDef(_def: ZodEffectsDef, refs: Refs, forceResolution: boolean): JsonSchema7Type | undefined; 5 | //# sourceMappingURL=effects.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/enum.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodEnumDef } from 'zod'; 2 | export type JsonSchema7EnumType = { 3 | type: 'string'; 4 | enum: string[]; 5 | }; 6 | export declare function parseEnumDef(def: ZodEnumDef): JsonSchema7EnumType; 7 | //# sourceMappingURL=enum.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/intersection.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodIntersectionDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | export type JsonSchema7AllOfType = { 5 | allOf: JsonSchema7Type[]; 6 | unevaluatedProperties?: boolean; 7 | }; 8 | export declare function parseIntersectionDef(def: ZodIntersectionDef, refs: Refs): JsonSchema7AllOfType | JsonSchema7Type | undefined; 9 | //# sourceMappingURL=intersection.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/literal.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodLiteralDef } from 'zod'; 2 | import { Refs } from "../Refs.js"; 3 | export type JsonSchema7LiteralType = { 4 | type: 'string' | 'number' | 'integer' | 'boolean'; 5 | const: string | number | boolean; 6 | } | { 7 | type: 'object' | 'array'; 8 | }; 9 | export declare function parseLiteralDef(def: ZodLiteralDef, refs: Refs): JsonSchema7LiteralType; 10 | //# sourceMappingURL=literal.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/map.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodMapDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | import { JsonSchema7RecordType } from "./record.js"; 5 | export type JsonSchema7MapType = { 6 | type: 'array'; 7 | maxItems: 125; 8 | items: { 9 | type: 'array'; 10 | items: [JsonSchema7Type, JsonSchema7Type]; 11 | minItems: 2; 12 | maxItems: 2; 13 | }; 14 | }; 15 | export declare function parseMapDef(def: ZodMapDef, refs: Refs): JsonSchema7MapType | JsonSchema7RecordType; 16 | //# sourceMappingURL=map.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/nativeEnum.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodNativeEnumDef } from 'zod'; 2 | export type JsonSchema7NativeEnumType = { 3 | type: 'string' | 'number' | ['string', 'number']; 4 | enum: (string | number)[]; 5 | }; 6 | export declare function parseNativeEnumDef(def: ZodNativeEnumDef): JsonSchema7NativeEnumType; 7 | //# sourceMappingURL=nativeEnum.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/never.d.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7NeverType = { 2 | not: {}; 3 | }; 4 | export declare function parseNeverDef(): JsonSchema7NeverType; 5 | //# sourceMappingURL=never.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/null.d.ts: -------------------------------------------------------------------------------- 1 | import { Refs } from "../Refs.js"; 2 | export type JsonSchema7NullType = { 3 | type: 'null'; 4 | }; 5 | export declare function parseNullDef(refs: Refs): JsonSchema7NullType; 6 | //# sourceMappingURL=null.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/nullable.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodNullableDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | import { JsonSchema7NullType } from "./null.js"; 5 | export type JsonSchema7NullableType = { 6 | anyOf: [JsonSchema7Type, JsonSchema7NullType]; 7 | } | { 8 | type: [string, 'null']; 9 | }; 10 | export declare function parseNullableDef(def: ZodNullableDef, refs: Refs): JsonSchema7NullableType | undefined; 11 | //# sourceMappingURL=nullable.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/number.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodNumberDef } from 'zod'; 2 | import { ErrorMessages } from "../errorMessages.js"; 3 | import { Refs } from "../Refs.js"; 4 | export type JsonSchema7NumberType = { 5 | type: 'number' | 'integer'; 6 | minimum?: number; 7 | exclusiveMinimum?: number; 8 | maximum?: number; 9 | exclusiveMaximum?: number; 10 | multipleOf?: number; 11 | errorMessage?: ErrorMessages; 12 | }; 13 | export declare function parseNumberDef(def: ZodNumberDef, refs: Refs): JsonSchema7NumberType; 14 | //# sourceMappingURL=number.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/object.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodObjectDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | export type JsonSchema7ObjectType = { 5 | type: 'object'; 6 | properties: Record; 7 | additionalProperties: boolean | JsonSchema7Type; 8 | required?: string[]; 9 | }; 10 | export declare function parseObjectDef(def: ZodObjectDef, refs: Refs): JsonSchema7ObjectType; 11 | //# sourceMappingURL=object.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/optional.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodOptionalDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | export declare const parseOptionalDef: (def: ZodOptionalDef, refs: Refs) => JsonSchema7Type | undefined; 5 | //# sourceMappingURL=optional.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/pipeline.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodPipelineDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | import { JsonSchema7AllOfType } from "./intersection.js"; 5 | export declare const parsePipelineDef: (def: ZodPipelineDef, refs: Refs) => JsonSchema7AllOfType | JsonSchema7Type | undefined; 6 | //# sourceMappingURL=pipeline.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/promise.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodPromiseDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | export declare function parsePromiseDef(def: ZodPromiseDef, refs: Refs): JsonSchema7Type | undefined; 5 | //# sourceMappingURL=promise.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/readonly.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodReadonlyDef } from 'zod'; 2 | import { Refs } from "../Refs.js"; 3 | export declare const parseReadonlyDef: (def: ZodReadonlyDef, refs: Refs) => import("../parseDef").JsonSchema7Type | undefined; 4 | //# sourceMappingURL=readonly.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/record.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodMapDef, ZodRecordDef, ZodTypeAny } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | import { JsonSchema7EnumType } from "./enum.js"; 5 | import { JsonSchema7StringType } from "./string.js"; 6 | type JsonSchema7RecordPropertyNamesType = Omit | Omit; 7 | export type JsonSchema7RecordType = { 8 | type: 'object'; 9 | additionalProperties: JsonSchema7Type; 10 | propertyNames?: JsonSchema7RecordPropertyNamesType; 11 | }; 12 | export declare function parseRecordDef(def: ZodRecordDef | ZodMapDef, refs: Refs): JsonSchema7RecordType; 13 | export {}; 14 | //# sourceMappingURL=record.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/set.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodSetDef } from 'zod'; 2 | import { ErrorMessages } from "../errorMessages.js"; 3 | import { JsonSchema7Type } from "../parseDef.js"; 4 | import { Refs } from "../Refs.js"; 5 | export type JsonSchema7SetType = { 6 | type: 'array'; 7 | uniqueItems: true; 8 | items?: JsonSchema7Type | undefined; 9 | minItems?: number; 10 | maxItems?: number; 11 | errorMessage?: ErrorMessages; 12 | }; 13 | export declare function parseSetDef(def: ZodSetDef, refs: Refs): JsonSchema7SetType; 14 | //# sourceMappingURL=set.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/string.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodStringDef } from 'zod'; 2 | import { ErrorMessages } from "../errorMessages.js"; 3 | import { Refs } from "../Refs.js"; 4 | /** 5 | * Generated from the regular expressions found here as of 2024-05-22: 6 | * https://github.com/colinhacks/zod/blob/master/src/types.ts. 7 | * 8 | * Expressions with /i flag have been changed accordingly. 9 | */ 10 | export declare const zodPatterns: { 11 | /** 12 | * `c` was changed to `[cC]` to replicate /i flag 13 | */ 14 | readonly cuid: RegExp; 15 | readonly cuid2: RegExp; 16 | readonly ulid: RegExp; 17 | /** 18 | * `a-z` was added to replicate /i flag 19 | */ 20 | readonly email: RegExp; 21 | /** 22 | * Constructed a valid Unicode RegExp 23 | * 24 | * Lazily instantiate since this type of regex isn't supported 25 | * in all envs (e.g. React Native). 26 | * 27 | * See: 28 | * https://github.com/colinhacks/zod/issues/2433 29 | * Fix in Zod: 30 | * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b 31 | */ 32 | readonly emoji: () => RegExp; 33 | /** 34 | * Unused 35 | */ 36 | readonly uuid: RegExp; 37 | /** 38 | * Unused 39 | */ 40 | readonly ipv4: RegExp; 41 | /** 42 | * Unused 43 | */ 44 | readonly ipv6: RegExp; 45 | readonly base64: RegExp; 46 | readonly nanoid: RegExp; 47 | }; 48 | export type JsonSchema7StringType = { 49 | type: 'string'; 50 | minLength?: number; 51 | maxLength?: number; 52 | format?: 'email' | 'idn-email' | 'uri' | 'uuid' | 'date-time' | 'ipv4' | 'ipv6' | 'date' | 'time' | 'duration'; 53 | pattern?: string; 54 | allOf?: { 55 | pattern: string; 56 | errorMessage?: ErrorMessages<{ 57 | pattern: string; 58 | }>; 59 | }[]; 60 | anyOf?: { 61 | format: string; 62 | errorMessage?: ErrorMessages<{ 63 | format: string; 64 | }>; 65 | }[]; 66 | errorMessage?: ErrorMessages; 67 | contentEncoding?: string; 68 | }; 69 | export declare function parseStringDef(def: ZodStringDef, refs: Refs): JsonSchema7StringType; 70 | //# sourceMappingURL=string.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/tuple.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodTupleDef, ZodTupleItems, ZodTypeAny } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | export type JsonSchema7TupleType = { 5 | type: 'array'; 6 | minItems: number; 7 | items: JsonSchema7Type[]; 8 | } & ({ 9 | maxItems: number; 10 | } | { 11 | additionalItems?: JsonSchema7Type | undefined; 12 | }); 13 | export declare function parseTupleDef(def: ZodTupleDef, refs: Refs): JsonSchema7TupleType; 14 | //# sourceMappingURL=tuple.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/undefined.d.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7UndefinedType = { 2 | not: {}; 3 | }; 4 | export declare function parseUndefinedDef(): JsonSchema7UndefinedType; 5 | //# sourceMappingURL=undefined.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/union.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodDiscriminatedUnionDef, ZodUnionDef } from 'zod'; 2 | import { JsonSchema7Type } from "../parseDef.js"; 3 | import { Refs } from "../Refs.js"; 4 | export declare const primitiveMappings: { 5 | readonly ZodString: "string"; 6 | readonly ZodNumber: "number"; 7 | readonly ZodBigInt: "integer"; 8 | readonly ZodBoolean: "boolean"; 9 | readonly ZodNull: "null"; 10 | }; 11 | type JsonSchema7Primitive = (typeof primitiveMappings)[keyof typeof primitiveMappings]; 12 | export type JsonSchema7UnionType = JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType; 13 | type JsonSchema7PrimitiveUnionType = { 14 | type: JsonSchema7Primitive | JsonSchema7Primitive[]; 15 | } | { 16 | type: JsonSchema7Primitive | JsonSchema7Primitive[]; 17 | enum: (string | number | bigint | boolean | null)[]; 18 | }; 19 | type JsonSchema7AnyOfType = { 20 | anyOf: JsonSchema7Type[]; 21 | }; 22 | export declare function parseUnionDef(def: ZodUnionDef | ZodDiscriminatedUnionDef, refs: Refs): JsonSchema7PrimitiveUnionType | JsonSchema7AnyOfType | undefined; 23 | export {}; 24 | //# sourceMappingURL=union.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/parsers/unknown.d.ts: -------------------------------------------------------------------------------- 1 | export type JsonSchema7UnknownType = {}; 2 | export declare function parseUnknownDef(): JsonSchema7UnknownType; 3 | //# sourceMappingURL=unknown.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/util.d.ts: -------------------------------------------------------------------------------- 1 | import type { ZodSchema, ZodTypeDef } from 'zod'; 2 | export declare const zodDef: (zodSchema: ZodSchema | ZodTypeDef) => ZodTypeDef; 3 | export declare function isEmptyObj(obj: Object | null | undefined): boolean; 4 | //# sourceMappingURL=util.d.ts.map -------------------------------------------------------------------------------- /openai-types/_vendor/zod-to-json-schema/zodToJsonSchema.d.ts: -------------------------------------------------------------------------------- 1 | import { ZodSchema } from 'zod'; 2 | import { Options, Targets } from "./Options.js"; 3 | import { JsonSchema7Type } from "./parseDef.js"; 4 | declare const zodToJsonSchema: (schema: ZodSchema, options?: string | Partial> | undefined) => (Target extends "jsonSchema7" ? JsonSchema7Type : object) & { 5 | $schema?: string; 6 | definitions?: { 7 | [key: string]: Target extends "jsonSchema7" ? JsonSchema7Type : Target extends "jsonSchema2019-09" ? JsonSchema7Type : object; 8 | }; 9 | }; 10 | export { zodToJsonSchema }; 11 | //# sourceMappingURL=zodToJsonSchema.d.ts.map -------------------------------------------------------------------------------- /openai-types/error.d.ts: -------------------------------------------------------------------------------- 1 | import { Headers } from "./core.js"; 2 | export declare class OpenAIError extends Error { 3 | } 4 | export declare class APIError extends OpenAIError { 5 | /** HTTP status for the response that caused the error */ 6 | readonly status: TStatus; 7 | /** HTTP headers for the response that caused the error */ 8 | readonly headers: THeaders; 9 | /** JSON body of the response that caused the error */ 10 | readonly error: TError; 11 | readonly code: string | null | undefined; 12 | readonly param: string | null | undefined; 13 | readonly type: string | undefined; 14 | readonly request_id: string | null | undefined; 15 | constructor(status: TStatus, error: TError, message: string | undefined, headers: THeaders); 16 | private static makeMessage; 17 | static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError; 18 | } 19 | export declare class APIUserAbortError extends APIError { 20 | constructor({ message }?: { 21 | message?: string; 22 | }); 23 | } 24 | export declare class APIConnectionError extends APIError { 25 | constructor({ message, cause }: { 26 | message?: string | undefined; 27 | cause?: Error | undefined; 28 | }); 29 | } 30 | export declare class APIConnectionTimeoutError extends APIConnectionError { 31 | constructor({ message }?: { 32 | message?: string; 33 | }); 34 | } 35 | export declare class BadRequestError extends APIError<400, Headers> { 36 | } 37 | export declare class AuthenticationError extends APIError<401, Headers> { 38 | } 39 | export declare class PermissionDeniedError extends APIError<403, Headers> { 40 | } 41 | export declare class NotFoundError extends APIError<404, Headers> { 42 | } 43 | export declare class ConflictError extends APIError<409, Headers> { 44 | } 45 | export declare class UnprocessableEntityError extends APIError<422, Headers> { 46 | } 47 | export declare class RateLimitError extends APIError<429, Headers> { 48 | } 49 | export declare class InternalServerError extends APIError { 50 | } 51 | export declare class LengthFinishReasonError extends OpenAIError { 52 | constructor(); 53 | } 54 | export declare class ContentFilterFinishReasonError extends OpenAIError { 55 | constructor(); 56 | } 57 | //# sourceMappingURL=error.d.ts.map -------------------------------------------------------------------------------- /openai-types/helpers/zod.d.ts: -------------------------------------------------------------------------------- 1 | import { ResponseFormatJSONSchema } from "../resources/index.js"; 2 | import type { infer as zodInfer, ZodType } from 'zod'; 3 | import { AutoParseableResponseFormat, AutoParseableTool } from "../lib/parser.js"; 4 | /** 5 | * Creates a chat completion `JSONSchema` response format object from 6 | * the given Zod schema. 7 | * 8 | * If this is passed to the `.parse()`, `.stream()` or `.runTools()` 9 | * chat completion methods then the response message will contain a 10 | * `.parsed` property that is the result of parsing the content with 11 | * the given Zod object. 12 | * 13 | * ```ts 14 | * const completion = await client.beta.chat.completions.parse({ 15 | * model: 'gpt-4o-2024-08-06', 16 | * messages: [ 17 | * { role: 'system', content: 'You are a helpful math tutor.' }, 18 | * { role: 'user', content: 'solve 8x + 31 = 2' }, 19 | * ], 20 | * response_format: zodResponseFormat( 21 | * z.object({ 22 | * steps: z.array(z.object({ 23 | * explanation: z.string(), 24 | * answer: z.string(), 25 | * })), 26 | * final_answer: z.string(), 27 | * }), 28 | * 'math_answer', 29 | * ), 30 | * }); 31 | * const message = completion.choices[0]?.message; 32 | * if (message?.parsed) { 33 | * console.log(message.parsed); 34 | * console.log(message.parsed.final_answer); 35 | * } 36 | * ``` 37 | * 38 | * This can be passed directly to the `.create()` method but will not 39 | * result in any automatic parsing, you'll have to parse the response yourself. 40 | */ 41 | export declare function zodResponseFormat(zodObject: ZodInput, name: string, props?: Omit): AutoParseableResponseFormat>; 42 | /** 43 | * Creates a chat completion `function` tool that can be invoked 44 | * automatically by the chat completion `.runTools()` method or automatically 45 | * parsed by `.parse()` / `.stream()`. 46 | */ 47 | export declare function zodFunction(options: { 48 | name: string; 49 | parameters: Parameters; 50 | function?: ((args: zodInfer) => unknown | Promise) | undefined; 51 | description?: string | undefined; 52 | }): AutoParseableTool<{ 53 | arguments: Parameters; 54 | name: string; 55 | function: (args: zodInfer) => unknown; 56 | }>; 57 | //# sourceMappingURL=zod.d.ts.map -------------------------------------------------------------------------------- /openai-types/internal/decoders/line.d.ts: -------------------------------------------------------------------------------- 1 | 2 | type Bytes = string | ArrayBuffer | Uint8Array | Buffer | null | undefined; 3 | /** 4 | * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally 5 | * reading lines from text. 6 | * 7 | * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 8 | */ 9 | export declare class LineDecoder { 10 | static NEWLINE_CHARS: Set; 11 | static NEWLINE_REGEXP: RegExp; 12 | buffer: string[]; 13 | trailingCR: boolean; 14 | textDecoder: any; 15 | constructor(); 16 | decode(chunk: Bytes): string[]; 17 | decodeText(bytes: Bytes): string; 18 | flush(): string[]; 19 | } 20 | export {}; 21 | //# sourceMappingURL=line.d.ts.map -------------------------------------------------------------------------------- /openai-types/internal/qs/formats.d.ts: -------------------------------------------------------------------------------- 1 | import type { Format } from "./types.js"; 2 | export declare const default_format: Format; 3 | export declare const formatters: Record string>; 4 | export declare const RFC1738 = "RFC1738"; 5 | export declare const RFC3986 = "RFC3986"; 6 | //# sourceMappingURL=formats.d.ts.map -------------------------------------------------------------------------------- /openai-types/internal/qs/index.d.ts: -------------------------------------------------------------------------------- 1 | declare const formats: { 2 | formatters: Record string>; 3 | RFC1738: string; 4 | RFC3986: string; 5 | default: import("./types").Format; 6 | }; 7 | export { stringify } from "./stringify.js"; 8 | export { formats }; 9 | export type { DefaultDecoder, DefaultEncoder, Format, ParseOptions, StringifyOptions } from "./types.js"; 10 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/internal/qs/stringify.d.ts: -------------------------------------------------------------------------------- 1 | import type { StringifyOptions } from "./types.js"; 2 | export declare function stringify(object: any, opts?: StringifyOptions): string; 3 | //# sourceMappingURL=stringify.d.ts.map -------------------------------------------------------------------------------- /openai-types/internal/qs/types.d.ts: -------------------------------------------------------------------------------- 1 | export type Format = 'RFC1738' | 'RFC3986'; 2 | export type DefaultEncoder = (str: any, defaultEncoder?: any, charset?: string) => string; 3 | export type DefaultDecoder = (str: string, decoder?: any, charset?: string) => string; 4 | export type BooleanOptional = boolean | undefined; 5 | export type StringifyBaseOptions = { 6 | delimiter?: string; 7 | allowDots?: boolean; 8 | encodeDotInKeys?: boolean; 9 | strictNullHandling?: boolean; 10 | skipNulls?: boolean; 11 | encode?: boolean; 12 | encoder?: (str: any, defaultEncoder: DefaultEncoder, charset: string, type: 'key' | 'value', format?: Format) => string; 13 | filter?: Array | ((prefix: PropertyKey, value: any) => any); 14 | arrayFormat?: 'indices' | 'brackets' | 'repeat' | 'comma'; 15 | indices?: boolean; 16 | sort?: ((a: PropertyKey, b: PropertyKey) => number) | null; 17 | serializeDate?: (d: Date) => string; 18 | format?: 'RFC1738' | 'RFC3986'; 19 | formatter?: (str: PropertyKey) => string; 20 | encodeValuesOnly?: boolean; 21 | addQueryPrefix?: boolean; 22 | charset?: 'utf-8' | 'iso-8859-1'; 23 | charsetSentinel?: boolean; 24 | allowEmptyArrays?: boolean; 25 | commaRoundTrip?: boolean; 26 | }; 27 | export type StringifyOptions = StringifyBaseOptions; 28 | export type ParseBaseOptions = { 29 | comma?: boolean; 30 | delimiter?: string | RegExp; 31 | depth?: number | false; 32 | decoder?: (str: string, defaultDecoder: DefaultDecoder, charset: string, type: 'key' | 'value') => any; 33 | arrayLimit?: number; 34 | parseArrays?: boolean; 35 | plainObjects?: boolean; 36 | allowPrototypes?: boolean; 37 | allowSparse?: boolean; 38 | parameterLimit?: number; 39 | strictDepth?: boolean; 40 | strictNullHandling?: boolean; 41 | ignoreQueryPrefix?: boolean; 42 | charset?: 'utf-8' | 'iso-8859-1'; 43 | charsetSentinel?: boolean; 44 | interpretNumericEntities?: boolean; 45 | allowEmptyArrays?: boolean; 46 | duplicates?: 'combine' | 'first' | 'last'; 47 | allowDots?: boolean; 48 | decodeDotInKeys?: boolean; 49 | }; 50 | export type ParseOptions = ParseBaseOptions; 51 | export type ParsedQs = { 52 | [key: string]: undefined | string | string[] | ParsedQs | ParsedQs[]; 53 | }; 54 | export type NonNullableProperties = { 55 | [K in keyof T]-?: Exclude; 56 | }; 57 | //# sourceMappingURL=types.d.ts.map -------------------------------------------------------------------------------- /openai-types/internal/qs/utils.d.ts: -------------------------------------------------------------------------------- 1 | import type { DefaultEncoder, Format } from "./types.js"; 2 | export declare function merge(target: any, source: any, options?: { 3 | plainObjects?: boolean; 4 | allowPrototypes?: boolean; 5 | }): any; 6 | export declare function assign_single_source(target: any, source: any): any; 7 | export declare function decode(str: string, _: any, charset: string): string; 8 | export declare const encode: (str: any, defaultEncoder: DefaultEncoder, charset: string, type: 'key' | 'value', format: Format) => string; 9 | export declare function compact(value: any): any; 10 | export declare function is_regexp(obj: any): boolean; 11 | export declare function is_buffer(obj: any): boolean; 12 | export declare function combine(a: any, b: any): never[]; 13 | export declare function maybe_map(val: T[], fn: (v: T) => T): T | T[]; 14 | //# sourceMappingURL=utils.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/AbstractChatCompletionRunner.d.ts: -------------------------------------------------------------------------------- 1 | import * as Core from "../core.js"; 2 | import { type CompletionUsage } from "../resources/completions.js"; 3 | import { type ChatCompletion, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionCreateParams } from "../resources/chat/completions.js"; 4 | import { type BaseFunctionsArgs } from "./RunnableFunction.js"; 5 | import { ChatCompletionFunctionRunnerParams, ChatCompletionToolRunnerParams } from "./ChatCompletionRunner.js"; 6 | import { ChatCompletionStreamingFunctionRunnerParams, ChatCompletionStreamingToolRunnerParams } from "./ChatCompletionStreamingRunner.js"; 7 | import { BaseEvents, EventStream } from "./EventStream.js"; 8 | import { ParsedChatCompletion } from "../resources/beta/chat/completions.js"; 9 | import OpenAI from "../index.js"; 10 | export interface RunnerOptions extends Core.RequestOptions { 11 | /** How many requests to make before canceling. Default 10. */ 12 | maxChatCompletions?: number; 13 | } 14 | export declare class AbstractChatCompletionRunner extends EventStream { 15 | #private; 16 | protected _chatCompletions: ParsedChatCompletion[]; 17 | messages: ChatCompletionMessageParam[]; 18 | protected _addChatCompletion(this: AbstractChatCompletionRunner, chatCompletion: ParsedChatCompletion): ParsedChatCompletion; 19 | protected _addMessage(this: AbstractChatCompletionRunner, message: ChatCompletionMessageParam, emit?: boolean): void; 20 | /** 21 | * @returns a promise that resolves with the final ChatCompletion, or rejects 22 | * if an error occurred or the stream ended prematurely without producing a ChatCompletion. 23 | */ 24 | finalChatCompletion(): Promise>; 25 | /** 26 | * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects 27 | * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. 28 | */ 29 | finalContent(): Promise; 30 | /** 31 | * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, 32 | * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. 33 | */ 34 | finalMessage(): Promise; 35 | /** 36 | * @returns a promise that resolves with the content of the final FunctionCall, or rejects 37 | * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. 38 | */ 39 | finalFunctionCall(): Promise; 40 | finalFunctionCallResult(): Promise; 41 | totalUsage(): Promise; 42 | allChatCompletions(): ChatCompletion[]; 43 | protected _emitFinal(this: AbstractChatCompletionRunner): void; 44 | protected _createChatCompletion(client: OpenAI, params: ChatCompletionCreateParams, options?: Core.RequestOptions): Promise>; 45 | protected _runChatCompletion(client: OpenAI, params: ChatCompletionCreateParams, options?: Core.RequestOptions): Promise; 46 | protected _runFunctions(client: OpenAI, params: ChatCompletionFunctionRunnerParams | ChatCompletionStreamingFunctionRunnerParams, options?: RunnerOptions): Promise; 47 | protected _runTools(client: OpenAI, params: ChatCompletionToolRunnerParams | ChatCompletionStreamingToolRunnerParams, options?: RunnerOptions): Promise; 48 | } 49 | export interface AbstractChatCompletionRunnerEvents extends BaseEvents { 50 | functionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void; 51 | message: (message: ChatCompletionMessageParam) => void; 52 | chatCompletion: (completion: ChatCompletion) => void; 53 | finalContent: (contentSnapshot: string) => void; 54 | finalMessage: (message: ChatCompletionMessageParam) => void; 55 | finalChatCompletion: (completion: ChatCompletion) => void; 56 | finalFunctionCall: (functionCall: ChatCompletionMessage.FunctionCall) => void; 57 | functionCallResult: (content: string) => void; 58 | finalFunctionCallResult: (content: string) => void; 59 | totalUsage: (usage: CompletionUsage) => void; 60 | } 61 | //# sourceMappingURL=AbstractChatCompletionRunner.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/AssistantStream.d.ts: -------------------------------------------------------------------------------- 1 | import { Message, Text, ImageFile, TextDelta, MessageDelta } from "../resources/beta/threads/messages.js"; 2 | import * as Core from "../core.js"; 3 | import { RequestOptions } from "../core.js"; 4 | import { Run, RunCreateParamsBase, Runs, RunSubmitToolOutputsParamsBase } from "../resources/beta/threads/runs/runs.js"; 5 | import { type ReadableStream } from "../_shims/index.js"; 6 | import { AssistantStreamEvent } from "../resources/beta/assistants.js"; 7 | import { RunStep, RunStepDelta, ToolCall, ToolCallDelta } from "../resources/beta/threads/runs/steps.js"; 8 | import { ThreadCreateAndRunParamsBase, Threads } from "../resources/beta/threads/threads.js"; 9 | import { BaseEvents, EventStream } from "./EventStream.js"; 10 | export interface AssistantStreamEvents extends BaseEvents { 11 | run: (run: Run) => void; 12 | messageCreated: (message: Message) => void; 13 | messageDelta: (message: MessageDelta, snapshot: Message) => void; 14 | messageDone: (message: Message) => void; 15 | runStepCreated: (runStep: RunStep) => void; 16 | runStepDelta: (delta: RunStepDelta, snapshot: Runs.RunStep) => void; 17 | runStepDone: (runStep: Runs.RunStep, snapshot: Runs.RunStep) => void; 18 | toolCallCreated: (toolCall: ToolCall) => void; 19 | toolCallDelta: (delta: ToolCallDelta, snapshot: ToolCall) => void; 20 | toolCallDone: (toolCall: ToolCall) => void; 21 | textCreated: (content: Text) => void; 22 | textDelta: (delta: TextDelta, snapshot: Text) => void; 23 | textDone: (content: Text, snapshot: Message) => void; 24 | imageFileDone: (content: ImageFile, snapshot: Message) => void; 25 | event: (event: AssistantStreamEvent) => void; 26 | } 27 | export type ThreadCreateAndRunParamsBaseStream = Omit & { 28 | stream?: true; 29 | }; 30 | export type RunCreateParamsBaseStream = Omit & { 31 | stream?: true; 32 | }; 33 | export type RunSubmitToolOutputsParamsStream = Omit & { 34 | stream?: true; 35 | }; 36 | export declare class AssistantStream extends EventStream implements AsyncIterable { 37 | #private; 38 | [Symbol.asyncIterator](): AsyncIterator; 39 | static fromReadableStream(stream: ReadableStream): AssistantStream; 40 | protected _fromReadableStream(readableStream: ReadableStream, options?: Core.RequestOptions): Promise; 41 | toReadableStream(): ReadableStream; 42 | static createToolAssistantStream(threadId: string, runId: string, runs: Runs, params: RunSubmitToolOutputsParamsStream, options: RequestOptions | undefined): AssistantStream; 43 | protected _createToolAssistantStream(run: Runs, threadId: string, runId: string, params: RunSubmitToolOutputsParamsStream, options?: Core.RequestOptions): Promise; 44 | static createThreadAssistantStream(params: ThreadCreateAndRunParamsBaseStream, thread: Threads, options?: RequestOptions): AssistantStream; 45 | static createAssistantStream(threadId: string, runs: Runs, params: RunCreateParamsBaseStream, options?: RequestOptions): AssistantStream; 46 | currentEvent(): AssistantStreamEvent | undefined; 47 | currentRun(): Run | undefined; 48 | currentMessageSnapshot(): Message | undefined; 49 | currentRunStepSnapshot(): Runs.RunStep | undefined; 50 | finalRunSteps(): Promise; 51 | finalMessages(): Promise; 52 | finalRun(): Promise; 53 | protected _createThreadAssistantStream(thread: Threads, params: ThreadCreateAndRunParamsBase, options?: Core.RequestOptions): Promise; 54 | protected _createAssistantStream(run: Runs, threadId: string, params: RunCreateParamsBase, options?: Core.RequestOptions): Promise; 55 | static accumulateDelta(acc: Record, delta: Record): Record; 56 | protected _addRun(run: Run): Run; 57 | protected _threadAssistantStream(params: ThreadCreateAndRunParamsBase, thread: Threads, options?: Core.RequestOptions): Promise; 58 | protected _runAssistantStream(threadId: string, runs: Runs, params: RunCreateParamsBase, options?: Core.RequestOptions): Promise; 59 | protected _runToolAssistantStream(threadId: string, runId: string, runs: Runs, params: RunSubmitToolOutputsParamsStream, options?: Core.RequestOptions): Promise; 60 | } 61 | //# sourceMappingURL=AssistantStream.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/ChatCompletionRunner.d.ts: -------------------------------------------------------------------------------- 1 | import { type ChatCompletionMessageParam, type ChatCompletionCreateParamsNonStreaming } from "../resources/chat/completions.js"; 2 | import { type RunnableFunctions, type BaseFunctionsArgs, RunnableTools } from "./RunnableFunction.js"; 3 | import { AbstractChatCompletionRunner, AbstractChatCompletionRunnerEvents, RunnerOptions } from "./AbstractChatCompletionRunner.js"; 4 | import OpenAI from "../index.js"; 5 | import { AutoParseableTool } from "../lib/parser.js"; 6 | export interface ChatCompletionRunnerEvents extends AbstractChatCompletionRunnerEvents { 7 | content: (content: string) => void; 8 | } 9 | export type ChatCompletionFunctionRunnerParams = Omit & { 10 | functions: RunnableFunctions; 11 | }; 12 | export type ChatCompletionToolRunnerParams = Omit & { 13 | tools: RunnableTools | AutoParseableTool[]; 14 | }; 15 | export declare class ChatCompletionRunner extends AbstractChatCompletionRunner { 16 | /** @deprecated - please use `runTools` instead. */ 17 | static runFunctions(client: OpenAI, params: ChatCompletionFunctionRunnerParams, options?: RunnerOptions): ChatCompletionRunner; 18 | static runTools(client: OpenAI, params: ChatCompletionToolRunnerParams, options?: RunnerOptions): ChatCompletionRunner; 19 | _addMessage(this: ChatCompletionRunner, message: ChatCompletionMessageParam, emit?: boolean): void; 20 | } 21 | //# sourceMappingURL=ChatCompletionRunner.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/ChatCompletionStreamingRunner.d.ts: -------------------------------------------------------------------------------- 1 | import { type ChatCompletionChunk, type ChatCompletionCreateParamsStreaming } from "../resources/chat/completions.js"; 2 | import { RunnerOptions, type AbstractChatCompletionRunnerEvents } from "./AbstractChatCompletionRunner.js"; 3 | import { type ReadableStream } from "../_shims/index.js"; 4 | import { RunnableTools, type BaseFunctionsArgs, type RunnableFunctions } from "./RunnableFunction.js"; 5 | import { ChatCompletionSnapshot, ChatCompletionStream } from "./ChatCompletionStream.js"; 6 | import OpenAI from "../index.js"; 7 | import { AutoParseableTool } from "../lib/parser.js"; 8 | export interface ChatCompletionStreamEvents extends AbstractChatCompletionRunnerEvents { 9 | content: (contentDelta: string, contentSnapshot: string) => void; 10 | chunk: (chunk: ChatCompletionChunk, snapshot: ChatCompletionSnapshot) => void; 11 | } 12 | export type ChatCompletionStreamingFunctionRunnerParams = Omit & { 13 | functions: RunnableFunctions; 14 | }; 15 | export type ChatCompletionStreamingToolRunnerParams = Omit & { 16 | tools: RunnableTools | AutoParseableTool[]; 17 | }; 18 | export declare class ChatCompletionStreamingRunner extends ChatCompletionStream implements AsyncIterable { 19 | static fromReadableStream(stream: ReadableStream): ChatCompletionStreamingRunner; 20 | /** @deprecated - please use `runTools` instead. */ 21 | static runFunctions(client: OpenAI, params: ChatCompletionStreamingFunctionRunnerParams, options?: RunnerOptions): ChatCompletionStreamingRunner; 22 | static runTools(client: OpenAI, params: ChatCompletionStreamingToolRunnerParams, options?: RunnerOptions): ChatCompletionStreamingRunner; 23 | } 24 | //# sourceMappingURL=ChatCompletionStreamingRunner.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/EventStream.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import { APIUserAbortError, OpenAIError } from "../error.js"; 3 | export declare class EventStream { 4 | #private; 5 | controller: AbortController; 6 | constructor(); 7 | protected _run(this: EventStream, executor: () => Promise): void; 8 | protected _connected(this: EventStream): void; 9 | get ended(): boolean; 10 | get errored(): boolean; 11 | get aborted(): boolean; 12 | abort(): void; 13 | /** 14 | * Adds the listener function to the end of the listeners array for the event. 15 | * No checks are made to see if the listener has already been added. Multiple calls passing 16 | * the same combination of event and listener will result in the listener being added, and 17 | * called, multiple times. 18 | * @returns this ChatCompletionStream, so that calls can be chained 19 | */ 20 | on(event: Event, listener: EventListener): this; 21 | /** 22 | * Removes the specified listener from the listener array for the event. 23 | * off() will remove, at most, one instance of a listener from the listener array. If any single 24 | * listener has been added multiple times to the listener array for the specified event, then 25 | * off() must be called multiple times to remove each instance. 26 | * @returns this ChatCompletionStream, so that calls can be chained 27 | */ 28 | off(event: Event, listener: EventListener): this; 29 | /** 30 | * Adds a one-time listener function for the event. The next time the event is triggered, 31 | * this listener is removed and then invoked. 32 | * @returns this ChatCompletionStream, so that calls can be chained 33 | */ 34 | once(event: Event, listener: EventListener): this; 35 | /** 36 | * This is similar to `.once()`, but returns a Promise that resolves the next time 37 | * the event is triggered, instead of calling a listener callback. 38 | * @returns a Promise that resolves the next time given event is triggered, 39 | * or rejects if an error is emitted. (If you request the 'error' event, 40 | * returns a promise that resolves with the error). 41 | * 42 | * Example: 43 | * 44 | * const message = await stream.emitted('message') // rejects if the stream errors 45 | */ 46 | emitted(event: Event): Promise extends [infer Param] ? Param : EventParameters extends [] ? void : EventParameters>; 47 | done(): Promise; 48 | _emit(event: Event, ...args: EventParameters): void; 49 | _emit(event: Event, ...args: EventParameters): void; 50 | protected _emitFinal(): void; 51 | } 52 | type EventListener = Events[EventType]; 53 | export type EventParameters = { 54 | [Event in EventType]: EventListener extends (...args: infer P) => any ? P : never; 55 | }[EventType]; 56 | export interface BaseEvents { 57 | connect: () => void; 58 | error: (error: OpenAIError) => void; 59 | abort: (error: APIUserAbortError) => void; 60 | end: () => void; 61 | } 62 | export {}; 63 | //# sourceMappingURL=EventStream.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/RunnableFunction.d.ts: -------------------------------------------------------------------------------- 1 | import { type ChatCompletionRunner } from "./ChatCompletionRunner.js"; 2 | import { type ChatCompletionStreamingRunner } from "./ChatCompletionStreamingRunner.js"; 3 | import { JSONSchema } from "./jsonschema.js"; 4 | type PromiseOrValue = T | Promise; 5 | export type RunnableFunctionWithParse = { 6 | /** 7 | * @param args the return value from `parse`. 8 | * @param runner the runner evaluating this callback. 9 | * @returns a string to send back to OpenAI. 10 | */ 11 | function: (args: Args, runner: ChatCompletionRunner | ChatCompletionStreamingRunner) => PromiseOrValue; 12 | /** 13 | * @param input the raw args from the OpenAI function call. 14 | * @returns the parsed arguments to pass to `function` 15 | */ 16 | parse: (input: string) => PromiseOrValue; 17 | /** 18 | * The parameters the function accepts, describes as a JSON Schema object. 19 | */ 20 | parameters: JSONSchema; 21 | /** 22 | * A description of what the function does, used by the model to choose when and how to call the function. 23 | */ 24 | description: string; 25 | /** 26 | * The name of the function to be called. Will default to function.name if omitted. 27 | */ 28 | name?: string | undefined; 29 | strict?: boolean | undefined; 30 | }; 31 | export type RunnableFunctionWithoutParse = { 32 | /** 33 | * @param args the raw args from the OpenAI function call. 34 | * @returns a string to send back to OpenAI 35 | */ 36 | function: (args: string, runner: ChatCompletionRunner | ChatCompletionStreamingRunner) => PromiseOrValue; 37 | /** 38 | * The parameters the function accepts, describes as a JSON Schema object. 39 | */ 40 | parameters: JSONSchema; 41 | /** 42 | * A description of what the function does, used by the model to choose when and how to call the function. 43 | */ 44 | description: string; 45 | /** 46 | * The name of the function to be called. Will default to function.name if omitted. 47 | */ 48 | name?: string | undefined; 49 | strict?: boolean | undefined; 50 | }; 51 | export type RunnableFunction = Args extends string ? RunnableFunctionWithoutParse : Args extends object ? RunnableFunctionWithParse : never; 52 | export type RunnableToolFunction = Args extends string ? RunnableToolFunctionWithoutParse : Args extends object ? RunnableToolFunctionWithParse : never; 53 | export type RunnableToolFunctionWithoutParse = { 54 | type: 'function'; 55 | function: RunnableFunctionWithoutParse; 56 | }; 57 | export type RunnableToolFunctionWithParse = { 58 | type: 'function'; 59 | function: RunnableFunctionWithParse; 60 | }; 61 | export declare function isRunnableFunctionWithParse(fn: any): fn is RunnableFunctionWithParse; 62 | export type BaseFunctionsArgs = readonly (object | string)[]; 63 | export type RunnableFunctions = [ 64 | any[] 65 | ] extends [FunctionsArgs] ? readonly RunnableFunction[] : { 66 | [Index in keyof FunctionsArgs]: Index extends number ? RunnableFunction : FunctionsArgs[Index]; 67 | }; 68 | export type RunnableTools = [ 69 | any[] 70 | ] extends [FunctionsArgs] ? readonly RunnableToolFunction[] : { 71 | [Index in keyof FunctionsArgs]: Index extends number ? RunnableToolFunction : FunctionsArgs[Index]; 72 | }; 73 | /** 74 | * This is helper class for passing a `function` and `parse` where the `function` 75 | * argument type matches the `parse` return type. 76 | * 77 | * @deprecated - please use ParsingToolFunction instead. 78 | */ 79 | export declare class ParsingFunction { 80 | function: RunnableFunctionWithParse['function']; 81 | parse: RunnableFunctionWithParse['parse']; 82 | parameters: RunnableFunctionWithParse['parameters']; 83 | description: RunnableFunctionWithParse['description']; 84 | name?: RunnableFunctionWithParse['name']; 85 | constructor(input: RunnableFunctionWithParse); 86 | } 87 | /** 88 | * This is helper class for passing a `function` and `parse` where the `function` 89 | * argument type matches the `parse` return type. 90 | */ 91 | export declare class ParsingToolFunction { 92 | type: 'function'; 93 | function: RunnableFunctionWithParse; 94 | constructor(input: RunnableFunctionWithParse); 95 | } 96 | export {}; 97 | //# sourceMappingURL=RunnableFunction.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/Util.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Like `Promise.allSettled()` but throws an error if any promises are rejected. 3 | */ 4 | export declare const allSettledWithThrow: (promises: Promise[]) => Promise; 5 | //# sourceMappingURL=Util.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/chatCompletionUtils.d.ts: -------------------------------------------------------------------------------- 1 | import { type ChatCompletionAssistantMessageParam, type ChatCompletionFunctionMessageParam, type ChatCompletionMessageParam, type ChatCompletionToolMessageParam } from "../resources.js"; 2 | export declare const isAssistantMessage: (message: ChatCompletionMessageParam | null | undefined) => message is ChatCompletionAssistantMessageParam; 3 | export declare const isFunctionMessage: (message: ChatCompletionMessageParam | null | undefined) => message is ChatCompletionFunctionMessageParam; 4 | export declare const isToolMessage: (message: ChatCompletionMessageParam | null | undefined) => message is ChatCompletionToolMessageParam; 5 | export declare function isPresent(obj: T | null | undefined): obj is T; 6 | //# sourceMappingURL=chatCompletionUtils.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/jsonschema.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Primitive type 3 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 4 | */ 5 | export type JSONSchemaTypeName = ({} & string) | 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null'; 6 | /** 7 | * Primitive type 8 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1.1 9 | */ 10 | export type JSONSchemaType = string | number | boolean | JSONSchemaObject | JSONSchemaArray | null; 11 | export interface JSONSchemaObject { 12 | [key: string]: JSONSchemaType; 13 | } 14 | export interface JSONSchemaArray extends Array { 15 | } 16 | /** 17 | * Meta schema 18 | * 19 | * Recommended values: 20 | * - 'http://json-schema.org/schema#' 21 | * - 'http://json-schema.org/hyper-schema#' 22 | * - 'http://json-schema.org/draft-07/schema#' 23 | * - 'http://json-schema.org/draft-07/hyper-schema#' 24 | * 25 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-5 26 | */ 27 | export type JSONSchemaVersion = string; 28 | /** 29 | * JSON Schema v7 30 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01 31 | */ 32 | export type JSONSchemaDefinition = JSONSchema | boolean; 33 | export interface JSONSchema { 34 | $id?: string | undefined; 35 | $comment?: string | undefined; 36 | /** 37 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.1 38 | */ 39 | type?: JSONSchemaTypeName | JSONSchemaTypeName[] | undefined; 40 | enum?: JSONSchemaType[] | undefined; 41 | const?: JSONSchemaType | undefined; 42 | /** 43 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.2 44 | */ 45 | multipleOf?: number | undefined; 46 | maximum?: number | undefined; 47 | exclusiveMaximum?: number | undefined; 48 | minimum?: number | undefined; 49 | exclusiveMinimum?: number | undefined; 50 | /** 51 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.3 52 | */ 53 | maxLength?: number | undefined; 54 | minLength?: number | undefined; 55 | pattern?: string | undefined; 56 | /** 57 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.4 58 | */ 59 | items?: JSONSchemaDefinition | JSONSchemaDefinition[] | undefined; 60 | additionalItems?: JSONSchemaDefinition | undefined; 61 | maxItems?: number | undefined; 62 | minItems?: number | undefined; 63 | uniqueItems?: boolean | undefined; 64 | contains?: JSONSchemaDefinition | undefined; 65 | /** 66 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.5 67 | */ 68 | maxProperties?: number | undefined; 69 | minProperties?: number | undefined; 70 | required?: string[] | undefined; 71 | properties?: { 72 | [key: string]: JSONSchemaDefinition; 73 | } | undefined; 74 | patternProperties?: { 75 | [key: string]: JSONSchemaDefinition; 76 | } | undefined; 77 | additionalProperties?: JSONSchemaDefinition | undefined; 78 | propertyNames?: JSONSchemaDefinition | undefined; 79 | /** 80 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.6 81 | */ 82 | if?: JSONSchemaDefinition | undefined; 83 | then?: JSONSchemaDefinition | undefined; 84 | else?: JSONSchemaDefinition | undefined; 85 | /** 86 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-6.7 87 | */ 88 | allOf?: JSONSchemaDefinition[] | undefined; 89 | anyOf?: JSONSchemaDefinition[] | undefined; 90 | oneOf?: JSONSchemaDefinition[] | undefined; 91 | not?: JSONSchemaDefinition | undefined; 92 | /** 93 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-7 94 | */ 95 | format?: string | undefined; 96 | /** 97 | * @see https://tools.ietf.org/html/draft-handrews-json-schema-validation-01#section-10 98 | */ 99 | title?: string | undefined; 100 | description?: string | undefined; 101 | default?: JSONSchemaType | undefined; 102 | readOnly?: boolean | undefined; 103 | writeOnly?: boolean | undefined; 104 | examples?: JSONSchemaType | undefined; 105 | } 106 | //# sourceMappingURL=jsonschema.d.ts.map -------------------------------------------------------------------------------- /openai-types/lib/parser.d.ts: -------------------------------------------------------------------------------- 1 | import { ChatCompletion, ChatCompletionCreateParams, ChatCompletionMessageToolCall, ChatCompletionTool } from "../resources/chat/completions.js"; 2 | import { ChatCompletionStreamingToolRunnerParams, ChatCompletionStreamParams, ChatCompletionToolRunnerParams, ParsedChatCompletion } from "../resources/beta/chat/completions.js"; 3 | import { ResponseFormatJSONSchema } from "../resources/shared.js"; 4 | type AnyChatCompletionCreateParams = ChatCompletionCreateParams | ChatCompletionToolRunnerParams | ChatCompletionStreamingToolRunnerParams | ChatCompletionStreamParams; 5 | export type ExtractParsedContentFromParams = Params['response_format'] extends AutoParseableResponseFormat ? P : null; 6 | export type AutoParseableResponseFormat = ResponseFormatJSONSchema & { 7 | __output: ParsedT; 8 | $brand: 'auto-parseable-response-format'; 9 | $parseRaw(content: string): ParsedT; 10 | }; 11 | export declare function makeParseableResponseFormat(response_format: ResponseFormatJSONSchema, parser: (content: string) => ParsedT): AutoParseableResponseFormat; 12 | export declare function isAutoParsableResponseFormat(response_format: any): response_format is AutoParseableResponseFormat; 13 | type ToolOptions = { 14 | name: string; 15 | arguments: any; 16 | function?: ((args: any) => any) | undefined; 17 | }; 18 | export type AutoParseableTool = ChatCompletionTool & { 19 | __arguments: OptionsT['arguments']; 20 | __name: OptionsT['name']; 21 | __hasFunction: HasFunction; 22 | $brand: 'auto-parseable-tool'; 23 | $callback: ((args: OptionsT['arguments']) => any) | undefined; 24 | $parseRaw(args: string): OptionsT['arguments']; 25 | }; 26 | export declare function makeParseableTool(tool: ChatCompletionTool, { parser, callback, }: { 27 | parser: (content: string) => OptionsT['arguments']; 28 | callback: ((args: any) => any) | undefined; 29 | }): AutoParseableTool; 30 | export declare function isAutoParsableTool(tool: any): tool is AutoParseableTool; 31 | export declare function maybeParseChatCompletion>>(completion: ChatCompletion, params: Params): ParsedChatCompletion; 32 | export declare function parseChatCompletion>(completion: ChatCompletion, params: Params): ParsedChatCompletion; 33 | export declare function shouldParseToolCall(params: ChatCompletionCreateParams | null | undefined, toolCall: ChatCompletionMessageToolCall): boolean; 34 | export declare function hasAutoParseableInput(params: AnyChatCompletionCreateParams): boolean; 35 | export declare function validateInputTools(tools: ChatCompletionTool[] | undefined): void; 36 | export {}; 37 | //# sourceMappingURL=parser.d.ts.map -------------------------------------------------------------------------------- /openai-types/pagination.d.ts: -------------------------------------------------------------------------------- 1 | import { AbstractPage, Response, APIClient, FinalRequestOptions, PageInfo } from "./core.js"; 2 | export interface PageResponse { 3 | data: Array; 4 | object: string; 5 | } 6 | /** 7 | * Note: no pagination actually occurs yet, this is for forwards-compatibility. 8 | */ 9 | export declare class Page extends AbstractPage implements PageResponse { 10 | data: Array; 11 | object: string; 12 | constructor(client: APIClient, response: Response, body: PageResponse, options: FinalRequestOptions); 13 | getPaginatedItems(): Item[]; 14 | /** 15 | * This page represents a response that isn't actually paginated at the API level 16 | * so there will never be any next page params. 17 | */ 18 | nextPageParams(): null; 19 | nextPageInfo(): null; 20 | } 21 | export interface CursorPageResponse { 22 | data: Array; 23 | } 24 | export interface CursorPageParams { 25 | after?: string; 26 | limit?: number; 27 | } 28 | export declare class CursorPage extends AbstractPage implements CursorPageResponse { 31 | data: Array; 32 | constructor(client: APIClient, response: Response, body: CursorPageResponse, options: FinalRequestOptions); 33 | getPaginatedItems(): Item[]; 34 | nextPageParams(): Partial | null; 35 | nextPageInfo(): PageInfo | null; 36 | } 37 | //# sourceMappingURL=pagination.d.ts.map -------------------------------------------------------------------------------- /openai-types/resource.d.ts: -------------------------------------------------------------------------------- 1 | import type { OpenAI } from "./index.js"; 2 | export declare class APIResource { 3 | protected _client: OpenAI; 4 | constructor(client: OpenAI); 5 | } 6 | //# sourceMappingURL=resource.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/audio/audio.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../resource.js"; 2 | import * as SpeechAPI from "./speech.js"; 3 | import { Speech, SpeechCreateParams, SpeechModel } from "./speech.js"; 4 | import * as TranscriptionsAPI from "./transcriptions.js"; 5 | import { Transcription, TranscriptionCreateParams, TranscriptionCreateResponse, TranscriptionSegment, TranscriptionVerbose, TranscriptionWord, Transcriptions } from "./transcriptions.js"; 6 | import * as TranslationsAPI from "./translations.js"; 7 | import { Translation, TranslationCreateParams, TranslationCreateResponse, TranslationVerbose, Translations } from "./translations.js"; 8 | export declare class Audio extends APIResource { 9 | transcriptions: TranscriptionsAPI.Transcriptions; 10 | translations: TranslationsAPI.Translations; 11 | speech: SpeechAPI.Speech; 12 | } 13 | export type AudioModel = 'whisper-1'; 14 | /** 15 | * The format of the output, in one of these options: `json`, `text`, `srt`, 16 | * `verbose_json`, or `vtt`. 17 | */ 18 | export type AudioResponseFormat = 'json' | 'text' | 'srt' | 'verbose_json' | 'vtt'; 19 | export declare namespace Audio { 20 | export { type AudioModel as AudioModel, type AudioResponseFormat as AudioResponseFormat }; 21 | export { Transcriptions as Transcriptions, type Transcription as Transcription, type TranscriptionSegment as TranscriptionSegment, type TranscriptionVerbose as TranscriptionVerbose, type TranscriptionWord as TranscriptionWord, type TranscriptionCreateResponse as TranscriptionCreateResponse, type TranscriptionCreateParams as TranscriptionCreateParams, }; 22 | export { Translations as Translations, type Translation as Translation, type TranslationVerbose as TranslationVerbose, type TranslationCreateResponse as TranslationCreateResponse, type TranslationCreateParams as TranslationCreateParams, }; 23 | export { Speech as Speech, type SpeechModel as SpeechModel, type SpeechCreateParams as SpeechCreateParams }; 24 | } 25 | //# sourceMappingURL=audio.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/audio/index.d.ts: -------------------------------------------------------------------------------- 1 | export { Audio, type AudioModel, type AudioResponseFormat } from "./audio.js"; 2 | export { Speech, type SpeechModel, type SpeechCreateParams } from "./speech.js"; 3 | export { Transcriptions, type Transcription, type TranscriptionSegment, type TranscriptionVerbose, type TranscriptionWord, type TranscriptionCreateResponse, type TranscriptionCreateParams, } from "./transcriptions.js"; 4 | export { Translations, type Translation, type TranslationVerbose, type TranslationCreateResponse, type TranslationCreateParams, } from "./translations.js"; 5 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/audio/speech.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../resource.js"; 2 | import * as Core from "../../core.js"; 3 | import { type Response } from "../../_shims/index.js"; 4 | export declare class Speech extends APIResource { 5 | /** 6 | * Generates audio from the input text. 7 | */ 8 | create(body: SpeechCreateParams, options?: Core.RequestOptions): Core.APIPromise; 9 | } 10 | export type SpeechModel = 'tts-1' | 'tts-1-hd'; 11 | export interface SpeechCreateParams { 12 | /** 13 | * The text to generate audio for. The maximum length is 4096 characters. 14 | */ 15 | input: string; 16 | /** 17 | * One of the available [TTS models](https://platform.openai.com/docs/models#tts): 18 | * `tts-1` or `tts-1-hd` 19 | */ 20 | model: (string & {}) | SpeechModel; 21 | /** 22 | * The voice to use when generating the audio. Supported voices are `alloy`, 23 | * `echo`, `fable`, `onyx`, `nova`, and `shimmer`. Previews of the voices are 24 | * available in the 25 | * [Text to speech guide](https://platform.openai.com/docs/guides/text-to-speech#voice-options). 26 | */ 27 | voice: 'alloy' | 'echo' | 'fable' | 'onyx' | 'nova' | 'shimmer'; 28 | /** 29 | * The format to audio in. Supported formats are `mp3`, `opus`, `aac`, `flac`, 30 | * `wav`, and `pcm`. 31 | */ 32 | response_format?: 'mp3' | 'opus' | 'aac' | 'flac' | 'wav' | 'pcm'; 33 | /** 34 | * The speed of the generated audio. Select a value from `0.25` to `4.0`. `1.0` is 35 | * the default. 36 | */ 37 | speed?: number; 38 | } 39 | export declare namespace Speech { 40 | export { type SpeechModel as SpeechModel, type SpeechCreateParams as SpeechCreateParams }; 41 | } 42 | //# sourceMappingURL=speech.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/audio/transcriptions.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../resource.js"; 2 | import * as Core from "../../core.js"; 3 | import * as AudioAPI from "./audio.js"; 4 | export declare class Transcriptions extends APIResource { 5 | /** 6 | * Transcribes audio into the input language. 7 | */ 8 | create(body: TranscriptionCreateParams<'json' | undefined>, options?: Core.RequestOptions): Core.APIPromise; 9 | create(body: TranscriptionCreateParams<'verbose_json'>, options?: Core.RequestOptions): Core.APIPromise; 10 | create(body: TranscriptionCreateParams<'srt' | 'vtt' | 'text'>, options?: Core.RequestOptions): Core.APIPromise; 11 | create(body: TranscriptionCreateParams, options?: Core.RequestOptions): Core.APIPromise; 12 | } 13 | /** 14 | * Represents a transcription response returned by model, based on the provided 15 | * input. 16 | */ 17 | export interface Transcription { 18 | /** 19 | * The transcribed text. 20 | */ 21 | text: string; 22 | } 23 | export interface TranscriptionSegment { 24 | /** 25 | * Unique identifier of the segment. 26 | */ 27 | id: number; 28 | /** 29 | * Average logprob of the segment. If the value is lower than -1, consider the 30 | * logprobs failed. 31 | */ 32 | avg_logprob: number; 33 | /** 34 | * Compression ratio of the segment. If the value is greater than 2.4, consider the 35 | * compression failed. 36 | */ 37 | compression_ratio: number; 38 | /** 39 | * End time of the segment in seconds. 40 | */ 41 | end: number; 42 | /** 43 | * Probability of no speech in the segment. If the value is higher than 1.0 and the 44 | * `avg_logprob` is below -1, consider this segment silent. 45 | */ 46 | no_speech_prob: number; 47 | /** 48 | * Seek offset of the segment. 49 | */ 50 | seek: number; 51 | /** 52 | * Start time of the segment in seconds. 53 | */ 54 | start: number; 55 | /** 56 | * Temperature parameter used for generating the segment. 57 | */ 58 | temperature: number; 59 | /** 60 | * Text content of the segment. 61 | */ 62 | text: string; 63 | /** 64 | * Array of token IDs for the text content. 65 | */ 66 | tokens: Array; 67 | } 68 | /** 69 | * Represents a verbose json transcription response returned by model, based on the 70 | * provided input. 71 | */ 72 | export interface TranscriptionVerbose { 73 | /** 74 | * The duration of the input audio. 75 | */ 76 | duration: string; 77 | /** 78 | * The language of the input audio. 79 | */ 80 | language: string; 81 | /** 82 | * The transcribed text. 83 | */ 84 | text: string; 85 | /** 86 | * Segments of the transcribed text and their corresponding details. 87 | */ 88 | segments?: Array; 89 | /** 90 | * Extracted words and their corresponding timestamps. 91 | */ 92 | words?: Array; 93 | } 94 | export interface TranscriptionWord { 95 | /** 96 | * End time of the word in seconds. 97 | */ 98 | end: number; 99 | /** 100 | * Start time of the word in seconds. 101 | */ 102 | start: number; 103 | /** 104 | * The text content of the word. 105 | */ 106 | word: string; 107 | } 108 | /** 109 | * Represents a transcription response returned by model, based on the provided 110 | * input. 111 | */ 112 | export type TranscriptionCreateResponse = Transcription | TranscriptionVerbose; 113 | export interface TranscriptionCreateParams { 114 | /** 115 | * The audio file object (not file name) to transcribe, in one of these formats: 116 | * flac, mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. 117 | */ 118 | file: Core.Uploadable; 119 | /** 120 | * ID of the model to use. Only `whisper-1` (which is powered by our open source 121 | * Whisper V2 model) is currently available. 122 | */ 123 | model: (string & {}) | AudioAPI.AudioModel; 124 | /** 125 | * The language of the input audio. Supplying the input language in 126 | * [ISO-639-1](https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes) format will 127 | * improve accuracy and latency. 128 | */ 129 | language?: string; 130 | /** 131 | * An optional text to guide the model's style or continue a previous audio 132 | * segment. The 133 | * [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) 134 | * should match the audio language. 135 | */ 136 | prompt?: string; 137 | /** 138 | * The format of the output, in one of these options: `json`, `text`, `srt`, 139 | * `verbose_json`, or `vtt`. 140 | */ 141 | response_format?: ResponseFormat; 142 | /** 143 | * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the 144 | * output more random, while lower values like 0.2 will make it more focused and 145 | * deterministic. If set to 0, the model will use 146 | * [log probability](https://en.wikipedia.org/wiki/Log_probability) to 147 | * automatically increase the temperature until certain thresholds are hit. 148 | */ 149 | temperature?: number; 150 | /** 151 | * The timestamp granularities to populate for this transcription. 152 | * `response_format` must be set `verbose_json` to use timestamp granularities. 153 | * Either or both of these options are supported: `word`, or `segment`. Note: There 154 | * is no additional latency for segment timestamps, but generating word timestamps 155 | * incurs additional latency. 156 | */ 157 | timestamp_granularities?: Array<'word' | 'segment'>; 158 | } 159 | export declare namespace Transcriptions { 160 | export { type Transcription as Transcription, type TranscriptionSegment as TranscriptionSegment, type TranscriptionVerbose as TranscriptionVerbose, type TranscriptionWord as TranscriptionWord, type TranscriptionCreateResponse as TranscriptionCreateResponse, type TranscriptionCreateParams as TranscriptionCreateParams, }; 161 | } 162 | //# sourceMappingURL=transcriptions.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/audio/translations.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../resource.js"; 2 | import * as Core from "../../core.js"; 3 | import * as AudioAPI from "./audio.js"; 4 | import * as TranscriptionsAPI from "./transcriptions.js"; 5 | export declare class Translations extends APIResource { 6 | /** 7 | * Translates audio into English. 8 | */ 9 | create(body: TranslationCreateParams<'json' | undefined>, options?: Core.RequestOptions): Core.APIPromise; 10 | create(body: TranslationCreateParams<'verbose_json'>, options?: Core.RequestOptions): Core.APIPromise; 11 | create(body: TranslationCreateParams<'text' | 'srt' | 'vtt'>, options?: Core.RequestOptions): Core.APIPromise; 12 | create(body: TranslationCreateParams, options?: Core.RequestOptions): Core.APIPromise; 13 | } 14 | export interface Translation { 15 | text: string; 16 | } 17 | export interface TranslationVerbose { 18 | /** 19 | * The duration of the input audio. 20 | */ 21 | duration: string; 22 | /** 23 | * The language of the output translation (always `english`). 24 | */ 25 | language: string; 26 | /** 27 | * The translated text. 28 | */ 29 | text: string; 30 | /** 31 | * Segments of the translated text and their corresponding details. 32 | */ 33 | segments?: Array; 34 | } 35 | export type TranslationCreateResponse = Translation | TranslationVerbose; 36 | export interface TranslationCreateParams { 37 | /** 38 | * The audio file object (not file name) translate, in one of these formats: flac, 39 | * mp3, mp4, mpeg, mpga, m4a, ogg, wav, or webm. 40 | */ 41 | file: Core.Uploadable; 42 | /** 43 | * ID of the model to use. Only `whisper-1` (which is powered by our open source 44 | * Whisper V2 model) is currently available. 45 | */ 46 | model: (string & {}) | AudioAPI.AudioModel; 47 | /** 48 | * An optional text to guide the model's style or continue a previous audio 49 | * segment. The 50 | * [prompt](https://platform.openai.com/docs/guides/speech-to-text#prompting) 51 | * should be in English. 52 | */ 53 | prompt?: string; 54 | /** 55 | * The format of the output, in one of these options: `json`, `text`, `srt`, 56 | * `verbose_json`, or `vtt`. 57 | */ 58 | response_format?: ResponseFormat; 59 | /** 60 | * The sampling temperature, between 0 and 1. Higher values like 0.8 will make the 61 | * output more random, while lower values like 0.2 will make it more focused and 62 | * deterministic. If set to 0, the model will use 63 | * [log probability](https://en.wikipedia.org/wiki/Log_probability) to 64 | * automatically increase the temperature until certain thresholds are hit. 65 | */ 66 | temperature?: number; 67 | } 68 | export declare namespace Translations { 69 | export { type Translation as Translation, type TranslationVerbose as TranslationVerbose, type TranslationCreateResponse as TranslationCreateResponse, type TranslationCreateParams as TranslationCreateParams, }; 70 | } 71 | //# sourceMappingURL=translations.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/batches.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../resource.js"; 2 | import * as Core from "../core.js"; 3 | import * as BatchesAPI from "./batches.js"; 4 | import { CursorPage, type CursorPageParams } from "../pagination.js"; 5 | export declare class Batches extends APIResource { 6 | /** 7 | * Creates and executes a batch from an uploaded file of requests 8 | */ 9 | create(body: BatchCreateParams, options?: Core.RequestOptions): Core.APIPromise; 10 | /** 11 | * Retrieves a batch. 12 | */ 13 | retrieve(batchId: string, options?: Core.RequestOptions): Core.APIPromise; 14 | /** 15 | * List your organization's batches. 16 | */ 17 | list(query?: BatchListParams, options?: Core.RequestOptions): Core.PagePromise; 18 | list(options?: Core.RequestOptions): Core.PagePromise; 19 | /** 20 | * Cancels an in-progress batch. The batch will be in status `cancelling` for up to 21 | * 10 minutes, before changing to `cancelled`, where it will have partial results 22 | * (if any) available in the output file. 23 | */ 24 | cancel(batchId: string, options?: Core.RequestOptions): Core.APIPromise; 25 | } 26 | export declare class BatchesPage extends CursorPage { 27 | } 28 | export interface Batch { 29 | id: string; 30 | /** 31 | * The time frame within which the batch should be processed. 32 | */ 33 | completion_window: string; 34 | /** 35 | * The Unix timestamp (in seconds) for when the batch was created. 36 | */ 37 | created_at: number; 38 | /** 39 | * The OpenAI API endpoint used by the batch. 40 | */ 41 | endpoint: string; 42 | /** 43 | * The ID of the input file for the batch. 44 | */ 45 | input_file_id: string; 46 | /** 47 | * The object type, which is always `batch`. 48 | */ 49 | object: 'batch'; 50 | /** 51 | * The current status of the batch. 52 | */ 53 | status: 'validating' | 'failed' | 'in_progress' | 'finalizing' | 'completed' | 'expired' | 'cancelling' | 'cancelled'; 54 | /** 55 | * The Unix timestamp (in seconds) for when the batch was cancelled. 56 | */ 57 | cancelled_at?: number; 58 | /** 59 | * The Unix timestamp (in seconds) for when the batch started cancelling. 60 | */ 61 | cancelling_at?: number; 62 | /** 63 | * The Unix timestamp (in seconds) for when the batch was completed. 64 | */ 65 | completed_at?: number; 66 | /** 67 | * The ID of the file containing the outputs of requests with errors. 68 | */ 69 | error_file_id?: string; 70 | errors?: Batch.Errors; 71 | /** 72 | * The Unix timestamp (in seconds) for when the batch expired. 73 | */ 74 | expired_at?: number; 75 | /** 76 | * The Unix timestamp (in seconds) for when the batch will expire. 77 | */ 78 | expires_at?: number; 79 | /** 80 | * The Unix timestamp (in seconds) for when the batch failed. 81 | */ 82 | failed_at?: number; 83 | /** 84 | * The Unix timestamp (in seconds) for when the batch started finalizing. 85 | */ 86 | finalizing_at?: number; 87 | /** 88 | * The Unix timestamp (in seconds) for when the batch started processing. 89 | */ 90 | in_progress_at?: number; 91 | /** 92 | * Set of 16 key-value pairs that can be attached to an object. This can be useful 93 | * for storing additional information about the object in a structured format. Keys 94 | * can be a maximum of 64 characters long and values can be a maxium of 512 95 | * characters long. 96 | */ 97 | metadata?: unknown | null; 98 | /** 99 | * The ID of the file containing the outputs of successfully executed requests. 100 | */ 101 | output_file_id?: string; 102 | /** 103 | * The request counts for different statuses within the batch. 104 | */ 105 | request_counts?: BatchRequestCounts; 106 | } 107 | export declare namespace Batch { 108 | interface Errors { 109 | data?: Array; 110 | /** 111 | * The object type, which is always `list`. 112 | */ 113 | object?: string; 114 | } 115 | } 116 | export interface BatchError { 117 | /** 118 | * An error code identifying the error type. 119 | */ 120 | code?: string; 121 | /** 122 | * The line number of the input file where the error occurred, if applicable. 123 | */ 124 | line?: number | null; 125 | /** 126 | * A human-readable message providing more details about the error. 127 | */ 128 | message?: string; 129 | /** 130 | * The name of the parameter that caused the error, if applicable. 131 | */ 132 | param?: string | null; 133 | } 134 | /** 135 | * The request counts for different statuses within the batch. 136 | */ 137 | export interface BatchRequestCounts { 138 | /** 139 | * Number of requests that have been completed successfully. 140 | */ 141 | completed: number; 142 | /** 143 | * Number of requests that have failed. 144 | */ 145 | failed: number; 146 | /** 147 | * Total number of requests in the batch. 148 | */ 149 | total: number; 150 | } 151 | export interface BatchCreateParams { 152 | /** 153 | * The time frame within which the batch should be processed. Currently only `24h` 154 | * is supported. 155 | */ 156 | completion_window: '24h'; 157 | /** 158 | * The endpoint to be used for all requests in the batch. Currently 159 | * `/v1/chat/completions`, `/v1/embeddings`, and `/v1/completions` are supported. 160 | * Note that `/v1/embeddings` batches are also restricted to a maximum of 50,000 161 | * embedding inputs across all requests in the batch. 162 | */ 163 | endpoint: '/v1/chat/completions' | '/v1/embeddings' | '/v1/completions'; 164 | /** 165 | * The ID of an uploaded file that contains requests for the new batch. 166 | * 167 | * See [upload file](https://platform.openai.com/docs/api-reference/files/create) 168 | * for how to upload a file. 169 | * 170 | * Your input file must be formatted as a 171 | * [JSONL file](https://platform.openai.com/docs/api-reference/batch/request-input), 172 | * and must be uploaded with the purpose `batch`. The file can contain up to 50,000 173 | * requests, and can be up to 200 MB in size. 174 | */ 175 | input_file_id: string; 176 | /** 177 | * Optional custom metadata for the batch. 178 | */ 179 | metadata?: Record | null; 180 | } 181 | export interface BatchListParams extends CursorPageParams { 182 | } 183 | export declare namespace Batches { 184 | export { type Batch as Batch, type BatchError as BatchError, type BatchRequestCounts as BatchRequestCounts, BatchesPage as BatchesPage, type BatchCreateParams as BatchCreateParams, type BatchListParams as BatchListParams, }; 185 | } 186 | //# sourceMappingURL=batches.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/beta/beta.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../resource.js"; 2 | import * as AssistantsAPI from "./assistants.js"; 3 | import * as ChatAPI from "./chat/chat.js"; 4 | import { Assistant, AssistantCreateParams, AssistantDeleted, AssistantListParams, AssistantStreamEvent, AssistantTool, AssistantUpdateParams, Assistants, AssistantsPage, CodeInterpreterTool, FileSearchTool, FunctionTool, MessageStreamEvent, RunStepStreamEvent, RunStreamEvent, ThreadStreamEvent } from "./assistants.js"; 5 | import * as ThreadsAPI from "./threads/threads.js"; 6 | import { AssistantResponseFormatOption, AssistantToolChoice, AssistantToolChoiceFunction, AssistantToolChoiceOption, Thread, ThreadCreateAndRunParams, ThreadCreateAndRunParamsNonStreaming, ThreadCreateAndRunParamsStreaming, ThreadCreateAndRunPollParams, ThreadCreateAndRunStreamParams, ThreadCreateParams, ThreadDeleted, ThreadUpdateParams, Threads } from "./threads/threads.js"; 7 | import * as VectorStoresAPI from "./vector-stores/vector-stores.js"; 8 | import { AutoFileChunkingStrategyParam, FileChunkingStrategy, FileChunkingStrategyParam, OtherFileChunkingStrategyObject, StaticFileChunkingStrategy, StaticFileChunkingStrategyObject, StaticFileChunkingStrategyParam, VectorStore, VectorStoreCreateParams, VectorStoreDeleted, VectorStoreListParams, VectorStoreUpdateParams, VectorStores, VectorStoresPage } from "./vector-stores/vector-stores.js"; 9 | import { Chat } from "./chat/chat.js"; 10 | export declare class Beta extends APIResource { 11 | vectorStores: VectorStoresAPI.VectorStores; 12 | chat: ChatAPI.Chat; 13 | assistants: AssistantsAPI.Assistants; 14 | threads: ThreadsAPI.Threads; 15 | } 16 | export declare namespace Beta { 17 | export { VectorStores as VectorStores, type AutoFileChunkingStrategyParam as AutoFileChunkingStrategyParam, type FileChunkingStrategy as FileChunkingStrategy, type FileChunkingStrategyParam as FileChunkingStrategyParam, type OtherFileChunkingStrategyObject as OtherFileChunkingStrategyObject, type StaticFileChunkingStrategy as StaticFileChunkingStrategy, type StaticFileChunkingStrategyObject as StaticFileChunkingStrategyObject, type StaticFileChunkingStrategyParam as StaticFileChunkingStrategyParam, type VectorStore as VectorStore, type VectorStoreDeleted as VectorStoreDeleted, VectorStoresPage as VectorStoresPage, type VectorStoreCreateParams as VectorStoreCreateParams, type VectorStoreUpdateParams as VectorStoreUpdateParams, type VectorStoreListParams as VectorStoreListParams, }; 18 | export { Chat }; 19 | export { Assistants as Assistants, type Assistant as Assistant, type AssistantDeleted as AssistantDeleted, type AssistantStreamEvent as AssistantStreamEvent, type AssistantTool as AssistantTool, type CodeInterpreterTool as CodeInterpreterTool, type FileSearchTool as FileSearchTool, type FunctionTool as FunctionTool, type MessageStreamEvent as MessageStreamEvent, type RunStepStreamEvent as RunStepStreamEvent, type RunStreamEvent as RunStreamEvent, type ThreadStreamEvent as ThreadStreamEvent, AssistantsPage as AssistantsPage, type AssistantCreateParams as AssistantCreateParams, type AssistantUpdateParams as AssistantUpdateParams, type AssistantListParams as AssistantListParams, }; 20 | export { Threads as Threads, type AssistantResponseFormatOption as AssistantResponseFormatOption, type AssistantToolChoice as AssistantToolChoice, type AssistantToolChoiceFunction as AssistantToolChoiceFunction, type AssistantToolChoiceOption as AssistantToolChoiceOption, type Thread as Thread, type ThreadDeleted as ThreadDeleted, type ThreadCreateParams as ThreadCreateParams, type ThreadUpdateParams as ThreadUpdateParams, type ThreadCreateAndRunParams as ThreadCreateAndRunParams, type ThreadCreateAndRunParamsNonStreaming as ThreadCreateAndRunParamsNonStreaming, type ThreadCreateAndRunParamsStreaming as ThreadCreateAndRunParamsStreaming, type ThreadCreateAndRunPollParams, type ThreadCreateAndRunStreamParams, }; 21 | } 22 | //# sourceMappingURL=beta.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/beta/chat/chat.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../../resource.js"; 2 | import * as CompletionsAPI from "./completions.js"; 3 | export declare class Chat extends APIResource { 4 | completions: CompletionsAPI.Completions; 5 | } 6 | export declare namespace Chat { 7 | export import Completions = CompletionsAPI.Completions; 8 | } 9 | //# sourceMappingURL=chat.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/beta/chat/completions.d.ts: -------------------------------------------------------------------------------- 1 | import * as Core from "../../../core.js"; 2 | import { APIResource } from "../../../resource.js"; 3 | import { ChatCompletionRunner, ChatCompletionFunctionRunnerParams } from "../../../lib/ChatCompletionRunner.js"; 4 | import { ChatCompletionStreamingRunner, ChatCompletionStreamingFunctionRunnerParams } from "../../../lib/ChatCompletionStreamingRunner.js"; 5 | import { BaseFunctionsArgs } from "../../../lib/RunnableFunction.js"; 6 | import { RunnerOptions } from "../../../lib/AbstractChatCompletionRunner.js"; 7 | import { ChatCompletionToolRunnerParams } from "../../../lib/ChatCompletionRunner.js"; 8 | import { ChatCompletionStreamingToolRunnerParams } from "../../../lib/ChatCompletionStreamingRunner.js"; 9 | import { ChatCompletionStream, type ChatCompletionStreamParams } from "../../../lib/ChatCompletionStream.js"; 10 | import { ChatCompletion, ChatCompletionCreateParamsNonStreaming, ChatCompletionMessage, ChatCompletionMessageToolCall } from "../../chat/completions.js"; 11 | import { ExtractParsedContentFromParams } from "../../../lib/parser.js"; 12 | export { ChatCompletionStreamingRunner, type ChatCompletionStreamingFunctionRunnerParams, } from "../../../lib/ChatCompletionStreamingRunner.js"; 13 | export { type RunnableFunction, type RunnableFunctions, type RunnableFunctionWithParse, type RunnableFunctionWithoutParse, ParsingFunction, ParsingToolFunction, } from "../../../lib/RunnableFunction.js"; 14 | export { type ChatCompletionToolRunnerParams } from "../../../lib/ChatCompletionRunner.js"; 15 | export { type ChatCompletionStreamingToolRunnerParams } from "../../../lib/ChatCompletionStreamingRunner.js"; 16 | export { ChatCompletionStream, type ChatCompletionStreamParams } from "../../../lib/ChatCompletionStream.js"; 17 | export { ChatCompletionRunner, type ChatCompletionFunctionRunnerParams, } from "../../../lib/ChatCompletionRunner.js"; 18 | export interface ParsedFunction extends ChatCompletionMessageToolCall.Function { 19 | parsed_arguments?: unknown; 20 | } 21 | export interface ParsedFunctionToolCall extends ChatCompletionMessageToolCall { 22 | function: ParsedFunction; 23 | } 24 | export interface ParsedChatCompletionMessage extends ChatCompletionMessage { 25 | parsed: ParsedT | null; 26 | tool_calls: Array; 27 | } 28 | export interface ParsedChoice extends ChatCompletion.Choice { 29 | message: ParsedChatCompletionMessage; 30 | } 31 | export interface ParsedChatCompletion extends ChatCompletion { 32 | choices: Array>; 33 | } 34 | export type ChatCompletionParseParams = ChatCompletionCreateParamsNonStreaming; 35 | export declare class Completions extends APIResource { 36 | parse>(body: Params, options?: Core.RequestOptions): Core.APIPromise>; 37 | /** 38 | * @deprecated - use `runTools` instead. 39 | */ 40 | runFunctions(body: ChatCompletionFunctionRunnerParams, options?: Core.RequestOptions): ChatCompletionRunner; 41 | runFunctions(body: ChatCompletionStreamingFunctionRunnerParams, options?: Core.RequestOptions): ChatCompletionStreamingRunner; 42 | /** 43 | * A convenience helper for using tool calls with the /chat/completions endpoint 44 | * which automatically calls the JavaScript functions you provide and sends their 45 | * results back to the /chat/completions endpoint, looping as long as the model 46 | * requests function calls. 47 | * 48 | * For more details and examples, see 49 | * [the docs](https://github.com/openai/openai-node#automated-function-calls) 50 | */ 51 | runTools, ParsedT = ExtractParsedContentFromParams>(body: Params, options?: RunnerOptions): ChatCompletionRunner; 52 | runTools, ParsedT = ExtractParsedContentFromParams>(body: Params, options?: RunnerOptions): ChatCompletionStreamingRunner; 53 | /** 54 | * Creates a chat completion stream 55 | */ 56 | stream>(body: Params, options?: Core.RequestOptions): ChatCompletionStream; 57 | } 58 | //# sourceMappingURL=completions.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/beta/chat/index.d.ts: -------------------------------------------------------------------------------- 1 | export { Chat } from "./chat.js"; 2 | export { Completions } from "./completions.js"; 3 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/beta/index.d.ts: -------------------------------------------------------------------------------- 1 | export { AssistantsPage, Assistants, type Assistant, type AssistantDeleted, type AssistantStreamEvent, type AssistantTool, type CodeInterpreterTool, type FileSearchTool, type FunctionTool, type MessageStreamEvent, type RunStepStreamEvent, type RunStreamEvent, type ThreadStreamEvent, type AssistantCreateParams, type AssistantUpdateParams, type AssistantListParams, } from "./assistants.js"; 2 | export { Beta } from "./beta.js"; 3 | export { Chat } from "./chat/index.js"; 4 | export { Threads, type AssistantResponseFormatOption, type AssistantToolChoice, type AssistantToolChoiceFunction, type AssistantToolChoiceOption, type Thread, type ThreadDeleted, type ThreadCreateParams, type ThreadUpdateParams, type ThreadCreateAndRunParams, type ThreadCreateAndRunParamsNonStreaming, type ThreadCreateAndRunParamsStreaming, type ThreadCreateAndRunPollParams, type ThreadCreateAndRunStreamParams, } from "./threads/index.js"; 5 | export { VectorStoresPage, VectorStores, type AutoFileChunkingStrategyParam, type FileChunkingStrategy, type FileChunkingStrategyParam, type OtherFileChunkingStrategyObject, type StaticFileChunkingStrategy, type StaticFileChunkingStrategyObject, type StaticFileChunkingStrategyParam, type VectorStore, type VectorStoreDeleted, type VectorStoreCreateParams, type VectorStoreUpdateParams, type VectorStoreListParams, } from "./vector-stores/index.js"; 6 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/beta/threads/index.d.ts: -------------------------------------------------------------------------------- 1 | export { MessagesPage, Messages, type Annotation, type AnnotationDelta, type FileCitationAnnotation, type FileCitationDeltaAnnotation, type FilePathAnnotation, type FilePathDeltaAnnotation, type ImageFile, type ImageFileContentBlock, type ImageFileDelta, type ImageFileDeltaBlock, type ImageURL, type ImageURLContentBlock, type ImageURLDelta, type ImageURLDeltaBlock, type Message, type MessageContent, type MessageContentDelta, type MessageContentPartParam, type MessageDeleted, type MessageDelta, type MessageDeltaEvent, type RefusalContentBlock, type RefusalDeltaBlock, type Text, type TextContentBlock, type TextContentBlockParam, type TextDelta, type TextDeltaBlock, type MessageCreateParams, type MessageUpdateParams, type MessageListParams, } from "./messages.js"; 2 | export { RunsPage, Runs, type RequiredActionFunctionToolCall, type Run, type RunStatus, type RunCreateParams, type RunCreateParamsNonStreaming, type RunCreateParamsStreaming, type RunUpdateParams, type RunListParams, type RunSubmitToolOutputsParams, type RunSubmitToolOutputsParamsNonStreaming, type RunSubmitToolOutputsParamsStreaming, type RunCreateAndPollParams, type RunCreateAndStreamParams, type RunStreamParams, type RunSubmitToolOutputsAndPollParams, type RunSubmitToolOutputsStreamParams, } from "./runs/index.js"; 3 | export { Threads, type AssistantResponseFormatOption, type AssistantToolChoice, type AssistantToolChoiceFunction, type AssistantToolChoiceOption, type Thread, type ThreadDeleted, type ThreadCreateParams, type ThreadUpdateParams, type ThreadCreateAndRunParams, type ThreadCreateAndRunParamsNonStreaming, type ThreadCreateAndRunParamsStreaming, type ThreadCreateAndRunPollParams, type ThreadCreateAndRunStreamParams, } from "./threads.js"; 4 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/beta/threads/runs/index.d.ts: -------------------------------------------------------------------------------- 1 | export { RunStepsPage, Steps, type CodeInterpreterLogs, type CodeInterpreterOutputImage, type CodeInterpreterToolCall, type CodeInterpreterToolCallDelta, type FileSearchToolCall, type FileSearchToolCallDelta, type FunctionToolCall, type FunctionToolCallDelta, type MessageCreationStepDetails, type RunStep, type RunStepDelta, type RunStepDeltaEvent, type RunStepDeltaMessageDelta, type RunStepInclude, type ToolCall, type ToolCallDelta, type ToolCallDeltaObject, type ToolCallsStepDetails, type StepRetrieveParams, type StepListParams, } from "./steps.js"; 2 | export { RunsPage, Runs, type RequiredActionFunctionToolCall, type Run, type RunStatus, type RunCreateParams, type RunCreateParamsNonStreaming, type RunCreateParamsStreaming, type RunUpdateParams, type RunListParams, type RunCreateAndPollParams, type RunCreateAndStreamParams, type RunStreamParams, type RunSubmitToolOutputsParams, type RunSubmitToolOutputsParamsNonStreaming, type RunSubmitToolOutputsParamsStreaming, type RunSubmitToolOutputsAndPollParams, type RunSubmitToolOutputsStreamParams, } from "./runs.js"; 3 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/beta/vector-stores/file-batches.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../../resource.js"; 2 | import { Uploadable } from "../../../core.js"; 3 | import * as Core from "../../../core.js"; 4 | import * as FilesAPI from "./files.js"; 5 | import { VectorStoreFilesPage } from "./files.js"; 6 | import * as VectorStoresAPI from "./vector-stores.js"; 7 | import { type CursorPageParams } from "../../../pagination.js"; 8 | export declare class FileBatches extends APIResource { 9 | /** 10 | * Create a vector store file batch. 11 | */ 12 | create(vectorStoreId: string, body: FileBatchCreateParams, options?: Core.RequestOptions): Core.APIPromise; 13 | /** 14 | * Retrieves a vector store file batch. 15 | */ 16 | retrieve(vectorStoreId: string, batchId: string, options?: Core.RequestOptions): Core.APIPromise; 17 | /** 18 | * Cancel a vector store file batch. This attempts to cancel the processing of 19 | * files in this batch as soon as possible. 20 | */ 21 | cancel(vectorStoreId: string, batchId: string, options?: Core.RequestOptions): Core.APIPromise; 22 | /** 23 | * Create a vector store batch and poll until all files have been processed. 24 | */ 25 | createAndPoll(vectorStoreId: string, body: FileBatchCreateParams, options?: Core.RequestOptions & { 26 | pollIntervalMs?: number; 27 | }): Promise; 28 | /** 29 | * Returns a list of vector store files in a batch. 30 | */ 31 | listFiles(vectorStoreId: string, batchId: string, query?: FileBatchListFilesParams, options?: Core.RequestOptions): Core.PagePromise; 32 | listFiles(vectorStoreId: string, batchId: string, options?: Core.RequestOptions): Core.PagePromise; 33 | /** 34 | * Wait for the given file batch to be processed. 35 | * 36 | * Note: this will return even if one of the files failed to process, you need to 37 | * check batch.file_counts.failed_count to handle this case. 38 | */ 39 | poll(vectorStoreId: string, batchId: string, options?: Core.RequestOptions & { 40 | pollIntervalMs?: number; 41 | }): Promise; 42 | /** 43 | * Uploads the given files concurrently and then creates a vector store file batch. 44 | * 45 | * The concurrency limit is configurable using the `maxConcurrency` parameter. 46 | */ 47 | uploadAndPoll(vectorStoreId: string, { files, fileIds }: { 48 | files: Uploadable[]; 49 | fileIds?: string[]; 50 | }, options?: Core.RequestOptions & { 51 | pollIntervalMs?: number; 52 | maxConcurrency?: number; 53 | }): Promise; 54 | } 55 | /** 56 | * A batch of files attached to a vector store. 57 | */ 58 | export interface VectorStoreFileBatch { 59 | /** 60 | * The identifier, which can be referenced in API endpoints. 61 | */ 62 | id: string; 63 | /** 64 | * The Unix timestamp (in seconds) for when the vector store files batch was 65 | * created. 66 | */ 67 | created_at: number; 68 | file_counts: VectorStoreFileBatch.FileCounts; 69 | /** 70 | * The object type, which is always `vector_store.file_batch`. 71 | */ 72 | object: 'vector_store.files_batch'; 73 | /** 74 | * The status of the vector store files batch, which can be either `in_progress`, 75 | * `completed`, `cancelled` or `failed`. 76 | */ 77 | status: 'in_progress' | 'completed' | 'cancelled' | 'failed'; 78 | /** 79 | * The ID of the 80 | * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object) 81 | * that the [File](https://platform.openai.com/docs/api-reference/files) is 82 | * attached to. 83 | */ 84 | vector_store_id: string; 85 | } 86 | export declare namespace VectorStoreFileBatch { 87 | interface FileCounts { 88 | /** 89 | * The number of files that where cancelled. 90 | */ 91 | cancelled: number; 92 | /** 93 | * The number of files that have been processed. 94 | */ 95 | completed: number; 96 | /** 97 | * The number of files that have failed to process. 98 | */ 99 | failed: number; 100 | /** 101 | * The number of files that are currently being processed. 102 | */ 103 | in_progress: number; 104 | /** 105 | * The total number of files. 106 | */ 107 | total: number; 108 | } 109 | } 110 | export interface FileBatchCreateParams { 111 | /** 112 | * A list of [File](https://platform.openai.com/docs/api-reference/files) IDs that 113 | * the vector store should use. Useful for tools like `file_search` that can access 114 | * files. 115 | */ 116 | file_ids: Array; 117 | /** 118 | * The chunking strategy used to chunk the file(s). If not set, will use the `auto` 119 | * strategy. Only applicable if `file_ids` is non-empty. 120 | */ 121 | chunking_strategy?: VectorStoresAPI.FileChunkingStrategyParam; 122 | } 123 | export interface FileBatchListFilesParams extends CursorPageParams { 124 | /** 125 | * A cursor for use in pagination. `before` is an object ID that defines your place 126 | * in the list. For instance, if you make a list request and receive 100 objects, 127 | * starting with obj_foo, your subsequent call can include before=obj_foo in order 128 | * to fetch the previous page of the list. 129 | */ 130 | before?: string; 131 | /** 132 | * Filter by file status. One of `in_progress`, `completed`, `failed`, `cancelled`. 133 | */ 134 | filter?: 'in_progress' | 'completed' | 'failed' | 'cancelled'; 135 | /** 136 | * Sort order by the `created_at` timestamp of the objects. `asc` for ascending 137 | * order and `desc` for descending order. 138 | */ 139 | order?: 'asc' | 'desc'; 140 | } 141 | export declare namespace FileBatches { 142 | export { type VectorStoreFileBatch as VectorStoreFileBatch, type FileBatchCreateParams as FileBatchCreateParams, type FileBatchListFilesParams as FileBatchListFilesParams, }; 143 | } 144 | export { VectorStoreFilesPage }; 145 | //# sourceMappingURL=file-batches.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/beta/vector-stores/index.d.ts: -------------------------------------------------------------------------------- 1 | export { FileBatches, type VectorStoreFileBatch, type FileBatchCreateParams, type FileBatchListFilesParams, } from "./file-batches.js"; 2 | export { VectorStoreFilesPage, Files, type VectorStoreFile, type VectorStoreFileDeleted, type FileCreateParams, type FileListParams, } from "./files.js"; 3 | export { VectorStoresPage, VectorStores, type AutoFileChunkingStrategyParam, type FileChunkingStrategy, type FileChunkingStrategyParam, type OtherFileChunkingStrategyObject, type StaticFileChunkingStrategy, type StaticFileChunkingStrategyObject, type StaticFileChunkingStrategyParam, type VectorStore, type VectorStoreDeleted, type VectorStoreCreateParams, type VectorStoreUpdateParams, type VectorStoreListParams, } from "./vector-stores.js"; 4 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/chat/chat.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../resource.js"; 2 | import * as CompletionsAPI from "./completions.js"; 3 | import { ChatCompletion, ChatCompletionAssistantMessageParam, ChatCompletionAudio, ChatCompletionAudioParam, ChatCompletionChunk, ChatCompletionContentPart, ChatCompletionContentPartImage, ChatCompletionContentPartInputAudio, ChatCompletionContentPartRefusal, ChatCompletionContentPartText, ChatCompletionCreateParams, ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, ChatCompletionDeveloperMessageParam, ChatCompletionFunctionCallOption, ChatCompletionFunctionMessageParam, ChatCompletionMessage, ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionModality, ChatCompletionNamedToolChoice, ChatCompletionPredictionContent, ChatCompletionReasoningEffort, ChatCompletionRole, ChatCompletionStreamOptions, ChatCompletionSystemMessageParam, ChatCompletionTokenLogprob, ChatCompletionTool, ChatCompletionToolChoiceOption, ChatCompletionToolMessageParam, ChatCompletionUserMessageParam, CompletionCreateParams, CompletionCreateParamsNonStreaming, CompletionCreateParamsStreaming, Completions, CreateChatCompletionRequestMessage } from "./completions.js"; 4 | export declare class Chat extends APIResource { 5 | completions: CompletionsAPI.Completions; 6 | } 7 | export type ChatModel = 'o1' | 'o1-2024-12-17' | 'o1-preview' | 'o1-preview-2024-09-12' | 'o1-mini' | 'o1-mini-2024-09-12' | 'gpt-4o' | 'gpt-4o-2024-11-20' | 'gpt-4o-2024-08-06' | 'gpt-4o-2024-05-13' | 'gpt-4o-audio-preview' | 'gpt-4o-audio-preview-2024-10-01' | 'gpt-4o-audio-preview-2024-12-17' | 'gpt-4o-mini-audio-preview' | 'gpt-4o-mini-audio-preview-2024-12-17' | 'chatgpt-4o-latest' | 'gpt-4o-mini' | 'gpt-4o-mini-2024-07-18' | 'gpt-4-turbo' | 'gpt-4-turbo-2024-04-09' | 'gpt-4-0125-preview' | 'gpt-4-turbo-preview' | 'gpt-4-1106-preview' | 'gpt-4-vision-preview' | 'gpt-4' | 'gpt-4-0314' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0314' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-0301' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-1106' | 'gpt-3.5-turbo-0125' | 'gpt-3.5-turbo-16k-0613'; 8 | export declare namespace Chat { 9 | export { type ChatModel as ChatModel }; 10 | export { Completions as Completions, type ChatCompletion as ChatCompletion, type ChatCompletionAssistantMessageParam as ChatCompletionAssistantMessageParam, type ChatCompletionAudio as ChatCompletionAudio, type ChatCompletionAudioParam as ChatCompletionAudioParam, type ChatCompletionChunk as ChatCompletionChunk, type ChatCompletionContentPart as ChatCompletionContentPart, type ChatCompletionContentPartImage as ChatCompletionContentPartImage, type ChatCompletionContentPartInputAudio as ChatCompletionContentPartInputAudio, type ChatCompletionContentPartRefusal as ChatCompletionContentPartRefusal, type ChatCompletionContentPartText as ChatCompletionContentPartText, type ChatCompletionDeveloperMessageParam as ChatCompletionDeveloperMessageParam, type ChatCompletionFunctionCallOption as ChatCompletionFunctionCallOption, type ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam, type ChatCompletionMessage as ChatCompletionMessage, type ChatCompletionMessageParam as ChatCompletionMessageParam, type ChatCompletionMessageToolCall as ChatCompletionMessageToolCall, type ChatCompletionModality as ChatCompletionModality, type ChatCompletionNamedToolChoice as ChatCompletionNamedToolChoice, type ChatCompletionPredictionContent as ChatCompletionPredictionContent, type ChatCompletionReasoningEffort as ChatCompletionReasoningEffort, type ChatCompletionRole as ChatCompletionRole, type ChatCompletionStreamOptions as ChatCompletionStreamOptions, type ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam, type ChatCompletionTokenLogprob as ChatCompletionTokenLogprob, type ChatCompletionTool as ChatCompletionTool, type ChatCompletionToolChoiceOption as ChatCompletionToolChoiceOption, type ChatCompletionToolMessageParam as ChatCompletionToolMessageParam, type ChatCompletionUserMessageParam as ChatCompletionUserMessageParam, type CreateChatCompletionRequestMessage as CreateChatCompletionRequestMessage, type ChatCompletionCreateParams as ChatCompletionCreateParams, type CompletionCreateParams as CompletionCreateParams, type ChatCompletionCreateParamsNonStreaming as ChatCompletionCreateParamsNonStreaming, type CompletionCreateParamsNonStreaming as CompletionCreateParamsNonStreaming, type ChatCompletionCreateParamsStreaming as ChatCompletionCreateParamsStreaming, type CompletionCreateParamsStreaming as CompletionCreateParamsStreaming, }; 11 | } 12 | //# sourceMappingURL=chat.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/chat/index.d.ts: -------------------------------------------------------------------------------- 1 | export { Chat, type ChatModel } from "./chat.js"; 2 | export { Completions, type ChatCompletion, type ChatCompletionAssistantMessageParam, type ChatCompletionAudio, type ChatCompletionAudioParam, type ChatCompletionChunk, type ChatCompletionContentPart, type ChatCompletionContentPartImage, type ChatCompletionContentPartInputAudio, type ChatCompletionContentPartRefusal, type ChatCompletionContentPartText, type ChatCompletionDeveloperMessageParam, type ChatCompletionFunctionCallOption, type ChatCompletionFunctionMessageParam, type ChatCompletionMessage, type ChatCompletionMessageParam, type ChatCompletionMessageToolCall, type ChatCompletionModality, type ChatCompletionNamedToolChoice, type ChatCompletionPredictionContent, type ChatCompletionReasoningEffort, type ChatCompletionRole, type ChatCompletionStreamOptions, type ChatCompletionSystemMessageParam, type ChatCompletionTokenLogprob, type ChatCompletionTool, type ChatCompletionToolChoiceOption, type ChatCompletionToolMessageParam, type ChatCompletionUserMessageParam, type CreateChatCompletionRequestMessage, type ChatCompletionCreateParams, type CompletionCreateParams, type ChatCompletionCreateParamsNonStreaming, type CompletionCreateParamsNonStreaming, type ChatCompletionCreateParamsStreaming, type CompletionCreateParamsStreaming, } from "./completions.js"; 3 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/embeddings.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../resource.js"; 2 | import * as Core from "../core.js"; 3 | export declare class Embeddings extends APIResource { 4 | /** 5 | * Creates an embedding vector representing the input text. 6 | */ 7 | create(body: EmbeddingCreateParams, options?: Core.RequestOptions): Core.APIPromise; 8 | } 9 | export interface CreateEmbeddingResponse { 10 | /** 11 | * The list of embeddings generated by the model. 12 | */ 13 | data: Array; 14 | /** 15 | * The name of the model used to generate the embedding. 16 | */ 17 | model: string; 18 | /** 19 | * The object type, which is always "list". 20 | */ 21 | object: 'list'; 22 | /** 23 | * The usage information for the request. 24 | */ 25 | usage: CreateEmbeddingResponse.Usage; 26 | } 27 | export declare namespace CreateEmbeddingResponse { 28 | /** 29 | * The usage information for the request. 30 | */ 31 | interface Usage { 32 | /** 33 | * The number of tokens used by the prompt. 34 | */ 35 | prompt_tokens: number; 36 | /** 37 | * The total number of tokens used by the request. 38 | */ 39 | total_tokens: number; 40 | } 41 | } 42 | /** 43 | * Represents an embedding vector returned by embedding endpoint. 44 | */ 45 | export interface Embedding { 46 | /** 47 | * The embedding vector, which is a list of floats. The length of vector depends on 48 | * the model as listed in the 49 | * [embedding guide](https://platform.openai.com/docs/guides/embeddings). 50 | */ 51 | embedding: Array; 52 | /** 53 | * The index of the embedding in the list of embeddings. 54 | */ 55 | index: number; 56 | /** 57 | * The object type, which is always "embedding". 58 | */ 59 | object: 'embedding'; 60 | } 61 | export type EmbeddingModel = 'text-embedding-ada-002' | 'text-embedding-3-small' | 'text-embedding-3-large'; 62 | export interface EmbeddingCreateParams { 63 | /** 64 | * Input text to embed, encoded as a string or array of tokens. To embed multiple 65 | * inputs in a single request, pass an array of strings or array of token arrays. 66 | * The input must not exceed the max input tokens for the model (8192 tokens for 67 | * `text-embedding-ada-002`), cannot be an empty string, and any array must be 2048 68 | * dimensions or less. 69 | * [Example Python code](https://cookbook.openai.com/examples/how_to_count_tokens_with_tiktoken) 70 | * for counting tokens. 71 | */ 72 | input: string | Array | Array | Array>; 73 | /** 74 | * ID of the model to use. You can use the 75 | * [List models](https://platform.openai.com/docs/api-reference/models/list) API to 76 | * see all of your available models, or see our 77 | * [Model overview](https://platform.openai.com/docs/models) for descriptions of 78 | * them. 79 | */ 80 | model: (string & {}) | EmbeddingModel; 81 | /** 82 | * The number of dimensions the resulting output embeddings should have. Only 83 | * supported in `text-embedding-3` and later models. 84 | */ 85 | dimensions?: number; 86 | /** 87 | * The format to return the embeddings in. Can be either `float` or 88 | * [`base64`](https://pypi.org/project/pybase64/). 89 | */ 90 | encoding_format?: 'float' | 'base64'; 91 | /** 92 | * A unique identifier representing your end-user, which can help OpenAI to monitor 93 | * and detect abuse. 94 | * [Learn more](https://platform.openai.com/docs/guides/safety-best-practices#end-user-ids). 95 | */ 96 | user?: string; 97 | } 98 | export declare namespace Embeddings { 99 | export { type CreateEmbeddingResponse as CreateEmbeddingResponse, type Embedding as Embedding, type EmbeddingModel as EmbeddingModel, type EmbeddingCreateParams as EmbeddingCreateParams, }; 100 | } 101 | //# sourceMappingURL=embeddings.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/files.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../resource.js"; 2 | import * as Core from "../core.js"; 3 | import { CursorPage, type CursorPageParams } from "../pagination.js"; 4 | import { type Response } from "../_shims/index.js"; 5 | export declare class Files extends APIResource { 6 | /** 7 | * Upload a file that can be used across various endpoints. Individual files can be 8 | * up to 512 MB, and the size of all files uploaded by one organization can be up 9 | * to 100 GB. 10 | * 11 | * The Assistants API supports files up to 2 million tokens and of specific file 12 | * types. See the 13 | * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for 14 | * details. 15 | * 16 | * The Fine-tuning API only supports `.jsonl` files. The input also has certain 17 | * required formats for fine-tuning 18 | * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or 19 | * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) 20 | * models. 21 | * 22 | * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also 23 | * has a specific required 24 | * [format](https://platform.openai.com/docs/api-reference/batch/request-input). 25 | * 26 | * Please [contact us](https://help.openai.com/) if you need to increase these 27 | * storage limits. 28 | */ 29 | create(body: FileCreateParams, options?: Core.RequestOptions): Core.APIPromise; 30 | /** 31 | * Returns information about a specific file. 32 | */ 33 | retrieve(fileId: string, options?: Core.RequestOptions): Core.APIPromise; 34 | /** 35 | * Returns a list of files. 36 | */ 37 | list(query?: FileListParams, options?: Core.RequestOptions): Core.PagePromise; 38 | list(options?: Core.RequestOptions): Core.PagePromise; 39 | /** 40 | * Delete a file. 41 | */ 42 | del(fileId: string, options?: Core.RequestOptions): Core.APIPromise; 43 | /** 44 | * Returns the contents of the specified file. 45 | */ 46 | content(fileId: string, options?: Core.RequestOptions): Core.APIPromise; 47 | /** 48 | * Returns the contents of the specified file. 49 | * 50 | * @deprecated The `.content()` method should be used instead 51 | */ 52 | retrieveContent(fileId: string, options?: Core.RequestOptions): Core.APIPromise; 53 | /** 54 | * Waits for the given file to be processed, default timeout is 30 mins. 55 | */ 56 | waitForProcessing(id: string, { pollInterval, maxWait }?: { 57 | pollInterval?: number; 58 | maxWait?: number; 59 | }): Promise; 60 | } 61 | export declare class FileObjectsPage extends CursorPage { 62 | } 63 | export type FileContent = string; 64 | export interface FileDeleted { 65 | id: string; 66 | deleted: boolean; 67 | object: 'file'; 68 | } 69 | /** 70 | * The `File` object represents a document that has been uploaded to OpenAI. 71 | */ 72 | export interface FileObject { 73 | /** 74 | * The file identifier, which can be referenced in the API endpoints. 75 | */ 76 | id: string; 77 | /** 78 | * The size of the file, in bytes. 79 | */ 80 | bytes: number; 81 | /** 82 | * The Unix timestamp (in seconds) for when the file was created. 83 | */ 84 | created_at: number; 85 | /** 86 | * The name of the file. 87 | */ 88 | filename: string; 89 | /** 90 | * The object type, which is always `file`. 91 | */ 92 | object: 'file'; 93 | /** 94 | * The intended purpose of the file. Supported values are `assistants`, 95 | * `assistants_output`, `batch`, `batch_output`, `fine-tune`, `fine-tune-results` 96 | * and `vision`. 97 | */ 98 | purpose: 'assistants' | 'assistants_output' | 'batch' | 'batch_output' | 'fine-tune' | 'fine-tune-results' | 'vision'; 99 | /** 100 | * @deprecated: Deprecated. The current status of the file, which can be either 101 | * `uploaded`, `processed`, or `error`. 102 | */ 103 | status: 'uploaded' | 'processed' | 'error'; 104 | /** 105 | * @deprecated: Deprecated. For details on why a fine-tuning training file failed 106 | * validation, see the `error` field on `fine_tuning.job`. 107 | */ 108 | status_details?: string; 109 | } 110 | /** 111 | * The intended purpose of the uploaded file. 112 | * 113 | * Use "assistants" for 114 | * [Assistants](https://platform.openai.com/docs/api-reference/assistants) and 115 | * [Message](https://platform.openai.com/docs/api-reference/messages) files, 116 | * "vision" for Assistants image file inputs, "batch" for 117 | * [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for 118 | * [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). 119 | */ 120 | export type FilePurpose = 'assistants' | 'batch' | 'fine-tune' | 'vision'; 121 | export interface FileCreateParams { 122 | /** 123 | * The File object (not file name) to be uploaded. 124 | */ 125 | file: Core.Uploadable; 126 | /** 127 | * The intended purpose of the uploaded file. 128 | * 129 | * Use "assistants" for 130 | * [Assistants](https://platform.openai.com/docs/api-reference/assistants) and 131 | * [Message](https://platform.openai.com/docs/api-reference/messages) files, 132 | * "vision" for Assistants image file inputs, "batch" for 133 | * [Batch API](https://platform.openai.com/docs/guides/batch), and "fine-tune" for 134 | * [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning). 135 | */ 136 | purpose: FilePurpose; 137 | } 138 | export interface FileListParams extends CursorPageParams { 139 | /** 140 | * Sort order by the `created_at` timestamp of the objects. `asc` for ascending 141 | * order and `desc` for descending order. 142 | */ 143 | order?: 'asc' | 'desc'; 144 | /** 145 | * Only return files with the given purpose. 146 | */ 147 | purpose?: string; 148 | } 149 | export declare namespace Files { 150 | export { type FileContent as FileContent, type FileDeleted as FileDeleted, type FileObject as FileObject, type FilePurpose as FilePurpose, FileObjectsPage as FileObjectsPage, type FileCreateParams as FileCreateParams, type FileListParams as FileListParams, }; 151 | } 152 | //# sourceMappingURL=files.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/fine-tuning/fine-tuning.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../resource.js"; 2 | import * as JobsAPI from "./jobs/jobs.js"; 3 | import { FineTuningJob, FineTuningJobEvent, FineTuningJobEventsPage, FineTuningJobIntegration, FineTuningJobWandbIntegration, FineTuningJobWandbIntegrationObject, FineTuningJobsPage, JobCreateParams, JobListEventsParams, JobListParams, Jobs } from "./jobs/jobs.js"; 4 | export declare class FineTuning extends APIResource { 5 | jobs: JobsAPI.Jobs; 6 | } 7 | export declare namespace FineTuning { 8 | export { Jobs as Jobs, type FineTuningJob as FineTuningJob, type FineTuningJobEvent as FineTuningJobEvent, type FineTuningJobIntegration as FineTuningJobIntegration, type FineTuningJobWandbIntegration as FineTuningJobWandbIntegration, type FineTuningJobWandbIntegrationObject as FineTuningJobWandbIntegrationObject, FineTuningJobsPage as FineTuningJobsPage, FineTuningJobEventsPage as FineTuningJobEventsPage, type JobCreateParams as JobCreateParams, type JobListParams as JobListParams, type JobListEventsParams as JobListEventsParams, }; 9 | } 10 | //# sourceMappingURL=fine-tuning.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/fine-tuning/index.d.ts: -------------------------------------------------------------------------------- 1 | export { FineTuning } from "./fine-tuning.js"; 2 | export { FineTuningJobsPage, FineTuningJobEventsPage, Jobs, type FineTuningJob, type FineTuningJobEvent, type FineTuningJobIntegration, type FineTuningJobWandbIntegration, type FineTuningJobWandbIntegrationObject, type JobCreateParams, type JobListParams, type JobListEventsParams, } from "./jobs/index.js"; 3 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/fine-tuning/jobs/checkpoints.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../../resource.js"; 2 | import * as Core from "../../../core.js"; 3 | import { CursorPage, type CursorPageParams } from "../../../pagination.js"; 4 | export declare class Checkpoints extends APIResource { 5 | /** 6 | * List checkpoints for a fine-tuning job. 7 | */ 8 | list(fineTuningJobId: string, query?: CheckpointListParams, options?: Core.RequestOptions): Core.PagePromise; 9 | list(fineTuningJobId: string, options?: Core.RequestOptions): Core.PagePromise; 10 | } 11 | export declare class FineTuningJobCheckpointsPage extends CursorPage { 12 | } 13 | /** 14 | * The `fine_tuning.job.checkpoint` object represents a model checkpoint for a 15 | * fine-tuning job that is ready to use. 16 | */ 17 | export interface FineTuningJobCheckpoint { 18 | /** 19 | * The checkpoint identifier, which can be referenced in the API endpoints. 20 | */ 21 | id: string; 22 | /** 23 | * The Unix timestamp (in seconds) for when the checkpoint was created. 24 | */ 25 | created_at: number; 26 | /** 27 | * The name of the fine-tuned checkpoint model that is created. 28 | */ 29 | fine_tuned_model_checkpoint: string; 30 | /** 31 | * The name of the fine-tuning job that this checkpoint was created from. 32 | */ 33 | fine_tuning_job_id: string; 34 | /** 35 | * Metrics at the step number during the fine-tuning job. 36 | */ 37 | metrics: FineTuningJobCheckpoint.Metrics; 38 | /** 39 | * The object type, which is always "fine_tuning.job.checkpoint". 40 | */ 41 | object: 'fine_tuning.job.checkpoint'; 42 | /** 43 | * The step number that the checkpoint was created at. 44 | */ 45 | step_number: number; 46 | } 47 | export declare namespace FineTuningJobCheckpoint { 48 | /** 49 | * Metrics at the step number during the fine-tuning job. 50 | */ 51 | interface Metrics { 52 | full_valid_loss?: number; 53 | full_valid_mean_token_accuracy?: number; 54 | step?: number; 55 | train_loss?: number; 56 | train_mean_token_accuracy?: number; 57 | valid_loss?: number; 58 | valid_mean_token_accuracy?: number; 59 | } 60 | } 61 | export interface CheckpointListParams extends CursorPageParams { 62 | } 63 | export declare namespace Checkpoints { 64 | export { type FineTuningJobCheckpoint as FineTuningJobCheckpoint, FineTuningJobCheckpointsPage as FineTuningJobCheckpointsPage, type CheckpointListParams as CheckpointListParams, }; 65 | } 66 | //# sourceMappingURL=checkpoints.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/fine-tuning/jobs/index.d.ts: -------------------------------------------------------------------------------- 1 | export { FineTuningJobCheckpointsPage, Checkpoints, type FineTuningJobCheckpoint, type CheckpointListParams, } from "./checkpoints.js"; 2 | export { FineTuningJobsPage, FineTuningJobEventsPage, Jobs, type FineTuningJob, type FineTuningJobEvent, type FineTuningJobIntegration, type FineTuningJobWandbIntegration, type FineTuningJobWandbIntegrationObject, type JobCreateParams, type JobListParams, type JobListEventsParams, } from "./jobs.js"; 3 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/index.d.ts: -------------------------------------------------------------------------------- 1 | export * from "./chat/index.js"; 2 | export * from "./shared.js"; 3 | export { Audio, type AudioModel, type AudioResponseFormat } from "./audio/audio.js"; 4 | export { BatchesPage, Batches, type Batch, type BatchError, type BatchRequestCounts, type BatchCreateParams, type BatchListParams, } from "./batches.js"; 5 | export { Beta } from "./beta/beta.js"; 6 | export { Completions, type Completion, type CompletionChoice, type CompletionUsage, type CompletionCreateParams, type CompletionCreateParamsNonStreaming, type CompletionCreateParamsStreaming, } from "./completions.js"; 7 | export { Embeddings, type CreateEmbeddingResponse, type Embedding, type EmbeddingModel, type EmbeddingCreateParams, } from "./embeddings.js"; 8 | export { FileObjectsPage, Files, type FileContent, type FileDeleted, type FileObject, type FilePurpose, type FileCreateParams, type FileListParams, } from "./files.js"; 9 | export { FineTuning } from "./fine-tuning/fine-tuning.js"; 10 | export { Images, type Image, type ImageModel, type ImagesResponse, type ImageCreateVariationParams, type ImageEditParams, type ImageGenerateParams, } from "./images.js"; 11 | export { ModelsPage, Models, type Model, type ModelDeleted } from "./models.js"; 12 | export { Moderations, type Moderation, type ModerationImageURLInput, type ModerationModel, type ModerationMultiModalInput, type ModerationTextInput, type ModerationCreateResponse, type ModerationCreateParams, } from "./moderations.js"; 13 | export { Uploads, type Upload, type UploadCreateParams, type UploadCompleteParams } from "./uploads/uploads.js"; 14 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/models.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../resource.js"; 2 | import * as Core from "../core.js"; 3 | import { Page } from "../pagination.js"; 4 | export declare class Models extends APIResource { 5 | /** 6 | * Retrieves a model instance, providing basic information about the model such as 7 | * the owner and permissioning. 8 | */ 9 | retrieve(model: string, options?: Core.RequestOptions): Core.APIPromise; 10 | /** 11 | * Lists the currently available models, and provides basic information about each 12 | * one such as the owner and availability. 13 | */ 14 | list(options?: Core.RequestOptions): Core.PagePromise; 15 | /** 16 | * Delete a fine-tuned model. You must have the Owner role in your organization to 17 | * delete a model. 18 | */ 19 | del(model: string, options?: Core.RequestOptions): Core.APIPromise; 20 | } 21 | /** 22 | * Note: no pagination actually occurs yet, this is for forwards-compatibility. 23 | */ 24 | export declare class ModelsPage extends Page { 25 | } 26 | /** 27 | * Describes an OpenAI model offering that can be used with the API. 28 | */ 29 | export interface Model { 30 | /** 31 | * The model identifier, which can be referenced in the API endpoints. 32 | */ 33 | id: string; 34 | /** 35 | * The Unix timestamp (in seconds) when the model was created. 36 | */ 37 | created: number; 38 | /** 39 | * The object type, which is always "model". 40 | */ 41 | object: 'model'; 42 | /** 43 | * The organization that owns the model. 44 | */ 45 | owned_by: string; 46 | } 47 | export interface ModelDeleted { 48 | id: string; 49 | deleted: boolean; 50 | object: string; 51 | } 52 | export declare namespace Models { 53 | export { type Model as Model, type ModelDeleted as ModelDeleted, ModelsPage as ModelsPage }; 54 | } 55 | //# sourceMappingURL=models.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/shared.d.ts: -------------------------------------------------------------------------------- 1 | export interface ErrorObject { 2 | code: string | null; 3 | message: string; 4 | param: string | null; 5 | type: string; 6 | } 7 | export interface FunctionDefinition { 8 | /** 9 | * The name of the function to be called. Must be a-z, A-Z, 0-9, or contain 10 | * underscores and dashes, with a maximum length of 64. 11 | */ 12 | name: string; 13 | /** 14 | * A description of what the function does, used by the model to choose when and 15 | * how to call the function. 16 | */ 17 | description?: string; 18 | /** 19 | * The parameters the functions accepts, described as a JSON Schema object. See the 20 | * [guide](https://platform.openai.com/docs/guides/function-calling) for examples, 21 | * and the 22 | * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for 23 | * documentation about the format. 24 | * 25 | * Omitting `parameters` defines a function with an empty parameter list. 26 | */ 27 | parameters?: FunctionParameters; 28 | /** 29 | * Whether to enable strict schema adherence when generating the function call. If 30 | * set to true, the model will follow the exact schema defined in the `parameters` 31 | * field. Only a subset of JSON Schema is supported when `strict` is `true`. Learn 32 | * more about Structured Outputs in the 33 | * [function calling guide](docs/guides/function-calling). 34 | */ 35 | strict?: boolean | null; 36 | } 37 | /** 38 | * The parameters the functions accepts, described as a JSON Schema object. See the 39 | * [guide](https://platform.openai.com/docs/guides/function-calling) for examples, 40 | * and the 41 | * [JSON Schema reference](https://json-schema.org/understanding-json-schema/) for 42 | * documentation about the format. 43 | * 44 | * Omitting `parameters` defines a function with an empty parameter list. 45 | */ 46 | export type FunctionParameters = Record; 47 | export interface ResponseFormatJSONObject { 48 | /** 49 | * The type of response format being defined: `json_object` 50 | */ 51 | type: 'json_object'; 52 | } 53 | export interface ResponseFormatJSONSchema { 54 | json_schema: ResponseFormatJSONSchema.JSONSchema; 55 | /** 56 | * The type of response format being defined: `json_schema` 57 | */ 58 | type: 'json_schema'; 59 | } 60 | export declare namespace ResponseFormatJSONSchema { 61 | interface JSONSchema { 62 | /** 63 | * The name of the response format. Must be a-z, A-Z, 0-9, or contain underscores 64 | * and dashes, with a maximum length of 64. 65 | */ 66 | name: string; 67 | /** 68 | * A description of what the response format is for, used by the model to determine 69 | * how to respond in the format. 70 | */ 71 | description?: string; 72 | /** 73 | * The schema for the response format, described as a JSON Schema object. 74 | */ 75 | schema?: Record; 76 | /** 77 | * Whether to enable strict schema adherence when generating the output. If set to 78 | * true, the model will always follow the exact schema defined in the `schema` 79 | * field. Only a subset of JSON Schema is supported when `strict` is `true`. To 80 | * learn more, read the 81 | * [Structured Outputs guide](https://platform.openai.com/docs/guides/structured-outputs). 82 | */ 83 | strict?: boolean | null; 84 | } 85 | } 86 | export interface ResponseFormatText { 87 | /** 88 | * The type of response format being defined: `text` 89 | */ 90 | type: 'text'; 91 | } 92 | //# sourceMappingURL=shared.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/uploads/index.d.ts: -------------------------------------------------------------------------------- 1 | export { Parts, type UploadPart, type PartCreateParams } from "./parts.js"; 2 | export { Uploads, type Upload, type UploadCreateParams, type UploadCompleteParams } from "./uploads.js"; 3 | //# sourceMappingURL=index.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/uploads/parts.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../resource.js"; 2 | import * as Core from "../../core.js"; 3 | export declare class Parts extends APIResource { 4 | /** 5 | * Adds a 6 | * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an 7 | * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. 8 | * A Part represents a chunk of bytes from the file you are trying to upload. 9 | * 10 | * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload 11 | * maximum of 8 GB. 12 | * 13 | * It is possible to add multiple Parts in parallel. You can decide the intended 14 | * order of the Parts when you 15 | * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). 16 | */ 17 | create(uploadId: string, body: PartCreateParams, options?: Core.RequestOptions): Core.APIPromise; 18 | } 19 | /** 20 | * The upload Part represents a chunk of bytes we can add to an Upload object. 21 | */ 22 | export interface UploadPart { 23 | /** 24 | * The upload Part unique identifier, which can be referenced in API endpoints. 25 | */ 26 | id: string; 27 | /** 28 | * The Unix timestamp (in seconds) for when the Part was created. 29 | */ 30 | created_at: number; 31 | /** 32 | * The object type, which is always `upload.part`. 33 | */ 34 | object: 'upload.part'; 35 | /** 36 | * The ID of the Upload object that this Part was added to. 37 | */ 38 | upload_id: string; 39 | } 40 | export interface PartCreateParams { 41 | /** 42 | * The chunk of bytes for this Part. 43 | */ 44 | data: Core.Uploadable; 45 | } 46 | export declare namespace Parts { 47 | export { type UploadPart as UploadPart, type PartCreateParams as PartCreateParams }; 48 | } 49 | //# sourceMappingURL=parts.d.ts.map -------------------------------------------------------------------------------- /openai-types/resources/uploads/uploads.d.ts: -------------------------------------------------------------------------------- 1 | import { APIResource } from "../../resource.js"; 2 | import * as Core from "../../core.js"; 3 | import * as FilesAPI from "../files.js"; 4 | import * as PartsAPI from "./parts.js"; 5 | import { PartCreateParams, Parts, UploadPart } from "./parts.js"; 6 | export declare class Uploads extends APIResource { 7 | parts: PartsAPI.Parts; 8 | /** 9 | * Creates an intermediate 10 | * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object 11 | * that you can add 12 | * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. 13 | * Currently, an Upload can accept at most 8 GB in total and expires after an hour 14 | * after you create it. 15 | * 16 | * Once you complete the Upload, we will create a 17 | * [File](https://platform.openai.com/docs/api-reference/files/object) object that 18 | * contains all the parts you uploaded. This File is usable in the rest of our 19 | * platform as a regular File object. 20 | * 21 | * For certain `purpose`s, the correct `mime_type` must be specified. Please refer 22 | * to documentation for the supported MIME types for your use case: 23 | * 24 | * - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files) 25 | * 26 | * For guidance on the proper filename extensions for each purpose, please follow 27 | * the documentation on 28 | * [creating a File](https://platform.openai.com/docs/api-reference/files/create). 29 | */ 30 | create(body: UploadCreateParams, options?: Core.RequestOptions): Core.APIPromise; 31 | /** 32 | * Cancels the Upload. No Parts may be added after an Upload is cancelled. 33 | */ 34 | cancel(uploadId: string, options?: Core.RequestOptions): Core.APIPromise; 35 | /** 36 | * Completes the 37 | * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). 38 | * 39 | * Within the returned Upload object, there is a nested 40 | * [File](https://platform.openai.com/docs/api-reference/files/object) object that 41 | * is ready to use in the rest of the platform. 42 | * 43 | * You can specify the order of the Parts by passing in an ordered list of the Part 44 | * IDs. 45 | * 46 | * The number of bytes uploaded upon completion must match the number of bytes 47 | * initially specified when creating the Upload object. No Parts may be added after 48 | * an Upload is completed. 49 | */ 50 | complete(uploadId: string, body: UploadCompleteParams, options?: Core.RequestOptions): Core.APIPromise; 51 | } 52 | /** 53 | * The Upload object can accept byte chunks in the form of Parts. 54 | */ 55 | export interface Upload { 56 | /** 57 | * The Upload unique identifier, which can be referenced in API endpoints. 58 | */ 59 | id: string; 60 | /** 61 | * The intended number of bytes to be uploaded. 62 | */ 63 | bytes: number; 64 | /** 65 | * The Unix timestamp (in seconds) for when the Upload was created. 66 | */ 67 | created_at: number; 68 | /** 69 | * The Unix timestamp (in seconds) for when the Upload was created. 70 | */ 71 | expires_at: number; 72 | /** 73 | * The name of the file to be uploaded. 74 | */ 75 | filename: string; 76 | /** 77 | * The object type, which is always "upload". 78 | */ 79 | object: 'upload'; 80 | /** 81 | * The intended purpose of the file. 82 | * [Please refer here](https://platform.openai.com/docs/api-reference/files/object#files/object-purpose) 83 | * for acceptable values. 84 | */ 85 | purpose: string; 86 | /** 87 | * The status of the Upload. 88 | */ 89 | status: 'pending' | 'completed' | 'cancelled' | 'expired'; 90 | /** 91 | * The ready File object after the Upload is completed. 92 | */ 93 | file?: FilesAPI.FileObject | null; 94 | } 95 | export interface UploadCreateParams { 96 | /** 97 | * The number of bytes in the file you are uploading. 98 | */ 99 | bytes: number; 100 | /** 101 | * The name of the file to upload. 102 | */ 103 | filename: string; 104 | /** 105 | * The MIME type of the file. 106 | * 107 | * This must fall within the supported MIME types for your file purpose. See the 108 | * supported MIME types for assistants and vision. 109 | */ 110 | mime_type: string; 111 | /** 112 | * The intended purpose of the uploaded file. 113 | * 114 | * See the 115 | * [documentation on File purposes](https://platform.openai.com/docs/api-reference/files/create#files-create-purpose). 116 | */ 117 | purpose: FilesAPI.FilePurpose; 118 | } 119 | export interface UploadCompleteParams { 120 | /** 121 | * The ordered list of Part IDs. 122 | */ 123 | part_ids: Array; 124 | /** 125 | * The optional md5 checksum for the file contents to verify if the bytes uploaded 126 | * matches what you expect. 127 | */ 128 | md5?: string; 129 | } 130 | export declare namespace Uploads { 131 | export { type Upload as Upload, type UploadCreateParams as UploadCreateParams, type UploadCompleteParams as UploadCompleteParams, }; 132 | export { Parts as Parts, type UploadPart as UploadPart, type PartCreateParams as PartCreateParams }; 133 | } 134 | //# sourceMappingURL=uploads.d.ts.map -------------------------------------------------------------------------------- /openai-types/shims/node.d.ts: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | import * as types from "../_shims/node-types.js"; 6 | declare module '../_shims/manual-types' { 7 | namespace manual { 8 | type Agent = types.Agent; 9 | export import fetch = types.fetch; 10 | type Request = types.Request; 11 | type RequestInfo = types.RequestInfo; 12 | type RequestInit = types.RequestInit; 13 | type Response = types.Response; 14 | type ResponseInit = types.ResponseInit; 15 | type ResponseType = types.ResponseType; 16 | type BodyInit = types.BodyInit; 17 | type Headers = types.Headers; 18 | type HeadersInit = types.HeadersInit; 19 | type BlobPropertyBag = types.BlobPropertyBag; 20 | type FilePropertyBag = types.FilePropertyBag; 21 | type FileFromPathOptions = types.FileFromPathOptions; 22 | export import FormData = types.FormData; 23 | export import File = types.File; 24 | export import Blob = types.Blob; 25 | type Readable = types.Readable; 26 | type FsReadStream = types.FsReadStream; 27 | export import ReadableStream = types.ReadableStream; 28 | } 29 | } 30 | //# sourceMappingURL=node.d.ts.map -------------------------------------------------------------------------------- /openai-types/shims/web.d.ts: -------------------------------------------------------------------------------- 1 | import * as types from "../_shims/web-types.js"; 2 | declare module '../_shims/manual-types' { 3 | namespace manual { 4 | type Agent = types.Agent; 5 | export import fetch = types.fetch; 6 | type Request = types.Request; 7 | type RequestInfo = types.RequestInfo; 8 | type RequestInit = types.RequestInit; 9 | type Response = types.Response; 10 | type ResponseInit = types.ResponseInit; 11 | type ResponseType = types.ResponseType; 12 | type BodyInit = types.BodyInit; 13 | type Headers = types.Headers; 14 | type HeadersInit = types.HeadersInit; 15 | type BlobPropertyBag = types.BlobPropertyBag; 16 | type FilePropertyBag = types.FilePropertyBag; 17 | type FileFromPathOptions = types.FileFromPathOptions; 18 | export import FormData = types.FormData; 19 | export import File = types.File; 20 | export import Blob = types.Blob; 21 | type Readable = types.Readable; 22 | type FsReadStream = types.FsReadStream; 23 | export import ReadableStream = types.ReadableStream; 24 | } 25 | } 26 | //# sourceMappingURL=web.d.ts.map -------------------------------------------------------------------------------- /openai-types/src/_shims/auto/types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | export type Agent = any; 5 | 6 | // @ts-ignore 7 | declare const _fetch: typeof fetch; 8 | export { _fetch as fetch }; 9 | 10 | // @ts-ignore 11 | type _Request = Request; 12 | export { _Request as Request }; 13 | 14 | // @ts-ignore 15 | type _RequestInfo = RequestInfo; 16 | export { type _RequestInfo as RequestInfo }; 17 | 18 | // @ts-ignore 19 | type _RequestInit = RequestInit; 20 | export { type _RequestInit as RequestInit }; 21 | 22 | // @ts-ignore 23 | type _Response = Response; 24 | export { _Response as Response }; 25 | 26 | // @ts-ignore 27 | type _ResponseInit = ResponseInit; 28 | export { type _ResponseInit as ResponseInit }; 29 | 30 | // @ts-ignore 31 | type _ResponseType = ResponseType; 32 | export { type _ResponseType as ResponseType }; 33 | 34 | // @ts-ignore 35 | type _BodyInit = BodyInit; 36 | export { type _BodyInit as BodyInit }; 37 | 38 | // @ts-ignore 39 | type _Headers = Headers; 40 | export { _Headers as Headers }; 41 | 42 | // @ts-ignore 43 | type _HeadersInit = HeadersInit; 44 | export { type _HeadersInit as HeadersInit }; 45 | 46 | type EndingType = 'native' | 'transparent'; 47 | 48 | export interface BlobPropertyBag { 49 | endings?: EndingType; 50 | type?: string; 51 | } 52 | 53 | export interface FilePropertyBag extends BlobPropertyBag { 54 | lastModified?: number; 55 | } 56 | 57 | export type FileFromPathOptions = Omit; 58 | 59 | // @ts-ignore 60 | type _FormData = FormData; 61 | // @ts-ignore 62 | declare const _FormData: typeof FormData; 63 | export { _FormData as FormData }; 64 | 65 | // @ts-ignore 66 | type _File = File; 67 | // @ts-ignore 68 | declare const _File: typeof File; 69 | export { _File as File }; 70 | 71 | // @ts-ignore 72 | type _Blob = Blob; 73 | // @ts-ignore 74 | declare const _Blob: typeof Blob; 75 | export { _Blob as Blob }; 76 | 77 | export declare class Readable { 78 | readable: boolean; 79 | readonly readableEnded: boolean; 80 | readonly readableFlowing: boolean | null; 81 | readonly readableHighWaterMark: number; 82 | readonly readableLength: number; 83 | readonly readableObjectMode: boolean; 84 | destroyed: boolean; 85 | read(size?: number): any; 86 | pause(): this; 87 | resume(): this; 88 | isPaused(): boolean; 89 | destroy(error?: Error): this; 90 | [Symbol.asyncIterator](): AsyncIterableIterator; 91 | } 92 | 93 | export declare class FsReadStream extends Readable { 94 | path: {}; // node type is string | Buffer 95 | } 96 | 97 | // @ts-ignore 98 | type _ReadableStream = ReadableStream; 99 | // @ts-ignore 100 | declare const _ReadableStream: typeof ReadableStream; 101 | export { _ReadableStream as ReadableStream }; 102 | -------------------------------------------------------------------------------- /openai-types/src/_shims/index.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | import { manual } from './manual-types'; 5 | import * as auto from "./auto/types"; 6 | import { type RequestOptions } from '../core'; 7 | 8 | type SelectType = unknown extends Manual ? Auto : Manual; 9 | 10 | export const kind: string; 11 | 12 | // @ts-ignore 13 | export type Agent = SelectType; 14 | 15 | // @ts-ignore 16 | export const fetch: SelectType; 17 | 18 | // @ts-ignore 19 | export type Request = SelectType; 20 | // @ts-ignore 21 | export type RequestInfo = SelectType; 22 | // @ts-ignore 23 | export type RequestInit = SelectType; 24 | 25 | // @ts-ignore 26 | export type Response = SelectType; 27 | // @ts-ignore 28 | export type ResponseInit = SelectType; 29 | // @ts-ignore 30 | export type ResponseType = SelectType; 31 | // @ts-ignore 32 | export type BodyInit = SelectType; 33 | // @ts-ignore 34 | export type Headers = SelectType; 35 | // @ts-ignore 36 | export const Headers: SelectType; 37 | // @ts-ignore 38 | export type HeadersInit = SelectType; 39 | 40 | // @ts-ignore 41 | export type BlobPropertyBag = SelectType; 42 | // @ts-ignore 43 | export type FilePropertyBag = SelectType; 44 | // @ts-ignore 45 | export type FileFromPathOptions = SelectType; 46 | // @ts-ignore 47 | export type FormData = SelectType; 48 | // @ts-ignore 49 | export const FormData: SelectType; 50 | // @ts-ignore 51 | export type File = SelectType; 52 | // @ts-ignore 53 | export const File: SelectType; 54 | // @ts-ignore 55 | export type Blob = SelectType; 56 | // @ts-ignore 57 | export const Blob: SelectType; 58 | 59 | // @ts-ignore 60 | export type Readable = SelectType; 61 | // @ts-ignore 62 | export type FsReadStream = SelectType; 63 | // @ts-ignore 64 | export type ReadableStream = SelectType; 65 | // @ts-ignore 66 | export const ReadableStream: SelectType; 67 | 68 | export function getMultipartRequestOptions>( 69 | form: FormData, 70 | opts: RequestOptions, 71 | ): Promise>; 72 | 73 | export function getDefaultAgent(url: string): any; 74 | 75 | // @ts-ignore 76 | export type FileFromPathOptions = SelectType; 77 | 78 | export function fileFromPath(path: string, options?: FileFromPathOptions): Promise; 79 | export function fileFromPath(path: string, filename?: string, options?: FileFromPathOptions): Promise; 80 | 81 | export function isFsReadStream(value: any): value is FsReadStream; 82 | -------------------------------------------------------------------------------- /openai-types/src/_shims/manual-types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | /** 5 | * Types will get added to this namespace when you import one of the following: 6 | * 7 | * import '../../shims/node.js' 8 | * import '../../shims/web.js' 9 | * 10 | * Importing more than one will cause type and runtime errors. 11 | */ 12 | export namespace manual {} 13 | -------------------------------------------------------------------------------- /openai-types/src/_shims/node-types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | import * as nf from 'node-fetch'; 5 | import * as fd from 'formdata-node'; 6 | 7 | export { type Agent } from 'node:http'; 8 | export { type Readable } from 'node:stream'; 9 | export { type ReadStream as FsReadStream } from 'node:fs'; 10 | export { ReadableStream } from 'node:stream/web'; 11 | 12 | export const fetch: typeof nf.default; 13 | 14 | export type Request = nf.Request; 15 | export type RequestInfo = nf.RequestInfo; 16 | export type RequestInit = nf.RequestInit; 17 | 18 | export type Response = nf.Response; 19 | export type ResponseInit = nf.ResponseInit; 20 | export type ResponseType = nf.ResponseType; 21 | export type BodyInit = nf.BodyInit; 22 | export type Headers = nf.Headers; 23 | export type HeadersInit = nf.HeadersInit; 24 | 25 | type EndingType = 'native' | 'transparent'; 26 | export interface BlobPropertyBag { 27 | endings?: EndingType; 28 | type?: string; 29 | } 30 | 31 | export interface FilePropertyBag extends BlobPropertyBag { 32 | lastModified?: number; 33 | } 34 | 35 | export type FileFromPathOptions = Omit; 36 | 37 | export type FormData = fd.FormData; 38 | export const FormData: typeof fd.FormData; 39 | export type File = fd.File; 40 | export const File: typeof fd.File; 41 | export type Blob = fd.Blob; 42 | export const Blob: typeof fd.Blob; 43 | -------------------------------------------------------------------------------- /openai-types/src/_shims/web-types.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Disclaimer: modules in _shims aren't intended to be imported by SDK users. 3 | */ 4 | export type Agent = any; 5 | 6 | declare const _fetch: typeof fetch; 7 | export { _fetch as fetch }; 8 | 9 | type _Request = Request; 10 | export { _Request as Request }; 11 | 12 | type _RequestInfo = RequestInfo; 13 | export { type _RequestInfo as RequestInfo }; 14 | 15 | type _RequestInit = RequestInit; 16 | export { type _RequestInit as RequestInit }; 17 | 18 | type _Response = Response; 19 | export { _Response as Response }; 20 | 21 | type _ResponseInit = ResponseInit; 22 | export { type _ResponseInit as ResponseInit }; 23 | 24 | type _ResponseType = ResponseType; 25 | export { type _ResponseType as ResponseType }; 26 | 27 | type _BodyInit = BodyInit; 28 | export { type _BodyInit as BodyInit }; 29 | 30 | type _Headers = Headers; 31 | export { _Headers as Headers }; 32 | 33 | type _HeadersInit = HeadersInit; 34 | export { type _HeadersInit as HeadersInit }; 35 | 36 | type EndingType = 'native' | 'transparent'; 37 | 38 | export interface BlobPropertyBag { 39 | endings?: EndingType; 40 | type?: string; 41 | } 42 | 43 | export interface FilePropertyBag extends BlobPropertyBag { 44 | lastModified?: number; 45 | } 46 | 47 | export type FileFromPathOptions = Omit; 48 | 49 | type _FormData = FormData; 50 | declare const _FormData: typeof FormData; 51 | export { _FormData as FormData }; 52 | 53 | type _File = File; 54 | declare const _File: typeof File; 55 | export { _File as File }; 56 | 57 | type _Blob = Blob; 58 | declare const _Blob: typeof Blob; 59 | export { _Blob as Blob }; 60 | 61 | export declare class Readable { 62 | readable: boolean; 63 | readonly readableEnded: boolean; 64 | readonly readableFlowing: boolean | null; 65 | readonly readableHighWaterMark: number; 66 | readonly readableLength: number; 67 | readonly readableObjectMode: boolean; 68 | destroyed: boolean; 69 | read(size?: number): any; 70 | pause(): this; 71 | resume(): this; 72 | isPaused(): boolean; 73 | destroy(error?: Error): this; 74 | [Symbol.asyncIterator](): AsyncIterableIterator; 75 | } 76 | 77 | export declare class FsReadStream extends Readable { 78 | path: {}; // node type is string | Buffer 79 | } 80 | 81 | type _ReadableStream = ReadableStream; 82 | declare const _ReadableStream: typeof ReadableStream; 83 | export { _ReadableStream as ReadableStream }; 84 | -------------------------------------------------------------------------------- /openai-types/streaming.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import { ReadableStream, type Response } from "./_shims/index.js"; 3 | export type ServerSentEvent = { 4 | event: string | null; 5 | data: string; 6 | raw: string[]; 7 | }; 8 | export declare class Stream implements AsyncIterable { 9 | private iterator; 10 | controller: AbortController; 11 | constructor(iterator: () => AsyncIterator, controller: AbortController); 12 | static fromSSEResponse(response: Response, controller: AbortController): Stream; 13 | /** 14 | * Generates a Stream from a newline-separated ReadableStream 15 | * where each item is a JSON value. 16 | */ 17 | static fromReadableStream(readableStream: ReadableStream, controller: AbortController): Stream; 18 | [Symbol.asyncIterator](): AsyncIterator; 19 | /** 20 | * Splits the stream into two streams which can be 21 | * independently read from at different speeds. 22 | */ 23 | tee(): [Stream, Stream]; 24 | /** 25 | * Converts this stream to a newline-separated ReadableStream of 26 | * JSON stringified values in the stream 27 | * which can be turned back into a Stream with `Stream.fromReadableStream()`. 28 | */ 29 | toReadableStream(): ReadableStream; 30 | } 31 | export declare function _iterSSEMessages(response: Response, controller: AbortController): AsyncGenerator; 32 | /** This is an internal helper function that's just used for testing */ 33 | export declare function _decodeChunks(chunks: string[]): string[]; 34 | /** 35 | * Most browsers don't yet have async iterable support for ReadableStream, 36 | * and Node has a very different way of reading bytes from its "ReadableStream". 37 | * 38 | * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 39 | */ 40 | export declare function readableStreamAsyncIterable(stream: any): AsyncIterableIterator; 41 | //# sourceMappingURL=streaming.d.ts.map -------------------------------------------------------------------------------- /openai-types/uploads.d.ts: -------------------------------------------------------------------------------- 1 | import { type RequestOptions } from "./core.js"; 2 | import { FormData, type Blob, type FilePropertyBag, type FsReadStream } from "./_shims/index.js"; 3 | import { MultipartBody } from "./_shims/MultipartBody.js"; 4 | export { fileFromPath } from "./_shims/index.js"; 5 | type BlobLikePart = string | ArrayBuffer | ArrayBufferView | BlobLike | Uint8Array | DataView; 6 | export type BlobPart = string | ArrayBuffer | ArrayBufferView | Blob | Uint8Array | DataView; 7 | /** 8 | * Typically, this is a native "File" class. 9 | * 10 | * We provide the {@link toFile} utility to convert a variety of objects 11 | * into the File class. 12 | * 13 | * For convenience, you can also pass a fetch Response, or in Node, 14 | * the result of fs.createReadStream(). 15 | */ 16 | export type Uploadable = FileLike | ResponseLike | FsReadStream; 17 | /** 18 | * Intended to match web.Blob, node.Blob, node-fetch.Blob, etc. 19 | */ 20 | export interface BlobLike { 21 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/size) */ 22 | readonly size: number; 23 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/type) */ 24 | readonly type: string; 25 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/text) */ 26 | text(): Promise; 27 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Blob/slice) */ 28 | slice(start?: number, end?: number): BlobLike; 29 | } 30 | /** 31 | * Intended to match web.File, node.File, node-fetch.File, etc. 32 | */ 33 | export interface FileLike extends BlobLike { 34 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/lastModified) */ 35 | readonly lastModified: number; 36 | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/File/name) */ 37 | readonly name: string; 38 | } 39 | /** 40 | * Intended to match web.Response, node.Response, node-fetch.Response, etc. 41 | */ 42 | export interface ResponseLike { 43 | url: string; 44 | blob(): Promise; 45 | } 46 | export declare const isResponseLike: (value: any) => value is ResponseLike; 47 | export declare const isFileLike: (value: any) => value is FileLike; 48 | /** 49 | * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check 50 | * adds the arrayBuffer() method type because it is available and used at runtime 51 | */ 52 | export declare const isBlobLike: (value: any) => value is BlobLike & { 53 | arrayBuffer(): Promise; 54 | }; 55 | export declare const isUploadable: (value: any) => value is Uploadable; 56 | export type ToFileInput = Uploadable | Exclude | AsyncIterable; 57 | /** 58 | * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats 59 | * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s 60 | * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible 61 | * @param {Object=} options additional properties 62 | * @param {string=} options.type the MIME type of the content 63 | * @param {number=} options.lastModified the last modified timestamp 64 | * @returns a {@link File} with the given properties 65 | */ 66 | export declare function toFile(value: ToFileInput | PromiseLike, name?: string | null | undefined, options?: FilePropertyBag | undefined): Promise; 67 | export declare const isMultipartBody: (body: any) => body is MultipartBody; 68 | /** 69 | * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. 70 | * Otherwise returns the request as is. 71 | */ 72 | export declare const maybeMultipartFormRequestOptions: >(opts: RequestOptions) => Promise>; 73 | export declare const multipartFormRequestOptions: >(opts: RequestOptions) => Promise>; 74 | export declare const createForm: >(body: T | undefined) => Promise; 75 | //# sourceMappingURL=uploads.d.ts.map -------------------------------------------------------------------------------- /openai-types/version.d.ts: -------------------------------------------------------------------------------- 1 | export declare const VERSION = "4.77.0"; 2 | //# sourceMappingURL=version.d.ts.map -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "openai-fetch", 3 | "type": "module", 4 | "version": "3.4.2", 5 | "description": "OpenAI client powered by fetch", 6 | "repository": "dexaai/openai-fetch", 7 | "license": "MIT", 8 | "author": { 9 | "name": "Riley Tomasek", 10 | "email": "hi@rile.yt", 11 | "url": "https://rile.yt" 12 | }, 13 | "packageManager": "pnpm@9.12.1", 14 | "engines": { 15 | "node": ">=18" 16 | }, 17 | "exports": { 18 | ".": { 19 | "types": "./dist/index.d.ts", 20 | "import": "./dist/index.js" 21 | }, 22 | "./package.json": "./package.json" 23 | }, 24 | "types": "dist/index.d.ts", 25 | "main": "dist/index.js", 26 | "sideEffects": false, 27 | "files": [ 28 | "dist", 29 | "openai-types" 30 | ], 31 | "scripts": { 32 | "build": "tsc --project tsconfig.dist.json", 33 | "clean": "rimraf dist openai-types node_modules", 34 | "clean:build": "rimraf dist openai-types", 35 | "dev": "tsc --watch", 36 | "extract-types": "node extract-types.mjs", 37 | "fix": "eslint --fix --quiet . ; prettier --write --log-level=silent .", 38 | "format": "prettier --check \"**/*.{js,ts,tsx}\"", 39 | "lint": "eslint src", 40 | "prebuild": "pnpm run clean:build && pnpm run extract-types", 41 | "prepare": "pnpm run build", 42 | "prepublishOnly": "pnpm run test", 43 | "pretest": "pnpm run build", 44 | "release": "np", 45 | "test": "pnpm run lint && pnpm run typecheck", 46 | "typecheck": "tsc --noEmit" 47 | }, 48 | "dependencies": { 49 | "ky": "^1.7.4" 50 | }, 51 | "devDependencies": { 52 | "@dexaai/eslint-config": "^1.3.6", 53 | "eslint": "^8.57.0", 54 | "np": "^10.1.0", 55 | "openai": "^4.77.0", 56 | "prettier": "^3.4.2", 57 | "rimraf": "^6.0.1", 58 | "typescript": "^5.7.2" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # OpenAI Fetch Client 2 | 3 | [![Build Status](https://github.com/rileytomasek/openai-fetch/actions/workflows/main.yml/badge.svg)](https://github.com/rileytomasek/openai-fetch/actions/workflows/main.yml) [![npm version](https://img.shields.io/npm/v/openai-fetch.svg?color=0c0)](https://www.npmjs.com/package/openai-fetch) 4 | 5 | A minimal and opinionated OpenAI client powered by fetch. 6 | 7 | Unfortunately, the official [openai](https://github.com/openai/openai-node) package patches fetch in problematic ways and is quite bloated. 8 | 9 | ### Reasons to consider using `openai-fetch`: 10 | 11 | - You want a fast and small client that doesn't patch fetch 12 | - Supports all envs with native fetch: Node 18+, browsers, Deno, Cloudflare Workers, etc 13 | - Package size: `openai-fetch` is [~14kb](https://bundlephobia.com/package/openai-fetch) and `openai` is [~152kb](https://bundlephobia.com/package/openai) 14 | - You only need chat, completions, embeddings, and moderations, and TTS 15 | 16 | ### Use the official `openai` package if: 17 | 18 | - Your runtime doesn't have native fetch support 19 | - Your app can't handle native ESM code 20 | - You need endpoints other than chat, completions, embeddings, and moderations, and TTS 21 | - You aren't concerned with lib size or fetch patching 22 | 23 | ## Install 24 | 25 | ```bash 26 | npm install openai-fetch 27 | ``` 28 | 29 | This package requires `node >= 18` or an environment with `fetch` support. 30 | 31 | This package exports [ESM](https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c). If your project uses CommonJS, consider switching to ESM or use the [dynamic `import()`](https://v8.dev/features/dynamic-import) function. 32 | 33 | ## Usage 34 | 35 | ```ts 36 | import { OpenAIClient } from 'openai-fetch'; 37 | 38 | const client = new OpenAIClient({ apiKey: '' }); 39 | ``` 40 | 41 | The `apiKey` is optional and will be read from `process.env.OPENAI_API_KEY` if present. 42 | 43 | ## API 44 | 45 | The API follows OpenAI very closely, so their [reference documentation](https://platform.openai.com/docs/api-reference) can generally be used. Everything is strongly typed, so you will know if anything is different as soon as TypeScript parses your code. 46 | 47 | ```ts 48 | // Generate a single chat completion 49 | client.createChatCompletion(params: ChatParams): Promise; 50 | 51 | // Stream a single completion via a ReadableStream 52 | client.streamChatCompletion(params: ChatStreamParams): Promise; 53 | 54 | // Generate one or more completions 55 | client.createCompletions(params: CompletionParams): Promise; 56 | 57 | // Stream a single completion via a ReadableStream 58 | client.streamCompletion(params: CompletionStreamParams): Promise; 59 | 60 | // Generate one or more embeddings 61 | client.createEmbeddings(params: EmbeddingParams): Promise 62 | 63 | // Checks for potentially harmful content 64 | client.createModeration(params: ModerationParams): Promise 65 | 66 | // Text-to-Speech 67 | client.createSpeech(params: SpeechParams): Promise 68 | ``` 69 | 70 | ### Type Definitions 71 | 72 | The type definitions are avaible through TSServer, and can be found here: [type definitions](/src/types.ts). 73 | 74 | ## License 75 | 76 | MIT © [Dexa](https://dexa.ai) 77 | -------------------------------------------------------------------------------- /src/errors.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copied from OpenAI's official Node client for better compatibility, 3 | * without importing a huge amount of dependencies and unnecessary code. 4 | * @see: https://github.com/openai/openai-node/blob/master/src/error.ts 5 | */ 6 | 7 | type Headers = Record; 8 | 9 | export const castToError = (err: any): Error => { 10 | if (err instanceof Error) return err; 11 | if (typeof err === 'object' && err !== null) { 12 | try { 13 | return new Error(JSON.stringify(err)); 14 | } catch {} 15 | } 16 | return new Error(err); 17 | }; 18 | 19 | export class OpenAIError extends Error {} 20 | 21 | export class APIError< 22 | TStatus extends number | undefined = number | undefined, 23 | THeaders extends Headers | undefined = Headers | undefined, 24 | TError extends object | undefined = object | undefined, 25 | > extends OpenAIError { 26 | /** HTTP status for the response that caused the error */ 27 | readonly status: TStatus; 28 | /** HTTP headers for the response that caused the error */ 29 | readonly headers: THeaders; 30 | /** JSON body of the response that caused the error */ 31 | readonly error: TError; 32 | 33 | readonly code: string | null | undefined; 34 | readonly param: string | null | undefined; 35 | readonly type: string | undefined; 36 | 37 | readonly request_id: string | null | undefined; 38 | 39 | constructor( 40 | status: TStatus, 41 | error: TError, 42 | message: string | undefined, 43 | headers: THeaders 44 | ) { 45 | super(`${APIError.makeMessage(status, error, message)}`); 46 | this.status = status; 47 | this.headers = headers; 48 | this.request_id = headers?.['x-request-id']; 49 | this.error = error; 50 | 51 | const data = error as Record; 52 | this.code = data?.code; 53 | this.param = data?.param; 54 | this.type = data?.type; 55 | } 56 | 57 | private static makeMessage( 58 | status: number | undefined, 59 | error: any, 60 | message: string | undefined 61 | ) { 62 | const msg = error?.message 63 | ? typeof error.message === 'string' 64 | ? error.message 65 | : JSON.stringify(error.message) 66 | : error 67 | ? JSON.stringify(error) 68 | : message; 69 | 70 | if (status && msg) { 71 | return `${status} ${msg}`; 72 | } 73 | if (status) { 74 | return `${status} status code (no body)`; 75 | } 76 | if (msg) { 77 | return msg; 78 | } 79 | return '(no status code or body)'; 80 | } 81 | 82 | static generate( 83 | status: number | undefined, 84 | errorResponse: object | undefined, 85 | message: string | undefined, 86 | headers: Headers | undefined 87 | ): APIError { 88 | if (!status || !headers) { 89 | return new APIConnectionError({ 90 | message, 91 | cause: castToError(errorResponse), 92 | }); 93 | } 94 | 95 | const error = (errorResponse as Record)?.error; 96 | 97 | if (status === 400) { 98 | return new BadRequestError(status, error, message, headers); 99 | } 100 | 101 | if (status === 401) { 102 | return new AuthenticationError(status, error, message, headers); 103 | } 104 | 105 | if (status === 403) { 106 | return new PermissionDeniedError(status, error, message, headers); 107 | } 108 | 109 | if (status === 404) { 110 | return new NotFoundError(status, error, message, headers); 111 | } 112 | 113 | if (status === 409) { 114 | return new ConflictError(status, error, message, headers); 115 | } 116 | 117 | if (status === 422) { 118 | return new UnprocessableEntityError(status, error, message, headers); 119 | } 120 | 121 | if (status === 429) { 122 | return new RateLimitError(status, error, message, headers); 123 | } 124 | 125 | if (status >= 500) { 126 | return new InternalServerError(status, error, message, headers); 127 | } 128 | 129 | return new APIError(status, error, message, headers); 130 | } 131 | } 132 | 133 | export class APIUserAbortError extends APIError< 134 | undefined, 135 | undefined, 136 | undefined 137 | > { 138 | constructor({ message }: { message?: string } = {}) { 139 | super(undefined, undefined, message || 'Request was aborted.', undefined); 140 | } 141 | } 142 | 143 | export class APIConnectionError extends APIError< 144 | undefined, 145 | undefined, 146 | undefined 147 | > { 148 | constructor({ 149 | message, 150 | cause, 151 | }: { 152 | message?: string | undefined; 153 | cause?: Error | undefined; 154 | }) { 155 | super(undefined, undefined, message || 'Connection error.', undefined); 156 | // in some environments the 'cause' property is already declared 157 | // @ts-ignore 158 | if (cause) this.cause = cause; 159 | } 160 | } 161 | 162 | export class APIConnectionTimeoutError extends APIConnectionError { 163 | constructor({ message }: { message?: string } = {}) { 164 | super({ message: message ?? 'Request timed out.' }); 165 | } 166 | } 167 | 168 | export class BadRequestError extends APIError<400, Headers> {} 169 | 170 | export class AuthenticationError extends APIError<401, Headers> {} 171 | 172 | export class PermissionDeniedError extends APIError<403, Headers> {} 173 | 174 | export class NotFoundError extends APIError<404, Headers> {} 175 | 176 | export class ConflictError extends APIError<409, Headers> {} 177 | 178 | export class UnprocessableEntityError extends APIError<422, Headers> {} 179 | 180 | export class RateLimitError extends APIError<429, Headers> {} 181 | 182 | export class InternalServerError extends APIError {} 183 | 184 | export class LengthFinishReasonError extends OpenAIError { 185 | constructor() { 186 | super(`Could not parse response content as the length limit was reached`); 187 | } 188 | } 189 | 190 | export class ContentFilterFinishReasonError extends OpenAIError { 191 | constructor() { 192 | super( 193 | `Could not parse response content as the request was rejected by the content filter` 194 | ); 195 | } 196 | } 197 | -------------------------------------------------------------------------------- /src/fetch-api.ts: -------------------------------------------------------------------------------- 1 | import ky, { type KyInstance, type Options } from 'ky'; 2 | 3 | import { APIError, castToError } from './errors.js'; 4 | 5 | const DEFAULT_BASE_URL = 'https://api.openai.com/v1'; 6 | 7 | export interface KyOptions extends Omit { 8 | credentials?: 'include' | 'omit' | 'same-origin'; 9 | } 10 | 11 | /** 12 | * Create an instance of Ky with options shared by all requests. 13 | */ 14 | export function createApiInstance(args: { 15 | apiKey: string; 16 | baseUrl?: string; 17 | organizationId?: string; 18 | kyOptions?: KyOptions; 19 | }): KyInstance { 20 | const { apiKey, baseUrl, organizationId, kyOptions = {} } = args; 21 | const { headers, hooks = {}, prefixUrl, retry, timeout, ...rest } = kyOptions; 22 | 23 | // Add a hook to handle OpenAI API errors 24 | if (!hooks.beforeError) { 25 | hooks.beforeError = []; 26 | } 27 | // @ts-ignore 28 | hooks.beforeError.push(async (error) => { 29 | const { response } = error; 30 | if (response) { 31 | const status = response.status; 32 | const headers = parseHeaders(response.headers); 33 | let errorResponse: object | undefined; 34 | let message: string | undefined; 35 | if (response.body) { 36 | const errText = await response 37 | .clone() 38 | .text() 39 | .catch((e) => castToError(e).message); 40 | errorResponse = safeJson(errText)?.error; 41 | message = errorResponse ? undefined : errText; 42 | } 43 | return new APIError(status, errorResponse, message, headers); 44 | } else { 45 | return APIError.generate(undefined, error, undefined, undefined); 46 | } 47 | }); 48 | 49 | return ky.extend({ 50 | prefixUrl: baseUrl || prefixUrl || DEFAULT_BASE_URL, 51 | headers: { 52 | 'User-Agent': 'openai-fetch', 53 | ...(apiKey && { 54 | Authorization: `Bearer ${apiKey}`, 55 | }), 56 | ...(organizationId && { 57 | 'OpenAI-Organization': organizationId, 58 | }), 59 | ...headers, 60 | }, 61 | retry: retry ?? { 62 | delay: (attemptCount) => { 63 | const INITIAL_DELAY = 0.3; 64 | const jitter = numberBetween(-0.3, 0.3); 65 | const sleep = INITIAL_DELAY * Math.pow(attemptCount - 1, 2); 66 | return (sleep + jitter) * 1000; 67 | }, 68 | }, 69 | timeout: timeout ?? 1000 * 60 * 10, 70 | hooks, 71 | ...rest, 72 | }); 73 | } 74 | 75 | function parseHeaders( 76 | headers: HeadersInit | null | undefined 77 | ): Record { 78 | try { 79 | return !headers 80 | ? {} 81 | : Symbol.iterator in headers 82 | ? Object.fromEntries( 83 | Array.from(headers as Iterable).map((header) => [ 84 | ...header, 85 | ]) 86 | ) 87 | : { ...headers }; 88 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 89 | } catch (e) { 90 | return {}; 91 | } 92 | } 93 | 94 | function safeJson(text: string) { 95 | try { 96 | return JSON.parse(text); 97 | // eslint-disable-next-line @typescript-eslint/no-unused-vars 98 | } catch (err) { 99 | return undefined; 100 | } 101 | } 102 | 103 | /** Get a random number between the specified range [min, max]. */ 104 | function numberBetween(min: number, max: number): number { 105 | return Math.random() * (max - min) + min; 106 | } 107 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | export { 2 | APIConnectionError, 3 | APIConnectionTimeoutError, 4 | APIError, 5 | APIUserAbortError, 6 | AuthenticationError, 7 | BadRequestError, 8 | ConflictError, 9 | InternalServerError, 10 | NotFoundError, 11 | OpenAIError, 12 | PermissionDeniedError, 13 | RateLimitError, 14 | UnprocessableEntityError, 15 | } from './errors.js'; 16 | export type { ConfigOpts } from './openai-client.js'; 17 | export { OpenAIClient } from './openai-client.js'; 18 | export type { 19 | ChatMessage, 20 | ChatParams, 21 | ChatResponse, 22 | ChatStreamParams, 23 | ChatStreamResponse, 24 | CompletionParams, 25 | CompletionResponse, 26 | CompletionStreamParams, 27 | CompletionStreamResponse, 28 | EmbeddingParams, 29 | EmbeddingResponse, 30 | SpeechParams, 31 | SpeechResponse, 32 | } from './types.js'; 33 | -------------------------------------------------------------------------------- /src/openai-client.ts: -------------------------------------------------------------------------------- 1 | import { type OpenAI } from 'openai'; 2 | 3 | import { createApiInstance, type KyOptions } from './fetch-api.js'; 4 | import { StreamCompletionChunker } from './streaming.js'; 5 | import { 6 | type ChatParams, 7 | type ChatResponse, 8 | type ChatStreamParams, 9 | type ChatStreamResponse, 10 | type CompletionParams, 11 | type CompletionResponse, 12 | type CompletionStreamParams, 13 | type CompletionStreamResponse, 14 | type EmbeddingParams, 15 | type EmbeddingResponse, 16 | type ModerationParams, 17 | type ModerationResponse, 18 | type SpeechParams, 19 | type SpeechResponse, 20 | } from './types.js'; 21 | 22 | export type ConfigOpts = { 23 | /** 24 | * The API key used to authenticate with the OpenAI API. 25 | * @see https://platform.openai.com/account/api-keys 26 | */ 27 | apiKey?: string; 28 | /** 29 | * The organization ID that should be billed for API requests. 30 | * This is only necessary if your API key is scoped to multiple organizations. 31 | * @see https://platform.openai.com/docs/api-reference/organization-optional 32 | */ 33 | organizationId?: string; 34 | /** 35 | * The HTTP endpoint for the OpenAI API. You probably don't want to change this. 36 | * @default https://api.openai.com/v1 37 | */ 38 | baseUrl?: string; 39 | /** 40 | * Options to pass to the underlying fetch library (Ky). 41 | * @see https://github.com/sindresorhus/ky/tree/main#options 42 | */ 43 | kyOptions?: KyOptions; 44 | }; 45 | 46 | /** Override the default Ky options for a single request. */ 47 | type RequestOpts = { 48 | headers?: KyOptions['headers']; 49 | signal?: AbortSignal; 50 | }; 51 | 52 | export class OpenAIClient { 53 | private api: ReturnType; 54 | 55 | constructor(opts: ConfigOpts = {}) { 56 | const process = globalThis.process || { env: {} }; 57 | const apiKey = opts.apiKey || process.env.OPENAI_API_KEY; 58 | const organizationId = opts.organizationId || process.env.OPENAI_ORG_ID; 59 | if (!apiKey) 60 | throw new Error( 61 | 'Missing OpenAI API key. Please provide one in the config or set the OPENAI_API_KEY environment variable.' 62 | ); 63 | this.api = createApiInstance({ 64 | apiKey, 65 | baseUrl: opts.baseUrl, 66 | organizationId, 67 | kyOptions: opts.kyOptions, 68 | }); 69 | } 70 | 71 | private getApi(opts?: RequestOpts) { 72 | return opts ? this.api.extend(opts) : this.api; 73 | } 74 | 75 | /** Create a completion for a chat message. */ 76 | async createChatCompletion( 77 | params: ChatParams, 78 | opts?: RequestOpts 79 | ): Promise { 80 | const response: OpenAI.ChatCompletion = await this.getApi(opts) 81 | .post('chat/completions', { json: params }) 82 | .json(); 83 | return response; 84 | } 85 | 86 | /** Create a chat completion and stream back partial progress. */ 87 | async streamChatCompletion( 88 | params: ChatStreamParams, 89 | opts?: RequestOpts 90 | ): Promise { 91 | const response = await this.getApi(opts).post('chat/completions', { 92 | json: { ...params, stream: true }, 93 | onDownloadProgress: () => {}, // trick ky to return ReadableStream. 94 | }); 95 | const stream = response.body as ReadableStream; 96 | return stream.pipeThrough( 97 | new StreamCompletionChunker( 98 | (response: OpenAI.ChatCompletionChunk) => response 99 | ) 100 | ); 101 | } 102 | 103 | /** Create completions for an array of prompt strings. */ 104 | async createCompletions( 105 | params: CompletionParams, 106 | opts?: RequestOpts 107 | ): Promise { 108 | const response: OpenAI.Completion = await this.getApi(opts) 109 | .post('completions', { json: params }) 110 | .json(); 111 | return response; 112 | } 113 | 114 | /** Create a completion for a single prompt string and stream back partial progress. */ 115 | async streamCompletion( 116 | params: CompletionStreamParams, 117 | opts?: RequestOpts 118 | ): Promise { 119 | const response = await this.getApi(opts).post('completions', { 120 | json: { ...params, stream: true }, 121 | onDownloadProgress: () => {}, // trick ky to return ReadableStream. 122 | }); 123 | const stream = response.body as ReadableStream; 124 | return stream.pipeThrough( 125 | new StreamCompletionChunker((response: OpenAI.Completion) => response) 126 | ); 127 | } 128 | 129 | /** Create an embedding vector representing the input text. */ 130 | async createEmbeddings( 131 | params: EmbeddingParams, 132 | opts?: RequestOpts 133 | ): Promise { 134 | const response: OpenAI.CreateEmbeddingResponse = await this.getApi(opts) 135 | .post('embeddings', { json: params }) 136 | .json(); 137 | return response; 138 | } 139 | 140 | /** Given some input text, outputs if the model classifies it as potentially harmful across several categories. */ 141 | async createModeration( 142 | params: ModerationParams, 143 | opts?: RequestOpts 144 | ): Promise { 145 | const response: OpenAI.ModerationCreateResponse = await this.getApi(opts) 146 | .post('moderations', { json: params }) 147 | .json(); 148 | return response; 149 | } 150 | 151 | /** Generates audio from the input text. Also known as TTS. */ 152 | async createSpeech( 153 | params: SpeechParams, 154 | opts?: RequestOpts 155 | ): Promise { 156 | const response = await this.getApi(opts) 157 | .post('audio/speech', { json: params }) 158 | .arrayBuffer(); 159 | return response; 160 | } 161 | } 162 | -------------------------------------------------------------------------------- /src/streaming.ts: -------------------------------------------------------------------------------- 1 | /** A function that converts from raw Completion response from OpenAI 2 | * into a nicer object which includes the first choice in response from OpenAI. 3 | */ 4 | type ResponseFactory = (response: Raw) => Nice; 5 | 6 | /** 7 | * A parser for the streaming responses from the OpenAI API. 8 | * 9 | * Conveniently shaped like an argument for WritableStream constructor. 10 | */ 11 | class OpenAIStreamParser { 12 | private responseFactory: ResponseFactory; 13 | onchunk?: (chunk: Nice) => void; 14 | onend?: () => void; 15 | buffer: string; 16 | 17 | constructor(responseFactory: ResponseFactory) { 18 | this.responseFactory = responseFactory; 19 | this.buffer = ''; 20 | } 21 | 22 | /** 23 | * Takes the ReadableStream chunks, produced by `fetch` and turns them into 24 | * `CompletionResponse` objects. 25 | * @param chunk The chunk of data from the stream. 26 | */ 27 | write(chunk: Uint8Array): void { 28 | const decoder = new TextDecoder(); 29 | const s = decoder.decode(chunk); 30 | let parts = s.split('\n'); 31 | 32 | // Buffer incomplete line. 33 | if (parts.length === 1) { 34 | this.buffer += parts[0]; 35 | return; 36 | } 37 | 38 | // Prepend the buffer to the first part. 39 | if (this.buffer.length > 0) { 40 | parts[0] = this.buffer + parts[0]; 41 | this.buffer = ''; 42 | } 43 | 44 | // If the last part isn't an empty string, then we need to buffer it. 45 | const last = parts[parts.length - 1]; 46 | if (last && last.length > 0) { 47 | this.buffer = parts.pop()!; 48 | } 49 | 50 | parts 51 | .map((line) => line.trim()) 52 | .filter((line) => line.length > 0) 53 | .forEach((line) => { 54 | const pos = line.indexOf(':'); 55 | const name = line.substring(0, pos); 56 | if (name !== 'data') return; 57 | const content = line.substring(pos + 1).trim(); 58 | if (content.length === 0) return; 59 | if (content === '[DONE]') { 60 | this.onend?.(); 61 | return; 62 | } 63 | try { 64 | const parsed = JSON.parse(content); 65 | this.onchunk?.(this.responseFactory(parsed)); 66 | } catch (e) { 67 | console.error('Failed parsing streamed JSON chunk', e); 68 | } 69 | }); 70 | } 71 | } 72 | 73 | /** 74 | * A transform stream that takes the streaming responses from the OpenAI API 75 | * and turns them into useful response objects. 76 | */ 77 | export class StreamCompletionChunker 78 | implements TransformStream 79 | { 80 | writable: WritableStream; 81 | readable: ReadableStream; 82 | 83 | constructor(responseFactory: ResponseFactory) { 84 | const parser = new OpenAIStreamParser(responseFactory); 85 | this.writable = new WritableStream(parser); 86 | this.readable = new ReadableStream({ 87 | start(controller) { 88 | parser.onchunk = (chunk: Nice) => controller.enqueue(chunk); 89 | parser.onend = () => controller.close(); 90 | }, 91 | }); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/types.ts: -------------------------------------------------------------------------------- 1 | import { type OpenAI } from '../openai-types/index.js'; 2 | 3 | /** The possible roles for a message. */ 4 | export type Role = 5 | | 'system' 6 | | 'developer' 7 | | 'user' 8 | | 'assistant' 9 | | 'function' 10 | | 'tool'; 11 | 12 | /** The name and arguments of a function that should be called, as generated by the model. */ 13 | export type FunctionCall = { 14 | /** The arguments to call the function with, as generated by the model in JSON format. */ 15 | arguments: string; 16 | /** The name of the function to call. */ 17 | name: string; 18 | }; 19 | 20 | /** The tool calls generated by the model, such as function calls. */ 21 | export type ToolCall = { 22 | /** The ID of the tool call. */ 23 | id: string; 24 | /** The type of the tool. Currently, only `function` is supported. */ 25 | type: 'function'; 26 | /** The function that the model called. */ 27 | function: FunctionCall; 28 | }; 29 | 30 | export type ChatMessage = { 31 | /** 32 | * The role of the messages author. One of `system`, `user`, `assistant`, 33 | * `tool`, or `function`. 34 | */ 35 | role: Role; 36 | 37 | /** 38 | * The contents of the message. `content` may be null for assistant messages 39 | * with function calls or for assistant messages if a `refusal` was given by 40 | * the model. 41 | */ 42 | content?: string | null; 43 | 44 | /** 45 | * The refusal message if one was generated by the model. 46 | */ 47 | refusal?: string | null; 48 | 49 | /** 50 | * The name and arguments of a function that should be called, as generated by the model. 51 | */ 52 | function_call?: FunctionCall; 53 | 54 | /** 55 | * The tool calls generated by the model, such as function calls. 56 | */ 57 | tool_calls?: ToolCall[]; 58 | 59 | /** 60 | * Tool call that this message is responding to. 61 | */ 62 | tool_call_id?: string; 63 | 64 | /** 65 | * An optional name for the participant. Provides the model information to 66 | * differentiate between participants of the same role. 67 | */ 68 | name?: string; 69 | }; 70 | 71 | export type ChatParams = Omit< 72 | OpenAI.ChatCompletionCreateParams, 73 | 'stream' | 'messages' 74 | > & { messages: ChatMessage[] }; 75 | export type ChatResponse = OpenAI.ChatCompletion; 76 | 77 | export type ChatStreamParams = ChatParams; 78 | export type ChatStreamChunk = OpenAI.ChatCompletionChunk; 79 | export type ChatStreamResponse = ReadableStream; 80 | 81 | export type CompletionParams = Omit; 82 | export type CompletionResponse = OpenAI.Completion; 83 | 84 | export type CompletionStreamParams = Omit< 85 | OpenAI.CompletionCreateParams, 86 | 'prompt' 87 | > & { prompt: string }; 88 | export type CompletionStreamResponse = ReadableStream; 89 | 90 | export type EmbeddingParams = OpenAI.EmbeddingCreateParams; 91 | export type EmbeddingResponse = OpenAI.CreateEmbeddingResponse; 92 | 93 | export type ModerationParams = OpenAI.ModerationCreateParams; 94 | export type ModerationResponse = OpenAI.ModerationCreateResponse; 95 | 96 | export type SpeechParams = OpenAI.Audio.SpeechCreateParams; 97 | export type SpeechResponse = ArrayBuffer; 98 | -------------------------------------------------------------------------------- /tsconfig.dist.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig", 3 | "compilerOptions": { 4 | "sourceMap": true, 5 | "inlineSources": true, 6 | "rootDir": "./src", 7 | "outDir": "./dist" 8 | }, 9 | "include": ["src", "openai-types"] 10 | } 11 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "include": ["src", "openai-types"], 3 | "exclude": ["**/node_modules", "**/.*/"], 4 | "compilerOptions": { 5 | "outDir": "dist", 6 | "module": "node16", 7 | "moduleResolution": "node16", 8 | "moduleDetection": "force", 9 | "target": "ES2022", // Node.js 18 10 | "lib": ["DOM", "DOM.Iterable", "ES2022"], 11 | "allowSyntheticDefaultImports": true, // To provide backwards compatibility, Node.js allows you to import most CommonJS packages with a default import. This flag tells TypeScript that it's okay to use import on CommonJS modules. 12 | "resolveJsonModule": false, // ESM doesn't yet support JSON modules. 13 | "jsx": "react", 14 | "declaration": true, 15 | "pretty": true, 16 | "stripInternal": true, 17 | "strict": true, 18 | "noImplicitReturns": true, 19 | "noImplicitOverride": true, 20 | "noUnusedLocals": true, 21 | "noUnusedParameters": true, 22 | "noFallthroughCasesInSwitch": true, 23 | "noUncheckedIndexedAccess": true, 24 | "noEmitOnError": true, 25 | "useDefineForClassFields": true, 26 | "forceConsistentCasingInFileNames": true, 27 | "skipLibCheck": true 28 | } 29 | } 30 | --------------------------------------------------------------------------------