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