3 lines
119 KiB
JavaScript
3 lines
119 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,s,n){return new(s||(s=Promise))((function(r,o){function i(e){try{c(n.next(e))}catch(e){o(e)}}function a(e){try{c(n.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(i,a)}c((n=n.apply(e,t||[])).next())}))}function s(e,t){const s=e.length>t.length?e.length:t.length;return 0===s?1:(s-function(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;const s=[],n=e.replace(/\s+/,""),r=t.replace(/\s+/,"");for(let e=0;e<=n.length;++e){s.push([e]);for(let t=1;t<=r.length;++t)s[e][t]=0===e?t:Math.min(s[e-1][t]+1,s[e][t-1]+1,s[e-1][t-1]+(n[e-1]===r[t-1]?0:1))}return s[n.length][r.length]}(e,t))/s}function n(e,t){let n={element:null,similarity:0,value:null};for(const r of t){const t=s(r.value,e);if(1===t)return{element:r.element,value:r.value,similarity:t};t>n.similarity&&(n={element:r.element,value:r.value,similarity:t})}return n}"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)}}var o;function i(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")}function a(e,t){const s=[];return e.querySelectorAll(t).forEach(((t,n)=>{var r,o,a;if("-1"===t.value)return;let c="";const l=e.querySelector(`#${t.id.replace(/:/g,"\\:")}_label`);c=l?null!==(r=l.textContent)&&void 0!==r?r:"":null!==(a=null===(o=t.parentElement)||void 0===o?void 0:o.textContent)&&void 0!==a?a:"",c=i(c.replace("Clear my choice","")),c&&s.push({index:n,text:c})})),s}!function(e){e.SINGLE_CHOICE="single_choice",e.MULTIPLE_CHOICE="multiple_choice",e.TRUE_FALSE="true_false",e.SHORT_TEXT="short_text",e.NUMERICAL="numerical",e.ESSAY="essay",e.MATCH="match",e.SELECT_MISSING_WORD="select_missing_word",e.DRAG_DROP_TEXT="drag_drop_text",e.ORDERING="ordering",e.UNKNOWN="unknown"}(o||(o={}));const c={role:"system",content:"\nYou are an expert quiz solver. \nPlease solve the provided question based on its type and provide the correct result.\n- For choice questions, output the exact index(es) of the correct answer(s).\n- For text/numerical questions, provide the exact wording or number.\n- For essay questions, provide a highly detailed and complete response.\nAlways output strict JSON according to the requested schema block.\n".trim()};function l(e,s,n){return t(this,void 0,void 0,(function*(){const t=s.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 n;const r=[],o=Array.from(t).map((e=>function(e,t=.75){return new Promise(((s,n)=>{const r=document.createElement("canvas"),o=r.getContext("2d");if(!o)return n("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);s(e),r.remove()},i.onerror=e=>{n(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:n}),r}))}function u(){var e,t;const s=new URLSearchParams(document.location.search);return{host:document.location.host,cmid:null!==(e=s.get("cmid"))&&void 0!==e?e:"",attempt:null!==(t=s.get("attempt"))&&void 0!==t?t:"",history:[]}}function d(){var e;return JSON.parse(null!==(e=sessionStorage.moodleGPTHistory)&&void 0!==e?e:"null")}function h(e,t){const s=["host","cmid","attempt"];for(const n of s)if(e[n]!==t[n])return!1;return!0}function p(e,s,n){return t(this,void 0,void 0,(function*(){const t=function(e,t){const s=e.closest(".que")||e.closest(".formulation")||e;if(s.classList.contains("multichoice")||s.classList.contains("calculatedmulti")){const e=s.querySelectorAll('.answer input[type="checkbox"]'),n=s.querySelectorAll('.answer input[type="radio"]');if(e.length>0)return{question_type:o.MULTIPLE_CHOICE,question_text:t,answer_options:a(s,'.answer input[type="checkbox"]')};if(n.length>0)return{question_type:o.SINGLE_CHOICE,question_text:t,answer_options:a(s,'.answer input[type="radio"]')}}if(s.classList.contains("truefalse"))return{question_type:o.TRUE_FALSE,question_text:t};if(s.classList.contains("shortanswer"))return{question_type:o.SHORT_TEXT,question_text:t};if(s.classList.contains("numerical")||s.classList.contains("calculated")||s.classList.contains("calculatedsimple"))return{question_type:o.NUMERICAL,question_text:t};if(s.classList.contains("essay"))return{question_type:o.ESSAY,question_text:t};if(s.classList.contains("match")){const e=[],n=[],r=s.querySelectorAll("tr");let a=0;return r.forEach((t=>{const s=t.querySelector(".text"),r=t.querySelector("select");if(s&&r){if(e.push({index:a,text:i(s.textContent||"")}),0===a){const e=r.querySelectorAll("option");let t=0;Array.from(e).slice(1).forEach((e=>{n.push({index:t++,text:i(e.textContent||"")})}))}a++}})),{question_type:o.MATCH,question_text:t,sub_questions:e,options:n}}if(s.classList.contains("gapselect")){const e=s.querySelectorAll("select"),n=[];return e.forEach(((e,t)=>{const s=e.querySelectorAll("option"),r=[];let o=0;Array.from(s).slice(1).forEach((e=>{r.push({index:o++,text:i(e.textContent||"")})})),n.push({index:t,options:r})})),{question_type:o.SELECT_MISSING_WORD,question_text:t,drop_downs:n}}if(s.classList.contains("ddwtos")){const e=s.querySelector(".answercontainer"),n=[];return e&&e.querySelectorAll(".draghome.unplaced").forEach(((e,t)=>{n.push({index:t,text:i(e.textContent||"")})})),{question_type:o.DRAG_DROP_TEXT,question_text:t,draggables:n}}if(s.classList.contains("ordering")){const e=s.querySelector(".sortablelist"),n=[];return e&&e.querySelectorAll(".sortableitem").forEach(((e,t)=>{var s;let r=(null===(s=e.textContent)||void 0===s?void 0:s.trim())||"";if(""===r){const t=e.querySelector("img");t&&(r=t.getAttribute("alt")||"")}n.push({index:t,text:i(r)})})),{question_type:o.ORDERING,question_text:t,items:n}}return null}(s,n),r=t?JSON.stringify(t,null,2):n,p={role:"user",content:yield l(e,s,r)},f=s=>{const n={history:s};return{messages:[c,...s,p],query:t,saveResponse(t){if(e.history){let e;n.history.push(p),n.history.push({role:"assistant",content:t});const s=d(),r=u();e=null!==s&&h(s,r)?s:r,e.history=n.history,sessionStorage.moodleGPTHistory=JSON.stringify(e)}}}};if(!e.history)return f([]);const m=d(),g=u();return null!==m&&h(m,g)?f(m.history):f(g.history)}))}function f(e,t,s,n,r){if("function"==typeof t||!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t.set(e,s),s}function m(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)}let g=function(){const{crypto:e}=globalThis;if(e?.randomUUID)return g=e.randomUUID.bind(e),e.randomUUID();const t=new Uint8Array(1),s=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,(e=>(+e^s()&15>>+e/4).toString(16)))};function y(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}const _=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){const t=new Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return new Error(JSON.stringify(e))}catch{}}return new Error(e)};class w extends Error{}class b extends w{constructor(e,t,s,n){super(`${b.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=t;const r=t;this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,s){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e||!n)return new x({message:s,cause:_(t)});const r=t?.error;return 400===e?new A(e,r,s,n):401===e?new E(e,r,s,n):403===e?new R(e,r,s,n):404===e?new $(e,r,s,n):409===e?new O(e,r,s,n):422===e?new I(e,r,s,n):429===e?new q(e,r,s,n):e>=500?new k(e,r,s,n):new b(e,r,s,n)}}class v extends b{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class x extends b{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class S extends x{constructor({message:e}={}){super({message:e??"Request timed out."})}}class A extends b{}class E extends b{}class R extends b{}class $ extends b{}class O extends b{}class I extends b{}class q extends b{}class k extends b{}class C extends w{constructor(){super("Could not parse response content as the length limit was reached")}}class T extends w{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class L extends Error{constructor(e){super(e)}}const P=/^[a-z][a-z0-9+.-]*:/i;let N=e=>(N=Array.isArray,N(e)),j=N;function M(e){return"object"!=typeof e?{}:e??{}}function D(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}const W=e=>new Promise((t=>setTimeout(t,e))),B="5.23.2";const U=()=>{const e="undefined"!=typeof Deno&&null!=Deno.build?"deno":"undefined"!=typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":F(Deno.build.os),"X-Stainless-Arch":H(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===e)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":F(globalThis.process.platform??"unknown"),"X-Stainless-Arch":H(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const t=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const e=s.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return t?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":B,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const H=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",F=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 X;function J(...e){const t=globalThis.ReadableStream;if(void 0===t)throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function K(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return J({start(){},async pull(e){const{done:s,value:n}=await t.next();s?e.close():e.enqueue(n)},async cancel(){await(t.return?.())}})}function G(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}}}const V=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),z="RFC3986",Q=e=>String(e),Y={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:Q};let Z=(e,t)=>(Z=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Z(e,t));const ee=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),te=1024;function se(e,t){if(N(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const ne={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},re=function(e,t){Array.prototype.push.apply(e,N(t)?t:[t])};let oe;const ie={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,s,n,r)=>{if(0===e.length)return e;let o=e;if("symbol"==typeof e?o=Symbol.prototype.toString.call(e):"string"!=typeof e&&(o=String(e)),"iso-8859-1"===s)return escape(o).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));let i="";for(let e=0;e<o.length;e+=te){const t=o.length>=te?o.slice(e,e+te):o,s=[];for(let e=0;e<t.length;++e){let n=t.charCodeAt(e);45===n||46===n||95===n||126===n||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122||"RFC1738"===r&&(40===n||41===n)?s[s.length]=t.charAt(e):n<128?s[s.length]=ee[n]:n<2048?s[s.length]=ee[192|n>>6]+ee[128|63&n]:n<55296||n>=57344?s[s.length]=ee[224|n>>12]+ee[128|n>>6&63]+ee[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),s[s.length]=ee[240|n>>18]+ee[128|n>>12&63]+ee[128|n>>6&63]+ee[128|63&n])}i+=s.join("")}return i},encodeValuesOnly:!1,format:z,formatter:Q,indices:!1,serializeDate:e=>(oe??(oe=Function.prototype.call.bind(Date.prototype.toISOString)))(e),skipNulls:!1,strictNullHandling:!1};const ae={};function ce(e,t,s,n,r,o,i,a,c,l,u,d,h,p,f,m,g,y){let _=e,w=y,b=0,v=!1;for(;void 0!==(w=w.get(ae))&&!v;){const t=w.get(e);if(b+=1,void 0!==t){if(t===b)throw new RangeError("Cyclic object value");v=!0}void 0===w.get(ae)&&(b=0)}if("function"==typeof l?_=l(t,_):_ instanceof Date?_=h?.(_):"comma"===s&&N(_)&&(_=se(_,(function(e){return e instanceof Date?h?.(e):e}))),null===_){if(o)return c&&!m?c(t,ie.encoder,g,"key",p):t;_=""}if("string"==typeof(x=_)||"number"==typeof x||"boolean"==typeof x||"symbol"==typeof x||"bigint"==typeof x||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(_)){if(c){const e=m?t:c(t,ie.encoder,g,"key",p);return[f?.(e)+"="+f?.(c(_,ie.encoder,g,"value",p))]}return[f?.(t)+"="+f?.(String(_))]}var x;const S=[];if(void 0===_)return S;let A;if("comma"===s&&N(_))m&&c&&(_=se(_,c)),A=[{value:_.length>0?_.join(",")||null:void 0}];else if(N(l))A=l;else{const e=Object.keys(_);A=u?e.sort(u):e}const E=a?String(t).replace(/\./g,"%2E"):String(t),R=n&&N(_)&&1===_.length?E+"[]":E;if(r&&N(_)&&0===_.length)return R+"[]";for(let t=0;t<A.length;++t){const w=A[t],v="object"==typeof w&&void 0!==w.value?w.value:_[w];if(i&&null===v)continue;const x=d&&a?w.replace(/\./g,"%2E"):w,E=N(_)?"function"==typeof s?s(R,x):R:R+(d?"."+x:"["+x+"]");y.set(e,b);const $=new WeakMap;$.set(ae,y),re(S,ce(v,E,s,n,r,o,i,a,"comma"===s&&m&&N(_)?null:c,l,u,d,h,p,f,m,g,$))}return S}function le(e,t={}){let s=e;const n=function(e=ie){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||ie.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let s=z;if(void 0!==e.format){if(!Z(Y,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=Y[s];let r,o=ie.filter;if(("function"==typeof e.filter||N(e.filter))&&(o=e.filter),r=e.arrayFormat&&e.arrayFormat in ne?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":ie.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||ie.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:ie.addQueryPrefix,allowDots:i,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:ie.allowEmptyArrays,arrayFormat:r,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:ie.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?ie.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:ie.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:ie.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:ie.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:ie.encodeValuesOnly,filter:o,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:ie.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:ie.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:ie.strictNullHandling}}(t);let r,o;"function"==typeof n.filter?(o=n.filter,s=o("",s)):N(n.filter)&&(o=n.filter,r=o);const i=[];if("object"!=typeof s||null===s)return"";const a=ne[n.arrayFormat],c="comma"===a&&n.commaRoundTrip;r||(r=Object.keys(s)),n.sort&&r.sort(n.sort);const l=new WeakMap;for(let e=0;e<r.length;++e){const t=r[e];n.skipNulls&&null===s[t]||re(i,ce(s[t],t,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}const u=i.join(n.delimiter);let d=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}let ue,de;function he(e){let t;return(ue??(t=new globalThis.TextEncoder,ue=t.encode.bind(t)))(e)}function pe(e){let t;return(de??(t=new globalThis.TextDecoder,de=t.decode.bind(t)))(e)}var fe,me;class ge{constructor(){fe.set(this,void 0),me.set(this,void 0),f(this,fe,new Uint8Array),f(this,me,null)}decode(e){if(null==e)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?he(e):e;f(this,fe,function(e){let t=0;for(const s of e)t+=s.length;const s=new Uint8Array(t);let n=0;for(const t of e)s.set(t,n),n+=t.length;return s}([m(this,fe,"f"),t]));const s=[];let n;for(;null!=(n=ye(m(this,fe,"f"),m(this,me,"f")));){if(n.carriage&&null==m(this,me,"f")){f(this,me,n.index);continue}if(null!=m(this,me,"f")&&(n.index!==m(this,me,"f")+1||n.carriage)){s.push(pe(m(this,fe,"f").subarray(0,m(this,me,"f")-1))),f(this,fe,m(this,fe,"f").subarray(m(this,me,"f"))),f(this,me,null);continue}const e=null!==m(this,me,"f")?n.preceding-1:n.preceding,t=pe(m(this,fe,"f").subarray(0,e));s.push(t),f(this,fe,m(this,fe,"f").subarray(n.index)),f(this,me,null)}return s}flush(){return m(this,fe,"f").length?this.decode("\n"):[]}}function ye(e,t){for(let s=t??0;s<e.length;s++){if(10===e[s])return{preceding:s,index:s+1,carriage:!1};if(13===e[s])return{preceding:s,index:s+1,carriage:!0}}return null}function _e(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}fe=new WeakMap,me=new WeakMap,ge.NEWLINE_CHARS=new Set(["\n","\r"]),ge.NEWLINE_REGEXP=/\r\n|[\n\r]/g;const we={off:0,error:200,warn:300,info:400,debug:500},be=(e,t,s)=>{var n,r;if(e)return n=we,r=e,Object.prototype.hasOwnProperty.call(n,r)?e:void Ee(s).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(we))}`)};function ve(){}function xe(e,t,s){return!t||we[e]>we[s]?ve:t[e].bind(t)}const Se={error:ve,warn:ve,info:ve,debug:ve};let Ae=new WeakMap;function Ee(e){const t=e.logger,s=e.logLevel??"off";if(!t)return Se;const n=Ae.get(t);if(n&&n[0]===s)return n[1];const r={error:xe("error",t,s),warn:xe("warn",t,s),info:xe("info",t,s),debug:xe("debug",t,s)};return Ae.set(t,[s,r]),r}const Re=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map((([e,t])=>[e,"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t])))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);var $e,Oe,Ie;class qe{constructor(e,t,s){this.iterator=e,$e.set(this,void 0),this.controller=t,f(this,$e,s)}static fromSSEResponse(e,t,s){let n=!1;const r=s?Ee(s):console;return new qe((async function*(){if(n)throw new w("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){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new w("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new w("Attempted to iterate over a response with no body")}const s=new ke,n=new ge,r=G(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const s of e){if(null==s)continue;const e=s instanceof ArrayBuffer?new Uint8Array(s):"string"==typeof s?he(s):s;let n,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(n=_e(t));)yield t.slice(0,n),t=t.slice(n)}t.length>0&&(yield t)}(r))for(const t of n.decode(e)){const e=s.decode(t);e&&(yield e)}for(const e of n.flush()){const t=s.decode(e);t&&(yield t)}}(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null!==n.event&&n.event.startsWith("thread.")){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 b(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}else{let t;try{t=JSON.parse(n.data)}catch(e){throw r.error("Could not parse message into JSON:",n.data),r.error("From chunk:",n.raw),e}if(t&&t.error)throw new b(void 0,t.error,void 0,e.headers);yield t}s=!0}catch(e){if(y(e))return;throw e}finally{s||t.abort()}}),t,s)}static fromReadableStream(e,t,s){let n=!1;return new qe((async function*(){if(n)throw new w("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 ge,s=G(e);for await(const e of s)for(const s of t.decode(e))yield s;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(e){if(y(e))return;throw e}finally{s||t.abort()}}),t,s)}[($e=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=s.next();e.push(n),t.push(n)}return n.shift()}});return[new qe((()=>n(e)),this.controller,m(this,$e,"f")),new qe((()=>n(t)),this.controller,m(this,$e,"f"))]}toReadableStream(){const e=this;let t;return J({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:n}=await t.next();if(n)return e.close();const r=he(JSON.stringify(s)+"\n");e.enqueue(r)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class ke{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=function(e,t){const s=e.indexOf(t);if(-1!==s)return[e.substring(0,s),t,e.substring(s+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}async function Ce(e,t){const{response:s,requestLogID:n,retryOfRequestLogID:r,startTime:o}=t,i=await(async()=>{if(t.options.stream)return Ee(e).debug("response",s.status,s.url,s.headers,s.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(s,t.controller,e):qe.fromSSEResponse(s,t.controller,e);if(204===s.status)return null;if(t.options.__binaryResponse)return s;const n=s.headers.get("content-type"),r=n?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){return Te(await s.json(),s)}return await s.text()})();return Ee(e).debug(`[${n}] response parsed`,Re({retryOfRequestLogID:r,url:s.url,status:s.status,body:i,durationMs:Date.now()-o})),i}function Te(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 Le extends Promise{constructor(e,t,s=Ce){super((e=>{e(null)})),this.responsePromise=t,this.parseResponse=s,Oe.set(this,void 0),f(this,Oe,e)}_thenUnwrap(e){return new Le(m(this,Oe,"f"),this.responsePromise,(async(t,s)=>Te(e(await this.parseResponse(t,s),s),s.response)))}asResponse(){return this.responsePromise.then((e=>e.response))}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then((e=>this.parseResponse(m(this,Oe,"f"),e)))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Oe=new WeakMap;class Pe{constructor(e,t,s,n){Ie.set(this,void 0),f(this,Ie,e),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageRequestOptions()}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new w("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await m(this,Ie,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ie=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Ne extends Le{constructor(e,t,s){super(e,t,(async(e,t)=>new s(e,t.response,await Ce(e,t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}class je extends Pe{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class Me extends Pe{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...M(this.options.query),after:t}}:null}}class De extends Pe{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return!1!==this.has_more&&super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...M(this.options.query),after:e}}:null}}const We=()=>{if("undefined"==typeof File){const{process:e}=globalThis,t="string"==typeof e?.versions?.node&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Be(e,t,s){return We(),new File(e,t??"unknown_file",s)}function Ue(e){return("object"==typeof e&&null!==e&&("name"in e&&e.name&&String(e.name)||"url"in e&&e.url&&String(e.url)||"filename"in e&&e.filename&&String(e.filename)||"path"in e&&e.path&&String(e.path))||"").split(/[\\/]/).pop()||void 0}const He=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],Fe=async(e,t)=>({...e,body:await Je(e.body,t)}),Xe=new WeakMap;const Je=async(e,t)=>{if(!await function(e){const t="function"==typeof e?e:e.fetch,s=Xe.get(t);if(s)return s;const n=(async()=>{try{const e="Response"in t?t.Response:(await t("data:,")).constructor,s=new FormData;return s.toString()!==await new e(s).text()}catch{return!0}})();return Xe.set(t,n),n}(t))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const s=new FormData;return await Promise.all(Object.entries(e||{}).map((([e,t])=>Ke(s,e,t)))),s},Ke=async(e,t,s)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if(s instanceof Response)e.append(t,Be([await s.blob()],Ue(s)));else if(He(s))e.append(t,Be([await new Response(K(s)).blob()],Ue(s)));else if((e=>e instanceof Blob&&"name"in e)(s))e.append(t,s,Ue(s));else if(Array.isArray(s))await Promise.all(s.map((s=>Ke(e,t+"[]",s))));else{if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map((([s,n])=>Ke(e,`${t}[${s}]`,n))))}}},Ge=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 Ve(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(Ge(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else{if(!He(e)){const t=e?.constructor?.name;throw new Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";const t=Object.getOwnPropertyNames(e);return`; props: [${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`)}for await(const s of e)t.push(...await Ve(s))}return t}class ze{constructor(e){this._client=e}}function Qe(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Ye=Object.freeze(Object.create(null)),Ze=(e=Qe)=>function(t,...s){if(1===t.length)return t[0];let n=!1;const r=[],o=t.reduce(((t,o,i)=>{/[?#]/.test(o)&&(n=!0);const a=s[i];let c=(n?encodeURIComponent:e)(""+a);return i!==s.length&&(null==a||"object"==typeof a&&a.toString===Object.getPrototypeOf(Object.getPrototypeOf(a.hasOwnProperty??Ye)??Ye)?.toString)&&(c=a+"",r.push({start:t.length+o.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(a).slice(8,-1)} is not a valid path parameter`})),t+o+(i===s.length?"":c)}),""),i=o.split(/[?#]/,1)[0],a=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;null!==(c=a.exec(i));)r.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(r.sort(((e,t)=>e.start-t.start)),r.length>0){let e=0;const t=r.reduce(((t,s)=>{const n=" ".repeat(s.start-e),r="^".repeat(s.length);return e=s.start+s.length,t+n+r}),"");throw new w(`Path parameters result in path with invalid segments:\n${r.map((e=>e.error)).join("\n")}\n${o}\n${t}`)}return o},et=Ze(Qe);let tt=class extends ze{list(e,t={},s){return this._client.getAPIList(et`/chat/completions/${e}/messages`,Me,{query:t,...s})}};function st(e){return void 0!==e&&"function"in e&&void 0!==e.function}function nt(e){return"auto-parseable-response-format"===e?.$brand}function rt(e){return"auto-parseable-tool"===e?.$brand}function ot(e,t){const s=e.choices.map((e=>{if("length"===e.finish_reason)throw new C;if("content_filter"===e.finish_reason)throw new T;return lt(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map((e=>function(e,t){const s=e.tools?.find((e=>st(e)&&e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:rt(s)?s.$parseRaw(t.function.arguments):s?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?it(t,e.message.content):null}}}));return{...e,choices:s}}function it(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 at(e,t){if(!e||!("tools"in e)||!e.tools)return!1;const s=e.tools?.find((e=>st(e)&&e.function?.name===t.function.name));return st(s)&&(rt(s)||s?.function.strict||!1)}function ct(e){return!!nt(e.response_format)||(e.tools?.some((e=>rt(e)||"function"===e.type&&!0===e.function.strict))??!1)}function lt(e){for(const t of e||[])if("function"!==t.type)throw new w(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}const ut=e=>"assistant"===e?.role,dt=e=>"tool"===e?.role;var ht,pt,ft,mt,gt,yt,_t,wt,bt,vt,xt,St,At,Et,Rt,$t,Ot,It,qt,kt,Ct;class Tt{constructor(){ht.add(this),this.controller=new AbortController,pt.set(this,void 0),ft.set(this,(()=>{})),mt.set(this,(()=>{})),gt.set(this,void 0),yt.set(this,(()=>{})),_t.set(this,(()=>{})),wt.set(this,{}),bt.set(this,!1),vt.set(this,!1),xt.set(this,!1),St.set(this,!1),f(this,pt,new Promise(((e,t)=>{f(this,ft,e),f(this,mt,t)}))),f(this,gt,new Promise(((e,t)=>{f(this,yt,e),f(this,_t,t)}))),m(this,pt,"f").catch((()=>{})),m(this,gt,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),m(this,ht,"m",At).bind(this))}),0)}_connected(){this.ended||(m(this,ft,"f").call(this),this._emit("connect"))}get ended(){return m(this,bt,"f")}get errored(){return m(this,vt,"f")}get aborted(){return m(this,xt,"f")}abort(){this.controller.abort()}on(e,t){return(m(this,wt,"f")[e]||(m(this,wt,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=m(this,wt,"f")[e];if(!s)return this;const n=s.findIndex((e=>e.listener===t));return n>=0&&s.splice(n,1),this}once(e,t){return(m(this,wt,"f")[e]||(m(this,wt,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,s)=>{f(this,St,!0),"error"!==e&&this.once("error",s),this.once(e,t)}))}async done(){f(this,St,!0),await m(this,gt,"f")}_emit(e,...t){if(m(this,bt,"f"))return;"end"===e&&(f(this,bt,!0),m(this,yt,"f").call(this));const s=m(this,wt,"f")[e];if(s&&(m(this,wt,"f")[e]=s.filter((e=>!e.once)),s.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return m(this,St,"f")||s?.length||Promise.reject(e),m(this,mt,"f").call(this,e),m(this,_t,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];m(this,St,"f")||s?.length||Promise.reject(e),m(this,mt,"f").call(this,e),m(this,_t,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function Lt(e){return"function"==typeof e.parse}pt=new WeakMap,ft=new WeakMap,mt=new WeakMap,gt=new WeakMap,yt=new WeakMap,_t=new WeakMap,wt=new WeakMap,bt=new WeakMap,vt=new WeakMap,xt=new WeakMap,St=new WeakMap,ht=new WeakSet,At=function(e){if(f(this,vt,!0),e instanceof Error&&"AbortError"===e.name&&(e=new v),e instanceof v)return f(this,xt,!0),this._emit("abort",e);if(e instanceof w)return this._emit("error",e);if(e instanceof Error){const t=new w(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new w(String(e)))};const Pt=10;class Nt extends Tt{constructor(){super(...arguments),Et.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),dt(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(ut(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionToolCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new w("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),m(this,Et,"m",Rt).call(this)}async finalMessage(){return await this.done(),m(this,Et,"m",$t).call(this)}async finalFunctionToolCall(){return await this.done(),m(this,Et,"m",Ot).call(this)}async finalFunctionToolCallResult(){return await this.done(),m(this,Et,"m",It).call(this)}async totalUsage(){return await this.done(),m(this,Et,"m",qt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=m(this,Et,"m",$t).call(this);t&&this._emit("finalMessage",t);const s=m(this,Et,"m",Rt).call(this);s&&this._emit("finalContent",s);const n=m(this,Et,"m",Ot).call(this);n&&this._emit("finalFunctionToolCall",n);const r=m(this,Et,"m",It).call(this);null!=r&&this._emit("finalFunctionToolCallResult",r),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",m(this,Et,"m",qt).call(this))}async _createChatCompletion(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),m(this,Et,"m",kt).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ot(r,t))}async _runChatCompletion(e,t,s){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){const n="tool",{tool_choice:r="auto",stream:o,...i}=t,a="string"!=typeof r&&"function"===r.type&&r?.function?.name,{maxChatCompletions:c=Pt}=s||{},l=t.tools.map((e=>{if(rt(e)){if(!e.$callback)throw new w("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e})),u={};for(const e of l)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const d="tools"in t?l.map((e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e)):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){const t=await this._createChatCompletion(e,{...i,tool_choice:r,tools:d,messages:[...this.messages]},s),o=t.choices[0]?.message;if(!o)throw new w("missing message in ChatCompletion response");if(!o.tool_calls?.length)return;for(const e of o.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:s,arguments:r}=e.function,o=u[s];if(!o){const e=`Invalid tool_call: ${JSON.stringify(s)}. Available options are: ${Object.keys(u).map((e=>JSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(a&&a!==s){const e=`Invalid tool_call: ${JSON.stringify(s)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let i;try{i=Lt(o)?await o.parse(r):r}catch(e){const s=e instanceof Error?e.message:String(e);this._addMessage({role:n,tool_call_id:t,content:s});continue}const c=await o.function(i,this),l=m(this,Et,"m",Ct).call(this,c);if(this._addMessage({role:n,tool_call_id:t,content:l}),a)return}}}}Et=new WeakSet,Rt=function(){return m(this,Et,"m",$t).call(this).content??null},$t=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(ut(t)){return{...t,content:t.content??null,refusal:t.refusal??null}}}throw new w("stream ended without producing a ChatCompletionMessage with role=assistant")},Ot=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ut(t)&&t?.tool_calls?.length)return t.tool_calls.filter((e=>"function"===e.type)).at(-1)?.function}},It=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(dt(t)&&null!=t.content&&"string"==typeof t.content&&this.messages.some((e=>"assistant"===e.role&&e.tool_calls?.some((e=>"function"===e.type&&e.id===t.tool_call_id)))))return t.content}},qt=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},kt=function(e){if(null!=e.n&&e.n>1)throw new w("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ct=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class jt extends Nt{static runTools(e,t,s){const n=new jt,r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,r))),n}_addMessage(e,t=!0){super._addMessage(e,t),ut(e)&&e.content&&this._emit("content",e.content)}}const Mt=1,Dt=2,Wt=4,Bt=8,Ut=16,Ht=32,Ft=64,Xt=128,Jt=256,Kt=511;class Gt extends Error{}class Vt extends Error{}const zt=(e,t)=>{const s=e.length;let n=0;const r=e=>{throw new Gt(`${e} at position ${n}`)},o=e=>{throw new Vt(`${e} at position ${n}`)},i=()=>(d(),n>=s&&r("Unexpected end of input"),'"'===e[n]?a():"{"===e[n]?c():"["===e[n]?l():"null"===e.substring(n,n+4)||Ut&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||Ht&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||Ht&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||Xt&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||Jt&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):"NaN"===e.substring(n,n+3)||Ft&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),a=()=>{const i=n;let a=!1;for(n++;n<s&&('"'!==e[n]||a&&"\\"===e[n-1]);)a="\\"===e[n]&&!a,n++;if('"'==e.charAt(n))try{return JSON.parse(e.substring(i,++n-Number(a)))}catch(e){o(String(e))}else if(Mt&t)try{return JSON.parse(e.substring(i,n-Number(a))+'"')}catch(t){return JSON.parse(e.substring(i,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},c=()=>{n++,d();const o={};try{for(;"}"!==e[n];){if(d(),n>=s&&Bt&t)return o;const r=a();d(),n++;try{const e=i();Object.defineProperty(o,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Bt&t)return o;throw e}d(),","===e[n]&&n++}}catch(e){if(Bt&t)return o;r("Expected '}' at end of object")}return n++,o},l=()=>{n++;const s=[];try{for(;"]"!==e[n];)s.push(i()),d(),","===e[n]&&n++}catch(e){if(Wt&t)return s;r("Expected ']' at end of array")}return n++,s},u=()=>{if(0===n){"-"===e&&Dt&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(s){if(Dt&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}o(String(s))}}const i=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=s||Dt&t||r("Unterminated number literal");try{return JSON.parse(e.substring(i,n))}catch(s){"-"===e.substring(i,n)&&Dt&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(e){o(String(e))}}},d=()=>{for(;n<s&&" \n\r\t".includes(e[n]);)n++};return i()},Qt=e=>function(e,t=Kt){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return zt(e.trim(),t)}(e,Kt^Dt);var Yt,Zt,es,ts,ss,ns,rs,os,is,as,cs,ls;class us extends Nt{constructor(e){super(),Yt.add(this),Zt.set(this,void 0),es.set(this,void 0),ts.set(this,void 0),f(this,Zt,e),f(this,es,[])}get currentChatCompletionSnapshot(){return m(this,ts,"f")}static fromReadableStream(e){const t=new us(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,s){const n=new us(t);return n._run((()=>n._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createChatCompletion(e,t,s){super._createChatCompletion;const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),m(this,Yt,"m",ss).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const e of r)m(this,Yt,"m",rs).call(this,e);if(r.controller.signal?.aborted)throw new v;return this._addChatCompletion(m(this,Yt,"m",as).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),m(this,Yt,"m",ss).call(this),this._connected();const n=qe.fromReadableStream(e,this.controller);let r;for await(const e of n)r&&r!==e.id&&this._addChatCompletion(m(this,Yt,"m",as).call(this)),m(this,Yt,"m",rs).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new v;return this._addChatCompletion(m(this,Yt,"m",as).call(this))}[(Zt=new WeakMap,es=new WeakMap,ts=new WeakMap,Yt=new WeakSet,ss=function(){this.ended||f(this,ts,void 0)},ns=function(e){let t=m(this,es,"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},m(this,es,"f")[e.index]=t,t)},rs=function(e){if(this.ended)return;const t=m(this,Yt,"m",ls).call(this,e);this._emit("chunk",e,t);for(const s of e.choices){const e=t.choices[s.index];null!=s.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",s.delta.content,e.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=s.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:e.message.refusal}),null!=s.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=s.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=m(this,Yt,"m",ns).call(this,e);e.finish_reason&&(m(this,Yt,"m",is).call(this,e),null!=n.current_tool_call_index&&m(this,Yt,"m",os).call(this,e,n.current_tool_call_index));for(const t of s.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(m(this,Yt,"m",is).call(this,e),null!=n.current_tool_call_index&&m(this,Yt,"m",os).call(this,e,n.current_tool_call_index)),n.current_tool_call_index=t.index;for(const t of s.delta.tool_calls??[]){const s=e.message.tool_calls?.[t.index];s?.type&&("function"===s?.type&&this._emit("tool_calls.function.arguments.delta",{name:s.function?.name,index:t.index,arguments:s.function.arguments,parsed_arguments:s.function.parsed_arguments,arguments_delta:t.function?.arguments??""}))}}},os=function(e,t){if(m(this,Yt,"m",ns).call(this,e).done_tool_calls.has(t))return;const s=e.message.tool_calls?.[t];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if("function"===s.type){const e=m(this,Zt,"f")?.tools?.find((e=>st(e)&&e.function.name===s.function.name));this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:t,arguments:s.function.arguments,parsed_arguments:rt(e)?e.$parseRaw(s.function.arguments):e?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},is=function(e){const t=m(this,Yt,"m",ns).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const s=m(this,Yt,"m",cs).call(this);this._emit("content.done",{content:e.message.content,parsed:s?s.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},as=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");const e=m(this,ts,"f");if(!e)throw new w("request ended without sending any chunks");return f(this,ts,void 0),f(this,es,[]),function(e,t){const{id:s,choices:n,created:r,model:o,system_fingerprint:i,...a}=e,c={...a,id:s,choices:n.map((({message:t,finish_reason:s,index:n,logprobs:r,...o})=>{if(!s)throw new w(`missing finish_reason for choice ${n}`);const{content:i=null,function_call:a,tool_calls:c,...l}=t,u=t.role;if(!u)throw new w(`missing role for choice ${n}`);if(a){const{arguments:e,name:c}=a;if(null==e)throw new w(`missing function_call.arguments for choice ${n}`);if(!c)throw new w(`missing function_call.name for choice ${n}`);return{...o,message:{content:i,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}}return c?{...o,index:n,finish_reason:s,logprobs:r,message:{...l,role:u,content:i,refusal:t.refusal??null,tool_calls:c.map(((t,s)=>{const{function:r,type:o,id:i,...a}=t,{arguments:c,name:l,...u}=r||{};if(null==i)throw new w(`missing choices[${n}].tool_calls[${s}].id\n${ds(e)}`);if(null==o)throw new w(`missing choices[${n}].tool_calls[${s}].type\n${ds(e)}`);if(null==l)throw new w(`missing choices[${n}].tool_calls[${s}].function.name\n${ds(e)}`);if(null==c)throw new w(`missing choices[${n}].tool_calls[${s}].function.arguments\n${ds(e)}`);return{...a,id:i,type:o,function:{...u,name:l,arguments:c}}}))}}:{...o,message:{...l,content:i,role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}})),created:r,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&ct(t)?ot(e,t):{...e,choices:e.choices.map((e=>(lt(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}})))}}(c,t)}(e,m(this,Zt,"f"))},cs=function(){const e=m(this,Zt,"f")?.response_format;return nt(e)?e:null},ls=function(e){var t,s,n,r;let o=m(this,ts,"f");const{choices:i,...a}=e;o?Object.assign(o,a):o=f(this,ts,{...a,choices:[]});for(const{delta:i,finish_reason:a,index:c,logprobs:l=null,...u}of e.choices){let e=o.choices[c];if(e||(e=o.choices[c]={finish_reason:a,index:c,message:{},logprobs:l,...u}),l)if(e.logprobs){const{content:n,refusal:r,...o}=l;Object.assign(e.logprobs,o),n&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...n)),r&&((s=e.logprobs).refusal??(s.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},l);if(a&&(e.finish_reason=a,m(this,Zt,"f")&&ct(m(this,Zt,"f")))){if("length"===a)throw new C;if("content_filter"===a)throw new T}if(Object.assign(e,u),!i)continue;const{content:d,refusal:h,function_call:p,role:f,tool_calls:g,...y}=i;if(Object.assign(e.message,y),h&&(e.message.refusal=(e.message.refusal||"")+h),f&&(e.message.role=f),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||"")+d,!e.message.refusal&&m(this,Yt,"m",cs).call(this)&&(e.message.parsed=Qt(e.message.content))),g){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:s,type:n,function:o,...i}of g){const a=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(a,i),s&&(a.id=s),n&&(a.type=n),o&&(a.function??(a.function={name:o.name??"",arguments:""})),o?.name&&(a.function.name=o.name),o?.arguments&&(a.function.arguments+=o.arguments,at(m(this,Zt,"f"),a)&&(a.function.parsed_arguments=Qt(a.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",(s=>{const n=t.shift();n?n.resolve(s):e.push(s)})),this.on("end",(()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),this.on("error",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise(((e,s)=>t.push({resolve:e,reject:s}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new qe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ds(e){return JSON.stringify(e)}class hs extends us{static fromReadableStream(e){const t=new hs(null);return t._run((()=>t._fromReadableStream(e))),t}static runTools(e,t,s){const n=new hs(t),r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,r))),n}}let ps=class extends ze{constructor(){super(...arguments),this.messages=new tt(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(et`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(et`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",Me,{query:e,...t})}delete(e,t){return this._client.delete(et`/chat/completions/${e}`,t)}parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new w(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new w(`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":"chat.completions.parse"}})._thenUnwrap((t=>ot(t,e)))}runTools(e,t){return e.stream?hs.runTools(this._client,e,t):jt.runTools(this._client,e,t)}stream(e,t){return us.createChatCompletion(this._client,e,t)}};ps.Messages=tt;class fs extends ze{constructor(){super(...arguments),this.completions=new ps(this._client)}}fs.Completions=ps;const ms=Symbol("brand.privateNullableHeaders");function*gs(e){if(!e)return;if(ms in e){const{values:t,nulls:s}=e;yield*t.entries();for(const e of s)yield[e,null];return}let t,s=!1;e instanceof Headers?t=e.entries():j(e)?t=e:(s=!0,t=Object.entries(e??{}));for(let e of t){const t=e[0];if("string"!=typeof t)throw new TypeError("expected header name to be a string");const n=j(e[1])?e[1]:[e[1]];let r=!1;for(const e of n)void 0!==e&&(s&&!r&&(r=!0,yield[t,null]),yield[t,e])}}const ys=e=>{const t=new Headers,s=new Set;for(const n of e){const e=new Set;for(const[r,o]of gs(n)){const n=r.toLowerCase();e.has(n)||(t.delete(r),e.add(n)),null===o?(t.delete(r),s.add(n)):(t.append(r,o),s.delete(n))}}return{[ms]:!0,values:t,nulls:s}};class _s extends ze{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:ys([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class ws extends ze{create(e,t){return this._client.post("/audio/transcriptions",Fe({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class bs extends ze{create(e,t){return this._client.post("/audio/translations",Fe({body:e,...t,__metadata:{model:e.model}},this._client))}}class vs extends ze{constructor(){super(...arguments),this.transcriptions=new ws(this._client),this.translations=new bs(this._client),this.speech=new _s(this._client)}}vs.Transcriptions=ws,vs.Translations=bs,vs.Speech=_s;class xs extends ze{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(et`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",Me,{query:e,...t})}cancel(e,t){return this._client.post(et`/batches/${e}/cancel`,t)}}class Ss extends ze{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(et`/assistants/${e}`,{...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(et`/assistants/${e}`,{body:t,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",Me,{query:e,...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(et`/assistants/${e}`,{...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class As extends ze{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Es extends ze{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let Rs=class extends ze{constructor(){super(...arguments),this.sessions=new As(this._client),this.transcriptionSessions=new Es(this._client)}};Rs.Sessions=As,Rs.TranscriptionSessions=Es;class $s extends ze{create(e,t,s){return this._client.post(et`/threads/${e}/messages`,{body:t,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(et`/threads/${n}/messages/${e}`,{...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:n,...r}=t;return this._client.post(et`/threads/${n}/messages/${e}`,{body:r,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(et`/threads/${e}/messages`,Me,{query:t,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{thread_id:n}=t;return this._client.delete(et`/threads/${n}/messages/${e}`,{...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class Os extends ze{retrieve(e,t,s){const{thread_id:n,run_id:r,...o}=t;return this._client.get(et`/threads/${n}/runs/${r}/steps/${e}`,{query:o,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){const{thread_id:n,...r}=t;return this._client.getAPIList(et`/threads/${n}/runs/${e}/steps`,Me,{query:r,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const Is=e=>void 0!==globalThis.process?globalThis.process.env?.[e]?.trim()??void 0:void 0!==globalThis.Deno?globalThis.Deno.env?.get?.(e)?.trim():void 0;var qs,ks,Cs,Ts,Ls,Ps,Ns,js,Ms,Ds,Ws,Bs,Us,Hs,Fs,Xs,Js,Ks,Gs,Vs,zs,Qs,Ys;class Zs extends Tt{constructor(){super(...arguments),qs.add(this),Cs.set(this,[]),Ts.set(this,{}),Ls.set(this,{}),Ps.set(this,void 0),Ns.set(this,void 0),js.set(this,void 0),Ms.set(this,void 0),Ds.set(this,void 0),Ws.set(this,void 0),Bs.set(this,void 0),Us.set(this,void 0),Hs.set(this,void 0)}[(Cs=new WeakMap,Ts=new WeakMap,Ls=new WeakMap,Ps=new WeakMap,Ns=new WeakMap,js=new WeakMap,Ms=new WeakMap,Ds=new WeakMap,Ws=new WeakMap,Bs=new WeakMap,Us=new WeakMap,Hs=new WeakMap,qs=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",(s=>{const n=t.shift();n?n.resolve(s):e.push(s)})),this.on("end",(()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),this.on("error",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise(((e,s)=>t.push({resolve:e,reject:s}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new ks;return t._run((()=>t._fromReadableStream(e))),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const n=qe.fromReadableStream(e,this.controller);for await(const e of n)m(this,qs,"m",Fs).call(this,e);if(n.controller.signal?.aborted)throw new v;return this._addRun(m(this,qs,"m",Xs).call(this))}toReadableStream(){return new qe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n){const r=new ks;return r._run((()=>r._runToolAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}async _createToolAssistantStream(e,t,s,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const o={...s,stream:!0},i=await e.submitToolOutputs(t,o,{...n,signal:this.controller.signal});this._connected();for await(const e of i)m(this,qs,"m",Fs).call(this,e);if(i.controller.signal?.aborted)throw new v;return this._addRun(m(this,qs,"m",Xs).call(this))}static createThreadAssistantStream(e,t,s){const n=new ks;return n._run((()=>n._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}static createAssistantStream(e,t,s,n){const r=new ks;return r._run((()=>r._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}currentEvent(){return m(this,Bs,"f")}currentRun(){return m(this,Us,"f")}currentMessageSnapshot(){return m(this,Ps,"f")}currentRunStepSnapshot(){return m(this,Hs,"f")}async finalRunSteps(){return await this.done(),Object.values(m(this,Ts,"f"))}async finalMessages(){return await this.done(),Object.values(m(this,Ls,"f"))}async finalRun(){if(await this.done(),!m(this,Ns,"f"))throw Error("Final run was not received.");return m(this,Ns,"f")}async _createThreadAssistantStream(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort())));const r={...t,stream:!0},o=await e.createAndRun(r,{...s,signal:this.controller.signal});this._connected();for await(const e of o)m(this,qs,"m",Fs).call(this,e);if(o.controller.signal?.aborted)throw new v;return this._addRun(m(this,qs,"m",Xs).call(this))}async _createAssistantStream(e,t,s,n){const r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const o={...s,stream:!0},i=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(const e of i)m(this,qs,"m",Fs).call(this,e);if(i.controller.signal?.aborted)throw new v;return this._addRun(m(this,qs,"m",Xs).call(this))}static accumulateDelta(e,t){for(const[s,n]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=n;continue}let t=e[s];if(null!=t)if("index"!==s&&"type"!==s){if("string"==typeof t&&"string"==typeof n)t+=n;else if("number"==typeof t&&"number"==typeof n)t+=n;else{if(!D(t)||!D(n)){if(Array.isArray(t)&&Array.isArray(n)){if(t.every((e=>"string"==typeof e||"number"==typeof e))){t.push(...n);continue}for(const e of n){if(!D(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const s=e.index;if(null==s)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof s)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${s}`);const n=t[s];null==n?t.push(e):t[s]=this.accumulateDelta(n,e)}continue}throw Error(`Unhandled record type: ${s}, deltaValue: ${n}, accValue: ${t}`)}t=this.accumulateDelta(t,n)}e[s]=t}else e[s]=n;else e[s]=n}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,n){return await this._createAssistantStream(t,e,s,n)}async _runToolAssistantStream(e,t,s,n){return await this._createToolAssistantStream(t,e,s,n)}}ks=Zs,Fs=function(e){if(!this.ended)switch(f(this,Bs,e),m(this,qs,"m",Gs).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":m(this,qs,"m",Ys).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":m(this,qs,"m",Ks).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":m(this,qs,"m",Js).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Xs=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");if(!m(this,Ns,"f"))throw Error("Final run has not been received");return m(this,Ns,"f")},Js=function(e){const[t,s]=m(this,qs,"m",zs).call(this,e,m(this,Ps,"f"));f(this,Ps,t),m(this,Ls,"f")[t.id]=t;for(const e of s){const s=t.content[e.index];"text"==s?.type&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if("text"==s.type&&s.text){let e=s.text,n=t.content[s.index];if(!n||"text"!=n.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,n.text)}if(s.index!=m(this,js,"f")){if(m(this,Ms,"f"))switch(m(this,Ms,"f").type){case"text":this._emit("textDone",m(this,Ms,"f").text,m(this,Ps,"f"));break;case"image_file":this._emit("imageFileDone",m(this,Ms,"f").image_file,m(this,Ps,"f"))}f(this,js,s.index)}f(this,Ms,t.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==m(this,js,"f")){const t=e.data.content[m(this,js,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,m(this,Ps,"f"));break;case"text":this._emit("textDone",t.text,m(this,Ps,"f"))}}m(this,Ps,"f")&&this._emit("messageDone",e.data),f(this,Ps,void 0)}},Ks=function(e){const t=m(this,qs,"m",Vs).call(this,e);switch(f(this,Hs,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&"tool_calls"==s.step_details.type&&s.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of s.step_details.tool_calls)e.index==m(this,Ds,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(m(this,Ws,"f")&&this._emit("toolCallDone",m(this,Ws,"f")),f(this,Ds,e.index),f(this,Ws,t.step_details.tool_calls[e.index]),m(this,Ws,"f")&&this._emit("toolCallCreated",m(this,Ws,"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":f(this,Hs,void 0);"tool_calls"==e.data.step_details.type&&m(this,Ws,"f")&&(this._emit("toolCallDone",m(this,Ws,"f")),f(this,Ws,void 0)),this._emit("runStepDone",e.data,t)}},Gs=function(e){m(this,Cs,"f").push(e),this._emit("event",e)},Vs=function(e){switch(e.event){case"thread.run.step.created":return m(this,Ts,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=m(this,Ts,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const n=ks.accumulateDelta(t,s.delta);m(this,Ts,"f")[e.data.id]=n}return m(this,Ts,"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":m(this,Ts,"f")[e.data.id]=e.data}if(m(this,Ts,"f")[e.data.id])return m(this,Ts,"f")[e.data.id];throw new Error("No snapshot available")},zs=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let n=e.data;if(n.delta.content)for(const e of n.delta.content)if(e.index in t.content){let s=t.content[e.index];t.content[e.index]=m(this,qs,"m",Qs).call(this,e,s)}else t.content[e.index]=e,s.push(e);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Qs=function(e,t){return ks.accumulateDelta(t,e)},Ys=function(e){switch(f(this,Us,e.data),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":case"thread.run.incomplete":f(this,Ns,e.data),m(this,Ws,"f")&&(this._emit("toolCallDone",m(this,Ws,"f")),f(this,Ws,void 0))}};let en=class extends ze{constructor(){super(...arguments),this.steps=new Os(this._client)}create(e,t,s){const{include:n,...r}=t;return this._client.post(et`/threads/${e}/runs`,{query:{include:n},body:r,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}retrieve(e,t,s){const{thread_id:n}=t;return this._client.get(et`/threads/${n}/runs/${e}`,{...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:n,...r}=t;return this._client.post(et`/threads/${n}/runs/${e}`,{body:r,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(et`/threads/${e}/runs`,Me,{query:t,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{thread_id:n}=t;return this._client.post(et`/threads/${n}/runs/${e}/cancel`,{...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(n.id,{thread_id:e},s)}createAndStream(e,t,s){return Zs.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const n=ys([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:o}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...n}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await W(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,s){return Zs.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:n,...r}=t;return this._client.post(et`/threads/${n}/runs/${e}/submit_tool_outputs`,{body:r,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,s){const n=await this.submitToolOutputs(e,t,s);return await this.poll(n.id,t,s)}submitToolOutputsStream(e,t,s){return Zs.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};en.Steps=Os;class tn extends ze{constructor(){super(...arguments),this.runs=new en(this._client),this.messages=new $s(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(et`/threads/${e}`,{...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(et`/threads/${e}`,{body:t,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(et`/threads/${e}`,{...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return Zs.createThreadAssistantStream(e,this._client.beta.threads,t)}}tn.Runs=en,tn.Messages=$s;class sn extends ze{constructor(){super(...arguments),this.realtime=new Rs(this._client),this.assistants=new Ss(this._client),this.threads=new tn(this._client)}}sn.Realtime=Rs,sn.Assistants=Ss,sn.Threads=tn;class nn extends ze{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class rn extends ze{retrieve(e,t,s){const{container_id:n}=t;return this._client.get(et`/containers/${n}/files/${e}/content`,{...s,headers:ys([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let on=class extends ze{constructor(){super(...arguments),this.content=new rn(this._client)}create(e,t,s){return this._client.post(et`/containers/${e}/files`,Fe({body:t,...s},this._client))}retrieve(e,t,s){const{container_id:n}=t;return this._client.get(et`/containers/${n}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(et`/containers/${e}/files`,Me,{query:t,...s})}delete(e,t,s){const{container_id:n}=t;return this._client.delete(et`/containers/${n}/files/${e}`,{...s,headers:ys([{Accept:"*/*"},s?.headers])})}};on.Content=rn;class an extends ze{constructor(){super(...arguments),this.files=new on(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(et`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",Me,{query:e,...t})}delete(e,t){return this._client.delete(et`/containers/${e}`,{...t,headers:ys([{Accept:"*/*"},t?.headers])})}}an.Files=on;class cn extends ze{create(e,t,s){const{include:n,...r}=t;return this._client.post(et`/conversations/${e}/items`,{query:{include:n},body:r,...s})}retrieve(e,t,s){const{conversation_id:n,...r}=t;return this._client.get(et`/conversations/${n}/items/${e}`,{query:r,...s})}list(e,t={},s){return this._client.getAPIList(et`/conversations/${e}/items`,De,{query:t,...s})}delete(e,t,s){const{conversation_id:n}=t;return this._client.delete(et`/conversations/${n}/items/${e}`,s)}}class ln extends ze{constructor(){super(...arguments),this.items=new cn(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(et`/conversations/${e}`,t)}update(e,t,s){return this._client.post(et`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(et`/conversations/${e}`,t)}}ln.Items=cn;class un extends ze{create(e,t){const s=!!e.encoding_format;let n=s?e.encoding_format:"base64";s&&Ee(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const r=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return s?r:(Ee(this._client).debug("embeddings/decoding base64 embeddings from base64"),r._thenUnwrap((e=>(e&&e.data&&e.data.forEach((e=>{const t=e.embedding;e.embedding=(e=>{if("undefined"!=typeof Buffer){const t=Buffer.from(e,"base64");return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{const t=atob(e),s=t.length,n=new Uint8Array(s);for(let e=0;e<s;e++)n[e]=t.charCodeAt(e);return Array.from(new Float32Array(n.buffer))}})(t)})),e))))}}class dn extends ze{retrieve(e,t,s){const{eval_id:n,run_id:r}=t;return this._client.get(et`/evals/${n}/runs/${r}/output_items/${e}`,s)}list(e,t,s){const{eval_id:n,...r}=t;return this._client.getAPIList(et`/evals/${n}/runs/${e}/output_items`,Me,{query:r,...s})}}class hn extends ze{constructor(){super(...arguments),this.outputItems=new dn(this._client)}create(e,t,s){return this._client.post(et`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){const{eval_id:n}=t;return this._client.get(et`/evals/${n}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(et`/evals/${e}/runs`,Me,{query:t,...s})}delete(e,t,s){const{eval_id:n}=t;return this._client.delete(et`/evals/${n}/runs/${e}`,s)}cancel(e,t,s){const{eval_id:n}=t;return this._client.post(et`/evals/${n}/runs/${e}`,s)}}hn.OutputItems=dn;class pn extends ze{constructor(){super(...arguments),this.runs=new hn(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(et`/evals/${e}`,t)}update(e,t,s){return this._client.post(et`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",Me,{query:e,...t})}delete(e,t){return this._client.delete(et`/evals/${e}`,t)}}pn.Runs=hn;let fn=class extends ze{create(e,t){return this._client.post("/files",Fe({body:e,...t},this._client))}retrieve(e,t){return this._client.get(et`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",Me,{query:e,...t})}delete(e,t){return this._client.delete(et`/files/${e}`,t)}content(e,t){return this._client.get(et`/files/${e}/content`,{...t,headers:ys([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){const n=new Set(["processed","error","deleted"]),r=Date.now();let o=await this.retrieve(e);for(;!o.status||!n.has(o.status);)if(await W(t),o=await this.retrieve(e),Date.now()-r>s)throw new S({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return o}};class mn extends ze{}let gn=class extends ze{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class yn extends ze{constructor(){super(...arguments),this.graders=new gn(this._client)}}yn.Graders=gn;class _n extends ze{create(e,t,s){return this._client.getAPIList(et`/fine_tuning/checkpoints/${e}/permissions`,je,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(et`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}delete(e,t,s){const{fine_tuned_model_checkpoint:n}=t;return this._client.delete(et`/fine_tuning/checkpoints/${n}/permissions/${e}`,s)}}let wn=class extends ze{constructor(){super(...arguments),this.permissions=new _n(this._client)}};wn.Permissions=_n;class bn extends ze{list(e,t={},s){return this._client.getAPIList(et`/fine_tuning/jobs/${e}/checkpoints`,Me,{query:t,...s})}}class vn extends ze{constructor(){super(...arguments),this.checkpoints=new bn(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(et`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",Me,{query:e,...t})}cancel(e,t){return this._client.post(et`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(et`/fine_tuning/jobs/${e}/events`,Me,{query:t,...s})}pause(e,t){return this._client.post(et`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(et`/fine_tuning/jobs/${e}/resume`,t)}}vn.Checkpoints=bn;class xn extends ze{constructor(){super(...arguments),this.methods=new mn(this._client),this.jobs=new vn(this._client),this.checkpoints=new wn(this._client),this.alpha=new yn(this._client)}}xn.Methods=mn,xn.Jobs=vn,xn.Checkpoints=wn,xn.Alpha=yn;class Sn extends ze{}class An extends ze{constructor(){super(...arguments),this.graderModels=new Sn(this._client)}}An.GraderModels=Sn;class En extends ze{createVariation(e,t){return this._client.post("/images/variations",Fe({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",Fe({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class Rn extends ze{retrieve(e,t){return this._client.get(et`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",je,e)}delete(e,t){return this._client.delete(et`/models/${e}`,t)}}class $n extends ze{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class On extends ze{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class In extends ze{constructor(){super(...arguments),this.clientSecrets=new On(this._client)}}function qn(e,t){return t&&function(e){if(nt(e.text?.format))return!0;return!1}(t)?kn(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 kn(e,t){const s=e.output.map((e=>{if("function_call"===e.type)return{...e,parsed_arguments:Tn(t,e)};if("message"===e.type){const s=e.content.map((e=>"output_text"===e.type?{...e,parsed:Cn(t,e.text)}:e));return{...e,content:s}}return e})),n=Object.assign({},e,{output:s});return Object.getOwnPropertyDescriptor(e,"output_text")||Ln(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const e of n.output)if("message"===e.type)for(const t of e.content)if("output_text"===t.type&&null!==t.parsed)return t.parsed;return null}}),n}function Cn(e,t){if("json_schema"!==e.text?.format?.type)return null;if("$parseRaw"in e.text?.format){const s=e.text?.format;return s.$parseRaw(t)}return JSON.parse(t)}function Tn(e,t){const s=(n=e.tools??[],r=t.name,n.find((e=>"function"===e.type&&e.name===r)));var n,r,o;return{...t,...t,parsed_arguments:(o=s,"auto-parseable-tool"===o?.$brand?s.$parseRaw(t.arguments):s?.strict?JSON.parse(t.arguments):null)}}function Ln(e){const t=[];for(const s of e.output)if("message"===s.type)for(const e of s.content)"output_text"===e.type&&t.push(e.text);e.output_text=t.join("")}var Pn,Nn,jn,Mn,Dn,Wn,Bn,Un;In.ClientSecrets=On;class Hn extends Tt{constructor(e){super(),Pn.add(this),Nn.set(this,void 0),jn.set(this,void 0),Mn.set(this,void 0),f(this,Nn,e)}static createResponse(e,t,s){const n=new Hn(t);return n._run((()=>n._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),n}async _createOrRetrieveResponse(e,t,s){const n=s?.signal;let r;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),m(this,Pn,"m",Dn).call(this);let o=null;"response_id"in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const e of r)m(this,Pn,"m",Wn).call(this,e,o);if(r.controller.signal?.aborted)throw new v;return m(this,Pn,"m",Bn).call(this)}[(Nn=new WeakMap,jn=new WeakMap,Mn=new WeakMap,Pn=new WeakSet,Dn=function(){this.ended||f(this,jn,void 0)},Wn=function(e,t){if(this.ended)return;const s=(e,s)=>{(null==t||s.sequence_number>t)&&this._emit(e,s)},n=m(this,Pn,"m",Un).call(this,e);switch(s("event",e),e.type){case"response.output_text.delta":{const t=n.output[e.output_index];if(!t)throw new w(`missing output at index ${e.output_index}`);if("message"===t.type){const n=t.content[e.content_index];if(!n)throw new w(`missing content at index ${e.content_index}`);if("output_text"!==n.type)throw new w(`expected content to be 'output_text', got ${n.type}`);s("response.output_text.delta",{...e,snapshot:n.text})}break}case"response.function_call_arguments.delta":{const t=n.output[e.output_index];if(!t)throw new w(`missing output at index ${e.output_index}`);"function_call"===t.type&&s("response.function_call_arguments.delta",{...e,snapshot:t.arguments});break}default:s(e.type,e)}},Bn=function(){if(this.ended)throw new w("stream has ended, this shouldn't happen");const e=m(this,jn,"f");if(!e)throw new w("request ended without sending any events");f(this,jn,void 0);const t=function(e,t){return qn(e,t)}(e,m(this,Nn,"f"));return f(this,Mn,t),t},Un=function(e){let t=m(this,jn,"f");if(!t){if("response.created"!==e.type)throw new w(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=f(this,jn,e.response),t}switch(e.type){case"response.output_item.added":t.output.push(e.item);break;case"response.content_part.added":{const s=t.output[e.output_index];if(!s)throw new w(`missing output at index ${e.output_index}`);const n=s.type,r=e.part;"message"===n&&"reasoning_text"!==r.type?s.content.push(r):"reasoning"===n&&"reasoning_text"===r.type&&(s.content||(s.content=[]),s.content.push(r));break}case"response.output_text.delta":{const s=t.output[e.output_index];if(!s)throw new w(`missing output at index ${e.output_index}`);if("message"===s.type){const t=s.content[e.content_index];if(!t)throw new w(`missing content at index ${e.content_index}`);if("output_text"!==t.type)throw new w(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case"response.function_call_arguments.delta":{const s=t.output[e.output_index];if(!s)throw new w(`missing output at index ${e.output_index}`);"function_call"===s.type&&(s.arguments+=e.delta);break}case"response.reasoning_text.delta":{const s=t.output[e.output_index];if(!s)throw new w(`missing output at index ${e.output_index}`);if("reasoning"===s.type){const t=s.content?.[e.content_index];if(!t)throw new w(`missing content at index ${e.content_index}`);if("reasoning_text"!==t.type)throw new w(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case"response.completed":f(this,jn,e.response)}return t},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",(s=>{const n=t.shift();n?n.resolve(s):e.push(s)})),this.on("end",(()=>{s=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),this.on("error",(e=>{s=!0;for(const s of t)s.reject(e);t.length=0})),{next:async()=>{if(!e.length)return s?{value:void 0,done:!0}:new Promise(((e,s)=>t.push({resolve:e,reject:s}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=m(this,Mn,"f");if(!e)throw new w("stream ended without producing a ChatCompletion");return e}}class Fn extends ze{list(e,t={},s){return this._client.getAPIList(et`/responses/${e}/input_items`,Me,{query:t,...s})}}class Xn extends ze{constructor(){super(...arguments),this.inputItems=new Fn(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&&Ln(e),e)))}retrieve(e,t={},s){return this._client.get(et`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap((e=>("object"in e&&"response"===e.object&&Ln(e),e)))}delete(e,t){return this._client.delete(et`/responses/${e}`,{...t,headers:ys([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap((t=>kn(t,e)))}stream(e,t){return Hn.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(et`/responses/${e}/cancel`,t)}}Xn.InputItems=Fn;class Jn extends ze{create(e,t,s){return this._client.post(et`/uploads/${e}/parts`,Fe({body:t,...s},this._client))}}class Kn extends ze{constructor(){super(...arguments),this.parts=new Jn(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(et`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(et`/uploads/${e}/complete`,{body:t,...s})}}Kn.Parts=Jn;class Gn extends ze{create(e,t,s){return this._client.post(et`/vector_stores/${e}/file_batches`,{body:t,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(et`/vector_stores/${n}/file_batches/${e}`,{...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{vector_store_id:n}=t;return this._client.post(et`/vector_stores/${n}/file_batches/${e}/cancel`,{...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t);return await this.poll(e,n.id,s)}listFiles(e,t,s){const{vector_store_id:n,...r}=t;return this._client.getAPIList(et`/vector_stores/${n}/file_batches/${e}/files`,Me,{query:r,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){const n=ys([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:r,response:o}=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await W(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},n){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const r=n?.maxConcurrency??5,o=Math.min(r,t.length),i=this._client,a=t.values(),c=[...s];const l=Array(o).fill(a).map((async function(e){for(let t of e){const e=await i.files.create({file:t,purpose:"assistants"},n);c.push(e.id)}}));return await(async e=>{const t=await Promise.allSettled(e),s=t.filter((e=>"rejected"===e.status));if(s.length){for(const e of s)console.error(e.reason);throw new Error(`${s.length} promise(s) failed - see the above errors`)}const n=[];for(const e of t)"fulfilled"===e.status&&n.push(e.value);return n})(l),await this.createAndPoll(e,{file_ids:c})}}class Vn extends ze{create(e,t,s){return this._client.post(et`/vector_stores/${e}/files`,{body:t,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:n}=t;return this._client.get(et`/vector_stores/${n}/files/${e}`,{...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{vector_store_id:n,...r}=t;return this._client.post(et`/vector_stores/${n}/files/${e}`,{body:r,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(et`/vector_stores/${e}/files`,Me,{query:t,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{vector_store_id:n}=t;return this._client.delete(et`/vector_stores/${n}/files/${e}`,{...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const n=await this.create(e,t,s);return await this.poll(e,n.id,s)}async poll(e,t,s){const n=ys([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const r=await this.retrieve(t,{vector_store_id:e},{...s,headers:n}).withResponse(),o=r.data;switch(o.status){case"in_progress":let e=5e3;if(s?.pollIntervalMs)e=s.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const s=parseInt(t);isNaN(s)||(e=s)}}await W(e);break;case"failed":case"completed":return o}}}async upload(e,t,s){const n=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:n.id},s)}async uploadAndPoll(e,t,s){const n=await this.upload(e,t,s);return await this.poll(e,n.id,s)}content(e,t,s){const{vector_store_id:n}=t;return this._client.getAPIList(et`/vector_stores/${n}/files/${e}/content`,je,{...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class zn extends ze{constructor(){super(...arguments),this.files=new Vn(this._client),this.fileBatches=new Gn(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(et`/vector_stores/${e}`,{...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(et`/vector_stores/${e}`,{body:t,...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",Me,{query:e,...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(et`/vector_stores/${e}`,{...t,headers:ys([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(et`/vector_stores/${e}/search`,je,{body:t,method:"post",...s,headers:ys([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}var Qn,Yn,Zn,er,tr,sr,nr;zn.Files=Vn,zn.FileBatches=Gn;class rr extends ze{constructor(){super(...arguments),Qn.add(this)}async unwrap(e,t,s=this._client.webhookSecret,n=300){return await this.verifySignature(e,t,s,n),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,n=300){if("undefined"==typeof crypto||"function"!=typeof crypto.subtle.importKey||"function"!=typeof crypto.subtle.verify)throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");m(this,Qn,"m",Yn).call(this,s);const r=ys([t]).values,o=m(this,Qn,"m",Zn).call(this,r,"webhook-signature"),i=m(this,Qn,"m",Zn).call(this,r,"webhook-timestamp"),a=m(this,Qn,"m",Zn).call(this,r,"webhook-id"),c=parseInt(i,10);if(isNaN(c))throw new L("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-c>n)throw new L("Webhook timestamp is too old");if(c>l+n)throw new L("Webhook timestamp is too new");const u=o.split(" ").map((e=>e.startsWith("v1,")?e.substring(3):e)),d=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),h=a?`${a}.${i}.${e}`:`${i}.${e}`,p=await crypto.subtle.importKey("raw",d,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const e of u)try{const t=Buffer.from(e,"base64");if(await crypto.subtle.verify("HMAC",p,t,(new TextEncoder).encode(h)))return}catch{continue}throw new L("The given webhook signature does not match the expected signature")}}Qn=new WeakSet,Yn=function(e){if("string"!=typeof e||0===e.length)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Zn=function(e,t){if(!e)throw new Error("Headers are required");const s=e.get(t);if(null==s)throw new Error(`Missing required header: ${t}`);return s};class or{constructor({baseURL:e=Is("OPENAI_BASE_URL"),apiKey:t=Is("OPENAI_API_KEY"),organization:s=Is("OPENAI_ORG_ID")??null,project:n=Is("OPENAI_PROJECT_ID")??null,webhookSecret:r=Is("OPENAI_WEBHOOK_SECRET")??null,...o}={}){if(er.add(this),sr.set(this,void 0),this.completions=new nn(this),this.chat=new fs(this),this.embeddings=new un(this),this.files=new fn(this),this.images=new En(this),this.audio=new vs(this),this.moderations=new $n(this),this.models=new Rn(this),this.fineTuning=new xn(this),this.graders=new An(this),this.vectorStores=new zn(this),this.webhooks=new rr(this),this.beta=new sn(this),this.batches=new xs(this),this.uploads=new Kn(this),this.responses=new Xn(this),this.realtime=new In(this),this.conversations=new ln(this),this.evals=new pn(this),this.containers=new an(this),void 0===t)throw new w("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const i={apiKey:t,organization:s,project:n,webhookSecret:r,...o,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new w("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");this.baseURL=i.baseURL,this.timeout=i.timeout??tr.DEFAULT_TIMEOUT,this.logger=i.logger??console;const a="warn";this.logLevel=a,this.logLevel=be(i.logLevel,"ClientOptions.logLevel",this)??be(Is("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??a,this.fetchOptions=i.fetchOptions,this.maxRetries=i.maxRetries??2,this.fetch=i.fetch??function(){if("undefined"!=typeof fetch)return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),f(this,sr,V),this._options=i,this.apiKey="string"==typeof t?t:"Missing Key",this.organization=s,this.project=n,this.webhookSecret=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return ys([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return le(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${B}`}defaultIdempotencyKey(){return`stainless-node-retry-${g()}`}makeStatusError(e,t,s,n){return b.generate(e,t,s,n)}async _callApiKey(){const e=this._options.apiKey;if("function"!=typeof e)return!1;let t;try{t=await e()}catch(e){if(e instanceof w)throw e;throw new w(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if("string"!=typeof t||!t)throw new w(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){const n=!m(this,er,"m",nr).call(this)&&s||this.baseURL,r=(e=>P.test(e))(e)?new URL(e):new URL(n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery();return function(e){if(!e)return!0;for(const t in e)return!1;return!0}(o)||(t={...o,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then((s=>({method:e,path:t,...s}))))}request(e,t=null){return new Le(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const n=await e,r=n.maxRetries??this.maxRetries;null==t&&(t=r),await this.prepareOptions(n);const{req:o,url:i,timeout:a}=await this.buildRequest(n,{retryCount:r-t});await this.prepareRequest(o,{url:i,options:n});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=void 0===s?"":`, retryOf: ${s}`,u=Date.now();if(Ee(this).debug(`[${c}] sending request`,Re({retryOfRequestLogID:s,method:n.method,url:i,options:n,headers:o.headers})),n.signal?.aborted)throw new v;const d=new AbortController,h=await this.fetchWithTimeout(i,o,a,d).catch(_),p=Date.now();if(h instanceof globalThis.Error){const e=`retrying, ${t} attempts remaining`;if(n.signal?.aborted)throw new v;const r=y(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(t)return Ee(this).info(`[${c}] connection ${r?"timed out":"failed"} - ${e}`),Ee(this).debug(`[${c}] connection ${r?"timed out":"failed"} (${e})`,Re({retryOfRequestLogID:s,url:i,durationMs:p-u,message:h.message})),this.retryRequest(n,t,s??c);if(Ee(this).info(`[${c}] connection ${r?"timed out":"failed"} - error; no more retries left`),Ee(this).debug(`[${c}] connection ${r?"timed out":"failed"} (error; no more retries left)`,Re({retryOfRequestLogID:s,url:i,durationMs:p-u,message:h.message})),r)throw new S;throw new x({cause:h})}const f=`[${c}${l}${[...h.headers.entries()].filter((([e])=>"x-request-id"===e)).map((([e,t])=>", "+e+": "+JSON.stringify(t))).join("")}] ${o.method} ${i} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){const e=await this.shouldRetry(h);if(t&&e){const e=`retrying, ${t} attempts remaining`;return await async function(e){if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await(e[Symbol.asyncIterator]().return?.());const t=e.getReader(),s=t.cancel();t.releaseLock(),await s}(h.body),Ee(this).info(`${f} - ${e}`),Ee(this).debug(`[${c}] response error (${e})`,Re({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(n,t,s??c,h.headers)}const r=e?"error; no more retries left":"error; not retryable";Ee(this).info(`${f} - ${r}`);const o=await h.text().catch((e=>_(e).message)),i=(e=>{try{return JSON.parse(e)}catch(e){return}})(o),a=i?void 0:o;Ee(this).debug(`[${c}] response error (${r})`,Re({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:a,durationMs:Date.now()-u}));throw this.makeStatusError(h.status,i,a,h.headers)}return Ee(this).info(f),Ee(this).debug(`[${c}] response start`,Re({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:n,controller:d,requestLogID:c,retryOfRequestLogID:s,startTime:u}}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new Ne(this,s,e)}async fetchWithTimeout(e,t,s,n){const{signal:r,method:o,...i}=t||{};r&&r.addEventListener("abort",(()=>n.abort()));const a=setTimeout((()=>n.abort()),s),c=globalThis.ReadableStream&&i.body instanceof globalThis.ReadableStream||"object"==typeof i.body&&null!==i.body&&Symbol.asyncIterator in i.body,l={signal:n.signal,...c?{duplex:"half"}:{},method:"GET",...i};o&&(l.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(a)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,s,n){let r;const o=n?.get("retry-after-ms");if(o){const e=parseFloat(o);Number.isNaN(e)||(r=e)}const i=n?.get("retry-after");if(i&&!r){const e=parseFloat(i);r=Number.isNaN(e)?Date.parse(i)-Date.now():1e3*e}if(!(r&&0<=r&&r<6e4)){const s=e.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(t,s)}return await W(r),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:n,path:r,query:o,defaultBaseURL:i}=s,a=this.buildURL(r,o,i);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new w(`${e} must be an integer`);if(t<0)throw new w(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:c,body:l}=this.buildBody({options:s});return{req:{method:n,headers:await this.buildHeaders({options:e,method:n,bodyHeaders:c,retryCount:t}),...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...s.fetchOptions??{}},url:a,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:n}){let r={};this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);const o=ys([r,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(n),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...X??(X=U()),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(o),o.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=ys([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:"object"==typeof e&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&"function"==typeof e.next)?{bodyHeaders:void 0,body:K(e)}:m(this,sr,"f").call(this,{body:e,headers:s})}}tr=or,sr=new WeakMap,er=new WeakSet,nr=function(){return"https://api.openai.com/v1"!==this.baseURL},or.OpenAI=tr,or.DEFAULT_TIMEOUT=6e5,or.OpenAIError=w,or.APIError=b,or.APIConnectionError=x,or.APIConnectionTimeoutError=S,or.APIUserAbortError=v,or.NotFoundError=$,or.ConflictError=O,or.RateLimitError=q,or.BadRequestError=A,or.AuthenticationError=E,or.InternalServerError=k,or.PermissionDeniedError=R,or.UnprocessableEntityError=I,or.InvalidWebhookSignatureError=L,or.toFile=async function(e,t,s){if(We(),(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&Ge(e))(e=await e))return e instanceof File?e:Be([await e.arrayBuffer()],e.name);if((e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob)(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),Be(await Ve(n),t,s)}const n=await Ve(e);if(t||(t=Ue(e)),!s?.type){const e=n.find((e=>"object"==typeof e&&"type"in e&&e.type));"string"==typeof e&&(s={...s,type:e})}return Be(n,t,s)},or.Completions=nn,or.Chat=fs,or.Embeddings=un,or.Files=fn,or.Images=En,or.Audio=vs,or.Moderations=$n,or.Models=Rn,or.FineTuning=xn,or.Graders=An,or.VectorStores=zn,or.Webhooks=rr,or.Beta=sn,or.Batches=xs,or.Uploads=Kn,or.Responses=Xn,or.Realtime=In,or.Conversations=ln,or.Evals=pn,or.Containers=an;const ir={[o.SINGLE_CHOICE]:{name:"single_choice_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.SINGLE_CHOICE]},correct_answer:{type:"object",properties:{index:{type:"integer"}},required:["index"],additionalProperties:!1}},required:["question_type","correct_answer"],additionalProperties:!1}},[o.MULTIPLE_CHOICE]:{name:"multiple_choice_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.MULTIPLE_CHOICE]},correct_answer:{type:"object",properties:{indexes:{type:"array",items:{type:"integer"}}},required:["indexes"],additionalProperties:!1}},required:["question_type","correct_answer"],additionalProperties:!1}},[o.TRUE_FALSE]:{name:"true_false_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.TRUE_FALSE]},correct_answer:{type:"boolean"}},required:["question_type","correct_answer"],additionalProperties:!1}},[o.SHORT_TEXT]:{name:"short_text_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.SHORT_TEXT]},correct_answer:{type:"string"}},required:["question_type","correct_answer"],additionalProperties:!1}},[o.NUMERICAL]:{name:"numerical_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.NUMERICAL]},correct_answer:{type:"number"}},required:["question_type","correct_answer"],additionalProperties:!1}},[o.ESSAY]:{name:"essay_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.ESSAY]},correct_answer:{type:"string"}},required:["question_type","correct_answer"],additionalProperties:!1}},[o.MATCH]:{name:"match_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.MATCH]},correct_answers:{type:"array",items:{type:"object",properties:{sub_question_index:{type:"integer"},option_index:{type:"integer"}},required:["sub_question_index","option_index"],additionalProperties:!1}}},required:["question_type","correct_answers"],additionalProperties:!1}},[o.SELECT_MISSING_WORD]:{name:"select_missing_word_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.SELECT_MISSING_WORD]},correct_answers:{type:"array",items:{type:"object",properties:{drop_down_index:{type:"integer"},option_index:{type:"integer"}},required:["drop_down_index","option_index"],additionalProperties:!1}}},required:["question_type","correct_answers"],additionalProperties:!1}},[o.DRAG_DROP_TEXT]:{name:"drag_drop_text_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.DRAG_DROP_TEXT]},correct_answers:{type:"array",items:{type:"object",properties:{blank_index:{type:"integer"},draggable_index:{type:"integer"}},required:["blank_index","draggable_index"],additionalProperties:!1}}},required:["question_type","correct_answers"],additionalProperties:!1}},[o.ORDERING]:{name:"ordering_response",strict:!0,schema:{type:"object",properties:{question_type:{type:"string",enum:[o.ORDERING]},correct_order:{type:"object",properties:{indexes:{type:"array",items:{type:"integer"}}},required:["indexes"],additionalProperties:!1}},required:["question_type","correct_order"],additionalProperties:!1}},[o.UNKNOWN]:void 0};function ar(e){const t=[],s=Array.from(e.querySelectorAll("tr")),n=[];s.map((e=>{const s=Array.from(e.querySelectorAll("td, th")).map(((e,t)=>{var s;const r=null===(s=e.textContent)||void 0===s?void 0:s.trim();return n[t]=Math.max(n[t]||0,(null==r?void 0:r.length)||0),null!=r?r:""}));t.push(s)}));const r=t[0].length,o=n.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(n[t]," "))).join(" | ")));return a.shift()+i+a.join("\n")}function cr(t,s){t.title&&e("Copied to clipboard"),navigator.clipboard.writeText(s.response)}function lr(e,t,s){const n=t[0];if(1!==t.length||!function(e){const t=e.getAttribute("contenteditable");return"string"==typeof t&&"false"!==t}(n))return!1;const r=s.response&&"correct_answer"in s.response?String(s.response.correct_answer):s.rawResponse;if(e.typing){let e=0;const t=function(s){if(s.preventDefault(),"Backspace"===s.key||e>=r.length)return void n.removeEventListener("keydown",t);n.textContent=r.slice(0,++e),n.focus();const o=document.createRange();o.selectNodeContents(n),o.collapse(!1);const i=window.getSelection();null!==i&&(i.removeAllRanges(),i.addRange(o))};n.addEventListener("keydown",t)}else n.textContent=r;return!0}function ur(e,t,s){var n,r;const o=t[0];if(1!==t.length||"number"!==o.type)return!1;const i=null===(r=null===(n=(s.response&&"correct_answer"in s.response?String(s.response.correct_answer):s.rawResponse).match(/\d+([,.]\d+)?/gi))||void 0===n?void 0:n[0])||void 0===r?void 0:r.replace(",",".");if(void 0===i)return!1;if(e.typing){let e=0;const t=function(s){s.preventDefault(),"Backspace"===s.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 dr(e,t,s){const a=null==t?void 0:t[0];if(!a||"radio"!==a.type)return!1;let c=null;if(s.response&&s.response.question_type===o.SINGLE_CHOICE){const e=s.response.correct_answer.index;e>=0&&e<t.length&&(c=t[e])}else if(s.response&&s.response.question_type===o.TRUE_FALSE){const e=!0===s.response.correct_answer,r=Array.from(t).map((e=>{var t,s;return{element:e,value:i(null!==(s=null===(t=null==e?void 0:e.parentElement)||void 0===t?void 0:t.textContent)&&void 0!==s?s:"")}})).filter((e=>""!==e.value)),o=n(e?"true":"false",r);c=o.element}else{const o=Array.from(t).map((e=>{var t,s;return{element:e,value:i(null!==(s=null===(t=null==e?void 0:e.parentElement)||void 0===t?void 0:t.textContent)&&void 0!==s?s:"")}})).filter((e=>""!==e.value)),a=n(s.rawResponse,o);e.logs&&a.value&&r.bestAnswer(a.value,a.similarity),c=a.element}return c&&(e.mouseover?c.addEventListener("mouseover",(()=>c.click()),{once:!0}):c.click()),!0}function hr(e,t,s){const a=null==t?void 0:t[0];if(!a||"checkbox"!==a.type)return!1;const c=new Set;if(s.response&&s.response.question_type===o.MULTIPLE_CHOICE){const n=s.response,r=new Set(n.correct_answer.indexes);Array.from(t).forEach(((e,t)=>{const s=e;r.has(t)&&c.add(s)})),e.logs&&console.log("Using strict mode multiple choice selection:",n.correct_answer.indexes)}else{const o=s.rawResponse.split("\n"),a=Array.from(t).map((e=>{var t,s;return{element:e,value:i(null!==(s=null===(t=null==e?void 0:e.parentElement)||void 0===t?void 0:t.textContent)&&void 0!==s?s:"")}})).filter((e=>""!==e.value));for(const t of o){const s=n(t,a);e.logs&&s.value&&r.bestAnswer(s.value,s.similarity),c.add(s.element)}}for(const s of Array.from(t)){const t=s,n=t.checked&&!c.has(t)||!t.checked&&c.has(t),r=()=>n&&t.click();e.mouseover?t.addEventListener("mouseover",r,{once:!0}):r()}return!0}function pr(e,t,s){if(0===t.length||"SELECT"!==t[0].tagName)return!1;const o=(s.response&&"correct_answer"in s.response?String(s.response.correct_answer):s.rawResponse).split("\n");e.logs&&r.array(o);for(let s=0;s<t.length&&o[s];++s){const a=t[s].querySelectorAll("option"),c=Array.from(a).slice(1).map((e=>{var t;return{element:e,value:i(null!==(t=e.textContent)&&void 0!==t?t:"")}})).filter((e=>""!==e.value)),l=n(o[s],c);e.logs&&l.value&&r.bestAnswer(l.value,l.similarity);const u=l.element,d=u.closest("select");null!==d&&(e.mouseover?d.addEventListener("click",(()=>u.selected=!0),{once:!0}):u.selected=!0)}return!0}function fr(e,t,s){const n=t[0];if(1!==t.length||"TEXTAREA"!==n.tagName&&"text"!==n.type)return!1;const r=s.response&&"correct_answer"in s.response?String(s.response.correct_answer):s.rawResponse;if(e.typing){let e=0;const t=function(s){s.preventDefault(),"Backspace"===s.key||e>=r.length?n.removeEventListener("keydown",t):n.value=r.slice(0,++e)};n.addEventListener("keydown",t)}else n.value=r;return!0}function mr(e,t,s){const n=t[0];if(!n.classList.contains("qtype_essay_editor"))return!1;const r=n.querySelector("iframe");if(!(r&&r.contentDocument&&r.contentDocument.body&&r.contentWindow))return!1;const o=r.contentDocument.body.querySelector("p");if(!o)return!1;const i=s.response&&"correct_answer"in s.response?String(s.response.correct_answer):s.rawResponse;if(e.typing){let e=0;const t=function(s){if(s.preventDefault(),"Backspace"===s.key||e>=i.length)return void r.contentWindow.removeEventListener("keydown",t);const n=document.createTextNode(i.charAt(e++));o.appendChild(n);const a=r.contentDocument.createRange();a.selectNodeContents(o),a.collapse(!1);const c=r.contentWindow.getSelection();c&&(c.removeAllRanges(),c.addRange(a)),r.contentWindow.focus()};r.contentWindow.addEventListener("keydown",t)}else o.textContent+=i;return!0}function gr(e,t,s){if(!s.response||s.response.question_type!==o.MATCH)return!1;const n=s.response,r=Array.from(t).filter((e=>"SELECT"===e.tagName));for(const t of n.correct_answers){const s=r[t.sub_question_index];if(!s)continue;const n=s.querySelectorAll("option")[t.option_index+1];n&&(e.mouseover?s.addEventListener("click",(()=>n.selected=!0),{once:!0}):n.selected=!0)}return!0}function yr(e,t,s){if(!s.response||s.response.question_type!==o.SELECT_MISSING_WORD)return!1;const n=s.response,r=Array.from(t).filter((e=>"SELECT"===e.tagName));for(const t of n.correct_answers){const s=r[t.drop_down_index];if(!s)continue;const n=s.querySelectorAll("option")[t.option_index+1];n&&(e.mouseover?s.addEventListener("click",(()=>n.selected=!0),{once:!0}):n.selected=!0)}return!0}function _r(e,t,s){if(!s.response||s.response.question_type!==o.DRAG_DROP_TEXT)return!1;const n=s.response,r=Array.from(t).filter((e=>e.classList.contains("placeinput")));for(const e of n.correct_answers){const t=r[e.blank_index];if(!t)continue;const s=t.closest(".que");if(!s)continue;const n=s.querySelectorAll(".draghome.unplaced")[e.draggable_index];if(!n)continue;const o=n.className.match(/choice(\d+)/);if(!o)continue;const i=o[1];t.value=i;const a=s.querySelector(`.place${e.blank_index+1}.drop`);a&&(a.textContent=n.textContent)}return!0}function wr(e,t,s){if(!s.response||s.response.question_type!==o.ORDERING)return!1;const n=s.response,r=Array.from(t).find((e=>e.classList.contains("sortablelist")));if(!r)return!0;const i=r.closest(".que");if(!i)return!0;const a=Array.from(r.querySelectorAll("li.sortableitem")),c=[],l=[];for(const e of n.correct_order.indexes){const t=a[e];t&&(c.push(t.id),l.push(t))}const u=i.querySelector('input[type="hidden"][name*="_response_"]');return u&&(u.value=c.join(",")),l.forEach((e=>{r.appendChild(e)})),!0}function br(e){return t(this,void 0,void 0,(function*(){e.config.cursor&&(e.questionElement.style.cursor="wait");const s=function(e){let t=e.innerText;const s=e.querySelectorAll(".accesshide");for(const e of s)t=t.replace(e.innerText,"");const n=e.querySelector(".qtype_essay_editor");n&&(t=t.replace(n.innerText,""));const r=e.querySelector('[role="button"]');r&&(t=t.replace(r.innerText,""));const o=e.querySelectorAll(".qtext table");for(const e of o)t=t.replace(e.innerText,"\n"+ar(e)+"\n");return i(t,!1)}(e.form),n=e.form.querySelectorAll(e.inputQuery),a=yield function(e,s,n){return t(this,void 0,void 0,(function*(){var t;const r=new AbortController,i=setTimeout((()=>r.abort()),1e3*(e.timeoutValue||20)),a=yield p(e,s,n),c=new or({apiKey:e.apiKey,baseURL:e.baseURL,project:e.projectId,dangerouslyAllowBrowser:!0}),l=a.query?a.query.question_type:o.UNKNOWN,u=l!==o.UNKNOWN?ir[l]:void 0,d={model:e.model,messages:a.messages.map((e=>Object.assign({},e))),max_completion_tokens:e.maxTokens||2e3};u&&(d.response_format={type:"json_object"},d.messages.length>0&&"system"===d.messages[0].role&&(d.messages[0].content+=`\n\nYou MUST respond in JSON strictly adhering to the following schema. Do NOT wrap the JSON in markdown code blocks. Output raw JSON only.\n\n${JSON.stringify(u,null,2)}`));const h=yield c.chat.completions.create(function(e,t){if(-1===e.search(/^o\d+/gi))return t;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,d),{signal:e.timeout?r.signal:null});clearTimeout(i);const f=null!==(t=h.choices[0].message.content)&&void 0!==t?t:"";let m=null;if(u)try{const e=f.replace(/^```(json)?[\s\S]*?\n([\s\S]*?)```$/g,"$2").replace(/^```(json)?|```$/gm,"").trim();m=JSON.parse(e)}catch(e){console.error("Failed to parse structured JSON from GPT",e)}return"function"==typeof a.saveResponse&&a.saveResponse(f),{questionQuery:a.query,response:m,rawResponse:f}}))}(e.config,e.questionElement,s).catch((e=>({error:e}))),c="object"==typeof a&&"error"in a;if(e.config.cursor&&(e.questionElement.style.cursor=e.config.infinite||c?"pointer":"initial"),c)console.error(a.error);else switch(e.config.logs&&(r.question(s),r.response(a)),e.config.mode){case"clipboard":!function(e){e.config.infinite||e.removeListener(),cr(e.config,e.gptAnswer)}({config:e.config,questionElement:e.questionElement,gptAnswer:a,removeListener:e.removeListener});break;case"question-to-answer":!function(e){var t;const s=e.questionElement;e.removeListener();const n=null!==(t=s.innerHTML)&&void 0!==t?t:"";s.innerHTML=e.gptAnswer.response,s.style.whiteSpace="pre-wrap",s.addEventListener("click",(function(){const t=s.innerHTML===e.gptAnswer.response;s.style.whiteSpace=t?"initial":"pre-wrap",s.innerHTML=t?n:e.gptAnswer.response}))}({gptAnswer:a,questionElement:e.questionElement,removeListener:e.removeListener});break;case"autocomplete":!function(e){e.config.infinite||e.removeListener();const t=[mr,lr,fr,ur,gr,yr,_r,wr,pr,dr,hr];for(const s of t)if(s(e.config,e.inputList,e.gptAnswer))return;cr(e.config,e.gptAnswer)}({config:e.config,gptAnswer:a,inputList:n,questionElement:e.questionElement,removeListener:e.removeListener})}}))}const vr=[],xr=[];function Sr(e){const t=xr.findIndex((t=>t.element===e));if(-1!==t){const e=xr.splice(t,1)[0];e.element.removeEventListener("click",e.fn)}}function Ar(t){if(xr.length>0){for(const e of xr)t.cursor&&(e.element.style.cursor="initial"),e.element.removeEventListener("click",e.fn);return t.title&&e("Removed"),void(xr.length=0)}const s=["checkbox","radio","text","number"].map((e=>`input[type="${e}"]`)).join(",")+", textarea, select, [contenteditable], .qtype_essay_editor, .placeinput, .sortablelist",n=document.querySelectorAll(".formulation");for(const e of n){const n=e.querySelector(".qtext");if(null===n)continue;t.cursor&&(n.style.cursor="pointer");const r=br.bind(null,{config:t,questionElement:n,form:e,inputQuery:s,removeListener:()=>Sr(n)});xr.push({element:n,fn:r}),n.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){vr.push(t.key),vr.length>e.code.length&&vr.shift(),vr.join("")===e.code&&(vr.length=0,Ar(e))}))}(t):Ar(t)}))}));
|
||
//# sourceMappingURL=MoodleGPT.js.map
|