shiplightai 0.1.36 → 0.1.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agentHelpers-YPJ5MC66.js → agentHelpers-NOLZIR3C.js} +1 -1
- package/dist/chunk-OR7KAD4P.js +11 -0
- package/dist/{chunk-PTSNTQWC.js → chunk-P4BBXZ3G.js} +1 -1
- package/dist/{chunk-GSIC3VVD.js → chunk-R7ATSUFU.js} +12 -12
- package/dist/{chunk-NVQUBIDY.js → chunk-UXUHCP6Q.js} +5 -5
- package/dist/{chunk-CYYG6ENT.js → chunk-Y2PSXQRK.js} +4 -4
- package/dist/cjs/debugger-pw.cjs +10 -8
- package/dist/cjs/fixture.cjs +19 -19
- package/dist/cjs/index.cjs +119 -119
- package/dist/cjs/reporter.cjs +22 -22
- package/dist/cli.js +65 -68
- package/dist/debugger-pw.d.ts +12 -10
- package/dist/debugger-pw.js +9 -5
- package/dist/{dist-KCCHXIDD.js → dist-5DXUMQPG.js} +1 -1
- package/dist/{dist-HCR36MMH.js → dist-GUSOYM4N.js} +1 -1
- package/dist/fixture.js +1 -1
- package/dist/{handler-MFCBIUIL.js → handler-SLPMHZMZ.js} +1 -1
- package/dist/index.js +1 -1
- package/dist/reporter.js +1 -1
- package/dist/{task-2SW3VSRI.js → task-5YHIIFEV.js} +1 -1
- package/dist/{testFlow-CMH7ZZR3.js → testFlow-HMS3VHCY.js} +1 -1
- package/package.json +2 -4
- package/dist/chunk-G7KWIGKV.js +0 -11
- package/dist/copilot-7JTVJQXP.js +0 -5
- /package/dist/{chunk-GBWDXF5V.js → chunk-7MOSQQFJ.js} +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
const require = __createRequire(import.meta.url);
|
|
3
|
-
import{b as gt,c as Or,d as Tr,e as Fr,f as Nr,n as Mr}from"./chunk-
|
|
3
|
+
import{b as gt,c as Or,d as Tr,e as Fr,f as Nr,n as Mr}from"./chunk-7MOSQQFJ.js";import{h as fn,l as hn}from"./chunk-ZI57Y3IM.js";import{a as ee}from"./chunk-T3H4NEVX.js";import{b as un,d as ws}from"./chunk-T2JTBHI7.js";import{zodToJsonSchema as pn}from"zod-to-json-schema";function Lr(s){let e=pn(s,{$refStrategy:"none"});if(e.$schema&&delete e.$schema,e.type!=="object")throw new Error(`Schema must be a Zod object schema, got type: ${e.type}`);return ur(e),e}function ha(s){return pn(s,{$refStrategy:"none"})}function ur(s){if(!(typeof s!="object"||s===null)){if(s.type==="object"&&(s.additionalProperties=!1,s.properties)){let e=Object.keys(s.properties);s.required=e;for(let t of Object.values(s.properties))ur(t)}s.type==="array"&&s.items&&ur(s.items);for(let e of["anyOf","oneOf","allOf"])Array.isArray(s[e])&&s[e].forEach(ur);for(let[e,t]of Object.entries(s))typeof t=="object"&&t!==null&&!["properties","items","anyOf","oneOf","allOf"].includes(e)&&ur(t)}}var dn=class{constructor(s){this.registry=s}getToolDefinitions(){return this.registry.getTools().filter(s=>s.availability.openai).map(s=>({type:"function",function:{name:s.name,description:s.description,parameters:Lr(s.schema),strict:!0}}))}getToolDefinitionsFiltered(s){let e=new Set(s);return this.registry.getTools().filter(t=>e.has(t.name)&&t.availability.openai).map(t=>({type:"function",function:{name:t.name,description:t.description,parameters:Lr(t.schema),strict:!0}}))}toJSON(){return this.getToolDefinitions()}getToolDefinition(s){let e=this.registry.get(s);if(e)return{type:"function",function:{name:e.name,description:e.description,parameters:Lr(e.schema),strict:!0}}}getToolCount(){return this.registry.size()}getToolNames(){return this.registry.getToolNames()}};function So(s,e){let t=new Map;for(let u of e)u.hash&&u.url?t.set(u.hash,u.url):u.uuid&&u.url&&t.set(u.uuid,u.url);let r=/!\[([^\]]*)\]\(image:([a-f0-9]{64}|[a-zA-Z0-9\-]+)\)/g,n=[],o=0,i;for(;(i=r.exec(s))!==null;){let u=s.slice(o,i.index);u&&n.push({type:"text",text:u});let p=i[2];t.has(p)?n.push({type:"image",image:new URL(t.get(p))}):n.push({type:"text",text:i[0]}),o=i.index+i[0].length}let a=s.slice(o);return a&&n.push({type:"text",text:a}),n.length===0&&n.push({type:"text",text:s}),n}function vo(s){let e=[];for(let t of s){let r=t.content||"",n=t.images||[],o=So(r,n);e.length>0&&o.length>0&&e.push({type:"text",text:`
|
|
4
4
|
|
|
5
5
|
`}),e.push(...o)}return e}var mn=!1;function jr(s,e=mn){if(e){let t=vo(s);if(t.length===0)return[];let r={type:"text",text:`
|
|
6
6
|
|
|
@@ -122,7 +122,7 @@ To use them, write Jinja-like template syntax: {{ placeholder_name }}
|
|
|
122
122
|
`}if(r&&r.length>0){let h=Ro(r);_+=`
|
|
123
123
|
`+h}return _+=`
|
|
124
124
|
Based on the above information, please determine the right action to accomplish the task.
|
|
125
|
-
`,m.push({type:"text",text:_}),m}function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function l(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var xs=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return xs=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function fr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var hr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var y=class extends Error{},B=class s extends y{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Re({message:r,cause:hr(t)});let o=t?.error;return e===400?new _t(e,o,r,n):e===401?new yt(e,o,r,n):e===403?new bt(e,o,r,n):e===404?new wt(e,o,r,n):e===409?new xt(e,o,r,n):e===422?new At(e,o,r,n):e===429?new It(e,o,r,n):e>=500?new St(e,o,r,n):new s(e,o,r,n)}},L=class extends B{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Re=class extends B{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},Ee=class extends Re{constructor({message:e}={}){super({message:e??"Request timed out."})}},_t=class extends B{},yt=class extends B{},bt=class extends B{},wt=class extends B{},xt=class extends B{},At=class extends B{},It=class extends B{},St=class extends B{},vt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},Pt=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},oe=class extends Error{constructor(e){super(e)}};var Co=/^[a-z][a-z0-9+.-]*:/i,bn=s=>Co.test(s),J=s=>(J=Array.isArray,J(s)),As=J;function Is(s){return typeof s!="object"?{}:s??{}}function wn(s){if(!s)return!0;for(let e in s)return!1;return!0}function xn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function pr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var An=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${s} must be an integer`);if(e<0)throw new y(`${s} must be a positive integer`);return e};var In=s=>{try{return JSON.parse(s)}catch{return}};var ie=s=>new Promise(e=>setTimeout(e,s));var Ce="6.25.0";var Rn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function $o(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var ko=()=>{let s=$o();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":vn(Deno.build.os),"X-Stainless-Arch":Sn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":vn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Sn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Oo();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Oo(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var Sn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",vn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Pn,En=()=>Pn??(Pn=ko());function Cn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ss(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Br(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Ss({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function vs(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function $n(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var kn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ur="RFC3986",Ps=s=>String(s),Dr={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:Ps},Rs="RFC1738";var Hr=(s,e)=>(Hr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Hr(s,e)),ae=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Es=1024,On=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=Es){let u=o.length>=Es?o.slice(a,a+Es):o,p=[];for(let m=0;m<u.length;++m){let d=u.charCodeAt(m);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===Rs&&(d===40||d===41)){p[p.length]=u.charAt(m);continue}if(d<128){p[p.length]=ae[d];continue}if(d<2048){p[p.length]=ae[192|d>>6]+ae[128|d&63];continue}if(d<55296||d>=57344){p[p.length]=ae[224|d>>12]+ae[128|d>>6&63]+ae[128|d&63];continue}m+=1,d=65536+((d&1023)<<10|u.charCodeAt(m)&1023),p[p.length]=ae[240|d>>18]+ae[128|d>>12&63]+ae[128|d>>6&63]+ae[128|d&63]}i+=p.join("")}return i};function Tn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Cs(s,e){if(J(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Nn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Mn=function(s,e){Array.prototype.push.apply(s,J(e)?e:[e])},Fn,U={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:On,encodeValuesOnly:!1,format:Ur,formatter:Ps,indices:!1,serializeDate(s){return(Fn??(Fn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function No(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var $s={};function Ln(s,e,t,r,n,o,i,a,u,p,m,d,_,h,A,b,R,v){let w=s,k=v,P=0,E=!1;for(;(k=k.get($s))!==void 0&&!E;){let T=k.get(s);if(P+=1,typeof T<"u"){if(T===P)throw new RangeError("Cyclic object value");E=!0}typeof k.get($s)>"u"&&(P=0)}if(typeof p=="function"?w=p(e,w):w instanceof Date?w=_?.(w):t==="comma"&&J(w)&&(w=Cs(w,function(T){return T instanceof Date?_?.(T):T})),w===null){if(o)return u&&!b?u(e,U.encoder,R,"key",h):e;w=""}if(No(w)||Tn(w)){if(u){let T=b?e:u(e,U.encoder,R,"key",h);return[A?.(T)+"="+A?.(u(w,U.encoder,R,"value",h))]}return[A?.(e)+"="+A?.(String(w))]}let O=[];if(typeof w>"u")return O;let C;if(t==="comma"&&J(w))b&&u&&(w=Cs(w,u)),C=[{value:w.length>0?w.join(",")||null:void 0}];else if(J(p))C=p;else{let T=Object.keys(w);C=m?T.sort(m):T}let F=a?String(e).replace(/\./g,"%2E"):String(e),N=r&&J(w)&&w.length===1?F+"[]":F;if(n&&J(w)&&w.length===0)return N+"[]";for(let T=0;T<C.length;++T){let $=C[T],Ie=typeof $=="object"&&typeof $.value<"u"?$.value:w[$];if(i&&Ie===null)continue;let Q=d&&a?$.replace(/\./g,"%2E"):$,dt=J(w)?typeof t=="function"?t(N,Q):N:N+(d?"."+Q:"["+Q+"]");v.set(s,P);let We=new WeakMap;We.set($s,v),Mn(O,Ln(Ie,dt,t,r,n,o,i,a,t==="comma"&&b&&J(w)?null:u,p,m,d,_,h,A,b,R,We))}return O}function Mo(s=U){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||U.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Ur;if(typeof s.format<"u"){if(!Hr(Dr,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Dr[t],n=U.filter;(typeof s.filter=="function"||J(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Nn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=U.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:U.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:U.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:U.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:U.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?U.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:U.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:U.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:U.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:U.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:U.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:U.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:U.strictNullHandling}}function ks(s,e={}){let t=s,r=Mo(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):J(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let a=Nn[r.arrayFormat],u=a==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let _=0;_<n.length;++_){let h=n[_];r.skipNulls&&t[h]===null||Mn(i,Ln(t[h],h,a,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,p))}let m=i.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),m.length>0?d+m:""}function Un(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var jn;function Rt(s){let e;return(jn??(e=new globalThis.TextEncoder,jn=e.encode.bind(e)))(s)}var Bn;function Os(s){let e;return(Bn??(e=new globalThis.TextDecoder,Bn=e.decode.bind(e)))(s)}var z,G,qe=class{constructor(){z.set(this,void 0),G.set(this,void 0),x(this,z,new Uint8Array,"f"),x(this,G,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Rt(e):e;x(this,z,Un([l(this,z,"f"),t]),"f");let r=[],n;for(;(n=jo(l(this,z,"f"),l(this,G,"f")))!=null;){if(n.carriage&&l(this,G,"f")==null){x(this,G,n.index,"f");continue}if(l(this,G,"f")!=null&&(n.index!==l(this,G,"f")+1||n.carriage)){r.push(Os(l(this,z,"f").subarray(0,l(this,G,"f")-1))),x(this,z,l(this,z,"f").subarray(l(this,G,"f")),"f"),x(this,G,null,"f");continue}let o=l(this,G,"f")!==null?n.preceding-1:n.preceding,i=Os(l(this,z,"f").subarray(0,o));r.push(i),x(this,z,l(this,z,"f").subarray(n.index),"f"),x(this,G,null,"f")}return r}flush(){return l(this,z,"f").length?this.decode(`
|
|
125
|
+
`,m.push({type:"text",text:_}),m}function x(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t}function l(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)}var xs=function(){let{crypto:s}=globalThis;if(s?.randomUUID)return xs=s.randomUUID.bind(s),s.randomUUID();let e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function fr(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}var hr=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){let e=new Error(s.message,s.cause?{cause:s.cause}:{});return s.stack&&(e.stack=s.stack),s.cause&&!e.cause&&(e.cause=s.cause),s.name&&(e.name=s.name),e}}catch{}try{return new Error(JSON.stringify(s))}catch{}}return new Error(s)};var y=class extends Error{},B=class s extends y{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new Se({message:r,cause:hr(t)});let o=t?.error;return e===400?new _t(e,o,r,n):e===401?new yt(e,o,r,n):e===403?new bt(e,o,r,n):e===404?new wt(e,o,r,n):e===409?new xt(e,o,r,n):e===422?new At(e,o,r,n):e===429?new It(e,o,r,n):e>=500?new St(e,o,r,n):new s(e,o,r,n)}},L=class extends B{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Se=class extends B{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ve=class extends Se{constructor({message:e}={}){super({message:e??"Request timed out."})}},_t=class extends B{},yt=class extends B{},bt=class extends B{},wt=class extends B{},xt=class extends B{},At=class extends B{},It=class extends B{},St=class extends B{},vt=class extends y{constructor(){super("Could not parse response content as the length limit was reached")}},Pt=class extends y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},oe=class extends Error{constructor(e){super(e)}};var Co=/^[a-z][a-z0-9+.-]*:/i,bn=s=>Co.test(s),q=s=>(q=Array.isArray,q(s)),As=q;function Is(s){return typeof s!="object"?{}:s??{}}function wn(s){if(!s)return!0;for(let e in s)return!1;return!0}function xn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function pr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var An=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new y(`${s} must be an integer`);if(e<0)throw new y(`${s} must be a positive integer`);return e};var In=s=>{try{return JSON.parse(s)}catch{return}};var ie=s=>new Promise(e=>setTimeout(e,s));var Pe="6.25.0";var Rn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function $o(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var ko=()=>{let s=$o();if(s==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"X-Stainless-OS":vn(Deno.build.os),"X-Stainless-Arch":Sn(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(s==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"X-Stainless-OS":vn(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Sn(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Oo();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Pe,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Oo(){if(typeof navigator>"u"||!navigator)return null;let s=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var Sn=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",vn=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Pn,En=()=>Pn??(Pn=ko());function Cn(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ss(...s){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...s)}function Br(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Ss({start(){},async pull(t){let{done:r,value:n}=await e.next();r?t.close():t.enqueue(n)},async cancel(){await e.return?.()}})}function vs(s){if(s[Symbol.asyncIterator])return s;let e=s.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function $n(s){if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await s[Symbol.asyncIterator]().return?.();return}let e=s.getReader(),t=e.cancel();e.releaseLock(),await t}var kn=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Ur="RFC3986",Ps=s=>String(s),Dr={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:Ps},Rs="RFC1738";var Hr=(s,e)=>(Hr=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Hr(s,e)),ae=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Es=1024,On=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=Es){let u=o.length>=Es?o.slice(a,a+Es):o,p=[];for(let m=0;m<u.length;++m){let d=u.charCodeAt(m);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||n===Rs&&(d===40||d===41)){p[p.length]=u.charAt(m);continue}if(d<128){p[p.length]=ae[d];continue}if(d<2048){p[p.length]=ae[192|d>>6]+ae[128|d&63];continue}if(d<55296||d>=57344){p[p.length]=ae[224|d>>12]+ae[128|d>>6&63]+ae[128|d&63];continue}m+=1,d=65536+((d&1023)<<10|u.charCodeAt(m)&1023),p[p.length]=ae[240|d>>18]+ae[128|d>>12&63]+ae[128|d>>6&63]+ae[128|d&63]}i+=p.join("")}return i};function Tn(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Cs(s,e){if(q(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var Nn={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},Mn=function(s,e){Array.prototype.push.apply(s,q(e)?e:[e])},Fn,U={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:On,encodeValuesOnly:!1,format:Ur,formatter:Ps,indices:!1,serializeDate(s){return(Fn??(Fn=Function.prototype.call.bind(Date.prototype.toISOString)))(s)},skipNulls:!1,strictNullHandling:!1};function No(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var $s={};function Ln(s,e,t,r,n,o,i,a,u,p,m,d,_,h,A,b,R,v){let w=s,k=v,P=0,E=!1;for(;(k=k.get($s))!==void 0&&!E;){let T=k.get(s);if(P+=1,typeof T<"u"){if(T===P)throw new RangeError("Cyclic object value");E=!0}typeof k.get($s)>"u"&&(P=0)}if(typeof p=="function"?w=p(e,w):w instanceof Date?w=_?.(w):t==="comma"&&q(w)&&(w=Cs(w,function(T){return T instanceof Date?_?.(T):T})),w===null){if(o)return u&&!b?u(e,U.encoder,R,"key",h):e;w=""}if(No(w)||Tn(w)){if(u){let T=b?e:u(e,U.encoder,R,"key",h);return[A?.(T)+"="+A?.(u(w,U.encoder,R,"value",h))]}return[A?.(e)+"="+A?.(String(w))]}let O=[];if(typeof w>"u")return O;let C;if(t==="comma"&&q(w))b&&u&&(w=Cs(w,u)),C=[{value:w.length>0?w.join(",")||null:void 0}];else if(q(p))C=p;else{let T=Object.keys(w);C=m?T.sort(m):T}let F=a?String(e).replace(/\./g,"%2E"):String(e),N=r&&q(w)&&w.length===1?F+"[]":F;if(n&&q(w)&&w.length===0)return N+"[]";for(let T=0;T<C.length;++T){let $=C[T],Ie=typeof $=="object"&&typeof $.value<"u"?$.value:w[$];if(i&&Ie===null)continue;let Q=d&&a?$.replace(/\./g,"%2E"):$,dt=q(w)?typeof t=="function"?t(N,Q):N:N+(d?"."+Q:"["+Q+"]");v.set(s,P);let Ue=new WeakMap;Ue.set($s,v),Mn(O,Ln(Ie,dt,t,r,n,o,i,a,t==="comma"&&b&&q(w)?null:u,p,m,d,_,h,A,b,R,Ue))}return O}function Mo(s=U){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||U.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Ur;if(typeof s.format<"u"){if(!Hr(Dr,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=Dr[t],n=U.filter;(typeof s.filter=="function"||q(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Nn?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=U.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:U.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:U.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:U.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:U.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?U.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:U.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:U.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:U.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:U.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:U.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:U.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:U.strictNullHandling}}function ks(s,e={}){let t=s,r=Mo(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):q(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let a=Nn[r.arrayFormat],u=a==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let p=new WeakMap;for(let _=0;_<n.length;++_){let h=n[_];r.skipNulls&&t[h]===null||Mn(i,Ln(t[h],h,a,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,p))}let m=i.join(r.delimiter),d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),m.length>0?d+m:""}function Un(s){let e=0;for(let n of s)e+=n.length;let t=new Uint8Array(e),r=0;for(let n of s)t.set(n,r),r+=n.length;return t}var jn;function Rt(s){let e;return(jn??(e=new globalThis.TextEncoder,jn=e.encode.bind(e)))(s)}var Bn;function Os(s){let e;return(Bn??(e=new globalThis.TextDecoder,Bn=e.decode.bind(e)))(s)}var z,G,qe=class{constructor(){z.set(this,void 0),G.set(this,void 0),x(this,z,new Uint8Array,"f"),x(this,G,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Rt(e):e;x(this,z,Un([l(this,z,"f"),t]),"f");let r=[],n;for(;(n=jo(l(this,z,"f"),l(this,G,"f")))!=null;){if(n.carriage&&l(this,G,"f")==null){x(this,G,n.index,"f");continue}if(l(this,G,"f")!=null&&(n.index!==l(this,G,"f")+1||n.carriage)){r.push(Os(l(this,z,"f").subarray(0,l(this,G,"f")-1))),x(this,z,l(this,z,"f").subarray(l(this,G,"f")),"f"),x(this,G,null,"f");continue}let o=l(this,G,"f")!==null?n.preceding-1:n.preceding,i=Os(l(this,z,"f").subarray(0,o));r.push(i),x(this,z,l(this,z,"f").subarray(n.index),"f"),x(this,G,null,"f")}return r}flush(){return l(this,z,"f").length?this.decode(`
|
|
126
126
|
`):[]}};z=new WeakMap,G=new WeakMap;qe.NEWLINE_CHARS=new Set([`
|
|
127
127
|
`,"\r"]);qe.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function jo(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Dn(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}var qr={off:0,error:200,warn:300,info:400,debug:500},Ts=(s,e,t)=>{if(s){if(xn(qr,s))return s;M(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(qr))}`)}};function dr(){}function Wr(s,e,t){return!e||qr[s]>qr[t]?dr:e[s].bind(e)}var Bo={error:dr,warn:dr,info:dr,debug:dr},Hn=new WeakMap;function M(s){let e=s.logger,t=s.logLevel??"off";if(!e)return Bo;let r=Hn.get(e);if(r&&r[0]===t)return r[1];let n={error:Wr("error",e,t),warn:Wr("warn",e,t),info:Wr("info",e,t),debug:Wr("debug",e,t)};return Hn.set(e,[t,n]),n}var he=s=>(s.options&&(s.options={...s.options},delete s.options.headers),s.headers&&(s.headers=Object.fromEntries((s.headers instanceof Headers?[...s.headers]:Object.entries(s.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in s&&(s.retryOfRequestLogID&&(s.retryOf=s.retryOfRequestLogID),delete s.retryOfRequestLogID),s);var mr,le=class s{constructor(e,t,r){this.iterator=e,mr.set(this,void 0),this.controller=t,x(this,mr,r,"f")}static fromSSEResponse(e,t,r,n){let o=!1,i=r?M(r):console;async function*a(){if(o)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");o=!0;let u=!1;try{for await(let p of Uo(e,t))if(!u){if(p.data.startsWith("[DONE]")){u=!0;continue}if(p.event===null||!p.event.startsWith("thread.")){let m;try{m=JSON.parse(p.data)}catch(d){throw i.error("Could not parse message into JSON:",p.data),i.error("From chunk:",p.raw),d}if(m&&m.error)throw new B(void 0,m.error,void 0,e.headers);yield n?{event:p.event,data:m}:m}else{let m;try{m=JSON.parse(p.data)}catch(d){throw console.error("Could not parse message into JSON:",p.data),console.error("From chunk:",p.raw),d}if(p.event=="error")throw new B(void 0,m.error,m.message,void 0);yield{event:p.event,data:m}}}u=!0}catch(p){if(fr(p))return;throw p}finally{u||t.abort()}}return new s(a,t,r)}static fromReadableStream(e,t,r){let n=!1;async function*o(){let a=new qe,u=vs(e);for await(let p of u)for(let m of a.decode(p))yield m;for(let p of a.flush())yield p}async function*i(){if(n)throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(let u of o())a||u&&(yield JSON.parse(u));a=!0}catch(u){if(fr(u))return;throw u}finally{a||t.abort()}}return new s(i,t,r)}[(mr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new s(()=>n(e),this.controller,l(this,mr,"f")),new s(()=>n(t),this.controller,l(this,mr,"f"))]}toReadableStream(){let e=this,t;return Ss({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{let{value:n,done:o}=await t.next();if(o)return r.close();let i=Rt(JSON.stringify(n)+`
|
|
128
128
|
`);r.enqueue(i)}catch(n){r.error(n)}},async cancel(){await t.return?.()}})}};async function*Uo(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new y("Attempted to iterate over a response with no body");let t=new Fs,r=new qe,n=vs(s.body);for await(let o of Do(n))for(let i of r.decode(o)){let a=t.decode(i);a&&(yield a)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*Do(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Rt(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Dn(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Fs=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
|
|
@@ -130,12 +130,12 @@ Based on the above information, please determine the right action to accomplish
|
|
|
130
130
|
${o.map(_=>_.error).join(`
|
|
131
131
|
`)}
|
|
132
132
|
${i}
|
|
133
|
-
${d}`)}return i},c=Go(Xn);var Ke=class extends f{list(e,t={},r){return this._client.getAPIList(c`/chat/completions/${e}/messages`,S,{query:t,...r})}};function wr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function xr(s){return s?.$brand==="auto-parseable-response-format"}function Ve(s){return s?.$brand==="auto-parseable-tool"}function zn(s,e){return!e||!Us(e)?{...s,choices:s.choices.map(t=>(Yn(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Ar(s,e)}function Ar(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new vt;if(r.finish_reason==="content_filter")throw new Pt;return Yn(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>ei(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Zo(e,r.message.content):null}}});return{...s,choices:t}}function Zo(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function ei(s,e){let t=s.tools?.find(r=>wr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ve(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Gn(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>wr(r)&&r.function?.name===e.function.name);return wr(t)&&(Ve(t)||t?.function.strict||!1)}function Us(s){return xr(s.response_format)?!0:s.tools?.some(e=>Ve(e)||e.type==="function"&&e.function.strict===!0)??!1}function Yn(s){for(let e of s||[])if(e.type!=="function")throw new y(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Qn(s){for(let e of s??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Ct=s=>s?.role==="assistant",Ds=s=>s?.role==="tool";var Hs,zr,Gr,Ir,Sr,Yr,vr,me,Pr,Qr,Zr,$t,Zn,$e=class{constructor(){Hs.add(this),this.controller=new AbortController,zr.set(this,void 0),Gr.set(this,()=>{}),Ir.set(this,()=>{}),Sr.set(this,void 0),Yr.set(this,()=>{}),vr.set(this,()=>{}),me.set(this,{}),Pr.set(this,!1),Qr.set(this,!1),Zr.set(this,!1),$t.set(this,!1),x(this,zr,new Promise((e,t)=>{x(this,Gr,e,"f"),x(this,Ir,t,"f")}),"f"),x(this,Sr,new Promise((e,t)=>{x(this,Yr,e,"f"),x(this,vr,t,"f")}),"f"),l(this,zr,"f").catch(()=>{}),l(this,Sr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},l(this,Hs,"m",Zn).bind(this))},0)}_connected(){this.ended||(l(this,Gr,"f").call(this),this._emit("connect"))}get ended(){return l(this,Pr,"f")}get errored(){return l(this,Qr,"f")}get aborted(){return l(this,Zr,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,me,"f")[e]||(l(this,me,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=l(this,me,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(l(this,me,"f")[e]||(l(this,me,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{x(this,$t,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){x(this,$t,!0,"f"),await l(this,Sr,"f")}_emit(e,...t){if(l(this,Pr,"f"))return;e==="end"&&(x(this,Pr,!0,"f"),l(this,Yr,"f").call(this));let r=l(this,me,"f")[e];if(r&&(l(this,me,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!l(this,$t,"f")&&!r?.length&&Promise.reject(n),l(this,Ir,"f").call(this,n),l(this,vr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!l(this,$t,"f")&&!r?.length&&Promise.reject(n),l(this,Ir,"f").call(this,n),l(this,vr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};zr=new WeakMap,Gr=new WeakMap,Ir=new WeakMap,Sr=new WeakMap,Yr=new WeakMap,vr=new WeakMap,me=new WeakMap,Pr=new WeakMap,Qr=new WeakMap,Zr=new WeakMap,$t=new WeakMap,Hs=new WeakSet,Zn=function(e){if(x(this,Qr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new L),e instanceof L)return x(this,Zr,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){let t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};function eo(s){return typeof s.parse=="function"}var X,Ws,es,qs,Js,Ks,to,ro,ti=10,kt=class extends $e{constructor(){super(...arguments),X.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),Ds(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Ct(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),l(this,X,"m",Ws).call(this)}async finalMessage(){return await this.done(),l(this,X,"m",es).call(this)}async finalFunctionToolCall(){return await this.done(),l(this,X,"m",qs).call(this)}async finalFunctionToolCallResult(){return await this.done(),l(this,X,"m",Js).call(this)}async totalUsage(){return await this.done(),l(this,X,"m",Ks).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=l(this,X,"m",es).call(this);t&&this._emit("finalMessage",t);let r=l(this,X,"m",Ws).call(this);r&&this._emit("finalContent",r);let n=l(this,X,"m",qs).call(this);n&&this._emit("finalFunctionToolCall",n);let o=l(this,X,"m",Js).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",l(this,X,"m",Ks).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,X,"m",to).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ar(o,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let n="tool",{tool_choice:o="auto",stream:i,...a}=t,u=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:p=ti}=r||{},m=t.tools.map(h=>{if(Ve(h)){if(!h.$callback)throw new y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),d={};for(let h of m)h.type==="function"&&(d[h.function.name||h.function.function.name]=h.function);let _="tools"in t?m.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of t.messages)this._addMessage(h,!1);for(let h=0;h<p;++h){let b=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:_,messages:[...this.messages]},r)).choices[0]?.message;if(!b)throw new y("missing message in ChatCompletion response");if(!b.tool_calls?.length)return;for(let R of b.tool_calls){if(R.type!=="function")continue;let v=R.id,{name:w,arguments:k}=R.function,P=d[w];if(P){if(u&&u!==w){let F=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:n,tool_call_id:v,content:F});continue}}else{let F=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(d).map(N=>JSON.stringify(N)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:v,content:F});continue}let E;try{E=eo(P)?await P.parse(k):k}catch(F){let N=F instanceof Error?F.message:String(F);this._addMessage({role:n,tool_call_id:v,content:N});continue}let O=await P.function(E,this),C=l(this,X,"m",ro).call(this,O);if(this._addMessage({role:n,tool_call_id:v,content:C}),u)return}}}};X=new WeakSet,Ws=function(){return l(this,X,"m",es).call(this).content??null},es=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Ct(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},qs=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ct(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},Js=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ds(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},Ks=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},to=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.")},ro=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Rr=class s extends kt{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),Ct(e)&&e.content&&this._emit("content",e.content)}};var H={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Vs=class extends Error{},Xs=class extends Error{};function ri(s,e=H.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return si(s.trim(),e)}var si=(s,e)=>{let t=s.length,r=0,n=_=>{throw new Vs(`${_} at position ${r}`)},o=_=>{throw new Xs(`${_} at position ${r}`)},i=()=>(d(),r>=t&&n("Unexpected end of input"),s[r]==='"'?a():s[r]==="{"?u():s[r]==="["?p():s.substring(r,r+4)==="null"||H.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||H.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||H.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||H.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||H.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||H.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):m()),a=()=>{let _=r,h=!1;for(r++;r<t&&(s[r]!=='"'||h&&s[r-1]==="\\");)h=s[r]==="\\"?!h:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(_,++r-Number(h)))}catch(A){o(String(A))}else if(H.STR&e)try{return JSON.parse(s.substring(_,r-Number(h))+'"')}catch{return JSON.parse(s.substring(_,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},u=()=>{r++,d();let _={};try{for(;s[r]!=="}";){if(d(),r>=t&&H.OBJ&e)return _;let h=a();d(),r++;try{let A=i();Object.defineProperty(_,h,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(H.OBJ&e)return _;throw A}d(),s[r]===","&&r++}}catch{if(H.OBJ&e)return _;n("Expected '}' at end of object")}return r++,_},p=()=>{r++;let _=[];try{for(;s[r]!=="]";)_.push(i()),d(),s[r]===","&&r++}catch{if(H.ARR&e)return _;n("Expected ']' at end of array")}return r++,_},m=()=>{if(r===0){s==="-"&&H.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(h){if(H.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(h))}}let _=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(H.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(_,r))}catch{s.substring(_,r)==="-"&&H.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(_,s.lastIndexOf("e")))}catch(A){o(String(A))}}},d=()=>{for(;r<t&&`
|
|
134
|
-
\r `.includes(s[r]);)r++};return i()},zs=s=>ri(s,H.ALL^H.NUM);var D,ge,Ot,
|
|
133
|
+
${d}`)}return i},c=Go(Xn);var Ke=class extends f{list(e,t={},r){return this._client.getAPIList(c`/chat/completions/${e}/messages`,S,{query:t,...r})}};function wr(s){return s!==void 0&&"function"in s&&s.function!==void 0}function xr(s){return s?.$brand==="auto-parseable-response-format"}function Ve(s){return s?.$brand==="auto-parseable-tool"}function zn(s,e){return!e||!Us(e)?{...s,choices:s.choices.map(t=>(Yn(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Ar(s,e)}function Ar(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new vt;if(r.finish_reason==="content_filter")throw new Pt;return Yn(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>ei(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?Zo(e,r.message.content):null}}});return{...s,choices:t}}function Zo(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function ei(s,e){let t=s.tools?.find(r=>wr(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ve(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Gn(s,e){if(!s||!("tools"in s)||!s.tools)return!1;let t=s.tools?.find(r=>wr(r)&&r.function?.name===e.function.name);return wr(t)&&(Ve(t)||t?.function.strict||!1)}function Us(s){return xr(s.response_format)?!0:s.tools?.some(e=>Ve(e)||e.type==="function"&&e.function.strict===!0)??!1}function Yn(s){for(let e of s||[])if(e.type!=="function")throw new y(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Qn(s){for(let e of s??[]){if(e.type!=="function")throw new y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Ct=s=>s?.role==="assistant",Ds=s=>s?.role==="tool";var Hs,zr,Gr,Ir,Sr,Yr,vr,me,Pr,Qr,Zr,$t,Zn,Re=class{constructor(){Hs.add(this),this.controller=new AbortController,zr.set(this,void 0),Gr.set(this,()=>{}),Ir.set(this,()=>{}),Sr.set(this,void 0),Yr.set(this,()=>{}),vr.set(this,()=>{}),me.set(this,{}),Pr.set(this,!1),Qr.set(this,!1),Zr.set(this,!1),$t.set(this,!1),x(this,zr,new Promise((e,t)=>{x(this,Gr,e,"f"),x(this,Ir,t,"f")}),"f"),x(this,Sr,new Promise((e,t)=>{x(this,Yr,e,"f"),x(this,vr,t,"f")}),"f"),l(this,zr,"f").catch(()=>{}),l(this,Sr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},l(this,Hs,"m",Zn).bind(this))},0)}_connected(){this.ended||(l(this,Gr,"f").call(this),this._emit("connect"))}get ended(){return l(this,Pr,"f")}get errored(){return l(this,Qr,"f")}get aborted(){return l(this,Zr,"f")}abort(){this.controller.abort()}on(e,t){return(l(this,me,"f")[e]||(l(this,me,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=l(this,me,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(l(this,me,"f")[e]||(l(this,me,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{x(this,$t,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){x(this,$t,!0,"f"),await l(this,Sr,"f")}_emit(e,...t){if(l(this,Pr,"f"))return;e==="end"&&(x(this,Pr,!0,"f"),l(this,Yr,"f").call(this));let r=l(this,me,"f")[e];if(r&&(l(this,me,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!l(this,$t,"f")&&!r?.length&&Promise.reject(n),l(this,Ir,"f").call(this,n),l(this,vr,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!l(this,$t,"f")&&!r?.length&&Promise.reject(n),l(this,Ir,"f").call(this,n),l(this,vr,"f").call(this,n),this._emit("end")}}_emitFinal(){}};zr=new WeakMap,Gr=new WeakMap,Ir=new WeakMap,Sr=new WeakMap,Yr=new WeakMap,vr=new WeakMap,me=new WeakMap,Pr=new WeakMap,Qr=new WeakMap,Zr=new WeakMap,$t=new WeakMap,Hs=new WeakSet,Zn=function(e){if(x(this,Qr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new L),e instanceof L)return x(this,Zr,!0,"f"),this._emit("abort",e);if(e instanceof y)return this._emit("error",e);if(e instanceof Error){let t=new y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new y(String(e)))};function eo(s){return typeof s.parse=="function"}var K,Ws,es,qs,Js,Ks,to,ro,ti=10,kt=class extends Re{constructor(){super(...arguments),K.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),Ds(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Ct(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),l(this,K,"m",Ws).call(this)}async finalMessage(){return await this.done(),l(this,K,"m",es).call(this)}async finalFunctionToolCall(){return await this.done(),l(this,K,"m",qs).call(this)}async finalFunctionToolCallResult(){return await this.done(),l(this,K,"m",Js).call(this)}async totalUsage(){return await this.done(),l(this,K,"m",Ks).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=l(this,K,"m",es).call(this);t&&this._emit("finalMessage",t);let r=l(this,K,"m",Ws).call(this);r&&this._emit("finalContent",r);let n=l(this,K,"m",qs).call(this);n&&this._emit("finalFunctionToolCall",n);let o=l(this,K,"m",Js).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",l(this,K,"m",Ks).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,K,"m",to).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ar(o,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){let n="tool",{tool_choice:o="auto",stream:i,...a}=t,u=typeof o!="string"&&o.type==="function"&&o?.function?.name,{maxChatCompletions:p=ti}=r||{},m=t.tools.map(h=>{if(Ve(h)){if(!h.$callback)throw new y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),d={};for(let h of m)h.type==="function"&&(d[h.function.name||h.function.function.name]=h.function);let _="tools"in t?m.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(let h of t.messages)this._addMessage(h,!1);for(let h=0;h<p;++h){let b=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:_,messages:[...this.messages]},r)).choices[0]?.message;if(!b)throw new y("missing message in ChatCompletion response");if(!b.tool_calls?.length)return;for(let R of b.tool_calls){if(R.type!=="function")continue;let v=R.id,{name:w,arguments:k}=R.function,P=d[w];if(P){if(u&&u!==w){let F=`Invalid tool_call: ${JSON.stringify(w)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:n,tool_call_id:v,content:F});continue}}else{let F=`Invalid tool_call: ${JSON.stringify(w)}. Available options are: ${Object.keys(d).map(N=>JSON.stringify(N)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:v,content:F});continue}let E;try{E=eo(P)?await P.parse(k):k}catch(F){let N=F instanceof Error?F.message:String(F);this._addMessage({role:n,tool_call_id:v,content:N});continue}let O=await P.function(E,this),C=l(this,K,"m",ro).call(this,O);if(this._addMessage({role:n,tool_call_id:v,content:C}),u)return}}}};K=new WeakSet,Ws=function(){return l(this,K,"m",es).call(this).content??null},es=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Ct(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},qs=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ct(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},Js=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ds(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},Ks=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},to=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.")},ro=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Rr=class s extends kt{static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),Ct(e)&&e.content&&this._emit("content",e.content)}};var H={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Vs=class extends Error{},Xs=class extends Error{};function ri(s,e=H.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return si(s.trim(),e)}var si=(s,e)=>{let t=s.length,r=0,n=_=>{throw new Vs(`${_} at position ${r}`)},o=_=>{throw new Xs(`${_} at position ${r}`)},i=()=>(d(),r>=t&&n("Unexpected end of input"),s[r]==='"'?a():s[r]==="{"?u():s[r]==="["?p():s.substring(r,r+4)==="null"||H.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||H.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||H.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||H.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||H.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||H.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):m()),a=()=>{let _=r,h=!1;for(r++;r<t&&(s[r]!=='"'||h&&s[r-1]==="\\");)h=s[r]==="\\"?!h:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(_,++r-Number(h)))}catch(A){o(String(A))}else if(H.STR&e)try{return JSON.parse(s.substring(_,r-Number(h))+'"')}catch{return JSON.parse(s.substring(_,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},u=()=>{r++,d();let _={};try{for(;s[r]!=="}";){if(d(),r>=t&&H.OBJ&e)return _;let h=a();d(),r++;try{let A=i();Object.defineProperty(_,h,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(H.OBJ&e)return _;throw A}d(),s[r]===","&&r++}}catch{if(H.OBJ&e)return _;n("Expected '}' at end of object")}return r++,_},p=()=>{r++;let _=[];try{for(;s[r]!=="]";)_.push(i()),d(),s[r]===","&&r++}catch{if(H.ARR&e)return _;n("Expected ']' at end of array")}return r++,_},m=()=>{if(r===0){s==="-"&&H.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(h){if(H.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(h))}}let _=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(H.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(_,r))}catch{s.substring(_,r)==="-"&&H.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(_,s.lastIndexOf("e")))}catch(A){o(String(A))}}},d=()=>{for(;r<t&&`
|
|
134
|
+
\r `.includes(s[r]);)r++};return i()},zs=s=>ri(s,H.ALL^H.NUM);var D,ge,Ot,Ee,Gs,ts,Ys,Qs,Zs,rs,en,so,Xe=class s extends kt{constructor(e){super(),D.add(this),ge.set(this,void 0),Ot.set(this,void 0),Ee.set(this,void 0),x(this,ge,e,"f"),x(this,Ot,[],"f")}get currentChatCompletionSnapshot(){return l(this,Ee,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,D,"m",Gs).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)l(this,D,"m",Ys).call(this,i);if(o.controller.signal?.aborted)throw new L;return this._addChatCompletion(l(this,D,"m",rs).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),l(this,D,"m",Gs).call(this),this._connected();let n=le.fromReadableStream(e,this.controller),o;for await(let i of n)o&&o!==i.id&&this._addChatCompletion(l(this,D,"m",rs).call(this)),l(this,D,"m",Ys).call(this,i),o=i.id;if(n.controller.signal?.aborted)throw new L;return this._addChatCompletion(l(this,D,"m",rs).call(this))}[(ge=new WeakMap,Ot=new WeakMap,Ee=new WeakMap,D=new WeakSet,Gs=function(){this.ended||x(this,Ee,void 0,"f")},ts=function(t){let r=l(this,Ot,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},l(this,Ot,"f")[t.index]=r,r)},Ys=function(t){if(this.ended)return;let r=l(this,D,"m",so).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=l(this,D,"m",ts).call(this,o);o.finish_reason&&(l(this,D,"m",Zs).call(this,o),i.current_tool_call_index!=null&&l(this,D,"m",Qs).call(this,o,i.current_tool_call_index));for(let a of n.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(l(this,D,"m",Zs).call(this,o),i.current_tool_call_index!=null&&l(this,D,"m",Qs).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of n.delta.tool_calls??[]){let u=o.message.tool_calls?.[a.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:a.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(u?.type,void 0))}}},Qs=function(t,r){if(l(this,D,"m",ts).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=l(this,ge,"f")?.tools?.find(a=>wr(a)&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ve(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Zs=function(t){let r=l(this,D,"m",ts).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=l(this,D,"m",en).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},rs=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=l(this,Ee,"f");if(!t)throw new y("request ended without sending any chunks");return x(this,Ee,void 0,"f"),x(this,Ot,[],"f"),ni(t,l(this,ge,"f"))},en=function(){let t=l(this,ge,"f")?.response_format;return xr(t)?t:null},so=function(t){var r,n,o,i;let a=l(this,Ee,"f"),{choices:u,...p}=t;a?Object.assign(a,p):a=x(this,Ee,{...p,choices:[]},"f");for(let{delta:m,finish_reason:d,index:_,logprobs:h=null,...A}of t.choices){let b=a.choices[_];if(b||(b=a.choices[_]={finish_reason:d,index:_,message:{},logprobs:h,...A}),h)if(!b.logprobs)b.logprobs=Object.assign({},h);else{let{content:O,refusal:C,...F}=h;Object.assign(b.logprobs,F),O&&((r=b.logprobs).content??(r.content=[]),b.logprobs.content.push(...O)),C&&((n=b.logprobs).refusal??(n.refusal=[]),b.logprobs.refusal.push(...C))}if(d&&(b.finish_reason=d,l(this,ge,"f")&&Us(l(this,ge,"f")))){if(d==="length")throw new vt;if(d==="content_filter")throw new Pt}if(Object.assign(b,A),!m)continue;let{content:R,refusal:v,function_call:w,role:k,tool_calls:P,...E}=m;if(Object.assign(b.message,E),v&&(b.message.refusal=(b.message.refusal||"")+v),k&&(b.message.role=k),w&&(b.message.function_call?(w.name&&(b.message.function_call.name=w.name),w.arguments&&((o=b.message.function_call).arguments??(o.arguments=""),b.message.function_call.arguments+=w.arguments)):b.message.function_call=w),R&&(b.message.content=(b.message.content||"")+R,!b.message.refusal&&l(this,D,"m",en).call(this)&&(b.message.parsed=zs(b.message.content))),P){b.message.tool_calls||(b.message.tool_calls=[]);for(let{index:O,id:C,type:F,function:N,...T}of P){let $=(i=b.message.tool_calls)[O]??(i[O]={});Object.assign($,T),C&&($.id=C),F&&($.type=F),N&&($.function??($.function={name:N.name??"",arguments:""})),N?.name&&($.function.name=N.name),N?.arguments&&($.function.arguments+=N.arguments,Gn(l(this,ge,"f"),$)&&($.function.parsed_arguments=zs($.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function ni(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:i,...a}=s,u={...a,id:t,choices:r.map(({message:p,finish_reason:m,index:d,logprobs:_,...h})=>{if(!m)throw new y(`missing finish_reason for choice ${d}`);let{content:A=null,function_call:b,tool_calls:R,...v}=p,w=p.role;if(!w)throw new y(`missing role for choice ${d}`);if(b){let{arguments:k,name:P}=b;if(k==null)throw new y(`missing function_call.arguments for choice ${d}`);if(!P)throw new y(`missing function_call.name for choice ${d}`);return{...h,message:{content:A,function_call:{arguments:k,name:P},role:w,refusal:p.refusal??null},finish_reason:m,index:d,logprobs:_}}return R?{...h,index:d,finish_reason:m,logprobs:_,message:{...v,role:w,content:A,refusal:p.refusal??null,tool_calls:R.map((k,P)=>{let{function:E,type:O,id:C,...F}=k,{arguments:N,name:T,...$}=E||{};if(C==null)throw new y(`missing choices[${d}].tool_calls[${P}].id
|
|
135
135
|
${ss(s)}`);if(O==null)throw new y(`missing choices[${d}].tool_calls[${P}].type
|
|
136
136
|
${ss(s)}`);if(T==null)throw new y(`missing choices[${d}].tool_calls[${P}].function.name
|
|
137
137
|
${ss(s)}`);if(N==null)throw new y(`missing choices[${d}].tool_calls[${P}].function.arguments
|
|
138
|
-
${ss(s)}`);return{...F,id:C,type:O,function:{...$,name:T,arguments:N}}})}}:{...h,message:{...v,content:A,role:w,refusal:p.refusal??null},finish_reason:m,index:d,logprobs:_}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return zn(u,e)}function ss(s){return JSON.stringify(s)}var Er=class s extends Xe{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}};var _e=class extends f{constructor(){super(...arguments),this.messages=new Ke(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(c`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(c`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/chat/completions/${e}`,t)}parse(e,t){return Qn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Ar(r,e))}runTools(e,t){return e.stream?Er.runTools(this._client,e,t):Rr.runTools(this._client,e,t)}stream(e,t){return Xe.createChatCompletion(this._client,e,t)}};_e.Messages=Ke;var Oe=class extends f{constructor(){super(...arguments),this.completions=new _e(this._client)}};Oe.Completions=_e;var no=Symbol("brand.privateNullableHeaders");function*ii(s){if(!s)return;if(no in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():As(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=As(r[1])?r[1]:[r[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,a])}}var g=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,i]of ii(r)){let a=o.toLowerCase();n.has(a)||(e.delete(o),n.add(a)),i===null?(e.delete(o),t.add(a)):(e.append(o,i),t.delete(a))}}return{[no]:!0,values:e,nulls:t}};var Tt=class extends f{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:g([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var Ft=class extends f{create(e,t){return this._client.post("/audio/transcriptions",te({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Nt=class extends f{create(e,t){return this._client.post("/audio/translations",te({body:e,...t,__metadata:{model:e.model}},this._client))}};var ue=class extends f{constructor(){super(...arguments),this.transcriptions=new Ft(this._client),this.translations=new Nt(this._client),this.speech=new Tt(this._client)}};ue.Transcriptions=Ft;ue.Translations=Nt;ue.Speech=Tt;var ze=class extends f{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(c`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",S,{query:e,...t})}cancel(e,t){return this._client.post(c`/batches/${e}/cancel`,t)}};var Mt=class extends f{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/assistants/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Lt=class extends f{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var jt=class extends f{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Te=class extends f{constructor(){super(...arguments),this.sessions=new Lt(this._client),this.transcriptionSessions=new jt(this._client)}};Te.Sessions=Lt;Te.TranscriptionSessions=jt;var Bt=class extends f{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(c`/chatkit/sessions/${e}/cancel`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var Ut=class extends f{retrieve(e,t){return this._client.get(c`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",pe,{query:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(c`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(c`/chatkit/threads/${e}/items`,pe,{query:t,...r,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var Fe=class extends f{constructor(){super(...arguments),this.sessions=new Bt(this._client),this.threads=new Ut(this._client)}};Fe.Sessions=Bt;Fe.Threads=Ut;var Dt=class extends f{create(e,t,r){return this._client.post(c`/threads/${e}/messages`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/messages/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/messages/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/messages`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(c`/threads/${n}/messages/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Ht=class extends f{retrieve(e,t,r){let{thread_id:n,run_id:o,...i}=t;return this._client.get(c`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(c`/threads/${n}/runs/${e}/steps`,S,{query:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var oo=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var Ne=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()};var W,Ye,tn,fe,ns,re,Qe,Wt,Ge,as,Y,os,is,kr,Cr,$r,io,ao,lo,co,uo,fo,ho,ye=class extends $e{constructor(){super(...arguments),W.add(this),tn.set(this,[]),fe.set(this,{}),ns.set(this,{}),re.set(this,void 0),Qe.set(this,void 0),Wt.set(this,void 0),Ge.set(this,void 0),as.set(this,void 0),Y.set(this,void 0),os.set(this,void 0),is.set(this,void 0),kr.set(this,void 0)}[(tn=new WeakMap,fe=new WeakMap,ns=new WeakMap,re=new WeakMap,Qe=new WeakMap,Wt=new WeakMap,Ge=new WeakMap,as=new WeakMap,Y=new WeakMap,os=new WeakMap,is=new WeakMap,kr=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Ye;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=le.fromReadableStream(e,this.controller);for await(let o of n)l(this,W,"m",Cr).call(this,o);if(n.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new Ye;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(let u of a)l(this,W,"m",Cr).call(this,u);if(a.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}static createThreadAssistantStream(e,t,r){let n=new Ye;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new Ye;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return l(this,os,"f")}currentRun(){return l(this,is,"f")}currentMessageSnapshot(){return l(this,re,"f")}currentRunStepSnapshot(){return l(this,kr,"f")}async finalRunSteps(){return await this.done(),Object.values(l(this,fe,"f"))}async finalMessages(){return await this.done(),Object.values(l(this,ns,"f"))}async finalRun(){if(await this.done(),!l(this,Qe,"f"))throw Error("Final run was not received.");return l(this,Qe,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let a of i)l(this,W,"m",Cr).call(this,a);if(i.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let u of a)l(this,W,"m",Cr).call(this,u);if(a.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(pr(o)&&pr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!pr(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let u=o[a];u==null?o.push(i):o[a]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};Ye=ye,Cr=function(e){if(!this.ended)switch(x(this,os,e,"f"),l(this,W,"m",lo).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":l(this,W,"m",ho).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":l(this,W,"m",ao).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":l(this,W,"m",io).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},$r=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!l(this,Qe,"f"))throw Error("Final run has not been received");return l(this,Qe,"f")},io=function(e){let[t,r]=l(this,W,"m",uo).call(this,e,l(this,re,"f"));x(this,re,t,"f"),l(this,ns,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=t.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=l(this,Wt,"f")){if(l(this,Ge,"f"))switch(l(this,Ge,"f").type){case"text":this._emit("textDone",l(this,Ge,"f").text,l(this,re,"f"));break;case"image_file":this._emit("imageFileDone",l(this,Ge,"f").image_file,l(this,re,"f"));break}x(this,Wt,n.index,"f")}x(this,Ge,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(l(this,Wt,"f")!==void 0){let n=e.data.content[l(this,Wt,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,l(this,re,"f"));break;case"text":this._emit("textDone",n.text,l(this,re,"f"));break}}l(this,re,"f")&&this._emit("messageDone",e.data),x(this,re,void 0,"f")}},ao=function(e){let t=l(this,W,"m",co).call(this,e);switch(x(this,kr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==l(this,as,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(l(this,Y,"f")&&this._emit("toolCallDone",l(this,Y,"f")),x(this,as,o.index,"f"),x(this,Y,t.step_details.tool_calls[o.index],"f"),l(this,Y,"f")&&this._emit("toolCallCreated",l(this,Y,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":x(this,kr,void 0,"f"),e.data.step_details.type=="tool_calls"&&l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),x(this,Y,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},lo=function(e){l(this,tn,"f").push(e),this._emit("event",e)},co=function(e){switch(e.event){case"thread.run.step.created":return l(this,fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=l(this,fe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=Ye.accumulateDelta(t,r.delta);l(this,fe,"f")[e.data.id]=n}return l(this,fe,"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":l(this,fe,"f")[e.data.id]=e.data;break}if(l(this,fe,"f")[e.data.id])return l(this,fe,"f")[e.data.id];throw new Error("No snapshot available")},uo=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=l(this,W,"m",fo).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},fo=function(e,t){return Ye.accumulateDelta(t,e)},ho=function(e){switch(x(this,is,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":x(this,Qe,e.data,"f"),l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),x(this,Y,void 0,"f"));break;case"thread.run.cancelling":break}};var Ze=class extends f{constructor(){super(...arguments),this.steps=new Ht(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/runs/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/runs`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(c`/threads/${n}/runs/${e}/cancel`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await ie(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return ye.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Ze.Steps=Ht;var Me=class extends f{constructor(){super(...arguments),this.runs=new Ze(this._client),this.messages=new Dt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/threads/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(c`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return ye.createThreadAssistantStream(e,this._client.beta.threads,t)}};Me.Runs=Ze;Me.Messages=Dt;var se=class extends f{constructor(){super(...arguments),this.realtime=new Te(this._client),this.chatkit=new Fe(this._client),this.assistants=new Mt(this._client),this.threads=new Me(this._client)}};se.Realtime=Te;se.ChatKit=Fe;se.Assistants=Mt;se.Threads=Me;var et=class extends f{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var qt=class extends f{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}/content`,{...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var tt=class extends f{constructor(){super(...arguments),this.content=new qt(this._client)}create(e,t,r){return this._client.post(c`/containers/${e}/files`,de({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/containers/${e}/files`,S,{query:t,...r})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(c`/containers/${n}/files/${e}`,{...r,headers:g([{Accept:"*/*"},r?.headers])})}};tt.Content=qt;var Le=class extends f{constructor(){super(...arguments),this.files=new tt(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(c`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/containers/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}};Le.Files=tt;var Jt=class extends f{create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/conversations/${e}/items`,{query:{include:n},body:o,...r})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(c`/conversations/${n}/items/${e}`,{query:o,...r})}list(e,t={},r){return this._client.getAPIList(c`/conversations/${e}/items`,pe,{query:t,...r})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(c`/conversations/${n}/items/${e}`,r)}};var je=class extends f{constructor(){super(...arguments),this.items=new Jt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(c`/conversations/${e}`,t)}update(e,t,r){return this._client.post(c`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(c`/conversations/${e}`,t)}};je.Items=Jt;var rt=class extends f{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&M(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?o:(M(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let u=a.embedding;a.embedding=oo(u)}),i)))}};var Kt=class extends f{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(c`/evals/${n}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(c`/evals/${n}/runs/${e}/output_items`,S,{query:o,...r})}};var st=class extends f{constructor(){super(...arguments),this.outputItems=new Kt(this._client)}create(e,t,r){return this._client.post(c`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(c`/evals/${n}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/evals/${e}/runs`,S,{query:t,...r})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(c`/evals/${n}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(c`/evals/${n}/runs/${e}`,r)}};st.OutputItems=Kt;var Be=class extends f{constructor(){super(...arguments),this.runs=new st(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(c`/evals/${e}`,t)}update(e,t,r){return this._client.post(c`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/evals/${e}`,t)}};Be.Runs=st;var nt=class extends f{create(e,t){return this._client.post("/files",te({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/files/${e}`,t)}content(e,t){return this._client.get(c`/files/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await ie(t),i=await this.retrieve(e),Date.now()-o>r)throw new Ee({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};var Vt=class extends f{};var Xt=class extends f{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var ot=class extends f{constructor(){super(...arguments),this.graders=new Xt(this._client)}};ot.Graders=Xt;var zt=class extends f{create(e,t,r){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,ce,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(c`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(c`/fine_tuning/checkpoints/${n}/permissions/${e}`,r)}};var it=class extends f{constructor(){super(...arguments),this.permissions=new zt(this._client)}};it.Permissions=zt;var Gt=class extends f{list(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...r})}};var at=class extends f{constructor(){super(...arguments),this.checkpoints=new Gt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(c`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",S,{query:e,...t})}cancel(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/events`,S,{query:t,...r})}pause(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/resume`,t)}};at.Checkpoints=Gt;var ne=class extends f{constructor(){super(...arguments),this.methods=new Vt(this._client),this.jobs=new at(this._client),this.checkpoints=new it(this._client),this.alpha=new ot(this._client)}};ne.Methods=Vt;ne.Jobs=at;ne.Checkpoints=it;ne.Alpha=ot;var Yt=class extends f{};var Ue=class extends f{constructor(){super(...arguments),this.graderModels=new Yt(this._client)}};Ue.GraderModels=Yt;var lt=class extends f{createVariation(e,t){return this._client.post("/images/variations",te({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",te({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};var ct=class extends f{retrieve(e,t){return this._client.get(c`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ce,e)}delete(e,t){return this._client.delete(c`/models/${e}`,t)}};var ut=class extends f{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Qt=class extends f{accept(e,t,r){return this._client.post(c`/realtime/calls/${e}/accept`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(c`/realtime/calls/${e}/hangup`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(c`/realtime/calls/${e}/refer`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(c`/realtime/calls/${e}/reject`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}};var Zt=class extends f{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var be=class extends f{constructor(){super(...arguments),this.clientSecrets=new Zt(this._client),this.calls=new Qt(this._client)}};be.ClientSecrets=Zt;be.Calls=Qt;function po(s,e){return!e||!Li(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:rn(s,e)}function rn(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:Ui(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:Mi(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||ls(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function Mi(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Li(s){return!!xr(s.text?.format)}function ji(s){return s?.$brand==="auto-parseable-tool"}function Bi(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Ui(s,e){let t=Bi(s.tools??[],e.name);return{...e,...e,parsed_arguments:ji(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function ls(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}var er,cs,De,us,mo,go,_o,yo,fs=class s extends $e{constructor(e){super(),er.add(this),cs.set(this,void 0),De.set(this,void 0),us.set(this,void 0),x(this,cs,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,er,"m",mo).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of o)l(this,er,"m",go).call(this,a,i);if(o.controller.signal?.aborted)throw new L;return l(this,er,"m",_o).call(this)}[(cs=new WeakMap,De=new WeakMap,us=new WeakMap,er=new WeakSet,mo=function(){this.ended||x(this,De,void 0,"f")},go=function(t,r){if(this.ended)return;let n=(i,a)=>{(r==null||a.sequence_number>r)&&this._emit(i,a)},o=l(this,er,"m",yo).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.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}`);n("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},_o=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=l(this,De,"f");if(!t)throw new y("request ended without sending any events");x(this,De,void 0,"f");let r=Di(t,l(this,cs,"f"));return x(this,us,r,"f"),r},yo=function(t){let r=l(this,De,"f");if(!r){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=x(this,De,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);let o=n.type,i=t.part;o==="message"&&i.type!=="reasoning_text"?n.content.push(i):o==="reasoning"&&i.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(i));break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new y(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let o=n.content?.[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="reasoning_text")throw new y(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.completed":{x(this,De,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=l(this,us,"f");if(!e)throw new y("stream ended without producing a ChatCompletion");return e}};function Di(s,e){return po(s,e)}var tr=class extends f{list(e,t={},r){return this._client.getAPIList(c`/responses/${e}/input_items`,S,{query:t,...r})}};var rr=class extends f{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var we=class extends f{constructor(){super(...arguments),this.inputItems=new tr(this._client),this.inputTokens=new rr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&ls(r),r))}retrieve(e,t={},r){return this._client.get(c`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ls(n),n))}delete(e,t){return this._client.delete(c`/responses/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>rn(r,e))}stream(e,t){return fs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(c`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};we.InputItems=tr;we.InputTokens=rr;var sr=class extends f{retrieve(e,t){return this._client.get(c`/skills/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}};var nr=class extends f{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}/content`,{...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var ft=class extends f{constructor(){super(...arguments),this.content=new nr(this._client)}create(e,t={},r){return this._client.post(c`/skills/${e}/versions`,de({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/skills/${e}/versions`,S,{query:t,...r})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(c`/skills/${n}/versions/${e}`,r)}};ft.Content=nr;var xe=class extends f{constructor(){super(...arguments),this.content=new sr(this._client),this.versions=new ft(this._client)}create(e={},t){return this._client.post("/skills",de({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/skills/${e}`,t)}update(e,t,r){return this._client.post(c`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/skills/${e}`,t)}};xe.Content=sr;xe.Versions=ft;var or=class extends f{create(e,t,r){return this._client.post(c`/uploads/${e}/parts`,te({body:t,...r},this._client))}};var He=class extends f{constructor(){super(...arguments),this.parts=new or(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(c`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(c`/uploads/${e}/complete`,{body:t,...r})}};He.Parts=or;var bo=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var ir=class extends f{create(e,t,r){return this._client.post(c`/vector_stores/${e}/file_batches`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/file_batches/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(c`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(c`/vector_stores/${n}/file_batches/${e}/files`,S,{query:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await ie(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,i=Math.min(o,t.length),a=this._client,u=t.values(),p=[...r];async function m(_){for(let h of _){let A=await a.files.create({file:h,purpose:"assistants"},n);p.push(A.id)}}let d=Array(i).fill(u).map(m);return await bo(d),await this.createAndPoll(e,{file_ids:p})}};var ar=class extends f{create(e,t,r){return this._client.post(c`/vector_stores/${e}/files`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/files/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(c`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/vector_stores/${e}/files`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(c`/vector_stores/${n}/files/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await ie(a);break;case"failed":case"completed":return i}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(c`/vector_stores/${n}/files/${e}/content`,ce,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Ae=class extends f{constructor(){super(...arguments),this.files=new ar(this._client),this.fileBatches=new ir(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/vector_stores/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(c`/vector_stores/${e}/search`,ce,{body:t,method:"post",...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};Ae.Files=ar;Ae.FileBatches=ir;var ht=class extends f{create(e,t){return this._client.post("/videos",de({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",pe,{query:e,...t})}delete(e,t){return this._client.delete(c`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(c`/videos/${e}/content`,{query:t,...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(c`/videos/${e}/remix`,de({body:t,...r},this._client))}};var lr,wo,hs,pt=class extends f{constructor(){super(...arguments),lr.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");l(this,lr,"m",wo).call(this,r);let o=g([t]).values,i=l(this,lr,"m",hs).call(this,o,"webhook-signature"),a=l(this,lr,"m",hs).call(this,o,"webhook-timestamp"),u=l(this,lr,"m",hs).call(this,o,"webhook-id"),p=parseInt(a,10);if(isNaN(p))throw new oe("Invalid webhook timestamp format");let m=Math.floor(Date.now()/1e3);if(m-p>n)throw new oe("Webhook timestamp is too old");if(p>m+n)throw new oe("Webhook timestamp is too new");let d=i.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),_=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=u?`${u}.${a}.${e}`:`${a}.${e}`,A=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of d)try{let R=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",A,R,new TextEncoder().encode(h)))return}catch{continue}throw new oe("The given webhook signature does not match the expected signature")}};lr=new WeakSet,wo=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},hs=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var sn,nn,ps,xo,I=class{constructor({baseURL:e=Ne("OPENAI_BASE_URL"),apiKey:t=Ne("OPENAI_API_KEY"),organization:r=Ne("OPENAI_ORG_ID")??null,project:n=Ne("OPENAI_PROJECT_ID")??null,webhookSecret:o=Ne("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(sn.add(this),ps.set(this,void 0),this.completions=new et(this),this.chat=new Oe(this),this.embeddings=new rt(this),this.files=new nt(this),this.images=new lt(this),this.audio=new ue(this),this.moderations=new ut(this),this.models=new ct(this),this.fineTuning=new ne(this),this.graders=new Ue(this),this.vectorStores=new Ae(this),this.webhooks=new pt(this),this.beta=new se(this),this.batches=new ze(this),this.uploads=new He(this),this.responses=new we(this),this.realtime=new be(this),this.conversations=new je(this),this.evals=new Be(this),this.containers=new Le(this),this.skills=new xe(this),this.videos=new ht(this),t===void 0)throw new y("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:n,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Rn())throw new y(`It looks like you're running in a browser-like environment.
|
|
138
|
+
${ss(s)}`);return{...F,id:C,type:O,function:{...$,name:T,arguments:N}}})}}:{...h,message:{...v,content:A,role:w,refusal:p.refusal??null},finish_reason:m,index:d,logprobs:_}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return zn(u,e)}function ss(s){return JSON.stringify(s)}var Er=class s extends Xe{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}};var _e=class extends f{constructor(){super(...arguments),this.messages=new Ke(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(c`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(c`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/chat/completions/${e}`,t)}parse(e,t){return Qn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>Ar(r,e))}runTools(e,t){return e.stream?Er.runTools(this._client,e,t):Rr.runTools(this._client,e,t)}stream(e,t){return Xe.createChatCompletion(this._client,e,t)}};_e.Messages=Ke;var Ce=class extends f{constructor(){super(...arguments),this.completions=new _e(this._client)}};Ce.Completions=_e;var no=Symbol("brand.privateNullableHeaders");function*ii(s){if(!s)return;if(no in s){let{values:r,nulls:n}=s;yield*r.entries();for(let o of n)yield[o,null];return}let e=!1,t;s instanceof Headers?t=s.entries():As(s)?t=s:(e=!0,t=Object.entries(s??{}));for(let r of t){let n=r[0];if(typeof n!="string")throw new TypeError("expected header name to be a string");let o=As(r[1])?r[1]:[r[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[n,null]),yield[n,a])}}var g=s=>{let e=new Headers,t=new Set;for(let r of s){let n=new Set;for(let[o,i]of ii(r)){let a=o.toLowerCase();n.has(a)||(e.delete(o),n.add(a)),i===null?(e.delete(o),t.add(a)):(e.append(o,i),t.delete(a))}}return{[no]:!0,values:e,nulls:t}};var Tt=class extends f{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:g([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}};var Ft=class extends f{create(e,t){return this._client.post("/audio/transcriptions",te({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}};var Nt=class extends f{create(e,t){return this._client.post("/audio/translations",te({body:e,...t,__metadata:{model:e.model}},this._client))}};var ue=class extends f{constructor(){super(...arguments),this.transcriptions=new Ft(this._client),this.translations=new Nt(this._client),this.speech=new Tt(this._client)}};ue.Transcriptions=Ft;ue.Translations=Nt;ue.Speech=Tt;var ze=class extends f{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(c`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",S,{query:e,...t})}cancel(e,t){return this._client.post(c`/batches/${e}/cancel`,t)}};var Mt=class extends f{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/assistants/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/assistants/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var Lt=class extends f{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var jt=class extends f{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};var $e=class extends f{constructor(){super(...arguments),this.sessions=new Lt(this._client),this.transcriptionSessions=new jt(this._client)}};$e.Sessions=Lt;$e.TranscriptionSessions=jt;var Bt=class extends f{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(c`/chatkit/sessions/${e}/cancel`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}};var Ut=class extends f{retrieve(e,t){return this._client.get(c`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",pe,{query:e,...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(c`/chatkit/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},r){return this._client.getAPIList(c`/chatkit/threads/${e}/items`,pe,{query:t,...r,headers:g([{"OpenAI-Beta":"chatkit_beta=v1"},r?.headers])})}};var ke=class extends f{constructor(){super(...arguments),this.sessions=new Bt(this._client),this.threads=new Ut(this._client)}};ke.Sessions=Bt;ke.Threads=Ut;var Dt=class extends f{create(e,t,r){return this._client.post(c`/threads/${e}/messages`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/messages/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/messages/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/messages`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{thread_id:n}=t;return this._client.delete(c`/threads/${n}/messages/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Ht=class extends f{retrieve(e,t,r){let{thread_id:n,run_id:o,...i}=t;return this._client.get(c`/threads/${n}/runs/${o}/steps/${e}`,{query:i,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){let{thread_id:n,...o}=t;return this._client.getAPIList(c`/threads/${n}/runs/${e}/steps`,S,{query:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var oo=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};var Oe=s=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[s]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(s)?.trim()};var W,Ye,tn,fe,ns,re,Qe,Wt,Ge,as,Y,os,is,kr,Cr,$r,io,ao,lo,co,uo,fo,ho,ye=class extends Re{constructor(){super(...arguments),W.add(this),tn.set(this,[]),fe.set(this,{}),ns.set(this,{}),re.set(this,void 0),Qe.set(this,void 0),Wt.set(this,void 0),Ge.set(this,void 0),as.set(this,void 0),Y.set(this,void 0),os.set(this,void 0),is.set(this,void 0),kr.set(this,void 0)}[(tn=new WeakMap,fe=new WeakMap,ns=new WeakMap,re=new WeakMap,Qe=new WeakMap,Wt=new WeakMap,Ge=new WeakMap,as=new WeakMap,Y=new WeakMap,os=new WeakMap,is=new WeakMap,kr=new WeakMap,W=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new Ye;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=le.fromReadableStream(e,this.controller);for await(let o of n)l(this,W,"m",Cr).call(this,o);if(n.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}toReadableStream(){return new le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n){let o=new Ye;return o._run(()=>o._runToolAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.submitToolOutputs(t,i,{...n,signal:this.controller.signal});this._connected();for await(let u of a)l(this,W,"m",Cr).call(this,u);if(a.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}static createThreadAssistantStream(e,t,r){let n=new Ye;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new Ye;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return l(this,os,"f")}currentRun(){return l(this,is,"f")}currentMessageSnapshot(){return l(this,re,"f")}currentRunStepSnapshot(){return l(this,kr,"f")}async finalRunSteps(){return await this.done(),Object.values(l(this,fe,"f"))}async finalMessages(){return await this.done(),Object.values(l(this,ns,"f"))}async finalRun(){if(await this.done(),!l(this,Qe,"f"))throw Error("Final run was not received.");return l(this,Qe,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let a of i)l(this,W,"m",Cr).call(this,a);if(i.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let u of a)l(this,W,"m",Cr).call(this,u);if(a.controller.signal?.aborted)throw new L;return this._addRun(l(this,W,"m",$r).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(pr(o)&&pr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!pr(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let u=o[a];u==null?o.push(i):o[a]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n){return await this._createToolAssistantStream(t,e,r,n)}};Ye=ye,Cr=function(e){if(!this.ended)switch(x(this,os,e,"f"),l(this,W,"m",lo).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":l(this,W,"m",ho).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":l(this,W,"m",ao).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":l(this,W,"m",io).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},$r=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");if(!l(this,Qe,"f"))throw Error("Final run has not been received");return l(this,Qe,"f")},io=function(e){let[t,r]=l(this,W,"m",uo).call(this,e,l(this,re,"f"));x(this,re,t,"f"),l(this,ns,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=t.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=l(this,Wt,"f")){if(l(this,Ge,"f"))switch(l(this,Ge,"f").type){case"text":this._emit("textDone",l(this,Ge,"f").text,l(this,re,"f"));break;case"image_file":this._emit("imageFileDone",l(this,Ge,"f").image_file,l(this,re,"f"));break}x(this,Wt,n.index,"f")}x(this,Ge,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(l(this,Wt,"f")!==void 0){let n=e.data.content[l(this,Wt,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,l(this,re,"f"));break;case"text":this._emit("textDone",n.text,l(this,re,"f"));break}}l(this,re,"f")&&this._emit("messageDone",e.data),x(this,re,void 0,"f")}},ao=function(e){let t=l(this,W,"m",co).call(this,e);switch(x(this,kr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==l(this,as,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(l(this,Y,"f")&&this._emit("toolCallDone",l(this,Y,"f")),x(this,as,o.index,"f"),x(this,Y,t.step_details.tool_calls[o.index],"f"),l(this,Y,"f")&&this._emit("toolCallCreated",l(this,Y,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":x(this,kr,void 0,"f"),e.data.step_details.type=="tool_calls"&&l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),x(this,Y,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},lo=function(e){l(this,tn,"f").push(e),this._emit("event",e)},co=function(e){switch(e.event){case"thread.run.step.created":return l(this,fe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=l(this,fe,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=Ye.accumulateDelta(t,r.delta);l(this,fe,"f")[e.data.id]=n}return l(this,fe,"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":l(this,fe,"f")[e.data.id]=e.data;break}if(l(this,fe,"f")[e.data.id])return l(this,fe,"f")[e.data.id];throw new Error("No snapshot available")},uo=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(let o of n.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=l(this,W,"m",fo).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},fo=function(e,t){return Ye.accumulateDelta(t,e)},ho=function(e){switch(x(this,is,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":x(this,Qe,e.data,"f"),l(this,Y,"f")&&(this._emit("toolCallDone",l(this,Y,"f")),x(this,Y,void 0,"f"));break;case"thread.run.cancelling":break}};var Ze=class extends f{constructor(){super(...arguments),this.steps=new Ht(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}retrieve(e,t,r){let{thread_id:n}=t;return this._client.get(c`/threads/${n}/runs/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/threads/${e}/runs`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{thread_id:n}=t;return this._client.post(c`/threads/${n}/runs/${e}/cancel`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(n.id,{thread_id:e},r)}createAndStream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await ie(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return ye.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){let{thread_id:n,...o}=t;return this._client.post(c`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1,__synthesizeEventData:!0})}async submitToolOutputsAndPoll(e,t,r){let n=await this.submitToolOutputs(e,t,r);return await this.poll(n.id,t,r)}submitToolOutputsStream(e,t,r){return ye.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};Ze.Steps=Ht;var Te=class extends f{constructor(){super(...arguments),this.runs=new Ze(this._client),this.messages=new Dt(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/threads/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(c`/threads/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0})}async createAndRunPoll(e,t){let r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return ye.createThreadAssistantStream(e,this._client.beta.threads,t)}};Te.Runs=Ze;Te.Messages=Dt;var se=class extends f{constructor(){super(...arguments),this.realtime=new $e(this._client),this.chatkit=new ke(this._client),this.assistants=new Mt(this._client),this.threads=new Te(this._client)}};se.Realtime=$e;se.ChatKit=ke;se.Assistants=Mt;se.Threads=Te;var et=class extends f{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var qt=class extends f{retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}/content`,{...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var tt=class extends f{constructor(){super(...arguments),this.content=new qt(this._client)}create(e,t,r){return this._client.post(c`/containers/${e}/files`,de({body:t,...r},this._client))}retrieve(e,t,r){let{container_id:n}=t;return this._client.get(c`/containers/${n}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/containers/${e}/files`,S,{query:t,...r})}delete(e,t,r){let{container_id:n}=t;return this._client.delete(c`/containers/${n}/files/${e}`,{...r,headers:g([{Accept:"*/*"},r?.headers])})}};tt.Content=qt;var Fe=class extends f{constructor(){super(...arguments),this.files=new tt(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(c`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/containers/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}};Fe.Files=tt;var Jt=class extends f{create(e,t,r){let{include:n,...o}=t;return this._client.post(c`/conversations/${e}/items`,{query:{include:n},body:o,...r})}retrieve(e,t,r){let{conversation_id:n,...o}=t;return this._client.get(c`/conversations/${n}/items/${e}`,{query:o,...r})}list(e,t={},r){return this._client.getAPIList(c`/conversations/${e}/items`,pe,{query:t,...r})}delete(e,t,r){let{conversation_id:n}=t;return this._client.delete(c`/conversations/${n}/items/${e}`,r)}};var Ne=class extends f{constructor(){super(...arguments),this.items=new Jt(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(c`/conversations/${e}`,t)}update(e,t,r){return this._client.post(c`/conversations/${e}`,{body:t,...r})}delete(e,t){return this._client.delete(c`/conversations/${e}`,t)}};Ne.Items=Jt;var rt=class extends f{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&M(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?o:(M(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let u=a.embedding;a.embedding=oo(u)}),i)))}};var Kt=class extends f{retrieve(e,t,r){let{eval_id:n,run_id:o}=t;return this._client.get(c`/evals/${n}/runs/${o}/output_items/${e}`,r)}list(e,t,r){let{eval_id:n,...o}=t;return this._client.getAPIList(c`/evals/${n}/runs/${e}/output_items`,S,{query:o,...r})}};var st=class extends f{constructor(){super(...arguments),this.outputItems=new Kt(this._client)}create(e,t,r){return this._client.post(c`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){let{eval_id:n}=t;return this._client.get(c`/evals/${n}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/evals/${e}/runs`,S,{query:t,...r})}delete(e,t,r){let{eval_id:n}=t;return this._client.delete(c`/evals/${n}/runs/${e}`,r)}cancel(e,t,r){let{eval_id:n}=t;return this._client.post(c`/evals/${n}/runs/${e}`,r)}};st.OutputItems=Kt;var Me=class extends f{constructor(){super(...arguments),this.runs=new st(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(c`/evals/${e}`,t)}update(e,t,r){return this._client.post(c`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/evals/${e}`,t)}};Me.Runs=st;var nt=class extends f{create(e,t){return this._client.post("/files",te({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/files/${e}`,t)}content(e,t){return this._client.get(c`/files/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await ie(t),i=await this.retrieve(e),Date.now()-o>r)throw new ve({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};var Vt=class extends f{};var Xt=class extends f{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};var ot=class extends f{constructor(){super(...arguments),this.graders=new Xt(this._client)}};ot.Graders=Xt;var zt=class extends f{create(e,t,r){return this._client.getAPIList(c`/fine_tuning/checkpoints/${e}/permissions`,ce,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(c`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){let{fine_tuned_model_checkpoint:n}=t;return this._client.delete(c`/fine_tuning/checkpoints/${n}/permissions/${e}`,r)}};var it=class extends f{constructor(){super(...arguments),this.permissions=new zt(this._client)}};it.Permissions=zt;var Gt=class extends f{list(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/checkpoints`,S,{query:t,...r})}};var at=class extends f{constructor(){super(...arguments),this.checkpoints=new Gt(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(c`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",S,{query:e,...t})}cancel(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(c`/fine_tuning/jobs/${e}/events`,S,{query:t,...r})}pause(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(c`/fine_tuning/jobs/${e}/resume`,t)}};at.Checkpoints=Gt;var ne=class extends f{constructor(){super(...arguments),this.methods=new Vt(this._client),this.jobs=new at(this._client),this.checkpoints=new it(this._client),this.alpha=new ot(this._client)}};ne.Methods=Vt;ne.Jobs=at;ne.Checkpoints=it;ne.Alpha=ot;var Yt=class extends f{};var Le=class extends f{constructor(){super(...arguments),this.graderModels=new Yt(this._client)}};Le.GraderModels=Yt;var lt=class extends f{createVariation(e,t){return this._client.post("/images/variations",te({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",te({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}};var ct=class extends f{retrieve(e,t){return this._client.get(c`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ce,e)}delete(e,t){return this._client.delete(c`/models/${e}`,t)}};var ut=class extends f{create(e,t){return this._client.post("/moderations",{body:e,...t})}};var Qt=class extends f{accept(e,t,r){return this._client.post(c`/realtime/calls/${e}/accept`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}hangup(e,t){return this._client.post(c`/realtime/calls/${e}/hangup`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}refer(e,t,r){return this._client.post(c`/realtime/calls/${e}/refer`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}reject(e,t={},r){return this._client.post(c`/realtime/calls/${e}/reject`,{body:t,...r,headers:g([{Accept:"*/*"},r?.headers])})}};var Zt=class extends f{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}};var be=class extends f{constructor(){super(...arguments),this.clientSecrets=new Zt(this._client),this.calls=new Qt(this._client)}};be.ClientSecrets=Zt;be.Calls=Qt;function po(s,e){return!e||!Li(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:rn(s,e)}function rn(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:Ui(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:Mi(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||ls(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function Mi(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Li(s){return!!xr(s.text?.format)}function ji(s){return s?.$brand==="auto-parseable-tool"}function Bi(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Ui(s,e){let t=Bi(s.tools??[],e.name);return{...e,...e,parsed_arguments:ji(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function ls(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}var er,cs,je,us,mo,go,_o,yo,fs=class s extends Re{constructor(e){super(),er.add(this),cs.set(this,void 0),je.set(this,void 0),us.set(this,void 0),x(this,cs,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),l(this,er,"m",mo).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of o)l(this,er,"m",go).call(this,a,i);if(o.controller.signal?.aborted)throw new L;return l(this,er,"m",_o).call(this)}[(cs=new WeakMap,je=new WeakMap,us=new WeakMap,er=new WeakSet,mo=function(){this.ended||x(this,je,void 0,"f")},go=function(t,r){if(this.ended)return;let n=(i,a)=>{(r==null||a.sequence_number>r)&&this._emit(i,a)},o=l(this,er,"m",yo).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.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}`);n("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new y(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},_o=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");let t=l(this,je,"f");if(!t)throw new y("request ended without sending any events");x(this,je,void 0,"f");let r=Di(t,l(this,cs,"f"));return x(this,us,r,"f"),r},yo=function(t){let r=l(this,je,"f");if(!r){if(t.type!=="response.created")throw new y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=x(this,je,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);let o=n.type,i=t.part;o==="message"&&i.type!=="reasoning_text"?n.content.push(i):o==="reasoning"&&i.type==="reasoning_text"&&(n.content||(n.content=[]),n.content.push(i));break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new y(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.reasoning_text.delta":{let n=r.output[t.output_index];if(!n)throw new y(`missing output at index ${t.output_index}`);if(n.type==="reasoning"){let o=n.content?.[t.content_index];if(!o)throw new y(`missing content at index ${t.content_index}`);if(o.type!=="reasoning_text")throw new y(`expected content to be 'reasoning_text', got ${o.type}`);o.text+=t.delta}break}case"response.completed":{x(this,je,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=l(this,us,"f");if(!e)throw new y("stream ended without producing a ChatCompletion");return e}};function Di(s,e){return po(s,e)}var tr=class extends f{list(e,t={},r){return this._client.getAPIList(c`/responses/${e}/input_items`,S,{query:t,...r})}};var rr=class extends f{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}};var we=class extends f{constructor(){super(...arguments),this.inputItems=new tr(this._client),this.inputTokens=new rr(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&ls(r),r))}retrieve(e,t={},r){return this._client.get(c`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&ls(n),n))}delete(e,t){return this._client.delete(c`/responses/${e}`,{...t,headers:g([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>rn(r,e))}stream(e,t){return fs.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(c`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post("/responses/compact",{body:e,...t})}};we.InputItems=tr;we.InputTokens=rr;var sr=class extends f{retrieve(e,t){return this._client.get(c`/skills/${e}/content`,{...t,headers:g([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}};var nr=class extends f{retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}/content`,{...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}};var ft=class extends f{constructor(){super(...arguments),this.content=new nr(this._client)}create(e,t={},r){return this._client.post(c`/skills/${e}/versions`,de({body:t,...r},this._client))}retrieve(e,t,r){let{skill_id:n}=t;return this._client.get(c`/skills/${n}/versions/${e}`,r)}list(e,t={},r){return this._client.getAPIList(c`/skills/${e}/versions`,S,{query:t,...r})}delete(e,t,r){let{skill_id:n}=t;return this._client.delete(c`/skills/${n}/versions/${e}`,r)}};ft.Content=nr;var xe=class extends f{constructor(){super(...arguments),this.content=new sr(this._client),this.versions=new ft(this._client)}create(e={},t){return this._client.post("/skills",de({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/skills/${e}`,t)}update(e,t,r){return this._client.post(c`/skills/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/skills",S,{query:e,...t})}delete(e,t){return this._client.delete(c`/skills/${e}`,t)}};xe.Content=sr;xe.Versions=ft;var or=class extends f{create(e,t,r){return this._client.post(c`/uploads/${e}/parts`,te({body:t,...r},this._client))}};var Be=class extends f{constructor(){super(...arguments),this.parts=new or(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(c`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(c`/uploads/${e}/complete`,{body:t,...r})}};Be.Parts=or;var bo=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var ir=class extends f{create(e,t,r){return this._client.post(c`/vector_stores/${e}/file_batches`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/file_batches/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){let{vector_store_id:n}=t;return this._client.post(c`/vector_stores/${n}/file_batches/${e}/cancel`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r){let{vector_store_id:n,...o}=t;return this._client.getAPIList(c`/vector_stores/${n}/file_batches/${e}/files`,S,{query:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:o,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=i.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await ie(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,i=Math.min(o,t.length),a=this._client,u=t.values(),p=[...r];async function m(_){for(let h of _){let A=await a.files.create({file:h,purpose:"assistants"},n);p.push(A.id)}}let d=Array(i).fill(u).map(m);return await bo(d),await this.createAndPoll(e,{file_ids:p})}};var ar=class extends f{create(e,t,r){return this._client.post(c`/vector_stores/${e}/files`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){let{vector_store_id:n}=t;return this._client.get(c`/vector_stores/${n}/files/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){let{vector_store_id:n,...o}=t;return this._client.post(c`/vector_stores/${n}/files/${e}`,{body:o,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(c`/vector_stores/${e}/files`,S,{query:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){let{vector_store_id:n}=t;return this._client.delete(c`/vector_stores/${n}/files/${e}`,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n=g([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){let o=await this.retrieve(t,{vector_store_id:e},{...r,headers:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let u=o.response.headers.get("openai-poll-after-ms");if(u){let p=parseInt(u);isNaN(p)||(a=p)}}await ie(a);break;case"failed":case"completed":return i}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){let{vector_store_id:n}=t;return this._client.getAPIList(c`/vector_stores/${n}/files/${e}/content`,ce,{...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};var Ae=class extends f{constructor(){super(...arguments),this.files=new ar(this._client),this.fileBatches=new ir(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(c`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(c`/vector_stores/${e}`,{body:t,...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",S,{query:e,...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(c`/vector_stores/${e}`,{...t,headers:g([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(c`/vector_stores/${e}/search`,ce,{body:t,method:"post",...r,headers:g([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}};Ae.Files=ar;Ae.FileBatches=ir;var ht=class extends f{create(e,t){return this._client.post("/videos",de({body:e,...t},this._client))}retrieve(e,t){return this._client.get(c`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",pe,{query:e,...t})}delete(e,t){return this._client.delete(c`/videos/${e}`,t)}downloadContent(e,t={},r){return this._client.get(c`/videos/${e}/content`,{query:t,...r,headers:g([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}remix(e,t,r){return this._client.post(c`/videos/${e}/remix`,de({body:t,...r},this._client))}};var lr,wo,hs,pt=class extends f{constructor(){super(...arguments),lr.add(this)}async unwrap(e,t,r=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,r,n),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,n=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");l(this,lr,"m",wo).call(this,r);let o=g([t]).values,i=l(this,lr,"m",hs).call(this,o,"webhook-signature"),a=l(this,lr,"m",hs).call(this,o,"webhook-timestamp"),u=l(this,lr,"m",hs).call(this,o,"webhook-id"),p=parseInt(a,10);if(isNaN(p))throw new oe("Invalid webhook timestamp format");let m=Math.floor(Date.now()/1e3);if(m-p>n)throw new oe("Webhook timestamp is too old");if(p>m+n)throw new oe("Webhook timestamp is too new");let d=i.split(" ").map(b=>b.startsWith("v1,")?b.substring(3):b),_=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=u?`${u}.${a}.${e}`:`${a}.${e}`,A=await crypto.subtle.importKey("raw",_,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(let b of d)try{let R=Buffer.from(b,"base64");if(await crypto.subtle.verify("HMAC",A,R,new TextEncoder().encode(h)))return}catch{continue}throw new oe("The given webhook signature does not match the expected signature")}};lr=new WeakSet,wo=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},hs=function(e,t){if(!e)throw new Error("Headers are required");let r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var sn,nn,ps,xo,I=class{constructor({baseURL:e=Oe("OPENAI_BASE_URL"),apiKey:t=Oe("OPENAI_API_KEY"),organization:r=Oe("OPENAI_ORG_ID")??null,project:n=Oe("OPENAI_PROJECT_ID")??null,webhookSecret:o=Oe("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(sn.add(this),ps.set(this,void 0),this.completions=new et(this),this.chat=new Ce(this),this.embeddings=new rt(this),this.files=new nt(this),this.images=new lt(this),this.audio=new ue(this),this.moderations=new ut(this),this.models=new ct(this),this.fineTuning=new ne(this),this.graders=new Le(this),this.vectorStores=new Ae(this),this.webhooks=new pt(this),this.beta=new se(this),this.batches=new ze(this),this.uploads=new Be(this),this.responses=new we(this),this.realtime=new be(this),this.conversations=new Ne(this),this.evals=new Me(this),this.containers=new Fe(this),this.skills=new xe(this),this.videos=new ht(this),t===void 0)throw new y("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let a={apiKey:t,organization:r,project:n,webhookSecret:o,...i,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Rn())throw new y(`It looks like you're running in a browser-like environment.
|
|
139
139
|
|
|
140
140
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
141
141
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -144,16 +144,16 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
144
144
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
145
145
|
|
|
146
146
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
147
|
-
`);this.baseURL=a.baseURL,this.timeout=a.timeout??nn.DEFAULT_TIMEOUT,this.logger=a.logger??console;let u="warn";this.logLevel=u,this.logLevel=Ts(a.logLevel,"ClientOptions.logLevel",this)??Ts(Ne("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Cn(),x(this,ps,kn,"f"),this._options=a,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=r,this.project=n,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return g([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return ks(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ce}`}defaultIdempotencyKey(){return`stainless-node-retry-${xs()}`}makeStatusError(e,t,r,n){return B.generate(e,t,r,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof y?r:new y(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new y(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!l(this,sn,"m",xo).call(this)&&r||this.baseURL,o=bn(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return wn(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Je(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:i,url:a,timeout:u}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(i,{url:a,options:n});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(M(this).debug(`[${p}] sending request`,he({retryOfRequestLogID:r,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new L;let _=new AbortController,h=await this.fetchWithTimeout(a,i,u,_).catch(hr),A=Date.now();if(h instanceof globalThis.Error){let v=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new L;let w=fr(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return M(this).info(`[${p}] connection ${w?"timed out":"failed"} - ${v}`),M(this).debug(`[${p}] connection ${w?"timed out":"failed"} (${v})`,he({retryOfRequestLogID:r,url:a,durationMs:A-d,message:h.message})),this.retryRequest(n,t,r??p);throw M(this).info(`[${p}] connection ${w?"timed out":"failed"} - error; no more retries left`),M(this).debug(`[${p}] connection ${w?"timed out":"failed"} (error; no more retries left)`,he({retryOfRequestLogID:r,url:a,durationMs:A-d,message:h.message})),w?new Ee:new Re({cause:h})}let b=[...h.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,w])=>", "+v+": "+JSON.stringify(w)).join(""),R=`[${p}${m}${b}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${A-d}ms`;if(!h.ok){let v=await this.shouldRetry(h);if(t&&v){let C=`retrying, ${t} attempts remaining`;return await $n(h.body),M(this).info(`${R} - ${C}`),M(this).debug(`[${p}] response error (${C})`,he({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:A-d})),this.retryRequest(n,t,r??p,h.headers)}let w=v?"error; no more retries left":"error; not retryable";M(this).info(`${R} - ${w}`);let k=await h.text().catch(C=>hr(C).message),P=In(k),E=P?void 0:k;throw M(this).debug(`[${p}] response error (${w})`,he({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:E,durationMs:Date.now()-d})),this.makeStatusError(h.status,P,E,h.headers)}return M(this).info(R),M(this).debug(`[${p}] response start`,he({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:A-d})),{response:h,options:n,controller:_,requestLogID:p,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new yr(this,r,e)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:i,...a}=t||{},u=this._makeAbort(n);o&&o.addEventListener("abort",u,{once:!0});let p=setTimeout(u,r),m=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:n.signal,...m?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(p)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,n){let o,i=n?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let a=n?.get("retry-after");if(a&&!o){let u=parseFloat(a);Number.isNaN(u)?o=Date.parse(a)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await ie(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:i,defaultBaseURL:a}=r,u=this.buildURL(o,i,a);"timeout"in r&&An("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:m}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=g([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...En(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=g([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Br(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:l(this,ps,"f").call(this,{body:e,headers:r})}};nn=I,ps=new WeakMap,sn=new WeakSet,xo=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=nn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=B;I.APIConnectionError=Re;I.APIConnectionTimeoutError=Ee;I.APIUserAbortError=L;I.NotFoundError=wt;I.ConflictError=xt;I.RateLimitError=It;I.BadRequestError=_t;I.AuthenticationError=yt;I.InternalServerError=St;I.PermissionDeniedError=bt;I.UnprocessableEntityError=At;I.InvalidWebhookSignatureError=oe;I.toFile=Xr;I.Completions=et;I.Chat=Oe;I.Embeddings=rt;I.Files=nt;I.Images=lt;I.Audio=ue;I.Moderations=ut;I.Models=ct;I.FineTuning=ne;I.Graders=Ue;I.VectorStores=Ae;I.Webhooks=pt;I.Beta=se;I.Batches=ze;I.Uploads=He;I.Responses=we;I.Realtime=be;I.Conversations=je;I.Evals=Be;I.Containers=Le;I.Skills=xe;I.Videos=ht;async function Yi(s,e,t){await s.evaluate(()=>{let m=document.getElementById("playwright-highlight-container");m&&m.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(d=>d()),window._highlightCleanupFunctions=[])});let r=await s.screenshot({type:"png",fullPage:!1}),{default:n}=await import("sharp"),o=n(r),i=await o.metadata(),a=i.width||0,u=i.height||0;ee.log(`Screenshot actual dimensions: ${a}x${u}, viewport: ${e}x${t}`);let p;return a!==e||u!==t?(ee.log(`Resizing screenshot from ${a}x${u} to ${e}x${t}`),p=await o.resize(e,t).png().toBuffer()):p=r,p.toString("base64")}async function on(s,e,t){let r=await s.evaluateHandle(u=>document.elementFromPoint(u.x,u.y),{x:e,y:t});if(!r)throw new Error(`No element found at (${e}, ${t})`);let n=r.asElement();if(!n)throw await r.dispose(),new Error(`No element found at (${e}, ${t})`);let o=await n.boundingBox();if(!o)throw await r.dispose(),new Error("Element has no bounding box");let i=e-(o.x+o.width/2),a=t-(o.y+o.height/2);return{relative_x:i,relative_y:a,element:n}}async function Qi(s,e){return e?{xpath:void 0,locator:(e?await fn(s,e):null)||void 0,frame_path:[]}:{xpath:void 0,locator:void 0,frame_path:[]}}async function Zi(s,e){let t=null,r=null;switch(e.type){case"click":{let o=e.button==="right"?"right_click_by_coordinates":"click_by_coordinates";if(e.x===void 0||e.y===void 0)break;let i=await on(s,e.x,e.y);t={action_name:o,kwargs:{relative_x:i.relative_x,relative_y:i.relative_y}},r=i.element;break}case"double_click":{if(e.x===void 0||e.y===void 0)break;let o=await on(s,e.x,e.y);t={action_name:"double_click_by_coordinates",kwargs:{relative_x:o.relative_x,relative_y:o.relative_y}},r=o.element;break}case"drag":{if(!e.path||e.path.length<2)break;let o=e.path[0].x,i=e.path[0].y,a=e.path[1].x,u=e.path[1].y,p=await on(s,o,i);t={action_name:"drag_drop",kwargs:{relative_x:p.relative_x,relative_y:p.relative_y,delta_x:a-o,delta_y:u-i}},r=p.element;break}}let n=await Qi(s,r);return{action_data:t,locatorInfo:n}}async function ds(s,e,t={}){try{let{page:r}=e,n=r.viewportSize();if(!n)return{status:"error",error:"Viewport size not available"};let o=n.width,i=n.height;ee.log(`Viewport size: ${o}x${i}`);let a=await Yi(r,o,i),u=un().env?.OPENAI_API_KEY;if(!u)return{status:"error",error:"OpenAI API key not found. Set OPENAI_API_KEY environment variable or configure via SDK config."};let p=new I({apiKey:u});ee.log("Sending request to OpenAI CUA...");let m=[{role:"user",content:[{type:"input_text",text:`
|
|
147
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??nn.DEFAULT_TIMEOUT,this.logger=a.logger??console;let u="warn";this.logLevel=u,this.logLevel=Ts(a.logLevel,"ClientOptions.logLevel",this)??Ts(Oe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??Cn(),x(this,ps,kn,"f"),this._options=a,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=r,this.project=n,this.webhookSecret=o}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return g([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return ks(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Pe}`}defaultIdempotencyKey(){return`stainless-node-retry-${xs()}`}makeStatusError(e,t,r,n){return B.generate(e,t,r,n)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(r){throw r instanceof y?r:new y(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof t!="string"||!t)throw new y(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,r){let n=!l(this,sn,"m",xo).call(this)&&r||this.baseURL,o=bn(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return wn(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(o.search=this.stringifyQuery(t)),o.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new Je(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){let n=await e,o=n.maxRetries??this.maxRetries;t==null&&(t=o),await this.prepareOptions(n);let{req:i,url:a,timeout:u}=await this.buildRequest(n,{retryCount:o-t});await this.prepareRequest(i,{url:a,options:n});let p="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),m=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(M(this).debug(`[${p}] sending request`,he({retryOfRequestLogID:r,method:n.method,url:a,options:n,headers:i.headers})),n.signal?.aborted)throw new L;let _=new AbortController,h=await this.fetchWithTimeout(a,i,u,_).catch(hr),A=Date.now();if(h instanceof globalThis.Error){let v=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new L;let w=fr(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return M(this).info(`[${p}] connection ${w?"timed out":"failed"} - ${v}`),M(this).debug(`[${p}] connection ${w?"timed out":"failed"} (${v})`,he({retryOfRequestLogID:r,url:a,durationMs:A-d,message:h.message})),this.retryRequest(n,t,r??p);throw M(this).info(`[${p}] connection ${w?"timed out":"failed"} - error; no more retries left`),M(this).debug(`[${p}] connection ${w?"timed out":"failed"} (error; no more retries left)`,he({retryOfRequestLogID:r,url:a,durationMs:A-d,message:h.message})),w?new ve:new Se({cause:h})}let b=[...h.headers.entries()].filter(([v])=>v==="x-request-id").map(([v,w])=>", "+v+": "+JSON.stringify(w)).join(""),R=`[${p}${m}${b}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${A-d}ms`;if(!h.ok){let v=await this.shouldRetry(h);if(t&&v){let C=`retrying, ${t} attempts remaining`;return await $n(h.body),M(this).info(`${R} - ${C}`),M(this).debug(`[${p}] response error (${C})`,he({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:A-d})),this.retryRequest(n,t,r??p,h.headers)}let w=v?"error; no more retries left":"error; not retryable";M(this).info(`${R} - ${w}`);let k=await h.text().catch(C=>hr(C).message),P=In(k),E=P?void 0:k;throw M(this).debug(`[${p}] response error (${w})`,he({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:E,durationMs:Date.now()-d})),this.makeStatusError(h.status,P,E,h.headers)}return M(this).info(R),M(this).debug(`[${p}] response start`,he({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:A-d})),{response:h,options:n,controller:_,requestLogID:p,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,r&&"then"in r?r.then(n=>({method:"get",path:e,...n})):{method:"get",path:e,...r})}requestAPIList(e,t){let r=this.makeRequest(t,null,void 0);return new yr(this,r,e)}async fetchWithTimeout(e,t,r,n){let{signal:o,method:i,...a}=t||{},u=this._makeAbort(n);o&&o.addEventListener("abort",u,{once:!0});let p=setTimeout(u,r),m=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,d={signal:n.signal,...m?{duplex:"half"}:{},method:"GET",...a};i&&(d.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(p)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,n){let o,i=n?.get("retry-after-ms");if(i){let u=parseFloat(i);Number.isNaN(u)||(o=u)}let a=n?.get("retry-after");if(a&&!o){let u=parseFloat(a);Number.isNaN(u)?o=Date.parse(a)-Date.now():o=u*1e3}if(!(o&&0<=o&&o<60*1e3)){let u=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,u)}return await ie(o),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}async buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:i,defaultBaseURL:a}=r,u=this.buildURL(o,i,a);"timeout"in r&&An("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let{bodyHeaders:p,body:m}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:n,bodyHeaders:p,retryCount:t});return{req:{method:n,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&m instanceof globalThis.ReadableStream&&{duplex:"half"},...m&&{body:m},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:n}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=g([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...En(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let r=g([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Br(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:l(this,ps,"f").call(this,{body:e,headers:r})}};nn=I,ps=new WeakMap,sn=new WeakSet,xo=function(){return this.baseURL!=="https://api.openai.com/v1"};I.OpenAI=nn;I.DEFAULT_TIMEOUT=6e5;I.OpenAIError=y;I.APIError=B;I.APIConnectionError=Se;I.APIConnectionTimeoutError=ve;I.APIUserAbortError=L;I.NotFoundError=wt;I.ConflictError=xt;I.RateLimitError=It;I.BadRequestError=_t;I.AuthenticationError=yt;I.InternalServerError=St;I.PermissionDeniedError=bt;I.UnprocessableEntityError=At;I.InvalidWebhookSignatureError=oe;I.toFile=Xr;I.Completions=et;I.Chat=Ce;I.Embeddings=rt;I.Files=nt;I.Images=lt;I.Audio=ue;I.Moderations=ut;I.Models=ct;I.FineTuning=ne;I.Graders=Le;I.VectorStores=Ae;I.Webhooks=pt;I.Beta=se;I.Batches=ze;I.Uploads=Be;I.Responses=we;I.Realtime=be;I.Conversations=Ne;I.Evals=Me;I.Containers=Fe;I.Skills=xe;I.Videos=ht;async function Yi(s,e,t){await s.evaluate(()=>{let m=document.getElementById("playwright-highlight-container");m&&m.remove(),window._highlightCleanupFunctions&&(window._highlightCleanupFunctions.forEach(d=>d()),window._highlightCleanupFunctions=[])});let r=await s.screenshot({type:"png",fullPage:!1}),{default:n}=await import("sharp"),o=n(r),i=await o.metadata(),a=i.width||0,u=i.height||0;ee.log(`Screenshot actual dimensions: ${a}x${u}, viewport: ${e}x${t}`);let p;return a!==e||u!==t?(ee.log(`Resizing screenshot from ${a}x${u} to ${e}x${t}`),p=await o.resize(e,t).png().toBuffer()):p=r,p.toString("base64")}async function on(s,e,t){let r=await s.evaluateHandle(u=>document.elementFromPoint(u.x,u.y),{x:e,y:t});if(!r)throw new Error(`No element found at (${e}, ${t})`);let n=r.asElement();if(!n)throw await r.dispose(),new Error(`No element found at (${e}, ${t})`);let o=await n.boundingBox();if(!o)throw await r.dispose(),new Error("Element has no bounding box");let i=e-(o.x+o.width/2),a=t-(o.y+o.height/2);return{relative_x:i,relative_y:a,element:n}}async function Qi(s,e){return e?{xpath:void 0,locator:(e?await fn(s,e):null)||void 0,frame_path:[]}:{xpath:void 0,locator:void 0,frame_path:[]}}async function Zi(s,e){let t=null,r=null;switch(e.type){case"click":{let o=e.button==="right"?"right_click_by_coordinates":"click_by_coordinates";if(e.x===void 0||e.y===void 0)break;let i=await on(s,e.x,e.y);t={action_name:o,kwargs:{relative_x:i.relative_x,relative_y:i.relative_y}},r=i.element;break}case"double_click":{if(e.x===void 0||e.y===void 0)break;let o=await on(s,e.x,e.y);t={action_name:"double_click_by_coordinates",kwargs:{relative_x:o.relative_x,relative_y:o.relative_y}},r=o.element;break}case"drag":{if(!e.path||e.path.length<2)break;let o=e.path[0].x,i=e.path[0].y,a=e.path[1].x,u=e.path[1].y,p=await on(s,o,i);t={action_name:"drag_drop",kwargs:{relative_x:p.relative_x,relative_y:p.relative_y,delta_x:a-o,delta_y:u-i}},r=p.element;break}}let n=await Qi(s,r);return{action_data:t,locatorInfo:n}}async function ds(s,e,t={}){try{let{page:r}=e,n=r.viewportSize();if(!n)return{status:"error",error:"Viewport size not available"};let o=n.width,i=n.height;ee.log(`Viewport size: ${o}x${i}`);let a=await Yi(r,o,i),u=un().env?.OPENAI_API_KEY;if(!u)return{status:"error",error:"OpenAI API key not found. Set OPENAI_API_KEY environment variable or configure via SDK config."};let p=new I({apiKey:u});ee.log("Sending request to OpenAI CUA...");let m=[{role:"user",content:[{type:"input_text",text:`
|
|
148
148
|
You will be given an action to execute and screenshot of the current screen.
|
|
149
149
|
Output one computer_call object that will accomplish this action.
|
|
150
150
|
Action: ${s}
|
|
151
151
|
`},{type:"input_image",detail:"auto",image_url:`data:image/png;base64,${a}`}]}],d=await p.responses.create({model:"computer-use-preview",tools:[{type:"computer_use_preview",display_width:o,display_height:i,environment:"browser"}],input:m,truncation:"auto",temperature:.1});ee.log("Received response from OpenAI CUA");let _=d.output.filter(R=>R.type==="computer_call")[0]??null;if(!_)return{status:"error",reasoning:d.output_text||""||"Invalid action generation response",error:"No computer_call action generated"};let h=_.action;ee.log(`Generated action: ${JSON.stringify(h)}`);let{action_data:A,locatorInfo:b}=await Zi(r,h);return A?{status:"success",actionEntity:{action_description:s,action_data:A,locator:b.locator||void 0,xpath:b.xpath||void 0,frame_path:b.frame_path},reasoning:"Action generated successfully using pure vision mode",goalAccomplished:!0}:{status:"error",error:"Failed to map action to ActionDataEntity"}}catch(r){return ee.error("Error generating CUA action",r),{status:"error",error:r.message||"Failed to generate action with pure vision"}}}function ms(s,e){return s?{prompt_tokens:s.promptTokens||s.inputTokens||0,completion_tokens:s.completionTokens||s.outputTokens||0,total_tokens:s.totalTokens||0,model:e}:null}async function ea(s){let e=s.context().pages(),t=null,r=[];for(let o=0;o<e.length;o++){let i=e[o];i===s&&(t=o);let a="(title unavailable)";try{a=await Promise.race([i.title(),new Promise((p,m)=>setTimeout(()=>m(new Error("timeout")),1e3))])}catch{}let u=`Tab ${o}: ${i.url()}`;a&&(u+=` - ${a.slice(0,50)}`),r.push(u)}let n=r.length>0?r.join(`
|
|
152
152
|
`):"";return{currentTabText:t!==null?`Current tab: ${t}
|
|
153
|
-
`:"",tabsText:n}}async function ta(s,e){let{currentTabText:t,tabsText:r}=await ea(s);return{elementsText:e,currentUrl:s.url(),currentTitle:await s.title(),currentTabText:t,tabsText:r}}async function gs(s,e){let{page:t,domService:r,agentServices:n}=s,o=typeof e=="boolean"?{useCleanScreenshot:e}:e||{},i=n.getInteractiveClassNames(),a=n.getIframeFallbackDomains(),{domState:u,screenshotBase64:p,slicedScreenshotsBase64:m}=await r.getClickableElementsWithScreenshot(t,{interactiveClassNames:i,playwrightFrameFallbackDomains:a,useCleanScreenshot:o.useCleanScreenshot,useSlicedScreenshots:o.useSlicedScreenshots,resizeSlicedScreenshots:o.resizeSlicedScreenshots,useAccessibilityTree:o.useAccessibilityTree,actionIntent:o.actionIntent}),d=u.elementTree.clickableElementsToString(),_=await ta(t,d);return m&&(_.slicedScreenshotsBase64=m),{domTree:d,screenshotBase64:p,slicedScreenshotsBase64:m,domState:u,pageContext:_}}import{z as _s}from"zod";function ra(s){let e=s.toLowerCase();return[/\b(type|enter|input|fill|write|set)\b/,/\b(text|value|field|box)\b.*\b(to|with|as)\b/,/\b(username|password|email|search|query)\b/].some(t=>t.test(e))?"input":[/\bscroll\b/,/\b(scroll|swipe)\s*(up|down|left|right)\b/,/\b(page|move)\s*(down|up)\b/].some(t=>t.test(e))?"scroll":[/\b(click|tap|press|select|choose|pick|check|toggle)\b/,/\b(open|close|submit|confirm|cancel|dismiss)\b/,/\b(button|link|menu|dropdown|checkbox|radio)\b/].some(t=>t.test(e))?"click":"all"}function sa(s){if(!s)return null;if(s instanceof URL)return s.href;if(typeof s=="object"&&s.href)return String(s.href);if(typeof s=="object"&&typeof s.toString=="function"){let e=s.toString();if(e.startsWith("http://")||e.startsWith("https://"))return e}return typeof s=="string"&&(s.startsWith("http://")||s.startsWith("https://"))?s:null}function na(s){return s.map(e=>({role:e.role,content:Array.isArray(e.content)?e.content.map(t=>{if(t.type==="image"){let r=t.image,n=sa(r);if(n)return{type:"image",file:n};let o=typeof r=="string"?r:"";return{type:"image",file:o.startsWith("data:")?o:`data:image/png;base64,${o}`}}return{type:"text",text:t.text}}):e.content}))}async function Ao(s,e,t={}){let{page:r,agentServices:n}=e,o=n.getModel(),i=t.temperature??0,a=n.retrieveKnowledges(s).catch(
|
|
153
|
+
`:"",tabsText:n}}async function ta(s,e){let{currentTabText:t,tabsText:r}=await ea(s);return{elementsText:e,currentUrl:s.url(),currentTitle:await s.title(),currentTabText:t,tabsText:r}}async function gs(s,e){let{page:t,domService:r,agentServices:n}=s,o=typeof e=="boolean"?{useCleanScreenshot:e}:e||{},i=n.getInteractiveClassNames(),a=n.getIframeFallbackDomains(),{domState:u,screenshotBase64:p,slicedScreenshotsBase64:m}=await r.getClickableElementsWithScreenshot(t,{interactiveClassNames:i,playwrightFrameFallbackDomains:a,useCleanScreenshot:o.useCleanScreenshot,useSlicedScreenshots:o.useSlicedScreenshots,resizeSlicedScreenshots:o.resizeSlicedScreenshots,useAccessibilityTree:o.useAccessibilityTree,actionIntent:o.actionIntent}),d=u.elementTree.clickableElementsToString(),_=await ta(t,d);return m&&(_.slicedScreenshotsBase64=m),{domTree:d,screenshotBase64:p,slicedScreenshotsBase64:m,domState:u,pageContext:_}}import{z as _s}from"zod";function ra(s){let e=s.toLowerCase();return[/\b(type|enter|input|fill|write|set)\b/,/\b(text|value|field|box)\b.*\b(to|with|as)\b/,/\b(username|password|email|search|query)\b/].some(t=>t.test(e))?"input":[/\bscroll\b/,/\b(scroll|swipe)\s*(up|down|left|right)\b/,/\b(page|move)\s*(down|up)\b/].some(t=>t.test(e))?"scroll":[/\b(click|tap|press|select|choose|pick|check|toggle)\b/,/\b(open|close|submit|confirm|cancel|dismiss)\b/,/\b(button|link|menu|dropdown|checkbox|radio)\b/].some(t=>t.test(e))?"click":"all"}function sa(s){if(!s)return null;if(s instanceof URL)return s.href;if(typeof s=="object"&&s.href)return String(s.href);if(typeof s=="object"&&typeof s.toString=="function"){let e=s.toString();if(e.startsWith("http://")||e.startsWith("https://"))return e}return typeof s=="string"&&(s.startsWith("http://")||s.startsWith("https://"))?s:null}function na(s){return s.map(e=>({role:e.role,content:Array.isArray(e.content)?e.content.map(t=>{if(t.type==="image"){let r=t.image,n=sa(r);if(n)return{type:"image",file:n};let o=typeof r=="string"?r:"";return{type:"image",file:o.startsWith("data:")?o:`data:image/png;base64,${o}`}}return{type:"text",text:t.text}}):e.content}))}async function Ao(s,e,t={}){let{page:r,agentServices:n}=e,o=n.getModel(),i=t.temperature??0,a=n.retrieveKnowledges(s).catch(X=>(ee.log(`Failed to retrieve knowledges: ${X.message}`),[])),u=n.isSlicedScreenshotsEnabled(),p=n.isResizeSlicedScreenshotsEnabled(),m=n.isKnowledgeImagesEnabled(),d=n.isAccessibilityTreeEnabled(),_=n.isActionIntentFilteringEnabled(),h=_?ra(s):"all";_&&h!=="all"&&ee.log(`Action intent filtering: detected '${h}' intent from statement`);let{screenshotBase64:A,domState:b,pageContext:R}=await gs(e,{useSlicedScreenshots:u,resizeSlicedScreenshots:p,useAccessibilityTree:d,actionIntent:h});e.domState=b;let v=new dn(gt).getToolDefinitions().map(X=>{let mt=X.function;return`${mt.name}: ${mt.description}
|
|
154
154
|
Parameters: ${JSON.stringify(mt.parameters,null,2)}`}).join(`
|
|
155
155
|
|
|
156
|
-
`),w=_n(v),k=await a,P=yn(R,s,e.variables,e.executionHistory,k.length>0?k:void 0,A,u,void 0,m,e.sensitiveKeys),E=[];t.chatHistory&&t.chatHistory.length>0&&t.chatHistory.forEach(
|
|
156
|
+
`),w=_n(v),k=await a,P=yn(R,s,e.variables,e.executionHistory,k.length>0?k:void 0,A,u,void 0,m,e.sensitiveKeys),E=[];t.chatHistory&&t.chatHistory.length>0&&t.chatHistory.forEach(X=>{X.role==="user"?E.push({role:"user",content:X.content}):X.role==="assistant"&&E.push({role:"assistant",content:X.content})}),E.push({role:"user",content:P});let O=na(E),C=gt.buildActionUnionSchema(),F=_s.object({thought:_s.string().describe("Step by step reasoning of your decision making process").optional().default(""),description:_s.string().describe("Detailed description of the action to be performed").optional().default(""),action:C,completes_instruction:_s.boolean().describe("Whether this action completes the given instruction").optional().default(!1)}),N=Array.isArray(P)?P.filter(X=>X.type==="image").length:0,T=Tr(o,N),$=await Nr({model:Or(o),system:w,messages:E,temperature:i,output:Fr.object({schema:F}),providerOptions:T}),Ie=$.reasoningText;ws.info(`Action Generation Reasoning: ${Ie}`);let Q=$.output,dt=JSON.stringify(Q,null,2);ws.info(`Generate Action Raw Output: ${dt}`);let Ue=[],cr=ms($.usage,o);cr&&Ue.push(cr);let De={systemPrompt:w,userPrompt:O,rawLlmResponse:dt,tokenUsages:Ue},He=Q.thought||"",We=Q.description||"",j=Q.action||{},V=Q.completes_instruction||!1;if(!j||Object.keys(j).length===0)return{status:"error",reasoning:He||We||"No action generated",goalAccomplished:V,error:"Agent did not generate any action",debugInfo:De};let J=Object.keys(j)[0];if(J==="done")return{status:"error",reasoning:He||We||"Task marked as done",goalAccomplished:V,error:"Agent indicated task is done without generating an action",debugInfo:De};if(J==="perform_accurate_operation")return await ds(s,e,t);let Z=j[J]||{},ln={};if(typeof Z.element_index=="number"){let X=Z.element_index;if(X<0)return{status:"error",reasoning:He||We||"No action generated",goalAccomplished:V,error:"Agent did not generate any action",debugInfo:De};let mt=b.selectorMap.get(X);mt&&(ln=await hn(r,mt))}let cn=We;return J==="verify"&&(cn=s,Z.statement=s),{status:"success",actionEntity:{...ln,action_description:cn||He||`${J}(${JSON.stringify(Z)})`,action_data:{action_name:J,kwargs:Z}},reasoning:He||We,goalAccomplished:V,debugInfo:De}}import{z as ys}from"zod";function oa(s){if(!s)return null;if(s instanceof URL)return s.href;if(typeof s=="object"&&s.href)return String(s.href);if(typeof s=="object"&&typeof s.toString=="function"){let e=s.toString();if(e.startsWith("http://")||e.startsWith("https://"))return e}return typeof s=="string"&&(s.startsWith("http://")||s.startsWith("https://"))?s:null}var ia=ys.object({screenshotDescription:ys.string().describe(`Description of the screenshot content, listing out key elements along with their Set of Mark indices,
|
|
157
157
|
and a description of their location: formatting example: [12] A red button with text "Submit", next to [11]
|
|
158
158
|
[45] A modal dialog titled "Confirmation",
|
|
159
159
|
in the center of the screen`),explanation:ys.string().describe("Step by step reasoning explaining your conclusion about the statement"),conclusion:ys.enum(["true","false","unknown"]).describe("Whether the statement is true, false, or unknown if you cannot make a conclusion")});async function an(s,e,t={}){return t.usePureVision?ds(s,e,t):Ao(s,e,t)}function aa(){let s=new Date,e=s.toLocaleDateString("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/Los_Angeles"}),t=s.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3,timeZoneName:"short",timeZone:"America/Los_Angeles"});return{dateString:e,timeString:t}}function la(){return`# Role
|
|
@@ -161,8 +161,8 @@ You are an experienced QA person for web applications.
|
|
|
161
161
|
You are tasked to verify the validity of a given statement based on the screenshot and element tree of a web page.
|
|
162
162
|
`}async function Io(s,e,t={}){let{page:r,executionHistory:n}=e,o=e.agentServices.getModel();try{let i=e.agentServices.isSlicedScreenshotsEnabled(),a=e.agentServices.isResizeSlicedScreenshotsEnabled(),u=e.agentServices.isKnowledgeImagesEnabled(),p=e.agentServices.isAccessibilityTreeEnabled(),{domTree:m,screenshotBase64:d,slicedScreenshotsBase64:_,domState:h,pageContext:A}=await gs(e,{useCleanScreenshot:t.useCleanScreenshotForAssertion,useSlicedScreenshots:i,resizeSlicedScreenshots:a,useAccessibilityTree:p});e.domState=h;let b="";n&&n.length>0&&(b=`
|
|
163
163
|
# Previous actions in this session:
|
|
164
|
-
${n.map(([j,
|
|
165
|
-
Result: ${
|
|
164
|
+
${n.map(([j,V],J)=>`${J+1}. Action: ${j}
|
|
165
|
+
Result: ${V}`).join(`
|
|
166
166
|
`)}
|
|
167
167
|
`);let{dateString:R,timeString:v}=aa(),w=`
|
|
168
168
|
# User statement
|
|
@@ -183,7 +183,7 @@ ${m}
|
|
|
183
183
|
|
|
184
184
|
## Screenshot
|
|
185
185
|
${i&&_?"The following images are sliced screenshots of the current webpage (left, middle, right sections).":"The image provided is a screenshot of the current webpage."}
|
|
186
|
-
`,k="";if(e.variables&&Object.keys(e.variables).length>0){let j=[];for(let
|
|
186
|
+
`,k="";if(e.variables&&Object.keys(e.variables).length>0){let j=[];for(let V of Object.keys(e.variables))if(!e.sensitiveKeys?.has(V)){let J=e.variables[V],Z=typeof J=="string"?J:JSON.stringify(J);j.push(` - ${V}: "${Z}"`)}j.length>0&&(k=`
|
|
187
187
|
## Available Variables
|
|
188
188
|
The following non-sensitive variables are available:
|
|
189
189
|
${j.join(`
|
|
@@ -193,4 +193,4 @@ ${b}
|
|
|
193
193
|
|
|
194
194
|
Today is ${R}. Current local time is ${v}.
|
|
195
195
|
Based on the above information, please determine if the statement is true.
|
|
196
|
-
`,E=await e.agentServices.retrieveKnowledges(s),O=[{type:"text",text:w}],C=0;if(i&&_&&_.length>0)for(let j of _)O.push({type:"image",image:j}),C++;else O.push({type:"image",image:d}),C=1;if(E&&E.length>0){let j=jr(E,u);O.push(...j)}O.push({type:"text",text:P});let F=E?gn(E,u):0,N=C+F,T=Tr(o,N),$=la(),Ie=await Nr({model:Or(o),system:$,messages:[{role:"user",content:O}],output:Fr.object({schema:ia}),temperature:0,providerOptions:T}),{conclusion:Q,explanation:dt}=Ie.output,
|
|
196
|
+
`,E=await e.agentServices.retrieveKnowledges(s),O=[{type:"text",text:w}],C=0;if(i&&_&&_.length>0)for(let j of _)O.push({type:"image",image:j}),C++;else O.push({type:"image",image:d}),C=1;if(E&&E.length>0){let j=jr(E,u);O.push(...j)}O.push({type:"text",text:P});let F=E?gn(E,u):0,N=C+F,T=Tr(o,N),$=la(),Ie=await Nr({model:Or(o),system:$,messages:[{role:"user",content:O}],output:Fr.object({schema:ia}),temperature:0,providerOptions:T}),{conclusion:Q,explanation:dt}=Ie.output,Ue=JSON.stringify(Ie.output,null,2),cr=[],De=ms(Ie.usage,o);De&&cr.push(De);let He=[{role:"user",content:O.map(j=>{if(j.type==="text")return{type:"text",text:j.text};if(j.type==="image"){let V=j.image,J=oa(V);if(J)return{type:"image",file:J};let Z=typeof V=="string"?V:"";return{type:"image",file:Z.startsWith("data:")?Z:`data:image/png;base64,${Z}`}}return{type:"text",text:"[unknown content type]"}})}],We={systemPrompt:$,userPrompt:He,rawLlmResponse:Ue,screenshotWithSom:d,tokenUsages:cr,retrievedKnowledges:E&&E.length>0?E:void 0,elementTree:m};return{success:Q==="true",explanation:dt,debugInfo:We}}catch(i){return{success:!1,error:i.message}}}async function ca(s,e){try{if(!s.action_data)return{success:!1,error:"Action entity missing action_data"};let{action_name:t,kwargs:r}=s.action_data;if(gt.has(t)){let n=await gt.execute(t,r,e),o=n?.success!==!1,i=n?.error||n?.message;return{success:o,error:o?void 0:i}}else{let{page:n,agentServices:o}=e;return await(await ua()).execute(n,s,o),{success:!0,error:void 0}}}catch(t){return{success:!1,error:t.message}}}var bs=null;async function ua(){if(bs)return bs;let s=await import("./handler-SLPMHZMZ.js");return bs=new s.default,bs}async function sg(s,e,t,r={},n){let o=n||{page:e,agentServices:t,domService:new Mr(t.getDomServiceOptions()),executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},i=t.replaceVariables(s),a=await an(i,o,r);return a.status==="error"?{status:"error",completed:a.goalAccomplished||!1,actionEntities:[],explanation:a.reasoning,error:a.error,debugInfo:a.debugInfo}:{status:"success",completed:a.goalAccomplished||!1,actionEntities:a.actionEntity?[a.actionEntity]:[],explanation:a.reasoning,debugInfo:a.debugInfo}}async function ng(s,e,t,r={},n){let o=n||{page:e,agentServices:t,domService:new Mr(t.getDomServiceOptions()),executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},i=t.replaceVariables(s),a=await an(i,o,r);if(a.status==="error"||!a.actionEntity)return{status:"error",completed:a.goalAccomplished||!1,actionEntities:[],explanation:a.reasoning,error:a.error||"No action generated",debugInfo:a.debugInfo};let{actionEntity:u,reasoning:p,goalAccomplished:m,debugInfo:d}=a,_=await ca(u,o);return _.success?(p&&t.addNote(p),{status:"success",completed:m||!1,actionEntities:[u],explanation:p,debugInfo:d}):{status:"error",completed:!1,actionEntities:[u],error:_.error||"Action execution failed",debugInfo:d}}async function og(s,e,t,r={}){let n={page:e,agentServices:t,domService:new Mr(t.getDomServiceOptions()),executionHistory:r.executionHistory,variables:r.variables,sensitiveKeys:r.sensitiveKeys},o=t.replaceVariables(s);return r.useCleanScreenshotForAssertion??(r.useCleanScreenshotForAssertion=t.isUseCleanScreenshotForAssertion()),Io(o,n,r)}async function ig(s,e,t,r,n={}){let{runTaskLoop:o}=await import("./task-5YHIIFEV.js"),i=r?u=>{r(u)}:void 0,a=await o(s,{page:e,agentServices:t,domService:void 0,executionHistory:n.executionHistory,variables:n.variables,sensitiveKeys:n.sensitiveKeys},{maxSteps:n.maxSteps,onEvent:i,abortSignal:n.abortSignal});return{status:a.success?"success":"error",completed:a.completed,actionEntities:a.trajectory.actions,explanation:a.summary,error:a.error,tokenUsages:a.metadata.tokenUsages}}export{ha as a,dn as b,ds as c,ca as d,sg as e,ng as f,og as g,ig as h};
|