@swifty.js/swifty 0.0.2-alpha → 0.0.3-alpha
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 +0 -119
- package/dist/agent-5YZWK2BD.js +4 -0
- package/dist/anthropic-PWUGDLNY.js +4 -0
- package/dist/checker-FDJ2Q62T.js +4 -0
- package/dist/chunk-35WOW2VS.js +234 -0
- package/dist/chunk-4KVSJNS6.js +90 -0
- package/dist/chunk-7MHXMDYC.js +35 -0
- package/dist/chunk-FZPTNGTU.js +4 -0
- package/dist/chunk-IE47RFDE.js +342 -0
- package/dist/chunk-S2DPVNBA.js +4 -0
- package/dist/chunk-UAHM3AAK.js +128 -0
- package/dist/{chunk-GW6RG76F.js → chunk-UBV5T4TV.js} +1 -1
- package/dist/chunk-XOFTPYYD.js +4 -0
- package/dist/glob_addon.node +0 -0
- package/dist/main.js +241 -242
- package/dist/{openai-BUFKIEZO.js → openai-S5NEHZTE.js} +11 -11
- package/dist/{server-4FIOX5PK.js → server-BK5ZG2JS.js} +22 -21
- package/dist/tool-filter-ERUPKZYV.js +4 -0
- package/package.json +4 -4
- package/dist/anthropic-RNEEF6RX.js +0 -4
- package/dist/chunk-SLGPWJQF.js +0 -121
- package/dist/chunk-YUOKPBUW.js +0 -526
- package/dist/tool-filter-6ETY4ZEY.js +0 -4
- /package/dist/{release-JP26O6LN.js → release-OQD3IZ5W.js} +0 -0
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { createRequire as __swiftyCreateRequire } from "node:module";
|
|
3
3
|
const require = __swiftyCreateRequire(import.meta.url);
|
|
4
|
-
import{$ as vn,N as Or,O as js,P as rs,Q as Ls,V as Cn,X as kn,Y as ss,Z as $n,_ as En,ca as Ms,da as Ks,e as Sn}from"./chunk-SLGPWJQF.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function c(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var Ue=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Ue=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Tr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Nr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var g=class extends Error{},T=class s extends g{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),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,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Ie({message:r,cause:Nr(t)});let o=t?.error;return e===400?new _t(e,o,r,n):e===401?new gt(e,o,r,n):e===403?new yt(e,o,r,n):e===404?new At(e,o,r,n):e===409?new bt(e,o,r,n):e===422?new wt(e,o,r,n):e===429?new It(e,o,r,n):e>=500?new Pt(e,o,r,n):new s(e,o,r,n)}},K=class extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Ie=class extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Pe=class extends Ie{constructor({message:e}={}){super({message:e??"Request timed out."})}},_t=class extends T{},gt=class extends T{},yt=class extends T{},At=class extends T{},bt=class extends T{},wt=class extends T{},It=class extends T{},Pt=class extends T{},xt=class extends g{constructor(){super("Could not parse response content as the length limit was reached")}},Rt=class extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ae=class extends Error{constructor(e){super(e)}},Be=class extends T{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let u=t;o=u.error;let l=u.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,r),this.error_code=o}},jr=class extends g{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var Yo=/^[a-z][a-z0-9+.-]*:/i,On=s=>Yo.test(s),X=s=>(X=Array.isArray,X(s)),Fs=X;function ns(s){return typeof s!="object"?{}:s??{}}function Us(s){if(!s)return!0;for(let e in s)return!1;return!0}function Tn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Lr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var Nn=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${s} must be an integer`);if(e<0)throw new g(`${s} must be a positive integer`);return e};var jn=s=>{try{return JSON.parse(s)}catch{return}};var ue=s=>new Promise(e=>setTimeout(e,s));var xe="6.46.0";var Fn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Qo(){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 Zo=()=>{let s=Qo();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"X-Stainless-OS":Mn(Deno.build.os),"X-Stainless-Arch":Ln(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":xe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"X-Stainless-OS":Mn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ln(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ei();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"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":xe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ei(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,u=r[3]||0;return{browser:e,version:`${n}.${o}.${u}`}}}return null}var Ln=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Mn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Kn,Un=()=>Kn??(Kn=Zo());function os(){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 Bs(...s){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(...s)}function is(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Bs({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function Ds(s){if(s[Symbol.asyncIterator])return s;let e=s.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 zs(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var Dn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var qs="RFC3986",Ws=s=>String(s),Hs={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:Ws},zn="RFC1738";var as=(s,e)=>(as=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),as(s,e)),ce=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Js=1024,qn=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),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 u="";for(let l=0;l<o.length;l+=Js){let m=o.length>=Js?o.slice(l,l+Js):o,p=[];for(let w=0;w<m.length;++w){let d=m.charCodeAt(w);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===zn&&(d===40||d===41)){p[p.length]=m.charAt(w);continue}if(d<128){p[p.length]=ce[d];continue}if(d<2048){p[p.length]=ce[192|d>>6]+ce[128|d&63];continue}if(d<55296||d>=57344){p[p.length]=ce[224|d>>12]+ce[128|d>>6&63]+ce[128|d&63];continue}w+=1,d=65536+((d&1023)<<10|m.charCodeAt(w)&1023),p[p.length]=ce[240|d>>18]+ce[128|d>>12&63]+ce[128|d>>6&63]+ce[128|d&63]}u+=p.join("")}return u};function Wn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Xs(s,e){if(X(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Jn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Xn=function(s,e){Array.prototype.push.apply(s,X(e)?e:[e])},Hn,B={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:qn,encodeValuesOnly:!1,format:qs,formatter:Ws,indices:!1,serializeDate(s){return(Hn??(Hn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function ri(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var Gs={};function Gn(s,e,t,r,n,o,u,l,m,p,w,d,f,b,y,A,I,k){let _=s,P=k,R=0,O=!1;for(;(P=P.get(Gs))!==void 0&&!O;){let M=P.get(s);if(R+=1,typeof M<"u"){if(M===R)throw new RangeError("Cyclic object value");O=!0}typeof P.get(Gs)>"u"&&(R=0)}if(typeof p=="function"?_=p(e,_):_ instanceof Date?_=f?.(_):t==="comma"&&X(_)&&(_=Xs(_,function(M){return M instanceof Date?f?.(M):M})),_===null){if(o)return m&&!A?m(e,B.encoder,I,"key",b):e;_=""}if(ri(_)||Wn(_)){if(m){let M=A?e:m(e,B.encoder,I,"key",b);return[y?.(M)+"="+y?.(m(_,B.encoder,I,"value",b))]}return[y?.(e)+"="+y?.(String(_))]}let v=[];if(typeof _>"u")return v;let N;if(t==="comma"&&X(_))A&&m&&(_=Xs(_,m)),N=[{value:_.length>0?_.join(",")||null:void 0}];else if(X(p))N=p;else{let M=Object.keys(_);N=w?M.sort(w):M}let j=l?String(e).replace(/\./g,"%2E"):String(e),J=r&&X(_)&&_.length===1?j+"[]":j;if(n&&X(_)&&_.length===0)return J+"[]";for(let M=0;M<N.length;++M){let U=N[M],xn=typeof U=="object"&&typeof U.value<"u"?U.value:_[U];if(u&&xn===null)continue;let Ns=d&&l?U.replace(/\./g,"%2E"):U,Go=X(_)?typeof t=="function"?t(J,Ns):J:J+(d?"."+Ns:"["+Ns+"]");k.set(s,R);let Rn=new WeakMap;Rn.set(Gs,k),Xn(v,Gn(xn,Go,t,r,n,o,u,l,t==="comma"&&A&&X(_)?null:m,p,w,d,f,b,y,A,I,Rn))}return v}function si(s=B){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||B.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=qs;if(typeof s.format<"u"){if(!as(Hs,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Hs[t],n=B.filter;(typeof s.filter=="function"||X(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Jn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=B.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let u=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:B.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:B.addQueryPrefix,allowDots:u,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:B.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:B.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?B.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:B.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:B.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:B.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:B.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:B.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:B.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:B.strictNullHandling}}function Vn(s,e={}){let t=s,r=si(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):X(r.filter)&&(o=r.filter,n=o);let u=[];if(typeof t!="object"||t===null)return"";let l=Jn[r.arrayFormat],m=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let f=0;f<n.length;++f){let b=n[f];r.skipNulls&&t[b]===null||Xn(u,Gn(t[b],b,l,m,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,p))}let w=u.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),w.length>0?d+w:""}function Yn(s){return Vn(s,{arrayFormat:"brackets"})}function eo(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var Qn;function St(s){let e;return(Qn??(e=new globalThis.TextEncoder,Qn=e.encode.bind(e)))(s)}var Zn;function Vs(s){let e;return(Zn??(e=new globalThis.TextDecoder,Zn=e.decode.bind(e)))(s)}var Q,Z,De=class{constructor(){Q.set(this,void 0),Z.set(this,void 0),x(this,Q,new Uint8Array,"f"),x(this,Z,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?St(e):e;x(this,Q,eo([c(this,Q,"f"),t]),"f");let r=[],n;for(;(n=oi(c(this,Q,"f"),c(this,Z,"f")))!=null;){if(n.carriage&&c(this,Z,"f")==null){x(this,Z,n.index,"f");continue}if(c(this,Z,"f")!=null&&(n.index!==c(this,Z,"f")+1||n.carriage)){r.push(Vs(c(this,Q,"f").subarray(0,c(this,Z,"f")-1))),x(this,Q,c(this,Q,"f").subarray(c(this,Z,"f")),"f"),x(this,Z,null,"f");continue}let o=c(this,Z,"f")!==null?n.preceding-1:n.preceding,u=Vs(c(this,Q,"f").subarray(0,o));r.push(u),x(this,Q,c(this,Q,"f").subarray(n.index),"f"),x(this,Z,null,"f")}return r}flush(){return c(this,Q,"f").length?this.decode(`
|
|
4
|
+
import{h as Ks,i as Us}from"./chunk-XOFTPYYD.js";import{b as Fs,c as En,d as ss,e as On,f as vn,g as Tn}from"./chunk-FZPTNGTU.js";import"./chunk-7MHXMDYC.js";import{J as vr,K as Ls,L as rs,M as Ms,R as $n,e as kn}from"./chunk-4KVSJNS6.js";import"./chunk-MQ5XOYLD.js";import"./chunk-X3UA5OZL.js";function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function c(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var Ue=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return Ue=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Tr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var Nr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var g=class extends Error{},T=class s extends g{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),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,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new we({message:r,cause:Nr(t)});let o=t?.error;return e===400?new _t(e,o,r,n):e===401?new gt(e,o,r,n):e===403?new yt(e,o,r,n):e===404?new At(e,o,r,n):e===409?new bt(e,o,r,n):e===422?new It(e,o,r,n):e===429?new wt(e,o,r,n):e>=500?new Pt(e,o,r,n):new s(e,o,r,n)}},F=class extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},we=class extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Pe=class extends we{constructor({message:e}={}){super({message:e??"Request timed out."})}},_t=class extends T{},gt=class extends T{},yt=class extends T{},At=class extends T{},bt=class extends T{},It=class extends T{},wt=class extends T{},Pt=class extends T{},xt=class extends g{constructor(){super("Could not parse response content as the length limit was reached")}},Rt=class extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},ae=class extends Error{constructor(e){super(e)}},Be=class extends T{constructor(e,t,r){let n="OAuth2 authentication error",o;if(t&&typeof t=="object"){let u=t;o=u.error;let l=u.error_description;l&&typeof l=="string"?n=l:o&&(n=o)}super(e,t,n,r),this.error_code=o}},jr=class extends g{constructor(e,t,r){super(e),this.provider=t,this.cause=r}};var Zo=/^[a-z][a-z0-9+.-]*:/i,Nn=s=>Zo.test(s),X=s=>(X=Array.isArray,X(s)),Bs=X;function ns(s){return typeof s!="object"?{}:s??{}}function Ds(s){if(!s)return!0;for(let e in s)return!1;return!0}function jn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function Lr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var Ln=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${s} must be an integer`);if(e<0)throw new g(`${s} must be a positive integer`);return e};var Mn=s=>{try{return JSON.parse(s)}catch{return}};var ue=s=>new Promise(e=>setTimeout(e,s));var xe="6.46.0";var Bn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function ei(){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 ti=()=>{let s=ei();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"X-Stainless-OS":Kn(Deno.build.os),"X-Stainless-Arch":Fn(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":xe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"X-Stainless-OS":Kn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Fn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=ri();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xe,"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":xe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ri(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,u=r[3]||0;return{browser:e,version:`${n}.${o}.${u}`}}}return null}var Fn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Kn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Un,Dn=()=>Un??(Un=ti());function os(){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 zs(...s){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(...s)}function is(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return zs({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function qs(s){if(s[Symbol.asyncIterator])return s;let e=s.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 Ws(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var qn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Hs="RFC3986",Js=s=>String(s),Xs={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:Js},Wn="RFC1738";var as=(s,e)=>(as=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),as(s,e)),ce=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Gs=1024,Hn=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),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 u="";for(let l=0;l<o.length;l+=Gs){let m=o.length>=Gs?o.slice(l,l+Gs):o,p=[];for(let I=0;I<m.length;++I){let h=m.charCodeAt(I);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||n===Wn&&(h===40||h===41)){p[p.length]=m.charAt(I);continue}if(h<128){p[p.length]=ce[h];continue}if(h<2048){p[p.length]=ce[192|h>>6]+ce[128|h&63];continue}if(h<55296||h>=57344){p[p.length]=ce[224|h>>12]+ce[128|h>>6&63]+ce[128|h&63];continue}I+=1,h=65536+((h&1023)<<10|m.charCodeAt(I)&1023),p[p.length]=ce[240|h>>18]+ce[128|h>>12&63]+ce[128|h>>6&63]+ce[128|h&63]}u+=p.join("")}return u};function Jn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Vs(s,e){if(X(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Gn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Vn=function(s,e){Array.prototype.push.apply(s,X(e)?e:[e])},Xn,B={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Hn,encodeValuesOnly:!1,format:Hs,formatter:Js,indices:!1,serializeDate(s){return(Xn??(Xn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function ni(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var Ys={};function Yn(s,e,t,r,n,o,u,l,m,p,I,h,f,b,y,A,w,k){let _=s,P=k,R=0,v=!1;for(;(P=P.get(Ys))!==void 0&&!v;){let M=P.get(s);if(R+=1,typeof M<"u"){if(M===R)throw new RangeError("Cyclic object value");v=!0}typeof P.get(Ys)>"u"&&(R=0)}if(typeof p=="function"?_=p(e,_):_ instanceof Date?_=f?.(_):t==="comma"&&X(_)&&(_=Vs(_,function(M){return M instanceof Date?f?.(M):M})),_===null){if(o)return m&&!A?m(e,B.encoder,w,"key",b):e;_=""}if(ni(_)||Jn(_)){if(m){let M=A?e:m(e,B.encoder,w,"key",b);return[y?.(M)+"="+y?.(m(_,B.encoder,w,"value",b))]}return[y?.(e)+"="+y?.(String(_))]}let O=[];if(typeof _>"u")return O;let N;if(t==="comma"&&X(_))A&&m&&(_=Vs(_,m)),N=[{value:_.length>0?_.join(",")||null:void 0}];else if(X(p))N=p;else{let M=Object.keys(_);N=I?M.sort(I):M}let j=l?String(e).replace(/\./g,"%2E"):String(e),J=r&&X(_)&&_.length===1?j+"[]":j;if(n&&X(_)&&_.length===0)return J+"[]";for(let M=0;M<N.length;++M){let U=N[M],Cn=typeof U=="object"&&typeof U.value<"u"?U.value:_[U];if(u&&Cn===null)continue;let js=h&&l?U.replace(/\./g,"%2E"):U,Yo=X(_)?typeof t=="function"?t(J,js):J:J+(h?"."+js:"["+js+"]");k.set(s,R);let Sn=new WeakMap;Sn.set(Ys,k),Vn(O,Yn(Cn,Yo,t,r,n,o,u,l,t==="comma"&&A&&X(_)?null:m,p,I,h,f,b,y,A,w,Sn))}return O}function oi(s=B){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||B.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Hs;if(typeof s.format<"u"){if(!as(Xs,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Xs[t],n=B.filter;(typeof s.filter=="function"||X(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Gn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=B.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let u=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:B.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:B.addQueryPrefix,allowDots:u,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:B.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:B.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?B.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:B.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:B.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:B.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:B.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:B.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:B.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:B.strictNullHandling}}function Qn(s,e={}){let t=s,r=oi(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):X(r.filter)&&(o=r.filter,n=o);let u=[];if(typeof t!="object"||t===null)return"";let l=Gn[r.arrayFormat],m=l==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let f=0;f<n.length;++f){let b=n[f];r.skipNulls&&t[b]===null||Vn(u,Yn(t[b],b,l,m,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,p))}let I=u.join(r.delimiter),h=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),I.length>0?h+I:""}function Zn(s){return Qn(s,{arrayFormat:"brackets"})}function ro(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var eo;function Ct(s){let e;return(eo??(e=new globalThis.TextEncoder,eo=e.encode.bind(e)))(s)}var to;function Qs(s){let e;return(to??(e=new globalThis.TextDecoder,to=e.decode.bind(e)))(s)}var Q,Z,De=class{constructor(){Q.set(this,void 0),Z.set(this,void 0),x(this,Q,new Uint8Array,"f"),x(this,Z,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Ct(e):e;x(this,Q,ro([c(this,Q,"f"),t]),"f");let r=[],n;for(;(n=ai(c(this,Q,"f"),c(this,Z,"f")))!=null;){if(n.carriage&&c(this,Z,"f")==null){x(this,Z,n.index,"f");continue}if(c(this,Z,"f")!=null&&(n.index!==c(this,Z,"f")+1||n.carriage)){r.push(Qs(c(this,Q,"f").subarray(0,c(this,Z,"f")-1))),x(this,Q,c(this,Q,"f").subarray(c(this,Z,"f")),"f"),x(this,Z,null,"f");continue}let o=c(this,Z,"f")!==null?n.preceding-1:n.preceding,u=Qs(c(this,Q,"f").subarray(0,o));r.push(u),x(this,Q,c(this,Q,"f").subarray(n.index),"f"),x(this,Z,null,"f")}return r}flush(){return c(this,Q,"f").length?this.decode(`
|
|
5
5
|
`):[]}};Q=new WeakMap,Z=new WeakMap;De.NEWLINE_CHARS=new Set([`
|
|
6
|
-
`,"\r"]);De.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function
|
|
7
|
-
`);r.enqueue(u)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*
|
|
8
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=ci(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function ci(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function ls(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,u=await(async()=>{if(e.options.stream)return L(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData):le.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let m=t.headers.get("content-type")?.split(";")[0]?.trim();if(m?.includes("application/json")||m?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let f=await t.json();return Zs(f,t)}return await t.text()})();return L(s).debug(`[${r}] response parsed`,me({retryOfRequestLogID:n,url:t.url,status:t.status,body:u,durationMs:Date.now()-o})),u}function Zs(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Fr,ze=class s extends Promise{constructor(e,t,r=ls){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Fr.set(this,void 0),x(this,Fr,e,"f")}_thenUnwrap(e){return new s(c(this,Fr,"f"),this.responsePromise,async(t,r)=>Zs(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,Fr,"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)}};Fr=new WeakMap;var ps,Ct=class{constructor(e,t,r,n){ps.set(this,void 0),x(this,ps,e,"f"),this.options=n,this.response=t,this.body=r}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,ps,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ps=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Ur=class extends ze{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await ls(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},G=class extends Ct{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},C=class extends Ct{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.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:{...ns(this.options.query),after:t}}:null}},E=class extends Ct{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.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:{...ns(this.options.query),after:e}}:null}},F=class extends Ct{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.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:{...ns(this.options.query),after:e}}:null}};var pi={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},di="urn:ietf:params:oauth:grant-type:token-exchange",ds=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??os()}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:di,subject_token:e,subject_token_type:pi[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 r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let m=await r.text(),p;try{p=JSON.parse(m)}catch{}throw r.status===400||r.status===401||r.status===403?new Be(r.status,p,r.headers):T.generate(r.status,p,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.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,u=n.expires_in??3600,l=Date.now()+u*1e3;return this.cachedToken={token:o,expiresAt:l},o}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var rn=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.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(s,e,t){return rn(),new File(s,e??"unknown_file",t)}function Br(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var hs=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",Re=async(s,e)=>en(s.body)?{...s,body:await no(s.body,e)}:s,V=async(s,e)=>({...s,body:await no(s.body,e)}),so=new WeakMap;function hi(s){let e=typeof s=="function"?s:s.fetch,t=so.get(e);if(t)return t;let r=(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 so.set(e,r),r}var no=async(s,e)=>{if(!await hi(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(s||{}).map(([r,n])=>tn(t,r,n))),t},oo=s=>s instanceof Blob&&"name"in s,mi=s=>typeof s=="object"&&s!==null&&(s instanceof Response||hs(s)||oo(s)),en=s=>{if(mi(s))return!0;if(Array.isArray(s))return s.some(en);if(s&&typeof s=="object"){for(let e in s)if(en(s[e]))return!0}return!1},tn=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,kt([await t.blob()],Br(t)));else if(hs(t))s.append(e,kt([await new Response(is(t)).blob()],Br(t)));else if(oo(t))s.append(e,t,Br(t));else if(Array.isArray(t))await Promise.all(t.map(r=>tn(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>tn(s,`${e}[${r}]`,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 io=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",fi=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&io(s),_i=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function ms(s,e,t){if(rn(),s=await s,fi(s))return s instanceof File?s:kt([await s.arrayBuffer()],s.name);if(_i(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),kt(await sn(n),e,t)}let r=await sn(s);if(e||(e=Br(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return kt(r,e,t)}async function sn(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(io(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(hs(s))for await(let t of s)e.push(...await sn(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${gi(s)}`)}return e}function gi(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var a=class{constructor(e){this._client=e}};function uo(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var ao=Object.freeze(Object.create(null)),Ai=(s=uo)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],u=t.reduce((w,d,f)=>{/[?#]/.test(d)&&(n=!0);let b=r[f],y=(n?encodeURIComponent:s)(""+b);return f!==r.length&&(b==null||typeof b=="object"&&b.toString===Object.getPrototypeOf(Object.getPrototypeOf(b.hasOwnProperty??ao)??ao)?.toString)&&(y=b+"",o.push({start:w.length+d.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(b).slice(8,-1)} is not a valid path parameter`})),w+d+(f===r.length?"":y)},""),l=u.split(/[?#]/,1)[0],m=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=m.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((w,d)=>w.start-d.start),o.length>0){let w=0,d=o.reduce((f,b)=>{let y=" ".repeat(b.start-w),A="^".repeat(b.length);return w=b.start+b.length,f+y+A},"");throw new g(`Path parameters result in path with invalid segments:
|
|
6
|
+
`,"\r"]);De.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ai(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function so(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var cs={off:0,error:200,warn:300,info:400,debug:500},Zs=(s,e,t)=>{if(s){if(jn(cs,s))return s;L(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(cs))}`)}};function Mr(){}function us(s,e,t){return!e||cs[s]>cs[t]?Mr:e[s].bind(e)}var ui={error:Mr,warn:Mr,info:Mr,debug:Mr},no=new WeakMap;function L(s){let e=s.logger,t=s.logLevel??"off";if(!e)return ui;let r=no.get(e);if(r&&r[0]===t)return r[1];let n={error:us("error",e,t),warn:us("warn",e,t),info:us("info",e,t),debug:us("debug",e,t)};return no.set(e,[t,n]),n}var me=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.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 s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var Fr,le=class s{constructor(e,t,r){this.iterator=e,Fr.set(this,void 0),this.controller=t,x(this,Fr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,u=r?L(r):console;async function*l(){if(o)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let m=!1;try{for await(let p of ci(e,t))if(!m){if(p.data.startsWith("[DONE]")){m=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let I;try{I=JSON.parse(p.data)}catch(h){throw u.error("Could not parse message into JSON:",p.data),u.error("From chunk:",p.raw),h}if(I&&I.error)throw new T(void 0,I.error,void 0,e.headers);yield n?{event:p.event,data:I}:I}else{let I;try{I=JSON.parse(p.data)}catch(h){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),h}if(p.event=="error")throw new T(void 0,I.error,I.message,void 0);yield{event:p.event,data:I}}}m=!0}catch(p){if(Tr(p))return;throw p}finally{m||t.abort()}}return new s(l,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let l=new De,m=qs(e);for await(let p of m)for(let I of l.decode(p))yield I;for(let p of l.flush())yield p}async function*u(){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 m of o())l||m&&(yield JSON.parse(m));l=!0}catch(m){if(Tr(m))return;throw m}finally{l||t.abort()}}return new s(u,t,r)}[(Fr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let u=r.next();e.push(u),t.push(u)}return o.shift()}});return[new s(()=>n(e),this.controller,c(this,Fr,"f")),new s(()=>n(t),this.controller,c(this,Fr,"f"))]}toReadableStream(){let e=this,t;return zs({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let u=Ct(JSON.stringify(n)+`
|
|
7
|
+
`);r.enqueue(u)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*ci(s,e){if(!s.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 en,r=new De,n=qs(s.body);for await(let o of li(n))for(let u of r.decode(o)){let l=t.decode(u);l&&(yield l)}for(let o of r.flush()){let u=t.decode(o);u&&(yield u)}}async function*li(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Ct(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=so(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var en=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,r,n]=pi(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function pi(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function ls(s,e){let{response:t,requestLogID:r,retryOfRequestLogID:n,startTime:o}=e,u=await(async()=>{if(e.options.stream)return L(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData):le.fromSSEResponse(t,e.controller,s,e.options.__synthesizeEventData);if(t.status===204)return null;if(e.options.__binaryResponse)return t;let m=t.headers.get("content-type")?.split(";")[0]?.trim();if(m?.includes("application/json")||m?.endsWith("+json")){if(t.headers.get("content-length")==="0")return;let f=await t.json();return tn(f,t)}return await t.text()})();return L(s).debug(`[${r}] response parsed`,me({retryOfRequestLogID:n,url:t.url,status:t.status,body:u,durationMs:Date.now()-o})),u}function tn(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Kr,ze=class s extends Promise{constructor(e,t,r=ls){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=r,Kr.set(this,void 0),x(this,Kr,e,"f")}_thenUnwrap(e){return new s(c(this,Kr,"f"),this.responsePromise,async(t,r)=>tn(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(c(this,Kr,"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)}};Kr=new WeakMap;var ps,St=class{constructor(e,t,r,n){ps.set(this,void 0),x(this,ps,e,"f"),this.options=n,this.response=t,this.body=r}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,ps,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ps=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Ur=class extends ze{constructor(e,t,r){super(e,t,async(n,o)=>new r(n,o.response,await ls(n,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},G=class extends St{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},S=class extends St{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.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:{...ns(this.options.query),after:t}}:null}},E=class extends St{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.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:{...ns(this.options.query),after:e}}:null}},K=class extends St{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.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:{...ns(this.options.query),after:e}}:null}};var di={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},mi="urn:ietf:params:oauth:grant-type:token-exchange",hs=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=t??os()}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:mi,subject_token:e,subject_token_type:di[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 r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let m=await r.text(),p;try{p=JSON.parse(m)}catch{}throw r.status===400||r.status===401||r.status===403?new Be(r.status,p,r.headers):T.generate(r.status,p,`Token exchange failed with status ${r.status}`,r.headers)}let n=await r.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,u=n.expires_in??3600,l=Date.now()+u*1e3;return this.cachedToken={token:o,expiresAt:l},o}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}};var nn=()=>{if(typeof File>"u"){let{process:s}=globalThis,e=typeof s?.versions?.node=="string"&&parseInt(s.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(s,e,t){return nn(),new File(s,e??"unknown_file",t)}function Br(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}var ds=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",Re=async(s,e)=>rn(s.body)?{...s,body:await io(s.body,e)}:s,V=async(s,e)=>({...s,body:await io(s.body,e)}),oo=new WeakMap;function fi(s){let e=typeof s=="function"?s:s.fetch,t=oo.get(e);if(t)return t;let r=(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,r),r}var io=async(s,e)=>{if(!await fi(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(s||{}).map(([r,n])=>sn(t,r,n))),t},ao=s=>s instanceof Blob&&"name"in s,_i=s=>typeof s=="object"&&s!==null&&(s instanceof Response||ds(s)||ao(s)),rn=s=>{if(_i(s))return!0;if(Array.isArray(s))return s.some(rn);if(s&&typeof s=="object"){for(let e in s)if(rn(s[e]))return!0}return!1},sn=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,kt([await t.blob()],Br(t)));else if(ds(t))s.append(e,kt([await new Response(is(t)).blob()],Br(t)));else if(ao(t))s.append(e,t,Br(t));else if(Array.isArray(t))await Promise.all(t.map(r=>sn(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>sn(s,`${e}[${r}]`,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 uo=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",gi=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&uo(s),yi=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function ms(s,e,t){if(nn(),s=await s,gi(s))return s instanceof File?s:kt([await s.arrayBuffer()],s.name);if(yi(s)){let n=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),kt(await on(n),e,t)}let r=await on(s);if(e||(e=Br(s)),!t?.type){let n=r.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof n=="string"&&(t={...t,type:n})}return kt(r,e,t)}async function on(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(uo(s))e.push(s instanceof Blob?s:await s.arrayBuffer());else if(ds(s))for await(let t of s)e.push(...await on(t));else{let t=s?.constructor?.name;throw new Error(`Unexpected data type: ${typeof s}${t?`; constructor: ${t}`:""}${Ai(s)}`)}return e}function Ai(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}var a=class{constructor(e){this._client=e}};function lo(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var co=Object.freeze(Object.create(null)),Ii=(s=lo)=>function(t,...r){if(t.length===1)return t[0];let n=!1,o=[],u=t.reduce((I,h,f)=>{/[?#]/.test(h)&&(n=!0);let b=r[f],y=(n?encodeURIComponent:s)(""+b);return f!==r.length&&(b==null||typeof b=="object"&&b.toString===Object.getPrototypeOf(Object.getPrototypeOf(b.hasOwnProperty??co)??co)?.toString)&&(y=b+"",o.push({start:I.length+h.length,length:y.length,error:`Value of type ${Object.prototype.toString.call(b).slice(8,-1)} is not a valid path parameter`})),I+h+(f===r.length?"":y)},""),l=u.split(/[?#]/,1)[0],m=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,p;for(;(p=m.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((I,h)=>I.start-h.start),o.length>0){let I=0,h=o.reduce((f,b)=>{let y=" ".repeat(b.start-I),A="^".repeat(b.length);return I=b.start+b.length,f+y+A},"");throw new g(`Path parameters result in path with invalid segments:
|
|
9
9
|
${o.map(f=>f.error).join(`
|
|
10
10
|
`)}
|
|
11
11
|
${u}
|
|
12
|
-
${d}`)}return u},i=Ai(uo);var qe=class extends a{list(e,t={},r){return this._client.getAPIList(i`/chat/completions/${e}/messages`,C,{query:t,...r,__security:{bearerAuth:!0}})}};function Dr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function zr(s){return s?.$brand==="auto-parseable-response-format"}function We(s){return s?.$brand==="auto-parseable-tool"}function lo(s,e){return!e||!nn(e)?{...s,choices:s.choices.map(t=>(ho(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:qr(s,e)}function qr(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new xt;if(r.finish_reason==="content_filter")throw new Rt;return ho(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>Ii(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?wi(e,r.message.content):null}}});return{...s,choices:t}}function wi(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function Ii(s,e){let t=s.tools?.find(r=>Dr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:We(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function po(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>Dr(r)&&r.function?.name===e.function.name);return Dr(t)&&(We(t)||t?.function.strict||!1)}function nn(s){return zr(s.response_format)?!0:s.tools?.some(e=>We(e)||e.type==="function"&&e.function.strict===!0)??!1}function ho(s){for(let e of s||[])if(e.type!=="function")throw new g(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function mo(s){for(let e of s??[]){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 $t=s=>s?.role==="assistant",on=s=>s?.role==="tool";var fs,_s,gs,Wr,Hr,ys,Jr,fe,As,Xr,bs,ws,Et,fo,_o,Se=class{constructor(){fs.add(this),this.controller=new AbortController,_s.set(this,void 0),gs.set(this,()=>{}),Wr.set(this,()=>{}),Hr.set(this,void 0),ys.set(this,()=>{}),Jr.set(this,()=>{}),fe.set(this,{}),As.set(this,[]),Xr.set(this,!1),bs.set(this,!1),ws.set(this,!1),Et.set(this,!1),x(this,_s,new Promise((e,t)=>{x(this,gs,e,"f"),x(this,Wr,t,"f")}),"f"),x(this,Hr,new Promise((e,t)=>{x(this,ys,e,"f"),x(this,Jr,t,"f")}),"f"),c(this,_s,"f").catch(()=>{}),c(this,Hr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,fs,"m",_o).bind(this))},0)}_connected(){this.ended||(c(this,gs,"f").call(this),this._emit("connect"))}get ended(){return c(this,Xr,"f")}get errored(){return c(this,bs,"f")}get aborted(){return c(this,ws,"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,As,"f").push({signal:e,listener:t})}on(e,t){return(c(this,fe,"f")[e]||(c(this,fe,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,fe,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(c(this,fe,"f")[e]||(c(this,fe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{x(this,Et,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){x(this,Et,!0,"f"),await c(this,Hr,"f")}_emit(e,...t){if(c(this,Xr,"f"))return;e==="end"&&(c(this,fs,"m",fo).call(this),x(this,Xr,!0,"f"),c(this,ys,"f").call(this));let r=c(this,fe,"f")[e];if(r&&(c(this,fe,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,Et,"f")&&!r?.length&&Promise.reject(n),c(this,Wr,"f").call(this,n),c(this,Jr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,Et,"f")&&!r?.length&&Promise.reject(n),c(this,Wr,"f").call(this,n),c(this,Jr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};_s=new WeakMap,gs=new WeakMap,Wr=new WeakMap,Hr=new WeakMap,ys=new WeakMap,Jr=new WeakMap,fe=new WeakMap,As=new WeakMap,Xr=new WeakMap,bs=new WeakMap,ws=new WeakMap,Et=new WeakMap,fs=new WeakSet,fo=function(){for(let{signal:e,listener:t}of c(this,As,"f").splice(0))e.removeEventListener("abort",t)},_o=function(e){if(x(this,bs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new K),e instanceof K)return x(this,ws,!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 go(s){return typeof s.parse=="function"}var Y,an,Is,un,cn,ln,yo,Ao,Pi=10;function xi(s){for(let e of s.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${Ue()}`)}var vt=class extends Se{constructor(){super(...arguments),Y.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){xi(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),on(e)&&e.content)this._emit("functionToolCallResult",e.content);else if($t(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new g("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,Y,"m",an).call(this)}async finalMessage(){return await this.done(),c(this,Y,"m",Is).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,Y,"m",un).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,Y,"m",cn).call(this)}async totalUsage(){return await this.done(),c(this,Y,"m",ln).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",Is).call(this);t&&this._emit("finalMessage",t);let r=c(this,Y,"m",an).call(this);r&&this._emit("finalContent",r);let n=c(this,Y,"m",un).call(this);n&&this._emit("finalFunctionToolCall",n);let o=c(this,Y,"m",cn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(u=>u.usage)&&this._emit("totalUsage",c(this,Y,"m",ln).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),c(this,Y,"m",yo).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(qr(n,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r,n){let o="tool",{tool_choice:u="auto",stream:l,...m}=t,p=typeof u!="string"&&u.type==="function"&&u?.function?.name,{maxChatCompletions:w=Pi,afterCompletion:d}=n||{},f=t.tools.map(I=>{if(We(I)){if(!I.$callback)throw new g("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:I.$callback,name:I.function.name,description:I.function.description||"",parameters:I.function.parameters,parse:I.$parseRaw,strict:!0}}}return I}),b={};for(let I of f)I.type==="function"&&(b[I.function.name||I.function.function.name]=I.function);let y="tools"in t?f.map(I=>I.type==="function"?{type:"function",function:{name:I.function.name||I.function.function.name,parameters:I.function.parameters,description:I.function.description,strict:I.function.strict}}:I):void 0;for(let I of t.messages)this._addMessage(I,!1);let A=async I=>{if(I.type!=="function")return{message:void 0,functionCalled:!1};let k=I.id,{name:_,arguments:P}=I.function,R=b[_];if(!R){let N=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(b).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:k,content:N},functionCalled:!1}}if(p&&p!==_){let N=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(p)} requested. Please try again`;return{message:{role:o,tool_call_id:k,content:N},functionCalled:!1}}let O;if(go(R)){let N;try{N=await R.parse(P)}catch(j){let J=j instanceof Error?j.message:String(j);return{message:{role:o,tool_call_id:k,content:J},functionCalled:!1}}O=await R.function(N,r)}else O=await R.function(P,r);let v=c(this,Y,"m",Ao).call(this,O);return{message:{role:o,tool_call_id:k,content:v},functionCalled:!0}};for(let I=0;I<w;++I){let k=await this._createChatCompletion(e,{...m,tool_choice:u,tools:y,messages:[...this.messages]},n),_=k.choices[0]?.message;if(!_)throw new g("missing message in ChatCompletion response");if(!_.tool_calls?.length){await d?.(k,r);return}if(p||t.parallel_tool_calls===!1)for(let P of _.tool_calls){let R=await A(P);if(R.message&&this._addMessage(R.message),p&&R.functionCalled){await d?.(k,r);return}}else{let P=await Promise.allSettled(_.tool_calls.map(A));for(let R of P)if(R.status==="rejected")throw R.reason;for(let R of P)R.status==="fulfilled"&&R.value.message&&this._addMessage(R.value.message)}await d?.(k,r)}}};Y=new WeakSet,an=function(){return c(this,Y,"m",Is).call(this).content??null},Is=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if($t(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new g("stream ended without producing a ChatCompletionMessage with role=assistant")},un=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if($t(t)&&t?.tool_calls?.length)for(let r=t.tool_calls.length-1;r>=0;r--){let n=t.tool_calls[r];if(n?.type==="function")return n.function}}},cn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(on(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},ln=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},yo=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.")},Ao=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Gr=class s extends vt{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),$t(e)&&e.content&&this._emit("content",e.content)}};var z={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},pn=class extends Error{},dn=class extends Error{};function Ri(s,e=z.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return Si(s.trim(),e)}var Si=(s,e)=>{let t=s.length,r=0,n=f=>{throw new pn(`${f} at position ${r}`)},o=f=>{throw new dn(`${f} at position ${r}`)},u=()=>(d(),r>=t&&n("Unexpected end of input"),s[r]==='"'?l():s[r]==="{"?m():s[r]==="["?p():s.substring(r,r+4)==="null"||z.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||z.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||z.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||z.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||z.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||z.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):w()),l=()=>{let f=r,b=!1;for(r++;r<t&&(s[r]!=='"'||b&&s[r-1]==="\\");)b=s[r]==="\\"?!b:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(f,++r-Number(b)))}catch(y){o(String(y))}else if(z.STR&e)try{return JSON.parse(s.substring(f,r-Number(b))+'"')}catch{return JSON.parse(s.substring(f,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},m=()=>{r++,d();let f={};try{for(;s[r]!=="}";){if(d(),r>=t&&z.OBJ&e)return f;let b=l();d(),r++;try{let y=u();Object.defineProperty(f,b,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(z.OBJ&e)return f;throw y}d(),s[r]===","&&r++}}catch{if(z.OBJ&e)return f;n("Expected '}' at end of object")}return r++,f},p=()=>{r++;let f=[];try{for(;s[r]!=="]";)f.push(u()),d(),s[r]===","&&r++}catch{if(z.ARR&e)return f;n("Expected ']' at end of array")}return r++,f},w=()=>{if(r===0){s==="-"&&z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(b){if(z.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(b))}}let f=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(z.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(f,r))}catch{s.substring(f,r)==="-"&&z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(f,s.lastIndexOf("e")))}catch(y){o(String(y))}}},d=()=>{for(;r<t&&`
|
|
13
|
-
\r `.includes(s[r]);)r++};return u()},
|
|
14
|
-
${
|
|
15
|
-
${
|
|
16
|
-
${An(s)}`);return{...j,id:N||`call_${Ue()}`,type:v,function:{...U,name:M,arguments:J}}})}}:{...b,message:{...k,content:y,role:_,refusal:p.refusal??null},finish_reason:w,index:d,logprobs:f}}),created:n,model:o,object:"chat.completion",...u?{system_fingerprint:u}:{}};return lo(m,e)}function An(s){return JSON.stringify(s)}var Vr=class s extends He{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}};var ge=class extends a{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,r){return this._client.post(i`/chat/completions/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chat/completions",C,{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 mo(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>qr(r,e))}runTools(e,t){return e.stream?Vr.runTools(this._client,e,t):Gr.runTools(this._client,e,t)}stream(e,t){return He.createChatCompletion(this._client,e,t)}};ge.Messages=qe;var ke=class extends a{constructor(){super(...arguments),this.completions=new ge(this._client)}};ke.Completions=ge;var Tt=class extends a{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",C,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Nt=class extends a{list(e={},t){return this._client.getAPIList("/organization/audit_logs",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var jt=class extends a{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",E,{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 Lt=class extends a{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 Mt=class extends a{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",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Kt=class extends a{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,r){return this._client.post(i`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ft=class extends a{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,r){return this._client.post(i`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ut=class extends a{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 Bt=class extends a{create(e,t,r){return this._client.post(i`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/roles`,F,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Dt=class extends a{create(e,t,r){return this._client.post(i`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/users`,F,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var $e=class extends a{constructor(){super(...arguments),this.users=new Dt(this._client),this.roles=new Bt(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,r){return this._client.post(i`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",F,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};$e.Users=Dt;$e.Roles=Bt;var zt=class extends a{retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/api_keys`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends a{list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/certificates`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/activate`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/deactivate`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Wt=class extends a{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var Ht=class extends a{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var Jt=class extends a{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Xt=class extends a{listRateLimits(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/rate_limits`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/rate_limits/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var Gt=class extends a{create(e,t,r){return this._client.post(i`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/roles/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/projects/${e}/roles`,F,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends a{create(e,t,r){return this._client.post(i`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/service_accounts`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Yt=class extends a{create(e,t,r){return this._client.post(i`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/spend_alerts`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Qt=class extends a{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/groups/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,group_id:o}=t;return this._client.get(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/groups/${e}/roles`,F,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,group_id:o}=t;return this._client.delete(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Je=class extends a{constructor(){super(...arguments),this.roles=new Qt(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,...o}=t;return this._client.get(i`/organization/projects/${n}/groups/${e}`,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/groups`,F,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Je.Roles=Qt;var Zt=class extends a{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/users/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,user_id:o}=t;return this._client.get(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/users/${e}/roles`,F,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,user_id:o}=t;return this._client.delete(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Xe=class extends a{constructor(){super(...arguments),this.roles=new Zt(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/users/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/users`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Xe.Roles=Zt;var q=class extends a{constructor(){super(...arguments),this.users=new Xe(this._client),this.serviceAccounts=new Vt(this._client),this.apiKeys=new zt(this._client),this.rateLimits=new Xt(this._client),this.modelPermissions=new Jt(this._client),this.hostedToolPermissions=new Ht(this._client),this.groups=new Je(this._client),this.roles=new Gt(this._client),this.dataRetention=new Wt(this._client),this.spendAlerts=new Yt(this._client),this.certificates=new qt(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,r){return this._client.post(i`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(i`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};q.Users=Xe;q.ServiceAccounts=Vt;q.APIKeys=zt;q.RateLimits=Xt;q.ModelPermissions=Jt;q.HostedToolPermissions=Ht;q.Groups=Je;q.Roles=Gt;q.DataRetention=Wt;q.SpendAlerts=Yt;q.Certificates=qt;var er=class extends a{create(e,t,r){return this._client.post(i`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{user_id:n}=t;return this._client.get(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/users/${e}/roles`,F,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{user_id:n}=t;return this._client.delete(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ge=class extends a{constructor(){super(...arguments),this.roles=new er(this._client)}retrieve(e,t){return this._client.get(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Ge.Roles=er;var W=class extends a{constructor(){super(...arguments),this.auditLogs=new Nt(this._client),this.adminAPIKeys=new Tt(this._client),this.usage=new Ut(this._client),this.invites=new Mt(this._client),this.users=new Ge(this._client),this.groups=new $e(this._client),this.roles=new Kt(this._client),this.dataRetention=new Lt(this._client),this.spendAlerts=new Ft(this._client),this.certificates=new jt(this._client),this.projects=new q(this._client)}};W.AuditLogs=Nt;W.AdminAPIKeys=Tt;W.Usage=Ut;W.Invites=Mt;W.Users=Ge;W.Groups=$e;W.Roles=Kt;W.DataRetention=Lt;W.SpendAlerts=Ft;W.Certificates=jt;W.Projects=q;var Ee=class extends a{constructor(){super(...arguments),this.organization=new W(this._client)}};Ee.Organization=W;var wo=Symbol("brand.privateNullableHeaders");function*sa(s){if(!s)return;if(wo in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():Fs(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=Fs(r[1])?r[1]:[r[1]],u=!1;for(let l of o)l!==void 0&&(e&&!u&&(u=!0,yield[n,null]),yield[n,l])}}var h=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,u]of sa(r)){let l=o.toLowerCase();n.has(l)||(e.delete(o),n.add(l)),u===null?(e.delete(o),t.add(l)):(e.append(o,u),t.delete(l))}}return{[wo]:!0,values:e,nulls:t}};var tr=class extends a{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:h([{Accept:"application/octet-stream"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var rr=class extends a{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var sr=class extends a{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var pe=class extends a{constructor(){super(...arguments),this.transcriptions=new rr(this._client),this.translations=new sr(this._client),this.speech=new tr(this._client)}};pe.Transcriptions=rr;pe.Translations=sr;pe.Speech=tr;var Ve=class extends a{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",C,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}};var nr=class extends a{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/assistants/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/assistants",C,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/assistants/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var or=class extends a{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var ir=class extends a{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var ve=class extends a{constructor(){super(...arguments),this.sessions=new or(this._client),this.transcriptionSessions=new ir(this._client)}};ve.Sessions=or;ve.TranscriptionSessions=ir;var ar=class extends a{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(i`/chatkit/sessions/${e}/cancel`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}};var ur=class extends a{retrieve(e,t){return this._client.get(i`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/chatkit/threads",E,{query:e,...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/chatkit/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},r){return this._client.getAPIList(i`/chatkit/threads/${e}/items`,E,{query:t,...r,headers:h([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var Oe=class extends a{constructor(){super(...arguments),this.sessions=new ar(this._client),this.threads=new ur(this._client)}};Oe.Sessions=ar;Oe.Threads=ur;var cr=class extends a{list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(i`/responses/${e}/input_items?beta=true`,C,{query:o,...r,headers:h([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};var lr=class extends a{count(e={},t){let{betas:r,...n}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:n,...t,headers:h([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};var Te=class extends a{constructor(){super(...arguments),this.inputItems=new cr(this._client),this.inputTokens=new lr(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/responses?beta=true",{body:n,...t,headers:h([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},r){let{betas:n,...o}=t??{};return this._client.get(i`/responses/${e}?beta=true`,{query:o,...r,headers:h([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(i`/responses/${e}?beta=true`,{...r,headers:h([{Accept:"*/*",...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},r){let{betas:n}=t??{};return this._client.post(i`/responses/${e}/cancel?beta=true`,{...r,headers:h([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:r,...n}=e;return this._client.post("/responses/compact?beta=true",{body:n,...t,headers:h([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};Te.InputItems=cr;Te.InputTokens=lr;var pr=class extends a{create(e,t,r){return this._client.post(i`/threads/${e}/messages`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/messages/${e}`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/messages`,C,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(i`/threads/${n}/messages/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var dr=class extends a{retrieve(e,t,r){let{thread_id:n,run_id:o,...u}=t;return this._client.get(i`/threads/${n}/runs/${o}/steps/${e}`,{query:u,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(i`/threads/${n}/runs/${e}/steps`,C,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Io=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var ne=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()||void 0};var H,Qe,bn,de,Rs,oe,Ze,hr,Ye,ks,ee,Ss,Cs,Zr,Yr,Qr,Po,xo,Ro,So,Co,ko,$o,ye=class extends Se{constructor(){super(...arguments),H.add(this),bn.set(this,[]),de.set(this,{}),Rs.set(this,{}),oe.set(this,void 0),Ze.set(this,void 0),hr.set(this,void 0),Ye.set(this,void 0),ks.set(this,void 0),ee.set(this,void 0),Ss.set(this,void 0),Cs.set(this,void 0),Zr.set(this,void 0)}[(bn=new WeakMap,de=new WeakMap,Rs=new WeakMap,oe=new WeakMap,Ze=new WeakMap,hr=new WeakMap,Ye=new WeakMap,ks=new WeakMap,ee=new WeakMap,Ss=new WeakMap,Cs=new WeakMap,Zr=new WeakMap,H=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,u)=>t.push({resolve:o,reject:u})).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 Qe;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=le.fromReadableStream(e,this.controller);for await(let n of r)c(this,H,"m",Yr).call(this,n);if(r.controller.signal?.aborted)throw new K;return this._addRun(c(this,H,"m",Qr).call(this))}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new Qe;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},u=await e.submitToolOutputs(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of u)c(this,H,"m",Yr).call(this,l);if(u.controller.signal?.aborted)throw new K;return this._addRun(c(this,H,"m",Qr).call(this))}static createThreadAssistantStream(e,t,r){let n=new Qe;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new Qe;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,Ss,"f")}currentRun(){return c(this,Cs,"f")}currentMessageSnapshot(){return c(this,oe,"f")}currentRunStepSnapshot(){return c(this,Zr,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,de,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,Rs,"f"))}async finalRun(){if(await this.done(),!c(this,Ze,"f"))throw Error("Final run was not received.");return c(this,Ze,"f")}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let u of o)c(this,H,"m",Yr).call(this,u);if(o.controller.signal?.aborted)throw new K;return this._addRun(c(this,H,"m",Qr).call(this))}async _createAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},u=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of u)c(this,H,"m",Yr).call(this,l);if(u.controller.signal?.aborted)throw new K;return this._addRun(c(this,H,"m",Qr).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(Lr(o)&&Lr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(u=>typeof u=="string"||typeof u=="number")){o.push(...n);continue}for(let u of n){if(!Lr(u))throw new Error(`Expected array delta entry to be an object but got: ${u}`);let l=u.index;if(l==null)throw console.error(u),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 m=o[l];m==null?o[l]=u:o[l]=this.accumulateDelta(m,u)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};Qe=ye,Yr=function(e){if(!this.ended)switch(x(this,Ss,e,"f"),c(this,H,"m",Ro).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,H,"m",$o).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,H,"m",xo).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,H,"m",Po).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Qr=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");if(!c(this,Ze,"f"))throw Error("Final run has not been received");return c(this,Ze,"f")},Po=function(e){let[t,r]=c(this,H,"m",Co).call(this,e,c(this,oe,"f"));x(this,oe,t,"f"),c(this,Rs,"f")[t.id]=t;for(let n of r){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,u=t.content[n.index];if(u&&u.type=="text")this._emit("textDelta",o,u.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=c(this,hr,"f")){if(c(this,Ye,"f"))switch(c(this,Ye,"f").type){case"text":this._emit("textDone",c(this,Ye,"f").text,c(this,oe,"f"));break;case"image_file":this._emit("imageFileDone",c(this,Ye,"f").image_file,c(this,oe,"f"));break}x(this,hr,n.index,"f")}x(this,Ye,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,hr,"f")!==void 0){let n=e.data.content[c(this,hr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,c(this,oe,"f"));break;case"text":this._emit("textDone",n.text,c(this,oe,"f"));break}}c(this,oe,"f")&&this._emit("messageDone",e.data),x(this,oe,void 0,"f")}},xo=function(e){let t=c(this,H,"m",So).call(this,e);switch(x(this,Zr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==c(this,ks,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,ee,"f")&&this._emit("toolCallDone",c(this,ee,"f")),x(this,ks,o.index,"f"),x(this,ee,t.step_details.tool_calls[o.index],"f"),c(this,ee,"f")&&this._emit("toolCallCreated",c(this,ee,"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,Zr,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,ee,"f")&&(this._emit("toolCallDone",c(this,ee,"f")),x(this,ee,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},Ro=function(e){c(this,bn,"f").push(e),this._emit("event",e)},So=function(e){switch(e.event){case"thread.run.step.created":return c(this,de,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,de,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=Qe.accumulateDelta(t,r.delta);c(this,de,"f")[e.data.id]=n}return c(this,de,"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,de,"f")[e.data.id]=e.data;break}if(c(this,de,"f")[e.data.id])return c(this,de,"f")[e.data.id];throw new Error("No snapshot available")},Co=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];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 u=t.content[o.index];t.content[o.index]=c(this,H,"m",ko).call(this,o,u)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},ko=function(e,t){return Qe.accumulateDelta(t,e)},$o=function(e){switch(x(this,Cs,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,Ze,e.data,"f"),c(this,ee,"f")&&(this._emit("toolCallDone",c(this,ee,"f")),x(this,ee,void 0,"f"));break;case"thread.run.cancelling":break}};var et=class extends a{constructor(){super(...arguments),this.steps=new dr(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/runs/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/runs`,C,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(i`/threads/${n}/runs/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:u}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=u.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ue(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return ye.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};et.Steps=dr;var Ne=class extends a{constructor(){super(...arguments),this.runs=new et(this._client),this.messages=new pr(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/threads/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/threads/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return ye.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ne.Runs=et;Ne.Messages=pr;var re=class extends a{constructor(){super(...arguments),this.realtime=new ve(this._client),this.responses=new Te(this._client),this.chatkit=new Oe(this._client),this.assistants=new nr(this._client),this.threads=new Ne(this._client)}};re.Realtime=ve;re.Responses=Te;re.ChatKit=Oe;re.Assistants=nr;re.Threads=Ne;var tt=class extends a{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var mr=class extends a{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var rt=class extends a{constructor(){super(...arguments),this.content=new mr(this._client)}create(e,t,r){return this._client.post(i`/containers/${e}/files`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/containers/${e}/files`,C,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(i`/containers/${n}/files/${e}`,{...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};rt.Content=mr;var je=class extends a{constructor(){super(...arguments),this.files=new rt(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",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/containers/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}};je.Files=rt;var fr=class extends a{create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/conversations/${e}/items`,{query:{include:n},body:o,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(i`/conversations/${n}/items/${e}`,{query:o,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/conversations/${e}/items`,E,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(i`/conversations/${n}/items/${e}`,{...r,__security:{bearerAuth:!0}})}};var Le=class extends a{constructor(){super(...arguments),this.items=new fr(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,r){return this._client.post(i`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Le.Items=fr;var st=class extends a{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&L(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 r?o:(L(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(u=>(u&&u.data&&u.data.forEach(l=>{let m=l.embedding;l.embedding=Io(m)}),u)))}};var _r=class extends a{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(i`/evals/${n}/runs/${o}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(i`/evals/${n}/runs/${e}/output_items`,C,{query:o,...r,__security:{bearerAuth:!0}})}};var nt=class extends a{constructor(){super(...arguments),this.outputItems=new _r(this._client)}create(e,t,r){return this._client.post(i`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/evals/${e}/runs`,C,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};nt.OutputItems=_r;var Me=class extends a{constructor(){super(...arguments),this.runs=new nt(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,r){return this._client.post(i`/evals/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/evals",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}};Me.Runs=nt;var ot=class extends a{create(e,t){return this._client.post("/files",V({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",C,{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:h([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),u=await this.retrieve(e);for(;!u.status||!n.has(u.status);)if(await ue(t),u=await this.retrieve(e),Date.now()-o>r)throw new Pe({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return u}};var gr=class extends a{};var yr=class extends a{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 it=class extends a{constructor(){super(...arguments),this.graders=new yr(this._client)}};it.Graders=yr;var Ar=class extends a{create(e,t,r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(i`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var at=class extends a{constructor(){super(...arguments),this.permissions=new Ar(this._client)}};at.Permissions=Ar;var br=class extends a{list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/checkpoints`,C,{query:t,...r,__security:{bearerAuth:!0}})}};var ut=class extends a{constructor(){super(...arguments),this.checkpoints=new br(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",C,{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={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/events`,C,{query:t,...r,__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}})}};ut.Checkpoints=br;var ie=class extends a{constructor(){super(...arguments),this.methods=new gr(this._client),this.jobs=new ut(this._client),this.checkpoints=new at(this._client),this.alpha=new it(this._client)}};ie.Methods=gr;ie.Jobs=ut;ie.Checkpoints=at;ie.Alpha=it;var wr=class extends a{};var Ke=class extends a{constructor(){super(...arguments),this.graderModels=new wr(this._client)}};Ke.GraderModels=wr;var ct=class extends a{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",V({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 lt=class extends a{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 pt=class extends a{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var Ir=class extends a{accept(e,t,r){return this._client.post(i`/realtime/calls/${e}/accept`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(i`/realtime/calls/${e}/hangup`,{...t,headers:h([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,r){return this._client.post(i`/realtime/calls/${e}/refer`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(i`/realtime/calls/${e}/reject`,{body:t,...r,headers:h([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var Pr=class extends a{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Ae=class extends a{constructor(){super(...arguments),this.clientSecrets=new Pr(this._client),this.calls=new Ir(this._client)}};Ae.ClientSecrets=Pr;Ae.Calls=Ir;function Eo(s,e){if(!e||!Ma(e)){let t={...s,output_parsed:null,output:s.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)};return vo(s,t)&&te(t),t}return wn(s,e)}function wn(s,e){let t=!s.status||s.status==="completed",r=s.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:t?Ua(e,o):null};if(o.type==="message"){let u=o.content.map(l=>l.type==="output_text"?{...l,parsed:t?La(e,l.text):null}:l);return{...o,content:u}}return o}),n=Object.assign({},s,{output:r});return vo(s,n)&&te(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let u of o.content)if(u.type==="output_text"&&u.parsed!==null)return u.parsed}return null}}),n}function La(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Ma(s){return!!zr(s.text?.format)}function Ka(s){return s?.$brand==="auto-parseable-tool"}function Fa(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Ua(s,e){let t=Fa(s.tools??[],e.name);return{...e,...e,parsed_arguments:Ka(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function vo(s,e){return!Object.getOwnPropertyDescriptor(s,"output_text")||e.output_text==null}function te(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}function To(s,e){if(!e){if(s.type!=="response.created")throw new g(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return Oo(s.response)}switch(s.type){case"response.output_item.added":{e.output.push(structuredClone(s.item)),s.item.type==="message"&&te(e);break}case"response.output_item.done":{$(e,s.output_index),e.output[s.output_index]=structuredClone(s.item),s.item.type==="message"&&te(e);break}case"response.content_part.added":{let t=$(e,s.output_index),r=t.type,n=s.part;r==="message"&&n.type!=="reasoning_text"?(t.content.push(structuredClone(n)),n.type==="output_text"&&te(e)):r==="reasoning"&&n.type==="reasoning_text"&&(t.content||(t.content=[]),t.content.push(structuredClone(n)));break}case"response.content_part.done":{let t=$(e,s.output_index),r=s.part;if(t.type==="message"&&r.type!=="reasoning_text")se(t.content,s.content_index),t.content[s.content_index]=structuredClone(r),r.type==="output_text"&&te(e);else if(t.type==="reasoning"&&r.type==="reasoning_text"){let n=t.content;if(!n)throw new g(`missing content at index ${s.content_index}`);se(n,s.content_index),n[s.content_index]=structuredClone(r)}break}case"response.output_text.delta":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.text+=s.delta,e.output_text+=s.delta}break}case"response.output_text.done":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.text=s.text,te(e)}break}case"response.output_text.annotation.added":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.annotations[s.annotation_index]=structuredClone(s.annotation)}break}case"response.refusal.delta":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="refusal")throw new g(`expected content to be 'refusal', got ${r.type}`);r.refusal+=s.delta}break}case"response.refusal.done":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="refusal")throw new g(`expected content to be 'refusal', got ${r.type}`);r.refusal=s.refusal}break}case"response.function_call_arguments.delta":{let t=$(e,s.output_index);t.type==="function_call"&&(t.arguments+=s.delta);break}case"response.function_call_arguments.done":{let t=$(e,s.output_index);t.type==="function_call"&&(t.arguments=s.arguments);break}case"response.reasoning_text.delta":{let t=$(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=se(t.content,s.content_index);if(r.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=s.delta}break}case"response.reasoning_text.done":{let t=$(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=se(t.content,s.content_index);if(r.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${r.type}`);r.text=s.text}break}case"response.reasoning_summary_part.added":{let t=$(e,s.output_index);t.type==="reasoning"&&t.summary.push(structuredClone(s.part));break}case"response.reasoning_summary_part.done":{let t=$(e,s.output_index);t.type==="reasoning"&&(se(t.summary,s.summary_index),t.summary[s.summary_index]=structuredClone(s.part));break}case"response.reasoning_summary_text.delta":{let t=$(e,s.output_index);if(t.type==="reasoning"){let r=se(t.summary,s.summary_index);r.text+=s.delta}break}case"response.reasoning_summary_text.done":{let t=$(e,s.output_index);if(t.type==="reasoning"){let r=se(t.summary,s.summary_index);r.text=s.text}break}case"response.custom_tool_call_input.delta":{let t=$(e,s.output_index);t.type==="custom_tool_call"&&(t.input+=s.delta);break}case"response.custom_tool_call_input.done":{let t=$(e,s.output_index);t.type==="custom_tool_call"&&(t.input=s.input);break}case"response.mcp_call_arguments.delta":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.arguments+=s.delta);break}case"response.mcp_call_arguments.done":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.arguments=s.arguments);break}case"response.code_interpreter_call_code.delta":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=(t.code??"")+s.delta);break}case"response.code_interpreter_call_code.done":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=s.code);break}case"response.code_interpreter_call.in_progress":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="interpreting");break}case"response.code_interpreter_call.completed":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="completed");break}case"response.file_search_call.in_progress":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="in_progress");break}case"response.file_search_call.searching":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="searching");break}case"response.file_search_call.completed":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="completed");break}case"response.web_search_call.in_progress":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="in_progress");break}case"response.web_search_call.searching":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="searching");break}case"response.web_search_call.completed":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="completed");break}case"response.image_generation_call.in_progress":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="in_progress");break}case"response.image_generation_call.generating":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="generating");break}case"response.image_generation_call.completed":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="completed");break}case"response.mcp_call.in_progress":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.status="in_progress");break}case"response.mcp_call.completed":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.status="completed");break}case"response.mcp_call.failed":{let t=$(e,s.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=Oo(s.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:Ba(s)}return e}function Oo(s){let e=structuredClone(s);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&te(e),e}function $(s,e){let t=s.output[e];if(!t)throw new g(`missing output at index ${e}`);return t}function se(s,e){let t=s[e];if(!t)throw new g(`missing content at index ${e}`);return t}function Ba(s){throw new g(`Unhandled response stream event: ${JSON.stringify(s)}`)}var es,$s,dt,Es,No,jo,Lo,vs=class s extends Se{constructor(e){super(),es.add(this),$s.set(this,void 0),dt.set(this,void 0),Es.set(this,void 0),x(this,$s,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){this._listenForAbort(r?.signal),c(this,es,"m",No).call(this);let n,o=null;"response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let u of n)c(this,es,"m",jo).call(this,u,o);if(n.controller.signal?.aborted)throw new K;return c(this,es,"m",Lo).call(this)}[($s=new WeakMap,dt=new WeakMap,Es=new WeakMap,es=new WeakSet,No=function(){this.ended||x(this,dt,void 0,"f")},jo=function(t,r){if(this.ended)return;let n=(u,l)=>{(r==null||l.sequence_number>r)&&this._emit(u,l)},o=To(t,c(this,dt,"f"));switch(x(this,dt,o,"f"),n("event",t),t.type){case"response.output_text.delta":{let u=o.output[t.output_index];if(!u)throw new g(`missing output at index ${t.output_index}`);if(u.type==="message"){let l=u.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 u=o.output[t.output_index];if(!u)throw new g(`missing output at index ${t.output_index}`);u.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:u.arguments});break}default:n(t.type,t);break}},Lo=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=c(this,dt,"f");if(!t)throw new g("request ended without sending any events");x(this,dt,void 0,"f");let r=Da(t,c(this,$s,"f"));return x(this,Es,r,"f"),r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,u)=>t.push({resolve:o,reject:u})).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,Es,"f");if(!e)throw new g("stream ended without producing a ChatCompletion");return e}};function Da(s,e){return Eo(s,e)}var xr=class extends a{list(e,t={},r){return this._client.getAPIList(i`/responses/${e}/input_items`,C,{query:t,...r,__security:{bearerAuth:!0}})}};var Rr=class extends a{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var he=class extends a{constructor(){super(...arguments),this.inputItems=new xr(this._client),this.inputTokens=new Rr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&te(r),r))}retrieve(e,t={},r){return this._client.get(i`/responses/${e}`,{query:t,...r,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&te(n),n))}delete(e,t){return this._client.delete(i`/responses/${e}`,{...t,headers:h([{Accept:"*/*"},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>wn(r,e))}stream(e,t){return vs.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}})}};he.InputItems=xr;he.InputTokens=Rr;var Sr=class extends a{retrieve(e,t){return this._client.get(i`/skills/${e}/content`,{...t,headers:h([{Accept:"application/binary"},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var Cr=class extends a{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}/content`,{...r,headers:h([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var ht=class extends a{constructor(){super(...arguments),this.content=new Cr(this._client)}create(e,t={},r){return this._client.post(i`/skills/${e}/versions`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/skills/${e}/versions`,C,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};ht.Content=Cr;var be=class extends a{constructor(){super(...arguments),this.content=new Sr(this._client),this.versions=new ht(this._client)}create(e={},t){return this._client.post("/skills",Re({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,r){return this._client.post(i`/skills/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/skills",C,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}};be.Content=Sr;be.Versions=ht;var kr=class extends a{create(e,t,r){return this._client.post(i`/uploads/${e}/parts`,V({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Fe=class extends a{constructor(){super(...arguments),this.parts=new kr(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,r){return this._client.post(i`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}};Fe.Parts=kr;var Mo=async s=>{let e=await Promise.allSettled(s),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 r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var $r=class extends a{create(e,t,r){return this._client.post(i`/vector_stores/${e}/file_batches`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/file_batches/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(i`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(i`/vector_stores/${n}/file_batches/${e}/files`,C,{query:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){let n=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:u}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=u.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ue(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},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,u=Math.min(o,t.length),l=this._client,m=t.values(),p=[...r];async function w(f){for(let b of f){let y=await l.files.create({file:b,purpose:"assistants"},n);p.push(y.id)}}let d=Array(u).fill(m).map(w);return await Mo(d),await this.createAndPoll(e,{file_ids:p})}};var Er=class extends a{create(e,t,r){return this._client.post(i`/vector_stores/${e}/files`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(i`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/vector_stores/${e}/files`,C,{query:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(i`/vector_stores/${n}/files/${e}`,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=h([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),u=o.data;switch(u.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=o.response.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ue(l);break;case"failed":case"completed":return u}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(i`/vector_stores/${n}/files/${e}/content`,G,{...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var we=class extends a{constructor(){super(...arguments),this.files=new Er(this._client),this.fileBatches=new $r(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(i`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){return this._client.post(i`/vector_stores/${e}`,{body:t,...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList("/vector_stores",C,{query:e,...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/vector_stores/${e}`,{...t,headers:h([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,r){return this._client.getAPIList(i`/vector_stores/${e}/search`,G,{body:t,method:"post",...r,headers:h([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};we.Files=Er;we.FileBatches=$r;var mt=class extends a{create(e,t){return this._client.post("/videos",V({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",E,{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",V({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(i`/videos/${e}/content`,{query:t,...r,headers:h([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",V({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",V({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,r){return this._client.post(i`/videos/${e}/remix`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var vr,Ko,Os,ft=class extends a{constructor(){super(...arguments),vr.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=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,vr,"m",Ko).call(this,r);let o=h([t]).values,u=c(this,vr,"m",Os).call(this,o,"webhook-signature"),l=c(this,vr,"m",Os).call(this,o,"webhook-timestamp"),m=c(this,vr,"m",Os).call(this,o,"webhook-id"),p=parseInt(l,10);if(isNaN(p))throw new ae("Invalid webhook timestamp format");let w=Math.floor(Date.now()/1e3);if(w-p>n)throw new ae("Webhook timestamp is too old");if(p>w+n)throw new ae("Webhook timestamp is too new");let d=u.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),b=m?`${m}.${l}.${e}`:`${l}.${e}`,y=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of d)try{let I=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",y,I,new TextEncoder().encode(b)))return}catch{continue}throw new ae("The given webhook signature does not match the expected signature")}};vr=new WeakSet,Ko=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")},Os=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Uo=Symbol.for("openai.node.providerDefinitions.v1"),Bo=globalThis,Do=Bo[Uo],zo=Do??new WeakMap;Do||Object.defineProperty(Bo,Uo,{value:zo});function qo(s){let e=zo.get(s);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var In,Pn,ts,Wo,Ya="workload-identity-auth",S=class{constructor(e={}){In.add(this),ts.set(this,void 0),this.completions=new tt(this),this.chat=new ke(this),this.embeddings=new st(this),this.files=new ot(this),this.images=new ct(this),this.audio=new pe(this),this.moderations=new pt(this),this.models=new lt(this),this.fineTuning=new ie(this),this.graders=new Ke(this),this.vectorStores=new we(this),this.webhooks=new ft(this),this.beta=new re(this),this.batches=new Ve(this),this.uploads=new Fe(this),this.admin=new Ee(this),this.responses=new he(this),this.realtime=new Ae(this),this.conversations=new Le(this),this.evals=new Me(this),this.containers=new je(this),this.skills=new be(this),this.videos=new mt(this);let t=e.provider;if(t){let A=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(I=>e[I]!=null);if(A.length)throw new g(`The \`provider\` option cannot be used with ${A.map(I=>`\`${I}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:r=t?null:ne("OPENAI_BASE_URL"),apiKey:n=t?null:ne("OPENAI_API_KEY")??null,adminAPIKey:o=t?null:ne("OPENAI_ADMIN_KEY")??null,organization:u=t?null:ne("OPENAI_ORG_ID")??null,project:l=t?null:ne("OPENAI_PROJECT_ID")??null,webhookSecret:m=ne("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:p,...w}=e,d=t?qo(t):void 0,f={apiKey:n,adminAPIKey:o,organization:u,project:l,webhookSecret:m,workloadIdentity:p,provider:t,...w,baseURL:d?.baseURL??(r||"https://api.openai.com/v1")};if(n&&p)throw new g("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!d&&!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(!f.dangerouslyAllowBrowser&&Fn())throw new g(`It looks like you're running in a browser-like environment.
|
|
12
|
+
${h}`)}return u},i=Ii(lo);var qe=class extends a{list(e,t={},r){return this._client.getAPIList(i`/chat/completions/${e}/messages`,S,{query:t,...r,__security:{bearerAuth:!0}})}};function Dr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function zr(s){return s?.$brand==="auto-parseable-response-format"}function We(s){return s?.$brand==="auto-parseable-tool"}function ho(s,e){return!e||!an(e)?{...s,choices:s.choices.map(t=>(fo(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:qr(s,e)}function qr(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new xt;if(r.finish_reason==="content_filter")throw new Rt;return fo(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>xi(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Pi(e,r.message.content):null}}});return{...s,choices:t}}function Pi(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function xi(s,e){let t=s.tools?.find(r=>Dr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:We(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function mo(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>Dr(r)&&r.function?.name===e.function.name);return Dr(t)&&(We(t)||t?.function.strict||!1)}function an(s){return zr(s.response_format)?!0:s.tools?.some(e=>We(e)||e.type==="function"&&e.function.strict===!0)??!1}function fo(s){for(let e of s||[])if(e.type!=="function")throw new g(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function _o(s){for(let e of s??[]){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 $t=s=>s?.role==="assistant",un=s=>s?.role==="tool";var fs,_s,gs,Wr,Hr,ys,Jr,fe,As,Xr,bs,Is,Et,go,yo,Ce=class{constructor(){fs.add(this),this.controller=new AbortController,_s.set(this,void 0),gs.set(this,()=>{}),Wr.set(this,()=>{}),Hr.set(this,void 0),ys.set(this,()=>{}),Jr.set(this,()=>{}),fe.set(this,{}),As.set(this,[]),Xr.set(this,!1),bs.set(this,!1),Is.set(this,!1),Et.set(this,!1),x(this,_s,new Promise((e,t)=>{x(this,gs,e,"f"),x(this,Wr,t,"f")}),"f"),x(this,Hr,new Promise((e,t)=>{x(this,ys,e,"f"),x(this,Jr,t,"f")}),"f"),c(this,_s,"f").catch(()=>{}),c(this,Hr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},c(this,fs,"m",yo).bind(this))},0)}_connected(){this.ended||(c(this,gs,"f").call(this),this._emit("connect"))}get ended(){return c(this,Xr,"f")}get errored(){return c(this,bs,"f")}get aborted(){return c(this,Is,"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,As,"f").push({signal:e,listener:t})}on(e,t){return(c(this,fe,"f")[e]||(c(this,fe,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=c(this,fe,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(c(this,fe,"f")[e]||(c(this,fe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{x(this,Et,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){x(this,Et,!0,"f"),await c(this,Hr,"f")}_emit(e,...t){if(c(this,Xr,"f"))return;e==="end"&&(c(this,fs,"m",go).call(this),x(this,Xr,!0,"f"),c(this,ys,"f").call(this));let r=c(this,fe,"f")[e];if(r&&(c(this,fe,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!c(this,Et,"f")&&!r?.length&&Promise.reject(n),c(this,Wr,"f").call(this,n),c(this,Jr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!c(this,Et,"f")&&!r?.length&&Promise.reject(n),c(this,Wr,"f").call(this,n),c(this,Jr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};_s=new WeakMap,gs=new WeakMap,Wr=new WeakMap,Hr=new WeakMap,ys=new WeakMap,Jr=new WeakMap,fe=new WeakMap,As=new WeakMap,Xr=new WeakMap,bs=new WeakMap,Is=new WeakMap,Et=new WeakMap,fs=new WeakSet,go=function(){for(let{signal:e,listener:t}of c(this,As,"f").splice(0))e.removeEventListener("abort",t)},yo=function(e){if(x(this,bs,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new F),e instanceof F)return x(this,Is,!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 Ao(s){return typeof s.parse=="function"}var Y,cn,ws,ln,pn,hn,bo,Io,Ri=10;function Ci(s){for(let e of s.choices)for(let t of e.message.tool_calls??[])t.id||(t.id=`call_${Ue()}`)}var Ot=class extends Ce{constructor(){super(...arguments),Y.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){Ci(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),un(e)&&e.content)this._emit("functionToolCallResult",e.content);else if($t(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new g("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),c(this,Y,"m",cn).call(this)}async finalMessage(){return await this.done(),c(this,Y,"m",ws).call(this)}async finalFunctionToolCall(){return await this.done(),c(this,Y,"m",ln).call(this)}async finalFunctionToolCallResult(){return await this.done(),c(this,Y,"m",pn).call(this)}async totalUsage(){return await this.done(),c(this,Y,"m",hn).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",ws).call(this);t&&this._emit("finalMessage",t);let r=c(this,Y,"m",cn).call(this);r&&this._emit("finalContent",r);let n=c(this,Y,"m",ln).call(this);n&&this._emit("finalFunctionToolCall",n);let o=c(this,Y,"m",pn).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(u=>u.usage)&&this._emit("totalUsage",c(this,Y,"m",hn).call(this))}async _createChatCompletion(e,t,r){this._listenForAbort(r?.signal),c(this,Y,"m",bo).call(this,t);let n=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(qr(n,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r,n){let o="tool",{tool_choice:u="auto",stream:l,...m}=t,p=typeof u!="string"&&u.type==="function"&&u?.function?.name,{maxChatCompletions:I=Ri,afterCompletion:h}=n||{},f=t.tools.map(w=>{if(We(w)){if(!w.$callback)throw new g("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:w.$callback,name:w.function.name,description:w.function.description||"",parameters:w.function.parameters,parse:w.$parseRaw,strict:!0}}}return w}),b={};for(let w of f)w.type==="function"&&(b[w.function.name||w.function.function.name]=w.function);let y="tools"in t?f.map(w=>w.type==="function"?{type:"function",function:{name:w.function.name||w.function.function.name,parameters:w.function.parameters,description:w.function.description,strict:w.function.strict}}:w):void 0;for(let w of t.messages)this._addMessage(w,!1);let A=async w=>{if(w.type!=="function")return{message:void 0,functionCalled:!1};let k=w.id,{name:_,arguments:P}=w.function,R=b[_];if(!R){let N=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(b).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;return{message:{role:o,tool_call_id:k,content:N},functionCalled:!1}}if(p&&p!==_){let N=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(p)} requested. Please try again`;return{message:{role:o,tool_call_id:k,content:N},functionCalled:!1}}let v;if(Ao(R)){let N;try{N=await R.parse(P)}catch(j){let J=j instanceof Error?j.message:String(j);return{message:{role:o,tool_call_id:k,content:J},functionCalled:!1}}v=await R.function(N,r)}else v=await R.function(P,r);let O=c(this,Y,"m",Io).call(this,v);return{message:{role:o,tool_call_id:k,content:O},functionCalled:!0}};for(let w=0;w<I;++w){let k=await this._createChatCompletion(e,{...m,tool_choice:u,tools:y,messages:[...this.messages]},n),_=k.choices[0]?.message;if(!_)throw new g("missing message in ChatCompletion response");if(!_.tool_calls?.length){await h?.(k,r);return}if(p||t.parallel_tool_calls===!1)for(let P of _.tool_calls){let R=await A(P);if(R.message&&this._addMessage(R.message),p&&R.functionCalled){await h?.(k,r);return}}else{let P=await Promise.allSettled(_.tool_calls.map(A));for(let R of P)if(R.status==="rejected")throw R.reason;for(let R of P)R.status==="fulfilled"&&R.value.message&&this._addMessage(R.value.message)}await h?.(k,r)}}};Y=new WeakSet,cn=function(){return c(this,Y,"m",ws).call(this).content??null},ws=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if($t(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new g("stream ended without producing a ChatCompletionMessage with role=assistant")},ln=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if($t(t)&&t?.tool_calls?.length)for(let r=t.tool_calls.length-1;r>=0;r--){let n=t.tool_calls[r];if(n?.type==="function")return n.function}}},pn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(un(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},hn=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},bo=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.")},Io=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Gr=class s extends Ot{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),$t(e)&&e.content&&this._emit("content",e.content)}};var z={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},dn=class extends Error{},mn=class extends Error{};function Si(s,e=z.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return ki(s.trim(),e)}var ki=(s,e)=>{let t=s.length,r=0,n=f=>{throw new dn(`${f} at position ${r}`)},o=f=>{throw new mn(`${f} at position ${r}`)},u=()=>(h(),r>=t&&n("Unexpected end of input"),s[r]==='"'?l():s[r]==="{"?m():s[r]==="["?p():s.substring(r,r+4)==="null"||z.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||z.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||z.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||z.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||z.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||z.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):I()),l=()=>{let f=r,b=!1;for(r++;r<t&&(s[r]!=='"'||b&&s[r-1]==="\\");)b=s[r]==="\\"?!b:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(f,++r-Number(b)))}catch(y){o(String(y))}else if(z.STR&e)try{return JSON.parse(s.substring(f,r-Number(b))+'"')}catch{return JSON.parse(s.substring(f,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},m=()=>{r++,h();let f={};try{for(;s[r]!=="}";){if(h(),r>=t&&z.OBJ&e)return f;let b=l();h(),r++;try{let y=u();Object.defineProperty(f,b,{value:y,writable:!0,enumerable:!0,configurable:!0})}catch(y){if(z.OBJ&e)return f;throw y}h(),s[r]===","&&r++}}catch{if(z.OBJ&e)return f;n("Expected '}' at end of object")}return r++,f},p=()=>{r++;let f=[];try{for(;s[r]!=="]";)f.push(u()),h(),s[r]===","&&r++}catch{if(z.ARR&e)return f;n("Expected ']' at end of array")}return r++,f},I=()=>{if(r===0){s==="-"&&z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(b){if(z.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(b))}}let f=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(z.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(f,r))}catch{s.substring(f,r)==="-"&&z.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(f,s.lastIndexOf("e")))}catch(y){o(String(y))}}},h=()=>{for(;r<t&&`
|
|
13
|
+
\r `.includes(s[r]);)r++};return u()},fn=s=>Si(s,z.ALL^z.NUM);var D,_e,vt,Se,_n,Ps,gn,yn,An,xs,bn,wo,He=class s extends Ot{constructor(e){super(),D.add(this),_e.set(this,void 0),vt.set(this,void 0),Se.set(this,void 0),x(this,_e,e,"f"),x(this,vt,[],"f")}get currentChatCompletionSnapshot(){return c(this,Se,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion,this._listenForAbort(r?.signal),c(this,D,"m",_n).call(this);let n=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let o of n)c(this,D,"m",gn).call(this,o);if(n.controller.signal?.aborted)throw new F;return this._addChatCompletion(c(this,D,"m",xs).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),c(this,D,"m",_n).call(this),this._connected();let r=le.fromReadableStream(e,this.controller),n;for await(let o of r)n&&n!==o.id&&this._addChatCompletion(c(this,D,"m",xs).call(this)),c(this,D,"m",gn).call(this,o),n=o.id;if(r.controller.signal?.aborted)throw new F;return this._addChatCompletion(c(this,D,"m",xs).call(this))}[(_e=new WeakMap,vt=new WeakMap,Se=new WeakMap,D=new WeakSet,_n=function(){this.ended||x(this,Se,void 0,"f")},Ps=function(t){let r=c(this,vt,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},c(this,vt,"f")[t.index]=r,r)},gn=function(t){if(this.ended)return;let r=c(this,D,"m",wo).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.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 u=c(this,D,"m",Ps).call(this,o);o.finish_reason&&(c(this,D,"m",An).call(this,o),u.current_tool_call_index!=null&&c(this,D,"m",yn).call(this,o,u.current_tool_call_index));for(let l of n.delta.tool_calls??[])u.current_tool_call_index!==l.index&&(c(this,D,"m",An).call(this,o),u.current_tool_call_index!=null&&c(this,D,"m",yn).call(this,o,u.current_tool_call_index)),u.current_tool_call_index=l.index;for(let l of n.delta.tool_calls??[]){let m=o.message.tool_calls?.[l.index];m?.type&&(m?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:m.function?.name,index:l.index,arguments:m.function.arguments,parsed_arguments:m.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(m?.type,void 0))}}},yn=function(t,r){if(c(this,D,"m",Ps).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];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 u=c(this,_e,"f")?.tools?.find(l=>Dr(l)&&l.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:We(u)?u.$parseRaw(o.function.arguments):u?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},An=function(t){let r=c(this,D,"m",Ps).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=c(this,D,"m",bn).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},xs=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=c(this,Se,"f");if(!t)throw new g("request ended without sending any chunks");return x(this,Se,void 0,"f"),x(this,vt,[],"f"),$i(t,c(this,_e,"f"))},bn=function(){let t=c(this,_e,"f")?.response_format;return zr(t)?t:null},wo=function(t){var r,n,o,u;let l=c(this,Se,"f"),{choices:m,...p}=t;l?Object.assign(l,p):l=x(this,Se,{...p,choices:[]},"f");for(let{delta:I,finish_reason:h,index:f,logprobs:b=null,...y}of t.choices){let A=l.choices[f];if(A||(A=l.choices[f]={finish_reason:h,index:f,message:{},logprobs:b,...y}),b)if(!A.logprobs)A.logprobs=Object.assign({},b);else{let{content:O,refusal:N,...j}=b;Object.assign(A.logprobs,j),O&&((r=A.logprobs).content??(r.content=[]),A.logprobs.content.push(...O)),N&&((n=A.logprobs).refusal??(n.refusal=[]),A.logprobs.refusal.push(...N))}if(h&&(A.finish_reason=h,c(this,_e,"f")&&an(c(this,_e,"f")))){if(h==="length")throw new xt;if(h==="content_filter")throw new Rt}if(Object.assign(A,y),!I)continue;let{content:w,refusal:k,function_call:_,role:P,tool_calls:R,...v}=I;if(Object.assign(A.message,v),k&&(A.message.refusal=(A.message.refusal||"")+k),P&&(A.message.role=P),_&&(A.message.function_call?(_.name&&(A.message.function_call.name=_.name),_.arguments&&((o=A.message.function_call).arguments??(o.arguments=""),A.message.function_call.arguments+=_.arguments)):A.message.function_call=_),w&&(A.message.content=(A.message.content||"")+w,!A.message.refusal&&c(this,D,"m",bn).call(this)&&(A.message.parsed=A.message.content.trim()?fn(A.message.content):null)),R){A.message.tool_calls||(A.message.tool_calls=[]);for(let{index:O,id:N,type:j,function:J,...M}of R){let U=(u=A.message.tool_calls)[O]??(u[O]={});Object.assign(U,M),N&&(U.id=N),j&&(U.type=j),J&&(U.function??(U.function={name:J.name??"",arguments:""})),J?.name&&(U.function.name=J.name),J?.arguments&&(U.function.arguments+=J.arguments,mo(c(this,_e,"f"),U)&&(U.function.parsed_arguments=fn(U.function.arguments)))}}}return l},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,u)=>t.push({resolve:o,reject:u})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function $i(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:u,...l}=s,m={...l,id:t,choices:r.map(({message:p,finish_reason:I,index:h,logprobs:f,...b})=>{if(!I)throw new g(`missing finish_reason for choice ${h}`);let{content:y=null,function_call:A,tool_calls:w,...k}=p,_=p.role;if(!_)throw new g(`missing role for choice ${h}`);if(A){let{arguments:P,name:R}=A;if(P==null)throw new g(`missing function_call.arguments for choice ${h}`);if(!R)throw new g(`missing function_call.name for choice ${h}`);return{...b,message:{content:y,function_call:{arguments:P,name:R},role:_,refusal:p.refusal??null},finish_reason:I,index:h,logprobs:f}}return w?{...b,index:h,finish_reason:I,logprobs:f,message:{...k,role:_,content:y,refusal:p.refusal??null,tool_calls:w.map((P,R)=>{let{function:v,type:O,id:N,...j}=P,{arguments:J,name:M,...U}=v||{};if(O==null)throw new g(`missing choices[${h}].tool_calls[${R}].type
|
|
14
|
+
${In(s)}`);if(M==null)throw new g(`missing choices[${h}].tool_calls[${R}].function.name
|
|
15
|
+
${In(s)}`);if(J==null)throw new g(`missing choices[${h}].tool_calls[${R}].function.arguments
|
|
16
|
+
${In(s)}`);return{...j,id:N||`call_${Ue()}`,type:O,function:{...U,name:M,arguments:J}}})}}:{...b,message:{...k,content:y,role:_,refusal:p.refusal??null},finish_reason:I,index:h,logprobs:f}}),created:n,model:o,object:"chat.completion",...u?{system_fingerprint:u}:{}};return ho(m,e)}function In(s){return JSON.stringify(s)}var Vr=class s extends He{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,n,o)),n}};var ge=class extends a{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,r){return this._client.post(i`/chat/completions/${e}`,{body:t,...r,__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 _o(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>qr(r,e))}runTools(e,t){return e.stream?Vr.runTools(this._client,e,t):Gr.runTools(this._client,e,t)}stream(e,t){return He.createChatCompletion(this._client,e,t)}};ge.Messages=qe;var ke=class extends a{constructor(){super(...arguments),this.completions=new ge(this._client)}};ke.Completions=ge;var Tt=class extends a{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 Nt=class extends a{list(e={},t){return this._client.getAPIList("/organization/audit_logs",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}};var jt=class extends a{create(e,t){return this._client.post("/organization/certificates",{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/organization/certificates/${e}`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/certificates/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/certificates",E,{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 Lt=class extends a{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 Mt=class extends a{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",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ft=class extends a{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,r){return this._client.post(i`/organization/roles/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/roles",K,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Kt=class extends a{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,r){return this._client.post(i`/organization/spend_alerts/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/spend_alerts",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Ut=class extends a{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 Bt=class extends a{create(e,t,r){return this._client.post(i`/organization/groups/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/roles`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Dt=class extends a{create(e,t,r){return this._client.post(i`/organization/groups/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{group_id:n}=t;return this._client.get(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/groups/${e}/users`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{group_id:n}=t;return this._client.delete(i`/organization/groups/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var $e=class extends a{constructor(){super(...arguments),this.users=new Dt(this._client),this.roles=new Bt(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,r){return this._client.post(i`/organization/groups/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/groups",K,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};$e.Users=Dt;$e.Roles=Bt;var zt=class extends a{retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/api_keys`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var qt=class extends a{list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/certificates`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/activate`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,r){return this._client.getAPIList(i`/organization/projects/${e}/certificates/deactivate`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}};var Wt=class extends a{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/data_retention`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var Ht=class extends a{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}};var Jt=class extends a{retrieve(e,t){return this._client.get(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/projects/${e}/model_permissions`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}};var Xt=class extends a{listRateLimits(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/rate_limits`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/rate_limits/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}};var Gt=class extends a{create(e,t,r){return this._client.post(i`/projects/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/roles/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/projects/${e}/roles`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/projects/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Vt=class extends a{create(e,t,r){return this._client.post(i`/organization/projects/${e}/service_accounts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/service_accounts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/service_accounts`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Yt=class extends a{create(e,t,r){return this._client.post(i`/organization/projects/${e}/spend_alerts`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/spend_alerts/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/spend_alerts`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Qt=class extends a{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/groups/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,group_id:o}=t;return this._client.get(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/groups/${e}/roles`,K,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,group_id:o}=t;return this._client.delete(i`/projects/${n}/groups/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Je=class extends a{constructor(){super(...arguments),this.roles=new Qt(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/groups`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,...o}=t;return this._client.get(i`/organization/projects/${n}/groups/${e}`,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/groups`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Je.Roles=Qt;var Zt=class extends a{create(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/projects/${n}/users/${e}/roles`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n,user_id:o}=t;return this._client.get(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t,r){let{project_id:n,...o}=t;return this._client.getAPIList(i`/projects/${n}/users/${e}/roles`,K,{query:o,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n,user_id:o}=t;return this._client.delete(i`/projects/${n}/users/${o}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Xe=class extends a{constructor(){super(...arguments),this.roles=new Zt(this._client)}create(e,t,r){return this._client.post(i`/organization/projects/${e}/users`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{project_id:n}=t;return this._client.get(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){let{project_id:n,...o}=t;return this._client.post(i`/organization/projects/${n}/users/${e}`,{body:o,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/projects/${e}/users`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{project_id:n}=t;return this._client.delete(i`/organization/projects/${n}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};Xe.Roles=Zt;var q=class extends a{constructor(){super(...arguments),this.users=new Xe(this._client),this.serviceAccounts=new Vt(this._client),this.apiKeys=new zt(this._client),this.rateLimits=new Xt(this._client),this.modelPermissions=new Jt(this._client),this.hostedToolPermissions=new Ht(this._client),this.groups=new Je(this._client),this.roles=new Gt(this._client),this.dataRetention=new Wt(this._client),this.spendAlerts=new Yt(this._client),this.certificates=new qt(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,r){return this._client.post(i`/organization/projects/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/projects",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(i`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}};q.Users=Xe;q.ServiceAccounts=Vt;q.APIKeys=zt;q.RateLimits=Xt;q.ModelPermissions=Jt;q.HostedToolPermissions=Ht;q.Groups=Je;q.Roles=Gt;q.DataRetention=Wt;q.SpendAlerts=Yt;q.Certificates=qt;var er=class extends a{create(e,t,r){return this._client.post(i`/organization/users/${e}/roles`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,r){let{user_id:n}=t;return this._client.get(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/organization/users/${e}/roles`,K,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{user_id:n}=t;return this._client.delete(i`/organization/users/${n}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var Ge=class extends a{constructor(){super(...arguments),this.roles=new er(this._client)}retrieve(e,t){return this._client.get(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,r){return this._client.post(i`/organization/users/${e}`,{body:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList("/organization/users",E,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(i`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}};Ge.Roles=er;var W=class extends a{constructor(){super(...arguments),this.auditLogs=new Nt(this._client),this.adminAPIKeys=new Tt(this._client),this.usage=new Ut(this._client),this.invites=new Mt(this._client),this.users=new Ge(this._client),this.groups=new $e(this._client),this.roles=new Ft(this._client),this.dataRetention=new Lt(this._client),this.spendAlerts=new Kt(this._client),this.certificates=new jt(this._client),this.projects=new q(this._client)}};W.AuditLogs=Nt;W.AdminAPIKeys=Tt;W.Usage=Ut;W.Invites=Mt;W.Users=Ge;W.Groups=$e;W.Roles=Ft;W.DataRetention=Lt;W.SpendAlerts=Kt;W.Certificates=jt;W.Projects=q;var Ee=class extends a{constructor(){super(...arguments),this.organization=new W(this._client)}};Ee.Organization=W;var Po=Symbol("brand.privateNullableHeaders");function*oa(s){if(!s)return;if(Po in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():Bs(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=Bs(r[1])?r[1]:[r[1]],u=!1;for(let l of o)l!==void 0&&(e&&!u&&(u=!0,yield[n,null]),yield[n,l])}}var d=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,u]of oa(r)){let l=o.toLowerCase();n.has(l)||(e.delete(o),n.add(l)),u===null?(e.delete(o),t.add(l)):(e.append(o,u),t.delete(l))}}return{[Po]:!0,values:e,nulls:t}};var tr=class extends a{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 rr=class extends a{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var sr=class extends a{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}};var pe=class extends a{constructor(){super(...arguments),this.transcriptions=new rr(this._client),this.translations=new sr(this._client),this.speech=new tr(this._client)}};pe.Transcriptions=rr;pe.Translations=sr;pe.Speech=tr;var Ve=class extends a{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 nr=class extends a{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,r){return this._client.post(i`/assistants/${e}`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.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 or=class extends a{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:d([{"OpenAI-Beta":"assistants=v2"},t?.headers]),__security:{bearerAuth:!0}})}};var ir=class extends a{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 Oe=class extends a{constructor(){super(...arguments),this.sessions=new or(this._client),this.transcriptionSessions=new ir(this._client)}};Oe.Sessions=or;Oe.TranscriptionSessions=ir;var ar=class extends a{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 ur=class extends a{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",E,{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={},r){return this._client.getAPIList(i`/chatkit/threads/${e}/items`,E,{query:t,...r,headers:d([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers]),__security:{bearerAuth:!0}})}};var ve=class extends a{constructor(){super(...arguments),this.sessions=new ar(this._client),this.threads=new ur(this._client)}};ve.Sessions=ar;ve.Threads=ur;var cr=class extends a{list(e,t={},r){let{betas:n,...o}=t??{};return this._client.getAPIList(i`/responses/${e}/input_items?beta=true`,S,{query:o,...r,headers:d([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}};var lr=class extends a{count(e={},t){let{betas:r,...n}=e??{};return this._client.post("/responses/input_tokens?beta=true",{body:n,...t,headers:d([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};var Te=class extends a{constructor(){super(...arguments),this.inputItems=new cr(this._client),this.inputTokens=new lr(this._client)}create(e,t){let{betas:r,...n}=e;return this._client.post("/responses?beta=true",{body:n,...t,headers:d([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},r){let{betas:n,...o}=t??{};return this._client.get(i`/responses/${e}?beta=true`,{query:o,...r,headers:d([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},r){let{betas:n}=t??{};return this._client.delete(i`/responses/${e}?beta=true`,{...r,headers:d([{Accept:"*/*",...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},r){let{betas:n}=t??{};return this._client.post(i`/responses/${e}/cancel?beta=true`,{...r,headers:d([{...n?.toString()!=null?{"openai-beta":n?.toString()}:void 0},r?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:r,...n}=e;return this._client.post("/responses/compact?beta=true",{body:n,...t,headers:d([{...r?.toString()!=null?{"openai-beta":r?.toString()}:void 0},t?.headers]),__security:{bearerAuth:!0}})}};Te.InputItems=cr;Te.InputTokens=lr;var pr=class extends a{create(e,t,r){return this._client.post(i`/threads/${e}/messages`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/messages/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/messages/${e}`,{body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/messages`,S,{query:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(i`/threads/${n}/messages/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var hr=class extends a{retrieve(e,t,r){let{thread_id:n,run_id:o,...u}=t;return this._client.get(i`/threads/${n}/runs/${o}/steps/${e}`,{query:u,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(i`/threads/${n}/runs/${e}/steps`,S,{query:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var xo=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var ne=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()||void 0};var H,Qe,wn,he,Rs,oe,Ze,dr,Ye,ks,ee,Cs,Ss,Zr,Yr,Qr,Ro,Co,So,ko,$o,Eo,Oo,ye=class extends Ce{constructor(){super(...arguments),H.add(this),wn.set(this,[]),he.set(this,{}),Rs.set(this,{}),oe.set(this,void 0),Ze.set(this,void 0),dr.set(this,void 0),Ye.set(this,void 0),ks.set(this,void 0),ee.set(this,void 0),Cs.set(this,void 0),Ss.set(this,void 0),Zr.set(this,void 0)}[(wn=new WeakMap,he=new WeakMap,Rs=new WeakMap,oe=new WeakMap,Ze=new WeakMap,dr=new WeakMap,Ye=new WeakMap,ks=new WeakMap,ee=new WeakMap,Cs=new WeakMap,Ss=new WeakMap,Zr=new WeakMap,H=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,u)=>t.push({resolve:o,reject:u})).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 Qe;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let r=le.fromReadableStream(e,this.controller);for await(let n of r)c(this,H,"m",Yr).call(this,n);if(r.controller.signal?.aborted)throw new F;return this._addRun(c(this,H,"m",Qr).call(this))}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new Qe;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},u=await e.submitToolOutputs(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of u)c(this,H,"m",Yr).call(this,l);if(u.controller.signal?.aborted)throw new F;return this._addRun(c(this,H,"m",Qr).call(this))}static createThreadAssistantStream(e,t,r){let n=new Qe;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new Qe;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return c(this,Cs,"f")}currentRun(){return c(this,Ss,"f")}currentMessageSnapshot(){return c(this,oe,"f")}currentRunStepSnapshot(){return c(this,Zr,"f")}async finalRunSteps(){return await this.done(),Object.values(c(this,he,"f"))}async finalMessages(){return await this.done(),Object.values(c(this,Rs,"f"))}async finalRun(){if(await this.done(),!c(this,Ze,"f"))throw Error("Final run was not received.");return c(this,Ze,"f")}async _createThreadAssistantStream(e,t,r){this._listenForAbort(r?.signal);let n={...t,stream:!0},o=await e.createAndRun(n,{...r,signal:this.controller.signal});this._connected();for await(let u of o)c(this,H,"m",Yr).call(this,u);if(o.controller.signal?.aborted)throw new F;return this._addRun(c(this,H,"m",Qr).call(this))}async _createAssistantStream(e,t,r,n){this._listenForAbort(n?.signal);let o={...r,stream:!0},u=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(let l of u)c(this,H,"m",Yr).call(this,l);if(u.controller.signal?.aborted)throw new F;return this._addRun(c(this,H,"m",Qr).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(Lr(o)&&Lr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(u=>typeof u=="string"||typeof u=="number")){o.push(...n);continue}for(let u of n){if(!Lr(u))throw new Error(`Expected array delta entry to be an object but got: ${u}`);let l=u.index;if(l==null)throw console.error(u),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 m=o[l];m==null?o[l]=u:o[l]=this.accumulateDelta(m,u)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};Qe=ye,Yr=function(e){if(!this.ended)switch(x(this,Cs,e,"f"),c(this,H,"m",So).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,H,"m",Oo).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,H,"m",Co).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,H,"m",Ro).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Qr=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");if(!c(this,Ze,"f"))throw Error("Final run has not been received");return c(this,Ze,"f")},Ro=function(e){let[t,r]=c(this,H,"m",$o).call(this,e,c(this,oe,"f"));x(this,oe,t,"f"),c(this,Rs,"f")[t.id]=t;for(let n of r){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,u=t.content[n.index];if(u&&u.type=="text")this._emit("textDelta",o,u.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=c(this,dr,"f")){if(c(this,Ye,"f"))switch(c(this,Ye,"f").type){case"text":this._emit("textDone",c(this,Ye,"f").text,c(this,oe,"f"));break;case"image_file":this._emit("imageFileDone",c(this,Ye,"f").image_file,c(this,oe,"f"));break}x(this,dr,n.index,"f")}x(this,Ye,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(c(this,dr,"f")!==void 0){let n=e.data.content[c(this,dr,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,c(this,oe,"f"));break;case"text":this._emit("textDone",n.text,c(this,oe,"f"));break}}c(this,oe,"f")&&this._emit("messageDone",e.data),x(this,oe,void 0,"f")}},Co=function(e){let t=c(this,H,"m",ko).call(this,e);switch(x(this,Zr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==c(this,ks,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(c(this,ee,"f")&&this._emit("toolCallDone",c(this,ee,"f")),x(this,ks,o.index,"f"),x(this,ee,t.step_details.tool_calls[o.index],"f"),c(this,ee,"f")&&this._emit("toolCallCreated",c(this,ee,"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,Zr,void 0,"f"),e.data.step_details.type=="tool_calls"&&c(this,ee,"f")&&(this._emit("toolCallDone",c(this,ee,"f")),x(this,ee,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},So=function(e){c(this,wn,"f").push(e),this._emit("event",e)},ko=function(e){switch(e.event){case"thread.run.step.created":return c(this,he,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=c(this,he,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=Qe.accumulateDelta(t,r.delta);c(this,he,"f")[e.data.id]=n}return c(this,he,"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,he,"f")[e.data.id]=e.data;break}if(c(this,he,"f")[e.data.id])return c(this,he,"f")[e.data.id];throw new Error("No snapshot available")},$o=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];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 u=t.content[o.index];t.content[o.index]=c(this,H,"m",Eo).call(this,o,u)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Eo=function(e,t){return Qe.accumulateDelta(t,e)},Oo=function(e){switch(x(this,Ss,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,Ze,e.data,"f"),c(this,ee,"f")&&(this._emit("toolCallDone",c(this,ee,"f")),x(this,ee,void 0,"f"));break;case"thread.run.cancelling":break}};var et=class extends a{constructor(){super(...arguments),this.steps=new hr(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(i`/threads/${n}/runs/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}`,{body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/threads/${e}/runs`,S,{query:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(i`/threads/${n}/runs/${e}/cancel`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=d([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:u}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=u.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ue(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(i`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return ye.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};et.Steps=hr;var Ne=class extends a{constructor(){super(...arguments),this.runs=new et(this._client),this.messages=new pr(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,r){return this._client.post(i`/threads/${e}`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.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 r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return ye.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ne.Runs=et;Ne.Messages=pr;var re=class extends a{constructor(){super(...arguments),this.realtime=new Oe(this._client),this.responses=new Te(this._client),this.chatkit=new ve(this._client),this.assistants=new nr(this._client),this.threads=new Ne(this._client)}};re.Realtime=Oe;re.Responses=Te;re.ChatKit=ve;re.Assistants=nr;re.Threads=Ne;var tt=class extends a{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}};var mr=class extends a{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}/content`,{...r,headers:d([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var rt=class extends a{constructor(){super(...arguments),this.content=new mr(this._client)}create(e,t,r){return this._client.post(i`/containers/${e}/files`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(i`/containers/${n}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/containers/${e}/files`,S,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(i`/containers/${n}/files/${e}`,{...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};rt.Content=mr;var je=class extends a{constructor(){super(...arguments),this.files=new rt(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}})}};je.Files=rt;var fr=class extends a{create(e,t,r){let{include:n,...o}=t;return this._client.post(i`/conversations/${e}/items`,{query:{include:n},body:o,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(i`/conversations/${n}/items/${e}`,{query:o,...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/conversations/${e}/items`,E,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(i`/conversations/${n}/items/${e}`,{...r,__security:{bearerAuth:!0}})}};var Le=class extends a{constructor(){super(...arguments),this.items=new fr(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,r){return this._client.post(i`/conversations/${e}`,{body:t,...r,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(i`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}};Le.Items=fr;var st=class extends a{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&L(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 r?o:(L(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(u=>(u&&u.data&&u.data.forEach(l=>{let m=l.embedding;l.embedding=xo(m)}),u)))}};var _r=class extends a{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(i`/evals/${n}/runs/${o}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(i`/evals/${n}/runs/${e}/output_items`,S,{query:o,...r,__security:{bearerAuth:!0}})}};var nt=class extends a{constructor(){super(...arguments),this.outputItems=new _r(this._client)}create(e,t,r){return this._client.post(i`/evals/${e}/runs`,{body:t,...r,__security:{bearerAuth:!0}})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/evals/${e}/runs`,S,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(i`/evals/${n}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};nt.OutputItems=_r;var Me=class extends a{constructor(){super(...arguments),this.runs=new nt(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,r){return this._client.post(i`/evals/${e}`,{body:t,...r,__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}})}};Me.Runs=nt;var ot=class extends a{create(e,t){return this._client.post("/files",V({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:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),u=await this.retrieve(e);for(;!u.status||!n.has(u.status);)if(await ue(t),u=await this.retrieve(e),Date.now()-o>r)throw new Pe({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return u}};var gr=class extends a{};var yr=class extends a{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 it=class extends a{constructor(){super(...arguments),this.graders=new yr(this._client)}};it.Graders=yr;var Ar=class extends a{create(e,t,r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,G,{body:t,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},r){return this._client.get(i`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/checkpoints/${e}/permissions`,E,{query:t,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(i`/fine_tuning/checkpoints/${n}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};var at=class extends a{constructor(){super(...arguments),this.permissions=new Ar(this._client)}};at.Permissions=Ar;var br=class extends a{list(e,t={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...r,__security:{bearerAuth:!0}})}};var ut=class extends a{constructor(){super(...arguments),this.checkpoints=new br(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={},r){return this._client.getAPIList(i`/fine_tuning/jobs/${e}/events`,S,{query:t,...r,__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}})}};ut.Checkpoints=br;var ie=class extends a{constructor(){super(...arguments),this.methods=new gr(this._client),this.jobs=new ut(this._client),this.checkpoints=new at(this._client),this.alpha=new it(this._client)}};ie.Methods=gr;ie.Jobs=ut;ie.Checkpoints=at;ie.Alpha=it;var Ir=class extends a{};var Fe=class extends a{constructor(){super(...arguments),this.graderModels=new Ir(this._client)}};Fe.GraderModels=Ir;var ct=class extends a{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post("/images/edits",V({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 lt=class extends a{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 pt=class extends a{create(e,t){return this._client.post("/moderations",{body:e,...t,__security:{bearerAuth:!0}})}};var wr=class extends a{accept(e,t,r){return this._client.post(i`/realtime/calls/${e}/accept`,{body:t,...r,headers:d([{Accept:"*/*"},r?.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,r){return this._client.post(i`/realtime/calls/${e}/refer`,{body:t,...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},r){return this._client.post(i`/realtime/calls/${e}/reject`,{body:t,...r,headers:d([{Accept:"*/*"},r?.headers]),__security:{bearerAuth:!0}})}};var Pr=class extends a{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t,__security:{bearerAuth:!0}})}};var Ae=class extends a{constructor(){super(...arguments),this.clientSecrets=new Pr(this._client),this.calls=new wr(this._client)}};Ae.ClientSecrets=Pr;Ae.Calls=wr;function vo(s,e){if(!e||!Ka(e)){let t={...s,output_parsed:null,output:s.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)};return To(s,t)&&te(t),t}return Pn(s,e)}function Pn(s,e){let t=!s.status||s.status==="completed",r=s.output.map(o=>{if(o.type==="function_call")return{...o,parsed_arguments:t?Da(e,o):null};if(o.type==="message"){let u=o.content.map(l=>l.type==="output_text"?{...l,parsed:t?Fa(e,l.text):null}:l);return{...o,content:u}}return o}),n=Object.assign({},s,{output:r});return To(s,n)&&te(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let o of n.output)if(o.type==="message"){for(let u of o.content)if(u.type==="output_text"&&u.parsed!==null)return u.parsed}return null}}),n}function Fa(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Ka(s){return!!zr(s.text?.format)}function Ua(s){return s?.$brand==="auto-parseable-tool"}function Ba(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Da(s,e){let t=Ba(s.tools??[],e.name);return{...e,...e,parsed_arguments:Ua(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function To(s,e){return!Object.getOwnPropertyDescriptor(s,"output_text")||e.output_text==null}function te(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}function jo(s,e){if(!e){if(s.type!=="response.created")throw new g(`When snapshot hasn't been set yet, expected 'response.created' event, got ${s.type}`);return No(s.response)}switch(s.type){case"response.output_item.added":{e.output.push(structuredClone(s.item)),s.item.type==="message"&&te(e);break}case"response.output_item.done":{$(e,s.output_index),e.output[s.output_index]=structuredClone(s.item),s.item.type==="message"&&te(e);break}case"response.content_part.added":{let t=$(e,s.output_index),r=t.type,n=s.part;r==="message"&&n.type!=="reasoning_text"?(t.content.push(structuredClone(n)),n.type==="output_text"&&te(e)):r==="reasoning"&&n.type==="reasoning_text"&&(t.content||(t.content=[]),t.content.push(structuredClone(n)));break}case"response.content_part.done":{let t=$(e,s.output_index),r=s.part;if(t.type==="message"&&r.type!=="reasoning_text")se(t.content,s.content_index),t.content[s.content_index]=structuredClone(r),r.type==="output_text"&&te(e);else if(t.type==="reasoning"&&r.type==="reasoning_text"){let n=t.content;if(!n)throw new g(`missing content at index ${s.content_index}`);se(n,s.content_index),n[s.content_index]=structuredClone(r)}break}case"response.output_text.delta":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.text+=s.delta,e.output_text+=s.delta}break}case"response.output_text.done":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.text=s.text,te(e)}break}case"response.output_text.annotation.added":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="output_text")throw new g(`expected content to be 'output_text', got ${r.type}`);r.annotations[s.annotation_index]=structuredClone(s.annotation)}break}case"response.refusal.delta":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="refusal")throw new g(`expected content to be 'refusal', got ${r.type}`);r.refusal+=s.delta}break}case"response.refusal.done":{let t=$(e,s.output_index);if(t.type==="message"){let r=se(t.content,s.content_index);if(r.type!=="refusal")throw new g(`expected content to be 'refusal', got ${r.type}`);r.refusal=s.refusal}break}case"response.function_call_arguments.delta":{let t=$(e,s.output_index);t.type==="function_call"&&(t.arguments+=s.delta);break}case"response.function_call_arguments.done":{let t=$(e,s.output_index);t.type==="function_call"&&(t.arguments=s.arguments);break}case"response.reasoning_text.delta":{let t=$(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=se(t.content,s.content_index);if(r.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${r.type}`);r.text+=s.delta}break}case"response.reasoning_text.done":{let t=$(e,s.output_index);if(t.type==="reasoning"){if(!t.content)throw new g(`missing content at index ${s.content_index}`);let r=se(t.content,s.content_index);if(r.type!=="reasoning_text")throw new g(`expected content to be 'reasoning_text', got ${r.type}`);r.text=s.text}break}case"response.reasoning_summary_part.added":{let t=$(e,s.output_index);t.type==="reasoning"&&t.summary.push(structuredClone(s.part));break}case"response.reasoning_summary_part.done":{let t=$(e,s.output_index);t.type==="reasoning"&&(se(t.summary,s.summary_index),t.summary[s.summary_index]=structuredClone(s.part));break}case"response.reasoning_summary_text.delta":{let t=$(e,s.output_index);if(t.type==="reasoning"){let r=se(t.summary,s.summary_index);r.text+=s.delta}break}case"response.reasoning_summary_text.done":{let t=$(e,s.output_index);if(t.type==="reasoning"){let r=se(t.summary,s.summary_index);r.text=s.text}break}case"response.custom_tool_call_input.delta":{let t=$(e,s.output_index);t.type==="custom_tool_call"&&(t.input+=s.delta);break}case"response.custom_tool_call_input.done":{let t=$(e,s.output_index);t.type==="custom_tool_call"&&(t.input=s.input);break}case"response.mcp_call_arguments.delta":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.arguments+=s.delta);break}case"response.mcp_call_arguments.done":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.arguments=s.arguments);break}case"response.code_interpreter_call_code.delta":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=(t.code??"")+s.delta);break}case"response.code_interpreter_call_code.done":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.code=s.code);break}case"response.code_interpreter_call.in_progress":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="in_progress");break}case"response.code_interpreter_call.interpreting":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="interpreting");break}case"response.code_interpreter_call.completed":{let t=$(e,s.output_index);t.type==="code_interpreter_call"&&(t.status="completed");break}case"response.file_search_call.in_progress":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="in_progress");break}case"response.file_search_call.searching":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="searching");break}case"response.file_search_call.completed":{let t=$(e,s.output_index);t.type==="file_search_call"&&(t.status="completed");break}case"response.web_search_call.in_progress":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="in_progress");break}case"response.web_search_call.searching":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="searching");break}case"response.web_search_call.completed":{let t=$(e,s.output_index);t.type==="web_search_call"&&(t.status="completed");break}case"response.image_generation_call.in_progress":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="in_progress");break}case"response.image_generation_call.generating":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="generating");break}case"response.image_generation_call.completed":{let t=$(e,s.output_index);t.type==="image_generation_call"&&(t.status="completed");break}case"response.mcp_call.in_progress":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.status="in_progress");break}case"response.mcp_call.completed":{let t=$(e,s.output_index);t.type==="mcp_call"&&(t.status="completed");break}case"response.mcp_call.failed":{let t=$(e,s.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=No(s.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:za(s)}return e}function No(s){let e=structuredClone(s);return(!Object.getOwnPropertyDescriptor(e,"output_text")||e.output_text==null)&&te(e),e}function $(s,e){let t=s.output[e];if(!t)throw new g(`missing output at index ${e}`);return t}function se(s,e){let t=s[e];if(!t)throw new g(`missing content at index ${e}`);return t}function za(s){throw new g(`Unhandled response stream event: ${JSON.stringify(s)}`)}var es,$s,ht,Es,Lo,Mo,Fo,Os=class s extends Ce{constructor(e){super(),es.add(this),$s.set(this,void 0),ht.set(this,void 0),Es.set(this,void 0),x(this,$s,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){this._listenForAbort(r?.signal),c(this,es,"m",Lo).call(this);let n,o=null;"response_id"in t?(n=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):n=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let u of n)c(this,es,"m",Mo).call(this,u,o);if(n.controller.signal?.aborted)throw new F;return c(this,es,"m",Fo).call(this)}[($s=new WeakMap,ht=new WeakMap,Es=new WeakMap,es=new WeakSet,Lo=function(){this.ended||x(this,ht,void 0,"f")},Mo=function(t,r){if(this.ended)return;let n=(u,l)=>{(r==null||l.sequence_number>r)&&this._emit(u,l)},o=jo(t,c(this,ht,"f"));switch(x(this,ht,o,"f"),n("event",t),t.type){case"response.output_text.delta":{let u=o.output[t.output_index];if(!u)throw new g(`missing output at index ${t.output_index}`);if(u.type==="message"){let l=u.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 u=o.output[t.output_index];if(!u)throw new g(`missing output at index ${t.output_index}`);u.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:u.arguments});break}default:n(t.type,t);break}},Fo=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");let t=c(this,ht,"f");if(!t)throw new g("request ended without sending any events");x(this,ht,void 0,"f");let r=qa(t,c(this,$s,"f"));return x(this,Es,r,"f"),r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,u)=>t.push({resolve:o,reject:u})).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,Es,"f");if(!e)throw new g("stream ended without producing a ChatCompletion");return e}};function qa(s,e){return vo(s,e)}var xr=class extends a{list(e,t={},r){return this._client.getAPIList(i`/responses/${e}/input_items`,S,{query:t,...r,__security:{bearerAuth:!0}})}};var Rr=class extends a{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t,__security:{bearerAuth:!0}})}};var de=class extends a{constructor(){super(...arguments),this.inputItems=new xr(this._client),this.inputTokens=new Rr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&te(r),r))}retrieve(e,t={},r){return this._client.get(i`/responses/${e}`,{query:t,...r,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(n=>("object"in n&&n.object==="response"&&te(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(r=>Pn(r,e))}stream(e,t){return Os.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}})}};de.InputItems=xr;de.InputTokens=Rr;var Cr=class extends a{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 Sr=class extends a{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}/content`,{...r,headers:d([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};var dt=class extends a{constructor(){super(...arguments),this.content=new Sr(this._client)}create(e,t={},r){return this._client.post(i`/skills/${e}/versions`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/skills/${e}/versions`,S,{query:t,...r,__security:{bearerAuth:!0}})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(i`/skills/${n}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};dt.Content=Sr;var be=class extends a{constructor(){super(...arguments),this.content=new Cr(this._client),this.versions=new dt(this._client)}create(e={},t){return this._client.post("/skills",Re({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,r){return this._client.post(i`/skills/${e}`,{body:t,...r,__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}})}};be.Content=Cr;be.Versions=dt;var kr=class extends a{create(e,t,r){return this._client.post(i`/uploads/${e}/parts`,V({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Ke=class extends a{constructor(){super(...arguments),this.parts=new kr(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,r){return this._client.post(i`/uploads/${e}/complete`,{body:t,...r,__security:{bearerAuth:!0}})}};Ke.Parts=kr;var Ko=async s=>{let e=await Promise.allSettled(s),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 r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var $r=class extends a{create(e,t,r){return this._client.post(i`/vector_stores/${e}/file_batches`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/file_batches/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(i`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(i`/vector_stores/${n}/file_batches/${e}/files`,S,{query:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,r){let n=d([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:u}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=u.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ue(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},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,u=Math.min(o,t.length),l=this._client,m=t.values(),p=[...r];async function I(f){for(let b of f){let y=await l.files.create({file:b,purpose:"assistants"},n);p.push(y.id)}}let h=Array(u).fill(m).map(I);return await Ko(h),await this.createAndPoll(e,{file_ids:p})}};var Er=class extends a{create(e,t,r){return this._client.post(i`/vector_stores/${e}/files`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(i`/vector_stores/${n}/files/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(i`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}list(e,t={},r){return this._client.getAPIList(i`/vector_stores/${e}/files`,S,{query:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(i`/vector_stores/${n}/files/${e}`,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=d([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),u=o.data;switch(u.status){case"in_progress":let l=5e3;if(r?.pollIntervalMs)l=r.pollIntervalMs;else{let m=o.response.headers.get("openai-poll-after-ms");if(m){let p=parseInt(m);isNaN(p)||(l=p)}}await ue(l);break;case"failed":case"completed":return u}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(i`/vector_stores/${n}/files/${e}/content`,G,{...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};var Ie=class extends a{constructor(){super(...arguments),this.files=new Er(this._client),this.fileBatches=new $r(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,r){return this._client.post(i`/vector_stores/${e}`,{body:t,...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.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,r){return this._client.getAPIList(i`/vector_stores/${e}/search`,G,{body:t,method:"post",...r,headers:d([{"OpenAI-Beta":"assistants=v2"},r?.headers]),__security:{bearerAuth:!0}})}};Ie.Files=Er;Ie.FileBatches=$r;var mt=class extends a{create(e,t){return this._client.post("/videos",V({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",E,{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",V({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},r){return this._client.get(i`/videos/${e}/content`,{query:t,...r,headers:d([{Accept:"application/binary"},r?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post("/videos/edits",V({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post("/videos/extensions",V({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,r){return this._client.post(i`/videos/${e}/remix`,Re({body:t,...r,__security:{bearerAuth:!0}},this._client))}};var Or,Uo,vs,ft=class extends a{constructor(){super(...arguments),Or.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=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,Or,"m",Uo).call(this,r);let o=d([t]).values,u=c(this,Or,"m",vs).call(this,o,"webhook-signature"),l=c(this,Or,"m",vs).call(this,o,"webhook-timestamp"),m=c(this,Or,"m",vs).call(this,o,"webhook-id"),p=parseInt(l,10);if(isNaN(p))throw new ae("Invalid webhook timestamp format");let I=Math.floor(Date.now()/1e3);if(I-p>n)throw new ae("Webhook timestamp is too old");if(p>I+n)throw new ae("Webhook timestamp is too new");let h=u.split(" ").map(A=>A.startsWith("v1,")?A.substring(3):A),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),b=m?`${m}.${l}.${e}`:`${l}.${e}`,y=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let A of h)try{let w=Buffer.from(A,"base64");if(await crypto.subtle.verify("HMAC",y,w,new TextEncoder().encode(b)))return}catch{continue}throw new ae("The given webhook signature does not match the expected signature")}};Or=new WeakSet,Uo=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")},vs=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Do=Symbol.for("openai.node.providerDefinitions.v1"),zo=globalThis,qo=zo[Do],Wo=qo??new WeakMap;qo||Object.defineProperty(zo,Do,{value:Wo});function Ho(s){let e=Wo.get(s);if(!e)throw new Error("Invalid provider. Providers must be created with createProvider().");return e.configure()}var xn,Rn,ts,Jo,Za="workload-identity-auth",C=class{constructor(e={}){xn.add(this),ts.set(this,void 0),this.completions=new tt(this),this.chat=new ke(this),this.embeddings=new st(this),this.files=new ot(this),this.images=new ct(this),this.audio=new pe(this),this.moderations=new pt(this),this.models=new lt(this),this.fineTuning=new ie(this),this.graders=new Fe(this),this.vectorStores=new Ie(this),this.webhooks=new ft(this),this.beta=new re(this),this.batches=new Ve(this),this.uploads=new Ke(this),this.admin=new Ee(this),this.responses=new de(this),this.realtime=new Ae(this),this.conversations=new Le(this),this.evals=new Me(this),this.containers=new je(this),this.skills=new be(this),this.videos=new mt(this);let t=e.provider;if(t){let A=["apiKey","adminAPIKey","workloadIdentity","baseURL"].filter(w=>e[w]!=null);if(A.length)throw new g(`The \`provider\` option cannot be used with ${A.map(w=>`\`${w}\``).join(", ")}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:r=t?null:ne("OPENAI_BASE_URL"),apiKey:n=t?null:ne("OPENAI_API_KEY")??null,adminAPIKey:o=t?null:ne("OPENAI_ADMIN_KEY")??null,organization:u=t?null:ne("OPENAI_ORG_ID")??null,project:l=t?null:ne("OPENAI_PROJECT_ID")??null,webhookSecret:m=ne("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:p,...I}=e,h=t?Ho(t):void 0,f={apiKey:n,adminAPIKey:o,organization:u,project:l,webhookSecret:m,workloadIdentity:p,provider:t,...I,baseURL:h?.baseURL??(r||"https://api.openai.com/v1")};if(n&&p)throw new g("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!h&&!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(!f.dangerouslyAllowBrowser&&Bn())throw new g(`It looks like you're running in a browser-like environment.
|
|
17
17
|
|
|
18
18
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
19
19
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -22,5 +22,5 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
22
22
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
23
23
|
|
|
24
24
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
25
|
-
`);this.baseURL=f.baseURL,this.timeout=f.timeout??
|
|
26
|
-
`)){let k=I.indexOf(":");k>=0&&(A[I.substring(0,k).trim()]=I.substring(k+1).trim())}f.defaultHeaders=h([A,f.defaultHeaders])}this._options=f,this._provider=d,p&&(this._workloadIdentityAuth=new ds(p,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=u,this.project=l,this.webhookSecret=m}withOptions(e){let t=this._options.provider,r=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 r&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,r!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&r.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 h([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return h([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return h([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return h([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Yn(e)}getUserAgent(){return`${this.constructor.name}/JS ${xe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ue()}`}makeStatusError(e,t,r,n){return T.generate(e,t,r,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(r){throw r instanceof g?r:new g(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}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,r){let n=!c(this,In,"m",Wo).call(this)&&r||this.baseURL,o=On(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),u=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!Us(u)||!Us(l))&&(t={...l,...u,...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:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ze(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:u,url:l,timeout:m}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(u,{url:l,options:n}),await this._provider?.prepareRequest?.(u,{url:l,options:n});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),w=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(L(this).debug(`[${p}] sending request`,me({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:u.headers})),n.signal?.aborted)throw new K;let f=n.__security??{bearerAuth:!0},b=new AbortController,y=await this.fetchWithAuth(l,u,m,b,f).catch(Nr),A=Date.now();if(y instanceof globalThis.Error){let _=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new K;let P=Tr(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(t)return L(this).info(`[${p}] connection ${P?"timed out":"failed"} - ${_}`),L(this).debug(`[${p}] connection ${P?"timed out":"failed"} (${_})`,me({retryOfRequestLogID:r,url:l,durationMs:A-d,message:y.message})),this.retryRequest(n,t,r??p);throw L(this).info(`[${p}] connection ${P?"timed out":"failed"} - error; no more retries left`),L(this).debug(`[${p}] connection ${P?"timed out":"failed"} (error; no more retries left)`,me({retryOfRequestLogID:r,url:l,durationMs:A-d,message:y.message})),y instanceof Be||y instanceof jr?y:P?new Pe:new Ie({message:Qa(y),cause:y})}let I=[...y.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,P])=>", "+_+": "+JSON.stringify(P)).join(""),k=`[${p}${w}${I}] ${u.method} ${l} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${A-d}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await zs(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??p);let _=await this.shouldRetry(y);if(t&&_){let j=`retrying, ${t} attempts remaining`;return await zs(y.body),L(this).info(`${k} - ${j}`),L(this).debug(`[${p}] response error (${j})`,me({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:A-d})),this.retryRequest(n,t,r??p,y.headers)}let P=_?"error; no more retries left":"error; not retryable";L(this).info(`${k} - ${P}`);let R=await y.text().catch(j=>Nr(j).message),O=jn(R),v=O?void 0:R;throw L(this).debug(`[${p}] response error (${P})`,me({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,message:v,durationMs:Date.now()-d})),this.makeStatusError(y.status,O,v,y.headers)}return L(this).info(k),L(this).debug(`[${p}] response start`,me({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:A-d})),{response:y,options:n,controller:b,requestLogID:p,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Ur(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let l=t.headers,m=l.get("Authorization");if(!m||m===`Bearer ${Ya}`){let p=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${p}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:u,...l}=t||{},m=this._makeAbort(n);o&&o.addEventListener("abort",m,{once:!0});let p=setTimeout(m,r),w=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,d={signal:n.signal,...w?{duplex:"half"}:{},method:"GET",...l};u&&(d.method=u.toUpperCase());try{return await this.fetch.call(void 0,e,d)}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,r,n){let o,u=n?.get("retry-after-ms");if(u){let m=parseFloat(u);Number.isNaN(m)||(o=m)}let l=n?.get("retry-after");if(l&&!o){let m=parseFloat(l);Number.isNaN(m)?o=Date.parse(l)-Date.now():o=m*1e3}if(o===void 0){let m=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,m)}return await ue(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,u=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return u*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:u,defaultBaseURL:l}=r,m=this.buildURL(o,u,l);"timeout"in r&&Nn("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:w,isStreamingBody:d}=this.buildBody({options:r});d&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:f,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&w instanceof globalThis.ReadableStream&&{duplex:"half"},...w&&{body:w},...this.fetchOptions??{},...r.fetchOptions??{}},url:m,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let u=h([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))}:{},...Un(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(u,e.__security??{bearerAuth:!0}),u.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...c(this,ts,"f").call(this,{body:t,headers:h([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=h([r]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,u=!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:!u}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:is(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,ts,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};Pn=S,ts=new WeakMap,In=new WeakSet,Wo=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};S.OpenAI=Pn;S.DEFAULT_TIMEOUT=6e5;S.OpenAIError=g;S.APIError=T;S.APIConnectionError=Ie;S.APIConnectionTimeoutError=Pe;S.APIUserAbortError=K;S.NotFoundError=At;S.ConflictError=bt;S.RateLimitError=It;S.BadRequestError=_t;S.AuthenticationError=gt;S.InternalServerError=Pt;S.PermissionDeniedError=yt;S.UnprocessableEntityError=wt;S.InvalidWebhookSignatureError=ae;S.toFile=ms;S.Completions=tt;S.Chat=ke;S.Embeddings=st;S.Files=ot;S.Images=ct;S.Audio=pe;S.Moderations=pt;S.Models=lt;S.FineTuning=ie;S.Graders=Ke;S.VectorStores=we;S.Webhooks=ft;S.Beta=re;S.Batches=Ve;S.Uploads=Fe;S.Admin=Ee;S.Responses=he;S.Realtime=Ae;S.Conversations=Le;S.Evals=Me;S.Containers=je;S.Skills=be;S.Videos=mt;function Qa(s){if(Za(s))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 Za(s){let e=s;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var Ts=Sn({module:"llm"});var Ho=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=Ks(e);if(!r)throw new ss("OpenAI API key not found, set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Ms(e)}async*stream(e,t,r){let n=eu(e.getMessages()),o=[];o.push({role:"system",content:this.systemPrompt});for(let f of n)o.push(f);let u=t.map(f=>{let b=f.input_schema;return{type:"function",name:f.name,description:f.description,parameters:b,strict:!1}}),l={model:this.model,input:o,stream:!0,max_output_tokens:this.maxOutputTokens,...u.length>0?{tools:u}:{}},m=0,p=0,w=0,d=0;try{let f=await this.client.responses.create(l,{...r?{signal:r}:{}}),b="",y="",A="",I="",k="";for await(let _ of f)if(_.type==="response.output_text.delta")yield{type:"text_delta",text:_.delta};else if(_.type==="response.reasoning_summary_text.delta")k+=_.delta,yield{type:"thinking_delta",text:_.delta};else if(_.type==="response.reasoning_summary_text.done")yield{type:"thinking_complete",thinking:k,signature:I};else if(_.type==="response.function_call_arguments.delta")A+=_.delta,yield{type:"tool_call_delta",text:_.delta};else if(_.type==="response.output_item.added")_.item.type==="function_call"?(b=_.item.name,y=_.item.call_id,A="",yield{type:"tool_call_start",toolName:b,toolId:y}):_.item.type==="reasoning"&&(I=_.item.id??"",k="");else if(_.type==="response.output_item.done"){if(_.item.type==="function_call"&&b){let P={};if(A)try{let R=JSON.parse(A);P=js(R)?rs(R):{[Or]:A}}catch(R){Ts.error({err:R},"llm operation failed"),P={[Or]:A}}yield{type:"tool_call_complete",toolId:y,toolName:b,arguments:P},b="",y="",A=""}}else if(_.type==="response.completed"){let P=_.response.usage;P&&(p=P.output_tokens,w=P.input_tokens_details.cached_tokens,m=Math.max(0,P.input_tokens-w));let R="end_turn",O=_.response;O.status==="incomplete"&&O.incomplete_details?.reason==="max_output_tokens"&&(R="max_tokens"),yield{type:"stream_end",stopReason:R,usage:{inputTokens:m,outputTokens:p,cacheReadInputTokens:w,cacheCreationInputTokens:d}}}}catch(f){throw Ts.error({err:f},"llm operation failed"),Xo(f)}}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}};function eu(s){let e=[];for(let t of s){if(t.thinkingBlocks)for(let r of t.thinkingBlocks)e.push({type:"reasoning",id:r.signature,summary:[{type:"summary_text",text:r.thinking}]});if(t.toolUses&&t.toolUses.length>0){t.content&&e.push({role:"assistant",content:t.content});for(let r of t.toolUses)e.push({type:"function_call",name:r.toolName,call_id:r.toolUseId,arguments:JSON.stringify(r.arguments)})}else if(t.toolResults&&t.toolResults.length>0)for(let r of t.toolResults)e.push({type:"function_call_output",call_id:r.toolUseId,output:r.content});else e.push({role:t.role,content:t.content})}return e}function tu(s){return/context_length_exceeded/i.test(s)||/maximum\scontext\slength/i.test(s)||/prompts?\s+too\s+long/i.test(s)}function By(s){let e=[];for(let t of s)if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:t.content||null,tool_calls:t.toolUses.map(r=>({id:r.toolUseId,type:"function",function:{name:r.toolName,arguments:JSON.stringify(r.arguments)}}))});else if(t.toolResults&&t.toolResults.length>0)for(let r of t.toolResults)e.push({role:"tool",tool_call_id:r.toolUseId,content:r.content});else t.role==="assistant"?e.push({role:"assistant",content:t.content}):e.push({role:t.role==="system"?"system":"user",content:t.content});return e}var Jo=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=Ks(e);if(!r)throw new ss("OpenAI API key not found. Set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new S({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Ms(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,r){let n=[{role:"system",content:this.systemPrompt},...ru(e.getMessages())],o=t.map(d=>({type:"function",function:{name:d.name,description:d.description,arguments:d.input_schema}})),u={model:this.model,messages:n,stream:!0,stream_options:{include_usage:!0},max_tokens:this.maxOutputTokens,...o.length>0?{tools:o}:{}},l=0,m=0,p=0,w=0;try{let d=await this.client.chat.completions.create(u,{...r?{signal:r}:{}}),f=new Map,b=null,y="";for await(let I of d){if(I.usage&&(m=I.usage.completion_tokens??0,p=I.usage.prompt_tokens_details?.cached_tokens??0,l=Math.max(0,(I.usage.prompt_tokens??0)-p)),I.choices.length===0)continue;let k=I.choices[0].delta;k.content&&(yield{type:"text_delta",text:k.content});let _=Cn(rs(k),"reasoning_content");if(_&&(y+=_,yield{type:"thinking_delta",text:_}),k.tool_calls)for(let P of k.tool_calls){f.has(P.index)||(f.set(P.index,{id:P.id??"",name:P.function?.name??"",args:""}),P.id&&(yield{type:"tool_call_start",toolName:P.function?.name??"",toolId:P.id??""}));let R=f.get(P.index);R&&(P.id&&(R.id=P.id),P.function?.name&&(R.name=P.function.name),P.function?.arguments&&(R.args+=P.function.arguments,yield{type:"tool_call_delta",text:P.function.arguments}))}if(I.choices[0].finish_reason){b=I.choices[0].finish_reason,y&&(yield{type:"thinking_complete",thinking:y,signature:""},y="");for(let P of f.values()){let R={},O=P.args;if(O){try{let v=JSON.parse(O);R=js(v)?rs(v):{[Or]:O}}catch(v){Ts.error({err:v},"llm operation failed"),R={[Or]:O}}yield{type:"tool_call_complete",toolName:P.name,toolId:P.id,arguments:R}}}}}let A;b==="length"?A="max_tokens":b==="tool_calls"||f.size>0?A="tool_use":A="end_turn",yield{type:"stream_end",stopReason:A,usage:{inputTokens:l,outputTokens:m,cacheReadInputTokens:p,cacheCreationInputTokens:w}}}catch(d){throw Ts.error({err:d},"llm operation failed"),Xo(d)}}};function Xo(s){return s instanceof S.APIError?s.status===413||s.status===400&&tu(s.message)?new vn(`Context Too Long: ${s.message}`):s.status===401?new ss(`Invalid API key: ${s.message}`):s.status===429?new $n("Rate limit error, please wait."):new kn(`OpenAI API error (${Ls(s.status)}): ${s.message}`):new En(`Network error: ${s instanceof Error?s.message:Ls(s)}`)}function ru(s){let e=[];for(let t of s){let r=t.thinkingBlocks?.map(n=>n.thinking).join("")??"";if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:t.content||null,tool_calls:t.toolUses.map(n=>({id:n.toolUseId,type:"function",function:{name:n.toolName,arguments:JSON.stringify(n.arguments)},...r?{reasoning_content:r}:{}}))});else if(t.toolResults&&t.toolResults.length>0)for(let n of t.toolResults)e.push({role:"tool",tool_call_id:n.toolUseId,content:n.content});else t.role==="assistant"?e.push({role:"assistant",content:t.content,...r?{reasoning_content:r}:{}}):e.push({role:t.role==="system"?"system":"user",content:t.content})}return e}export{Ho as OpenAIClient,Jo as OpenAICompatClient,By as buildChatCompletionMessage,ru as buildChatCompletionMessages,eu as buildOpenAIInput};
|
|
25
|
+
`);this.baseURL=f.baseURL,this.timeout=f.timeout??Rn.DEFAULT_TIMEOUT,this.logger=f.logger??console;let b="warn";this.logLevel=b,this.logLevel=Zs(f.logLevel,"ClientOptions.logLevel",this)??Zs(ne("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??b,this.fetchOptions=f.fetchOptions,this.maxRetries=f.maxRetries??2,this.fetch=f.fetch??os(),x(this,ts,qn,"f");let y=t?void 0:ne("OPENAI_CUSTOM_HEADERS");if(y){let A={};for(let w of y.split(`
|
|
26
|
+
`)){let k=w.indexOf(":");k>=0&&(A[w.substring(0,k).trim()]=w.substring(k+1).trim())}f.defaultHeaders=d([A,f.defaultHeaders])}this._options=f,this._provider=h,p&&(this._workloadIdentityAuth=new hs(p,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=o,this.organization=u,this.project=l,this.webhookSecret=m}withOptions(e){let t=this._options.provider,r=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 r&&(delete n.apiKey,delete n.adminAPIKey,delete n.workloadIdentity,delete n.baseURL,r!==t&&(delete n.organization,delete n.project,delete n.defaultHeaders)),new this.constructor({...n,...e,provider:r})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(t.has("authorization")||t.has("api-key"))&&!(this._workloadIdentityAuth&&r.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 Zn(e)}getUserAgent(){return`${this.constructor.name}/JS ${xe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ue()}`}makeStatusError(e,t,r,n){return T.generate(e,t,r,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(r){throw r instanceof g?r:new g(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}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,r){let n=!c(this,xn,"m",Jo).call(this)&&r||this.baseURL,o=Nn(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),u=this.defaultQuery(),l=Object.fromEntries(o.searchParams);return(!Ds(u)||!Ds(l))&&(t={...l,...u,...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:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new ze(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:u,url:l,timeout:m}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(u,{url:l,options:n}),await this._provider?.prepareRequest?.(u,{url:l,options:n});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),I=r===void 0?"":`, retryOf: ${r}`,h=Date.now();if(L(this).debug(`[${p}] sending request`,me({retryOfRequestLogID:r,method:n.method,url:l,options:n,headers:u.headers})),n.signal?.aborted)throw new F;let f=n.__security??{bearerAuth:!0},b=new AbortController,y=await this.fetchWithAuth(l,u,m,b,f).catch(Nr),A=Date.now();if(y instanceof globalThis.Error){let _=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new F;let P=Tr(y)||/timed? ?out/i.test(String(y)+("cause"in y?String(y.cause):""));if(t)return L(this).info(`[${p}] connection ${P?"timed out":"failed"} - ${_}`),L(this).debug(`[${p}] connection ${P?"timed out":"failed"} (${_})`,me({retryOfRequestLogID:r,url:l,durationMs:A-h,message:y.message})),this.retryRequest(n,t,r??p);throw L(this).info(`[${p}] connection ${P?"timed out":"failed"} - error; no more retries left`),L(this).debug(`[${p}] connection ${P?"timed out":"failed"} (error; no more retries left)`,me({retryOfRequestLogID:r,url:l,durationMs:A-h,message:y.message})),y instanceof Be||y instanceof jr?y:P?new Pe:new we({message:eu(y),cause:y})}let w=[...y.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,P])=>", "+_+": "+JSON.stringify(P)).join(""),k=`[${p}${I}${w}] ${u.method} ${l} ${y.ok?"succeeded":"failed"} with status ${y.status} in ${A-h}ms`;if(!y.ok){if(y.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!n.__metadata?.hasStreamingBody&&!n.__metadata?.workloadIdentityTokenRefreshed)return await Ws(y.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...n,__metadata:{...n.__metadata,workloadIdentityTokenRefreshed:!0}},t,r??p);let _=await this.shouldRetry(y);if(t&&_){let j=`retrying, ${t} attempts remaining`;return await Ws(y.body),L(this).info(`${k} - ${j}`),L(this).debug(`[${p}] response error (${j})`,me({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:A-h})),this.retryRequest(n,t,r??p,y.headers)}let P=_?"error; no more retries left":"error; not retryable";L(this).info(`${k} - ${P}`);let R=await y.text().catch(j=>Nr(j).message),v=Mn(R),O=v?void 0:R;throw L(this).debug(`[${p}] response error (${P})`,me({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,message:O,durationMs:Date.now()-h})),this.makeStatusError(y.status,v,O,y.headers)}return L(this).info(k),L(this).debug(`[${p}] response start`,me({retryOfRequestLogID:r,url:y.url,status:y.status,headers:y.headers,durationMs:A-h})),{response:y,options:n,controller:b,requestLogID:p,retryOfRequestLogID:r,startTime:h}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new Ur(this,r,e)}async fetchWithAuth(e,t,r,n,o={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&o.bearerAuth){let l=t.headers,m=l.get("Authorization");if(!m||m===`Bearer ${Za}`){let p=await this._workloadIdentityAuth.getToken();l.set("Authorization",`Bearer ${p}`)}}return await this.fetchWithTimeout(e,t,r,n)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:u,...l}=t||{},m=this._makeAbort(n);o&&o.addEventListener("abort",m,{once:!0});let p=setTimeout(m,r),I=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,h={signal:n.signal,...I?{duplex:"half"}:{},method:"GET",...l};u&&(h.method=u.toUpperCase());try{return await this.fetch.call(void 0,e,h)}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,r,n){let o,u=n?.get("retry-after-ms");if(u){let m=parseFloat(u);Number.isNaN(m)||(o=m)}let l=n?.get("retry-after");if(l&&!o){let m=parseFloat(l);Number.isNaN(m)?o=Date.parse(l)-Date.now():o=m*1e3}if(o===void 0){let m=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,m)}return await ue(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,u=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return u*l*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:u,defaultBaseURL:l}=r,m=this.buildURL(o,u,l);"timeout"in r&&Ln("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:I,isStreamingBody:h}=this.buildBody({options:r});h&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});let f=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:f,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&I instanceof globalThis.ReadableStream&&{duplex:"half"},...I&&{body:I},...this.fetchOptions??{},...r.fetchOptions??{}},url:m,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let u=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))}:{},...Dn(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this._provider||this.validateHeaders(u,e.__security??{bearerAuth:!0}),u.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:r}=e;if(!t)return t===void 0&&"body"in e?{...c(this,ts,"f").call(this,{body:t,headers:d([r])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let n=d([r]),o=typeof globalThis.ReadableStream<"u"&&t instanceof globalThis.ReadableStream,u=!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:!u}:typeof t=="object"&&(Symbol.asyncIterator in t||Symbol.iterator in t&&"next"in t&&typeof t.next=="function")?{bodyHeaders:void 0,body:is(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,ts,"f").call(this,{body:t,headers:n}),isStreamingBody:!1}}};Rn=C,ts=new WeakMap,xn=new WeakSet,Jo=function(){return this._provider!==void 0||this.baseURL!=="https://api.openai.com/v1"};C.OpenAI=Rn;C.DEFAULT_TIMEOUT=6e5;C.OpenAIError=g;C.APIError=T;C.APIConnectionError=we;C.APIConnectionTimeoutError=Pe;C.APIUserAbortError=F;C.NotFoundError=At;C.ConflictError=bt;C.RateLimitError=wt;C.BadRequestError=_t;C.AuthenticationError=gt;C.InternalServerError=Pt;C.PermissionDeniedError=yt;C.UnprocessableEntityError=It;C.InvalidWebhookSignatureError=ae;C.toFile=ms;C.Completions=tt;C.Chat=ke;C.Embeddings=st;C.Files=ot;C.Images=ct;C.Audio=pe;C.Moderations=pt;C.Models=lt;C.FineTuning=ie;C.Graders=Fe;C.VectorStores=Ie;C.Webhooks=ft;C.Beta=re;C.Batches=Ve;C.Uploads=Ke;C.Admin=Ee;C.Responses=de;C.Realtime=Ae;C.Conversations=Le;C.Evals=Me;C.Containers=je;C.Skills=be;C.Videos=mt;function eu(s){if(tu(s))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 tu(s){let e=s;for(let t=0;t<8&&e&&typeof e=="object";t++){let r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var Ts=kn({module:"llm"});var Xo=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=Us(e);if(!r)throw new ss("OpenAI API key not found, set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new C({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Ks(e)}async*stream(e,t,r){let n=ru(Fs(e.getMessages())),o=[];o.push({role:"system",content:this.systemPrompt});for(let f of n)o.push(f);let u=t.map(f=>{let b=f.input_schema;return{type:"function",name:f.name,description:f.description,parameters:b,strict:!1}}),l={model:this.model,input:o,stream:!0,max_output_tokens:this.maxOutputTokens,...u.length>0?{tools:u}:{}},m=0,p=0,I=0,h=0;try{let f=await this.client.responses.create(l,{...r?{signal:r}:{}}),b="",y="",A="",w="",k="";for await(let _ of f)if(_.type==="response.output_text.delta")yield{type:"text_delta",text:_.delta};else if(_.type==="response.reasoning_summary_text.delta")k+=_.delta,yield{type:"thinking_delta",text:_.delta};else if(_.type==="response.reasoning_summary_text.done")yield{type:"thinking_complete",thinking:k,signature:w};else if(_.type==="response.function_call_arguments.delta")A+=_.delta,yield{type:"tool_call_delta",text:_.delta};else if(_.type==="response.output_item.added")_.item.type==="function_call"?(b=_.item.name,y=_.item.call_id,A="",yield{type:"tool_call_start",toolName:b,toolId:y}):_.item.type==="reasoning"&&(w=_.item.id??"",k="");else if(_.type==="response.output_item.done"){if(_.item.type==="function_call"&&b){let P={};if(A)try{let R=JSON.parse(A);P=Ls(R)?rs(R):{[vr]:A}}catch(R){Ts.error({err:R},"llm operation failed"),P={[vr]:A}}yield{type:"tool_call_complete",toolId:y,toolName:b,arguments:P},b="",y="",A=""}}else if(_.type==="response.completed"){let P=_.response.usage;P&&(p=P.output_tokens,I=P.input_tokens_details.cached_tokens,m=Math.max(0,P.input_tokens-I));let R="end_turn",v=_.response;v.status==="incomplete"&&v.incomplete_details?.reason==="max_output_tokens"&&(R="max_tokens"),yield{type:"stream_end",stopReason:R,usage:{inputTokens:m,outputTokens:p,cacheReadInputTokens:I,cacheCreationInputTokens:h}}}}catch(f){throw Ts.error({err:f},"llm operation failed"),Vo(f)}}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}};function Ns(s){return`data:${s.mediaType};base64,${s.data}`}function ru(s){let e=[];for(let t of s){if(t.thinkingBlocks)for(let r of t.thinkingBlocks)e.push({type:"reasoning",id:r.signature,summary:[{type:"summary_text",text:r.thinking}]});if(t.toolUses&&t.toolUses.length>0){t.content&&e.push({role:"assistant",content:t.content});for(let r of t.toolUses)e.push({type:"function_call",name:r.toolName,call_id:r.toolUseId,arguments:JSON.stringify(r.arguments)})}else if(t.toolResults&&t.toolResults.length>0){let r=[];for(let n of t.toolResults)if(e.push({type:"function_call_output",call_id:n.toolUseId,output:n.content}),n.images?.length){r.push({type:"input_text",text:`[Image(s) returned by tool call ${n.toolUseId}]`});for(let o of n.images)r.push({type:"input_image",image_url:Ns(o),detail:"auto"})}r.length>0&&e.push({role:"user",content:r})}else t.role==="user"&&t.images?.length?e.push({role:"user",content:[{type:"input_text",text:t.content},...t.images.map(r=>({type:"input_image",image_url:Ns(r),detail:"auto"}))]}):e.push({role:t.role,content:t.content})}return e}function su(s){return/context_length_exceeded/i.test(s)||/maximum\scontext\slength/i.test(s)||/prompts?\s+too\s+long/i.test(s)}function qy(s){let e=[];for(let t of s)if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:t.content||null,tool_calls:t.toolUses.map(r=>({id:r.toolUseId,type:"function",function:{name:r.toolName,arguments:JSON.stringify(r.arguments)}}))});else if(t.toolResults&&t.toolResults.length>0)for(let r of t.toolResults)e.push({role:"tool",tool_call_id:r.toolUseId,content:r.content});else t.role==="assistant"?e.push({role:"assistant",content:t.content}):e.push({role:t.role==="system"?"system":"user",content:t.content});return e}var Go=class{client;model;systemPrompt;maxOutputTokens;constructor(e,t){let r=Us(e);if(!r)throw new ss("OpenAI API key not found. Set OPENAI_API_KEY in .swifty/config.y(a)ml, or via OPENAI_API_KEY env variable.");this.client=new C({apiKey:r,baseURL:e.base_url}),this.model=e.model,this.systemPrompt=t,this.maxOutputTokens=Ks(e)}setSystemPrompt(e){this.systemPrompt=e}setMaxOutputTokens(e){this.maxOutputTokens=e}async*stream(e,t,r){let n=[{role:"system",content:this.systemPrompt},...nu(Fs(e.getMessages()))],o=t.map(h=>({type:"function",function:{name:h.name,description:h.description,arguments:h.input_schema}})),u={model:this.model,messages:n,stream:!0,stream_options:{include_usage:!0},max_tokens:this.maxOutputTokens,...o.length>0?{tools:o}:{}},l=0,m=0,p=0,I=0;try{let h=await this.client.chat.completions.create(u,{...r?{signal:r}:{}}),f=new Map,b=null,y="";for await(let w of h){if(w.usage&&(m=w.usage.completion_tokens??0,p=w.usage.prompt_tokens_details?.cached_tokens??0,l=Math.max(0,(w.usage.prompt_tokens??0)-p)),w.choices.length===0)continue;let k=w.choices[0].delta;k.content&&(yield{type:"text_delta",text:k.content});let _=$n(rs(k),"reasoning_content");if(_&&(y+=_,yield{type:"thinking_delta",text:_}),k.tool_calls)for(let P of k.tool_calls){f.has(P.index)||(f.set(P.index,{id:P.id??"",name:P.function?.name??"",args:""}),P.id&&(yield{type:"tool_call_start",toolName:P.function?.name??"",toolId:P.id??""}));let R=f.get(P.index);R&&(P.id&&(R.id=P.id),P.function?.name&&(R.name=P.function.name),P.function?.arguments&&(R.args+=P.function.arguments,yield{type:"tool_call_delta",text:P.function.arguments}))}if(w.choices[0].finish_reason){b=w.choices[0].finish_reason,y&&(yield{type:"thinking_complete",thinking:y,signature:""},y="");for(let P of f.values()){let R={},v=P.args;if(v){try{let O=JSON.parse(v);R=Ls(O)?rs(O):{[vr]:v}}catch(O){Ts.error({err:O},"llm operation failed"),R={[vr]:v}}yield{type:"tool_call_complete",toolName:P.name,toolId:P.id,arguments:R}}}}}let A;b==="length"?A="max_tokens":b==="tool_calls"||f.size>0?A="tool_use":A="end_turn",yield{type:"stream_end",stopReason:A,usage:{inputTokens:l,outputTokens:m,cacheReadInputTokens:p,cacheCreationInputTokens:I}}}catch(h){throw Ts.error({err:h},"llm operation failed"),Vo(h)}}};function Vo(s){return s instanceof C.APIError?s.status===413||s.status===400&&su(s.message)?new Tn(`Context Too Long: ${s.message}`):s.status===401?new ss(`Invalid API key: ${s.message}`):s.status===429?new On("Rate limit error, please wait."):new En(`OpenAI API error (${Ms(s.status)}): ${s.message}`):new vn(`Network error: ${s instanceof Error?s.message:Ms(s)}`)}function nu(s){let e=[];for(let t of s){let r=t.thinkingBlocks?.map(n=>n.thinking).join("")??"";if(t.toolUses&&t.toolUses.length>0)e.push({role:"assistant",content:t.content||null,tool_calls:t.toolUses.map(n=>({id:n.toolUseId,type:"function",function:{name:n.toolName,arguments:JSON.stringify(n.arguments)},...r?{reasoning_content:r}:{}}))});else if(t.toolResults&&t.toolResults.length>0){let n=[];for(let o of t.toolResults)if(e.push({role:"tool",tool_call_id:o.toolUseId,content:o.content}),o.images?.length){n.push({type:"text",text:`[Image(s) returned by tool call ${o.toolUseId}]`});for(let u of o.images)n.push({type:"image_url",image_url:{url:Ns(u)}})}n.length>0&&e.push({role:"user",content:n})}else t.role==="assistant"?e.push({role:"assistant",content:t.content,...r?{reasoning_content:r}:{}}):t.role==="user"&&t.images?.length?e.push({role:"user",content:[{type:"text",text:t.content},...t.images.map(n=>({type:"image_url",image_url:{url:Ns(n)}}))]}):e.push({role:t.role==="system"?"system":"user",content:t.content})}return e}export{Xo as OpenAIClient,Go as OpenAICompatClient,qy as buildChatCompletionMessage,nu as buildChatCompletionMessages,ru as buildOpenAIInput};
|