3 lines
97 KiB
JavaScript
3 lines
97 KiB
JavaScript
!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";const e={actualMode:"autocomplete"},t=["logs","title","cursor","typing","mouseover","infinite","timeout","history","includeImages"],s=document.querySelector("#mode").querySelectorAll("button");function n(e,t,s,n){return new(s||(s=Promise))((function(r,o){function a(e){try{c(n.next(e))}catch(e){o(e)}}function i(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(a,i)}c((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const r="RFC3986",o={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},a=Array.isArray,i=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),c=1024;function l(e,t){if(a(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const u=Object.prototype.hasOwnProperty,h={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},d=Array.isArray,f=Array.prototype.push,p=function(e,t){f.apply(e,d(t)?t:[t])},m=Date.prototype.toISOString,g={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,s,n,r)=>{if(0===e.length)return e;let o=e;if("symbol"==typeof e?o=Symbol.prototype.toString.call(e):"string"!=typeof e&&(o=String(e)),"iso-8859-1"===s)return escape(o).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));let a="";for(let e=0;e<o.length;e+=c){const t=o.length>=c?o.slice(e,e+c):o,s=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===r&&(40===n||41===n)?s[s.length]=t.charAt(e):n<128?s[s.length]=i[n]:n<2048?s[s.length]=i[192|n>>6]+i[128|63&n]:n<55296||n>=57344?s[s.length]=i[224|n>>12]+i[128|n>>6&63]+i[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),s[s.length]=i[240|n>>18]+i[128|n>>12&63]+i[128|n>>6&63]+i[128|63&n])}a+=s.join("")}return a},encodeValuesOnly:!1,format:r,formatter:o[r],indices:!1,serializeDate:e=>m.call(e),skipNulls:!1,strictNullHandling:!1};const y={};function w(e,t,s,n,r,o,a,i,c,u,h,f,m,_,b,v,x,S){let A=e,E=S,P=0,I=!1;for(;void 0!==(E=E.get(y))&&!I;){const t=E.get(e);if(P+=1,void 0!==t){if(t===P)throw new RangeError("Cyclic object value");I=!0}void 0===E.get(y)&&(P=0)}if("function"==typeof u?A=u(t,A):A instanceof Date?A=m?.(A):"comma"===s&&d(A)&&(A=l(A,(function(e){return e instanceof Date?m?.(e):e}))),null===A){if(o)return c&&!v?c(t,g.encoder,x,"key",_):t;A=""}if("string"==typeof(R=A)||"number"==typeof R||"boolean"==typeof R||"symbol"==typeof R||"bigint"==typeof R||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(A)){if(c){const e=v?t:c(t,g.encoder,x,"key",_);return[b?.(e)+"="+b?.(c(A,g.encoder,x,"value",_))]}return[b?.(t)+"="+b?.(String(A))]}var R;const $=[];if(void 0===A)return $;let C;if("comma"===s&&d(A))v&&c&&(A=l(A,c)),C=[{value:A.length>0?A.join(",")||null:void 0}];else if(d(u))C=u;else{const e=Object.keys(A);C=h?e.sort(h):e}const k=i?String(t).replace(/\./g,"%2E"):String(t),O=n&&d(A)&&1===A.length?k+"[]":k;if(r&&d(A)&&0===A.length)return O+"[]";for(let t=0;t<C.length;++t){const l=C[t],g="object"==typeof l&&void 0!==l.value?l.value:A[l];if(a&&null===g)continue;const E=f&&i?l.replace(/\./g,"%2E"):l,I=d(A)?"function"==typeof s?s(O,E):O:O+(f?"."+E:"["+E+"]");S.set(e,P);const R=new WeakMap;R.set(y,S),p($,w(g,I,s,n,r,o,a,i,"comma"===s&&v&&d(A)?null:c,u,h,f,m,_,b,v,x,R))}return $}function _(e,t={}){let s=e;const n=function(e=g){if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.encodeDotInKeys&&"boolean"!=typeof e.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");const t=e.charset||g.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=r;if(void 0!==e.format){if(!u.call(o,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=o[s];let a,i=g.filter;if(("function"==typeof e.filter||d(e.filter))&&(i=e.filter),a=e.arrayFormat&&e.arrayFormat in h?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":g.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const c=void 0===e.allowDots?1==!!e.encodeDotInKeys||g.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:g.addQueryPrefix,allowDots:c,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:g.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:g.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?g.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:g.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:g.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:g.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:g.encodeValuesOnly,filter:i,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:g.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:g.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:g.strictNullHandling}}(t);let a,i;"function"==typeof n.filter?(i=n.filter,s=i("",s)):d(n.filter)&&(i=n.filter,a=i);const c=[];if("object"!=typeof s||null===s)return"";const l=h[n.arrayFormat],f="comma"===l&&n.commaRoundTrip;a||(a=Object.keys(s)),n.sort&&a.sort(n.sort);const m=new WeakMap;for(let e=0;e<a.length;++e){const t=a[e];n.skipNulls&&null===s[t]||p(c,w(s[t],t,l,f,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,m))}const y=c.join(n.delimiter);let _=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?_+="utf8=%26%2310003%3B&":_+="utf8=%E2%9C%93&"),y.length>0?_+y:""}const b="4.87.4";let v,x,S,A,E,P,I,R,$,C=!1;class k{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}v||function(e,t={auto:!1}){if(C)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(v)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${v}'\``);C=t.auto,v=e.kind,x=e.fetch,S=e.FormData,A=e.File,E=e.ReadableStream,P=e.getMultipartRequestOptions,I=e.getDefaultAgent,R=e.fileFromPath,$=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let s,n,r,o;try{s=fetch,n=Request,r=Response,o=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:s,Request:n,Response:r,Headers:o,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new k(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class O extends Error{}class T extends O{constructor(e,t,s,n){super(`${T.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.request_id=n?.["x-request-id"],this.error=t;const r=t;this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,s){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e||!n)return new M({message:s,cause:je(t)});const r=t?.error;return 400===e?new N(e,r,s,n):401===e?new D(e,r,s,n):403===e?new B(e,r,s,n):404===e?new L(e,r,s,n):409===e?new F(e,r,s,n):422===e?new W(e,r,s,n):429===e?new U(e,r,s,n):e>=500?new X(e,r,s,n):new T(e,r,s,n)}}class j extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class M extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class q extends M{constructor({message:e}={}){super({message:e??"Request timed out."})}}class N extends T{}class D extends T{}class B extends T{}class L extends T{}class F extends T{}class W extends T{}class U extends T{}class X extends T{}class J extends O{constructor(){super("Could not parse response content as the length limit was reached")}}class H extends O{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var V,K=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},z=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)};class G{constructor(){V.set(this,void 0),this.buffer=new Uint8Array,K(this,V,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let s=new Uint8Array(this.buffer.length+t.length);s.set(this.buffer),s.set(t,this.buffer.length),this.buffer=s;const n=[];let r;for(;null!=(r=Q(this.buffer,z(this,V,"f")));){if(r.carriage&&null==z(this,V,"f")){K(this,V,r.index,"f");continue}if(null!=z(this,V,"f")&&(r.index!==z(this,V,"f")+1||r.carriage)){n.push(this.decodeText(this.buffer.slice(0,z(this,V,"f")-1))),this.buffer=this.buffer.slice(z(this,V,"f")),K(this,V,null,"f");continue}const e=null!==z(this,V,"f")?r.preceding-1:r.preceding,t=this.decodeText(this.buffer.slice(0,e));n.push(t),this.buffer=this.buffer.slice(r.index),K(this,V,null,"f")}return n}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new O(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new O(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new O("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function Q(e,t){for(let s=t??0;s<e.length;s++){if(10===e[s])return{preceding:s,index:s+1,carriage:!1};if(13===e[s])return{preceding:s,index:s+1,carriage:!0}}return null}function Y(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}function Z(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}V=new WeakMap,G.NEWLINE_CHARS=new Set(["\n","\r"]),G.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class ee{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let s=!1;return new ee((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(const s of async function*(e,t){if(!e.body)throw t.abort(),new O("Attempted to iterate over a response with no body");const s=new te,n=new G,r=Z(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const s of e){if(null==s)continue;const e=s instanceof ArrayBuffer?new Uint8Array(s):"string"==typeof s?(new TextEncoder).encode(s):s;let n,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(n=Y(t));)yield t.slice(0,n),t=t.slice(n)}t.length>0&&(yield t)}(r))for(const t of n.decode(e)){const e=s.decode(t);e&&(yield e)}for(const e of n.flush()){const t=s.decode(e);t&&(yield t)}}(e,t))if(!n)if(s.data.startsWith("[DONE]"))n=!0;else if(null===s.event||s.event.startsWith("response.")){let e;try{e=JSON.parse(s.data)}catch(e){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),e}if(e&&e.error)throw new T(void 0,e.error,void 0,void 0);yield e}else{let e;try{e=JSON.parse(s.data)}catch(e){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),e}if("error"==s.event)throw new T(void 0,e.error,e.message,void 0);yield{event:s.event,data:e}}n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}static fromReadableStream(e,t){let s=!1;return new ee((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(const t of async function*(){const t=new G,s=Z(e);for await(const e of s)for(const s of t.decode(e))yield s;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=s.next();e.push(n),t.push(n)}return n.shift()}});return[new ee((()=>n(e)),this.controller),new ee((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const s=new TextEncoder;return new E({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:r}=await t.next();if(r)return e.close();const o=s.encode(JSON.stringify(n)+"\n");e.enqueue(o)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class te{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 e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=function(e,t){const s=e.indexOf(t);if(-1!==s)return[e.substring(0,s),t,e.substring(s+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}const se=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,ne=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&re(e),re=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function oe(e,t,s){if(e=await e,ne(e))return e;if(se(e)){const n=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const r=re(n)?[await n.arrayBuffer()]:[n];return new A(r,t,s)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(re(e))t.push(await e.arrayBuffer());else{if(!ie(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const s of e)t.push(s)}return t}(e);if(t||(t=function(e){return ae(e.name)||ae(e.filename)||ae(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!s?.type){const e=n[0]?.type;"string"==typeof e&&(s={...s,type:e})}return new A(n,t,s)}const ae=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,ie=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],ce=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],le=async e=>{const t=await ue(e.body);return P(t,e)},ue=async e=>{const t=new S;return await Promise.all(Object.entries(e||{}).map((([e,s])=>he(t,e,s)))),t},he=async(e,t,s)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if((e=>ne(e)||se(e)||$(e))(s)){const n=await oe(s);e.append(t,n)}else if(Array.isArray(s))await Promise.all(s.map((s=>he(e,t+"[]",s))));else{if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map((([s,n])=>he(e,`${t}[${s}]`,n))))}}};var de,fe=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},pe=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)};async function me(e){const{response:t}=e;if(e.options.stream)return Le("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):ee.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const s=t.headers.get("content-type"),n=s?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){const e=await t.json();return Le("response",t.status,t.url,t.headers,e),ge(e,t)}const r=await t.text();return Le("response",t.status,t.url,t.headers,r),r}function ge(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class ye extends Promise{constructor(e,t=me){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new ye(this.responsePromise,(async t=>ge(e(await this.parseResponse(t),t),t.response)))}asResponse(){return this.responsePromise.then((e=>e.response))}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class we{constructor({baseURL:e,maxRetries:t=2,timeout:s=6e5,httpAgent:n,fetch:r}){this.baseURL=e,this.maxRetries=Te("maxRetries",t),this.timeout=Te("timeout",s),this.httpAgent=n,this.fetch=r??x}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Re(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Fe()}`}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,s){return this.request(Promise.resolve(s).then((async s=>{const n=s&&re(s?.body)?new DataView(await s.body.arrayBuffer()):s?.body instanceof DataView?s.body:s?.body instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s?.body)?new DataView(s.body.buffer):s?.body;return{method:e,path:t,...s,body:n}})))}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){e={...e};const{method:s,path:n,query:r,headers:o={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:ce(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,i=this.calculateContentLength(a),c=this.buildURL(n,r);"timeout"in e&&Te("timeout",e.timeout),e.timeout=e.timeout??this.timeout;const l=e.httpAgent??this.httpAgent??I(c),u=e.timeout+1e3;"number"==typeof l?.options?.timeout&&u>(l.options.timeout??0)&&(l.options.timeout=u),this.idempotencyHeader&&"get"!==s&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:s,...a&&{body:a},headers:this.buildHeaders({options:e,headers:o,contentLength:i,retryCount:t}),...l&&{agent:l},signal:e.signal??null},url:c,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:s,retryCount:n}){const r={};s&&(r["content-length"]=s);const o=this.defaultHeaders(e);return De(r,o),De(r,t),ce(e.body)&&"node"!==v&&delete r["content-type"],void 0===We(o,"x-stainless-retry-count")&&void 0===We(t,"x-stainless-retry-count")&&(r["x-stainless-retry-count"]=String(n)),void 0===We(o,"x-stainless-timeout")&&void 0===We(t,"x-stainless-timeout")&&e.timeout&&(r["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:s}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,s,n){return T.generate(e,t,s,n)}request(e,t=null){return new ye(this.makeRequest(e,t))}async makeRequest(e,t){const s=await e,n=s.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(s);const{req:r,url:o,timeout:a}=this.buildRequest(s,{retryCount:n-t});if(await this.prepareRequest(r,{url:o,options:s}),Le("request",o,s,r.headers),s.signal?.aborted)throw new j;const i=new AbortController,c=await this.fetchWithTimeout(o,r,a,i).catch(je);if(c instanceof Error){if(s.signal?.aborted)throw new j;if(t)return this.retryRequest(s,t);if("AbortError"===c.name)throw new q;throw new M({cause:c})}const l=ve(c.headers);if(!c.ok){if(t&&this.shouldRetry(c)){return Le(`response (error; ${`retrying, ${t} attempts remaining`})`,c.status,o,l),this.retryRequest(s,t,l)}const e=await c.text().catch((e=>je(e).message)),n=$e(e),r=n?void 0:e;Le(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,c.status,o,l,r);throw this.makeStatusError(c.status,n,r,l)}return{response:c,options:s,controller:i}}requestAPIList(e,t){const s=this.makeRequest(t,null);return new be(this,s,e)}buildURL(e,t){const s=ke(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return qe(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new O(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,s,n){const{signal:r,...o}=t||{};r&&r.addEventListener("abort",(()=>n.abort()));const a=setTimeout((()=>n.abort()),s),i={signal:n.signal,...o};return i.method&&(i.method=i.method.toUpperCase()),this.fetch.call(void 0,e,i).finally((()=>{clearTimeout(a)}))}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,s){let n;const r=s?.["retry-after-ms"];if(r){const e=parseFloat(r);Number.isNaN(e)||(n=e)}const o=s?.["retry-after"];if(o&&!n){const e=parseFloat(o);n=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){const s=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,s)}return await Oe(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${b}`}}class _e{constructor(e,t,s,n){de.set(this,void 0),fe(this,de,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new O("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const s=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of s)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await pe(this,de,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(de=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class be extends ye{constructor(e,t,s){super(t,(async t=>new s(e,t.response,await me(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const ve=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const s=t.toString();return e[s.toLowerCase()]||e[s]}}),xe={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},Se=e=>"object"==typeof e&&null!==e&&!qe(e)&&Object.keys(e).every((e=>Ne(xe,e))),Ae=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b,"X-Stainless-OS":Pe(Deno.build.os),"X-Stainless-Arch":Ee(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b,"X-Stainless-OS":Pe(process.platform),"X-Stainless-Arch":Ee(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{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:t,pattern:s}of e){const e=s.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":b,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Ee=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",Pe=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let Ie;const Re=()=>Ie??(Ie=Ae()),$e=e=>{try{return JSON.parse(e)}catch(e){return}},Ce=/^[a-z][a-z0-9+.-]*:/i,ke=e=>Ce.test(e),Oe=e=>new Promise((t=>setTimeout(t,e))),Te=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new O(`${e} must be an integer`);if(t<0)throw new O(`${e} must be a positive integer`);return t},je=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},Me=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function qe(e){if(!e)return!0;for(const t in e)return!1;return!0}function Ne(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function De(e,t){for(const s in t){if(!Ne(t,s))continue;const n=s.toLowerCase();if(!n)continue;const r=t[s];null===r?delete e[n]:void 0!==r&&(e[n]=r)}}const Be=new Set(["authorization","api-key"]);function Le(e,...t){if("undefined"!=typeof process&&"true"===process?.env?.DEBUG){const s=t.map((e=>{if(!e)return e;if(e.headers){const t={...e,headers:{...e.headers}};for(const s in e.headers)Be.has(s.toLowerCase())&&(t.headers[s]="REDACTED");return t}let t=null;for(const s in e)Be.has(s.toLowerCase())&&(t??(t={...e}),t[s]="REDACTED");return t??e}));console.log(`OpenAI:DEBUG:${e}`,...s)}}const Fe=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),We=(e,t)=>{const s=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const n=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,s)=>t+s.toUpperCase()));for(const r of[t,s,t.toUpperCase(),n]){const t=e.get(r);if(t)return t}}for(const[n,r]of Object.entries(e))if(n.toLowerCase()===s)return Array.isArray(r)?(r.length<=1||console.warn(`Received ${r.length} entries for the ${t} header, using the first entry.`),r[0]):r};function Ue(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class Xe extends _e{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class Je extends _e{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class He{constructor(e){this._client=e}}let Ve=class extends He{list(e,t={},s){return Se(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Ge,{query:t,...s})}},Ke=class extends He{constructor(){super(...arguments),this.messages=new Ve(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return Se(e)?this.list({},e):this._client.getAPIList("/chat/completions",ze,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class ze extends Je{}class Ge extends Je{}Ke.ChatCompletionsPage=ze,Ke.Messages=Ve;let Qe=class extends He{constructor(){super(...arguments),this.completions=new Ke(this._client)}};Qe.Completions=Ke,Qe.ChatCompletionsPage=ze;class Ye extends He{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class Ze extends He{create(e,t){return this._client.post("/audio/transcriptions",le({body:e,...t,__metadata:{model:e.model}}))}}class et extends He{create(e,t){return this._client.post("/audio/translations",le({body:e,...t,__metadata:{model:e.model}}))}}class tt extends He{constructor(){super(...arguments),this.transcriptions=new Ze(this._client),this.translations=new et(this._client),this.speech=new Ye(this._client)}}tt.Transcriptions=Ze,tt.Translations=et,tt.Speech=Ye;class st extends He{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return Se(e)?this.list({},e):this._client.getAPIList("/batches",nt,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class nt extends Je{}st.BatchesPage=nt;class rt extends He{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,s){return this._client.post(`/assistants/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e={},t){return Se(e)?this.list({},e):this._client.getAPIList("/assistants",ot,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class ot extends Je{}function at(e){return"function"==typeof e.parse}rt.AssistantsPage=ot;const it=e=>"assistant"===e?.role,ct=e=>"function"===e?.role,lt=e=>"tool"===e?.role;var ut,ht,dt,ft,pt,mt,gt,yt,wt,_t,bt,vt,xt,St=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},At=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)};class Et{constructor(){ut.add(this),this.controller=new AbortController,ht.set(this,void 0),dt.set(this,(()=>{})),ft.set(this,(()=>{})),pt.set(this,void 0),mt.set(this,(()=>{})),gt.set(this,(()=>{})),yt.set(this,{}),wt.set(this,!1),_t.set(this,!1),bt.set(this,!1),vt.set(this,!1),St(this,ht,new Promise(((e,t)=>{St(this,dt,e,"f"),St(this,ft,t,"f")})),"f"),St(this,pt,new Promise(((e,t)=>{St(this,mt,e,"f"),St(this,gt,t,"f")})),"f"),At(this,ht,"f").catch((()=>{})),At(this,pt,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),At(this,ut,"m",xt).bind(this))}),0)}_connected(){this.ended||(At(this,dt,"f").call(this),this._emit("connect"))}get ended(){return At(this,wt,"f")}get errored(){return At(this,_t,"f")}get aborted(){return At(this,bt,"f")}abort(){this.controller.abort()}on(e,t){return(At(this,yt,"f")[e]||(At(this,yt,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=At(this,yt,"f")[e];if(!s)return this;const n=s.findIndex((e=>e.listener===t));return n>=0&&s.splice(n,1),this}once(e,t){return(At(this,yt,"f")[e]||(At(this,yt,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,s)=>{St(this,vt,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)}))}async done(){St(this,vt,!0,"f"),await At(this,pt,"f")}_emit(e,...t){if(At(this,wt,"f"))return;"end"===e&&(St(this,wt,!0,"f"),At(this,mt,"f").call(this));const s=At(this,yt,"f")[e];if(s&&(At(this,yt,"f")[e]=s.filter((e=>!e.once)),s.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return At(this,vt,"f")||s?.length||Promise.reject(e),At(this,ft,"f").call(this,e),At(this,gt,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];At(this,vt,"f")||s?.length||Promise.reject(e),At(this,ft,"f").call(this,e),At(this,gt,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function Pt(e){return"auto-parseable-response-format"===e?.$brand}function It(e){return"auto-parseable-tool"===e?.$brand}function Rt(e,t){const s=e.choices.map((e=>{if("length"===e.finish_reason)throw new J;if("content_filter"===e.finish_reason)throw new H;return{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map((e=>function(e,t){const s=e.tools?.find((e=>e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:It(s)?s.$parseRaw(t.function.arguments):s?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?$t(t,e.message.content):null}}}));return{...e,choices:s}}function $t(e,t){if("json_schema"!==e.response_format?.type)return null;if("json_schema"===e.response_format?.type){if("$parseRaw"in e.response_format){return e.response_format.$parseRaw(t)}return JSON.parse(t)}return null}function Ct(e,t){if(!e)return!1;const s=e.tools?.find((e=>e.function?.name===t.function.name));return It(s)||s?.function.strict||!1}function kt(e){return!!Pt(e.response_format)||(e.tools?.some((e=>It(e)||"function"===e.type&&!0===e.function.strict))??!1)}ht=new WeakMap,dt=new WeakMap,ft=new WeakMap,pt=new WeakMap,mt=new WeakMap,gt=new WeakMap,yt=new WeakMap,wt=new WeakMap,_t=new WeakMap,bt=new WeakMap,vt=new WeakMap,ut=new WeakSet,xt=function(e){if(St(this,_t,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new j),e instanceof j)return St(this,bt,!0,"f"),this._emit("abort",e);if(e instanceof O)return this._emit("error",e);if(e instanceof Error){const t=new O(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new O(String(e)))};var Ot,Tt,jt,Mt,qt,Nt,Dt,Bt,Lt=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)};const Ft=10;class Wt extends Et{constructor(){super(...arguments),Ot.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(ct(e)||lt(e))&&e.content)this._emit("functionCallResult",e.content);else if(it(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(it(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new O("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Lt(this,Ot,"m",Tt).call(this)}async finalMessage(){return await this.done(),Lt(this,Ot,"m",jt).call(this)}async finalFunctionCall(){return await this.done(),Lt(this,Ot,"m",Mt).call(this)}async finalFunctionCallResult(){return await this.done(),Lt(this,Ot,"m",qt).call(this)}async totalUsage(){return await this.done(),Lt(this,Ot,"m",Nt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Lt(this,Ot,"m",jt).call(this);t&&this._emit("finalMessage",t);const s=Lt(this,Ot,"m",Tt).call(this);s&&this._emit("finalContent",s);const n=Lt(this,Ot,"m",Mt).call(this);n&&this._emit("finalFunctionCall",n);const r=Lt(this,Ot,"m",qt).call(this);null!=r&&this._emit("finalFunctionCallResult",r),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",Lt(this,Ot,"m",Nt).call(this))}async _createChatCompletion(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Lt(this,Ot,"m",Dt).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Rt(r,t))}async _runChatCompletion(e,t,s){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,s)}async _runFunctions(e,t,s){const n="function",{function_call:r="auto",stream:o,...a}=t,i="string"!=typeof r&&r?.name,{maxChatCompletions:c=Ft}=s||{},l={};for(const e of t.functions)l[e.name||e.function.name]=e;const u=t.functions.map((e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description})));for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){const t=await this._createChatCompletion(e,{...a,function_call:r,functions:u,messages:[...this.messages]},s),o=t.choices[0]?.message;if(!o)throw new O("missing message in ChatCompletion response");if(!o.function_call)return;const{name:c,arguments:h}=o.function_call,d=l[c];if(!d){const e=`Invalid function_call: ${JSON.stringify(c)}. Available options are: ${u.map((e=>JSON.stringify(e.name))).join(", ")}. Please try again`;this._addMessage({role:n,name:c,content:e});continue}if(i&&i!==c){const e=`Invalid function_call: ${JSON.stringify(c)}. ${JSON.stringify(i)} requested. Please try again`;this._addMessage({role:n,name:c,content:e});continue}let f;try{f=at(d)?await d.parse(h):h}catch(e){this._addMessage({role:n,name:c,content:e instanceof Error?e.message:String(e)});continue}const p=await d.function(f,this),m=Lt(this,Ot,"m",Bt).call(this,p);if(this._addMessage({role:n,name:c,content:m}),i)return}}async _runTools(e,t,s){const n="tool",{tool_choice:r="auto",stream:o,...a}=t,i="string"!=typeof r&&r?.function?.name,{maxChatCompletions:c=Ft}=s||{},l=t.tools.map((e=>{if(It(e)){if(!e.$callback)throw new O("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e})),u={};for(const e of l)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const h="tools"in t?l.map((e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e)):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){const t=await this._createChatCompletion(e,{...a,tool_choice:r,tools:h,messages:[...this.messages]},s),o=t.choices[0]?.message;if(!o)throw new O("missing message in ChatCompletion response");if(!o.tool_calls?.length)return;for(const e of o.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:s,arguments:r}=e.function,o=u[s];if(!o){const e=`Invalid tool_call: ${JSON.stringify(s)}. Available options are: ${Object.keys(u).map((e=>JSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(i&&i!==s){const e=`Invalid tool_call: ${JSON.stringify(s)}. ${JSON.stringify(i)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let a;try{a=at(o)?await o.parse(r):r}catch(e){const s=e instanceof Error?e.message:String(e);this._addMessage({role:n,tool_call_id:t,content:s});continue}const c=await o.function(a,this),l=Lt(this,Ot,"m",Bt).call(this,c);if(this._addMessage({role:n,tool_call_id:t,content:l}),i)return}}}}Ot=new WeakSet,Tt=function(){return Lt(this,Ot,"m",jt).call(this).content??null},jt=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(it(t)){const{function_call:e,...s}=t,n={...s,content:t.content??null,refusal:t.refusal??null};return e&&(n.function_call=e),n}}throw new O("stream ended without producing a ChatCompletionMessage with role=assistant")},Mt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(it(t)&&t?.function_call)return t.function_call;if(it(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},qt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ct(t)&&null!=t.content)return t.content;if(lt(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some((e=>"assistant"===e.role&&e.tool_calls?.some((e=>"function"===e.type&&e.id===t.tool_call_id)))))return t.content}},Nt=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Dt=function(e){if(null!=e.n&&e.n>1)throw new O("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Bt=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Ut extends Wt{static runFunctions(e,t,s){const n=new Ut,r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,r))),n}static runTools(e,t,s){const n=new Ut,r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,r))),n}_addMessage(e,t=!0){super._addMessage(e,t),it(e)&&e.content&&this._emit("content",e.content)}}const Xt=1,Jt=2,Ht=4,Vt=8,Kt=16,zt=32,Gt=64,Qt=128,Yt=256,Zt=511;class es extends Error{}class ts extends Error{}const ss=(e,t)=>{const s=e.length;let n=0;const r=e=>{throw new es(`${e} at position ${n}`)},o=e=>{throw new ts(`${e} at position ${n}`)},a=()=>(h(),n>=s&&r("Unexpected end of input"),'"'===e[n]?i():"{"===e[n]?c():"["===e[n]?l():"null"===e.substring(n,n+4)||Kt&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||zt&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||zt&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||Qt&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||Yt&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):"NaN"===e.substring(n,n+3)||Gt&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),i=()=>{const a=n;let i=!1;for(n++;n<s&&('"'!==e[n]||i&&"\\"===e[n-1]);)i="\\"===e[n]&&!i,n++;if('"'==e.charAt(n))try{return JSON.parse(e.substring(a,++n-Number(i)))}catch(e){o(String(e))}else if(Xt&t)try{return JSON.parse(e.substring(a,n-Number(i))+'"')}catch(t){return JSON.parse(e.substring(a,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,h();const o={};try{for(;"}"!==e[n];){if(h(),n>=s&&Vt&t)return o;const r=i();h(),n++;try{const e=a();Object.defineProperty(o,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Vt&t)return o;throw e}h(),","===e[n]&&n++}}catch(e){if(Vt&t)return o;r("Expected '}' at end of object")}return n++,o},l=()=>{n++;const s=[];try{for(;"]"!==e[n];)s.push(a()),h(),","===e[n]&&n++}catch(e){if(Ht&t)return s;r("Expected ']' at end of array")}return n++,s},u=()=>{if(0===n){"-"===e&&Jt&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(s){if(Jt&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}o(String(s))}}const a=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=s||Jt&t||r("Unterminated number literal");try{return JSON.parse(e.substring(a,n))}catch(s){"-"===e.substring(a,n)&&Jt&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(a,e.lastIndexOf("e")))}catch(e){o(String(e))}}},h=()=>{for(;n<s&&" \n\r\t".includes(e[n]);)n++};return a()},ns=e=>function(e,t=Zt){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return ss(e.trim(),t)}(e,Zt^Jt);var rs,os,as,is,cs,ls,us,hs,ds,fs,ps,ms,gs=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},ys=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)};class ws extends Wt{constructor(e){super(),rs.add(this),os.set(this,void 0),as.set(this,void 0),is.set(this,void 0),gs(this,os,e,"f"),gs(this,as,[],"f")}get currentChatCompletionSnapshot(){return ys(this,is,"f")}static fromReadableStream(e){const t=new ws(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,s){const n=new ws(t);return n._run((()=>n._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createChatCompletion(e,t,s){super._createChatCompletion;const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),ys(this,rs,"m",cs).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const e of r)ys(this,rs,"m",us).call(this,e);if(r.controller.signal?.aborted)throw new j;return this._addChatCompletion(ys(this,rs,"m",fs).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),ys(this,rs,"m",cs).call(this),this._connected();const n=ee.fromReadableStream(e,this.controller);let r;for await(const e of n)r&&r!==e.id&&this._addChatCompletion(ys(this,rs,"m",fs).call(this)),ys(this,rs,"m",us).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new j;return this._addChatCompletion(ys(this,rs,"m",fs).call(this))}[(os=new WeakMap,as=new WeakMap,is=new WeakMap,rs=new WeakSet,cs=function(){this.ended||gs(this,is,void 0,"f")},ls=function(e){let t=ys(this,as,"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},ys(this,as,"f")[e.index]=t,t)},us=function(e){if(this.ended)return;const t=ys(this,rs,"m",ms).call(this,e);this._emit("chunk",e,t);for(const s of e.choices){const e=t.choices[s.index];null!=s.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",s.delta.content,e.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=s.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:e.message.refusal}),null!=s.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=s.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=ys(this,rs,"m",ls).call(this,e);e.finish_reason&&(ys(this,rs,"m",ds).call(this,e),null!=n.current_tool_call_index&&ys(this,rs,"m",hs).call(this,e,n.current_tool_call_index));for(const t of s.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(ys(this,rs,"m",ds).call(this,e),null!=n.current_tool_call_index&&ys(this,rs,"m",hs).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(const t of s.delta.tool_calls??[]){const s=e.message.tool_calls?.[t.index];s?.type&&("function"===s?.type&&this._emit("tool_calls.function.arguments.delta",{name:s.function?.name,index:t.index,arguments:s.function.arguments,parsed_arguments:s.function.parsed_arguments,arguments_delta:t.function?.arguments??""}))}}},hs=function(e,t){if(ys(this,rs,"m",ls).call(this,e).done_tool_calls.has(t))return;const s=e.message.tool_calls?.[t];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if("function"===s.type){const e=ys(this,os,"f")?.tools?.find((e=>"function"===e.type&&e.function.name===s.function.name));this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:t,arguments:s.function.arguments,parsed_arguments:It(e)?e.$parseRaw(s.function.arguments):e?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},ds=function(e){const t=ys(this,rs,"m",ls).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const s=ys(this,rs,"m",ps).call(this);this._emit("content.done",{content:e.message.content,parsed:s?s.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},fs=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");const e=ys(this,is,"f");if(!e)throw new O("request ended without sending any chunks");return gs(this,is,void 0,"f"),gs(this,as,[],"f"),function(e,t){const{id:s,choices:n,created:r,model:o,system_fingerprint:a,...i}=e,c={...i,id:s,choices:n.map((({message:t,finish_reason:s,index:n,logprobs:r,...o})=>{if(!s)throw new O(`missing finish_reason for choice ${n}`);const{content:a=null,function_call:i,tool_calls:c,...l}=t,u=t.role;if(!u)throw new O(`missing role for choice ${n}`);if(i){const{arguments:e,name:c}=i;if(null==e)throw new O(`missing function_call.arguments for choice ${n}`);if(!c)throw new O(`missing function_call.name for choice ${n}`);return{...o,message:{content:a,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}}return c?{...o,index:n,finish_reason:s,logprobs:r,message:{...l,role:u,content:a,refusal:t.refusal??null,tool_calls:c.map(((t,s)=>{const{function:r,type:o,id:a,...i}=t,{arguments:c,name:l,...u}=r||{};if(null==a)throw new O(`missing choices[${n}].tool_calls[${s}].id\n${_s(e)}`);if(null==o)throw new O(`missing choices[${n}].tool_calls[${s}].type\n${_s(e)}`);if(null==l)throw new O(`missing choices[${n}].tool_calls[${s}].function.name\n${_s(e)}`);if(null==c)throw new O(`missing choices[${n}].tool_calls[${s}].function.arguments\n${_s(e)}`);return{...i,id:a,type:o,function:{...u,name:l,arguments:c}}}))}}:{...o,message:{...l,content:a,role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}})),created:r,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return function(e,t){return t&&kt(t)?Rt(e,t):{...e,choices:e.choices.map((e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}})))}}(c,t)}(e,ys(this,os,"f"))},ps=function(){const e=ys(this,os,"f")?.response_format;return Pt(e)?e:null},ms=function(e){var t,s,n,r;let o=ys(this,is,"f");const{choices:a,...i}=e;o?Object.assign(o,i):o=gs(this,is,{...i,choices:[]},"f");for(const{delta:a,finish_reason:i,index:c,logprobs:l=null,...u}of e.choices){let e=o.choices[c];if(e||(e=o.choices[c]={finish_reason:i,index:c,message:{},logprobs:l,...u}),l)if(e.logprobs){const{content:n,refusal:r,...o}=l;Object.assign(e.logprobs,o),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),r&&((s=e.logprobs).refusal??(s.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},l);if(i&&(e.finish_reason=i,ys(this,os,"f")&&kt(ys(this,os,"f")))){if("length"===i)throw new J;if("content_filter"===i)throw new H}if(Object.assign(e,u),!a)continue;const{content:h,refusal:d,function_call:f,role:p,tool_calls:m,...g}=a;if(Object.assign(e.message,g),d&&(e.message.refusal=(e.message.refusal||"")+d),p&&(e.message.role=p),f&&(e.message.function_call?(f.name&&(e.message.function_call.name=f.name),f.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=f.arguments)):e.message.function_call=f),h&&(e.message.content=(e.message.content||"")+h,!e.message.refusal&&ys(this,rs,"m",ps).call(this)&&(e.message.parsed=ns(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:s,type:n,function:o,...a}of m){const i=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(i,a),s&&(i.id=s),n&&(i.type=n),o&&(i.function??(i.function={name:o.name??"",arguments:""})),o?.name&&(i.function.name=o.name),o?.arguments&&(i.function.arguments+=o.arguments,Ct(ys(this,os,"f"),i)&&(i.function.parsed_arguments=ns(i.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",(s=>{const n=t.shift();n?n.resolve(s):e.push(s)})),this.on("end",(()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),this.on("error",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise(((e,s)=>t.push({resolve:e,reject:s}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function _s(e){return JSON.stringify(e)}class bs extends ws{static fromReadableStream(e){const t=new bs(null);return t._run((()=>t._fromReadableStream(e))),t}static runFunctions(e,t,s){const n=new bs(null),r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,r))),n}static runTools(e,t,s){const n=new bs(t),r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,r))),n}}let vs=class extends He{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new O(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new O(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((t=>Rt(t,e)))}runFunctions(e,t){return e.stream?bs.runFunctions(this._client,e,t):Ut.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?bs.runTools(this._client,e,t):Ut.runTools(this._client,e,t)}stream(e,t){return ws.createChatCompletion(this._client,e,t)}};class xs extends He{constructor(){super(...arguments),this.completions=new vs(this._client)}}!function(e){e.Completions=vs}(xs||(xs={}));class Ss extends He{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class As extends He{constructor(){super(...arguments),this.sessions=new Ss(this._client)}}As.Sessions=Ss;var Es,Ps,Is,Rs,$s,Cs,ks,Os,Ts,js,Ms,qs,Ns,Ds,Bs,Ls,Fs,Ws,Us,Xs,Js,Hs,Vs=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)},Ks=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s};class zs extends Et{constructor(){super(...arguments),Es.add(this),Ps.set(this,[]),Is.set(this,{}),Rs.set(this,{}),$s.set(this,void 0),Cs.set(this,void 0),ks.set(this,void 0),Os.set(this,void 0),Ts.set(this,void 0),js.set(this,void 0),Ms.set(this,void 0),qs.set(this,void 0),Ns.set(this,void 0)}[(Ps=new WeakMap,Is=new WeakMap,Rs=new WeakMap,$s=new WeakMap,Cs=new WeakMap,ks=new WeakMap,Os=new WeakMap,Ts=new WeakMap,js=new WeakMap,Ms=new WeakMap,qs=new WeakMap,Ns=new WeakMap,Es=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",(s=>{const n=t.shift();n?n.resolve(s):e.push(s)})),this.on("end",(()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),this.on("error",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise(((e,s)=>t.push({resolve:e,reject:s}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new zs;return t._run((()=>t._fromReadableStream(e))),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const n=ee.fromReadableStream(e,this.controller);for await(const e of n)Vs(this,Es,"m",Ds).call(this,e);if(n.controller.signal?.aborted)throw new j;return this._addRun(Vs(this,Es,"m",Bs).call(this))}toReadableStream(){return new ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n,r){const o=new zs;return o._run((()=>o._runToolAssistantStream(e,t,s,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),o}async _createToolAssistantStream(e,t,s,n,r){const o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",(()=>this.controller.abort())));const a={...n,stream:!0},i=await e.submitToolOutputs(t,s,a,{...r,signal:this.controller.signal});this._connected();for await(const e of i)Vs(this,Es,"m",Ds).call(this,e);if(i.controller.signal?.aborted)throw new j;return this._addRun(Vs(this,Es,"m",Bs).call(this))}static createThreadAssistantStream(e,t,s){const n=new zs;return n._run((()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}static createAssistantStream(e,t,s,n){const r=new zs;return r._run((()=>r._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}currentEvent(){return Vs(this,Ms,"f")}currentRun(){return Vs(this,qs,"f")}currentMessageSnapshot(){return Vs(this,$s,"f")}currentRunStepSnapshot(){return Vs(this,Ns,"f")}async finalRunSteps(){return await this.done(),Object.values(Vs(this,Is,"f"))}async finalMessages(){return await this.done(),Object.values(Vs(this,Rs,"f"))}async finalRun(){if(await this.done(),!Vs(this,Cs,"f"))throw Error("Final run was not received.");return Vs(this,Cs,"f")}async _createThreadAssistantStream(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort())));const r={...t,stream:!0},o=await e.createAndRun(r,{...s,signal:this.controller.signal});this._connected();for await(const e of o)Vs(this,Es,"m",Ds).call(this,e);if(o.controller.signal?.aborted)throw new j;return this._addRun(Vs(this,Es,"m",Bs).call(this))}async _createAssistantStream(e,t,s,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const o={...s,stream:!0},a=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(const e of a)Vs(this,Es,"m",Ds).call(this,e);if(a.controller.signal?.aborted)throw new j;return this._addRun(Vs(this,Es,"m",Bs).call(this))}static accumulateDelta(e,t){for(const[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let t=e[s];if(null!=t)if("index"!==s&&"type"!==s){if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else{if(!Ue(t)||!Ue(n)){if(Array.isArray(t)&&Array.isArray(n)){if(t.every((e=>"string"==typeof e||"number"==typeof e))){t.push(...n);continue}for(const e of n){if(!Ue(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const s=e.index;if(null==s)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof s)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${s}`);const n=t[s];null==n?t.push(e):t[s]=this.accumulateDelta(n,e)}continue}throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${t}`)}t=this.accumulateDelta(t,n)}e[s]=t}else e[s]=n;else e[s]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n,r){return await this._createToolAssistantStream(s,e,t,n,r)}}Ds=function(e){if(!this.ended)switch(Ks(this,Ms,e,"f"),Vs(this,Es,"m",Ws).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Vs(this,Es,"m",Hs).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Vs(this,Es,"m",Fs).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":Vs(this,Es,"m",Ls).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Bs=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");if(!Vs(this,Cs,"f"))throw Error("Final run has not been received");return Vs(this,Cs,"f")},Ls=function(e){const[t,s]=Vs(this,Es,"m",Xs).call(this,e,Vs(this,$s,"f"));Ks(this,$s,t,"f"),Vs(this,Rs,"f")[t.id]=t;for(const e of s){const s=t.content[e.index];"text"==s?.type&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if("text"==s.type&&s.text){let e=s.text,n=t.content[s.index];if(!n||"text"!=n.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,n.text)}if(s.index!=Vs(this,ks,"f")){if(Vs(this,Os,"f"))switch(Vs(this,Os,"f").type){case"text":this._emit("textDone",Vs(this,Os,"f").text,Vs(this,$s,"f"));break;case"image_file":this._emit("imageFileDone",Vs(this,Os,"f").image_file,Vs(this,$s,"f"))}Ks(this,ks,s.index,"f")}Ks(this,Os,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==Vs(this,ks,"f")){const t=e.data.content[Vs(this,ks,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,Vs(this,$s,"f"));break;case"text":this._emit("textDone",t.text,Vs(this,$s,"f"))}}Vs(this,$s,"f")&&this._emit("messageDone",e.data),Ks(this,$s,void 0,"f")}},Fs=function(e){const t=Vs(this,Es,"m",Us).call(this,e);switch(Ks(this,Ns,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&"tool_calls"==s.step_details.type&&s.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of s.step_details.tool_calls)e.index==Vs(this,Ts,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(Vs(this,js,"f")&&this._emit("toolCallDone",Vs(this,js,"f")),Ks(this,Ts,e.index,"f"),Ks(this,js,t.step_details.tool_calls[e.index],"f"),Vs(this,js,"f")&&this._emit("toolCallCreated",Vs(this,js,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":Ks(this,Ns,void 0,"f");"tool_calls"==e.data.step_details.type&&Vs(this,js,"f")&&(this._emit("toolCallDone",Vs(this,js,"f")),Ks(this,js,void 0,"f")),this._emit("runStepDone",e.data,t)}},Ws=function(e){Vs(this,Ps,"f").push(e),this._emit("event",e)},Us=function(e){switch(e.event){case"thread.run.step.created":return Vs(this,Is,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Vs(this,Is,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const n=zs.accumulateDelta(t,s.delta);Vs(this,Is,"f")[e.data.id]=n}return Vs(this,Is,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":Vs(this,Is,"f")[e.data.id]=e.data}if(Vs(this,Is,"f")[e.data.id])return Vs(this,Is,"f")[e.data.id];throw new Error("No snapshot available")},Xs=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(const e of n.delta.content)if(e.index in t.content){let s=t.content[e.index];t.content[e.index]=Vs(this,Es,"m",Js).call(this,e,s)}else t.content[e.index]=e,s.push(e);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Js=function(e,t){return zs.accumulateDelta(t,e)},Hs=function(e){switch(Ks(this,qs,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":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":Ks(this,Cs,e.data,"f"),Vs(this,js,"f")&&(this._emit("toolCallDone",Vs(this,js,"f")),Ks(this,js,void 0,"f"))}};class Gs extends He{create(e,t,s){return this._client.post(`/threads/${e}/messages`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}retrieve(e,t,s){return this._client.get(`/threads/${e}/messages/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}update(e,t,s,n){return this._client.post(`/threads/${e}/messages/${t}`,{body:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},s){return Se(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Qs,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}del(e,t,s){return this._client.delete(`/threads/${e}/messages/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Qs extends Je{}Gs.MessagesPage=Qs;class Ys extends He{retrieve(e,t,s,n={},r){return Se(n)?this.retrieve(e,t,s,{},n):this._client.get(`/threads/${e}/runs/${t}/steps/${s}`,{query:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t,s={},n){return Se(s)?this.list(e,t,{},s):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Zs,{query:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class Zs extends Je{}Ys.RunStepsPage=Zs;class en extends He{constructor(){super(...arguments),this.steps=new Ys(this._client)}create(e,t,s){const{include:n,...r}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:n},body:r,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers},stream:t.stream??!1})}retrieve(e,t,s){return this._client.get(`/threads/${e}/runs/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}update(e,t,s,n){return this._client.post(`/threads/${e}/runs/${t}`,{body:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},s){return Se(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,tn,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}cancel(e,t,s){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(e,n.id,s)}createAndStream(e,t,s){return zs.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const n={...s?.headers,"X-Stainless-Poll-Helper":"true"};for(s?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){const{data:r,response:o}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await Oe(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,s){return zs.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s,n){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:s.stream??!1})}async submitToolOutputsAndPoll(e,t,s,n){const r=await this.submitToolOutputs(e,t,s,n);return await this.poll(e,r.id,n)}submitToolOutputsStream(e,t,s,n){return zs.createToolAssistantStream(e,t,this._client.beta.threads.runs,s,n)}}class tn extends Je{}en.RunsPage=tn,en.Steps=Ys,en.RunStepsPage=Zs;class sn extends He{constructor(){super(...arguments),this.runs=new en(this._client),this.messages=new Gs(this._client)}create(e={},t){return Se(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,s){return this._client.post(`/threads/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.thread_id,s.id,t)}createAndRunStream(e,t){return zs.createThreadAssistantStream(e,this._client.beta.threads,t)}}sn.Runs=en,sn.RunsPage=tn,sn.Messages=Gs,sn.MessagesPage=Qs;class nn extends He{constructor(){super(...arguments),this.realtime=new As(this._client),this.chat=new xs(this._client),this.assistants=new rt(this._client),this.threads=new sn(this._client)}}nn.Realtime=As,nn.Assistants=rt,nn.AssistantsPage=ot,nn.Threads=sn;class rn extends He{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class on extends He{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}let an=class extends He{create(e,t){return this._client.post("/files",le({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return Se(e)?this.list({},e):this._client.getAPIList("/files",cn,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){const n=new Set(["processed","error","deleted"]),r=Date.now();let o=await this.retrieve(e);for(;!o.status||!n.has(o.status);)if(await Oe(t),o=await this.retrieve(e),Date.now()-r>s)throw new q({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return o}};class cn extends Je{}an.FileObjectsPage=cn;class ln extends He{list(e,t={},s){return Se(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,un,{query:t,...s})}}class un extends Je{}ln.FineTuningJobCheckpointsPage=un;class hn extends He{constructor(){super(...arguments),this.checkpoints=new ln(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return Se(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",dn,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return Se(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,fn,{query:t,...s})}}class dn extends Je{}class fn extends Je{}hn.FineTuningJobsPage=dn,hn.FineTuningJobEventsPage=fn,hn.Checkpoints=ln,hn.FineTuningJobCheckpointsPage=un;class pn extends He{constructor(){super(...arguments),this.jobs=new hn(this._client)}}pn.Jobs=hn,pn.FineTuningJobsPage=dn,pn.FineTuningJobEventsPage=fn;class mn extends He{createVariation(e,t){return this._client.post("/images/variations",le({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",le({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class gn extends He{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",yn,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class yn extends Xe{}gn.ModelsPage=yn;class wn extends He{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function _n(e,t){return t&&function(e){if(Pt(e.text?.format))return!0;return!1}(t)?bn(e,t):{...e,output_parsed:null,output:e.output.map((e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map((e=>({...e,parsed:null})))}:e))}}function bn(e,t){const s=e.output.map((e=>{if("function_call"===e.type)return{...e,parsed_arguments:xn(t,e)};if("message"===e.type){const s=e.content.map((e=>"output_text"===e.type?{...e,parsed:vn(t,e.text)}:e));return{...e,content:s}}return e})),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||Sn(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const e of n.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),n}function vn(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const s=e.text?.format;return s.$parseRaw(t)}return JSON.parse(t)}function xn(e,t){const s=(n=e.tools??[],r=t.name,n.find((e=>"function"===e.type&&e.name===r)));var n,r,o;return{...t,...t,parsed_arguments:(o=s,"auto-parseable-tool"===o?.$brand?s.$parseRaw(t.arguments):s?.strict?JSON.parse(t.arguments):null)}}function Sn(e){const t=[];for(const s of e.output)if("message"===s.type)for(const e of s.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}class An extends He{list(e,t={},s){return Se(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Nn,{query:t,...s})}}var En,Pn,In,Rn,$n,Cn,kn,On,Tn=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},jn=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)};class Mn extends Et{constructor(e){super(),En.add(this),Pn.set(this,void 0),In.set(this,void 0),Rn.set(this,void 0),Tn(this,Pn,e,"f")}static createResponse(e,t,s){const n=new Mn(t);return n._run((()=>n._createResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createResponse(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),jn(this,En,"m",$n).call(this);const r=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const e of r)jn(this,En,"m",Cn).call(this,e);if(r.controller.signal?.aborted)throw new j;return jn(this,En,"m",kn).call(this)}[(Pn=new WeakMap,In=new WeakMap,Rn=new WeakMap,En=new WeakSet,$n=function(){this.ended||Tn(this,In,void 0,"f")},Cn=function(e){if(this.ended)return;const t=jn(this,En,"m",On).call(this,e);switch(this._emit("event",e),e.type){case"response.output_text.delta":{const s=t.output[e.output_index];if(!s)throw new O(`missing output at index ${e.output_index}`);if("message"===s.type){const t=s.content[e.content_index];if(!t)throw new O(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new O(`expected content to be 'output_text', got ${t.type}`);this._emit("response.output_text.delta",{...e,snapshot:t.text})}break}case"response.function_call_arguments.delta":{const s=t.output[e.output_index];if(!s)throw new O(`missing output at index ${e.output_index}`);"function_call"===s.type&&this._emit("response.function_call_arguments.delta",{...e,snapshot:s.arguments});break}default:this._emit(e.type,e)}},kn=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");const e=jn(this,In,"f");if(!e)throw new O("request ended without sending any events");Tn(this,In,void 0,"f");const t=function(e,t){return _n(e,t)}(e,jn(this,Pn,"f"));return Tn(this,Rn,t,"f"),t},On=function(e){let t=jn(this,In,"f");if(!t){if("response.created"!==e.type)throw new O(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=Tn(this,In,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const s=t.output[e.output_index];if(!s)throw new O(`missing output at index ${e.output_index}`);"message"===s.type&&s.content.push(e.part);break}case"response.output_text.delta":{const s=t.output[e.output_index];if(!s)throw new O(`missing output at index ${e.output_index}`);if("message"===s.type){const t=s.content[e.content_index];if(!t)throw new O(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new O(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const s=t.output[e.output_index];if(!s)throw new O(`missing output at index ${e.output_index}`);"function_call"===s.type&&(s.arguments+=e.delta);break}case"response.completed":Tn(this,In,e.response,"f")}return t},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",(s=>{const n=t.shift();n?n.resolve(s):e.push(s)})),this.on("end",(()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),this.on("error",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise(((e,s)=>t.push({resolve:e,reject:s}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=jn(this,Rn,"f");if(!e)throw new O("stream ended without producing a ChatCompletion");return e}}class qn extends He{constructor(){super(...arguments),this.inputItems=new An(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((e=>("object"in e&&"response"===e.object&&Sn(e),e)))}retrieve(e,t={},s){return Se(t)?this.retrieve(e,{},t):this._client.get(`/responses/${e}`,{query:t,...s})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((t=>bn(t,e)))}stream(e,t){return Mn.createResponse(this._client,e,t)}}class Nn extends Je{}qn.InputItems=An;class Dn extends He{create(e,t,s){return this._client.post(`/uploads/${e}/parts`,le({body:t,...s}))}}class Bn extends He{constructor(){super(...arguments),this.parts=new Dn(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(`/uploads/${e}/complete`,{body:t,...s})}}Bn.Parts=Dn;class Ln extends He{create(e,t,s){return this._client.post(`/vector_stores/${e}/files`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}retrieve(e,t,s){return this._client.get(`/vector_stores/${e}/files/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}update(e,t,s,n){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},s){return Se(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,Fn,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}del(e,t,s){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){const n={...s?.headers,"X-Stainless-Poll-Helper":"true"};for(s?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){const r=await this.retrieve(e,t,{...s,headers:n}).withResponse(),o=r.data;switch(o.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await Oe(e);break;case"failed":case"completed":return o}}}async upload(e,t,s){const n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){const n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Wn,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Fn extends Je{}class Wn extends Xe{}Ln.VectorStoreFilesPage=Fn,Ln.FileContentResponsesPage=Wn;class Un extends He{create(e,t,s){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}retrieve(e,t,s){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}cancel(e,t,s){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async createAndPoll(e,t,s){const n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s={},n){return Se(s)?this.listFiles(e,t,{},s):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,Fn,{query:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async poll(e,t,s){const n={...s?.headers,"X-Stainless-Poll-Helper":"true"};for(s?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){const{data:r,response:o}=await this.retrieve(e,t,{...s,headers:n}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await Oe(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const r=n?.maxConcurrency??5,o=Math.min(r,t.length),a=this._client,i=t.values(),c=[...s];const l=Array(o).fill(i).map((async function(e){for(let t of e){const e=await a.files.create({file:t,purpose:"assistants"},n);c.push(e.id)}}));return await(async e=>{const t=await Promise.allSettled(e),s=t.filter((e=>"rejected"===e.status));if(s.length){for(const e of s)console.error(e.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n})(l),await this.createAndPoll(e,{file_ids:c})}}class Xn extends He{constructor(){super(...arguments),this.files=new Ln(this._client),this.fileBatches=new Un(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,s){return this._client.post(`/vector_stores/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e={},t){return Se(e)?this.list({},e):this._client.getAPIList("/vector_stores",Jn,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,s){return this._client.getAPIList(`/vector_stores/${e}/search`,Hn,{body:t,method:"post",...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Jn extends Je{}class Hn extends Xe{}var Vn;Xn.VectorStoresPage=Jn,Xn.VectorStoreSearchResponsesPage=Hn,Xn.Files=Ln,Xn.VectorStoreFilesPage=Fn,Xn.FileContentResponsesPage=Wn,Xn.FileBatches=Un;class Kn extends we{constructor({baseURL:e=Me("OPENAI_BASE_URL"),apiKey:t=Me("OPENAI_API_KEY"),organization:s=Me("OPENAI_ORG_ID")??null,project:n=Me("OPENAI_PROJECT_ID")??null,...r}={}){if(void 0===t)throw new O("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 o={apiKey:t,organization:s,project:n,...r,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new O("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new rn(this),this.chat=new Qe(this),this.embeddings=new on(this),this.files=new an(this),this.images=new mn(this),this.audio=new tt(this),this.moderations=new wn(this),this.models=new gn(this),this.fineTuning=new pn(this),this.vectorStores=new Xn(this),this.beta=new nn(this),this.batches=new st(this),this.uploads=new Bn(this),this.responses=new qn(this),this._options=o,this.apiKey=t,this.organization=s,this.project=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return _(e,{arrayFormat:"brackets"})}}function zn({msg:e,isError:t,isInfinite:s}){const n=document.querySelector("#message");n.style.color=t?"red":"limegreen",n.textContent=e,n.style.display="block",s||setTimeout((()=>n.style.display="none"),5e3)}Vn=Kn,Kn.OpenAI=Vn,Kn.DEFAULT_TIMEOUT=6e5,Kn.OpenAIError=O,Kn.APIError=T,Kn.APIConnectionError=M,Kn.APIConnectionTimeoutError=q,Kn.APIUserAbortError=j,Kn.NotFoundError=L,Kn.ConflictError=F,Kn.RateLimitError=U,Kn.BadRequestError=N,Kn.AuthenticationError=D,Kn.InternalServerError=X,Kn.PermissionDeniedError=B,Kn.UnprocessableEntityError=W,Kn.toFile=oe,Kn.fileFromPath=R,Kn.Completions=rn,Kn.Chat=Qe,Kn.ChatCompletionsPage=ze,Kn.Embeddings=on,Kn.Files=an,Kn.FileObjectsPage=cn,Kn.Images=mn,Kn.Audio=tt,Kn.Moderations=wn,Kn.Models=gn,Kn.ModelsPage=yn,Kn.FineTuning=pn,Kn.VectorStores=Xn,Kn.VectorStoresPage=Jn,Kn.VectorStoreSearchResponsesPage=Hn,Kn.Beta=nn,Kn.Batches=st,Kn.BatchesPage=nt,Kn.Uploads=Bn,Kn.Responses=qn;const Gn=document.querySelector("#apiKey"),Qn=document.querySelector("#model"),Yn=document.querySelector("#models"),Zn=document.querySelector("#includeImages-line"),er=document.querySelector("#baseURL");function tr(){!function(e){const t=e.match(/gpt-(\d+)/);return!!(null==t?void 0:t[1])&&Number(t[1])>=4}(Qn.value)?Zn.style.display="none":Zn.style.display="flex"}Qn.addEventListener("input",tr),Qn.addEventListener("focus",(function(){return n(this,void 0,void 0,(function*(){var e,t;const s=null===(e=Gn.value)||void 0===e?void 0:e.trim(),n=null===(t=er.value)||void 0===t?void 0:t.trim();if(s){Qn.innerHTML="";try{const e=new Kn({apiKey:s,baseURL:n,dangerouslyAllowBrowser:!0}),t=(yield e.models.list()).data.filter((e=>e.id.startsWith("gpt")||e.id.startsWith("o1")||e.id.startsWith("chatgpt")));t.sort(((e,t)=>t.id.localeCompare(e.id)));for(const e of t){const t=document.createElement("option");t.value=e.id,t.textContent=e.id,Yn.appendChild(t)}tr()}catch(e){console.error(e),zn({msg:e,isError:!0})}}}))}));document.querySelector("#check-model").addEventListener("click",(function(){return n(this,void 0,void 0,(function*(){var e,t,s;const n=null===(e=Qn.value)||void 0===e?void 0:e.trim(),r=null===(t=Gn.value)||void 0===t?void 0:t.trim(),o=null===(s=er.value)||void 0===s?void 0:s.trim();try{const e=new Kn({apiKey:r,baseURL:o,dangerouslyAllowBrowser:!0});yield e.chat.completions.create({model:n,messages:[{role:"user",content:"reply just pong"}]}),zn({msg:"The model is valid!"})}catch(e){zn({msg:e,isError:!0})}}))}));const sr=["includeImages"],nr={autocomplete:[],clipboard:["typing","mouseover"],"question-to-answer":["typing","infinite","mouseover"]};function rr(){const s=nr[e.actualMode],n=t.filter((e=>!s.includes(e)&&!sr.includes(e)));for(const e of s)document.querySelector("#"+e).parentElement.style.display="none";for(const e of n)document.querySelector("#"+e).parentElement.style.display=""}for(const t of s)t.addEventListener("click",(function(){const n=t.value;e.actualMode=n;for(const e of s)e.value!==n?e.classList.add("not-selected"):e.classList.remove("not-selected");rr()}));const or="1.1.2",ar=document.querySelector("#version");function ir(e,t=!0){if(t)return void(ar.textContent="v"+e);const s=document.createElement("a");s.href="https://github.com/yoannchb-pro/MoodleGPT",s.rel="noopener noreferrer",s.target="_blank",s.textContent="v"+e,ar.appendChild(s),ar.appendChild(document.createTextNode(" is now available !"))}!function(){n(this,void 0,void 0,(function*(){const e=yield function(){return n(this,void 0,void 0,(function*(){const e=yield fetch("https://raw.githubusercontent.com/yoannchb-pro/MoodleGPT/main/package.json");return(yield e.json()).version}))}().catch((e=>(console.error(e),or))),t=e.split("."),s=or.split("."),r=Math.min(t.length,s.length);for(let n=0;n<r;++n){if(parseInt(t[n])>parseInt(s[n]))return ir(e,!1);if(parseInt(s[n])>parseInt(t[n]))return ir(or)}ir(or)}))}();const cr=document.querySelector("#settings"),lr=document.querySelector("#advanced-settings"),ur=document.querySelector("#switch-settings");ur.addEventListener("click",(function(e){e.preventDefault(),"flex"===lr.style.display?(cr.style.display="flex",lr.style.display="none",ur.textContent="Advanced settings"):(cr.style.display="none",lr.style.display="flex",ur.textContent="Go back to settings")}));const hr=document.querySelector(".save"),dr=["apiKey","code","model","baseURL","maxTokens"];hr.addEventListener("click",(function(){const[s,n,r,o,a]=dr.map((e=>document.querySelector("#"+e).value.trim())),[i,c,l,u,h,d,f,p,m]=t.map((e=>{const t=document.querySelector("#"+e);return t.checked&&"none"!==t.parentElement.style.display}));s&&r?n.length>0&&n.length<2?zn({msg:"The code should at least contain 2 characters",isError:!0}):(chrome.storage.sync.set({moodleGPT:{apiKey:s,code:n,model:r,baseURL:o,maxTokens:a?parseInt(a):void 0,logs:i,title:c,cursor:l,typing:u,mouseover:h,infinite:d,timeout:f,history:p,includeImages:m,mode:e.actualMode}}),zn({msg:"Configuration saved"})):zn({msg:"Please complete all the form",isError:!0})})),chrome.storage.sync.get(["moodleGPT"]).then((function(n){const r=n.moodleGPT;if(r){if(r.mode){e.actualMode=r.mode;for(const e of s)e.value===r.mode?e.classList.remove("not-selected"):e.classList.add("not-selected")}dr.forEach((e=>r[e]?document.querySelector("#"+e).value=r[e]:null)),t.forEach((e=>document.querySelector("#"+e).checked=r[e]||""))}rr(),tr()}))}));
|
|
//# sourceMappingURL=popup.js.map
|