(() => { "use strict"; const e = "RFC3986", t = { RFC1738: e => String(e).replace(/%20/g, "+"), RFC3986: e => String(e) }, s = (Object.prototype.hasOwnProperty, Array.isArray), n = (() => { const e = []; for (let t = 0; t < 256; ++t)e.push("%" + ((t < 16 ? "0" : "") + t.toString(16)).toUpperCase()); return e })(), r = 1024; function o(e, t) { if (s(e)) { const s = []; for (let n = 0; n < e.length; n += 1)s.push(t(e[n])); return s } return t(e) } const a = Object.prototype.hasOwnProperty, i = { brackets: e => String(e) + "[]", comma: "comma", indices: (e, t) => String(e) + "[" + t + "]", repeat: e => String(e) }, l = Array.isArray, c = Array.prototype.push, u = function (e, t) { c.apply(e, l(t) ? t : [t]) }, h = Date.prototype.toISOString, d = { addQueryPrefix: !1, allowDots: !1, allowEmptyArrays: !1, arrayFormat: "indices", charset: "utf-8", charsetSentinel: !1, delimiter: "&", encode: !0, encodeDotInKeys: !1, encoder: (e, t, s, o, a) => { if (0 === e.length) return e; let i = e; if ("symbol" == typeof e ? i = Symbol.prototype.toString.call(e) : "string" != typeof e && (i = String(e)), "iso-8859-1" === s) return escape(i).replace(/%u[0-9a-f]{4}/gi, (function (e) { return "%26%23" + parseInt(e.slice(2), 16) + "%3B" })); let l = ""; for (let e = 0; e < i.length; e += r) { const t = i.length >= r ? i.slice(e, e + r) : i, s = []; for (let e = 0; e < t.length; ++e) { let r = t.charCodeAt(e); 45 === r || 46 === r || 95 === r || 126 === r || r >= 48 && r <= 57 || r >= 65 && r <= 90 || r >= 97 && r <= 122 || "RFC1738" === a && (40 === r || 41 === r) ? s[s.length] = t.charAt(e) : r < 128 ? s[s.length] = n[r] : r < 2048 ? s[s.length] = n[192 | r >> 6] + n[128 | 63 & r] : r < 55296 || r >= 57344 ? s[s.length] = n[224 | r >> 12] + n[128 | r >> 6 & 63] + n[128 | 63 & r] : (e += 1, r = 65536 + ((1023 & r) << 10 | 1023 & t.charCodeAt(e)), s[s.length] = n[240 | r >> 18] + n[128 | r >> 12 & 63] + n[128 | r >> 6 & 63] + n[128 | 63 & r]) } l += s.join("") } return l }, encodeValuesOnly: !1, format: e, formatter: t[e], indices: !1, serializeDate: e => h.call(e), skipNulls: !1, strictNullHandling: !1 }, f = {}; function p(e, t, s, n, r, a, i, c, h, m, g, y, w, b, _, v, x, S) { let A = e, R = S, E = 0, P = !1; for (; void 0 !== (R = R.get(f)) && !P;) { const t = R.get(e); if (E += 1, void 0 !== t) { if (t === E) throw new RangeError("Cyclic object value"); P = !0 } void 0 === R.get(f) && (E = 0) } if ("function" == typeof m ? A = m(t, A) : A instanceof Date ? A = w?.(A) : "comma" === s && l(A) && (A = o(A, (function (e) { return e instanceof Date ? w?.(e) : e }))), null === A) { if (a) return h && !v ? h(t, d.encoder, x, "key", b) : t; A = "" } if ("string" == typeof (I = A) || "number" == typeof I || "boolean" == typeof I || "symbol" == typeof I || "bigint" == typeof I || function (e) { return !(!e || "object" != typeof e || !(e.constructor && e.constructor.isBuffer && e.constructor.isBuffer(e))) }(A)) { if (h) { const e = v ? t : h(t, d.encoder, x, "key", b); return [_?.(e) + "=" + _?.(h(A, d.encoder, x, "value", b))] } return [_?.(t) + "=" + _?.(String(A))] } var I; const C = []; if (void 0 === A) return C; let O; if ("comma" === s && l(A)) v && h && (A = o(A, h)), O = [{ value: A.length > 0 ? A.join(",") || null : void 0 }]; else if (l(m)) O = m; else { const e = Object.keys(A); O = g ? e.sort(g) : e } const $ = c ? String(t).replace(/\./g, "%2E") : String(t), k = n && l(A) && 1 === A.length ? $ + "[]" : $; if (r && l(A) && 0 === A.length) return k + "[]"; for (let t = 0; t < O.length; ++t) { const o = O[t], d = "object" == typeof o && void 0 !== o.value ? o.value : A[o]; if (i && null === d) continue; const R = y && c ? o.replace(/\./g, "%2E") : o, P = l(A) ? "function" == typeof s ? s(k, R) : k : k + (y ? "." + R : "[" + R + "]"); S.set(e, E); const I = new WeakMap; I.set(f, S), u(C, p(d, P, s, n, r, a, i, c, "comma" === s && v && l(A) ? null : h, m, g, y, w, b, _, v, x, I)) } return C } const m = "4.83.0"; let g, y, w, b, _, v, x, S, A, R = !1, E = null, P = null, I = null, C = null; class O { constructor(e) { this.body = e } get [Symbol.toStringTag]() { return "MultipartBody" } } g || function (e, t = { auto: !1 }) { if (R) throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`); if (g) throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${g}'\``); R = t.auto, g = e.kind, y = e.fetch, E = e.Request, P = e.Response, I = e.Headers, w = e.FormData, C = e.Blob, b = e.File, _ = e.ReadableStream, v = e.getMultipartRequestOptions, x = e.getDefaultAgent, S = e.fileFromPath, A = e.isFsReadStream }(function ({ manuallyImported: e } = {}) { const t = e ? "You may need to use polyfills" : "Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n"; let s, n, r, o; try { s = fetch, n = Request, r = Response, o = Headers } catch (e) { throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`) } return { kind: "web", fetch: s, Request: n, Response: r, Headers: o, FormData: "undefined" != typeof FormData ? FormData : class { constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`) } }, Blob: "undefined" != typeof Blob ? Blob : class { constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`) } }, File: "undefined" != typeof File ? File : class { constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`) } }, ReadableStream: "undefined" != typeof ReadableStream ? ReadableStream : class { constructor() { throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`) } }, getMultipartRequestOptions: async (e, t) => ({ ...t, body: new O(e) }), getDefaultAgent: e => { }, fileFromPath: () => { throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads") }, isFsReadStream: e => !1 } }(), { auto: !0 }); class $ extends Error { } class k extends $ { constructor(e, t, s, n) { super(`${k.makeMessage(e, t, s)}`), this.status = e, this.headers = n, this.request_id = n?.["x-request-id"], this.error = t; const r = t; this.code = r?.code, this.param = r?.param, this.type = r?.type } static makeMessage(e, t, s) { const n = t?.message ? "string" == typeof t.message ? t.message : JSON.stringify(t.message) : t ? JSON.stringify(t) : s; return e && n ? `${e} ${n}` : e ? `${e} status code (no body)` : n || "(no status code or body)" } static generate(e, t, s, n) { if (!e || !n) return new j({ message: s, cause: Ee(t) }); const r = t?.error; return 400 === e ? new N(e, r, s, n) : 401 === e ? new D(e, r, s, n) : 403 === e ? new B(e, r, s, n) : 404 === e ? new F(e, r, s, n) : 409 === e ? new q(e, r, s, n) : 422 === e ? new L(e, r, s, n) : 429 === e ? new W(e, r, s, n) : e >= 500 ? new U(e, r, s, n) : new k(e, r, s, n) } } class T extends k { constructor({ message: e } = {}) { super(void 0, void 0, e || "Request was aborted.", void 0) } } class j extends k { constructor({ message: e, cause: t }) { super(void 0, void 0, e || "Connection error.", void 0), t && (this.cause = t) } } class M extends j { constructor({ message: e } = {}) { super({ message: e ?? "Request timed out." }) } } class N extends k { } class D extends k { } class B extends k { } class F extends k { } class q extends k { } class L extends k { } class W extends k { } class U extends k { } class X extends $ { constructor() { super("Could not parse response content as the length limit was reached") } } class J extends $ { constructor() { super("Could not parse response content as the request was rejected by the content filter") } } class H { constructor() { this.buffer = [], this.trailingCR = !1 } decode(e) { let t = this.decodeText(e); if (this.trailingCR && (t = "\r" + t, this.trailingCR = !1), t.endsWith("\r") && (this.trailingCR = !0, t = t.slice(0, -1)), !t) return []; const s = H.NEWLINE_CHARS.has(t[t.length - 1] || ""); let n = t.split(H.NEWLINE_REGEXP); return s && n.pop(), 1 !== n.length || s ? (this.buffer.length > 0 && (n = [this.buffer.join("") + n[0], ...n.slice(1)], this.buffer = []), s || (this.buffer = [n.pop() || ""]), n) : (this.buffer.push(n[0]), []) } decodeText(e) { if (null == e) return ""; if ("string" == typeof e) return e; if ("undefined" != typeof Buffer) { if (e instanceof Buffer) return e.toString(); if (e instanceof Uint8Array) return Buffer.from(e).toString(); throw new $(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`) } if ("undefined" != typeof TextDecoder) { if (e instanceof Uint8Array || e instanceof ArrayBuffer) return this.textDecoder ?? (this.textDecoder = new TextDecoder("utf8")), this.textDecoder.decode(e); throw new $(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`) } throw new $("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.") } flush() { if (!this.buffer.length && !this.trailingCR) return []; const e = [this.buffer.join("")]; return this.buffer = [], this.trailingCR = !1, e } } function V(e) { if (e[Symbol.asyncIterator]) return e; const t = e.getReader(); return { async next() { try { const e = await t.read(); return e?.done && t.releaseLock(), e } catch (e) { throw t.releaseLock(), e } }, async return() { const e = t.cancel(); return t.releaseLock(), await e, { done: !0, value: void 0 } }, [Symbol.asyncIterator]() { return this } } } H.NEWLINE_CHARS = new Set(["\n", "\r"]), H.NEWLINE_REGEXP = /\r\n|[\n\r]/g; class K { constructor(e, t) { this.iterator = e, this.controller = t } static fromSSEResponse(e, t) { let s = !1; return new K((async function* () { if (s) throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); s = !0; let n = !1; try { for await (const s of async function* (e, t) { if (!e.body) throw t.abort(), new $("Attempted to iterate over a response with no body"); const s = new Q, n = new H, r = V(e.body); for await (const e of async function* (e) { let t = new Uint8Array; for await (const s of e) { if (null == s) continue; const e = s instanceof ArrayBuffer ? new Uint8Array(s) : "string" == typeof s ? (new TextEncoder).encode(s) : s; let n, r = new Uint8Array(t.length + e.length); for (r.set(t), r.set(e, t.length), t = r; -1 !== (n = z(t));)yield t.slice(0, n), t = t.slice(n) } t.length > 0 && (yield t) }(r)) for (const t of n.decode(e)) { const e = s.decode(t); e && (yield e) } for (const e of n.flush()) { const t = s.decode(e); t && (yield t) } }(e, t)) if (!n) if (s.data.startsWith("[DONE]")) n = !0; else if (null === s.event) { let e; try { e = JSON.parse(s.data) } catch (e) { throw console.error("Could not parse message into JSON:", s.data), console.error("From chunk:", s.raw), e } if (e && e.error) throw new k(void 0, e.error, void 0, void 0); yield e } else { let e; try { e = JSON.parse(s.data) } catch (e) { throw console.error("Could not parse message into JSON:", s.data), console.error("From chunk:", s.raw), e } if ("error" == s.event) throw new k(void 0, e.error, e.message, void 0); yield { event: s.event, data: e } } n = !0 } catch (e) { if (e instanceof Error && "AbortError" === e.name) return; throw e } finally { n || t.abort() } }), t) } static fromReadableStream(e, t) { let s = !1; return new K((async function* () { if (s) throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); s = !0; let n = !1; try { for await (const t of async function* () { const t = new H, s = V(e); for await (const e of s) for (const s of t.decode(e)) yield s; for (const e of t.flush()) yield e }()) n || t && (yield JSON.parse(t)); n = !0 } catch (e) { if (e instanceof Error && "AbortError" === e.name) return; throw e } finally { n || t.abort() } }), t) } [Symbol.asyncIterator]() { return this.iterator() } tee() { const e = [], t = [], s = this.iterator(), n = n => ({ next: () => { if (0 === n.length) { const n = s.next(); e.push(n), t.push(n) } return n.shift() } }); return [new K((() => n(e)), this.controller), new K((() => n(t)), this.controller)] } toReadableStream() { const e = this; let t; const s = new TextEncoder; return new _({ async start() { t = e[Symbol.asyncIterator]() }, async pull(e) { try { const { value: n, done: r } = await t.next(); if (r) return e.close(); const o = s.encode(JSON.stringify(n) + "\n"); e.enqueue(o) } catch (t) { e.error(t) } }, async cancel() { await (t.return?.()) } }) } } function z(e) { for (let t = 0; t < e.length - 2; t++) { if (10 === e[t] && 10 === e[t + 1]) return t + 2; if (13 === e[t] && 13 === e[t + 1]) return t + 2; if (13 === e[t] && 10 === e[t + 1] && t + 3 < e.length && 13 === e[t + 2] && 10 === e[t + 3]) return t + 4 } return -1 } class Q { constructor() { this.event = null, this.data = [], this.chunks = [] } decode(e) { if (e.endsWith("\r") && (e = e.substring(0, e.length - 1)), !e) { if (!this.event && !this.data.length) return null; const e = { event: this.event, data: this.data.join("\n"), raw: this.chunks }; return this.event = null, this.data = [], this.chunks = [], e } if (this.chunks.push(e), e.startsWith(":")) return null; let [t, s, n] = function (e) { const t = e.indexOf(":"); return -1 !== t ? [e.substring(0, t), ":", e.substring(t + 1)] : [e, "", ""] }(e); return n.startsWith(" ") && (n = n.substring(1)), "event" === t ? this.event = n : "data" === t && this.data.push(n), null } } const G = e => null != e && "object" == typeof e && "string" == typeof e.url && "function" == typeof e.blob, Y = e => null != e && "object" == typeof e && "string" == typeof e.name && "number" == typeof e.lastModified && Z(e), Z = e => null != e && "object" == typeof e && "number" == typeof e.size && "string" == typeof e.type && "function" == typeof e.text && "function" == typeof e.slice && "function" == typeof e.arrayBuffer; async function ee(e, t, s) { if (e = await e, Y(e)) return e; if (G(e)) { const n = await e.blob(); t || (t = new URL(e.url).pathname.split(/[\\/]/).pop() ?? "unknown_file"); const r = Z(n) ? [await n.arrayBuffer()] : [n]; return new b(r, t, s) } const n = await async function (e) { let t = []; if ("string" == typeof e || ArrayBuffer.isView(e) || e instanceof ArrayBuffer) t.push(e); else if (Z(e)) t.push(await e.arrayBuffer()); else { if (!se(e)) throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function (e) { return `[${Object.getOwnPropertyNames(e).map((e => `"${e}"`)).join(", ")}]` }(e)}`); for await (const s of e) t.push(s) } return t }(e); if (t || (t = function (e) { return te(e.name) || te(e.filename) || te(e.path)?.split(/[\\/]/).pop() }(e) ?? "unknown_file"), !s?.type) { const e = n[0]?.type; "string" == typeof e && (s = { ...s, type: e }) } return new b(n, t, s) } const te = e => "string" == typeof e ? e : "undefined" != typeof Buffer && e instanceof Buffer ? String(e) : void 0, se = e => null != e && "object" == typeof e && "function" == typeof e[Symbol.asyncIterator], ne = e => e && "object" == typeof e && e.body && "MultipartBody" === e[Symbol.toStringTag], re = async e => { const t = await oe(e.body); return v(t, e) }, oe = async e => { const t = new w; return await Promise.all(Object.entries(e || {}).map((([e, s]) => ae(t, e, s)))), t }, ae = async (e, t, s) => { if (void 0 !== s) { if (null == s) throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`); if ("string" == typeof s || "number" == typeof s || "boolean" == typeof s) e.append(t, String(s)); else if ((e => Y(e) || G(e) || A(e))(s)) { const n = await ee(s); e.append(t, n) } else if (Array.isArray(s)) await Promise.all(s.map((s => ae(e, t + "[]", s)))); else { if ("object" != typeof s) throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`); await Promise.all(Object.entries(s).map((([s, n]) => ae(e, `${t}[${s}]`, n)))) } } }; var ie; async function le(e) { const { response: t } = e; if (e.options.stream) return ke("response", t.status, t.url, t.headers, t.body), e.options.__streamClass ? e.options.__streamClass.fromSSEResponse(t, e.controller) : K.fromSSEResponse(t, e.controller); if (204 === t.status) return null; if (e.options.__binaryResponse) return t; const s = t.headers.get("content-type"); if (s?.includes("application/json") || s?.includes("application/vnd.api+json")) { const e = await t.json(); return ke("response", t.status, t.url, t.headers, e), ce(e, t) } const n = await t.text(); return ke("response", t.status, t.url, t.headers, n), n } function ce(e, t) { return !e || "object" != typeof e || Array.isArray(e) ? e : Object.defineProperty(e, "_request_id", { value: t.headers.get("x-request-id"), enumerable: !1 }) } class ue extends Promise { constructor(e, t = le) { super((e => { e(null) })), this.responsePromise = e, this.parseResponse = t } _thenUnwrap(e) { return new ue(this.responsePromise, (async t => ce(e(await this.parseResponse(t), t), t.response))) } asResponse() { return this.responsePromise.then((e => e.response)) } async withResponse() { const [e, t] = await Promise.all([this.parse(), this.asResponse()]); return { data: e, response: t, request_id: t.headers.get("x-request-id") } } parse() { return this.parsedPromise || (this.parsedPromise = this.responsePromise.then(this.parseResponse)), this.parsedPromise } then(e, t) { return this.parse().then(e, t) } catch(e) { return this.parse().catch(e) } finally(e) { return this.parse().finally(e) } } class he { constructor({ baseURL: e, maxRetries: t = 2, timeout: s = 6e5, httpAgent: n, fetch: r }) { this.baseURL = e, this.maxRetries = Re("maxRetries", t), this.timeout = Re("timeout", s), this.httpAgent = n, this.fetch = r ?? y } authHeaders(e) { return {} } defaultHeaders(e) { return { Accept: "application/json", "Content-Type": "application/json", "User-Agent": this.getUserAgent(), ..._e(), ...this.authHeaders(e) } } validateHeaders(e, t) { } defaultIdempotencyKey() { return `stainless-node-retry-${Te()}` } get(e, t) { return this.methodRequest("get", e, t) } post(e, t) { return this.methodRequest("post", e, t) } patch(e, t) { return this.methodRequest("patch", e, t) } put(e, t) { return this.methodRequest("put", e, t) } delete(e, t) { return this.methodRequest("delete", e, t) } methodRequest(e, t, s) { return this.request(Promise.resolve(s).then((async s => { const n = s && Z(s?.body) ? new DataView(await s.body.arrayBuffer()) : s?.body instanceof DataView ? s.body : s?.body instanceof ArrayBuffer ? new DataView(s.body) : s && ArrayBuffer.isView(s?.body) ? new DataView(s.body.buffer) : s?.body; return { method: e, path: t, ...s, body: n } }))) } getAPIList(e, t, s) { return this.requestAPIList(t, { method: "get", path: e, ...s }) } calculateContentLength(e) { if ("string" == typeof e) { if ("undefined" != typeof Buffer) return Buffer.byteLength(e, "utf8").toString(); if ("undefined" != typeof TextEncoder) return (new TextEncoder).encode(e).length.toString() } else if (ArrayBuffer.isView(e)) return e.byteLength.toString(); return null } buildRequest(e, { retryCount: t = 0 } = {}) { e = { ...e }; const { method: s, path: n, query: r, headers: o = {} } = e, a = ArrayBuffer.isView(e.body) || e.__binaryRequest && "string" == typeof e.body ? e.body : ne(e.body) ? e.body.body : e.body ? JSON.stringify(e.body, null, 2) : null, i = this.calculateContentLength(a), l = this.buildURL(n, r); "timeout" in e && Re("timeout", e.timeout), e.timeout = e.timeout ?? this.timeout; const c = e.httpAgent ?? this.httpAgent ?? x(l), u = e.timeout + 1e3; return "number" == typeof c?.options?.timeout && u > (c.options.timeout ?? 0) && (c.options.timeout = u), this.idempotencyHeader && "get" !== s && (e.idempotencyKey || (e.idempotencyKey = this.defaultIdempotencyKey()), o[this.idempotencyHeader] = e.idempotencyKey), { req: { method: s, ...a && { body: a }, headers: this.buildHeaders({ options: e, headers: o, contentLength: i, retryCount: t }), ...c && { agent: c }, signal: e.signal ?? null }, url: l, timeout: e.timeout } } buildHeaders({ options: e, headers: t, contentLength: s, retryCount: n }) { const r = {}; s && (r["content-length"] = s); const o = this.defaultHeaders(e); return Oe(r, o), Oe(r, t), ne(e.body) && "node" !== g && delete r["content-type"], void 0 === je(o, "x-stainless-retry-count") && void 0 === je(t, "x-stainless-retry-count") && (r["x-stainless-retry-count"] = String(n)), void 0 === je(o, "x-stainless-timeout") && void 0 === je(t, "x-stainless-timeout") && e.timeout && (r["x-stainless-timeout"] = String(e.timeout)), this.validateHeaders(r, t), r } async prepareOptions(e) { } async prepareRequest(e, { url: t, options: s }) { } parseHeaders(e) { return e ? Symbol.iterator in e ? Object.fromEntries(Array.from(e).map((e => [...e]))) : { ...e } : {} } makeStatusError(e, t, s, n) { return k.generate(e, t, s, n) } request(e, t = null) { return new ue(this.makeRequest(e, t)) } async makeRequest(e, t) { const s = await e, n = s.maxRetries ?? this.maxRetries; null == t && (t = n), await this.prepareOptions(s); const { req: r, url: o, timeout: a } = this.buildRequest(s, { retryCount: n - t }); if (await this.prepareRequest(r, { url: o, options: s }), ke("request", o, s, r.headers), s.signal?.aborted) throw new T; const i = new AbortController, l = await this.fetchWithTimeout(o, r, a, i).catch(Ee); if (l instanceof Error) { if (s.signal?.aborted) throw new T; if (t) return this.retryRequest(s, t); if ("AbortError" === l.name) throw new M; throw new j({ cause: l }) } const c = pe(l.headers); if (!l.ok) { if (t && this.shouldRetry(l)) return ke(`response (error; retrying, ${t} attempts remaining)`, l.status, o, c), this.retryRequest(s, t, c); const e = await l.text().catch((e => Ee(e).message)), n = ve(e), r = n ? void 0 : e; throw ke(`response (error; ${t ? "(error; no more retries left)" : "(error; not retryable)"})`, l.status, o, c, r), this.makeStatusError(l.status, n, r, c) } return { response: l, options: s, controller: i } } requestAPIList(e, t) { const s = this.makeRequest(t, null); return new fe(this, s, e) } buildURL(e, t) { const s = Se(e) ? new URL(e) : new URL(this.baseURL + (this.baseURL.endsWith("/") && e.startsWith("/") ? e.slice(1) : e)), n = this.defaultQuery(); return Ie(n) || (t = { ...n, ...t }), "object" == typeof t && t && !Array.isArray(t) && (s.search = this.stringifyQuery(t)), s.toString() } stringifyQuery(e) { return Object.entries(e).filter((([e, t]) => void 0 !== t)).map((([e, t]) => { if ("string" == typeof t || "number" == typeof t || "boolean" == typeof t) return `${encodeURIComponent(e)}=${encodeURIComponent(t)}`; if (null === t) return `${encodeURIComponent(e)}=`; throw new $(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`) })).join("&") } async fetchWithTimeout(e, t, s, n) { const { signal: r, ...o } = t || {}; r && r.addEventListener("abort", (() => n.abort())); const a = setTimeout((() => n.abort()), s), i = { signal: n.signal, ...o }; return i.method && (i.method = i.method.toUpperCase()), this.fetch.call(void 0, e, i).finally((() => { clearTimeout(a) })) } shouldRetry(e) { const t = e.headers.get("x-should-retry"); return "true" === t || "false" !== t && (408 === e.status || 409 === e.status || 429 === e.status || e.status >= 500) } async retryRequest(e, t, s) { let n; const r = s?.["retry-after-ms"]; if (r) { const e = parseFloat(r); Number.isNaN(e) || (n = e) } const o = s?.["retry-after"]; if (o && !n) { const e = parseFloat(o); n = Number.isNaN(e) ? Date.parse(o) - Date.now() : 1e3 * e } if (!(n && 0 <= n && n < 6e4)) { const s = e.maxRetries ?? this.maxRetries; n = this.calculateDefaultRetryTimeoutMillis(t, s) } return await Ae(n), this.makeRequest(e, t - 1) } calculateDefaultRetryTimeoutMillis(e, t) { const s = t - e; return Math.min(.5 * Math.pow(2, s), 8) * (1 - .25 * Math.random()) * 1e3 } getUserAgent() { return `${this.constructor.name}/JS ${m}` } } class de { constructor(e, t, s, n) { ie.set(this, void 0), function (e, t, s, n, r) { if ("m" === n) throw new TypeError("Private method is not writable"); if ("a" === n && !r) throw new TypeError("Private accessor was defined without a setter"); if ("function" == typeof t ? e !== t || !r : !t.has(e)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); "a" === n ? r.call(e, s) : r ? r.value = s : t.set(e, s) }(this, ie, e, "f"), this.options = n, this.response = t, this.body = s } hasNextPage() { return !!this.getPaginatedItems().length && null != this.nextPageInfo() } async getNextPage() { const e = this.nextPageInfo(); if (!e) throw new $("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); const t = { ...this.options }; if ("params" in e && "object" == typeof t.query) t.query = { ...t.query, ...e.params }; else if ("url" in e) { const s = [...Object.entries(t.query || {}), ...e.url.searchParams.entries()]; for (const [t, n] of s) e.url.searchParams.set(t, n); t.query = void 0, t.path = e.url.toString() } return await function (e, t, s, n) { if ("a" === s && !n) throw new TypeError("Private accessor was defined without a getter"); if ("function" == typeof t ? e !== t || !n : !t.has(e)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return "m" === s ? n : "a" === s ? n.call(e) : n ? n.value : t.get(e) }(this, ie, "f").requestAPIList(this.constructor, t) } async*iterPages() { let e = this; for (yield e; e.hasNextPage();)e = await e.getNextPage(), yield e } async*[(ie = new WeakMap, Symbol.asyncIterator)]() { for await (const e of this.iterPages()) for (const t of e.getPaginatedItems()) yield t } } class fe extends ue { constructor(e, t, s) { super(t, (async t => new s(e, t.response, await le(t), t.options))) } async*[Symbol.asyncIterator]() { const e = await (this); for await (const t of e) yield t } } const pe = e => new Proxy(Object.fromEntries(e.entries()), { get(e, t) { const s = t.toString(); return e[s.toLowerCase()] || e[s] } }), me = { method: !0, path: !0, query: !0, body: !0, headers: !0, maxRetries: !0, stream: !0, timeout: !0, httpAgent: !0, signal: !0, idempotencyKey: !0, __metadata: !0, __binaryRequest: !0, __binaryResponse: !0, __streamClass: !0 }, ge = e => "object" == typeof e && null !== e && !Ie(e) && Object.keys(e).every((e => Ce(me, e))), ye = e => "x32" === e ? "x32" : "x86_64" === e || "x64" === e ? "x64" : "arm" === e ? "arm" : "aarch64" === e || "arm64" === e ? "arm64" : e ? `other:${e}` : "unknown", we = e => (e = e.toLowerCase()).includes("ios") ? "iOS" : "android" === e ? "Android" : "darwin" === e ? "MacOS" : "win32" === e ? "Windows" : "freebsd" === e ? "FreeBSD" : "openbsd" === e ? "OpenBSD" : "linux" === e ? "Linux" : e ? `Other:${e}` : "Unknown"; let be; const _e = () => be ?? (be = (() => { if ("undefined" != typeof Deno && null != Deno.build) return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": m, "X-Stainless-OS": we(Deno.build.os), "X-Stainless-Arch": ye(Deno.build.arch), "X-Stainless-Runtime": "deno", "X-Stainless-Runtime-Version": "string" == typeof Deno.version ? Deno.version : Deno.version?.deno ?? "unknown" }; if ("undefined" != typeof EdgeRuntime) return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": m, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": `other:${EdgeRuntime}`, "X-Stainless-Runtime": "edge", "X-Stainless-Runtime-Version": process.version }; if ("[object process]" === Object.prototype.toString.call("undefined" != typeof process ? process : 0)) return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": m, "X-Stainless-OS": we(process.platform), "X-Stainless-Arch": ye(process.arch), "X-Stainless-Runtime": "node", "X-Stainless-Runtime-Version": process.version }; const e = function () { if ("undefined" == typeof navigator || !navigator) return null; const e = [{ key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }]; for (const { key: t, pattern: s } of e) { const e = s.exec(navigator.userAgent); if (e) return { browser: t, version: `${e[1] || 0}.${e[2] || 0}.${e[3] || 0}` } } return null }(); return e ? { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": m, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": "unknown", "X-Stainless-Runtime": `browser:${e.browser}`, "X-Stainless-Runtime-Version": e.version } : { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": m, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": "unknown", "X-Stainless-Runtime": "unknown", "X-Stainless-Runtime-Version": "unknown" } })()), ve = e => { try { return JSON.parse(e) } catch (e) { return } }, xe = /^[a-z][a-z0-9+.-]*:/i, Se = e => xe.test(e), Ae = e => new Promise((t => setTimeout(t, e))), Re = (e, t) => { if ("number" != typeof t || !Number.isInteger(t)) throw new $(`${e} must be an integer`); if (t < 0) throw new $(`${e} must be a positive integer`); return t }, Ee = e => { if (e instanceof Error) return e; if ("object" == typeof e && null !== e) try { return new Error(JSON.stringify(e)) } catch { } return new Error(e) }, Pe = e => "undefined" != typeof process ? process.env?.[e]?.trim() ?? void 0 : "undefined" != typeof Deno ? Deno.env?.get?.(e)?.trim() : void 0; function Ie(e) { if (!e) return !0; for (const t in e) return !1; return !0 } function Ce(e, t) { return Object.prototype.hasOwnProperty.call(e, t) } function Oe(e, t) { for (const s in t) { if (!Ce(t, s)) continue; const n = s.toLowerCase(); if (!n) continue; const r = t[s]; null === r ? delete e[n] : void 0 !== r && (e[n] = r) } } const $e = new Set(["authorization", "api-key"]); function ke(e, ...t) { if ("undefined" != typeof process && "true" === process?.env?.DEBUG) { const s = t.map((e => { if (!e) return e; if (e.headers) { const t = { ...e, headers: { ...e.headers } }; for (const s in e.headers) $e.has(s.toLowerCase()) && (t.headers[s] = "REDACTED"); return t } let t = null; for (const s in e) $e.has(s.toLowerCase()) && (t ?? (t = { ...e }), t[s] = "REDACTED"); return t ?? e })); console.log(`OpenAI:DEBUG:${e}`, ...s) } } const Te = () => "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (e => { const t = 16 * Math.random() | 0; return ("x" === e ? t : 3 & t | 8).toString(16) })), je = (e, t) => { const s = t.toLowerCase(); if ((e => "function" == typeof e?.get)(e)) { const n = t[0]?.toUpperCase() + t.substring(1).replace(/([^\w])(\w)/g, ((e, t, s) => t + s.toUpperCase())); for (const r of [t, s, t.toUpperCase(), n]) { const t = e.get(r); if (t) return t } } for (const [n, r] of Object.entries(e)) if (n.toLowerCase() === s) return Array.isArray(r) ? (r.length <= 1 || console.warn(`Received ${r.length} entries for the ${t} header, using the first entry.`), r[0]) : r }; function Me(e) { return null != e && "object" == typeof e && !Array.isArray(e) } class Ne { constructor(e) { this._client = e } } class De extends Ne { create(e, t) { return this._client.post("/completions", { body: e, ...t, stream: e.stream ?? !1 }) } } class Be extends Ne { create(e, t) { return this._client.post("/chat/completions", { body: e, ...t, stream: e.stream ?? !1 }) } } class Fe extends Ne { constructor() { super(...arguments), this.completions = new Be(this._client) } } Fe.Completions = Be; class qe extends Ne { create(e, t) { return this._client.post("/embeddings", { body: e, ...t }) } } class Le extends de { constructor(e, t, s, n) { super(e, t, s, n), this.data = s.data || [], this.object = s.object } getPaginatedItems() { return this.data ?? [] } nextPageParams() { return null } nextPageInfo() { return null } } class We extends de { constructor(e, t, s, n) { super(e, t, s, n), this.data = s.data || [] } getPaginatedItems() { return this.data ?? [] } nextPageParams() { const e = this.nextPageInfo(); if (!e) return null; if ("params" in e) return e.params; const t = Object.fromEntries(e.url.searchParams); return Object.keys(t).length ? t : null } nextPageInfo() { const e = this.getPaginatedItems(); if (!e.length) return null; const t = e[e.length - 1]?.id; return t ? { params: { after: t } } : null } } class Ue extends Ne { create(e, t) { return this._client.post("/files", re({ body: e, ...t })) } retrieve(e, t) { return this._client.get(`/files/${e}`, t) } list(e = {}, t) { return ge(e) ? this.list({}, e) : this._client.getAPIList("/files", Xe, { query: e, ...t }) } del(e, t) { return this._client.delete(`/files/${e}`, t) } content(e, t) { return this._client.get(`/files/${e}/content`, { ...t, headers: { Accept: "application/binary", ...t?.headers }, __binaryResponse: !0 }) } retrieveContent(e, t) { return this._client.get(`/files/${e}/content`, t) } async waitForProcessing(e, { pollInterval: t = 5e3, maxWait: s = 18e5 } = {}) { const n = new Set(["processed", "error", "deleted"]), r = Date.now(); let o = await this.retrieve(e); for (; !o.status || !n.has(o.status);)if (await Ae(t), o = await this.retrieve(e), Date.now() - r > s) throw new M({ message: `Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.` }); return o } } class Xe extends We { } Ue.FileObjectsPage = Xe; class Je extends Ne { createVariation(e, t) { return this._client.post("/images/variations", re({ body: e, ...t })) } edit(e, t) { return this._client.post("/images/edits", re({ body: e, ...t })) } generate(e, t) { return this._client.post("/images/generations", { body: e, ...t }) } } class He extends Ne { create(e, t) { return this._client.post("/audio/speech", { body: e, ...t, headers: { Accept: "application/octet-stream", ...t?.headers }, __binaryResponse: !0 }) } } class Ve extends Ne { create(e, t) { return this._client.post("/audio/transcriptions", re({ body: e, ...t, __metadata: { model: e.model } })) } } class Ke extends Ne { create(e, t) { return this._client.post("/audio/translations", re({ body: e, ...t, __metadata: { model: e.model } })) } } class ze extends Ne { constructor() { super(...arguments), this.transcriptions = new Ve(this._client), this.translations = new Ke(this._client), this.speech = new He(this._client) } } ze.Transcriptions = Ve, ze.Translations = Ke, ze.Speech = He; class Qe extends Ne { create(e, t) { return this._client.post("/moderations", { body: e, ...t }) } } class Ge extends Ne { retrieve(e, t) { return this._client.get(`/models/${e}`, t) } list(e) { return this._client.getAPIList("/models", Ye, e) } del(e, t) { return this._client.delete(`/models/${e}`, t) } } class Ye extends Le { } Ge.ModelsPage = Ye; class Ze extends Ne { list(e, t = {}, s) { return ge(t) ? this.list(e, {}, t) : this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`, et, { query: t, ...s }) } } class et extends We { } Ze.FineTuningJobCheckpointsPage = et; class tt extends Ne { constructor() { super(...arguments), this.checkpoints = new Ze(this._client) } create(e, t) { return this._client.post("/fine_tuning/jobs", { body: e, ...t }) } retrieve(e, t) { return this._client.get(`/fine_tuning/jobs/${e}`, t) } list(e = {}, t) { return ge(e) ? this.list({}, e) : this._client.getAPIList("/fine_tuning/jobs", st, { query: e, ...t }) } cancel(e, t) { return this._client.post(`/fine_tuning/jobs/${e}/cancel`, t) } listEvents(e, t = {}, s) { return ge(t) ? this.listEvents(e, {}, t) : this._client.getAPIList(`/fine_tuning/jobs/${e}/events`, nt, { query: t, ...s }) } } class st extends We { } class nt extends We { } tt.FineTuningJobsPage = st, tt.FineTuningJobEventsPage = nt, tt.Checkpoints = Ze, tt.FineTuningJobCheckpointsPage = et; class rt extends Ne { constructor() { super(...arguments), this.jobs = new tt(this._client) } } rt.Jobs = tt, rt.FineTuningJobsPage = st, rt.FineTuningJobEventsPage = nt; class ot extends Ne { create(e, t) { return this._client.post("/assistants", { body: e, ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } retrieve(e, t) { return this._client.get(`/assistants/${e}`, { ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } update(e, t, s) { return this._client.post(`/assistants/${e}`, { body: t, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } list(e = {}, t) { return ge(e) ? this.list({}, e) : this._client.getAPIList("/assistants", at, { query: e, ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } del(e, t) { return this._client.delete(`/assistants/${e}`, { ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } } class at extends We { } function it(e) { return "function" == typeof e.parse } ot.AssistantsPage = at; const lt = e => "assistant" === e?.role, ct = e => "function" === e?.role, ut = e => "tool" === e?.role; var ht, dt, ft, pt, mt, gt, yt, wt, bt, _t, vt, xt, St, At = function (e, t, s, n, r) { if ("m" === n) throw new TypeError("Private method is not writable"); if ("a" === n && !r) throw new TypeError("Private accessor was defined without a setter"); if ("function" == typeof t ? e !== t || !r : !t.has(e)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return "a" === n ? r.call(e, s) : r ? r.value = s : t.set(e, s), s }, Rt = function (e, t, s, n) { if ("a" === s && !n) throw new TypeError("Private accessor was defined without a getter"); if ("function" == typeof t ? e !== t || !n : !t.has(e)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return "m" === s ? n : "a" === s ? n.call(e) : n ? n.value : t.get(e) }; class Et { constructor() { ht.add(this), this.controller = new AbortController, dt.set(this, void 0), ft.set(this, (() => { })), pt.set(this, (() => { })), mt.set(this, void 0), gt.set(this, (() => { })), yt.set(this, (() => { })), wt.set(this, {}), bt.set(this, !1), _t.set(this, !1), vt.set(this, !1), xt.set(this, !1), At(this, dt, new Promise(((e, t) => { At(this, ft, e, "f"), At(this, pt, t, "f") })), "f"), At(this, mt, new Promise(((e, t) => { At(this, gt, e, "f"), At(this, yt, t, "f") })), "f"), Rt(this, dt, "f").catch((() => { })), Rt(this, mt, "f").catch((() => { })) } _run(e) { setTimeout((() => { e().then((() => { this._emitFinal(), this._emit("end") }), Rt(this, ht, "m", St).bind(this)) }), 0) } _connected() { this.ended || (Rt(this, ft, "f").call(this), this._emit("connect")) } get ended() { return Rt(this, bt, "f") } get errored() { return Rt(this, _t, "f") } get aborted() { return Rt(this, vt, "f") } abort() { this.controller.abort() } on(e, t) { return (Rt(this, wt, "f")[e] || (Rt(this, wt, "f")[e] = [])).push({ listener: t }), this } off(e, t) { const s = Rt(this, wt, "f")[e]; if (!s) return this; const n = s.findIndex((e => e.listener === t)); return n >= 0 && s.splice(n, 1), this } once(e, t) { return (Rt(this, wt, "f")[e] || (Rt(this, wt, "f")[e] = [])).push({ listener: t, once: !0 }), this } emitted(e) { return new Promise(((t, s) => { At(this, xt, !0, "f"), "error" !== e && this.once("error", s), this.once(e, t) })) } async done() { At(this, xt, !0, "f"), await Rt(this, mt, "f") } _emit(e, ...t) { if (Rt(this, bt, "f")) return; "end" === e && (At(this, bt, !0, "f"), Rt(this, gt, "f").call(this)); const s = Rt(this, wt, "f")[e]; if (s && (Rt(this, wt, "f")[e] = s.filter((e => !e.once)), s.forEach((({ listener: e }) => e(...t)))), "abort" === e) { const e = t[0]; return Rt(this, xt, "f") || s?.length || Promise.reject(e), Rt(this, pt, "f").call(this, e), Rt(this, yt, "f").call(this, e), void this._emit("end") } if ("error" === e) { const e = t[0]; Rt(this, xt, "f") || s?.length || Promise.reject(e), Rt(this, pt, "f").call(this, e), Rt(this, yt, "f").call(this, e), this._emit("end") } } _emitFinal() { } } function Pt(e) { return "auto-parseable-response-format" === e?.$brand } function It(e) { return "auto-parseable-tool" === e?.$brand } function Ct(e, t) { const s = e.choices.map((e => { if ("length" === e.finish_reason) throw new X; if ("content_filter" === e.finish_reason) throw new J; return { ...e, message: { ...e.message, tool_calls: e.message.tool_calls?.map((e => function (e, t) { const s = e.tools?.find((e => e.function?.name === t.function.name)); return { ...t, function: { ...t.function, parsed_arguments: It(s) ? s.$parseRaw(t.function.arguments) : s?.function.strict ? JSON.parse(t.function.arguments) : null } } }(t, e))) ?? [], parsed: e.message.content && !e.message.refusal ? Ot(t, e.message.content) : null } } })); return { ...e, choices: s } } function Ot(e, t) { return "json_schema" !== e.response_format?.type ? null : "json_schema" === e.response_format?.type ? "$parseRaw" in e.response_format ? e.response_format.$parseRaw(t) : JSON.parse(t) : null } function $t(e, t) { if (!e) return !1; const s = e.tools?.find((e => e.function?.name === t.function.name)); return It(s) || s?.function.strict || !1 } function kt(e) { return !!Pt(e.response_format) || (e.tools?.some((e => It(e) || "function" === e.type && !0 === e.function.strict)) ?? !1) } dt = new WeakMap, ft = new WeakMap, pt = new WeakMap, mt = new WeakMap, gt = new WeakMap, yt = new WeakMap, wt = new WeakMap, bt = new WeakMap, _t = new WeakMap, vt = new WeakMap, xt = new WeakMap, ht = new WeakSet, St = function (e) { if (At(this, _t, !0, "f"), e instanceof Error && "AbortError" === e.name && (e = new T), e instanceof T) return At(this, vt, !0, "f"), this._emit("abort", e); if (e instanceof $) return this._emit("error", e); if (e instanceof Error) { const t = new $(e.message); return t.cause = e, this._emit("error", t) } return this._emit("error", new $(String(e))) }; var Tt, jt, Mt, Nt, Dt, Bt, Ft, qt, Lt = function (e, t, s, n) { if ("a" === s && !n) throw new TypeError("Private accessor was defined without a getter"); if ("function" == typeof t ? e !== t || !n : !t.has(e)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return "m" === s ? n : "a" === s ? n.call(e) : n ? n.value : t.get(e) }; const Wt = 10; class Ut extends Et { constructor() { super(...arguments), Tt.add(this), this._chatCompletions = [], this.messages = [] } _addChatCompletion(e) { this._chatCompletions.push(e), this._emit("chatCompletion", e); const t = e.choices[0]?.message; return t && this._addMessage(t), e } _addMessage(e, t = !0) { if ("content" in e || (e.content = null), this.messages.push(e), t) if (this._emit("message", e), (ct(e) || ut(e)) && e.content) this._emit("functionCallResult", e.content); else if (lt(e) && e.function_call) this._emit("functionCall", e.function_call); else if (lt(e) && e.tool_calls) for (const t of e.tool_calls) "function" === t.type && this._emit("functionCall", t.function) } async finalChatCompletion() { await this.done(); const e = this._chatCompletions[this._chatCompletions.length - 1]; if (!e) throw new $("stream ended without producing a ChatCompletion"); return e } async finalContent() { return await this.done(), Lt(this, Tt, "m", jt).call(this) } async finalMessage() { return await this.done(), Lt(this, Tt, "m", Mt).call(this) } async finalFunctionCall() { return await this.done(), Lt(this, Tt, "m", Nt).call(this) } async finalFunctionCallResult() { return await this.done(), Lt(this, Tt, "m", Dt).call(this) } async totalUsage() { return await this.done(), Lt(this, Tt, "m", Bt).call(this) } allChatCompletions() { return [...this._chatCompletions] } _emitFinal() { const e = this._chatCompletions[this._chatCompletions.length - 1]; e && this._emit("finalChatCompletion", e); const t = Lt(this, Tt, "m", Mt).call(this); t && this._emit("finalMessage", t); const s = Lt(this, Tt, "m", jt).call(this); s && this._emit("finalContent", s); const n = Lt(this, Tt, "m", Nt).call(this); n && this._emit("finalFunctionCall", n); const r = Lt(this, Tt, "m", Dt).call(this); null != r && this._emit("finalFunctionCallResult", r), this._chatCompletions.some((e => e.usage)) && this._emit("totalUsage", Lt(this, Tt, "m", Bt).call(this)) } async _createChatCompletion(e, t, s) { const n = s?.signal; n && (n.aborted && this.controller.abort(), n.addEventListener("abort", (() => this.controller.abort()))), Lt(this, Tt, "m", Ft).call(this, t); const r = await e.chat.completions.create({ ...t, stream: !1 }, { ...s, signal: this.controller.signal }); return this._connected(), this._addChatCompletion(Ct(r, t)) } async _runChatCompletion(e, t, s) { for (const e of t.messages) this._addMessage(e, !1); return await this._createChatCompletion(e, t, s) } async _runFunctions(e, t, s) { const n = "function", { function_call: r = "auto", stream: o, ...a } = t, i = "string" != typeof r && r?.name, { maxChatCompletions: l = Wt } = s || {}, c = {}; for (const e of t.functions) c[e.name || e.function.name] = e; const u = t.functions.map((e => ({ name: e.name || e.function.name, parameters: e.parameters, description: e.description }))); for (const e of t.messages) this._addMessage(e, !1); for (let t = 0; t < l; ++t) { const t = await this._createChatCompletion(e, { ...a, function_call: r, functions: u, messages: [...this.messages] }, s), o = t.choices[0]?.message; if (!o) throw new $("missing message in ChatCompletion response"); if (!o.function_call) return; const { name: l, arguments: h } = o.function_call, d = c[l]; if (!d) { const e = `Invalid function_call: ${JSON.stringify(l)}. Available options are: ${u.map((e => JSON.stringify(e.name))).join(", ")}. Please try again`; this._addMessage({ role: n, name: l, content: e }); continue } if (i && i !== l) { const e = `Invalid function_call: ${JSON.stringify(l)}. ${JSON.stringify(i)} requested. Please try again`; this._addMessage({ role: n, name: l, content: e }); continue } let f; try { f = it(d) ? await d.parse(h) : h } catch (e) { this._addMessage({ role: n, name: l, content: e instanceof Error ? e.message : String(e) }); continue } const p = await d.function(f, this), m = Lt(this, Tt, "m", qt).call(this, p); if (this._addMessage({ role: n, name: l, content: m }), i) return } } async _runTools(e, t, s) { const n = "tool", { tool_choice: r = "auto", stream: o, ...a } = t, i = "string" != typeof r && r?.function?.name, { maxChatCompletions: l = Wt } = s || {}, c = t.tools.map((e => { if (It(e)) { if (!e.$callback) throw new $("Tool given to `.runTools()` that does not have an associated function"); return { type: "function", function: { function: e.$callback, name: e.function.name, description: e.function.description || "", parameters: e.function.parameters, parse: e.$parseRaw, strict: !0 } } } return e })), u = {}; for (const e of c) "function" === e.type && (u[e.function.name || e.function.function.name] = e.function); const h = "tools" in t ? c.map((e => "function" === e.type ? { type: "function", function: { name: e.function.name || e.function.function.name, parameters: e.function.parameters, description: e.function.description, strict: e.function.strict } } : e)) : void 0; for (const e of t.messages) this._addMessage(e, !1); for (let t = 0; t < l; ++t) { const t = await this._createChatCompletion(e, { ...a, tool_choice: r, tools: h, messages: [...this.messages] }, s), o = t.choices[0]?.message; if (!o) throw new $("missing message in ChatCompletion response"); if (!o.tool_calls?.length) return; for (const e of o.tool_calls) { if ("function" !== e.type) continue; const t = e.id, { name: s, arguments: r } = e.function, o = u[s]; if (!o) { const e = `Invalid tool_call: ${JSON.stringify(s)}. Available options are: ${Object.keys(u).map((e => JSON.stringify(e))).join(", ")}. Please try again`; this._addMessage({ role: n, tool_call_id: t, content: e }); continue } if (i && i !== s) { const e = `Invalid tool_call: ${JSON.stringify(s)}. ${JSON.stringify(i)} requested. Please try again`; this._addMessage({ role: n, tool_call_id: t, content: e }); continue } let a; try { a = it(o) ? await o.parse(r) : r } catch (e) { const s = e instanceof Error ? e.message : String(e); this._addMessage({ role: n, tool_call_id: t, content: s }); continue } const l = await o.function(a, this), c = Lt(this, Tt, "m", qt).call(this, l); if (this._addMessage({ role: n, tool_call_id: t, content: c }), i) return } } } } Tt = new WeakSet, jt = function () { return Lt(this, Tt, "m", Mt).call(this).content ?? null }, Mt = function () { let e = this.messages.length; for (; e-- > 0;) { const t = this.messages[e]; if (lt(t)) { const { function_call: e, ...s } = t, n = { ...s, content: t.content ?? null, refusal: t.refusal ?? null }; return e && (n.function_call = e), n } } throw new $("stream ended without producing a ChatCompletionMessage with role=assistant") }, Nt = function () { for (let e = this.messages.length - 1; e >= 0; e--) { const t = this.messages[e]; if (lt(t) && t?.function_call) return t.function_call; if (lt(t) && t?.tool_calls?.length) return t.tool_calls.at(-1)?.function } }, Dt = function () { for (let e = this.messages.length - 1; e >= 0; e--) { const t = this.messages[e]; if (ct(t) && null != t.content) return t.content; if (ut(t) && null != t.content && "string" == typeof t.content && this.messages.some((e => "assistant" === e.role && e.tool_calls?.some((e => "function" === e.type && e.id === t.tool_call_id))))) return t.content } }, Bt = function () { const e = { completion_tokens: 0, prompt_tokens: 0, total_tokens: 0 }; for (const { usage: t } of this._chatCompletions) t && (e.completion_tokens += t.completion_tokens, e.prompt_tokens += t.prompt_tokens, e.total_tokens += t.total_tokens); return e }, Ft = function (e) { if (null != e.n && e.n > 1) throw new $("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.") }, qt = function (e) { return "string" == typeof e ? e : void 0 === e ? "undefined" : JSON.stringify(e) }; class Xt extends Ut { static runFunctions(e, t, s) { const n = new Xt, r = { ...s, headers: { ...s?.headers, "X-Stainless-Helper-Method": "runFunctions" } }; return n._run((() => n._runFunctions(e, t, r))), n } static runTools(e, t, s) { const n = new Xt, r = { ...s, headers: { ...s?.headers, "X-Stainless-Helper-Method": "runTools" } }; return n._run((() => n._runTools(e, t, r))), n } _addMessage(e, t = !0) { super._addMessage(e, t), lt(e) && e.content && this._emit("content", e.content) } } class Jt extends Error { } class Ht extends Error { } const Vt = e => function (e, t = 511) { if ("string" != typeof e) throw new TypeError("expecting str, got " + typeof e); if (!e.trim()) throw new Error(`${e} is empty`); return ((e, t) => { const s = e.length; let n = 0; const r = e => { throw new Jt(`${e} at position ${n}`) }, o = e => { throw new Ht(`${e} at position ${n}`) }, a = () => (h(), n >= s && r("Unexpected end of input"), '"' === e[n] ? i() : "{" === e[n] ? l() : "[" === e[n] ? c() : "null" === e.substring(n, n + 4) || 16 & t && s - n < 4 && "null".startsWith(e.substring(n)) ? (n += 4, null) : "true" === e.substring(n, n + 4) || 32 & t && s - n < 4 && "true".startsWith(e.substring(n)) ? (n += 4, !0) : "false" === e.substring(n, n + 5) || 32 & t && s - n < 5 && "false".startsWith(e.substring(n)) ? (n += 5, !1) : "Infinity" === e.substring(n, n + 8) || 128 & t && s - n < 8 && "Infinity".startsWith(e.substring(n)) ? (n += 8, 1 / 0) : "-Infinity" === e.substring(n, n + 9) || 256 & t && 1 < s - n && s - n < 9 && "-Infinity".startsWith(e.substring(n)) ? (n += 9, -1 / 0) : "NaN" === e.substring(n, n + 3) || 64 & t && s - n < 3 && "NaN".startsWith(e.substring(n)) ? (n += 3, NaN) : u()), i = () => { const a = n; let i = !1; for (n++; n < s && ('"' !== e[n] || i && "\\" === e[n - 1]);)i = "\\" === e[n] && !i, n++; if ('"' == e.charAt(n)) try { return JSON.parse(e.substring(a, ++n - Number(i))) } catch (e) { o(String(e)) } else if (1 & t) try { return JSON.parse(e.substring(a, n - Number(i)) + '"') } catch (t) { return JSON.parse(e.substring(a, e.lastIndexOf("\\")) + '"') } r("Unterminated string literal") }, l = () => { n++, h(); const o = {}; try { for (; "}" !== e[n];) { if (h(), n >= s && 8 & t) return o; const r = i(); h(), n++; try { const e = a(); Object.defineProperty(o, r, { value: e, writable: !0, enumerable: !0, configurable: !0 }) } catch (e) { if (8 & t) return o; throw e } h(), "," === e[n] && n++ } } catch (e) { if (8 & t) return o; r("Expected '}' at end of object") } return n++, o }, c = () => { n++; const s = []; try { for (; "]" !== e[n];)s.push(a()), h(), "," === e[n] && n++ } catch (e) { if (4 & t) return s; r("Expected ']' at end of array") } return n++, s }, u = () => { if (0 === n) { "-" === e && 2 & t && r("Not sure what '-' is"); try { return JSON.parse(e) } catch (s) { if (2 & t) try { return "." === e[e.length - 1] ? JSON.parse(e.substring(0, e.lastIndexOf("."))) : JSON.parse(e.substring(0, e.lastIndexOf("e"))) } catch (e) { } o(String(s)) } } const a = n; for ("-" === e[n] && n++; e[n] && !",]}".includes(e[n]);)n++; n != s || 2 & t || r("Unterminated number literal"); try { return JSON.parse(e.substring(a, n)) } catch (s) { "-" === e.substring(a, n) && 2 & t && r("Not sure what '-' is"); try { return JSON.parse(e.substring(a, e.lastIndexOf("e"))) } catch (e) { o(String(e)) } } }, h = () => { for (; n < s && " \n\r\t".includes(e[n]);)n++ }; return a() })(e.trim(), t) }(e, 509); var Kt, zt, Qt, Gt, Yt, Zt, es, ts, ss, ns, rs, os, as = function (e, t, s, n, r) { if ("m" === n) throw new TypeError("Private method is not writable"); if ("a" === n && !r) throw new TypeError("Private accessor was defined without a setter"); if ("function" == typeof t ? e !== t || !r : !t.has(e)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return "a" === n ? r.call(e, s) : r ? r.value = s : t.set(e, s), s }, is = function (e, t, s, n) { if ("a" === s && !n) throw new TypeError("Private accessor was defined without a getter"); if ("function" == typeof t ? e !== t || !n : !t.has(e)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return "m" === s ? n : "a" === s ? n.call(e) : n ? n.value : t.get(e) }; class ls extends Ut { constructor(e) { super(), Kt.add(this), zt.set(this, void 0), Qt.set(this, void 0), Gt.set(this, void 0), as(this, zt, e, "f"), as(this, Qt, [], "f") } get currentChatCompletionSnapshot() { return is(this, Gt, "f") } static fromReadableStream(e) { const t = new ls(null); return t._run((() => t._fromReadableStream(e))), t } static createChatCompletion(e, t, s) { const n = new ls(t); return n._run((() => n._runChatCompletion(e, { ...t, stream: !0 }, { ...s, headers: { ...s?.headers, "X-Stainless-Helper-Method": "stream" } }))), n } async _createChatCompletion(e, t, s) { super._createChatCompletion; const n = s?.signal; n && (n.aborted && this.controller.abort(), n.addEventListener("abort", (() => this.controller.abort()))), is(this, Kt, "m", Yt).call(this); const r = await e.chat.completions.create({ ...t, stream: !0 }, { ...s, signal: this.controller.signal }); this._connected(); for await (const e of r) is(this, Kt, "m", es).call(this, e); if (r.controller.signal?.aborted) throw new T; return this._addChatCompletion(is(this, Kt, "m", ns).call(this)) } async _fromReadableStream(e, t) { const s = t?.signal; s && (s.aborted && this.controller.abort(), s.addEventListener("abort", (() => this.controller.abort()))), is(this, Kt, "m", Yt).call(this), this._connected(); const n = K.fromReadableStream(e, this.controller); let r; for await (const e of n) r && r !== e.id && this._addChatCompletion(is(this, Kt, "m", ns).call(this)), is(this, Kt, "m", es).call(this, e), r = e.id; if (n.controller.signal?.aborted) throw new T; return this._addChatCompletion(is(this, Kt, "m", ns).call(this)) } [(zt = new WeakMap, Qt = new WeakMap, Gt = new WeakMap, Kt = new WeakSet, Yt = function () { this.ended || as(this, Gt, void 0, "f") }, Zt = function (e) { let t = is(this, Qt, "f")[e.index]; return t || (t = { content_done: !1, refusal_done: !1, logprobs_content_done: !1, logprobs_refusal_done: !1, done_tool_calls: new Set, current_tool_call_index: null }, is(this, Qt, "f")[e.index] = t, t) }, es = function (e) { if (this.ended) return; const t = is(this, Kt, "m", os).call(this, e); this._emit("chunk", e, t); for (const s of e.choices) { const e = t.choices[s.index]; null != s.delta.content && "assistant" === e.message?.role && e.message?.content && (this._emit("content", s.delta.content, e.message.content), this._emit("content.delta", { delta: s.delta.content, snapshot: e.message.content, parsed: e.message.parsed })), null != s.delta.refusal && "assistant" === e.message?.role && e.message?.refusal && this._emit("refusal.delta", { delta: s.delta.refusal, snapshot: e.message.refusal }), null != s.logprobs?.content && "assistant" === e.message?.role && this._emit("logprobs.content.delta", { content: s.logprobs?.content, snapshot: e.logprobs?.content ?? [] }), null != s.logprobs?.refusal && "assistant" === e.message?.role && this._emit("logprobs.refusal.delta", { refusal: s.logprobs?.refusal, snapshot: e.logprobs?.refusal ?? [] }); const n = is(this, Kt, "m", Zt).call(this, e); e.finish_reason && (is(this, Kt, "m", ss).call(this, e), null != n.current_tool_call_index && is(this, Kt, "m", ts).call(this, e, n.current_tool_call_index)); for (const t of s.delta.tool_calls ?? []) n.current_tool_call_index !== t.index && (is(this, Kt, "m", ss).call(this, e), null != n.current_tool_call_index && is(this, Kt, "m", ts).call(this, e, n.current_tool_call_index)), n.current_tool_call_index = t.index; for (const t of s.delta.tool_calls ?? []) { const s = e.message.tool_calls?.[t.index]; s?.type && "function" === s?.type && this._emit("tool_calls.function.arguments.delta", { name: s.function?.name, index: t.index, arguments: s.function.arguments, parsed_arguments: s.function.parsed_arguments, arguments_delta: t.function?.arguments ?? "" }) } } }, ts = function (e, t) { if (is(this, Kt, "m", Zt).call(this, e).done_tool_calls.has(t)) return; const s = e.message.tool_calls?.[t]; if (!s) throw new Error("no tool call snapshot"); if (!s.type) throw new Error("tool call snapshot missing `type`"); if ("function" === s.type) { const e = is(this, zt, "f")?.tools?.find((e => "function" === e.type && e.function.name === s.function.name)); this._emit("tool_calls.function.arguments.done", { name: s.function.name, index: t, arguments: s.function.arguments, parsed_arguments: It(e) ? e.$parseRaw(s.function.arguments) : e?.function.strict ? JSON.parse(s.function.arguments) : null }) } else s.type }, ss = function (e) { const t = is(this, Kt, "m", Zt).call(this, e); if (e.message.content && !t.content_done) { t.content_done = !0; const s = is(this, Kt, "m", rs).call(this); this._emit("content.done", { content: e.message.content, parsed: s ? s.$parseRaw(e.message.content) : null }) } e.message.refusal && !t.refusal_done && (t.refusal_done = !0, this._emit("refusal.done", { refusal: e.message.refusal })), e.logprobs?.content && !t.logprobs_content_done && (t.logprobs_content_done = !0, this._emit("logprobs.content.done", { content: e.logprobs.content })), e.logprobs?.refusal && !t.logprobs_refusal_done && (t.logprobs_refusal_done = !0, this._emit("logprobs.refusal.done", { refusal: e.logprobs.refusal })) }, ns = function () { if (this.ended) throw new $("stream has ended, this shouldn't happen"); const e = is(this, Gt, "f"); if (!e) throw new $("request ended without sending any chunks"); return as(this, Gt, void 0, "f"), as(this, Qt, [], "f"), function (e, t) { const { id: s, choices: n, created: r, model: o, system_fingerprint: a, ...i } = e, l = { ...i, id: s, choices: n.map((({ message: t, finish_reason: s, index: n, logprobs: r, ...o }) => { if (!s) throw new $(`missing finish_reason for choice ${n}`); const { content: a = null, function_call: i, tool_calls: l, ...c } = t, u = t.role; if (!u) throw new $(`missing role for choice ${n}`); if (i) { const { arguments: e, name: l } = i; if (null == e) throw new $(`missing function_call.arguments for choice ${n}`); if (!l) throw new $(`missing function_call.name for choice ${n}`); return { ...o, message: { content: a, function_call: { arguments: e, name: l }, role: u, refusal: t.refusal ?? null }, finish_reason: s, index: n, logprobs: r } } return l ? { ...o, index: n, finish_reason: s, logprobs: r, message: { ...c, role: u, content: a, refusal: t.refusal ?? null, tool_calls: l.map(((t, s) => { const { function: r, type: o, id: a, ...i } = t, { arguments: l, name: c, ...u } = r || {}; if (null == a) throw new $(`missing choices[${n}].tool_calls[${s}].id\n${cs(e)}`); if (null == o) throw new $(`missing choices[${n}].tool_calls[${s}].type\n${cs(e)}`); if (null == c) throw new $(`missing choices[${n}].tool_calls[${s}].function.name\n${cs(e)}`); if (null == l) throw new $(`missing choices[${n}].tool_calls[${s}].function.arguments\n${cs(e)}`); return { ...i, id: a, type: o, function: { ...u, name: c, arguments: l } } })) } } : { ...o, message: { ...c, content: a, role: u, refusal: t.refusal ?? null }, finish_reason: s, index: n, logprobs: r } })), created: r, model: o, object: "chat.completion", ...a ? { system_fingerprint: a } : {} }; return function (e, t) { return t && kt(t) ? Ct(e, t) : { ...e, choices: e.choices.map((e => ({ ...e, message: { ...e.message, parsed: null, tool_calls: e.message.tool_calls ?? [] } }))) } }(l, t) }(e, is(this, zt, "f")) }, rs = function () { const e = is(this, zt, "f")?.response_format; return Pt(e) ? e : null }, os = function (e) { var t, s, n, r; let o = is(this, Gt, "f"); const { choices: a, ...i } = e; o ? Object.assign(o, i) : o = as(this, Gt, { ...i, choices: [] }, "f"); for (const { delta: a, finish_reason: i, index: l, logprobs: c = null, ...u } of e.choices) { let e = o.choices[l]; if (e || (e = o.choices[l] = { finish_reason: i, index: l, message: {}, logprobs: c, ...u }), c) if (e.logprobs) { const { content: n, refusal: r, ...o } = c; Object.assign(e.logprobs, o), n && ((t = e.logprobs).content ?? (t.content = []), e.logprobs.content.push(...n)), r && ((s = e.logprobs).refusal ?? (s.refusal = []), e.logprobs.refusal.push(...r)) } else e.logprobs = Object.assign({}, c); if (i && (e.finish_reason = i, is(this, zt, "f") && kt(is(this, zt, "f")))) { if ("length" === i) throw new X; if ("content_filter" === i) throw new J } if (Object.assign(e, u), !a) continue; const { content: h, refusal: d, function_call: f, role: p, tool_calls: m, ...g } = a; if (Object.assign(e.message, g), d && (e.message.refusal = (e.message.refusal || "") + d), p && (e.message.role = p), f && (e.message.function_call ? (f.name && (e.message.function_call.name = f.name), f.arguments && ((n = e.message.function_call).arguments ?? (n.arguments = ""), e.message.function_call.arguments += f.arguments)) : e.message.function_call = f), h && (e.message.content = (e.message.content || "") + h, !e.message.refusal && is(this, Kt, "m", rs).call(this) && (e.message.parsed = Vt(e.message.content))), m) { e.message.tool_calls || (e.message.tool_calls = []); for (const { index: t, id: s, type: n, function: o, ...a } of m) { const i = (r = e.message.tool_calls)[t] ?? (r[t] = {}); Object.assign(i, a), s && (i.id = s), n && (i.type = n), o && (i.function ?? (i.function = { name: o.name ?? "", arguments: "" })), o?.name && (i.function.name = o.name), o?.arguments && (i.function.arguments += o.arguments, $t(is(this, zt, "f"), i) && (i.function.parsed_arguments = Vt(i.function.arguments))) } } } return o }, Symbol.asyncIterator)]() { const e = [], t = []; let s = !1; return this.on("chunk", (s => { const n = t.shift(); n ? n.resolve(s) : e.push(s) })), this.on("end", (() => { s = !0; for (const e of t) e.resolve(void 0); t.length = 0 })), this.on("abort", (e => { s = !0; for (const s of t) s.reject(e); t.length = 0 })), this.on("error", (e => { s = !0; for (const s of t) s.reject(e); t.length = 0 })), { next: async () => e.length ? { value: e.shift(), done: !1 } : s ? { value: void 0, done: !0 } : new Promise(((e, s) => t.push({ resolve: e, reject: s }))).then((e => e ? { value: e, done: !1 } : { value: void 0, done: !0 })), return: async () => (this.abort(), { value: void 0, done: !0 }) } } toReadableStream() { return new K(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream() } } function cs(e) { return JSON.stringify(e) } class us extends ls { static fromReadableStream(e) { const t = new us(null); return t._run((() => t._fromReadableStream(e))), t } static runFunctions(e, t, s) { const n = new us(null), r = { ...s, headers: { ...s?.headers, "X-Stainless-Helper-Method": "runFunctions" } }; return n._run((() => n._runFunctions(e, t, r))), n } static runTools(e, t, s) { const n = new us(t), r = { ...s, headers: { ...s?.headers, "X-Stainless-Helper-Method": "runTools" } }; return n._run((() => n._runTools(e, t, r))), n } } class hs extends Ne { parse(e, t) { return function (e) { for (const t of e ?? []) { if ("function" !== t.type) throw new $(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``); if (!0 !== t.function.strict) throw new $(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`) } }(e.tools), this._client.chat.completions.create(e, { ...t, headers: { ...t?.headers, "X-Stainless-Helper-Method": "beta.chat.completions.parse" } })._thenUnwrap((t => Ct(t, e))) } runFunctions(e, t) { return e.stream ? us.runFunctions(this._client, e, t) : Xt.runFunctions(this._client, e, t) } runTools(e, t) { return e.stream ? us.runTools(this._client, e, t) : Xt.runTools(this._client, e, t) } stream(e, t) { return ls.createChatCompletion(this._client, e, t) } } class ds extends Ne { constructor() { super(...arguments), this.completions = new hs(this._client) } } !function (e) { e.Completions = hs }(ds || (ds = {})); class fs extends Ne { create(e, t) { return this._client.post("/realtime/sessions", { body: e, ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } } class ps extends Ne { constructor() { super(...arguments), this.sessions = new fs(this._client) } } ps.Sessions = fs; var ms, gs, ys, ws, bs, _s, vs, xs, Ss, As, Rs, Es, Ps, Is, Cs, Os, $s, ks, Ts, js, Ms, Ns, Ds, Bs = function (e, t, s, n) { if ("a" === s && !n) throw new TypeError("Private accessor was defined without a getter"); if ("function" == typeof t ? e !== t || !n : !t.has(e)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return "m" === s ? n : "a" === s ? n.call(e) : n ? n.value : t.get(e) }, Fs = function (e, t, s, n, r) { if ("m" === n) throw new TypeError("Private method is not writable"); if ("a" === n && !r) throw new TypeError("Private accessor was defined without a setter"); if ("function" == typeof t ? e !== t || !r : !t.has(e)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return "a" === n ? r.call(e, s) : r ? r.value = s : t.set(e, s), s }; class qs extends Et { constructor() { super(...arguments), ms.add(this), gs.set(this, []), ys.set(this, {}), ws.set(this, {}), bs.set(this, void 0), _s.set(this, void 0), vs.set(this, void 0), xs.set(this, void 0), Ss.set(this, void 0), As.set(this, void 0), Rs.set(this, void 0), Es.set(this, void 0), Ps.set(this, void 0) } [(gs = new WeakMap, ys = new WeakMap, ws = new WeakMap, bs = new WeakMap, _s = new WeakMap, vs = new WeakMap, xs = new WeakMap, Ss = new WeakMap, As = new WeakMap, Rs = new WeakMap, Es = new WeakMap, Ps = new WeakMap, ms = new WeakSet, Symbol.asyncIterator)]() { const e = [], t = []; let s = !1; return this.on("event", (s => { const n = t.shift(); n ? n.resolve(s) : e.push(s) })), this.on("end", (() => { s = !0; for (const e of t) e.resolve(void 0); t.length = 0 })), this.on("abort", (e => { s = !0; for (const s of t) s.reject(e); t.length = 0 })), this.on("error", (e => { s = !0; for (const s of t) s.reject(e); t.length = 0 })), { next: async () => e.length ? { value: e.shift(), done: !1 } : s ? { value: void 0, done: !0 } : new Promise(((e, s) => t.push({ resolve: e, reject: s }))).then((e => e ? { value: e, done: !1 } : { value: void 0, done: !0 })), return: async () => (this.abort(), { value: void 0, done: !0 }) } } static fromReadableStream(e) { const t = new qs; return t._run((() => t._fromReadableStream(e))), t } async _fromReadableStream(e, t) { const s = t?.signal; s && (s.aborted && this.controller.abort(), s.addEventListener("abort", (() => this.controller.abort()))), this._connected(); const n = K.fromReadableStream(e, this.controller); for await (const e of n) Bs(this, ms, "m", Is).call(this, e); if (n.controller.signal?.aborted) throw new T; return this._addRun(Bs(this, ms, "m", Cs).call(this)) } toReadableStream() { return new K(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream() } static createToolAssistantStream(e, t, s, n, r) { const o = new qs; return o._run((() => o._runToolAssistantStream(e, t, s, n, { ...r, headers: { ...r?.headers, "X-Stainless-Helper-Method": "stream" } }))), o } async _createToolAssistantStream(e, t, s, n, r) { const o = r?.signal; o && (o.aborted && this.controller.abort(), o.addEventListener("abort", (() => this.controller.abort()))); const a = { ...n, stream: !0 }, i = await e.submitToolOutputs(t, s, a, { ...r, signal: this.controller.signal }); this._connected(); for await (const e of i) Bs(this, ms, "m", Is).call(this, e); if (i.controller.signal?.aborted) throw new T; return this._addRun(Bs(this, ms, "m", Cs).call(this)) } static createThreadAssistantStream(e, t, s) { const n = new qs; return n._run((() => n._threadAssistantStream(e, t, { ...s, headers: { ...s?.headers, "X-Stainless-Helper-Method": "stream" } }))), n } static createAssistantStream(e, t, s, n) { const r = new qs; return r._run((() => r._runAssistantStream(e, t, s, { ...n, headers: { ...n?.headers, "X-Stainless-Helper-Method": "stream" } }))), r } currentEvent() { return Bs(this, Rs, "f") } currentRun() { return Bs(this, Es, "f") } currentMessageSnapshot() { return Bs(this, bs, "f") } currentRunStepSnapshot() { return Bs(this, Ps, "f") } async finalRunSteps() { return await this.done(), Object.values(Bs(this, ys, "f")) } async finalMessages() { return await this.done(), Object.values(Bs(this, ws, "f")) } async finalRun() { if (await this.done(), !Bs(this, _s, "f")) throw Error("Final run was not received."); return Bs(this, _s, "f") } async _createThreadAssistantStream(e, t, s) { const n = s?.signal; n && (n.aborted && this.controller.abort(), n.addEventListener("abort", (() => this.controller.abort()))); const r = { ...t, stream: !0 }, o = await e.createAndRun(r, { ...s, signal: this.controller.signal }); this._connected(); for await (const e of o) Bs(this, ms, "m", Is).call(this, e); if (o.controller.signal?.aborted) throw new T; return this._addRun(Bs(this, ms, "m", Cs).call(this)) } async _createAssistantStream(e, t, s, n) { const r = n?.signal; r && (r.aborted && this.controller.abort(), r.addEventListener("abort", (() => this.controller.abort()))); const o = { ...s, stream: !0 }, a = await e.create(t, o, { ...n, signal: this.controller.signal }); this._connected(); for await (const e of a) Bs(this, ms, "m", Is).call(this, e); if (a.controller.signal?.aborted) throw new T; return this._addRun(Bs(this, ms, "m", Cs).call(this)) } static accumulateDelta(e, t) { for (const [s, n] of Object.entries(t)) { if (!e.hasOwnProperty(s)) { e[s] = n; continue } let t = e[s]; if (null != t) if ("index" !== s && "type" !== s) { if ("string" == typeof t && "string" == typeof n) t += n; else if ("number" == typeof t && "number" == typeof n) t += n; else { if (!Me(t) || !Me(n)) { if (Array.isArray(t) && Array.isArray(n)) { if (t.every((e => "string" == typeof e || "number" == typeof e))) { t.push(...n); continue } for (const e of n) { if (!Me(e)) throw new Error(`Expected array delta entry to be an object but got: ${e}`); const s = e.index; if (null == s) throw console.error(e), new Error("Expected array delta entry to have an `index` property"); if ("number" != typeof s) throw new Error(`Expected array delta entry \`index\` property to be a number but got ${s}`); const n = t[s]; null == n ? t.push(e) : t[s] = this.accumulateDelta(n, e) } continue } throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${t}`) } t = this.accumulateDelta(t, n) } e[s] = t } else e[s] = n; else e[s] = n } return e } _addRun(e) { return e } async _threadAssistantStream(e, t, s) { return await this._createThreadAssistantStream(t, e, s) } async _runAssistantStream(e, t, s, n) { return await this._createAssistantStream(t, e, s, n) } async _runToolAssistantStream(e, t, s, n, r) { return await this._createToolAssistantStream(s, e, t, n, r) } } Is = function (e) { if (!this.ended) switch (Fs(this, Rs, e, "f"), Bs(this, ms, "m", ks).call(this, e), e.event) { case "thread.created": break; case "thread.run.created": case "thread.run.queued": case "thread.run.in_progress": case "thread.run.requires_action": case "thread.run.completed": case "thread.run.failed": case "thread.run.cancelling": case "thread.run.cancelled": case "thread.run.expired": Bs(this, ms, "m", Ns).call(this, e); break; case "thread.run.step.created": case "thread.run.step.in_progress": case "thread.run.step.delta": case "thread.run.step.completed": case "thread.run.step.failed": case "thread.run.step.cancelled": case "thread.run.step.expired": Bs(this, ms, "m", $s).call(this, e); break; case "thread.message.created": case "thread.message.in_progress": case "thread.message.delta": case "thread.message.completed": case "thread.message.incomplete": Bs(this, ms, "m", Os).call(this, e); break; case "error": throw new Error("Encountered an error event in event processing - errors should be processed earlier") } }, Cs = function () { if (this.ended) throw new $("stream has ended, this shouldn't happen"); if (!Bs(this, _s, "f")) throw Error("Final run has not been received"); return Bs(this, _s, "f") }, Os = function (e) { const [t, s] = Bs(this, ms, "m", js).call(this, e, Bs(this, bs, "f")); Fs(this, bs, t, "f"), Bs(this, ws, "f")[t.id] = t; for (const e of s) { const s = t.content[e.index]; "text" == s?.type && this._emit("textCreated", s.text) } switch (e.event) { case "thread.message.created": this._emit("messageCreated", e.data); break; case "thread.message.in_progress": break; case "thread.message.delta": if (this._emit("messageDelta", e.data.delta, t), e.data.delta.content) for (const s of e.data.delta.content) { if ("text" == s.type && s.text) { let e = s.text, n = t.content[s.index]; if (!n || "text" != n.type) throw Error("The snapshot associated with this text delta is not text or missing"); this._emit("textDelta", e, n.text) } if (s.index != Bs(this, vs, "f")) { if (Bs(this, xs, "f")) switch (Bs(this, xs, "f").type) { case "text": this._emit("textDone", Bs(this, xs, "f").text, Bs(this, bs, "f")); break; case "image_file": this._emit("imageFileDone", Bs(this, xs, "f").image_file, Bs(this, bs, "f")) }Fs(this, vs, s.index, "f") } Fs(this, xs, t.content[s.index], "f") } break; case "thread.message.completed": case "thread.message.incomplete": if (void 0 !== Bs(this, vs, "f")) { const t = e.data.content[Bs(this, vs, "f")]; if (t) switch (t.type) { case "image_file": this._emit("imageFileDone", t.image_file, Bs(this, bs, "f")); break; case "text": this._emit("textDone", t.text, Bs(this, bs, "f")) } } Bs(this, bs, "f") && this._emit("messageDone", e.data), Fs(this, bs, void 0, "f") } }, $s = function (e) { const t = Bs(this, ms, "m", Ts).call(this, e); switch (Fs(this, Ps, t, "f"), e.event) { case "thread.run.step.created": this._emit("runStepCreated", e.data); break; case "thread.run.step.delta": const s = e.data.delta; if (s.step_details && "tool_calls" == s.step_details.type && s.step_details.tool_calls && "tool_calls" == t.step_details.type) for (const e of s.step_details.tool_calls) e.index == Bs(this, Ss, "f") ? this._emit("toolCallDelta", e, t.step_details.tool_calls[e.index]) : (Bs(this, As, "f") && this._emit("toolCallDone", Bs(this, As, "f")), Fs(this, Ss, e.index, "f"), Fs(this, As, t.step_details.tool_calls[e.index], "f"), Bs(this, As, "f") && this._emit("toolCallCreated", Bs(this, As, "f"))); this._emit("runStepDelta", e.data.delta, t); break; case "thread.run.step.completed": case "thread.run.step.failed": case "thread.run.step.cancelled": case "thread.run.step.expired": Fs(this, Ps, void 0, "f"), "tool_calls" == e.data.step_details.type && Bs(this, As, "f") && (this._emit("toolCallDone", Bs(this, As, "f")), Fs(this, As, void 0, "f")), this._emit("runStepDone", e.data, t) } }, ks = function (e) { Bs(this, gs, "f").push(e), this._emit("event", e) }, Ts = function (e) { switch (e.event) { case "thread.run.step.created": return Bs(this, ys, "f")[e.data.id] = e.data, e.data; case "thread.run.step.delta": let t = Bs(this, ys, "f")[e.data.id]; if (!t) throw Error("Received a RunStepDelta before creation of a snapshot"); let s = e.data; if (s.delta) { const n = qs.accumulateDelta(t, s.delta); Bs(this, ys, "f")[e.data.id] = n } return Bs(this, ys, "f")[e.data.id]; case "thread.run.step.completed": case "thread.run.step.failed": case "thread.run.step.cancelled": case "thread.run.step.expired": case "thread.run.step.in_progress": Bs(this, ys, "f")[e.data.id] = e.data }if (Bs(this, ys, "f")[e.data.id]) return Bs(this, ys, "f")[e.data.id]; throw new Error("No snapshot available") }, js = function (e, t) { let s = []; switch (e.event) { case "thread.message.created": return [e.data, s]; case "thread.message.delta": if (!t) throw Error("Received a delta with no existing snapshot (there should be one from message creation)"); let n = e.data; if (n.delta.content) for (const e of n.delta.content) if (e.index in t.content) { let s = t.content[e.index]; t.content[e.index] = Bs(this, ms, "m", Ms).call(this, e, s) } else t.content[e.index] = e, s.push(e); return [t, s]; case "thread.message.in_progress": case "thread.message.completed": case "thread.message.incomplete": if (t) return [t, s]; throw Error("Received thread message event with no existing snapshot") }throw Error("Tried to accumulate a non-message event") }, Ms = function (e, t) { return qs.accumulateDelta(t, e) }, Ns = function (e) { switch (Fs(this, Es, e.data, "f"), e.event) { case "thread.run.created": case "thread.run.queued": case "thread.run.in_progress": case "thread.run.cancelling": break; case "thread.run.requires_action": case "thread.run.cancelled": case "thread.run.failed": case "thread.run.completed": case "thread.run.expired": Fs(this, _s, e.data, "f"), Bs(this, As, "f") && (this._emit("toolCallDone", Bs(this, As, "f")), Fs(this, As, void 0, "f")) } }; class Ls extends Ne { create(e, t, s) { return this._client.post(`/threads/${e}/messages`, { body: t, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } retrieve(e, t, s) { return this._client.get(`/threads/${e}/messages/${t}`, { ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } update(e, t, s, n) { return this._client.post(`/threads/${e}/messages/${t}`, { body: s, ...n, headers: { "OpenAI-Beta": "assistants=v2", ...n?.headers } }) } list(e, t = {}, s) { return ge(t) ? this.list(e, {}, t) : this._client.getAPIList(`/threads/${e}/messages`, Ws, { query: t, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } del(e, t, s) { return this._client.delete(`/threads/${e}/messages/${t}`, { ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } } class Ws extends We { } Ls.MessagesPage = Ws; class Us extends Ne { retrieve(e, t, s, n = {}, r) { return ge(n) ? this.retrieve(e, t, s, {}, n) : this._client.get(`/threads/${e}/runs/${t}/steps/${s}`, { query: n, ...r, headers: { "OpenAI-Beta": "assistants=v2", ...r?.headers } }) } list(e, t, s = {}, n) { return ge(s) ? this.list(e, t, {}, s) : this._client.getAPIList(`/threads/${e}/runs/${t}/steps`, Xs, { query: s, ...n, headers: { "OpenAI-Beta": "assistants=v2", ...n?.headers } }) } } class Xs extends We { } Us.RunStepsPage = Xs; class Js extends Ne { constructor() { super(...arguments), this.steps = new Us(this._client) } create(e, t, s) { const { include: n, ...r } = t; return this._client.post(`/threads/${e}/runs`, { query: { include: n }, body: r, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers }, stream: t.stream ?? !1 }) } retrieve(e, t, s) { return this._client.get(`/threads/${e}/runs/${t}`, { ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } update(e, t, s, n) { return this._client.post(`/threads/${e}/runs/${t}`, { body: s, ...n, headers: { "OpenAI-Beta": "assistants=v2", ...n?.headers } }) } list(e, t = {}, s) { return ge(t) ? this.list(e, {}, t) : this._client.getAPIList(`/threads/${e}/runs`, Hs, { query: t, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } cancel(e, t, s) { return this._client.post(`/threads/${e}/runs/${t}/cancel`, { ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } async createAndPoll(e, t, s) { const n = await this.create(e, t, s); return await this.poll(e, n.id, s) } createAndStream(e, t, s) { return qs.createAssistantStream(e, this._client.beta.threads.runs, t, s) } async poll(e, t, s) { const n = { ...s?.headers, "X-Stainless-Poll-Helper": "true" }; for (s?.pollIntervalMs && (n["X-Stainless-Custom-Poll-Interval"] = s.pollIntervalMs.toString()); ;) { const { data: r, response: o } = await this.retrieve(e, t, { ...s, headers: { ...s?.headers, ...n } }).withResponse(); switch (r.status) { case "queued": case "in_progress": case "cancelling": let e = 5e3; if (s?.pollIntervalMs) e = s.pollIntervalMs; else { const t = o.headers.get("openai-poll-after-ms"); if (t) { const s = parseInt(t); isNaN(s) || (e = s) } } await Ae(e); break; case "requires_action": case "incomplete": case "cancelled": case "completed": case "failed": case "expired": return r } } } stream(e, t, s) { return qs.createAssistantStream(e, this._client.beta.threads.runs, t, s) } submitToolOutputs(e, t, s, n) { return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`, { body: s, ...n, headers: { "OpenAI-Beta": "assistants=v2", ...n?.headers }, stream: s.stream ?? !1 }) } async submitToolOutputsAndPoll(e, t, s, n) { const r = await this.submitToolOutputs(e, t, s, n); return await this.poll(e, r.id, n) } submitToolOutputsStream(e, t, s, n) { return qs.createToolAssistantStream(e, t, this._client.beta.threads.runs, s, n) } } class Hs extends We { } Js.RunsPage = Hs, Js.Steps = Us, Js.RunStepsPage = Xs; class Vs extends Ne { constructor() { super(...arguments), this.runs = new Js(this._client), this.messages = new Ls(this._client) } create(e = {}, t) { return ge(e) ? this.create({}, e) : this._client.post("/threads", { body: e, ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } retrieve(e, t) { return this._client.get(`/threads/${e}`, { ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } update(e, t, s) { return this._client.post(`/threads/${e}`, { body: t, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } del(e, t) { return this._client.delete(`/threads/${e}`, { ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } createAndRun(e, t) { return this._client.post("/threads/runs", { body: e, ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers }, stream: e.stream ?? !1 }) } async createAndRunPoll(e, t) { const s = await this.createAndRun(e, t); return await this.runs.poll(s.thread_id, s.id, t) } createAndRunStream(e, t) { return qs.createThreadAssistantStream(e, this._client.beta.threads, t) } } Vs.Runs = Js, Vs.RunsPage = Hs, Vs.Messages = Ls, Vs.MessagesPage = Ws; class Ks extends Ne { create(e, t, s) { return this._client.post(`/vector_stores/${e}/files`, { body: t, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } retrieve(e, t, s) { return this._client.get(`/vector_stores/${e}/files/${t}`, { ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } list(e, t = {}, s) { return ge(t) ? this.list(e, {}, t) : this._client.getAPIList(`/vector_stores/${e}/files`, zs, { query: t, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } del(e, t, s) { return this._client.delete(`/vector_stores/${e}/files/${t}`, { ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } async createAndPoll(e, t, s) { const n = await this.create(e, t, s); return await this.poll(e, n.id, s) } async poll(e, t, s) { const n = { ...s?.headers, "X-Stainless-Poll-Helper": "true" }; for (s?.pollIntervalMs && (n["X-Stainless-Custom-Poll-Interval"] = s.pollIntervalMs.toString()); ;) { const r = await this.retrieve(e, t, { ...s, headers: n }).withResponse(), o = r.data; switch (o.status) { case "in_progress": let e = 5e3; if (s?.pollIntervalMs) e = s.pollIntervalMs; else { const t = r.response.headers.get("openai-poll-after-ms"); if (t) { const s = parseInt(t); isNaN(s) || (e = s) } } await Ae(e); break; case "failed": case "completed": return o } } } async upload(e, t, s) { const n = await this._client.files.create({ file: t, purpose: "assistants" }, s); return this.create(e, { file_id: n.id }, s) } async uploadAndPoll(e, t, s) { const n = await this.upload(e, t, s); return await this.poll(e, n.id, s) } } class zs extends We { } Ks.VectorStoreFilesPage = zs; class Qs extends Ne { create(e, t, s) { return this._client.post(`/vector_stores/${e}/file_batches`, { body: t, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } retrieve(e, t, s) { return this._client.get(`/vector_stores/${e}/file_batches/${t}`, { ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } cancel(e, t, s) { return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`, { ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } async createAndPoll(e, t, s) { const n = await this.create(e, t); return await this.poll(e, n.id, s) } listFiles(e, t, s = {}, n) { return ge(s) ? this.listFiles(e, t, {}, s) : this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`, zs, { query: s, ...n, headers: { "OpenAI-Beta": "assistants=v2", ...n?.headers } }) } async poll(e, t, s) { const n = { ...s?.headers, "X-Stainless-Poll-Helper": "true" }; for (s?.pollIntervalMs && (n["X-Stainless-Custom-Poll-Interval"] = s.pollIntervalMs.toString()); ;) { const { data: r, response: o } = await this.retrieve(e, t, { ...s, headers: n }).withResponse(); switch (r.status) { case "in_progress": let e = 5e3; if (s?.pollIntervalMs) e = s.pollIntervalMs; else { const t = o.headers.get("openai-poll-after-ms"); if (t) { const s = parseInt(t); isNaN(s) || (e = s) } } await Ae(e); break; case "failed": case "cancelled": case "completed": return r } } } async uploadAndPoll(e, { files: t, fileIds: s = [] }, n) { if (null == t || 0 == t.length) throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead"); const r = n?.maxConcurrency ?? 5, o = Math.min(r, t.length), a = this._client, i = t.values(), l = [...s], c = Array(o).fill(i).map((async function (e) { for (let t of e) { const e = await a.files.create({ file: t, purpose: "assistants" }, n); l.push(e.id) } })); return await (async e => { const t = await Promise.allSettled(e), s = t.filter((e => "rejected" === e.status)); if (s.length) { for (const e of s) console.error(e.reason); throw new Error(`${s.length} promise(s) failed - see the above errors`) } const n = []; for (const e of t) "fulfilled" === e.status && n.push(e.value); return n })(c), await this.createAndPoll(e, { file_ids: l }) } } class Gs extends Ne { constructor() { super(...arguments), this.files = new Ks(this._client), this.fileBatches = new Qs(this._client) } create(e, t) { return this._client.post("/vector_stores", { body: e, ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } retrieve(e, t) { return this._client.get(`/vector_stores/${e}`, { ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } update(e, t, s) { return this._client.post(`/vector_stores/${e}`, { body: t, ...s, headers: { "OpenAI-Beta": "assistants=v2", ...s?.headers } }) } list(e = {}, t) { return ge(e) ? this.list({}, e) : this._client.getAPIList("/vector_stores", Ys, { query: e, ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } del(e, t) { return this._client.delete(`/vector_stores/${e}`, { ...t, headers: { "OpenAI-Beta": "assistants=v2", ...t?.headers } }) } } class Ys extends We { } Gs.VectorStoresPage = Ys, Gs.Files = Ks, Gs.VectorStoreFilesPage = zs, Gs.FileBatches = Qs; class Zs extends Ne { constructor() { super(...arguments), this.realtime = new ps(this._client), this.vectorStores = new Gs(this._client), this.chat = new ds(this._client), this.assistants = new ot(this._client), this.threads = new Vs(this._client) } } Zs.Realtime = ps, Zs.VectorStores = Gs, Zs.VectorStoresPage = Ys, Zs.Assistants = ot, Zs.AssistantsPage = at, Zs.Threads = Vs; class en extends Ne { create(e, t) { return this._client.post("/batches", { body: e, ...t }) } retrieve(e, t) { return this._client.get(`/batches/${e}`, t) } list(e = {}, t) { return ge(e) ? this.list({}, e) : this._client.getAPIList("/batches", tn, { query: e, ...t }) } cancel(e, t) { return this._client.post(`/batches/${e}/cancel`, t) } } class tn extends We { } en.BatchesPage = tn; class sn extends Ne { create(e, t, s) { return this._client.post(`/uploads/${e}/parts`, re({ body: t, ...s })) } } class nn extends Ne { constructor() { super(...arguments), this.parts = new sn(this._client) } create(e, t) { return this._client.post("/uploads", { body: e, ...t }) } cancel(e, t) { return this._client.post(`/uploads/${e}/cancel`, t) } complete(e, t, s) { return this._client.post(`/uploads/${e}/complete`, { body: t, ...s }) } } nn.Parts = sn; class rn extends he { constructor({ baseURL: e = Pe("OPENAI_BASE_URL"), apiKey: t = Pe("OPENAI_API_KEY"), organization: s = Pe("OPENAI_ORG_ID") ?? null, project: n = Pe("OPENAI_PROJECT_ID") ?? null, ...r } = {}) { if (void 0 === t) throw new $("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' })."); const o = { apiKey: t, organization: s, project: n, ...r, baseURL: e || "https://api.openai.com/v1" }; if (!o.dangerouslyAllowBrowser && "undefined" != typeof window && void 0 !== window.document && "undefined" != typeof navigator) throw new $("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"); super({ baseURL: o.baseURL, timeout: o.timeout ?? 6e5, httpAgent: o.httpAgent, maxRetries: o.maxRetries, fetch: o.fetch }), this.completions = new De(this), this.chat = new Fe(this), this.embeddings = new qe(this), this.files = new Ue(this), this.images = new Je(this), this.audio = new ze(this), this.moderations = new Qe(this), this.models = new Ge(this), this.fineTuning = new rt(this), this.beta = new Zs(this), this.batches = new en(this), this.uploads = new nn(this), this._options = o, this.apiKey = t, this.organization = s, this.project = n } defaultQuery() { return this._options.defaultQuery } defaultHeaders(e) { return { ...super.defaultHeaders(e), "OpenAI-Organization": this.organization, "OpenAI-Project": this.project, ...this._options.defaultHeaders } } authHeaders(e) { return { Authorization: `Bearer ${this.apiKey}` } } stringifyQuery(s) { return function (s, n = {}) { let r = s; const o = function (s = d) { if (void 0 !== s.allowEmptyArrays && "boolean" != typeof s.allowEmptyArrays) throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); if (void 0 !== s.encodeDotInKeys && "boolean" != typeof s.encodeDotInKeys) throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); if (null !== s.encoder && void 0 !== s.encoder && "function" != typeof s.encoder) throw new TypeError("Encoder has to be a function."); const n = s.charset || d.charset; if (void 0 !== s.charset && "utf-8" !== s.charset && "iso-8859-1" !== s.charset) throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); let r = e; if (void 0 !== s.format) { if (!a.call(t, s.format)) throw new TypeError("Unknown format option provided."); r = s.format } const o = t[r]; let c, u = d.filter; if (("function" == typeof s.filter || l(s.filter)) && (u = s.filter), c = s.arrayFormat && s.arrayFormat in i ? s.arrayFormat : "indices" in s ? s.indices ? "indices" : "repeat" : d.arrayFormat, "commaRoundTrip" in s && "boolean" != typeof s.commaRoundTrip) throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); const h = void 0 === s.allowDots ? 1 == !!s.encodeDotInKeys || d.allowDots : !!s.allowDots; return { addQueryPrefix: "boolean" == typeof s.addQueryPrefix ? s.addQueryPrefix : d.addQueryPrefix, allowDots: h, allowEmptyArrays: "boolean" == typeof s.allowEmptyArrays ? !!s.allowEmptyArrays : d.allowEmptyArrays, arrayFormat: c, charset: n, charsetSentinel: "boolean" == typeof s.charsetSentinel ? s.charsetSentinel : d.charsetSentinel, commaRoundTrip: !!s.commaRoundTrip, delimiter: void 0 === s.delimiter ? d.delimiter : s.delimiter, encode: "boolean" == typeof s.encode ? s.encode : d.encode, encodeDotInKeys: "boolean" == typeof s.encodeDotInKeys ? s.encodeDotInKeys : d.encodeDotInKeys, encoder: "function" == typeof s.encoder ? s.encoder : d.encoder, encodeValuesOnly: "boolean" == typeof s.encodeValuesOnly ? s.encodeValuesOnly : d.encodeValuesOnly, filter: u, format: r, formatter: o, serializeDate: "function" == typeof s.serializeDate ? s.serializeDate : d.serializeDate, skipNulls: "boolean" == typeof s.skipNulls ? s.skipNulls : d.skipNulls, sort: "function" == typeof s.sort ? s.sort : null, strictNullHandling: "boolean" == typeof s.strictNullHandling ? s.strictNullHandling : d.strictNullHandling } }(n); let c, h; "function" == typeof o.filter ? (h = o.filter, r = h("", r)) : l(o.filter) && (h = o.filter, c = h); const f = []; if ("object" != typeof r || null === r) return ""; const m = i[o.arrayFormat], g = "comma" === m && o.commaRoundTrip; c || (c = Object.keys(r)), o.sort && c.sort(o.sort); const y = new WeakMap; for (let e = 0; e < c.length; ++e) { const t = c[e]; o.skipNulls && null === r[t] || u(f, p(r[t], t, m, g, o.allowEmptyArrays, o.strictNullHandling, o.skipNulls, o.encodeDotInKeys, o.encode ? o.encoder : null, o.filter, o.sort, o.allowDots, o.serializeDate, o.format, o.formatter, o.encodeValuesOnly, o.charset, y)) } const w = f.join(o.delimiter); let b = !0 === o.addQueryPrefix ? "?" : ""; return o.charsetSentinel && ("iso-8859-1" === o.charset ? b += "utf8=%26%2310003%3B&" : b += "utf8=%E2%9C%93&"), w.length > 0 ? b + w : "" }(s, { arrayFormat: "brackets" }) } } Ds = rn, rn.OpenAI = Ds, rn.DEFAULT_TIMEOUT = 6e5, rn.OpenAIError = $, rn.APIError = k, rn.APIConnectionError = j, rn.APIConnectionTimeoutError = M, rn.APIUserAbortError = T, rn.NotFoundError = F, rn.ConflictError = q, rn.RateLimitError = W, rn.BadRequestError = N, rn.AuthenticationError = D, rn.InternalServerError = U, rn.PermissionDeniedError = B, rn.UnprocessableEntityError = L, rn.toFile = ee, rn.fileFromPath = S, rn.Completions = De, rn.Chat = Fe, rn.Embeddings = qe, rn.Files = Ue, rn.FileObjectsPage = Xe, rn.Images = Je, rn.Audio = ze, rn.Moderations = Qe, rn.Models = Ge, rn.ModelsPage = Ye, rn.FineTuning = rt, rn.Beta = Zs, rn.Batches = en, rn.BatchesPage = tn, rn.Uploads = nn, new Set(["/completions", "/chat/completions", "/embeddings", "/audio/transcriptions", "/audio/translations", "/audio/speech", "/images/generations"]); const on = rn; window.OpenAI = on })();