client.mjs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. // File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
  2. var _OpenAI_instances, _a, _OpenAI_encoder, _OpenAI_baseURLOverridden;
  3. import { __classPrivateFieldGet, __classPrivateFieldSet } from "./internal/tslib.mjs";
  4. import { uuid4 } from "./internal/utils/uuid.mjs";
  5. import { validatePositiveInteger, isAbsoluteURL, safeJSON } from "./internal/utils/values.mjs";
  6. import { sleep } from "./internal/utils/sleep.mjs";
  7. import { castToError, isAbortError } from "./internal/errors.mjs";
  8. import { getPlatformHeaders } from "./internal/detect-platform.mjs";
  9. import * as Shims from "./internal/shims.mjs";
  10. import * as Opts from "./internal/request-options.mjs";
  11. import * as qs from "./internal/qs/index.mjs";
  12. import { VERSION } from "./version.mjs";
  13. import * as Errors from "./core/error.mjs";
  14. import * as Pagination from "./core/pagination.mjs";
  15. import * as Uploads from "./core/uploads.mjs";
  16. import * as API from "./resources/index.mjs";
  17. import { APIPromise } from "./core/api-promise.mjs";
  18. import { Batches, } from "./resources/batches.mjs";
  19. import { Completions, } from "./resources/completions.mjs";
  20. import { Embeddings, } from "./resources/embeddings.mjs";
  21. import { Files, } from "./resources/files.mjs";
  22. import { Images, } from "./resources/images.mjs";
  23. import { Models } from "./resources/models.mjs";
  24. import { Moderations, } from "./resources/moderations.mjs";
  25. import { Videos, } from "./resources/videos.mjs";
  26. import { Webhooks } from "./resources/webhooks.mjs";
  27. import { Audio } from "./resources/audio/audio.mjs";
  28. import { Beta } from "./resources/beta/beta.mjs";
  29. import { Chat } from "./resources/chat/chat.mjs";
  30. import { Containers, } from "./resources/containers/containers.mjs";
  31. import { Conversations } from "./resources/conversations/conversations.mjs";
  32. import { Evals, } from "./resources/evals/evals.mjs";
  33. import { FineTuning } from "./resources/fine-tuning/fine-tuning.mjs";
  34. import { Graders } from "./resources/graders/graders.mjs";
  35. import { Realtime } from "./resources/realtime/realtime.mjs";
  36. import { Responses } from "./resources/responses/responses.mjs";
  37. import { Uploads as UploadsAPIUploads, } from "./resources/uploads/uploads.mjs";
  38. import { VectorStores, } from "./resources/vector-stores/vector-stores.mjs";
  39. import { isRunningInBrowser } from "./internal/detect-platform.mjs";
  40. import { buildHeaders } from "./internal/headers.mjs";
  41. import { readEnv } from "./internal/utils/env.mjs";
  42. import { formatRequestDetails, loggerFor, parseLogLevel, } from "./internal/utils/log.mjs";
  43. import { isEmptyObj } from "./internal/utils/values.mjs";
  44. /**
  45. * API Client for interfacing with the OpenAI API.
  46. */
  47. export class OpenAI {
  48. /**
  49. * API Client for interfacing with the OpenAI API.
  50. *
  51. * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]
  52. * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]
  53. * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]
  54. * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null]
  55. * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.
  56. * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.
  57. * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls.
  58. * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.
  59. * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.
  60. * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API.
  61. * @param {Record<string, string | undefined>} opts.defaultQuery - Default query parameters to include with every request to the API.
  62. * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.
  63. */
  64. constructor({ baseURL = readEnv('OPENAI_BASE_URL'), apiKey = readEnv('OPENAI_API_KEY'), organization = readEnv('OPENAI_ORG_ID') ?? null, project = readEnv('OPENAI_PROJECT_ID') ?? null, webhookSecret = readEnv('OPENAI_WEBHOOK_SECRET') ?? null, ...opts } = {}) {
  65. _OpenAI_instances.add(this);
  66. _OpenAI_encoder.set(this, void 0);
  67. this.completions = new API.Completions(this);
  68. this.chat = new API.Chat(this);
  69. this.embeddings = new API.Embeddings(this);
  70. this.files = new API.Files(this);
  71. this.images = new API.Images(this);
  72. this.audio = new API.Audio(this);
  73. this.moderations = new API.Moderations(this);
  74. this.models = new API.Models(this);
  75. this.fineTuning = new API.FineTuning(this);
  76. this.graders = new API.Graders(this);
  77. this.vectorStores = new API.VectorStores(this);
  78. this.webhooks = new API.Webhooks(this);
  79. this.beta = new API.Beta(this);
  80. this.batches = new API.Batches(this);
  81. this.uploads = new API.Uploads(this);
  82. this.responses = new API.Responses(this);
  83. this.realtime = new API.Realtime(this);
  84. this.conversations = new API.Conversations(this);
  85. this.evals = new API.Evals(this);
  86. this.containers = new API.Containers(this);
  87. this.videos = new API.Videos(this);
  88. if (apiKey === undefined) {
  89. throw new Errors.OpenAIError('Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.');
  90. }
  91. const options = {
  92. apiKey,
  93. organization,
  94. project,
  95. webhookSecret,
  96. ...opts,
  97. baseURL: baseURL || `https://api.openai.com/v1`,
  98. };
  99. if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) {
  100. throw new Errors.OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");
  101. }
  102. this.baseURL = options.baseURL;
  103. this.timeout = options.timeout ?? _a.DEFAULT_TIMEOUT /* 10 minutes */;
  104. this.logger = options.logger ?? console;
  105. const defaultLogLevel = 'warn';
  106. // Set default logLevel early so that we can log a warning in parseLogLevel.
  107. this.logLevel = defaultLogLevel;
  108. this.logLevel =
  109. parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ??
  110. parseLogLevel(readEnv('OPENAI_LOG'), "process.env['OPENAI_LOG']", this) ??
  111. defaultLogLevel;
  112. this.fetchOptions = options.fetchOptions;
  113. this.maxRetries = options.maxRetries ?? 2;
  114. this.fetch = options.fetch ?? Shims.getDefaultFetch();
  115. __classPrivateFieldSet(this, _OpenAI_encoder, Opts.FallbackEncoder, "f");
  116. this._options = options;
  117. this.apiKey = typeof apiKey === 'string' ? apiKey : 'Missing Key';
  118. this.organization = organization;
  119. this.project = project;
  120. this.webhookSecret = webhookSecret;
  121. }
  122. /**
  123. * Create a new client instance re-using the same options given to the current client with optional overriding.
  124. */
  125. withOptions(options) {
  126. const client = new this.constructor({
  127. ...this._options,
  128. baseURL: this.baseURL,
  129. maxRetries: this.maxRetries,
  130. timeout: this.timeout,
  131. logger: this.logger,
  132. logLevel: this.logLevel,
  133. fetch: this.fetch,
  134. fetchOptions: this.fetchOptions,
  135. apiKey: this.apiKey,
  136. organization: this.organization,
  137. project: this.project,
  138. webhookSecret: this.webhookSecret,
  139. ...options,
  140. });
  141. return client;
  142. }
  143. defaultQuery() {
  144. return this._options.defaultQuery;
  145. }
  146. validateHeaders({ values, nulls }) {
  147. return;
  148. }
  149. async authHeaders(opts) {
  150. return buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]);
  151. }
  152. stringifyQuery(query) {
  153. return qs.stringify(query, { arrayFormat: 'brackets' });
  154. }
  155. getUserAgent() {
  156. return `${this.constructor.name}/JS ${VERSION}`;
  157. }
  158. defaultIdempotencyKey() {
  159. return `stainless-node-retry-${uuid4()}`;
  160. }
  161. makeStatusError(status, error, message, headers) {
  162. return Errors.APIError.generate(status, error, message, headers);
  163. }
  164. async _callApiKey() {
  165. const apiKey = this._options.apiKey;
  166. if (typeof apiKey !== 'function')
  167. return false;
  168. let token;
  169. try {
  170. token = await apiKey();
  171. }
  172. catch (err) {
  173. if (err instanceof Errors.OpenAIError)
  174. throw err;
  175. throw new Errors.OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`,
  176. // @ts-ignore
  177. { cause: err });
  178. }
  179. if (typeof token !== 'string' || !token) {
  180. throw new Errors.OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`);
  181. }
  182. this.apiKey = token;
  183. return true;
  184. }
  185. buildURL(path, query, defaultBaseURL) {
  186. const baseURL = (!__classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL;
  187. const url = isAbsoluteURL(path) ?
  188. new URL(path)
  189. : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));
  190. const defaultQuery = this.defaultQuery();
  191. if (!isEmptyObj(defaultQuery)) {
  192. query = { ...defaultQuery, ...query };
  193. }
  194. if (typeof query === 'object' && query && !Array.isArray(query)) {
  195. url.search = this.stringifyQuery(query);
  196. }
  197. return url.toString();
  198. }
  199. /**
  200. * Used as a callback for mutating the given `FinalRequestOptions` object.
  201. */
  202. async prepareOptions(options) {
  203. await this._callApiKey();
  204. }
  205. /**
  206. * Used as a callback for mutating the given `RequestInit` object.
  207. *
  208. * This is useful for cases where you want to add certain headers based off of
  209. * the request properties, e.g. `method` or `url`.
  210. */
  211. async prepareRequest(request, { url, options }) { }
  212. get(path, opts) {
  213. return this.methodRequest('get', path, opts);
  214. }
  215. post(path, opts) {
  216. return this.methodRequest('post', path, opts);
  217. }
  218. patch(path, opts) {
  219. return this.methodRequest('patch', path, opts);
  220. }
  221. put(path, opts) {
  222. return this.methodRequest('put', path, opts);
  223. }
  224. delete(path, opts) {
  225. return this.methodRequest('delete', path, opts);
  226. }
  227. methodRequest(method, path, opts) {
  228. return this.request(Promise.resolve(opts).then((opts) => {
  229. return { method, path, ...opts };
  230. }));
  231. }
  232. request(options, remainingRetries = null) {
  233. return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined));
  234. }
  235. async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) {
  236. const options = await optionsInput;
  237. const maxRetries = options.maxRetries ?? this.maxRetries;
  238. if (retriesRemaining == null) {
  239. retriesRemaining = maxRetries;
  240. }
  241. await this.prepareOptions(options);
  242. const { req, url, timeout } = await this.buildRequest(options, {
  243. retryCount: maxRetries - retriesRemaining,
  244. });
  245. await this.prepareRequest(req, { url, options });
  246. /** Not an API request ID, just for correlating local log entries. */
  247. const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0');
  248. const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`;
  249. const startTime = Date.now();
  250. loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({
  251. retryOfRequestLogID,
  252. method: options.method,
  253. url,
  254. options,
  255. headers: req.headers,
  256. }));
  257. if (options.signal?.aborted) {
  258. throw new Errors.APIUserAbortError();
  259. }
  260. const controller = new AbortController();
  261. const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);
  262. const headersTime = Date.now();
  263. if (response instanceof globalThis.Error) {
  264. const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
  265. if (options.signal?.aborted) {
  266. throw new Errors.APIUserAbortError();
  267. }
  268. // detect native connection timeout errors
  269. // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)"
  270. // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)"
  271. // others do not provide enough information to distinguish timeouts from other connection errors
  272. const isTimeout = isAbortError(response) ||
  273. /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : ''));
  274. if (retriesRemaining) {
  275. loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`);
  276. loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({
  277. retryOfRequestLogID,
  278. url,
  279. durationMs: headersTime - startTime,
  280. message: response.message,
  281. }));
  282. return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID);
  283. }
  284. loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`);
  285. loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({
  286. retryOfRequestLogID,
  287. url,
  288. durationMs: headersTime - startTime,
  289. message: response.message,
  290. }));
  291. if (isTimeout) {
  292. throw new Errors.APIConnectionTimeoutError();
  293. }
  294. throw new Errors.APIConnectionError({ cause: response });
  295. }
  296. const specialHeaders = [...response.headers.entries()]
  297. .filter(([name]) => name === 'x-request-id')
  298. .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value))
  299. .join('');
  300. const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`;
  301. if (!response.ok) {
  302. const shouldRetry = await this.shouldRetry(response);
  303. if (retriesRemaining && shouldRetry) {
  304. const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;
  305. // We don't need the body of this response.
  306. await Shims.CancelReadableStream(response.body);
  307. loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
  308. loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
  309. retryOfRequestLogID,
  310. url: response.url,
  311. status: response.status,
  312. headers: response.headers,
  313. durationMs: headersTime - startTime,
  314. }));
  315. return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers);
  316. }
  317. const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`;
  318. loggerFor(this).info(`${responseInfo} - ${retryMessage}`);
  319. const errText = await response.text().catch((err) => castToError(err).message);
  320. const errJSON = safeJSON(errText);
  321. const errMessage = errJSON ? undefined : errText;
  322. loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({
  323. retryOfRequestLogID,
  324. url: response.url,
  325. status: response.status,
  326. headers: response.headers,
  327. message: errMessage,
  328. durationMs: Date.now() - startTime,
  329. }));
  330. const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers);
  331. throw err;
  332. }
  333. loggerFor(this).info(responseInfo);
  334. loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({
  335. retryOfRequestLogID,
  336. url: response.url,
  337. status: response.status,
  338. headers: response.headers,
  339. durationMs: headersTime - startTime,
  340. }));
  341. return { response, options, controller, requestLogID, retryOfRequestLogID, startTime };
  342. }
  343. getAPIList(path, Page, opts) {
  344. return this.requestAPIList(Page, { method: 'get', path, ...opts });
  345. }
  346. requestAPIList(Page, options) {
  347. const request = this.makeRequest(options, null, undefined);
  348. return new Pagination.PagePromise(this, request, Page);
  349. }
  350. async fetchWithTimeout(url, init, ms, controller) {
  351. const { signal, method, ...options } = init || {};
  352. if (signal)
  353. signal.addEventListener('abort', () => controller.abort());
  354. const timeout = setTimeout(() => controller.abort(), ms);
  355. const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) ||
  356. (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body);
  357. const fetchOptions = {
  358. signal: controller.signal,
  359. ...(isReadableBody ? { duplex: 'half' } : {}),
  360. method: 'GET',
  361. ...options,
  362. };
  363. if (method) {
  364. // Custom methods like 'patch' need to be uppercased
  365. // See https://github.com/nodejs/undici/issues/2294
  366. fetchOptions.method = method.toUpperCase();
  367. }
  368. try {
  369. // use undefined this binding; fetch errors if bound to something else in browser/cloudflare
  370. return await this.fetch.call(undefined, url, fetchOptions);
  371. }
  372. finally {
  373. clearTimeout(timeout);
  374. }
  375. }
  376. async shouldRetry(response) {
  377. // Note this is not a standard header.
  378. const shouldRetryHeader = response.headers.get('x-should-retry');
  379. // If the server explicitly says whether or not to retry, obey.
  380. if (shouldRetryHeader === 'true')
  381. return true;
  382. if (shouldRetryHeader === 'false')
  383. return false;
  384. // Retry on request timeouts.
  385. if (response.status === 408)
  386. return true;
  387. // Retry on lock timeouts.
  388. if (response.status === 409)
  389. return true;
  390. // Retry on rate limits.
  391. if (response.status === 429)
  392. return true;
  393. // Retry internal errors.
  394. if (response.status >= 500)
  395. return true;
  396. return false;
  397. }
  398. async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) {
  399. let timeoutMillis;
  400. // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.
  401. const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms');
  402. if (retryAfterMillisHeader) {
  403. const timeoutMs = parseFloat(retryAfterMillisHeader);
  404. if (!Number.isNaN(timeoutMs)) {
  405. timeoutMillis = timeoutMs;
  406. }
  407. }
  408. // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After
  409. const retryAfterHeader = responseHeaders?.get('retry-after');
  410. if (retryAfterHeader && !timeoutMillis) {
  411. const timeoutSeconds = parseFloat(retryAfterHeader);
  412. if (!Number.isNaN(timeoutSeconds)) {
  413. timeoutMillis = timeoutSeconds * 1000;
  414. }
  415. else {
  416. timeoutMillis = Date.parse(retryAfterHeader) - Date.now();
  417. }
  418. }
  419. // If the API asks us to wait a certain amount of time (and it's a reasonable amount),
  420. // just do what it says, but otherwise calculate a default
  421. if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {
  422. const maxRetries = options.maxRetries ?? this.maxRetries;
  423. timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);
  424. }
  425. await sleep(timeoutMillis);
  426. return this.makeRequest(options, retriesRemaining - 1, requestLogID);
  427. }
  428. calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {
  429. const initialRetryDelay = 0.5;
  430. const maxRetryDelay = 8.0;
  431. const numRetries = maxRetries - retriesRemaining;
  432. // Apply exponential backoff, but not more than the max.
  433. const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);
  434. // Apply some jitter, take up to at most 25 percent of the retry time.
  435. const jitter = 1 - Math.random() * 0.25;
  436. return sleepSeconds * jitter * 1000;
  437. }
  438. async buildRequest(inputOptions, { retryCount = 0 } = {}) {
  439. const options = { ...inputOptions };
  440. const { method, path, query, defaultBaseURL } = options;
  441. const url = this.buildURL(path, query, defaultBaseURL);
  442. if ('timeout' in options)
  443. validatePositiveInteger('timeout', options.timeout);
  444. options.timeout = options.timeout ?? this.timeout;
  445. const { bodyHeaders, body } = this.buildBody({ options });
  446. const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount });
  447. const req = {
  448. method,
  449. headers: reqHeaders,
  450. ...(options.signal && { signal: options.signal }),
  451. ...(globalThis.ReadableStream &&
  452. body instanceof globalThis.ReadableStream && { duplex: 'half' }),
  453. ...(body && { body }),
  454. ...(this.fetchOptions ?? {}),
  455. ...(options.fetchOptions ?? {}),
  456. };
  457. return { req, url, timeout: options.timeout };
  458. }
  459. async buildHeaders({ options, method, bodyHeaders, retryCount, }) {
  460. let idempotencyHeaders = {};
  461. if (this.idempotencyHeader && method !== 'get') {
  462. if (!options.idempotencyKey)
  463. options.idempotencyKey = this.defaultIdempotencyKey();
  464. idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey;
  465. }
  466. const headers = buildHeaders([
  467. idempotencyHeaders,
  468. {
  469. Accept: 'application/json',
  470. 'User-Agent': this.getUserAgent(),
  471. 'X-Stainless-Retry-Count': String(retryCount),
  472. ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}),
  473. ...getPlatformHeaders(),
  474. 'OpenAI-Organization': this.organization,
  475. 'OpenAI-Project': this.project,
  476. },
  477. await this.authHeaders(options),
  478. this._options.defaultHeaders,
  479. bodyHeaders,
  480. options.headers,
  481. ]);
  482. this.validateHeaders(headers);
  483. return headers.values;
  484. }
  485. buildBody({ options: { body, headers: rawHeaders } }) {
  486. if (!body) {
  487. return { bodyHeaders: undefined, body: undefined };
  488. }
  489. const headers = buildHeaders([rawHeaders]);
  490. if (
  491. // Pass raw type verbatim
  492. ArrayBuffer.isView(body) ||
  493. body instanceof ArrayBuffer ||
  494. body instanceof DataView ||
  495. (typeof body === 'string' &&
  496. // Preserve legacy string encoding behavior for now
  497. headers.values.has('content-type')) ||
  498. // `Blob` is superset of `File`
  499. (globalThis.Blob && body instanceof globalThis.Blob) ||
  500. // `FormData` -> `multipart/form-data`
  501. body instanceof FormData ||
  502. // `URLSearchParams` -> `application/x-www-form-urlencoded`
  503. body instanceof URLSearchParams ||
  504. // Send chunked stream (each chunk has own `length`)
  505. (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) {
  506. return { bodyHeaders: undefined, body: body };
  507. }
  508. else if (typeof body === 'object' &&
  509. (Symbol.asyncIterator in body ||
  510. (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) {
  511. return { bodyHeaders: undefined, body: Shims.ReadableStreamFrom(body) };
  512. }
  513. else {
  514. return __classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers });
  515. }
  516. }
  517. }
  518. _a = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() {
  519. return this.baseURL !== 'https://api.openai.com/v1';
  520. };
  521. OpenAI.OpenAI = _a;
  522. OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes
  523. OpenAI.OpenAIError = Errors.OpenAIError;
  524. OpenAI.APIError = Errors.APIError;
  525. OpenAI.APIConnectionError = Errors.APIConnectionError;
  526. OpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;
  527. OpenAI.APIUserAbortError = Errors.APIUserAbortError;
  528. OpenAI.NotFoundError = Errors.NotFoundError;
  529. OpenAI.ConflictError = Errors.ConflictError;
  530. OpenAI.RateLimitError = Errors.RateLimitError;
  531. OpenAI.BadRequestError = Errors.BadRequestError;
  532. OpenAI.AuthenticationError = Errors.AuthenticationError;
  533. OpenAI.InternalServerError = Errors.InternalServerError;
  534. OpenAI.PermissionDeniedError = Errors.PermissionDeniedError;
  535. OpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError;
  536. OpenAI.InvalidWebhookSignatureError = Errors.InvalidWebhookSignatureError;
  537. OpenAI.toFile = Uploads.toFile;
  538. OpenAI.Completions = Completions;
  539. OpenAI.Chat = Chat;
  540. OpenAI.Embeddings = Embeddings;
  541. OpenAI.Files = Files;
  542. OpenAI.Images = Images;
  543. OpenAI.Audio = Audio;
  544. OpenAI.Moderations = Moderations;
  545. OpenAI.Models = Models;
  546. OpenAI.FineTuning = FineTuning;
  547. OpenAI.Graders = Graders;
  548. OpenAI.VectorStores = VectorStores;
  549. OpenAI.Webhooks = Webhooks;
  550. OpenAI.Beta = Beta;
  551. OpenAI.Batches = Batches;
  552. OpenAI.Uploads = UploadsAPIUploads;
  553. OpenAI.Responses = Responses;
  554. OpenAI.Realtime = Realtime;
  555. OpenAI.Conversations = Conversations;
  556. OpenAI.Evals = Evals;
  557. OpenAI.Containers = Containers;
  558. OpenAI.Videos = Videos;
  559. //# sourceMappingURL=client.mjs.map