@agentica/chat 0.16.0 → 0.16.1

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.
@@ -1,115 +0,0 @@
1
- import{j as I,o as os,r as Ue,T as bt}from"../client-CpqWRuez.js";import{_ as xt,F as ls,T as xn,R as cs,c as An,d as Sn,B as us}from"../index-OZsaCgkq.js";import{v as ds,A as hs,b as We,_ as Je,c as fs}from"../_isFormatUri-D5w_moxp.js";import{D as ms}from"../Divider-B8tz1oz7.js";const Tt="RFC3986",Ft={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},ps="RFC1738",gs=Array.isArray,z=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),At=1024,_s=(r,e,t,n,s)=>{if(r.length===0)return r;let a=r;if(typeof r=="symbol"?a=Symbol.prototype.toString.call(r):typeof r!="string"&&(a=String(r)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<a.length;l+=At){const u=a.length>=At?a.slice(l,l+At):a,d=[];for(let o=0;o<u.length;++o){let c=u.charCodeAt(o);if(c===45||c===46||c===95||c===126||c>=48&&c<=57||c>=65&&c<=90||c>=97&&c<=122||s===ps&&(c===40||c===41)){d[d.length]=u.charAt(o);continue}if(c<128){d[d.length]=z[c];continue}if(c<2048){d[d.length]=z[192|c>>6]+z[128|c&63];continue}if(c<55296||c>=57344){d[d.length]=z[224|c>>12]+z[128|c>>6&63]+z[128|c&63];continue}o+=1,c=65536+((c&1023)<<10|u.charCodeAt(o)&1023),d[d.length]=z[240|c>>18]+z[128|c>>12&63]+z[128|c>>6&63]+z[128|c&63]}i+=d.join("")}return i};function ys(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Cn(r,e){if(gs(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const ws=Object.prototype.hasOwnProperty,Vn={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Y=Array.isArray,bs=Array.prototype.push,Kn=function(r,e){bs.apply(r,Y(e)?e:[e])},xs=Date.prototype.toISOString,k={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:_s,encodeValuesOnly:!1,format:Tt,formatter:Ft[Tt],indices:!1,serializeDate(r){return xs.call(r)},skipNulls:!1,strictNullHandling:!1};function As(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const St={};function Gn(r,e,t,n,s,a,i,l,u,d,o,c,h,f,w,g,_,N){let m=r,C=N,b=0,O=!1;for(;(C=C.get(St))!==void 0&&!O;){const $=C.get(r);if(b+=1,typeof $<"u"){if($===b)throw new RangeError("Cyclic object value");O=!0}typeof C.get(St)>"u"&&(b=0)}if(typeof d=="function"?m=d(e,m):m instanceof Date?m=h==null?void 0:h(m):t==="comma"&&Y(m)&&(m=Cn(m,function($){return $ instanceof Date?h==null?void 0:h($):$})),m===null){if(a)return u&&!g?u(e,k.encoder,_,"key",f):e;m=""}if(As(m)||ys(m)){if(u){const $=g?e:u(e,k.encoder,_,"key",f);return[(w==null?void 0:w($))+"="+(w==null?void 0:w(u(m,k.encoder,_,"value",f)))]}return[(w==null?void 0:w(e))+"="+(w==null?void 0:w(String(m)))]}const v=[];if(typeof m>"u")return v;let S;if(t==="comma"&&Y(m))g&&u&&(m=Cn(m,u)),S=[{value:m.length>0?m.join(",")||null:void 0}];else if(Y(d))S=d;else{const $=Object.keys(m);S=o?$.sort(o):$}const H=l?String(e).replace(/\./g,"%2E"):String(e),T=n&&Y(m)&&m.length===1?H+"[]":H;if(s&&Y(m)&&m.length===0)return T+"[]";for(let $=0;$<S.length;++$){const P=S[$],de=typeof P=="object"&&typeof P.value<"u"?P.value:m[P];if(i&&de===null)continue;const wt=c&&l?P.replace(/\./g,"%2E"):P,is=Y(m)?typeof t=="function"?t(T,wt):T:T+(c?"."+wt:"["+wt+"]");N.set(r,b);const bn=new WeakMap;bn.set(St,N),Kn(v,Gn(de,is,t,n,s,a,i,l,t==="comma"&&g&&Y(m)?null:u,d,o,c,h,f,w,g,_,bn))}return v}function Ss(r=k){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=r.charset||k.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Tt;if(typeof r.format<"u"){if(!ws.call(Ft,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=Ft[t];let s=k.filter;(typeof r.filter=="function"||Y(r.filter))&&(s=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in Vn?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=k.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:k.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:k.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:k.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:k.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?k.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:k.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:k.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:k.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:k.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:k.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:k.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:k.strictNullHandling}}function Cs(r,e={}){let t=r;const n=Ss(e);let s,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):Y(n.filter)&&(a=n.filter,s=a);const i=[];if(typeof t!="object"||t===null)return"";const l=Vn[n.arrayFormat],u=l==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const d=new WeakMap;for(let h=0;h<s.length;++h){const f=s[h];n.skipNulls&&t[f]===null||Kn(i,Gn(t[f],f,l,u,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}const o=i.join(n.delimiter);let c=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?c+="utf8=%26%2310003%3B&":c+="utf8=%E2%9C%93&"),o.length>0?c+o:""}const ge="4.91.1";let vn=!1,Te,Qn,zn,kt,Yn,Zn,er,tr,nr;function vs(r,e={auto:!1}){if(vn)throw new Error(`you must \`import 'openai/shims/${r.kind}'\` before importing anything else from openai`);if(Te)throw new Error(`can't \`import 'openai/shims/${r.kind}'\` after \`import 'openai/shims/${Te}'\``);vn=e.auto,Te=r.kind,Qn=r.fetch,zn=r.FormData,kt=r.File,Yn=r.ReadableStream,Zn=r.getMultipartRequestOptions,er=r.getDefaultAgent,tr=r.fileFromPath,nr=r.isFsReadStream}class Rs{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function Ps({manuallyImported:r}={}){const e=r?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let t,n,s,a;try{t=fetch,n=Request,s=Response,a=Headers}catch(i){throw new Error(`this environment is missing the following Web Fetch API type: ${i.message}. ${e}`)}return{kind:"web",fetch:t,Request:n,Response:s,Headers:a,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(i,l)=>({...l,body:new Rs(i)}),getDefaultAgent:i=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:i=>!1}}const rr=()=>{Te||vs(Ps(),{auto:!0})};rr();class y extends Error{}class j extends y{constructor(e,t,n,s){super(`${j.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s==null?void 0:s["x-request-id"],this.error=t;const a=t;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.type}static makeMessage(e,t,n){const s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new ct({message:n,cause:Bt(t)});const a=t==null?void 0:t.error;return e===400?new sr(e,a,n,s):e===401?new ar(e,a,n,s):e===403?new ir(e,a,n,s):e===404?new or(e,a,n,s):e===409?new lr(e,a,n,s):e===422?new cr(e,a,n,s):e===429?new ur(e,a,n,s):e>=500?new dr(e,a,n,s):new j(e,a,n,s)}}class V extends j{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class ct extends j{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Xt extends ct{constructor({message:e}={}){super({message:e??"Request timed out."})}}class sr extends j{}class ar extends j{}class ir extends j{}class or extends j{}class lr extends j{}class cr extends j{}class ur extends j{}class dr extends j{}class hr extends y{constructor(){super("Could not parse response content as the length limit was reached")}}class fr extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var qe=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},le=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},q;class ut{constructor(){q.set(this,void 0),this.buffer=new Uint8Array,qe(this,q,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e;let n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;const s=[];let a;for(;(a=Is(this.buffer,le(this,q,"f")))!=null;){if(a.carriage&&le(this,q,"f")==null){qe(this,q,a.index,"f");continue}if(le(this,q,"f")!=null&&(a.index!==le(this,q,"f")+1||a.carriage)){s.push(this.decodeText(this.buffer.slice(0,le(this,q,"f")-1))),this.buffer=this.buffer.slice(le(this,q,"f")),qe(this,q,null,"f");continue}const i=le(this,q,"f")!==null?a.preceding-1:a.preceding,l=this.decodeText(this.buffer.slice(0,i));s.push(l),this.buffer=this.buffer.slice(a.index),qe(this,q,null,"f")}return s}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new y(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new y(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new y("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
2
- `):[]}}q=new WeakMap;ut.NEWLINE_CHARS=new Set([`
3
- `,"\r"]);ut.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Is(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Es(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}function mr(r){if(r[Symbol.asyncIterator])return r;const e=r.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class ee{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*s(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(const i of $s(e,t))if(!a){if(i.data.startsWith("[DONE]")){a=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let l;try{l=JSON.parse(i.data)}catch(u){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),u}if(l&&l.error)throw new j(void 0,l.error,void 0,xr(e.headers));yield l}else{let l;try{l=JSON.parse(i.data)}catch(u){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),u}if(i.event=="error")throw new j(void 0,l.error,l.message,void 0);yield{event:i.event,data:l}}}a=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{a||t.abort()}}return new ee(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){const i=new ut,l=mr(e);for await(const u of l)for(const d of i.decode(u))yield d;for(const u of i.flush())yield u}async function*a(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(const l of s())i||l&&(yield JSON.parse(l));i=!0}catch(l){if(l instanceof Error&&l.name==="AbortError")return;throw l}finally{i||t.abort()}}return new ee(a,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=n.next();e.push(i),t.push(i)}return a.shift()}});return[new ee(()=>s(e),this.controller),new ee(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new Yn({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:a,done:i}=await t.next();if(i)return s.close();const l=n.encode(JSON.stringify(a)+`
4
- `);s.enqueue(l)}catch(a){s.error(a)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}}async function*$s(r,e){if(!r.body)throw e.abort(),new y("Attempted to iterate over a response with no body");const t=new Ts,n=new ut,s=mr(r.body);for await(const a of Os(s))for(const i of n.decode(a)){const l=t.decode(i);l&&(yield l)}for(const a of n.flush()){const i=t.decode(a);i&&(yield i)}}async function*Os(r){let e=new Uint8Array;for await(const t of r){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t;let s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let a;for(;(a=Es(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class Ts{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;const a={event:this.event,data:this.data.join(`
5
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=Fs(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function Fs(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}const pr=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",gr=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&dt(r),dt=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",ks=r=>gr(r)||pr(r)||nr(r);async function _r(r,e,t){var s;if(r=await r,gr(r))return r;if(pr(r)){const a=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");const i=dt(a)?[await a.arrayBuffer()]:[a];return new kt(i,e,t)}const n=await Ms(r);if(e||(e=Ns(r)??"unknown_file"),!(t!=null&&t.type)){const a=(s=n[0])==null?void 0:s.type;typeof a=="string"&&(t={...t,type:a})}return new kt(n,e,t)}async function Ms(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(dt(r))e.push(await r.arrayBuffer());else if(Ds(r))for await(const n of r)e.push(n);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${(t=r==null?void 0:r.constructor)==null?void 0:t.name}; props: ${Bs(r)}`);return e}function Bs(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Ns(r){var e;return Ct(r.name)||Ct(r.filename)||((e=Ct(r.path))==null?void 0:e.split(/[\\/]/).pop())}const Ct=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Ds=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Rn=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody",Ae=async r=>{const e=await js(r.body);return Zn(e,r)},js=async r=>{const e=new zn;return await Promise.all(Object.entries(r||{}).map(([t,n])=>Mt(e,t,n))),e},Mt=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(ks(t)){const n=await _r(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>Mt(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>Mt(r,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var we={},Ls=function(r,e,t,n,s){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(r,t),t},Us=function(r,e,t,n){if(typeof e=="function"?r!==e||!0:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Xe;rr();async function yr(r){var i;const{response:e}=r;if(r.options.stream)return ie("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):ee.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;const t=e.headers.get("content-type"),n=(i=t==null?void 0:t.split(";")[0])==null?void 0:i.trim();if((n==null?void 0:n.includes("application/json"))||(n==null?void 0:n.endsWith("+json"))){const l=await e.json();return ie("response",e.status,e.url,e.headers,l),wr(l,e)}const a=await e.text();return ie("response",e.status,e.url,e.headers,a),a}function wr(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}class ht extends Promise{constructor(e,t=yr){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new ht(this.responsePromise,async t=>wr(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[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(this.parseResponse)),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)}}class Ws{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:a}){this.baseURL=e,this.maxRetries=vt("maxRetries",t),this.timeout=vt("timeout",n),this.httpAgent=s,this.fetch=a??Qn}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Vs(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${zs()}`}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,n){return this.request(Promise.resolve(n).then(async s=>{const a=s&&dt(s==null?void 0:s.body)?new DataView(await s.body.arrayBuffer()):(s==null?void 0:s.body)instanceof DataView?s.body:(s==null?void 0:s.body)instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s==null?void 0:s.body)?new DataView(s.body.buffer):s==null?void 0:s.body;return{method:e,path:t,...s,body:a}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){var w;e={...e};const{method:n,path:s,query:a,headers:i={}}=e,l=ArrayBuffer.isView(e.body)||e.__binaryRequest&&typeof e.body=="string"?e.body:Rn(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,u=this.calculateContentLength(l),d=this.buildURL(s,a);"timeout"in e&&vt("timeout",e.timeout),e.timeout=e.timeout??this.timeout;const o=e.httpAgent??this.httpAgent??er(d),c=e.timeout+1e3;typeof((w=o==null?void 0:o.options)==null?void 0:w.timeout)=="number"&&c>(o.options.timeout??0)&&(o.options.timeout=c),this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const h=this.buildHeaders({options:e,headers:i,contentLength:u,retryCount:t});return{req:{method:n,...l&&{body:l},headers:h,...o&&{agent:o},signal:e.signal??null},url:d,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const a={};n&&(a["content-length"]=n);const i=this.defaultHeaders(e);return $n(a,i),$n(a,t),Rn(e.body)&&Te!=="node"&&delete a["content-type"],Ve(i,"x-stainless-retry-count")===void 0&&Ve(t,"x-stainless-retry-count")===void 0&&(a["x-stainless-retry-count"]=String(s)),Ve(i,"x-stainless-timeout")===void 0&&Ve(t,"x-stainless-timeout")===void 0&&e.timeout&&(a["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(a,t),a}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,s){return j.generate(e,t,n,s)}request(e,t=null){return new ht(this.makeRequest(e,t))}async makeRequest(e,t){var c,h;const n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);const{req:a,url:i,timeout:l}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(a,{url:i,options:n}),ie("request",i,n,a.headers),(c=n.signal)!=null&&c.aborted)throw new V;const u=new AbortController,d=await this.fetchWithTimeout(i,a,l,u).catch(Bt);if(d instanceof Error){if((h=n.signal)!=null&&h.aborted)throw new V;if(t)return this.retryRequest(n,t);throw d.name==="AbortError"?new Xt:new ct({cause:d})}const o=xr(d.headers);if(!d.ok){if(t&&this.shouldRetry(d)){const m=`retrying, ${t} attempts remaining`;return ie(`response (error; ${m})`,d.status,i,o),this.retryRequest(n,t,o)}const f=await d.text().catch(m=>Bt(m).message),w=Ks(f),g=w?void 0:f;throw ie(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,d.status,i,o,g),this.makeStatusError(d.status,w,g,o)}return{response:d,options:n,controller:u}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new Js(this,n,e)}buildURL(e,t){const n=Qs(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Ar(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new y(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){const{signal:a,...i}=t||{};a&&a.addEventListener("abort",()=>s.abort());const l=setTimeout(()=>s.abort(),n),u={signal:s.signal,...i};return u.method&&(u.method=u.method.toUpperCase()),this.fetch.call(void 0,e,u).finally(()=>{clearTimeout(l)})}shouldRetry(e){const 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,n){let s;const a=n==null?void 0:n["retry-after-ms"];if(a){const l=parseFloat(a);Number.isNaN(l)||(s=l)}const i=n==null?void 0:n["retry-after"];if(i&&!s){const l=parseFloat(i);Number.isNaN(l)?s=Date.parse(i)-Date.now():s=l*1e3}if(!(s&&0<=s&&s<60*1e3)){const l=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Be(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,i=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return i*l*1e3}getUserAgent(){return`${this.constructor.name}/JS ${ge}`}}class br{constructor(e,t,n,s){Xe.set(this,void 0),Ls(this,Xe,e),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[s,a]of n)e.url.searchParams.set(s,a);t.query=void 0,t.path=e.url.toString()}return await Us(this,Xe,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Xe=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Js extends ht{constructor(e,t,n){super(t,async s=>new n(e,s.response,await yr(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const xr=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),qs={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},B=r=>typeof r=="object"&&r!==null&&!Ar(r)&&Object.keys(r).every(e=>Sr(qs,e)),Xs=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":In(Deno.build.os),"X-Stainless-Arch":Pn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((e=Deno.version)==null?void 0:e.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":In(process.platform),"X-Stainless-Arch":Pn(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const r=Hs();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ge,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Hs(){if(typeof navigator>"u"||!navigator)return null;const r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of r){const n=t.exec(navigator.userAgent);if(n){const s=n[1]||0,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const Pn=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",In=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown");let En;const Vs=()=>En??(En=Xs()),Ks=r=>{try{return JSON.parse(r)}catch{return}},Gs=/^[a-z][a-z0-9+.-]*:/i,Qs=r=>Gs.test(r),Be=r=>new Promise(e=>setTimeout(e,r)),vt=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${r} must be an integer`);if(e<0)throw new y(`${r} must be a positive integer`);return e},Bt=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(r)},He=r=>{var e,t,n,s;if(typeof process<"u")return((e=we==null?void 0:we[r])==null?void 0:e.trim())??void 0;if(typeof Deno<"u")return(s=(n=(t=Deno.env)==null?void 0:t.get)==null?void 0:n.call(t,r))==null?void 0:s.trim()};function Ar(r){if(!r)return!0;for(const e in r)return!1;return!0}function Sr(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function $n(r,e){for(const t in e){if(!Sr(e,t))continue;const n=t.toLowerCase();if(!n)continue;const s=e[t];s===null?delete r[n]:s!==void 0&&(r[n]=s)}}const On=new Set(["authorization","api-key"]);function ie(r,...e){if(typeof process<"u"&&(we==null?void 0:we.DEBUG)==="true"){const t=e.map(n=>{if(!n)return n;if(n.headers){const a={...n,headers:{...n.headers}};for(const i in n.headers)On.has(i.toLowerCase())&&(a.headers[i]="REDACTED");return a}let s=null;for(const a in n)On.has(a.toLowerCase())&&(s??(s={...n}),s[a]="REDACTED");return s??n});console.log(`OpenAI:DEBUG:${r}`,...t)}}const zs=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Ys=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Zs=r=>typeof(r==null?void 0:r.get)=="function",Ve=(r,e)=>{var n;const t=e.toLowerCase();if(Zs(r)){const s=((n=e[0])==null?void 0:n.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(a,i,l)=>i+l.toUpperCase());for(const a of[e,t,e.toUpperCase(),s]){const i=r.get(a);if(i)return i}}for(const[s,a]of Object.entries(r))if(s.toLowerCase()===t)return Array.isArray(a)?(a.length<=1||console.warn(`Received ${a.length} entries for the ${e} header, using the first entry.`),a[0]):a},ea=r=>{if(typeof Buffer<"u")return Array.from(new Float32Array(Buffer.from(r,"base64").buffer));{const e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};function Rt(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}class Ht extends br{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class W extends br{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){var n;const e=this.getPaginatedItems();if(!e.length)return null;const t=(n=e[e.length-1])==null?void 0:n.id;return t?{params:{after:t}}:null}}class A{constructor(e){this._client=e}}let Cr=class extends A{list(e,t={},n){return B(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,ta,{query:t,...n})}},ft=class extends A{constructor(){super(...arguments),this.messages=new Cr(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return B(e)?this.list({},e):this._client.getAPIList("/chat/completions",mt,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class mt extends W{}class ta extends W{}ft.ChatCompletionsPage=mt;ft.Messages=Cr;let pt=class extends A{constructor(){super(...arguments),this.completions=new ft(this._client)}};pt.Completions=ft;pt.ChatCompletionsPage=mt;class vr extends A{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t==null?void 0:t.headers},__binaryResponse:!0})}}class Rr extends A{create(e,t){return this._client.post("/audio/transcriptions",Ae({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Pr extends A{create(e,t){return this._client.post("/audio/translations",Ae({body:e,...t,__metadata:{model:e.model}}))}}class Ne extends A{constructor(){super(...arguments),this.transcriptions=new Rr(this._client),this.translations=new Pr(this._client),this.speech=new vr(this._client)}}Ne.Transcriptions=Rr;Ne.Translations=Pr;Ne.Speech=vr;class Vt extends A{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return B(e)?this.list({},e):this._client.getAPIList("/batches",Kt,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class Kt extends W{}Vt.BatchesPage=Kt;class Gt extends A{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e={},t){return B(e)?this.list({},e):this._client.getAPIList("/assistants",Qt,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Qt extends W{}Gt.AssistantsPage=Qt;function Tn(r){return typeof r.parse=="function"}const be=r=>(r==null?void 0:r.role)==="assistant",Ir=r=>(r==null?void 0:r.role)==="function",Er=r=>(r==null?void 0:r.role)==="tool";var K=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},E=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Nt,Ze,et,Re,Pe,tt,Ie,ne,Ee,at,it,_e,$r;class zt{constructor(){Nt.add(this),this.controller=new AbortController,Ze.set(this,void 0),et.set(this,()=>{}),Re.set(this,()=>{}),Pe.set(this,void 0),tt.set(this,()=>{}),Ie.set(this,()=>{}),ne.set(this,{}),Ee.set(this,!1),at.set(this,!1),it.set(this,!1),_e.set(this,!1),K(this,Ze,new Promise((e,t)=>{K(this,et,e,"f"),K(this,Re,t,"f")}),"f"),K(this,Pe,new Promise((e,t)=>{K(this,tt,e,"f"),K(this,Ie,t,"f")}),"f"),E(this,Ze,"f").catch(()=>{}),E(this,Pe,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},E(this,Nt,"m",$r).bind(this))},0)}_connected(){this.ended||(E(this,et,"f").call(this),this._emit("connect"))}get ended(){return E(this,Ee,"f")}get errored(){return E(this,at,"f")}get aborted(){return E(this,it,"f")}abort(){this.controller.abort()}on(e,t){return(E(this,ne,"f")[e]||(E(this,ne,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=E(this,ne,"f")[e];if(!n)return this;const s=n.findIndex(a=>a.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(E(this,ne,"f")[e]||(E(this,ne,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{K(this,_e,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){K(this,_e,!0,"f"),await E(this,Pe,"f")}_emit(e,...t){if(E(this,Ee,"f"))return;e==="end"&&(K(this,Ee,!0,"f"),E(this,tt,"f").call(this));const n=E(this,ne,"f")[e];if(n&&(E(this,ne,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!E(this,_e,"f")&&!(n!=null&&n.length)&&Promise.reject(s),E(this,Re,"f").call(this,s),E(this,Ie,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!E(this,_e,"f")&&!(n!=null&&n.length)&&Promise.reject(s),E(this,Re,"f").call(this,s),E(this,Ie,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Ze=new WeakMap,et=new WeakMap,Re=new WeakMap,Pe=new WeakMap,tt=new WeakMap,Ie=new WeakMap,ne=new WeakMap,Ee=new WeakMap,at=new WeakMap,it=new WeakMap,_e=new WeakMap,Nt=new WeakSet,$r=function(e){if(K(this,at,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new V),e instanceof V)return K(this,it,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){const t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};function Yt(r){return(r==null?void 0:r.$brand)==="auto-parseable-response-format"}function De(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function na(r,e){return!e||!Or(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Zt(r,e)}function Zt(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new hr;if(n.finish_reason==="content_filter")throw new fr;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(a=>sa(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?ra(e,n.message.content):null}}});return{...r,choices:t}}function ra(r,e){var t,n;return((t=r.response_format)==null?void 0:t.type)!=="json_schema"?null:((n=r.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function sa(r,e){var n;const t=(n=r.tools)==null?void 0:n.find(s=>{var a;return((a=s.function)==null?void 0:a.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:De(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function aa(r,e){var n;if(!r)return!1;const t=(n=r.tools)==null?void 0:n.find(s=>{var a;return((a=s.function)==null?void 0:a.name)===e.function.name});return De(t)||(t==null?void 0:t.function.strict)||!1}function Or(r){var e;return Yt(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>De(t)||t.type==="function"&&t.function.strict===!0))??!1}function ia(r){for(const e of r??[]){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 U=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},L,Dt,ot,jt,Lt,Ut,Tr,Wt;const Fn=10;class Fr extends zt{constructor(){super(...arguments),L.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(n=e.choices[0])==null?void 0:n.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),(Ir(e)||Er(e))&&e.content)this._emit("functionCallResult",e.content);else if(be(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(be(e)&&e.tool_calls)for(const n of e.tool_calls)n.type==="function"&&this._emit("functionCall",n.function)}}async finalChatCompletion(){await this.done();const 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(),U(this,L,"m",Dt).call(this)}async finalMessage(){return await this.done(),U(this,L,"m",ot).call(this)}async finalFunctionCall(){return await this.done(),U(this,L,"m",jt).call(this)}async finalFunctionCallResult(){return await this.done(),U(this,L,"m",Lt).call(this)}async totalUsage(){return await this.done(),U(this,L,"m",Ut).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=U(this,L,"m",ot).call(this);t&&this._emit("finalMessage",t);const n=U(this,L,"m",Dt).call(this);n&&this._emit("finalContent",n);const s=U(this,L,"m",jt).call(this);s&&this._emit("finalFunctionCall",s);const a=U(this,L,"m",Lt).call(this);a!=null&&this._emit("finalFunctionCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",U(this,L,"m",Ut).call(this))}async _createChatCompletion(e,t,n){const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),U(this,L,"m",Tr).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Zt(a,t))}async _runChatCompletion(e,t,n){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){var h;const s="function",{function_call:a="auto",stream:i,...l}=t,u=typeof a!="string"&&(a==null?void 0:a.name),{maxChatCompletions:d=Fn}=n||{},o={};for(const f of t.functions)o[f.name||f.function.name]=f;const c=t.functions.map(f=>({name:f.name||f.function.name,parameters:f.parameters,description:f.description}));for(const f of t.messages)this._addMessage(f,!1);for(let f=0;f<d;++f){const g=(h=(await this._createChatCompletion(e,{...l,function_call:a,functions:c,messages:[...this.messages]},n)).choices[0])==null?void 0:h.message;if(!g)throw new y("missing message in ChatCompletion response");if(!g.function_call)return;const{name:_,arguments:N}=g.function_call,m=o[_];if(m){if(u&&u!==_){const v=`Invalid function_call: ${JSON.stringify(_)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,name:_,content:v});continue}}else{const v=`Invalid function_call: ${JSON.stringify(_)}. Available options are: ${c.map(S=>JSON.stringify(S.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:_,content:v});continue}let C;try{C=Tn(m)?await m.parse(N):N}catch(v){this._addMessage({role:s,name:_,content:v instanceof Error?v.message:String(v)});continue}const b=await m.function(C,this),O=U(this,L,"m",Wt).call(this,b);if(this._addMessage({role:s,name:_,content:O}),u)return}}async _runTools(e,t,n){var f,w,g;const s="tool",{tool_choice:a="auto",stream:i,...l}=t,u=typeof a!="string"&&((f=a==null?void 0:a.function)==null?void 0:f.name),{maxChatCompletions:d=Fn}=n||{},o=t.tools.map(_=>{if(De(_)){if(!_.$callback)throw new y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:_.$callback,name:_.function.name,description:_.function.description||"",parameters:_.function.parameters,parse:_.$parseRaw,strict:!0}}}return _}),c={};for(const _ of o)_.type==="function"&&(c[_.function.name||_.function.function.name]=_.function);const h="tools"in t?o.map(_=>_.type==="function"?{type:"function",function:{name:_.function.name||_.function.function.name,parameters:_.function.parameters,description:_.function.description,strict:_.function.strict}}:_):void 0;for(const _ of t.messages)this._addMessage(_,!1);for(let _=0;_<d;++_){const m=(w=(await this._createChatCompletion(e,{...l,tool_choice:a,tools:h,messages:[...this.messages]},n)).choices[0])==null?void 0:w.message;if(!m)throw new y("missing message in ChatCompletion response");if(!((g=m.tool_calls)!=null&&g.length))return;for(const C of m.tool_calls){if(C.type!=="function")continue;const b=C.id,{name:O,arguments:v}=C.function,S=c[O];if(S){if(u&&u!==O){const P=`Invalid tool_call: ${JSON.stringify(O)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:b,content:P});continue}}else{const P=`Invalid tool_call: ${JSON.stringify(O)}. Available options are: ${Object.keys(c).map(de=>JSON.stringify(de)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:b,content:P});continue}let H;try{H=Tn(S)?await S.parse(v):v}catch(P){const de=P instanceof Error?P.message:String(P);this._addMessage({role:s,tool_call_id:b,content:de});continue}const T=await S.function(H,this),$=U(this,L,"m",Wt).call(this,T);if(this._addMessage({role:s,tool_call_id:b,content:$}),u)return}}}}L=new WeakSet,Dt=function(){return U(this,L,"m",ot).call(this).content??null},ot=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(be(t)){const{function_call:n,...s}=t,a={...s,content:t.content??null,refusal:t.refusal??null};return n&&(a.function_call=n),a}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},jt=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const s=this.messages[n];if(be(s)&&(s!=null&&s.function_call))return s.function_call;if(be(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},Lt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ir(t)&&t.content!=null||Er(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>{var s;return n.role==="assistant"&&((s=n.tool_calls)==null?void 0:s.some(a=>a.type==="function"&&a.id===t.tool_call_id))}))return t.content}},Ut=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{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},Tr=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.")},Wt=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class ke extends Fr{static runFunctions(e,t,n){const s=new ke,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,a)),s}static runTools(e,t,n){const s=new ke,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}_addMessage(e,t=!0){super._addMessage(e,t),be(e)&&e.content&&this._emit("content",e.content)}}const kr=1,Mr=2,Br=4,Nr=8,Dr=16,jr=32,Lr=64,Ur=128,Wr=256,Jr=Ur|Wr,qr=Dr|jr|Jr|Lr,Xr=kr|Mr|qr,Hr=Br|Nr,oa=Xr|Hr,M={STR:kr,NUM:Mr,ARR:Br,OBJ:Nr,NULL:Dr,BOOL:jr,NAN:Lr,INFINITY:Ur,MINUS_INFINITY:Wr,INF:Jr,SPECIAL:qr,ATOM:Xr,COLLECTION:Hr,ALL:oa};class la extends Error{}class ca extends Error{}function ua(r,e=M.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return da(r.trim(),e)}const da=(r,e)=>{const t=r.length;let n=0;const s=h=>{throw new la(`${h} at position ${n}`)},a=h=>{throw new ca(`${h} at position ${n}`)},i=()=>(c(),n>=t&&s("Unexpected end of input"),r[n]==='"'?l():r[n]==="{"?u():r[n]==="["?d():r.substring(n,n+4)==="null"||M.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||M.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||M.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||M.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||M.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||M.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):o()),l=()=>{const h=n;let f=!1;for(n++;n<t&&(r[n]!=='"'||f&&r[n-1]==="\\");)f=r[n]==="\\"?!f:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(h,++n-Number(f)))}catch(w){a(String(w))}else if(M.STR&e)try{return JSON.parse(r.substring(h,n-Number(f))+'"')}catch{return JSON.parse(r.substring(h,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{n++,c();const h={};try{for(;r[n]!=="}";){if(c(),n>=t&&M.OBJ&e)return h;const f=l();c(),n++;try{const w=i();Object.defineProperty(h,f,{value:w,writable:!0,enumerable:!0,configurable:!0})}catch(w){if(M.OBJ&e)return h;throw w}c(),r[n]===","&&n++}}catch{if(M.OBJ&e)return h;s("Expected '}' at end of object")}return n++,h},d=()=>{n++;const h=[];try{for(;r[n]!=="]";)h.push(i()),c(),r[n]===","&&n++}catch{if(M.ARR&e)return h;s("Expected ']' at end of array")}return n++,h},o=()=>{if(n===0){r==="-"&&M.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(f){if(M.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}a(String(f))}}const h=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(M.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(h,n))}catch{r.substring(h,n)==="-"&&M.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(h,r.lastIndexOf("e")))}catch(w){a(String(w))}}},c=()=>{for(;n<t&&`
6
- \r `.includes(r[n]);)n++};return i()},kn=r=>ua(r,M.ALL^M.NUM);var he=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},R=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},F,te,fe,re,Pt,Ke,It,Et,$t,Ge,Ot,Mn;class Me extends Fr{constructor(e){super(),F.add(this),te.set(this,void 0),fe.set(this,void 0),re.set(this,void 0),he(this,te,e,"f"),he(this,fe,[],"f")}get currentChatCompletionSnapshot(){return R(this,re,"f")}static fromReadableStream(e){const t=new Me(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new Me(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){var i;super._createChatCompletion;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),R(this,F,"m",Pt).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of a)R(this,F,"m",It).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new V;return this._addChatCompletion(R(this,F,"m",Ge).call(this))}async _fromReadableStream(e,t){var i;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),R(this,F,"m",Pt).call(this),this._connected();const s=ee.fromReadableStream(e,this.controller);let a;for await(const l of s)a&&a!==l.id&&this._addChatCompletion(R(this,F,"m",Ge).call(this)),R(this,F,"m",It).call(this,l),a=l.id;if((i=s.controller.signal)!=null&&i.aborted)throw new V;return this._addChatCompletion(R(this,F,"m",Ge).call(this))}[(te=new WeakMap,fe=new WeakMap,re=new WeakMap,F=new WeakSet,Pt=function(){this.ended||he(this,re,void 0,"f")},Ke=function(t){let n=R(this,fe,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},R(this,fe,"f")[t.index]=n,n)},It=function(t){var s,a,i,l,u,d,o,c,h,f,w,g,_,N,m;if(this.ended)return;const n=R(this,F,"m",Mn).call(this,t);this._emit("chunk",t,n);for(const C of t.choices){const b=n.choices[C.index];C.delta.content!=null&&((s=b.message)==null?void 0:s.role)==="assistant"&&((a=b.message)!=null&&a.content)&&(this._emit("content",C.delta.content,b.message.content),this._emit("content.delta",{delta:C.delta.content,snapshot:b.message.content,parsed:b.message.parsed})),C.delta.refusal!=null&&((i=b.message)==null?void 0:i.role)==="assistant"&&((l=b.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:C.delta.refusal,snapshot:b.message.refusal}),((u=C.logprobs)==null?void 0:u.content)!=null&&((d=b.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(o=C.logprobs)==null?void 0:o.content,snapshot:((c=b.logprobs)==null?void 0:c.content)??[]}),((h=C.logprobs)==null?void 0:h.refusal)!=null&&((f=b.message)==null?void 0:f.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(w=C.logprobs)==null?void 0:w.refusal,snapshot:((g=b.logprobs)==null?void 0:g.refusal)??[]});const O=R(this,F,"m",Ke).call(this,b);b.finish_reason&&(R(this,F,"m",$t).call(this,b),O.current_tool_call_index!=null&&R(this,F,"m",Et).call(this,b,O.current_tool_call_index));for(const v of C.delta.tool_calls??[])O.current_tool_call_index!==v.index&&(R(this,F,"m",$t).call(this,b),O.current_tool_call_index!=null&&R(this,F,"m",Et).call(this,b,O.current_tool_call_index)),O.current_tool_call_index=v.index;for(const v of C.delta.tool_calls??[]){const S=(_=b.message.tool_calls)==null?void 0:_[v.index];S!=null&&S.type&&((S==null?void 0:S.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(N=S.function)==null?void 0:N.name,index:v.index,arguments:S.function.arguments,parsed_arguments:S.function.parsed_arguments,arguments_delta:((m=v.function)==null?void 0:m.arguments)??""}):(S==null||S.type,void 0))}}},Et=function(t,n){var i,l,u;if(R(this,F,"m",Ke).call(this,t).done_tool_calls.has(n))return;const a=(i=t.message.tool_calls)==null?void 0:i[n];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const d=(u=(l=R(this,te,"f"))==null?void 0:l.tools)==null?void 0:u.find(o=>o.type==="function"&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:De(d)?d.$parseRaw(a.function.arguments):d!=null&&d.function.strict?JSON.parse(a.function.arguments):null})}else a.type},$t=function(t){var s,a;const n=R(this,F,"m",Ke).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=R(this,F,"m",Ot).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(s=t.logprobs)!=null&&s.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(a=t.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Ge=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");const t=R(this,re,"f");if(!t)throw new y("request ended without sending any chunks");return he(this,re,void 0,"f"),he(this,fe,[],"f"),ha(t,R(this,te,"f"))},Ot=function(){var n;const t=(n=R(this,te,"f"))==null?void 0:n.response_format;return Yt(t)?t:null},Mn=function(t){var n,s,a,i;let l=R(this,re,"f");const{choices:u,...d}=t;l?Object.assign(l,d):l=he(this,re,{...d,choices:[]},"f");for(const{delta:o,finish_reason:c,index:h,logprobs:f=null,...w}of t.choices){let g=l.choices[h];if(g||(g=l.choices[h]={finish_reason:c,index:h,message:{},logprobs:f,...w}),f)if(!g.logprobs)g.logprobs=Object.assign({},f);else{const{content:v,refusal:S,...H}=f;Object.assign(g.logprobs,H),v&&((n=g.logprobs).content??(n.content=[]),g.logprobs.content.push(...v)),S&&((s=g.logprobs).refusal??(s.refusal=[]),g.logprobs.refusal.push(...S))}if(c&&(g.finish_reason=c,R(this,te,"f")&&Or(R(this,te,"f")))){if(c==="length")throw new hr;if(c==="content_filter")throw new fr}if(Object.assign(g,w),!o)continue;const{content:_,refusal:N,function_call:m,role:C,tool_calls:b,...O}=o;if(Object.assign(g.message,O),N&&(g.message.refusal=(g.message.refusal||"")+N),C&&(g.message.role=C),m&&(g.message.function_call?(m.name&&(g.message.function_call.name=m.name),m.arguments&&((a=g.message.function_call).arguments??(a.arguments=""),g.message.function_call.arguments+=m.arguments)):g.message.function_call=m),_&&(g.message.content=(g.message.content||"")+_,!g.message.refusal&&R(this,F,"m",Ot).call(this)&&(g.message.parsed=kn(g.message.content))),b){g.message.tool_calls||(g.message.tool_calls=[]);for(const{index:v,id:S,type:H,function:T,...$}of b){const P=(i=g.message.tool_calls)[v]??(i[v]={});Object.assign(P,$),S&&(P.id=S),H&&(P.type=H),T&&(P.function??(P.function={name:T.name??"",arguments:""})),T!=null&&T.name&&(P.function.name=T.name),T!=null&&T.arguments&&(P.function.arguments+=T.arguments,aa(R(this,te,"f"),P)&&(P.function.parsed_arguments=kn(P.function.arguments)))}}}return l},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ha(r,e){const{id:t,choices:n,created:s,model:a,system_fingerprint:i,...l}=r,u={...l,id:t,choices:n.map(({message:d,finish_reason:o,index:c,logprobs:h,...f})=>{if(!o)throw new y(`missing finish_reason for choice ${c}`);const{content:w=null,function_call:g,tool_calls:_,...N}=d,m=d.role;if(!m)throw new y(`missing role for choice ${c}`);if(g){const{arguments:C,name:b}=g;if(C==null)throw new y(`missing function_call.arguments for choice ${c}`);if(!b)throw new y(`missing function_call.name for choice ${c}`);return{...f,message:{content:w,function_call:{arguments:C,name:b},role:m,refusal:d.refusal??null},finish_reason:o,index:c,logprobs:h}}return _?{...f,index:c,finish_reason:o,logprobs:h,message:{...N,role:m,content:w,refusal:d.refusal??null,tool_calls:_.map((C,b)=>{const{function:O,type:v,id:S,...H}=C,{arguments:T,name:$,...P}=O||{};if(S==null)throw new y(`missing choices[${c}].tool_calls[${b}].id
7
- ${Qe(r)}`);if(v==null)throw new y(`missing choices[${c}].tool_calls[${b}].type
8
- ${Qe(r)}`);if($==null)throw new y(`missing choices[${c}].tool_calls[${b}].function.name
9
- ${Qe(r)}`);if(T==null)throw new y(`missing choices[${c}].tool_calls[${b}].function.arguments
10
- ${Qe(r)}`);return{...H,id:S,type:v,function:{...P,name:$,arguments:T}}})}}:{...f,message:{...N,content:w,role:m,refusal:d.refusal??null},finish_reason:o,index:c,logprobs:h}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return na(u,e)}function Qe(r){return JSON.stringify(r)}class xe extends Me{static fromReadableStream(e){const t=new xe(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new xe(null),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,a)),s}static runTools(e,t,n){const s=new xe(t),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}}let Vr=class extends A{parse(e,t){return ia(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(n=>Zt(n,e))}runFunctions(e,t){return e.stream?xe.runFunctions(this._client,e,t):ke.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?xe.runTools(this._client,e,t):ke.runTools(this._client,e,t)}stream(e,t){return Me.createChatCompletion(this._client,e,t)}};class Jt extends A{constructor(){super(...arguments),this.completions=new Vr(this._client)}}(function(r){r.Completions=Vr})(Jt||(Jt={}));class Kr extends A{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Gr extends A{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class gt extends A{constructor(){super(...arguments),this.sessions=new Kr(this._client),this.transcriptionSessions=new Gr(this._client)}}gt.Sessions=Kr;gt.TranscriptionSessions=Gr;var p=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},J=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},D,qt,Z,nt,G,ue,ye,ce,lt,X,rt,st,Fe,$e,Oe,Bn,Nn,Dn,jn,Ln,Un,Wn;class Q extends zt{constructor(){super(...arguments),D.add(this),qt.set(this,[]),Z.set(this,{}),nt.set(this,{}),G.set(this,void 0),ue.set(this,void 0),ye.set(this,void 0),ce.set(this,void 0),lt.set(this,void 0),X.set(this,void 0),rt.set(this,void 0),st.set(this,void 0),Fe.set(this,void 0)}[(qt=new WeakMap,Z=new WeakMap,nt=new WeakMap,G=new WeakMap,ue=new WeakMap,ye=new WeakMap,ce=new WeakMap,lt=new WeakMap,X=new WeakMap,rt=new WeakMap,st=new WeakMap,Fe=new WeakMap,D=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Q;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var a;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=ee.fromReadableStream(e,this.controller);for await(const i of s)p(this,D,"m",$e).call(this,i);if((a=s.controller.signal)!=null&&a.aborted)throw new V;return this._addRun(p(this,D,"m",Oe).call(this))}toReadableStream(){return new ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,a){const i=new Q;return i._run(()=>i._runToolAssistantStream(e,t,n,s,{...a,headers:{...a==null?void 0:a.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,n,s,a){var d;const i=a==null?void 0:a.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const l={...s,stream:!0},u=await e.submitToolOutputs(t,n,l,{...a,signal:this.controller.signal});this._connected();for await(const o of u)p(this,D,"m",$e).call(this,o);if((d=u.controller.signal)!=null&&d.aborted)throw new V;return this._addRun(p(this,D,"m",Oe).call(this))}static createThreadAssistantStream(e,t,n){const s=new Q;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){const a=new Q;return a._run(()=>a._runAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return p(this,rt,"f")}currentRun(){return p(this,st,"f")}currentMessageSnapshot(){return p(this,G,"f")}currentRunStepSnapshot(){return p(this,Fe,"f")}async finalRunSteps(){return await this.done(),Object.values(p(this,Z,"f"))}async finalMessages(){return await this.done(),Object.values(p(this,nt,"f"))}async finalRun(){if(await this.done(),!p(this,ue,"f"))throw Error("Final run was not received.");return p(this,ue,"f")}async _createThreadAssistantStream(e,t,n){var l;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},i=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(const u of i)p(this,D,"m",$e).call(this,u);if((l=i.controller.signal)!=null&&l.aborted)throw new V;return this._addRun(p(this,D,"m",Oe).call(this))}async _createAssistantStream(e,t,n,s){var u;const a=s==null?void 0:s.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const d of l)p(this,D,"m",$e).call(this,d);if((u=l.controller.signal)!=null&&u.aborted)throw new V;return this._addRun(p(this,D,"m",Oe).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let a=e[n];if(a==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(Rt(a)&&Rt(s))a=this.accumulateDelta(a,s);else if(Array.isArray(a)&&Array.isArray(s)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...s);continue}for(const i of s){if(!Rt(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),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}`);const u=a[l];u==null?a.push(i):a[l]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${a}`);e[n]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,a){return await this._createToolAssistantStream(n,e,t,s,a)}}$e=function(e){if(!this.ended)switch(J(this,rt,e,"f"),p(this,D,"m",Dn).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":p(this,D,"m",Wn).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":p(this,D,"m",Nn).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":p(this,D,"m",Bn).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Oe=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!p(this,ue,"f"))throw Error("Final run has not been received");return p(this,ue,"f")},Bn=function(e){const[t,n]=p(this,D,"m",Ln).call(this,e,p(this,G,"f"));J(this,G,t,"f"),p(this,nt,"f")[t.id]=t;for(const s of n){const a=t.content[s.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.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(const s of e.data.delta.content){if(s.type=="text"&&s.text){let a=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=p(this,ye,"f")){if(p(this,ce,"f"))switch(p(this,ce,"f").type){case"text":this._emit("textDone",p(this,ce,"f").text,p(this,G,"f"));break;case"image_file":this._emit("imageFileDone",p(this,ce,"f").image_file,p(this,G,"f"));break}J(this,ye,s.index,"f")}J(this,ce,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(p(this,ye,"f")!==void 0){const s=e.data.content[p(this,ye,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,p(this,G,"f"));break;case"text":this._emit("textDone",s.text,p(this,G,"f"));break}}p(this,G,"f")&&this._emit("messageDone",e.data),J(this,G,void 0,"f")}},Nn=function(e){const t=p(this,D,"m",jn).call(this,e);switch(J(this,Fe,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const a of n.step_details.tool_calls)a.index==p(this,lt,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(p(this,X,"f")&&this._emit("toolCallDone",p(this,X,"f")),J(this,lt,a.index,"f"),J(this,X,t.step_details.tool_calls[a.index],"f"),p(this,X,"f")&&this._emit("toolCallCreated",p(this,X,"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":J(this,Fe,void 0,"f"),e.data.step_details.type=="tool_calls"&&p(this,X,"f")&&(this._emit("toolCallDone",p(this,X,"f")),J(this,X,void 0,"f")),this._emit("runStepDone",e.data,t);break}},Dn=function(e){p(this,qt,"f").push(e),this._emit("event",e)},jn=function(e){switch(e.event){case"thread.run.step.created":return p(this,Z,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=p(this,Z,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=Q.accumulateDelta(t,n.delta);p(this,Z,"f")[e.data.id]=s}return p(this,Z,"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":p(this,Z,"f")[e.data.id]=e.data;break}if(p(this,Z,"f")[e.data.id])return p(this,Z,"f")[e.data.id];throw new Error("No snapshot available")},Ln=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const a of s.delta.content)if(a.index in t.content){let i=t.content[a.index];t.content[a.index]=p(this,D,"m",Un).call(this,a,i)}else t.content[a.index]=a,n.push(a);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Un=function(e,t){return Q.accumulateDelta(t,e)},Wn=function(e){switch(J(this,st,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":J(this,ue,e.data,"f"),p(this,X,"f")&&(this._emit("toolCallDone",p(this,X,"f")),J(this,X,void 0,"f"));break}};class en extends A{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return B(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,tn,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class tn extends W{}en.MessagesPage=tn;class nn extends A{retrieve(e,t,n,s={},a){return B(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...a,headers:{"OpenAI-Beta":"assistants=v2",...a==null?void 0:a.headers}})}list(e,t,n={},s){return B(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,rn,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}}class rn extends W{}nn.RunStepsPage=rn;class je extends A{constructor(){super(...arguments),this.steps=new nn(this._client)}create(e,t,n){const{include:s,...a}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:a,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return B(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,sn,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}createAndStream(e,t,n){return Q.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:a,response:i}=await this.retrieve(e,t,{...n,headers:{...n==null?void 0:n.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const u=i.headers.get("openai-poll-after-ms");if(u){const d=parseInt(u);isNaN(d)||(l=d)}}await Be(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,n){return Q.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const a=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,a.id,s)}submitToolOutputsStream(e,t,n,s){return Q.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}}class sn extends W{}je.RunsPage=sn;je.Steps=nn;je.RunStepsPage=rn;class Se extends A{constructor(){super(...arguments),this.runs=new je(this._client),this.messages=new en(this._client)}create(e={},t){return B(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return Q.createThreadAssistantStream(e,this._client.beta.threads,t)}}Se.Runs=je;Se.RunsPage=sn;Se.Messages=en;Se.MessagesPage=tn;class Ce extends A{constructor(){super(...arguments),this.realtime=new gt(this._client),this.chat=new Jt(this._client),this.assistants=new Gt(this._client),this.threads=new Se(this._client)}}Ce.Realtime=gt;Ce.Assistants=Gt;Ce.AssistantsPage=Qt;Ce.Threads=Se;class Qr extends A{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class zr extends A{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&ie("Request","User defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?a:(ie("response","Decoding base64 embeddings to float32 array"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const u=l.embedding;l.embedding=ea(u)}),i)))}}let an=class extends A{create(e,t){return this._client.post("/files",Ae({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return B(e)?this.list({},e):this._client.getAPIList("/files",on,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t==null?void 0:t.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await Be(t),i=await this.retrieve(e),Date.now()-a>n)throw new Xt({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class on extends W{}an.FileObjectsPage=on;class ln extends A{list(e,t={},n){return B(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,cn,{query:t,...n})}}class cn extends W{}ln.FineTuningJobCheckpointsPage=cn;class ve extends A{constructor(){super(...arguments),this.checkpoints=new ln(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return B(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",un,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return B(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,dn,{query:t,...n})}}class un extends W{}class dn extends W{}ve.FineTuningJobsPage=un;ve.FineTuningJobEventsPage=dn;ve.Checkpoints=ln;ve.FineTuningJobCheckpointsPage=cn;class Le extends A{constructor(){super(...arguments),this.jobs=new ve(this._client)}}Le.Jobs=ve;Le.FineTuningJobsPage=un;Le.FineTuningJobEventsPage=dn;class Yr extends A{createVariation(e,t){return this._client.post("/images/variations",Ae({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",Ae({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class hn extends A{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",fn,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class fn extends Ht{}hn.ModelsPage=fn;class Zr extends A{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function fa(r,e){return!e||!pa(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:es(r,e)}function es(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:ya(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:ma(e,i.text)}:i);return{...s,content:a}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||ts(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const s of n.output)if(s.type==="message"){for(const a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function ma(r,e){var t,n,s,a;return((n=(t=r.text)==null?void 0:t.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((s=r.text)==null?void 0:s.format)?((a=r.text)==null?void 0:a.format).$parseRaw(e):JSON.parse(e)}function pa(r){var e;return!!Yt((e=r.text)==null?void 0:e.format)}function ga(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function _a(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function ya(r,e){const t=_a(r.tools??[],e.name);return{...e,...e,parsed_arguments:ga(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function ts(r){const e=[];for(const t of r.output)if(t.type==="message")for(const n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}class ns extends A{list(e,t={},n){return B(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,ba,{query:t,...n})}}var me=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},se=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},pe,ze,ae,Ye,Jn,qn,Xn,Hn;class mn extends zt{constructor(e){super(),pe.add(this),ze.set(this,void 0),ae.set(this,void 0),Ye.set(this,void 0),me(this,ze,e,"f")}static createResponse(e,t,n){const s=new mn(t);return s._run(()=>s._createResponse(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createResponse(e,t,n){var i;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),se(this,pe,"m",Jn).call(this);const a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of a)se(this,pe,"m",qn).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new V;return se(this,pe,"m",Xn).call(this)}[(ze=new WeakMap,ae=new WeakMap,Ye=new WeakMap,pe=new WeakSet,Jn=function(){this.ended||me(this,ae,void 0,"f")},qn=function(t){if(this.ended)return;const n=se(this,pe,"m",Hn).call(this,t);switch(this._emit("event",t),t.type){case"response.output_text.delta":{const s=n.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);if(s.type==="message"){const a=s.content[t.content_index];if(!a)throw new y(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new y(`expected content to be 'output_text', got ${a.type}`);this._emit("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{const s=n.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);s.type==="function_call"&&this._emit("response.function_call_arguments.delta",{...t,snapshot:s.arguments});break}default:this._emit(t.type,t);break}},Xn=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");const t=se(this,ae,"f");if(!t)throw new y("request ended without sending any events");me(this,ae,void 0,"f");const n=wa(t,se(this,ze,"f"));return me(this,Ye,n,"f"),n},Hn=function(t){let n=se(this,ae,"f");if(!n){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=me(this,ae,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{const s=n.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{const s=n.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);if(s.type==="message"){const a=s.content[t.content_index];if(!a)throw new y(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new y(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const s=n.output[t.output_index];if(!s)throw new y(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{me(this,ae,t.response,"f");break}}return n},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=se(this,Ye,"f");if(!e)throw new y("stream ended without producing a ChatCompletion");return e}}function wa(r,e){return fa(r,e)}class pn extends A{constructor(){super(...arguments),this.inputItems=new ns(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ts(n),n))}retrieve(e,t={},n){return B(t)?this.retrieve(e,{},t):this._client.get(`/responses/${e}`,{query:t,...n})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>es(n,e))}stream(e,t){return mn.createResponse(this._client,e,t)}}class ba extends W{}pn.InputItems=ns;class rs extends A{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,Ae({body:t,...n}))}}class gn extends A{constructor(){super(...arguments),this.parts=new rs(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}gn.Parts=rs;const xa=async r=>{const e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length){for(const s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const n=[];for(const s of e)s.status==="fulfilled"&&n.push(s.value);return n};class _t extends A{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return B(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,yt,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const a=await this.retrieve(e,t,{...n,headers:s}).withResponse(),i=a.data;switch(i.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const u=a.response.headers.get("openai-poll-after-ms");if(u){const d=parseInt(u);isNaN(d)||(l=d)}}await Be(l);break;case"failed":case"completed":return i}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,_n,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class yt extends W{}class _n extends Ht{}_t.VectorStoreFilesPage=yt;_t.FileContentResponsesPage=_n;class ss extends A{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return B(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,yt,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:a,response:i}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(a.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const u=i.headers.get("openai-poll-after-ms");if(u){const d=parseInt(u);isNaN(d)||(l=d)}}await Be(l);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){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");const a=(s==null?void 0:s.maxConcurrency)??5,i=Math.min(a,t.length),l=this._client,u=t.values(),d=[...n];async function o(h){for(let f of h){const w=await l.files.create({file:f,purpose:"assistants"},s);d.push(w.id)}}const c=Array(i).fill(u).map(o);return await xa(c),await this.createAndPoll(e,{file_ids:d})}}class oe extends A{constructor(){super(...arguments),this.files=new _t(this._client),this.fileBatches=new ss(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e={},t){return B(e)?this.list({},e):this._client.getAPIList("/vector_stores",yn,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,wn,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class yn extends W{}class wn extends Ht{}oe.VectorStoresPage=yn;oe.VectorStoreSearchResponsesPage=wn;oe.Files=_t;oe.VectorStoreFilesPage=yt;oe.FileContentResponsesPage=_n;oe.FileBatches=ss;var as;class x extends Ws{constructor({baseURL:e=He("OPENAI_BASE_URL"),apiKey:t=He("OPENAI_API_KEY"),organization:n=He("OPENAI_ORG_ID")??null,project:s=He("OPENAI_PROJECT_ID")??null,...a}={}){if(t===void 0)throw new y("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const i={apiKey:t,organization:n,project:s,...a,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&Ys())throw new y(`It looks like you're running in a browser-like environment.
11
-
12
- This is disabled by default, as it risks exposing your secret API credentials to attackers.
13
- If you understand the risks and have appropriate mitigations in place,
14
- you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
15
-
16
- new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
17
-
18
- https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
19
- `);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new Qr(this),this.chat=new pt(this),this.embeddings=new zr(this),this.files=new an(this),this.images=new Yr(this),this.audio=new Ne(this),this.moderations=new Zr(this),this.models=new hn(this),this.fineTuning=new Le(this),this.vectorStores=new oe(this),this.beta=new Ce(this),this.batches=new Vt(this),this.uploads=new gn(this),this.responses=new pn(this),this._options=i,this.apiKey=t,this.organization=n,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Cs(e,{arrayFormat:"brackets"})}}as=x;x.OpenAI=as;x.DEFAULT_TIMEOUT=6e5;x.OpenAIError=y;x.APIError=j;x.APIConnectionError=ct;x.APIConnectionTimeoutError=Xt;x.APIUserAbortError=V;x.NotFoundError=or;x.ConflictError=lr;x.RateLimitError=ur;x.BadRequestError=sr;x.AuthenticationError=ar;x.InternalServerError=dr;x.PermissionDeniedError=ir;x.UnprocessableEntityError=cr;x.toFile=_r;x.fileFromPath=tr;x.Completions=Qr;x.Chat=pt;x.ChatCompletionsPage=mt;x.Embeddings=zr;x.Files=an;x.FileObjectsPage=on;x.Images=Yr;x.Audio=Ne;x.Moderations=Zr;x.Models=hn;x.ModelsPage=fn;x.FineTuning=Le;x.VectorStores=oe;x.VectorStoresPage=yn;x.VectorStoreSearchResponsesPage=wn;x.Beta=Ce;x.Batches=Vt;x.BatchesPage=Kt;x.Uploads=gn;x.Responses=pn;class Aa{constructor(){this.articles=[]}index(){return this.articles}create(e){const t={id:ds(),title:e.input.title,body:e.input.body,thumbnail:e.input.thumbnail,created_at:new Date().toISOString(),updated_at:new Date().toISOString()};return this.articles.push(t),t}update(e){const t=this.articles.find(n=>n.id===e.id);if(t===void 0)throw new Error("Unable to find the matched article.");e.input.title!==void 0&&(t.title=e.input.title),e.input.body!==void 0&&(t.body=e.input.body),e.input.thumbnail!==void 0&&(t.thumbnail=e.input.thumbnail),t.updated_at=new Date().toISOString()}erase(e){const t=this.articles.findIndex(n=>n.id===e.id);if(t===-1)throw new Error("Unable to find the matched article.");this.articles.splice(t,1)}}function Sa(r){const e=new Aa,t=new hs({model:"chatgpt",vendor:{api:new x({apiKey:r.apiKey,dangerouslyAllowBrowser:!0}),model:r.model??"gpt-4o-mini"},controllers:[{protocol:"class",name:"bbs",application:{model:"chatgpt",options:{reference:!1,strict:!1,separate:null},functions:[{name:"index",parameters:{description:"",type:"object",properties:{},additionalProperties:!1,required:[],$defs:{}},output:{description:"List of every articles",type:"array",items:{description:`Description of the current {@link IBbsArticle} type:
20
-
21
- > Article entity.
22
- >
23
- > \`IBbsArticle\` is an entity representing an article in the BBS (Bulletin Board System).`,type:"object",properties:{id:{title:"Primary Key",description:`Primary Key.
24
-
25
-
26
- @format uuid`,type:"string"},created_at:{title:"Creation time of the article",description:`Creation time of the article.
27
-
28
-
29
- @format date-time`,type:"string"},updated_at:{title:"Last updated time of the article",description:`Last updated time of the article.
30
-
31
-
32
- @format date-time`,type:"string"},title:{title:"Title of the article",description:`Title of the article.
33
-
34
- Representative title of the article.`,type:"string"},body:{title:"Content body",description:`Content body.
35
-
36
- Content body of the article writtn in the markdown format.`,type:"string"},thumbnail:{title:"Thumbnail image URI",description:`Thumbnail image URI.
37
-
38
- Thumbnail image URI which can represent the article.
39
-
40
- If configured as \`null\`, it means that no thumbnail image in the article.`,anyOf:[{type:"null"},{type:"string",description:`@format uri
41
- @contentMediaType image/*`}]}},required:["id","created_at","updated_at","title","body","thumbnail"]}},description:`Get all articles.
42
-
43
- List up every articles archived in the BBS DB.`,validate:n=>({success:!0,data:n})},{name:"create",parameters:{description:" Properties of create function",type:"object",properties:{input:{description:`Information of the article to create
44
-
45
- ------------------------------
46
-
47
- Description of the current {@link IBbsArticle.ICreate} type:
48
-
49
- > Information of the article to create.
50
-
51
- ------------------------------
52
-
53
- Description of the parent {@link IBbsArticle} type:
54
-
55
- > Article entity.
56
- >
57
- > \`IBbsArticle\` is an entity representing an article in the BBS (Bulletin Board System).`,type:"object",properties:{title:{title:"Title of the article",description:`Title of the article.
58
-
59
- Representative title of the article.`,type:"string"},body:{title:"Content body",description:`Content body.
60
-
61
- Content body of the article writtn in the markdown format.`,type:"string"},thumbnail:{title:"Thumbnail image URI",description:`Thumbnail image URI.
62
-
63
- Thumbnail image URI which can represent the article.
64
-
65
- If configured as \`null\`, it means that no thumbnail image in the article.`,anyOf:[{type:"null"},{type:"string",description:`@format uri
66
- @contentMediaType image/*`}]}},required:["title","body","thumbnail"]}},required:["input"],additionalProperties:!1,$defs:{}},output:{description:`Description of the current {@link IBbsArticle} type:
67
-
68
- > Article entity.
69
- >
70
- > \`IBbsArticle\` is an entity representing an article in the BBS (Bulletin Board System).`,type:"object",properties:{id:{title:"Primary Key",description:`Primary Key.
71
-
72
-
73
- @format uuid`,type:"string"},created_at:{title:"Creation time of the article",description:`Creation time of the article.
74
-
75
-
76
- @format date-time`,type:"string"},updated_at:{title:"Last updated time of the article",description:`Last updated time of the article.
77
-
78
-
79
- @format date-time`,type:"string"},title:{title:"Title of the article",description:`Title of the article.
80
-
81
- Representative title of the article.`,type:"string"},body:{title:"Content body",description:`Content body.
82
-
83
- Content body of the article writtn in the markdown format.`,type:"string"},thumbnail:{title:"Thumbnail image URI",description:`Thumbnail image URI.
84
-
85
- Thumbnail image URI which can represent the article.
86
-
87
- If configured as \`null\`, it means that no thumbnail image in the article.`,anyOf:[{type:"null"},{type:"string",description:`@format uri
88
- @contentMediaType image/*`}]}},required:["id","created_at","updated_at","title","body","thumbnail"]},description:`Create a new article.
89
-
90
- Writes a new article and archives it into the DB.`,validate:(()=>{const n=o=>typeof o.input=="object"&&o.input!==null&&s(o.input),s=o=>typeof o.title=="string"&&typeof o.body=="string"&&(o.thumbnail===null||typeof o.thumbnail=="string"&&We(o.thumbnail)),a=(o,c,h=!0)=>[(typeof o.input=="object"&&o.input!==null||d(h,{path:c+".input",expected:"IBbsArticle.ICreate",value:o.input}))&&i(o.input,c+".input",h)||d(h,{path:c+".input",expected:"IBbsArticle.ICreate",value:o.input})].every(f=>f),i=(o,c,h=!0)=>[typeof o.title=="string"||d(h,{path:c+".title",expected:"string",value:o.title}),typeof o.body=="string"||d(h,{path:c+".body",expected:"string",value:o.body}),o.thumbnail===null||typeof o.thumbnail=="string"&&(We(o.thumbnail)||d(h,{path:c+".thumbnail",expected:'string & Format<"uri">',value:o.thumbnail}))||d(h,{path:c+".thumbnail",expected:'((string & Format<"uri"> & ContentMediaType<"image/*">) | null)',value:o.thumbnail})].every(f=>f),l=o=>typeof o=="object"&&o!==null&&n(o);let u,d;return o=>{if(l(o)===!1){u=[],d=xt(u),((h,f,w=!0)=>(typeof h=="object"&&h!==null||d(!0,{path:f+"",expected:"__type",value:h}))&&a(h,f+"",!0)||d(!0,{path:f+"",expected:"__type",value:h}))(o,"$input",!0);const c=u.length===0;return c?{success:c,data:o}:{success:c,errors:u,data:o}}return{success:!0,data:o}}})()},{name:"update",parameters:{description:" Properties of update function",type:"object",properties:{id:{title:"Target article's {@link IBbsArticle.id}",description:`Target article's {@link IBbsArticle.id}.
91
-
92
-
93
- @format uuid`,type:"string"},input:{description:`New content to update.
94
-
95
- ------------------------------
96
-
97
- Description of the current {@link PartialIBbsArticle.ICreate} type:
98
-
99
- > Make all properties in T optional`,type:"object",properties:{title:{title:"Title of the article",description:`Title of the article.
100
-
101
- Representative title of the article.`,type:"string"},body:{title:"Content body",description:`Content body.
102
-
103
- Content body of the article writtn in the markdown format.`,type:"string"},thumbnail:{title:"Thumbnail image URI",description:`Thumbnail image URI.
104
-
105
- Thumbnail image URI which can represent the article.
106
-
107
- If configured as \`null\`, it means that no thumbnail image in the article.`,anyOf:[{type:"null"},{type:"string",description:`@format uri
108
- @contentMediaType image/*`}]}},required:[]}},required:["id","input"],additionalProperties:!1,$defs:{}},description:`Update an article.
109
-
110
- Updates an article with new content.`,validate:(()=>{const n=o=>typeof o.id=="string"&&Je(o.id)&&typeof o.input=="object"&&o.input!==null&&Array.isArray(o.input)===!1&&s(o.input),s=o=>(o.title===void 0||typeof o.title=="string")&&(o.body===void 0||typeof o.body=="string")&&(o.thumbnail===null||o.thumbnail===void 0||typeof o.thumbnail=="string"&&We(o.thumbnail)),a=(o,c,h=!0)=>[typeof o.id=="string"&&(Je(o.id)||d(h,{path:c+".id",expected:'string & Format<"uuid">',value:o.id}))||d(h,{path:c+".id",expected:'(string & Format<"uuid">)',value:o.id}),(typeof o.input=="object"&&o.input!==null&&Array.isArray(o.input)===!1||d(h,{path:c+".input",expected:"Partial<IBbsArticle.ICreate>",value:o.input}))&&i(o.input,c+".input",h)||d(h,{path:c+".input",expected:"Partial<IBbsArticle.ICreate>",value:o.input})].every(f=>f),i=(o,c,h=!0)=>[o.title===void 0||typeof o.title=="string"||d(h,{path:c+".title",expected:"(string | undefined)",value:o.title}),o.body===void 0||typeof o.body=="string"||d(h,{path:c+".body",expected:"(string | undefined)",value:o.body}),o.thumbnail===null||o.thumbnail===void 0||typeof o.thumbnail=="string"&&(We(o.thumbnail)||d(h,{path:c+".thumbnail",expected:'string & Format<"uri">',value:o.thumbnail}))||d(h,{path:c+".thumbnail",expected:'((string & Format<"uri"> & ContentMediaType<"image/*">) | null | undefined)',value:o.thumbnail})].every(f=>f),l=o=>typeof o=="object"&&o!==null&&n(o);let u,d;return o=>{if(l(o)===!1){u=[],d=xt(u),((h,f,w=!0)=>(typeof h=="object"&&h!==null||d(!0,{path:f+"",expected:"__type",value:h}))&&a(h,f+"",!0)||d(!0,{path:f+"",expected:"__type",value:h}))(o,"$input",!0);const c=u.length===0;return c?{success:c,data:o}:{success:c,errors:u,data:o}}return{success:!0,data:o}}})()},{name:"erase",parameters:{description:" Properties of erase function",type:"object",properties:{id:{title:"Target article's {@link IBbsArticle.id}",description:`Target article's {@link IBbsArticle.id}.
111
-
112
-
113
- @format uuid`,type:"string"}},required:["id"],additionalProperties:!1,$defs:{}},description:`Erase an article.
114
-
115
- Erases an article from the DB.`,validate:(()=>{const n=u=>typeof u.id=="string"&&Je(u.id),s=(u,d,o=!0)=>[typeof u.id=="string"&&(Je(u.id)||l(o,{path:d+".id",expected:'string & Format<"uuid">',value:u.id}))||l(o,{path:d+".id",expected:'(string & Format<"uuid">)',value:u.id})].every(c=>c),a=u=>typeof u=="object"&&u!==null&&n(u);let i,l;return u=>{if(a(u)===!1){i=[],l=xt(i),((o,c,h=!0)=>(typeof o=="object"&&o!==null||l(!0,{path:c+"",expected:"__type",value:o}))&&s(o,c+"",!0)||l(!0,{path:c+"",expected:"__type",value:o}))(u,"$input",!0);const d=i.length===0;return d?{success:d,data:u}:{success:d,errors:i,data:u}}return{success:!0,data:u}}})()}]},execute:e}],config:{locale:r.locale,timezone:r.timezone,executor:{initialize:null}}});return I.jsx(fs,{agent:t})}function Ca(){const[r,e]=Ue.useState(""),[t,n]=Ue.useState("gpt-4o-mini"),[s,a]=Ue.useState(window.navigator.language),[i,l]=Ue.useState(!1);return I.jsx("div",{style:{width:"100%",height:"100%"},children:i===!0?I.jsx(Sa,{apiKey:r,model:t,locale:s}):I.jsxs(ls,{style:{width:"calc(100% - 60px)",padding:15,margin:15},children:[I.jsx(bt,{variant:"h6",children:"BBS AI Chatbot"}),I.jsx("br",{}),I.jsx(ms,{}),I.jsx("br",{}),"Demonstration of Agentica with TypeScript Controller Class.",I.jsx("br",{}),I.jsx("br",{}),I.jsx(bt,{variant:"h6",children:" OpenAI Configuration "}),I.jsx(xn,{onChange:u=>e(u.target.value),defaultValue:r,label:"OpenAI API Key",variant:"outlined",placeholder:"Your OpenAI API Key",error:r.length===0}),I.jsx("br",{}),I.jsxs(cs,{defaultValue:t,onChange:(u,d)=>n(d),style:{paddingLeft:15},children:[I.jsx(An,{control:I.jsx(Sn,{}),label:"GPT-4o Mini",value:"gpt-4o-mini"}),I.jsx(An,{control:I.jsx(Sn,{}),label:"GPT-4o",value:"gpt-4o"})]}),I.jsx("br",{}),I.jsx(bt,{variant:"h6",children:" Membership Information "}),I.jsx("br",{}),I.jsx(xn,{onChange:u=>a(u.target.value),defaultValue:s,label:"Locale",variant:"outlined",error:s.length===0}),I.jsx("br",{}),I.jsx("br",{}),I.jsx(us,{component:"a",fullWidth:!0,variant:"contained",color:"info",size:"large",disabled:r.length===0||s.length===0,onClick:()=>l(!0),children:"Start AI Chatbot"})]})})}os(window.document.getElementById("root")).render(I.jsx(Ca,{}));