agricultural-sock-amalysis/docs/dist/assets/aiService-C9Fe_Phd-d1533d53.js

41 lines
98 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import{j as Un,u as Wn,G as Fn}from"./main-f65d595e.js";function v(s,e,t,n,r){if(typeof e=="function"?s!==e||!0:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(s,t),t}function a(s,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(s):n?n.value:e.get(s)}let _s=function(){const{crypto:s}=globalThis;if(s!=null&&s.randomUUID)return _s=s.randomUUID.bind(s),s.randomUUID();const e=new Uint8Array(1),t=s?()=>s.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^t()&15>>+n/4).toString(16))};function ft(s){return typeof s=="object"&&s!==null&&("name"in s&&s.name==="AbortError"||"message"in s&&String(s.message).includes("FetchRequestCanceledException"))}const mt=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null){try{if(Object.prototype.toString.call(s)==="[object Error]"){const 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)};class w extends Error{}class D extends w{constructor(e,t,n,r){super(`${D.makeMessage(e,t,n)}`),this.status=e,this.headers=r,this.requestID=r==null?void 0:r.get("x-request-id"),this.error=t;const o=t;this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(e,t,n){const r=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,n,r){if(!e||!r)return new Ye({message:n,cause:mt(t)});const o=t==null?void 0:t.error;return e===400?new vs(e,o,n,r):e===401?new bs(e,o,n,r):e===403?new xs(e,o,n,r):e===404?new Ss(e,o,n,r):e===409?new $s(e,o,n,r):e===422?new As(e,o,n,r):e===429?new Is(e,o,n,r):e>=500?new Os(e,o,n,r):new D(e,o,n,r)}}class H extends D{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ye extends D{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class It extends Ye{constructor({message:e}={}){super({message:e??"Request timed out."})}}class vs extends D{}class bs extends D{}class xs extends D{}class Ss extends D{}class $s extends D{}class As extends D{}class Is extends D{}class Os extends D{}class Rs extends w{constructor(){super("Could not parse response content as the length limit was reached")}}class ks extends w{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}const Xn=/^[a-z][a-z0-9+.-]*:/i,Hn=s=>Xn.test(s);function Jn(s){return typeof s!="object"?{}:s??{}}function Kn(s){if(!s)return!0;for(const e in s)return!1;return!0}function Vn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function it(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}const zn=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new w(`${s} must be an integer`);if(e<0)throw new w(`${s} must be a positive integer`);return e},Gn=s=>{try{return JSON.parse(s)}catch{return}},Ie=s=>new Promise(e=>setTimeout(e,s)),He={off:0,error:200,warn:300,info:400,debug:500},zt=(s,e,t)=>{if(s){if(Vn(He,s))return s;q(t).warn(`${e} was set to ${JSON.stringify(s)}, expected one of ${JSON.stringify(Object.keys(He))}`)}};function fe(){}function Ee(s,e,t){return!e||He[s]>He[t]?fe:e[s].bind(e)}const Qn={error:fe,warn:fe,info:fe,debug:fe};let Gt=new WeakMap;function q(s){const e=s.logger,t=s.logLevel??"off";if(!e)return Qn;const n=Gt.get(e);if(n&&n[0]===t)return n[1];const r={error:Ee("error",e,t),warn:Ee("warn",e,t),info:Ee("info",e,t),debug:Ee("debug",e,t)};return Gt.set(e,[t,r]),r}const se=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),ce="5.0.1",Yn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Zn(){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"}const er=()=>{var s;const e=Zn();if(e==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":Yt(Deno.build.os),"X-Stainless-Arch":Qt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((s=Deno.version)==null?void 0:s.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(e==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":Yt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Qt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=tr();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.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 tr(){if(typeof navigator>"u"||!navigator)return null;const 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(const{key:e,pattern:t}of s){const n=t.exec(navigator.userAgent);if(n){const r=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${r}.${o}.${i}`}}}return null}const Qt=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Yt=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");let Zt;const sr=()=>Zt??(Zt=er());function nr(){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 Es(...s){const 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 Ps(s){let e=Symbol.asyncIterator in s?s[Symbol.asyncIterator]():s[Symbol.iterator]();return Es({start(){},async pull(t){const{done:n,value:r}=await e.next();n?t.close():t.enqueue(r)},async cancel(){var t;await((t=e.return)==null?void 0:t.call(e))}})}function Cs(s){if(s[Symbol.asyncIterator])return s;const e=s.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function rr(s){var e,t;if(s===null||typeof s!="object")return;if(s[Symbol.asyncIterator]){await((t=(e=s[Symbol.asyncIterator]()).return)==null?void 0:t.call(e));return}const n=s.getReader(),r=n.cancel();n.releaseLock(),await r}const or=({headers:s,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),gt="RFC3986",yt={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:s=>String(s)},ir="RFC1738",ar=Array.isArray,V=(()=>{const s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})(),at=1024,lr=(s,e,t,n,r)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=at){const c=o.length>=at?o.slice(l,l+at):o,d=[];for(let m=0;m<c.length;++m){let u=c.charCodeAt(m);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||r===ir&&(u===40||u===41)){d[d.length]=c.charAt(m);continue}if(u<128){d[d.length]=V[u];continue}if(u<2048){d[d.length]=V[192|u>>6]+V[128|u&63];continue}if(u<55296||u>=57344){d[d.length]=V[224|u>>12]+V[128|u>>6&63]+V[128|u&63];continue}m+=1,u=65536+((u&1023)<<10|c.charCodeAt(m)&1023),d[d.length]=V[240|u>>18]+V[128|u>>12&63]+V[128|u>>6&63]+V[128|u&63]}i+=d.join("")}return i};function cr(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function es(s,e){if(ar(s)){const t=[];for(let n=0;n<s.length;n+=1)t.push(e(s[n]));return t}return e(s)}const ur=Object.prototype.hasOwnProperty,Ts={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},z=Array.isArray,dr=Array.prototype.push,Ns=function(s,e){dr.apply(s,z(e)?e:[e])},hr=Date.prototype.toISOString,j={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:lr,encodeValuesOnly:!1,format:gt,formatter:yt[gt],indices:!1,serializeDate(s){return hr.call(s)},skipNulls:!1,strictNullHandling:!1};function pr(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}const lt={};function js(s,e,t,n,r,o,i,l,c,d,m,u,g,S,p,$,b,E){let f=s,_=E,A=0,k=!1;for(;(_=_.get(lt))!==void 0&&!k;){const I=_.get(s);if(A+=1,typeof I<"u"){if(I===A)throw new RangeError("Cyclic object value");k=!0}typeof _.get(lt)>"u"&&(A=0)}if(typeof d=="function"?f=d(e,f):f instanceof Date?f=g==null?void 0:g(f):t==="comma"&&z(f)&&(f=es(f,function(I){return I instanceof Date?g==null?void 0:g(I):I})),f===null){if(o)return c&&!$?c(e,j.encoder,b,"key",S):e;f=""}if(pr(f)||cr(f)){if(c){const I=$?e:c(e,j.encoder,b,"key",S);return[(p==null?void 0:p(I))+"="+(p==null?void 0:p(c(f,j.encoder,b,"value",S)))]}return[(p==null?void 0:p(e))+"="+(p==null?void 0:p(String(f)))]}const R=[];if(typeof f>"u")return R;let T;if(t==="comma"&&z(f))$&&c&&(f=es(f,c)),T=[{value:f.length>0?f.join(",")||null:void 0}];else if(z(d))T=d;else{const I=Object.keys(f);T=m?I.sort(m):I}const P=l?String(e).replace(/\./g,"%2E"):String(e),J=n&&z(f)&&f.length===1?P+"[]":P;if(r&&z(f)&&f.length===0)return J+"[]";for(let I=0;I<T.length;++I){const X=T[I],Kt=typeof X=="object"&&typeof X.value<"u"?X.value:f[X];if(i&&Kt===null)continue;const ot=u&&l?X.replace(/\./g,"%2E"):X,Bn=z(f)?typeof t=="function"?t(J,ot):J:J+(u?"."+ot:"["+ot+"]");E.set(s,A);const Vt=new WeakMap;Vt.set(lt,E),Ns(R,js(Kt,Bn,t,n,r,o,i,l,t==="comma"&&$&&z(f)?null:c,d,m,u,g,S,p,$,b,Vt))}return R}function fr(s=j){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.");const e=s.charset||j.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=gt;if(typeof s.format<"u"){if(!ur.call(yt,s.format))throw new TypeError("Unknown format option provided.");t=s.format}const n=yt[t];let r=j.filter;(typeof s.filter=="function"||z(s.filter))&&(r=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Ts?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=j.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:j.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:j.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:j.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:j.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?j.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:j.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:j.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:j.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:j.encodeValuesOnly,filter:r,format:t,formatter:n,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:j.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:j.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:j.strictNullHandling}}function mr(s,e={}){let t=s;const n=fr(e);let r,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):z(n.filter)&&(o=n.filter,r=o);const i=[];if(typeof t!="object"||t===null)return"";const l=Ts[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;r||(r=Object.keys(t)),n.sort&&r.sort(n.sort);const d=new WeakMap;for(let g=0;g<r.length;++g){const S=r[g];n.skipNulls&&t[S]===null||Ns(i,js(t[S],S,l,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}const m=i.join(n.delimiter);let u=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),m.length>0?u+m:""}function gr(s){let e=0;for(const r of s)e+=r.length;const t=new Uint8Array(e);let n=0;for(const r of s)t.set(r,n),n+=r.length;return t}let ts;function Ot(s){let e;return(ts??(e=new globalThis.TextEncoder,ts=e.encode.bind(e)))(s)}let ss;function ns(s){let e;return(ss??(e=new globalThis.TextDecoder,ss=e.decode.bind(e)))(s)}var U,W;class Ze{constructor(){U.set(this,void 0),W.set(this,void 0),v(this,U,new Uint8Array),v(this,W,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Ot(e):e;v(this,U,gr([a(this,U,"f"),t]));const n=[];let r;for(;(r=yr(a(this,U,"f"),a(this,W,"f")))!=null;){if(r.carriage&&a(this,W,"f")==null){v(this,W,r.index);continue}if(a(this,W,"f")!=null&&(r.index!==a(this,W,"f")+1||r.carriage)){n.push(ns(a(this,U,"f").subarray(0,a(this,W,"f")-1))),v(this,U,a(this,U,"f").subarray(a(this,W,"f"))),v(this,W,null);continue}const o=a(this,W,"f")!==null?r.preceding-1:r.preceding,i=ns(a(this,U,"f").subarray(0,o));n.push(i),v(this,U,a(this,U,"f").subarray(r.index)),v(this,W,null)}return n}flush(){return a(this,U,"f").length?this.decode(`
`):[]}}U=new WeakMap,W=new WeakMap;Ze.NEWLINE_CHARS=new Set([`
`,"\r"]);Ze.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function yr(s,e){for(let t=e??0;t<s.length;t++){if(s[t]===10)return{preceding:t,index:t+1,carriage:!1};if(s[t]===13)return{preceding:t,index:t+1,carriage:!0}}return null}function wr(s){for(let e=0;e<s.length-1;e++){if(s[e]===10&&s[e+1]===10||s[e]===13&&s[e+1]===13)return e+2;if(s[e]===13&&s[e+1]===10&&e+3<s.length&&s[e+2]===13&&s[e+3]===10)return e+4}return-1}class Q{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*r(){if(n)throw new w("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(const i of _r(e,t))if(!o){if(i.data.startsWith("[DONE]")){o=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let l;try{l=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(l&&l.error)throw new D(void 0,l.error,void 0,e.headers);yield l}else{let l;try{l=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(i.event=="error")throw new D(void 0,l.error,l.message,void 0);yield{event:i.event,data:l}}}o=!0}catch(i){if(ft(i))return;throw i}finally{o||t.abort()}}return new Q(r,t)}static fromReadableStream(e,t){let n=!1;async function*r(){const i=new Ze,l=Cs(e);for await(const c of l)for(const d of i.decode(c))yield d;for(const c of i.flush())yield c}async function*o(){if(n)throw new w("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(const l of r())i||l&&(yield JSON.parse(l));i=!0}catch(l){if(ft(l))return;throw l}finally{i||t.abort()}}return new Q(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),r=o=>({next:()=>{if(o.length===0){const i=n.next();e.push(i),t.push(i)}return o.shift()}});return[new Q(()=>r(e),this.controller),new Q(()=>r(t),this.controller)]}toReadableStream(){const e=this;let t;return Es({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{const{value:r,done:o}=await t.next();if(o)return n.close();const i=Ot(JSON.stringify(r)+`
`);n.enqueue(i)}catch(r){n.error(r)}},async cancel(){var n;await((n=t.return)==null?void 0:n.call(t))}})}}async function*_r(s,e){if(!s.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new w("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 w("Attempted to iterate over a response with no body");const t=new br,n=new Ze,r=Cs(s.body);for await(const o of vr(r))for(const i of n.decode(o)){const l=t.decode(i);l&&(yield l)}for(const o of n.flush()){const i=t.decode(o);i&&(yield i)}}async function*vr(s){let e=new Uint8Array;for await(const t of s){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?Ot(t):t;let r=new Uint8Array(e.length+n.length);r.set(e),r.set(n,e.length),e=r;let o;for(;(o=wr(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}class br{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,r]=xr(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function xr(s,e){const t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}async function Ls(s,e){const{response:t,requestLogID:n,retryOfRequestLogID:r,startTime:o}=e,i=await(async()=>{var l;if(e.options.stream)return q(s).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Q.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const c=t.headers.get("content-type"),d=(l=c==null?void 0:c.split(";")[0])==null?void 0:l.trim();if(d!=null&&d.includes("application/json")||d!=null&&d.endsWith("+json")){const m=await t.json();return Ms(m,t)}return await t.text()})();return q(s).debug(`[${n}] response parsed`,se({retryOfRequestLogID:r,url:t.url,status:t.status,body:i,durationMs:Date.now()-o})),i}function Ms(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var me;class et extends Promise{constructor(e,t,n=Ls){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=n,me.set(this,void 0),v(this,me,e)}_thenUnwrap(e){return new et(a(this,me,"f"),this.responsePromise,async(t,n)=>Ms(e(await this.parseResponse(t,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(a(this,me,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}me=new WeakMap;var Pe;class Ds{constructor(e,t,n,r){Pe.set(this,void 0),v(this,Pe,e),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new w("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await a(this,Pe,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Pe=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Sr extends et{constructor(e,t,n){super(e,t,async(r,o)=>new n(r,o.response,await Ls(r,o),o.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class tt extends Ds{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class C extends Ds{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var e;const t=this.getPaginatedItems(),n=(e=t[t.length-1])==null?void 0:e.id;return n?{...this.options,query:{...Jn(this.options.query),after:n}}:null}}const qs=()=>{var s;if(typeof File>"u"){const{process:e}=globalThis,t=typeof((s=e==null?void 0:e.versions)==null?void 0:s.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function xe(s,e,t){return qs(),new File(s,e??"unknown_file",t)}function Me(s){return(typeof s=="object"&&s!==null&&("name"in s&&s.name&&String(s.name)||"url"in s&&s.url&&String(s.url)||"filename"in s&&s.filename&&String(s.filename)||"path"in s&&s.path&&String(s.path))||"").split(/[\\/]/).pop()||void 0}const Bs=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",ie=async(s,e)=>({...s,body:await Ar(s.body,e)}),rs=new WeakMap;function $r(s){const e=typeof s=="function"?s:s.fetch,t=rs.get(e);if(t)return t;const n=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new r(o).text()}catch{return!0}})();return rs.set(e,n),n}const Ar=async(s,e)=>{if(!await $r(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(s||{}).map(([n,r])=>wt(t,n,r))),t},Ir=s=>s instanceof Blob&&"name"in s,wt=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(t instanceof Response)s.append(e,xe([await t.blob()],Me(t)));else if(Bs(t))s.append(e,xe([await new Response(Ps(t)).blob()],Me(t)));else if(Ir(t))s.append(e,t,Me(t));else if(Array.isArray(t))await Promise.all(t.map(n=>wt(s,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,r])=>wt(s,`${e}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},Us=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",Or=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Us(s),Rr=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function";async function kr(s,e,t){if(qs(),s=await s,Or(s))return s instanceof File?s:xe([await s.arrayBuffer()],s.name);if(Rr(s)){const r=await s.blob();return e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()),xe(await _t(r),e,t)}const n=await _t(s);if(e||(e=Me(s)),!(t!=null&&t.type)){const r=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof r=="string"&&(t={...t,type:r})}return xe(n,e,t)}async function _t(s){var e;let t=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)t.push(s);else if(Us(s))t.push(s instanceof Blob?s:await s.arrayBuffer());else if(Bs(s))for await(const n of s)t.push(...await _t(n));else{const n=(e=s==null?void 0:s.constructor)==null?void 0:e.name;throw new Error(`Unexpected data type: ${typeof s}${n?`; constructor: ${n}`:""}${Er(s)}`)}return t}function Er(s){return typeof s!="object"||s===null?"":`; props: [${Object.getOwnPropertyNames(s).map(e=>`"${e}"`).join(", ")}]`}class x{constructor(e){this._client=e}}function Ws(s){return s.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Pr=(s=Ws)=>function(e,...t){if(e.length===1)return e[0];let n=!1;const r=e.reduce((d,m,u)=>(/[?#]/.test(m)&&(n=!0),d+m+(u===t.length?"":(n?encodeURIComponent:s)(String(t[u])))),""),o=r.split(/[?#]/,1)[0],i=[],l=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let c;for(;(c=l.exec(o))!==null;)i.push({start:c.index,length:c[0].length});if(i.length>0){let d=0;const m=i.reduce((u,g)=>{const S=" ".repeat(g.start-d),p="^".repeat(g.length);return d=g.start+g.length,u+S+p},"");throw new w(`Path parameters result in path with invalid segments:
${r}
${m}`)}return r},h=Pr(Ws);let Fs=class extends x{list(s,e={},t){return this._client.getAPIList(h`/chat/completions/${s}/messages`,C,{query:e,...t})}};function Cr(s){return typeof s.parse=="function"}const Je=s=>(s==null?void 0:s.role)==="assistant",Xs=s=>(s==null?void 0:s.role)==="tool";var vt,De,qe,ge,ye,Be,we,Z,_e,Ke,Ve,ue,Hs;class Rt{constructor(){vt.add(this),this.controller=new AbortController,De.set(this,void 0),qe.set(this,()=>{}),ge.set(this,()=>{}),ye.set(this,void 0),Be.set(this,()=>{}),we.set(this,()=>{}),Z.set(this,{}),_e.set(this,!1),Ke.set(this,!1),Ve.set(this,!1),ue.set(this,!1),v(this,De,new Promise((e,t)=>{v(this,qe,e,"f"),v(this,ge,t,"f")})),v(this,ye,new Promise((e,t)=>{v(this,Be,e,"f"),v(this,we,t,"f")})),a(this,De,"f").catch(()=>{}),a(this,ye,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},a(this,vt,"m",Hs).bind(this))},0)}_connected(){this.ended||(a(this,qe,"f").call(this),this._emit("connect"))}get ended(){return a(this,_e,"f")}get errored(){return a(this,Ke,"f")}get aborted(){return a(this,Ve,"f")}abort(){this.controller.abort()}on(e,t){return(a(this,Z,"f")[e]||(a(this,Z,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=a(this,Z,"f")[e];if(!n)return this;const r=n.findIndex(o=>o.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(a(this,Z,"f")[e]||(a(this,Z,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{v(this,ue,!0),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){v(this,ue,!0),await a(this,ye,"f")}_emit(e,...t){if(a(this,_e,"f"))return;e==="end"&&(v(this,_e,!0),a(this,Be,"f").call(this));const n=a(this,Z,"f")[e];if(n&&(a(this,Z,"f")[e]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!a(this,ue,"f")&&!(n!=null&&n.length)&&Promise.reject(r),a(this,ge,"f").call(this,r),a(this,we,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!a(this,ue,"f")&&!(n!=null&&n.length)&&Promise.reject(r),a(this,ge,"f").call(this,r),a(this,we,"f").call(this,r),this._emit("end")}}_emitFinal(){}}De=new WeakMap,qe=new WeakMap,ge=new WeakMap,ye=new WeakMap,Be=new WeakMap,we=new WeakMap,Z=new WeakMap,_e=new WeakMap,Ke=new WeakMap,Ve=new WeakMap,ue=new WeakMap,vt=new WeakSet,Hs=function(s){if(v(this,Ke,!0),s instanceof Error&&s.name==="AbortError"&&(s=new H),s instanceof H)return v(this,Ve,!0),this._emit("abort",s);if(s instanceof w)return this._emit("error",s);if(s instanceof Error){const e=new w(s.message);return e.cause=s,this._emit("error",e)}return this._emit("error",new w(String(s)))};function kt(s){return(s==null?void 0:s.$brand)==="auto-parseable-response-format"}function Oe(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function Tr(s,e){return!e||!Js(e)?{...s,choices:s.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Et(s,e)}function Et(s,e){const t=s.choices.map(n=>{var r;if(n.finish_reason==="length")throw new Rs;if(n.finish_reason==="content_filter")throw new ks;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((r=n.message.tool_calls)==null?void 0:r.map(o=>jr(e,o)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Nr(e,n.message.content):null}}});return{...s,choices:t}}function Nr(s,e){var t,n;return((t=s.response_format)==null?void 0:t.type)!=="json_schema"?null:((n=s.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function jr(s,e){var t;const n=(t=s.tools)==null?void 0:t.find(r=>{var o;return((o=r.function)==null?void 0:o.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Oe(n)?n.$parseRaw(e.function.arguments):n!=null&&n.function.strict?JSON.parse(e.function.arguments):null}}}function Lr(s,e){var t;if(!s)return!1;const n=(t=s.tools)==null?void 0:t.find(r=>{var o;return((o=r.function)==null?void 0:o.name)===e.function.name});return Oe(n)||(n==null?void 0:n.function.strict)||!1}function Js(s){var e;return kt(s.response_format)?!0:((e=s.tools)==null?void 0:e.some(t=>Oe(t)||t.type==="function"&&t.function.strict===!0))??!1}function Mr(s){for(const e of s??[]){if(e.type!=="function")throw new w(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new w(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var B,bt,ze,xt,St,$t,Ks,Vs;const Dr=10;class zs extends Rt{constructor(){super(...arguments),B.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var t;this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=(t=e.choices[0])==null?void 0:t.message;return n&&this._addMessage(n),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),Xs(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Je(e)&&e.tool_calls)for(const n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new w("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),a(this,B,"m",bt).call(this)}async finalMessage(){return await this.done(),a(this,B,"m",ze).call(this)}async finalFunctionToolCall(){return await this.done(),a(this,B,"m",xt).call(this)}async finalFunctionToolCallResult(){return await this.done(),a(this,B,"m",St).call(this)}async totalUsage(){return await this.done(),a(this,B,"m",$t).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=a(this,B,"m",ze).call(this);t&&this._emit("finalMessage",t);const n=a(this,B,"m",bt).call(this);n&&this._emit("finalContent",n);const r=a(this,B,"m",xt).call(this);r&&this._emit("finalFunctionToolCall",r);const o=a(this,B,"m",St).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",a(this,B,"m",$t).call(this))}async _createChatCompletion(e,t,n){const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),a(this,B,"m",Ks).call(this,t);const o=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Et(o,t))}async _runChatCompletion(e,t,n){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){var r,o,i;const l="tool",{tool_choice:c="auto",stream:d,...m}=t,u=typeof c!="string"&&((r=c==null?void 0:c.function)==null?void 0:r.name),{maxChatCompletions:g=Dr}=n||{},S=t.tools.map(b=>{if(Oe(b)){if(!b.$callback)throw new w("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:b.$callback,name:b.function.name,description:b.function.description||"",parameters:b.function.parameters,parse:b.$parseRaw,strict:!0}}}return b}),p={};for(const b of S)b.type==="function"&&(p[b.function.name||b.function.function.name]=b.function);const $="tools"in t?S.map(b=>b.type==="function"?{type:"function",function:{name:b.function.name||b.function.function.name,parameters:b.function.parameters,description:b.function.description,strict:b.function.strict}}:b):void 0;for(const b of t.messages)this._addMessage(b,!1);for(let b=0;b<g;++b){const E=(o=(await this._createChatCompletion(e,{...m,tool_choice:c,tools:$,messages:[...this.messages]},n)).choices[0])==null?void 0:o.message;if(!E)throw new w("missing message in ChatCompletion response");if(!((i=E.tool_calls)!=null&&i.length))return;for(const f of E.tool_calls){if(f.type!=="function")continue;const _=f.id,{name:A,arguments:k}=f.function,R=p[A];if(R){if(u&&u!==A){const I=`Invalid tool_call: ${JSON.stringify(A)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:l,tool_call_id:_,content:I});continue}}else{const I=`Invalid tool_call: ${JSON.stringify(A)}. Available options are: ${Object.keys(p).map(X=>JSON.stringify(X)).join(", ")}. Please try again`;this._addMessage({role:l,tool_call_id:_,content:I});continue}let T;try{T=Cr(R)?await R.parse(k):k}catch(I){const X=I instanceof Error?I.message:String(I);this._addMessage({role:l,tool_call_id:_,content:X});continue}const P=await R.function(T,this),J=a(this,B,"m",Vs).call(this,P);if(this._addMessage({role:l,tool_call_id:_,content:J}),u)return}}}}B=new WeakSet,bt=function(){return a(this,B,"m",ze).call(this).content??null},ze=function(){let s=this.messages.length;for(;s-- >0;){const e=this.messages[s];if(Je(e))return{...e,content:e.content??null,refusal:e.refusal??null}}throw new w("stream ended without producing a ChatCompletionMessage with role=assistant")},xt=function(){var s,e;for(let t=this.messages.length-1;t>=0;t--){const n=this.messages[t];if(Je(n)&&(s=n==null?void 0:n.tool_calls)!=null&&s.length)return(e=n.tool_calls.at(-1))==null?void 0:e.function}},St=function(){for(let s=this.messages.length-1;s>=0;s--){const e=this.messages[s];if(Xs(e)&&e.content!=null&&typeof e.content=="string"&&this.messages.some(t=>{var n;return t.role==="assistant"&&((n=t.tool_calls)==null?void 0:n.some(r=>r.type==="function"&&r.id===e.tool_call_id))}))return e.content}},$t=function(){const s={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:e}of this._chatCompletions)e&&(s.completion_tokens+=e.completion_tokens,s.prompt_tokens+=e.prompt_tokens,s.total_tokens+=e.total_tokens);return s},Ks=function(s){if(s.n!=null&&s.n>1)throw new w("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Vs=function(s){return typeof s=="string"?s:s===void 0?"undefined":JSON.stringify(s)};class Pt extends zs{static runTools(e,t,n){const r=new Pt,o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,o)),r}_addMessage(e,t=!0){super._addMessage(e,t),Je(e)&&e.content&&this._emit("content",e.content)}}const Gs=1,Qs=2,Ys=4,Zs=8,en=16,tn=32,sn=64,nn=128,rn=256,on=nn|rn,an=en|tn|on|sn,ln=Gs|Qs|an,cn=Ys|Zs,qr=ln|cn,L={STR:Gs,NUM:Qs,ARR:Ys,OBJ:Zs,NULL:en,BOOL:tn,NAN:sn,INFINITY:nn,MINUS_INFINITY:rn,INF:on,SPECIAL:an,ATOM:ln,COLLECTION:cn,ALL:qr};class Br extends Error{}class Ur extends Error{}function Wr(s,e=L.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return Fr(s.trim(),e)}const Fr=(s,e)=>{const t=s.length;let n=0;const r=g=>{throw new Br(`${g} at position ${n}`)},o=g=>{throw new Ur(`${g} at position ${n}`)},i=()=>(u(),n>=t&&r("Unexpected end of input"),s[n]==='"'?l():s[n]==="{"?c():s[n]==="["?d():s.substring(n,n+4)==="null"||L.NULL&e&&t-n<4&&"null".startsWith(s.substring(n))?(n+=4,null):s.substring(n,n+4)==="true"||L.BOOL&e&&t-n<4&&"true".startsWith(s.substring(n))?(n+=4,!0):s.substring(n,n+5)==="false"||L.BOOL&e&&t-n<5&&"false".startsWith(s.substring(n))?(n+=5,!1):s.substring(n,n+8)==="Infinity"||L.INFINITY&e&&t-n<8&&"Infinity".startsWith(s.substring(n))?(n+=8,1/0):s.substring(n,n+9)==="-Infinity"||L.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(s.substring(n))?(n+=9,-1/0):s.substring(n,n+3)==="NaN"||L.NAN&e&&t-n<3&&"NaN".startsWith(s.substring(n))?(n+=3,NaN):m()),l=()=>{const g=n;let S=!1;for(n++;n<t&&(s[n]!=='"'||S&&s[n-1]==="\\");)S=s[n]==="\\"?!S:!1,n++;if(s.charAt(n)=='"')try{return JSON.parse(s.substring(g,++n-Number(S)))}catch(p){o(String(p))}else if(L.STR&e)try{return JSON.parse(s.substring(g,n-Number(S))+'"')}catch{return JSON.parse(s.substring(g,s.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,u();const g={};try{for(;s[n]!=="}";){if(u(),n>=t&&L.OBJ&e)return g;const S=l();u(),n++;try{const p=i();Object.defineProperty(g,S,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(L.OBJ&e)return g;throw p}u(),s[n]===","&&n++}}catch{if(L.OBJ&e)return g;r("Expected '}' at end of object")}return n++,g},d=()=>{n++;const g=[];try{for(;s[n]!=="]";)g.push(i()),u(),s[n]===","&&n++}catch{if(L.ARR&e)return g;r("Expected ']' at end of array")}return n++,g},m=()=>{if(n===0){s==="-"&&L.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s)}catch(S){if(L.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(S))}}const g=n;for(s[n]==="-"&&n++;s[n]&&!",]}".includes(s[n]);)n++;n==t&&!(L.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(s.substring(g,n))}catch{s.substring(g,n)==="-"&&L.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(s.substring(g,s.lastIndexOf("e")))}catch(S){o(String(S))}}},u=()=>{for(;n<t&&`
\r `.includes(s[n]);)n++};return i()},os=s=>Wr(s,L.ALL^L.NUM);var N,Y,ae,ee,ct,Ce,ut,dt,ht,Te,pt,is;class Ae extends zs{constructor(e){super(),N.add(this),Y.set(this,void 0),ae.set(this,void 0),ee.set(this,void 0),v(this,Y,e),v(this,ae,[])}get currentChatCompletionSnapshot(){return a(this,ee,"f")}static fromReadableStream(e){const t=new Ae(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const r=new Ae(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,n){var r;super._createChatCompletion;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),a(this,N,"m",ct).call(this);const i=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of i)a(this,N,"m",ut).call(this,l);if((r=i.controller.signal)!=null&&r.aborted)throw new H;return this._addChatCompletion(a(this,N,"m",Te).call(this))}async _fromReadableStream(e,t){var n;const r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),a(this,N,"m",ct).call(this),this._connected();const o=Q.fromReadableStream(e,this.controller);let i;for await(const l of o)i&&i!==l.id&&this._addChatCompletion(a(this,N,"m",Te).call(this)),a(this,N,"m",ut).call(this,l),i=l.id;if((n=o.controller.signal)!=null&&n.aborted)throw new H;return this._addChatCompletion(a(this,N,"m",Te).call(this))}[(Y=new WeakMap,ae=new WeakMap,ee=new WeakMap,N=new WeakSet,ct=function(){this.ended||v(this,ee,void 0)},Ce=function(e){let t=a(this,ae,"f")[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},a(this,ae,"f")[e.index]=t,t)},ut=function(e){var t,n,r,o,i,l,c,d,m,u,g,S,p,$,b;if(this.ended)return;const E=a(this,N,"m",is).call(this,e);this._emit("chunk",e,E);for(const f of e.choices){const _=E.choices[f.index];f.delta.content!=null&&((t=_.message)==null?void 0:t.role)==="assistant"&&(n=_.message)!=null&&n.content&&(this._emit("content",f.delta.content,_.message.content),this._emit("content.delta",{delta:f.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),f.delta.refusal!=null&&((r=_.message)==null?void 0:r.role)==="assistant"&&(o=_.message)!=null&&o.refusal&&this._emit("refusal.delta",{delta:f.delta.refusal,snapshot:_.message.refusal}),((i=f.logprobs)==null?void 0:i.content)!=null&&((l=_.message)==null?void 0:l.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(c=f.logprobs)==null?void 0:c.content,snapshot:((d=_.logprobs)==null?void 0:d.content)??[]}),((m=f.logprobs)==null?void 0:m.refusal)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(g=f.logprobs)==null?void 0:g.refusal,snapshot:((S=_.logprobs)==null?void 0:S.refusal)??[]});const A=a(this,N,"m",Ce).call(this,_);_.finish_reason&&(a(this,N,"m",ht).call(this,_),A.current_tool_call_index!=null&&a(this,N,"m",dt).call(this,_,A.current_tool_call_index));for(const k of f.delta.tool_calls??[])A.current_tool_call_index!==k.index&&(a(this,N,"m",ht).call(this,_),A.current_tool_call_index!=null&&a(this,N,"m",dt).call(this,_,A.current_tool_call_index)),A.current_tool_call_index=k.index;for(const k of f.delta.tool_calls??[]){const R=(p=_.message.tool_calls)==null?void 0:p[k.index];R!=null&&R.type&&((R==null?void 0:R.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:($=R.function)==null?void 0:$.name,index:k.index,arguments:R.function.arguments,parsed_arguments:R.function.parsed_arguments,arguments_delta:((b=k.function)==null?void 0:b.arguments)??""}):R==null||R.type)}}},dt=function(e,t){var n,r,o;if(a(this,N,"m",Ce).call(this,e).done_tool_calls.has(t))return;const i=(n=e.message.tool_calls)==null?void 0:n[t];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){const l=(o=(r=a(this,Y,"f"))==null?void 0:r.tools)==null?void 0:o.find(c=>c.type==="function"&&c.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:t,arguments:i.function.arguments,parsed_arguments:Oe(l)?l.$parseRaw(i.function.arguments):l!=null&&l.function.strict?JSON.parse(i.function.arguments):null})}else i.type},ht=function(e){var t,n;const r=a(this,N,"m",Ce).call(this,e);if(e.message.content&&!r.content_done){r.content_done=!0;const o=a(this,N,"m",pt).call(this);this._emit("content.done",{content:e.message.content,parsed:o?o.$parseRaw(e.message.content):null})}e.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),(t=e.logprobs)!=null&&t.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),(n=e.logprobs)!=null&&n.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},Te=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");const e=a(this,ee,"f");if(!e)throw new w("request ended without sending any chunks");return v(this,ee,void 0),v(this,ae,[]),Xr(e,a(this,Y,"f"))},pt=function(){var e;const t=(e=a(this,Y,"f"))==null?void 0:e.response_format;return kt(t)?t:null},is=function(e){var t,n,r,o;let i=a(this,ee,"f");const{choices:l,...c}=e;i?Object.assign(i,c):i=v(this,ee,{...c,choices:[]});for(const{delta:d,finish_reason:m,index:u,logprobs:g=null,...S}of e.choices){let p=i.choices[u];if(p||(p=i.choices[u]={finish_reason:m,index:u,message:{},logprobs:g,...S}),g)if(!p.logprobs)p.logprobs=Object.assign({},g);else{const{content:k,refusal:R,...T}=g;Object.assign(p.logprobs,T),k&&((t=p.logprobs).content??(t.content=[]),p.logprobs.content.push(...k)),R&&((n=p.logprobs).refusal??(n.refusal=[]),p.logprobs.refusal.push(...R))}if(m&&(p.finish_reason=m,a(this,Y,"f")&&Js(a(this,Y,"f")))){if(m==="length")throw new Rs;if(m==="content_filter")throw new ks}if(Object.assign(p,S),!d)continue;const{content:$,refusal:b,function_call:E,role:f,tool_calls:_,...A}=d;if(Object.assign(p.message,A),b&&(p.message.refusal=(p.message.refusal||"")+b),f&&(p.message.role=f),E&&(p.message.function_call?(E.name&&(p.message.function_call.name=E.name),E.arguments&&((r=p.message.function_call).arguments??(r.arguments=""),p.message.function_call.arguments+=E.arguments)):p.message.function_call=E),$&&(p.message.content=(p.message.content||"")+$,!p.message.refusal&&a(this,N,"m",pt).call(this)&&(p.message.parsed=os(p.message.content))),_){p.message.tool_calls||(p.message.tool_calls=[]);for(const{index:k,id:R,type:T,function:P,...J}of _){const I=(o=p.message.tool_calls)[k]??(o[k]={});Object.assign(I,J),R&&(I.id=R),T&&(I.type=T),P&&(I.function??(I.function={name:P.name??"",arguments:""})),P!=null&&P.name&&(I.function.name=P.name),P!=null&&P.arguments&&(I.function.arguments+=P.arguments,Lr(a(this,Y,"f"),I)&&(I.function.parsed_arguments=os(I.function.arguments)))}}}return i},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",r=>{const o=t.shift();o?o.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const o of t)o.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const o of t)o.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((r,o)=>t.push({resolve:r,reject:o})).then(r=>r?{value:r,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Xr(s,e){const{id:t,choices:n,created:r,model:o,system_fingerprint:i,...l}=s,c={...l,id:t,choices:n.map(({message:d,finish_reason:m,index:u,logprobs:g,...S})=>{if(!m)throw new w(`missing finish_reason for choice ${u}`);const{content:p=null,function_call:$,tool_calls:b,...E}=d,f=d.role;if(!f)throw new w(`missing role for choice ${u}`);if($){const{arguments:_,name:A}=$;if(_==null)throw new w(`missing function_call.arguments for choice ${u}`);if(!A)throw new w(`missing function_call.name for choice ${u}`);return{...S,message:{content:p,function_call:{arguments:_,name:A},role:f,refusal:d.refusal??null},finish_reason:m,index:u,logprobs:g}}return b?{...S,index:u,finish_reason:m,logprobs:g,message:{...E,role:f,content:p,refusal:d.refusal??null,tool_calls:b.map((_,A)=>{const{function:k,type:R,id:T,...P}=_,{arguments:J,name:I,...X}=k||{};if(T==null)throw new w(`missing choices[${u}].tool_calls[${A}].id
${Ne(s)}`);if(R==null)throw new w(`missing choices[${u}].tool_calls[${A}].type
${Ne(s)}`);if(I==null)throw new w(`missing choices[${u}].tool_calls[${A}].function.name
${Ne(s)}`);if(J==null)throw new w(`missing choices[${u}].tool_calls[${A}].function.arguments
${Ne(s)}`);return{...P,id:T,type:R,function:{...X,name:I,arguments:J}}})}}:{...S,message:{...E,content:p,role:f,refusal:d.refusal??null},finish_reason:m,index:u,logprobs:g}}),created:r,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Tr(c,e)}function Ne(s){return JSON.stringify(s)}class Ge extends Ae{static fromReadableStream(e){const t=new Ge(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,n){const r=new Ge(t),o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,o)),r}}let Ct=class extends x{constructor(){super(...arguments),this.messages=new Fs(this._client)}create(s,e){return this._client.post("/chat/completions",{body:s,...e,stream:s.stream??!1})}retrieve(s,e){return this._client.get(h`/chat/completions/${s}`,e)}update(s,e,t){return this._client.post(h`/chat/completions/${s}`,{body:e,...t})}list(s={},e){return this._client.getAPIList("/chat/completions",C,{query:s,...e})}delete(s,e){return this._client.delete(h`/chat/completions/${s}`,e)}parse(s,e){return Mr(s.tools),this._client.chat.completions.create(s,{...e,headers:{...e==null?void 0:e.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(t=>Et(t,s))}runTools(s,e){return s.stream?Ge.runTools(this._client,s,e):Pt.runTools(this._client,s,e)}stream(s,e){return Ae.createChatCompletion(this._client,s,e)}};Ct.Messages=Fs;class Tt extends x{constructor(){super(...arguments),this.completions=new Ct(this._client)}}Tt.Completions=Ct;const un=Symbol("brand.privateNullableHeaders"),as=Array.isArray;function*Hr(s){if(!s)return;if(un in s){const{values:n,nulls:r}=s;yield*n.entries();for(const o of r)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 n of t){const r=n[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const o=as(n[1])?n[1]:[n[1]];let i=!1;for(const l of o)l!==void 0&&(e&&!i&&(i=!0,yield[r,null]),yield[r,l])}}const y=s=>{const e=new Headers,t=new Set;for(const n of s){const r=new Set;for(const[o,i]of Hr(n)){const l=o.toLowerCase();r.has(l)||(e.delete(o),r.add(l)),i===null?(e.delete(o),t.add(l)):(e.append(o,i),t.delete(l))}}return{[un]:!0,values:e,nulls:t}};class dn extends x{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:y([{Accept:"application/octet-stream"},t==null?void 0:t.headers]),__binaryResponse:!0})}}class hn extends x{create(e,t){return this._client.post("/audio/transcriptions",ie({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class pn extends x{create(e,t){return this._client.post("/audio/translations",ie({body:e,...t,__metadata:{model:e.model}},this._client))}}class Re extends x{constructor(){super(...arguments),this.transcriptions=new hn(this._client),this.translations=new pn(this._client),this.speech=new dn(this._client)}}Re.Transcriptions=hn;Re.Translations=pn;Re.Speech=dn;class fn extends x{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(h`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",C,{query:e,...t})}cancel(e,t){return this._client.post(h`/batches/${e}/cancel`,t)}}class mn extends x{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(h`/assistants/${e}`,{...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(h`/assistants/${e}`,{body:t,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},t){return this._client.getAPIList("/assistants",C,{query:e,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}delete(e,t){return this._client.delete(h`/assistants/${e}`,{...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}class gn extends x{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}class yn extends x{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}}class st extends x{constructor(){super(...arguments),this.sessions=new gn(this._client),this.transcriptionSessions=new yn(this._client)}}st.Sessions=gn;st.TranscriptionSessions=yn;class wn extends x{create(e,t,n){return this._client.post(h`/threads/${e}/messages`,{body:t,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,t,n){const{thread_id:r}=t;return this._client.get(h`/threads/${r}/messages/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,t,n){const{thread_id:r,...o}=t;return this._client.post(h`/threads/${r}/messages/${e}`,{body:o,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t={},n){return this._client.getAPIList(h`/threads/${e}/messages`,C,{query:t,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t,n){const{thread_id:r}=t;return this._client.delete(h`/threads/${r}/messages/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class _n extends x{retrieve(e,t,n){const{thread_id:r,run_id:o,...i}=t;return this._client.get(h`/threads/${r}/runs/${o}/steps/${e}`,{query:i,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t,n){const{thread_id:r,...o}=t;return this._client.getAPIList(h`/threads/${r}/runs/${e}/steps`,C,{query:o,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}const Jr=s=>{if(typeof Buffer<"u"){const e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(s),t=e.length,n=new Uint8Array(t);for(let r=0;r<t;r++)n[r]=e.charCodeAt(r);return Array.from(new Float32Array(n.buffer))}},pe=s=>{var e,t,n,r,o;if(typeof globalThis.process<"u")return((t=(e=globalThis.process.env)==null?void 0:e[s])==null?void 0:t.trim())??void 0;if(typeof globalThis.Deno<"u")return(o=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,s))==null?void 0:o.trim()};var M,re,At,G,Ue,K,oe,de,ne,Qe,F,We,Fe,Se,ve,be,ls,cs,us,ds,hs,ps,fs;class $e extends Rt{constructor(){super(...arguments),M.add(this),At.set(this,[]),G.set(this,{}),Ue.set(this,{}),K.set(this,void 0),oe.set(this,void 0),de.set(this,void 0),ne.set(this,void 0),Qe.set(this,void 0),F.set(this,void 0),We.set(this,void 0),Fe.set(this,void 0),Se.set(this,void 0)}[(At=new WeakMap,G=new WeakMap,Ue=new WeakMap,K=new WeakMap,oe=new WeakMap,de=new WeakMap,ne=new WeakMap,Qe=new WeakMap,F=new WeakMap,We=new WeakMap,Fe=new WeakMap,Se=new WeakMap,M=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",r=>{const o=t.shift();o?o.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const o of t)o.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const o of t)o.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((r,o)=>t.push({resolve:r,reject:o})).then(r=>r?{value:r,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new re;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var n;const r=t==null?void 0:t.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const o=Q.fromReadableStream(e,this.controller);for await(const i of o)a(this,M,"m",ve).call(this,i);if((n=o.controller.signal)!=null&&n.aborted)throw new H;return this._addRun(a(this,M,"m",be).call(this))}toReadableStream(){return new Q(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){const o=new re;return o._run(()=>o._runToolAssistantStream(e,t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,n,r){var o;const i=r==null?void 0:r.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const l={...n,stream:!0},c=await e.submitToolOutputs(t,l,{...r,signal:this.controller.signal});this._connected();for await(const d of c)a(this,M,"m",ve).call(this,d);if((o=c.controller.signal)!=null&&o.aborted)throw new H;return this._addRun(a(this,M,"m",be).call(this))}static createThreadAssistantStream(e,t,n){const r=new re;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,n,r){const o=new re;return o._run(()=>o._runAssistantStream(e,t,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return a(this,We,"f")}currentRun(){return a(this,Fe,"f")}currentMessageSnapshot(){return a(this,K,"f")}currentRunStepSnapshot(){return a(this,Se,"f")}async finalRunSteps(){return await this.done(),Object.values(a(this,G,"f"))}async finalMessages(){return await this.done(),Object.values(a(this,Ue,"f"))}async finalRun(){if(await this.done(),!a(this,oe,"f"))throw Error("Final run was not received.");return a(this,oe,"f")}async _createThreadAssistantStream(e,t,n){var r;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const i={...t,stream:!0},l=await e.createAndRun(i,{...n,signal:this.controller.signal});this._connected();for await(const c of l)a(this,M,"m",ve).call(this,c);if((r=l.controller.signal)!=null&&r.aborted)throw new H;return this._addRun(a(this,M,"m",be).call(this))}async _createAssistantStream(e,t,n,r){var o;const i=r==null?void 0:r.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const l={...n,stream:!0},c=await e.create(t,l,{...r,signal:this.controller.signal});this._connected();for await(const d of c)a(this,M,"m",ve).call(this,d);if((o=c.controller.signal)!=null&&o.aborted)throw new H;return this._addRun(a(this,M,"m",be).call(this))}static accumulateDelta(e,t){for(const[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let o=e[n];if(o==null){e[n]=r;continue}if(n==="index"||n==="type"){e[n]=r;continue}if(typeof o=="string"&&typeof r=="string")o+=r;else if(typeof o=="number"&&typeof r=="number")o+=r;else if(it(o)&&it(r))o=this.accumulateDelta(o,r);else if(Array.isArray(o)&&Array.isArray(r)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...r);continue}for(const i of r){if(!it(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const c=o[l];c==null?o.push(i):o[l]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}}re=$e,ve=function(s){if(!this.ended)switch(v(this,We,s),a(this,M,"m",us).call(this,s),s.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":a(this,M,"m",fs).call(this,s);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":a(this,M,"m",cs).call(this,s);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":a(this,M,"m",ls).call(this,s);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},be=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");if(!a(this,oe,"f"))throw Error("Final run has not been received");return a(this,oe,"f")},ls=function(s){const[e,t]=a(this,M,"m",hs).call(this,s,a(this,K,"f"));v(this,K,e),a(this,Ue,"f")[e.id]=e;for(const n of t){const r=e.content[n.index];(r==null?void 0:r.type)=="text"&&this._emit("textCreated",r.text)}switch(s.event){case"thread.message.created":this._emit("messageCreated",s.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",s.data.delta,e),s.data.delta.content)for(const n of s.data.delta.content){if(n.type=="text"&&n.text){let r=n.text,o=e.content[n.index];if(o&&o.type=="text")this._emit("textDelta",r,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=a(this,de,"f")){if(a(this,ne,"f"))switch(a(this,ne,"f").type){case"text":this._emit("textDone",a(this,ne,"f").text,a(this,K,"f"));break;case"image_file":this._emit("imageFileDone",a(this,ne,"f").image_file,a(this,K,"f"));break}v(this,de,n.index)}v(this,ne,e.content[n.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(a(this,de,"f")!==void 0){const n=s.data.content[a(this,de,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,a(this,K,"f"));break;case"text":this._emit("textDone",n.text,a(this,K,"f"));break}}a(this,K,"f")&&this._emit("messageDone",s.data),v(this,K,void 0)}},cs=function(s){const e=a(this,M,"m",ds).call(this,s);switch(v(this,Se,e),s.event){case"thread.run.step.created":this._emit("runStepCreated",s.data);break;case"thread.run.step.delta":const t=s.data.delta;if(t.step_details&&t.step_details.type=="tool_calls"&&t.step_details.tool_calls&&e.step_details.type=="tool_calls")for(const n of t.step_details.tool_calls)n.index==a(this,Qe,"f")?this._emit("toolCallDelta",n,e.step_details.tool_calls[n.index]):(a(this,F,"f")&&this._emit("toolCallDone",a(this,F,"f")),v(this,Qe,n.index),v(this,F,e.step_details.tool_calls[n.index]),a(this,F,"f")&&this._emit("toolCallCreated",a(this,F,"f")));this._emit("runStepDelta",s.data.delta,e);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":v(this,Se,void 0),s.data.step_details.type=="tool_calls"&&a(this,F,"f")&&(this._emit("toolCallDone",a(this,F,"f")),v(this,F,void 0)),this._emit("runStepDone",s.data,e);break}},us=function(s){a(this,At,"f").push(s),this._emit("event",s)},ds=function(s){switch(s.event){case"thread.run.step.created":return a(this,G,"f")[s.data.id]=s.data,s.data;case"thread.run.step.delta":let e=a(this,G,"f")[s.data.id];if(!e)throw Error("Received a RunStepDelta before creation of a snapshot");let t=s.data;if(t.delta){const n=re.accumulateDelta(e,t.delta);a(this,G,"f")[s.data.id]=n}return a(this,G,"f")[s.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":a(this,G,"f")[s.data.id]=s.data;break}if(a(this,G,"f")[s.data.id])return a(this,G,"f")[s.data.id];throw new Error("No snapshot available")},hs=function(s,e){let t=[];switch(s.event){case"thread.message.created":return[s.data,t];case"thread.message.delta":if(!e)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=s.data;if(n.delta.content)for(const r of n.delta.content)if(r.index in e.content){let o=e.content[r.index];e.content[r.index]=a(this,M,"m",ps).call(this,r,o)}else e.content[r.index]=r,t.push(r);return[e,t];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(e)return[e,t];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},ps=function(s,e){return re.accumulateDelta(e,s)},fs=function(s){switch(v(this,Fe,s.data),s.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":v(this,oe,s.data),a(this,F,"f")&&(this._emit("toolCallDone",a(this,F,"f")),v(this,F,void 0));break}};let Nt=class extends x{constructor(){super(...arguments),this.steps=new _n(this._client)}create(s,e,t){const{include:n,...r}=e;return this._client.post(h`/threads/${s}/runs`,{query:{include:n},body:r,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),stream:e.stream??!1})}retrieve(s,e,t){const{thread_id:n}=e;return this._client.get(h`/threads/${n}/runs/${s}`,{...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(s,e,t){const{thread_id:n,...r}=e;return this._client.post(h`/threads/${n}/runs/${s}`,{body:r,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}list(s,e={},t){return this._client.getAPIList(h`/threads/${s}/runs`,C,{query:e,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}cancel(s,e,t){const{thread_id:n}=e;return this._client.post(h`/threads/${n}/runs/${s}/cancel`,{...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}async createAndPoll(s,e,t){const n=await this.create(s,e,t);return await this.poll(n.id,{thread_id:s},t)}createAndStream(s,e,t){return $e.createAssistantStream(s,this._client.beta.threads.runs,e,t)}async poll(s,e,t){var n;const r=y([t==null?void 0:t.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((n=t==null?void 0:t.pollIntervalMs)==null?void 0:n.toString())??void 0}]);for(;;){const{data:o,response:i}=await this.retrieve(s,e,{...t,headers:{...t==null?void 0:t.headers,...r}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(t!=null&&t.pollIntervalMs)l=t.pollIntervalMs;else{const c=i.headers.get("openai-poll-after-ms");if(c){const d=parseInt(c);isNaN(d)||(l=d)}}await Ie(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(s,e,t){return $e.createAssistantStream(s,this._client.beta.threads.runs,e,t)}submitToolOutputs(s,e,t){const{thread_id:n,...r}=e;return this._client.post(h`/threads/${n}/runs/${s}/submit_tool_outputs`,{body:r,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),stream:e.stream??!1})}async submitToolOutputsAndPoll(s,e,t){const n=await this.submitToolOutputs(s,e,t);return await this.poll(n.id,e,t)}submitToolOutputsStream(s,e,t){return $e.createToolAssistantStream(s,this._client.beta.threads.runs,e,t)}};Nt.Steps=_n;class nt extends x{constructor(){super(...arguments),this.runs=new Nt(this._client),this.messages=new wn(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(h`/threads/${e}`,{...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(h`/threads/${e}`,{body:t,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t){return this._client.delete(h`/threads/${e}`,{...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return $e.createThreadAssistantStream(e,this._client.beta.threads,t)}}nt.Runs=Nt;nt.Messages=wn;class ke extends x{constructor(){super(...arguments),this.realtime=new st(this._client),this.assistants=new mn(this._client),this.threads=new nt(this._client)}}ke.Realtime=st;ke.Assistants=mn;ke.Threads=nt;class vn extends x{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class bn extends x{retrieve(e,t,n){const{container_id:r}=t;return this._client.get(h`/containers/${r}/files/${e}/content`,{...n,headers:y([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}}let jt=class extends x{constructor(){super(...arguments),this.content=new bn(this._client)}create(s,e,t){return this._client.post(h`/containers/${s}/files`,ie({body:e,...t},this._client))}retrieve(s,e,t){const{container_id:n}=e;return this._client.get(h`/containers/${n}/files/${s}`,t)}list(s,e={},t){return this._client.getAPIList(h`/containers/${s}/files`,C,{query:e,...t})}delete(s,e,t){const{container_id:n}=e;return this._client.delete(h`/containers/${n}/files/${s}`,{...t,headers:y([{Accept:"*/*"},t==null?void 0:t.headers])})}};jt.Content=bn;class Lt extends x{constructor(){super(...arguments),this.files=new jt(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(h`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",C,{query:e,...t})}delete(e,t){return this._client.delete(h`/containers/${e}`,{...t,headers:y([{Accept:"*/*"},t==null?void 0:t.headers])})}}Lt.Files=jt;class xn extends x{create(e,t){const n=!!e.encoding_format;let r=n?e.encoding_format:"base64";n&&q(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const o=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return n?o:(q(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const c=l.embedding;l.embedding=Jr(c)}),i)))}}class Sn extends x{retrieve(e,t,n){const{eval_id:r,run_id:o}=t;return this._client.get(h`/evals/${r}/runs/${o}/output_items/${e}`,n)}list(e,t,n){const{eval_id:r,...o}=t;return this._client.getAPIList(h`/evals/${r}/runs/${e}/output_items`,C,{query:o,...n})}}class Mt extends x{constructor(){super(...arguments),this.outputItems=new Sn(this._client)}create(e,t,n){return this._client.post(h`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){const{eval_id:r}=t;return this._client.get(h`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(h`/evals/${e}/runs`,C,{query:t,...n})}delete(e,t,n){const{eval_id:r}=t;return this._client.delete(h`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){const{eval_id:r}=t;return this._client.post(h`/evals/${r}/runs/${e}`,n)}}Mt.OutputItems=Sn;class Dt extends x{constructor(){super(...arguments),this.runs=new Mt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(h`/evals/${e}`,t)}update(e,t,n){return this._client.post(h`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList("/evals",C,{query:e,...t})}delete(e,t){return this._client.delete(h`/evals/${e}`,t)}}Dt.Runs=Mt;let $n=class extends x{create(s,e){return this._client.post("/files",ie({body:s,...e},this._client))}retrieve(s,e){return this._client.get(h`/files/${s}`,e)}list(s={},e){return this._client.getAPIList("/files",C,{query:s,...e})}delete(s,e){return this._client.delete(h`/files/${s}`,e)}content(s,e){return this._client.get(h`/files/${s}/content`,{...e,headers:y([{Accept:"application/binary"},e==null?void 0:e.headers]),__binaryResponse:!0})}async waitForProcessing(s,{pollInterval:e=5e3,maxWait:t=30*60*1e3}={}){const n=new Set(["processed","error","deleted"]),r=Date.now();let o=await this.retrieve(s);for(;!o.status||!n.has(o.status);)if(await Ie(e),o=await this.retrieve(s),Date.now()-r>t)throw new It({message:`Giving up on waiting for file ${s} to finish processing after ${t} milliseconds.`});return o}};class An extends x{}let In=class extends x{run(s,e){return this._client.post("/fine_tuning/alpha/graders/run",{body:s,...e})}validate(s,e){return this._client.post("/fine_tuning/alpha/graders/validate",{body:s,...e})}};class qt extends x{constructor(){super(...arguments),this.graders=new In(this._client)}}qt.Graders=In;class On extends x{create(e,t,n){return this._client.getAPIList(h`/fine_tuning/checkpoints/${e}/permissions`,tt,{body:t,method:"post",...n})}retrieve(e,t={},n){return this._client.get(h`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){const{fine_tuned_model_checkpoint:r}=t;return this._client.delete(h`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}}let Bt=class extends x{constructor(){super(...arguments),this.permissions=new On(this._client)}};Bt.Permissions=On;class Rn extends x{list(e,t={},n){return this._client.getAPIList(h`/fine_tuning/jobs/${e}/checkpoints`,C,{query:t,...n})}}class Ut extends x{constructor(){super(...arguments),this.checkpoints=new Rn(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(h`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",C,{query:e,...t})}cancel(e,t){return this._client.post(h`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(h`/fine_tuning/jobs/${e}/events`,C,{query:t,...n})}pause(e,t){return this._client.post(h`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(h`/fine_tuning/jobs/${e}/resume`,t)}}Ut.Checkpoints=Rn;class he extends x{constructor(){super(...arguments),this.methods=new An(this._client),this.jobs=new Ut(this._client),this.checkpoints=new Bt(this._client),this.alpha=new qt(this._client)}}he.Methods=An;he.Jobs=Ut;he.Checkpoints=Bt;he.Alpha=qt;class kn extends x{}class Wt extends x{constructor(){super(...arguments),this.graderModels=new kn(this._client)}}Wt.GraderModels=kn;class En extends x{createVariation(e,t){return this._client.post("/images/variations",ie({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",ie({body:e,...t},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Pn extends x{retrieve(e,t){return this._client.get(h`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",tt,e)}delete(e,t){return this._client.delete(h`/models/${e}`,t)}}class Cn extends x{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Kr(s,e){return!e||!zr(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(n=>({...n,parsed:null}))}:t)}:Tn(s,e)}function Tn(s,e){const t=s.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:Yr(e,r)};if(r.type==="message"){const o=r.content.map(i=>i.type==="output_text"?{...i,parsed:Vr(e,i.text)}:i);return{...r,content:o}}return r}),n=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||Nn(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const r of n.output)if(r.type==="message"){for(const o of r.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function Vr(s,e){var t,n,r,o;return((n=(t=s.text)==null?void 0:t.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((r=s.text)==null?void 0:r.format)?((o=s.text)==null?void 0:o.format).$parseRaw(e):JSON.parse(e)}function zr(s){var e;return!!kt((e=s.text)==null?void 0:e.format)}function Gr(s){return(s==null?void 0:s.$brand)==="auto-parseable-tool"}function Qr(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Yr(s,e){const t=Qr(s.tools??[],e.name);return{...e,...e,parsed_arguments:Gr(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function Nn(s){const e=[];for(const t of s.output)if(t.type==="message")for(const n of t.content)n.type==="output_text"&&e.push(n.text);s.output_text=e.join("")}var le,je,te,Le,ms,gs,ys,ws;class Ft extends Rt{constructor(e){super(),le.add(this),je.set(this,void 0),te.set(this,void 0),Le.set(this,void 0),v(this,je,e)}static createResponse(e,t,n){const r=new Ft(t);return r._run(()=>r._createOrRetrieveResponse(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,t,n){var r;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),a(this,le,"m",ms).call(this);let i,l=null;"response_id"in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),l=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const c of i)a(this,le,"m",gs).call(this,c,l);if((r=i.controller.signal)!=null&&r.aborted)throw new H;return a(this,le,"m",ys).call(this)}[(je=new WeakMap,te=new WeakMap,Le=new WeakMap,le=new WeakSet,ms=function(){this.ended||v(this,te,void 0)},gs=function(e,t){if(this.ended)return;const n=(o,i)=>{(t==null||i.sequence_number>t)&&this._emit(o,i)},r=a(this,le,"m",ws).call(this,e);switch(n("event",e),e.type){case"response.output_text.delta":{const o=r.output[e.output_index];if(!o)throw new w(`missing output at index ${e.output_index}`);if(o.type==="message"){const i=o.content[e.content_index];if(!i)throw new w(`missing content at index ${e.content_index}`);if(i.type!=="output_text")throw new w(`expected content to be 'output_text', got ${i.type}`);n("response.output_text.delta",{...e,snapshot:i.text})}break}case"response.function_call_arguments.delta":{const o=r.output[e.output_index];if(!o)throw new w(`missing output at index ${e.output_index}`);o.type==="function_call"&&n("response.function_call_arguments.delta",{...e,snapshot:o.arguments});break}default:n(e.type,e);break}},ys=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");const e=a(this,te,"f");if(!e)throw new w("request ended without sending any events");v(this,te,void 0);const t=Zr(e,a(this,je,"f"));return v(this,Le,t),t},ws=function(e){let t=a(this,te,"f");if(!t){if(e.type!=="response.created")throw new w(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=v(this,te,e.response),t}switch(e.type){case"response.output_item.added":{t.output.push(e.item);break}case"response.content_part.added":{const n=t.output[e.output_index];if(!n)throw new w(`missing output at index ${e.output_index}`);n.type==="message"&&n.content.push(e.part);break}case"response.output_text.delta":{const n=t.output[e.output_index];if(!n)throw new w(`missing output at index ${e.output_index}`);if(n.type==="message"){const r=n.content[e.content_index];if(!r)throw new w(`missing content at index ${e.content_index}`);if(r.type!=="output_text")throw new w(`expected content to be 'output_text', got ${r.type}`);r.text+=e.delta}break}case"response.function_call_arguments.delta":{const n=t.output[e.output_index];if(!n)throw new w(`missing output at index ${e.output_index}`);n.type==="function_call"&&(n.arguments+=e.delta);break}case"response.completed":{v(this,te,e.response);break}}return t},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",r=>{const o=t.shift();o?o.resolve(r):e.push(r)}),this.on("end",()=>{n=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{n=!0;for(const o of t)o.reject(r);t.length=0}),this.on("error",r=>{n=!0;for(const o of t)o.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((r,o)=>t.push({resolve:r,reject:o})).then(r=>r?{value:r,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=a(this,Le,"f");if(!e)throw new w("stream ended without producing a ChatCompletion");return e}}function Zr(s,e){return Kr(s,e)}class jn extends x{list(e,t={},n){return this._client.getAPIList(h`/responses/${e}/input_items`,C,{query:t,...n})}}class Xt extends x{constructor(){super(...arguments),this.inputItems=new jn(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&Nn(n),n))}retrieve(e,t={},n){return this._client.get(h`/responses/${e}`,{query:t,...n,stream:(t==null?void 0:t.stream)??!1})}delete(e,t){return this._client.delete(h`/responses/${e}`,{...t,headers:y([{Accept:"*/*"},t==null?void 0:t.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>Tn(n,e))}stream(e,t){return Ft.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(h`/responses/${e}/cancel`,{...t,headers:y([{Accept:"*/*"},t==null?void 0:t.headers])})}}Xt.InputItems=jn;class Ln extends x{create(e,t,n){return this._client.post(h`/uploads/${e}/parts`,ie({body:t,...n},this._client))}}class Ht extends x{constructor(){super(...arguments),this.parts=new Ln(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(h`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(h`/uploads/${e}/complete`,{body:t,...n})}}Ht.Parts=Ln;const eo=async s=>{const e=await Promise.allSettled(s),t=e.filter(r=>r.status==="rejected");if(t.length){for(const r of t)console.error(r.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const n=[];for(const r of e)r.status==="fulfilled"&&n.push(r.value);return n};class Mn extends x{create(e,t,n){return this._client.post(h`/vector_stores/${e}/file_batches`,{body:t,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,t,n){const{vector_store_id:r}=t;return this._client.get(h`/vector_stores/${r}/file_batches/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,t,n){const{vector_store_id:r}=t;return this._client.post(h`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,t,n){const r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){const{vector_store_id:r,...o}=t;return this._client.getAPIList(h`/vector_stores/${r}/file_batches/${e}/files`,C,{query:o,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(e,t,n){var r;const o=y([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((r=n==null?void 0:n.pollIntervalMs)==null?void 0:r.toString())??void 0}]);for(;;){const{data:i,response:l}=await this.retrieve(t,{vector_store_id:e},{...n,headers:o}).withResponse();switch(i.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const d=l.headers.get("openai-poll-after-ms");if(d){const m=parseInt(d);isNaN(m)||(c=m)}}await Ie(c);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const o=(r==null?void 0:r.maxConcurrency)??5,i=Math.min(o,t.length),l=this._client,c=t.values(),d=[...n];async function m(g){for(let S of g){const p=await l.files.create({file:S,purpose:"assistants"},r);d.push(p.id)}}const u=Array(i).fill(c).map(m);return await eo(u),await this.createAndPoll(e,{file_ids:d})}}class Dn extends x{create(e,t,n){return this._client.post(h`/vector_stores/${e}/files`,{body:t,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,t,n){const{vector_store_id:r}=t;return this._client.get(h`/vector_stores/${r}/files/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,t,n){const{vector_store_id:r,...o}=t;return this._client.post(h`/vector_stores/${r}/files/${e}`,{body:o,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,t={},n){return this._client.getAPIList(h`/vector_stores/${e}/files`,C,{query:t,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,t,n){const{vector_store_id:r}=t;return this._client.delete(h`/vector_stores/${r}/files/${e}`,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,t,n){const r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){var r;const o=y([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((r=n==null?void 0:n.pollIntervalMs)==null?void 0:r.toString())??void 0}]);for(;;){const i=await this.retrieve(t,{vector_store_id:e},{...n,headers:o}).withResponse(),l=i.data;switch(l.status){case"in_progress":let c=5e3;if(n!=null&&n.pollIntervalMs)c=n.pollIntervalMs;else{const d=i.response.headers.get("openai-poll-after-ms");if(d){const m=parseInt(d);isNaN(m)||(c=m)}}await Ie(c);break;case"failed":case"completed":return l}}}async upload(e,t,n){const r=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){const r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){const{vector_store_id:r}=t;return this._client.getAPIList(h`/vector_stores/${r}/files/${e}/content`,tt,{...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}class rt extends x{constructor(){super(...arguments),this.files=new Dn(this._client),this.fileBatches=new Mn(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}retrieve(e,t){return this._client.get(h`/vector_stores/${e}`,{...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}update(e,t,n){return this._client.post(h`/vector_stores/${e}`,{body:t,...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",C,{query:e,...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}delete(e,t){return this._client.delete(h`/vector_stores/${e}`,{...t,headers:y([{"OpenAI-Beta":"assistants=v2"},t==null?void 0:t.headers])})}search(e,t,n){return this._client.getAPIList(h`/vector_stores/${e}/search`,tt,{body:t,method:"post",...n,headers:y([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}}rt.Files=Dn;rt.FileBatches=Mn;var Jt,Xe;class O{constructor({baseURL:e=pe("OPENAI_BASE_URL"),apiKey:t=pe("OPENAI_API_KEY"),organization:n=pe("OPENAI_ORG_ID")??null,project:r=pe("OPENAI_PROJECT_ID")??null,...o}={}){if(Xe.set(this,void 0),this.completions=new vn(this),this.chat=new Tt(this),this.embeddings=new xn(this),this.files=new $n(this),this.images=new En(this),this.audio=new Re(this),this.moderations=new Cn(this),this.models=new Pn(this),this.fineTuning=new he(this),this.graders=new Wt(this),this.vectorStores=new rt(this),this.beta=new ke(this),this.batches=new fn(this),this.uploads=new Ht(this),this.responses=new Xt(this),this.evals=new Dt(this),this.containers=new Lt(this),t===void 0)throw new w("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const i={apiKey:t,organization:n,project:r,...o,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&Yn())throw new w(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);this.baseURL=i.baseURL,this.timeout=i.timeout??Jt.DEFAULT_TIMEOUT,this.logger=i.logger??console;const l="warn";this.logLevel=l,this.logLevel=zt(i.logLevel,"ClientOptions.logLevel",this)??zt(pe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??nr(),v(this,Xe,or),this._options=i,this.apiKey=t,this.organization=n,this.project=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}authHeaders(e){return y([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return mr(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${ce}`}defaultIdempotencyKey(){return`stainless-node-retry-${_s()}`}makeStatusError(e,t,n,r){return D.generate(e,t,n,r)}buildURL(e,t){const n=Hn(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),r=this.defaultQuery();return Kn(r)||(t={...r,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new et(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){var r,o;const i=await e,l=i.maxRetries??this.maxRetries;t==null&&(t=l),await this.prepareOptions(i);const{req:c,url:d,timeout:m}=this.buildRequest(i,{retryCount:l-t});await this.prepareRequest(c,{url:d,options:i});const u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),g=n===void 0?"":`, retryOf: ${n}`,S=Date.now();if(q(this).debug(`[${u}] sending request`,se({retryOfRequestLogID:n,method:i.method,url:d,options:i,headers:c.headers})),(r=i.signal)!=null&&r.aborted)throw new H;const p=new AbortController,$=await this.fetchWithTimeout(d,c,m,p).catch(mt),b=Date.now();if($ instanceof Error){const _=`retrying, ${t} attempts remaining`;if((o=i.signal)!=null&&o.aborted)throw new H;const A=ft($)||/timed? ?out/i.test(String($)+("cause"in $?String($.cause):""));if(t)return q(this).info(`[${u}] connection ${A?"timed out":"failed"} - ${_}`),q(this).debug(`[${u}] connection ${A?"timed out":"failed"} (${_})`,se({retryOfRequestLogID:n,url:d,durationMs:b-S,message:$.message})),this.retryRequest(i,t,n??u);throw q(this).info(`[${u}] connection ${A?"timed out":"failed"} - error; no more retries left`),q(this).debug(`[${u}] connection ${A?"timed out":"failed"} (error; no more retries left)`,se({retryOfRequestLogID:n,url:d,durationMs:b-S,message:$.message})),A?new It:new Ye({cause:$})}const E=[...$.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,A])=>", "+_+": "+JSON.stringify(A)).join(""),f=`[${u}${g}${E}] ${c.method} ${d} ${$.ok?"succeeded":"failed"} with status ${$.status} in ${b-S}ms`;if(!$.ok){const _=this.shouldRetry($);if(t&&_){const P=`retrying, ${t} attempts remaining`;return await rr($.body),q(this).info(`${f} - ${P}`),q(this).debug(`[${u}] response error (${P})`,se({retryOfRequestLogID:n,url:$.url,status:$.status,headers:$.headers,durationMs:b-S})),this.retryRequest(i,t,n??u,$.headers)}const A=_?"error; no more retries left":"error; not retryable";q(this).info(`${f} - ${A}`);const k=await $.text().catch(P=>mt(P).message),R=Gn(k),T=R?void 0:k;throw q(this).debug(`[${u}] response error (${A})`,se({retryOfRequestLogID:n,url:$.url,status:$.status,headers:$.headers,message:T,durationMs:Date.now()-S})),this.makeStatusError($.status,R,T,$.headers)}return q(this).info(f),q(this).debug(`[${u}] response start`,se({retryOfRequestLogID:n,url:$.url,status:$.status,headers:$.headers,durationMs:b-S})),{response:$,options:i,controller:p,requestLogID:u,retryOfRequestLogID:n,startTime:S}}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}requestAPIList(e,t){const n=this.makeRequest(t,null,void 0);return new Sr(this,n,e)}async fetchWithTimeout(e,t,n,r){const{signal:o,method:i,...l}=t||{};o&&o.addEventListener("abort",()=>r.abort());const c=setTimeout(()=>r.abort(),n),d=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,m={signal:r.signal,...d?{duplex:"half"}:{},method:"GET",...l};i&&(m.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,m)}finally{clearTimeout(c)}}shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let o;const i=r==null?void 0:r.get("retry-after-ms");if(i){const c=parseFloat(i);Number.isNaN(c)||(o=c)}const l=r==null?void 0:r.get("retry-after");if(l&&!o){const c=parseFloat(l);Number.isNaN(c)?o=Date.parse(l)-Date.now():o=c*1e3}if(!(o&&0<=o&&o<60*1e3)){const c=e.maxRetries??this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(t,c)}return await Ie(o),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e,r=Math.min(.5*Math.pow(2,n),8),o=1-Math.random()*.25;return r*o*1e3}buildRequest(e,{retryCount:t=0}={}){const n={...e},{method:r,path:o,query:i}=n,l=this.buildURL(o,i);"timeout"in n&&zn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const{bodyHeaders:c,body:d}=this.buildBody({options:n}),m=this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t});return{req:{method:r,headers:m,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let o={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);const i=y([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...sr(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const n=y([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof 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:Ps(e)}:a(this,Xe,"f").call(this,{body:e,headers:n})}}Jt=O,Xe=new WeakMap;O.OpenAI=Jt;O.DEFAULT_TIMEOUT=6e5;O.OpenAIError=w;O.APIError=D;O.APIConnectionError=Ye;O.APIConnectionTimeoutError=It;O.APIUserAbortError=H;O.NotFoundError=Ss;O.ConflictError=$s;O.RateLimitError=Is;O.BadRequestError=vs;O.AuthenticationError=bs;O.InternalServerError=Os;O.PermissionDeniedError=xs;O.UnprocessableEntityError=As;O.toFile=kr;O.Completions=vn;O.Chat=Tt;O.Embeddings=xn;O.Files=$n;O.Images=En;O.Audio=Re;O.Moderations=Cn;O.Models=Pn;O.FineTuning=he;O.Graders=Wt;O.VectorStores=rt;O.Beta=ke;O.Batches=fn;O.Uploads=Ht;O.Responses=Xt;O.Evals=Dt;O.Containers=Lt;class to{constructor(){this.clients=new Map}getClient(e,t){var n;const r=`${e}-${t.baseUrl}-${(n=t.apiKey)==null?void 0:n.slice(-8)}`;if(!this.clients.has(r)){let o;switch(e){case"openai":case"deepseek":case"deepseek-v3":case"deepseek-reasoner":case"custom":o=new O({baseURL:t.baseUrl,apiKey:t.apiKey,dangerouslyAllowBrowser:!0});break;case"claude":o=new O({baseURL:t.baseUrl,apiKey:t.apiKey,dangerouslyAllowBrowser:!0,defaultHeaders:{"anthropic-version":"2023-06-01","content-type":"application/json"}});break;case"gemini":o=new O({baseURL:t.baseUrl,apiKey:t.apiKey,dangerouslyAllowBrowser:!0});break;default:throw new Error(`不支持的AI提供商: ${e}`)}this.clients.set(r,o)}return this.clients.get(r)}async sendMessage(e,t={}){var n,r;try{const o=Un(),i=Wn();if(!i.apiKey)throw new Error("未配置API密钥");const l=this.getClient(o.provider,i),c=[{role:"system",content:await this.getSystemPrompt(t)},{role:"user",content:e}];if(t.history&&t.history.length>0){const m=t.history.slice(-4).map(u=>({role:u.type==="user"?"user":"assistant",content:u.text}));c.splice(1,0,...m)}const d=(r=(n=(await l.chat.completions.create({model:i.modelId,messages:c,max_tokens:i.maxTokens,temperature:i.temperature,stream:!1})).choices[0])==null?void 0:n.message)==null?void 0:r.content;if(!d)throw new Error("AI响应为空");return d}catch(o){throw console.error("❌ AI调用失败:",o),this.handleError(o)}}async getSystemPrompt(e={}){let t=(await Fn()).systemPrompt;return(!t||t.trim()==="")&&(t=`你是Vue Docs UI文档网站的AI助手。你的任务是帮助用户理解文档内容回答技术问题并提供有用的指导。
请遵循以下原则:
1. 提供准确、有用的技术信息
2. 保持友好、专业的语调
3. 如果不确定答案,请诚实地说明
4. 尽量给出具体的代码示例或步骤
5. 使用中文回答问题
你特别擅长回答关于:
- Vue.js 开发
- 组件库使用
- 文档编写和维护
- 前端开发最佳实践
- 技术概念解释`),e.currentPage?`${t}
当前用户正在查看页面:${e.currentPage}`:e.documentContent?`${t}
相关文档内容:
${e.documentContent.slice(0,1e3)}`:t}async testConnection(){try{return{success:!0,message:"连接测试成功",response:await this.sendMessage("你好,请回复一个简短的测试消息。",{})}}catch(e){return{success:!1,message:e.message}}}handleError(e){var t,n;return e.code==="invalid_api_key"?new Error("API密钥无效请检查配置"):e.code==="insufficient_quota"?new Error("API配额不足请检查账户余额"):e.code==="rate_limit_exceeded"?new Error("请求频率过高,请稍后重试"):e.code==="model_not_found"?new Error("指定的模型不存在,请检查模型配置"):(t=e.message)!=null&&t.includes("fetch")?new Error("网络连接失败请检查网络和API端点"):(n=e.message)!=null&&n.includes("CORS")?new Error("跨域请求被阻止请检查API配置"):new Error(`AI调用失败: ${e.message}`)}clearClients(){this.clients.clear()}}const qn=new to,no=(s,e)=>qn.sendMessage(s,e),ro=()=>qn.testConnection();export{qn as default,no as sendAIMessage,ro as testAIConnection};