/**
 * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0.
 * Original file: /npm/openai@4.47.1/index.mjs
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
import*as t from"/npm/openai@4.47.1/_shims/auto/runtime/+esm";import{APIError as e,APIUserAbortError as n,OpenAIError as r}from"/npm/openai@4.47.1/error/+esm";import{Stream as s}from"/npm/openai@4.47.1/streaming/+esm";import*as i from"/npm/openai@4.47.1/core/+esm";var o="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function a(){throw new Error("setTimeout has not been defined")}function c(){throw new Error("clearTimeout has not been defined")}var l=a,h=c;function u(t){if(l===setTimeout)return setTimeout(t,0);if((l===a||!l)&&setTimeout)return l=setTimeout,setTimeout(t,0);try{return l(t,0)}catch(e){try{return l.call(null,t,0)}catch(e){return l.call(this,t,0)}}}"function"==typeof o.setTimeout&&(l=setTimeout),"function"==typeof o.clearTimeout&&(h=clearTimeout);var f,d=[],p=!1,m=-1;function g(){p&&f&&(p=!1,f.length?d=f.concat(d):m=-1,d.length&&w())}function w(){if(!p){var t=u(g);p=!0;for(var e=d.length;e;){for(f=d,d=[];++m<e;)f&&f[m].run();m=-1,e=d.length}f=null,p=!1,function(t){if(h===clearTimeout)return clearTimeout(t);if((h===c||!h)&&clearTimeout)return h=clearTimeout,clearTimeout(t);try{return h(t)}catch(e){try{return h.call(null,t)}catch(e){return h.call(this,t)}}}(t)}}function y(t,e){this.fun=t,this.array=e}y.prototype.run=function(){this.fun.apply(null,this.array)};function _(){}var b=_,v=_,A=_,E=_,P=_,R=_,S=_;var x=o.performance||{},I=x.now||x.mozNow||x.msNow||x.oNow||x.webkitNow||function(){return(new Date).getTime()};var T=new Date;var C={nextTick:function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];d.push(new y(t,e)),1!==d.length||p||u(w)},title:"browser",browser:!0,env:{},argv:[],version:"",versions:{},on:b,addListener:v,once:A,off:E,removeListener:P,removeAllListeners:R,emit:S,binding:function(t){throw new Error("process.binding is not supported")},cwd:function(){return"/"},chdir:function(t){throw new Error("process.chdir is not supported")},umask:function(){return 0},hrtime:function(t){var e=.001*I.call(x),n=Math.floor(e),r=Math.floor(e%1*1e9);return t&&(n-=t[0],(r-=t[1])<0&&(n--,r+=1e9)),[n,r]},platform:"browser",release:{},config:{},uptime:function(){return(new Date-T)/1e3}},O=[],k=[],M="undefined"!=typeof Uint8Array?Uint8Array:Array,$=!1;function B(){$=!0;for(var t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=0;e<64;++e)O[e]=t[e],k[t.charCodeAt(e)]=e;k["-".charCodeAt(0)]=62,k["_".charCodeAt(0)]=63}function U(t,e,n){for(var r,s,i=[],o=e;o<n;o+=3)r=(t[o]<<16)+(t[o+1]<<8)+t[o+2],i.push(O[(s=r)>>18&63]+O[s>>12&63]+O[s>>6&63]+O[63&s]);return i.join("")}function L(t){var e;$||B();for(var n=t.length,r=n%3,s="",i=[],o=16383,a=0,c=n-r;a<c;a+=o)i.push(U(t,a,a+o>c?c:a+o));return 1===r?(e=t[n-1],s+=O[e>>2],s+=O[e<<4&63],s+="=="):2===r&&(e=(t[n-2]<<8)+t[n-1],s+=O[e>>10],s+=O[e>>4&63],s+=O[e<<2&63],s+="="),i.push(s),i.join("")}function j(t,e,n,r,s){var i,o,a=8*s-r-1,c=(1<<a)-1,l=c>>1,h=-7,u=n?s-1:0,f=n?-1:1,d=t[e+u];for(u+=f,i=d&(1<<-h)-1,d>>=-h,h+=a;h>0;i=256*i+t[e+u],u+=f,h-=8);for(o=i&(1<<-h)-1,i>>=-h,h+=r;h>0;o=256*o+t[e+u],u+=f,h-=8);if(0===i)i=1-l;else{if(i===c)return o?NaN:1/0*(d?-1:1);o+=Math.pow(2,r),i-=l}return(d?-1:1)*o*Math.pow(2,i-r)}function D(t,e,n,r,s,i){var o,a,c,l=8*i-s-1,h=(1<<l)-1,u=h>>1,f=23===s?Math.pow(2,-24)-Math.pow(2,-77):0,d=r?0:i-1,p=r?1:-1,m=e<0||0===e&&1/e<0?1:0;for(e=Math.abs(e),isNaN(e)||e===1/0?(a=isNaN(e)?1:0,o=h):(o=Math.floor(Math.log(e)/Math.LN2),e*(c=Math.pow(2,-o))<1&&(o--,c*=2),(e+=o+u>=1?f/c:f*Math.pow(2,1-u))*c>=2&&(o++,c/=2),o+u>=h?(a=0,o=h):o+u>=1?(a=(e*c-1)*Math.pow(2,s),o+=u):(a=e*Math.pow(2,u-1)*Math.pow(2,s),o=0));s>=8;t[n+d]=255&a,d+=p,a/=256,s-=8);for(o=o<<s|a,l+=s;l>0;t[n+d]=255&o,d+=p,o/=256,l-=8);t[n+d-p]|=128*m}var N={}.toString,q=Array.isArray||function(t){return"[object Array]"==N.call(t)};function W(){return Y.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function F(t,e){if(W()<e)throw new RangeError("Invalid typed array length");return Y.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(e)).__proto__=Y.prototype:(null===t&&(t=new Y(e)),t.length=e),t}function Y(t,e,n){if(!(Y.TYPED_ARRAY_SUPPORT||this instanceof Y))return new Y(t,e,n);if("number"==typeof t){if("string"==typeof e)throw new Error("If encoding is specified then the first argument must be a string");return H(this,t)}return X(this,t,e,n)}function X(t,e,n,r){if("number"==typeof e)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer?function(t,e,n,r){if(e.byteLength,n<0||e.byteLength<n)throw new RangeError("'offset' is out of bounds");if(e.byteLength<n+(r||0))throw new RangeError("'length' is out of bounds");e=void 0===n&&void 0===r?new Uint8Array(e):void 0===r?new Uint8Array(e,n):new Uint8Array(e,n,r);Y.TYPED_ARRAY_SUPPORT?(t=e).__proto__=Y.prototype:t=J(t,e);return t}(t,e,n,r):"string"==typeof e?function(t,e,n){"string"==typeof n&&""!==n||(n="utf8");if(!Y.isEncoding(n))throw new TypeError('"encoding" must be a valid string encoding');var r=0|G(e,n);t=F(t,r);var s=t.write(e,n);s!==r&&(t=t.slice(0,s));return t}(t,e,n):function(t,e){if(K(e)){var n=0|V(e.length);return 0===(t=F(t,n)).length||e.copy(t,0,0,n),t}if(e){if("undefined"!=typeof ArrayBuffer&&e.buffer instanceof ArrayBuffer||"length"in e)return"number"!=typeof e.length||(r=e.length)!=r?F(t,0):J(t,e);if("Buffer"===e.type&&q(e.data))return J(t,e.data)}var r;throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}(t,e)}function z(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function H(t,e){if(z(e),t=F(t,e<0?0:0|V(e)),!Y.TYPED_ARRAY_SUPPORT)for(var n=0;n<e;++n)t[n]=0;return t}function J(t,e){var n=e.length<0?0:0|V(e.length);t=F(t,n);for(var r=0;r<n;r+=1)t[r]=255&e[r];return t}function V(t){if(t>=W())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+W().toString(16)+" bytes");return 0|t}function K(t){return!(null==t||!t._isBuffer)}function G(t,e){if(K(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var n=t.length;if(0===n)return 0;for(var r=!1;;)switch(e){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":case void 0:return Pt(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return Rt(t).length;default:if(r)return Pt(t).length;e=(""+e).toLowerCase(),r=!0}}function Q(t,e,n){var r=!1;if((void 0===e||e<0)&&(e=0),e>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(e>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return dt(this,e,n);case"utf8":case"utf-8":return lt(this,e,n);case"ascii":return ut(this,e,n);case"latin1":case"binary":return ft(this,e,n);case"base64":return ct(this,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return pt(this,e,n);default:if(r)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),r=!0}}function Z(t,e,n){var r=t[e];t[e]=t[n],t[n]=r}function tt(t,e,n,r,s){if(0===t.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),n=+n,isNaN(n)&&(n=s?0:t.length-1),n<0&&(n=t.length+n),n>=t.length){if(s)return-1;n=t.length-1}else if(n<0){if(!s)return-1;n=0}if("string"==typeof e&&(e=Y.from(e,r)),K(e))return 0===e.length?-1:et(t,e,n,r,s);if("number"==typeof e)return e&=255,Y.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?s?Uint8Array.prototype.indexOf.call(t,e,n):Uint8Array.prototype.lastIndexOf.call(t,e,n):et(t,[e],n,r,s);throw new TypeError("val must be string, number or Buffer")}function et(t,e,n,r,s){var i,o=1,a=t.length,c=e.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(t.length<2||e.length<2)return-1;o=2,a/=2,c/=2,n/=2}function l(t,e){return 1===o?t[e]:t.readUInt16BE(e*o)}if(s){var h=-1;for(i=n;i<a;i++)if(l(t,i)===l(e,-1===h?0:i-h)){if(-1===h&&(h=i),i-h+1===c)return h*o}else-1!==h&&(i-=i-h),h=-1}else for(n+c>a&&(n=a-c),i=n;i>=0;i--){for(var u=!0,f=0;f<c;f++)if(l(t,i+f)!==l(e,f)){u=!1;break}if(u)return i}return-1}function nt(t,e,n,r){n=Number(n)||0;var s=t.length-n;r?(r=Number(r))>s&&(r=s):r=s;var i=e.length;if(i%2!=0)throw new TypeError("Invalid hex string");r>i/2&&(r=i/2);for(var o=0;o<r;++o){var a=parseInt(e.substr(2*o,2),16);if(isNaN(a))return o;t[n+o]=a}return o}function rt(t,e,n,r){return St(Pt(e,t.length-n),t,n,r)}function st(t,e,n,r){return St(function(t){for(var e=[],n=0;n<t.length;++n)e.push(255&t.charCodeAt(n));return e}(e),t,n,r)}function it(t,e,n,r){return st(t,e,n,r)}function ot(t,e,n,r){return St(Rt(e),t,n,r)}function at(t,e,n,r){return St(function(t,e){for(var n,r,s,i=[],o=0;o<t.length&&!((e-=2)<0);++o)r=(n=t.charCodeAt(o))>>8,s=n%256,i.push(s),i.push(r);return i}(e,t.length-n),t,n,r)}function ct(t,e,n){return 0===e&&n===t.length?L(t):L(t.slice(e,n))}function lt(t,e,n){n=Math.min(t.length,n);for(var r=[],s=e;s<n;){var i,o,a,c,l=t[s],h=null,u=l>239?4:l>223?3:l>191?2:1;if(s+u<=n)switch(u){case 1:l<128&&(h=l);break;case 2:128==(192&(i=t[s+1]))&&(c=(31&l)<<6|63&i)>127&&(h=c);break;case 3:i=t[s+1],o=t[s+2],128==(192&i)&&128==(192&o)&&(c=(15&l)<<12|(63&i)<<6|63&o)>2047&&(c<55296||c>57343)&&(h=c);break;case 4:i=t[s+1],o=t[s+2],a=t[s+3],128==(192&i)&&128==(192&o)&&128==(192&a)&&(c=(15&l)<<18|(63&i)<<12|(63&o)<<6|63&a)>65535&&c<1114112&&(h=c)}null===h?(h=65533,u=1):h>65535&&(h-=65536,r.push(h>>>10&1023|55296),h=56320|1023&h),r.push(h),s+=u}return function(t){var e=t.length;if(e<=ht)return String.fromCharCode.apply(String,t);var n="",r=0;for(;r<e;)n+=String.fromCharCode.apply(String,t.slice(r,r+=ht));return n}(r)}Y.TYPED_ARRAY_SUPPORT=void 0===o.TYPED_ARRAY_SUPPORT||o.TYPED_ARRAY_SUPPORT,W(),Y.poolSize=8192,Y._augment=function(t){return t.__proto__=Y.prototype,t},Y.from=function(t,e,n){return X(null,t,e,n)},Y.TYPED_ARRAY_SUPPORT&&(Y.prototype.__proto__=Uint8Array.prototype,Y.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&Y[Symbol.species]),Y.alloc=function(t,e,n){return function(t,e,n,r){return z(e),e<=0?F(t,e):void 0!==n?"string"==typeof r?F(t,e).fill(n,r):F(t,e).fill(n):F(t,e)}(null,t,e,n)},Y.allocUnsafe=function(t){return H(null,t)},Y.allocUnsafeSlow=function(t){return H(null,t)},Y.isBuffer=function(t){return null!=t&&(!!t._isBuffer||xt(t)||function(t){return"function"==typeof t.readFloatLE&&"function"==typeof t.slice&&xt(t.slice(0,0))}(t))},Y.compare=function(t,e){if(!K(t)||!K(e))throw new TypeError("Arguments must be Buffers");if(t===e)return 0;for(var n=t.length,r=e.length,s=0,i=Math.min(n,r);s<i;++s)if(t[s]!==e[s]){n=t[s],r=e[s];break}return n<r?-1:r<n?1:0},Y.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},Y.concat=function(t,e){if(!q(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return Y.alloc(0);var n;if(void 0===e)for(e=0,n=0;n<t.length;++n)e+=t[n].length;var r=Y.allocUnsafe(e),s=0;for(n=0;n<t.length;++n){var i=t[n];if(!K(i))throw new TypeError('"list" argument must be an Array of Buffers');i.copy(r,s),s+=i.length}return r},Y.byteLength=G,Y.prototype._isBuffer=!0,Y.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var e=0;e<t;e+=2)Z(this,e,e+1);return this},Y.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var e=0;e<t;e+=4)Z(this,e,e+3),Z(this,e+1,e+2);return this},Y.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var e=0;e<t;e+=8)Z(this,e,e+7),Z(this,e+1,e+6),Z(this,e+2,e+5),Z(this,e+3,e+4);return this},Y.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?lt(this,0,t):Q.apply(this,arguments)},Y.prototype.equals=function(t){if(!K(t))throw new TypeError("Argument must be a Buffer");return this===t||0===Y.compare(this,t)},Y.prototype.inspect=function(){var t="";return this.length>0&&(t=this.toString("hex",0,50).match(/.{2}/g).join(" "),this.length>50&&(t+=" ... ")),"<Buffer "+t+">"},Y.prototype.compare=function(t,e,n,r,s){if(!K(t))throw new TypeError("Argument must be a Buffer");if(void 0===e&&(e=0),void 0===n&&(n=t?t.length:0),void 0===r&&(r=0),void 0===s&&(s=this.length),e<0||n>t.length||r<0||s>this.length)throw new RangeError("out of range index");if(r>=s&&e>=n)return 0;if(r>=s)return-1;if(e>=n)return 1;if(this===t)return 0;for(var i=(s>>>=0)-(r>>>=0),o=(n>>>=0)-(e>>>=0),a=Math.min(i,o),c=this.slice(r,s),l=t.slice(e,n),h=0;h<a;++h)if(c[h]!==l[h]){i=c[h],o=l[h];break}return i<o?-1:o<i?1:0},Y.prototype.includes=function(t,e,n){return-1!==this.indexOf(t,e,n)},Y.prototype.indexOf=function(t,e,n){return tt(this,t,e,n,!0)},Y.prototype.lastIndexOf=function(t,e,n){return tt(this,t,e,n,!1)},Y.prototype.write=function(t,e,n,r){if(void 0===e)r="utf8",n=this.length,e=0;else if(void 0===n&&"string"==typeof e)r=e,n=this.length,e=0;else{if(!isFinite(e))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");e|=0,isFinite(n)?(n|=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}var s=this.length-e;if((void 0===n||n>s)&&(n=s),t.length>0&&(n<0||e<0)||e>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");for(var i=!1;;)switch(r){case"hex":return nt(this,t,e,n);case"utf8":case"utf-8":return rt(this,t,e,n);case"ascii":return st(this,t,e,n);case"latin1":case"binary":return it(this,t,e,n);case"base64":return ot(this,t,e,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return at(this,t,e,n);default:if(i)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),i=!0}},Y.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ht=4096;function ut(t,e,n){var r="";n=Math.min(t.length,n);for(var s=e;s<n;++s)r+=String.fromCharCode(127&t[s]);return r}function ft(t,e,n){var r="";n=Math.min(t.length,n);for(var s=e;s<n;++s)r+=String.fromCharCode(t[s]);return r}function dt(t,e,n){var r=t.length;(!e||e<0)&&(e=0),(!n||n<0||n>r)&&(n=r);for(var s="",i=e;i<n;++i)s+=Et(t[i]);return s}function pt(t,e,n){for(var r=t.slice(e,n),s="",i=0;i<r.length;i+=2)s+=String.fromCharCode(r[i]+256*r[i+1]);return s}function mt(t,e,n){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+e>n)throw new RangeError("Trying to access beyond buffer length")}function gt(t,e,n,r,s,i){if(!K(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(e>s||e<i)throw new RangeError('"value" argument is out of bounds');if(n+r>t.length)throw new RangeError("Index out of range")}function wt(t,e,n,r){e<0&&(e=65535+e+1);for(var s=0,i=Math.min(t.length-n,2);s<i;++s)t[n+s]=(e&255<<8*(r?s:1-s))>>>8*(r?s:1-s)}function yt(t,e,n,r){e<0&&(e=4294967295+e+1);for(var s=0,i=Math.min(t.length-n,4);s<i;++s)t[n+s]=e>>>8*(r?s:3-s)&255}function _t(t,e,n,r,s,i){if(n+r>t.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function bt(t,e,n,r,s){return s||_t(t,0,n,4),D(t,e,n,r,23,4),n+4}function vt(t,e,n,r,s){return s||_t(t,0,n,8),D(t,e,n,r,52,8),n+8}Y.prototype.slice=function(t,e){var n,r=this.length;if((t=~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),(e=void 0===e?r:~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),e<t&&(e=t),Y.TYPED_ARRAY_SUPPORT)(n=this.subarray(t,e)).__proto__=Y.prototype;else{var s=e-t;n=new Y(s,void 0);for(var i=0;i<s;++i)n[i]=this[i+t]}return n},Y.prototype.readUIntLE=function(t,e,n){t|=0,e|=0,n||mt(t,e,this.length);for(var r=this[t],s=1,i=0;++i<e&&(s*=256);)r+=this[t+i]*s;return r},Y.prototype.readUIntBE=function(t,e,n){t|=0,e|=0,n||mt(t,e,this.length);for(var r=this[t+--e],s=1;e>0&&(s*=256);)r+=this[t+--e]*s;return r},Y.prototype.readUInt8=function(t,e){return e||mt(t,1,this.length),this[t]},Y.prototype.readUInt16LE=function(t,e){return e||mt(t,2,this.length),this[t]|this[t+1]<<8},Y.prototype.readUInt16BE=function(t,e){return e||mt(t,2,this.length),this[t]<<8|this[t+1]},Y.prototype.readUInt32LE=function(t,e){return e||mt(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},Y.prototype.readUInt32BE=function(t,e){return e||mt(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},Y.prototype.readIntLE=function(t,e,n){t|=0,e|=0,n||mt(t,e,this.length);for(var r=this[t],s=1,i=0;++i<e&&(s*=256);)r+=this[t+i]*s;return r>=(s*=128)&&(r-=Math.pow(2,8*e)),r},Y.prototype.readIntBE=function(t,e,n){t|=0,e|=0,n||mt(t,e,this.length);for(var r=e,s=1,i=this[t+--r];r>0&&(s*=256);)i+=this[t+--r]*s;return i>=(s*=128)&&(i-=Math.pow(2,8*e)),i},Y.prototype.readInt8=function(t,e){return e||mt(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},Y.prototype.readInt16LE=function(t,e){e||mt(t,2,this.length);var n=this[t]|this[t+1]<<8;return 32768&n?4294901760|n:n},Y.prototype.readInt16BE=function(t,e){e||mt(t,2,this.length);var n=this[t+1]|this[t]<<8;return 32768&n?4294901760|n:n},Y.prototype.readInt32LE=function(t,e){return e||mt(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},Y.prototype.readInt32BE=function(t,e){return e||mt(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},Y.prototype.readFloatLE=function(t,e){return e||mt(t,4,this.length),j(this,t,!0,23,4)},Y.prototype.readFloatBE=function(t,e){return e||mt(t,4,this.length),j(this,t,!1,23,4)},Y.prototype.readDoubleLE=function(t,e){return e||mt(t,8,this.length),j(this,t,!0,52,8)},Y.prototype.readDoubleBE=function(t,e){return e||mt(t,8,this.length),j(this,t,!1,52,8)},Y.prototype.writeUIntLE=function(t,e,n,r){(t=+t,e|=0,n|=0,r)||gt(this,t,e,n,Math.pow(2,8*n)-1,0);var s=1,i=0;for(this[e]=255&t;++i<n&&(s*=256);)this[e+i]=t/s&255;return e+n},Y.prototype.writeUIntBE=function(t,e,n,r){(t=+t,e|=0,n|=0,r)||gt(this,t,e,n,Math.pow(2,8*n)-1,0);var s=n-1,i=1;for(this[e+s]=255&t;--s>=0&&(i*=256);)this[e+s]=t/i&255;return e+n},Y.prototype.writeUInt8=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,1,255,0),Y.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[e]=255&t,e+1},Y.prototype.writeUInt16LE=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,2,65535,0),Y.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):wt(this,t,e,!0),e+2},Y.prototype.writeUInt16BE=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,2,65535,0),Y.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):wt(this,t,e,!1),e+2},Y.prototype.writeUInt32LE=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,4,4294967295,0),Y.TYPED_ARRAY_SUPPORT?(this[e+3]=t>>>24,this[e+2]=t>>>16,this[e+1]=t>>>8,this[e]=255&t):yt(this,t,e,!0),e+4},Y.prototype.writeUInt32BE=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,4,4294967295,0),Y.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):yt(this,t,e,!1),e+4},Y.prototype.writeIntLE=function(t,e,n,r){if(t=+t,e|=0,!r){var s=Math.pow(2,8*n-1);gt(this,t,e,n,s-1,-s)}var i=0,o=1,a=0;for(this[e]=255&t;++i<n&&(o*=256);)t<0&&0===a&&0!==this[e+i-1]&&(a=1),this[e+i]=(t/o|0)-a&255;return e+n},Y.prototype.writeIntBE=function(t,e,n,r){if(t=+t,e|=0,!r){var s=Math.pow(2,8*n-1);gt(this,t,e,n,s-1,-s)}var i=n-1,o=1,a=0;for(this[e+i]=255&t;--i>=0&&(o*=256);)t<0&&0===a&&0!==this[e+i+1]&&(a=1),this[e+i]=(t/o|0)-a&255;return e+n},Y.prototype.writeInt8=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,1,127,-128),Y.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[e]=255&t,e+1},Y.prototype.writeInt16LE=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,2,32767,-32768),Y.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8):wt(this,t,e,!0),e+2},Y.prototype.writeInt16BE=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,2,32767,-32768),Y.TYPED_ARRAY_SUPPORT?(this[e]=t>>>8,this[e+1]=255&t):wt(this,t,e,!1),e+2},Y.prototype.writeInt32LE=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,4,2147483647,-2147483648),Y.TYPED_ARRAY_SUPPORT?(this[e]=255&t,this[e+1]=t>>>8,this[e+2]=t>>>16,this[e+3]=t>>>24):yt(this,t,e,!0),e+4},Y.prototype.writeInt32BE=function(t,e,n){return t=+t,e|=0,n||gt(this,t,e,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),Y.TYPED_ARRAY_SUPPORT?(this[e]=t>>>24,this[e+1]=t>>>16,this[e+2]=t>>>8,this[e+3]=255&t):yt(this,t,e,!1),e+4},Y.prototype.writeFloatLE=function(t,e,n){return bt(this,t,e,!0,n)},Y.prototype.writeFloatBE=function(t,e,n){return bt(this,t,e,!1,n)},Y.prototype.writeDoubleLE=function(t,e,n){return vt(this,t,e,!0,n)},Y.prototype.writeDoubleBE=function(t,e,n){return vt(this,t,e,!1,n)},Y.prototype.copy=function(t,e,n,r){if(n||(n=0),r||0===r||(r=this.length),e>=t.length&&(e=t.length),e||(e=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===t.length||0===this.length)return 0;if(e<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("sourceStart out of bounds");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),t.length-e<r-n&&(r=t.length-e+n);var s,i=r-n;if(this===t&&n<e&&e<r)for(s=i-1;s>=0;--s)t[s+e]=this[s+n];else if(i<1e3||!Y.TYPED_ARRAY_SUPPORT)for(s=0;s<i;++s)t[s+e]=this[s+n];else Uint8Array.prototype.set.call(t,this.subarray(n,n+i),e);return i},Y.prototype.fill=function(t,e,n,r){if("string"==typeof t){if("string"==typeof e?(r=e,e=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),1===t.length){var s=t.charCodeAt(0);s<256&&(t=s)}if(void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!Y.isEncoding(r))throw new TypeError("Unknown encoding: "+r)}else"number"==typeof t&&(t&=255);if(e<0||this.length<e||this.length<n)throw new RangeError("Out of range index");if(n<=e)return this;var i;if(e>>>=0,n=void 0===n?this.length:n>>>0,t||(t=0),"number"==typeof t)for(i=e;i<n;++i)this[i]=t;else{var o=K(t)?t:Pt(new Y(t,r).toString()),a=o.length;for(i=0;i<n-e;++i)this[i+e]=o[i%a]}return this};var At=/[^+\/0-9A-Za-z-_]/g;function Et(t){return t<16?"0"+t.toString(16):t.toString(16)}function Pt(t,e){var n;e=e||1/0;for(var r=t.length,s=null,i=[],o=0;o<r;++o){if((n=t.charCodeAt(o))>55295&&n<57344){if(!s){if(n>56319){(e-=3)>-1&&i.push(239,191,189);continue}if(o+1===r){(e-=3)>-1&&i.push(239,191,189);continue}s=n;continue}if(n<56320){(e-=3)>-1&&i.push(239,191,189),s=n;continue}n=65536+(s-55296<<10|n-56320)}else s&&(e-=3)>-1&&i.push(239,191,189);if(s=null,n<128){if((e-=1)<0)break;i.push(n)}else if(n<2048){if((e-=2)<0)break;i.push(n>>6|192,63&n|128)}else if(n<65536){if((e-=3)<0)break;i.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((e-=4)<0)break;i.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return i}function Rt(t){return function(t){var e,n,r,s,i,o;$||B();var a=t.length;if(a%4>0)throw new Error("Invalid string. Length must be a multiple of 4");i="="===t[a-2]?2:"="===t[a-1]?1:0,o=new M(3*a/4-i),r=i>0?a-4:a;var c=0;for(e=0,n=0;e<r;e+=4,n+=3)s=k[t.charCodeAt(e)]<<18|k[t.charCodeAt(e+1)]<<12|k[t.charCodeAt(e+2)]<<6|k[t.charCodeAt(e+3)],o[c++]=s>>16&255,o[c++]=s>>8&255,o[c++]=255&s;return 2===i?(s=k[t.charCodeAt(e)]<<2|k[t.charCodeAt(e+1)]>>4,o[c++]=255&s):1===i&&(s=k[t.charCodeAt(e)]<<10|k[t.charCodeAt(e+1)]<<4|k[t.charCodeAt(e+2)]>>2,o[c++]=s>>8&255,o[c++]=255&s),o}(function(t){if((t=function(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}(t).replace(At,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}(t))}function St(t,e,n,r){for(var s=0;s<r&&!(s+n>=e.length||s>=t.length);++s)e[s+n]=t[s];return s}function xt(t){return!!t.constructor&&"function"==typeof t.constructor.isBuffer&&t.constructor.isBuffer(t)}const It="4.47.1";let Tt,Ct,Ot,kt,Mt,$t,Bt,Ut,Lt,jt=!1;Tt||function(t,e={auto:!1}){if(jt)throw new Error(`you must \`import 'openai/shims/${t.kind}'\` before importing anything else from openai`);if(Tt)throw new Error(`can't \`import 'openai/shims/${t.kind}'\` after \`import 'openai/shims/${Tt}'\``);jt=e.auto,Tt=t.kind,Ct=t.fetch,t.Request,t.Response,t.Headers,Ot=t.FormData,t.Blob,kt=t.File,Mt=t.ReadableStream,$t=t.getMultipartRequestOptions,Bt=t.getDefaultAgent,Ut=t.fileFromPath,Lt=t.isFsReadStream}(t.getRuntime(),{auto:!0});class Dt extends Error{}class Nt extends Dt{constructor(t,e,n,r){super(`${Nt.makeMessage(t,e,n)}`),this.status=t,this.headers=r,this.request_id=r?.["x-request-id"];const s=e;this.error=s,this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(t,e,n){const r=e?.message?"string"==typeof e.message?e.message:JSON.stringify(e.message):e?JSON.stringify(e):n;return t&&r?`${t} ${r}`:t?`${t} status code (no body)`:r||"(no status code or body)"}static generate(t,e,n,r){if(!t)return new Wt({cause:Be(e)});const s=e?.error;return 400===t?new Yt(t,s,n,r):401===t?new Xt(t,s,n,r):403===t?new zt(t,s,n,r):404===t?new Ht(t,s,n,r):409===t?new Jt(t,s,n,r):422===t?new Vt(t,s,n,r):429===t?new Kt(t,s,n,r):t>=500?new Gt(t,s,n,r):new Nt(t,s,n,r)}}class qt extends Nt{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0),this.status=void 0}}class Wt extends Nt{constructor({message:t,cause:e}){super(void 0,void 0,t||"Connection error.",void 0),this.status=void 0,e&&(this.cause=e)}}class Ft extends Wt{constructor({message:t}={}){super({message:t??"Request timed out."})}}class Yt extends Nt{constructor(){super(...arguments),this.status=400}}class Xt extends Nt{constructor(){super(...arguments),this.status=401}}class zt extends Nt{constructor(){super(...arguments),this.status=403}}class Ht extends Nt{constructor(){super(...arguments),this.status=404}}class Jt extends Nt{constructor(){super(...arguments),this.status=409}}class Vt extends Nt{constructor(){super(...arguments),this.status=422}}class Kt extends Nt{constructor(){super(...arguments),this.status=429}}class Gt extends Nt{}var Qt=Object.freeze({__proto__:null,OpenAIError:Dt,APIError:Nt,APIUserAbortError:qt,APIConnectionError:Wt,APIConnectionTimeoutError:Ft,BadRequestError:Yt,AuthenticationError:Xt,PermissionDeniedError:zt,NotFoundError:Ht,ConflictError:Jt,UnprocessableEntityError:Vt,RateLimitError:Kt,InternalServerError:Gt});class Zt{constructor(t,e){this.iterator=t,this.controller=e}static fromSSEResponse(t,n){let r=!1;return new Zt((async function*(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let s=!1;try{for await(const r of async function*(t,e){if(!t.body)throw e.abort(),new Dt("Attempted to iterate over a response with no body");const n=new ee,r=new ne,s=re(t.body);for await(const t of async function*(t){let e=new Uint8Array;for await(const n of t){if(null==n)continue;const t=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?(new TextEncoder).encode(n):n;let r,s=new Uint8Array(e.length+t.length);for(s.set(e),s.set(t,e.length),e=s;-1!==(r=te(e));)yield e.slice(0,r),e=e.slice(r)}e.length>0&&(yield e)}(s))for(const e of r.decode(t)){const t=n.decode(e);t&&(yield t)}for(const t of r.flush()){const e=n.decode(t);e&&(yield e)}}(t,n))if(!s)if(r.data.startsWith("[DONE]"))s=!0;else if(null===r.event){let t;try{t=JSON.parse(r.data)}catch(t){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),t}if(t&&t.error)throw new e(void 0,t.error,void 0,void 0);yield t}else{let t;try{t=JSON.parse(r.data)}catch(t){throw console.error("Could not parse message into JSON:",r.data),console.error("From chunk:",r.raw),t}if("error"==r.event)throw new e(void 0,t.error,t.message,void 0);yield{event:r.event,data:t}}s=!0}catch(t){if(t instanceof Error&&"AbortError"===t.name)return;throw t}finally{s||n.abort()}}),n)}static fromReadableStream(t,e){let n=!1;return new Zt((async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let r=!1;try{for await(const e of async function*(){const e=new ne,n=re(t);for await(const t of n)for(const n of e.decode(t))yield n;for(const t of e.flush())yield t}())r||e&&(yield JSON.parse(e));r=!0}catch(t){if(t instanceof Error&&"AbortError"===t.name)return;throw t}finally{r||e.abort()}}),e)}[Symbol.asyncIterator](){return this.iterator()}tee(){const t=[],e=[],n=this.iterator(),r=r=>({next:()=>{if(0===r.length){const r=n.next();t.push(r),e.push(r)}return r.shift()}});return[new Zt((()=>r(t)),this.controller),new Zt((()=>r(e)),this.controller)]}toReadableStream(){const t=this;let e;const n=new TextEncoder;return new Mt({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{const{value:r,done:s}=await e.next();if(s)return t.close();const i=n.encode(JSON.stringify(r)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){await(e.return?.())}})}}function te(t){for(let e=0;e<t.length-2;e++){if(10===t[e]&&10===t[e+1])return e+2;if(13===t[e]&&13===t[e+1])return e+2;if(13===t[e]&&10===t[e+1]&&e+3<t.length&&13===t[e+2]&&10===t[e+3])return e+4}return-1}class ee{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const t={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],t}if(this.chunks.push(t),t.startsWith(":"))return null;let[e,n,r]=function(t,e){const n=t.indexOf(e);if(-1!==n)return[t.substring(0,n),e,t.substring(n+e.length)];return[t,"",""]}(t,":");return r.startsWith(" ")&&(r=r.substring(1)),"event"===e?this.event=r:"data"===e&&this.data.push(r),null}}class ne{constructor(){this.buffer=[],this.trailingCR=!1}decode(t){let e=this.decodeText(t);if(this.trailingCR&&(e="\r"+e,this.trailingCR=!1),e.endsWith("\r")&&(this.trailingCR=!0,e=e.slice(0,-1)),!e)return[];const n=ne.NEWLINE_CHARS.has(e[e.length-1]||"");let r=e.split(ne.NEWLINE_REGEXP);return n&&r.pop(),1!==r.length||n?(this.buffer.length>0&&(r=[this.buffer.join("")+r[0],...r.slice(1)],this.buffer=[]),n||(this.buffer=[r.pop()||""]),r):(this.buffer.push(r[0]),[])}decodeText(t){if(null==t)return"";if("string"==typeof t)return t;if(void 0!==Y){if(t instanceof Y)return t.toString();if(t instanceof Uint8Array)return Y.from(t).toString();throw new Dt(`Unexpected: received non-Uint8Array (${t.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(t instanceof Uint8Array||t instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(t);throw new Dt(`Unexpected: received non-Uint8Array/ArrayBuffer (${t.constructor.name}) in a web platform. Please report this error.`)}throw new Dt("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const t=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,t}}function re(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const t=await e.read();return 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}}}ne.NEWLINE_CHARS=new Set(["\n","\r"]),ne.NEWLINE_REGEXP=/\r\n|[\n\r]/g;const se=t=>null!=t&&"object"==typeof t&&"string"==typeof t.url&&"function"==typeof t.blob,ie=t=>null!=t&&"object"==typeof t&&"string"==typeof t.name&&"number"==typeof t.lastModified&&oe(t),oe=t=>null!=t&&"object"==typeof t&&"number"==typeof t.size&&"string"==typeof t.type&&"function"==typeof t.text&&"function"==typeof t.slice&&"function"==typeof t.arrayBuffer;async function ae(t,e,n){if(t=await t,n??(n=ie(t)?{lastModified:t.lastModified,type:t.type}:{}),se(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new kt([r],e,n)}const r=await async function(t){let e=[];if("string"==typeof t||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(oe(t))e.push(await t.arrayBuffer());else{if(!le(t))throw new Error(`Unexpected data type: ${typeof t}; constructor: ${t?.constructor?.name}; props: ${function(t){const e=Object.getOwnPropertyNames(t);return`[${e.map((t=>`"${t}"`)).join(", ")}]`}(t)}`);for await(const n of t)e.push(n)}return e}(t);if(e||(e=function(t){return ce(t.name)||ce(t.filename)||ce(t.path)?.split(/[\\/]/).pop()}(t)??"unknown_file"),!n.type){const t=r[0]?.type;"string"==typeof t&&(n={...n,type:t})}return new kt(r,e,n)}const ce=t=>"string"==typeof t?t:void 0!==Y&&t instanceof Y?String(t):void 0,le=t=>null!=t&&"object"==typeof t&&"function"==typeof t[Symbol.asyncIterator],he=t=>t&&"object"==typeof t&&t.body&&"MultipartBody"===t[Symbol.toStringTag],ue=async t=>{const e=await fe(t.body);return $t(e,t)},fe=async t=>{const e=new Ot;return await Promise.all(Object.entries(t||{}).map((([t,n])=>de(e,t,n)))),e},de=async(t,e,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)t.append(e,String(n));else if((t=>ie(t)||se(t)||Lt(t))(n)){const r=await ae(n);t.append(e,r)}else if(Array.isArray(n))await Promise.all(n.map((n=>de(t,e+"[]",n))));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map((([n,r])=>de(t,`${e}[${n}]`,r))))}}};var pe,me=function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n},ge=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};async function we(t){const{response:e}=t;if(t.options.stream)return Ne("response",e.status,e.url,e.headers,e.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(e,t.controller):Zt.fromSSEResponse(e,t.controller);if(204===e.status)return null;if(t.options.__binaryResponse)return e;const n=e.headers.get("content-type");if(n?.includes("application/json")||n?.includes("application/vnd.api+json")){const t=await e.json();return Ne("response",e.status,e.url,e.headers,t),t}const r=await e.text();return Ne("response",e.status,e.url,e.headers,r),r}class ye extends Promise{constructor(t,e=we){super((t=>{t(null)})),this.responsePromise=t,this.parseResponse=e}_thenUnwrap(t){return new ye(this.responsePromise,(async e=>t(await this.parseResponse(e))))}asResponse(){return this.responsePromise.then((t=>t.response))}async withResponse(){const[t,e]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:e}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(t,e){return this.parse().then(t,e)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}class _e{constructor({baseURL:t,maxRetries:e=2,timeout:n=6e5,httpAgent:r,fetch:s}){this.baseURL=t,this.maxRetries=$e("maxRetries",e),this.timeout=$e("timeout",n),this.httpAgent=r,this.fetch=s??Ct}authHeaders(t){return{}}defaultHeaders(t){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Te(),...this.authHeaders(t)}}validateHeaders(t,e){}defaultIdempotencyKey(){return`stainless-node-retry-${qe()}`}get(t,e){return this.methodRequest("get",t,e)}post(t,e){return this.methodRequest("post",t,e)}patch(t,e){return this.methodRequest("patch",t,e)}put(t,e){return this.methodRequest("put",t,e)}delete(t,e){return this.methodRequest("delete",t,e)}methodRequest(t,e,n){return this.request(Promise.resolve(n).then((n=>({method:t,path:e,...n}))))}getAPIList(t,e,n){return this.requestAPIList(e,{method:"get",path:t,...n})}calculateContentLength(t){if("string"==typeof t){if(void 0!==Y)return Y.byteLength(t,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(t).length.toString()}}return null}buildRequest(t){const{method:e,path:n,query:r,headers:s={}}=t,i=he(t.body)?t.body.body:t.body?JSON.stringify(t.body,null,2):null,o=this.calculateContentLength(i),a=this.buildURL(n,r);"timeout"in t&&$e("timeout",t.timeout);const c=t.timeout??this.timeout,l=t.httpAgent??this.httpAgent??Bt(a),h=c+1e3;"number"==typeof l?.options?.timeout&&h>(l.options.timeout??0)&&(l.options.timeout=h),this.idempotencyHeader&&"get"!==e&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=t.idempotencyKey);return{req:{method:e,...i&&{body:i},headers:this.buildHeaders({options:t,headers:s,contentLength:o}),...l&&{agent:l},signal:t.signal??null},url:a,timeout:c}}buildHeaders({options:t,headers:e,contentLength:n}){const r={};n&&(r["content-length"]=n);return De(r,this.defaultHeaders(t)),De(r,e),he(t.body)&&"node"!==Tt&&delete r["content-type"],this.validateHeaders(r,e),r}async prepareOptions(t){}async prepareRequest(t,{url:e,options:n}){}parseHeaders(t){return t?Symbol.iterator in t?Object.fromEntries(Array.from(t).map((t=>[...t]))):{...t}:{}}makeStatusError(t,e,n,r){return Nt.generate(t,e,n,r)}request(t,e=null){return new ye(this.makeRequest(t,e))}async makeRequest(t,e){const n=await t;null==e&&(e=n.maxRetries??this.maxRetries),await this.prepareOptions(n);const{req:r,url:s,timeout:i}=this.buildRequest(n);if(await this.prepareRequest(r,{url:s,options:n}),Ne("request",s,n,r.headers),n.signal?.aborted)throw new qt;const o=new AbortController,a=await this.fetchWithTimeout(s,r,i,o).catch(Be);if(a instanceof Error){if(n.signal?.aborted)throw new qt;if(e)return this.retryRequest(n,e);if("AbortError"===a.name)throw new Ft;throw new Wt({cause:a})}const c=Ae(a.headers);if(!a.ok){if(e&&this.shouldRetry(a)){return Ne(`response (error; ${`retrying, ${e} attempts remaining`})`,a.status,s,c),this.retryRequest(n,e,c)}const t=await a.text().catch((t=>Be(t).message)),r=Ce(t),i=r?void 0:t;Ne(`response (error; ${e?"(error; no more retries left)":"(error; not retryable)"})`,a.status,s,c,i);throw this.makeStatusError(a.status,r,i,c)}return{response:a,options:n,controller:o}}requestAPIList(t,e){const n=this.makeRequest(e,null);return new ve(this,n,t)}buildURL(t,e){const n=ke(t)?new URL(t):new URL(this.baseURL+(this.baseURL.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),r=this.defaultQuery();return Le(r)||(e={...r,...e}),"object"==typeof e&&e&&!Array.isArray(e)&&(n.search=this.stringifyQuery(e)),n.toString()}stringifyQuery(t){return Object.entries(t).filter((([t,e])=>void 0!==e)).map((([t,e])=>{if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return`${encodeURIComponent(t)}=${encodeURIComponent(e)}`;if(null===e)return`${encodeURIComponent(t)}=`;throw new Dt(`Cannot stringify type ${typeof e}; 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(t,e,n,r){const{signal:s,...i}=e||{};s&&s.addEventListener("abort",(()=>r.abort()));const o=setTimeout((()=>r.abort()),n);return this.getRequestClient().fetch.call(void 0,t,{signal:r.signal,...i}).finally((()=>{clearTimeout(o)}))}getRequestClient(){return{fetch:this.fetch}}shouldRetry(t){const e=t.headers.get("x-should-retry");return"true"===e||"false"!==e&&(408===t.status||(409===t.status||(429===t.status||t.status>=500)))}async retryRequest(t,e,n){let r;const s=n?.["retry-after-ms"];if(s){const t=parseFloat(s);Number.isNaN(t)||(r=t)}const i=n?.["retry-after"];if(i&&!r){const t=parseFloat(i);r=Number.isNaN(t)?Date.parse(i)-Date.now():1e3*t}if(!(r&&0<=r&&r<6e4)){const n=t.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(e,n)}return await Me(r),this.makeRequest(t,e-1)}calculateDefaultRetryTimeoutMillis(t,e){const n=e-t;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${It}`}}class be{constructor(t,e,n,r){pe.set(this,void 0),me(this,pe,t,"f"),this.options=r,this.response=e,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const t=this.nextPageInfo();if(!t)throw new Dt("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const e={...this.options};if("params"in t&&"object"==typeof e.query)e.query={...e.query,...t.params};else if("url"in t){const n=[...Object.entries(e.query||{}),...t.url.searchParams.entries()];for(const[e,r]of n)t.url.searchParams.set(e,r);e.query=void 0,e.path=t.url.toString()}return await ge(this,pe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(pe=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const e of t.getPaginatedItems())yield e}}class ve extends ye{constructor(t,e,n){super(e,(async e=>new n(t,e.response,await we(e),e.options)))}async*[Symbol.asyncIterator](){const t=await(this);for await(const e of t)yield e}}const Ae=t=>new Proxy(Object.fromEntries(t.entries()),{get(t,e){const n=e.toString();return t[n.toLowerCase()]||t[n]}}),Ee={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryResponse:!0,__streamClass:!0},Pe=t=>"object"==typeof t&&null!==t&&!Le(t)&&Object.keys(t).every((t=>je(Ee,t))),Re=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":It,"X-Stainless-OS":xe(Deno.build.os),"X-Stainless-Arch":Se(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":It,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":C.version};if("[object process]"===Object.prototype.toString.call(void 0!==C?C:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":It,"X-Stainless-OS":xe(C.platform),"X-Stainless-Arch":Se(C.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":C.version};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const t=[{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:n}of t){const t=n.exec(navigator.userAgent);if(t){return{browser:e,version:`${t[1]||0}.${t[2]||0}.${t[3]||0}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":It,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":It,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Se=t=>"x32"===t?"x32":"x86_64"===t||"x64"===t?"x64":"arm"===t?"arm":"aarch64"===t||"arm64"===t?"arm64":t?`other:${t}`:"unknown",xe=t=>(t=t.toLowerCase()).includes("ios")?"iOS":"android"===t?"Android":"darwin"===t?"MacOS":"win32"===t?"Windows":"freebsd"===t?"FreeBSD":"openbsd"===t?"OpenBSD":"linux"===t?"Linux":t?`Other:${t}`:"Unknown";let Ie;const Te=()=>Ie??(Ie=Re()),Ce=t=>{try{return JSON.parse(t)}catch(t){return}},Oe=new RegExp("^(?:[a-z]+:)?//","i"),ke=t=>Oe.test(t),Me=t=>new Promise((e=>setTimeout(e,t))),$e=(t,e)=>{if("number"!=typeof e||!Number.isInteger(e))throw new Dt(`${t} must be an integer`);if(e<0)throw new Dt(`${t} must be a positive integer`);return e},Be=t=>t instanceof Error?t:new Error(t),Ue=t=>void 0!==C?C.env?.[t]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(t)?.trim():void 0;function Le(t){if(!t)return!0;for(const e in t)return!1;return!0}function je(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function De(t,e){for(const n in e){if(!je(e,n))continue;const r=n.toLowerCase();if(!r)continue;const s=e[n];null===s?delete t[r]:void 0!==s&&(t[r]=s)}}function Ne(t,...e){void 0!==C&&"true"===C?.env?.DEBUG&&console.log(`OpenAI:DEBUG:${t}`,...e)}const qe=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(t=>{const e=16*Math.random()|0;return("x"===t?e:3&e|8).toString(16)}));class We extends be{constructor(t,e,n,r){super(t,e,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class Fe extends be{constructor(t,e,n,r){super(t,e,n,r),this.data=n.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){const t=this.nextPageInfo();if(!t)return null;if("params"in t)return t.params;const e=Object.fromEntries(t.url.searchParams);return Object.keys(e).length?e:null}nextPageInfo(){const t=this.getPaginatedItems();if(!t.length)return null;const e=t[t.length-1]?.id;return e?{params:{after:e}}:null}}class Ye{constructor(t){this._client=t}}class Xe extends Ye{create(t,e){return this._client.post("/chat/completions",{body:t,...e,stream:t.stream??!1})}}Xe||(Xe={});class ze extends Ye{constructor(){super(...arguments),this.completions=new Xe(this._client)}}(ze||(ze={})).Completions=Xe;class He extends Ye{create(t,e){return this._client.post("/audio/speech",{body:t,...e,__binaryResponse:!0})}}He||(He={});class Je extends Ye{create(t,e){return this._client.post("/audio/transcriptions",ue({body:t,...e}))}}Je||(Je={});class Ve extends Ye{create(t,e){return this._client.post("/audio/translations",ue({body:t,...e}))}}Ve||(Ve={});class Ke extends Ye{constructor(){super(...arguments),this.transcriptions=new Je(this._client),this.translations=new Ve(this._client),this.speech=new He(this._client)}}!function(t){t.Transcriptions=Je,t.Translations=Ve,t.Speech=He}(Ke||(Ke={}));class Ge extends Ye{create(t,e){return this._client.post("/batches",{body:t,...e})}retrieve(t,e){return this._client.get(`/batches/${t}`,e)}list(t={},e){return Pe(t)?this.list({},t):this._client.getAPIList("/batches",Qe,{query:t,...e})}cancel(t,e){return this._client.post(`/batches/${t}/cancel`,e)}}class Qe extends Fe{}!function(t){t.BatchesPage=Qe}(Ge||(Ge={}));class Ze extends Ye{create(t,e){return this._client.post("/assistants",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}retrieve(t,e){return this._client.get(`/assistants/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}update(t,e,n){return this._client.post(`/assistants/${t}`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(t={},e){return Pe(t)?this.list({},t):this._client.getAPIList("/assistants",tn,{query:t,...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}del(t,e){return this._client.delete(`/assistants/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}}class tn extends Fe{}function en(t){return"function"==typeof t.parse}!function(t){t.AssistantsPage=tn}(Ze||(Ze={}));const nn=t=>"assistant"===t?.role,rn=t=>"function"===t?.role,sn=t=>"tool"===t?.role;var on,an,cn,ln,hn,un,fn,dn,pn,mn,gn,wn,yn,_n,bn,vn,An,En,Pn,Rn,Sn=function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n},xn=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};const In=10;class Tn{constructor(){on.add(this),this.controller=new AbortController,an.set(this,void 0),cn.set(this,(()=>{})),ln.set(this,(()=>{})),hn.set(this,void 0),un.set(this,(()=>{})),fn.set(this,(()=>{})),dn.set(this,{}),this._chatCompletions=[],this.messages=[],pn.set(this,!1),mn.set(this,!1),gn.set(this,!1),wn.set(this,!1),En.set(this,(t=>{if(Sn(this,mn,!0,"f"),t instanceof Error&&"AbortError"===t.name&&(t=new n),t instanceof n)return Sn(this,gn,!0,"f"),this._emit("abort",t);if(t instanceof r)return this._emit("error",t);if(t instanceof Error){const e=new r(t.message);return e.cause=t,this._emit("error",e)}return this._emit("error",new r(String(t)))})),Sn(this,an,new Promise(((t,e)=>{Sn(this,cn,t,"f"),Sn(this,ln,e,"f")})),"f"),Sn(this,hn,new Promise(((t,e)=>{Sn(this,un,t,"f"),Sn(this,fn,e,"f")})),"f"),xn(this,an,"f").catch((()=>{})),xn(this,hn,"f").catch((()=>{}))}_run(t){setTimeout((()=>{t().then((()=>{this._emitFinal(),this._emit("end")}),xn(this,En,"f"))}),0)}_addChatCompletion(t){this._chatCompletions.push(t),this._emit("chatCompletion",t);const e=t.choices[0]?.message;return e&&this._addMessage(e),t}_addMessage(t,e=!0){if("content"in t||(t.content=null),this.messages.push(t),e)if(this._emit("message",t),(rn(t)||sn(t))&&t.content)this._emit("functionCallResult",t.content);else if(nn(t)&&t.function_call)this._emit("functionCall",t.function_call);else if(nn(t)&&t.tool_calls)for(const e of t.tool_calls)"function"===e.type&&this._emit("functionCall",e.function)}_connected(){this.ended||(xn(this,cn,"f").call(this),this._emit("connect"))}get ended(){return xn(this,pn,"f")}get errored(){return xn(this,mn,"f")}get aborted(){return xn(this,gn,"f")}abort(){this.controller.abort()}on(t,e){return(xn(this,dn,"f")[t]||(xn(this,dn,"f")[t]=[])).push({listener:e}),this}off(t,e){const n=xn(this,dn,"f")[t];if(!n)return this;const r=n.findIndex((t=>t.listener===e));return r>=0&&n.splice(r,1),this}once(t,e){return(xn(this,dn,"f")[t]||(xn(this,dn,"f")[t]=[])).push({listener:e,once:!0}),this}emitted(t){return new Promise(((e,n)=>{Sn(this,wn,!0,"f"),"error"!==t&&this.once("error",n),this.once(t,e)}))}async done(){Sn(this,wn,!0,"f"),await xn(this,hn,"f")}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new r("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),xn(this,on,"m",yn).call(this)}async finalMessage(){return await this.done(),xn(this,on,"m",_n).call(this)}async finalFunctionCall(){return await this.done(),xn(this,on,"m",bn).call(this)}async finalFunctionCallResult(){return await this.done(),xn(this,on,"m",vn).call(this)}async totalUsage(){return await this.done(),xn(this,on,"m",An).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emit(t,...e){if(xn(this,pn,"f"))return;"end"===t&&(Sn(this,pn,!0,"f"),xn(this,un,"f").call(this));const n=xn(this,dn,"f")[t];if(n&&(xn(this,dn,"f")[t]=n.filter((t=>!t.once)),n.forEach((({listener:t})=>t(...e)))),"abort"===t){const t=e[0];return xn(this,wn,"f")||n?.length||Promise.reject(t),xn(this,ln,"f").call(this,t),xn(this,fn,"f").call(this,t),void this._emit("end")}if("error"===t){const t=e[0];xn(this,wn,"f")||n?.length||Promise.reject(t),xn(this,ln,"f").call(this,t),xn(this,fn,"f").call(this,t),this._emit("end")}}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const e=xn(this,on,"m",_n).call(this);e&&this._emit("finalMessage",e);const n=xn(this,on,"m",yn).call(this);n&&this._emit("finalContent",n);const r=xn(this,on,"m",bn).call(this);r&&this._emit("finalFunctionCall",r);const s=xn(this,on,"m",vn).call(this);null!=s&&this._emit("finalFunctionCallResult",s),this._chatCompletions.some((t=>t.usage))&&this._emit("totalUsage",xn(this,on,"m",An).call(this))}async _createChatCompletion(t,e,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),xn(this,on,"m",Pn).call(this,e);const s=await t.create({...e,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(s)}async _runChatCompletion(t,e,n){for(const t of e.messages)this._addMessage(t,!1);return await this._createChatCompletion(t,e,n)}async _runFunctions(t,e,n){const s="function",{function_call:i="auto",stream:o,...a}=e,c="string"!=typeof i&&i?.name,{maxChatCompletions:l=In}=n||{},h={};for(const t of e.functions)h[t.name||t.function.name]=t;const u=e.functions.map((t=>({name:t.name||t.function.name,parameters:t.parameters,description:t.description})));for(const t of e.messages)this._addMessage(t,!1);for(let e=0;e<l;++e){const e=await this._createChatCompletion(t,{...a,function_call:i,functions:u,messages:[...this.messages]},n),o=e.choices[0]?.message;if(!o)throw new r("missing message in ChatCompletion response");if(!o.function_call)return;const{name:l,arguments:f}=o.function_call,d=h[l];if(!d){const t=`Invalid function_call: ${JSON.stringify(l)}. Available options are: ${u.map((t=>JSON.stringify(t.name))).join(", ")}. Please try again`;this._addMessage({role:s,name:l,content:t});continue}if(c&&c!==l){const t=`Invalid function_call: ${JSON.stringify(l)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,name:l,content:t});continue}let p;try{p=en(d)?await d.parse(f):f}catch(t){this._addMessage({role:s,name:l,content:t instanceof Error?t.message:String(t)});continue}const m=await d.function(p,this),g=xn(this,on,"m",Rn).call(this,m);if(this._addMessage({role:s,name:l,content:g}),c)return}}async _runTools(t,e,n){const s="tool",{tool_choice:i="auto",stream:o,...a}=e,c="string"!=typeof i&&i?.function?.name,{maxChatCompletions:l=In}=n||{},h={};for(const t of e.tools)"function"===t.type&&(h[t.function.name||t.function.function.name]=t.function);const u="tools"in e?e.tools.map((t=>"function"===t.type?{type:"function",function:{name:t.function.name||t.function.function.name,parameters:t.function.parameters,description:t.function.description}}:t)):void 0;for(const t of e.messages)this._addMessage(t,!1);for(let e=0;e<l;++e){const e=await this._createChatCompletion(t,{...a,tool_choice:i,tools:u,messages:[...this.messages]},n),o=e.choices[0]?.message;if(!o)throw new r("missing message in ChatCompletion response");if(!o.tool_calls)return;for(const t of o.tool_calls){if("function"!==t.type)continue;const e=t.id,{name:n,arguments:r}=t.function,i=h[n];if(!i){const t=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${u.map((t=>JSON.stringify(t.function.name))).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:e,content:t});continue}if(c&&c!==n){const t=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:e,content:t});continue}let o;try{o=en(i)?await i.parse(r):r}catch(t){const n=t instanceof Error?t.message:String(t);this._addMessage({role:s,tool_call_id:e,content:n});continue}const a=await i.function(o,this),l=xn(this,on,"m",Rn).call(this,a);if(this._addMessage({role:s,tool_call_id:e,content:l}),c)return}}}}an=new WeakMap,cn=new WeakMap,ln=new WeakMap,hn=new WeakMap,un=new WeakMap,fn=new WeakMap,dn=new WeakMap,pn=new WeakMap,mn=new WeakMap,gn=new WeakMap,wn=new WeakMap,En=new WeakMap,on=new WeakSet,yn=function(){return xn(this,on,"m",_n).call(this).content??null},_n=function(){let t=this.messages.length;for(;t-- >0;){const e=this.messages[t];if(nn(e))return{...e,content:e.content??null}}throw new r("stream ended without producing a ChatCompletionMessage with role=assistant")},bn=function(){for(let t=this.messages.length-1;t>=0;t--){const e=this.messages[t];if(nn(e)&&e?.function_call)return e.function_call;if(nn(e)&&e?.tool_calls?.length)return e.tool_calls.at(-1)?.function}},vn=function(){for(let t=this.messages.length-1;t>=0;t--){const e=this.messages[t];if(rn(e)&&null!=e.content)return e.content;if(sn(e)&&null!=e.content&&this.messages.some((t=>"assistant"===t.role&&t.tool_calls?.some((t=>"function"===t.type&&t.id===e.tool_call_id)))))return e.content}},An=function(){const t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:e}of this._chatCompletions)e&&(t.completion_tokens+=e.completion_tokens,t.prompt_tokens+=e.prompt_tokens,t.total_tokens+=e.total_tokens);return t},Pn=function(t){if(null!=t.n&&t.n>1)throw new r("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Rn=function(t){return"string"==typeof t?t:void 0===t?"undefined":JSON.stringify(t)};class Cn extends Tn{static runFunctions(t,e,n){const r=new Cn,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return r._run((()=>r._runFunctions(t,e,s))),r}static runTools(t,e,n){const r=new Cn,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run((()=>r._runTools(t,e,s))),r}_addMessage(t){super._addMessage(t),nn(t)&&t.content&&this._emit("content",t.content)}}var On,kn,Mn,$n,Bn,Un,Ln=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)},jn=function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n};class Dn extends Tn{constructor(){super(...arguments),On.add(this),kn.set(this,void 0)}get currentChatCompletionSnapshot(){return Ln(this,kn,"f")}static fromReadableStream(t){const e=new Dn;return e._run((()=>e._fromReadableStream(t))),e}static createChatCompletion(t,e,n){const r=new Dn;return r._run((()=>r._runChatCompletion(t,{...e,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}async _createChatCompletion(t,e,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),Ln(this,On,"m",Mn).call(this);const i=await t.create({...e,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const t of i)Ln(this,On,"m",$n).call(this,t);if(i.controller.signal?.aborted)throw new n;return this._addChatCompletion(Ln(this,On,"m",Bn).call(this))}async _fromReadableStream(t,e){const r=e?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),Ln(this,On,"m",Mn).call(this),this._connected();const i=s.fromReadableStream(t,this.controller);let o;for await(const t of i)o&&o!==t.id&&this._addChatCompletion(Ln(this,On,"m",Bn).call(this)),Ln(this,On,"m",$n).call(this,t),o=t.id;if(i.controller.signal?.aborted)throw new n;return this._addChatCompletion(Ln(this,On,"m",Bn).call(this))}[(kn=new WeakMap,On=new WeakSet,Mn=function(){this.ended||jn(this,kn,void 0,"f")},$n=function(t){if(this.ended)return;const e=Ln(this,On,"m",Un).call(this,t);this._emit("chunk",t,e);const n=t.choices[0]?.delta?.content,r=e.choices[0]?.message;null!=n&&"assistant"===r?.role&&r?.content&&this._emit("content",n,r.content)},Bn=function(){if(this.ended)throw new r("stream has ended, this shouldn't happen");const t=Ln(this,kn,"f");if(!t)throw new r("request ended without sending any chunks");return jn(this,kn,void 0,"f"),function(t){const{id:e,choices:n,created:s,model:i,system_fingerprint:o,...a}=t;return{...a,id:e,choices:n.map((({message:e,finish_reason:n,index:s,logprobs:i,...o})=>{if(!n)throw new r(`missing finish_reason for choice ${s}`);const{content:a=null,function_call:c,tool_calls:l,...h}=e,u=e.role;if(!u)throw new r(`missing role for choice ${s}`);if(c){const{arguments:t,name:e}=c;if(null==t)throw new r(`missing function_call.arguments for choice ${s}`);if(!e)throw new r(`missing function_call.name for choice ${s}`);return{...o,message:{content:a,function_call:{arguments:t,name:e},role:u},finish_reason:n,index:s,logprobs:i}}return l?{...o,index:s,finish_reason:n,logprobs:i,message:{...h,role:u,content:a,tool_calls:l.map(((e,n)=>{const{function:i,type:o,id:a,...c}=e,{arguments:l,name:h,...u}=i||{};if(null==a)throw new r(`missing choices[${s}].tool_calls[${n}].id\n${Nn(t)}`);if(null==o)throw new r(`missing choices[${s}].tool_calls[${n}].type\n${Nn(t)}`);if(null==h)throw new r(`missing choices[${s}].tool_calls[${n}].function.name\n${Nn(t)}`);if(null==l)throw new r(`missing choices[${s}].tool_calls[${n}].function.arguments\n${Nn(t)}`);return{...c,id:a,type:o,function:{...u,name:h,arguments:l}}}))}}:{...o,message:{...h,content:a,role:u},finish_reason:n,index:s,logprobs:i}})),created:s,model:i,object:"chat.completion",...o?{system_fingerprint:o}:{}}}(t)},Un=function(t){var e,n,r;let s=Ln(this,kn,"f");const{choices:i,...o}=t;s?Object.assign(s,o):s=jn(this,kn,{...o,choices:[]},"f");for(const{delta:i,finish_reason:o,index:a,logprobs:c=null,...l}of t.choices){let t=s.choices[a];if(t||(t=s.choices[a]={finish_reason:o,index:a,message:{},logprobs:c,...l}),c)if(t.logprobs){const{content:n,...r}=c;Object.assign(t.logprobs,r),n&&((e=t.logprobs).content??(e.content=[]),t.logprobs.content.push(...n))}else t.logprobs=Object.assign({},c);if(o&&(t.finish_reason=o),Object.assign(t,l),!i)continue;const{content:h,function_call:u,role:f,tool_calls:d,...p}=i;if(Object.assign(t.message,p),h&&(t.message.content=(t.message.content||"")+h),f&&(t.message.role=f),u&&(t.message.function_call?(u.name&&(t.message.function_call.name=u.name),u.arguments&&((n=t.message.function_call).arguments??(n.arguments=""),t.message.function_call.arguments+=u.arguments)):t.message.function_call=u),d){t.message.tool_calls||(t.message.tool_calls=[]);for(const{index:e,id:n,type:s,function:i,...o}of d){const a=(r=t.message.tool_calls)[e]??(r[e]={});Object.assign(a,o),n&&(a.id=n),s&&(a.type=s),i&&(a.function??(a.function={arguments:""})),i?.name&&(a.function.name=i.name),i?.arguments&&(a.function.arguments+=i.arguments)}}}return s},Symbol.asyncIterator)](){const t=[],e=[];let n=!1;return this.on("chunk",(n=>{const r=e.shift();r?r.resolve(n):t.push(n)})),this.on("end",(()=>{n=!0;for(const t of e)t.resolve(void 0);e.length=0})),this.on("abort",(t=>{n=!0;for(const n of e)n.reject(t);e.length=0})),this.on("error",(t=>{n=!0;for(const n of e)n.reject(t);e.length=0})),{next:async()=>{if(!t.length)return n?{value:void 0,done:!0}:new Promise(((t,n)=>e.push({resolve:t,reject:n}))).then((t=>t?{value:t,done:!1}:{value:void 0,done:!0}));return{value:t.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Nn(t){return JSON.stringify(t)}class qn extends Dn{static fromReadableStream(t){const e=new qn;return e._run((()=>e._fromReadableStream(t))),e}static runFunctions(t,e,n){const r=new qn,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return r._run((()=>r._runFunctions(t,e,s))),r}static runTools(t,e,n){const r=new qn,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run((()=>r._runTools(t,e,s))),r}}class Wn extends Ye{runFunctions(t,e){return t.stream?qn.runFunctions(this._client.chat.completions,t,e):Cn.runFunctions(this._client.chat.completions,t,e)}runTools(t,e){return t.stream?qn.runTools(this._client.chat.completions,t,e):Cn.runTools(this._client.chat.completions,t,e)}stream(t,e){return Dn.createChatCompletion(this._client.chat.completions,t,e)}}class Fn extends Ye{constructor(){super(...arguments),this.completions=new Wn(this._client)}}!function(t){t.Completions=Wn}(Fn||(Fn={}));var Yn,Xn,zn,Hn,Jn,Vn,Kn,Gn,Qn,Zn,tr,er,nr=function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n},rr=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)};class sr{constructor(){this.controller=new AbortController,Yn.set(this,void 0),Xn.set(this,(()=>{})),zn.set(this,(()=>{})),Hn.set(this,void 0),Jn.set(this,(()=>{})),Vn.set(this,(()=>{})),Kn.set(this,{}),Gn.set(this,!1),Qn.set(this,!1),Zn.set(this,!1),tr.set(this,!1),er.set(this,(t=>{if(nr(this,Qn,!0,"f"),t instanceof Error&&"AbortError"===t.name&&(t=new n),t instanceof n)return nr(this,Zn,!0,"f"),this._emit("abort",t);if(t instanceof r)return this._emit("error",t);if(t instanceof Error){const e=new r(t.message);return e.cause=t,this._emit("error",e)}return this._emit("error",new r(String(t)))})),nr(this,Yn,new Promise(((t,e)=>{nr(this,Xn,t,"f"),nr(this,zn,e,"f")})),"f"),nr(this,Hn,new Promise(((t,e)=>{nr(this,Jn,t,"f"),nr(this,Vn,e,"f")})),"f"),rr(this,Yn,"f").catch((()=>{})),rr(this,Hn,"f").catch((()=>{}))}_run(t){setTimeout((()=>{t().then((()=>{this._emit("end")}),rr(this,er,"f"))}),0)}_addRun(t){return t}_connected(){this.ended||(rr(this,Xn,"f").call(this),this._emit("connect"))}get ended(){return rr(this,Gn,"f")}get errored(){return rr(this,Qn,"f")}get aborted(){return rr(this,Zn,"f")}abort(){this.controller.abort()}on(t,e){return(rr(this,Kn,"f")[t]||(rr(this,Kn,"f")[t]=[])).push({listener:e}),this}off(t,e){const n=rr(this,Kn,"f")[t];if(!n)return this;const r=n.findIndex((t=>t.listener===e));return r>=0&&n.splice(r,1),this}once(t,e){return(rr(this,Kn,"f")[t]||(rr(this,Kn,"f")[t]=[])).push({listener:e,once:!0}),this}emitted(t){return new Promise(((e,n)=>{nr(this,tr,!0,"f"),"error"!==t&&this.once("error",n),this.once(t,e)}))}async done(){nr(this,tr,!0,"f"),await rr(this,Hn,"f")}_emit(t,...e){if(rr(this,Gn,"f"))return;"end"===t&&(nr(this,Gn,!0,"f"),rr(this,Jn,"f").call(this));const n=rr(this,Kn,"f")[t];if(n&&(rr(this,Kn,"f")[t]=n.filter((t=>!t.once)),n.forEach((({listener:t})=>t(...e)))),"abort"===t){const t=e[0];return rr(this,tr,"f")||n?.length||Promise.reject(t),rr(this,zn,"f").call(this,t),rr(this,Vn,"f").call(this,t),void this._emit("end")}if("error"===t){const t=e[0];rr(this,tr,"f")||n?.length||Promise.reject(t),rr(this,zn,"f").call(this,t),rr(this,Vn,"f").call(this,t),this._emit("end")}}async _threadAssistantStream(t,e,n){return await this._createThreadAssistantStream(e,t,n)}async _runAssistantStream(t,e,n,r){return await this._createAssistantStream(e,t,n,r)}async _runToolAssistantStream(t,e,n,r,s){return await this._createToolAssistantStream(n,t,e,r,s)}async _createThreadAssistantStream(t,e,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const s=await t.createAndRun({...e,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addRun(s)}async _createToolAssistantStream(t,e,n,r,s){const i=s?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",(()=>this.controller.abort())));const o=await t.submitToolOutputs(e,n,{...r,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addRun(o)}async _createAssistantStream(t,e,n,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort())));const i=await t.create(e,{...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addRun(i)}}Yn=new WeakMap,Xn=new WeakMap,zn=new WeakMap,Hn=new WeakMap,Jn=new WeakMap,Vn=new WeakMap,Kn=new WeakMap,Gn=new WeakMap,Qn=new WeakMap,Zn=new WeakMap,tr=new WeakMap,er=new WeakMap;var ir,or,ar,cr,lr,hr,ur,fr,dr,pr,mr,gr,wr,yr,_r,br,vr,Ar,Er,Pr,Rr,Sr,xr=function(t,e,n,r){if("a"===n&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?r:"a"===n?r.call(t):r?r.value:e.get(t)},Ir=function(t,e,n,r,s){if("m"===r)throw new TypeError("Private method is not writable");if("a"===r&&!s)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===r?s.call(t,n):s?s.value=n:e.set(t,n),n};class Tr extends sr{constructor(){super(...arguments),ir.add(this),or.set(this,[]),ar.set(this,{}),cr.set(this,{}),lr.set(this,void 0),hr.set(this,void 0),ur.set(this,void 0),fr.set(this,void 0),dr.set(this,void 0),pr.set(this,void 0),mr.set(this,void 0),gr.set(this,void 0),wr.set(this,void 0)}[(or=new WeakMap,ar=new WeakMap,cr=new WeakMap,lr=new WeakMap,hr=new WeakMap,ur=new WeakMap,fr=new WeakMap,dr=new WeakMap,pr=new WeakMap,mr=new WeakMap,gr=new WeakMap,wr=new WeakMap,ir=new WeakSet,Symbol.asyncIterator)](){const t=[],e=[];let n=!1;return this.on("event",(n=>{const r=e.shift();r?r.resolve(n):t.push(n)})),this.on("end",(()=>{n=!0;for(const t of e)t.resolve(void 0);e.length=0})),this.on("abort",(t=>{n=!0;for(const n of e)n.reject(t);e.length=0})),this.on("error",(t=>{n=!0;for(const n of e)n.reject(t);e.length=0})),{next:async()=>{if(!t.length)return n?{value:void 0,done:!0}:new Promise(((t,n)=>e.push({resolve:t,reject:n}))).then((t=>t?{value:t,done:!1}:{value:void 0,done:!0}));return{value:t.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(t){const e=new Tr;return e._run((()=>e._fromReadableStream(t))),e}async _fromReadableStream(t,e){const r=e?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const i=s.fromReadableStream(t,this.controller);for await(const t of i)xr(this,ir,"m",yr).call(this,t);if(i.controller.signal?.aborted)throw new n;return this._addRun(xr(this,ir,"m",_r).call(this))}toReadableStream(){return new s(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(t,e,n,r,s){const i=new Tr;return i._run((()=>i._runToolAssistantStream(t,e,n,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),i}async _createToolAssistantStream(t,e,r,s,i){const o=i?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",(()=>this.controller.abort())));const a={...s,stream:!0},c=await t.submitToolOutputs(e,r,a,{...i,signal:this.controller.signal});this._connected();for await(const t of c)xr(this,ir,"m",yr).call(this,t);if(c.controller.signal?.aborted)throw new n;return this._addRun(xr(this,ir,"m",_r).call(this))}static createThreadAssistantStream(t,e,n){const r=new Tr;return r._run((()=>r._threadAssistantStream(t,e,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}static createAssistantStream(t,e,n,r){const s=new Tr;return s._run((()=>s._runAssistantStream(t,e,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}currentEvent(){return xr(this,mr,"f")}currentRun(){return xr(this,gr,"f")}currentMessageSnapshot(){return xr(this,lr,"f")}currentRunStepSnapshot(){return xr(this,wr,"f")}async finalRunSteps(){return await this.done(),Object.values(xr(this,ar,"f"))}async finalMessages(){return await this.done(),Object.values(xr(this,cr,"f"))}async finalRun(){if(await this.done(),!xr(this,hr,"f"))throw Error("Final run was not received.");return xr(this,hr,"f")}async _createThreadAssistantStream(t,e,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort())));const i={...e,stream:!0},o=await t.createAndRun(i,{...r,signal:this.controller.signal});this._connected();for await(const t of o)xr(this,ir,"m",yr).call(this,t);if(o.controller.signal?.aborted)throw new n;return this._addRun(xr(this,ir,"m",_r).call(this))}async _createAssistantStream(t,e,r,s){const i=s?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",(()=>this.controller.abort())));const o={...r,stream:!0},a=await t.create(e,o,{...s,signal:this.controller.signal});this._connected();for await(const t of a)xr(this,ir,"m",yr).call(this,t);if(a.controller.signal?.aborted)throw new n;return this._addRun(xr(this,ir,"m",_r).call(this))}static accumulateDelta(t,e){for(const[n,r]of Object.entries(e)){if(!t.hasOwnProperty(n)){t[n]=r;continue}let e=t[n];if(null!=e)if("index"!==n&&"type"!==n){if("string"==typeof e&&"string"==typeof r)e+=r;else if("number"==typeof e&&"number"==typeof r)e+=r;else if(i.isObj(e)&&i.isObj(r))e=this.accumulateDelta(e,r);else{if(!Array.isArray(e)||!Array.isArray(r))throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${e}`);if(e.every((t=>"string"==typeof t||"number"==typeof t))){e.push(...r);continue}}t[n]=e}else t[n]=r;else t[n]=r}return t}}yr=function(t){if(!this.ended)switch(Ir(this,mr,t,"f"),xr(this,ir,"m",Ar).call(this,t),t.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":xr(this,ir,"m",Sr).call(this,t);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":xr(this,ir,"m",vr).call(this,t);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":xr(this,ir,"m",br).call(this,t);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},_r=function(){if(this.ended)throw new r("stream has ended, this shouldn't happen");if(!xr(this,hr,"f"))throw Error("Final run has not been received");return xr(this,hr,"f")},br=function(t){const[e,n]=xr(this,ir,"m",Pr).call(this,t,xr(this,lr,"f"));Ir(this,lr,e,"f"),xr(this,cr,"f")[e.id]=e;for(const t of n){const n=e.content[t.index];"text"==n?.type&&this._emit("textCreated",n.text)}switch(t.event){case"thread.message.created":this._emit("messageCreated",t.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",t.data.delta,e),t.data.delta.content)for(const n of t.data.delta.content){if("text"==n.type&&n.text){let t=n.text,r=e.content[n.index];if(!r||"text"!=r.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",t,r.text)}if(n.index!=xr(this,ur,"f")){if(xr(this,fr,"f"))switch(xr(this,fr,"f").type){case"text":this._emit("textDone",xr(this,fr,"f").text,xr(this,lr,"f"));break;case"image_file":this._emit("imageFileDone",xr(this,fr,"f").image_file,xr(this,lr,"f"))}Ir(this,ur,n.index,"f")}Ir(this,fr,e.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==xr(this,ur,"f")){const e=t.data.content[xr(this,ur,"f")];if(e)switch(e.type){case"image_file":this._emit("imageFileDone",e.image_file,xr(this,lr,"f"));break;case"text":this._emit("textDone",e.text,xr(this,lr,"f"))}}xr(this,lr,"f")&&this._emit("messageDone",t.data),Ir(this,lr,void 0,"f")}},vr=function(t){const e=xr(this,ir,"m",Er).call(this,t);switch(Ir(this,wr,e,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":const n=t.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==e.step_details.type)for(const t of n.step_details.tool_calls)t.index==xr(this,dr,"f")?this._emit("toolCallDelta",t,e.step_details.tool_calls[t.index]):(xr(this,pr,"f")&&this._emit("toolCallDone",xr(this,pr,"f")),Ir(this,dr,t.index,"f"),Ir(this,pr,e.step_details.tool_calls[t.index],"f"),xr(this,pr,"f")&&this._emit("toolCallCreated",xr(this,pr,"f")));this._emit("runStepDelta",t.data.delta,e);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Ir(this,wr,void 0,"f");"tool_calls"==t.data.step_details.type&&xr(this,pr,"f")&&(this._emit("toolCallDone",xr(this,pr,"f")),Ir(this,pr,void 0,"f")),this._emit("runStepDone",t.data,e)}},Ar=function(t){xr(this,or,"f").push(t),this._emit("event",t)},Er=function(t){switch(t.event){case"thread.run.step.created":return xr(this,ar,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let e=xr(this,ar,"f")[t.data.id];if(!e)throw Error("Received a RunStepDelta before creation of a snapshot");let n=t.data;if(n.delta){const r=Tr.accumulateDelta(e,n.delta);xr(this,ar,"f")[t.data.id]=r}return xr(this,ar,"f")[t.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":xr(this,ar,"f")[t.data.id]=t.data}if(xr(this,ar,"f")[t.data.id])return xr(this,ar,"f")[t.data.id];throw new Error("No snapshot available")},Pr=function(t,e){let n=[];switch(t.event){case"thread.message.created":return[t.data,n];case"thread.message.delta":if(!e)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=t.data;if(r.delta.content)for(const t of r.delta.content)if(t.index in e.content){let n=e.content[t.index];e.content[t.index]=xr(this,ir,"m",Rr).call(this,t,n)}else e.content[t.index]=t,n.push(t);return[e,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(e)return[e,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Rr=function(t,e){return Tr.accumulateDelta(e,t)},Sr=function(t){switch(Ir(this,gr,t.data,"f"),t.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":Ir(this,hr,t.data,"f"),xr(this,pr,"f")&&(this._emit("toolCallDone",xr(this,pr,"f")),Ir(this,pr,void 0,"f"))}};class Cr extends Ye{create(t,e,n){return this._client.post(`/threads/${t}/messages`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(t,e,n){return this._client.get(`/threads/${t}/messages/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(t,e,n,r){return this._client.post(`/threads/${t}/messages/${e}`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(t,e={},n){return Pe(e)?this.list(t,{},e):this._client.getAPIList(`/threads/${t}/messages`,Or,{query:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(t,e,n){return this._client.delete(`/threads/${t}/messages/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class Or extends Fe{}!function(t){t.MessagesPage=Or}(Cr||(Cr={}));class kr extends Ye{retrieve(t,e,n,r){return this._client.get(`/threads/${t}/runs/${e}/steps/${n}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(t,e,n={},r){return Pe(n)?this.list(t,e,{},n):this._client.getAPIList(`/threads/${t}/runs/${e}/steps`,Mr,{query:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}}class Mr extends Fe{}!function(t){t.RunStepsPage=Mr}(kr||(kr={}));class $r extends Ye{constructor(){super(...arguments),this.steps=new kr(this._client)}create(t,e,n){return this._client.post(`/threads/${t}/runs`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:e.stream??!1})}retrieve(t,e,n){return this._client.get(`/threads/${t}/runs/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(t,e,n,r){return this._client.post(`/threads/${t}/runs/${e}`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(t,e={},n){return Pe(e)?this.list(t,{},e):this._client.getAPIList(`/threads/${t}/runs`,Br,{query:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(t,e,n){return this._client.post(`/threads/${t}/runs/${e}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(t,e,n){const r=await this.create(t,e,n);return await this.poll(t,r.id,n)}createAndStream(t,e,n){return Tr.createAssistantStream(t,this._client.beta.threads.runs,e,n)}async poll(t,e,n){const r={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:s,response:i}=await this.retrieve(t,e,{...n,headers:{...n?.headers,...r}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let t=5e3;if(n?.pollIntervalMs)t=n.pollIntervalMs;else{const e=i.headers.get("openai-poll-after-ms");if(e){const n=parseInt(e);isNaN(n)||(t=n)}}await Me(t);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(t,e,n){return Tr.createAssistantStream(t,this._client.beta.threads.runs,e,n)}submitToolOutputs(t,e,n,r){return this._client.post(`/threads/${t}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(t,e,n,r){const s=await this.submitToolOutputs(t,e,n,r);return await this.poll(t,s.id,r)}submitToolOutputsStream(t,e,n,r){return Tr.createToolAssistantStream(t,e,this._client.beta.threads.runs,n,r)}}class Br extends Fe{}!function(t){t.RunsPage=Br,t.Steps=kr,t.RunStepsPage=Mr}($r||($r={}));class Ur extends Ye{constructor(){super(...arguments),this.runs=new $r(this._client),this.messages=new Cr(this._client)}create(t={},e){return Pe(t)?this.create({},t):this._client.post("/threads",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}retrieve(t,e){return this._client.get(`/threads/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}update(t,e,n){return this._client.post(`/threads/${t}`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(t,e){return this._client.delete(`/threads/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}createAndRun(t,e){return this._client.post("/threads/runs",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers},stream:t.stream??!1})}async createAndRunPoll(t,e){const n=await this.createAndRun(t,e);return await this.runs.poll(n.thread_id,n.id,e)}createAndRunStream(t,e){return Tr.createThreadAssistantStream(t,this._client.beta.threads,e)}}!function(t){t.Runs=$r,t.RunsPage=Br,t.Messages=Cr,t.MessagesPage=Or}(Ur||(Ur={}));class Lr extends Ye{create(t,e,n){return this._client.post(`/vector_stores/${t}/files`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(t,e,n){return this._client.get(`/vector_stores/${t}/files/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(t,e={},n){return Pe(e)?this.list(t,{},e):this._client.getAPIList(`/vector_stores/${t}/files`,jr,{query:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(t,e,n){return this._client.delete(`/vector_stores/${t}/files/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(t,e,n){const r=await this.create(t,e,n);return await this.poll(t,r.id,n)}async poll(t,e,n){const r={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const s=await this.retrieve(t,e,{...n,headers:r}).withResponse(),i=s.data;switch(i.status){case"in_progress":let t=5e3;if(n?.pollIntervalMs)t=n.pollIntervalMs;else{const e=s.response.headers.get("openai-poll-after-ms");if(e){const n=parseInt(e);isNaN(n)||(t=n)}}await Me(t);break;case"failed":case"completed":return i}}}async upload(t,e,n){const r=await this._client.files.create({file:e,purpose:"assistants"},n);return this.create(t,{file_id:r.id},n)}async uploadAndPoll(t,e,n){const r=await this.upload(t,e,n);return await this.poll(t,r.id,n)}}class jr extends Fe{}(Lr||(Lr={})).VectorStoreFilesPage=jr;class Dr extends Ye{create(t,e,n){return this._client.post(`/vector_stores/${t}/file_batches`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(t,e,n){return this._client.get(`/vector_stores/${t}/file_batches/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(t,e,n){return this._client.post(`/vector_stores/${t}/file_batches/${e}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(t,e,n){const r=await this.create(t,e);return await this.poll(t,r.id,n)}listFiles(t,e,n={},r){return Pe(n)?this.listFiles(t,e,{},n):this._client.getAPIList(`/vector_stores/${t}/file_batches/${e}/files`,jr,{query:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async poll(t,e,n){const r={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(r["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:s,response:i}=await this.retrieve(t,e,{...n,headers:r}).withResponse();switch(s.status){case"in_progress":let t=5e3;if(n?.pollIntervalMs)t=n.pollIntervalMs;else{const e=i.headers.get("openai-poll-after-ms");if(e){const n=parseInt(e);isNaN(n)||(t=n)}}await Me(t);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(t,{files:e,fileIds:n=[]},r){if(null===e||0==e.length)throw new Error("No files provided to process.");const s=r?.maxConcurrency??5,i=Math.min(s,e.length),o=this._client,a=e.values(),c=[...n];const l=Array(i).fill(a).map((async function(t){for(let e of t){const t=await o.files.create({file:e,purpose:"assistants"},r);c.push(t.id)}}));return await(async t=>{const e=await Promise.allSettled(t),n=e.filter((t=>"rejected"===t.status));if(n.length){for(const t of n)console.error(t.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const t of e)"fulfilled"===t.status&&r.push(t.value);return r})(l),await this.createAndPoll(t,{file_ids:c})}}Dr||(Dr={});class Nr extends Ye{constructor(){super(...arguments),this.files=new Lr(this._client),this.fileBatches=new Dr(this._client)}create(t,e){return this._client.post("/vector_stores",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}retrieve(t,e){return this._client.get(`/vector_stores/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}update(t,e,n){return this._client.post(`/vector_stores/${t}`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(t={},e){return Pe(t)?this.list({},t):this._client.getAPIList("/vector_stores",qr,{query:t,...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}del(t,e){return this._client.delete(`/vector_stores/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}}class qr extends Fe{}!function(t){t.VectorStoresPage=qr,t.Files=Lr,t.VectorStoreFilesPage=jr,t.FileBatches=Dr}(Nr||(Nr={}));class Wr extends Ye{constructor(){super(...arguments),this.vectorStores=new Nr(this._client),this.chat=new Fn(this._client),this.assistants=new Ze(this._client),this.threads=new Ur(this._client)}}!function(t){t.VectorStores=Nr,t.VectorStoresPage=qr,t.Chat=Fn,t.Assistants=Ze,t.AssistantsPage=tn,t.Threads=Ur}(Wr||(Wr={}));class Fr extends Ye{create(t,e){return this._client.post("/completions",{body:t,...e,stream:t.stream??!1})}}Fr||(Fr={});class Yr extends Ye{create(t,e){return this._client.post("/embeddings",{body:t,...e})}}Yr||(Yr={});class Xr extends Ye{create(t,e){return this._client.post("/files",ue({body:t,...e}))}retrieve(t,e){return this._client.get(`/files/${t}`,e)}list(t={},e){return Pe(t)?this.list({},t):this._client.getAPIList("/files",zr,{query:t,...e})}del(t,e){return this._client.delete(`/files/${t}`,e)}content(t,e){return this._client.get(`/files/${t}/content`,{...e,__binaryResponse:!0})}retrieveContent(t,e){return this._client.get(`/files/${t}/content`,{...e,headers:{Accept:"application/json",...e?.headers}})}async waitForProcessing(t,{pollInterval:e=5e3,maxWait:n=18e5}={}){const r=new Set(["processed","error","deleted"]),s=Date.now();let i=await this.retrieve(t);for(;!i.status||!r.has(i.status);)if(await Me(e),i=await this.retrieve(t),Date.now()-s>n)throw new Ft({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return i}}class zr extends We{}!function(t){t.FileObjectsPage=zr}(Xr||(Xr={}));class Hr extends Ye{list(t,e={},n){return Pe(e)?this.list(t,{},e):this._client.getAPIList(`/fine_tuning/jobs/${t}/checkpoints`,Jr,{query:e,...n})}}class Jr extends Fe{}!function(t){t.FineTuningJobCheckpointsPage=Jr}(Hr||(Hr={}));class Vr extends Ye{constructor(){super(...arguments),this.checkpoints=new Hr(this._client)}create(t,e){return this._client.post("/fine_tuning/jobs",{body:t,...e})}retrieve(t,e){return this._client.get(`/fine_tuning/jobs/${t}`,e)}list(t={},e){return Pe(t)?this.list({},t):this._client.getAPIList("/fine_tuning/jobs",Kr,{query:t,...e})}cancel(t,e){return this._client.post(`/fine_tuning/jobs/${t}/cancel`,e)}listEvents(t,e={},n){return Pe(e)?this.listEvents(t,{},e):this._client.getAPIList(`/fine_tuning/jobs/${t}/events`,Gr,{query:e,...n})}}class Kr extends Fe{}class Gr extends Fe{}!function(t){t.FineTuningJobsPage=Kr,t.FineTuningJobEventsPage=Gr,t.Checkpoints=Hr,t.FineTuningJobCheckpointsPage=Jr}(Vr||(Vr={}));class Qr extends Ye{constructor(){super(...arguments),this.jobs=new Vr(this._client)}}!function(t){t.Jobs=Vr,t.FineTuningJobsPage=Kr,t.FineTuningJobEventsPage=Gr}(Qr||(Qr={}));class Zr extends Ye{createVariation(t,e){return this._client.post("/images/variations",ue({body:t,...e}))}edit(t,e){return this._client.post("/images/edits",ue({body:t,...e}))}generate(t,e){return this._client.post("/images/generations",{body:t,...e})}}Zr||(Zr={});class ts extends Ye{retrieve(t,e){return this._client.get(`/models/${t}`,e)}list(t){return this._client.getAPIList("/models",es,t)}del(t,e){return this._client.delete(`/models/${t}`,e)}}class es extends We{}!function(t){t.ModelsPage=es}(ts||(ts={}));class ns extends Ye{create(t,e){return this._client.post("/moderations",{body:t,...e})}}var rs;ns||(ns={});class ss extends _e{constructor({baseURL:t=Ue("OPENAI_BASE_URL"),apiKey:e=Ue("OPENAI_API_KEY"),organization:n=Ue("OPENAI_ORG_ID")??null,project:r=Ue("OPENAI_PROJECT_ID")??null,...s}={}){if(void 0===e)throw new Dt("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const i={apiKey:e,organization:n,project:r,...s,baseURL:t||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new Dt("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new Fr(this),this.chat=new ze(this),this.embeddings=new Yr(this),this.files=new Xr(this),this.images=new Zr(this),this.audio=new Ke(this),this.moderations=new ns(this),this.models=new ts(this),this.fineTuning=new Qr(this),this.beta=new Wr(this),this.batches=new Ge(this),this._options=i,this.apiKey=e,this.organization=n,this.project=r}defaultQuery(){return this._options.defaultQuery}defaultHeaders(t){return{...super.defaultHeaders(t),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(t){return{Authorization:`Bearer ${this.apiKey}`}}}rs=ss,ss.OpenAI=rs,ss.OpenAIError=Dt,ss.APIError=Nt,ss.APIConnectionError=Wt,ss.APIConnectionTimeoutError=Ft,ss.APIUserAbortError=qt,ss.NotFoundError=Ht,ss.ConflictError=Jt,ss.RateLimitError=Kt,ss.BadRequestError=Yt,ss.AuthenticationError=Xt,ss.InternalServerError=Gt,ss.PermissionDeniedError=zt,ss.UnprocessableEntityError=Vt,ss.toFile=ae,ss.fileFromPath=Ut;const{OpenAIError:is,APIError:os,APIConnectionError:as,APIConnectionTimeoutError:cs,APIUserAbortError:ls,NotFoundError:hs,ConflictError:us,RateLimitError:fs,BadRequestError:ds,AuthenticationError:ps,InternalServerError:ms,PermissionDeniedError:gs,UnprocessableEntityError:ws}=Qt;var ys=ae,_s=Ut;!function(t){t.Page=We,t.CursorPage=Fe,t.Completions=Fr,t.Chat=ze,t.Embeddings=Yr,t.Files=Xr,t.FileObjectsPage=zr,t.Images=Zr,t.Audio=Ke,t.Moderations=ns,t.Models=ts,t.ModelsPage=es,t.FineTuning=Qr,t.Beta=Wr,t.Batches=Ge,t.BatchesPage=Qe}(ss||(ss={}));class bs extends ss{constructor({baseURL:t=Ue("OPENAI_BASE_URL"),apiKey:e=Ue("AZURE_OPENAI_API_KEY"),apiVersion:n=Ue("OPENAI_API_VERSION"),endpoint:r,deployment:s,azureADTokenProvider:i,dangerouslyAllowBrowser:o,...a}={}){if(!n)throw new Dt("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).");if("function"==typeof i&&(o=!0),!i&&!e)throw new Dt("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&e)throw new Dt("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(e??(e=As),a.defaultQuery={...a.defaultQuery,"api-version":n},t){if(r)throw new Dt("baseURL and endpoint are mutually exclusive")}else{if(r||(r=C.env.AZURE_OPENAI_ENDPOINT),!r)throw new Dt("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");t=`${r}/openai`}super({apiKey:e,baseURL:t,...a,...void 0!==o?{dangerouslyAllowBrowser:o}:{}}),this.apiVersion="",this._azureADTokenProvider=i,this.apiVersion=n,this._deployment=s}buildRequest(t){if(vs.has(t.path)&&"post"===t.method&&void 0!==t.body){if(null==(e=t.body)||"object"!=typeof e||Array.isArray(e))throw new Error("Expected request body to be an object");const n=this._deployment||t.body.model;delete t.body.model,void 0===n||this.baseURL.includes("/deployments")||(t.path=`/deployments/${n}${t.path}`)}var e;return super.buildRequest(t)}async _getAzureADToken(){if("function"==typeof this._azureADTokenProvider){const t=await this._azureADTokenProvider();if(!t||"string"!=typeof t)throw new Dt(`Expected 'azureADTokenProvider' argument to return a string but it returned ${t}`);return t}}authHeaders(t){return{}}async prepareOptions(t){if(t.headers?.Authorization||t.headers?.["api-key"])return super.prepareOptions(t);const e=await this._getAzureADToken();if(t.headers??(t.headers={}),e)t.headers.Authorization=`Bearer ${e}`;else{if(this.apiKey===As)throw new Dt("Unable to handle auth");t.headers["api-key"]=this.apiKey}return super.prepareOptions(t)}}const vs=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches"]),As="<Missing Key>";var Es=ss;export{as as APIConnectionError,cs as APIConnectionTimeoutError,os as APIError,ls as APIUserAbortError,ps as AuthenticationError,bs as AzureOpenAI,ds as BadRequestError,us as ConflictError,ms as InternalServerError,hs as NotFoundError,ss as OpenAI,is as OpenAIError,gs as PermissionDeniedError,fs as RateLimitError,ws as UnprocessableEntityError,Es as default,_s as fileFromPath,ys as toFile};
//# sourceMappingURL=/sm/58366badaf7c9a87b1546690c38a9cb64ed349464a43c021e01819bda8036318.map