UNPKG

sinsintro-ai-assistant-dh

Version:

A single npm package providing a React-based voice assistant with OpenAI function-calling, purely client-side.

1,439 lines 179 kB
import Br, { useState as Bt, useRef as ye, useEffect as Hn } from "react"; var nt = { exports: {} }, Be = {}; /** * @license React * react-jsx-runtime.production.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Gn; function Dr() { if (Gn) return Be; Gn = 1; var s = Symbol.for("react.transitional.element"), e = Symbol.for("react.fragment"); function t(n, r, a) { var i = null; if (a !== void 0 && (i = "" + a), r.key !== void 0 && (i = "" + r.key), "key" in r) { a = {}; for (var o in r) o !== "key" && (a[o] = r[o]); } else a = r; return r = a.ref, { $$typeof: s, type: n, key: i, ref: r !== void 0 ? r : null, props: a }; } return Be.Fragment = e, Be.jsx = t, Be.jsxs = t, Be; } var De = {}; /** * @license React * react-jsx-runtime.development.js * * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Yn; function jr() { return Yn || (Yn = 1, process.env.NODE_ENV !== "production" && function() { function s(l) { if (l == null) return null; if (typeof l == "function") return l.$$typeof === I ? null : l.displayName || l.name || null; if (typeof l == "string") return l; switch (l) { case p: return "Fragment"; case B: return "Profiler"; case _: return "StrictMode"; case T: return "Suspense"; case C: return "SuspenseList"; case k: return "Activity"; } if (typeof l == "object") switch (typeof l.tag == "number" && console.error( "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue." ), l.$$typeof) { case y: return "Portal"; case A: return (l.displayName || "Context") + ".Provider"; case g: return (l._context.displayName || "Context") + ".Consumer"; case x: var P = l.render; return l = l.displayName, l || (l = P.displayName || P.name || "", l = l !== "" ? "ForwardRef(" + l + ")" : "ForwardRef"), l; case E: return P = l.displayName || null, P !== null ? P : s(l.type) || "Memo"; case W: P = l._payload, l = l._init; try { return s(l(P)); } catch { } } return null; } function e(l) { return "" + l; } function t(l) { try { e(l); var P = !1; } catch { P = !0; } if (P) { P = console; var N = P.error, q = typeof Symbol == "function" && Symbol.toStringTag && l[Symbol.toStringTag] || l.constructor.name || "Object"; return N.call( P, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", q ), e(l); } } function n(l) { if (l === p) return "<>"; if (typeof l == "object" && l !== null && l.$$typeof === W) return "<...>"; try { var P = s(l); return P ? "<" + P + ">" : "<...>"; } catch { return "<...>"; } } function r() { var l = v.A; return l === null ? null : l.getOwner(); } function a() { return Error("react-stack-top-frame"); } function i(l) { if (te.call(l, "key")) { var P = Object.getOwnPropertyDescriptor(l, "key").get; if (P && P.isReactWarning) return !1; } return l.key !== void 0; } function o(l, P) { function N() { Z || (Z = !0, console.error( "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", P )); } N.isReactWarning = !0, Object.defineProperty(l, "key", { get: N, configurable: !0 }); } function u() { var l = s(this.type); return Re[l] || (Re[l] = !0, console.error( "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release." )), l = this.props.ref, l !== void 0 ? l : null; } function f(l, P, N, q, de, ae, Nt, Mt) { return N = ae.ref, l = { $$typeof: h, type: l, key: P, props: ae, _owner: de }, (N !== void 0 ? N : null) !== null ? Object.defineProperty(l, "ref", { enumerable: !1, get: u }) : Object.defineProperty(l, "ref", { enumerable: !1, value: null }), l._store = {}, Object.defineProperty(l._store, "validated", { configurable: !1, enumerable: !1, writable: !0, value: 0 }), Object.defineProperty(l, "_debugInfo", { configurable: !1, enumerable: !1, writable: !0, value: null }), Object.defineProperty(l, "_debugStack", { configurable: !1, enumerable: !1, writable: !0, value: Nt }), Object.defineProperty(l, "_debugTask", { configurable: !1, enumerable: !1, writable: !0, value: Mt }), Object.freeze && (Object.freeze(l.props), Object.freeze(l)), l; } function m(l, P, N, q, de, ae, Nt, Mt) { var H = P.children; if (H !== void 0) if (q) if ($(H)) { for (q = 0; q < H.length; q++) c(H[q]); Object.freeze && Object.freeze(H); } else console.error( "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead." ); else c(H); if (te.call(P, "key")) { H = s(l); var Ae = Object.keys(P).filter(function(Lr) { return Lr !== "key"; }); q = 0 < Ae.length ? "{key: someKey, " + Ae.join(": ..., ") + ": ...}" : "{key: someKey}", qn[H + q] || (Ae = 0 < Ae.length ? "{" + Ae.join(": ..., ") + ": ...}" : "{}", console.error( `A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`, q, H, Ae, H ), qn[H + q] = !0); } if (H = null, N !== void 0 && (t(N), H = "" + N), i(P) && (t(P.key), H = "" + P.key), "key" in P) { N = {}; for (var Lt in P) Lt !== "key" && (N[Lt] = P[Lt]); } else N = P; return H && o( N, typeof l == "function" ? l.displayName || l.name || "Unknown" : l ), f( l, H, ae, de, r(), N, Nt, Mt ); } function c(l) { typeof l == "object" && l !== null && l.$$typeof === h && l._store && (l._store.validated = 1); } var d = Br, h = Symbol.for("react.transitional.element"), y = Symbol.for("react.portal"), p = Symbol.for("react.fragment"), _ = Symbol.for("react.strict_mode"), B = Symbol.for("react.profiler"), g = Symbol.for("react.consumer"), A = Symbol.for("react.context"), x = Symbol.for("react.forward_ref"), T = Symbol.for("react.suspense"), C = Symbol.for("react.suspense_list"), E = Symbol.for("react.memo"), W = Symbol.for("react.lazy"), k = Symbol.for("react.activity"), I = Symbol.for("react.client.reference"), v = d.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, te = Object.prototype.hasOwnProperty, $ = Array.isArray, F = console.createTask ? console.createTask : function() { return null; }; d = { "react-stack-bottom-frame": function(l) { return l(); } }; var Z, Re = {}, Xn = d["react-stack-bottom-frame"].bind( d, a )(), Vn = F(n(a)), qn = {}; De.Fragment = p, De.jsx = function(l, P, N, q, de) { var ae = 1e4 > v.recentlyCreatedOwnerStacks++; return m( l, P, N, !1, q, de, ae ? Error("react-stack-top-frame") : Xn, ae ? F(n(l)) : Vn ); }, De.jsxs = function(l, P, N, q, de) { var ae = 1e4 > v.recentlyCreatedOwnerStacks++; return m( l, P, N, !0, q, de, ae ? Error("react-stack-top-frame") : Xn, ae ? F(n(l)) : Vn ); }; }()), De; } var Kn; function Ur() { return Kn || (Kn = 1, process.env.NODE_ENV === "production" ? nt.exports = Dr() : nt.exports = jr()), nt.exports; } var Qn = Ur(); const Yt = "RFC3986", Kt = { RFC1738: (s) => String(s).replace(/%20/g, "+"), RFC3986: (s) => String(s) }, Wr = "RFC1738", Jr = Array.isArray, ie = (() => { const s = []; for (let e = 0; e < 256; ++e) s.push("%" + ((e < 16 ? "0" : "") + e.toString(16)).toUpperCase()); return s; })(), Dt = 1024, Xr = (s, e, t, n, r) => { if (s.length === 0) return s; let a = s; if (typeof s == "symbol" ? a = Symbol.prototype.toString.call(s) : typeof s != "string" && (a = String(s)), t === "iso-8859-1") return escape(a).replace(/%u[0-9a-f]{4}/gi, function(o) { return "%26%23" + parseInt(o.slice(2), 16) + "%3B"; }); let i = ""; for (let o = 0; o < a.length; o += Dt) { const u = a.length >= Dt ? a.slice(o, o + Dt) : a, f = []; for (let m = 0; m < u.length; ++m) { let c = u.charCodeAt(m); if (c === 45 || // - c === 46 || // . c === 95 || // _ c === 126 || // ~ c >= 48 && c <= 57 || // 0-9 c >= 65 && c <= 90 || // a-z c >= 97 && c <= 122 || // A-Z r === Wr && (c === 40 || c === 41)) { f[f.length] = u.charAt(m); continue; } if (c < 128) { f[f.length] = ie[c]; continue; } if (c < 2048) { f[f.length] = ie[192 | c >> 6] + ie[128 | c & 63]; continue; } if (c < 55296 || c >= 57344) { f[f.length] = ie[224 | c >> 12] + ie[128 | c >> 6 & 63] + ie[128 | c & 63]; continue; } m += 1, c = 65536 + ((c & 1023) << 10 | u.charCodeAt(m) & 1023), f[f.length] = ie[240 | c >> 18] + ie[128 | c >> 12 & 63] + ie[128 | c >> 6 & 63] + ie[128 | c & 63]; } i += f.join(""); } return i; }; function Vr(s) { return !s || typeof s != "object" ? !1 : !!(s.constructor && s.constructor.isBuffer && s.constructor.isBuffer(s)); } function zn(s, e) { if (Jr(s)) { const t = []; for (let n = 0; n < s.length; n += 1) t.push(e(s[n])); return t; } return e(s); } const qr = Object.prototype.hasOwnProperty, xs = { brackets(s) { return String(s) + "[]"; }, comma: "comma", indices(s, e) { return String(s) + "[" + e + "]"; }, repeat(s) { return String(s); } }, oe = Array.isArray, Hr = Array.prototype.push, Ss = function(s, e) { Hr.apply(s, oe(e) ? e : [e]); }, Gr = Date.prototype.toISOString, j = { addQueryPrefix: !1, allowDots: !1, allowEmptyArrays: !1, arrayFormat: "indices", charset: "utf-8", charsetSentinel: !1, delimiter: "&", encode: !0, encodeDotInKeys: !1, encoder: Xr, encodeValuesOnly: !1, format: Yt, formatter: Kt[Yt], /** @deprecated */ indices: !1, serializeDate(s) { return Gr.call(s); }, skipNulls: !1, strictNullHandling: !1 }; function Yr(s) { return typeof s == "string" || typeof s == "number" || typeof s == "boolean" || typeof s == "symbol" || typeof s == "bigint"; } const jt = {}; function Rs(s, e, t, n, r, a, i, o, u, f, m, c, d, h, y, p, _, B) { let g = s, A = B, x = 0, T = !1; for (; (A = A.get(jt)) !== void 0 && !T; ) { const I = A.get(s); if (x += 1, typeof I < "u") { if (I === x) throw new RangeError("Cyclic object value"); T = !0; } typeof A.get(jt) > "u" && (x = 0); } if (typeof f == "function" ? g = f(e, g) : g instanceof Date ? g = d == null ? void 0 : d(g) : t === "comma" && oe(g) && (g = zn(g, function(I) { return I instanceof Date ? d == null ? void 0 : d(I) : I; })), g === null) { if (a) return u && !p ? ( // @ts-expect-error u(e, j.encoder, _, "key", h) ) : e; g = ""; } if (Yr(g) || Vr(g)) { if (u) { const I = p ? e : u(e, j.encoder, _, "key", h); return [ (y == null ? void 0 : y(I)) + "=" + // @ts-expect-error (y == null ? void 0 : y(u(g, j.encoder, _, "value", h))) ]; } return [(y == null ? void 0 : y(e)) + "=" + (y == null ? void 0 : y(String(g)))]; } const C = []; if (typeof g > "u") return C; let E; if (t === "comma" && oe(g)) p && u && (g = zn(g, u)), E = [{ value: g.length > 0 ? g.join(",") || null : void 0 }]; else if (oe(f)) E = f; else { const I = Object.keys(g); E = m ? I.sort(m) : I; } const W = o ? String(e).replace(/\./g, "%2E") : String(e), k = n && oe(g) && g.length === 1 ? W + "[]" : W; if (r && oe(g) && g.length === 0) return k + "[]"; for (let I = 0; I < E.length; ++I) { const v = E[I], te = ( // @ts-ignore typeof v == "object" && typeof v.value < "u" ? v.value : g[v] ); if (i && te === null) continue; const $ = c && o ? v.replace(/\./g, "%2E") : v, F = oe(g) ? typeof t == "function" ? t(k, $) : k : k + (c ? "." + $ : "[" + $ + "]"); B.set(s, x); const Z = /* @__PURE__ */ new WeakMap(); Z.set(jt, B), Ss(C, Rs( te, F, t, n, r, a, i, o, // @ts-ignore t === "comma" && p && oe(g) ? null : u, f, m, c, d, h, y, p, _, Z )); } return C; } function Kr(s = j) { if (typeof s.allowEmptyArrays < "u" && typeof s.allowEmptyArrays != "boolean") throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided"); if (typeof s.encodeDotInKeys < "u" && typeof s.encodeDotInKeys != "boolean") throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided"); if (s.encoder !== null && typeof s.encoder < "u" && typeof s.encoder != "function") throw new TypeError("Encoder has to be a function."); const e = s.charset || j.charset; if (typeof s.charset < "u" && s.charset !== "utf-8" && s.charset !== "iso-8859-1") throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined"); let t = Yt; if (typeof s.format < "u") { if (!qr.call(Kt, s.format)) throw new TypeError("Unknown format option provided."); t = s.format; } const n = Kt[t]; let r = j.filter; (typeof s.filter == "function" || oe(s.filter)) && (r = s.filter); let a; if (s.arrayFormat && s.arrayFormat in xs ? a = s.arrayFormat : "indices" in s ? a = s.indices ? "indices" : "repeat" : a = j.arrayFormat, "commaRoundTrip" in s && typeof s.commaRoundTrip != "boolean") throw new TypeError("`commaRoundTrip` must be a boolean, or absent"); const i = typeof s.allowDots > "u" ? s.encodeDotInKeys ? !0 : j.allowDots : !!s.allowDots; return { addQueryPrefix: typeof s.addQueryPrefix == "boolean" ? s.addQueryPrefix : j.addQueryPrefix, // @ts-ignore allowDots: i, allowEmptyArrays: typeof s.allowEmptyArrays == "boolean" ? !!s.allowEmptyArrays : j.allowEmptyArrays, arrayFormat: a, charset: e, charsetSentinel: typeof s.charsetSentinel == "boolean" ? s.charsetSentinel : j.charsetSentinel, commaRoundTrip: !!s.commaRoundTrip, delimiter: typeof s.delimiter > "u" ? j.delimiter : s.delimiter, encode: typeof s.encode == "boolean" ? s.encode : j.encode, encodeDotInKeys: typeof s.encodeDotInKeys == "boolean" ? s.encodeDotInKeys : j.encodeDotInKeys, encoder: typeof s.encoder == "function" ? s.encoder : j.encoder, encodeValuesOnly: typeof s.encodeValuesOnly == "boolean" ? s.encodeValuesOnly : j.encodeValuesOnly, filter: r, format: t, formatter: n, serializeDate: typeof s.serializeDate == "function" ? s.serializeDate : j.serializeDate, skipNulls: typeof s.skipNulls == "boolean" ? s.skipNulls : j.skipNulls, // @ts-ignore sort: typeof s.sort == "function" ? s.sort : null, strictNullHandling: typeof s.strictNullHandling == "boolean" ? s.strictNullHandling : j.strictNullHandling }; } function Qr(s, e = {}) { let t = s; const n = Kr(e); let r, a; typeof n.filter == "function" ? (a = n.filter, t = a("", t)) : oe(n.filter) && (a = n.filter, r = a); const i = []; if (typeof t != "object" || t === null) return ""; const o = xs[n.arrayFormat], u = o === "comma" && n.commaRoundTrip; r || (r = Object.keys(t)), n.sort && r.sort(n.sort); const f = /* @__PURE__ */ new WeakMap(); for (let d = 0; d < r.length; ++d) { const h = r[d]; n.skipNulls && t[h] === null || Ss(i, Rs( t[h], h, // @ts-expect-error o, u, n.allowEmptyArrays, n.strictNullHandling, n.skipNulls, n.encodeDotInKeys, n.encode ? n.encoder : null, n.filter, n.sort, n.allowDots, n.serializeDate, n.format, n.formatter, n.encodeValuesOnly, n.charset, f )); } const m = i.join(n.delimiter); let c = n.addQueryPrefix === !0 ? "?" : ""; return n.charsetSentinel && (n.charset === "iso-8859-1" ? c += "utf8=%26%2310003%3B&" : c += "utf8=%E2%9C%93&"), m.length > 0 ? c + m : ""; } const $e = "4.100.0"; let Zn = !1, qe, As, Es, Qt, Ps, Cs, vs, $s, Os; function zr(s, e = { auto: !1 }) { if (Zn) throw new Error(`you must \`import 'openai/shims/${s.kind}'\` before importing anything else from openai`); if (qe) throw new Error(`can't \`import 'openai/shims/${s.kind}'\` after \`import 'openai/shims/${qe}'\``); Zn = e.auto, qe = s.kind, As = s.fetch, Es = s.FormData, Qt = s.File, Ps = s.ReadableStream, Cs = s.getMultipartRequestOptions, vs = s.getDefaultAgent, $s = s.fileFromPath, Os = s.isFsReadStream; } class Zr { constructor(e) { this.body = e; } get [Symbol.toStringTag]() { return "MultipartBody"; } } function ea({ manuallyImported: s } = {}) { const e = s ? "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 t, n, r, a; try { t = fetch, n = Request, r = Response, a = Headers; } catch (i) { throw new Error(`this environment is missing the following Web Fetch API type: ${i.message}. ${e}`); } return { kind: "web", fetch: t, Request: n, Response: r, Headers: a, FormData: ( // @ts-ignore typeof FormData < "u" ? FormData : class { // @ts-ignore constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`); } } ), Blob: typeof Blob < "u" ? Blob : class { constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`); } }, File: ( // @ts-ignore typeof File < "u" ? File : class { // @ts-ignore constructor() { throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`); } } ), ReadableStream: ( // @ts-ignore typeof ReadableStream < "u" ? ReadableStream : class { // @ts-ignore constructor() { throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`); } } ), getMultipartRequestOptions: async (i, o) => ({ ...o, body: new Zr(i) }), getDefaultAgent: (i) => { }, 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: (i) => !1 }; } const Is = () => { qe || zr(ea(), { auto: !0 }); }; Is(); class b extends Error { } class X extends b { constructor(e, t, n, r) { super(`${X.makeMessage(e, t, n)}`), this.status = e, this.headers = r, this.request_id = r == null ? void 0 : r["x-request-id"], this.error = t; const a = t; this.code = a == null ? void 0 : a.code, this.param = a == null ? void 0 : a.param, this.type = a == null ? void 0 : a.type; } static makeMessage(e, t, n) { const r = t != null && t.message ? typeof t.message == "string" ? t.message : JSON.stringify(t.message) : t ? JSON.stringify(t) : n; return e && r ? `${e} ${r}` : e ? `${e} status code (no body)` : r || "(no status code or body)"; } static generate(e, t, n, r) { if (!e || !r) return new Rt({ message: n, cause: Zt(t) }); const a = t == null ? void 0 : t.error; return e === 400 ? new Ts(e, a, n, r) : e === 401 ? new ks(e, a, n, r) : e === 403 ? new Fs(e, a, n, r) : e === 404 ? new Ns(e, a, n, r) : e === 409 ? new Ms(e, a, n, r) : e === 422 ? new Ls(e, a, n, r) : e === 429 ? new Bs(e, a, n, r) : e >= 500 ? new Ds(e, a, n, r) : new X(e, a, n, r); } } class ee extends X { constructor({ message: e } = {}) { super(void 0, void 0, e || "Request was aborted.", void 0); } } class Rt extends X { constructor({ message: e, cause: t }) { super(void 0, void 0, e || "Connection error.", void 0), t && (this.cause = t); } } class ln extends Rt { constructor({ message: e } = {}) { super({ message: e ?? "Request timed out." }); } } class Ts extends X { } class ks extends X { } class Fs extends X { } class Ns extends X { } class Ms extends X { } class Ls extends X { } class Bs extends X { } class Ds extends X { } class js extends b { constructor() { super("Could not parse response content as the length limit was reached"); } } class Us extends b { constructor() { super("Could not parse response content as the request was rejected by the content filter"); } } var st = function(s, e, t, n, r) { if (n === "m") throw new TypeError("Private method is not writable"); if (n === "a" && !r) throw new TypeError("Private accessor was defined without a setter"); if (typeof e == "function" ? s !== e || !r : !e.has(s)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return n === "a" ? r.call(s, t) : r ? r.value = t : e.set(s, t), t; }, be = function(s, e, t, n) { if (t === "a" && !n) throw new TypeError("Private accessor was defined without a getter"); if (typeof e == "function" ? s !== e || !n : !e.has(s)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return t === "m" ? n : t === "a" ? n.call(s) : n ? n.value : e.get(s); }, Q; class At { constructor() { Q.set(this, void 0), this.buffer = new Uint8Array(), st(this, Q, null, "f"); } decode(e) { if (e == null) return []; const t = e instanceof ArrayBuffer ? new Uint8Array(e) : typeof e == "string" ? new TextEncoder().encode(e) : e; let n = new Uint8Array(this.buffer.length + t.length); n.set(this.buffer), n.set(t, this.buffer.length), this.buffer = n; const r = []; let a; for (; (a = ta(this.buffer, be(this, Q, "f"))) != null; ) { if (a.carriage && be(this, Q, "f") == null) { st(this, Q, a.index, "f"); continue; } if (be(this, Q, "f") != null && (a.index !== be(this, Q, "f") + 1 || a.carriage)) { r.push(this.decodeText(this.buffer.slice(0, be(this, Q, "f") - 1))), this.buffer = this.buffer.slice(be(this, Q, "f")), st(this, Q, null, "f"); continue; } const i = be(this, Q, "f") !== null ? a.preceding - 1 : a.preceding, o = this.decodeText(this.buffer.slice(0, i)); r.push(o), this.buffer = this.buffer.slice(a.index), st(this, Q, null, "f"); } return r; } decodeText(e) { if (e == null) return ""; if (typeof e == "string") return e; if (typeof Buffer < "u") { if (e instanceof Buffer) return e.toString(); if (e instanceof Uint8Array) return Buffer.from(e).toString(); throw new b(`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 (typeof TextDecoder < "u") { if (e instanceof Uint8Array || e instanceof ArrayBuffer) return this.textDecoder ?? (this.textDecoder = new TextDecoder("utf8")), this.textDecoder.decode(e); throw new b(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`); } throw new b("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error."); } flush() { return this.buffer.length ? this.decode(` `) : []; } } Q = /* @__PURE__ */ new WeakMap(); At.NEWLINE_CHARS = /* @__PURE__ */ new Set([` `, "\r"]); At.NEWLINE_REGEXP = /\r\n|[\n\r]/g; function ta(s, e) { for (let r = e ?? 0; r < s.length; r++) { if (s[r] === 10) return { preceding: r, index: r + 1, carriage: !1 }; if (s[r] === 13) return { preceding: r, index: r + 1, carriage: !0 }; } return null; } function na(s) { for (let n = 0; n < s.length - 1; n++) { if (s[n] === 10 && s[n + 1] === 10 || s[n] === 13 && s[n + 1] === 13) return n + 2; if (s[n] === 13 && s[n + 1] === 10 && n + 3 < s.length && s[n + 2] === 13 && s[n + 3] === 10) return n + 4; } return -1; } function Ws(s) { if (s[Symbol.asyncIterator]) return s; const e = s.getReader(); return { async next() { try { const t = await e.read(); return t != null && t.done && e.releaseLock(), t; } catch (t) { throw e.releaseLock(), t; } }, async return() { const t = e.cancel(); return e.releaseLock(), await t, { done: !0, value: void 0 }; }, [Symbol.asyncIterator]() { return this; } }; } class le { constructor(e, t) { this.iterator = e, this.controller = t; } static fromSSEResponse(e, t) { let n = !1; async function* r() { if (n) throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); n = !0; let a = !1; try { for await (const i of sa(e, t)) if (!a) { if (i.data.startsWith("[DONE]")) { a = !0; continue; } if (i.event === null || i.event.startsWith("response.") || i.event.startsWith("transcript.")) { let o; try { o = JSON.parse(i.data); } catch (u) { throw console.error("Could not parse message into JSON:", i.data), console.error("From chunk:", i.raw), u; } if (o && o.error) throw new X(void 0, o.error, void 0, Ys(e.headers)); yield o; } else { let o; try { o = JSON.parse(i.data); } catch (u) { throw console.error("Could not parse message into JSON:", i.data), console.error("From chunk:", i.raw), u; } if (i.event == "error") throw new X(void 0, o.error, o.message, void 0); yield { event: i.event, data: o }; } } a = !0; } catch (i) { if (i instanceof Error && i.name === "AbortError") return; throw i; } finally { a || t.abort(); } } return new le(r, t); } /** * Generates a Stream from a newline-separated ReadableStream * where each item is a JSON value. */ static fromReadableStream(e, t) { let n = !1; async function* r() { const i = new At(), o = Ws(e); for await (const u of o) for (const f of i.decode(u)) yield f; for (const u of i.flush()) yield u; } async function* a() { if (n) throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream."); n = !0; let i = !1; try { for await (const o of r()) i || o && (yield JSON.parse(o)); i = !0; } catch (o) { if (o instanceof Error && o.name === "AbortError") return; throw o; } finally { i || t.abort(); } } return new le(a, t); } [Symbol.asyncIterator]() { return this.iterator(); } /** * Splits the stream into two streams which can be * independently read from at different speeds. */ tee() { const e = [], t = [], n = this.iterator(), r = (a) => ({ next: () => { if (a.length === 0) { const i = n.next(); e.push(i), t.push(i); } return a.shift(); } }); return [ new le(() => r(e), this.controller), new le(() => r(t), this.controller) ]; } /** * Converts this stream to a newline-separated ReadableStream of * JSON stringified values in the stream * which can be turned back into a Stream with `Stream.fromReadableStream()`. */ toReadableStream() { const e = this; let t; const n = new TextEncoder(); return new Ps({ async start() { t = e[Symbol.asyncIterator](); }, async pull(r) { try { const { value: a, done: i } = await t.next(); if (i) return r.close(); const o = n.encode(JSON.stringify(a) + ` `); r.enqueue(o); } catch (a) { r.error(a); } }, async cancel() { var r; await ((r = t.return) == null ? void 0 : r.call(t)); } }); } } async function* sa(s, e) { if (!s.body) throw e.abort(), new b("Attempted to iterate over a response with no body"); const t = new aa(), n = new At(), r = Ws(s.body); for await (const a of ra(r)) for (const i of n.decode(a)) { const o = t.decode(i); o && (yield o); } for (const a of n.flush()) { const i = t.decode(a); i && (yield i); } } async function* ra(s) { let e = new Uint8Array(); for await (const t of s) { if (t == null) continue; const n = t instanceof ArrayBuffer ? new Uint8Array(t) : typeof t == "string" ? new TextEncoder().encode(t) : t; let r = new Uint8Array(e.length + n.length); r.set(e), r.set(n, e.length), e = r; let a; for (; (a = na(e)) !== -1; ) yield e.slice(0, a), e = e.slice(a); } e.length > 0 && (yield e); } class aa { 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 a = { event: this.event, data: this.data.join(` `), raw: this.chunks }; return this.event = null, this.data = [], this.chunks = [], a; } if (this.chunks.push(e), e.startsWith(":")) return null; let [t, n, r] = ia(e, ":"); return r.startsWith(" ") && (r = r.substring(1)), t === "event" ? this.event = r : t === "data" && this.data.push(r), null; } } function ia(s, e) { const t = s.indexOf(e); return t !== -1 ? [s.substring(0, t), e, s.substring(t + e.length)] : [s, "", ""]; } const Js = (s) => s != null && typeof s == "object" && typeof s.url == "string" && typeof s.blob == "function", Xs = (s) => s != null && typeof s == "object" && typeof s.name == "string" && typeof s.lastModified == "number" && Et(s), Et = (s) => s != null && typeof s == "object" && typeof s.size == "number" && typeof s.type == "string" && typeof s.text == "function" && typeof s.slice == "function" && typeof s.arrayBuffer == "function", oa = (s) => Xs(s) || Js(s) || Os(s); async function Vs(s, e, t) { var r; if (s = await s, Xs(s)) return s; if (Js(s)) { const a = await s.blob(); e || (e = new URL(s.url).pathname.split(/[\\/]/).pop() ?? "unknown_file"); const i = Et(a) ? [await a.arrayBuffer()] : [a]; return new Qt(i, e, t); } const n = await ca(s); if (e || (e = ua(s) ?? "unknown_file"), !(t != null && t.type)) { const a = (r = n[0]) == null ? void 0 : r.type; typeof a == "string" && (t = { ...t, type: a }); } return new Qt(n, e, t); } async function ca(s) { var t; let e = []; if (typeof s == "string" || ArrayBuffer.isView(s) || // includes Uint8Array, Buffer, etc. s instanceof ArrayBuffer) e.push(s); else if (Et(s)) e.push(await s.arrayBuffer()); else if (fa(s)) for await (const n of s) e.push(n); else throw new Error(`Unexpected data type: ${typeof s}; constructor: ${(t = s == null ? void 0 : s.constructor) == null ? void 0 : t.name}; props: ${la(s)}`); return e; } function la(s) { return `[${Object.getOwnPropertyNames(s).map((t) => `"${t}"`).join(", ")}]`; } function ua(s) { var e; return Ut(s.name) || Ut(s.filename) || // For fs.ReadStream ((e = Ut(s.path)) == null ? void 0 : e.split(/[\\/]/).pop()); } const Ut = (s) => { if (typeof s == "string") return s; if (typeof Buffer < "u" && s instanceof Buffer) return String(s); }, fa = (s) => s != null && typeof s == "object" && typeof s[Symbol.asyncIterator] == "function", es = (s) => s && typeof s == "object" && s.body && s[Symbol.toStringTag] === "MultipartBody", Fe = async (s) => { const e = await da(s.body); return Cs(e, s); }, da = async (s) => { const e = new Es(); return await Promise.all(Object.entries(s || {}).map(([t, n]) => zt(e, t, n))), e; }, zt = async (s, e, t) => { if (t !== void 0) { if (t == null) throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`); if (typeof t == "string" || typeof t == "number" || typeof t == "boolean") s.append(e, String(t)); else if (oa(t)) { const n = await Vs(t); s.append(e, n); } else if (Array.isArray(t)) await Promise.all(t.map((n) => zt(s, e + "[]", n))); else if (typeof t == "object") await Promise.all(Object.entries(t).map(([n, r]) => zt(s, `${e}[${n}]`, r))); else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`); } }; var ha = function(s, e, t, n, r) { if (n === "m") throw new TypeError("Private method is not writable"); if (n === "a" && !r) throw new TypeError("Private accessor was defined without a setter"); if (typeof e == "function" ? s !== e || !r : !e.has(s)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); return n === "a" ? r.call(s, t) : r ? r.value = t : e.set(s, t), t; }, ma = function(s, e, t, n) { if (t === "a" && !n) throw new TypeError("Private accessor was defined without a getter"); if (typeof e == "function" ? s !== e || !n : !e.has(s)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); return t === "m" ? n : t === "a" ? n.call(s) : n ? n.value : e.get(s); }, rt; Is(); async function qs(s) { var i; const { response: e } = s; if (s.options.stream) return ge("response", e.status, e.url, e.headers, e.body), s.options.__streamClass ? s.options.__streamClass.fromSSEResponse(e, s.controller) : le.fromSSEResponse(e, s.controller); if (e.status === 204) return null; if (s.options.__binaryResponse) return e; const t = e.headers.get("content-type"), n = (i = t == null ? void 0 : t.split(";")[0]) == null ? void 0 : i.trim(); if ((n == null ? void 0 : n.includes("application/json")) || (n == null ? void 0 : n.endsWith("+json"))) { const o = await e.json(); return ge("response", e.status, e.url, e.headers, o), Hs(o, e); } const a = await e.text(); return ge("response", e.status, e.url, e.headers, a), a; } function Hs(s, e) { return !s || typeof s != "object" || Array.isArray(s) ? s : Object.defineProperty(s, "_request_id", { value: e.headers.get("x-request-id"), enumerable: !1 }); } class Pt extends Promise { constructor(e, t = qs) { super((n) => { n(null); }), this.responsePromise = e, this.parseResponse = t; } _thenUnwrap(e) { return new Pt(this.responsePromise, async (t) => Hs(e(await this.parseResponse(t), t), t.response)); } /** * Gets the raw `Response` instance instead of parsing the response * data. * * If you want to parse the response body but still get the `Response` * instance, you can use {@link withResponse()}. * * 👋 Getting the wrong TypeScript type for `Response`? * Try setting `"moduleResolution": "NodeNext"` if you can, * or add one of these imports before your first `import … from 'openai'`: * - `import 'openai/shims/node'` (if you're running on Node) * - `import 'openai/shims/web'` (otherwise) */ asResponse() { return this.responsePromise.then((e) => e.response); } /** * Gets the parsed response data, the raw `Response` instance and the ID of the request, * returned via the X-Request-ID header which is useful for debugging requests and reporting * issues to OpenAI. * * If you just want to get the raw `Response` instance without parsing it, * you can use {@link asResponse()}. * * * 👋 Getting the wrong TypeScript type for `Response`? * Try setting `"moduleResolution": "NodeNext"` if you can, * or add one of these imports before your first `import … from 'openai'`: * - `import 'openai/shims/node'` (if you're running on Node) * - `import 'openai/shims/web'` (otherwise) */ 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 pa { constructor({ baseURL: e, maxRetries: t = 2, timeout: n = 6e5, // 10 minutes httpAgent: r, fetch: a }) { this.baseURL = e, this.maxRetries = Wt("maxRetries", t), this.timeout = Wt("timeout", n), this.httpAgent = r, this.fetch = a ?? As; } authHeaders(e) { return {}; } /** * Override this to add your own default headers, for example: * * { * ...super.defaultHeaders(), * Authorization: 'Bearer 123', * } */ defaultHeaders(e) { return { Accept: "application/json", "Content-Type": "application/json", "User-Agent": this.getUserAgent(), ...ba(), ...this.authHeaders(e) }; } /** * Override this to add your own headers validation: */ validateHeaders(e, t) { } defaultIdempotencyKey() { return `stainless-node-retry-${Aa()}`; } 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, n) { return this.request(Promise.resolve(n).then(async (r) => { const a = r && Et(r == null ? void 0 : r.body) ? new DataView(await r.body.arrayBuffer()) : (r == null ? void 0 : r.body) instanceof DataView ? r.body : (r == null ? void 0 : r.body) instanceof ArrayBuffer ? new DataView(r.body) : r && ArrayBuffer.isView(r == null ? void 0 : r.body) ? new DataView(r.body.buffer) : r == null ? void 0 : r.body; return { method: e, path: t, ...r, body: a }; })); } getAPIList(e, t, n) { return this.requestAPIList(t, { method: "get", path: e, ...n }); } calculateContentLength(e) { if (typeof e == "string") { if (typeof Buffer < "u") return Buffer.byteLength(e, "utf8").toString(); if (typeof TextEncoder < "u") return new TextEncoder().encode(e).length.toString(); } else if (ArrayBuffer.isView(e)) return e.byteLength.toString(); return null; } buildRequest(e, { retryCount: t = 0 } = {}) { var p; const n = { ...e }, { method: r, path: a, query: i, headers: o = {} } = n, u = ArrayBuffer.isView(n.body) || n.__binaryRequest && typeof n.body == "string" ? n.body : es(n.body) ? n.body.body : n.body ? JSON.stringify(n.body, null, 2) : null, f = this.calculateContentLength(u), m = this.buildURL(a, i); "timeout" in n && Wt("timeout", n.timeout), n.timeout = n.timeout ?? this.timeout; const c = n.httpAgent ?? this.httpAgent ?? vs(m), d = n.timeout + 1e3; typeof ((p = c == null ? void 0 : c.options) == null ? void 0 : p.timeout) == "number" && d > (c.options.timeout ?? 0) && (c.options.timeout = d), this.idempotencyHeader && r !== "get" && (e.idempotencyKey || (e.idempotencyKey = this.defaultIdempotencyKey()), o[this.idempotencyHeader] = e.idempotencyKey); const h = this.buildHeaders({ options: n, headers: o, contentLength: f, retryCount: t }); return { req: { method: r, ...u && { body: u }, headers: h, ...c && { agent: c }, // @ts-ignore node-fetch uses a custom AbortSignal type that is // not compatible with standard web types signal: n.signal ?? null }, url: m, timeout: n.timeout }; } buildHeaders({ options: e, headers: t, contentLength: n, retryCount: r }) { const a = {}; n && (a["content-length"] = n); const i = this.defaultHeaders(e); return rs(a, i), rs(a, t), es(e.body) && qe !== "node" && delete a["content-type"], it(i, "x-stainless-retry-count") === void 0 && it(t, "x-stainless-retry-count") === void 0 && (a["x-stainless-retry-count"] = String(r)), it(i, "x-stainless-timeout") === void 0 && it(t, "x-stainless-timeout") === void 0 && e.timeout && (a["x-stainless-timeout"] = String(Math.trunc(e.timeout / 1e3))), this.validateHeaders(a, t), a; } /** * Used as a callback for mutating the given `FinalRequestOptions` object. */ async prepareOptions(e) { } /** * Used as a callback for mutating the given `RequestInit` object. * * This is useful for cases where you want to add certain headers based off of * the request properties, e.g. `method` or `url`. */ async prepareRequest(e, { url: t, options: n }) { } parseHeaders(e) { return e ? Symbol.iterator in e ? Object.fromEntries(Array.from(e).map((t) => [...t])) : { ...e } : {}; } makeStatusError(e, t, n, r) { return X.generate(e, t, n, r); } request(e, t = null) { return new Pt(this.makeRequest(e, t)); } async makeRequest(e, t) { var c, d; const n = await e, r = n.maxRetries ?? this.maxRetries; t == null && (t = r), await this.prepareOptions(n); const { req: a, url: i, timeout: o } = this.buildRequest(n, { retryCount: r - t }); if (await this.prepareRequest(a, { url: i, options: n }), ge("request", i, n, a.headers), (c = n.signal) != null && c.aborted) throw new ee(); const u = new AbortController(), f = await this.fetchWithTimeout(i, a, o, u).catch(Zt); if (f instanceof Error) { if ((d = n.signal) != null && d.aborted) throw new ee(); if (t) return this.retryRequest(n, t); throw f.name === "AbortError" ? new ln() : new Rt({ cause: f }); } const m = Ys(f.headers); if (!f.ok) { if (t && this.shouldRetry(f)) { const g = `retrying, ${t} attempts remaining`; return ge(`response (error; ${g})`, f.status, i, m), this.retryRequest(n, t, m); } const h = await f.text().catch((g) => Zt(g).message), y = xa(h), p = y ? void 0 : h; throw ge(`response (error; ${t ? "(error; no more retries left)" : "(error; not retryable)"})`, f.status, i, m, p), this.makeStatusError(f.status, y, p, m); } return { response: f, options: n, controller: u }; } requestAPIList(e, t) { const n = this.makeRequest(t, null); return new ga(this, n, e); } buildURL(e, t) { const n = Ra(e) ? new URL(e) : new URL(this.baseURL + (this.baseURL.endsWith("/") && e.startsWith("/") ? e.slice(1) : e)), r = this.defaultQuery(); return Ks(r) || (t = { ...r, ...t }), typeof t == "object" && t && !Array.isArray(t) && (n.search = this.stringifyQuery(t)), n.toString(); } stringifyQuery(e) { return Object.entries(e).filter(([t, n]) => typeof n < "u").map(([t, n]) => { if (typeof n == "string" || typeof n == "number" || typeof n == "boolean") return `${encodeURIComponent(t)}=${encodeURIComponent(n)}`; if (n === null) return `${encodeURIComponent(t)}=`; throw new b(`Cannot stringify type ${typeof n}; 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, n, r) { const { signal: a, ...i } = t || {}; a && a.addEventListener("abort", () => r.abort()); const o = setTimeout(() => r.abort(), n), u = { signal: r.signal, ...i }; return u.method && (u.method = u.method.toUpperCase()), // use undefined this binding; fetch errors if bound to something else in browser/cloudflare this.fetch.call(void 0, e, u).finally(() => { clearTimeout(o); }); } shouldRetry(e) { const t = e.headers.get("x-should-retry"); return t === "true" ? !0 : t === "false" ? !1 : e.status === 408 || e.status === 409 || e.status === 429 || e.status >= 500; } async retryRequest(e, t, n) { let r; const a = n == null ? void 0 : n["retry-after-ms"]; if (a) { const o = parseFloat(a); Number.isNaN(o) || (r = o); } const i = n == null ? void 0 : n["retry-after"]; if (i && !r) { const o = parseFloat(i); Number.isNaN(o) ? r = Date.parse(i) - Date.now() : r = o * 1e3; } if (!(r && 0 <= r && r < 60 * 1e3)) { const o = e.maxRetries ?? this.maxRetries; r = this.calculateDefaultRetryTimeoutMillis(t, o); } return await Ke(r), this.makeRequest(e, t - 1); } calculateDefaultRetryTimeoutMillis(e, t) { const a = t - e, i = Math.min(0.5 * Math.pow(2, a), 8), o = 1 - Math.random() * 0.25; return i * o * 1e3; } getUserAgent() { return `${this.constructor.name}/JS ${$e}`; } } class Gs { constructor(e, t, n, r) { rt.set(this, void 0), ha(this, rt, e, "f"), this.options = r, this.response = t, this.body = n; } hasNextPage() { return this.getPaginatedItems().length ? this.nextPageInfo() != null : !1; } async getNextPage() { const e = this.nextPageInfo(); if (!e) throw new b("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`."); const t = { ...this.options }; if ("params" in e && typeof t.query == "object") t.query = { ...t.query, ...e.params }; else if ("url" in e) { const n = [...Object.entries(t.query || {}), ...e.url.searchParams.entries()]; for (const [r, a] of n) e.url.searchParams.set(r, a); t.query = void 0, t.path = e.url.toString(); } return await ma(this, rt, "f").requestAPIList(this.constructor, t); } async *iterPages() { let e = this; for (yield e; e.hasNextPage(); ) e = await e.getNextPage(), yield e; } async *[(rt = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() { for await (const e of this.iterPages()) for (const t of e.getPaginatedItems()) yield t; } } class ga extends Pt { constructor(e, t, n) { super(t, async (r) => new n(e, r.response, await qs(r), r.options)); } /** * Allow auto-paginating iteration on an unawaited list call, eg: * * for await (const item of client.items.list()) { * console.log(item) * } */ async *[Symbol.asyncIterator]() { const e = await this; for await (const t of e) yield t; } } const Ys = (s) => new Proxy(Object.fromEntries( // @ts-ignore s.entries() ), { get(e, t) { const n = t.toString(); return e[n.toLowerCase()] || e[n]; } }), _a = { 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 }, L = (s) => typeof s == "object" && s !== null && !Ks(s) && Object.keys(s).every((e) => Qs(_a, e)), wa = () => { var e; if (typeof Deno < "u" && Deno.build != null) return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": $e, "X-Stainless-OS": ns(Deno.build.os), "X-Stainless-Arch": ts(Deno.build.arch), "X-Stainless-Runtime": "deno", "X-Stainless-Runtime-Version": typeof Deno.version == "string" ? Deno.version : ((e = Deno.version) == null ? void 0 : e.deno) ?? "unknown" }; if (typeof EdgeRuntime < "u") return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": $e, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": `other:${EdgeRuntime}`, "X-Stainless-Runtime": "edge", "X-Stainless-Runtime-Version"