@shumai-one/shumai-agent 0.6.1 → 0.6.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/chunk-023w4q1f.js +2 -0
- package/bin/chunk-29r6a67p.js +2 -0
- package/bin/chunk-2exf93nx.js +3 -0
- package/bin/chunk-3ev1fh2w.js +3 -0
- package/bin/chunk-3kt4k4jg.js +11 -0
- package/bin/chunk-62n25c3m.js +2 -0
- package/bin/chunk-6pf9rgk6.js +2 -0
- package/bin/chunk-7bn1mjf2.js +3 -0
- package/bin/chunk-7pwsjw9r.js +8 -0
- package/bin/{chunk-n91txatn.js → chunk-847yv5m2.js} +10 -10
- package/bin/chunk-9fqyh49m.js +2 -0
- package/bin/chunk-a5rn622e.js +7 -0
- package/bin/chunk-akj1v1zj.js +5 -0
- package/bin/{chunk-dcm0shkz.js → chunk-am25vkck.js} +2 -2
- package/bin/chunk-at5qzp08.js +7 -0
- package/bin/chunk-b2n9g75s.js +2 -0
- package/bin/chunk-b767451d.js +3 -0
- package/bin/chunk-bsxxt20c.js +2 -0
- package/bin/{chunk-081jf273.js → chunk-crc78aby.js} +2 -2
- package/bin/chunk-ee8rt9we.js +2 -0
- package/bin/chunk-eh6xcwvv.js +16 -0
- package/bin/chunk-fgabndrh.js +4 -0
- package/bin/chunk-fq1tf20c.js +45 -0
- package/bin/chunk-g7ad4dw4.js +2 -0
- package/bin/chunk-g7v8pfhe.js +2 -0
- package/bin/chunk-gx33h4rt.js +3 -0
- package/bin/chunk-hnpr396w.js +12 -0
- package/bin/chunk-hssdv3mc.js +2 -0
- package/bin/chunk-m3saxrzj.js +13 -0
- package/bin/chunk-mnd4dn3q.js +2 -0
- package/bin/chunk-nmygzasv.js +2 -0
- package/bin/chunk-nwz9f1dy.js +2 -0
- package/bin/chunk-p5nhcxwg.js +3 -0
- package/bin/chunk-pbdctjg4.js +2 -0
- package/bin/chunk-pphsqcqt.js +2 -0
- package/bin/{chunk-rjcyh2qr.js → chunk-pqa01d4g.js} +1 -1
- package/bin/{chunk-d7q1ddrt.js → chunk-q0x8yqms.js} +2 -2
- package/bin/chunk-q5w77y3e.js +2 -0
- package/bin/chunk-rf428t28.js +2 -0
- package/bin/chunk-rkcsrrvy.js +497 -0
- package/bin/chunk-rtqengn3.js +2 -0
- package/bin/chunk-rx0fmt6n.js +4 -0
- package/bin/chunk-ss91akc0.js +2 -0
- package/bin/{chunk-3mt7vfsa.js → chunk-stex0y7j.js} +2 -2
- package/bin/chunk-vngxwvwv.js +2 -0
- package/bin/chunk-w0e5ek1r.js +2 -0
- package/bin/chunk-x71z4a2a.js +3 -0
- package/bin/chunk-z19gfsnw.js +3 -0
- package/bin/chunk-z3gbypjs.js +2 -0
- package/bin/chunk-zphx997k.js +8 -0
- package/bin/shumai-agent-app.js +862 -979
- package/package.json +7 -7
- package/prisma/migrations/20261026024507_hash_api_tokens/migration.sql +28 -0
- package/prisma/migrations/20261026031904_add_audit_log_via/migration.sql +2 -0
- package/prisma/migrations/20261029024626_add_oauth_and_jwks/migration.sql +205 -0
- package/prisma/migrations/20261029030321_default_empty_arrays_oauth/migration.sql +25 -0
- package/prisma/schema.prisma +186 -1
- package/bin/chunk-104551jk.js +0 -2
- package/bin/chunk-12a4ms93.js +0 -2
- package/bin/chunk-21s7ywef.js +0 -2
- package/bin/chunk-2zbfptzv.js +0 -3
- package/bin/chunk-3k48ht8h.js +0 -3
- package/bin/chunk-4qhy3xyh.js +0 -2
- package/bin/chunk-5xpxamqh.js +0 -2
- package/bin/chunk-6gnxwws5.js +0 -2
- package/bin/chunk-6w8btwke.js +0 -2
- package/bin/chunk-795fnqct.js +0 -2
- package/bin/chunk-8qgdqxgq.js +0 -3
- package/bin/chunk-9g06vmtt.js +0 -16
- package/bin/chunk-9k039vqv.js +0 -8
- package/bin/chunk-abfpprr0.js +0 -2
- package/bin/chunk-abswqtw4.js +0 -45
- package/bin/chunk-b7bn9n73.js +0 -2
- package/bin/chunk-brkgxzw3.js +0 -3
- package/bin/chunk-d5cz2jys.js +0 -2
- package/bin/chunk-dnawwy6j.js +0 -2
- package/bin/chunk-eaeecavf.js +0 -4
- package/bin/chunk-ete48wns.js +0 -7
- package/bin/chunk-fe1zpwxx.js +0 -2
- package/bin/chunk-gdp22mc0.js +0 -13
- package/bin/chunk-gpxzz0sd.js +0 -2
- package/bin/chunk-gwfmhykm.js +0 -2
- package/bin/chunk-ha2rjcts.js +0 -3
- package/bin/chunk-hjh1b6ty.js +0 -3
- package/bin/chunk-jg1ya6rg.js +0 -12
- package/bin/chunk-jq958epm.js +0 -3
- package/bin/chunk-kfnrfz1s.js +0 -11
- package/bin/chunk-kr9njcy8.js +0 -2
- package/bin/chunk-m9m58xw1.js +0 -2
- package/bin/chunk-ms2vtvq9.js +0 -2
- package/bin/chunk-n7h0dxfb.js +0 -2
- package/bin/chunk-n7ne3vvj.js +0 -2
- package/bin/chunk-nbj41zxc.js +0 -5
- package/bin/chunk-re34q2ps.js +0 -7
- package/bin/chunk-s13yr8m9.js +0 -8
- package/bin/chunk-tqrmdcmr.js +0 -4
- package/bin/chunk-w1vsn0sd.js +0 -2
- package/bin/chunk-wpstpsy7.js +0 -2
- package/bin/chunk-ytgrcxjs.js +0 -3
- package/bin/chunk-z6b82z34.js +0 -86
|
@@ -1,18 +1,18 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function w(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Jr=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Jr=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(s)=>(+s^r()&15>>+s/4).toString(16))};function dt(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var pt=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class m extends Error{}class T extends m{constructor(e,t,r,s){super(`${T.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let n=t;this.code=n?.code,this.param=n?.param,this.type=n?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Ae({message:r,cause:pt(t)});let n=t?.error;if(e===400)return new mt(e,n,r,s);if(e===401)return new _t(e,n,r,s);if(e===403)return new gt(e,n,r,s);if(e===404)return new yt(e,n,r,s);if(e===409)return new bt(e,n,r,s);if(e===422)return new wt(e,n,r,s);if(e===429)return new xt(e,n,r,s);if(e>=500)return new At(e,n,r,s);return new T(e,n,r,s)}}class N extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ae extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class Ie extends Ae{constructor({message:e}={}){super({message:e??"Request timed out."})}}class mt extends T{}class _t extends T{}class gt extends T{}class yt extends T{}class bt extends T{}class wt extends T{}class xt extends T{}class At extends T{}class It extends m{constructor(){super("Could not parse response content as the length limit was reached")}}class Pt extends m{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class ne extends Error{constructor(e){super(e)}}var Dn=/^[a-z][a-z0-9+.-]*:/i,Es=(e)=>Dn.test(e),j=(e)=>(j=Array.isArray,j(e)),Xr=j;function Vr(e){if(typeof e!=="object")return{};return e??{}}function vs(e){if(!e)return!0;for(let t in e)return!1;return!0}function $s(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ue(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var ks=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var Os=(e)=>{try{return JSON.parse(e)}catch(t){return}};var Q=(e)=>new Promise((t)=>setTimeout(t,e));var he="6.26.0";var Ms=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Wn(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var qn=()=>{let e=Wn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":Fs(Deno.build.os),"X-Stainless-Arch":Ts(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":Fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ts(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Hn();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Hn(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:t,version:`${n}.${o}.${a}`}}}return null}var Ts=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Fs=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Ns,Ls=()=>Ns??(Ns=qn());function Bs(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Kr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function mr(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Kr({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Gr(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Us(e){if(e===null||typeof e!=="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var js=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var zr="RFC3986",Qr=(e)=>String(e),Yr={RFC1738:(e)=>String(e).replace(/%20/g,"+"),RFC3986:Qr},Ds="RFC1738";var _r=(e,t)=>(_r=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),_r(e,t)),Y=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var Zr=1024,Ws=(e,t,r,s,n)=>{if(e.length===0)return e;let o=e;if(typeof e==="symbol")o=Symbol.prototype.toString.call(e);else if(typeof e!=="string")o=String(e);if(r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(f){return"%26%23"+parseInt(f.slice(2),16)+"%3B"});let a="";for(let f=0;f<o.length;f+=Zr){let d=o.length>=Zr?o.slice(f,f+Zr):o,_=[];for(let b=0;b<d.length;++b){let p=d.charCodeAt(b);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===Ds&&(p===40||p===41)){_[_.length]=d.charAt(b);continue}if(p<128){_[_.length]=Y[p];continue}if(p<2048){_[_.length]=Y[192|p>>6]+Y[128|p&63];continue}if(p<55296||p>=57344){_[_.length]=Y[224|p>>12]+Y[128|p>>6&63]+Y[128|p&63];continue}b+=1,p=65536+((p&1023)<<10|d.charCodeAt(b)&1023),_[_.length]=Y[240|p>>18]+Y[128|p>>12&63]+Y[128|p>>6&63]+Y[128|p&63]}a+=_.join("")}return a};function qs(e){if(!e||typeof e!=="object")return!1;return!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function es(e,t){if(j(e)){let r=[];for(let s=0;s<e.length;s+=1)r.push(t(e[s]));return r}return t(e)}var Js={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Xs=function(e,t){Array.prototype.push.apply(e,j(t)?t:[t])},Hs,M={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ws,encodeValuesOnly:!1,format:zr,formatter:Qr,indices:!1,serializeDate(e){return(Hs??(Hs=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Vn(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="symbol"||typeof e==="bigint"}var ts={};function Vs(e,t,r,s,n,o,a,f,d,_,b,p,u,x,y,C,R,P){let I=e,O=P,v=0,q=!1;while((O=O.get(ts))!==void 0&&!q){let S=O.get(e);if(v+=1,typeof S<"u")if(S===v)throw RangeError("Cyclic object value");else q=!0;if(typeof O.get(ts)>"u")v=0}if(typeof _==="function")I=_(t,I);else if(I instanceof Date)I=u?.(I);else if(r==="comma"&&j(I))I=es(I,function(S){if(S instanceof Date)return u?.(S);return S});if(I===null){if(o)return d&&!C?d(t,M.encoder,R,"key",x):t;I=""}if(Vn(I)||qs(I)){if(d){let S=C?t:d(t,M.encoder,R,"key",x);return[y?.(S)+"="+y?.(d(I,M.encoder,R,"value",x))]}return[y?.(t)+"="+y?.(String(I))]}let F=[];if(typeof I>"u")return F;let E;if(r==="comma"&&j(I)){if(C&&d)I=es(I,d);E=[{value:I.length>0?I.join(",")||null:void 0}]}else if(j(_))E=_;else{let S=Object.keys(I);E=b?S.sort(b):S}let D=f?String(t).replace(/\./g,"%2E"):String(t),se=s&&j(I)&&I.length===1?D+"[]":D;if(n&&j(I)&&I.length===0)return se+"[]";for(let S=0;S<E.length;++S){let fe=E[S],Rs=typeof fe==="object"&&typeof fe.value<"u"?fe.value:I[fe];if(a&&Rs===null)continue;let Hr=p&&f?fe.replace(/\./g,"%2E"):fe,Un=j(I)?typeof r==="function"?r(se,Hr):se:se+(p?"."+Hr:"["+Hr+"]");P.set(e,v);let Cs=new WeakMap;Cs.set(ts,P),Xs(F,Vs(Rs,Un,r,s,n,o,a,f,r==="comma"&&C&&j(I)?null:d,_,b,p,u,x,y,C,R,Cs))}return F}function Kn(e=M){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!=="function")throw TypeError("Encoder has to be a function.");let t=e.charset||M.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=zr;if(typeof e.format<"u"){if(!_r(Yr,e.format))throw TypeError("Unknown format option provided.");r=e.format}let s=Yr[r],n=M.filter;if(typeof e.filter==="function"||j(e.filter))n=e.filter;let o;if(e.arrayFormat&&e.arrayFormat in Js)o=e.arrayFormat;else if("indices"in e)o=e.indices?"indices":"repeat";else o=M.arrayFormat;if("commaRoundTrip"in e&&typeof e.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof e.allowDots>"u"?!!e.encodeDotInKeys===!0?!0:M.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==="boolean"?e.addQueryPrefix:M.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays==="boolean"?!!e.allowEmptyArrays:M.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel==="boolean"?e.charsetSentinel:M.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?M.delimiter:e.delimiter,encode:typeof e.encode==="boolean"?e.encode:M.encode,encodeDotInKeys:typeof e.encodeDotInKeys==="boolean"?e.encodeDotInKeys:M.encodeDotInKeys,encoder:typeof e.encoder==="function"?e.encoder:M.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==="boolean"?e.encodeValuesOnly:M.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof e.serializeDate==="function"?e.serializeDate:M.serializeDate,skipNulls:typeof e.skipNulls==="boolean"?e.skipNulls:M.skipNulls,sort:typeof e.sort==="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling==="boolean"?e.strictNullHandling:M.strictNullHandling}}function Ks(e,t={}){let r=e,s=Kn(t),n,o;if(typeof s.filter==="function")o=s.filter,r=o("",r);else if(j(s.filter))o=s.filter,n=o;let a=[];if(typeof r!=="object"||r===null)return"";let f=Js[s.arrayFormat],d=f==="comma"&&s.commaRoundTrip;if(!n)n=Object.keys(r);if(s.sort)n.sort(s.sort);let _=new WeakMap;for(let u=0;u<n.length;++u){let x=n[u];if(s.skipNulls&&r[x]===null)continue;Xs(a,Vs(r[x],x,f,d,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,_))}let b=a.join(s.delimiter),p=s.addQueryPrefix===!0?"?":"";if(s.charsetSentinel)if(s.charset==="iso-8859-1")p+="utf8=%26%2310003%3B&";else p+="utf8=%E2%9C%93&";return b.length>0?p+b:""}function Gs(e){return Ks(e,{arrayFormat:"brackets"})}function Ys(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var zs;function je(e){let t;return(zs??(t=new globalThis.TextEncoder,zs=t.encode.bind(t)))(e)}var Qs;function rs(e){let t;return(Qs??(t=new globalThis.TextDecoder,Qs=t.decode.bind(t)))(e)}var H,J;class De{constructor(){H.set(this,void 0),J.set(this,void 0),w(this,H,new Uint8Array,"f"),w(this,J,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?je(e):e;w(this,H,Ys([i(this,H,"f"),t]),"f");let r=[],s;while((s=zn(i(this,H,"f"),i(this,J,"f")))!=null){if(s.carriage&&i(this,J,"f")==null){w(this,J,s.index,"f");continue}if(i(this,J,"f")!=null&&(s.index!==i(this,J,"f")+1||s.carriage)){r.push(rs(i(this,H,"f").subarray(0,i(this,J,"f")-1))),w(this,H,i(this,H,"f").subarray(i(this,J,"f")),"f"),w(this,J,null,"f");continue}let n=i(this,J,"f")!==null?s.preceding-1:s.preceding,o=rs(i(this,H,"f").subarray(0,n));r.push(o),w(this,H,i(this,H,"f").subarray(s.index),"f"),w(this,J,null,"f")}return r}flush(){if(!i(this,H,"f").length)return[];return this.decode(`
|
|
2
|
+
function b(e,t,r,s,n){if(s==="m")throw TypeError("Private method is not writable");if(s==="a"&&!n)throw TypeError("Private accessor was defined without a setter");if(typeof t==="function"?e!==t||!n:!t.has(e))throw TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(e,r):n?n.value=r:t.set(e,r),r}function i(e,t,r,s){if(r==="a"&&!s)throw TypeError("Private accessor was defined without a getter");if(typeof t==="function"?e!==t||!s:!t.has(e))throw TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(e):s?s.value:t.get(e)}var Jr=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Jr=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(s)=>(+s^r()&15>>+s/4).toString(16))};function dt(e){return typeof e==="object"&&e!==null&&(("name"in e)&&e.name==="AbortError"||("message"in e)&&String(e.message).includes("FetchRequestCanceledException"))}var pt=(e)=>{if(e instanceof Error)return e;if(typeof e==="object"&&e!==null){try{if(Object.prototype.toString.call(e)==="[object Error]"){let t=Error(e.message,e.cause?{cause:e.cause}:{});if(e.stack)t.stack=e.stack;if(e.cause&&!t.cause)t.cause=e.cause;if(e.name)t.name=e.name;return t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)};class m extends Error{}class T extends m{constructor(e,t,r,s){super(`${T.makeMessage(e,t,r)}`);this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;let n=t;this.code=n?.code,this.param=n?.param,this.type=n?.type}static makeMessage(e,t,r){let s=t?.message?typeof t.message==="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;if(e&&s)return`${e} ${s}`;if(e)return`${e} status code (no body)`;if(s)return s;return"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Ae({message:r,cause:pt(t)});let n=t?.error;if(e===400)return new mt(e,n,r,s);if(e===401)return new _t(e,n,r,s);if(e===403)return new gt(e,n,r,s);if(e===404)return new yt(e,n,r,s);if(e===409)return new bt(e,n,r,s);if(e===422)return new wt(e,n,r,s);if(e===429)return new xt(e,n,r,s);if(e>=500)return new At(e,n,r,s);return new T(e,n,r,s)}}class N extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ae extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0);if(t)this.cause=t}}class Ie extends Ae{constructor({message:e}={}){super({message:e??"Request timed out."})}}class mt extends T{}class _t extends T{}class gt extends T{}class yt extends T{}class bt extends T{}class wt extends T{}class xt extends T{}class At extends T{}class It extends m{constructor(){super("Could not parse response content as the length limit was reached")}}class Pt extends m{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class ne extends Error{constructor(e){super(e)}}var Dn=/^[a-z][a-z0-9+.-]*:/i,Es=(e)=>Dn.test(e),j=(e)=>(j=Array.isArray,j(e)),Xr=j;function Vr(e){if(typeof e!=="object")return{};return e??{}}function vs(e){if(!e)return!0;for(let t in e)return!1;return!0}function $s(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ue(e){return e!=null&&typeof e==="object"&&!Array.isArray(e)}var ks=(e,t)=>{if(typeof t!=="number"||!Number.isInteger(t))throw new m(`${e} must be an integer`);if(t<0)throw new m(`${e} must be a positive integer`);return t};var Os=(e)=>{try{return JSON.parse(e)}catch(t){return}};var Q=(e)=>new Promise((t)=>setTimeout(t,e));var he="6.26.0";var Ms=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Wn(){if(typeof Deno<"u"&&Deno.build!=null)return"deno";if(typeof EdgeRuntime<"u")return"edge";if(Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]")return"node";return"unknown"}var qn=()=>{let e=Wn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":Fs(Deno.build.os),"X-Stainless-Arch":Ts(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version==="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":Fs(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ts(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let t=Hn();if(t)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version};return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":he,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Hn(){if(typeof navigator>"u"||!navigator)return null;let e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:t,pattern:r}of e){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:t,version:`${n}.${o}.${a}`}}}return null}var Ts=(e)=>{if(e==="x32")return"x32";if(e==="x86_64"||e==="x64")return"x64";if(e==="arm")return"arm";if(e==="aarch64"||e==="arm64")return"arm64";if(e)return`other:${e}`;return"unknown"},Fs=(e)=>{if(e=e.toLowerCase(),e.includes("ios"))return"iOS";if(e==="android")return"Android";if(e==="darwin")return"MacOS";if(e==="win32")return"Windows";if(e==="freebsd")return"FreeBSD";if(e==="openbsd")return"OpenBSD";if(e==="linux")return"Linux";if(e)return`Other:${e}`;return"Unknown"},Ns,Ls=()=>Ns??(Ns=qn());function Bs(){if(typeof fetch<"u")return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Kr(...e){let t=globalThis.ReadableStream;if(typeof t>"u")throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function pr(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Kr({start(){},async pull(r){let{done:s,value:n}=await t.next();if(s)r.close();else r.enqueue(n)},async cancel(){await t.return?.()}})}function Gr(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let r=await t.read();if(r?.done)t.releaseLock();return r}catch(r){throw t.releaseLock(),r}},async return(){let r=t.cancel();return t.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Us(e){if(e===null||typeof e!=="object")return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),r=t.cancel();t.releaseLock(),await r}var js=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)});var zr="RFC3986",Qr=(e)=>String(e),Yr={RFC1738:(e)=>String(e).replace(/%20/g,"+"),RFC3986:Qr},Ds="RFC1738";var mr=(e,t)=>(mr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),mr(e,t)),Y=(()=>{let e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})();var Zr=1024,Ws=(e,t,r,s,n)=>{if(e.length===0)return e;let o=e;if(typeof e==="symbol")o=Symbol.prototype.toString.call(e);else if(typeof e!=="string")o=String(e);if(r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(f){return"%26%23"+parseInt(f.slice(2),16)+"%3B"});let a="";for(let f=0;f<o.length;f+=Zr){let d=o.length>=Zr?o.slice(f,f+Zr):o,_=[];for(let y=0;y<d.length;++y){let p=d.charCodeAt(y);if(p===45||p===46||p===95||p===126||p>=48&&p<=57||p>=65&&p<=90||p>=97&&p<=122||n===Ds&&(p===40||p===41)){_[_.length]=d.charAt(y);continue}if(p<128){_[_.length]=Y[p];continue}if(p<2048){_[_.length]=Y[192|p>>6]+Y[128|p&63];continue}if(p<55296||p>=57344){_[_.length]=Y[224|p>>12]+Y[128|p>>6&63]+Y[128|p&63];continue}y+=1,p=65536+((p&1023)<<10|d.charCodeAt(y)&1023),_[_.length]=Y[240|p>>18]+Y[128|p>>12&63]+Y[128|p>>6&63]+Y[128|p&63]}a+=_.join("")}return a};function qs(e){if(!e||typeof e!=="object")return!1;return!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function es(e,t){if(j(e)){let r=[];for(let s=0;s<e.length;s+=1)r.push(t(e[s]));return r}return t(e)}var Js={brackets(e){return String(e)+"[]"},comma:"comma",indices(e,t){return String(e)+"["+t+"]"},repeat(e){return String(e)}},Xs=function(e,t){Array.prototype.push.apply(e,j(t)?t:[t])},Hs,M={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ws,encodeValuesOnly:!1,format:zr,formatter:Qr,indices:!1,serializeDate(e){return(Hs??(Hs=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1};function Vn(e){return typeof e==="string"||typeof e==="number"||typeof e==="boolean"||typeof e==="symbol"||typeof e==="bigint"}var ts={};function Vs(e,t,r,s,n,o,a,f,d,_,y,p,u,w,g,R,S,I){let A=e,k=I,E=0,q=!1;while((k=k.get(ts))!==void 0&&!q){let P=k.get(e);if(E+=1,typeof P<"u")if(P===E)throw RangeError("Cyclic object value");else q=!0;if(typeof k.get(ts)>"u")E=0}if(typeof _==="function")A=_(t,A);else if(A instanceof Date)A=u?.(A);else if(r==="comma"&&j(A))A=es(A,function(P){if(P instanceof Date)return u?.(P);return P});if(A===null){if(o)return d&&!R?d(t,M.encoder,S,"key",w):t;A=""}if(Vn(A)||qs(A)){if(d){let P=R?t:d(t,M.encoder,S,"key",w);return[g?.(P)+"="+g?.(d(A,M.encoder,S,"value",w))]}return[g?.(t)+"="+g?.(String(A))]}let F=[];if(typeof A>"u")return F;let C;if(r==="comma"&&j(A)){if(R&&d)A=es(A,d);C=[{value:A.length>0?A.join(",")||null:void 0}]}else if(j(_))C=_;else{let P=Object.keys(A);C=y?P.sort(y):P}let D=f?String(t).replace(/\./g,"%2E"):String(t),se=s&&j(A)&&A.length===1?D+"[]":D;if(n&&j(A)&&A.length===0)return se+"[]";for(let P=0;P<C.length;++P){let fe=C[P],Rs=typeof fe==="object"&&typeof fe.value<"u"?fe.value:A[fe];if(a&&Rs===null)continue;let Hr=p&&f?fe.replace(/\./g,"%2E"):fe,Un=j(A)?typeof r==="function"?r(se,Hr):se:se+(p?"."+Hr:"["+Hr+"]");I.set(e,E);let Cs=new WeakMap;Cs.set(ts,I),Xs(F,Vs(Rs,Un,r,s,n,o,a,f,r==="comma"&&R&&j(A)?null:d,_,y,p,u,w,g,R,S,Cs))}return F}function Kn(e=M){if(typeof e.allowEmptyArrays<"u"&&typeof e.allowEmptyArrays!=="boolean")throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof e.encodeDotInKeys<"u"&&typeof e.encodeDotInKeys!=="boolean")throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&typeof e.encoder<"u"&&typeof e.encoder!=="function")throw TypeError("Encoder has to be a function.");let t=e.charset||M.charset;if(typeof e.charset<"u"&&e.charset!=="utf-8"&&e.charset!=="iso-8859-1")throw TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=zr;if(typeof e.format<"u"){if(!mr(Yr,e.format))throw TypeError("Unknown format option provided.");r=e.format}let s=Yr[r],n=M.filter;if(typeof e.filter==="function"||j(e.filter))n=e.filter;let o;if(e.arrayFormat&&e.arrayFormat in Js)o=e.arrayFormat;else if("indices"in e)o=e.indices?"indices":"repeat";else o=M.arrayFormat;if("commaRoundTrip"in e&&typeof e.commaRoundTrip!=="boolean")throw TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof e.allowDots>"u"?!!e.encodeDotInKeys===!0?!0:M.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==="boolean"?e.addQueryPrefix:M.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof e.allowEmptyArrays==="boolean"?!!e.allowEmptyArrays:M.allowEmptyArrays,arrayFormat:o,charset:t,charsetSentinel:typeof e.charsetSentinel==="boolean"?e.charsetSentinel:M.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:typeof e.delimiter>"u"?M.delimiter:e.delimiter,encode:typeof e.encode==="boolean"?e.encode:M.encode,encodeDotInKeys:typeof e.encodeDotInKeys==="boolean"?e.encodeDotInKeys:M.encodeDotInKeys,encoder:typeof e.encoder==="function"?e.encoder:M.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==="boolean"?e.encodeValuesOnly:M.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof e.serializeDate==="function"?e.serializeDate:M.serializeDate,skipNulls:typeof e.skipNulls==="boolean"?e.skipNulls:M.skipNulls,sort:typeof e.sort==="function"?e.sort:null,strictNullHandling:typeof e.strictNullHandling==="boolean"?e.strictNullHandling:M.strictNullHandling}}function Ks(e,t={}){let r=e,s=Kn(t),n,o;if(typeof s.filter==="function")o=s.filter,r=o("",r);else if(j(s.filter))o=s.filter,n=o;let a=[];if(typeof r!=="object"||r===null)return"";let f=Js[s.arrayFormat],d=f==="comma"&&s.commaRoundTrip;if(!n)n=Object.keys(r);if(s.sort)n.sort(s.sort);let _=new WeakMap;for(let u=0;u<n.length;++u){let w=n[u];if(s.skipNulls&&r[w]===null)continue;Xs(a,Vs(r[w],w,f,d,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,_))}let y=a.join(s.delimiter),p=s.addQueryPrefix===!0?"?":"";if(s.charsetSentinel)if(s.charset==="iso-8859-1")p+="utf8=%26%2310003%3B&";else p+="utf8=%E2%9C%93&";return y.length>0?p+y:""}function Gs(e){return Ks(e,{arrayFormat:"brackets"})}function Ys(e){let t=0;for(let n of e)t+=n.length;let r=new Uint8Array(t),s=0;for(let n of e)r.set(n,s),s+=n.length;return r}var zs;function je(e){let t;return(zs??(t=new globalThis.TextEncoder,zs=t.encode.bind(t)))(e)}var Qs;function rs(e){let t;return(Qs??(t=new globalThis.TextDecoder,Qs=t.decode.bind(t)))(e)}var H,J;class De{constructor(){H.set(this,void 0),J.set(this,void 0),b(this,H,new Uint8Array,"f"),b(this,J,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==="string"?je(e):e;b(this,H,Ys([i(this,H,"f"),t]),"f");let r=[],s;while((s=zn(i(this,H,"f"),i(this,J,"f")))!=null){if(s.carriage&&i(this,J,"f")==null){b(this,J,s.index,"f");continue}if(i(this,J,"f")!=null&&(s.index!==i(this,J,"f")+1||s.carriage)){r.push(rs(i(this,H,"f").subarray(0,i(this,J,"f")-1))),b(this,H,i(this,H,"f").subarray(i(this,J,"f")),"f"),b(this,J,null,"f");continue}let n=i(this,J,"f")!==null?s.preceding-1:s.preceding,o=rs(i(this,H,"f").subarray(0,n));r.push(o),b(this,H,i(this,H,"f").subarray(s.index),"f"),b(this,J,null,"f")}return r}flush(){if(!i(this,H,"f").length)return[];return this.decode(`
|
|
3
3
|
`)}}H=new WeakMap,J=new WeakMap;De.NEWLINE_CHARS=new Set([`
|
|
4
|
-
`,"\r"]);De.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zn(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Zs(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var
|
|
4
|
+
`,"\r"]);De.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function zn(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Zs(e){for(let s=0;s<e.length-1;s++){if(e[s]===10&&e[s+1]===10)return s+2;if(e[s]===13&&e[s+1]===13)return s+2;if(e[s]===13&&e[s+1]===10&&s+3<e.length&&e[s+2]===13&&e[s+3]===10)return s+4}return-1}var gr={off:0,error:200,warn:300,info:400,debug:500},ss=(e,t,r)=>{if(!e)return;if($s(gr,e))return e;v(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(gr))}`);return};function St(){}function _r(e,t,r){if(!t||gr[e]>gr[r])return St;else return t[e].bind(t)}var Qn={error:St,warn:St,info:St,debug:St},en=new WeakMap;function v(e){let t=e.logger,r=e.logLevel??"off";if(!t)return Qn;let s=en.get(t);if(s&&s[0]===r)return s[1];let n={error:_r("error",t,r),warn:_r("warn",t,r),info:_r("info",t,r),debug:_r("debug",t,r)};return en.set(t,[r,n]),n}var oe=(e)=>{if(e.options)e.options={...e.options},delete e.options.headers;if(e.headers)e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([t,r])=>[t,t.toLowerCase()==="authorization"||t.toLowerCase()==="cookie"||t.toLowerCase()==="set-cookie"?"***":r]));if("retryOfRequestLogID"in e){if(e.retryOfRequestLogID)e.retryOf=e.retryOfRequestLogID;delete e.retryOfRequestLogID}return e};var Rt;class X{constructor(e,t,r){this.iterator=e,Rt.set(this,void 0),this.controller=t,b(this,Rt,r,"f")}static fromSSEResponse(e,t,r,s){let n=!1,o=r?v(r):console;async function*a(){if(n)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let f=!1;try{for await(let d of Yn(e,t)){if(f)continue;if(d.data.startsWith("[DONE]")){f=!0;continue}if(d.event===null||!d.event.startsWith("thread.")){let _;try{_=JSON.parse(d.data)}catch(y){throw o.error("Could not parse message into JSON:",d.data),o.error("From chunk:",d.raw),y}if(_&&_.error)throw new T(void 0,_.error,void 0,e.headers);yield s?{event:d.event,data:_}:_}else{let _;try{_=JSON.parse(d.data)}catch(y){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),y}if(d.event=="error")throw new T(void 0,_.error,_.message,void 0);yield{event:d.event,data:_}}}f=!0}catch(d){if(dt(d))return;throw d}finally{if(!f)t.abort()}}return new X(a,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*n(){let a=new De,f=Gr(e);for await(let d of f)for(let _ of a.decode(d))yield _;for(let d of a.flush())yield d}async function*o(){if(s)throw new m("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let f of n()){if(a)continue;if(f)yield JSON.parse(f)}a=!0}catch(f){if(dt(f))return;throw f}finally{if(!a)t.abort()}}return new X(o,t,r)}[(Rt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),s=(n)=>({next:()=>{if(n.length===0){let o=r.next();e.push(o),t.push(o)}return n.shift()}});return[new X(()=>s(e),this.controller,i(this,Rt,"f")),new X(()=>s(t),this.controller,i(this,Rt,"f"))]}toReadableStream(){let e=this,t;return Kr({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:s,done:n}=await t.next();if(n)return r.close();let o=je(JSON.stringify(s)+`
|
|
5
5
|
`);r.enqueue(o)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*Yn(e,t){if(!e.body){if(t.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative")throw new m("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new m("Attempted to iterate over a response with no body")}let r=new tn,s=new De,n=Gr(e.body);for await(let o of Zn(n))for(let a of s.decode(o)){let f=r.decode(a);if(f)yield f}for(let o of s.flush()){let a=r.decode(o);if(a)yield a}}async function*Zn(e){let t=new Uint8Array;for await(let r of e){if(r==null)continue;let s=r instanceof ArrayBuffer?new Uint8Array(r):typeof r==="string"?je(r):r,n=new Uint8Array(t.length+s.length);n.set(t),n.set(s,t.length),t=n;let o;while((o=Zs(t))!==-1)yield t.slice(0,o),t=t.slice(o)}if(t.length>0)yield t}class tn{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r"))e=e.substring(0,e.length-1);if(!e){if(!this.event&&!this.data.length)return null;let n={event:this.event,data:this.data.join(`
|
|
6
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=eo(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function eo(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function
|
|
6
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],n}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=eo(e,":");if(s.startsWith(" "))s=s.substring(1);if(t==="event")this.event=s;else if(t==="data")this.data.push(s);return null}}function eo(e,t){let r=e.indexOf(t);if(r!==-1)return[e.substring(0,r),t,e.substring(r+t.length)];return[e,"",""]}async function yr(e,t){let{response:r,requestLogID:s,retryOfRequestLogID:n,startTime:o}=t,a=await(async()=>{if(t.options.stream){if(v(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)return t.options.__streamClass.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData);return X.fromSSEResponse(r,t.controller,e,t.options.__synthesizeEventData)}if(r.status===204)return null;if(t.options.__binaryResponse)return r;let d=r.headers.get("content-type")?.split(";")[0]?.trim();if(d?.includes("application/json")||d?.endsWith("+json")){if(r.headers.get("content-length")==="0")return;let u=await r.json();return ns(u,r)}return await r.text()})();return v(e).debug(`[${s}] response parsed`,oe({retryOfRequestLogID:n,url:r.url,status:r.status,body:a,durationMs:Date.now()-o})),a}function ns(e,t){if(!e||typeof e!=="object"||Array.isArray(e))return e;return Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}var Ct;class Pe extends Promise{constructor(e,t,r=yr){super((s)=>{s(null)});this.responsePromise=t,this.parseResponse=r,Ct.set(this,void 0),b(this,Ct,e,"f")}_thenUnwrap(e){return new Pe(i(this,Ct,"f"),this.responsePromise,async(t,r)=>ns(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then((e)=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){if(!this.parsedPromise)this.parsedPromise=this.responsePromise.then((e)=>this.parseResponse(i(this,Ct,"f"),e));return this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Ct=new WeakMap;var br;class wr{constructor(e,t,r,s){br.set(this,void 0),b(this,br,e,"f"),this.options=s,this.response=t,this.body=r}hasNextPage(){if(!this.getPaginatedItems().length)return!1;return this.nextPageRequestOptions()!=null}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await i(this,br,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;yield e;while(e.hasNextPage())e=await e.getNextPage(),yield e}async*[(br=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}}class xr extends Pe{constructor(e,t,r){super(e,t,async(s,n)=>new r(s,n.response,await yr(s,n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}}class ie extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class x extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;if(!t)return null;return{...this.options,query:{...Vr(this.options.query),after:t}}}}class Z extends wr{constructor(e,t,r,s){super(e,t,r,s);this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){if(this.has_more===!1)return!1;return super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;if(!e)return null;return{...this.options,query:{...Vr(this.options.query),after:e}}}}var as=()=>{if(typeof File>"u"){let{process:e}=globalThis,t=typeof e?.versions?.node==="string"&&parseInt(e.versions.node.split("."))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function We(e,t,r){return as(),new File(e,t??"unknown_file",r)}function Et(e){return(typeof e==="object"&&e!==null&&(("name"in e)&&e.name&&String(e.name)||("url"in e)&&e.url&&String(e.url)||("filename"in e)&&e.filename&&String(e.filename)||("path"in e)&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}var Ar=(e)=>e!=null&&typeof e==="object"&&typeof e[Symbol.asyncIterator]==="function",ae=async(e,t)=>{if(!os(e.body))return e;return{...e,body:await sn(e.body,t)}},K=async(e,t)=>({...e,body:await sn(e.body,t)}),rn=new WeakMap;function ro(e){let t=typeof e==="function"?e:e.fetch,r=rn.get(t);if(r)return r;let s=(async()=>{try{let n="Response"in t?t.Response:(await t("data:,")).constructor,o=new FormData;if(o.toString()===await new n(o).text())return!1;return!0}catch{return!0}})();return rn.set(t,s),s}var sn=async(e,t)=>{if(!await ro(t))throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(e||{}).map(([s,n])=>is(r,s,n))),r},nn=(e)=>e instanceof Blob&&("name"in e),so=(e)=>typeof e==="object"&&e!==null&&(e instanceof Response||Ar(e)||nn(e)),os=(e)=>{if(so(e))return!0;if(Array.isArray(e))return e.some(os);if(e&&typeof e==="object"){for(let t in e)if(os(e[t]))return!0}return!1},is=async(e,t,r)=>{if(r===void 0)return;if(r==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof r==="string"||typeof r==="number"||typeof r==="boolean")e.append(t,String(r));else if(r instanceof Response)e.append(t,We([await r.blob()],Et(r)));else if(Ar(r))e.append(t,We([await new Response(pr(r)).blob()],Et(r)));else if(nn(r))e.append(t,r,Et(r));else if(Array.isArray(r))await Promise.all(r.map((s)=>is(e,t+"[]",s)));else if(typeof r==="object")await Promise.all(Object.entries(r).map(([s,n])=>is(e,`${t}[${s}]`,n)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)};var on=(e)=>e!=null&&typeof e==="object"&&typeof e.size==="number"&&typeof e.type==="string"&&typeof e.text==="function"&&typeof e.slice==="function"&&typeof e.arrayBuffer==="function",no=(e)=>e!=null&&typeof e==="object"&&typeof e.name==="string"&&typeof e.lastModified==="number"&&on(e),oo=(e)=>e!=null&&typeof e==="object"&&typeof e.url==="string"&&typeof e.blob==="function";async function Ir(e,t,r){if(as(),e=await e,no(e)){if(e instanceof File)return e;return We([await e.arrayBuffer()],e.name)}if(oo(e)){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),We(await ls(n),t,r)}let s=await ls(e);if(t||(t=Et(e)),!r?.type){let n=s.find((o)=>typeof o==="object"&&("type"in o)&&o.type);if(typeof n==="string")r={...r,type:n}}return We(s,t,r)}async function ls(e){let t=[];if(typeof e==="string"||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(on(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(Ar(e))for await(let r of e)t.push(...await ls(r));else{let r=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${r?`; constructor: ${r}`:""}${io(e)}`)}return t}function io(e){if(typeof e!=="object"||e===null)return"";return`; props: [${Object.getOwnPropertyNames(e).map((r)=>`"${r}"`).join(", ")}]`}class c{constructor(e){this._client=e}}function ln(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var an=Object.freeze(Object.create(null)),lo=(e=ln)=>function(r,...s){if(r.length===1)return r[0];let n=!1,o=[],a=r.reduce((y,p,u)=>{if(/[?#]/.test(p))n=!0;let w=s[u],g=(n?encodeURIComponent:e)(""+w);if(u!==s.length&&(w==null||typeof w==="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??an)??an)?.toString))g=w+"",o.push({start:y.length+p.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`});return y+p+(u===s.length?"":g)},""),f=a.split(/[?#]/,1)[0],d=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,_;while((_=d.exec(f))!==null)o.push({start:_.index,length:_[0].length,error:`Value "${_[0]}" can't be safely passed as a path parameter`});if(o.sort((y,p)=>y.start-p.start),o.length>0){let y=0,p=o.reduce((u,w)=>{let g=" ".repeat(w.start-y),R="^".repeat(w.length);return y=w.start+w.length,u+g+R},"");throw new m(`Path parameters result in path with invalid segments:
|
|
7
7
|
${o.map((u)=>u.error).join(`
|
|
8
8
|
`)}
|
|
9
9
|
${a}
|
|
10
|
-
${p}`)}return a},l=lo(ln);class qe extends c{list(e,t={},r){return this._client.getAPIList(l`/chat/completions/${e}/messages`,A,{query:t,...r})}}function vt(e){return e!==void 0&&"function"in e&&e.function!==void 0}function $t(e){return e?.$brand==="auto-parseable-response-format"}function Se(e){return e?.$brand==="auto-parseable-tool"}function cn(e,t){if(!t||!cs(t))return{...e,choices:e.choices.map((r)=>(fn(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))};return kt(e,t)}function kt(e,t){let r=e.choices.map((s)=>{if(s.finish_reason==="length")throw new It;if(s.finish_reason==="content_filter")throw new Pt;return fn(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map((n)=>ho(t,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?fo(t,s.message.content):null}}});return{...e,choices:r}}function fo(e,t){if(e.response_format?.type!=="json_schema")return null;if(e.response_format?.type==="json_schema"){if("$parseRaw"in e.response_format)return e.response_format.$parseRaw(t);return JSON.parse(t)}return null}function ho(e,t){let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Se(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function un(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return vt(r)&&(Se(r)||r?.function.strict||!1)}function cs(e){if($t(e.response_format))return!0;return e.tools?.some((t)=>Se(t)||t.type==="function"&&t.function.strict===!0)??!1}function fn(e){for(let t of e||[])if(t.type!=="function")throw new m(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function hn(e){for(let t of e??[]){if(t.type!=="function")throw new m(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new m(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var He=(e)=>e?.role==="assistant",us=(e)=>e?.role==="tool";var fs,Sr,Rr,Tt,Ft,Cr,Nt,le,Mt,Er,vr,Je,dn;class Re{constructor(){fs.add(this),this.controller=new AbortController,Sr.set(this,void 0),Rr.set(this,()=>{}),Tt.set(this,()=>{}),Ft.set(this,void 0),Cr.set(this,()=>{}),Nt.set(this,()=>{}),le.set(this,{}),Mt.set(this,!1),Er.set(this,!1),vr.set(this,!1),Je.set(this,!1),w(this,Sr,new Promise((e,t)=>{w(this,Rr,e,"f"),w(this,Tt,t,"f")}),"f"),w(this,Ft,new Promise((e,t)=>{w(this,Cr,e,"f"),w(this,Nt,t,"f")}),"f"),i(this,Sr,"f").catch(()=>{}),i(this,Ft,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},i(this,fs,"m",dn).bind(this))},0)}_connected(){if(this.ended)return;i(this,Rr,"f").call(this),this._emit("connect")}get ended(){return i(this,Mt,"f")}get errored(){return i(this,Er,"f")}get aborted(){return i(this,vr,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,le,"f")[e]||(i(this,le,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,le,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(i(this,le,"f")[e]||(i(this,le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(w(this,Je,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){w(this,Je,!0,"f"),await i(this,Ft,"f")}_emit(e,...t){if(i(this,Mt,"f"))return;if(e==="end")w(this,Mt,!0,"f"),i(this,Cr,"f").call(this);let r=i(this,le,"f")[e];if(r)i(this,le,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!i(this,Je,"f")&&!r?.length)Promise.reject(s);i(this,Tt,"f").call(this,s),i(this,Nt,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!i(this,Je,"f")&&!r?.length)Promise.reject(s);i(this,Tt,"f").call(this,s),i(this,Nt,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Sr=new WeakMap,Rr=new WeakMap,Tt=new WeakMap,Ft=new WeakMap,Cr=new WeakMap,Nt=new WeakMap,le=new WeakMap,Mt=new WeakMap,Er=new WeakMap,vr=new WeakMap,Je=new WeakMap,fs=new WeakSet,dn=function(t){if(w(this,Er,!0,"f"),t instanceof Error&&t.name==="AbortError")t=new N;if(t instanceof N)return w(this,vr,!0,"f"),this._emit("abort",t);if(t instanceof m)return this._emit("error",t);if(t instanceof Error){let r=new m(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new m(String(t)))};function pn(e){return typeof e.parse==="function"}var W,hs,$r,ds,ps,ms,mn,_n,po=10;class Lt extends Re{constructor(){super(...arguments);W.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;if(t)this._addMessage(t);return e}_addMessage(e,t=!0){if(!("content"in e))e.content=null;if(this.messages.push(e),t){if(this._emit("message",e),us(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(He(e)&&e.tool_calls){for(let r of e.tool_calls)if(r.type==="function")this._emit("functionToolCall",r.function)}}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new m("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),i(this,W,"m",hs).call(this)}async finalMessage(){return await this.done(),i(this,W,"m",$r).call(this)}async finalFunctionToolCall(){return await this.done(),i(this,W,"m",ds).call(this)}async finalFunctionToolCallResult(){return await this.done(),i(this,W,"m",ps).call(this)}async totalUsage(){return await this.done(),i(this,W,"m",ms).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];if(e)this._emit("finalChatCompletion",e);let t=i(this,W,"m",$r).call(this);if(t)this._emit("finalMessage",t);let r=i(this,W,"m",hs).call(this);if(r)this._emit("finalContent",r);let s=i(this,W,"m",ds).call(this);if(s)this._emit("finalFunctionToolCall",s);let n=i(this,W,"m",ps).call(this);if(n!=null)this._emit("finalFunctionToolCallResult",n);if(this._chatCompletions.some((o)=>o.usage))this._emit("totalUsage",i(this,W,"m",ms).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,W,"m",mn).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(kt(n,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let{tool_choice:n="auto",stream:o,...a}=t,f=typeof n!=="string"&&n.type==="function"&&n?.function?.name,{maxChatCompletions:d=po}=r||{},_=t.tools.map((u)=>{if(Se(u)){if(!u.$callback)throw new m("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),b={};for(let u of _)if(u.type==="function")b[u.function.name||u.function.function.name]=u.function;let p="tools"in t?_.map((u)=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(let u of t.messages)this._addMessage(u,!1);for(let u=0;u<d;++u){let y=(await this._createChatCompletion(e,{...a,tool_choice:n,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!y)throw new m("missing message in ChatCompletion response");if(!y.tool_calls?.length)return;for(let C of y.tool_calls){if(C.type!=="function")continue;let R=C.id,{name:P,arguments:I}=C.function,O=b[P];if(!O){let E=`Invalid tool_call: ${JSON.stringify(P)}. Available options are: ${Object.keys(b).map((D)=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:R,content:E});continue}else if(f&&f!==P){let E=`Invalid tool_call: ${JSON.stringify(P)}. ${JSON.stringify(f)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:R,content:E});continue}let v;try{v=pn(O)?await O.parse(I):I}catch(E){let D=E instanceof Error?E.message:String(E);this._addMessage({role:"tool",tool_call_id:R,content:D});continue}let q=await O.function(v,this),F=i(this,W,"m",_n).call(this,q);if(this._addMessage({role:"tool",tool_call_id:R,content:F}),f)return}}return}}W=new WeakSet,hs=function(){return i(this,W,"m",$r).call(this).content??null},$r=function(){let t=this.messages.length;while(t-- >0){let r=this.messages[t];if(He(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new m("stream ended without producing a ChatCompletionMessage with role=assistant")},ds=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(He(r)&&r?.tool_calls?.length)return r.tool_calls.filter((s)=>s.type==="function").at(-1)?.function}return},ps=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(us(r)&&r.content!=null&&typeof r.content==="string"&&this.messages.some((s)=>s.role==="assistant"&&s.tool_calls?.some((n)=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}return},ms=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)if(r)t.completion_tokens+=r.completion_tokens,t.prompt_tokens+=r.prompt_tokens,t.total_tokens+=r.total_tokens;return t},mn=function(t){if(t.n!=null&&t.n>1)throw new m("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_n=function(t){return typeof t==="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Bt extends Lt{static runTools(e,t,r){let s=new Bt,n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}_addMessage(e,t=!0){if(super._addMessage(e,t),He(e)&&e.content)this._emit("content",e.content)}}var B={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class gn extends Error{}class yn extends Error{}function mo(e,t=B.ALL){if(typeof e!=="string")throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return _o(e.trim(),t)}var _o=(e,t)=>{let r=e.length,s=0,n=(u)=>{throw new gn(`${u} at position ${s}`)},o=(u)=>{throw new yn(`${u} at position ${s}`)},a=()=>{if(p(),s>=r)n("Unexpected end of input");if(e[s]==='"')return f();if(e[s]==="{")return d();if(e[s]==="[")return _();if(e.substring(s,s+4)==="null"||B.NULL&t&&r-s<4&&"null".startsWith(e.substring(s)))return s+=4,null;if(e.substring(s,s+4)==="true"||B.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s)))return s+=4,!0;if(e.substring(s,s+5)==="false"||B.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s)))return s+=5,!1;if(e.substring(s,s+8)==="Infinity"||B.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s)))return s+=8,1/0;if(e.substring(s,s+9)==="-Infinity"||B.MINUS_INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s)))return s+=9,-1/0;if(e.substring(s,s+3)==="NaN"||B.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s)))return s+=3,NaN;return b()},f=()=>{let u=s,x=!1;s++;while(s<r&&(e[s]!=='"'||x&&e[s-1]==="\\"))x=e[s]==="\\"?!x:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(u,++s-Number(x)))}catch(y){o(String(y))}else if(B.STR&t)try{return JSON.parse(e.substring(u,s-Number(x))+'"')}catch(y){return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{s++,p();let u={};try{while(e[s]!=="}"){if(p(),s>=r&&B.OBJ&t)return u;let x=f();p(),s++;try{let y=a();Object.defineProperty(u,x,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(B.OBJ&t)return u;else throw y}if(p(),e[s]===",")s++}}catch(x){if(B.OBJ&t)return u;else n("Expected '}' at end of object")}return s++,u},_=()=>{s++;let u=[];try{while(e[s]!=="]")if(u.push(a()),p(),e[s]===",")s++}catch(x){if(B.ARR&t)return u;n("Expected ']' at end of array")}return s++,u},b=()=>{if(s===0){if(e==="-"&&B.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e)}catch(x){if(B.NUM&t)try{if(e[e.length-1]===".")return JSON.parse(e.substring(0,e.lastIndexOf(".")));return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(y){}o(String(x))}}let u=s;if(e[s]==="-")s++;while(e[s]&&!",]}".includes(e[s]))s++;if(s==r&&!(B.NUM&t))n("Unterminated number literal");try{return JSON.parse(e.substring(u,s))}catch(x){if(e.substring(u,s)==="-"&&B.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(y){o(String(y))}}},p=()=>{while(s<r&&`
|
|
11
|
-
\r `.includes(e[s]))s++};return a()},_s=(e)=>mo(e,B.ALL^B.NUM);var L,ce,Xe,de,gs,
|
|
12
|
-
${
|
|
13
|
-
${
|
|
14
|
-
${
|
|
15
|
-
${Tr(e)}`);return{...D,id:E,type:F,function:{...fe,name:S,arguments:se}}})}};return{...x,message:{...P,content:y,role:I,refusal:_.refusal??null},finish_reason:b,index:p,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return cn(d,t)}function Tr(e){return JSON.stringify(e)}function wn(e){return}function xn(e){}class Ve extends pe{static fromReadableStream(e){let t=new Ve(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Ve(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class me extends c{constructor(){super(...arguments);this.messages=new qe(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return hn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>kt(r,e))}runTools(e,t){if(e.stream)return Ve.runTools(this._client,e,t);return Bt.runTools(this._client,e,t)}stream(e,t){return pe.createChatCompletion(this._client,e,t)}}me.Messages=qe;class Ce extends c{constructor(){super(...arguments);this.completions=new me(this._client)}}Ce.Completions=me;var An=Symbol("brand.privateNullableHeaders");function*bo(e){if(!e)return;if(An in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Xr(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Xr(s[1])?s[1]:[s[1]],a=!1;for(let f of o){if(f===void 0)continue;if(t&&!a)a=!0,yield[n,null];yield[n,f]}}}var h=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,a]of bo(s)){let f=o.toLowerCase();if(!n.has(f))t.delete(o),n.add(f);if(a===null)t.delete(o),r.add(f);else t.append(o,a),r.delete(f)}}return{[An]:!0,values:t,nulls:r}};class Ut extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class jt extends c{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Dt extends c{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}}class ue extends c{constructor(){super(...arguments);this.transcriptions=new jt(this._client),this.translations=new Dt(this._client),this.speech=new Ut(this._client)}}ue.Transcriptions=jt;ue.Translations=Dt;ue.Speech=Ut;class Ke extends c{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(l`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",A,{query:e,...t})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,t)}}class Wt extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",A,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ht extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new qt(this._client),this.transcriptionSessions=new Ht(this._client)}}Ee.Sessions=qt;Ee.TranscriptionSessions=Ht;class Jt extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class Xt extends c{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Z,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,Z,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class ve extends c{constructor(){super(...arguments);this.sessions=new Jt(this._client),this.threads=new Xt(this._client)}}ve.Sessions=Jt;ve.Threads=Xt;class Vt extends c{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/messages`,A,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Kt extends c{retrieve(e,t,r){let{thread_id:s,run_id:n,...o}=t;return this._client.get(l`/threads/${s}/runs/${n}/steps/${e}`,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...n}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,A,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var In=(e)=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var G=(e)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim();return};var U,ke,As,ee,Fr,z,Oe,Ge,$e,Lr,V,Nr,Mr,Qt,Gt,zt,Pn,Sn,Rn,Cn,En,vn,$n;class _e extends Re{constructor(){super(...arguments);U.add(this),As.set(this,[]),ee.set(this,{}),Fr.set(this,{}),z.set(this,void 0),Oe.set(this,void 0),Ge.set(this,void 0),$e.set(this,void 0),Lr.set(this,void 0),V.set(this,void 0),Nr.set(this,void 0),Mr.set(this,void 0),Qt.set(this,void 0)}[(As=new WeakMap,ee=new WeakMap,Fr=new WeakMap,z=new WeakMap,Oe=new WeakMap,Ge=new WeakMap,$e=new WeakMap,Lr=new WeakMap,V=new WeakMap,Nr=new WeakMap,Mr=new WeakMap,Qt=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new ke;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}this._connected();let s=X.fromReadableStream(e,this.controller);for await(let n of s)i(this,U,"m",Gt).call(this,n);if(s.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}toReadableStream(){return new X(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new ke;return n._run(()=>n._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,U,"m",Gt).call(this,f);if(a.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}static createThreadAssistantStream(e,t,r){let s=new ke;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let n=new ke;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Nr,"f")}currentRun(){return i(this,Mr,"f")}currentMessageSnapshot(){return i(this,z,"f")}currentRunStepSnapshot(){return i(this,Qt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,ee,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Fr,"f"))}async finalRun(){if(await this.done(),!i(this,Oe,"f"))throw Error("Final run was not received.");return i(this,Oe,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)i(this,U,"m",Gt).call(this,a);if(o.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}async _createAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,U,"m",Gt).call(this,f);if(a.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",zt).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let n=e[r];if(n===null||n===void 0){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof n==="string"&&typeof s==="string")n+=s;else if(typeof n==="number"&&typeof s==="number")n+=s;else if(Ue(n)&&Ue(s))n=this.accumulateDelta(n,s);else if(Array.isArray(n)&&Array.isArray(s)){if(n.every((o)=>typeof o==="string"||typeof o==="number")){n.push(...s);continue}for(let o of s){if(!Ue(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),Error("Expected array delta entry to have an `index` property");if(typeof a!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let f=n[a];if(f==null)n.push(o);else n[a]=this.accumulateDelta(f,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${n}`);e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}ke=_e,Gt=function(t){if(this.ended)return;switch(w(this,Nr,t,"f"),i(this,U,"m",Rn).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.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":i(this,U,"m",$n).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":i(this,U,"m",Sn).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":i(this,U,"m",Pn).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:Oo(t)}},zt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!i(this,Oe,"f"))throw Error("Final run has not been received");return i(this,Oe,"f")},Pn=function(t){let[r,s]=i(this,U,"m",En).call(this,t,i(this,z,"f"));w(this,z,r,"f"),i(this,Fr,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];if(o?.type=="text")this._emit("textCreated",o.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,r),t.data.delta.content)for(let n of t.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=i(this,Ge,"f")){if(i(this,$e,"f"))switch(i(this,$e,"f").type){case"text":this._emit("textDone",i(this,$e,"f").text,i(this,z,"f"));break;case"image_file":this._emit("imageFileDone",i(this,$e,"f").image_file,i(this,z,"f"));break}w(this,Ge,n.index,"f")}w(this,$e,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,Ge,"f")!==void 0){let n=t.data.content[i(this,Ge,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,i(this,z,"f"));break;case"text":this._emit("textDone",n.text,i(this,z,"f"));break}}if(i(this,z,"f"))this._emit("messageDone",t.data);w(this,z,void 0,"f")}},Sn=function(t){let r=i(this,U,"m",Cn).call(this,t);switch(w(this,Qt,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)if(o.index==i(this,Lr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f"));if(w(this,Lr,o.index,"f"),w(this,V,r.step_details.tool_calls[o.index],"f"),i(this,V,"f"))this._emit("toolCallCreated",i(this,V,"f"))}this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(w(this,Qt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f")),w(this,V,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Rn=function(t){i(this,As,"f").push(t),this._emit("event",t)},Cn=function(t){switch(t.event){case"thread.run.step.created":return i(this,ee,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,ee,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){let n=ke.accumulateDelta(r,s.delta);i(this,ee,"f")[t.data.id]=n}return i(this,ee,"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":i(this,ee,"f")[t.data.id]=t.data;break}if(i(this,ee,"f")[t.data.id])return i(this,ee,"f")[t.data.id];throw Error("No snapshot available")},En=function(t,r){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=t.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let a=r.content[o.index];r.content[o.index]=i(this,U,"m",vn).call(this,o,a)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},vn=function(t,r){return ke.accumulateDelta(r,t)},$n=function(t){switch(w(this,Mr,t.data,"f"),t.event){case"thread.run.created":break;case"thread.run.queued":break;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":case"thread.run.incomplete":if(w(this,Oe,t.data,"f"),i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f")),w(this,V,void 0,"f");break;case"thread.run.cancelling":break}};function Oo(e){}class ze extends c{constructor(){super(...arguments);this.steps=new Kt(this._client)}create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/runs`,A,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return _e.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}ze.Steps=Kt;class Te extends c{constructor(){super(...arguments);this.runs=new ze(this._client),this.messages=new Vt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return _e.createThreadAssistantStream(e,this._client.beta.threads,t)}}Te.Runs=ze;Te.Messages=Vt;class te extends c{constructor(){super(...arguments);this.realtime=new Ee(this._client),this.chatkit=new ve(this._client),this.assistants=new Wt(this._client),this.threads=new Te(this._client)}}te.Realtime=Ee;te.ChatKit=ve;te.Assistants=Wt;te.Threads=Te;class Qe extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Yt extends c{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class Ye extends c{constructor(){super(...arguments);this.content=new Yt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ae({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/containers/${e}/files`,A,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers])})}}Ye.Content=Yt;class Fe extends c{constructor(){super(...arguments);this.files=new Ye(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(l`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}}Fe.Files=Ye;class Zt extends c{create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:n,...r})}retrieve(e,t,r){let{conversation_id:s,...n}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:n,...r})}list(e,t={},r){return this._client.getAPIList(l`/conversations/${e}/items`,Z,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Ne extends c{constructor(){super(...arguments);this.items=new Zt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,t)}update(e,t,r){return this._client.post(l`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(l`/conversations/${e}`,t)}}Ne.Items=Zt;class Ze extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)k(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let n=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});if(r)return n;return k(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap((o)=>{if(o&&o.data)o.data.forEach((a)=>{let f=a.embedding;a.embedding=In(f)});return o})}}class er extends c{retrieve(e,t,r){let{eval_id:s,run_id:n}=t;return this._client.get(l`/evals/${s}/runs/${n}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...n}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,A,{query:n,...r})}}class et extends c{constructor(){super(...arguments);this.outputItems=new er(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/evals/${e}/runs`,A,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,r)}}et.OutputItems=er;class Me extends c{constructor(){super(...arguments);this.runs=new et(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(l`/evals/${e}`,t)}update(e,t,r){return this._client.post(l`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/evals/${e}`,t)}}Me.Runs=et;class tt extends c{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/files/${e}`,t)}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:r=1800000}={}){let s=new Set(["processed","error","deleted"]),n=Date.now(),o=await this.retrieve(e);while(!o.status||!s.has(o.status))if(await Q(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ie({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class tr extends c{}class rr extends c{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class rt extends c{constructor(){super(...arguments);this.graders=new rr(this._client)}}rt.Graders=rr;class sr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,ie,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Z,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}class st extends c{constructor(){super(...arguments);this.permissions=new sr(this._client)}}st.Permissions=sr;class nr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,A,{query:t,...r})}}class nt extends c{constructor(){super(...arguments);this.checkpoints=new nr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",A,{query:e,...t})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,A,{query:t,...r})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,t)}}nt.Checkpoints=nr;class re extends c{constructor(){super(...arguments);this.methods=new tr(this._client),this.jobs=new nt(this._client),this.checkpoints=new st(this._client),this.alpha=new rt(this._client)}}re.Methods=tr;re.Jobs=nt;re.Checkpoints=st;re.Alpha=rt;class or extends c{}class Le extends c{constructor(){super(...arguments);this.graderModels=new or(this._client)}}Le.GraderModels=or;class ot extends c{createVariation(e,t){return this._client.post("/images/variations",K({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",K({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class it extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ie,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class at extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class ir extends c{accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}}class ar extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class ge extends c{constructor(){super(...arguments);this.clientSecrets=new ar(this._client),this.calls=new ir(this._client)}}ge.ClientSecrets=ar;ge.Calls=ir;function kn(e,t){if(!t||!Qo(t))return{...e,output_parsed:null,output:e.output.map((r)=>{if(r.type==="function_call")return{...r,parsed_arguments:null};if(r.type==="message")return{...r,content:r.content.map((s)=>({...s,parsed:null}))};else return r})};return Is(e,t)}function Is(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:ei(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:zo(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Br(s);return Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output){if(n.type!=="message")continue;for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}function zo(e,t){if(e.text?.format?.type!=="json_schema")return null;if("$parseRaw"in e.text?.format)return(e.text?.format).$parseRaw(t);return JSON.parse(t)}function Qo(e){if($t(e.text?.format))return!0;return!1}function Yo(e){return e?.$brand==="auto-parseable-tool"}function Zo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function ei(e,t){let r=Zo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Yo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Br(e){let t=[];for(let r of e.output){if(r.type!=="message")continue;for(let s of r.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}var lt,Ur,ye,jr,On,Tn,Fn,Nn;class Dr extends Re{constructor(e){super();lt.add(this),Ur.set(this,void 0),ye.set(this,void 0),jr.set(this,void 0),w(this,Ur,e,"f")}static createResponse(e,t,r){let s=new Dr(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,lt,"m",On).call(this);let n,o=null;if("response_id"in t)n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of n)i(this,lt,"m",Tn).call(this,a,o);if(n.controller.signal?.aborted)throw new N;return i(this,lt,"m",Fn).call(this)}[(Ur=new WeakMap,ye=new WeakMap,jr=new WeakMap,lt=new WeakSet,On=function(){if(this.ended)return;w(this,ye,void 0,"f")},Tn=function(t,r){if(this.ended)return;let s=(o,a)=>{if(r==null||a.sequence_number>r)this._emit(o,a)},n=i(this,lt,"m",Nn).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new m(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new m(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="function_call")s("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:s(t.type,t);break}},Fn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,ye,"f");if(!t)throw new m("request ended without sending any events");w(this,ye,void 0,"f");let r=ti(t,i(this,Ur,"f"));return w(this,jr,r,"f"),r},Nn=function(t){let r=i(this,ye,"f");if(!r){if(t.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=w(this,ye,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);let n=s.type,o=t.part;if(n==="message"&&o.type!=="reasoning_text")s.content.push(o);else if(n==="reasoning"&&o.type==="reasoning_text"){if(!s.content)s.content=[];s.content.push(o)}break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="message"){let n=s.content[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="output_text")throw new m(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="function_call")s.arguments+=t.delta;break}case"response.reasoning_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="reasoning"){let n=s.content?.[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.completed":{w(this,ye,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=i(this,jr,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}}function ti(e,t){return kn(e,t)}class lr extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,A,{query:t,...r})}}class cr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class be extends c{constructor(){super(...arguments);this.inputItems=new lr(this._client),this.inputTokens=new cr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((r)=>{if("object"in r&&r.object==="response")Br(r);return r})}retrieve(e,t={},r){return this._client.get(l`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")Br(s);return s})}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((r)=>Is(r,e))}stream(e,t){return Dr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}be.InputItems=lr;be.InputTokens=cr;class ur extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class fr extends c{retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class ct extends c{constructor(){super(...arguments);this.content=new fr(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ae({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/skills/${e}/versions`,A,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}ct.Content=fr;class we extends c{constructor(){super(...arguments);this.content=new ur(this._client),this.versions=new ct(this._client)}create(e={},t){return this._client.post("/skills",ae({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/skills/${e}`,t)}update(e,t,r){return this._client.post(l`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",A,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}we.Content=ur;we.Versions=ct;class hr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,K({body:t,...r},this._client))}}class Be extends c{constructor(){super(...arguments);this.parts=new hr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,{body:t,...r})}}Be.Parts=hr;var Mn=async(e)=>{let t=await Promise.allSettled(e),r=t.filter((n)=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of t)if(n.status==="fulfilled")s.push(n.value);return s};class dr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...n}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,A,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(n.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let n=s?.maxConcurrency??5,o=Math.min(n,t.length),a=this._client,f=t.values(),d=[...r];async function _(p){for(let u of p){let x=await a.files.create({file:u,purpose:"assistants"},s);d.push(x.id)}}let b=Array(o).fill(f).map(_);return await Mn(b),await this.createAndPoll(e,{file_ids:d})}}class pr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...n}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/vector_stores/${e}/files`,A,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let n=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),o=n.data;switch(o.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=n.response.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,ie,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class xe extends c{constructor(){super(...arguments);this.files=new pr(this._client),this.fileBatches=new dr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",A,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(l`/vector_stores/${e}/search`,ie,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}xe.Files=pr;xe.FileBatches=dr;class ut extends c{create(e,t){return this._client.post("/videos",ae({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Z,{query:e,...t})}delete(e,t){return this._client.delete(l`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(l`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,ae({body:t,...r},this._client))}}var ft,Ln,Wr;class ht extends c{constructor(){super(...arguments);ft.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");i(this,ft,"m",Ln).call(this,r);let n=h([t]).values,o=i(this,ft,"m",Wr).call(this,n,"webhook-signature"),a=i(this,ft,"m",Wr).call(this,n,"webhook-timestamp"),f=i(this,ft,"m",Wr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new ne("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1000);if(_-d>s)throw new ne("Webhook timestamp is too old");if(d>_+s)throw new ne("Webhook timestamp is too new");let b=o.split(" ").map((y)=>y.startsWith("v1,")?y.substring(3):y),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),u=f?`${f}.${a}.${e}`:`${a}.${e}`,x=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let y of b)try{let C=Buffer.from(y,"base64");if(await crypto.subtle.verify("HMAC",x,C,new TextEncoder().encode(u)))return}catch{continue}throw new ne("The given webhook signature does not match the expected signature")}}ft=new WeakSet,Ln=function(t){if(typeof t!=="string"||t.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Wr=function(t,r){if(!t)throw Error("Headers are required");let s=t.get(r);if(s===null||s===void 0)throw Error(`Missing required header: ${r}`);return s};var Ps,Ss,qr,Bn;class g{constructor({baseURL:e=G("OPENAI_BASE_URL"),apiKey:t=G("OPENAI_API_KEY"),organization:r=G("OPENAI_ORG_ID")??null,project:s=G("OPENAI_PROJECT_ID")??null,webhookSecret:n=G("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Ps.add(this),qr.set(this,void 0),this.completions=new Qe(this),this.chat=new Ce(this),this.embeddings=new Ze(this),this.files=new tt(this),this.images=new ot(this),this.audio=new ue(this),this.moderations=new at(this),this.models=new it(this),this.fineTuning=new re(this),this.graders=new Le(this),this.vectorStores=new xe(this),this.webhooks=new ht(this),this.beta=new te(this),this.batches=new Ke(this),this.uploads=new Be(this),this.responses=new be(this),this.realtime=new ge(this),this.conversations=new Ne(this),this.evals=new Me(this),this.containers=new Fe(this),this.skills=new we(this),this.videos=new ut(this),t===void 0)throw new m("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:s,webhookSecret:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Ms())throw new m(`It looks like you're running in a browser-like environment.
|
|
10
|
+
${p}`)}return a},l=lo(ln);class qe extends c{list(e,t={},r){return this._client.getAPIList(l`/chat/completions/${e}/messages`,x,{query:t,...r})}}function vt(e){return e!==void 0&&"function"in e&&e.function!==void 0}function $t(e){return e?.$brand==="auto-parseable-response-format"}function Se(e){return e?.$brand==="auto-parseable-tool"}function cn(e,t){if(!t||!cs(t))return{...e,choices:e.choices.map((r)=>(fn(r.message.tool_calls),{...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))};return kt(e,t)}function kt(e,t){let r=e.choices.map((s)=>{if(s.finish_reason==="length")throw new It;if(s.finish_reason==="content_filter")throw new Pt;return fn(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map((n)=>ho(t,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?fo(t,s.message.content):null}}});return{...e,choices:r}}function fo(e,t){if(e.response_format?.type!=="json_schema")return null;if(e.response_format?.type==="json_schema"){if("$parseRaw"in e.response_format)return e.response_format.$parseRaw(t);return JSON.parse(t)}return null}function ho(e,t){let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:Se(r)?r.$parseRaw(t.function.arguments):r?.function.strict?JSON.parse(t.function.arguments):null}}}function un(e,t){if(!e||!("tools"in e)||!e.tools)return!1;let r=e.tools?.find((s)=>vt(s)&&s.function?.name===t.function.name);return vt(r)&&(Se(r)||r?.function.strict||!1)}function cs(e){if($t(e.response_format))return!0;return e.tools?.some((t)=>Se(t)||t.type==="function"&&t.function.strict===!0)??!1}function fn(e){for(let t of e||[])if(t.type!=="function")throw new m(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function hn(e){for(let t of e??[]){if(t.type!=="function")throw new m(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new m(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var He=(e)=>e?.role==="assistant",us=(e)=>e?.role==="tool";var fs,Pr,Sr,Ot,Tt,Rr,Ft,le,Nt,Cr,Er,Je,dn;class Re{constructor(){fs.add(this),this.controller=new AbortController,Pr.set(this,void 0),Sr.set(this,()=>{}),Ot.set(this,()=>{}),Tt.set(this,void 0),Rr.set(this,()=>{}),Ft.set(this,()=>{}),le.set(this,{}),Nt.set(this,!1),Cr.set(this,!1),Er.set(this,!1),Je.set(this,!1),b(this,Pr,new Promise((e,t)=>{b(this,Sr,e,"f"),b(this,Ot,t,"f")}),"f"),b(this,Tt,new Promise((e,t)=>{b(this,Rr,e,"f"),b(this,Ft,t,"f")}),"f"),i(this,Pr,"f").catch(()=>{}),i(this,Tt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},i(this,fs,"m",dn).bind(this))},0)}_connected(){if(this.ended)return;i(this,Sr,"f").call(this),this._emit("connect")}get ended(){return i(this,Nt,"f")}get errored(){return i(this,Cr,"f")}get aborted(){return i(this,Er,"f")}abort(){this.controller.abort()}on(e,t){return(i(this,le,"f")[e]||(i(this,le,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=i(this,le,"f")[e];if(!r)return this;let s=r.findIndex((n)=>n.listener===t);if(s>=0)r.splice(s,1);return this}once(e,t){return(i(this,le,"f")[e]||(i(this,le,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{if(b(this,Je,!0,"f"),e!=="error")this.once("error",r);this.once(e,t)})}async done(){b(this,Je,!0,"f"),await i(this,Tt,"f")}_emit(e,...t){if(i(this,Nt,"f"))return;if(e==="end")b(this,Nt,!0,"f"),i(this,Rr,"f").call(this);let r=i(this,le,"f")[e];if(r)i(this,le,"f")[e]=r.filter((s)=>!s.once),r.forEach(({listener:s})=>s(...t));if(e==="abort"){let s=t[0];if(!i(this,Je,"f")&&!r?.length)Promise.reject(s);i(this,Ot,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=t[0];if(!i(this,Je,"f")&&!r?.length)Promise.reject(s);i(this,Ot,"f").call(this,s),i(this,Ft,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Pr=new WeakMap,Sr=new WeakMap,Ot=new WeakMap,Tt=new WeakMap,Rr=new WeakMap,Ft=new WeakMap,le=new WeakMap,Nt=new WeakMap,Cr=new WeakMap,Er=new WeakMap,Je=new WeakMap,fs=new WeakSet,dn=function(t){if(b(this,Cr,!0,"f"),t instanceof Error&&t.name==="AbortError")t=new N;if(t instanceof N)return b(this,Er,!0,"f"),this._emit("abort",t);if(t instanceof m)return this._emit("error",t);if(t instanceof Error){let r=new m(t.message);return r.cause=t,this._emit("error",r)}return this._emit("error",new m(String(t)))};function pn(e){return typeof e.parse==="function"}var W,hs,vr,ds,ps,ms,mn,_n,po=10;class Mt extends Re{constructor(){super(...arguments);W.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;if(t)this._addMessage(t);return e}_addMessage(e,t=!0){if(!("content"in e))e.content=null;if(this.messages.push(e),t){if(this._emit("message",e),us(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(He(e)&&e.tool_calls){for(let r of e.tool_calls)if(r.type==="function")this._emit("functionToolCall",r.function)}}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new m("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),i(this,W,"m",hs).call(this)}async finalMessage(){return await this.done(),i(this,W,"m",vr).call(this)}async finalFunctionToolCall(){return await this.done(),i(this,W,"m",ds).call(this)}async finalFunctionToolCallResult(){return await this.done(),i(this,W,"m",ps).call(this)}async totalUsage(){return await this.done(),i(this,W,"m",ms).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];if(e)this._emit("finalChatCompletion",e);let t=i(this,W,"m",vr).call(this);if(t)this._emit("finalMessage",t);let r=i(this,W,"m",hs).call(this);if(r)this._emit("finalContent",r);let s=i(this,W,"m",ds).call(this);if(s)this._emit("finalFunctionToolCall",s);let n=i(this,W,"m",ps).call(this);if(n!=null)this._emit("finalFunctionToolCallResult",n);if(this._chatCompletions.some((o)=>o.usage))this._emit("totalUsage",i(this,W,"m",ms).call(this))}async _createChatCompletion(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,W,"m",mn).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(kt(n,t))}async _runChatCompletion(e,t,r){for(let s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let{tool_choice:n="auto",stream:o,...a}=t,f=typeof n!=="string"&&n.type==="function"&&n?.function?.name,{maxChatCompletions:d=po}=r||{},_=t.tools.map((u)=>{if(Se(u)){if(!u.$callback)throw new m("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),y={};for(let u of _)if(u.type==="function")y[u.function.name||u.function.function.name]=u.function;let p="tools"in t?_.map((u)=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(let u of t.messages)this._addMessage(u,!1);for(let u=0;u<d;++u){let g=(await this._createChatCompletion(e,{...a,tool_choice:n,tools:p,messages:[...this.messages]},r)).choices[0]?.message;if(!g)throw new m("missing message in ChatCompletion response");if(!g.tool_calls?.length)return;for(let R of g.tool_calls){if(R.type!=="function")continue;let S=R.id,{name:I,arguments:A}=R.function,k=y[I];if(!k){let C=`Invalid tool_call: ${JSON.stringify(I)}. Available options are: ${Object.keys(y).map((D)=>JSON.stringify(D)).join(", ")}. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}else if(f&&f!==I){let C=`Invalid tool_call: ${JSON.stringify(I)}. ${JSON.stringify(f)} requested. Please try again`;this._addMessage({role:"tool",tool_call_id:S,content:C});continue}let E;try{E=pn(k)?await k.parse(A):A}catch(C){let D=C instanceof Error?C.message:String(C);this._addMessage({role:"tool",tool_call_id:S,content:D});continue}let q=await k.function(E,this),F=i(this,W,"m",_n).call(this,q);if(this._addMessage({role:"tool",tool_call_id:S,content:F}),f)return}}return}}W=new WeakSet,hs=function(){return i(this,W,"m",vr).call(this).content??null},vr=function(){let t=this.messages.length;while(t-- >0){let r=this.messages[t];if(He(r))return{...r,content:r.content??null,refusal:r.refusal??null}}throw new m("stream ended without producing a ChatCompletionMessage with role=assistant")},ds=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(He(r)&&r?.tool_calls?.length)return r.tool_calls.filter((s)=>s.type==="function").at(-1)?.function}return},ps=function(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(us(r)&&r.content!=null&&typeof r.content==="string"&&this.messages.some((s)=>s.role==="assistant"&&s.tool_calls?.some((n)=>n.type==="function"&&n.id===r.tool_call_id)))return r.content}return},ms=function(){let t={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)if(r)t.completion_tokens+=r.completion_tokens,t.prompt_tokens+=r.prompt_tokens,t.total_tokens+=r.total_tokens;return t},mn=function(t){if(t.n!=null&&t.n>1)throw new m("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},_n=function(t){return typeof t==="string"?t:t===void 0?"undefined":JSON.stringify(t)};class Lt extends Mt{static runTools(e,t,r){let s=new Lt,n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}_addMessage(e,t=!0){if(super._addMessage(e,t),He(e)&&e.content)this._emit("content",e.content)}}var B={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511};class gn extends Error{}class yn extends Error{}function mo(e,t=B.ALL){if(typeof e!=="string")throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return _o(e.trim(),t)}var _o=(e,t)=>{let r=e.length,s=0,n=(u)=>{throw new gn(`${u} at position ${s}`)},o=(u)=>{throw new yn(`${u} at position ${s}`)},a=()=>{if(p(),s>=r)n("Unexpected end of input");if(e[s]==='"')return f();if(e[s]==="{")return d();if(e[s]==="[")return _();if(e.substring(s,s+4)==="null"||B.NULL&t&&r-s<4&&"null".startsWith(e.substring(s)))return s+=4,null;if(e.substring(s,s+4)==="true"||B.BOOL&t&&r-s<4&&"true".startsWith(e.substring(s)))return s+=4,!0;if(e.substring(s,s+5)==="false"||B.BOOL&t&&r-s<5&&"false".startsWith(e.substring(s)))return s+=5,!1;if(e.substring(s,s+8)==="Infinity"||B.INFINITY&t&&r-s<8&&"Infinity".startsWith(e.substring(s)))return s+=8,1/0;if(e.substring(s,s+9)==="-Infinity"||B.MINUS_INFINITY&t&&1<r-s&&r-s<9&&"-Infinity".startsWith(e.substring(s)))return s+=9,-1/0;if(e.substring(s,s+3)==="NaN"||B.NAN&t&&r-s<3&&"NaN".startsWith(e.substring(s)))return s+=3,NaN;return y()},f=()=>{let u=s,w=!1;s++;while(s<r&&(e[s]!=='"'||w&&e[s-1]==="\\"))w=e[s]==="\\"?!w:!1,s++;if(e.charAt(s)=='"')try{return JSON.parse(e.substring(u,++s-Number(w)))}catch(g){o(String(g))}else if(B.STR&t)try{return JSON.parse(e.substring(u,s-Number(w))+'"')}catch(g){return JSON.parse(e.substring(u,e.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},d=()=>{s++,p();let u={};try{while(e[s]!=="}"){if(p(),s>=r&&B.OBJ&t)return u;let w=f();p(),s++;try{let g=a();Object.defineProperty(u,w,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(B.OBJ&t)return u;else throw g}if(p(),e[s]===",")s++}}catch(w){if(B.OBJ&t)return u;else n("Expected '}' at end of object")}return s++,u},_=()=>{s++;let u=[];try{while(e[s]!=="]")if(u.push(a()),p(),e[s]===",")s++}catch(w){if(B.ARR&t)return u;n("Expected ']' at end of array")}return s++,u},y=()=>{if(s===0){if(e==="-"&&B.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e)}catch(w){if(B.NUM&t)try{if(e[e.length-1]===".")return JSON.parse(e.substring(0,e.lastIndexOf(".")));return JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(g){}o(String(w))}}let u=s;if(e[s]==="-")s++;while(e[s]&&!",]}".includes(e[s]))s++;if(s==r&&!(B.NUM&t))n("Unterminated number literal");try{return JSON.parse(e.substring(u,s))}catch(w){if(e.substring(u,s)==="-"&&B.NUM&t)n("Not sure what '-' is");try{return JSON.parse(e.substring(u,e.lastIndexOf("e")))}catch(g){o(String(g))}}},p=()=>{while(s<r&&`
|
|
11
|
+
\r `.includes(e[s]))s++};return a()},_s=(e)=>mo(e,B.ALL^B.NUM);var L,ce,Xe,de,gs,$r,ys,bs,ws,kr,xs,bn;class pe extends Mt{constructor(e){super();L.add(this),ce.set(this,void 0),Xe.set(this,void 0),de.set(this,void 0),b(this,ce,e,"f"),b(this,Xe,[],"f")}get currentChatCompletionSnapshot(){return i(this,de,"f")}static fromReadableStream(e){let t=new pe(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let s=new pe(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,L,"m",gs).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)i(this,L,"m",ys).call(this,o);if(n.controller.signal?.aborted)throw new N;return this._addChatCompletion(i(this,L,"m",kr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}i(this,L,"m",gs).call(this),this._connected();let s=X.fromReadableStream(e,this.controller),n;for await(let o of s){if(n&&n!==o.id)this._addChatCompletion(i(this,L,"m",kr).call(this));i(this,L,"m",ys).call(this,o),n=o.id}if(s.controller.signal?.aborted)throw new N;return this._addChatCompletion(i(this,L,"m",kr).call(this))}[(ce=new WeakMap,Xe=new WeakMap,de=new WeakMap,L=new WeakSet,gs=function(){if(this.ended)return;b(this,de,void 0,"f")},$r=function(t){let r=i(this,Xe,"f")[t.index];if(r)return r;return r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},i(this,Xe,"f")[t.index]=r,r},ys=function(t){if(this.ended)return;let r=i(this,L,"m",bn).call(this,t);this._emit("chunk",t,r);for(let s of t.choices){let n=r.choices[s.index];if(s.delta.content!=null&&n.message?.role==="assistant"&&n.message?.content)this._emit("content",s.delta.content,n.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:n.message.content,parsed:n.message.parsed});if(s.delta.refusal!=null&&n.message?.role==="assistant"&&n.message?.refusal)this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:n.message.refusal});if(s.logprobs?.content!=null&&n.message?.role==="assistant")this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:n.logprobs?.content??[]});if(s.logprobs?.refusal!=null&&n.message?.role==="assistant")this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:n.logprobs?.refusal??[]});let o=i(this,L,"m",$r).call(this,n);if(n.finish_reason){if(i(this,L,"m",ws).call(this,n),o.current_tool_call_index!=null)i(this,L,"m",bs).call(this,n,o.current_tool_call_index)}for(let a of s.delta.tool_calls??[]){if(o.current_tool_call_index!==a.index){if(i(this,L,"m",ws).call(this,n),o.current_tool_call_index!=null)i(this,L,"m",bs).call(this,n,o.current_tool_call_index)}o.current_tool_call_index=a.index}for(let a of s.delta.tool_calls??[]){let f=n.message.tool_calls?.[a.index];if(!f?.type)continue;if(f?.type==="function")this._emit("tool_calls.function.arguments.delta",{name:f.function?.name,index:a.index,arguments:f.function.arguments,parsed_arguments:f.function.parsed_arguments,arguments_delta:a.function?.arguments??""});else xn(f?.type)}}},bs=function(t,r){if(i(this,L,"m",$r).call(this,t).done_tool_calls.has(r))return;let n=t.message.tool_calls?.[r];if(!n)throw Error("no tool call snapshot");if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type==="function"){let o=i(this,ce,"f")?.tools?.find((a)=>vt(a)&&a.function.name===n.function.name);this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:r,arguments:n.function.arguments,parsed_arguments:Se(o)?o.$parseRaw(n.function.arguments):o?.function.strict?JSON.parse(n.function.arguments):null})}else xn(n.type)},ws=function(t){let r=i(this,L,"m",$r).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let s=i(this,L,"m",xs).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}if(t.message.refusal&&!r.refusal_done)r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal});if(t.logprobs?.content&&!r.logprobs_content_done)r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content});if(t.logprobs?.refusal&&!r.logprobs_refusal_done)r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal})},kr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,de,"f");if(!t)throw new m("request ended without sending any chunks");return b(this,de,void 0,"f"),b(this,Xe,[],"f"),go(t,i(this,ce,"f"))},xs=function(){let t=i(this,ce,"f")?.response_format;if($t(t))return t;return null},bn=function(t){var r,s,n,o;let a=i(this,de,"f"),{choices:f,...d}=t;if(!a)a=b(this,de,{...d,choices:[]},"f");else Object.assign(a,d);for(let{delta:_,finish_reason:y,index:p,logprobs:u=null,...w}of t.choices){let g=a.choices[p];if(!g)g=a.choices[p]={finish_reason:y,index:p,message:{},logprobs:u,...w};if(u)if(!g.logprobs)g.logprobs=Object.assign({},u);else{let{content:q,refusal:F,...C}=u;if(wn(C),Object.assign(g.logprobs,C),q)(r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...q);if(F)(s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...F)}if(y){if(g.finish_reason=y,i(this,ce,"f")&&cs(i(this,ce,"f"))){if(y==="length")throw new It;if(y==="content_filter")throw new Pt}}if(Object.assign(g,w),!_)continue;let{content:R,refusal:S,function_call:I,role:A,tool_calls:k,...E}=_;if(wn(E),Object.assign(g.message,E),S)g.message.refusal=(g.message.refusal||"")+S;if(A)g.message.role=A;if(I)if(!g.message.function_call)g.message.function_call=I;else{if(I.name)g.message.function_call.name=I.name;if(I.arguments)(n=g.message.function_call).arguments??(n.arguments=""),g.message.function_call.arguments+=I.arguments}if(R){if(g.message.content=(g.message.content||"")+R,!g.message.refusal&&i(this,L,"m",xs).call(this))g.message.parsed=_s(g.message.content)}if(k){if(!g.message.tool_calls)g.message.tool_calls=[];for(let{index:q,id:F,type:C,function:D,...se}of k){let P=(o=g.message.tool_calls)[q]??(o[q]={});if(Object.assign(P,se),F)P.id=F;if(C)P.type=C;if(D)P.function??(P.function={name:D.name??"",arguments:""});if(D?.name)P.function.name=D.name;if(D?.arguments){if(P.function.arguments+=D.arguments,un(i(this,ce,"f"),P))P.function.parsed_arguments=_s(P.function.arguments)}}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new X(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function go(e,t){let{id:r,choices:s,created:n,model:o,system_fingerprint:a,...f}=e,d={...f,id:r,choices:s.map(({message:_,finish_reason:y,index:p,logprobs:u,...w})=>{if(!y)throw new m(`missing finish_reason for choice ${p}`);let{content:g=null,function_call:R,tool_calls:S,...I}=_,A=_.role;if(!A)throw new m(`missing role for choice ${p}`);if(R){let{arguments:k,name:E}=R;if(k==null)throw new m(`missing function_call.arguments for choice ${p}`);if(!E)throw new m(`missing function_call.name for choice ${p}`);return{...w,message:{content:g,function_call:{arguments:k,name:E},role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}if(S)return{...w,index:p,finish_reason:y,logprobs:u,message:{...I,role:A,content:g,refusal:_.refusal??null,tool_calls:S.map((k,E)=>{let{function:q,type:F,id:C,...D}=k,{arguments:se,name:P,...fe}=q||{};if(C==null)throw new m(`missing choices[${p}].tool_calls[${E}].id
|
|
12
|
+
${Or(e)}`);if(F==null)throw new m(`missing choices[${p}].tool_calls[${E}].type
|
|
13
|
+
${Or(e)}`);if(P==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.name
|
|
14
|
+
${Or(e)}`);if(se==null)throw new m(`missing choices[${p}].tool_calls[${E}].function.arguments
|
|
15
|
+
${Or(e)}`);return{...D,id:C,type:F,function:{...fe,name:P,arguments:se}}})}};return{...w,message:{...I,content:g,role:A,refusal:_.refusal??null},finish_reason:y,index:p,logprobs:u}}),created:n,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return cn(d,t)}function Or(e){return JSON.stringify(e)}function wn(e){return}function xn(e){}class Ve extends pe{static fromReadableStream(e){let t=new Ve(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let s=new Ve(t),n={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,n)),s}}class me extends c{constructor(){super(...arguments);this.messages=new qe(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(l`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(l`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/chat/completions/${e}`,t)}parse(e,t){return hn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap((r)=>kt(r,e))}runTools(e,t){if(e.stream)return Ve.runTools(this._client,e,t);return Lt.runTools(this._client,e,t)}stream(e,t){return pe.createChatCompletion(this._client,e,t)}}me.Messages=qe;class Ce extends c{constructor(){super(...arguments);this.completions=new me(this._client)}}Ce.Completions=me;var An=Symbol("brand.privateNullableHeaders");function*bo(e){if(!e)return;if(An in e){let{values:s,nulls:n}=e;yield*s.entries();for(let o of n)yield[o,null];return}let t=!1,r;if(e instanceof Headers)r=e.entries();else if(Xr(e))r=e;else t=!0,r=Object.entries(e??{});for(let s of r){let n=s[0];if(typeof n!=="string")throw TypeError("expected header name to be a string");let o=Xr(s[1])?s[1]:[s[1]],a=!1;for(let f of o){if(f===void 0)continue;if(t&&!a)a=!0,yield[n,null];yield[n,f]}}}var h=(e)=>{let t=new Headers,r=new Set;for(let s of e){let n=new Set;for(let[o,a]of bo(s)){let f=o.toLowerCase();if(!n.has(f))t.delete(o),n.add(f);if(a===null)t.delete(o),r.add(f);else t.append(o,a),r.delete(f)}}return{[An]:!0,values:t,nulls:r}};class Bt extends c{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Ut extends c{create(e,t){return this._client.post("/audio/transcriptions",K({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class jt extends c{create(e,t){return this._client.post("/audio/translations",K({body:e,...t,__metadata:{model:e.model}},this._client))}}class ue extends c{constructor(){super(...arguments);this.transcriptions=new Ut(this._client),this.translations=new jt(this._client),this.speech=new Bt(this._client)}}ue.Transcriptions=Ut;ue.Translations=jt;ue.Speech=Bt;class Ke extends c{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(l`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/batches/${e}/cancel`,t)}}class Dt extends c{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Wt extends c{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class qt extends c{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ee extends c{constructor(){super(...arguments);this.sessions=new Wt(this._client),this.transcriptionSessions=new qt(this._client)}}Ee.Sessions=Wt;Ee.TranscriptionSessions=qt;class Ht extends c{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(l`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}class Jt extends c{retrieve(e,t){return this._client.get(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Z,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(l`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(l`/chatkit/threads/${e}/items`,Z,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}}class ve extends c{constructor(){super(...arguments);this.sessions=new Ht(this._client),this.threads=new Jt(this._client)}}ve.Sessions=Ht;ve.Threads=Jt;class Xt extends c{create(e,t,r){return this._client.post(l`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/messages/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/messages`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:s}=t;return this._client.delete(l`/threads/${s}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Vt extends c{retrieve(e,t,r){let{thread_id:s,run_id:n,...o}=t;return this._client.get(l`/threads/${s}/runs/${n}/steps/${e}`,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:s,...n}=t;return this._client.getAPIList(l`/threads/${s}/runs/${e}/steps`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}var In=(e)=>{if(typeof Buffer<"u"){let t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),r=t.length,s=new Uint8Array(r);for(let n=0;n<r;n++)s[n]=t.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var G=(e)=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[e]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(e)?.trim();return};var U,ke,As,ee,Fr,z,Oe,Ge,$e,Lr,V,Nr,Mr,zt,Kt,Gt,Pn,Sn,Rn,Cn,En,vn,$n;class _e extends Re{constructor(){super(...arguments);U.add(this),As.set(this,[]),ee.set(this,{}),Fr.set(this,{}),z.set(this,void 0),Oe.set(this,void 0),Ge.set(this,void 0),$e.set(this,void 0),Lr.set(this,void 0),V.set(this,void 0),Nr.set(this,void 0),Mr.set(this,void 0),zt.set(this,void 0)}[(As=new WeakMap,ee=new WeakMap,Fr=new WeakMap,z=new WeakMap,Oe=new WeakMap,Ge=new WeakMap,$e=new WeakMap,Lr=new WeakMap,V=new WeakMap,Nr=new WeakMap,Mr=new WeakMap,zt=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new ke;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;if(r){if(r.aborted)this.controller.abort();r.addEventListener("abort",()=>this.controller.abort())}this._connected();let s=X.fromReadableStream(e,this.controller);for await(let n of s)i(this,U,"m",Kt).call(this,n);if(s.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",Gt).call(this))}toReadableStream(){return new X(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){let n=new ke;return n._run(()=>n._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createToolAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.submitToolOutputs(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,U,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",Gt).call(this))}static createThreadAssistantStream(e,t,r){let s=new ke;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){let n=new ke;return n._run(()=>n._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}currentEvent(){return i(this,Nr,"f")}currentRun(){return i(this,Mr,"f")}currentMessageSnapshot(){return i(this,z,"f")}currentRunStepSnapshot(){return i(this,zt,"f")}async finalRunSteps(){return await this.done(),Object.values(i(this,ee,"f"))}async finalMessages(){return await this.done(),Object.values(i(this,Fr,"f"))}async finalRun(){if(await this.done(),!i(this,Oe,"f"))throw Error("Final run was not received.");return i(this,Oe,"f")}async _createThreadAssistantStream(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let a of o)i(this,U,"m",Kt).call(this,a);if(o.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",Gt).call(this))}async _createAssistantStream(e,t,r,s){let n=s?.signal;if(n){if(n.aborted)this.controller.abort();n.addEventListener("abort",()=>this.controller.abort())}let o={...r,stream:!0},a=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(let f of a)i(this,U,"m",Kt).call(this,f);if(a.controller.signal?.aborted)throw new N;return this._addRun(i(this,U,"m",Gt).call(this))}static accumulateDelta(e,t){for(let[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let n=e[r];if(n===null||n===void 0){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof n==="string"&&typeof s==="string")n+=s;else if(typeof n==="number"&&typeof s==="number")n+=s;else if(Ue(n)&&Ue(s))n=this.accumulateDelta(n,s);else if(Array.isArray(n)&&Array.isArray(s)){if(n.every((o)=>typeof o==="string"||typeof o==="number")){n.push(...s);continue}for(let o of s){if(!Ue(o))throw Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),Error("Expected array delta entry to have an `index` property");if(typeof a!=="number")throw Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let f=n[a];if(f==null)n.push(o);else n[a]=this.accumulateDelta(f,o)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${n}`);e[r]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}ke=_e,Kt=function(t){if(this.ended)return;switch(b(this,Nr,t,"f"),i(this,U,"m",Rn).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.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":i(this,U,"m",$n).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":i(this,U,"m",Sn).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":i(this,U,"m",Pn).call(this,t);break;case"error":throw Error("Encountered an error event in event processing - errors should be processed earlier");default:Oo(t)}},Gt=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!i(this,Oe,"f"))throw Error("Final run has not been received");return i(this,Oe,"f")},Pn=function(t){let[r,s]=i(this,U,"m",En).call(this,t,i(this,z,"f"));b(this,z,r,"f"),i(this,Fr,"f")[r.id]=r;for(let n of s){let o=r.content[n.index];if(o?.type=="text")this._emit("textCreated",o.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,r),t.data.delta.content)for(let n of t.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=r.content[n.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=i(this,Ge,"f")){if(i(this,$e,"f"))switch(i(this,$e,"f").type){case"text":this._emit("textDone",i(this,$e,"f").text,i(this,z,"f"));break;case"image_file":this._emit("imageFileDone",i(this,$e,"f").image_file,i(this,z,"f"));break}b(this,Ge,n.index,"f")}b(this,$e,r.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(i(this,Ge,"f")!==void 0){let n=t.data.content[i(this,Ge,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,i(this,z,"f"));break;case"text":this._emit("textDone",n.text,i(this,z,"f"));break}}if(i(this,z,"f"))this._emit("messageDone",t.data);b(this,z,void 0,"f")}},Sn=function(t){let r=i(this,U,"m",Cn).call(this,t);switch(b(this,zt,r,"f"),t.event){case"thread.run.step.created":this._emit("runStepCreated",t.data);break;case"thread.run.step.delta":let s=t.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)if(o.index==i(this,Lr,"f"))this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]);else{if(i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f"));if(b(this,Lr,o.index,"f"),b(this,V,r.step_details.tool_calls[o.index],"f"),i(this,V,"f"))this._emit("toolCallCreated",i(this,V,"f"))}this._emit("runStepDelta",t.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":if(b(this,zt,void 0,"f"),t.data.step_details.type=="tool_calls"){if(i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f")),b(this,V,void 0,"f")}this._emit("runStepDone",t.data,r);break;case"thread.run.step.in_progress":break}},Rn=function(t){i(this,As,"f").push(t),this._emit("event",t)},Cn=function(t){switch(t.event){case"thread.run.step.created":return i(this,ee,"f")[t.data.id]=t.data,t.data;case"thread.run.step.delta":let r=i(this,ee,"f")[t.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let s=t.data;if(s.delta){let n=ke.accumulateDelta(r,s.delta);i(this,ee,"f")[t.data.id]=n}return i(this,ee,"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":i(this,ee,"f")[t.data.id]=t.data;break}if(i(this,ee,"f")[t.data.id])return i(this,ee,"f")[t.data.id];throw Error("No snapshot available")},En=function(t,r){let s=[];switch(t.event){case"thread.message.created":return[t.data,s];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=t.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in r.content){let a=r.content[o.index];r.content[o.index]=i(this,U,"m",vn).call(this,o,a)}else r.content[o.index]=o,s.push(o);return[r,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,s];else throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},vn=function(t,r){return ke.accumulateDelta(r,t)},$n=function(t){switch(b(this,Mr,t.data,"f"),t.event){case"thread.run.created":break;case"thread.run.queued":break;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":case"thread.run.incomplete":if(b(this,Oe,t.data,"f"),i(this,V,"f"))this._emit("toolCallDone",i(this,V,"f")),b(this,V,void 0,"f");break;case"thread.run.cancelling":break}};function Oo(e){}class ze extends c{constructor(){super(...arguments);this.steps=new Vt(this._client)}create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/threads/${e}/runs`,{query:{include:s},body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:s}=t;return this._client.get(l`/threads/${s}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/threads/${e}/runs`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:s}=t;return this._client.post(l`/threads/${s}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(n.status){case"queued":case"in_progress":case"cancelling":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return n}}}stream(e,t,r){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:s,...n}=t;return this._client.post(l`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return _e.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}}ze.Steps=Vt;class Te extends c{constructor(){super(...arguments);this.runs=new ze(this._client),this.messages=new Xt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(l`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return _e.createThreadAssistantStream(e,this._client.beta.threads,t)}}Te.Runs=ze;Te.Messages=Xt;class te extends c{constructor(){super(...arguments);this.realtime=new Ee(this._client),this.chatkit=new ve(this._client),this.assistants=new Dt(this._client),this.threads=new Te(this._client)}}te.Realtime=Ee;te.ChatKit=ve;te.Assistants=Dt;te.Threads=Te;class Qe extends c{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Qt extends c{retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class Ye extends c{constructor(){super(...arguments);this.content=new Qt(this._client)}create(e,t,r){return this._client.post(l`/containers/${e}/files`,ae({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:s}=t;return this._client.get(l`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/containers/${e}/files`,x,{query:t,...r})}delete(e,t,r){let{container_id:s}=t;return this._client.delete(l`/containers/${s}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers])})}}Ye.Content=Qt;class Fe extends c{constructor(){super(...arguments);this.files=new Ye(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(l`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}}Fe.Files=Ye;class Yt extends c{create(e,t,r){let{include:s,...n}=t;return this._client.post(l`/conversations/${e}/items`,{query:{include:s},body:n,...r})}retrieve(e,t,r){let{conversation_id:s,...n}=t;return this._client.get(l`/conversations/${s}/items/${e}`,{query:n,...r})}list(e,t={},r){return this._client.getAPIList(l`/conversations/${e}/items`,Z,{query:t,...r})}delete(e,t,r){let{conversation_id:s}=t;return this._client.delete(l`/conversations/${s}/items/${e}`,r)}}class Ne extends c{constructor(){super(...arguments);this.items=new Yt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(l`/conversations/${e}`,t)}update(e,t,r){return this._client.post(l`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(l`/conversations/${e}`,t)}}Ne.Items=Yt;class Ze extends c{create(e,t){let r=!!e.encoding_format,s=r?e.encoding_format:"base64";if(r)v(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let n=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});if(r)return n;return v(this._client).debug("embeddings/decoding base64 embeddings from base64"),n._thenUnwrap((o)=>{if(o&&o.data)o.data.forEach((a)=>{let f=a.embedding;a.embedding=In(f)});return o})}}class Zt extends c{retrieve(e,t,r){let{eval_id:s,run_id:n}=t;return this._client.get(l`/evals/${s}/runs/${n}/output_items/${e}`,r)}list(e,t,r){let{eval_id:s,...n}=t;return this._client.getAPIList(l`/evals/${s}/runs/${e}/output_items`,x,{query:n,...r})}}class et extends c{constructor(){super(...arguments);this.outputItems=new Zt(this._client)}create(e,t,r){return this._client.post(l`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:s}=t;return this._client.get(l`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/evals/${e}/runs`,x,{query:t,...r})}delete(e,t,r){let{eval_id:s}=t;return this._client.delete(l`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:s}=t;return this._client.post(l`/evals/${s}/runs/${e}`,r)}}et.OutputItems=Zt;class Me extends c{constructor(){super(...arguments);this.runs=new et(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(l`/evals/${e}`,t)}update(e,t,r){return this._client.post(l`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/evals/${e}`,t)}}Me.Runs=et;class tt extends c{create(e,t){return this._client.post("/files",K({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/files/${e}`,t)}content(e,t){return this._client.get(l`/files/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5000,maxWait:r=1800000}={}){let s=new Set(["processed","error","deleted"]),n=Date.now(),o=await this.retrieve(e);while(!o.status||!s.has(o.status))if(await Q(t),o=await this.retrieve(e),Date.now()-n>r)throw new Ie({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return o}}class er extends c{}class tr extends c{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}}class rt extends c{constructor(){super(...arguments);this.graders=new tr(this._client)}}rt.Graders=tr;class rr extends c{create(e,t,r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,ie,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(l`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/checkpoints/${e}/permissions`,Z,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:s}=t;return this._client.delete(l`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}class st extends c{constructor(){super(...arguments);this.permissions=new rr(this._client)}}st.Permissions=rr;class sr extends c{list(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/checkpoints`,x,{query:t,...r})}}class nt extends c{constructor(){super(...arguments);this.checkpoints=new sr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(l`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",x,{query:e,...t})}cancel(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(l`/fine_tuning/jobs/${e}/events`,x,{query:t,...r})}pause(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(l`/fine_tuning/jobs/${e}/resume`,t)}}nt.Checkpoints=sr;class re extends c{constructor(){super(...arguments);this.methods=new er(this._client),this.jobs=new nt(this._client),this.checkpoints=new st(this._client),this.alpha=new rt(this._client)}}re.Methods=er;re.Jobs=nt;re.Checkpoints=st;re.Alpha=rt;class nr extends c{}class Le extends c{constructor(){super(...arguments);this.graderModels=new nr(this._client)}}Le.GraderModels=nr;class ot extends c{createVariation(e,t){return this._client.post("/images/variations",K({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",K({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class it extends c{retrieve(e,t){return this._client.get(l`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ie,e)}delete(e,t){return this._client.delete(l`/models/${e}`,t)}}class at extends c{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class or extends c{accept(e,t,r){return this._client.post(l`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(l`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(l`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(l`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers])})}}class ir extends c{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class ge extends c{constructor(){super(...arguments);this.clientSecrets=new ir(this._client),this.calls=new or(this._client)}}ge.ClientSecrets=ir;ge.Calls=or;function kn(e,t){if(!t||!Qo(t))return{...e,output_parsed:null,output:e.output.map((r)=>{if(r.type==="function_call")return{...r,parsed_arguments:null};if(r.type==="message")return{...r,content:r.content.map((s)=>({...s,parsed:null}))};else return r})};return Is(e,t)}function Is(e,t){let r=e.output.map((n)=>{if(n.type==="function_call")return{...n,parsed_arguments:ei(t,n)};if(n.type==="message"){let o=n.content.map((a)=>{if(a.type==="output_text")return{...a,parsed:zo(t,a.text)};return a});return{...n,content:o}}return n}),s=Object.assign({},e,{output:r});if(!Object.getOwnPropertyDescriptor(e,"output_text"))Br(s);return Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(let n of s.output){if(n.type!=="message")continue;for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),s}function zo(e,t){if(e.text?.format?.type!=="json_schema")return null;if("$parseRaw"in e.text?.format)return(e.text?.format).$parseRaw(t);return JSON.parse(t)}function Qo(e){if($t(e.text?.format))return!0;return!1}function Yo(e){return e?.$brand==="auto-parseable-tool"}function Zo(e,t){return e.find((r)=>r.type==="function"&&r.name===t)}function ei(e,t){let r=Zo(e.tools??[],t.name);return{...t,...t,parsed_arguments:Yo(r)?r.$parseRaw(t.arguments):r?.strict?JSON.parse(t.arguments):null}}function Br(e){let t=[];for(let r of e.output){if(r.type!=="message")continue;for(let s of r.content)if(s.type==="output_text")t.push(s.text)}e.output_text=t.join("")}var lt,Ur,ye,jr,On,Tn,Fn,Nn;class Dr extends Re{constructor(e){super();lt.add(this),Ur.set(this,void 0),ye.set(this,void 0),jr.set(this,void 0),b(this,Ur,e,"f")}static createResponse(e,t,r){let s=new Dr(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){let s=r?.signal;if(s){if(s.aborted)this.controller.abort();s.addEventListener("abort",()=>this.controller.abort())}i(this,lt,"m",On).call(this);let n,o=null;if("response_id"in t)n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null;else n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let a of n)i(this,lt,"m",Tn).call(this,a,o);if(n.controller.signal?.aborted)throw new N;return i(this,lt,"m",Fn).call(this)}[(Ur=new WeakMap,ye=new WeakMap,jr=new WeakMap,lt=new WeakSet,On=function(){if(this.ended)return;b(this,ye,void 0,"f")},Tn=function(t,r){if(this.ended)return;let s=(o,a)=>{if(r==null||a.sequence_number>r)this._emit(o,a)},n=i(this,lt,"m",Nn).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new m(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new m(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=n.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="function_call")s("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:s(t.type,t);break}},Fn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=i(this,ye,"f");if(!t)throw new m("request ended without sending any events");b(this,ye,void 0,"f");let r=ti(t,i(this,Ur,"f"));return b(this,jr,r,"f"),r},Nn=function(t){let r=i(this,ye,"f");if(!r){if(t.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=b(this,ye,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);let n=s.type,o=t.part;if(n==="message"&&o.type!=="reasoning_text")s.content.push(o);else if(n==="reasoning"&&o.type==="reasoning_text"){if(!s.content)s.content=[];s.content.push(o)}break}case"response.output_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="message"){let n=s.content[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="output_text")throw new m(`expected content to be 'output_text', got ${n.type}`);n.text+=t.delta}break}case"response.function_call_arguments.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="function_call")s.arguments+=t.delta;break}case"response.reasoning_text.delta":{let s=r.output[t.output_index];if(!s)throw new m(`missing output at index ${t.output_index}`);if(s.type==="reasoning"){let n=s.content?.[t.content_index];if(!n)throw new m(`missing content at index ${t.content_index}`);if(n.type!=="reasoning_text")throw new m(`expected content to be 'reasoning_text', got ${n.type}`);n.text+=t.delta}break}case"response.completed":{b(this,ye,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",(s)=>{let n=t.shift();if(n)n.resolve(s);else e.push(s)}),this.on("end",()=>{r=!0;for(let s of t)s.resolve(void 0);t.length=0}),this.on("abort",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),this.on("error",(s)=>{r=!0;for(let n of t)n.reject(s);t.length=0}),{next:async()=>{if(!e.length){if(r)return{value:void 0,done:!0};return new Promise((n,o)=>t.push({resolve:n,reject:o})).then((n)=>n?{value:n,done:!1}:{value:void 0,done:!0})}return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=i(this,jr,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}}function ti(e,t){return kn(e,t)}class ar extends c{list(e,t={},r){return this._client.getAPIList(l`/responses/${e}/input_items`,x,{query:t,...r})}}class lr extends c{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class be extends c{constructor(){super(...arguments);this.inputItems=new ar(this._client),this.inputTokens=new lr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((r)=>{if("object"in r&&r.object==="response")Br(r);return r})}retrieve(e,t={},r){return this._client.get(l`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap((s)=>{if("object"in s&&s.object==="response")Br(s);return s})}delete(e,t){return this._client.delete(l`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((r)=>Is(r,e))}stream(e,t){return Dr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(l`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}}be.InputItems=ar;be.InputTokens=lr;class cr extends c{retrieve(e,t){return this._client.get(l`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}}class ur extends c{retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}class ct extends c{constructor(){super(...arguments);this.content=new ur(this._client)}create(e,t={},r){return this._client.post(l`/skills/${e}/versions`,ae({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:s}=t;return this._client.get(l`/skills/${s}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(l`/skills/${e}/versions`,x,{query:t,...r})}delete(e,t,r){let{skill_id:s}=t;return this._client.delete(l`/skills/${s}/versions/${e}`,r)}}ct.Content=ur;class we extends c{constructor(){super(...arguments);this.content=new cr(this._client),this.versions=new ct(this._client)}create(e={},t){return this._client.post("/skills",ae({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/skills/${e}`,t)}update(e,t,r){return this._client.post(l`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",x,{query:e,...t})}delete(e,t){return this._client.delete(l`/skills/${e}`,t)}}we.Content=cr;we.Versions=ct;class fr extends c{create(e,t,r){return this._client.post(l`/uploads/${e}/parts`,K({body:t,...r},this._client))}}class Be extends c{constructor(){super(...arguments);this.parts=new fr(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(l`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(l`/uploads/${e}/complete`,{body:t,...r})}}Be.Parts=fr;var Mn=async(e)=>{let t=await Promise.allSettled(e),r=t.filter((n)=>n.status==="rejected");if(r.length){for(let n of r)console.error(n.reason);throw Error(`${r.length} promise(s) failed - see the above errors`)}let s=[];for(let n of t)if(n.status==="fulfilled")s.push(n.value);return s};class hr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:s}=t;return this._client.post(l`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){let{vector_store_id:s,...n}=t;return this._client.getAPIList(l`/vector_stores/${s}/file_batches/${e}/files`,x,{query:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let{data:n,response:o}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(n.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=o.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"failed":case"cancelled":case"completed":return n}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let n=s?.maxConcurrency??5,o=Math.min(n,t.length),a=this._client,f=t.values(),d=[...r];async function _(p){for(let u of p){let w=await a.files.create({file:u,purpose:"assistants"},s);d.push(w.id)}}let y=Array(o).fill(f).map(_);return await Mn(y),await this.createAndPoll(e,{file_ids:d})}}class dr extends c{create(e,t,r){return this._client.post(l`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:s}=t;return this._client.get(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:s,...n}=t;return this._client.post(l`/vector_stores/${s}/files/${e}`,{body:n,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(l`/vector_stores/${e}/files`,x,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:s}=t;return this._client.delete(l`/vector_stores/${s}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){let s=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);while(!0){let n=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),o=n.data;switch(o.status){case"in_progress":let a=5000;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let f=n.response.headers.get("openai-poll-after-ms");if(f){let d=parseInt(f);if(!isNaN(d))a=d}}await Q(a);break;case"failed":case"completed":return o}}}async upload(e,t,r){let s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){let s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){let{vector_store_id:s}=t;return this._client.getAPIList(l`/vector_stores/${s}/files/${e}/content`,ie,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class xe extends c{constructor(){super(...arguments);this.files=new dr(this._client),this.fileBatches=new hr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(l`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",x,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(l`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(l`/vector_stores/${e}/search`,ie,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}xe.Files=dr;xe.FileBatches=hr;class ut extends c{create(e,t){return this._client.post("/videos",ae({body:e,...t},this._client))}retrieve(e,t){return this._client.get(l`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Z,{query:e,...t})}delete(e,t){return this._client.delete(l`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(l`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(l`/videos/${e}/remix`,ae({body:t,...r},this._client))}}var ft,Ln,Wr;class ht extends c{constructor(){super(...arguments);ft.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!=="function"||typeof crypto.subtle.verify!=="function")throw Error("Webhook signature verification is only supported when the `crypto` global is defined");i(this,ft,"m",Ln).call(this,r);let n=h([t]).values,o=i(this,ft,"m",Wr).call(this,n,"webhook-signature"),a=i(this,ft,"m",Wr).call(this,n,"webhook-timestamp"),f=i(this,ft,"m",Wr).call(this,n,"webhook-id"),d=parseInt(a,10);if(isNaN(d))throw new ne("Invalid webhook timestamp format");let _=Math.floor(Date.now()/1000);if(_-d>s)throw new ne("Webhook timestamp is too old");if(d>_+s)throw new ne("Webhook timestamp is too new");let y=o.split(" ").map((g)=>g.startsWith("v1,")?g.substring(3):g),p=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),u=f?`${f}.${a}.${e}`:`${a}.${e}`,w=await crypto.subtle.importKey("raw",p,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let g of y)try{let R=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",w,R,new TextEncoder().encode(u)))return}catch{continue}throw new ne("The given webhook signature does not match the expected signature")}}ft=new WeakSet,Ln=function(t){if(typeof t!=="string"||t.length===0)throw Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Wr=function(t,r){if(!t)throw Error("Headers are required");let s=t.get(r);if(s===null||s===void 0)throw Error(`Missing required header: ${r}`);return s};var Ps,Ss,qr,Bn;class O{constructor({baseURL:e=G("OPENAI_BASE_URL"),apiKey:t=G("OPENAI_API_KEY"),organization:r=G("OPENAI_ORG_ID")??null,project:s=G("OPENAI_PROJECT_ID")??null,webhookSecret:n=G("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(Ps.add(this),qr.set(this,void 0),this.completions=new Qe(this),this.chat=new Ce(this),this.embeddings=new Ze(this),this.files=new tt(this),this.images=new ot(this),this.audio=new ue(this),this.moderations=new at(this),this.models=new it(this),this.fineTuning=new re(this),this.graders=new Le(this),this.vectorStores=new xe(this),this.webhooks=new ht(this),this.beta=new te(this),this.batches=new Ke(this),this.uploads=new Be(this),this.responses=new be(this),this.realtime=new ge(this),this.conversations=new Ne(this),this.evals=new Me(this),this.containers=new Fe(this),this.skills=new we(this),this.videos=new ut(this),t===void 0)throw new m("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:s,webhookSecret:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Ms())throw new m(`It looks like you're running in a browser-like environment.
|
|
16
16
|
|
|
17
17
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
18
18
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -21,4 +21,4 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
21
21
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
22
22
|
|
|
23
23
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
24
|
-
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Ss.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=ss(a.logLevel,"ClientOptions.logLevel",this)??ss(G("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Bs(),w(this,qr,js,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Gs(e)}getUserAgent(){return`${this.constructor.name}/JS ${he}`}defaultIdempotencyKey(){return`stainless-node-retry-${Jr()}`}makeStatusError(e,t,r,s){return T.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Ps,"m",Bn).call(this)&&r||this.baseURL,n=Es(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!vs(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Pe(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,b=Date.now();if(k(this).debug(`[${d}] sending request`,oe({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new N;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(pt),x=Date.now();if(u instanceof globalThis.Error){let R=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new N;let P=dt(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return k(this).info(`[${d}] connection ${P?"timed out":"failed"} - ${R}`),k(this).debug(`[${d}] connection ${P?"timed out":"failed"} (${R})`,oe({retryOfRequestLogID:r,url:a,durationMs:x-b,message:u.message})),this.retryRequest(s,t,r??d);if(k(this).info(`[${d}] connection ${P?"timed out":"failed"} - error; no more retries left`),k(this).debug(`[${d}] connection ${P?"timed out":"failed"} (error; no more retries left)`,oe({retryOfRequestLogID:r,url:a,durationMs:x-b,message:u.message})),P)throw new Ie;throw new Ae({cause:u})}let y=[...u.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,P])=>", "+R+": "+JSON.stringify(P)).join(""),C=`[${d}${_}${y}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${x-b}ms`;if(!u.ok){let R=await this.shouldRetry(u);if(t&&R){let F=`retrying, ${t} attempts remaining`;return await Us(u.body),k(this).info(`${C} - ${F}`),k(this).debug(`[${d}] response error (${F})`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:x-b})),this.retryRequest(s,t,r??d,u.headers)}let P=R?"error; no more retries left":"error; not retryable";k(this).info(`${C} - ${P}`);let I=await u.text().catch((F)=>pt(F).message),O=Os(I),v=O?void 0:I;throw k(this).debug(`[${d}] response error (${P})`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:v,durationMs:Date.now()-b})),this.makeStatusError(u.status,O,v,u.headers)}return k(this).info(C),k(this).debug(`[${d}] response start`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:x-b})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:b}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Ar(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,b={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)b.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,b)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await Q(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)ks("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),b=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:b,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ls(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:mr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,qr,"f").call(this,{body:e,headers:r})}}Ss=g,qr=new WeakMap,Ps=new WeakSet,Bn=function(){return this.baseURL!=="https://api.openai.com/v1"};g.OpenAI=Ss;g.DEFAULT_TIMEOUT=600000;g.OpenAIError=m;g.APIError=T;g.APIConnectionError=Ae;g.APIConnectionTimeoutError=Ie;g.APIUserAbortError=N;g.NotFoundError=yt;g.ConflictError=bt;g.RateLimitError=xt;g.BadRequestError=mt;g.AuthenticationError=_t;g.InternalServerError=At;g.PermissionDeniedError=gt;g.UnprocessableEntityError=wt;g.InvalidWebhookSignatureError=ne;g.toFile=Pr;g.Completions=Qe;g.Chat=Ce;g.Embeddings=Ze;g.Files=tt;g.Images=ot;g.Audio=ue;g.Moderations=at;g.Models=it;g.FineTuning=re;g.Graders=Le;g.VectorStores=xe;g.Webhooks=ht;g.Beta=te;g.Batches=Ke;g.Uploads=Be;g.Responses=be;g.Realtime=ge;g.Conversations=Ne;g.Evals=Me;g.Containers=Fe;g.Skills=we;g.Videos=ut;class Ot extends g{constructor({baseURL:e=G("OPENAI_BASE_URL"),apiKey:t=G("AZURE_OPENAI_API_KEY"),apiVersion:r=G("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new m("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(typeof o==="function")a=!0;if(!o&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":r},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(fi.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Ue(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var fi=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{g,Ot};
|
|
24
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Ss.DEFAULT_TIMEOUT,this.logger=a.logger??console;let f="warn";this.logLevel=f,this.logLevel=ss(a.logLevel,"ClientOptions.logLevel",this)??ss(G("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??f,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Bs(),b(this,qr,js,"f"),this._options=a,this.apiKey=typeof t==="string"?t:"Missing Key",this.organization=r,this.project=s,this.webhookSecret=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){return}async authHeaders(e){return h([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Gs(e)}getUserAgent(){return`${this.constructor.name}/JS ${he}`}defaultIdempotencyKey(){return`stainless-node-retry-${Jr()}`}makeStatusError(e,t,r,s){return T.generate(e,t,r,s)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=="function")return!1;let t;try{t=await e()}catch(r){if(r instanceof m)throw r;throw new m(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!=="string"||!t)throw new m(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let s=!i(this,Ps,"m",Bn).call(this)&&r||this.baseURL,n=Es(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();if(!vs(o))t={...o,...t};if(typeof t==="object"&&t&&!Array.isArray(t))n.search=this.stringifyQuery(t);return n.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then((s)=>({method:e,path:t,...s})))}request(e,t=null){return new Pe(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let s=await e,n=s.maxRetries??this.maxRetries;if(t==null)t=n;await this.prepareOptions(s);let{req:o,url:a,timeout:f}=await this.buildRequest(s,{retryCount:n-t});await this.prepareRequest(o,{url:a,options:s});let d="log_"+(Math.random()*16777216|0).toString(16).padStart(6,"0"),_=r===void 0?"":`, retryOf: ${r}`,y=Date.now();if(v(this).debug(`[${d}] sending request`,oe({retryOfRequestLogID:r,method:s.method,url:a,options:s,headers:o.headers})),s.signal?.aborted)throw new N;let p=new AbortController,u=await this.fetchWithTimeout(a,o,f,p).catch(pt),w=Date.now();if(u instanceof globalThis.Error){let S=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new N;let I=dt(u)||/timed? ?out/i.test(String(u)+("cause"in u?String(u.cause):""));if(t)return v(this).info(`[${d}] connection ${I?"timed out":"failed"} - ${S}`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (${S})`,oe({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),this.retryRequest(s,t,r??d);if(v(this).info(`[${d}] connection ${I?"timed out":"failed"} - error; no more retries left`),v(this).debug(`[${d}] connection ${I?"timed out":"failed"} (error; no more retries left)`,oe({retryOfRequestLogID:r,url:a,durationMs:w-y,message:u.message})),I)throw new Ie;throw new Ae({cause:u})}let g=[...u.headers.entries()].filter(([S])=>S==="x-request-id").map(([S,I])=>", "+S+": "+JSON.stringify(I)).join(""),R=`[${d}${_}${g}] ${o.method} ${a} ${u.ok?"succeeded":"failed"} with status ${u.status} in ${w-y}ms`;if(!u.ok){let S=await this.shouldRetry(u);if(t&&S){let F=`retrying, ${t} attempts remaining`;return await Us(u.body),v(this).info(`${R} - ${F}`),v(this).debug(`[${d}] response error (${F})`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),this.retryRequest(s,t,r??d,u.headers)}let I=S?"error; no more retries left":"error; not retryable";v(this).info(`${R} - ${I}`);let A=await u.text().catch((F)=>pt(F).message),k=Os(A),E=k?void 0:A;throw v(this).debug(`[${d}] response error (${I})`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,message:E,durationMs:Date.now()-y})),this.makeStatusError(u.status,k,E,u.headers)}return v(this).info(R),v(this).debug(`[${d}] response start`,oe({retryOfRequestLogID:r,url:u.url,status:u.status,headers:u.headers,durationMs:w-y})),{response:u,options:s,controller:p,requestLogID:d,retryOfRequestLogID:r,startTime:y}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then((s)=>({method:"get",path:e,...s})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new xr(this,r,e)}async fetchWithTimeout(e,t,r,s){let{signal:n,method:o,...a}=t||{},f=this._makeAbort(s);if(n)n.addEventListener("abort",f,{once:!0});let d=setTimeout(f,r),_=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body==="object"&&a.body!==null&&Symbol.asyncIterator in a.body,y={signal:s.signal,..._?{duplex:"half"}:{},method:"GET",...a};if(o)y.method=o.toUpperCase();try{return await this.fetch.call(void 0,e,y)}finally{clearTimeout(d)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");if(t==="true")return!0;if(t==="false")return!1;if(e.status===408)return!0;if(e.status===409)return!0;if(e.status===429)return!0;if(e.status>=500)return!0;return!1}async retryRequest(e,t,r,s){let n,o=s?.get("retry-after-ms");if(o){let f=parseFloat(o);if(!Number.isNaN(f))n=f}let a=s?.get("retry-after");if(a&&!n){let f=parseFloat(a);if(!Number.isNaN(f))n=f*1000;else n=Date.parse(a)-Date.now()}if(n===void 0){let f=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,f)}return await Q(n),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e,o=Math.min(0.5*Math.pow(2,n),8),a=1-Math.random()*0.25;return o*a*1000}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:s,path:n,query:o,defaultBaseURL:a}=r,f=this.buildURL(n,o,a);if("timeout"in r)ks("timeout",r.timeout);r.timeout=r.timeout??this.timeout;let{bodyHeaders:d,body:_}=this.buildBody({options:r}),y=await this.buildHeaders({options:e,method:s,bodyHeaders:d,retryCount:t});return{req:{method:s,headers:y,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&_ instanceof globalThis.ReadableStream&&{duplex:"half"},..._&&{body:_},...this.fetchOptions??{},...r.fetchOptions??{}},url:f,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let n={};if(this.idempotencyHeader&&t!=="get"){if(!e.idempotencyKey)e.idempotencyKey=this.defaultIdempotencyKey();n[this.idempotencyHeader]=e.idempotencyKey}let o=h([n,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1000))}:{},...Ls(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=h([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};else if(typeof e==="object"&&((Symbol.asyncIterator in e)||(Symbol.iterator in e)&&("next"in e)&&typeof e.next==="function"))return{bodyHeaders:void 0,body:pr(e)};else if(typeof e==="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded")return{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)};else return i(this,qr,"f").call(this,{body:e,headers:r})}}Ss=O,qr=new WeakMap,Ps=new WeakSet,Bn=function(){return this.baseURL!=="https://api.openai.com/v1"};O.OpenAI=Ss;O.DEFAULT_TIMEOUT=600000;O.OpenAIError=m;O.APIError=T;O.APIConnectionError=Ae;O.APIConnectionTimeoutError=Ie;O.APIUserAbortError=N;O.NotFoundError=yt;O.ConflictError=bt;O.RateLimitError=xt;O.BadRequestError=mt;O.AuthenticationError=_t;O.InternalServerError=At;O.PermissionDeniedError=gt;O.UnprocessableEntityError=wt;O.InvalidWebhookSignatureError=ne;O.toFile=Ir;O.Completions=Qe;O.Chat=Ce;O.Embeddings=Ze;O.Files=tt;O.Images=ot;O.Audio=ue;O.Moderations=at;O.Models=it;O.FineTuning=re;O.Graders=Le;O.VectorStores=xe;O.Webhooks=ht;O.Beta=te;O.Batches=Ke;O.Uploads=Be;O.Responses=be;O.Realtime=ge;O.Conversations=Ne;O.Evals=Me;O.Containers=Fe;O.Skills=we;O.Videos=ut;class Tr extends O{constructor({baseURL:e=G("OPENAI_BASE_URL"),apiKey:t=G("AZURE_OPENAI_API_KEY"),apiVersion:r=G("OPENAI_API_VERSION"),endpoint:s,deployment:n,azureADTokenProvider:o,dangerouslyAllowBrowser:a,...f}={}){if(!r)throw new m("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(typeof o==="function")a=!0;if(!o&&!t)throw new m("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(o&&t)throw new m("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(f.defaultQuery={...f.defaultQuery,"api-version":r},!e){if(!s)s=process.env.AZURE_OPENAI_ENDPOINT;if(!s)throw new m("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}else if(s)throw new m("baseURL and endpoint are mutually exclusive");super({apiKey:o??t,baseURL:e,...f,...a!==void 0?{dangerouslyAllowBrowser:a}:{}});this.apiVersion="",this.apiVersion=r,this.deploymentName=n}async buildRequest(e,t={}){if(fi.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!Ue(e.body))throw Error("Expected request body to be an object");let r=this.deploymentName||e.body.model||e.__metadata?.model;if(r!==void 0&&!this.baseURL.includes("/deployments"))e.path=`/deployments/${r}${e.path}`}return super.buildRequest(e,t)}async authHeaders(e){if(typeof this._options.apiKey==="string")return h([{"api-key":this.apiKey}]);return super.authHeaders(e)}}var fi=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]);export{O,Tr};
|