3 lines
104 KiB
JavaScript
3 lines
104 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,_=function(e,t){w.apply(e,y(t)?t:[t])},b=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=>b.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,b){let A=e,E=b,R=0,P=!1;for(;void 0!==(E=E.get(x))&&!P;){const t=E.get(e);if(R+=1,void 0!==t){if(t===R)throw new RangeError("Cyclic object value");P=!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(k=A)||"number"==typeof k||"boolean"==typeof k||"symbol"==typeof k||"bigint"==typeof k||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 k;const C=[];if(void 0===A)return C;let $;if("comma"===n&&y(A))g&&l&&(A=p(A,l)),$=[{value:A.length>0?A.join(",")||null:void 0}];else if(y(c))$=c;else{const e=Object.keys(A);$=u?e.sort(u):e}const I=a?String(t).replace(/\./g,"%2E"):String(t),O=s&&y(A)&&1===A.length?I+"[]":I;if(r&&y(A)&&0===A.length)return O+"[]";for(let t=0;t<$.length;++t){const p=$[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,P=y(A)?"function"==typeof n?n(O,E):O:O+(h?"."+E:"["+E+"]");b.set(e,R);const k=new WeakMap;k.set(x,b),_(C,S(v,P,n,s,r,o,i,a,"comma"===n&&g&&y(A)?null:l,c,u,h,d,f,m,g,w,k))}return C}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]||_(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.87.4";let R,P,k,C,$,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,P=e.fetch,k=e.FormData,C=e.File,$=e.ReadableStream,I=e.getMultipartRequestOptions,O=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 L extends Error{}class N extends L{constructor(e,t,n,s){super(`${N.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:De(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 J(e,r,n,s):409===e?new H(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 N(e,r,n,s)}}class D extends N{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class B extends N{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 N{}class U extends N{}class X extends N{}class J extends N{}class H extends N{}class V extends N{}class K extends N{}class z extends N{}class Q extends L{constructor(){super("Could not parse response content as the length limit was reached")}}class G extends L{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var Y,Z=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},ee=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 te{constructor(){Y.set(this,void 0),this.buffer=new Uint8Array,Z(this,Y,null,"f")}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?(new TextEncoder).encode(e):e;let n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;const s=[];let r;for(;null!=(r=ne(this.buffer,ee(this,Y,"f")));){if(r.carriage&&null==ee(this,Y,"f")){Z(this,Y,r.index,"f");continue}if(null!=ee(this,Y,"f")&&(r.index!==ee(this,Y,"f")+1||r.carriage)){s.push(this.decodeText(this.buffer.slice(0,ee(this,Y,"f")-1))),this.buffer=this.buffer.slice(ee(this,Y,"f")),Z(this,Y,null,"f");continue}const e=null!==ee(this,Y,"f")?r.preceding-1:r.preceding,t=this.decodeText(this.buffer.slice(0,e));s.push(t),this.buffer=this.buffer.slice(r.index),Z(this,Y,null,"f")}return s}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 L(`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 L(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new L("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode("\n"):[]}}function ne(e,t){for(let n=t??0;n<e.length;n++){if(10===e[n])return{preceding:n,index:n+1,carriage:!1};if(13===e[n])return{preceding:n,index:n+1,carriage:!0}}return null}function se(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}function re(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=new WeakMap,te.NEWLINE_CHARS=new Set(["\n","\r"]),te.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class oe{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;return new oe((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 L("Attempted to iterate over a response with no body");const n=new ie,s=new te,r=re(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=se(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||n.event.startsWith("response.")){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 N(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 N(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 oe((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 te,n=re(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 oe((()=>s(e)),this.controller),new oe((()=>s(t)),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new $({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?.())}})}}class ie{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 ae=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,le=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&ce(e),ce=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 ue(e,t,n){if(e=await e,le(e))return e;if(ae(e)){const s=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const r=ce(s)?[await s.arrayBuffer()]:[s];return new C(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(ce(e))t.push(await e.arrayBuffer());else{if(!de(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 he(e.name)||he(e.filename)||he(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!n?.type){const e=s[0]?.type;"string"==typeof e&&(n={...n,type:e})}return new C(s,t,n)}const he=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,de=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],fe=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],pe=async e=>{const t=await me(e.body);return I(t,e)},me=async e=>{const t=new k;return await Promise.all(Object.entries(e||{}).map((([e,n])=>ge(t,e,n)))),t},ge=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=>le(e)||ae(e)||j(e))(n)){const s=await ue(n);e.append(t,s)}else if(Array.isArray(n))await Promise.all(n.map((n=>ge(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])=>ge(e,`${t}[${n}]`,s))))}}};var ye,we=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},_e=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 be(e){const{response:t}=e;if(e.options.stream)return Je("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):oe.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const n=t.headers.get("content-type"),s=n?.split(";")[0]?.trim();if(s?.includes("application/json")||s?.endsWith("+json")){const e=await t.json();return Je("response",t.status,t.url,t.headers,e),ve(e,t)}const r=await t.text();return Je("response",t.status,t.url,t.headers,r),r}function ve(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 xe extends Promise{constructor(e,t=be){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new xe(this.responsePromise,(async t=>ve(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 Se{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:r}){this.baseURL=e,this.maxRetries=Ne("maxRetries",t),this.timeout=Ne("timeout",n),this.httpAgent=s,this.fetch=r??P}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Te(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${He()}`}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&&ce(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}={}){e={...e};const{method:n,path:s,query:r,headers:o={}}=e,i=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:fe(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&&Ne("timeout",e.timeout),e.timeout=e.timeout??this.timeout;const c=e.httpAgent??this.httpAgent??O(l),u=e.timeout+1e3;"number"==typeof c?.options?.timeout&&u>(c.options.timeout??0)&&(c.options.timeout=u),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}),...c&&{agent:c},signal:e.signal??null},url:l,timeout:e.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const r={};n&&(r["content-length"]=n);const o=this.defaultHeaders(e);return Ue(r,o),Ue(r,t),fe(e.body)&&"node"!==R&&delete r["content-type"],void 0===Ve(o,"x-stainless-retry-count")&&void 0===Ve(t,"x-stainless-retry-count")&&(r["x-stainless-retry-count"]=String(s)),void 0===Ve(o,"x-stainless-timeout")&&void 0===Ve(t,"x-stainless-timeout")&&e.timeout&&(r["x-stainless-timeout"]=String(e.timeout)),this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,n,s){return N.generate(e,t,n,s)}request(e,t=null){return new xe(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}),Je("request",o,n,r.headers),n.signal?.aborted)throw new D;const a=new AbortController,l=await this.fetchWithTimeout(o,r,i,a).catch(De);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=Re(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){return Je(`response (error; ${`retrying, ${t} attempts remaining`})`,l.status,o,c),this.retryRequest(n,t,c)}const e=await l.text().catch((e=>De(e).message)),s=je(e),r=s?void 0:e;Je(`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 Ee(this,n,e)}buildURL(e,t){const n=Me(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Fe(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 L(`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 Le(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 Ae{constructor(e,t,n,s){ye.set(this,void 0),we(this,ye,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 L("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 _e(this,ye,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ye=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Ee extends xe{constructor(e,t,n){super(t,(async t=>new n(e,t.response,await be(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const Re=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),Pe={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},ke=e=>"object"==typeof e&&null!==e&&!Fe(e)&&Object.keys(e).every((e=>We(Pe,e))),Ce=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E,"X-Stainless-OS":Ie(Deno.build.os),"X-Stainless-Arch":$e(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":Ie(process.platform),"X-Stainless-Arch":$e(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 $e=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",Ie=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 Oe;const Te=()=>Oe??(Oe=Ce()),je=e=>{try{return JSON.parse(e)}catch(e){return}},qe=/^[a-z][a-z0-9+.-]*:/i,Me=e=>qe.test(e),Le=e=>new Promise((t=>setTimeout(t,e))),Ne=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new L(`${e} must be an integer`);if(t<0)throw new L(`${e} must be a positive integer`);return t},De=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)},Be=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function Fe(e){if(!e)return!0;for(const t in e)return!1;return!0}function We(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ue(e,t){for(const n in t){if(!We(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 Xe=new Set(["authorization","api-key"]);function Je(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)Xe.has(n.toLowerCase())&&(t.headers[n]="REDACTED");return t}let t=null;for(const n in e)Xe.has(n.toLowerCase())&&(t??(t={...e}),t[n]="REDACTED");return t??e}));console.log(`OpenAI:DEBUG:${e}`,...n)}}const He=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),Ve=(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 Ke(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class ze extends Ae{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 Qe extends Ae{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class Ge{constructor(e){this._client=e}}let Ye=class extends Ge{list(e,t={},n){return ke(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,tt,{query:t,...n})}},Ze=class extends Ge{constructor(){super(...arguments),this.messages=new Ye(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return ke(e)?this.list({},e):this._client.getAPIList("/chat/completions",et,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class et extends Qe{}class tt extends Qe{}Ze.ChatCompletionsPage=et,Ze.Messages=Ye;let nt=class extends Ge{constructor(){super(...arguments),this.completions=new Ze(this._client)}};nt.Completions=Ze,nt.ChatCompletionsPage=et;class st extends Ge{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class rt extends Ge{create(e,t){return this._client.post("/audio/transcriptions",pe({body:e,...t,__metadata:{model:e.model}}))}}class ot extends Ge{create(e,t){return this._client.post("/audio/translations",pe({body:e,...t,__metadata:{model:e.model}}))}}class it extends Ge{constructor(){super(...arguments),this.transcriptions=new rt(this._client),this.translations=new ot(this._client),this.speech=new st(this._client)}}it.Transcriptions=rt,it.Translations=ot,it.Speech=st;class at extends Ge{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 ke(e)?this.list({},e):this._client.getAPIList("/batches",lt,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class lt extends Qe{}at.BatchesPage=lt;class ct extends Ge{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 ke(e)?this.list({},e):this._client.getAPIList("/assistants",ut,{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 ut extends Qe{}function ht(e){return"function"==typeof e.parse}ct.AssistantsPage=ut;const dt=e=>"assistant"===e?.role,ft=e=>"function"===e?.role,pt=e=>"tool"===e?.role;var mt,gt,yt,wt,_t,bt,vt,xt,St,At,Et,Rt,Pt,kt=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},Ct=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 $t{constructor(){mt.add(this),this.controller=new AbortController,gt.set(this,void 0),yt.set(this,(()=>{})),wt.set(this,(()=>{})),_t.set(this,void 0),bt.set(this,(()=>{})),vt.set(this,(()=>{})),xt.set(this,{}),St.set(this,!1),At.set(this,!1),Et.set(this,!1),Rt.set(this,!1),kt(this,gt,new Promise(((e,t)=>{kt(this,yt,e,"f"),kt(this,wt,t,"f")})),"f"),kt(this,_t,new Promise(((e,t)=>{kt(this,bt,e,"f"),kt(this,vt,t,"f")})),"f"),Ct(this,gt,"f").catch((()=>{})),Ct(this,_t,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),Ct(this,mt,"m",Pt).bind(this))}),0)}_connected(){this.ended||(Ct(this,yt,"f").call(this),this._emit("connect"))}get ended(){return Ct(this,St,"f")}get errored(){return Ct(this,At,"f")}get aborted(){return Ct(this,Et,"f")}abort(){this.controller.abort()}on(e,t){return(Ct(this,xt,"f")[e]||(Ct(this,xt,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=Ct(this,xt,"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(Ct(this,xt,"f")[e]||(Ct(this,xt,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,n)=>{kt(this,Rt,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)}))}async done(){kt(this,Rt,!0,"f"),await Ct(this,_t,"f")}_emit(e,...t){if(Ct(this,St,"f"))return;"end"===e&&(kt(this,St,!0,"f"),Ct(this,bt,"f").call(this));const n=Ct(this,xt,"f")[e];if(n&&(Ct(this,xt,"f")[e]=n.filter((e=>!e.once)),n.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return Ct(this,Rt,"f")||n?.length||Promise.reject(e),Ct(this,wt,"f").call(this,e),Ct(this,vt,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];Ct(this,Rt,"f")||n?.length||Promise.reject(e),Ct(this,wt,"f").call(this,e),Ct(this,vt,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function It(e){return"auto-parseable-response-format"===e?.$brand}function Ot(e){return"auto-parseable-tool"===e?.$brand}function Tt(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,...e.message.tool_calls?{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:Ot(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?jt(t,e.message.content):null}}}));return{...e,choices:n}}function jt(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 qt(e,t){if(!e)return!1;const n=e.tools?.find((e=>e.function?.name===t.function.name));return Ot(n)||n?.function.strict||!1}function Mt(e){return!!It(e.response_format)||(e.tools?.some((e=>Ot(e)||"function"===e.type&&!0===e.function.strict))??!1)}gt=new WeakMap,yt=new WeakMap,wt=new WeakMap,_t=new WeakMap,bt=new WeakMap,vt=new WeakMap,xt=new WeakMap,St=new WeakMap,At=new WeakMap,Et=new WeakMap,Rt=new WeakMap,mt=new WeakSet,Pt=function(e){if(kt(this,At,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new D),e instanceof D)return kt(this,Et,!0,"f"),this._emit("abort",e);if(e instanceof L)return this._emit("error",e);if(e instanceof Error){const t=new L(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new L(String(e)))};var Lt,Nt,Dt,Bt,Ft,Wt,Ut,Xt,Jt=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 Ht=10;class Vt extends $t{constructor(){super(...arguments),Lt.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),(ft(e)||pt(e))&&e.content)this._emit("functionCallResult",e.content);else if(dt(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(dt(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 L("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Jt(this,Lt,"m",Nt).call(this)}async finalMessage(){return await this.done(),Jt(this,Lt,"m",Dt).call(this)}async finalFunctionCall(){return await this.done(),Jt(this,Lt,"m",Bt).call(this)}async finalFunctionCallResult(){return await this.done(),Jt(this,Lt,"m",Ft).call(this)}async totalUsage(){return await this.done(),Jt(this,Lt,"m",Wt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Jt(this,Lt,"m",Dt).call(this);t&&this._emit("finalMessage",t);const n=Jt(this,Lt,"m",Nt).call(this);n&&this._emit("finalContent",n);const s=Jt(this,Lt,"m",Bt).call(this);s&&this._emit("finalFunctionCall",s);const r=Jt(this,Lt,"m",Ft).call(this);null!=r&&this._emit("finalFunctionCallResult",r),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",Jt(this,Lt,"m",Wt).call(this))}async _createChatCompletion(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),Jt(this,Lt,"m",Ut).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Tt(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=Ht}=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 L("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=ht(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=Jt(this,Lt,"m",Xt).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=Ht}=n||{},c=t.tools.map((e=>{if(Ot(e)){if(!e.$callback)throw new L("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 L("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=ht(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=Jt(this,Lt,"m",Xt).call(this,l);if(this._addMessage({role:s,tool_call_id:t,content:c}),a)return}}}}Lt=new WeakSet,Nt=function(){return Jt(this,Lt,"m",Dt).call(this).content??null},Dt=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(dt(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 L("stream ended without producing a ChatCompletionMessage with role=assistant")},Bt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(dt(t)&&t?.function_call)return t.function_call;if(dt(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Ft=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ft(t)&&null!=t.content)return t.content;if(pt(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}},Wt=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},Ut=function(e){if(null!=e.n&&e.n>1)throw new L("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Xt=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Kt extends Vt{static runFunctions(e,t,n){const s=new Kt,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 Kt,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),dt(e)&&e.content&&this._emit("content",e.content)}}const zt=1,Qt=2,Gt=4,Yt=8,Zt=16,en=32,tn=64,nn=128,sn=256,rn=511;class on extends Error{}class an extends Error{}const ln=(e,t)=>{const n=e.length;let s=0;const r=e=>{throw new on(`${e} at position ${s}`)},o=e=>{throw new an(`${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)||Zt&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||en&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||en&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||nn&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||sn&t&&1<n-s&&n-s<9&&"-Infinity".startsWith(e.substring(s))?(s+=9,-1/0):"NaN"===e.substring(s,s+3)||tn&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(zt&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&&Yt&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(Yt&t)return o;throw e}h(),","===e[s]&&s++}}catch(e){if(Yt&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(Gt&t)return n;r("Expected ']' at end of array")}return s++,n},u=()=>{if(0===s){"-"===e&&Qt&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(n){if(Qt&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||Qt&t||r("Unterminated number literal");try{return JSON.parse(e.substring(i,s))}catch(n){"-"===e.substring(i,s)&&Qt&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()},cn=e=>function(e,t=rn){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return ln(e.trim(),t)}(e,rn^Qt);var un,hn,dn,fn,pn,mn,gn,yn,wn,_n,bn,vn,xn=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},Sn=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 An extends Vt{constructor(e){super(),un.add(this),hn.set(this,void 0),dn.set(this,void 0),fn.set(this,void 0),xn(this,hn,e,"f"),xn(this,dn,[],"f")}get currentChatCompletionSnapshot(){return Sn(this,fn,"f")}static fromReadableStream(e){const t=new An(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,n){const s=new An(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()))),Sn(this,un,"m",pn).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)Sn(this,un,"m",gn).call(this,e);if(r.controller.signal?.aborted)throw new D;return this._addChatCompletion(Sn(this,un,"m",_n).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Sn(this,un,"m",pn).call(this),this._connected();const s=oe.fromReadableStream(e,this.controller);let r;for await(const e of s)r&&r!==e.id&&this._addChatCompletion(Sn(this,un,"m",_n).call(this)),Sn(this,un,"m",gn).call(this,e),r=e.id;if(s.controller.signal?.aborted)throw new D;return this._addChatCompletion(Sn(this,un,"m",_n).call(this))}[(hn=new WeakMap,dn=new WeakMap,fn=new WeakMap,un=new WeakSet,pn=function(){this.ended||xn(this,fn,void 0,"f")},mn=function(e){let t=Sn(this,dn,"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},Sn(this,dn,"f")[e.index]=t,t)},gn=function(e){if(this.ended)return;const t=Sn(this,un,"m",vn).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=Sn(this,un,"m",mn).call(this,e);e.finish_reason&&(Sn(this,un,"m",wn).call(this,e),null!=s.current_tool_call_index&&Sn(this,un,"m",yn).call(this,e,s.current_tool_call_index));for(const t of n.delta.tool_calls??[])s.current_tool_call_index!==t.index&&(Sn(this,un,"m",wn).call(this,e),null!=s.current_tool_call_index&&Sn(this,un,"m",yn).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??""}))}}},yn=function(e,t){if(Sn(this,un,"m",mn).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=Sn(this,hn,"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:Ot(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},wn=function(e){const t=Sn(this,un,"m",mn).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=Sn(this,un,"m",bn).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}))},_n=function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");const e=Sn(this,fn,"f");if(!e)throw new L("request ended without sending any chunks");return xn(this,fn,void 0,"f"),xn(this,dn,[],"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 L(`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 L(`missing role for choice ${s}`);if(a){const{arguments:e,name:l}=a;if(null==e)throw new L(`missing function_call.arguments for choice ${s}`);if(!l)throw new L(`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 L(`missing choices[${s}].tool_calls[${n}].id\n${En(e)}`);if(null==o)throw new L(`missing choices[${s}].tool_calls[${n}].type\n${En(e)}`);if(null==c)throw new L(`missing choices[${s}].tool_calls[${n}].function.name\n${En(e)}`);if(null==l)throw new L(`missing choices[${s}].tool_calls[${n}].function.arguments\n${En(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&&Mt(t)?Tt(e,t):{...e,choices:e.choices.map((e=>({...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}})))}}(l,t)}(e,Sn(this,hn,"f"))},bn=function(){const e=Sn(this,hn,"f")?.response_format;return It(e)?e:null},vn=function(e){var t,n,s,r;let o=Sn(this,fn,"f");const{choices:i,...a}=e;o?Object.assign(o,a):o=xn(this,fn,{...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,Sn(this,hn,"f")&&Mt(Sn(this,hn,"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&&Sn(this,un,"m",bn).call(this)&&(e.message.parsed=cn(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,qt(Sn(this,hn,"f"),a)&&(a.function.parsed_arguments=cn(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 oe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function En(e){return JSON.stringify(e)}class Rn extends An{static fromReadableStream(e){const t=new Rn(null);return t._run((()=>t._fromReadableStream(e))),t}static runFunctions(e,t,n){const s=new Rn(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 Rn(t),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run((()=>s._runTools(e,t,r))),s}}let Pn=class extends Ge{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new L(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new L(`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=>Tt(t,e)))}runFunctions(e,t){return e.stream?Rn.runFunctions(this._client,e,t):Kt.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?Rn.runTools(this._client,e,t):Kt.runTools(this._client,e,t)}stream(e,t){return An.createChatCompletion(this._client,e,t)}};class kn extends Ge{constructor(){super(...arguments),this.completions=new Pn(this._client)}}!function(e){e.Completions=Pn}(kn||(kn={}));class Cn extends Ge{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class $n extends Ge{constructor(){super(...arguments),this.sessions=new Cn(this._client)}}$n.Sessions=Cn;var In,On,Tn,jn,qn,Mn,Ln,Nn,Dn,Bn,Fn,Wn,Un,Xn,Jn,Hn,Vn,Kn,zn,Qn,Gn,Yn,Zn=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)},es=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 ts extends $t{constructor(){super(...arguments),In.add(this),On.set(this,[]),Tn.set(this,{}),jn.set(this,{}),qn.set(this,void 0),Mn.set(this,void 0),Ln.set(this,void 0),Nn.set(this,void 0),Dn.set(this,void 0),Bn.set(this,void 0),Fn.set(this,void 0),Wn.set(this,void 0),Un.set(this,void 0)}[(On=new WeakMap,Tn=new WeakMap,jn=new WeakMap,qn=new WeakMap,Mn=new WeakMap,Ln=new WeakMap,Nn=new WeakMap,Dn=new WeakMap,Bn=new WeakMap,Fn=new WeakMap,Wn=new WeakMap,Un=new WeakMap,In=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 ts;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=oe.fromReadableStream(e,this.controller);for await(const e of s)Zn(this,In,"m",Xn).call(this,e);if(s.controller.signal?.aborted)throw new D;return this._addRun(Zn(this,In,"m",Jn).call(this))}toReadableStream(){return new oe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,r){const o=new ts;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)Zn(this,In,"m",Xn).call(this,e);if(a.controller.signal?.aborted)throw new D;return this._addRun(Zn(this,In,"m",Jn).call(this))}static createThreadAssistantStream(e,t,n){const s=new ts;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 ts;return r._run((()=>r._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}currentEvent(){return Zn(this,Fn,"f")}currentRun(){return Zn(this,Wn,"f")}currentMessageSnapshot(){return Zn(this,qn,"f")}currentRunStepSnapshot(){return Zn(this,Un,"f")}async finalRunSteps(){return await this.done(),Object.values(Zn(this,Tn,"f"))}async finalMessages(){return await this.done(),Object.values(Zn(this,jn,"f"))}async finalRun(){if(await this.done(),!Zn(this,Mn,"f"))throw Error("Final run was not received.");return Zn(this,Mn,"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)Zn(this,In,"m",Xn).call(this,e);if(o.controller.signal?.aborted)throw new D;return this._addRun(Zn(this,In,"m",Jn).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)Zn(this,In,"m",Xn).call(this,e);if(i.controller.signal?.aborted)throw new D;return this._addRun(Zn(this,In,"m",Jn).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(!Ke(t)||!Ke(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(!Ke(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)}}Xn=function(e){if(!this.ended)switch(es(this,Fn,e,"f"),Zn(this,In,"m",Kn).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Zn(this,In,"m",Yn).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":Zn(this,In,"m",Vn).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":Zn(this,In,"m",Hn).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Jn=function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");if(!Zn(this,Mn,"f"))throw Error("Final run has not been received");return Zn(this,Mn,"f")},Hn=function(e){const[t,n]=Zn(this,In,"m",Qn).call(this,e,Zn(this,qn,"f"));es(this,qn,t,"f"),Zn(this,jn,"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!=Zn(this,Ln,"f")){if(Zn(this,Nn,"f"))switch(Zn(this,Nn,"f").type){case"text":this._emit("textDone",Zn(this,Nn,"f").text,Zn(this,qn,"f"));break;case"image_file":this._emit("imageFileDone",Zn(this,Nn,"f").image_file,Zn(this,qn,"f"))}es(this,Ln,n.index,"f")}es(this,Nn,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==Zn(this,Ln,"f")){const t=e.data.content[Zn(this,Ln,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,Zn(this,qn,"f"));break;case"text":this._emit("textDone",t.text,Zn(this,qn,"f"))}}Zn(this,qn,"f")&&this._emit("messageDone",e.data),es(this,qn,void 0,"f")}},Vn=function(e){const t=Zn(this,In,"m",zn).call(this,e);switch(es(this,Un,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==Zn(this,Dn,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(Zn(this,Bn,"f")&&this._emit("toolCallDone",Zn(this,Bn,"f")),es(this,Dn,e.index,"f"),es(this,Bn,t.step_details.tool_calls[e.index],"f"),Zn(this,Bn,"f")&&this._emit("toolCallCreated",Zn(this,Bn,"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":es(this,Un,void 0,"f");"tool_calls"==e.data.step_details.type&&Zn(this,Bn,"f")&&(this._emit("toolCallDone",Zn(this,Bn,"f")),es(this,Bn,void 0,"f")),this._emit("runStepDone",e.data,t)}},Kn=function(e){Zn(this,On,"f").push(e),this._emit("event",e)},zn=function(e){switch(e.event){case"thread.run.step.created":return Zn(this,Tn,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Zn(this,Tn,"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=ts.accumulateDelta(t,n.delta);Zn(this,Tn,"f")[e.data.id]=s}return Zn(this,Tn,"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":Zn(this,Tn,"f")[e.data.id]=e.data}if(Zn(this,Tn,"f")[e.data.id])return Zn(this,Tn,"f")[e.data.id];throw new Error("No snapshot available")},Qn=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]=Zn(this,In,"m",Gn).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")},Gn=function(e,t){return ts.accumulateDelta(t,e)},Yn=function(e){switch(es(this,Wn,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":es(this,Mn,e.data,"f"),Zn(this,Bn,"f")&&(this._emit("toolCallDone",Zn(this,Bn,"f")),es(this,Bn,void 0,"f"))}};class ns extends Ge{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 ke(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,ss,{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 ss extends Qe{}ns.MessagesPage=ss;class rs extends Ge{retrieve(e,t,n,s={},r){return ke(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 ke(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,os,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class os extends Qe{}rs.RunStepsPage=os;class is extends Ge{constructor(){super(...arguments),this.steps=new rs(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 ke(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,as,{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 ts.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 Le(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,n){return ts.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 ts.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}}class as extends Qe{}is.RunsPage=as,is.Steps=rs,is.RunStepsPage=os;class ls extends Ge{constructor(){super(...arguments),this.runs=new is(this._client),this.messages=new ns(this._client)}create(e={},t){return ke(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 ts.createThreadAssistantStream(e,this._client.beta.threads,t)}}ls.Runs=is,ls.RunsPage=as,ls.Messages=ns,ls.MessagesPage=ss;class cs extends Ge{constructor(){super(...arguments),this.realtime=new $n(this._client),this.chat=new kn(this._client),this.assistants=new ct(this._client),this.threads=new ls(this._client)}}cs.Realtime=$n,cs.Assistants=ct,cs.AssistantsPage=ut,cs.Threads=ls;class us extends Ge{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class hs extends Ge{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}let ds=class extends Ge{create(e,t){return this._client.post("/files",pe({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return ke(e)?this.list({},e):this._client.getAPIList("/files",fs,{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 Le(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 fs extends Qe{}ds.FileObjectsPage=fs;class ps extends Ge{list(e,t={},n){return ke(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,ms,{query:t,...n})}}class ms extends Qe{}ps.FineTuningJobCheckpointsPage=ms;class gs extends Ge{constructor(){super(...arguments),this.checkpoints=new ps(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 ke(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",ys,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return ke(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,ws,{query:t,...n})}}class ys extends Qe{}class ws extends Qe{}gs.FineTuningJobsPage=ys,gs.FineTuningJobEventsPage=ws,gs.Checkpoints=ps,gs.FineTuningJobCheckpointsPage=ms;class _s extends Ge{constructor(){super(...arguments),this.jobs=new gs(this._client)}}_s.Jobs=gs,_s.FineTuningJobsPage=ys,_s.FineTuningJobEventsPage=ws;class bs extends Ge{createVariation(e,t){return this._client.post("/images/variations",pe({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",pe({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class vs extends Ge{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",xs,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class xs extends ze{}vs.ModelsPage=xs;class Ss extends Ge{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function As(e,t){return t&&function(e){if(It(e.text?.format))return!0;return!1}(t)?Es(e,t):{...e,output_parsed:null,output:e.output.map((e=>"function_call"===e.type?{...e,parsed_arguments:null}:"message"===e.type?{...e,content:e.content.map((e=>({...e,parsed:null})))}:e))}}function Es(e,t){const n=e.output.map((e=>{if("function_call"===e.type)return{...e,parsed_arguments:Ps(t,e)};if("message"===e.type){const n=e.content.map((e=>"output_text"===e.type?{...e,parsed:Rs(t,e.text)}:e));return{...e,content:n}}return e})),s=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,"output_text")||ks(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const e of s.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),s}function Rs(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const n=e.text?.format;return n.$parseRaw(t)}return JSON.parse(t)}function Ps(e,t){const n=(s=e.tools??[],r=t.name,s.find((e=>"function"===e.type&&e.name===r)));var s,r,o;return{...t,...t,parsed_arguments:(o=n,"auto-parseable-tool"===o?.$brand?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null)}}function ks(e){const t=[];for(const n of e.output)if("message"===n.type)for(const e of n.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}class Cs extends Ge{list(e,t={},n){return ke(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Ws,{query:t,...n})}}var $s,Is,Os,Ts,js,qs,Ms,Ls,Ns=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},Ds=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 Bs extends $t{constructor(e){super(),$s.add(this),Is.set(this,void 0),Os.set(this,void 0),Ts.set(this,void 0),Ns(this,Is,e,"f")}static createResponse(e,t,n){const s=new Bs(t);return s._run((()=>s._createResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}async _createResponse(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),Ds(this,$s,"m",js).call(this);const r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const e of r)Ds(this,$s,"m",qs).call(this,e);if(r.controller.signal?.aborted)throw new D;return Ds(this,$s,"m",Ms).call(this)}[(Is=new WeakMap,Os=new WeakMap,Ts=new WeakMap,$s=new WeakSet,js=function(){this.ended||Ns(this,Os,void 0,"f")},qs=function(e){if(this.ended)return;const t=Ds(this,$s,"m",Ls).call(this,e);switch(this._emit("event",e),e.type){case"response.output_text.delta":{const n=t.output[e.output_index];if(!n)throw new L(`missing output at index ${e.output_index}`);if("message"===n.type){const t=n.content[e.content_index];if(!t)throw new L(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new L(`expected content to be 'output_text', got ${t.type}`);this._emit("response.output_text.delta",{...e,snapshot:t.text})}break}case"response.function_call_arguments.delta":{const n=t.output[e.output_index];if(!n)throw new L(`missing output at index ${e.output_index}`);"function_call"===n.type&&this._emit("response.function_call_arguments.delta",{...e,snapshot:n.arguments});break}default:this._emit(e.type,e)}},Ms=function(){if(this.ended)throw new L("stream has ended, this shouldn't happen");const e=Ds(this,Os,"f");if(!e)throw new L("request ended without sending any events");Ns(this,Os,void 0,"f");const t=function(e,t){return As(e,t)}(e,Ds(this,Is,"f"));return Ns(this,Ts,t,"f"),t},Ls=function(e){let t=Ds(this,Os,"f");if(!t){if("response.created"!==e.type)throw new L(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=Ns(this,Os,e.response,"f"),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const n=t.output[e.output_index];if(!n)throw new L(`missing output at index ${e.output_index}`);"message"===n.type&&n.content.push(e.part);break}case"response.output_text.delta":{const n=t.output[e.output_index];if(!n)throw new L(`missing output at index ${e.output_index}`);if("message"===n.type){const t=n.content[e.content_index];if(!t)throw new L(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new L(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const n=t.output[e.output_index];if(!n)throw new L(`missing output at index ${e.output_index}`);"function_call"===n.type&&(n.arguments+=e.delta);break}case"response.completed":Ns(this,Os,e.response,"f")}return t},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})}}async finalResponse(){await this.done();const e=Ds(this,Ts,"f");if(!e)throw new L("stream ended without producing a ChatCompletion");return e}}class Fs extends Ge{constructor(){super(...arguments),this.inputItems=new Cs(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap((e=>("object"in e&&"response"===e.object&&ks(e),e)))}retrieve(e,t={},n){return ke(t)?this.retrieve(e,{},t):this._client.get(`/responses/${e}`,{query:t,...n})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((t=>Es(t,e)))}stream(e,t){return Bs.createResponse(this._client,e,t)}}class Ws extends Qe{}Fs.InputItems=Cs;class Us extends Ge{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,pe({body:t,...n}))}}class Xs extends Ge{constructor(){super(...arguments),this.parts=new Us(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})}}Xs.Parts=Us;class Js extends Ge{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}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return ke(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,Hs,{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 Le(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)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Vs,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class Hs extends Qe{}class Vs extends ze{}Js.VectorStoreFilesPage=Hs,Js.FileContentResponsesPage=Vs;class Ks extends Ge{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 ke(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,Hs,{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 Le(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 zs extends Ge{constructor(){super(...arguments),this.files=new Js(this._client),this.fileBatches=new Ks(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 ke(e)?this.list({},e):this._client.getAPIList("/vector_stores",Qs,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,Gs,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class Qs extends Qe{}class Gs extends ze{}var Ys;zs.VectorStoresPage=Qs,zs.VectorStoreSearchResponsesPage=Gs,zs.Files=Js,zs.VectorStoreFilesPage=Hs,zs.FileContentResponsesPage=Vs,zs.FileBatches=Ks;class Zs extends Se{constructor({baseURL:e=Be("OPENAI_BASE_URL"),apiKey:t=Be("OPENAI_API_KEY"),organization:n=Be("OPENAI_ORG_ID")??null,project:s=Be("OPENAI_PROJECT_ID")??null,...r}={}){if(void 0===t)throw new L("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 L("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 us(this),this.chat=new nt(this),this.embeddings=new hs(this),this.files=new ds(this),this.images=new bs(this),this.audio=new it(this),this.moderations=new Ss(this),this.models=new vs(this),this.fineTuning=new _s(this),this.vectorStores=new zs(this),this.beta=new cs(this),this.batches=new at(this),this.uploads=new Xs(this),this.responses=new Fs(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 er(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 tr(t,n){t.title&&e("Copied to clipboard"),navigator.clipboard.writeText(n.response)}function nr(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 sr(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 rr(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 or(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 ir(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 ar(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 lr(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 cr(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"+er(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 Zs({apiKey:e.apiKey,baseURL:e.baseURL,dangerouslyAllowBrowser:!0}),u=yield c.chat.completions.create(function(e,t){if(!e.startsWith("o1"))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(),tr(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=[lr,nr,ar,sr,ir,rr,or];for(const n of t)if(n(e.config,e.inputList,e.gptAnswer))return;tr(e.config,e.gptAnswer)}({config:e.config,gptAnswer:i,inputList:s,questionElement:e.questionElement,removeListener:e.removeListener})}}))}Ys=Zs,Zs.OpenAI=Ys,Zs.DEFAULT_TIMEOUT=6e5,Zs.OpenAIError=L,Zs.APIError=N,Zs.APIConnectionError=B,Zs.APIConnectionTimeoutError=F,Zs.APIUserAbortError=D,Zs.NotFoundError=J,Zs.ConflictError=H,Zs.RateLimitError=K,Zs.BadRequestError=W,Zs.AuthenticationError=U,Zs.InternalServerError=z,Zs.PermissionDeniedError=X,Zs.UnprocessableEntityError=V,Zs.toFile=ue,Zs.fileFromPath=T,Zs.Completions=us,Zs.Chat=nt,Zs.ChatCompletionsPage=et,Zs.Embeddings=hs,Zs.Files=ds,Zs.FileObjectsPage=fs,Zs.Images=bs,Zs.Audio=it,Zs.Moderations=Ss,Zs.Models=vs,Zs.ModelsPage=xs,Zs.FineTuning=_s,Zs.VectorStores=zs,Zs.VectorStoresPage=Qs,Zs.VectorStoreSearchResponsesPage=Gs,Zs.Beta=cs,Zs.Batches=at,Zs.BatchesPage=lt,Zs.Uploads=Xs,Zs.Responses=Fs;const ur=[],hr=[];function dr(e){const t=hr.findIndex((t=>t.element===e));if(-1!==t){const e=hr.splice(t,1)[0];e.element.removeEventListener("click",e.fn)}}function fr(t){if(hr.length>0){for(const e of hr)t.cursor&&(e.element.style.cursor="initial"),e.element.removeEventListener("click",e.fn);return t.title&&e("Removed"),void(hr.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=cr.bind(null,{config:t,questionElement:s,form:e,inputQuery:n,removeListener:()=>dr(s)});hr.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){ur.push(t.key),ur.length>e.code.length&&ur.shift(),ur.join("")===e.code&&(ur.length=0,fr(e))}))}(t):fr(t)}))}));
|
||
//# sourceMappingURL=MoodleGPT.js.map
|