@swifty.js/swifty 0.0.29 → 0.0.31
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/README.md +25 -11
- package/dist/agent-O6C4FCQY.js +4 -0
- package/dist/anthropic-CFM2DXMB.js +4 -0
- package/dist/checker-A6PGACKZ.js +4 -0
- package/dist/chunk-4ABFUBO4.js +601 -0
- package/dist/{chunk-K5ZK27BX.js → chunk-AGJYBJ5M.js} +1 -1
- package/dist/chunk-AQ3A5CF4.js +5 -0
- package/dist/chunk-MVVSONAE.js +4 -0
- package/dist/chunk-OQCEP2F5.js +4 -0
- package/dist/{chunk-QFSCPD63.js → chunk-TCQ4EB4G.js} +1 -1
- package/dist/chunk-Y2UUXOQA.js +4 -0
- package/dist/chunk-YAXZ2OUD.js +150 -0
- package/dist/lib/agent-YRTROHXU.js +10 -0
- package/dist/lib/{anthropic-KWO3KLNV.js → anthropic-R6DMXE7U.js} +4 -5
- package/dist/lib/{checker-AXHPKVBY.js → checker-M7RKMKJQ.js} +2 -3
- package/dist/lib/{chunk-KZSBR4FO.js → chunk-4MDCRPVV.js} +76 -40
- package/dist/lib/{chunk-DJ6AILPN.js → chunk-A4MXZA5Q.js} +209 -51
- package/dist/lib/{chunk-2IVEVG5N.js → chunk-EWE5IWZE.js} +28 -25
- package/dist/lib/{chunk-KG4MJGKQ.js → chunk-FZ4Y6MBN.js} +1 -4
- package/dist/lib/{chunk-GCY44T7S.js → chunk-J6AV7SIF.js} +221 -351
- package/dist/lib/{chunk-3FBS5NB7.js → chunk-OEPCNATU.js} +217 -41
- package/dist/lib/{chunk-Z4CYHTII.js → chunk-OQIQOU5S.js} +85 -26
- package/dist/lib/{chunk-PIL7M52F.js → chunk-XT67KGWE.js} +16 -3
- package/dist/lib/index.d.ts +1212 -932
- package/dist/lib/index.js +2836 -1611
- package/dist/lib/{openai-PBF7EWNJ.js → openai-5N42ZYIJ.js} +2 -2
- package/dist/lib/{tool-filter-R6HDDJHE.js → tool-filter-XG2GXFVN.js} +3 -2
- package/dist/main.js +197 -189
- package/dist/openai-NQYARTT6.js +34 -0
- package/dist/{server-G23HCFLI.js → server-BNT2IIKB.js} +18 -18
- package/dist/tool-filter-5NDJMSTD.js +4 -0
- package/package.json +4 -3
- package/dist/agent-YR6YK26C.js +0 -4
- package/dist/anthropic-5GRR5JCT.js +0 -4
- package/dist/checker-N5TIJEN5.js +0 -4
- package/dist/chunk-D34FUVGU.js +0 -4
- package/dist/chunk-E55KH72M.js +0 -4
- package/dist/chunk-LIMEBKCY.js +0 -408
- package/dist/chunk-POHIQUFP.js +0 -301
- package/dist/chunk-QCKJLO6X.js +0 -4
- package/dist/chunk-TMEX7RFA.js +0 -4
- package/dist/chunk-Y6SQB5FG.js +0 -4
- package/dist/glob.wasm +0 -0
- package/dist/lib/agent-5WEKVRTD.js +0 -11
- package/dist/lib/chunk-GHF2PSEW.js +0 -8
- package/dist/lib/glob.wasm +0 -0
- package/dist/openai-QQ2K7GPF.js +0 -34
- package/dist/tool-filter-VBP6WOGO.js +0 -4
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
|
+
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
+
import{A as Ps,B as xs,D as cn,m as tn,o as rn,q as sn,r as nn,t as on,u as an,x as Rt,y as Is,z as so}from"./chunk-AQ3A5CF4.js";import{I as ro,J as Hr,K as ue,L as ws,M as un,R as oe}from"./chunk-OTVZGPHD.js";import"./chunk-X3UA5OZL.js";function x(r,e,t,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(r,t):n?n.value=t:e.set(r,t),t}function c(r,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(r):s?s.value:e.get(r)}var Je=function(){let{crypto:r}=globalThis;if(r?.randomUUID)return Je=r.randomUUID.bind(r),r.randomUUID();let e=new Uint8Array(1),t=r?()=>r.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))};function Wr(r){return typeof r=="object"&&r!==null&&("name"in r&&r.name==="AbortError"||"message"in r&&String(r.message).includes("FetchRequestCanceledException"))}var Jr=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null){try{if(Object.prototype.toString.call(r)==="[object Error]"){let e=new Error(r.message,r.cause?{cause:r.cause}:{});return r.stack&&(e.stack=r.stack),r.cause&&!e.cause&&(e.cause=r.cause),r.name&&(e.name=r.name),e}}catch{}try{return new Error(JSON.stringify(r))}catch{}}return new Error(r)};var g=class extends Error{},F=class r extends g{constructor(e,t,s,n){super(`${r.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,s){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e||!n)return new ke({message:s,cause:Jr(t)});let o=t?.error;return e===400?new Ct(e,o,s,n):e===401?new St(e,o,s,n):e===403?new kt(e,o,s,n):e===404?new $t(e,o,s,n):e===409?new Et(e,o,s,n):e===422?new Ot(e,o,s,n):e===429?new vt(e,o,s,n):e>=500?new Tt(e,o,s,n):new r(e,o,s,n)}},M=class extends F{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ke=class extends F{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},$e=class extends ke{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ct=class extends F{},St=class extends F{},kt=class extends F{},$t=class extends F{},Et=class extends F{},Ot=class extends F{},vt=class extends F{},Tt=class extends F{},Lt=class extends g{constructor(){super("Could not parse response content as the length limit was reached")}},jt=class extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},fe=class extends Error{constructor(e){super(e)}},Xe=class extends F{constructor(e,t,s){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let a=t;o=a.error;let l=a.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,s),this.error_code=o}},Xr=class extends g{constructor(e,t,s){super(e),this.provider=t,this.cause=s}};var xi=/^[a-z][a-z0-9+.-]*:/i,no=r=>xi.test(r),V=r=>(V=Array.isArray,V(r)),ln=V;function Rs(r){return typeof r!="object"?{}:r??{}}function pn(r){if(!r)return!0;for(let e in r)return!1;return!0}function oo(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Vr(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var io=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${r} must be an integer`);if(e<0)throw new g(`${r} must be a positive integer`);return e};var ao=r=>{try{return JSON.parse(r)}catch{return}};var he=r=>new Promise(e=>setTimeout(e,r));var Ee="6.49.0";var po=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Ri(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var Ci=()=>{let r=Ri();if(r==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ee,"X-Stainless-OS":co(Deno.build.os),"X-Stainless-Arch":uo(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":Ee,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(r==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ee,"X-Stainless-OS":co(globalThis.process.platform??"unknown"),"X-Stainless-Arch":uo(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Si();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ee,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ee,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Si(){if(typeof navigator>"u"||!navigator)return null;let r=[{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:e,pattern:t}of r){let s=t.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,a=s[3]||0;return{browser:e,version:`${n}.${o}.${a}`}}}return null}var uo=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",co=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),lo,fo=()=>lo??(lo=Ci());function Cs(){if(typeof fetch<"u")return fetch;throw new 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 dn(...r){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...r)}function Gr(r){let e=Symbol.asyncIterator in r?r[Symbol.asyncIterator]():r[Symbol.iterator]();return dn({start(){},async pull(t){let{done:s,value:n}=await e.next();s?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function Ss(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function fn(r){if(r===null||typeof r!="object")return;if(r[Symbol.asyncIterator]){await r[Symbol.asyncIterator]().return?.();return}let e=r.getReader(),t=e.cancel();e.releaseLock(),await t}var mo=({headers:r,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var hn="RFC3986",mn=r=>String(r),_n={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:mn},_o="RFC1738";var ks=(r,e)=>(ks=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),ks(r,e)),me=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var yn=1024,yo=(r,e,t,s,n)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<o.length;l+=yn){let f=o.length>=yn?o.slice(l,l+yn):o,p=[];for(let h=0;h<f.length;++h){let _=f.charCodeAt(h);if(_===45||_===46||_===95||_===126||_>=48&&_<=57||_>=65&&_<=90||_>=97&&_<=122||n===_o&&(_===40||_===41)){p[p.length]=f.charAt(h);continue}if(_<128){p[p.length]=me[_];continue}if(_<2048){p[p.length]=me[192|_>>6]+me[128|_&63];continue}if(_<55296||_>=57344){p[p.length]=me[224|_>>12]+me[128|_>>6&63]+me[128|_&63];continue}h+=1,_=65536+((_&1023)<<10|f.charCodeAt(h)&1023),p[p.length]=me[240|_>>18]+me[128|_>>12&63]+me[128|_>>6&63]+me[128|_&63]}a+=p.join("")}return a};function go(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function gn(r,e){if(V(r)){let t=[];for(let s=0;s<r.length;s+=1)t.push(e(r[s]));return t}return e(r)}var bo={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},wo=function(r,e){Array.prototype.push.apply(r,V(e)?e:[e])},Ao,z={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:yo,encodeValuesOnly:!1,format:hn,formatter:mn,indices:!1,serializeDate(r){return(Ao??(Ao=Function.prototype.call.bind(Date.prototype.toISOString)))(r)},skipNulls:!1,strictNullHandling:!1};function $i(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var An={};function Io(r,e,t,s,n,o,a,l,f,p,h,_,m,w,P,b,I,$){let A=r,E=$,y=0,C=!1;for(;(E=E.get(An))!==void 0&&!C;){let T=E.get(r);if(y+=1,typeof T<"u"){if(T===y)throw new RangeError("Cyclic object value");C=!0}typeof E.get(An)>"u"&&(y=0)}if(typeof p=="function"?A=p(e,A):A instanceof Date?A=m?.(A):t==="comma"&&V(A)&&(A=gn(A,function(T){return T instanceof Date?m?.(T):T})),A===null){if(o)return f&&!b?f(e,z.encoder,I,"key",w):e;A=""}if($i(A)||go(A)){if(f){let T=b?e:f(e,z.encoder,I,"key",w);return[P?.(T)+"="+P?.(f(A,z.encoder,I,"value",w))]}return[P?.(e)+"="+P?.(String(A))]}let k=[];if(typeof A>"u")return k;let L;if(t==="comma"&&V(A))b&&f&&(A=gn(A,f)),L=[{value:A.length>0?A.join(",")||null:void 0}];else if(V(p))L=p;else{let T=Object.keys(A);L=h?T.sort(h):T}let j=l?String(e).replace(/\./g,"%2E"):String(e),N=s&&V(A)&&A.length===1?j+"[]":j;if(n&&V(A)&&A.length===0)return N+"[]";for(let T=0;T<L.length;++T){let W=L[T],xt=typeof W=="object"&&typeof W.value<"u"?W.value:A[W];if(a&&xt===null)continue;let J=_&&l?W.replace(/\./g,"%2E"):W,As=V(A)?typeof t=="function"?t(N,J):N:N+(_?"."+J:"["+J+"]");$.set(r,y);let bs=new WeakMap;bs.set(An,$),wo(k,Io(xt,As,t,s,n,o,a,l,t==="comma"&&b&&V(A)?null:f,p,h,_,m,w,P,b,I,bs))}return k}function Ei(r=z){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||z.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=hn;if(typeof r.format<"u"){if(!ks(_n,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let s=_n[t],n=z.filter;(typeof r.filter=="function"||V(r.filter))&&(n=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in bo?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=z.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:z.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:z.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:z.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:z.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?z.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:z.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:z.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:z.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:z.encodeValuesOnly,filter:n,format:t,formatter:s,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:z.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:z.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:z.strictNullHandling}}function Po(r,e={}){let t=r,s=Ei(e),n,o;typeof s.filter=="function"?(o=s.filter,t=o("",t)):V(s.filter)&&(o=s.filter,n=o);let a=[];if(typeof t!="object"||t===null)return"";let l=bo[s.arrayFormat],f=l==="comma"&&s.commaRoundTrip;n||(n=Object.keys(t)),s.sort&&n.sort(s.sort);let p=new WeakMap;for(let m=0;m<n.length;++m){let w=n[m];s.skipNulls&&t[w]===null||wo(a,Io(t[w],w,l,f,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,p))}let h=a.join(s.delimiter),_=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?_+="utf8=%26%2310003%3B&":_+="utf8=%E2%9C%93&"),h.length>0?_+h:""}function xo(r){return Po(r,{arrayFormat:"brackets"})}function So(r){let e=0;for(let n of r)e+=n.length;let t=new Uint8Array(e),s=0;for(let n of r)t.set(n,s),s+=n.length;return t}var Ro;function ee(r){let e;return(Ro??(e=new globalThis.TextEncoder,Ro=e.encode.bind(e)))(r)}var Co;function bn(r){let e;return(Co??(e=new globalThis.TextDecoder,Co=e.decode.bind(e)))(r)}var te,re,Ve=class{constructor(){te.set(this,void 0),re.set(this,void 0),x(this,te,new Uint8Array,"f"),x(this,re,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ee(e):e;x(this,te,So([c(this,te,"f"),t]),"f");let s=[],n;for(;(n=vi(c(this,te,"f"),c(this,re,"f")))!=null;){if(n.carriage&&c(this,re,"f")==null){x(this,re,n.index,"f");continue}if(c(this,re,"f")!=null&&(n.index!==c(this,re,"f")+1||n.carriage)){s.push(bn(c(this,te,"f").subarray(0,c(this,re,"f")-1))),x(this,te,c(this,te,"f").subarray(c(this,re,"f")),"f"),x(this,re,null,"f");continue}let o=c(this,re,"f")!==null?n.preceding-1:n.preceding,a=bn(c(this,te,"f").subarray(0,o));s.push(a),x(this,te,c(this,te,"f").subarray(n.index),"f"),x(this,re,null,"f")}return s}flush(){return c(this,te,"f").length?this.decode(`
|
|
5
|
+
`):[]}};te=new WeakMap,re=new WeakMap;Ve.NEWLINE_CHARS=new Set([`
|
|
6
|
+
`,"\r"]);Ve.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function vi(r,e){for(let n=e??0;n<r.length;n++){if(r[n]===10)return{preceding:n,index:n+1,carriage:!1};if(r[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function ko(r){for(let s=0;s<r.length-1;s++){if(r[s]===10&&r[s+1]===10||r[s]===13&&r[s+1]===13)return s+2;if(r[s]===13&&r[s+1]===10&&s+3<r.length&&r[s+2]===13&&r[s+3]===10)return s+4}return-1}var Es={off:0,error:200,warn:300,info:400,debug:500},wn=(r,e,t)=>{if(r){if(oo(Es,r))return r;K(t).warn(`${e} was set to ${JSON.stringify(r)}, expected one of ${JSON.stringify(Object.keys(Es))}`)}};function Qr(){}function $s(r,e,t){return!e||Es[r]>Es[t]?Qr:e[r].bind(e)}var Ti={error:Qr,warn:Qr,info:Qr,debug:Qr},$o=new WeakMap;function K(r){let e=r.logger,t=r.logLevel??"off";if(!e)return Ti;let s=$o.get(e);if(s&&s[0]===t)return s[1];let n={error:$s("error",e,t),warn:$s("warn",e,t),info:$s("info",e,t),debug:$s("debug",e,t)};return $o.set(e,[t,n]),n}var Ae=r=>(r.options&&(r.options={...r.options},delete r.options.headers),r.headers&&(r.headers=Object.fromEntries((r.headers instanceof Headers?[...r.headers]:Object.entries(r.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="x-amz-security-token"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in r&&(r.retryOfRequestLogID&&(r.retryOf=r.retryOfRequestLogID),delete r.retryOfRequestLogID),r);var Yr,Z=class r{constructor(e,t,s){this.iterator=e,Yr.set(this,void 0),this.controller=t,x(this,Yr,s,"f")}static fromSSEResponse(e,t,s,n){let o=!1,a=s?K(s):console;async function*l(){if(o)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let f=!1;try{for await(let p of Li(e,t))if(!f){if(p.data.startsWith("[DONE]")){f=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let h;try{h=JSON.parse(p.data)}catch(_){throw a.error("Could not parse message into JSON:",p.data),a.error("From chunk:",p.raw),_}if(h&&h.error)throw new F(void 0,h.error,void 0,e.headers);yield n?{event:p.event,data:h}:h}else{let h;try{h=JSON.parse(p.data)}catch(_){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),_}if(p.event=="error")throw new F(void 0,h.error,h.message,void 0);yield{event:p.event,data:h}}}f=!0}catch(p){if(Wr(p))return;throw p}finally{f||t.abort()}}return new r(l,t,s)}static fromReadableStream(e,t,s){let n=!1;async function*o(){let l=new Ve,f=e.getReader(),p=!1,h,_=()=>{h??(h=f.cancel()),h.catch(()=>{})};t.signal.addEventListener("abort",_,{once:!0});try{if(t.signal.aborted){_();return}for(;;){let{value:m,done:w}=await f.read();if(w){p=!0;break}if(t.signal.aborted)return;for(let P of l.decode(m)){if(t.signal.aborted)return;yield P}}if(t.signal.aborted)return;for(let m of l.flush()){if(t.signal.aborted)return;yield m}}finally{t.signal.removeEventListener("abort",_),p||_(),f.releaseLock()}}async function*a(){if(n)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{for await(let f of o())l||f&&(yield JSON.parse(f));l=!0}catch(f){if(t.signal.aborted||Wr(f))return;throw f}finally{l||t.abort()}}return new r(a,t,s)}[(Yr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],s=this.iterator(),n=o=>({next:()=>{if(o.length===0){let a=s.next();e.push(a),t.push(a)}return o.shift()}});return[new r(()=>n(e),this.controller,c(this,Yr,"f")),new r(()=>n(t),this.controller,c(this,Yr,"f"))]}toReadableStream(){let e=this,t;return dn({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{let{value:n,done:o}=await t.next();if(o)return s.close();let a=ee(JSON.stringify(n)+`
|
|
7
|
+
`);s.enqueue(a)}catch(n){s.error(n)}},async cancel(){await t.return?.()}})}};async function*Li(r,e){if(!r.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new g("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new g("Attempted to iterate over a response with no body");let t=new In,s=new Ve,n=Ss(r.body);for await(let o of ji(n))for(let a of s.decode(o)){let l=t.decode(a);l&&(yield l)}for(let o of s.flush()){let a=t.decode(o);a&&(yield a)}}async function*ji(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?ee(t):t,n=new Uint8Array(e.length+s.length);n.set(e),n.set(s,e.length),e=n;let o;for(;(o=ko(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var In=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
8
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=Ni(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Ni(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}async function Os(r,e){let{response:t,requestLogID:s,retryOfRequestLogID:n,startTime:o}=e,a=await(async()=>{if(e.options.stream)return K(r).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData):Z.fromSSEResponse(t,e.controller,r,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let f=t.headers.get("content-type")?.split(";")[0]?.trim();if(f?.includes("application/json")||f?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let m=await t.json();return Pn(m,t)}return await t.text()})();return K(r).debug(`[${s}] response parsed`,Ae({retryOfRequestLogID:n,url:t.url,status:t.status,body:a,durationMs:Date.now()-o})),a}function Pn(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Zr,Ge=class r extends Promise{constructor(e,t,s=Os){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=s,Zr.set(this,void 0),x(this,Zr,e,"f")}_thenUnwrap(e){return new r(c(this,Zr,"f"),this.responsePromise,async(t,s)=>Pn(e(await this.parseResponse(t,s),s),s.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(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,Zr,"f"),e))),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)}};Zr=new WeakMap;var vs,Nt=class{constructor(e,t,s,n){vs.set(this,void 0),x(this,vs,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await c(this,vs,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(vs=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},es=class extends Ge{constructor(e,t,s){super(e,t,async(n,o)=>new s(n,o.response,await Os(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},G=class extends Nt{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},S=class extends Nt{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Rs(this.options.query),after:t}}:null}},v=class extends Nt{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Rs(this.options.query),after:e}}:null}},B=class extends Nt{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.next=s.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Rs(this.options.query),after:e}}:null}};var Mi={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},Ki="urn:ietf:params:oauth:grant-type:token-exchange",Ts=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??Cs()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),t={grant_type:Ki,subject_token:e,subject_token_type:Mi[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let s=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let f=await s.text(),p;try{p=JSON.parse(f)}catch{}throw s.status===400||s.status===401||s.status===403?new Xe(s.status,p,s.headers):F.generate(s.status,p,`Token exchange failed with status ${s.status}`,s.headers)}let n=await s.json();if(typeof n!="object"||n===null||!("access_token"in n)||typeof n.access_token!="string"||n.access_token.trim().length===0)throw new g("Token exchange response missing 'access_token' field");let o=n.access_token,a=n.expires_in??3600,l=Date.now()+a*1e3;return this.cachedToken={token:o,expiresAt:l},o}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let s=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-s}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var Eo=Symbol("brand.privateNullableHeaders"),Bi=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function*Ui(r){if(!r)return;if(Eo in r){let{values:s,nulls:n}=r;yield*s.entries();for(let o of n)yield[o,null];return}let e=!1,t;r instanceof Headers?t=r.entries():ln(r)?t=r:(e=!0,t=Object.entries(r??{}));for(let s of t){let n=s[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=ln(s[1])?s[1]:[s[1]],a=!1;for(let l of o)l!==void 0&&(e&&!a&&(a=!0,yield[n,null]),yield[n,l])}}var d=r=>{let e=new Headers,t=new Set;for(let s of r){let n=new Set;for(let[o,a]of Ui(s)){if(!Bi.test(o))throw new TypeError(`Header name must be a valid HTTP token ["${o}"]`);let l=o.toLowerCase();n.has(l)||(e.delete(l),n.add(l)),a===null?(e.delete(l),t.add(l)):(e.append(l,a),t.delete(l))}}return{[Eo]:!0,values:e,nulls:t}};var vo=Symbol("brand.privateStreamingFile");function js(r,e,t){if(!e)throw new TypeError("toStreamingFile requires a non-empty file name");return{[vo]:!0,data:r,name:e,...t?.type?{type:t.type}:{}}}var kn=()=>{if(typeof File>"u"){let{process:r}=globalThis,e=typeof r?.versions?.node=="string"&&parseInt(r.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Kt(r,e,t){return kn(),new File(r,e??"unknown_file",t)}function Mt(r){return(typeof r=="object"&&r!==null&&("name"in r&&r.name&&String(r.name)||"url"in r&&r.url&&String(r.url)||"filename"in r&&r.filename&&String(r.filename)||"path"in r&&r.path&&String(r.path))||"").split(/[\\/]/).pop()||void 0}var Bt=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Oe=async(r,e)=>Rn(r.body)?Ls(r.body)?Lo(r):{...r,body:await To(r.body,e)}:r,Q=async(r,e)=>Ls(r.body)?Lo(r):{...r,body:await To(r.body,e)},Oo=new WeakMap;function zi(r){let e=typeof r=="function"?r:r.fetch,t=Oo.get(e);if(t)return t;let s=(async()=>{try{let n="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new n(o).text()}catch{return!0}})();return Oo.set(e,s),s}var To=async(r,e)=>{if(!await zi(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let t=new FormData;return await Promise.all(Object.entries(r||{}).map(([s,n])=>Sn(t,s,n))),t},Ns=r=>r instanceof Blob&&"name"in r,$n=r=>typeof r=="object"&&r!==null&&"getReader"in r&&typeof r.getReader=="function",ts=r=>typeof r=="object"&&r!==null&&vo in r,En=r=>typeof r=="object"&&r!==null&&(r instanceof Response||Bt(r)||$n(r)||ts(r)||Ns(r)),Ls=r=>{if(ts(r)||Bt(r)||$n(r))return!0;if(Array.isArray(r))return r.some(Ls);if(r&&typeof r=="object"&&!Ns(r)&&!(r instanceof Response)){for(let e in r)if(Ls(r[e]))return!0}return!1},Rn=r=>{if(En(r))return!0;if(Array.isArray(r))return r.some(Rn);if(r&&typeof r=="object"){for(let e in r)if(Rn(r[e]))return!0}return!1},Lo=r=>{let e=`openai-${Math.random().toString(36).slice(2)}`,t=Gr(Di(r.body,e));return{...r,body:t,headers:d([{"content-type":`multipart/form-data; boundary=${e}`},r.headers])}};async function*Di(r,e){for await(let{key:t,value:s}of qi(r)){if(yield ee(`--${e}\r
|
|
9
|
+
`),En(s)){let n=Hi(s),o=Wi(s);yield ee(`Content-Disposition: form-data; name="${xn(t)}"; filename="${xn(n)}"\r
|
|
10
|
+
Content-Type: ${o}\r
|
|
11
|
+
\r
|
|
12
|
+
`),yield*Ft(Ji(s))}else yield ee(`Content-Disposition: form-data; name="${xn(t)}"\r
|
|
13
|
+
\r
|
|
14
|
+
${String(s)}`);yield ee(`\r
|
|
15
|
+
`)}yield ee(`--${e}--\r
|
|
16
|
+
`)}async function*qi(r){if(!(!r||typeof r!="object"))for(let[e,t]of Object.entries(r))yield*Cn(e,t)}async function*Cn(r,e){if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${r}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean"||En(e))yield{key:r,value:e};else if(Array.isArray(e))for(let t of e)yield*Cn(r+"[]",t);else if(typeof e=="object")for(let[t,s]of Object.entries(e))yield*Cn(`${r}[${t}]`,s);else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}}function Hi(r){return ts(r)?r.name:Mt(r)??"unknown_file"}function Wi(r){return ts(r)?r.type||"application/octet-stream":Ns(r)&&r.type?r.type:r instanceof Response&&r.headers.get("content-type")||"application/octet-stream"}function Ji(r){return ts(r)?r.data:r}async function*Ft(r){if(typeof r=="string")yield ee(r);else if(ArrayBuffer.isView(r))yield new Uint8Array(r.buffer,r.byteOffset,r.byteLength);else if(r instanceof ArrayBuffer)yield new Uint8Array(r);else if(r instanceof Response)r.body?yield*Ft(r.body):yield*Ft(await r.blob());else if(r instanceof Blob)typeof r.stream=="function"?yield*Ft(r.stream()):yield new Uint8Array(await r.arrayBuffer());else if($n(r))for await(let e of Ss(r))yield*Ft(e);else if(Bt(r))for await(let e of r)yield*Ft(e);else throw new TypeError(`Invalid streaming file chunk: ${String(r)}`)}function xn(r){return r.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}var Sn=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(t instanceof Response)r.append(e,Kt([await t.blob()],Mt(t)));else if(Bt(t))r.append(e,Kt([await new Response(Gr(t)).blob()],Mt(t)));else if(Ns(t))r.append(e,t,Mt(t));else if(Array.isArray(t))await Promise.all(t.map(s=>Sn(r,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,n])=>Sn(r,`${e}[${s}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var jo=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Xi=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&jo(r),Vi=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function";async function Fs(r,e,t){if(kn(),r=await r,Xi(r))return r instanceof File?r:Kt([await r.arrayBuffer()],r.name);if(Vi(r)){let n=await r.blob();return e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()),Kt(await On(n),e,t)}let s=await On(r);if(e||(e=Mt(r)),!t?.type){let n=s.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return Kt(s,e,t)}async function On(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(jo(r))e.push(r instanceof Blob?r:await r.arrayBuffer());else if(Bt(r))for await(let t of r)e.push(...await On(t));else{let t=r?.constructor?.name;throw new Error(`Unexpected data type: ${typeof r}${t?`; constructor: ${t}`:""}${Gi(r)}`)}return e}function Gi(r){return typeof r!="object"||r===null?"":`; props: [${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}var u=class{constructor(e){this._client=e}};function Fo(r){return r.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var No=Object.freeze(Object.create(null)),Yi=(r=Fo)=>function(t,...s){if(t.length===1)return t[0];let n=!1,o=[],a=t.reduce((h,_,m)=>{/[?#]/.test(_)&&(n=!0);let w=s[m],P=(n?encodeURIComponent:r)(""+w);return m!==s.length&&(w==null||typeof w=="object"&&w.toString===Object.getPrototypeOf(Object.getPrototypeOf(w.hasOwnProperty??No)??No)?.toString)&&(P=w+"",o.push({start:h.length+_.length,length:P.length,error:`Value of type ${Object.prototype.toString.call(w).slice(8,-1)} is not a valid path parameter`})),h+_+(m===s.length?"":P)},""),l=a.split(/[?#]/,1)[0],f=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=f.exec(l))!==null;)o.push({start:p.index,length:p[0].length,error:`Value "${p[0]}" can't be safely passed as a path parameter`});if(o.sort((h,_)=>h.start-_.start),o.length>0){let h=0,_=o.reduce((m,w)=>{let P=" ".repeat(w.start-h),b="^".repeat(w.length);return h=w.start+w.length,m+P+b},"");throw new g(`Path parameters result in path with invalid segments:
|
|
17
|
+
${o.map(m=>m.error).join(`
|
|
18
|
+
`)}
|
|
19
|
+
${a}
|
|
20
|
+
${_}`)}return a},i=Yi(Fo);var Qe=class extends u{list(e,t={},s){return this._client.getAPIList(i`/chat/completions/${e}/messages`,S,{query:t,...s,__security:{bearerAuth:!0}})}};function rs(r){return r!==void 0&&"function"in r&&r.function!==void 0}function ss(r){return r?.$brand==="auto-parseable-response-format"}function Ye(r){return r?.$brand==="auto-parseable-tool"}function Ko(r,e){return!e||!vn(e)?{...r,choices:r.choices.map(t=>(Uo(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:ns(r,e)}function ns(r,e){let t=r.choices.map(s=>{if(s.finish_reason==="length")throw new Lt;if(s.finish_reason==="content_filter")throw new jt;return Uo(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(n=>ta(e,n))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?ea(e,s.message.content):null}}});return{...r,choices:t}}function ea(r,e){return r.response_format?.type!=="json_schema"?null:r.response_format?.type==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function ta(r,e){let t=r.tools?.find(s=>rs(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ye(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Bo(r,e){if(!r||!("tools"in r)||!r.tools)return!1;let t=r.tools?.find(s=>rs(s)&&s.function?.name===e.function.name);return rs(t)&&(Ye(t)||t?.function.strict||!1)}function vn(r){return ss(r.response_format)?!0:r.tools?.some(e=>Ye(e)||e.type==="function"&&e.function.strict===!0)??!1}function Uo(r){for(let e of r||[])if(e.type!=="function")throw new g(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function zo(r){for(let e of r??[]){if(e.type!=="function")throw new g(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new g(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var be=r=>r?.role==="assistant",os=r=>r?.role==="tool";var is,Ms,Ks,as,us,Bs,cs,we,Us,ls,zs,Ds,Ut,Do,Tn,ve=class{constructor(){is.add(this),this.controller=new AbortController,Ms.set(this,void 0),Ks.set(this,()=>{}),as.set(this,()=>{}),us.set(this,void 0),Bs.set(this,()=>{}),cs.set(this,()=>{}),we.set(this,{}),Us.set(this,[]),ls.set(this,!1),zs.set(this,!1),Ds.set(this,!1),Ut.set(this,!1),x(this,Ms,new Promise((e,t)=>{x(this,Ks,e,"f"),x(this,as,t,"f")}),"f"),x(this,us,new Promise((e,t)=>{x(this,Bs,e,"f"),x(this,cs,t,"f")}),"f"),c(this,Ms,"f").catch(()=>{}),c(this,us,"f").catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(t){c(this,is,"m",Tn).call(this,t);return}this._emit("end")},c(this,is,"m",Tn).bind(this))},0)}_connected(){this.ended||(c(this,Ks,"f").call(this),this._emit("connect"))}get ended(){return c(this,ls,"f")}get errored(){return c(this,zs,"f")}get aborted(){return c(this,Ds,"f")}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener("abort",t,{once:!0}),c(this,Us,"f").push({signal:e,listener:t})}on(e,t){return(c(this,we,"f")[e]||(c(this,we,"f")[e]=[])).push({listener:t}),this}off(e,t){let s=c(this,we,"f")[e];if(!s)return this;let n=s.findIndex(o=>o.listener===t);return n>=0&&s.splice(n,1),this}once(e,t){return(c(this,we,"f")[e]||(c(this,we,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{x(this,Ut,!0,"f"),e!=="error"&&this.once("error",s),this.once(e,t)})}events(e){let t=[],s=[],n=this.ended,o,a=!1,l=()=>({value:void 0,done:!0}),f=()=>{for(;s.length;)s.shift().resolve(l())},p=()=>{!o||a||!s.length||(a=!0,s.shift().reject(o))},h=()=>{this.off(e,_),this.off("end",w),e!=="error"&&this.off("error",m),e!=="abort"&&this.off("abort",m)},_=(...P)=>{if(n)return;let b=s.shift();b?b.resolve({value:P,done:!1}):t.push(P)},m=P=>{o=P,t.length||p()},w=()=>{n=!0,h(),t.length||(p(),f())};return n||(this.on(e,_),this.on("end",w),e!=="error"&&this.on("error",m),e!=="abort"&&this.on("abort",m)),{next:()=>{let P=t.shift();return P?Promise.resolve({value:P,done:!1}):o&&!a?(a=!0,Promise.reject(o)):n?Promise.resolve(l()):new Promise((b,I)=>{s.push({resolve:b,reject:I})})},return:()=>(n=!0,t.length=0,h(),f(),Promise.resolve(l())),[Symbol.asyncIterator](){return this}}}async done(){x(this,Ut,!0,"f"),await c(this,us,"f")}_emit(e,...t){if(c(this,ls,"f"))return;e==="end"&&(c(this,is,"m",Do).call(this),x(this,ls,!0,"f"),c(this,Bs,"f").call(this));let s=c(this,we,"f")[e];if(s&&(c(this,we,"f")[e]=s.filter(n=>!n.once),s.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,Ut,"f")&&!s?.length&&Promise.reject(n),c(this,as,"f").call(this,n),c(this,cs,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,Ut,"f")&&!s?.length&&Promise.reject(n),c(this,as,"f").call(this,n),c(this,cs,"f").call(this,n),this._emit("end")}}_emitFinal(){}};Ms=new WeakMap,Ks=new WeakMap,as=new WeakMap,us=new WeakMap,Bs=new WeakMap,cs=new WeakMap,we=new WeakMap,Us=new WeakMap,ls=new WeakMap,zs=new WeakMap,Ds=new WeakMap,Ut=new WeakMap,is=new WeakSet,Do=function(){for(let{signal:e,listener:t}of c(this,Us,"f").splice(0))e.removeEventListener("abort",t)},Tn=function(e){if(x(this,zs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new M),e instanceof M)return x(this,Ds,!0,"f"),this._emit("abort",e);if(e instanceof g)return this._emit("error",e);if(e instanceof Error){let t=new g(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new g(String(e)))};function qo(r){return typeof r.parse=="function"}var Y,Ln,qs,jn,Nn,Fn,Ho,Wo,ra=10;function sa(r){for(let e of r.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${Je()}`)}function na(r){if(!be(r))return r;let e={role:"assistant"};return r.audio!=null&&(e.audio={id:r.audio.id}),r.content!==void 0&&(e.content=r.content),r.function_call!=null&&(e.function_call=r.function_call),r.name!==void 0&&(e.name=r.name),r.refusal!=null&&(e.refusal=r.refusal),r.tool_calls!==void 0&&(e.tool_calls=r.tool_calls.map(t=>t.type==="custom"?{id:t.id,type:t.type,custom:{input:t.custom.input,name:t.custom.name}}:{id:t.id,type:t.type,function:{arguments:t.function.arguments,name:t.function.name}})),e}var zt=class extends ve{constructor(){super(...arguments),Y.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){sa(e),this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),os(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(be(e)&&e.tool_calls)for(let s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new g("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,Y,"m",Ln).call(this)}async finalMessage(){return await this.done(),c(this,Y,"m",qs).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,Y,"m",jn).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,Y,"m",Nn).call(this)}async totalUsage(){return await this.done(),c(this,Y,"m",Fn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=c(this,Y,"m",qs).call(this);t&&this._emit("finalMessage",t);let s=c(this,Y,"m",Ln).call(this);s&&this._emit("finalContent",s);let n=c(this,Y,"m",jn).call(this);n&&this._emit("finalFunctionToolCall",n);let o=c(this,Y,"m",Nn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",c(this,Y,"m",Fn).call(this))}async _createChatCompletion(e,t,s){this._listenForAbort(s?.signal),c(this,Y,"m",Ho).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ns(n,t))}async _runChatCompletion(e,t,s){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s,n){let o="tool",{tool_choice:a="auto",stream:l,toolContext:f,...p}=t,h=f,_=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:m=ra,afterCompletion:w}=n||{},P=t.tools.map(A=>{if(Ye(A)){if(!A.$callback)throw new g("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:A.$callback,name:A.function.name,description:A.function.description||"",parameters:A.function.parameters,parse:A.$parseRaw,strict:!0}}}return A}),b={};for(let A of P)A.type==="function"&&(b[A.function.name||A.function.function.name]=A.function);let I="tools"in t?P.map(A=>A.type==="function"?{type:"function",function:{name:A.function.name||A.function.function.name,parameters:A.function.parameters,description:A.function.description,strict:A.function.strict}}:A):void 0;for(let A of t.messages)this._addMessage(A,!1);let $=async A=>{if(A.type!=="function")return{message:void 0,functionCalled:!1};let E=A.id,{name:y,arguments:C}=A.function,k=b[y];if(!k){let N=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(b).map(T=>JSON.stringify(T)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:E,content:N},functionCalled:!1}}if(_&&_!==y){let N=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(_)} requested. Please try again`;return{message:{role:o,tool_call_id:E,content:N},functionCalled:!1}}let L;if(qo(k)){let N;try{N=await k.parse(C)}catch(T){let W=T instanceof Error?T.message:String(T);return{message:{role:o,tool_call_id:E,content:W},functionCalled:!1}}L=await k.function(N,s,h)}else L=await k.function(C,s,h);let j=c(this,Y,"m",Wo).call(this,L);return{message:{role:o,tool_call_id:E,content:j},functionCalled:!0}};for(let A=0;A<m;++A){let E=await this._createChatCompletion(e,{...p,tool_choice:a,tools:I,messages:this.messages.map(na)},n),y=E.choices[0]?.message;if(!y)throw new g("missing message in ChatCompletion response");if(!y.tool_calls?.length){await w?.(E,s);return}if(_||t.parallel_tool_calls===!1)for(let C of y.tool_calls){let k=await $(C);if(k.message&&this._addMessage(k.message),_&&k.functionCalled){await w?.(E,s);return}}else{let C=await Promise.allSettled(y.tool_calls.map($));for(let k of C)if(k.status==="rejected")throw k.reason;for(let k of C)k.status==="fulfilled"&&k.value.message&&this._addMessage(k.value.message)}await w?.(E,s)}}};Y=new WeakSet,Ln=function(){return c(this,Y,"m",qs).call(this).content??null},qs=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(be(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new g("stream ended without producing a ChatCompletionMessage with role=assistant")},jn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(be(t)&&t?.tool_calls?.length)for(let s=t.tool_calls.length-1;s>=0;s--){let n=t.tool_calls[s];if(n?.type==="function")return n.function}}},Nn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(os(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},Fn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Ho=function(e){if(e.n!=null&&e.n>1)throw new g("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Wo=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var ps=class r extends zt{static runTools(e,t,s){let n=new r,o={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),be(e)&&e.content&&this._emit("content",e.content)}};var D={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},Mn=class extends Error{},Kn=class extends Error{};function oa(r,e=D.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return ia(r.trim(),e)}var ia=(r,e)=>{let t=r.length,s=0,n=m=>{throw new Mn(`${m} at position ${s}`)},o=m=>{throw new Kn(`${m} at position ${s}`)},a=()=>(_(),s>=t&&n("Unexpected end of input"),r[s]==='"'?l():r[s]==="{"?f():r[s]==="["?p():r.substring(s,s+4)==="null"||D.NULL&e&&t-s<4&&"null".startsWith(r.substring(s))?(s+=4,null):r.substring(s,s+4)==="true"||D.BOOL&e&&t-s<4&&"true".startsWith(r.substring(s))?(s+=4,!0):r.substring(s,s+5)==="false"||D.BOOL&e&&t-s<5&&"false".startsWith(r.substring(s))?(s+=5,!1):r.substring(s,s+8)==="Infinity"||D.INFINITY&e&&t-s<8&&"Infinity".startsWith(r.substring(s))?(s+=8,1/0):r.substring(s,s+9)==="-Infinity"||D.MINUS_INFINITY&e&&1<t-s&&t-s<9&&"-Infinity".startsWith(r.substring(s))?(s+=9,-1/0):r.substring(s,s+3)==="NaN"||D.NAN&e&&t-s<3&&"NaN".startsWith(r.substring(s))?(s+=3,NaN):h()),l=()=>{let m=s,w=!1;for(s++;s<t&&(r[s]!=='"'||w&&r[s-1]==="\\");)w=r[s]==="\\"?!w:!1,s++;if(r.charAt(s)=='"')try{return JSON.parse(r.substring(m,++s-Number(w)))}catch(P){o(String(P))}else if(D.STR&e)try{return JSON.parse(r.substring(m,s-Number(w))+'"')}catch{return JSON.parse(r.substring(m,r.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},f=()=>{s++,_();let m={};try{for(;r[s]!=="}";){if(_(),s>=t&&D.OBJ&e)return m;let w=l();_(),s++;try{let P=a();Object.defineProperty(m,w,{value:P,writable:!0,enumerable:!0,configurable:!0})}catch(P){if(D.OBJ&e)return m;throw P}_(),r[s]===","&&s++}}catch{if(D.OBJ&e)return m;n("Expected '}' at end of object")}return s++,m},p=()=>{s++;let m=[];try{for(;r[s]!=="]";)m.push(a()),_(),r[s]===","&&s++}catch{if(D.ARR&e)return m;n("Expected ']' at end of array")}return s++,m},h=()=>{if(s===0){r==="-"&&D.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(r)}catch(w){if(D.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(w))}}let m=s;for(r[s]==="-"&&s++;r[s]&&!",]}".includes(r[s]);)s++;s==t&&!(D.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(r.substring(m,s))}catch{r.substring(m,s)==="-"&&D.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(r.substring(m,r.lastIndexOf("e")))}catch(P){o(String(P))}}},_=()=>{for(;s<t&&`
|
|
21
|
+
\r `.includes(r[s]);)s++};return a()},Bn=r=>oa(r,D.ALL^D.NUM);var U,Ie,Te,Dt,ce,Un,Hs,zn,Dn,qn,ds,Hn,Jo,Jn="chat.completion.chunk.message:";function Xo(r,e,t){let s={type:"message",message:e,...t?{tool_call_ids:t}:{}};return{id:r.id,choices:[],created:r.created,model:r.model,object:`${Jn}${JSON.stringify(s)}`}}function aa(r){return"type"in r&&r.type==="message"&&"message"in r||"object"in r&&typeof r.object=="string"&&r.object.startsWith(Jn)}function ua(r){return"type"in r?r:JSON.parse(r.object.slice(Jn.length))}var Ze=class r extends zt{constructor(e){super(),U.add(this),Ie.set(this,void 0),Te.set(this,void 0),Dt.set(this,void 0),ce.set(this,void 0),x(this,Ie,e,"f"),x(this,Te,new Set,"f"),x(this,Dt,[],"f")}get currentChatCompletionSnapshot(){return c(this,ce,"f")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){let n=new r(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,s){super._createChatCompletion,this._listenForAbort(s?.signal),c(this,U,"m",Un).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(let o of n)c(this,U,"m",zn).call(this,o);if(n.controller.signal?.aborted)throw new M;return this._addChatCompletion(c(this,U,"m",ds).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,U,"m",Un).call(this),this._connected();let s=Z.fromReadableStream(e,this.controller),n;for await(let a of s){if(aa(a)){let f=ua(a);if(c(this,ce,"f")){let p=c(this,ce,"f").choices[0]?.message.tool_calls;for(let[h,_]of f.tool_call_ids?.entries()??[]){let m=p?.[h];m&&_&&(m.id=_)}this._addChatCompletion(c(this,U,"m",ds).call(this)),n=void 0}this._addMessage(f.message);continue}let l=a;n&&l.id&&n!==l.id&&this._addChatCompletion(c(this,U,"m",ds).call(this)),c(this,U,"m",zn).call(this,l),l.id&&(n=l.id)}if(s.controller.signal?.aborted)throw new M;if(c(this,ce,"f"))return this._addChatCompletion(c(this,U,"m",ds).call(this));let o=this._chatCompletions[this._chatCompletions.length-1];if(o)return o;throw new g("request ended without sending any chunks")}[(Ie=new WeakMap,Te=new WeakMap,Dt=new WeakMap,ce=new WeakMap,U=new WeakSet,Un=function(){this.ended||(x(this,Te,new Set,"f"),x(this,ce,void 0,"f"))},Hs=function(t){let s=c(this,Dt,"f")[t.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,Dt,"f")[t.index]=s,s)},zn=function(t){if(this.ended)return;let s=c(this,U,"m",Jo).call(this,t);this._emit("chunk",t,s);for(let n of t.choices){let o=s.choices[n.index],{delta:a}=n;a?.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",a.content,o.message.content),this._emit("content.delta",{delta:a.content,snapshot:o.message.content,parsed:o.message.parsed})),a?.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:a.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let l=c(this,U,"m",Hs).call(this,o);o.finish_reason&&(c(this,U,"m",qn).call(this,o),l.current_tool_call_index!=null&&c(this,U,"m",Dn).call(this,o,l.current_tool_call_index));for(let f of a?.tool_calls??[])l.current_tool_call_index!==f.index&&(c(this,U,"m",qn).call(this,o),l.current_tool_call_index!=null&&c(this,U,"m",Dn).call(this,o,l.current_tool_call_index)),l.current_tool_call_index=f.index;for(let f of a?.tool_calls??[]){let p=o.message.tool_calls?.[f.index];p?.type&&(p?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:p.function?.name,index:f.index,arguments:p.function.arguments,parsed_arguments:p.function.parsed_arguments,arguments_delta:f.function?.arguments??""}):(p?.type,void 0))}}},Dn=function(t,s){if(c(this,U,"m",Hs).call(this,t).done_tool_calls.has(s))return;let o=t.message.tool_calls?.[s];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let a=c(this,Ie,"f")?.tools?.find(l=>rs(l)&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:s,arguments:o.function.arguments,parsed_arguments:Ye(a)?a.$parseRaw(o.function.arguments):a?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},qn=function(t){let s=c(this,U,"m",Hs).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;let n=c(this,U,"m",Hn).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},ds=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=c(this,ce,"f");if(!t)throw new g("request ended without sending any chunks");let s=c(this,Te,"f");return x(this,Te,new Set,"f"),x(this,ce,void 0,"f"),x(this,Dt,[],"f"),ca(t,c(this,Ie,"f"),s)},Hn=function(){let t=c(this,Ie,"f")?.response_format;return ss(t)?t:null},Jo=function(t){var s,n,o,a,l;let f=c(this,ce,"f"),{choices:p,...h}=t;f?t.id&&Object.assign(f,h):f=x(this,ce,{...h,choices:[]},"f");for(let{delta:_,finish_reason:m,index:w,logprobs:P=null,...b}of t.choices){let I=f.choices[w];if(I||(I=f.choices[w]={finish_reason:m,index:w,message:{},logprobs:P,...b}),P)if(!I.logprobs)I.logprobs=Object.assign({},P);else{let{content:j,refusal:N,...T}=P;Object.assign(I.logprobs,T),j&&((s=I.logprobs).content??(s.content=[]),I.logprobs.content.push(...j)),N&&((n=I.logprobs).refusal??(n.refusal=[]),I.logprobs.refusal.push(...N))}if(m&&(I.finish_reason=m,c(this,Ie,"f")&&vn(c(this,Ie,"f")))){if(m==="length")throw new Lt;if(m==="content_filter")throw new jt}if(Object.assign(I,b),!_)continue;c(this,Te,"f").delete(w);let{audio:$,content:A,refusal:E,function_call:y,role:C,tool_calls:k,...L}=_;if(Object.assign(I.message,L),$?.expires_at!=null&&$.id==null&&$.data==null&&$.transcript==null&&A==null&&E==null&&y==null&&C==null&&k==null&&Object.keys(L).length===0&&c(this,Te,"f").add(w),E&&(I.message.refusal=(I.message.refusal||"")+E),C&&(I.message.role=C),$){let j=(o=I.message).audio??(o.audio={});$.id!=null&&(j.id=$.id),$.data!=null&&(j.data=(j.data??"")+$.data),$.transcript!=null&&(j.transcript=(j.transcript??"")+$.transcript),$.expires_at!=null&&(j.expires_at=$.expires_at)}if(y&&(I.message.function_call?(y.name&&(I.message.function_call.name=y.name),y.arguments&&((a=I.message.function_call).arguments??(a.arguments=""),I.message.function_call.arguments+=y.arguments)):I.message.function_call=y),A&&(I.message.content=(I.message.content||"")+A,!I.message.refusal&&c(this,U,"m",Hn).call(this)&&(I.message.parsed=I.message.content.trim()?Bn(I.message.content):null)),k){I.message.tool_calls||(I.message.tool_calls=[]);for(let{index:j,id:N,type:T,function:W,...xt}of k){let J=(l=I.message.tool_calls)[j]??(l[j]={});Object.assign(J,xt),N&&(J.id=N),T&&(J.type=T),W&&(J.function??(J.function={name:W.name??"",arguments:""})),W?.name&&(J.function.name=W.name),W?.arguments&&(J.function.arguments+=W.arguments,Bo(c(this,Ie,"f"),J)&&(J.function.parsed_arguments=Bn(J.function.arguments)))}}}return f},Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function ca(r,e,t){let{id:s,choices:n,created:o,model:a,system_fingerprint:l,...f}=r,p={...f,id:s,choices:n.map(({message:h,finish_reason:_,index:m,logprobs:w,...P})=>{let{content:b=null,function_call:I,tool_calls:$,audio:A,...E}=h,y=_??(t.has(m)&&la(A)?"stop":null);if(!y)throw new g(`missing finish_reason for choice ${m}`);let C=A?{audio:A}:{},k=h.role;if(!k)throw new g(`missing role for choice ${m}`);if(I){let{arguments:L,name:j}=I;if(L==null)throw new g(`missing function_call.arguments for choice ${m}`);if(!j)throw new g(`missing function_call.name for choice ${m}`);return{...P,message:{...C,content:b,function_call:{arguments:L,name:j},role:k,refusal:h.refusal??null},finish_reason:y,index:m,logprobs:w}}return $?{...P,index:m,finish_reason:y,logprobs:w,message:{...E,...C,role:k,content:b,refusal:h.refusal??null,tool_calls:$.map((L,j)=>{let{function:N,type:T,id:W,...xt}=L,{arguments:J,name:As,...bs}=N||{};if(T==null)throw new g(`missing choices[${m}].tool_calls[${j}].type
|
|
22
|
+
${Wn(r)}`);if(As==null)throw new g(`missing choices[${m}].tool_calls[${j}].function.name
|
|
23
|
+
${Wn(r)}`);if(J==null)throw new g(`missing choices[${m}].tool_calls[${j}].function.arguments
|
|
24
|
+
${Wn(r)}`);return{...xt,id:W||`call_${Je()}`,type:T,function:{...bs,name:As,arguments:J}}})}}:{...P,message:{...E,...C,content:b,role:k,refusal:h.refusal??null},finish_reason:y,index:m,logprobs:w}}),created:o,model:a,object:"chat.completion",...l?{system_fingerprint:l}:{}};return Ko(p,e)}function la(r){return r?.id!=null&&r.data!=null&&r.transcript!=null&&r.expires_at!=null}function Wn(r){return JSON.stringify(r)}var fs=class r extends Ze{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}toReadableStream(){let e=[],t=[],s=!1,n,o,a=p=>{let h=t.shift();h?h.resolve(p):e.push(p)};this.on("chunk",p=>{n=p,a(p)}),this.on("message",p=>{if(be(p)){o=p.tool_calls?.map(h=>h.id);return}if(os(p)){if(!n)throw new g("cannot serialize a tool message before receiving any chunks");a(Xo(n,p,o))}}),this.on("end",()=>{s=!0;for(let p of t)p.resolve(void 0);t.length=0}),this.on("abort",p=>{s=!0;for(let h of t)h.reject(p);t.length=0}),this.on("error",p=>{s=!0;for(let h of t)h.reject(p);t.length=0});let l=()=>({next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise((h,_)=>t.push({resolve:h,reject:_})).then(h=>h?{value:h,done:!1}:{value:void 0,done:!0});let p=e.shift();return p?{value:p,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})});return new Z(l,this.controller).toReadableStream()}static runTools(e,t,s){let n=new r(t),o={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}};var Pe=class extends u{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,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(i`/chat/completions/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return zo(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>ns(s,e))}runTools(e,t){return e.stream?fs.runTools(this._client,e,t):ps.runTools(this._client,e,t)}stream(e,t){return Ze.createChatCompletion(this._client,e,t)}};Pe.Messages=Qe;var Le=class extends u{constructor(){super(...arguments),this.completions=new Pe(this._client)}};Le.Completions=Pe;var qt=class extends u{create(e,t){return this._client.post("/organization/admin_api_keys",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/admin_api_keys",S,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ht=class extends u{list(e={},t){return this._client.getAPIList("/organization/audit_logs",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Wt=class extends u{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},s){return this._client.get(i`/organization/certificates/${e}`,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/certificates/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList("/organization/certificates/activate",G,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList("/organization/certificates/deactivate",G,{body:e,method:"post",...t,__security:{adminAPIKeyAuth:!0}})}};var Jt=class extends u{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/data_retention",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Xt=class extends u{create(e,t){return this._client.post("/organization/invites",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/invites",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends u{create(e,t){return this._client.post("/organization/roles",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/roles/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Gt=class extends u{create(e,t){return this._client.post("/organization/spend_alerts",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/spend_alerts/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Qt=class extends u{retrieve(e){return this._client.get("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post("/organization/spend_limit",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete("/organization/spend_limit",{...e,__security:{adminAPIKeyAuth:!0}})}};var Yt=class extends u{audioSpeeches(e,t){return this._client.get("/organization/usage/audio_speeches",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get("/organization/usage/completions",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get("/organization/costs",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get("/organization/usage/embeddings",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get("/organization/usage/file_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get("/organization/usage/images",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get("/organization/usage/moderations",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get("/organization/usage/vector_stores",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get("/organization/usage/web_search_calls",{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var Zt=class extends u{create(e,t,s){return this._client.post(i`/organization/groups/${e}/roles`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/organization/groups/${e}/roles`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var er=class extends u{create(e,t,s){return this._client.post(i`/organization/groups/${e}/users`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/organization/groups/${e}/users`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var je=class extends u{constructor(){super(...arguments),this.users=new er(this._client),this.roles=new Zt(this._client)}create(e,t){return this._client.post("/organization/groups",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/groups/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",B,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};je.Users=er;je.Roles=Zt;var tr=class extends u{retrieve(e,t,s){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/organization/projects/${e}/api_keys`,v,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/api_keys/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var rr=class extends u{list(e,t={},s){return this._client.getAPIList(i`/organization/projects/${e}/certificates`,v,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}activate(e,t,s){return this._client.getAPIList(i`/organization/projects/${e}/certificates/activate`,G,{body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,s){return this._client.getAPIList(i`/organization/projects/${e}/certificates/deactivate`,G,{body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}};var sr=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/projects/${e}/data_retention`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}};var nr=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}};var or=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/projects/${e}/model_permissions`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var ir=class extends u{listRateLimits(e,t={},s){return this._client.getAPIList(i`/organization/projects/${e}/rate_limits`,v,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,s){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/rate_limits/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}};var ar=class extends u{create(e,t,s){return this._client.post(i`/projects/${e}/roles`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{project_id:n}=t;return this._client.get(i`/projects/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/roles/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/projects/${e}/roles`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{project_id:n}=t;return this._client.delete(i`/projects/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var ur=class extends u{create(e,t,s){return this._client.post(i`/organization/projects/${e}/spend_alerts`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/spend_alerts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/organization/projects/${e}/spend_alerts`,v,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/spend_alerts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var cr=class extends u{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/projects/${e}/spend_limit`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}};var lr=class extends u{create(e,t,s){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/groups/${e}/roles`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{project_id:n,group_id:o}=t;return this._client.get(i`/projects/${n}/groups/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t,s){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/groups/${e}/roles`,B,{query:o,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{project_id:n,group_id:o}=t;return this._client.delete(i`/projects/${n}/groups/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var et=class extends u{constructor(){super(...arguments),this.roles=new lr(this._client)}create(e,t,s){return this._client.post(i`/organization/projects/${e}/groups`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{project_id:n,...o}=t;return this._client.get(i`/organization/projects/${n}/groups/${e}`,{query:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/organization/projects/${e}/groups`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/groups/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};et.Roles=lr;var pr=class extends u{create(e,t,s){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}/api_keys`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}};var tt=class extends u{constructor(){super(...arguments),this.apiKeys=new pr(this._client)}create(e,t,s){return this._client.post(i`/organization/projects/${e}/service_accounts`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/organization/projects/${e}/service_accounts`,v,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/service_accounts/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};tt.APIKeys=pr;var dr=class extends u{create(e,t,s){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/users/${e}/roles`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{project_id:n,user_id:o}=t;return this._client.get(i`/projects/${n}/users/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t,s){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/users/${e}/roles`,B,{query:o,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{project_id:n,user_id:o}=t;return this._client.delete(i`/projects/${n}/users/${o}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var rt=class extends u{constructor(){super(...arguments),this.roles=new dr(this._client)}create(e,t,s){return this._client.post(i`/organization/projects/${e}/users`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/users/${e}`,{body:o,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/organization/projects/${e}/users`,v,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/users/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};rt.Roles=dr;var q=class extends u{constructor(){super(...arguments),this.users=new rt(this._client),this.serviceAccounts=new tt(this._client),this.apiKeys=new tr(this._client),this.rateLimits=new ir(this._client),this.modelPermissions=new or(this._client),this.hostedToolPermissions=new nr(this._client),this.groups=new et(this._client),this.roles=new ar(this._client),this.dataRetention=new sr(this._client),this.spendLimit=new cr(this._client),this.spendAlerts=new ur(this._client),this.certificates=new rr(this._client)}create(e,t){return this._client.post("/organization/projects",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(i`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/projects/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(i`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};q.Users=rt;q.ServiceAccounts=tt;q.APIKeys=tr;q.RateLimits=ir;q.ModelPermissions=or;q.HostedToolPermissions=nr;q.Groups=et;q.Roles=ar;q.DataRetention=sr;q.SpendLimit=cr;q.SpendAlerts=ur;q.Certificates=rr;var fr=class extends u{create(e,t,s){return this._client.post(i`/organization/users/${e}/roles`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,s){let{user_id:n}=t;return this._client.get(i`/organization/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/organization/users/${e}/roles`,B,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{user_id:n}=t;return this._client.delete(i`/organization/users/${n}/roles/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var st=class extends u{constructor(){super(...arguments),this.roles=new fr(this._client)}retrieve(e,t){return this._client.get(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,s){return this._client.post(i`/organization/users/${e}`,{body:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",v,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};st.Roles=fr;var H=class extends u{constructor(){super(...arguments),this.auditLogs=new Ht(this._client),this.adminAPIKeys=new qt(this._client),this.usage=new Yt(this._client),this.invites=new Xt(this._client),this.users=new st(this._client),this.groups=new je(this._client),this.roles=new Vt(this._client),this.dataRetention=new Jt(this._client),this.spendLimit=new Qt(this._client),this.spendAlerts=new Gt(this._client),this.certificates=new Wt(this._client),this.projects=new q(this._client)}};H.AuditLogs=Ht;H.AdminAPIKeys=qt;H.Usage=Yt;H.Invites=Xt;H.Users=st;H.Groups=je;H.Roles=Vt;H.DataRetention=Jt;H.SpendLimit=Qt;H.SpendAlerts=Gt;H.Certificates=Wt;H.Projects=q;var Ne=class extends u{constructor(){super(...arguments),this.organization=new H(this._client)}};Ne.Organization=H;var hr=class extends u{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:d([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var mr=class extends u{create(e,t){return this._client.post("/audio/transcriptions",Q({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var _r=class extends u{create(e,t){return this._client.post("/audio/translations",Q({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var _e=class extends u{constructor(){super(...arguments),this.transcriptions=new mr(this._client),this.translations=new _r(this._client),this.speech=new hr(this._client)}};_e.Transcriptions=mr;_e.Translations=_r;_e.Speech=hr;var nt=class extends u{create(e,t){return this._client.post("/batches",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/batches",S,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var yr=class extends u{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/assistants/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(i`/assistants/${e}`,{body:t,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",S,{query:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/assistants/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var gr=class extends u{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Ar=class extends u{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var Fe=class extends u{constructor(){super(...arguments),this.sessions=new gr(this._client),this.transcriptionSessions=new Ar(this._client)}};Fe.Sessions=gr;Fe.TranscriptionSessions=Ar;var br=class extends u{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/chatkit/sessions/${e}/cancel`,{...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var wr=class extends u{retrieve(e,t){return this._client.get(i`/chatkit/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",v,{query:e,...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chatkit/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},s){return this._client.getAPIList(i`/chatkit/threads/${e}/items`,v,{query:t,...s,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers]),__security:{bearerAuth:!0}})}};var Me=class extends u{constructor(){super(...arguments),this.sessions=new br(this._client),this.threads=new wr(this._client)}};Me.Sessions=br;Me.Threads=wr;var Ir=class extends u{list(e,t={},s){let{betas:n,...o}=t??{};return this._client.getAPIList(i`/responses/${e}/input_items?beta=true`,S,{query:o,...s,headers:d([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},s?.headers]),__security:{bearerAuth:!0}})}};var Pr=class extends u{count(e={},t){let{betas:s,...n}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:n,...t,headers:d([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};var Ke=class extends u{constructor(){super(...arguments),this.inputItems=new Ir(this._client),this.inputTokens=new Pr(this._client)}create(e,t){let{betas:s,...n}=e;return this._client.post("/responses?beta=true",{body:n,...t,headers:d([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},s){let{betas:n,...o}=t??{};return this._client.get(i`/responses/${e}?beta=true`,{query:o,...s,headers:d([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},s?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},s){let{betas:n}=t??{};return this._client.delete(i`/responses/${e}?beta=true`,{...s,headers:d([{Accept:"*/*",...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},s){let{betas:n}=t??{};return this._client.post(i`/responses/${e}/cancel?beta=true`,{...s,headers:d([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},s?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:s,...n}=e;return this._client.post("/responses/compact?beta=true",{body:n,...t,headers:d([{...s?.toString()!=null?{"openai-beta":s?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};Ke.InputItems=Ir;Ke.InputTokens=Pr;var xr=class extends u{create(e,t,s){return this._client.post(i`/threads/${e}/messages`,{body:t,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,s){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/messages/${e}`,{...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/messages/${e}`,{body:o,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/threads/${e}/messages`,S,{query:t,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,t,s){let{thread_id:n}=t;return this._client.delete(i`/threads/${n}/messages/${e}`,{...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var Rr=class extends u{retrieve(e,t,s){let{thread_id:n,run_id:o,...a}=t;return this._client.get(i`/threads/${n}/runs/${o}/steps/${e}`,{query:a,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t,s){let{thread_id:n,...o}=t;return this._client.getAPIList(i`/threads/${n}/runs/${e}/steps`,S,{query:o,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var Vo=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,s=new Uint8Array(t);for(let n=0;n<t;n++)s[n]=e.charCodeAt(n);return Array.from(new Float32Array(s.buffer))}};var le=r=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[r]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(r)?.trim()||void 0};var X,it,Xn,ye,Ws,pe,at,Cr,ot,Vs,se,Js,Xs,_s,hs,ms,Go,Qo,Yo,Zo,ei,ti,ri,xe=class extends ve{constructor(){super(...arguments),X.add(this),Xn.set(this,[]),ye.set(this,{}),Ws.set(this,{}),pe.set(this,void 0),at.set(this,void 0),Cr.set(this,void 0),ot.set(this,void 0),Vs.set(this,void 0),se.set(this,void 0),Js.set(this,void 0),Xs.set(this,void 0),_s.set(this,void 0)}[(Xn=new WeakMap,ye=new WeakMap,Ws=new WeakMap,pe=new WeakMap,at=new WeakMap,Cr=new WeakMap,ot=new WeakMap,Vs=new WeakMap,se=new WeakMap,Js=new WeakMap,Xs=new WeakMap,_s=new WeakMap,X=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("event",n=>{let o=structuredClone(n),a=t.shift();a?a.resolve(o):e.push(o)}),this.on("end",()=>{s=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new it;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let s=Z.fromReadableStream(e,this.controller);for await(let n of s)c(this,X,"m",hs).call(this,n);if(s.controller.signal?.aborted)throw new M;return this._addRun(c(this,X,"m",ms).call(this))}toReadableStream(){return new Z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n){let o=new it;return o._run(()=>o._runToolAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,s,n){this._listenForAbort(n?.signal);let o={...s,stream:!0},a=await e.submitToolOutputs(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of a)c(this,X,"m",hs).call(this,l);if(a.controller.signal?.aborted)throw new M;return this._addRun(c(this,X,"m",ms).call(this))}static createThreadAssistantStream(e,t,s){let n=new it;return n._run(()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,s,n){let o=new it;return o._run(()=>o._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,Js,"f")}currentRun(){return c(this,Xs,"f")}currentMessageSnapshot(){return c(this,pe,"f")}currentRunStepSnapshot(){return c(this,_s,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,ye,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,Ws,"f"))}async finalRun(){if(await this.done(),!c(this,at,"f"))throw Error("Final run was not received.");return c(this,at,"f")}async _createThreadAssistantStream(e,t,s){this._listenForAbort(s?.signal);let n={...t,stream:!0},o=await e.createAndRun(n,{...s,signal:this.controller.signal});this._connected();for await(let a of o)c(this,X,"m",hs).call(this,a);if(o.controller.signal?.aborted)throw new M;return this._addRun(c(this,X,"m",ms).call(this))}async _createAssistantStream(e,t,s,n){this._listenForAbort(n?.signal);let o={...s,stream:!0},a=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of a)c(this,X,"m",hs).call(this,l);if(a.controller.signal?.aborted)throw new M;return this._addRun(c(this,X,"m",ms).call(this))}static accumulateDelta(e,t){for(let[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let o=e[s];if(o==null){e[s]=n;continue}if(s==="index"||s==="type"){e[s]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(Vr(o)&&Vr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...n);continue}for(let a of n){if(!Vr(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);let l=a.index;if(l==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);let f=o[l];f==null?o[l]=a:o[l]=this.accumulateDelta(f,a)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${o}`);e[s]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n){return await this._createToolAssistantStream(t,e,s,n)}};it=xe,hs=function(e){if(!this.ended)switch(x(this,Js,e,"f"),c(this,X,"m",Yo).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":c(this,X,"m",ri).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":c(this,X,"m",Qo).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":c(this,X,"m",Go).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},ms=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");if(!c(this,at,"f"))throw Error("Final run has not been received");return c(this,at,"f")},Go=function(e){let[t,s]=c(this,X,"m",ei).call(this,e,c(this,pe,"f"));x(this,pe,t,"f"),c(this,Ws,"f")[t.id]=t;for(let n of s){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,a=t.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!=c(this,Cr,"f")){if(c(this,ot,"f"))switch(c(this,ot,"f").type){case"text":this._emit("textDone",c(this,ot,"f").text,c(this,pe,"f"));break;case"image_file":this._emit("imageFileDone",c(this,ot,"f").image_file,c(this,pe,"f"));break}x(this,Cr,n.index,"f")}x(this,ot,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,Cr,"f")!==void 0){let n=e.data.content[c(this,Cr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,c(this,pe,"f"));break;case"text":this._emit("textDone",n.text,c(this,pe,"f"));break}}c(this,pe,"f")&&this._emit("messageDone",e.data),x(this,pe,void 0,"f")}},Qo=function(e){let t=c(this,X,"m",Zo).call(this,e);switch(x(this,_s,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of s.step_details.tool_calls)o.index==c(this,Vs,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,se,"f")&&this._emit("toolCallDone",c(this,se,"f")),x(this,Vs,o.index,"f"),x(this,se,t.step_details.tool_calls[o.index],"f"),c(this,se,"f")&&this._emit("toolCallCreated",c(this,se,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":x(this,_s,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,se,"f")&&(this._emit("toolCallDone",c(this,se,"f")),x(this,se,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Yo=function(e){c(this,Xn,"f").push(e),this._emit("event",e)},Zo=function(e){switch(e.event){case"thread.run.step.created":return c(this,ye,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,ye,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){let n=it.accumulateDelta(t,s.delta);c(this,ye,"f")[e.data.id]=n}return c(this,ye,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":c(this,ye,"f")[e.data.id]=e.data;break}if(c(this,ye,"f")[e.data.id])return c(this,ye,"f")[e.data.id];throw new Error("No snapshot available")},ei=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=c(this,X,"m",ti).call(this,o,a)}else t.content[o.index]=o,s.push(o);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},ti=function(e,t){return it.accumulateDelta(t,e)},ri=function(e){switch(x(this,Xs,e.data,"f"),e.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":x(this,at,e.data,"f"),c(this,se,"f")&&(this._emit("toolCallDone",c(this,se,"f")),x(this,se,void 0,"f"));break;case"thread.run.cancelling":break}};var ut=class extends u{constructor(){super(...arguments),this.steps=new Rr(this._client)}create(e,t,s){let{include:n,...o}=t;return this._client.post(i`/threads/${e}/runs`,{query:{include:n},body:o,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,s){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/runs/${e}`,{...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}`,{body:o,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/threads/${e}/runs`,S,{query:t,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,s){let{thread_id:n}=t;return this._client.post(i`/threads/${n}/runs/${e}/cancel`,{...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,s){let n=await this.create(e,t,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,t,s){return xe.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){let n=d([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{let f=a.headers.get("openai-poll-after-ms");if(f){let p=parseInt(f);isNaN(p)||(l=p)}}await he(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,s){return xe.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,s){let n=await this.submitToolOutputs(e,t,s);return await this.poll(n.id,t,s)}submitToolOutputsStream(e,t,s){return xe.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};ut.Steps=Rr;var Be=class extends u{constructor(){super(...arguments),this.runs=new ut(this._client),this.messages=new xr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(i`/threads/${e}`,{body:t,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/threads/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return xe.createThreadAssistantStream(e,this._client.beta.threads,t)}};Be.Runs=ut;Be.Messages=xr;var ie=class extends u{constructor(){super(...arguments),this.realtime=new Fe(this._client),this.responses=new Ke(this._client),this.chatkit=new Me(this._client),this.assistants=new yr(this._client),this.threads=new Be(this._client)}};ie.Realtime=Fe;ie.Responses=Ke;ie.ChatKit=Me;ie.Assistants=yr;ie.Threads=Be;var ct=class extends u{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var Sr=class extends u{retrieve(e,t,s){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}/content`,{...s,headers:d([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var lt=class extends u{constructor(){super(...arguments),this.content=new Sr(this._client)}create(e,t,s){return this._client.post(i`/containers/${e}/files`,Oe({body:t,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,s){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/containers/${e}/files`,S,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){let{container_id:n}=t;return this._client.delete(i`/containers/${n}/files/${e}`,{...s,headers:d([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}};lt.Content=Sr;var Ue=class extends u{constructor(){super(...arguments),this.files=new lt(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/containers",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/containers/${e}`,{...t,headers:d([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};Ue.Files=lt;var kr=class extends u{create(e,t,s){let{include:n,...o}=t;return this._client.post(i`/conversations/${e}/items`,{query:{include:n},body:o,...s,__security:{bearerAuth:!0}})}retrieve(e,t,s){let{conversation_id:n,...o}=t;return this._client.get(i`/conversations/${n}/items/${e}`,{query:o,...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/conversations/${e}/items`,v,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){let{conversation_id:n}=t;return this._client.delete(i`/conversations/${n}/items/${e}`,{...s,__security:{bearerAuth:!0}})}};var ze=class extends u{constructor(){super(...arguments),this.items=new kr(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(i`/conversations/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};ze.Items=kr;var pt=class extends u{create(e,t){let s=!!e.encoding_format,n=s?e.encoding_format:"base64";s&&K(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t,__security:{bearerAuth:!0}});return s?o:(K(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(l=>{let f=l.embedding;l.embedding=Vo(f)}),a)))}};var $r=class extends u{retrieve(e,t,s){let{eval_id:n,run_id:o}=t;return this._client.get(i`/evals/${n}/runs/${o}/output_items/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t,s){let{eval_id:n,...o}=t;return this._client.getAPIList(i`/evals/${n}/runs/${e}/output_items`,S,{query:o,...s,__security:{bearerAuth:!0}})}};var dt=class extends u{constructor(){super(...arguments),this.outputItems=new $r(this._client)}create(e,t,s){return this._client.post(i`/evals/${e}/runs`,{body:t,...s,__security:{bearerAuth:!0}})}retrieve(e,t,s){let{eval_id:n}=t;return this._client.get(i`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/evals/${e}/runs`,S,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){let{eval_id:n}=t;return this._client.delete(i`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}cancel(e,t,s){let{eval_id:n}=t;return this._client.post(i`/evals/${n}/runs/${e}`,{...s,__security:{bearerAuth:!0}})}};dt.OutputItems=$r;var De=class extends u{constructor(){super(...arguments),this.runs=new dt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(i`/evals/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};De.Runs=dt;var ft=class extends u{create(e,t){return this._client.post("/files",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/files",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(i`/files/${e}/content`,{...t,headers:d([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),a=await this.retrieve(e);for(;!a.status||!n.has(a.status);)if(await he(t),a=await this.retrieve(e),Date.now()-o>s)throw new $e({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}};var Er=class extends u{};var Or=class extends u{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t,__security:{bearerAuth:!0}})}};var ht=class extends u{constructor(){super(...arguments),this.graders=new Or(this._client)}};ht.Graders=Or;var vr=class extends u{create(e,t,s){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,G,{body:t,method:"post",...s,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},s){return this._client.get(i`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,v,{query:t,...s,__security:{adminAPIKeyAuth:!0}})}delete(e,t,s){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(i`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...s,__security:{adminAPIKeyAuth:!0}})}};var mt=class extends u{constructor(){super(...arguments),this.permissions=new vr(this._client)}};mt.Permissions=vr;var Tr=class extends u{list(e,t={},s){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...s,__security:{bearerAuth:!0}})}};var _t=class extends u{constructor(){super(...arguments),this.checkpoints=new Tr(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",S,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},s){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/events`,S,{query:t,...s,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(i`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}};_t.Checkpoints=Tr;var de=class extends u{constructor(){super(...arguments),this.methods=new Er(this._client),this.jobs=new _t(this._client),this.checkpoints=new mt(this._client),this.alpha=new ht(this._client)}};de.Methods=Er;de.Jobs=_t;de.Checkpoints=mt;de.Alpha=ht;var Lr=class extends u{};var qe=class extends u{constructor(){super(...arguments),this.graderModels=new Lr(this._client)}};qe.GraderModels=Lr;var yt=class extends u{createVariation(e,t){return this._client.post("/images/variations",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",Q({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var gt=class extends u{retrieve(e,t){return this._client.get(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",G,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/models/${e}`,{...t,__security:{bearerAuth:!0}})}};var At=class extends u{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var jr=class extends u{accept(e,t,s){return this._client.post(i`/realtime/calls/${e}/accept`,{body:t,...s,headers:d([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(i`/realtime/calls/${e}/hangup`,{...t,headers:d([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,s){return this._client.post(i`/realtime/calls/${e}/refer`,{body:t,...s,headers:d([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},s){return this._client.post(i`/realtime/calls/${e}/reject`,{body:t,...s,headers:d([{Accept:"*/*"},s?.headers]),__security:{bearerAuth:!0}})}};var Nr=class extends u{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Re=class extends u{constructor(){super(...arguments),this.clientSecrets=new Nr(this._client),this.calls=new jr(this._client)}};Re.ClientSecrets=Nr;Re.Calls=jr;function si(r,e){if(!e||!Iu(e)){let t={...r,output_parsed:null,output:r.output.map(s=>s.type==="function_call"?{...s,parsed_arguments:null}:s.type==="message"?{...s,content:s.content.map(n=>({...n,parsed:null}))}:s)};return oi(r,t)&&ne(t),t}return Vn(r,e)}function Vn(r,e){let t=!r.status||r.status==="completed",s=r.output.map(o=>{if(o.type==="function_call")return t?xu(e,o):{...o,parsed_arguments:null};if(o.type==="message"){let a=o.content.map(l=>l.type==="output_text"?{...l,parsed:t?wu(e,l.text):null}:l);return{...o,content:a}}return o}),n=Object.assign({},r,{output:s});return oi(r,n)&&ne(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let a of o.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function wu(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function Iu(r){return ss(r.text?.format)?!0:Array.isArray(r.tools)&&r.tools.some(e=>ni(e)||e.type==="function"&&e.strict===!0)}function ni(r){return r?.$brand==="auto-parseable-tool"}function Pu(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function xu(r,e){let t=Pu(r.tools??[],e.name);return{...e,...e,parsed_arguments:ni(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function oi(r,e){return!Object.getOwnPropertyDescriptor(r,"output_text")||e.output_text==null}function ne(r){let e=[];for(let t of r.output)if(t.type==="message")for(let s of t.content)s.type==="output_text"&&e.push(s.text);r.output_text=e.join("")}function ai(r,e){if(!e){if(r.type!=="response.created")throw new g(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return ii(r.response)}switch(r.type){case"response.output_item.added":{e.output.push(structuredClone(r.item)),r.item.type==="message"&&ne(e);break}case"response.output_item.done":{O(e,r.output_index),e.output[r.output_index]=structuredClone(r.item),r.item.type==="message"&&ne(e);break}case"response.content_part.added":{let t=O(e,r.output_index),s=t.type,n=r.part;s==="message"&&n.type!=="reasoning_text"?(t.content.push(structuredClone(n)),n.type==="output_text"&&ne(e)):s==="reasoning"&&n.type==="reasoning_text"&&(t.content||(t.content=[]),t.content.push(structuredClone(n)));break}case"response.content_part.done":{let t=O(e,r.output_index),s=r.part;if(t.type==="message"&&s.type!=="reasoning_text")ae(t.content,r.content_index),t.content[r.content_index]=structuredClone(s),s.type==="output_text"&&ne(e);else if(t.type==="reasoning"&&s.type==="reasoning_text"){let n=t.content;if(!n)throw new g(`missing content at index ${r.content_index}`);ae(n,r.content_index),n[r.content_index]=structuredClone(s)}break}case"response.output_text.delta":{let t=O(e,r.output_index);if(t.type==="message"){let s=ae(t.content,r.content_index);if(s.type!=="output_text")throw new g(`expected content to be 'output_text', got ${s.type}`);s.text+=r.delta,e.output_text+=r.delta}break}case"response.output_text.done":{let t=O(e,r.output_index);if(t.type==="message"){let s=ae(t.content,r.content_index);if(s.type!=="output_text")throw new g(`expected content to be 'output_text', got ${s.type}`);s.text=r.text,ne(e)}break}case"response.output_text.annotation.added":{let t=O(e,r.output_index);if(t.type==="message"){let s=ae(t.content,r.content_index);if(s.type!=="output_text")throw new g(`expected content to be 'output_text', got ${s.type}`);s.annotations[r.annotation_index]=structuredClone(r.annotation)}break}case"response.refusal.delta":{let t=O(e,r.output_index);if(t.type==="message"){let s=ae(t.content,r.content_index);if(s.type!=="refusal")throw new g(`expected content to be 'refusal', got ${s.type}`);s.refusal+=r.delta}break}case"response.refusal.done":{let t=O(e,r.output_index);if(t.type==="message"){let s=ae(t.content,r.content_index);if(s.type!=="refusal")throw new g(`expected content to be 'refusal', got ${s.type}`);s.refusal=r.refusal}break}case"response.function_call_arguments.delta":{let t=O(e,r.output_index);t.type==="function_call"&&(t.arguments+=r.delta);break}case"response.function_call_arguments.done":{let t=O(e,r.output_index);t.type==="function_call"&&(t.arguments=r.arguments);break}case"response.reasoning_text.delta":{let t=O(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${r.content_index}`);let s=ae(t.content,r.content_index);if(s.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${s.type}`);s.text+=r.delta}break}case"response.reasoning_text.done":{let t=O(e,r.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${r.content_index}`);let s=ae(t.content,r.content_index);if(s.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${s.type}`);s.text=r.text}break}case"response.reasoning_summary_part.added":{let t=O(e,r.output_index);t.type==="reasoning"&&t.summary.push(structuredClone(r.part));break}case"response.reasoning_summary_part.done":{let t=O(e,r.output_index);t.type==="reasoning"&&(ae(t.summary,r.summary_index),t.summary[r.summary_index]=structuredClone(r.part));break}case"response.reasoning_summary_text.delta":{let t=O(e,r.output_index);if(t.type==="reasoning"){let s=ae(t.summary,r.summary_index);s.text+=r.delta}break}case"response.reasoning_summary_text.done":{let t=O(e,r.output_index);if(t.type==="reasoning"){let s=ae(t.summary,r.summary_index);s.text=r.text}break}case"response.custom_tool_call_input.delta":{let t=O(e,r.output_index);t.type==="custom_tool_call"&&(t.input+=r.delta);break}case"response.custom_tool_call_input.done":{let t=O(e,r.output_index);t.type==="custom_tool_call"&&(t.input=r.input);break}case"response.mcp_call_arguments.delta":{let t=O(e,r.output_index);t.type==="mcp_call"&&(t.arguments+=r.delta);break}case"response.mcp_call_arguments.done":{let t=O(e,r.output_index);t.type==="mcp_call"&&(t.arguments=r.arguments);break}case"response.code_interpreter_call_code.delta":{let t=O(e,r.output_index);t.type==="code_interpreter_call"&&(t.code=(t.code??"")+r.delta);break}case"response.code_interpreter_call_code.done":{let t=O(e,r.output_index);t.type==="code_interpreter_call"&&(t.code=r.code);break}case"response.code_interpreter_call.in_progress":{let t=O(e,r.output_index);t.type==="code_interpreter_call"&&(t.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let t=O(e,r.output_index);t.type==="code_interpreter_call"&&(t.status="interpreting");break}case"response.code_interpreter_call.completed":{let t=O(e,r.output_index);t.type==="code_interpreter_call"&&(t.status="completed");break}case"response.file_search_call.in_progress":{let t=O(e,r.output_index);t.type==="file_search_call"&&(t.status="in_progress");break}case"response.file_search_call.searching":{let t=O(e,r.output_index);t.type==="file_search_call"&&(t.status="searching");break}case"response.file_search_call.completed":{let t=O(e,r.output_index);t.type==="file_search_call"&&(t.status="completed");break}case"response.web_search_call.in_progress":{let t=O(e,r.output_index);t.type==="web_search_call"&&(t.status="in_progress");break}case"response.web_search_call.searching":{let t=O(e,r.output_index);t.type==="web_search_call"&&(t.status="searching");break}case"response.web_search_call.completed":{let t=O(e,r.output_index);t.type==="web_search_call"&&(t.status="completed");break}case"response.image_generation_call.in_progress":{let t=O(e,r.output_index);t.type==="image_generation_call"&&(t.status="in_progress");break}case"response.image_generation_call.generating":{let t=O(e,r.output_index);t.type==="image_generation_call"&&(t.status="generating");break}case"response.image_generation_call.completed":{let t=O(e,r.output_index);t.type==="image_generation_call"&&(t.status="completed");break}case"response.mcp_call.in_progress":{let t=O(e,r.output_index);t.type==="mcp_call"&&(t.status="in_progress");break}case"response.mcp_call.completed":{let t=O(e,r.output_index);t.type==="mcp_call"&&(t.status="completed");break}case"response.mcp_call.failed":{let t=O(e,r.output_index);t.type==="mcp_call"&&(t.status="failed");break}case"response.created":case"response.queued":case"response.in_progress":case"response.completed":case"response.failed":case"response.incomplete":{e=ii(r.response);break}case"response.audio.delta":case"response.audio.done":case"response.audio.transcript.delta":case"response.audio.transcript.done":case"response.image_generation_call.partial_image":case"response.mcp_list_tools.in_progress":case"response.mcp_list_tools.completed":case"response.mcp_list_tools.failed":case"keepalive":case"error":break;default:Ru(r)}return e}function ii(r){let e=structuredClone(r);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&ne(e),e}function O(r,e){let t=r.output[e];if(!t)throw new g(`missing output at index ${e}`);return t}function ae(r,e){let t=r[e];if(!t)throw new g(`missing content at index ${e}`);return t}function Ru(r){throw new g(`Unhandled response stream event: ${JSON.stringify(r)}`)}var He,Gs,bt,Qs,Gn,Qn,Yn,Ys=class r extends ve{constructor(e){super(),He.add(this),Gs.set(this,void 0),bt.set(this,void 0),Qs.set(this,void 0),x(this,Gs,e,"f")}static createResponse(e,t,s){let n=new r(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}async _createOrRetrieveResponse(e,t,s){this._listenForAbort(s?.signal),c(this,He,"m",Gn).call(this);let n,o=null;"response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(let a of n)c(this,He,"m",Qn).call(this,a,o);if(n.controller.signal?.aborted)throw new M;return c(this,He,"m",Yn).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,He,"m",Gn).call(this),this._connected();let s=Z.fromReadableStream(e,this.controller);for await(let n of s)c(this,He,"m",Qn).call(this,n,null);if(s.controller.signal?.aborted)throw new M;return c(this,He,"m",Yn).call(this)}[(Gs=new WeakMap,bt=new WeakMap,Qs=new WeakMap,He=new WeakSet,Gn=function(){this.ended||x(this,bt,void 0,"f")},Qn=function(t,s){if(this.ended)return;let n=(a,l)=>{(s==null||l.sequence_number>s)&&this._emit(a,l)},o=ai(t,c(this,bt,"f"));switch(x(this,bt,o,"f"),n("event",t),t.type){case"response.output_text.delta":{let a=o.output[t.output_index];if(!a)throw new g(`missing output at index ${t.output_index}`);if(a.type==="message"){let l=a.content[t.content_index];if(!l)throw new g(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new g(`expected content to be 'output_text', got ${l.type}`);n("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{let a=o.output[t.output_index];if(!a)throw new g(`missing output at index ${t.output_index}`);a.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:n(t.type,t);break}},Yn=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=c(this,bt,"f");if(!t)throw new g("request ended without sending any events");x(this,bt,void 0,"f");let s=Cu(t,c(this,Gs,"f"));return x(this,Qs,s,"f"),s},Symbol.asyncIterator)](){let e=[],t=[],s=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{s=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{s=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=c(this,Qs,"f");if(!e)throw new g("stream ended without producing a ChatCompletion");return e}};function Cu(r,e){return si(r,e)}var Fr=class extends u{list(e,t={},s){return this._client.getAPIList(i`/responses/${e}/input_items`,S,{query:t,...s,__security:{bearerAuth:!0}})}};var Mr=class extends u{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var ge=class extends u{constructor(){super(...arguments),this.inputItems=new Fr(this._client),this.inputTokens=new Mr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(s=>("object"in s&&s.object==="response"&&ne(s),s))}retrieve(e,t={},s){return this._client.get(i`/responses/${e}`,{query:t,...s,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ne(n),n))}delete(e,t){return this._client.delete(i`/responses/${e}`,{...t,headers:d([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>Vn(s,e))}stream(e,t){return Ys.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(i`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post("/responses/compact",{body:e,...t,__security:{bearerAuth:!0}})}};ge.InputItems=Fr;ge.InputTokens=Mr;var Kr=class extends u{retrieve(e,t){return this._client.get(i`/skills/${e}/content`,{...t,headers:d([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Br=class extends u{retrieve(e,t,s){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}/content`,{...s,headers:d([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var wt=class extends u{constructor(){super(...arguments),this.content=new Br(this._client)}create(e,t={},s){return this._client.post(i`/skills/${e}/versions`,Oe({body:t,...s,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,s){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/skills/${e}/versions`,S,{query:t,...s,__security:{bearerAuth:!0}})}delete(e,t,s){let{skill_id:n}=t;return this._client.delete(i`/skills/${n}/versions/${e}`,{...s,__security:{bearerAuth:!0}})}};wt.Content=Br;var Ce=class extends u{constructor(){super(...arguments),this.content=new Kr(this._client),this.versions=new wt(this._client)}create(e={},t){return this._client.post("/skills",Oe({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(i`/skills/${e}`,{body:t,...s,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",S,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};Ce.Content=Kr;Ce.Versions=wt;var Ur=class extends u{create(e,t,s){return this._client.post(i`/uploads/${e}/parts`,Q({body:t,...s,__security:{bearerAuth:!0}},this._client))}};var We=class extends u{constructor(){super(...arguments),this.parts=new Ur(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,s){return this._client.post(i`/uploads/${e}/complete`,{body:t,...s,__security:{bearerAuth:!0}})}};We.Parts=Ur;var ui=async r=>{let e=await Promise.allSettled(r),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let s=[];for(let n of e)n.status==="fulfilled"&&s.push(n.value);return s};var zr=class extends u{create(e,t,s){return this._client.post(i`/vector_stores/${e}/file_batches`,{body:t,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,s){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/file_batches/${e}`,{...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,s){let{vector_store_id:n}=t;return this._client.post(i`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,s){let n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s){let{vector_store_id:n,...o}=t;return this._client.getAPIList(i`/vector_stores/${n}/file_batches/${e}/files`,S,{query:o,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,s){let n=d([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:a}=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{let f=a.headers.get("openai-poll-after-ms");if(f){let p=parseInt(f);isNaN(p)||(l=p)}}await he(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,a=Math.min(o,t.length),l=this._client,f=t.values(),p=[...s];async function h(m){for(let w of m){let P=await l.files.create({file:w,purpose:"assistants"},n);p.push(P.id)}}let _=Array(a).fill(f).map(h);return await ui(_),await this.createAndPoll(e,{file_ids:p})}};var Dr=class extends u{create(e,t,s){return this._client.post(i`/vector_stores/${e}/files`,{body:t,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,s){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/files/${e}`,{...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){let{vector_store_id:n,...o}=t;return this._client.post(i`/vector_stores/${n}/files/${e}`,{body:o,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e,t={},s){return this._client.getAPIList(i`/vector_stores/${e}/files`,S,{query:t,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}delete(e,t,s){let{vector_store_id:n}=t;return this._client.delete(i`/vector_stores/${n}/files/${e}`,{...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,s){let n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){let n=d([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse(),a=o.data;switch(a.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{let f=o.response.headers.get("openai-poll-after-ms");if(f){let p=parseInt(f);isNaN(p)||(l=p)}}await he(l);break;case"failed":case"completed":return a}}}async upload(e,t,s){let n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){let n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){let{vector_store_id:n}=t;return this._client.getAPIList(i`/vector_stores/${n}/files/${e}/content`,G,{...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};var Se=class extends u{constructor(){super(...arguments),this.files=new Dr(this._client),this.fileBatches=new zr(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/vector_stores/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,s){return this._client.post(i`/vector_stores/${e}`,{body:t,...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",S,{query:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/vector_stores/${e}`,{...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,s){return this._client.getAPIList(i`/vector_stores/${e}/search`,G,{body:t,method:"post",...s,headers:d([{"OpenAI-Beta":"assistants=v2"},s?.headers]),__security:{bearerAuth:!0}})}};Se.Files=Dr;Se.FileBatches=zr;var It=class extends u{create(e,t){return this._client.post("/videos",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/videos",v,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post("/videos/characters",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},s){return this._client.get(i`/videos/${e}/content`,{query:t,...s,headers:d([{Accept:"application/binary"},s?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",Q({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(i`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,s){return this._client.post(i`/videos/${e}/remix`,Oe({body:t,...s,__security:{bearerAuth:!0}},this._client))}};var qr,ci,Zs,Pt=class extends u{constructor(){super(...arguments),qr.add(this)}async unwrap(e,t,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,s,n),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");c(this,qr,"m",ci).call(this,s);let o=d([t]).values,a=c(this,qr,"m",Zs).call(this,o,"webhook-signature"),l=c(this,qr,"m",Zs).call(this,o,"webhook-timestamp"),f=c(this,qr,"m",Zs).call(this,o,"webhook-id"),p=parseInt(l,10);if(isNaN(p))throw new fe("Invalid webhook timestamp format");let h=Math.floor(Date.now()/1e3);if(h-p>n)throw new fe("Webhook timestamp is too old");if(p>h+n)throw new fe("Webhook timestamp is too new");let _=a.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),m=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),w=f?`${f}.${l}.${e}`:`${l}.${e}`,P=await crypto.subtle.importKey("raw",m,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of _)try{let I=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",P,I,new TextEncoder().encode(w)))return}catch{continue}throw new fe("The given webhook signature does not match the expected signature")}};qr=new WeakSet,ci=function(e){if(typeof e!="string"||e.length===0)throw new 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")},Zs=function(e,t){if(!e)throw new Error("Headers are required");let s=e.get(t);if(s==null)throw new Error(`Missing required header: ${t}`);return s};var pi=Symbol.for("openai.node.providerDefinitions.v1"),di=globalThis,fi=di[pi],hi=fi??new WeakMap;fi||Object.defineProperty(di,pi,{value:hi});function mi(r){let e=hi.get(r);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var Zn,eo,ys,_i,ju="workload-identity-auth",R=class{constructor(e={}){Zn.add(this),ys.set(this,void 0),this.completions=new ct(this),this.chat=new Le(this),this.embeddings=new pt(this),this.files=new ft(this),this.images=new yt(this),this.audio=new _e(this),this.moderations=new At(this),this.models=new gt(this),this.fineTuning=new de(this),this.graders=new qe(this),this.vectorStores=new Se(this),this.webhooks=new Pt(this),this.beta=new ie(this),this.batches=new nt(this),this.uploads=new We(this),this.admin=new Ne(this),this.responses=new ge(this),this.realtime=new Re(this),this.conversations=new ze(this),this.evals=new De(this),this.containers=new Ue(this),this.skills=new Ce(this),this.videos=new It(this);let t=e.provider;if(t){let b=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(I=>e[I]!=null);if(b.length)throw new g(`The \`provider\` option cannot be used with ${b.map(I=>`\`${I}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:s=t?null:le("OPENAI_BASE_URL"),apiKey:n=t?null:le("OPENAI_API_KEY")??null,adminAPIKey:o=t?null:le("OPENAI_ADMIN_KEY")??null,organization:a=t?null:le("OPENAI_ORG_ID")??null,project:l=t?null:le("OPENAI_PROJECT_ID")??null,webhookSecret:f=le("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:p,...h}=e,_=t?mi(t):void 0,m={apiKey:n,adminAPIKey:o,organization:a,project:l,webhookSecret:f,workloadIdentity:p,provider:t,...h,baseURL:_?.baseURL??(s||"https://api.openai.com/v1")};if(n&&p)throw new g("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!_&&!n&&!o&&!p)throw new g("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!m.dangerouslyAllowBrowser&&po())throw new g(`It looks like you're running in a browser-like environment.
|
|
25
|
+
|
|
26
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
27
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
28
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
29
|
+
|
|
30
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
31
|
+
|
|
32
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
33
|
+
`);this.baseURL=m.baseURL,this.timeout=m.timeout??eo.DEFAULT_TIMEOUT,this.logger=m.logger??console;let w="warn";this.logLevel=w,this.logLevel=wn(m.logLevel,"ClientOptions.logLevel",this)??wn(le("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??w,this.fetchOptions=m.fetchOptions,this.maxRetries=m.maxRetries??2,this.fetch=m.fetch??Cs(),x(this,ys,mo,"f");let P=t?void 0:le("OPENAI_CUSTOM_HEADERS");if(P){let b={};for(let I of P.split(`
|
|
34
|
+
`)){let $=I.indexOf(":");$>=0&&(b[I.substring(0,$).trim()]=I.substring($+1).trim())}m.defaultHeaders=d([b,m.defaultHeaders])}this._options=m,this._provider=_,p&&(this._workloadIdentityAuth=new Ts(p,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=a,this.project=l,this.webhookSecret=f}withOptions(e){let t=this._options.provider,s=e.provider??t,n={...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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return s&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,s!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:s})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&s.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return d([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return d([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return d([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return d([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return xo(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ee}`}defaultIdempotencyKey(){return`stainless-node-retry-${Je()}`}makeStatusError(e,t,s,n){return F.generate(e,t,s,n)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(s){throw s instanceof g?s:new g(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof t!="string"||!t)throw new g(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){let n=!c(this,Zn,"m",_i).call(this)&&s||this.baseURL,o=no(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!pn(a)||!pn(l))&&(t={...l,...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){if(this._provider)return;(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Ge(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:a,url:l,timeout:f}=await this.buildRequest(n,{retryCount:o-t}),p=n.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:l,options:n}),await this._provider?.prepareRequest?.(a,{url:l,options:n});let h="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),_=s===void 0?"":`, retryOf: ${s}`,m=Date.now();if(K(this).debug(`[${h}] sending request`,Ae({retryOfRequestLogID:s,method:n.method,url:l,options:n,headers:a.headers})),n.signal?.aborted)throw new M;let w=n.__security??{bearerAuth:!0},P=new AbortController,b=await this.fetchWithAuth(l,a,f,P,w).catch(Jr),I=Date.now();if(b instanceof globalThis.Error){let E=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new M;let y=Wr(b)||/timed? ?out/i.test(String(b)+("cause"in b?String(b.cause):""));if(t&&!p)return K(this).info(`[${h}] connection ${y?"timed out":"failed"} - ${E}`),K(this).debug(`[${h}] connection ${y?"timed out":"failed"} (${E})`,Ae({retryOfRequestLogID:s,url:l,durationMs:I-m,message:b.message})),this.retryRequest(n,t,s??h);let C=p?"error; streaming body cannot be retried":"error; no more retries left";throw K(this).info(`[${h}] connection ${y?"timed out":"failed"} - ${C}`),K(this).debug(`[${h}] connection ${y?"timed out":"failed"} (${C})`,Ae({retryOfRequestLogID:s,url:l,durationMs:I-m,message:b.message})),b instanceof Xe||b instanceof Xr?b:y?new $e:new ke({message:Nu(b),cause:b})}let $=[...b.headers.entries()].filter(([E])=>E==="x-request-id").map(([E,y])=>", "+E+": "+JSON.stringify(y)).join(""),A=`[${h}${_}${$}] ${a.method} ${l} ${b.ok?"succeeded":"failed"} with status ${b.status} in ${I-m}ms`;if(!b.ok){if(b.status===401&&this._workloadIdentityAuth&&w.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await fn(b.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,s??h);let E=await this.shouldRetry(b);if(t&&E&&!p){let N=`retrying, ${t} attempts remaining`;return await fn(b.body),K(this).info(`${A} - ${N}`),K(this).debug(`[${h}] response error (${N})`,Ae({retryOfRequestLogID:s,url:b.url,status:b.status,headers:b.headers,durationMs:I-m})),this.retryRequest(n,t,s??h,b.headers)}let y=E?p?"error; streaming body cannot be retried":"error; no more retries left":"error; not retryable";K(this).info(`${A} - ${y}`);let C=await b.text().catch(N=>Jr(N).message),k=ao(C),L=k?void 0:C;throw K(this).debug(`[${h}] response error (${y})`,Ae({retryOfRequestLogID:s,url:b.url,status:b.status,headers:b.headers,message:L,durationMs:Date.now()-m})),this.makeStatusError(b.status,k,L,b.headers)}return K(this).info(A),K(this).debug(`[${h}] response start`,Ae({retryOfRequestLogID:s,url:b.url,status:b.status,headers:b.headers,durationMs:I-m})),{response:b,options:n,controller:P,requestLogID:h,retryOfRequestLogID:s,startTime:m}}getAPIList(e,t,s){return this.requestAPIList(t,s&&"then"in s?s.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...s})}requestAPIList(e,t){let s=this.makeRequest(t,null,void 0);return new es(this,s,e)}async fetchWithAuth(e,t,s,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let l=t.headers,f=l.get("Authorization");if(!f||f===`Bearer ${ju}`){let p=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${p}`)}}return await this.fetchWithTimeout(e,t,s,n)}async fetchWithTimeout(e,t,s,n){let{signal:o,method:a,...l}=t||{},f=this._makeAbort(n);o&&o.addEventListener("abort",f,{once:!0});let p=setTimeout(f,s),h=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,_={signal:n.signal,...h?{duplex:"half"}:{},method:"GET",...l};a&&(_.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,_)}finally{clearTimeout(p)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s,n){let o,a=n?.get("retry-after-ms");if(a){let f=parseFloat(a);Number.isNaN(f)||(o=f)}let l=n?.get("retry-after");if(l&&!o){let f=parseFloat(l);Number.isNaN(f)?o=Date.parse(l)-Date.now():o=f*1e3}if(o===void 0){let f=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,f)}return await he(o),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,a=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return a*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let s={...e},{method:n,path:o,query:a,defaultBaseURL:l}=s,f=this.buildURL(o,a,l);"timeout"in s&&io("timeout",s.timeout),s.timeout=s.timeout??this.timeout;let{bodyHeaders:p,body:h,isStreamingBody:_}=this.buildBody({options:s});_&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let m=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:m,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"},...h&&{body:h},...this.fetchOptions??{},...s.fetchOptions??{}},url:f,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let a=d([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...fo(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,s,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:s}=e;if(!t)return t===void 0&&"body"in e?{...c(this,ys,"f").call(this,{body:t,headers:d([s])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=d([s]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,a=!o&&(typeof t=="string"||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||typeof globalThis.Blob<"u"&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t=="string"&&n.values.has("content-type")||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||o?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:Gr(t),isStreamingBody:!0}:typeof t=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(t),isStreamingBody:!1}:{...c(this,ys,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};eo=R,ys=new WeakMap,Zn=new WeakSet,_i=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};R.OpenAI=eo;R.DEFAULT_TIMEOUT=6e5;R.OpenAIError=g;R.APIError=F;R.APIConnectionError=ke;R.APIConnectionTimeoutError=$e;R.APIUserAbortError=M;R.NotFoundError=$t;R.ConflictError=Et;R.RateLimitError=vt;R.BadRequestError=Ct;R.AuthenticationError=St;R.InternalServerError=Tt;R.PermissionDeniedError=kt;R.UnprocessableEntityError=Ot;R.InvalidWebhookSignatureError=fe;R.toFile=Fs;R.toStreamingFile=js;R.Completions=ct;R.Chat=Le;R.Embeddings=pt;R.Files=ft;R.Images=yt;R.Audio=_e;R.Moderations=At;R.Models=gt;R.FineTuning=de;R.Graders=qe;R.VectorStores=Se;R.Webhooks=Pt;R.Beta=ie;R.Batches=nt;R.Uploads=We;R.Admin=Ne;R.Responses=ge;R.Realtime=Re;R.Conversations=ze;R.Evals=De;R.Containers=Ue;R.Skills=Ce;R.Videos=It;function Nu(r){if(Fu(r))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function Fu(r){let e=r;for(let t=0;t<8&&e&&typeof e=="object";t++){let s=e;if(s.code==="UND_ERR_INVALID_ARG"&&typeof s.message=="string"&&s.message.includes("invalid onRequestStart method"))return!0;e=s.cause}return!1}var en=ro({module:"llm"});function Mu(r){switch(r.type){case"scroll":return{type:"scroll",x:r.x,y:r.y,scrollX:r.scroll_x,scrollY:r.scroll_y,...r.keys?.length?{keys:r.keys}:{}};case"click":case"double_click":case"drag":case"move":{let{keys:e,...t}=r;return{...t,...e?.length?{keys:e}:{}}}default:return{...r}}}function Ku(r){return{actions:(r.actions??(r.action?[r.action]:[])).map(Mu),pendingSafetyChecks:r.pending_safety_checks.map(t=>({id:t.id,...t.code?{code:t.code}:{},...t.message?{message:t.message}:{}})),status:r.status}}function Bu(r){if("type"in r&&r.type==="computer")return{...r};if("input_schema"in r){let e=r;return{type:"function",name:e.name,description:e.description,parameters:e.input_schema,strict:e.strict??!1}}if("type"in r&&r.type==="function"&&"parameters"in r)return{...r};throw new Error("OpenAI Responses received a tool schema serialized for another protocol.")}function Uu(r){if("input_schema"in r){let e=r;return{type:"function",function:{name:e.name,description:e.description,parameters:e.input_schema,strict:e.strict??!1}}}if("function"in r)return{...r};throw new Error("OpenAI Chat Completions received a tool schema serialized for another protocol.")}var yi=class{protocol="openai";client;model;systemPrompt;maxOutputTokens;thinkingLevel;config;constructor(e,t){let s=an(e);if(!s)throw new Is("OpenAI API key not found, set OPENAI_API_KEY in ~/.swifty/config.yaml, or via OPENAI_API_KEY env variable.");this.client=new R({apiKey:s,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=on(e),this.config={...e},this.thinkingLevel=tn(e)}async*stream(e,t,s){let n=Xu(cn(e.getMessages())),o=[];o.push({role:"system",content:this.systemPrompt});for(let w of n)o.push(w);let a=t.map(Bu),l=rn(this.getThinkingLevel(),this.config),f={model:this.model,input:o,stream:!0,max_output_tokens:this.maxOutputTokens,...a.length>0?{tools:a}:{},...l!==null?{reasoning:{effort:l,...l!=="none"?{summary:"auto"}:{}}}:{}},p=0,h=0,_=0,m=0;try{let w=await this.client.responses.create(f,{...s?{signal:s}:{}}),P="",b="",I="",$="",A="",E=!1;for await(let y of w)if(y.type==="response.output_text.delta")yield{type:"text_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.delta")A+=y.delta,yield{type:"thinking_delta",text:y.delta};else if(y.type==="response.reasoning_summary_text.done")yield{type:"thinking_complete",thinking:A,signature:$};else if(y.type==="response.function_call_arguments.delta")I+=y.delta,yield{type:"tool_call_delta",text:y.delta};else if(y.type==="response.output_item.added")y.item.type==="function_call"?(P=y.item.name,b=y.item.call_id,I="",yield{type:"tool_call_start",toolName:P,toolId:b}):y.item.type==="computer_call"?yield{type:"tool_call_start",toolName:"ComputerUse",toolId:y.item.call_id}:y.item.type==="reasoning"&&($=y.item.id??"",A="");else if(y.type==="response.output_item.done")if(y.item.type==="function_call"&&P){let C={};if(I)try{let k=JSON.parse(I);C=ue(k)?ws(k):{}}catch(k){en.error({err:k},"llm operation failed"),C={}}yield{type:"tool_call_complete",toolId:b,toolName:P,arguments:C},P="",b="",I=""}else y.item.type==="computer_call"&&(yield{type:"tool_call_complete",toolId:y.item.call_id,toolName:"ComputerUse",arguments:Ku(y.item),providerItemId:y.item.id});else if(y.type==="response.completed"||y.type==="response.incomplete"){E=!0;let C=y.response.usage;C&&(h=C.output_tokens,_=C.input_tokens_details?.cached_tokens??0,p=Math.max(0,C.input_tokens-_));let k="end_turn",L=y.response;if(y.type==="response.incomplete"||L.status==="incomplete"){let j=L.incomplete_details;if(j?.reason==="max_output_tokens")k="max_tokens";else throw new Rt(`Response incomplete: ${j?.reason??"unknown reason"}`)}yield{type:"stream_end",stopReason:k,usage:{inputTokens:p,outputTokens:h,cacheReadInputTokens:_,cacheCreationInputTokens:m}}}else if(y.type==="response.failed"){let C=y.response.error,k=`${C?.code??"unknown"}: ${C?.message??"Response failed"}`;throw to(k)?new xs(k):new Rt(k)}else if(y.type==="error"){let C=`${y.code??"unknown"}: ${y.message}`;throw to(C)?new xs(C):new Rt(C)}if(!E)throw new Ps("OpenAI Responses stream ended before a terminal response event")}catch(w){throw en.error({err:w},"llm operation failed"),Ii(w)}}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}setThinkingLevel(e){return this.thinkingLevel=nn(this.config,e),this.thinkingLevel}getThinkingLevel(){return this.thinkingLevel}getSupportedThinkingLevels(){return sn(this.config)}};function gs(r){if(!ue(r)||r.type!=="image"||!ue(r.source))return null;if(r.source.type==="url")return oe(r.source,"url")||null;if(r.source.type!=="base64")return null;let e=oe(r.source,"media_type"),t=oe(r.source,"data");return e&&t?`data:${e};base64,${t}`:null}function zu(r){if(!ue(r)||r.type!=="document"||!ue(r.source))return null;let e=typeof r.title=="string"&&r.title?r.title:"tool-result";if(r.source.type==="url"){let t=oe(r.source,"url");return t?{type:"input_file",file_url:t}:null}if(r.source.type==="base64"){let t=oe(r.source,"data");return t?{type:"input_file",file_data:t,filename:`${e}.pdf`}:null}if(r.source.type==="text"){let t=oe(r.source,"data");return t?{type:"input_file",file_data:Buffer.from(t,"utf-8").toString("base64"),filename:`${e}.txt`}:null}return null}function Du(r){if(!ue(r)||r.type!=="document"||!ue(r.source))return null;let e=typeof r.title=="string"&&r.title?r.title:"tool-result";if(r.source.type==="base64"){let t=oe(r.source,"data");return t?{type:"file",file:{file_data:t,filename:`${e}.pdf`}}:null}if(r.source.type==="text"){let t=oe(r.source,"data");return t?{type:"file",file:{file_data:Buffer.from(t,"utf-8").toString("base64"),filename:`${e}.txt`}}:null}return null}function qu(r){if(!r.contentBlocks?.length)return r.content;let e=[];r.content&&e.push({type:"input_text",text:r.content});for(let t of r.contentBlocks){let s=gs(t);if(s){e.push({type:"input_image",image_url:s,detail:"auto"});continue}let n=zu(t);n&&e.push(n)}return e.length>0?e:r.content}function Hu(r){if(!Array.isArray(r.actions))return[];let e=[];for(let t of r.actions)if(!(!ue(t)||typeof t.type!="string")){if(t.type==="scroll"){e.push({type:"scroll",x:Number(t.x),y:Number(t.y),scroll_x:Number(t.scrollX),scroll_y:Number(t.scrollY),...Array.isArray(t.keys)?{keys:t.keys.map(String)}:{}});continue}e.push(t)}return e}function gi(r){return Array.isArray(r.pendingSafetyChecks)?r.pendingSafetyChecks.flatMap(e=>!ue(e)||typeof e.id!="string"?[]:[{id:e.id,...typeof e.code=="string"?{code:e.code}:{},...typeof e.message=="string"?{message:e.message}:{}}]):[]}function Wu(r){for(let e of r.contentBlocks??[]){let t=gs(e);if(t)return t}}function Ju(r){if(!r.contentBlocks?.length)return[];let e=[];for(let t of r.contentBlocks){let s=gs(t);if(s){e.push({type:"image_url",image_url:{url:s}});continue}let n=Du(t);n&&e.push(n)}return e.length===0?[]:[{type:"text",text:`[Rich content returned by tool call ${r.toolUseId}]`},...e]}function Ai(r){if(typeof r=="string")return r;let e=[];for(let t of r)if(t.type==="text")e.push({type:"input_text",text:oe(t,"text")});else{let s=gs(t);s&&e.push({type:"input_image",image_url:s,detail:"auto"})}return e}function bi(r){if(typeof r=="string")return r;let e=[];for(let t of r)if(t.type==="text")e.push({type:"text",text:oe(t,"text")});else{let s=gs(t);s&&e.push({type:"image_url",image_url:{url:s}})}return e}function Xu(r){let e=[],t=new Map;for(let s of r)for(let n of s.toolUses??[])n.toolName==="ComputerUse"&&t.set(n.toolUseId,n);for(let s of r){if(s.thinkingBlocks)for(let n of s.thinkingBlocks)e.push({type:"reasoning",id:n.signature,summary:[{type:"summary_text",text:n.thinking}]});if(s.toolUses&&s.toolUses.length>0){let n=typeof s.content=="string"?s.content:Hr(s.content);n&&e.push({role:"assistant",content:n});for(let o of s.toolUses)if(o.toolName==="ComputerUse"){let a=o.arguments.status;e.push({type:"computer_call",id:o.providerItemId??o.toolUseId,call_id:o.toolUseId,status:a==="in_progress"||a==="incomplete"?a:"completed",actions:Hu(o.arguments),pending_safety_checks:gi(o.arguments)})}else e.push({type:"function_call",name:o.toolName,call_id:o.toolUseId,arguments:JSON.stringify(o.arguments)})}else if(s.toolResults&&s.toolResults.length>0){for(let n of s.toolResults){let o=t.get(n.toolUseId);if(o){let a=Wu(n);e.push({type:"computer_call_output",call_id:n.toolUseId,output:{type:"computer_screenshot",...a?{image_url:a}:{}},acknowledged_safety_checks:gi(o.arguments)}),(n.isError||!a)&&e.push({role:"user",content:n.content})}else e.push({type:"function_call_output",call_id:n.toolUseId,output:qu(n)})}s.content.length>0&&e.push({role:"user",content:Ai(s.content)})}else s.role==="assistant"?e.push({role:"assistant",content:typeof s.content=="string"?s.content:Hr(s.content)}):e.push({role:s.role,content:Ai(s.content)})}return e}function to(r){return/context_length_exceeded/i.test(r)||/maximum\scontext\slength/i.test(r)||/prompts?\s+too\s+long/i.test(r)}var wi=class{protocol="openai-compat";client;model;systemPrompt;maxOutputTokens;thinkingLevel;config;constructor(e,t){let s=an(e);if(!s)throw new Is("OpenAI API key not found. Set OPENAI_API_KEY in ~/.swifty/config.yaml, or via OPENAI_API_KEY env variable.");this.client=new R({apiKey:s,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=on(e),this.config={...e},this.thinkingLevel=tn(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}setThinkingLevel(e){return this.thinkingLevel=nn(this.config,e),this.thinkingLevel}getThinkingLevel(){return this.thinkingLevel}getSupportedThinkingLevels(){return sn(this.config)}async*stream(e,t,s){let n=[{role:"system",content:this.systemPrompt},...Vu(cn(e.getMessages()))],o=t.map(Uu),a=rn(this.getThinkingLevel(),this.config),l={model:this.model,messages:n,stream:!0,stream_options:{include_usage:!0},max_tokens:this.maxOutputTokens,...o.length>0?{tools:o}:{},...a!==null?{reasoning_effort:a}:{}},f=0,p=0,h=0,_=0;try{let m=await this.client.chat.completions.create(l,{...s?{signal:s}:{}}),w=new Map,P=null,b="";for await(let $ of m){if($.usage&&(p=$.usage.completion_tokens??0,h=$.usage.prompt_tokens_details?.cached_tokens??0,f=Math.max(0,($.usage.prompt_tokens??0)-h)),$.choices.length===0)continue;let A=$.choices[0].delta;A.content&&(yield{type:"text_delta",text:A.content});let E=oe(ws(A),"reasoning_content");if(E&&(b+=E,yield{type:"thinking_delta",text:E}),A.tool_calls)for(let y of A.tool_calls){w.has(y.index)||(w.set(y.index,{id:y.id??"",name:y.function?.name??"",args:""}),y.id&&(yield{type:"tool_call_start",toolName:y.function?.name??"",toolId:y.id??""}));let C=w.get(y.index);C&&(y.id&&(C.id=y.id),y.function?.name&&(C.name=y.function.name),y.function?.arguments&&(C.args+=y.function.arguments,yield{type:"tool_call_delta",text:y.function.arguments}))}if($.choices[0].finish_reason){P=$.choices[0].finish_reason,b&&(yield{type:"thinking_complete",thinking:b,signature:""},b="");for(let y of w.values()){let C={},k=y.args;if(k){try{let L=JSON.parse(k);C=ue(L)?ws(L):{}}catch(L){en.error({err:L},"llm operation failed"),C={}}yield{type:"tool_call_complete",toolName:y.name,toolId:y.id,arguments:C}}}}}if(P===null)throw new Ps("Chat Completions stream ended before a finish reason");let I;P==="length"?I="max_tokens":P==="tool_calls"||w.size>0?I="tool_use":I="end_turn",yield{type:"stream_end",stopReason:I,usage:{inputTokens:f,outputTokens:p,cacheReadInputTokens:h,cacheCreationInputTokens:_}}}catch(m){throw en.error({err:m},"llm operation failed"),Ii(m)}}};function Ii(r){if(r instanceof Rt)return r;if(r instanceof R.APIError){if(r.status===413||r.status===400&&to(r.message))return new xs(`Context Too Long: ${r.message}`);if(r.status===401)return new Is(`Invalid API key: ${r.message}`);if(r.status===429){let e=r.headers;return new so("Rate limit error, please wait.",e instanceof Headers?e.get("retry-after")??void 0:void 0)}return new Rt(`OpenAI API error (${un(r.status)}): ${r.message}`)}return new Ps(`Network error: ${r instanceof Error?r.message:un(r)}`)}function Vu(r){let e=[];for(let t of r){let s=t.thinkingBlocks?.map(o=>o.thinking).join("")??"",n=typeof t.content=="string"?t.content:Hr(t.content);if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:n||null,...s?{reasoning_content:s}:{},tool_calls:t.toolUses.map(o=>({id:o.toolUseId,type:"function",function:{name:o.toolName,arguments:JSON.stringify(o.arguments)}}))});else if(t.toolResults&&t.toolResults.length>0){let o=[];for(let a of t.toolResults)e.push({role:"tool",tool_call_id:a.toolUseId,content:a.content}),o.push(...Ju(a));if(t.content.length>0){let a=bi(t.content);o.push(...typeof a=="string"?[{type:"text",text:a}]:a)}o.length>0&&e.push({role:"user",content:o})}else t.role==="assistant"?e.push({role:"assistant",content:n,...s?{reasoning_content:s}:{}}):t.role==="system"?e.push({role:"system",content:typeof t.content=="string"?t.content:Hr(t.content)}):e.push({role:"user",content:bi(t.content)})}return e}export{yi as OpenAIClient,wi as OpenAICompatClient,Vu as buildChatCompletionMessages,Xu as buildOpenAIInput};
|