core.d.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267
  1. import { Stream } from "./streaming.js";
  2. import { APIError } from "./error.js";
  3. import { type Readable, type Agent, type RequestInfo, type RequestInit, type Response, type HeadersInit } from "./_shims/index.js";
  4. export { type Response };
  5. import { BlobLike } from "./uploads.js";
  6. export { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, type Uploadable, } from "./uploads.js";
  7. export type Fetch = (url: RequestInfo, init?: RequestInit) => Promise<Response>;
  8. /**
  9. * An alias to the builtin `Array` type so we can
  10. * easily alias it in import statements if there are name clashes.
  11. */
  12. type _Array<T> = Array<T>;
  13. /**
  14. * An alias to the builtin `Record` type so we can
  15. * easily alias it in import statements if there are name clashes.
  16. */
  17. type _Record<K extends keyof any, T> = Record<K, T>;
  18. export type { _Array as Array, _Record as Record };
  19. type PromiseOrValue<T> = T | Promise<T>;
  20. type APIResponseProps = {
  21. response: Response;
  22. options: FinalRequestOptions;
  23. controller: AbortController;
  24. };
  25. type WithRequestID<T> = T extends Array<any> | Response | AbstractPage<any> ? T : T extends Record<string, any> ? T & {
  26. _request_id?: string | null;
  27. } : T;
  28. /**
  29. * A subclass of `Promise` providing additional helper methods
  30. * for interacting with the SDK.
  31. */
  32. export declare class APIPromise<T> extends Promise<WithRequestID<T>> {
  33. private responsePromise;
  34. private parseResponse;
  35. private parsedPromise;
  36. constructor(responsePromise: Promise<APIResponseProps>, parseResponse?: (props: APIResponseProps) => PromiseOrValue<WithRequestID<T>>);
  37. _thenUnwrap<U>(transform: (data: T, props: APIResponseProps) => U): APIPromise<U>;
  38. /**
  39. * Gets the raw `Response` instance instead of parsing the response
  40. * data.
  41. *
  42. * If you want to parse the response body but still get the `Response`
  43. * instance, you can use {@link withResponse()}.
  44. *
  45. * 👋 Getting the wrong TypeScript type for `Response`?
  46. * Try setting `"moduleResolution": "NodeNext"` if you can,
  47. * or add one of these imports before your first `import … from 'openai'`:
  48. * - `import 'openai/shims/node'` (if you're running on Node)
  49. * - `import 'openai/shims/web'` (otherwise)
  50. */
  51. asResponse(): Promise<Response>;
  52. /**
  53. * Gets the parsed response data, the raw `Response` instance and the ID of the request,
  54. * returned via the X-Request-ID header which is useful for debugging requests and reporting
  55. * issues to OpenAI.
  56. *
  57. * If you just want to get the raw `Response` instance without parsing it,
  58. * you can use {@link asResponse()}.
  59. *
  60. *
  61. * 👋 Getting the wrong TypeScript type for `Response`?
  62. * Try setting `"moduleResolution": "NodeNext"` if you can,
  63. * or add one of these imports before your first `import … from 'openai'`:
  64. * - `import 'openai/shims/node'` (if you're running on Node)
  65. * - `import 'openai/shims/web'` (otherwise)
  66. */
  67. withResponse(): Promise<{
  68. data: T;
  69. response: Response;
  70. request_id: string | null | undefined;
  71. }>;
  72. private parse;
  73. then<TResult1 = WithRequestID<T>, TResult2 = never>(onfulfilled?: ((value: WithRequestID<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
  74. catch<TResult = never>(onrejected?: ((reason: any) => TResult | PromiseLike<TResult>) | undefined | null): Promise<WithRequestID<T> | TResult>;
  75. finally(onfinally?: (() => void) | undefined | null): Promise<WithRequestID<T>>;
  76. }
  77. export declare abstract class APIClient {
  78. baseURL: string;
  79. maxRetries: number;
  80. timeout: number;
  81. httpAgent: Agent | undefined;
  82. private fetch;
  83. protected idempotencyHeader?: string;
  84. constructor({ baseURL, maxRetries, timeout, // 10 minutes
  85. httpAgent, fetch: overriddenFetch, }: {
  86. baseURL: string;
  87. maxRetries?: number | undefined;
  88. timeout: number | undefined;
  89. httpAgent: Agent | undefined;
  90. fetch: Fetch | undefined;
  91. });
  92. protected authHeaders(opts: FinalRequestOptions): Headers;
  93. /**
  94. * Override this to add your own default headers, for example:
  95. *
  96. * {
  97. * ...super.defaultHeaders(),
  98. * Authorization: 'Bearer 123',
  99. * }
  100. */
  101. protected defaultHeaders(opts: FinalRequestOptions): Headers;
  102. protected abstract defaultQuery(): DefaultQuery | undefined;
  103. /**
  104. * Override this to add your own headers validation:
  105. */
  106. protected validateHeaders(headers: Headers, customHeaders: Headers): void;
  107. protected defaultIdempotencyKey(): string;
  108. get<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
  109. post<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
  110. patch<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
  111. put<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
  112. delete<Req, Rsp>(path: string, opts?: PromiseOrValue<RequestOptions<Req>>): APIPromise<Rsp>;
  113. private methodRequest;
  114. getAPIList<Item, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(path: string, Page: new (...args: any[]) => PageClass, opts?: RequestOptions<any>): PagePromise<PageClass, Item>;
  115. private calculateContentLength;
  116. buildRequest<Req>(inputOptions: FinalRequestOptions<Req>, { retryCount }?: {
  117. retryCount?: number;
  118. }): {
  119. req: RequestInit;
  120. url: string;
  121. timeout: number;
  122. };
  123. private buildHeaders;
  124. /**
  125. * Used as a callback for mutating the given `FinalRequestOptions` object.
  126. */
  127. protected prepareOptions(options: FinalRequestOptions): Promise<void>;
  128. /**
  129. * Used as a callback for mutating the given `RequestInit` object.
  130. *
  131. * This is useful for cases where you want to add certain headers based off of
  132. * the request properties, e.g. `method` or `url`.
  133. */
  134. protected prepareRequest(request: RequestInit, { url, options }: {
  135. url: string;
  136. options: FinalRequestOptions;
  137. }): Promise<void>;
  138. protected parseHeaders(headers: HeadersInit | null | undefined): Record<string, string>;
  139. protected makeStatusError(status: number | undefined, error: Object | undefined, message: string | undefined, headers: Headers | undefined): APIError;
  140. request<Req, Rsp>(options: PromiseOrValue<FinalRequestOptions<Req>>, remainingRetries?: number | null): APIPromise<Rsp>;
  141. private makeRequest;
  142. requestAPIList<Item = unknown, PageClass extends AbstractPage<Item> = AbstractPage<Item>>(Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass, options: FinalRequestOptions): PagePromise<PageClass, Item>;
  143. buildURL<Req>(path: string, query: Req | null | undefined): string;
  144. protected stringifyQuery(query: Record<string, unknown>): string;
  145. fetchWithTimeout(url: RequestInfo, init: RequestInit | undefined, ms: number, controller: AbortController): Promise<Response>;
  146. private shouldRetry;
  147. private retryRequest;
  148. private calculateDefaultRetryTimeoutMillis;
  149. private getUserAgent;
  150. }
  151. export type PageInfo = {
  152. url: URL;
  153. } | {
  154. params: Record<string, unknown> | null;
  155. };
  156. export declare abstract class AbstractPage<Item> implements AsyncIterable<Item> {
  157. #private;
  158. protected options: FinalRequestOptions;
  159. protected response: Response;
  160. protected body: unknown;
  161. constructor(client: APIClient, response: Response, body: unknown, options: FinalRequestOptions);
  162. /**
  163. * @deprecated Use nextPageInfo instead
  164. */
  165. abstract nextPageParams(): Partial<Record<string, unknown>> | null;
  166. abstract nextPageInfo(): PageInfo | null;
  167. abstract getPaginatedItems(): Item[];
  168. hasNextPage(): boolean;
  169. getNextPage(): Promise<this>;
  170. iterPages(): AsyncGenerator<this>;
  171. [Symbol.asyncIterator](): AsyncGenerator<Item>;
  172. }
  173. /**
  174. * This subclass of Promise will resolve to an instantiated Page once the request completes.
  175. *
  176. * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:
  177. *
  178. * for await (const item of client.items.list()) {
  179. * console.log(item)
  180. * }
  181. */
  182. export declare class PagePromise<PageClass extends AbstractPage<Item>, Item = ReturnType<PageClass['getPaginatedItems']>[number]> extends APIPromise<PageClass> implements AsyncIterable<Item> {
  183. constructor(client: APIClient, request: Promise<APIResponseProps>, Page: new (...args: ConstructorParameters<typeof AbstractPage>) => PageClass);
  184. /**
  185. * Allow auto-paginating iteration on an unawaited list call, eg:
  186. *
  187. * for await (const item of client.items.list()) {
  188. * console.log(item)
  189. * }
  190. */
  191. [Symbol.asyncIterator](): AsyncGenerator<Item>;
  192. }
  193. export declare const createResponseHeaders: (headers: Awaited<ReturnType<Fetch>>['headers']) => Record<string, string>;
  194. type HTTPMethod = 'get' | 'post' | 'put' | 'patch' | 'delete';
  195. export type RequestClient = {
  196. fetch: Fetch;
  197. };
  198. export type Headers = Record<string, string | null | undefined>;
  199. export type DefaultQuery = Record<string, string | undefined>;
  200. export type KeysEnum<T> = {
  201. [P in keyof Required<T>]: true;
  202. };
  203. export type RequestOptions<Req = unknown | Record<string, unknown> | Readable | BlobLike | ArrayBufferView | ArrayBuffer> = {
  204. method?: HTTPMethod;
  205. path?: string;
  206. query?: Req | undefined;
  207. body?: Req | null | undefined;
  208. headers?: Headers | undefined;
  209. maxRetries?: number;
  210. stream?: boolean | undefined;
  211. timeout?: number;
  212. httpAgent?: Agent;
  213. signal?: AbortSignal | undefined | null;
  214. idempotencyKey?: string;
  215. __metadata?: Record<string, unknown>;
  216. __binaryRequest?: boolean | undefined;
  217. __binaryResponse?: boolean | undefined;
  218. __streamClass?: typeof Stream;
  219. };
  220. export declare const isRequestOptions: (obj: unknown) => obj is RequestOptions<unknown>;
  221. export type FinalRequestOptions<Req = unknown | Record<string, unknown> | Readable | DataView> = RequestOptions<Req> & {
  222. method: HTTPMethod;
  223. path: string;
  224. };
  225. export declare const safeJSON: (text: string) => any;
  226. export declare const sleep: (ms: number) => Promise<unknown>;
  227. export declare const castToError: (err: any) => Error;
  228. export declare const ensurePresent: <T>(value: T | null | undefined) => T;
  229. /**
  230. * Read an environment variable.
  231. *
  232. * Trims beginning and trailing whitespace.
  233. *
  234. * Will return undefined if the environment variable doesn't exist or cannot be accessed.
  235. */
  236. export declare const readEnv: (env: string) => string | undefined;
  237. export declare const coerceInteger: (value: unknown) => number;
  238. export declare const coerceFloat: (value: unknown) => number;
  239. export declare const coerceBoolean: (value: unknown) => boolean;
  240. export declare const maybeCoerceInteger: (value: unknown) => number | undefined;
  241. export declare const maybeCoerceFloat: (value: unknown) => number | undefined;
  242. export declare const maybeCoerceBoolean: (value: unknown) => boolean | undefined;
  243. export declare function isEmptyObj(obj: Object | null | undefined): boolean;
  244. export declare function hasOwn(obj: Object, key: string): boolean;
  245. export declare function debug(action: string, ...args: any[]): void;
  246. export declare const isRunningInBrowser: () => boolean;
  247. export interface HeadersProtocol {
  248. get: (header: string) => string | null | undefined;
  249. }
  250. export type HeadersLike = Record<string, string | string[] | undefined> | HeadersProtocol;
  251. export declare const isHeadersProtocol: (headers: any) => headers is HeadersProtocol;
  252. export declare const getRequiredHeader: (headers: HeadersLike | Headers, header: string) => string;
  253. export declare const getHeader: (headers: HeadersLike | Headers, header: string) => string | undefined;
  254. /**
  255. * Encodes a string to Base64 format.
  256. */
  257. export declare const toBase64: (str: string | null | undefined) => string;
  258. /**
  259. * Converts a Base64 encoded string to a Float32Array.
  260. * @param base64Str - The Base64 encoded string.
  261. * @returns An Array of numbers interpreted as Float32 values.
  262. */
  263. export declare const toFloat32Array: (base64Str: string) => Array<number>;
  264. export declare function isObj(obj: unknown): obj is Record<string, unknown>;
  265. //# sourceMappingURL=core.d.ts.map