3 lines
95 KiB
JavaScript
3 lines
95 KiB
JavaScript
!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e){const t=document.title;document.title=e,setTimeout((()=>document.title=t),3e3)}function t(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{l(s.next(e))}catch(e){o(e)}}function a(e){try{l(s.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((s=s.apply(e,t||[])).next())}))}function n(e,t){const n=e.length>t.length?e.length:t.length;return 0===n?1:(n-function(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;const n=[],s=e.replace(/\s+/,""),r=t.replace(/\s+/,"");for(let e=0;e<=s.length;++e){n.push([e]);for(let t=1;t<=r.length;++t)n[e][t]=0===e?t:Math.min(n[e-1][t]+1,n[e][t-1]+1,n[e-1][t-1]+(s[e-1]===r[t-1]?0:1))}return n[s.length][r.length]}(e,t))/n}function s(e,t){let s={element:null,similarity:0,value:null};for(const r of t){const t=n(r.value,e);if(1===t)return{element:r.element,value:r.value,similarity:t};t>s.similarity&&(s={element:r.element,value:r.value,similarity:t})}return s}"function"==typeof SuppressedError&&SuppressedError;class r{static question(e){console.log("%c[QUESTION]: %s","color: cyan",e)}static bestAnswer(e,t){console.log("%c[BEST ANSWER]: %s","color: green",`"${e}" with a similarity of ${function(e){return Math.round(100*e*100)/100+"%"}(t)}`)}static array(e){console.log("[CORRECTS] ",e)}static response(e){console.log("Original:\n"+e.response),console.log("Normalized:\n"+e.normalizedResponse)}}function o(e,t=!0){t&&(e=e.toLowerCase());return e.replace(/\n+/gi,"\n").replace(/(\n\s*\n)+/g,"\n").replace(/[ \t]+/gi," ").trim().replace(/^[a-z\d]\.\s/gi,"").replace(/\n[a-z\d]\.\s/gi,"\n")}const i={role:"system",content:"\nAct as a quiz solver for the best notation with the following rules:\n- If no answer(s) are given, answer the statement as usual without following the other rules, providing the most detailed, complete and precise explanation. \n- But for the calculation provide this format 'result: <result of the equation>'\n- For 'put in order' questions, maintain the answer in the order as presented in the question but assocy the correct order to it by usin this format '<order>:<answer 1>\n<order>:<answer 2>', ignore other rules.\n- Always reply in the format: '<answer 1>\n<answer 2>\n...'.\n- Retain only the correct answer(s).\n- Maintain the same order for the answers as in the text.\n- Retain all text from the answer with its description, content or definition.\n- Only provide answers that exactly match the given answer in the text.\n- The question always has the correct answer(s), so you should always provide an answer.\n- Always respond in the same language as the user's question.\n".trim()};function a(e,n,s){return t(this,void 0,void 0,(function*(){const t=n.querySelectorAll("img");if(!e.includeImages||!function(e){const t=e.match(/gpt-(\d+)/);return!!(null==t?void 0:t[1])&&Number(t[1])>=4}(e.model)||0===t.length)return s;const r=[],o=Array.from(t).map((e=>function(e,t=.75){return new Promise(((n,s)=>{const r=document.createElement("canvas"),o=r.getContext("2d");if(!o)return s("Can't get the canvas context, ensure your navigator support canvas"),void r.remove();const i=new Image;i.crossOrigin="Anonymous",i.onload=()=>{r.width=i.width,r.height=i.height,o.drawImage(i,0,0);const e=r.toDataURL("image/png",t);n(e),r.remove()},i.onerror=e=>{s(e),r.remove()},i.src=e.src}))}(e))),i=yield Promise.allSettled(o);for(const t of i)"fulfilled"===t.status?r.push({type:"image_url",image_url:{url:t.value}}):e.logs&&console.error(t.reason);return r.push({type:"text",text:s}),r}))}function l(e,n,s){return t(this,void 0,void 0,(function*(){const t={role:"user",content:yield a(e,n,s)};if(!e.history)return{messages:[i,t]};let r;const o=function(){var e;return JSON.parse(null!==(e=sessionStorage.moodleGPTHistory)&&void 0!==e?e:"null")}(),l=function(){var e,t;const n=new URLSearchParams(document.location.search);return{host:document.location.host,cmid:null!==(e=n.get("cmid"))&&void 0!==e?e:"",attempt:null!==(t=n.get("attempt"))&&void 0!==t?t:"",history:[]}}();return r=null!==o&&function(e,t){const n=["host","cmid","attempt"];for(const s of n)if(e[s]!==t[s])return!1;return!0}(o,l)?o:l,{messages:[i,...r.history,t],saveResponse(n){e.history&&(r.history.push(t),r.history.push({role:"assistant",content:n}),sessionStorage.moodleGPTHistory=JSON.stringify(r))}}}))}const c="RFC3986",u={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},h=Array.isArray,d=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),f=1024;function p(e,t){if(h(e)){const n=[];for(let s=0;s<e.length;s+=1)n.push(t(e[s]));return n}return t(e)}const m=Object.prototype.hasOwnProperty,g={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},y=Array.isArray,w=Array.prototype.push,b=function(e,t){w.apply(e,y(t)?t:[t])},_=Date.prototype.toISOString,v={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,n,s,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"===n)return escape(o).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));let i="";for(let e=0;e<o.length;e+=f){const t=o.length>=f?o.slice(e,e+f):o,n=[];for(let e=0;e<t.length;++e){let s=t.charCodeAt(e);45===s||46===s||95===s||126===s||s>=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||"RFC1738"===r&&(40===s||41===s)?n[n.length]=t.charAt(e):s<128?n[n.length]=d[s]:s<2048?n[n.length]=d[192|s>>6]+d[128|63&s]:s<55296||s>=57344?n[n.length]=d[224|s>>12]+d[128|s>>6&63]+d[128|63&s]:(e+=1,s=65536+((1023&s)<<10|1023&t.charCodeAt(e)),n[n.length]=d[240|s>>18]+d[128|s>>12&63]+d[128|s>>6&63]+d[128|63&s])}i+=n.join("")}return i},encodeValuesOnly:!1,format:c,formatter:u[c],indices:!1,serializeDate:e=>_.call(e),skipNulls:!1,strictNullHandling:!1};const x={};function S(e,t,n,s,r,o,i,a,l,c,u,h,d,f,m,g,w,_){let A=e,E=_,R=0,k=!1;for(;void 0!==(E=E.get(x))&&!k;){const t=E.get(e);if(R+=1,void 0!==t){if(t===R)throw new RangeError("Cyclic object value");k=!0}void 0===E.get(x)&&(R=0)}if("function"==typeof c?A=c(t,A):A instanceof Date?A=d?.(A):"comma"===n&&y(A)&&(A=p(A,(function(e){return e instanceof Date?d?.(e):e}))),null===A){if(o)return l&&!g?l(t,v.encoder,w,"key",f):t;A=""}if("string"==typeof(C=A)||"number"==typeof C||"boolean"==typeof C||"symbol"==typeof C||"bigint"==typeof C||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(A)){if(l){const e=g?t:l(t,v.encoder,w,"key",f);return[m?.(e)+"="+m?.(l(A,v.encoder,w,"value",f))]}return[m?.(t)+"="+m?.(String(A))]}var C;const P=[];if(void 0===A)return P;let I;if("comma"===n&&y(A))g&&l&&(A=p(A,l)),I=[{value:A.length>0?A.join(",")||null:void 0}];else if(y(c))I=c;else{const e=Object.keys(A);I=u?e.sort(u):e}const O=a?String(t).replace(/\./g,"%2E"):String(t),$=s&&y(A)&&1===A.length?O+"[]":O;if(r&&y(A)&&0===A.length)return $+"[]";for(let t=0;t<I.length;++t){const p=I[t],v="object"==typeof p&&void 0!==p.value?p.value:A[p];if(i&&null===v)continue;const E=h&&a?p.replace(/\./g,"%2E"):p,k=y(A)?"function"==typeof n?n($,E):$:$+(h?"."+E:"["+E+"]");_.set(e,R);const C=new WeakMap;C.set(x,_),b(P,S(v,k,n,s,r,o,i,a,"comma"===n&&g&&y(A)?null:l,c,u,h,d,f,m,g,w,C))}return P}function A(e,t={}){let n=e;const s=function(e=v){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||v.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 n=c;if(void 0!==e.format){if(!m.call(u,e.format))throw new TypeError("Unknown format option provided.");n=e.format}const s=u[n];let r,o=v.filter;if(("function"==typeof e.filter||y(e.filter))&&(o=e.filter),r=e.arrayFormat&&e.arrayFormat in g?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":v.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=void 0===e.allowDots?1==!!e.encodeDotInKeys||v.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:v.addQueryPrefix,allowDots:i,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:v.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:v.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?v.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:v.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:v.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:v.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:v.encodeValuesOnly,filter:o,format:n,formatter:s,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:v.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:v.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:v.strictNullHandling}}(t);let r,o;"function"==typeof s.filter?(o=s.filter,n=o("",n)):y(s.filter)&&(o=s.filter,r=o);const i=[];if("object"!=typeof n||null===n)return"";const a=g[s.arrayFormat],l="comma"===a&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const h=new WeakMap;for(let e=0;e<r.length;++e){const t=r[e];s.skipNulls&&null===n[t]||b(i,S(n[t],t,a,l,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,h))}const d=i.join(s.delimiter);let f=!0===s.addQueryPrefix?"?":"";return s.charsetSentinel&&("iso-8859-1"===s.charset?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),d.length>0?f+d:""}const E="4.82.0";let R,k,C,P,I,O,$,T,j,q=!1;class M{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}R||function(e,t={auto:!1}){if(q)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(R)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${R}'\``);q=t.auto,R=e.kind,k=e.fetch,C=e.FormData,P=e.File,I=e.ReadableStream,O=e.getMultipartRequestOptions,$=e.getDefaultAgent,T=e.fileFromPath,j=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 n,s,r,o;try{n=fetch,s=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:n,Request:s,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 M(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 N extends Error{}class L extends N{constructor(e,t,n,s){super(`${L.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["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,n){const s=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new B({message:n,cause:qe(t)});const r=t?.error;return 400===e?new W(e,r,n,s):401===e?new U(e,r,n,s):403===e?new X(e,r,n,s):404===e?new H(e,r,n,s):409===e?new J(e,r,n,s):422===e?new V(e,r,n,s):429===e?new K(e,r,n,s):e>=500?new z(e,r,n,s):new L(e,r,n,s)}}class D extends L{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class B extends L{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class F extends B{constructor({message:e}={}){super({message:e??"Request timed out."})}}class W extends L{}class U extends L{}class X extends L{}class H extends L{}class J extends L{}class V extends L{}class K extends L{}class z extends L{}class Q extends N{constructor(){super("Could not parse response content as the length limit was reached")}}class G extends N{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Y{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];const n=Y.NEWLINE_CHARS.has(t[t.length-1]||"");let s=t.split(Y.NEWLINE_REGEXP);return n&&s.pop(),1!==s.length||n?(this.buffer.length>0&&(s=[this.buffer.join("")+s[0],...s.slice(1)],this.buffer=[]),n||(this.buffer=[s.pop()||""]),s):(this.buffer.push(s[0]),[])}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 N(`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 N(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new N("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}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}}}Y.NEWLINE_CHARS=new Set(["\n","\r"]),Y.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class ee{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;return new ee((async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const n of async function*(e,t){if(!e.body)throw t.abort(),new N("Attempted to iterate over a response with no body");const n=new ne,s=new Y,r=Z(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?(new TextEncoder).encode(n):n;let s,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(s=te(t));)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}(r))for(const t of s.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of s.flush()){const t=n.decode(e);t&&(yield t)}}(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null===n.event){let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if(e&&e.error)throw new L(void 0,e.error,void 0,void 0);yield e}else{let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if("error"==n.event)throw new L(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}s=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{s||t.abort()}}),t)}static fromReadableStream(e,t){let n=!1;return new ee((async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const t of async function*(){const t=new Y,n=Z(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{s||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=s=>({next:()=>{if(0===s.length){const s=n.next();e.push(s),t.push(s)}return s.shift()}});return[new ee((()=>s(e)),this.controller),new ee((()=>s(t)),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new I({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:r}=await t.next();if(r)return e.close();const o=n.encode(JSON.stringify(s)+"\n");e.enqueue(o)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}function te(e){for(let t=0;t<e.length-2;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}class ne{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,n,s]=function(e,t){const n=e.indexOf(t);if(-1!==n)return[e.substring(0,n),t,e.substring(n+t.length)];return[e,"",""]}(e,":");return s.startsWith(" ")&&(s=s.substring(1)),"event"===t?this.event=s:"data"===t&&this.data.push(s),null}}const se=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,re=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&oe(e),oe=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 ie(e,t,n){if(e=await e,re(e))return e;if(se(e)){const s=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const r=oe(s)?[await s.arrayBuffer()]:[s];return new P(r,t,n)}const s=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(oe(e))t.push(await e.arrayBuffer());else{if(!le(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 n of e)t.push(n)}return t}(e);if(t||(t=function(e){return ae(e.name)||ae(e.filename)||ae(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!n?.type){const e=s[0]?.type;"string"==typeof e&&(n={...n,type:e})}return new P(s,t,n)}const ae=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,le=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],ce=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],ue=async e=>{const t=await he(e.body);return O(t,e)},he=async e=>{const t=new C;return await Promise.all(Object.entries(e||{}).map((([e,n])=>de(t,e,n)))),t},de=async(e,t,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(t,String(n));else if((e=>re(e)||se(e)||j(e))(n)){const s=await ie(n);e.append(t,s)}else if(Array.isArray(n))await Promise.all(n.map((n=>de(e,t+"[]",n))));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map((([n,s])=>de(e,`${t}[${n}]`,s))))}}};var fe,pe=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!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"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},me=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};async function ge(e){const{response:t}=e;if(e.options.stream)return Fe("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 n=t.headers.get("content-type");if(n?.includes("application/json")||n?.includes("application/vnd.api+json")){const e=await t.json();return Fe("response",t.status,t.url,t.headers,e),ye(e,t)}const s=await t.text();return Fe("response",t.status,t.url,t.headers,s),s}function ye(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 we extends Promise{constructor(e,t=ge){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new we(this.responsePromise,(async t=>ye(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 be{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:r}){this.baseURL=e,this.maxRetries=je("maxRetries",t),this.timeout=je("timeout",n),this.httpAgent=s,this.fetch=r??k}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Pe(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${We()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then((async n=>{const s=n&&oe(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:s}})))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}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}={}){const{method:n,path:s,query:r,headers:o={}}=e,i=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,a=this.calculateContentLength(i),l=this.buildURL(s,r);"timeout"in e&&je("timeout",e.timeout);const c=e.timeout??this.timeout,u=e.httpAgent??this.httpAgent??$(l),h=c+1e3;"number"==typeof u?.options?.timeout&&h>(u.options.timeout??0)&&(u.options.timeout=h),this.idempotencyHeader&&"get"!==n&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:n,...i&&{body:i},headers:this.buildHeaders({options:e,headers:o,contentLength:a,retryCount:t}),...u&&{agent:u},signal:e.signal??null},url:l,timeout:c}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const r={};n&&(r["content-length"]=n);const o=this.defaultHeaders(e);return De(r,o),De(r,t),ce(e.body)&&"node"!==R&&delete r["content-type"],void 0===Ue(o,"x-stainless-retry-count")&&void 0===Ue(t,"x-stainless-retry-count")&&(r["x-stainless-retry-count"]=String(s)),this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,n,s){return L.generate(e,t,n,s)}request(e,t=null){return new we(this.makeRequest(e,t))}async makeRequest(e,t){const n=await e,s=n.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(n);const{req:r,url:o,timeout:i}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(r,{url:o,options:n}),Fe("request",o,n,r.headers),n.signal?.aborted)throw new D;const a=new AbortController,l=await this.fetchWithTimeout(o,r,i,a).catch(qe);if(l instanceof Error){if(n.signal?.aborted)throw new D;if(t)return this.retryRequest(n,t);if("AbortError"===l.name)throw new F;throw new B({cause:l})}const c=xe(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){return Fe(`response (error; ${`retrying, ${t} attempts remaining`})`,l.status,o,c),this.retryRequest(n,t,c)}const e=await l.text().catch((e=>qe(e).message)),s=Ie(e),r=s?void 0:e;Fe(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,o,c,r);throw this.makeStatusError(l.status,s,r,c)}return{response:l,options:n,controller:a}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new ve(this,n,e)}buildURL(e,t){const n=$e(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Ne(s)||(t={...s,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.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 N(`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,n,s){const{signal:r,...o}=t||{};r&&r.addEventListener("abort",(()=>s.abort()));const i=setTimeout((()=>s.abort()),n),a={signal:s.signal,...o};return a.method&&(a.method=a.method.toUpperCase()),this.fetch.call(void 0,e,a).finally((()=>{clearTimeout(i)}))}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,n){let s;const r=n?.["retry-after-ms"];if(r){const e=parseFloat(r);Number.isNaN(e)||(s=e)}const o=n?.["retry-after"];if(o&&!s){const e=parseFloat(o);s=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const n=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Te(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${E}`}}class _e{constructor(e,t,n,s){fe.set(this,void 0),pe(this,fe,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new N("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 n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,s]of n)e.url.searchParams.set(t,s);t.query=void 0,t.path=e.url.toString()}return await me(this,fe,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(fe=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class ve extends we{constructor(e,t,n){super(t,(async t=>new n(e,t.response,await ge(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const xe=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),Se={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},Ae=e=>"object"==typeof e&&null!==e&&!Ne(e)&&Object.keys(e).every((e=>Le(Se,e))),Ee=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E,"X-Stainless-OS":ke(Deno.build.os),"X-Stainless-Arch":Re(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":E,"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":E,"X-Stainless-OS":ke(process.platform),"X-Stainless-Arch":Re(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:n}of e){const e=n.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":E,"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":E,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Re=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ke=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 Ce;const Pe=()=>Ce??(Ce=Ee()),Ie=e=>{try{return JSON.parse(e)}catch(e){return}},Oe=/^[a-z][a-z0-9+.-]*:/i,$e=e=>Oe.test(e),Te=e=>new Promise((t=>setTimeout(t,e))),je=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new N(`${e} must be an integer`);if(t<0)throw new N(`${e} must be a positive integer`);return t},qe=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 Ne(e){if(!e)return!0;for(const t in e)return!1;return!0}function Le(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function De(e,t){for(const n in t){if(!Le(t,n))continue;const s=n.toLowerCase();if(!s)continue;const r=t[n];null===r?delete e[s]:void 0!==r&&(e[s]=r)}}const Be=new Set(["authorization","api-key"]);function Fe(e,...t){if("undefined"!=typeof process&&"true"===process?.env?.DEBUG){const n=t.map((e=>{if(!e)return e;if(e.headers){const t={...e,headers:{...e.headers}};for(const n in e.headers)Be.has(n.toLowerCase())&&(t.headers[n]="REDACTED");return t}let t=null;for(const n in e)Be.has(n.toLowerCase())&&(t??(t={...e}),t[n]="REDACTED");return t??e}));console.log(`OpenAI:DEBUG:${e}`,...n)}}const We=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),Ue=(e,t)=>{const n=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const s=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,n)=>t+n.toUpperCase()));for(const r of[t,n,t.toUpperCase(),s]){const t=e.get(r);if(t)return t}}for(const[s,r]of Object.entries(e))if(s.toLowerCase()===n)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 Xe(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class He extends _e{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class Je extends _e{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[]}getPaginatedItems(){return this.data??[]}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 Ve{constructor(e){this._client=e}}let Ke=class extends Ve{create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}},ze=class extends Ve{constructor(){super(...arguments),this.completions=new Ke(this._client)}};ze.Completions=Ke;class Qe extends Ve{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class Ge extends Ve{create(e,t){return this._client.post("/audio/transcriptions",ue({body:e,...t}))}}class Ye extends Ve{create(e,t){return this._client.post("/audio/translations",ue({body:e,...t}))}}class Ze extends Ve{constructor(){super(...arguments),this.transcriptions=new Ge(this._client),this.translations=new Ye(this._client),this.speech=new Qe(this._client)}}Ze.Transcriptions=Ge,Ze.Translations=Ye,Ze.Speech=Qe;class et extends Ve{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 Ae(e)?this.list({},e):this._client.getAPIList("/batches",tt,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class tt extends Je{}et.BatchesPage=tt;class nt extends Ve{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,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return Ae(e)?this.list({},e):this._client.getAPIList("/assistants",st,{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 st extends Je{}function rt(e){return"function"==typeof e.parse}nt.AssistantsPage=st;const ot=e=>"assistant"===e?.role,it=e=>"function"===e?.role,at=e=>"tool"===e?.role;var lt,ct,ut,ht,dt,ft,pt,mt,gt,yt,wt,bt,_t,vt=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!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"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},xt=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class St{constructor(){lt.add(this),this.controller=new AbortController,ct.set(this,void 0),ut.set(this,(()=>{})),ht.set(this,(()=>{})),dt.set(this,void 0),ft.set(this,(()=>{})),pt.set(this,(()=>{})),mt.set(this,{}),gt.set(this,!1),yt.set(this,!1),wt.set(this,!1),bt.set(this,!1),vt(this,ct,new Promise(((e,t)=>{vt(this,ut,e,"f"),vt(this,ht,t,"f")})),"f"),vt(this,dt,new Promise(((e,t)=>{vt(this,ft,e,"f"),vt(this,pt,t,"f")})),"f"),xt(this,ct,"f").catch((()=>{})),xt(this,dt,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),xt(this,lt,"m",_t).bind(this))}),0)}_connected(){this.ended||(xt(this,ut,"f").call(this),this._emit("connect"))}get ended(){return xt(this,gt,"f")}get errored(){return xt(this,yt,"f")}get aborted(){return xt(this,wt,"f")}abort(){this.controller.abort()}on(e,t){return(xt(this,mt,"f")[e]||(xt(this,mt,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=xt(this,mt,"f")[e];if(!n)return this;const s=n.findIndex((e=>e.listener===t));return s>=0&&n.splice(s,1),this}once(e,t){return(xt(this,mt,"f")[e]||(xt(this,mt,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,n)=>{vt(this,bt,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)}))}async done(){vt(this,bt,!0,"f"),await xt(this,dt,"f")}_emit(e,...t){if(xt(this,gt,"f"))return;"end"===e&&(vt(this,gt,!0,"f"),xt(this,ft,"f").call(this));const n=xt(this,mt,"f")[e];if(n&&(xt(this,mt,"f")[e]=n.filter((e=>!e.once)),n.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return xt(this,bt,"f")||n?.length||Promise.reject(e),xt(this,ht,"f").call(this,e),xt(this,pt,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];xt(this,bt,"f")||n?.length||Promise.reject(e),xt(this,ht,"f").call(this,e),xt(this,pt,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function At(e){return"auto-parseable-response-format"===e?.$brand}function Et(e){return"auto-parseable-tool"===e?.$brand}function Rt(e,t){const n=e.choices.map((e=>{if("length"===e.finish_reason)throw new Q;if("content_filter"===e.finish_reason)throw new G;return{...e,message:{...e.message,tool_calls:e.message.tool_calls?.map((e=>function(e,t){const n=e.tools?.find((e=>e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:Et(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??[],parsed:e.message.content&&!e.message.refusal?kt(t,e.message.content):null}}}));return{...e,choices:n}}function kt(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 n=e.tools?.find((e=>e.function?.name===t.function.name));return Et(n)||n?.function.strict||!1}function Pt(e){return!!At(e.response_format)||(e.tools?.some((e=>Et(e)||"function"===e.type&&!0===e.function.strict))??!1)}ct=new WeakMap,ut=new WeakMap,ht=new WeakMap,dt=new WeakMap,ft=new WeakMap,pt=new WeakMap,mt=new WeakMap,gt=new WeakMap,yt=new WeakMap,wt=new WeakMap,bt=new WeakMap,lt=new WeakSet,_t=function(e){if(vt(this,yt,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new D),e instanceof D)return vt(this,wt,!0,"f"),this._emit("abort",e);if(e instanceof N)return this._emit("error",e);if(e instanceof Error){const t=new N(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new N(String(e)))};var It,Ot,$t,Tt,jt,qt,Mt,Nt,Lt=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};const Dt=10;class Bt extends St{constructor(){super(...arguments),It.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),(it(e)||at(e))&&e.content)this._emit("functionCallResult",e.content);else if(ot(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(ot(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 N("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Lt(this,It,"m",Ot).call(this)}async finalMessage(){return await this.done(),Lt(this,It,"m",$t).call(this)}async finalFunctionCall(){return await this.done(),Lt(this,It,"m",Tt).call(this)}async finalFunctionCallResult(){return await this.done(),Lt(this,It,"m",jt).call(this)}async totalUsage(){return await this.done(),Lt(this,It,"m",qt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Lt(this,It,"m",$t).call(this);t&&this._emit("finalMessage",t);const n=Lt(this,It,"m",Ot).call(this);n&&this._emit("finalContent",n);const s=Lt(this,It,"m",Tt).call(this);s&&this._emit("finalFunctionCall",s);const r=Lt(this,It,"m",jt).call(this);null!=r&&this._emit("finalFunctionCallResult",r),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",Lt(this,It,"m",qt).call(this))}async _createChatCompletion(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),Lt(this,It,"m",Mt).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Rt(r,t))}async _runChatCompletion(e,t,n){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){const s="function",{function_call:r="auto",stream:o,...i}=t,a="string"!=typeof r&&r?.name,{maxChatCompletions:l=Dt}=n||{},c={};for(const e of t.functions)c[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<l;++t){const t=await this._createChatCompletion(e,{...i,function_call:r,functions:u,messages:[...this.messages]},n),o=t.choices[0]?.message;if(!o)throw new N("missing message in ChatCompletion response");if(!o.function_call)return;const{name:l,arguments:h}=o.function_call,d=c[l];if(!d){const e=`Invalid function_call: ${JSON.stringify(l)}. Available options are: ${u.map((e=>JSON.stringify(e.name))).join(", ")}. Please try again`;this._addMessage({role:s,name:l,content:e});continue}if(a&&a!==l){const e=`Invalid function_call: ${JSON.stringify(l)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:s,name:l,content:e});continue}let f;try{f=rt(d)?await d.parse(h):h}catch(e){this._addMessage({role:s,name:l,content:e instanceof Error?e.message:String(e)});continue}const p=await d.function(f,this),m=Lt(this,It,"m",Nt).call(this,p);if(this._addMessage({role:s,name:l,content:m}),a)return}}async _runTools(e,t,n){const s="tool",{tool_choice:r="auto",stream:o,...i}=t,a="string"!=typeof r&&r?.function?.name,{maxChatCompletions:l=Dt}=n||{},c=t.tools.map((e=>{if(Et(e)){if(!e.$callback)throw new N("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 c)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const h="tools"in t?c.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<l;++t){const t=await this._createChatCompletion(e,{...i,tool_choice:r,tools:h,messages:[...this.messages]},n),o=t.choices[0]?.message;if(!o)throw new N("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:n,arguments:r}=e.function,o=u[n];if(!o){const e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(u).map((e=>JSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}if(a&&a!==n){const e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}let i;try{i=rt(o)?await o.parse(r):r}catch(e){const n=e instanceof Error?e.message:String(e);this._addMessage({role:s,tool_call_id:t,content:n});continue}const l=await o.function(i,this),c=Lt(this,It,"m",Nt).call(this,l);if(this._addMessage({role:s,tool_call_id:t,content:c}),a)return}}}}It=new WeakSet,Ot=function(){return Lt(this,It,"m",$t).call(this).content??null},$t=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(ot(t)){const{function_call:e,...n}=t,s={...n,content:t.content??null,refusal:t.refusal??null};return e&&(s.function_call=e),s}}throw new N("stream ended without producing a ChatCompletionMessage with role=assistant")},Tt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ot(t)&&t?.function_call)return t.function_call;if(ot(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},jt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(it(t)&&null!=t.content)return t.content;if(at(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}},qt=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},Mt=function(e){if(null!=e.n&&e.n>1)throw new N("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Nt=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Ft extends Bt{static runFunctions(e,t,n){const s=new Ft,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run((()=>s._runFunctions(e,t,r))),s}static runTools(e,t,n){const s=new Ft,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run((()=>s._runTools(e,t,r))),s}_addMessage(e,t=!0){super._addMessage(e,t),ot(e)&&e.content&&this._emit("content",e.content)}}const Wt=1,Ut=2,Xt=4,Ht=8,Jt=16,Vt=32,Kt=64,zt=128,Qt=256,Gt=511;class Yt extends Error{}class Zt extends Error{}const en=(e,t)=>{const n=e.length;let s=0;const r=e=>{throw new Yt(`${e} at position ${s}`)},o=e=>{throw new Zt(`${e} at position ${s}`)},i=()=>(h(),s>=n&&r("Unexpected end of input"),'"'===e[s]?a():"{"===e[s]?l():"["===e[s]?c():"null"===e.substring(s,s+4)||Jt&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||Vt&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||Vt&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||zt&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||Qt&t&&1<n-s&&n-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||Kt&t&&n-s<3&&"NaN".startsWith(e.substring(s))?(s+=3,NaN):u()),a=()=>{const i=s;let a=!1;for(s++;s<n&&('"'!==e[s]||a&&"\\"===e[s-1]);)a="\\"===e[s]&&!a,s++;if('"'==e.charAt(s))try{return JSON.parse(e.substring(i,++s-Number(a)))}catch(e){o(String(e))}else if(Wt&t)try{return JSON.parse(e.substring(i,s-Number(a))+'"')}catch(t){return JSON.parse(e.substring(i,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{s++,h();const o={};try{for(;"}"!==e[s];){if(h(),s>=n&&Ht&t)return o;const r=a();h(),s++;try{const e=i();Object.defineProperty(o,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Ht&t)return o;throw e}h(),","===e[s]&&s++}}catch(e){if(Ht&t)return o;r("Expected '}' at end of object")}return s++,o},c=()=>{s++;const n=[];try{for(;"]"!==e[s];)n.push(i()),h(),","===e[s]&&s++}catch(e){if(Xt&t)return n;r("Expected ']' at end of array")}return s++,n},u=()=>{if(0===s){"-"===e&&Ut&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(n){if(Ut&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(n))}}const i=s;for("-"===e[s]&&s++;e[s]&&!",]}".includes(e[s]);)s++;s!=n||Ut&t||r("Unterminated number literal");try{return JSON.parse(e.substring(i,s))}catch(n){"-"===e.substring(i,s)&&Ut&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(e){o(String(e))}}},h=()=>{for(;s<n&&" \n\r\t".includes(e[s]);)s++};return i()},tn=e=>function(e,t=Gt){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return en(e.trim(),t)}(e,Gt^Ut);var nn,sn,rn,on,an,ln,cn,un,hn,dn,fn,pn,mn=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!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"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},gn=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class yn extends Bt{constructor(e){super(),nn.add(this),sn.set(this,void 0),rn.set(this,void 0),on.set(this,void 0),mn(this,sn,e,"f"),mn(this,rn,[],"f")}get currentChatCompletionSnapshot(){return gn(this,on,"f")}static fromReadableStream(e){const t=new yn(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,n){const s=new yn(t);return s._run((()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}async _createChatCompletion(e,t,n){super._createChatCompletion;const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),gn(this,nn,"m",an).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const e of r)gn(this,nn,"m",cn).call(this,e);if(r.controller.signal?.aborted)throw new D;return this._addChatCompletion(gn(this,nn,"m",dn).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),gn(this,nn,"m",an).call(this),this._connected();const s=ee.fromReadableStream(e,this.controller);let r;for await(const e of s)r&&r!==e.id&&this._addChatCompletion(gn(this,nn,"m",dn).call(this)),gn(this,nn,"m",cn).call(this,e),r=e.id;if(s.controller.signal?.aborted)throw new D;return this._addChatCompletion(gn(this,nn,"m",dn).call(this))}[(sn=new WeakMap,rn=new WeakMap,on=new WeakMap,nn=new WeakSet,an=function(){this.ended||mn(this,on,void 0,"f")},ln=function(e){let t=gn(this,rn,"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},gn(this,rn,"f")[e.index]=t,t)},cn=function(e){if(this.ended)return;const t=gn(this,nn,"m",pn).call(this,e);this._emit("chunk",e,t);for(const n of e.choices){const e=t.choices[n.index];null!=n.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",n.delta.content,e.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=n.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:e.message.refusal}),null!=n.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=n.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const s=gn(this,nn,"m",ln).call(this,e);e.finish_reason&&(gn(this,nn,"m",hn).call(this,e),null!=s.current_tool_call_index&&gn(this,nn,"m",un).call(this,e,s.current_tool_call_index));for(const t of n.delta.tool_calls??[])s.current_tool_call_index!==t.index&&(gn(this,nn,"m",hn).call(this,e),null!=s.current_tool_call_index&&gn(this,nn,"m",un).call(this,e,s.current_tool_call_index)),s.current_tool_call_index=t.index;for(const t of n.delta.tool_calls??[]){const n=e.message.tool_calls?.[t.index];n?.type&&("function"===n?.type&&this._emit("tool_calls.function.arguments.delta",{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??""}))}}},un=function(e,t){if(gn(this,nn,"m",ln).call(this,e).done_tool_calls.has(t))return;const n=e.message.tool_calls?.[t];if(!n)throw new Error("no tool call snapshot");if(!n.type)throw new Error("tool call snapshot missing `type`");if("function"===n.type){const e=gn(this,sn,"f")?.tools?.find((e=>"function"===e.type&&e.function.name===n.function.name));this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:Et(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},hn=function(e){const t=gn(this,nn,"m",ln).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=gn(this,nn,"m",fn).call(this);this._emit("content.done",{content:e.message.content,parsed:n?n.$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}))},dn=function(){if(this.ended)throw new N("stream has ended, this shouldn't happen");const e=gn(this,on,"f");if(!e)throw new N("request ended without sending any chunks");return mn(this,on,void 0,"f"),mn(this,rn,[],"f"),function(e,t){const{id:n,choices:s,created:r,model:o,system_fingerprint:i,...a}=e,l={...a,id:n,choices:s.map((({message:t,finish_reason:n,index:s,logprobs:r,...o})=>{if(!n)throw new N(`missing finish_reason for choice ${s}`);const{content:i=null,function_call:a,tool_calls:l,...c}=t,u=t.role;if(!u)throw new N(`missing role for choice ${s}`);if(a){const{arguments:e,name:l}=a;if(null==e)throw new N(`missing function_call.arguments for choice ${s}`);if(!l)throw new N(`missing function_call.name for choice ${s}`);return{...o,message:{content:i,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}return l?{...o,index:s,finish_reason:n,logprobs:r,message:{...c,role:u,content:i,refusal:t.refusal??null,tool_calls:l.map(((t,n)=>{const{function:r,type:o,id:i,...a}=t,{arguments:l,name:c,...u}=r||{};if(null==i)throw new N(`missing choices[${s}].tool_calls[${n}].id\n${wn(e)}`);if(null==o)throw new N(`missing choices[${s}].tool_calls[${n}].type\n${wn(e)}`);if(null==c)throw new N(`missing choices[${s}].tool_calls[${n}].function.name\n${wn(e)}`);if(null==l)throw new N(`missing choices[${s}].tool_calls[${n}].function.arguments\n${wn(e)}`);return{...a,id:i,type:o,function:{...u,name:c,arguments:l}}}))}}:{...o,message:{...c,content:i,role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}})),created:r,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&Pt(t)?Rt(e,t):{...e,choices:e.choices.map((e=>({...e,message:{...e.message,parsed:null,tool_calls:e.message.tool_calls??[]}})))}}(l,t)}(e,gn(this,sn,"f"))},fn=function(){const e=gn(this,sn,"f")?.response_format;return At(e)?e:null},pn=function(e){var t,n,s,r;let o=gn(this,on,"f");const{choices:i,...a}=e;o?Object.assign(o,a):o=mn(this,on,{...a,choices:[]},"f");for(const{delta:i,finish_reason:a,index:l,logprobs:c=null,...u}of e.choices){let e=o.choices[l];if(e||(e=o.choices[l]={finish_reason:a,index:l,message:{},logprobs:c,...u}),c)if(e.logprobs){const{content:s,refusal:r,...o}=c;Object.assign(e.logprobs,o),s&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...s)),r&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},c);if(a&&(e.finish_reason=a,gn(this,sn,"f")&&Pt(gn(this,sn,"f")))){if("length"===a)throw new Q;if("content_filter"===a)throw new G}if(Object.assign(e,u),!i)continue;const{content:h,refusal:d,function_call:f,role:p,tool_calls:m,...g}=i;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&&((s=e.message.function_call).arguments??(s.arguments=""),e.message.function_call.arguments+=f.arguments)):e.message.function_call=f),h&&(e.message.content=(e.message.content||"")+h,!e.message.refusal&&gn(this,nn,"m",fn).call(this)&&(e.message.parsed=tn(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:n,type:s,function:o,...i}of m){const a=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(a,i),n&&(a.id=n),s&&(a.type=s),o&&(a.function??(a.function={name:o.name??"",arguments:""})),o?.name&&(a.function.name=o.name),o?.arguments&&(a.function.arguments+=o.arguments,Ct(gn(this,sn,"f"),a)&&(a.function.parsed_arguments=tn(a.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",(n=>{const s=t.shift();s?s.resolve(n):e.push(n)})),this.on("end",(()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),this.on("error",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise(((e,n)=>t.push({resolve:e,reject:n}))).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 wn(e){return JSON.stringify(e)}class bn extends yn{static fromReadableStream(e){const t=new bn(null);return t._run((()=>t._fromReadableStream(e))),t}static runFunctions(e,t,n){const s=new bn(null),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run((()=>s._runFunctions(e,t,r))),s}static runTools(e,t,n){const s=new bn(t),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run((()=>s._runTools(e,t,r))),s}}let _n=class extends Ve{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new N(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new N(`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?bn.runFunctions(this._client,e,t):Ft.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?bn.runTools(this._client,e,t):Ft.runTools(this._client,e,t)}stream(e,t){return yn.createChatCompletion(this._client,e,t)}};class vn extends Ve{constructor(){super(...arguments),this.completions=new _n(this._client)}}!function(e){e.Completions=_n}(vn||(vn={}));class xn extends Ve{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Sn extends Ve{constructor(){super(...arguments),this.sessions=new xn(this._client)}}Sn.Sessions=xn;var An,En,Rn,kn,Cn,Pn,In,On,$n,Tn,jn,qn,Mn,Nn,Ln,Dn,Bn,Fn,Wn,Un,Xn,Hn,Jn=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},Vn=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!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"===s?r.call(e,n):r?r.value=n:t.set(e,n),n};class Kn extends St{constructor(){super(...arguments),An.add(this),En.set(this,[]),Rn.set(this,{}),kn.set(this,{}),Cn.set(this,void 0),Pn.set(this,void 0),In.set(this,void 0),On.set(this,void 0),$n.set(this,void 0),Tn.set(this,void 0),jn.set(this,void 0),qn.set(this,void 0),Mn.set(this,void 0)}[(En=new WeakMap,Rn=new WeakMap,kn=new WeakMap,Cn=new WeakMap,Pn=new WeakMap,In=new WeakMap,On=new WeakMap,$n=new WeakMap,Tn=new WeakMap,jn=new WeakMap,qn=new WeakMap,Mn=new WeakMap,An=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",(n=>{const s=t.shift();s?s.resolve(n):e.push(n)})),this.on("end",(()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),this.on("error",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise(((e,n)=>t.push({resolve:e,reject:n}))).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 Kn;return t._run((()=>t._fromReadableStream(e))),t}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const s=ee.fromReadableStream(e,this.controller);for await(const e of s)Jn(this,An,"m",Nn).call(this,e);if(s.controller.signal?.aborted)throw new D;return this._addRun(Jn(this,An,"m",Ln).call(this))}toReadableStream(){return new ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,r){const o=new Kn;return o._run((()=>o._runToolAssistantStream(e,t,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),o}async _createToolAssistantStream(e,t,n,s,r){const o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",(()=>this.controller.abort())));const i={...s,stream:!0},a=await e.submitToolOutputs(t,n,i,{...r,signal:this.controller.signal});this._connected();for await(const e of a)Jn(this,An,"m",Nn).call(this,e);if(a.controller.signal?.aborted)throw new D;return this._addRun(Jn(this,An,"m",Ln).call(this))}static createThreadAssistantStream(e,t,n){const s=new Kn;return s._run((()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}static createAssistantStream(e,t,n,s){const r=new Kn;return r._run((()=>r._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}currentEvent(){return Jn(this,jn,"f")}currentRun(){return Jn(this,qn,"f")}currentMessageSnapshot(){return Jn(this,Cn,"f")}currentRunStepSnapshot(){return Jn(this,Mn,"f")}async finalRunSteps(){return await this.done(),Object.values(Jn(this,Rn,"f"))}async finalMessages(){return await this.done(),Object.values(Jn(this,kn,"f"))}async finalRun(){if(await this.done(),!Jn(this,Pn,"f"))throw Error("Final run was not received.");return Jn(this,Pn,"f")}async _createThreadAssistantStream(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort())));const r={...t,stream:!0},o=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(const e of o)Jn(this,An,"m",Nn).call(this,e);if(o.controller.signal?.aborted)throw new D;return this._addRun(Jn(this,An,"m",Ln).call(this))}async _createAssistantStream(e,t,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const o={...n,stream:!0},i=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(const e of i)Jn(this,An,"m",Nn).call(this,e);if(i.controller.signal?.aborted)throw new D;return this._addRun(Jn(this,An,"m",Ln).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let t=e[n];if(null!=t)if("index"!==n&&"type"!==n){if("string"==typeof t&&"string"==typeof s)t+=s;else if("number"==typeof t&&"number"==typeof s)t+=s;else{if(!Xe(t)||!Xe(s)){if(Array.isArray(t)&&Array.isArray(s)){if(t.every((e=>"string"==typeof e||"number"==typeof e))){t.push(...s);continue}for(const e of s){if(!Xe(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const n=e.index;if(null==n)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof n)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);const s=t[n];null==s?t.push(e):t[n]=this.accumulateDelta(s,e)}continue}throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${t}`)}t=this.accumulateDelta(t,s)}e[n]=t}else e[n]=s;else e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,r){return await this._createToolAssistantStream(n,e,t,s,r)}}Nn=function(e){if(!this.ended)switch(Vn(this,jn,e,"f"),Jn(this,An,"m",Fn).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.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Jn(this,An,"m",Hn).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":Jn(this,An,"m",Bn).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":Jn(this,An,"m",Dn).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ln=function(){if(this.ended)throw new N("stream has ended, this shouldn't happen");if(!Jn(this,Pn,"f"))throw Error("Final run has not been received");return Jn(this,Pn,"f")},Dn=function(e){const[t,n]=Jn(this,An,"m",Un).call(this,e,Jn(this,Cn,"f"));Vn(this,Cn,t,"f"),Jn(this,kn,"f")[t.id]=t;for(const e of n){const n=t.content[e.index];"text"==n?.type&&this._emit("textCreated",n.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 n of e.data.delta.content){if("text"==n.type&&n.text){let e=n.text,s=t.content[n.index];if(!s||"text"!=s.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,s.text)}if(n.index!=Jn(this,In,"f")){if(Jn(this,On,"f"))switch(Jn(this,On,"f").type){case"text":this._emit("textDone",Jn(this,On,"f").text,Jn(this,Cn,"f"));break;case"image_file":this._emit("imageFileDone",Jn(this,On,"f").image_file,Jn(this,Cn,"f"))}Vn(this,In,n.index,"f")}Vn(this,On,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==Jn(this,In,"f")){const t=e.data.content[Jn(this,In,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,Jn(this,Cn,"f"));break;case"text":this._emit("textDone",t.text,Jn(this,Cn,"f"))}}Jn(this,Cn,"f")&&this._emit("messageDone",e.data),Vn(this,Cn,void 0,"f")}},Bn=function(e){const t=Jn(this,An,"m",Wn).call(this,e);switch(Vn(this,Mn,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of n.step_details.tool_calls)e.index==Jn(this,$n,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(Jn(this,Tn,"f")&&this._emit("toolCallDone",Jn(this,Tn,"f")),Vn(this,$n,e.index,"f"),Vn(this,Tn,t.step_details.tool_calls[e.index],"f"),Jn(this,Tn,"f")&&this._emit("toolCallCreated",Jn(this,Tn,"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":Vn(this,Mn,void 0,"f");"tool_calls"==e.data.step_details.type&&Jn(this,Tn,"f")&&(this._emit("toolCallDone",Jn(this,Tn,"f")),Vn(this,Tn,void 0,"f")),this._emit("runStepDone",e.data,t)}},Fn=function(e){Jn(this,En,"f").push(e),this._emit("event",e)},Wn=function(e){switch(e.event){case"thread.run.step.created":return Jn(this,Rn,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Jn(this,Rn,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=Kn.accumulateDelta(t,n.delta);Jn(this,Rn,"f")[e.data.id]=s}return Jn(this,Rn,"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":Jn(this,Rn,"f")[e.data.id]=e.data}if(Jn(this,Rn,"f")[e.data.id])return Jn(this,Rn,"f")[e.data.id];throw new Error("No snapshot available")},Un=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const e of s.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=Jn(this,An,"m",Xn).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Xn=function(e,t){return Kn.accumulateDelta(t,e)},Hn=function(e){switch(Vn(this,qn,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":Vn(this,Pn,e.data,"f"),Jn(this,Tn,"f")&&(this._emit("toolCallDone",Jn(this,Tn,"f")),Vn(this,Tn,void 0,"f"))}};class zn extends Ve{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Ae(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Qn,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class Qn extends Je{}zn.MessagesPage=Qn;class Gn extends Ve{retrieve(e,t,n,s={},r){return Ae(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t,n={},s){return Ae(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Yn,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Yn extends Je{}Gn.RunStepsPage=Yn;class Zn extends Ve{constructor(){super(...arguments),this.steps=new Gn(this._client)}create(e,t,n){const{include:s,...r}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Ae(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,es,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}createAndStream(e,t,n){return Kn.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:o}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Te(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,n){return Kn.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const r=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,r.id,s)}submitToolOutputsStream(e,t,n,s){return Kn.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}}class es extends Je{}Zn.RunsPage=es,Zn.Steps=Gn,Zn.RunStepsPage=Yn;class ts extends Ve{constructor(){super(...arguments),this.runs=new Zn(this._client),this.messages=new zn(this._client)}create(e={},t){return Ae(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,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.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 n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return Kn.createThreadAssistantStream(e,this._client.beta.threads,t)}}ts.Runs=Zn,ts.RunsPage=es,ts.Messages=zn,ts.MessagesPage=Qn;let ns=class extends Ve{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},n){return Ae(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,ss,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const r=await this.retrieve(e,t,{...n,headers:s}).withResponse(),o=r.data;switch(o.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Te(e);break;case"failed":case"completed":return o}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}};class ss extends Je{}ns.VectorStoreFilesPage=ss;class rs extends Ve{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return Ae(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,ss,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:o}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Te(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){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=s?.maxConcurrency??5,o=Math.min(r,t.length),i=this._client,a=t.values(),l=[...n];const c=Array(o).fill(a).map((async function(e){for(let t of e){const e=await i.files.create({file:t,purpose:"assistants"},s);l.push(e.id)}}));return await(async e=>{const t=await Promise.allSettled(e),n=t.filter((e=>"rejected"===e.status));if(n.length){for(const e of n)console.error(e.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const e of t)"fulfilled"===e.status&&s.push(e.value);return s})(c),await this.createAndPoll(e,{file_ids:l})}}class os extends Ve{constructor(){super(...arguments),this.files=new ns(this._client),this.fileBatches=new rs(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,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return Ae(e)?this.list({},e):this._client.getAPIList("/vector_stores",is,{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}})}}class is extends Je{}os.VectorStoresPage=is,os.Files=ns,os.VectorStoreFilesPage=ss,os.FileBatches=rs;class as extends Ve{constructor(){super(...arguments),this.realtime=new Sn(this._client),this.vectorStores=new os(this._client),this.chat=new vn(this._client),this.assistants=new nt(this._client),this.threads=new ts(this._client)}}as.Realtime=Sn,as.VectorStores=os,as.VectorStoresPage=is,as.Assistants=nt,as.AssistantsPage=st,as.Threads=ts;class ls extends Ve{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class cs extends Ve{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}class us extends Ve{create(e,t){return this._client.post("/files",ue({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return Ae(e)?this.list({},e):this._client.getAPIList("/files",hs,{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:n=18e5}={}){const s=new Set(["processed","error","deleted"]),r=Date.now();let o=await this.retrieve(e);for(;!o.status||!s.has(o.status);)if(await Te(t),o=await this.retrieve(e),Date.now()-r>n)throw new F({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return o}}class hs extends Je{}us.FileObjectsPage=hs;class ds extends Ve{list(e,t={},n){return Ae(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,fs,{query:t,...n})}}class fs extends Je{}ds.FineTuningJobCheckpointsPage=fs;class ps extends Ve{constructor(){super(...arguments),this.checkpoints=new ds(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 Ae(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",ms,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return Ae(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,gs,{query:t,...n})}}class ms extends Je{}class gs extends Je{}ps.FineTuningJobsPage=ms,ps.FineTuningJobEventsPage=gs,ps.Checkpoints=ds,ps.FineTuningJobCheckpointsPage=fs;class ys extends Ve{constructor(){super(...arguments),this.jobs=new ps(this._client)}}ys.Jobs=ps,ys.FineTuningJobsPage=ms,ys.FineTuningJobEventsPage=gs;class ws extends Ve{createVariation(e,t){return this._client.post("/images/variations",ue({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",ue({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class bs extends Ve{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",_s,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class _s extends He{}bs.ModelsPage=_s;class vs extends Ve{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class xs extends Ve{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,ue({body:t,...n}))}}class Ss extends Ve{constructor(){super(...arguments),this.parts=new xs(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}var As;Ss.Parts=xs;class Es extends be{constructor({baseURL:e=Me("OPENAI_BASE_URL"),apiKey:t=Me("OPENAI_API_KEY"),organization:n=Me("OPENAI_ORG_ID")??null,project:s=Me("OPENAI_PROJECT_ID")??null,...r}={}){if(void 0===t)throw new N("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:n,project:s,...r,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new N("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 ls(this),this.chat=new ze(this),this.embeddings=new cs(this),this.files=new us(this),this.images=new ws(this),this.audio=new Ze(this),this.moderations=new vs(this),this.models=new bs(this),this.fineTuning=new ys(this),this.beta=new as(this),this.batches=new et(this),this.uploads=new Ss(this),this._options=o,this.apiKey=t,this.organization=n,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return A(e,{arrayFormat:"brackets"})}}function Rs(e){const t=[],n=Array.from(e.querySelectorAll("tr")),s=[];n.map((e=>{const n=Array.from(e.querySelectorAll("td, th")).map(((e,t)=>{var n;const r=null===(n=e.textContent)||void 0===n?void 0:n.trim();return s[t]=Math.max(s[t]||0,(null==r?void 0:r.length)||0),null!=r?r:""}));t.push(n)}));const r=t[0].length,o=s.reduce(((e,t)=>e+t),0)+3*(r-1),i="\n"+Array(o).fill("-").join("")+"\n",a=t.map((e=>e.map(((e,t)=>e.padEnd(s[t]," "))).join(" | ")));return a.shift()+i+a.join("\n")}function ks(t,n){t.title&&e("Copied to clipboard"),navigator.clipboard.writeText(n.response)}function Cs(e,t,n){const s=t[0];if(1!==t.length||!function(e){const t=e.getAttribute("contenteditable");return"string"==typeof t&&"false"!==t}(s))return!1;if(e.typing){let e=0;const t=function(r){if(r.preventDefault(),"Backspace"===r.key||e>=n.response.length)return void s.removeEventListener("keydown",t);s.textContent=n.response.slice(0,++e),s.focus();const o=document.createRange();o.selectNodeContents(s),o.collapse(!1);const i=window.getSelection();null!==i&&(i.removeAllRanges(),i.addRange(o))};s.addEventListener("keydown",t)}else s.textContent=n.response;return!0}function Ps(e,t,n){var s,r;const o=t[0];if(1!==t.length||"number"!==o.type)return!1;const i=null===(r=null===(s=n.normalizedResponse.match(/\d+([,.]\d+)?/gi))||void 0===s?void 0:s[0])||void 0===r?void 0:r.replace(",",".");if(void 0===i)return!1;if(e.typing){let e=0;const t=function(n){n.preventDefault(),"Backspace"===n.key||e>=i.length?o.removeEventListener("keydown",t):("."===i.slice(e,e+1)&&++e,o.value=i.slice(0,++e))};o.addEventListener("keydown",t)}else o.value=i;return!0}function Is(e,t,n){const i=null==t?void 0:t[0];if(!i||"radio"!==i.type)return!1;const a=Array.from(t).map((e=>{var t,n;return{element:e,value:o(null!==(n=null===(t=null==e?void 0:e.parentElement)||void 0===t?void 0:t.textContent)&&void 0!==n?n:"")}})).filter((e=>""!==e.value)),l=s(n.normalizedResponse,a);e.logs&&l.value&&r.bestAnswer(l.value,l.similarity);const c=l.element;return e.mouseover?c.addEventListener("mouseover",(()=>c.click()),{once:!0}):c.click(),!0}function Os(e,t,n){const i=null==t?void 0:t[0];if(!i||"checkbox"!==i.type)return!1;const a=n.normalizedResponse.split("\n"),l=Array.from(t).map((e=>{var t,n;return{element:e,value:o(null!==(n=null===(t=null==e?void 0:e.parentElement)||void 0===t?void 0:t.textContent)&&void 0!==n?n:"")}})).filter((e=>""!==e.value)),c=new Set;for(const t of a){const n=s(t,l);e.logs&&n.value&&r.bestAnswer(n.value,n.similarity),c.add(n.element)}for(const t of l.map((e=>e.element))){const n=t.checked&&!c.has(t)||!t.checked&&c.has(t),s=()=>n&&t.click();e.mouseover?t.addEventListener("mouseover",s,{once:!0}):s()}return!0}function $s(e,t,n){if(0===t.length||"SELECT"!==t[0].tagName)return!1;const i=n.normalizedResponse.split("\n");e.logs&&r.array(i);for(let n=0;n<t.length&&i[n];++n){const a=t[n].querySelectorAll("option"),l=Array.from(a).slice(1).map((e=>{var t;return{element:e,value:o(null!==(t=e.textContent)&&void 0!==t?t:"")}})).filter((e=>""!==e.value)),c=s(i[n],l);e.logs&&c.value&&r.bestAnswer(c.value,c.similarity);const u=c.element,h=u.closest("select");null!==h&&(e.mouseover?h.addEventListener("click",(()=>u.selected=!0),{once:!0}):u.selected=!0)}return!0}function Ts(e,t,n){const s=t[0];if(1!==t.length||"TEXTAREA"!==s.tagName&&"text"!==s.type)return!1;if(e.typing){let e=0;const t=function(r){r.preventDefault(),"Backspace"===r.key||e>=n.response.length?s.removeEventListener("keydown",t):s.value=n.response.slice(0,++e)};s.addEventListener("keydown",t)}else s.value=n.response;return!0}function js(e,t,n){const s=t[0];if(!s.classList.contains("qtype_essay_editor"))return!1;const r=s.querySelector("iframe");if(!(r&&r.contentDocument&&r.contentDocument.body&&r.contentWindow))return!1;const o=r.contentDocument.body.querySelector("p");if(!o)return!1;if(e.typing){let e=0;const t=function(s){if(s.preventDefault(),"Backspace"===s.key||e>=n.response.length)return void r.contentWindow.removeEventListener("keydown",t);const i=document.createTextNode(n.response.charAt(e++));o.appendChild(i);const a=r.contentDocument.createRange();a.selectNodeContents(o),a.collapse(!1);const l=r.contentWindow.getSelection();l&&(l.removeAllRanges(),l.addRange(a)),r.contentWindow.focus()};r.contentWindow.addEventListener("keydown",t)}else o.textContent+=n.response;return!0}function qs(e){return t(this,void 0,void 0,(function*(){e.config.cursor&&(e.questionElement.style.cursor="wait");const n=function(e){let t=e.innerText;const n=e.querySelectorAll(".accesshide");for(const e of n)t=t.replace(e.innerText,"");const s=e.querySelector(".qtype_essay_editor");s&&(t=t.replace(s.innerText,""));const r=e.querySelectorAll(".qtext table");for(const e of r)t=t.replace(e.innerText,"\n"+Rs(e)+"\n");return o(t,!1)}(e.form),s=e.form.querySelectorAll(e.inputQuery),i=yield function(e,n,s){return t(this,void 0,void 0,(function*(){var t;const r=new AbortController,i=setTimeout((()=>r.abort()),2e4),a=yield l(e,n,s),c=new Es({apiKey:e.apiKey,baseURL:e.baseURL,dangerouslyAllowBrowser:!0}),u=yield c.chat.completions.create(function(e,t){if(!e.startsWith("o1")&&!e.startsWith("o3"))return t;t.max_tokens&&(t.max_completion_tokens=t.max_tokens,delete t.max_tokens),t.temperature&&delete t.temperature,t.top_p&&delete t.top_p;for(const e of t.messages)"system"===e.role&&(e.role="user");return t}(e.model,{model:e.model,messages:a.messages,temperature:.1,top_p:.6,presence_penalty:0,max_tokens:e.maxTokens||2e3}),{signal:e.timeout?r.signal:null});clearTimeout(i);const h=null!==(t=u.choices[0].message.content)&&void 0!==t?t:"";return"function"==typeof a.saveResponse&&a.saveResponse(h),{question:s,response:h,normalizedResponse:o(h)}}))}(e.config,e.questionElement,n).catch((e=>({error:e}))),a="object"==typeof i&&"error"in i;if(e.config.cursor&&(e.questionElement.style.cursor=e.config.infinite||a?"pointer":"initial"),a)console.error(i.error);else switch(e.config.logs&&(r.question(n),r.response(i)),e.config.mode){case"clipboard":!function(e){e.config.infinite||e.removeListener(),ks(e.config,e.gptAnswer)}({config:e.config,questionElement:e.questionElement,gptAnswer:i,removeListener:e.removeListener});break;case"question-to-answer":!function(e){var t;const n=e.questionElement;e.removeListener();const s=null!==(t=n.innerHTML)&&void 0!==t?t:"";n.innerHTML=e.gptAnswer.response,n.style.whiteSpace="pre-wrap",n.addEventListener("click",(function(){const t=n.innerHTML===e.gptAnswer.response;n.style.whiteSpace=t?"initial":"pre-wrap",n.innerHTML=t?s:e.gptAnswer.response}))}({gptAnswer:i,questionElement:e.questionElement,removeListener:e.removeListener});break;case"autocomplete":!function(e){e.config.infinite||e.removeListener();const t=[js,Cs,Ts,Ps,$s,Is,Os];for(const n of t)if(n(e.config,e.inputList,e.gptAnswer))return;ks(e.config,e.gptAnswer)}({config:e.config,gptAnswer:i,inputList:s,questionElement:e.questionElement,removeListener:e.removeListener})}}))}As=Es,Es.OpenAI=As,Es.DEFAULT_TIMEOUT=6e5,Es.OpenAIError=N,Es.APIError=L,Es.APIConnectionError=B,Es.APIConnectionTimeoutError=F,Es.APIUserAbortError=D,Es.NotFoundError=H,Es.ConflictError=J,Es.RateLimitError=K,Es.BadRequestError=W,Es.AuthenticationError=U,Es.InternalServerError=z,Es.PermissionDeniedError=X,Es.UnprocessableEntityError=V,Es.toFile=ie,Es.fileFromPath=T,Es.Completions=ls,Es.Chat=ze,Es.Embeddings=cs,Es.Files=us,Es.FileObjectsPage=hs,Es.Images=ws,Es.Audio=Ze,Es.Moderations=vs,Es.Models=bs,Es.ModelsPage=_s,Es.FineTuning=ys,Es.Beta=as,Es.Batches=et,Es.BatchesPage=tt,Es.Uploads=Ss;const Ms=[],Ns=[];function Ls(e){const t=Ns.findIndex((t=>t.element===e));if(-1!==t){const e=Ns.splice(t,1)[0];e.element.removeEventListener("click",e.fn)}}function Ds(t){if(console.log("Setting up MoodleGPT..."),Ns.length>0){for(const e of Ns)t.cursor&&(e.element.style.cursor="initial"),e.element.removeEventListener("click",e.fn);return t.title&&e("Removed"),void(Ns.length=0)}const n=["checkbox","radio","text","number"].map((e=>`input[type="${e}"]`)).join(",")+", textarea, select, [contenteditable], .qtype_essay_editor",s=document.querySelectorAll(".formulation");for(const e of s){const s=e.querySelector(".qtext");if(null===s)continue;t.cursor&&(s.style.cursor="pointer");const r=qs.bind(null,{config:t,questionElement:s,form:e,inputQuery:n,removeListener:()=>Ls(s)});Ns.push({element:s,fn:r}),s.addEventListener("click",r)}t.title&&e("Injected")}chrome.storage.sync.get(["moodleGPT"]).then((function(e){const t=e.moodleGPT;if(!t)throw new Error("Please configure MoodleGPT into the extension");t.code?function(e){document.body.addEventListener("keydown",(function(t){Ms.push(t.key),Ms.length>e.code.length&&Ms.shift(),Ms.join("")===e.code&&(Ms.length=0,Ds(e))}))}(t):Ds(t)}))}));
|
||
//# sourceMappingURL=MoodleGPT.js.map
|