sinsintro-ai-assistant-dh
Version:
A single npm package providing a React-based voice assistant with OpenAI function-calling, purely client-side.
26 lines • 116 kB
JavaScript
(function(U,he){typeof exports=="object"&&typeof module<"u"?module.exports=he(require("react")):typeof define=="function"&&define.amd?define(["react"],he):(U=typeof globalThis<"u"?globalThis:U||self,U.SinsIntroAIAssistant=he(U.React))})(this,function(U){"use strict";var he={exports:{}},De={};/**
* @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 Jn;function Nr(){if(Jn)return De;Jn=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 De.Fragment=e,De.jsx=t,De.jsxs=t,De}var je={};/**
* @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 Xn;function Mr(){return Xn||(Xn=1,process.env.NODE_ENV!=="production"&&function(){function s(l){if(l==null)return null;if(typeof l=="function")return l.$$typeof===T?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 $: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 H: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 M=P.error,G=typeof Symbol=="function"&&Symbol.toStringTag&&l[Symbol.toStringTag]||l.constructor.name||"Object";return M.call(P,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",G),e(l)}}function n(l){if(l===p)return"<>";if(typeof l=="object"&&l!==null&&l.$$typeof===H)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(ae.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 M(){te||(te=!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))}M.isReactWarning=!0,Object.defineProperty(l,"key",{get:M,configurable:!0})}function u(){var l=s(this.type);return Le[l]||(Le[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,M,G,be,ue,jn,Un){return M=ue.ref,l={$$typeof:h,type:l,key:P,props:ue,_owner:be},(M!==void 0?M: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:jn}),Object.defineProperty(l,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:Un}),Object.freeze&&(Object.freeze(l.props),Object.freeze(l)),l}function m(l,P,M,G,be,ue,jn,Un){var Y=P.children;if(Y!==void 0)if(G)if(O(Y)){for(G=0;G<Y.length;G++)c(Y[G]);Object.freeze&&Object.freeze(Y)}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(Y);if(ae.call(P,"key")){Y=s(l);var Be=Object.keys(P).filter(function(Ya){return Ya!=="key"});G=0<Be.length?"{key: someKey, "+Be.join(": ..., ")+": ...}":"{key: someKey}",Fr[Y+G]||(Be=0<Be.length?"{"+Be.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} />`,G,Y,Be,Y),Fr[Y+G]=!0)}if(Y=null,M!==void 0&&(t(M),Y=""+M),i(P)&&(t(P.key),Y=""+P.key),"key"in P){M={};for(var Wn in P)Wn!=="key"&&(M[Wn]=P[Wn])}else M=P;return Y&&o(M,typeof l=="function"?l.displayName||l.name||"Unknown":l),f(l,Y,ue,be,r(),M,jn,Un)}function c(l){typeof l=="object"&&l!==null&&l.$$typeof===h&&l._store&&(l._store.validated=1)}var d=U,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"),$=Symbol.for("react.suspense"),C=Symbol.for("react.suspense_list"),E=Symbol.for("react.memo"),H=Symbol.for("react.lazy"),k=Symbol.for("react.activity"),T=Symbol.for("react.client.reference"),v=d.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ae=Object.prototype.hasOwnProperty,O=Array.isArray,N=console.createTask?console.createTask:function(){return null};d={"react-stack-bottom-frame":function(l){return l()}};var te,Le={},$r=d["react-stack-bottom-frame"].bind(d,a)(),kr=N(n(a)),Fr={};je.Fragment=p,je.jsx=function(l,P,M,G,be){var ue=1e4>v.recentlyCreatedOwnerStacks++;return m(l,P,M,!1,G,be,ue?Error("react-stack-top-frame"):$r,ue?N(n(l)):kr)},je.jsxs=function(l,P,M,G,be){var ue=1e4>v.recentlyCreatedOwnerStacks++;return m(l,P,M,!0,G,be,ue?Error("react-stack-top-frame"):$r,ue?N(n(l)):kr)}}()),je}var Vn;function Lr(){return Vn||(Vn=1,process.env.NODE_ENV==="production"?he.exports=Nr():he.exports=Mr()),he.exports}var Hn=Lr();const Nt="RFC3986",Mt={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:s=>String(s)},Br="RFC1738",Dr=Array.isArray,ie=(()=>{const s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})(),Lt=1024,jr=(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+=Lt){const u=a.length>=Lt?a.slice(o,o+Lt):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||c>=65&&c<=90||c>=97&&c<=122||r===Br&&(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 Ur(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function qn(s,e){if(Dr(s)){const t=[];for(let n=0;n<s.length;n+=1)t.push(e(s[n]));return t}return e(s)}const Wr=Object.prototype.hasOwnProperty,Gn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},oe=Array.isArray,Jr=Array.prototype.push,Yn=function(s,e){Jr.apply(s,oe(e)?e:[e])},Xr=Date.prototype.toISOString,D={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:jr,encodeValuesOnly:!1,format:Nt,formatter:Mt[Nt],indices:!1,serializeDate(s){return Xr.call(s)},skipNulls:!1,strictNullHandling:!1};function Vr(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}const Bt={};function Kn(s,e,t,n,r,a,i,o,u,f,m,c,d,h,y,p,_,B){let g=s,A=B,x=0,$=!1;for(;(A=A.get(Bt))!==void 0&&!$;){const T=A.get(s);if(x+=1,typeof T<"u"){if(T===x)throw new RangeError("Cyclic object value");$=!0}typeof A.get(Bt)>"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=qn(g,function(T){return T instanceof Date?d==null?void 0:d(T):T})),g===null){if(a)return u&&!p?u(e,D.encoder,_,"key",h):e;g=""}if(Vr(g)||Ur(g)){if(u){const T=p?e:u(e,D.encoder,_,"key",h);return[(y==null?void 0:y(T))+"="+(y==null?void 0:y(u(g,D.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=qn(g,u)),E=[{value:g.length>0?g.join(",")||null:void 0}];else if(oe(f))E=f;else{const T=Object.keys(g);E=m?T.sort(m):T}const H=o?String(e).replace(/\./g,"%2E"):String(e),k=n&&oe(g)&&g.length===1?H+"[]":H;if(r&&oe(g)&&g.length===0)return k+"[]";for(let T=0;T<E.length;++T){const v=E[T],ae=typeof v=="object"&&typeof v.value<"u"?v.value:g[v];if(i&&ae===null)continue;const O=c&&o?v.replace(/\./g,"%2E"):v,N=oe(g)?typeof t=="function"?t(k,O):k:k+(c?"."+O:"["+O+"]");B.set(s,x);const te=new WeakMap;te.set(Bt,B),Yn(C,Kn(ae,N,t,n,r,a,i,o,t==="comma"&&p&&oe(g)?null:u,f,m,c,d,h,y,p,_,te))}return C}function Hr(s=D){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||D.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=Nt;if(typeof s.format<"u"){if(!Wr.call(Mt,s.format))throw new TypeError("Unknown format option provided.");t=s.format}const n=Mt[t];let r=D.filter;(typeof s.filter=="function"||oe(s.filter))&&(r=s.filter);let a;if(s.arrayFormat&&s.arrayFormat in Gn?a=s.arrayFormat:"indices"in s?a=s.indices?"indices":"repeat":a=D.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:D.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:D.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:D.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:D.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?D.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:D.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:D.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:D.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:D.encodeValuesOnly,filter:r,format:t,formatter:n,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:D.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:D.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:D.strictNullHandling}}function qr(s,e={}){let t=s;const n=Hr(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=Gn[n.arrayFormat],u=o==="comma"&&n.commaRoundTrip;r||(r=Object.keys(t)),n.sort&&r.sort(n.sort);const f=new WeakMap;for(let d=0;d<r.length;++d){const h=r[d];n.skipNulls&&t[h]===null||Yn(i,Kn(t[h],h,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 Ae="4.100.0";let Qn=!1,Ue,zn,Zn,Dt,es,ts,ns,ss,rs;function Gr(s,e={auto:!1}){if(Qn)throw new Error(`you must \`import 'openai/shims/${s.kind}'\` before importing anything else from openai`);if(Ue)throw new Error(`can't \`import 'openai/shims/${s.kind}'\` after \`import 'openai/shims/${Ue}'\``);Qn=e.auto,Ue=s.kind,zn=s.fetch,Zn=s.FormData,Dt=s.File,es=s.ReadableStream,ts=s.getMultipartRequestOptions,ns=s.getDefaultAgent,ss=s.fileFromPath,rs=s.isFsReadStream}class Yr{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function Kr({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:typeof FormData<"u"?FormData:class{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:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(i,o)=>({...o,body:new Yr(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 as=()=>{Ue||Gr(Kr(),{auto:!0})};as();class b extends Error{}class J extends b{constructor(e,t,n,r){super(`${J.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 st({message:n,cause:Xt(t)});const a=t==null?void 0:t.error;return e===400?new is(e,a,n,r):e===401?new os(e,a,n,r):e===403?new cs(e,a,n,r):e===404?new ls(e,a,n,r):e===409?new us(e,a,n,r):e===422?new fs(e,a,n,r):e===429?new ds(e,a,n,r):e>=500?new hs(e,a,n,r):new J(e,a,n,r)}}class ee extends J{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class st extends J{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class jt extends st{constructor({message:e}={}){super({message:e??"Request timed out."})}}class is extends J{}class os extends J{}class cs extends J{}class ls extends J{}class us extends J{}class fs extends J{}class ds extends J{}class hs extends J{}class ms extends b{constructor(){super("Could not parse response content as the length limit was reached")}}class ps extends b{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var rt=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},xe=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,rt(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=Qr(this.buffer,xe(this,Q,"f")))!=null;){if(a.carriage&&xe(this,Q,"f")==null){rt(this,Q,a.index,"f");continue}if(xe(this,Q,"f")!=null&&(a.index!==xe(this,Q,"f")+1||a.carriage)){r.push(this.decodeText(this.buffer.slice(0,xe(this,Q,"f")-1))),this.buffer=this.buffer.slice(xe(this,Q,"f")),rt(this,Q,null,"f");continue}const i=xe(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),rt(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=new WeakMap,at.NEWLINE_CHARS=new Set([`
`,"\r"]),at.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Qr(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 zr(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 gs(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 ce{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 Zr(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 J(void 0,o.error,void 0,As(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 J(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 ce(r,t)}static fromReadableStream(e,t){let n=!1;async function*r(){const i=new at,o=gs(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 ce(a,t)}[Symbol.asyncIterator](){return this.iterator()}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 ce(()=>r(e),this.controller),new ce(()=>r(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new es({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*Zr(s,e){if(!s.body)throw e.abort(),new b("Attempted to iterate over a response with no body");const t=new ta,n=new at,r=gs(s.body);for await(const a of ea(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*ea(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=zr(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class ta{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]=na(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function na(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}const _s=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function",ws=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&it(s),it=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",sa=s=>ws(s)||_s(s)||rs(s);async function ys(s,e,t){var r;if(s=await s,ws(s))return s;if(_s(s)){const a=await s.blob();e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()??"unknown_file");const i=it(a)?[await a.arrayBuffer()]:[a];return new Dt(i,e,t)}const n=await ra(s);if(e||(e=ia(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 Dt(n,e,t)}async function ra(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(it(s))e.push(await s.arrayBuffer());else if(oa(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: ${aa(s)}`);return e}function aa(s){return`[${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}function ia(s){var e;return Ut(s.name)||Ut(s.filename)||((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)},oa=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",bs=s=>s&&typeof s=="object"&&s.body&&s[Symbol.toStringTag]==="MultipartBody",Ee=async s=>{const e=await ca(s.body);return ts(e,s)},ca=async s=>{const e=new Zn;return await Promise.all(Object.entries(s||{}).map(([t,n])=>Wt(e,t,n))),e},Wt=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(sa(t)){const n=await ys(t);s.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>Wt(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>Wt(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 la=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},ua=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)},ot;as();async function xs(s){var i;const{response:e}=s;if(s.options.stream)return me("response",e.status,e.url,e.headers,e.body),s.options.__streamClass?s.options.__streamClass.fromSSEResponse(e,s.controller):ce.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 me("response",e.status,e.url,e.headers,o),Ss(o,e)}const a=await e.text();return me("response",e.status,e.url,e.headers,a),a}function Ss(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 ct extends Promise{constructor(e,t=xs){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new ct(this.responsePromise,async t=>Ss(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 fa{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:r,fetch:a}){this.baseURL=e,this.maxRetries=Jt("maxRetries",t),this.timeout=Jt("timeout",n),this.httpAgent=r,this.fetch=a??zn}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...ga(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${ba()}`}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&&it(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:bs(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&&Jt("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const c=n.httpAgent??this.httpAgent??ns(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},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 Is(a,i),Is(a,t),bs(e.body)&&Ue!=="node"&&delete a["content-type"],ut(i,"x-stainless-retry-count")===void 0&&ut(t,"x-stainless-retry-count")===void 0&&(a["x-stainless-retry-count"]=String(r)),ut(i,"x-stainless-timeout")===void 0&&ut(t,"x-stainless-timeout")===void 0&&e.timeout&&(a["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(a,t),a}async prepareOptions(e){}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 J.generate(e,t,n,r)}request(e,t=null){return new ct(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}),me("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(Xt);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 jt:new st({cause:f})}const m=As(f.headers);if(!f.ok){if(t&&this.shouldRetry(f)){const g=`retrying, ${t} attempts remaining`;return me(`response (error; ${g})`,f.status,i,m),this.retryRequest(n,t,m)}const h=await f.text().catch(g=>Xt(g).message),y=_a(h),p=y?void 0:h;throw me(`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 da(this,n,e)}buildURL(e,t){const n=ya(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery();return vs(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()),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 We(r),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Ae}`}}class Rs{constructor(e,t,n,r){ot.set(this,void 0),la(this,ot,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 ua(this,ot,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ot=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class da extends ct{constructor(e,t,n){super(t,async r=>new n(e,r.response,await xs(r),r.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const As=s=>new Proxy(Object.fromEntries(s.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),ha={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&&!vs(s)&&Object.keys(s).every(e=>Os(ha,e)),ma=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ae,"X-Stainless-OS":Ps(Deno.build.os),"X-Stainless-Arch":Es(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":Ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ae,"X-Stainless-OS":Ps(process.platform),"X-Stainless-Arch":Es(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const s=pa();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${s.browser}`,"X-Stainless-Runtime-Version":s.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ae,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function pa(){if(typeof navigator>"u"||!navigator)return null;const s=[{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:e,pattern:t}of s){const n=t.exec(navigator.userAgent);if(n){const r=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${r}.${a}.${i}`}}}return null}const Es=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Ps=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown");let Cs;const ga=()=>Cs??(Cs=ma()),_a=s=>{try{return JSON.parse(s)}catch{return}},wa=/^[a-z][a-z0-9+.-]*:/i,ya=s=>wa.test(s),We=s=>new Promise(e=>setTimeout(e,s)),Jt=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new b(`${s} must be an integer`);if(e<0)throw new b(`${s} must be a positive integer`);return e},Xt=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null)try{return new Error(JSON.stringify(s))}catch{}return new Error(s)},lt=s=>{var e,t,n,r,a;if(typeof process<"u")return((t=(e=process.env)==null?void 0:e[s])==null?void 0:t.trim())??void 0;if(typeof Deno<"u")return(a=(r=(n=Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,s))==null?void 0:a.trim()};function vs(s){if(!s)return!0;for(const e in s)return!1;return!0}function Os(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Is(s,e){for(const t in e){if(!Os(e,t))continue;const n=t.toLowerCase();if(!n)continue;const r=e[t];r===null?delete s[n]:r!==void 0&&(s[n]=r)}}const Ts=new Set(["authorization","api-key"]);function me(s,...e){var t;if(typeof process<"u"&&((t=process==null?void 0:process.env)==null?void 0:t.DEBUG)==="true"){const n=e.map(r=>{if(!r)return r;if(r.headers){const i={...r,headers:{...r.headers}};for(const o in r.headers)Ts.has(o.toLowerCase())&&(i.headers[o]="REDACTED");return i}let a=null;for(const i in r)Ts.has(i.toLowerCase())&&(a??(a={...r}),a[i]="REDACTED");return a??r});console.log(`OpenAI:DEBUG:${s}`,...n)}}const ba=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)}),xa=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Sa=s=>typeof(s==null?void 0:s.get)=="function",ut=(s,e)=>{var n;const t=e.toLowerCase();if(Sa(s)){const r=((n=e[0])==null?void 0:n.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(a,i,o)=>i+o.toUpperCase());for(const a of[e,t,e.toUpperCase(),r]){const i=s.get(a);if(i)return i}}for(const[r,a]of Object.entries(s))if(r.toLowerCase()===t)return Array.isArray(a)?(a.length<=1||console.warn(`Received ${a.length} entries for the ${e} header, using the first entry.`),a[0]):a},Ra=s=>{if(typeof Buffer<"u"){const e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(s),t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return Array.from(new Float32Array(n.buffer))}};function Vt(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}class ft extends Rs{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class X extends Rs{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}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(){var n;const e=this.getPaginatedItems();if(!e.length)return null;const t=(n=e[e.length-1])==null?void 0:n.id;return t?{params:{after:t}}:null}}class S{constructor(e){this._client=e}}let $s=class extends S{list(e,t={},n){return L(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Aa,{query:t,...n})}},dt=class extends S{constructor(){super(...arguments),this.messages=new $s(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return L(e)?this.list({},e):this._client.getAPIList("/chat/completions",ht,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class ht extends X{}class Aa extends X{}dt.ChatCompletionsPage=ht,dt.Messages=$s;let mt=class extends S{constructor(){super(...arguments),this.completions=new dt(this._client)}};mt.Completions=dt,mt.ChatCompletionsPage=ht;class ks extends S{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t==null?void 0:t.headers},__binaryResponse:!0})}}class Fs extends S{create(e,t){return this._client.post("/audio/transcriptions",Ee({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Ns extends S{create(e,t){return this._client.post("/audio/translations",Ee({body:e,...t,__metadata:{model:e.model}}))}}class Je extends S{constructor(){super(...arguments),this.transcriptions=new Fs(this._client),this.translations=new Ns(this._client),this.speech=new ks(this._client)}}Je.Transcriptions=Fs,Je.Translations=Ns,Je.Speech=ks;class Ht extends S{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 L(e)?this.list({},e):this._client.getAPIList("/batches",qt,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class qt extends X{}Ht.BatchesPage=qt;var ne=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},F=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)},Gt,pt,gt,Xe,Ve,_t,He,fe,qe,wt,yt,Pe,Ms;class Yt{constructor(){Gt.add(this),this.controller=new AbortController,pt.set(this,void 0),gt.set(this,()=>{}),Xe.set(this,()=>{}),Ve.set(this,void 0),_t.set(this,()=>{}),He.set(this,()=>{}),fe.set(this,{}),qe.set(this,!1),wt.set(this,!1),yt.set(this,!1),Pe.set(this,!1),ne(this,pt,new Promise((e,t)=>{ne(this,gt,e,"f"),ne(this,Xe,t,"f")}),"f"),ne(this,Ve,new Promise((e,t)=>{ne(this,_t,e,"f"),ne(this,He,t,"f")}),"f"),F(this,pt,"f").catch(()=>{}),F(this,Ve,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},F(this,Gt,"m",Ms).bind(this))},0)}_connected(){this.ended||(F(this,gt,"f").call(this),this._emit("connect"))}get ended(){return F(this,qe,"f")}get errored(){return F(this,wt,"f")}get aborted(){return F(this,yt,"f")}abort(){this.controller.abort()}on(e,t){return(F(this,fe,"f")[e]||(F(this,fe,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=F(this,fe,"f")[e];if(!n)return this;const r=n.findIndex(a=>a.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(F(this,fe,"f")[e]||(F(this,fe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{ne(this,Pe,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){ne(this,Pe,!0,"f"),await F(this,Ve,"f")}_emit(e,...t){if(F(this,qe,"f"))return;e==="end"&&(ne(this,qe,!0,"f"),F(this,_t,"f").call(this));const n=F(this,fe,"f")[e];if(n&&(F(this,fe,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!F(this,Pe,"f")&&!(n!=null&&n.length)&&Promise.reject(r),F(this,Xe,"f").call(this,r),F(this,He,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!F(this,Pe,"f")&&!(n!=null&&n.length)&&Promise.reject(r),F(this,Xe,"f").call(this,r),F(this,He,"f").call(this,r),this._emit("end")}}_emitFinal(){}}pt=new WeakMap,gt=new WeakMap,Xe=new WeakMap,Ve=new WeakMap,_t=new WeakMap,He=new WeakMap,fe=new WeakMap,qe=new WeakMap,wt=new WeakMap,yt=new WeakMap,Pe=new WeakMap,Gt=new WeakSet,Ms=function(e){if(ne(this,wt,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new ee),e instanceof ee)return ne(this,yt,!0,"f"),this._emit("abort",e);if(e instanceof b)return this._emit("error",e);if(e instanceof Error){const t=new b(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new b(String(e)))};var w=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)},z=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},V,Kt,le,bt,se,Se,Ce,Re,xt,Z,St,Rt,Ge,Ye,Ke,Ls,Bs,Ds,js,Us,Ws,Js;class re extends Yt{constructor(){super(...arguments),V.add(this),Kt.set(this,[]),le.set(this,{}),bt.set(this,{}),se.set(this,void 0),Se.set(this,void 0),Ce.set(this,void 0),Re.set(this,void 0),xt.set(this,void 0),Z.set(this,void 0),St.set(this,void 0),Rt.set(this,void 0),Ge.set(this,void 0)}[(Kt=new WeakMap,le=new WeakMap,bt=new WeakMap,se=new WeakMap,Se=new WeakMap,Ce=new WeakMap,Re=new WeakMap,xt=new WeakMap,Z=new WeakMap,St=new WeakMap,Rt=new WeakMap,Ge=new WeakMap,V=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",r=>{const a=t.shift();a?a.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const a of t)a.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new re;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var a;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=ce.fromReadableStream(e,this.controller);for await(const i of r)w(this,V,"m",Ye).call(this,i);if((a=r.controller.signal)!=null&&a.aborted)throw new ee;return this._addRun(w(this,V,"m",Ke).call(this))}toReadableStream(){return new ce(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r,a){const i=new re;return i._run(()=>i._runToolAssistantStream(e,t,n,r,{...a,headers:{...a==null?void 0:a.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,n,r,a){var f;const i=a==null?void 0:a.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const o={...r,stream:!0},u=await e.submitToolOutputs(t,n,o,{...a,signal:this.controller.signal});this._connected();for await(const m of u)w(this,V,"m",Ye).call(this,m);if((f=u.controller.signal)!=null&&f.aborted)throw new ee;return this._addRun(w(this,V,"m",Ke).call(this))}static createThreadAssistantStream(e,t,n){const r=new re;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,n,r){const a=new re;return a._run(()=>a._runAssistantStream(e,t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return w(this,St,"f")}currentRun(){return w(this,Rt,"f")}currentMessageSnapshot(){return w(this,se,"f")}currentRunStepSnapshot(){return w(this,Ge,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,le,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,bt,"f"))}async finalRun(){if(await this.done(),!w(this,Se,"f"))throw Error("Final run was not received.");return w(this,Se,"f")}async _createThreadAssistantStream(e,t,n){var o;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},i=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(const u of i)w(this,V,"m",Ye).call(this,u);if((o=i.controller.signal)!=null&&o.aborted)throw new ee;return this._addRun(w(this,V,"m",Ke).call(this))}async _createAssistantStream(e,t,n,r){var u;const a=r==null?void 0:r.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},o=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(const f of o)w(this,V,"m",Ye).call(this,f);if((u=o.controller.signal)!=null&&u.aborted)throw new ee;return this._addRun(w(this,V,"m",Ke).call(this))}static accumulateDelta(e,t){for(const[n,r]of Object