From 16a82fe3d84efde6573d440396b1ae2c29db9d98 Mon Sep 17 00:00:00 2001 From: yoannchb-pro <71560747+yoannchb-pro@users.noreply.github.com> Date: Tue, 14 Jan 2025 12:23:13 -0500 Subject: [PATCH] v1.1.2 --- .eslintrc.js | 5 +- CHANGELOG.md | 6 ++ README.md | 4 +- extension/MoodleGPT.js | 2 +- extension/MoodleGPT.js.map | 2 +- extension/manifest.json | 2 +- extension/popup/index.html | 50 +++++++----- extension/popup/js/gptVersion.js | 54 ------------- extension/popup/js/utils.js | 25 ------ extension/popup/popup.js | 2 + extension/popup/popup.js.map | 1 + extension/popup/style.css | 43 ++++++++++ package.json | 8 +- rollup.config.js | 31 +++++--- src/{ => background}/core/code-listener.ts | 4 +- src/{ => background}/core/create-question.ts | 4 +- .../core/get-content-with-history.ts | 28 +++---- src/{ => background}/core/get-response.ts | 33 ++++---- .../core/modes/autocomplete.ts | 20 ++--- src/{ => background}/core/modes/clipboard.ts | 6 +- .../core/modes/question-to-answer.ts | 2 +- src/{ => background}/core/questions/atto.ts | 4 +- .../core/questions/checkbox.ts | 10 +-- .../core/questions/clipboard.ts | 6 +- .../core/questions/contenteditable.ts | 4 +- src/{ => background}/core/questions/number.ts | 4 +- src/{ => background}/core/questions/radio.ts | 10 +-- src/{ => background}/core/questions/select.ts | 10 +-- .../core/questions/textbox.ts | 4 +- src/{ => background}/core/reply.ts | 4 +- src/{ => background}/index.ts | 2 +- src/{ => background}/types/config.ts | 0 src/{ => background}/types/gpt-answer.ts | 0 src/{ => background}/types/message.ts | 0 src/background/utils/fixe-o1.ts | 26 +++++++ .../utils/html-table-to-string.ts | 0 src/{ => background}/utils/image-to-base64.ts | 0 src/{ => background}/utils/logs.ts | 2 +- src/{ => background}/utils/normalize-text.ts | 0 .../utils/pick-best-response.ts | 0 .../utils/title-indications.ts | 0 .../utils/version-support-images.ts | 0 src/popup/data.ts | 15 ++++ src/popup/gpt-version.ts | 78 +++++++++++++++++++ .../popup/js/index.js => src/popup/index.ts | 43 +++++----- .../popup/mode-handler.ts | 19 ++--- src/popup/settings.ts | 21 +++++ src/popup/utils.ts | 31 ++++++++ .../js/version.js => src/popup/version.ts | 12 ++- tsconfig.json | 10 +-- 50 files changed, 404 insertions(+), 243 deletions(-) delete mode 100644 extension/popup/js/gptVersion.js delete mode 100644 extension/popup/js/utils.js create mode 100644 extension/popup/popup.js create mode 100644 extension/popup/popup.js.map rename src/{ => background}/core/code-listener.ts (95%) rename src/{ => background}/core/create-question.ts (88%) rename src/{ => background}/core/get-content-with-history.ts (84%) rename src/{ => background}/core/get-response.ts (71%) rename src/{ => background}/core/modes/autocomplete.ts (56%) rename src/{ => background}/core/modes/clipboard.ts (70%) rename src/{ => background}/core/modes/question-to-answer.ts (94%) rename src/{ => background}/core/questions/atto.ts (94%) rename src/{ => background}/core/questions/checkbox.ts (85%) rename src/{ => background}/core/questions/clipboard.ts (67%) rename src/{ => background}/core/questions/contenteditable.ts (93%) rename src/{ => background}/core/questions/number.ts (91%) rename src/{ => background}/core/questions/radio.ts (79%) rename src/{ => background}/core/questions/select.ts (84%) rename src/{ => background}/core/questions/textbox.ts (90%) rename src/{ => background}/core/reply.ts (95%) rename src/{ => background}/index.ts (89%) rename src/{ => background}/types/config.ts (100%) rename src/{ => background}/types/gpt-answer.ts (100%) rename src/{ => background}/types/message.ts (100%) create mode 100644 src/background/utils/fixe-o1.ts rename src/{ => background}/utils/html-table-to-string.ts (100%) rename src/{ => background}/utils/image-to-base64.ts (100%) rename src/{ => background}/utils/logs.ts (93%) rename src/{ => background}/utils/normalize-text.ts (100%) rename src/{ => background}/utils/pick-best-response.ts (100%) rename src/{ => background}/utils/title-indications.ts (100%) rename src/{ => background}/utils/version-support-images.ts (100%) create mode 100644 src/popup/data.ts create mode 100644 src/popup/gpt-version.ts rename extension/popup/js/index.js => src/popup/index.ts (57%) rename extension/popup/js/modeHandler.js => src/popup/mode-handler.ts (67%) create mode 100644 src/popup/settings.ts create mode 100644 src/popup/utils.ts rename extension/popup/js/version.js => src/popup/version.ts (85%) diff --git a/.eslintrc.js b/.eslintrc.js index 2f4fec9..6b3393b 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -12,7 +12,10 @@ module.exports = { overrides: [ { files: ['extension/popup/*.js', 'src/**/*.ts'], - rules: {} + rules: { + '@typescript-eslint/no-explicit-any': 'off', + 'no-constant-condition': 'off' + } } ] }; diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c6ec4d..7ff2b8a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # CHANGELOG +## v1.1.2 + +- Advanced settings +- Added OpenAI SDK for better support +- o1 model support + ## v1.1.1 - Bugs correction diff --git a/README.md b/README.md index cc8039e..047bdff 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ href="https://www.flaticon.com/free-icons/mortarboard" target="_blank" rel="noopener noreferrer" title="Mortarboard icons created by itim2101 - Flaticon" >Mortarboard icons created by itim2101 - Flaticon

-# MoodleGPT 1.1.1 +# MoodleGPT 1.1.2 This extension allows you to hide CHAT-GPT in a Moodle quiz. You just need to click on the question you want to solve, and CHAT-GPT will automatically provide the answer. However, one needs to be careful because as we know, CHAT-GPT can make errors especially in calculations. @@ -12,7 +12,7 @@ Find the extension on the Chrome Webstore right [here](https://chrome.google.com ## Summary -- [MoodleGPT 1.1.1](#moodlegpt-111) +- [MoodleGPT 1.1.2](#moodlegpt-112) - [Chrome Webstore](#chrome-webstore) - [Summary](#summary) - [Disclaimer !](#disclaimer-) diff --git a/extension/MoodleGPT.js b/extension/MoodleGPT.js index b9bb58b..37c8216 100644 --- a/extension/MoodleGPT.js +++ b/extension/MoodleGPT.js @@ -1,2 +1,2 @@ -!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e){const n=document.title;document.title=e,setTimeout((()=>document.title=n),3e3)}function n(e,n,t,o){return new(t||(t=Promise))((function(r,s){function i(e){try{c(o.next(e))}catch(e){s(e)}}function l(e){try{c(o.throw(e))}catch(e){s(e)}}function c(e){var n;e.done?r(e.value):(n=e.value,n instanceof t?n:new t((function(e){e(n)}))).then(i,l)}c((o=o.apply(e,n||[])).next())}))}function t(e,n){const t=e.length>n.length?e.length:n.length;return 0===t?1:(t-function(e,n){if(0===e.length)return n.length;if(0===n.length)return e.length;const t=[],o=e.replace(/\s+/,""),r=n.replace(/\s+/,"");for(let e=0;e<=o.length;++e){t.push([e]);for(let n=1;n<=r.length;++n)t[e][n]=0===e?n:Math.min(t[e-1][n]+1,t[e][n-1]+1,t[e-1][n-1]+(o[e-1]===r[n-1]?0:1))}return t[o.length][r.length]}(e,n))/t}function o(e,n){let o={element:null,similarity:0,value:null};for(const r of n){const n=t(r.value,e);if(1===n)return{element:r.element,value:r.value,similarity:n};n>o.similarity&&(o={element:r.element,value:r.value,similarity:n})}return o}"function"==typeof SuppressedError&&SuppressedError;class r{static question(e){console.log("%c[QUESTION]: %s","color: cyan",e)}static bestAnswer(e,n){console.log("%c[BEST ANSWER]: %s","color: green",`"${e}" with a similarity of ${function(e){return Math.round(100*e*100)/100+"%"}(n)}`)}static array(e){console.log("[CORRECTS] ",e)}static response(e){console.log("Original:\n"+e.response),console.log("Normalized:\n"+e.normalizedResponse)}}function s(e,n=!0){n&&(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")}var i,l;!function(e){e.SYSTEM="system",e.USER="user",e.ASSISTANT="assistant"}(i||(i={})),function(e){e.TEXT="text",e.IMAGE="image_url"}(l||(l={}));const c="\nAct as a quiz solver for the best notation with the following rules:\n- If no answer(s) are given, answer the statement as usual without following the other rules, providing the most detailed, complete and precise explanation. \n- But for the calculation provide this format 'result: '\n- For 'put in order' questions, maintain the answer in the order as presented in the question but assocy the correct order to it by usin this format ':\n:', ignore other rules.\n- Always reply in the format: '\n\n...'.\n- Retain only the correct answer(s).\n- Maintain the same order for the answers as in the text.\n- Retain all text from the answer with its description, content or definition.\n- Only provide answers that exactly match the given answer in the text.\n- The question always has the correct answer(s), so you should always provide an answer.\n- Always respond in the same language as the user's question.\n".trim(),a={role:i.SYSTEM,content:c};function u(e,t,o){return n(this,void 0,void 0,(function*(){const n=t.querySelectorAll("img");if(!e.includeImages||!function(e){const n=e.match(/gpt-(\d+)/);return!!(null==n?void 0:n[1])&&Number(n[1])>=4}(e.model)||0===n.length)return o;const r=[],s=Array.from(n).map((e=>function(e,n=.75){return new Promise(((t,o)=>{const r=document.createElement("canvas"),s=r.getContext("2d");if(!s)return o("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,s.drawImage(i,0,0);const e=r.toDataURL("image/png",n);t(e),r.remove()},i.onerror=e=>{o(e),r.remove()},i.src=e.src}))}(e))),i=yield Promise.allSettled(s);for(const n of i)"fulfilled"===n.status?r.push({type:l.IMAGE,image_url:{url:n.value}}):e.logs&&console.error(n.reason);return r.push({type:l.TEXT,text:o}),r}))}function d(e,t,o){return n(this,void 0,void 0,(function*(){const n=yield u(e,t,o),r={role:i.USER,content:n};if(!e.history)return{messages:[a,r]};let s;const l=JSON.parse(null!==(c=sessionStorage.moodleGPTHistory)&&void 0!==c?c:"null");var c;const d=function(){var e,n;const t=new URLSearchParams(document.location.search);return{host:document.location.host,cmid:null!==(e=t.get("cmid"))&&void 0!==e?e:"",attempt:null!==(n=t.get("attempt"))&&void 0!==n?n:"",history:[]}}();return s=null!==l&&function(e,n){const t=["host","cmid","attempt"];for(const o of t)if(e[o]!==n[o])return!1;return!0}(l,d)?l:d,{messages:[a,...s.history,r],saveResponse(n){e.history&&(s.history.push(r),s.history.push({role:i.ASSISTANT,content:n}),sessionStorage.moodleGPTHistory=JSON.stringify(s))}}}))}function f(e){const n=[],t=Array.from(e.querySelectorAll("tr")),o=[];t.map((e=>{const t=Array.from(e.querySelectorAll("td, th")).map(((e,n)=>{var t;const r=null===(t=e.textContent)||void 0===t?void 0:t.trim();return o[n]=Math.max(o[n]||0,(null==r?void 0:r.length)||0),null!=r?r:""}));n.push(t)}));const r=n[0].length,s=o.reduce(((e,n)=>e+n),0)+3*(r-1),i="\n"+Array(s).fill("-").join("")+"\n",l=n.map((e=>e.map(((e,n)=>e.padEnd(o[n]," "))).join(" | ")));return l.shift()+i+l.join("\n")}function m(n,t){n.title&&e("Copied to clipboard"),navigator.clipboard.writeText(t.response)}function p(e,n,t){const o=n[0];if(1!==n.length||!function(e){const n=e.getAttribute("contenteditable");return"string"==typeof n&&"false"!==n}(o))return!1;if(e.typing){let e=0;const n=function(r){if(r.preventDefault(),"Backspace"===r.key||e>=t.response.length)return void o.removeEventListener("keydown",n);o.textContent=t.response.slice(0,++e),o.focus();const s=document.createRange();s.selectNodeContents(o),s.collapse(!1);const i=window.getSelection();null!==i&&(i.removeAllRanges(),i.addRange(s))};o.addEventListener("keydown",n)}else o.textContent=t.response;return!0}function v(e,n,t){var o,r;const s=n[0];if(1!==n.length||"number"!==s.type)return!1;const i=null===(r=null===(o=t.normalizedResponse.match(/\d+([,.]\d+)?/gi))||void 0===o?void 0:o[0])||void 0===r?void 0:r.replace(",",".");if(void 0===i)return!1;if(e.typing){let e=0;const n=function(t){t.preventDefault(),"Backspace"===t.key||e>=i.length?s.removeEventListener("keydown",n):("."===i.slice(e,e+1)&&++e,s.value=i.slice(0,++e))};s.addEventListener("keydown",n)}else s.value=i;return!0}function h(e,n,t){const i=null==n?void 0:n[0];if(!i||"radio"!==i.type)return!1;const l=Array.from(n).map((e=>{var n,t;return{element:e,value:s(null!==(t=null===(n=null==e?void 0:e.parentElement)||void 0===n?void 0:n.textContent)&&void 0!==t?t:"")}})).filter((e=>""!==e.value)),c=o(t.normalizedResponse,l);e.logs&&c.value&&r.bestAnswer(c.value,c.similarity);const a=c.element;return e.mouseover?a.addEventListener("mouseover",(()=>a.click()),{once:!0}):a.click(),!0}function g(e,n,t){const i=null==n?void 0:n[0];if(!i||"checkbox"!==i.type)return!1;const l=t.normalizedResponse.split("\n"),c=Array.from(n).map((e=>{var n,t;return{element:e,value:s(null!==(t=null===(n=null==e?void 0:e.parentElement)||void 0===n?void 0:n.textContent)&&void 0!==t?t:"")}})).filter((e=>""!==e.value)),a=new Set;for(const n of l){const t=o(n,c);e.logs&&t.value&&r.bestAnswer(t.value,t.similarity),a.add(t.element)}for(const n of c.map((e=>e.element))){const t=n.checked&&!a.has(n)||!n.checked&&a.has(n),o=()=>t&&n.click();e.mouseover?n.addEventListener("mouseover",o,{once:!0}):o()}return!0}function y(e,n,t){if(0===n.length||"SELECT"!==n[0].tagName)return!1;const i=t.normalizedResponse.split("\n");e.logs&&r.array(i);for(let t=0;t{var n;return{element:e,value:s(null!==(n=e.textContent)&&void 0!==n?n:"")}})).filter((e=>""!==e.value)),a=o(i[t],c);e.logs&&a.value&&r.bestAnswer(a.value,a.similarity);const u=a.element,d=u.closest("select");null!==d&&(e.mouseover?d.addEventListener("click",(()=>u.selected=!0),{once:!0}):u.selected=!0)}return!0}function w(e,n,t){const o=n[0];if(1!==n.length||"TEXTAREA"!==o.tagName&&"text"!==o.type)return!1;if(e.typing){let e=0;const n=function(r){r.preventDefault(),"Backspace"===r.key||e>=t.response.length?o.removeEventListener("keydown",n):o.value=t.response.slice(0,++e)};o.addEventListener("keydown",n)}else o.value=t.response;return!0}function E(e,n,t){const o=n[0];if(!o.classList.contains("qtype_essay_editor"))return!1;const r=o.querySelector("iframe");if(!(r&&r.contentDocument&&r.contentDocument.body&&r.contentWindow))return!1;const s=r.contentDocument.body.querySelector("p");if(!s)return!1;if(e.typing){let e=0;const n=function(o){if(o.preventDefault(),"Backspace"===o.key||e>=t.response.length)return void r.contentWindow.removeEventListener("keydown",n);const i=document.createTextNode(t.response.charAt(e++));s.appendChild(i);const l=r.contentDocument.createRange();l.selectNodeContents(s),l.collapse(!1);const c=r.contentWindow.getSelection();c&&(c.removeAllRanges(),c.addRange(l)),r.contentWindow.focus()};r.contentWindow.addEventListener("keydown",n)}else s.textContent+=t.response;return!0}function A(e){return n(this,void 0,void 0,(function*(){e.config.cursor&&(e.questionElement.style.cursor="wait");const t=function(e){let n=e.innerText;const t=e.querySelectorAll(".accesshide");for(const e of t)n=n.replace(e.innerText,"");const o=e.querySelector(".qtype_essay_editor");o&&(n=n.replace(o.innerText,""));const r=e.querySelectorAll(".qtext table");for(const e of r)n=n.replace(e.innerText,"\n"+f(e)+"\n");return s(n,!1)}(e.form),o=e.form.querySelectorAll(e.inputQuery),i=yield function(e,t,o){return n(this,void 0,void 0,(function*(){const n=new AbortController,r=setTimeout((()=>n.abort()),2e4),i=yield d(e,t,o),l=yield fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e.apiKey}`},signal:e.timeout?n.signal:null,body:JSON.stringify({model:e.model,messages:i.messages,temperature:.1,top_p:.6,presence_penalty:0,max_tokens:2e3})});clearTimeout(r);const c=(yield l.json()).choices[0].message.content;return"function"==typeof i.saveResponse&&i.saveResponse(c),{question:o,response:c,normalizedResponse:s(c)}}))}(e.config,e.questionElement,t).catch((e=>({error:e}))),l="object"==typeof i&&"error"in i;if(e.config.cursor&&(e.questionElement.style.cursor=e.config.infinite||l?"pointer":"initial"),l)console.error(i.error);else switch(e.config.logs&&(r.question(t),r.response(i)),e.config.mode){case"clipboard":!function(e){e.config.infinite||e.removeListener(),m(e.config,e.gptAnswer)}({config:e.config,questionElement:e.questionElement,gptAnswer:i,removeListener:e.removeListener});break;case"question-to-answer":!function(e){var n;const t=e.questionElement;e.removeListener();const o=null!==(n=t.innerHTML)&&void 0!==n?n:"";t.innerHTML=e.gptAnswer.response,t.style.whiteSpace="pre-wrap",t.addEventListener("click",(function(){const n=t.innerHTML===e.gptAnswer.response;t.style.whiteSpace=n?"initial":"pre-wrap",t.innerHTML=n?o:e.gptAnswer.response}))}({gptAnswer:i,questionElement:e.questionElement,removeListener:e.removeListener});break;case"autocomplete":!function(e){e.config.infinite||e.removeListener();const n=[E,p,w,v,y,h,g];for(const t of n)if(t(e.config,e.inputList,e.gptAnswer))return;m(e.config,e.gptAnswer)}({config:e.config,gptAnswer:i,inputList:o,questionElement:e.questionElement,removeListener:e.removeListener})}}))}const S=[],q=[];function L(e){const n=q.findIndex((n=>n.element===e));if(-1!==n){const e=q.splice(n,1)[0];e.element.removeEventListener("click",e.fn)}}function T(n){if(q.length>0){for(const e of q)n.cursor&&(e.element.style.cursor="initial"),e.element.removeEventListener("click",e.fn);return n.title&&e("Removed"),void(q.length=0)}const t=["checkbox","radio","text","number"].map((e=>`input[type="${e}"]`)).join(",")+", textarea, select, [contenteditable], .qtype_essay_editor",o=document.querySelectorAll(".formulation");for(const e of o){const o=e.querySelector(".qtext");if(null===o)continue;n.cursor&&(o.style.cursor="pointer");const r=A.bind(null,{config:n,questionElement:o,form:e,inputQuery:t,removeListener:()=>L(o)});q.push({element:o,fn:r}),o.addEventListener("click",r)}n.title&&e("Injected")}chrome.storage.sync.get(["moodleGPT"]).then((function(e){const n=e.moodleGPT;if(!n)throw new Error("Please configure MoodleGPT into the extension");n.code?function(e){document.body.addEventListener("keydown",(function(n){S.push(n.key),S.length>e.code.length&&S.shift(),S.join("")===e.code&&(S.length=0,T(e))}))}(n):T(n)}))})); +!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";function e(e){const t=document.title;document.title=e,setTimeout((()=>document.title=t),3e3)}function t(e,t,n,s){return new(n||(n=Promise))((function(r,o){function i(e){try{l(s.next(e))}catch(e){o(e)}}function a(e){try{l(s.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((s=s.apply(e,t||[])).next())}))}function n(e,t){const n=e.length>t.length?e.length:t.length;return 0===n?1:(n-function(e,t){if(0===e.length)return t.length;if(0===t.length)return e.length;const n=[],s=e.replace(/\s+/,""),r=t.replace(/\s+/,"");for(let e=0;e<=s.length;++e){n.push([e]);for(let t=1;t<=r.length;++t)n[e][t]=0===e?t:Math.min(n[e-1][t]+1,n[e][t-1]+1,n[e-1][t-1]+(s[e-1]===r[t-1]?0:1))}return n[s.length][r.length]}(e,t))/n}function s(e,t){let s={element:null,similarity:0,value:null};for(const r of t){const t=n(r.value,e);if(1===t)return{element:r.element,value:r.value,similarity:t};t>s.similarity&&(s={element:r.element,value:r.value,similarity:t})}return s}"function"==typeof SuppressedError&&SuppressedError;class r{static question(e){console.log("%c[QUESTION]: %s","color: cyan",e)}static bestAnswer(e,t){console.log("%c[BEST ANSWER]: %s","color: green",`"${e}" with a similarity of ${function(e){return Math.round(100*e*100)/100+"%"}(t)}`)}static array(e){console.log("[CORRECTS] ",e)}static response(e){console.log("Original:\n"+e.response),console.log("Normalized:\n"+e.normalizedResponse)}}function o(e,t=!0){t&&(e=e.toLowerCase());return e.replace(/\n+/gi,"\n").replace(/(\n\s*\n)+/g,"\n").replace(/[ \t]+/gi," ").trim().replace(/^[a-z\d]\.\s/gi,"").replace(/\n[a-z\d]\.\s/gi,"\n")}const i={role:"system",content:"\nAct as a quiz solver for the best notation with the following rules:\n- If no answer(s) are given, answer the statement as usual without following the other rules, providing the most detailed, complete and precise explanation. \n- But for the calculation provide this format 'result: '\n- For 'put in order' questions, maintain the answer in the order as presented in the question but assocy the correct order to it by usin this format ':\n:', ignore other rules.\n- Always reply in the format: '\n\n...'.\n- Retain only the correct answer(s).\n- Maintain the same order for the answers as in the text.\n- Retain all text from the answer with its description, content or definition.\n- Only provide answers that exactly match the given answer in the text.\n- The question always has the correct answer(s), so you should always provide an answer.\n- Always respond in the same language as the user's question.\n".trim()};function a(e,n,s){return t(this,void 0,void 0,(function*(){const t=n.querySelectorAll("img");if(!e.includeImages||!function(e){const t=e.match(/gpt-(\d+)/);return!!(null==t?void 0:t[1])&&Number(t[1])>=4}(e.model)||0===t.length)return s;const r=[],o=Array.from(t).map((e=>function(e,t=.75){return new Promise(((n,s)=>{const r=document.createElement("canvas"),o=r.getContext("2d");if(!o)return s("Can't get the canvas context, ensure your navigator support canvas"),void r.remove();const i=new Image;i.crossOrigin="Anonymous",i.onload=()=>{r.width=i.width,r.height=i.height,o.drawImage(i,0,0);const e=r.toDataURL("image/png",t);n(e),r.remove()},i.onerror=e=>{s(e),r.remove()},i.src=e.src}))}(e))),i=yield Promise.allSettled(o);for(const t of i)"fulfilled"===t.status?r.push({type:"image_url",image_url:{url:t.value}}):e.logs&&console.error(t.reason);return r.push({type:"text",text:s}),r}))}function l(e,n,s){return t(this,void 0,void 0,(function*(){const t={role:"user",content:yield a(e,n,s)};if(!e.history)return{messages:[i,t]};let r;const o=function(){var e;return JSON.parse(null!==(e=sessionStorage.moodleGPTHistory)&&void 0!==e?e:"null")}(),l=function(){var e,t;const n=new URLSearchParams(document.location.search);return{host:document.location.host,cmid:null!==(e=n.get("cmid"))&&void 0!==e?e:"",attempt:null!==(t=n.get("attempt"))&&void 0!==t?t:"",history:[]}}();return r=null!==o&&function(e,t){const n=["host","cmid","attempt"];for(const s of n)if(e[s]!==t[s])return!1;return!0}(o,l)?o:l,{messages:[i,...r.history,t],saveResponse(n){e.history&&(r.history.push(t),r.history.push({role:"assistant",content:n}),sessionStorage.moodleGPTHistory=JSON.stringify(r))}}}))}const c="RFC3986",u={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},h=Array.isArray,d=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),f=1024;function p(e,t){if(h(e)){const n=[];for(let s=0;sString(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},y=Array.isArray,w=Array.prototype.push,b=function(e,t){w.apply(e,y(t)?t:[t])},_=Date.prototype.toISOString,v={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:(e,t,n,s,r)=>{if(0===e.length)return e;let o=e;if("symbol"==typeof e?o=Symbol.prototype.toString.call(e):"string"!=typeof e&&(o=String(e)),"iso-8859-1"===n)return escape(o).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));let i="";for(let e=0;e=f?o.slice(e,e+f):o,n=[];for(let e=0;e=48&&s<=57||s>=65&&s<=90||s>=97&&s<=122||"RFC1738"===r&&(40===s||41===s)?n[n.length]=t.charAt(e):s<128?n[n.length]=d[s]:s<2048?n[n.length]=d[192|s>>6]+d[128|63&s]:s<55296||s>=57344?n[n.length]=d[224|s>>12]+d[128|s>>6&63]+d[128|63&s]:(e+=1,s=65536+((1023&s)<<10|1023&t.charCodeAt(e)),n[n.length]=d[240|s>>18]+d[128|s>>12&63]+d[128|s>>6&63]+d[128|63&s])}i+=n.join("")}return i},encodeValuesOnly:!1,format:c,formatter:u[c],indices:!1,serializeDate:e=>_.call(e),skipNulls:!1,strictNullHandling:!1};const x={};function S(e,t,n,s,r,o,i,a,l,c,u,h,d,f,m,g,w,_){let A=e,E=_,R=0,k=!1;for(;void 0!==(E=E.get(x))&&!k;){const t=E.get(e);if(R+=1,void 0!==t){if(t===R)throw new RangeError("Cyclic object value");k=!0}void 0===E.get(x)&&(R=0)}if("function"==typeof c?A=c(t,A):A instanceof Date?A=d?.(A):"comma"===n&&y(A)&&(A=p(A,(function(e){return e instanceof Date?d?.(e):e}))),null===A){if(o)return l&&!g?l(t,v.encoder,w,"key",f):t;A=""}if("string"==typeof(P=A)||"number"==typeof P||"boolean"==typeof P||"symbol"==typeof P||"bigint"==typeof P||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(A)){if(l){const e=g?t:l(t,v.encoder,w,"key",f);return[m?.(e)+"="+m?.(l(A,v.encoder,w,"value",f))]}return[m?.(t)+"="+m?.(String(A))]}var P;const C=[];if(void 0===A)return C;let I;if("comma"===n&&y(A))g&&l&&(A=p(A,l)),I=[{value:A.length>0?A.join(",")||null:void 0}];else if(y(c))I=c;else{const e=Object.keys(A);I=u?e.sort(u):e}const O=a?String(t).replace(/\./g,"%2E"):String(t),$=s&&y(A)&&1===A.length?O+"[]":O;if(r&&y(A)&&0===A.length)return $+"[]";for(let t=0;t0?f+d:""}const E="4.78.1";let R,k,P,C,I,O,$,T,j,q=!1;class N{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}R||function(e,t={auto:!1}){if(q)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(R)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${R}'\``);q=t.auto,R=e.kind,k=e.fetch,P=e.FormData,C=e.File,I=e.ReadableStream,O=e.getMultipartRequestOptions,$=e.getDefaultAgent,T=e.fileFromPath,j=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let n,s,r,o;try{n=fetch,s=Request,r=Response,o=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:n,Request:s,Response:r,Headers:o,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new N(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class M extends Error{}class L extends M{constructor(e,t,n,s){super(`${L.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s?.["x-request-id"],this.error=t;const r=t;this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,n){const s=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new B({message:n,cause:qe(t)});const r=t?.error;return 400===e?new W(e,r,n,s):401===e?new U(e,r,n,s):403===e?new X(e,r,n,s):404===e?new H(e,r,n,s):409===e?new J(e,r,n,s):422===e?new V(e,r,n,s):429===e?new K(e,r,n,s):e>=500?new z(e,r,n,s):new L(e,r,n,s)}}class D extends L{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class B extends L{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class F extends B{constructor({message:e}={}){super({message:e??"Request timed out."})}}class W extends L{}class U extends L{}class X extends L{}class H extends L{}class J extends L{}class V extends L{}class K extends L{}class z extends L{}class Q extends M{constructor(){super("Could not parse response content as the length limit was reached")}}class G extends M{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Y{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];const n=Y.NEWLINE_CHARS.has(t[t.length-1]||"");let s=t.split(Y.NEWLINE_REGEXP);return n&&s.pop(),1!==s.length||n?(this.buffer.length>0&&(s=[this.buffer.join("")+s[0],...s.slice(1)],this.buffer=[]),n||(this.buffer=[s.pop()||""]),s):(this.buffer.push(s[0]),[])}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new M(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new M(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new M("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}Y.NEWLINE_CHARS=new Set(["\n","\r"]),Y.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class Z{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;return new Z((async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const n of async function*(e,t){if(!e.body)throw t.abort(),new M("Attempted to iterate over a response with no body");const n=new te,s=new Y,r=ne(e.body);for await(const e of async function*(e){let t=new Uint8Array;for await(const n of e){if(null==n)continue;const e=n instanceof ArrayBuffer?new Uint8Array(n):"string"==typeof n?(new TextEncoder).encode(n):n;let s,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(s=ee(t));)yield t.slice(0,s),t=t.slice(s)}t.length>0&&(yield t)}(r))for(const t of s.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of s.flush()){const t=n.decode(e);t&&(yield t)}}(e,t))if(!s)if(n.data.startsWith("[DONE]"))s=!0;else if(null===n.event){let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if(e&&e.error)throw new L(void 0,e.error,void 0,void 0);yield e}else{let e;try{e=JSON.parse(n.data)}catch(e){throw console.error("Could not parse message into JSON:",n.data),console.error("From chunk:",n.raw),e}if("error"==n.event)throw new L(void 0,e.error,e.message,void 0);yield{event:n.event,data:e}}s=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{s||t.abort()}}),t)}static fromReadableStream(e,t){let n=!1;return new Z((async function*(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(const t of async function*(){const t=new Y,n=ne(e);for await(const e of n)for(const n of t.decode(e))yield n;for(const e of t.flush())yield e}())s||t&&(yield JSON.parse(t));s=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{s||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=s=>({next:()=>{if(0===s.length){const s=n.next();e.push(s),t.push(s)}return s.shift()}});return[new Z((()=>s(e)),this.controller),new Z((()=>s(t)),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new I({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:s,done:r}=await t.next();if(r)return e.close();const o=n.encode(JSON.stringify(s)+"\n");e.enqueue(o)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}function ee(e){for(let t=0;tnull!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,re=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&oe(e),oe=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function ie(e,t,n){if(e=await e,re(e))return e;if(se(e)){const s=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const r=oe(s)?[await s.arrayBuffer()]:[s];return new C(r,t,n)}const s=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(oe(e))t.push(await e.arrayBuffer());else{if(!le(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const n of e)t.push(n)}return t}(e);if(t||(t=function(e){return ae(e.name)||ae(e.filename)||ae(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!n?.type){const e=s[0]?.type;"string"==typeof e&&(n={...n,type:e})}return new C(s,t,n)}const ae=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,le=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],ce=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],ue=async e=>{const t=await he(e.body);return O(t,e)},he=async e=>{const t=new P;return await Promise.all(Object.entries(e||{}).map((([e,n])=>de(t,e,n)))),t},de=async(e,t,n)=>{if(void 0!==n){if(null==n)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof n||"number"==typeof n||"boolean"==typeof n)e.append(t,String(n));else if((e=>re(e)||se(e)||j(e))(n)){const s=await ie(n);e.append(t,s)}else if(Array.isArray(n))await Promise.all(n.map((n=>de(e,t+"[]",n))));else{if("object"!=typeof n)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`);await Promise.all(Object.entries(n).map((([n,s])=>de(e,`${t}[${n}]`,s))))}}};var fe,pe=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},me=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};async function ge(e){const{response:t}=e;if(e.options.stream)return Be("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):Z.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const n=t.headers.get("content-type");if(n?.includes("application/json")||n?.includes("application/vnd.api+json")){const e=await t.json();return Be("response",t.status,t.url,t.headers,e),ye(e,t)}const s=await t.text();return Be("response",t.status,t.url,t.headers,s),s}function ye(e,t){return!e||"object"!=typeof e||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get("x-request-id"),enumerable:!1})}class we extends Promise{constructor(e,t=ge){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new we(this.responsePromise,(async t=>ye(e(await this.parseResponse(t),t),t.response)))}asResponse(){return this.responsePromise.then((e=>e.response))}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class be{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:r}){this.baseURL=e,this.maxRetries=je("maxRetries",t),this.timeout=je("timeout",n),this.httpAgent=s,this.fetch=r??k}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Ce(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Fe()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then((async n=>{const s=n&&oe(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:s}})))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){const{method:n,path:s,query:r,headers:o={}}=e,i=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:ce(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,a=this.calculateContentLength(i),l=this.buildURL(s,r);"timeout"in e&&je("timeout",e.timeout);const c=e.timeout??this.timeout,u=e.httpAgent??this.httpAgent??$(l),h=c+1e3;"number"==typeof u?.options?.timeout&&h>(u.options.timeout??0)&&(u.options.timeout=h),this.idempotencyHeader&&"get"!==n&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:n,...i&&{body:i},headers:this.buildHeaders({options:e,headers:o,contentLength:a,retryCount:t}),...u&&{agent:u},signal:e.signal??null},url:l,timeout:c}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const r={};n&&(r["content-length"]=n);const o=this.defaultHeaders(e);return De(r,o),De(r,t),ce(e.body)&&"node"!==R&&delete r["content-type"],void 0===We(o,"x-stainless-retry-count")&&void 0===We(t,"x-stainless-retry-count")&&(r["x-stainless-retry-count"]=String(s)),this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,n,s){return L.generate(e,t,n,s)}request(e,t=null){return new we(this.makeRequest(e,t))}async makeRequest(e,t){const n=await e,s=n.maxRetries??this.maxRetries;null==t&&(t=s),await this.prepareOptions(n);const{req:r,url:o,timeout:i}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(r,{url:o,options:n}),Be("request",o,n,r.headers),n.signal?.aborted)throw new D;const a=new AbortController,l=await this.fetchWithTimeout(o,r,i,a).catch(qe);if(l instanceof Error){if(n.signal?.aborted)throw new D;if(t)return this.retryRequest(n,t);if("AbortError"===l.name)throw new F;throw new B({cause:l})}const c=xe(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){return Be(`response (error; ${`retrying, ${t} attempts remaining`})`,l.status,o,c),this.retryRequest(n,t,c)}const e=await l.text().catch((e=>qe(e).message)),s=Ie(e),r=s?void 0:e;Be(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,o,c,r);throw this.makeStatusError(l.status,s,r,c)}return{response:l,options:n,controller:a}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new ve(this,n,e)}buildURL(e,t){const n=$e(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Me(s)||(t={...s,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new M(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,n,s){const{signal:r,...o}=t||{};r&&r.addEventListener("abort",(()=>s.abort()));const i=setTimeout((()=>s.abort()),n),a={signal:s.signal,...o};return a.method&&(a.method=a.method.toUpperCase()),this.fetch.call(void 0,e,a).finally((()=>{clearTimeout(i)}))}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,n){let s;const r=n?.["retry-after-ms"];if(r){const e=parseFloat(r);Number.isNaN(e)||(s=e)}const o=n?.["retry-after"];if(o&&!s){const e=parseFloat(o);s=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){const n=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Te(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const n=t-e;return Math.min(.5*Math.pow(2,n),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${E}`}}class _e{constructor(e,t,n,s){fe.set(this,void 0),pe(this,fe,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new M("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,s]of n)e.url.searchParams.set(t,s);t.query=void 0,t.path=e.url.toString()}return await me(this,fe,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(fe=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class ve extends we{constructor(e,t,n){super(t,(async t=>new n(e,t.response,await ge(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const xe=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),Se={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},Ae=e=>"object"==typeof e&&null!==e&&!Me(e)&&Object.keys(e).every((e=>Le(Se,e))),Ee=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E,"X-Stainless-OS":ke(Deno.build.os),"X-Stainless-Arch":Re(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:Deno.version?.deno??"unknown"};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E,"X-Stainless-OS":ke(process.platform),"X-Stainless-Arch":Re(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:n}of e){const e=n.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":E,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const Re=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ke=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let Pe;const Ce=()=>Pe??(Pe=Ee()),Ie=e=>{try{return JSON.parse(e)}catch(e){return}},Oe=/^[a-z][a-z0-9+.-]*:/i,$e=e=>Oe.test(e),Te=e=>new Promise((t=>setTimeout(t,e))),je=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new M(`${e} must be an integer`);if(t<0)throw new M(`${e} must be a positive integer`);return t},qe=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},Ne=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function Me(e){if(!e)return!0;for(const t in e)return!1;return!0}function Le(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function De(e,t){for(const n in t){if(!Le(t,n))continue;const s=n.toLowerCase();if(!s)continue;const r=t[n];null===r?delete e[s]:void 0!==r&&(e[s]=r)}}function Be(e,...t){"undefined"!=typeof process&&"true"===process?.env?.DEBUG&&console.log(`OpenAI:DEBUG:${e}`,...t)}const Fe=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),We=(e,t)=>{const n=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const s=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,n)=>t+n.toUpperCase()));for(const r of[t,n,t.toUpperCase(),s]){const t=e.get(r);if(t)return t}}for(const[s,r]of Object.entries(e))if(s.toLowerCase()===n)return Array.isArray(r)?(r.length<=1||console.warn(`Received ${r.length} entries for the ${t} header, using the first entry.`),r[0]):r};function Ue(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class Xe extends _e{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class He extends _e{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class Je{constructor(e){this._client=e}}let Ve=class extends Je{create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}},Ke=class extends Je{constructor(){super(...arguments),this.completions=new Ve(this._client)}};Ke.Completions=Ve;class ze extends Je{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class Qe extends Je{create(e,t){return this._client.post("/audio/transcriptions",ue({body:e,...t}))}}class Ge extends Je{create(e,t){return this._client.post("/audio/translations",ue({body:e,...t}))}}class Ye extends Je{constructor(){super(...arguments),this.transcriptions=new Qe(this._client),this.translations=new Ge(this._client),this.speech=new ze(this._client)}}Ye.Transcriptions=Qe,Ye.Translations=Ge,Ye.Speech=ze;class Ze extends Je{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return Ae(e)?this.list({},e):this._client.getAPIList("/batches",et,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class et extends He{}Ze.BatchesPage=et;class tt extends Je{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return Ae(e)?this.list({},e):this._client.getAPIList("/assistants",nt,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class nt extends He{}function st(e){return"function"==typeof e.parse}tt.AssistantsPage=nt;const rt=e=>"assistant"===e?.role,ot=e=>"function"===e?.role,it=e=>"tool"===e?.role;var at,lt,ct,ut,ht,dt,ft,pt,mt,gt,yt,wt,bt,_t=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},vt=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class xt{constructor(){at.add(this),this.controller=new AbortController,lt.set(this,void 0),ct.set(this,(()=>{})),ut.set(this,(()=>{})),ht.set(this,void 0),dt.set(this,(()=>{})),ft.set(this,(()=>{})),pt.set(this,{}),mt.set(this,!1),gt.set(this,!1),yt.set(this,!1),wt.set(this,!1),_t(this,lt,new Promise(((e,t)=>{_t(this,ct,e,"f"),_t(this,ut,t,"f")})),"f"),_t(this,ht,new Promise(((e,t)=>{_t(this,dt,e,"f"),_t(this,ft,t,"f")})),"f"),vt(this,lt,"f").catch((()=>{})),vt(this,ht,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),vt(this,at,"m",bt).bind(this))}),0)}_connected(){this.ended||(vt(this,ct,"f").call(this),this._emit("connect"))}get ended(){return vt(this,mt,"f")}get errored(){return vt(this,gt,"f")}get aborted(){return vt(this,yt,"f")}abort(){this.controller.abort()}on(e,t){return(vt(this,pt,"f")[e]||(vt(this,pt,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=vt(this,pt,"f")[e];if(!n)return this;const s=n.findIndex((e=>e.listener===t));return s>=0&&n.splice(s,1),this}once(e,t){return(vt(this,pt,"f")[e]||(vt(this,pt,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,n)=>{_t(this,wt,!0,"f"),"error"!==e&&this.once("error",n),this.once(e,t)}))}async done(){_t(this,wt,!0,"f"),await vt(this,ht,"f")}_emit(e,...t){if(vt(this,mt,"f"))return;"end"===e&&(_t(this,mt,!0,"f"),vt(this,dt,"f").call(this));const n=vt(this,pt,"f")[e];if(n&&(vt(this,pt,"f")[e]=n.filter((e=>!e.once)),n.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return vt(this,wt,"f")||n?.length||Promise.reject(e),vt(this,ut,"f").call(this,e),vt(this,ft,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];vt(this,wt,"f")||n?.length||Promise.reject(e),vt(this,ut,"f").call(this,e),vt(this,ft,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function St(e){return"auto-parseable-response-format"===e?.$brand}function At(e){return"auto-parseable-tool"===e?.$brand}function Et(e,t){const n=e.choices.map((e=>{if("length"===e.finish_reason)throw new Q;if("content_filter"===e.finish_reason)throw new G;return{...e,message:{...e.message,tool_calls:e.message.tool_calls?.map((e=>function(e,t){const n=e.tools?.find((e=>e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:At(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??[],parsed:e.message.content&&!e.message.refusal?Rt(t,e.message.content):null}}}));return{...e,choices:n}}function Rt(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 kt(e,t){if(!e)return!1;const n=e.tools?.find((e=>e.function?.name===t.function.name));return At(n)||n?.function.strict||!1}function Pt(e){return!!St(e.response_format)||(e.tools?.some((e=>At(e)||"function"===e.type&&!0===e.function.strict))??!1)}lt=new WeakMap,ct=new WeakMap,ut=new WeakMap,ht=new WeakMap,dt=new WeakMap,ft=new WeakMap,pt=new WeakMap,mt=new WeakMap,gt=new WeakMap,yt=new WeakMap,wt=new WeakMap,at=new WeakSet,bt=function(e){if(_t(this,gt,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new D),e instanceof D)return _t(this,yt,!0,"f"),this._emit("abort",e);if(e instanceof M)return this._emit("error",e);if(e instanceof Error){const t=new M(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new M(String(e)))};var Ct,It,Ot,$t,Tt,jt,qt,Nt,Mt=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};const Lt=10;class Dt extends xt{constructor(){super(...arguments),Ct.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),(ot(e)||it(e))&&e.content)this._emit("functionCallResult",e.content);else if(rt(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(rt(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new M("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Mt(this,Ct,"m",It).call(this)}async finalMessage(){return await this.done(),Mt(this,Ct,"m",Ot).call(this)}async finalFunctionCall(){return await this.done(),Mt(this,Ct,"m",$t).call(this)}async finalFunctionCallResult(){return await this.done(),Mt(this,Ct,"m",Tt).call(this)}async totalUsage(){return await this.done(),Mt(this,Ct,"m",jt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Mt(this,Ct,"m",Ot).call(this);t&&this._emit("finalMessage",t);const n=Mt(this,Ct,"m",It).call(this);n&&this._emit("finalContent",n);const s=Mt(this,Ct,"m",$t).call(this);s&&this._emit("finalFunctionCall",s);const r=Mt(this,Ct,"m",Tt).call(this);null!=r&&this._emit("finalFunctionCallResult",r),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",Mt(this,Ct,"m",jt).call(this))}async _createChatCompletion(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),Mt(this,Ct,"m",qt).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Et(r,t))}async _runChatCompletion(e,t,n){for(const e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){const s="function",{function_call:r="auto",stream:o,...i}=t,a="string"!=typeof r&&r?.name,{maxChatCompletions:l=Lt}=n||{},c={};for(const e of t.functions)c[e.name||e.function.name]=e;const u=t.functions.map((e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description})));for(const e of t.messages)this._addMessage(e,!1);for(let t=0;tJSON.stringify(e.name))).join(", ")}. Please try again`;this._addMessage({role:s,name:l,content:e});continue}if(a&&a!==l){const e=`Invalid function_call: ${JSON.stringify(l)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:s,name:l,content:e});continue}let f;try{f=st(d)?await d.parse(h):h}catch(e){this._addMessage({role:s,name:l,content:e instanceof Error?e.message:String(e)});continue}const p=await d.function(f,this),m=Mt(this,Ct,"m",Nt).call(this,p);if(this._addMessage({role:s,name:l,content:m}),a)return}}async _runTools(e,t,n){const s="tool",{tool_choice:r="auto",stream:o,...i}=t,a="string"!=typeof r&&r?.function?.name,{maxChatCompletions:l=Lt}=n||{},c=t.tools.map((e=>{if(At(e)){if(!e.$callback)throw new M("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e})),u={};for(const e of c)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const h="tools"in t?c.map((e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e)):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;tJSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}if(a&&a!==n){const e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(a)} requested. Please try again`;this._addMessage({role:s,tool_call_id:t,content:e});continue}let i;try{i=st(o)?await o.parse(r):r}catch(e){const n=e instanceof Error?e.message:String(e);this._addMessage({role:s,tool_call_id:t,content:n});continue}const l=await o.function(i,this),c=Mt(this,Ct,"m",Nt).call(this,l);if(this._addMessage({role:s,tool_call_id:t,content:c}),a)return}}}}Ct=new WeakSet,It=function(){return Mt(this,Ct,"m",Ot).call(this).content??null},Ot=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(rt(t)){const{function_call:e,...n}=t,s={...n,content:t.content??null,refusal:t.refusal??null};return e&&(s.function_call=e),s}}throw new M("stream ended without producing a ChatCompletionMessage with role=assistant")},$t=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(rt(t)&&t?.function_call)return t.function_call;if(rt(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Tt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ot(t)&&null!=t.content)return t.content;if(it(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}},jt=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},qt=function(e){if(null!=e.n&&e.n>1)throw new M("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Nt=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Bt extends Dt{static runFunctions(e,t,n){const s=new Bt,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run((()=>s._runFunctions(e,t,r))),s}static runTools(e,t,n){const s=new Bt,r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run((()=>s._runTools(e,t,r))),s}_addMessage(e,t=!0){super._addMessage(e,t),rt(e)&&e.content&&this._emit("content",e.content)}}const Ft=1,Wt=2,Ut=4,Xt=8,Ht=16,Jt=32,Vt=64,Kt=128,zt=256,Qt=511;class Gt extends Error{}class Yt extends Error{}const Zt=(e,t)=>{const n=e.length;let s=0;const r=e=>{throw new Gt(`${e} at position ${s}`)},o=e=>{throw new Yt(`${e} at position ${s}`)},i=()=>(h(),s>=n&&r("Unexpected end of input"),'"'===e[s]?a():"{"===e[s]?l():"["===e[s]?c():"null"===e.substring(s,s+4)||Ht&t&&n-s<4&&"null".startsWith(e.substring(s))?(s+=4,null):"true"===e.substring(s,s+4)||Jt&t&&n-s<4&&"true".startsWith(e.substring(s))?(s+=4,!0):"false"===e.substring(s,s+5)||Jt&t&&n-s<5&&"false".startsWith(e.substring(s))?(s+=5,!1):"Infinity"===e.substring(s,s+8)||Kt&t&&n-s<8&&"Infinity".startsWith(e.substring(s))?(s+=8,1/0):"-Infinity"===e.substring(s,s+9)||zt&t&&1{const i=s;let a=!1;for(s++;s{s++,h();const o={};try{for(;"}"!==e[s];){if(h(),s>=n&&Xt&t)return o;const r=a();h(),s++;try{const e=i();Object.defineProperty(o,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Xt&t)return o;throw e}h(),","===e[s]&&s++}}catch(e){if(Xt&t)return o;r("Expected '}' at end of object")}return s++,o},c=()=>{s++;const n=[];try{for(;"]"!==e[s];)n.push(i()),h(),","===e[s]&&s++}catch(e){if(Ut&t)return n;r("Expected ']' at end of array")}return s++,n},u=()=>{if(0===s){"-"===e&&Wt&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(n){if(Wt&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}o(String(n))}}const i=s;for("-"===e[s]&&s++;e[s]&&!",]}".includes(e[s]);)s++;s!=n||Wt&t||r("Unterminated number literal");try{return JSON.parse(e.substring(i,s))}catch(n){"-"===e.substring(i,s)&&Wt&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(i,e.lastIndexOf("e")))}catch(e){o(String(e))}}},h=()=>{for(;sfunction(e,t=Qt){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,Qt^Wt);var tn,nn,sn,rn,on,an,ln,cn,un,hn,dn,fn,pn=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n},mn=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)};class gn extends Dt{constructor(e){super(),tn.add(this),nn.set(this,void 0),sn.set(this,void 0),rn.set(this,void 0),pn(this,nn,e,"f"),pn(this,sn,[],"f")}get currentChatCompletionSnapshot(){return mn(this,rn,"f")}static fromReadableStream(e){const t=new gn(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,n){const s=new gn(t);return s._run((()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}async _createChatCompletion(e,t,n){super._createChatCompletion;const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),mn(this,tn,"m",on).call(this);const r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const e of r)mn(this,tn,"m",ln).call(this,e);if(r.controller.signal?.aborted)throw new D;return this._addChatCompletion(mn(this,tn,"m",hn).call(this))}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),mn(this,tn,"m",on).call(this),this._connected();const s=Z.fromReadableStream(e,this.controller);let r;for await(const e of s)r&&r!==e.id&&this._addChatCompletion(mn(this,tn,"m",hn).call(this)),mn(this,tn,"m",ln).call(this,e),r=e.id;if(s.controller.signal?.aborted)throw new D;return this._addChatCompletion(mn(this,tn,"m",hn).call(this))}[(nn=new WeakMap,sn=new WeakMap,rn=new WeakMap,tn=new WeakSet,on=function(){this.ended||pn(this,rn,void 0,"f")},an=function(e){let t=mn(this,sn,"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},mn(this,sn,"f")[e.index]=t,t)},ln=function(e){if(this.ended)return;const t=mn(this,tn,"m",fn).call(this,e);this._emit("chunk",e,t);for(const n of e.choices){const e=t.choices[n.index];null!=n.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",n.delta.content,e.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=n.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:e.message.refusal}),null!=n.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=n.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const s=mn(this,tn,"m",an).call(this,e);e.finish_reason&&(mn(this,tn,"m",un).call(this,e),null!=s.current_tool_call_index&&mn(this,tn,"m",cn).call(this,e,s.current_tool_call_index));for(const t of n.delta.tool_calls??[])s.current_tool_call_index!==t.index&&(mn(this,tn,"m",un).call(this,e),null!=s.current_tool_call_index&&mn(this,tn,"m",cn).call(this,e,s.current_tool_call_index)),s.current_tool_call_index=t.index;for(const t of n.delta.tool_calls??[]){const n=e.message.tool_calls?.[t.index];n?.type&&("function"===n?.type&&this._emit("tool_calls.function.arguments.delta",{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??""}))}}},cn=function(e,t){if(mn(this,tn,"m",an).call(this,e).done_tool_calls.has(t))return;const n=e.message.tool_calls?.[t];if(!n)throw new Error("no tool call snapshot");if(!n.type)throw new Error("tool call snapshot missing `type`");if("function"===n.type){const e=mn(this,nn,"f")?.tools?.find((e=>"function"===e.type&&e.function.name===n.function.name));this._emit("tool_calls.function.arguments.done",{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:At(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},un=function(e){const t=mn(this,tn,"m",an).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const n=mn(this,tn,"m",dn).call(this);this._emit("content.done",{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},hn=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");const e=mn(this,rn,"f");if(!e)throw new M("request ended without sending any chunks");return pn(this,rn,void 0,"f"),pn(this,sn,[],"f"),function(e,t){const{id:n,choices:s,created:r,model:o,system_fingerprint:i,...a}=e,l={...a,id:n,choices:s.map((({message:t,finish_reason:n,index:s,logprobs:r,...o})=>{if(!n)throw new M(`missing finish_reason for choice ${s}`);const{content:i=null,function_call:a,tool_calls:l,...c}=t,u=t.role;if(!u)throw new M(`missing role for choice ${s}`);if(a){const{arguments:e,name:l}=a;if(null==e)throw new M(`missing function_call.arguments for choice ${s}`);if(!l)throw new M(`missing function_call.name for choice ${s}`);return{...o,message:{content:i,function_call:{arguments:e,name:l},role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}}return l?{...o,index:s,finish_reason:n,logprobs:r,message:{...c,role:u,content:i,refusal:t.refusal??null,tool_calls:l.map(((t,n)=>{const{function:r,type:o,id:i,...a}=t,{arguments:l,name:c,...u}=r||{};if(null==i)throw new M(`missing choices[${s}].tool_calls[${n}].id\n${yn(e)}`);if(null==o)throw new M(`missing choices[${s}].tool_calls[${n}].type\n${yn(e)}`);if(null==c)throw new M(`missing choices[${s}].tool_calls[${n}].function.name\n${yn(e)}`);if(null==l)throw new M(`missing choices[${s}].tool_calls[${n}].function.arguments\n${yn(e)}`);return{...a,id:i,type:o,function:{...u,name:c,arguments:l}}}))}}:{...o,message:{...c,content:i,role:u,refusal:t.refusal??null},finish_reason:n,index:s,logprobs:r}})),created:r,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return function(e,t){return t&&Pt(t)?Et(e,t):{...e,choices:e.choices.map((e=>({...e,message:{...e.message,parsed:null,tool_calls:e.message.tool_calls??[]}})))}}(l,t)}(e,mn(this,nn,"f"))},dn=function(){const e=mn(this,nn,"f")?.response_format;return St(e)?e:null},fn=function(e){var t,n,s,r;let o=mn(this,rn,"f");const{choices:i,...a}=e;o?Object.assign(o,a):o=pn(this,rn,{...a,choices:[]},"f");for(const{delta:i,finish_reason:a,index:l,logprobs:c=null,...u}of e.choices){let e=o.choices[l];if(e||(e=o.choices[l]={finish_reason:a,index:l,message:{},logprobs:c,...u}),c)if(e.logprobs){const{content:s,refusal:r,...o}=c;Object.assign(e.logprobs,o),s&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...s)),r&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...r))}else e.logprobs=Object.assign({},c);if(a&&(e.finish_reason=a,mn(this,nn,"f")&&Pt(mn(this,nn,"f")))){if("length"===a)throw new Q;if("content_filter"===a)throw new G}if(Object.assign(e,u),!i)continue;const{content:h,refusal:d,function_call:f,role:p,tool_calls:m,...g}=i;if(Object.assign(e.message,g),d&&(e.message.refusal=(e.message.refusal||"")+d),p&&(e.message.role=p),f&&(e.message.function_call?(f.name&&(e.message.function_call.name=f.name),f.arguments&&((s=e.message.function_call).arguments??(s.arguments=""),e.message.function_call.arguments+=f.arguments)):e.message.function_call=f),h&&(e.message.content=(e.message.content||"")+h,!e.message.refusal&&mn(this,tn,"m",dn).call(this)&&(e.message.parsed=en(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:n,type:s,function:o,...i}of m){const a=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(a,i),n&&(a.id=n),s&&(a.type=s),o&&(a.function??(a.function={name:o.name??"",arguments:""})),o?.name&&(a.function.name=o.name),o?.arguments&&(a.function.arguments+=o.arguments,kt(mn(this,nn,"f"),a)&&(a.function.parsed_arguments=en(a.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",(n=>{const s=t.shift();s?s.resolve(n):e.push(n)})),this.on("end",(()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),this.on("error",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise(((e,n)=>t.push({resolve:e,reject:n}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function yn(e){return JSON.stringify(e)}class wn extends gn{static fromReadableStream(e){const t=new wn(null);return t._run((()=>t._fromReadableStream(e))),t}static runFunctions(e,t,n){const s=new wn(null),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run((()=>s._runFunctions(e,t,r))),s}static runTools(e,t,n){const s=new wn(t),r={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run((()=>s._runTools(e,t,r))),s}}let bn=class extends Je{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new M(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new M(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((t=>Et(t,e)))}runFunctions(e,t){return e.stream?wn.runFunctions(this._client,e,t):Bt.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?wn.runTools(this._client,e,t):Bt.runTools(this._client,e,t)}stream(e,t){return gn.createChatCompletion(this._client,e,t)}};class _n extends Je{constructor(){super(...arguments),this.completions=new bn(this._client)}}!function(e){e.Completions=bn}(_n);class vn extends Je{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class xn extends Je{constructor(){super(...arguments),this.sessions=new vn(this._client)}}xn.Sessions=vn;var Sn,An,En,Rn,kn,Pn,Cn,In,On,$n,Tn,jn,qn,Nn,Mn,Ln,Dn,Bn,Fn,Wn,Un,Xn,Hn=function(e,t,n,s){if("a"===n&&!s)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!s:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===n?s:"a"===n?s.call(e):s?s.value:t.get(e)},Jn=function(e,t,n,s,r){if("m"===s)throw new TypeError("Private method is not writable");if("a"===s&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===s?r.call(e,n):r?r.value=n:t.set(e,n),n};class Vn extends xt{constructor(){super(...arguments),Sn.add(this),An.set(this,[]),En.set(this,{}),Rn.set(this,{}),kn.set(this,void 0),Pn.set(this,void 0),Cn.set(this,void 0),In.set(this,void 0),On.set(this,void 0),$n.set(this,void 0),Tn.set(this,void 0),jn.set(this,void 0),qn.set(this,void 0)}[(An=new WeakMap,En=new WeakMap,Rn=new WeakMap,kn=new WeakMap,Pn=new WeakMap,Cn=new WeakMap,In=new WeakMap,On=new WeakMap,$n=new WeakMap,Tn=new WeakMap,jn=new WeakMap,qn=new WeakMap,Sn=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",(n=>{const s=t.shift();s?s.resolve(n):e.push(n)})),this.on("end",(()=>{n=!0;for(const e of t)e.resolve(void 0);t.length=0})),this.on("abort",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),this.on("error",(e=>{n=!0;for(const n of t)n.reject(e);t.length=0})),{next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise(((e,n)=>t.push({resolve:e,reject:n}))).then((e=>e?{value:e,done:!1}:{value:void 0,done:!0}));return{value:e.shift(),done:!1}},return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Vn;return t._run((()=>t._fromReadableStream(e))),t}async _fromReadableStream(e,t){const n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),this._connected();const s=Z.fromReadableStream(e,this.controller);for await(const e of s)Hn(this,Sn,"m",Nn).call(this,e);if(s.controller.signal?.aborted)throw new D;return this._addRun(Hn(this,Sn,"m",Mn).call(this))}toReadableStream(){return new Z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,r){const o=new Vn;return o._run((()=>o._runToolAssistantStream(e,t,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),o}async _createToolAssistantStream(e,t,n,s,r){const o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",(()=>this.controller.abort())));const i={...s,stream:!0},a=await e.submitToolOutputs(t,n,i,{...r,signal:this.controller.signal});this._connected();for await(const e of a)Hn(this,Sn,"m",Nn).call(this,e);if(a.controller.signal?.aborted)throw new D;return this._addRun(Hn(this,Sn,"m",Mn).call(this))}static createThreadAssistantStream(e,t,n){const s=new Vn;return s._run((()=>s._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),s}static createAssistantStream(e,t,n,s){const r=new Vn;return r._run((()=>r._runAssistantStream(e,t,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}currentEvent(){return Hn(this,Tn,"f")}currentRun(){return Hn(this,jn,"f")}currentMessageSnapshot(){return Hn(this,kn,"f")}currentRunStepSnapshot(){return Hn(this,qn,"f")}async finalRunSteps(){return await this.done(),Object.values(Hn(this,En,"f"))}async finalMessages(){return await this.done(),Object.values(Hn(this,Rn,"f"))}async finalRun(){if(await this.done(),!Hn(this,Pn,"f"))throw Error("Final run was not received.");return Hn(this,Pn,"f")}async _createThreadAssistantStream(e,t,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort())));const r={...t,stream:!0},o=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(const e of o)Hn(this,Sn,"m",Nn).call(this,e);if(o.controller.signal?.aborted)throw new D;return this._addRun(Hn(this,Sn,"m",Mn).call(this))}async _createAssistantStream(e,t,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",(()=>this.controller.abort())));const o={...n,stream:!0},i=await e.create(t,o,{...s,signal:this.controller.signal});this._connected();for await(const e of i)Hn(this,Sn,"m",Nn).call(this,e);if(i.controller.signal?.aborted)throw new D;return this._addRun(Hn(this,Sn,"m",Mn).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let t=e[n];if(null!=t)if("index"!==n&&"type"!==n){if("string"==typeof t&&"string"==typeof s)t+=s;else if("number"==typeof t&&"number"==typeof s)t+=s;else{if(!Ue(t)||!Ue(s)){if(Array.isArray(t)&&Array.isArray(s)){if(t.every((e=>"string"==typeof e||"number"==typeof e))){t.push(...s);continue}for(const e of s){if(!Ue(e))throw new Error(`Expected array delta entry to be an object but got: ${e}`);const n=e.index;if(null==n)throw console.error(e),new Error("Expected array delta entry to have an `index` property");if("number"!=typeof n)throw new Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);const s=t[n];null==s?t.push(e):t[n]=this.accumulateDelta(s,e)}continue}throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${t}`)}t=this.accumulateDelta(t,s)}e[n]=t}else e[n]=s;else e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,r){return await this._createToolAssistantStream(n,e,t,s,r)}}Nn=function(e){if(!this.ended)switch(Jn(this,Tn,e,"f"),Hn(this,Sn,"m",Bn).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Hn(this,Sn,"m",Xn).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":Hn(this,Sn,"m",Dn).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":Hn(this,Sn,"m",Ln).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Mn=function(){if(this.ended)throw new M("stream has ended, this shouldn't happen");if(!Hn(this,Pn,"f"))throw Error("Final run has not been received");return Hn(this,Pn,"f")},Ln=function(e){const[t,n]=Hn(this,Sn,"m",Wn).call(this,e,Hn(this,kn,"f"));Jn(this,kn,t,"f"),Hn(this,Rn,"f")[t.id]=t;for(const e of n){const n=t.content[e.index];"text"==n?.type&&this._emit("textCreated",n.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const n of e.data.delta.content){if("text"==n.type&&n.text){let e=n.text,s=t.content[n.index];if(!s||"text"!=s.type)throw Error("The snapshot associated with this text delta is not text or missing");this._emit("textDelta",e,s.text)}if(n.index!=Hn(this,Cn,"f")){if(Hn(this,In,"f"))switch(Hn(this,In,"f").type){case"text":this._emit("textDone",Hn(this,In,"f").text,Hn(this,kn,"f"));break;case"image_file":this._emit("imageFileDone",Hn(this,In,"f").image_file,Hn(this,kn,"f"))}Jn(this,Cn,n.index,"f")}Jn(this,In,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==Hn(this,Cn,"f")){const t=e.data.content[Hn(this,Cn,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,Hn(this,kn,"f"));break;case"text":this._emit("textDone",t.text,Hn(this,kn,"f"))}}Hn(this,kn,"f")&&this._emit("messageDone",e.data),Jn(this,kn,void 0,"f")}},Dn=function(e){const t=Hn(this,Sn,"m",Fn).call(this,e);switch(Jn(this,qn,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&"tool_calls"==n.step_details.type&&n.step_details.tool_calls&&"tool_calls"==t.step_details.type)for(const e of n.step_details.tool_calls)e.index==Hn(this,On,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(Hn(this,$n,"f")&&this._emit("toolCallDone",Hn(this,$n,"f")),Jn(this,On,e.index,"f"),Jn(this,$n,t.step_details.tool_calls[e.index],"f"),Hn(this,$n,"f")&&this._emit("toolCallCreated",Hn(this,$n,"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":Jn(this,qn,void 0,"f");"tool_calls"==e.data.step_details.type&&Hn(this,$n,"f")&&(this._emit("toolCallDone",Hn(this,$n,"f")),Jn(this,$n,void 0,"f")),this._emit("runStepDone",e.data,t)}},Bn=function(e){Hn(this,An,"f").push(e),this._emit("event",e)},Fn=function(e){switch(e.event){case"thread.run.step.created":return Hn(this,En,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Hn(this,En,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=Vn.accumulateDelta(t,n.delta);Hn(this,En,"f")[e.data.id]=s}return Hn(this,En,"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":Hn(this,En,"f")[e.data.id]=e.data}if(Hn(this,En,"f")[e.data.id])return Hn(this,En,"f")[e.data.id];throw new Error("No snapshot available")},Wn=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const e of s.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=Hn(this,Sn,"m",Un).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Un=function(e,t){return Vn.accumulateDelta(t,e)},Xn=function(e){switch(Jn(this,jn,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":Jn(this,Pn,e.data,"f"),Hn(this,$n,"f")&&(this._emit("toolCallDone",Hn(this,$n,"f")),Jn(this,$n,void 0,"f"))}};class Kn extends Je{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Ae(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,zn,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class zn extends He{}Kn.MessagesPage=zn;class Qn extends Je{retrieve(e,t,n,s={},r){return Ae(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t,n={},s){return Ae(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Gn,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Gn extends He{}Qn.RunStepsPage=Gn;class Yn extends Je{constructor(){super(...arguments),this.steps=new Qn(this._client)}create(e,t,n){const{include:s,...r}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},n){return Ae(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Zn,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}createAndStream(e,t,n){return Vn.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:o}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...s}}).withResponse();switch(r.status){case"queued":case"in_progress":case"cancelling":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Te(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,n){return Vn.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const r=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,r.id,s)}submitToolOutputsStream(e,t,n,s){return Vn.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}}class Zn extends He{}Yn.RunsPage=Zn,Yn.Steps=Qn,Yn.RunStepsPage=Gn;class es extends Je{constructor(){super(...arguments),this.runs=new Yn(this._client),this.messages=new Kn(this._client)}create(e={},t){return Ae(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return Vn.createThreadAssistantStream(e,this._client.beta.threads,t)}}es.Runs=Yn,es.RunsPage=Zn,es.Messages=Kn,es.MessagesPage=zn;let ts=class extends Je{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},n){return Ae(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,ns,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const r=await this.retrieve(e,t,{...n,headers:s}).withResponse(),o=r.data;switch(o.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=r.response.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Te(e);break;case"failed":case"completed":return o}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}};class ns extends He{}ts.VectorStoreFilesPage=ns;class ss extends Je{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return Ae(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,ns,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}async poll(e,t,n){const s={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:r,response:o}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(r.status){case"in_progress":let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{const t=o.headers.get("openai-poll-after-ms");if(t){const n=parseInt(t);isNaN(n)||(e=n)}}await Te(e);break;case"failed":case"cancelled":case"completed":return r}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(null==t||0==t.length)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const r=s?.maxConcurrency??5,o=Math.min(r,t.length),i=this._client,a=t.values(),l=[...n];const c=Array(o).fill(a).map((async function(e){for(let t of e){const e=await i.files.create({file:t,purpose:"assistants"},s);l.push(e.id)}}));return await(async e=>{const t=await Promise.allSettled(e),n=t.filter((e=>"rejected"===e.status));if(n.length){for(const e of n)console.error(e.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const s=[];for(const e of t)"fulfilled"===e.status&&s.push(e.value);return s})(c),await this.createAndPoll(e,{file_ids:l})}}class rs extends Je{constructor(){super(...arguments),this.files=new ts(this._client),this.fileBatches=new ss(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return Ae(e)?this.list({},e):this._client.getAPIList("/vector_stores",os,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class os extends He{}rs.VectorStoresPage=os,rs.Files=ts,rs.VectorStoreFilesPage=ns,rs.FileBatches=ss;class is extends Je{constructor(){super(...arguments),this.realtime=new xn(this._client),this.vectorStores=new rs(this._client),this.chat=new _n(this._client),this.assistants=new tt(this._client),this.threads=new es(this._client)}}is.Realtime=xn,is.VectorStores=rs,is.VectorStoresPage=os,is.Assistants=tt,is.AssistantsPage=nt,is.Threads=es;class as extends Je{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class ls extends Je{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}class cs extends Je{create(e,t){return this._client.post("/files",ue({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return Ae(e)?this.list({},e):this._client.getAPIList("/files",us,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){const s=new Set(["processed","error","deleted"]),r=Date.now();let o=await this.retrieve(e);for(;!o.status||!s.has(o.status);)if(await Te(t),o=await this.retrieve(e),Date.now()-r>n)throw new F({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return o}}class us extends He{}cs.FileObjectsPage=us;class hs extends Je{list(e,t={},n){return Ae(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,ds,{query:t,...n})}}class ds extends He{}hs.FineTuningJobCheckpointsPage=ds;class fs extends Je{constructor(){super(...arguments),this.checkpoints=new hs(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return Ae(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",ps,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return Ae(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,ms,{query:t,...n})}}class ps extends He{}class ms extends He{}fs.FineTuningJobsPage=ps,fs.FineTuningJobEventsPage=ms,fs.Checkpoints=hs,fs.FineTuningJobCheckpointsPage=ds;class gs extends Je{constructor(){super(...arguments),this.jobs=new fs(this._client)}}gs.Jobs=fs,gs.FineTuningJobsPage=ps,gs.FineTuningJobEventsPage=ms;class ys extends Je{createVariation(e,t){return this._client.post("/images/variations",ue({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",ue({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class ws extends Je{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",bs,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class bs extends Xe{}ws.ModelsPage=bs;class _s extends Je{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class vs extends Je{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,ue({body:t,...n}))}}class xs extends Je{constructor(){super(...arguments),this.parts=new vs(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}var Ss;xs.Parts=vs;class As extends be{constructor({baseURL:e=Ne("OPENAI_BASE_URL"),apiKey:t=Ne("OPENAI_API_KEY"),organization:n=Ne("OPENAI_ORG_ID")??null,project:s=Ne("OPENAI_PROJECT_ID")??null,...r}={}){if(void 0===t)throw new M("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const o={apiKey:t,organization:n,project:s,...r,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new M("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new as(this),this.chat=new Ke(this),this.embeddings=new ls(this),this.files=new cs(this),this.images=new ys(this),this.audio=new Ye(this),this.moderations=new _s(this),this.models=new ws(this),this.fineTuning=new gs(this),this.beta=new is(this),this.batches=new Ze(this),this.uploads=new xs(this),this._options=o,this.apiKey=t,this.organization=n,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return A(e,{arrayFormat:"brackets"})}}function Es(e){const t=[],n=Array.from(e.querySelectorAll("tr")),s=[];n.map((e=>{const n=Array.from(e.querySelectorAll("td, th")).map(((e,t)=>{var n;const r=null===(n=e.textContent)||void 0===n?void 0:n.trim();return s[t]=Math.max(s[t]||0,(null==r?void 0:r.length)||0),null!=r?r:""}));t.push(n)}));const r=t[0].length,o=s.reduce(((e,t)=>e+t),0)+3*(r-1),i="\n"+Array(o).fill("-").join("")+"\n",a=t.map((e=>e.map(((e,t)=>e.padEnd(s[t]," "))).join(" | ")));return a.shift()+i+a.join("\n")}function Rs(t,n){t.title&&e("Copied to clipboard"),navigator.clipboard.writeText(n.response)}function ks(e,t,n){const s=t[0];if(1!==t.length||!function(e){const t=e.getAttribute("contenteditable");return"string"==typeof t&&"false"!==t}(s))return!1;if(e.typing){let e=0;const t=function(r){if(r.preventDefault(),"Backspace"===r.key||e>=n.response.length)return void s.removeEventListener("keydown",t);s.textContent=n.response.slice(0,++e),s.focus();const o=document.createRange();o.selectNodeContents(s),o.collapse(!1);const i=window.getSelection();null!==i&&(i.removeAllRanges(),i.addRange(o))};s.addEventListener("keydown",t)}else s.textContent=n.response;return!0}function Ps(e,t,n){var s,r;const o=t[0];if(1!==t.length||"number"!==o.type)return!1;const i=null===(r=null===(s=n.normalizedResponse.match(/\d+([,.]\d+)?/gi))||void 0===s?void 0:s[0])||void 0===r?void 0:r.replace(",",".");if(void 0===i)return!1;if(e.typing){let e=0;const t=function(n){n.preventDefault(),"Backspace"===n.key||e>=i.length?o.removeEventListener("keydown",t):("."===i.slice(e,e+1)&&++e,o.value=i.slice(0,++e))};o.addEventListener("keydown",t)}else o.value=i;return!0}function Cs(e,t,n){const i=null==t?void 0:t[0];if(!i||"radio"!==i.type)return!1;const a=Array.from(t).map((e=>{var t,n;return{element:e,value:o(null!==(n=null===(t=null==e?void 0:e.parentElement)||void 0===t?void 0:t.textContent)&&void 0!==n?n:"")}})).filter((e=>""!==e.value)),l=s(n.normalizedResponse,a);e.logs&&l.value&&r.bestAnswer(l.value,l.similarity);const c=l.element;return e.mouseover?c.addEventListener("mouseover",(()=>c.click()),{once:!0}):c.click(),!0}function Is(e,t,n){const i=null==t?void 0:t[0];if(!i||"checkbox"!==i.type)return!1;const a=n.normalizedResponse.split("\n"),l=Array.from(t).map((e=>{var t,n;return{element:e,value:o(null!==(n=null===(t=null==e?void 0:e.parentElement)||void 0===t?void 0:t.textContent)&&void 0!==n?n:"")}})).filter((e=>""!==e.value)),c=new Set;for(const t of a){const n=s(t,l);e.logs&&n.value&&r.bestAnswer(n.value,n.similarity),c.add(n.element)}for(const t of l.map((e=>e.element))){const n=t.checked&&!c.has(t)||!t.checked&&c.has(t),s=()=>n&&t.click();e.mouseover?t.addEventListener("mouseover",s,{once:!0}):s()}return!0}function Os(e,t,n){if(0===t.length||"SELECT"!==t[0].tagName)return!1;const i=n.normalizedResponse.split("\n");e.logs&&r.array(i);for(let n=0;n{var t;return{element:e,value:o(null!==(t=e.textContent)&&void 0!==t?t:"")}})).filter((e=>""!==e.value)),c=s(i[n],l);e.logs&&c.value&&r.bestAnswer(c.value,c.similarity);const u=c.element,h=u.closest("select");null!==h&&(e.mouseover?h.addEventListener("click",(()=>u.selected=!0),{once:!0}):u.selected=!0)}return!0}function $s(e,t,n){const s=t[0];if(1!==t.length||"TEXTAREA"!==s.tagName&&"text"!==s.type)return!1;if(e.typing){let e=0;const t=function(r){r.preventDefault(),"Backspace"===r.key||e>=n.response.length?s.removeEventListener("keydown",t):s.value=n.response.slice(0,++e)};s.addEventListener("keydown",t)}else s.value=n.response;return!0}function Ts(e,t,n){const s=t[0];if(!s.classList.contains("qtype_essay_editor"))return!1;const r=s.querySelector("iframe");if(!(r&&r.contentDocument&&r.contentDocument.body&&r.contentWindow))return!1;const o=r.contentDocument.body.querySelector("p");if(!o)return!1;if(e.typing){let e=0;const t=function(s){if(s.preventDefault(),"Backspace"===s.key||e>=n.response.length)return void r.contentWindow.removeEventListener("keydown",t);const i=document.createTextNode(n.response.charAt(e++));o.appendChild(i);const a=r.contentDocument.createRange();a.selectNodeContents(o),a.collapse(!1);const l=r.contentWindow.getSelection();l&&(l.removeAllRanges(),l.addRange(a)),r.contentWindow.focus()};r.contentWindow.addEventListener("keydown",t)}else o.textContent+=n.response;return!0}function js(e){return t(this,void 0,void 0,(function*(){e.config.cursor&&(e.questionElement.style.cursor="wait");const n=function(e){let t=e.innerText;const n=e.querySelectorAll(".accesshide");for(const e of n)t=t.replace(e.innerText,"");const s=e.querySelector(".qtype_essay_editor");s&&(t=t.replace(s.innerText,""));const r=e.querySelectorAll(".qtext table");for(const e of r)t=t.replace(e.innerText,"\n"+Es(e)+"\n");return o(t,!1)}(e.form),s=e.form.querySelectorAll(e.inputQuery),i=yield function(e,n,s){return t(this,void 0,void 0,(function*(){var t;const r=new AbortController,i=setTimeout((()=>r.abort()),2e4),a=yield l(e,n,s),c=new As({apiKey:e.apiKey,dangerouslyAllowBrowser:!0}),u=yield c.chat.completions.create(function(e,t){if(!e.startsWith("o1"))return t;t.max_tokens&&(t.max_completion_tokens=t.max_tokens,delete t.max_tokens),t.temperature&&delete t.temperature,t.top_p&&delete t.top_p;for(const e of t.messages)"system"===e.role&&(e.role="user");return t}(e.model,{model:e.model,messages:a.messages,temperature:.1,top_p:.6,presence_penalty:0,max_tokens:2e3}),{signal:e.timeout?r.signal:null});clearTimeout(i);const h=null!==(t=u.choices[0].message.content)&&void 0!==t?t:"";return"function"==typeof a.saveResponse&&a.saveResponse(h),{question:s,response:h,normalizedResponse:o(h)}}))}(e.config,e.questionElement,n).catch((e=>({error:e}))),a="object"==typeof i&&"error"in i;if(e.config.cursor&&(e.questionElement.style.cursor=e.config.infinite||a?"pointer":"initial"),a)console.error(i.error);else switch(e.config.logs&&(r.question(n),r.response(i)),e.config.mode){case"clipboard":!function(e){e.config.infinite||e.removeListener(),Rs(e.config,e.gptAnswer)}({config:e.config,questionElement:e.questionElement,gptAnswer:i,removeListener:e.removeListener});break;case"question-to-answer":!function(e){var t;const n=e.questionElement;e.removeListener();const s=null!==(t=n.innerHTML)&&void 0!==t?t:"";n.innerHTML=e.gptAnswer.response,n.style.whiteSpace="pre-wrap",n.addEventListener("click",(function(){const t=n.innerHTML===e.gptAnswer.response;n.style.whiteSpace=t?"initial":"pre-wrap",n.innerHTML=t?s:e.gptAnswer.response}))}({gptAnswer:i,questionElement:e.questionElement,removeListener:e.removeListener});break;case"autocomplete":!function(e){e.config.infinite||e.removeListener();const t=[Ts,ks,$s,Ps,Os,Cs,Is];for(const n of t)if(n(e.config,e.inputList,e.gptAnswer))return;Rs(e.config,e.gptAnswer)}({config:e.config,gptAnswer:i,inputList:s,questionElement:e.questionElement,removeListener:e.removeListener})}}))}Ss=As,As.OpenAI=Ss,As.DEFAULT_TIMEOUT=6e5,As.OpenAIError=M,As.APIError=L,As.APIConnectionError=B,As.APIConnectionTimeoutError=F,As.APIUserAbortError=D,As.NotFoundError=H,As.ConflictError=J,As.RateLimitError=K,As.BadRequestError=W,As.AuthenticationError=U,As.InternalServerError=z,As.PermissionDeniedError=X,As.UnprocessableEntityError=V,As.toFile=ie,As.fileFromPath=T,As.Completions=as,As.Chat=Ke,As.Embeddings=ls,As.Files=cs,As.FileObjectsPage=us,As.Images=ys,As.Audio=Ye,As.Moderations=_s,As.Models=ws,As.ModelsPage=bs,As.FineTuning=gs,As.Beta=is,As.Batches=Ze,As.BatchesPage=et,As.Uploads=xs;const qs=[],Ns=[];function Ms(e){const t=Ns.findIndex((t=>t.element===e));if(-1!==t){const e=Ns.splice(t,1)[0];e.element.removeEventListener("click",e.fn)}}function Ls(t){if(Ns.length>0){for(const e of Ns)t.cursor&&(e.element.style.cursor="initial"),e.element.removeEventListener("click",e.fn);return t.title&&e("Removed"),void(Ns.length=0)}const n=["checkbox","radio","text","number"].map((e=>`input[type="${e}"]`)).join(",")+", textarea, select, [contenteditable], .qtype_essay_editor",s=document.querySelectorAll(".formulation");for(const e of s){const s=e.querySelector(".qtext");if(null===s)continue;t.cursor&&(s.style.cursor="pointer");const r=js.bind(null,{config:t,questionElement:s,form:e,inputQuery:n,removeListener:()=>Ms(s)});Ns.push({element:s,fn:r}),s.addEventListener("click",r)}t.title&&e("Injected")}chrome.storage.sync.get(["moodleGPT"]).then((function(e){const t=e.moodleGPT;if(!t)throw new Error("Please configure MoodleGPT into the extension");t.code?function(e){document.body.addEventListener("keydown",(function(t){qs.push(t.key),qs.length>e.code.length&&qs.shift(),qs.join("")===e.code&&(qs.length=0,Ls(e))}))}(t):Ls(t)}))})); //# sourceMappingURL=MoodleGPT.js.map diff --git a/extension/MoodleGPT.js.map b/extension/MoodleGPT.js.map index 76f0a5a..940914e 100644 --- a/extension/MoodleGPT.js.map +++ b/extension/MoodleGPT.js.map @@ -1 +1 @@ -{"version":3,"file":"MoodleGPT.js","sources":["../src/utils/title-indications.ts","../node_modules/tslib/tslib.es6.js","../src/utils/pick-best-response.ts","../src/utils/logs.ts","../src/utils/normalize-text.ts","../src/types/message.ts","../src/core/get-content-with-history.ts","../src/utils/version-support-images.ts","../src/utils/image-to-base64.ts","../src/utils/html-table-to-string.ts","../src/core/questions/clipboard.ts","../src/core/questions/contenteditable.ts","../src/core/questions/number.ts","../src/core/questions/radio.ts","../src/core/questions/checkbox.ts","../src/core/questions/select.ts","../src/core/questions/textbox.ts","../src/core/questions/atto.ts","../src/core/reply.ts","../src/core/create-question.ts","../src/core/get-response.ts","../src/core/modes/clipboard.ts","../src/core/modes/question-to-answer.ts","../src/core/modes/autocomplete.ts","../src/core/code-listener.ts","../src/index.ts"],"sourcesContent":["/**\r\n * Show some informations into the document title and remove it after 3000ms\r\n * @param text\r\n */\r\nfunction titleIndications(text: string) {\r\n const backTitle = document.title;\r\n document.title = text;\r\n setTimeout(() => (document.title = backTitle), 3000);\r\n}\r\n\r\nexport default titleIndications;\r\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n};\r\n","type BestResponse = {\r\n similarity: number;\r\n value: string | null;\r\n element: HTMLElement | null;\r\n};\r\n\r\ntype ResponsesBySimilarity = {\r\n similarity: number;\r\n value: string;\r\n element: HTMLElement;\r\n};\r\n\r\n/**\r\n * Calculate the levenshtein distance between two sentence\r\n * @param str1\r\n * @param str2\r\n * @returns\r\n */\r\nfunction levenshteinDistance(str1: string, str2: string) {\r\n if (str1.length === 0) return str2.length;\r\n if (str2.length === 0) return str1.length;\r\n\r\n const matrix: number[][] = [];\r\n const str1WithoutSpaces = str1.replace(/\\s+/, '');\r\n const str2WithoutSpaces = str2.replace(/\\s+/, '');\r\n\r\n for (let i = 0; i <= str1WithoutSpaces.length; ++i) {\r\n matrix.push([i]);\r\n for (let j = 1; j <= str2WithoutSpaces.length; ++j) {\r\n matrix[i][j] =\r\n i === 0\r\n ? j\r\n : Math.min(\r\n matrix[i - 1][j] + 1,\r\n matrix[i][j - 1] + 1,\r\n matrix[i - 1][j - 1] + (str1WithoutSpaces[i - 1] === str2WithoutSpaces[j - 1] ? 0 : 1)\r\n );\r\n }\r\n }\r\n\r\n return matrix[str1WithoutSpaces.length][str2WithoutSpaces.length];\r\n}\r\n\r\n/**\r\n * Calculate the similarity between two sentences from 0 to 1 (best)\r\n * @param str1\r\n * @param str2\r\n * @returns\r\n */\r\nfunction sentenceSimilarity(str1: string, str2: string) {\r\n const longerLength = str1.length > str2.length ? str1.length : str2.length;\r\n if (longerLength === 0) return 1;\r\n return (longerLength - levenshteinDistance(str1, str2)) / longerLength;\r\n}\r\n\r\n/**\r\n * Pick the best sentence that correspond to the answer\r\n * @param arr\r\n * @param answer\r\n * @returns\r\n */\r\nexport function pickBestReponse(\r\n answer: string,\r\n arr: { element: HTMLElement; value: string }[]\r\n): BestResponse {\r\n let bestResponse: BestResponse = {\r\n element: null,\r\n similarity: 0,\r\n value: null\r\n };\r\n for (const obj of arr) {\r\n const similarity = sentenceSimilarity(obj.value, answer);\r\n if (similarity === 1) {\r\n return { element: obj.element, value: obj.value, similarity };\r\n }\r\n if (similarity > bestResponse.similarity) {\r\n bestResponse = { element: obj.element, value: obj.value, similarity };\r\n }\r\n }\r\n return bestResponse;\r\n}\r\n\r\n/**\r\n * Return the sentences sorted by score with a score superior or equal to what is asked\r\n * @param answer\r\n * @param arr\r\n * @param score\r\n * @returns\r\n */\r\nexport function pickResponsesWithSimilarityGreaterThan(\r\n answer: string,\r\n arr: { element: HTMLElement; value: string }[],\r\n score: number\r\n): ResponsesBySimilarity[] {\r\n const responses: ResponsesBySimilarity[] = [];\r\n for (const obj of arr) {\r\n const similarity = sentenceSimilarity(obj.value, answer);\r\n if (similarity >= score)\r\n responses.push({\r\n similarity,\r\n value: obj.value,\r\n element: obj.element\r\n });\r\n }\r\n return responses.sort((a, b) => a.similarity - b.similarity);\r\n}\r\n\r\n/**\r\n * Convert a number to a readable string pourcentage\r\n * @param similarity\r\n */\r\nexport function toPourcentage(similarity: number): string {\r\n return Math.round(similarity * 100 * 100) / 100 + '%';\r\n}\r\n","import GPTAnswer from '@typing/gpt-answer';\r\nimport { toPourcentage } from './pick-best-response';\r\n\r\nclass Logs {\r\n static question(text: string) {\r\n const css = 'color: cyan';\r\n console.log('%c[QUESTION]: %s', css, text);\r\n }\r\n\r\n static bestAnswer(answer: string, similarity: number) {\r\n const css = 'color: green';\r\n console.log(\r\n '%c[BEST ANSWER]: %s',\r\n css,\r\n `\"${answer}\" with a similarity of ${toPourcentage(similarity)}`\r\n );\r\n }\r\n\r\n static array(arr: unknown[]) {\r\n console.log('[CORRECTS] ', arr);\r\n }\r\n\r\n static response(gptAnswer: GPTAnswer) {\r\n console.log('Original:\\n' + gptAnswer.response);\r\n console.log('Normalized:\\n' + gptAnswer.normalizedResponse);\r\n }\r\n}\r\n\r\nexport default Logs;\r\n","/**\r\n * Normlize text\r\n * @param text\r\n */\r\nfunction normalizeText(text: string, toLowerCase: boolean = true) {\r\n if (toLowerCase) text = text.toLowerCase();\r\n\r\n const normalizedText = text\r\n .replace(/\\n+/gi, '\\n') //remove duplicate new lines\r\n .replace(/(\\n\\s*\\n)+/g, '\\n') //remove useless white space from textcontent\r\n .replace(/[ \\t]+/gi, ' ') //replace multiples space or tabs by a space\r\n .trim()\r\n // We remove the following content because sometimes ChatGPT will reply: \"answer d\"\r\n .replace(/^[a-z\\d]\\.\\s/gi, '') //a. text, b. text, c. text, 1. text, 2. text, 3.text\r\n .replace(/\\n[a-z\\d]\\.\\s/gi, '\\n'); //same but with new line\r\n\r\n return normalizedText;\r\n}\r\n\r\nexport default normalizeText;\r\n","export enum ROLE {\r\n SYSTEM = 'system',\r\n USER = 'user',\r\n ASSISTANT = 'assistant'\r\n}\r\n\r\nexport enum CONTENT_TYPE {\r\n TEXT = 'text',\r\n IMAGE = 'image_url'\r\n}\r\n\r\nexport type MessageContent =\r\n | string\r\n | Array<\r\n | {\r\n type: CONTENT_TYPE.TEXT;\r\n text: string;\r\n }\r\n | {\r\n type: CONTENT_TYPE.IMAGE;\r\n image_url: { url: string };\r\n }\r\n >;\r\n\r\nexport type Message = {\r\n role: ROLE;\r\n content: MessageContent;\r\n};\r\n","import type Config from '@typing/config';\r\nimport { ROLE, CONTENT_TYPE, type MessageContent, type Message } from '@typing/message';\r\nimport imageToBase64 from '@utils/image-to-base64';\r\nimport isGPTModelGreaterOrEqualTo4 from '@utils/version-support-images';\r\n\r\n// The attempt and the cmid allow us to identify a quiz\r\ntype History = {\r\n host: string;\r\n cmid: string; // The id of the quiz\r\n attempt: string; // The attempt of the current quiz\r\n history: { role: ROLE; content: MessageContent }[];\r\n};\r\n\r\nconst INSTRUCTION: string = `\r\nAct as a quiz solver for the best notation with the following rules:\r\n- If no answer(s) are given, answer the statement as usual without following the other rules, providing the most detailed, complete and precise explanation. \r\n- But for the calculation provide this format 'result: '\r\n- For 'put in order' questions, maintain the answer in the order as presented in the question but assocy the correct order to it by usin this format ':\\n:', ignore other rules.\r\n- Always reply in the format: '\\n\\n...'.\r\n- Retain only the correct answer(s).\r\n- Maintain the same order for the answers as in the text.\r\n- Retain all text from the answer with its description, content or definition.\r\n- Only provide answers that exactly match the given answer in the text.\r\n- The question always has the correct answer(s), so you should always provide an answer.\r\n- Always respond in the same language as the user's question.\r\n`.trim();\r\n\r\nconst SYSTEM_INSTRUCTION_MESSAGE = {\r\n role: ROLE.SYSTEM,\r\n content: INSTRUCTION\r\n} as const satisfies Message;\r\n\r\n/**\r\n * Get the content to send to ChatGPT API (it allows to includes images if supported)\r\n * @param config\r\n */\r\nasync function getContent(\r\n config: Config,\r\n questionElement: HTMLElement,\r\n question: string\r\n): Promise {\r\n const imagesElements = questionElement.querySelectorAll('img');\r\n\r\n if (\r\n !config.includeImages ||\r\n !isGPTModelGreaterOrEqualTo4(config.model) ||\r\n imagesElements.length === 0\r\n ) {\r\n return question;\r\n }\r\n\r\n const contentWithImages: MessageContent = [];\r\n\r\n const base64Images = Array.from(imagesElements).map(imgEl => imageToBase64(imgEl));\r\n const base64ImagesResolved = await Promise.allSettled(base64Images);\r\n\r\n for (const result of base64ImagesResolved) {\r\n if (result.status === 'fulfilled') {\r\n contentWithImages.push({\r\n type: CONTENT_TYPE.IMAGE,\r\n image_url: { url: result.value }\r\n });\r\n } else if (config.logs) {\r\n console.error(result.reason);\r\n }\r\n }\r\n\r\n contentWithImages.push({\r\n type: CONTENT_TYPE.TEXT,\r\n text: question\r\n });\r\n\r\n return contentWithImages;\r\n}\r\n\r\n/**\r\n * Create a new history object from the current page\r\n * @returns\r\n */\r\nfunction createNewHistory(): History {\r\n const urlParams = new URLSearchParams(document.location.search);\r\n\r\n return {\r\n host: document.location.host,\r\n cmid: urlParams.get('cmid') ?? '',\r\n attempt: urlParams.get('attempt') ?? '',\r\n history: []\r\n };\r\n}\r\n\r\n/**\r\n * Load the past history from the session storage otherwise return the default history object\r\n * @returns\r\n */\r\nfunction loadPastHistory(): History | null {\r\n return JSON.parse(sessionStorage.moodleGPTHistory ?? 'null');\r\n}\r\n\r\n/**\r\n * Check if two history are from the same origin\r\n * @param a\r\n * @param b\r\n * @returns\r\n */\r\nfunction areHistoryFromSameQuiz(a: History, b: History): boolean {\r\n const KEYS_TO_COMPARE: (keyof History)[] = ['host', 'cmid', 'attempt'];\r\n\r\n for (const key of KEYS_TO_COMPARE) {\r\n if (a[key] !== b[key]) return false;\r\n }\r\n\r\n return true;\r\n}\r\n\r\n/**\r\n * Return the content to send to chatgpt api with history if needed\r\n * @param config\r\n * @param questionElement\r\n * @param question\r\n * @returns\r\n */\r\nasync function getContentWithHistory(\r\n config: Config,\r\n questionElement: HTMLElement,\r\n question: string\r\n): Promise<{\r\n messages: [typeof SYSTEM_INSTRUCTION_MESSAGE, ...Message[]];\r\n saveResponse?: (response: string) => void;\r\n}> {\r\n const content = await getContent(config, questionElement, question);\r\n const message = { role: ROLE.USER, content };\r\n\r\n if (!config.history) return { messages: [SYSTEM_INSTRUCTION_MESSAGE, message] };\r\n\r\n let history: History;\r\n\r\n const pastHistory: History | null = loadPastHistory();\r\n const newHistory: History = createNewHistory();\r\n\r\n if (pastHistory === null || !areHistoryFromSameQuiz(pastHistory, newHistory)) {\r\n history = newHistory;\r\n } else {\r\n history = pastHistory;\r\n }\r\n\r\n return {\r\n messages: [SYSTEM_INSTRUCTION_MESSAGE, ...history.history, message],\r\n saveResponse(response: string) {\r\n // Register the conversation\r\n if (config.history) {\r\n history.history.push(message);\r\n history.history.push({ role: ROLE.ASSISTANT, content: response });\r\n sessionStorage.moodleGPTHistory = JSON.stringify(history);\r\n }\r\n }\r\n };\r\n}\r\n\r\nexport default getContentWithHistory;\r\n","/**\r\n * Check if the current ChatGPT version is greater or equal to 4\r\n * @param version\r\n * @returns\r\n */\r\nfunction isGPTModelGreaterOrEqualTo4(version: string): boolean {\r\n const versionNumber = version.match(/gpt-(\\d+)/);\r\n if (!versionNumber?.[1]) {\r\n return false;\r\n }\r\n return Number(versionNumber[1]) >= 4;\r\n}\r\n\r\nexport default isGPTModelGreaterOrEqualTo4;\r\n","/**\r\n * Convert an image html element into a base64 image string\r\n * @param imageElement\r\n * @param quality (default: 0.75 -> 75%)\r\n * @returns\r\n */\r\nfunction imageToBase64(imageElement: HTMLImageElement, quality = 0.75): Promise {\r\n return new Promise((resolve, reject) => {\r\n const canvas = document.createElement('canvas');\r\n const ctx = canvas.getContext('2d');\r\n\r\n if (!ctx) {\r\n reject(\"Can't get the canvas context, ensure your navigator support canvas\");\r\n canvas.remove();\r\n return;\r\n }\r\n\r\n const img = new Image();\r\n img.crossOrigin = 'Anonymous';\r\n img.onload = () => {\r\n canvas.width = img.width;\r\n canvas.height = img.height;\r\n ctx.drawImage(img, 0, 0);\r\n\r\n const base64 = canvas.toDataURL('image/png', quality);\r\n resolve(base64);\r\n\r\n canvas.remove();\r\n };\r\n\r\n img.onerror = err => {\r\n reject(err);\r\n canvas.remove();\r\n };\r\n\r\n img.src = imageElement.src;\r\n });\r\n}\r\n\r\nexport default imageToBase64;\r\n","/**\r\n * Convert table to representating string table\r\n * @param table\r\n * @returns\r\n */\r\nfunction htmlTableToString(table: HTMLTableElement) {\r\n const tab: string[][] = [];\r\n const lines = Array.from(table.querySelectorAll('tr'));\r\n const maxColumnsLength: number[] = [];\r\n\r\n lines.map(line => {\r\n const cells = Array.from(line.querySelectorAll('td, th'));\r\n const cellsContent = cells.map((cell, index) => {\r\n const content = cell.textContent?.trim();\r\n maxColumnsLength[index] = Math.max(maxColumnsLength[index] || 0, content?.length || 0);\r\n return content ?? '';\r\n });\r\n tab.push(cellsContent);\r\n });\r\n\r\n const jointure = ' | ';\r\n const headerLineLength = tab[0].length;\r\n const lineSeparationSize =\r\n maxColumnsLength.reduce((a, b) => a + b, 0) + (headerLineLength - 1) * jointure.length;\r\n const lineSeparation = '\\n' + Array(lineSeparationSize).fill('-').join('') + '\\n';\r\n\r\n const mappedTab = tab.map(line => {\r\n const mappedLine = line.map((content, index) =>\r\n content.padEnd(\r\n maxColumnsLength[index],\r\n '\\u00A0' // For no matching with \\s\r\n )\r\n );\r\n return mappedLine.join(jointure);\r\n });\r\n\r\n const head = mappedTab.shift();\r\n\r\n return head + lineSeparation + mappedTab.join('\\n');\r\n}\r\n\r\nexport default htmlTableToString;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\nimport titleIndications from '@utils/title-indications';\r\n\r\n/**\r\n * Copy the response in the clipboard if we can automaticaly fill the question\r\n * @param config\r\n * @param gptAnswer\r\n */\r\nfunction handleClipboard(config: Config, gptAnswer: GPTAnswer) {\r\n if (config.title) titleIndications('Copied to clipboard');\r\n navigator.clipboard.writeText(gptAnswer.response);\r\n}\r\n\r\nexport default handleClipboard;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\n\r\nfunction isContentEditable(element: HTMLElement) {\r\n const contenteditable = element.getAttribute('contenteditable');\r\n return typeof contenteditable === 'string' && contenteditable !== 'false';\r\n}\r\n\r\n/**\r\n * Hanlde contenteditable elements\r\n * @param config\r\n * @param inputList\r\n * @param gptAnswer\r\n * @returns\r\n */\r\nfunction handleContentEditable(\r\n config: Config,\r\n inputList: NodeListOf,\r\n gptAnswer: GPTAnswer\r\n): boolean {\r\n const input = inputList[0];\r\n\r\n if (\r\n inputList.length !== 1 || // for now we don't handle many input for editable textcontent\r\n !isContentEditable(input)\r\n ) {\r\n return false;\r\n }\r\n\r\n if (config.typing) {\r\n let index = 0;\r\n\r\n const eventHandler = function (event: KeyboardEvent) {\r\n event.preventDefault();\r\n\r\n if (event.key === 'Backspace' || index >= gptAnswer.response.length) {\r\n input.removeEventListener('keydown', eventHandler);\r\n return;\r\n }\r\n\r\n input.textContent = gptAnswer.response.slice(0, ++index);\r\n\r\n // Put the cursor at the end of the typed text\r\n input.focus();\r\n const range = document.createRange();\r\n range.selectNodeContents(input);\r\n range.collapse(false);\r\n const selection = window.getSelection();\r\n if (selection !== null) {\r\n selection.removeAllRanges();\r\n selection.addRange(range);\r\n }\r\n };\r\n\r\n input.addEventListener('keydown', eventHandler);\r\n } else {\r\n input.textContent = gptAnswer.response;\r\n }\r\n\r\n return true;\r\n}\r\n\r\nexport default handleContentEditable;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\n\r\n/**\r\n * Handle number input\r\n * @param config\r\n * @param inputList\r\n * @param gptAnswer\r\n * @returns\r\n */\r\nfunction handleNumber(\r\n config: Config,\r\n inputList: NodeListOf,\r\n gptAnswer: GPTAnswer\r\n): boolean {\r\n const input = inputList[0] as HTMLInputElement | HTMLTextAreaElement;\r\n\r\n if (\r\n inputList.length !== 1 || // for now we don't handle many input number\r\n input.type !== 'number'\r\n ) {\r\n return false;\r\n }\r\n\r\n const number = gptAnswer.normalizedResponse.match(/\\d+([,.]\\d+)?/gi)?.[0]?.replace(',', '.');\r\n\r\n if (number === undefined) return false;\r\n\r\n if (config.typing) {\r\n let index = 0;\r\n\r\n const eventHanlder = function (event: Event) {\r\n event.preventDefault();\r\n if ((event).key === 'Backspace' || index >= number.length) {\r\n input.removeEventListener('keydown', eventHanlder);\r\n return;\r\n }\r\n\r\n if (number.slice(index, index + 1) === '.') ++index;\r\n\r\n input.value = number.slice(0, ++index);\r\n };\r\n\r\n input.addEventListener('keydown', eventHanlder);\r\n } else {\r\n input.value = number;\r\n }\r\n\r\n return true;\r\n}\r\n\r\nexport default handleNumber;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\nimport Logs from '@utils/logs';\r\nimport normalizeText from '@utils/normalize-text';\r\nimport { pickBestReponse } from '@utils/pick-best-response';\r\n\r\n/**\r\n * Handle input radio elements\r\n * @param config\r\n * @param inputList\r\n * @param gptAnswer\r\n */\r\nfunction handleRadio(\r\n config: Config,\r\n inputList: NodeListOf,\r\n gptAnswer: GPTAnswer\r\n): boolean {\r\n const firstInput = inputList?.[0] as HTMLInputElement;\r\n\r\n // Handle the case the input is not a radio\r\n if (!firstInput || firstInput.type !== 'radio') {\r\n return false;\r\n }\r\n\r\n const possibleAnswers = Array.from(inputList)\r\n .map(inp => ({\r\n element: inp,\r\n value: normalizeText(inp?.parentElement?.textContent ?? '')\r\n }))\r\n .filter(obj => obj.value !== '');\r\n\r\n const bestAnswer = pickBestReponse(gptAnswer.normalizedResponse, possibleAnswers);\r\n\r\n if (config.logs && bestAnswer.value) {\r\n Logs.bestAnswer(bestAnswer.value, bestAnswer.similarity);\r\n }\r\n\r\n const correctInput = bestAnswer.element as HTMLInputElement;\r\n if (config.mouseover) {\r\n correctInput.addEventListener('mouseover', () => correctInput.click(), {\r\n once: true\r\n });\r\n } else {\r\n correctInput.click();\r\n }\r\n\r\n return true;\r\n}\r\n\r\nexport default handleRadio;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\nimport Logs from '@utils/logs';\r\nimport normalizeText from '@utils/normalize-text';\r\nimport { pickBestReponse } from '@utils/pick-best-response';\r\n\r\n/**\r\n * Handle input checkbox elements\r\n * @param config\r\n * @param inputList\r\n * @param gptAnswer\r\n */\r\nfunction handleCheckbox(\r\n config: Config,\r\n inputList: NodeListOf,\r\n gptAnswer: GPTAnswer\r\n): boolean {\r\n const firstInput = inputList?.[0] as HTMLInputElement;\r\n\r\n // Handle the case the input is not a checkbox\r\n if (!firstInput || firstInput.type !== 'checkbox') {\r\n return false;\r\n }\r\n\r\n const corrects = gptAnswer.normalizedResponse.split('\\n');\r\n\r\n const possibleAnswers = Array.from(inputList)\r\n .map(inp => ({\r\n element: inp as HTMLInputElement,\r\n value: normalizeText(inp?.parentElement?.textContent ?? '')\r\n }))\r\n .filter(obj => obj.value !== '');\r\n\r\n // Find the best answers elements\r\n const correctElements: Set = new Set();\r\n for (const correct of corrects) {\r\n const bestAnswer = pickBestReponse(correct, possibleAnswers);\r\n\r\n if (config.logs && bestAnswer.value) {\r\n Logs.bestAnswer(bestAnswer.value, bestAnswer.similarity);\r\n }\r\n\r\n correctElements.add(bestAnswer.element as HTMLInputElement);\r\n }\r\n\r\n // Check if it should be checked or not\r\n for (const element of possibleAnswers.map(e => e.element)) {\r\n const needAction =\r\n (element.checked && !correctElements.has(element)) ||\r\n (!element.checked && correctElements.has(element));\r\n\r\n const action = () => needAction && element.click();\r\n\r\n if (config.mouseover) {\r\n element.addEventListener('mouseover', action, {\r\n once: true\r\n });\r\n } else {\r\n action();\r\n }\r\n }\r\n\r\n return true;\r\n}\r\n\r\nexport default handleCheckbox;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\nimport Logs from '@utils/logs';\r\nimport normalizeText from '@utils/normalize-text';\r\nimport { pickBestReponse } from '@utils/pick-best-response';\r\n\r\n/**\r\n * Handle select elements (and put in order select)\r\n * @param config\r\n * @param inputList\r\n * @param gptAnswer\r\n * @returns\r\n */\r\nfunction handleSelect(\r\n config: Config,\r\n inputList: NodeListOf,\r\n gptAnswer: GPTAnswer\r\n): boolean {\r\n if (inputList.length === 0 || inputList[0].tagName !== 'SELECT') return false;\r\n\r\n const corrects = gptAnswer.normalizedResponse.split('\\n');\r\n\r\n if (config.logs) Logs.array(corrects);\r\n\r\n for (let i = 0; i < inputList.length; ++i) {\r\n if (!corrects[i]) break;\r\n\r\n const options = inputList[i].querySelectorAll('option');\r\n\r\n const possibleAnswers = Array.from(options)\r\n .slice(1) // We remove the first option which correspond to \"Choose...\"\r\n .map(opt => ({\r\n element: opt,\r\n value: normalizeText(opt.textContent ?? '')\r\n }))\r\n .filter(obj => obj.value !== '');\r\n\r\n const bestAnswer = pickBestReponse(corrects[i], possibleAnswers);\r\n\r\n if (config.logs && bestAnswer.value) {\r\n Logs.bestAnswer(bestAnswer.value, bestAnswer.similarity);\r\n }\r\n\r\n const correctOption = bestAnswer.element as HTMLOptionElement;\r\n const currentSelect = correctOption.closest('select');\r\n\r\n if (currentSelect === null) continue;\r\n\r\n if (config.mouseover) {\r\n currentSelect.addEventListener('click', () => (correctOption.selected = true), {\r\n once: true\r\n });\r\n } else {\r\n correctOption.selected = true;\r\n }\r\n }\r\n\r\n return true;\r\n}\r\n\r\nexport default handleSelect;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\n\r\n/**\r\n * Handle textbox\r\n * @param config\r\n * @param inputList\r\n * @param gptAnswer\r\n * @returns\r\n */\r\nfunction handleTextbox(\r\n config: Config,\r\n inputList: NodeListOf,\r\n gptAnswer: GPTAnswer\r\n): boolean {\r\n const input = inputList[0] as HTMLInputElement | HTMLTextAreaElement;\r\n\r\n if (\r\n inputList.length !== 1 || // for now we don't handle many input text\r\n (input.tagName !== 'TEXTAREA' && input.type !== 'text')\r\n ) {\r\n return false;\r\n }\r\n\r\n if (config.typing) {\r\n let index = 0;\r\n\r\n const eventHandler = function (event: Event) {\r\n event.preventDefault();\r\n\r\n if ((event).key === 'Backspace' || index >= gptAnswer.response.length) {\r\n input.removeEventListener('keydown', eventHandler);\r\n return;\r\n }\r\n\r\n input.value = gptAnswer.response.slice(0, ++index);\r\n };\r\n\r\n input.addEventListener('keydown', eventHandler);\r\n } else {\r\n input.value = gptAnswer.response;\r\n }\r\n\r\n return true;\r\n}\r\n\r\nexport default handleTextbox;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\n\r\n/**\r\n * Hanlde atto editor\r\n * See: https://docs.moodle.org/404/en/Atto_editor#Atto_accessibility\r\n * @param config\r\n * @param inputList\r\n * @param gptAnswer\r\n * @returns\r\n */\r\nfunction handleAtto(\r\n config: Config,\r\n inputList: NodeListOf,\r\n gptAnswer: GPTAnswer\r\n): boolean {\r\n const input = inputList[0];\r\n\r\n if (!input.classList.contains('qtype_essay_editor')) {\r\n return false;\r\n }\r\n\r\n const iframe = input.querySelector('iframe');\r\n if (!iframe || !iframe.contentDocument || !iframe.contentDocument.body || !iframe.contentWindow) {\r\n return false;\r\n }\r\n const iframeBody = iframe.contentDocument.body;\r\n\r\n const textContainer = iframeBody.querySelector('p');\r\n if (!textContainer) return false;\r\n\r\n if (config.typing) {\r\n let index = 0;\r\n const eventHandler = function (event: KeyboardEvent) {\r\n event.preventDefault();\r\n\r\n if (event.key === 'Backspace' || index >= gptAnswer.response.length) {\r\n iframe.contentWindow!.removeEventListener('keydown', eventHandler);\r\n return;\r\n }\r\n\r\n // Append text one character at a time\r\n const textNode = document.createTextNode(gptAnswer.response.charAt(index++));\r\n textContainer.appendChild(textNode);\r\n\r\n // Move the cursor after the last character\r\n const range = iframe.contentDocument!.createRange();\r\n range.selectNodeContents(textContainer);\r\n range.collapse(false); // Collapse the range to the end point\r\n const selection = iframe.contentWindow!.getSelection();\r\n if (selection) {\r\n selection.removeAllRanges();\r\n selection.addRange(range);\r\n }\r\n\r\n iframe.contentWindow!.focus(); // Focus the iframe window to see cursor\r\n };\r\n\r\n iframe.contentWindow.addEventListener('keydown', eventHandler);\r\n } else {\r\n textContainer.textContent += gptAnswer.response;\r\n }\r\n\r\n return true;\r\n}\r\n\r\nexport default handleAtto;\r\n","import type Config from '@typing/config';\r\nimport Logs from '@utils/logs';\r\nimport getChatGPTResponse from './get-response';\r\nimport createAndNormalizeQuestion from './create-question';\r\nimport clipboardMode from './modes/clipboard';\r\nimport questionToAnswerMode from './modes/question-to-answer';\r\nimport autoCompleteMode from './modes/autocomplete';\r\n\r\ntype Props = {\r\n config: Config;\r\n questionElement: HTMLElement;\r\n form: HTMLElement;\r\n inputQuery: string;\r\n removeListener: () => void;\r\n};\r\n\r\n/**\r\n * Reply to the question\r\n * @param props\r\n * @returns\r\n */\r\nasync function reply(props: Props): Promise {\r\n if (props.config.cursor) props.questionElement.style.cursor = 'wait';\r\n\r\n const question = createAndNormalizeQuestion(props.form);\r\n const inputList: NodeListOf = props.form.querySelectorAll(props.inputQuery);\r\n\r\n const gptAnswer = await getChatGPTResponse(props.config, props.questionElement, question).catch(\r\n error => ({\r\n error\r\n })\r\n );\r\n\r\n const haveError = typeof gptAnswer === 'object' && 'error' in gptAnswer;\r\n\r\n if (props.config.cursor) {\r\n props.questionElement.style.cursor = props.config.infinite || haveError ? 'pointer' : 'initial';\r\n }\r\n\r\n if (haveError) {\r\n console.error(gptAnswer.error);\r\n return;\r\n }\r\n\r\n if (props.config.logs) {\r\n Logs.question(question);\r\n Logs.response(gptAnswer);\r\n }\r\n\r\n switch (props.config.mode) {\r\n case 'clipboard':\r\n clipboardMode({\r\n config: props.config,\r\n questionElement: props.questionElement,\r\n gptAnswer,\r\n removeListener: props.removeListener\r\n });\r\n break;\r\n case 'question-to-answer':\r\n questionToAnswerMode({\r\n gptAnswer,\r\n questionElement: props.questionElement,\r\n removeListener: props.removeListener\r\n });\r\n break;\r\n case 'autocomplete':\r\n autoCompleteMode({\r\n config: props.config,\r\n gptAnswer,\r\n inputList,\r\n questionElement: props.questionElement,\r\n removeListener: props.removeListener\r\n });\r\n break;\r\n }\r\n}\r\n\r\nexport default reply;\r\n","import normalizeText from '@utils/normalize-text';\r\nimport htmlTableToString from '@utils/html-table-to-string';\r\n\r\n/**\r\n * Normalize the question as text and add sub informations\r\n * @param langage\r\n * @param question\r\n * @returns\r\n */\r\nfunction createAndNormalizeQuestion(questionContainer: HTMLElement) {\r\n let question = questionContainer.innerText;\r\n\r\n // We remove unnecessary information\r\n const accesshideElements: NodeListOf =\r\n questionContainer.querySelectorAll('.accesshide');\r\n for (const useless of accesshideElements) {\r\n question = question.replace(useless.innerText, '');\r\n }\r\n const attoText = questionContainer.querySelector('.qtype_essay_editor');\r\n if (attoText) {\r\n question = question.replace((attoText as HTMLElement).innerText, '');\r\n }\r\n\r\n // Make tables more readable for chat-gpt\r\n const tables: NodeListOf = questionContainer.querySelectorAll('.qtext table');\r\n for (const table of tables) {\r\n question = question.replace(table.innerText, '\\n' + htmlTableToString(table) + '\\n');\r\n }\r\n\r\n return normalizeText(question, false);\r\n}\r\n\r\nexport default createAndNormalizeQuestion;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\nimport normalizeText from '@utils/normalize-text';\r\nimport getContentWithHistory from './get-content-with-history';\r\n\r\n/**\r\n * Get the response from chatGPT api\r\n * @param config\r\n * @param question\r\n * @returns\r\n */\r\nasync function getChatGPTResponse(\r\n config: Config,\r\n questionElement: HTMLElement,\r\n question: string\r\n): Promise {\r\n const controller = new AbortController();\r\n const timeoutControler = setTimeout(() => controller.abort(), 20 * 1000);\r\n\r\n // Get the content to send to chatgpt\r\n // Including the instructions to the AI, the images as base64 if needed, the question and the past conversation if history is set to true\r\n const contentHandler = await getContentWithHistory(config, questionElement, question);\r\n\r\n const req = await fetch('https://api.openai.com/v1/chat/completions', {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n Authorization: `Bearer ${config.apiKey}`\r\n },\r\n signal: config.timeout ? controller.signal : null,\r\n body: JSON.stringify({\r\n model: config.model,\r\n messages: contentHandler.messages,\r\n\r\n temperature: 0.1, // Controls the randomness of the generated responses, with lower values producing more deterministic and predictable outputs. With set to 0.1 instead of 0 for more creativity.\r\n top_p: 0.6, // Determines the diversity of the generated responses\r\n presence_penalty: 0, // Encourages the model to introduce new concepts by penalizing words that have already appeared in the text.\r\n max_tokens: 2000 // Maximum length of the response\r\n })\r\n });\r\n\r\n clearTimeout(timeoutControler);\r\n\r\n const rep = await req.json();\r\n const response = rep.choices[0].message.content;\r\n\r\n // Save the response into the history\r\n if (typeof contentHandler.saveResponse === 'function') contentHandler.saveResponse(response);\r\n\r\n return {\r\n question,\r\n response,\r\n normalizedResponse: normalizeText(response)\r\n };\r\n}\r\n\r\nexport default getChatGPTResponse;\r\n","import type Config from '@typing/config';\r\nimport type GPTAnswer from '@typing/gpt-answer';\r\nimport handleClipboard from '@core/questions/clipboard';\r\n\r\ntype Props = {\r\n config: Config;\r\n questionElement: HTMLElement;\r\n gptAnswer: GPTAnswer;\r\n removeListener: () => void;\r\n};\r\n\r\n/**\r\n * Clipboard mode:\r\n * Simply copy the answer into the clipboard\r\n * @param props\r\n */\r\nfunction clipboardMode(props: Props) {\r\n if (!props.config.infinite) props.removeListener();\r\n handleClipboard(props.config, props.gptAnswer);\r\n}\r\n\r\nexport default clipboardMode;\r\n","import type GPTAnswer from '@typing/gpt-answer';\r\n\r\ntype Props = {\r\n questionElement: HTMLElement;\r\n gptAnswer: GPTAnswer;\r\n removeListener: () => void;\r\n};\r\n\r\n/**\r\n * Question to answer mode:\r\n * Simply turn the question into the answer by clicking on it\r\n * @param props\r\n */\r\nfunction questionToAnswerMode(props: Props) {\r\n const questionElement = props.questionElement;\r\n\r\n props.removeListener();\r\n\r\n const questionBackup = questionElement.innerHTML ?? '';\r\n questionElement.innerHTML = props.gptAnswer.response;\r\n questionElement.style.whiteSpace = 'pre-wrap';\r\n\r\n // To go back to the question / answer\r\n questionElement.addEventListener('click', function () {\r\n const contentIsResponse = questionElement.innerHTML === props.gptAnswer.response;\r\n\r\n questionElement.style.whiteSpace = contentIsResponse ? 'initial' : 'pre-wrap';\r\n questionElement.innerHTML = contentIsResponse ? questionBackup : props.gptAnswer.response;\r\n });\r\n}\r\n\r\nexport default questionToAnswerMode;\r\n","import type GPTAnswer from '@typing/gpt-answer';\r\nimport type Config from '@typing/config';\r\nimport handleClipboard from '@core/questions/clipboard';\r\nimport handleContentEditable from '@core/questions/contenteditable';\r\nimport handleNumber from '@core/questions/number';\r\nimport handleRadio from '@core/questions/radio';\r\nimport handleCheckbox from '@core/questions/checkbox';\r\nimport handleSelect from '@core/questions/select';\r\nimport handleTextbox from '@core/questions/textbox';\r\nimport handleAtto from '@core/questions/atto';\r\n\r\ntype Props = {\r\n config: Config;\r\n questionElement: HTMLElement;\r\n inputList: NodeListOf;\r\n gptAnswer: GPTAnswer;\r\n removeListener: () => void;\r\n};\r\n\r\n/**\r\n * Autocomplete mode:\r\n * Autocomplete the question by checking the good answer\r\n * @param props\r\n * @returns\r\n */\r\nfunction autoCompleteMode(props: Props) {\r\n if (!props.config.infinite) props.removeListener();\r\n\r\n const handlers = [\r\n handleAtto,\r\n handleContentEditable,\r\n handleTextbox,\r\n handleNumber,\r\n handleSelect,\r\n handleRadio,\r\n handleCheckbox\r\n ];\r\n\r\n for (const handler of handlers) {\r\n if (handler(props.config, props.inputList, props.gptAnswer)) return;\r\n }\r\n\r\n // In the case we can't auto complete the question\r\n handleClipboard(props.config, props.gptAnswer);\r\n}\r\n\r\nexport default autoCompleteMode;\r\n","import type Config from '@typing/config';\r\nimport titleIndications from '@utils/title-indications';\r\nimport reply from './reply';\r\n\r\ntype Listener = {\r\n element: HTMLElement;\r\n fn: (this: HTMLElement, ev: MouseEvent) => void;\r\n};\r\n\r\nconst pressedKeys: string[] = [];\r\nconst listeners: Listener[] = [];\r\n\r\n/**\r\n * Create a listener on the keyboard to inject the code\r\n * @param config\r\n */\r\nfunction codeListener(config: Config) {\r\n document.body.addEventListener('keydown', function (event) {\r\n pressedKeys.push(event.key);\r\n if (pressedKeys.length > config.code!.length) pressedKeys.shift();\r\n if (pressedKeys.join('') === config.code) {\r\n pressedKeys.length = 0;\r\n setUpMoodleGpt(config);\r\n }\r\n });\r\n}\r\n\r\n/**\r\n * Remove the event listener on a specific question\r\n * @param element\r\n */\r\nfunction removeListener(element: HTMLElement) {\r\n const index = listeners.findIndex(listener => listener.element === element);\r\n if (index !== -1) {\r\n const listener = listeners.splice(index, 1)[0];\r\n listener.element.removeEventListener('click', listener.fn);\r\n }\r\n}\r\n\r\n/**\r\n * Setup moodleGPT into the page (remove/injection)\r\n * @param config\r\n * @returns\r\n */\r\nfunction setUpMoodleGpt(config: Config) {\r\n // Removing events if there are already declared\r\n if (listeners.length > 0) {\r\n for (const listener of listeners) {\r\n if (config.cursor) listener.element.style.cursor = 'initial';\r\n listener.element.removeEventListener('click', listener.fn);\r\n }\r\n if (config.title) titleIndications('Removed');\r\n listeners.length = 0;\r\n return;\r\n }\r\n\r\n // Query to find inputs and forms\r\n const inputTypeQuery = ['checkbox', 'radio', 'text', 'number']\r\n .map(e => `input[type=\"${e}\"]`)\r\n .join(',');\r\n const inputQuery = inputTypeQuery + ', textarea, select, [contenteditable], .qtype_essay_editor';\r\n const forms = document.querySelectorAll('.formulation');\r\n\r\n // For each form we inject a function on the queqtion\r\n for (const form of forms) {\r\n const questionElement: HTMLElement | null = form.querySelector('.qtext');\r\n\r\n if (questionElement === null) continue;\r\n\r\n if (config.cursor) questionElement.style.cursor = 'pointer';\r\n\r\n const injectionFunction = reply.bind(null, {\r\n config,\r\n questionElement,\r\n form: form as HTMLElement,\r\n inputQuery,\r\n removeListener: () => removeListener(questionElement)\r\n });\r\n\r\n listeners.push({ element: questionElement, fn: injectionFunction });\r\n questionElement.addEventListener('click', injectionFunction);\r\n }\r\n\r\n if (config.title) titleIndications('Injected');\r\n}\r\n\r\nexport { codeListener, removeListener, setUpMoodleGpt };\r\n","import type Config from '@typing/config';\r\nimport { codeListener, setUpMoodleGpt } from './core/code-listener';\r\n\r\nchrome.storage.sync.get(['moodleGPT']).then(function (storage) {\r\n const config: Config = storage.moodleGPT;\r\n\r\n if (!config) throw new Error('Please configure MoodleGPT into the extension');\r\n\r\n if (config.code) {\r\n codeListener(config);\r\n } else {\r\n setUpMoodleGpt(config);\r\n }\r\n});\r\n"],"names":["titleIndications","text","backTitle","document","title","setTimeout","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","sentenceSimilarity","str1","str2","longerLength","length","matrix","str1WithoutSpaces","replace","str2WithoutSpaces","i","push","j","Math","min","levenshteinDistance","pickBestReponse","answer","arr","bestResponse","element","similarity","obj","SuppressedError","Logs","question","console","log","bestAnswer","round","toPourcentage","array","response","gptAnswer","normalizedResponse","normalizeText","toLowerCase","trim","ROLE","CONTENT_TYPE","INSTRUCTION","SYSTEM_INSTRUCTION_MESSAGE","role","SYSTEM","content","getContent","config","questionElement","imagesElements","querySelectorAll","includeImages","version","versionNumber","match","Number","isGPTModelGreaterOrEqualTo4","model","contentWithImages","base64Images","Array","from","map","imgEl","imageElement","quality","canvas","createElement","ctx","getContext","remove","img","Image","crossOrigin","onload","width","height","drawImage","base64","toDataURL","onerror","err","src","imageToBase64","base64ImagesResolved","allSettled","status","type","IMAGE","image_url","url","logs","error","reason","TEXT","getContentWithHistory","message","USER","history","messages","pastHistory","JSON","parse","_a","sessionStorage","moodleGPTHistory","newHistory","urlParams","URLSearchParams","location","search","host","cmid","get","attempt","_b","createNewHistory","a","b","KEYS_TO_COMPARE","key","areHistoryFromSameQuiz","saveResponse","ASSISTANT","stringify","htmlTableToString","table","tab","lines","maxColumnsLength","line","cellsContent","cell","index","textContent","max","headerLineLength","lineSeparationSize","reduce","jointure","lineSeparation","fill","join","mappedTab","padEnd","shift","handleClipboard","navigator","clipboard","writeText","handleContentEditable","inputList","input","contenteditable","getAttribute","isContentEditable","typing","eventHandler","event","preventDefault","removeEventListener","slice","focus","range","createRange","selectNodeContents","collapse","selection","window","getSelection","removeAllRanges","addRange","addEventListener","handleNumber","number","undefined","eventHanlder","handleRadio","firstInput","possibleAnswers","inp","parentElement","filter","correctInput","mouseover","click","once","handleCheckbox","corrects","split","correctElements","Set","correct","add","needAction","checked","has","action","handleSelect","tagName","options","opt","correctOption","currentSelect","closest","selected","handleTextbox","handleAtto","classList","contains","iframe","querySelector","contentDocument","body","contentWindow","textContainer","textNode","createTextNode","charAt","appendChild","reply","props","cursor","style","questionContainer","innerText","accesshideElements","useless","attoText","tables","createAndNormalizeQuestion","form","inputQuery","controller","AbortController","timeoutControler","abort","contentHandler","req","fetch","method","headers","Authorization","apiKey","signal","timeout","temperature","top_p","presence_penalty","max_tokens","clearTimeout","json","choices","getChatGPTResponse","catch","haveError","infinite","mode","removeListener","clipboardMode","questionBackup","innerHTML","whiteSpace","contentIsResponse","questionToAnswerMode","handlers","handler","autoCompleteMode","pressedKeys","listeners","findIndex","listener","splice","fn","setUpMoodleGpt","forms","injectionFunction","bind","chrome","storage","sync","moodleGPT","Error","code","codeListener"],"mappings":"2FAIA,SAASA,EAAiBC,GACxB,MAAMC,EAAYC,SAASC,MAC3BD,SAASC,MAAQH,EACjBI,YAAW,IAAOF,SAASC,MAAQF,GAAY,IACjD,CC0GO,SAASI,EAAUC,EAASC,EAAYC,EAAGC,GAE9C,OAAO,IAAKD,IAAMA,EAAIE,WAAU,SAAUC,EAASC,GAC/C,SAASC,EAAUC,GAAS,IAAMC,EAAKN,EAAUO,KAAKF,GAAQ,CAAG,MAAOG,GAAKL,EAAOK,GAAO,CAC3F,SAASC,EAASJ,GAAS,IAAMC,EAAKN,EAAiB,MAAEK,GAAU,CAAC,MAAOG,GAAKL,EAAOK,GAAO,CAC9F,SAASF,EAAKI,GAJlB,IAAeL,EAIaK,EAAOC,KAAOT,EAAQQ,EAAOL,QAJ1CA,EAIyDK,EAAOL,MAJhDA,aAAiBN,EAAIM,EAAQ,IAAIN,GAAE,SAAUG,GAAWA,EAAQG,EAAO,K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AY9H,KAAK,MAAQ/F,EAAO4O,OAClCf,EAAYtQ,OAAS,EACrB4Q,EAAenO,GAEnB,GACF,CChBI6O,CAAa7O,GAEbmO,EAAenO,EAEnB","x_google_ignoreList":[1]} \ No newline at end of file +{"version":3,"file":"MoodleGPT.js","sources":["../src/background/utils/title-indications.ts","../node_modules/tslib/tslib.es6.js","../src/background/utils/pick-best-response.ts","../src/background/utils/logs.ts","../src/background/utils/normalize-text.ts","../src/background/core/get-content-with-history.ts","../src/background/utils/version-support-images.ts","../src/background/utils/image-to-base64.ts","../node_modules/openai/internal/qs/formats.mjs","../node_modules/openai/internal/qs/utils.mjs","../node_modules/openai/internal/qs/stringify.mjs","../node_modules/openai/version.mjs","../node_modules/openai/_shims/registry.mjs","../node_modules/openai/_shims/MultipartBody.mjs","../node_modules/openai/_shims/index.mjs","../node_modules/openai/_shims/web-runtime.mjs","../node_modules/openai/error.mjs","../node_modules/openai/internal/decoders/line.mjs","../node_modules/openai/streaming.mjs","../node_modules/openai/uploads.mjs","../node_modules/openai/core.mjs","../node_modules/openai/pagination.mjs","../node_modules/openai/resource.mjs","../node_modules/openai/resources/chat/completions.mjs","../node_modules/openai/resources/chat/chat.mjs","../node_modules/openai/resources/audio/speech.mjs","../node_modules/openai/resources/audio/transcriptions.mjs","../node_modules/openai/resources/audio/translations.mjs","../node_modules/openai/resources/audio/audio.mjs","../node_modules/openai/resources/batches.mjs","../node_modules/openai/resources/beta/assistants.mjs","../node_modules/openai/lib/RunnableFunction.mjs","../node_modules/openai/lib/chatCompletionUtils.mjs","../node_modules/openai/lib/EventStream.mjs","../node_modules/openai/lib/parser.mjs","../node_modules/openai/lib/AbstractChatCompletionRunner.mjs","../node_modules/openai/lib/ChatCompletionRunner.mjs","../node_modules/openai/_vendor/partial-json-parser/parser.mjs","../node_modules/openai/lib/ChatCompletionStream.mjs","../node_modules/openai/lib/ChatCompletionStreamingRunner.mjs","../node_modules/openai/resources/beta/chat/completions.mjs","../node_modules/openai/resources/beta/chat/chat.mjs","../node_modules/openai/resources/beta/realtime/sessions.mjs","../node_modules/openai/resources/beta/realtime/realtime.mjs","../node_modules/openai/lib/AssistantStream.mjs","../node_modules/openai/resources/beta/threads/messages.mjs","../node_modules/openai/resources/beta/threads/runs/steps.mjs","../node_modules/openai/resources/beta/threads/runs/runs.mjs","../node_modules/openai/resources/beta/threads/threads.mjs","../node_modules/openai/resources/beta/vector-stores/files.mjs","../node_modules/openai/resources/beta/vector-stores/file-batches.mjs","../node_modules/openai/lib/Util.mjs","../node_modules/openai/resources/beta/vector-stores/vector-stores.mjs","../node_modules/openai/resources/beta/beta.mjs","../node_modules/openai/resources/completions.mjs","../node_modules/openai/resources/embeddings.mjs","../node_modules/openai/resources/files.mjs","../node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs","../node_modules/openai/resources/fine-tuning/jobs/jobs.mjs","../node_modules/openai/resources/fine-tuning/fine-tuning.mjs","../node_modules/openai/resources/images.mjs","../node_modules/openai/resources/models.mjs","../node_modules/openai/resources/moderations.mjs","../node_modules/openai/resources/uploads/parts.mjs","../node_modules/openai/resources/uploads/uploads.mjs","../node_modules/openai/index.mjs","../src/background/utils/html-table-to-string.ts","../src/background/core/questions/clipboard.ts","../src/background/core/questions/contenteditable.ts","../src/background/core/questions/number.ts","../src/background/core/questions/radio.ts","../src/background/core/questions/checkbox.ts","../src/background/core/questions/select.ts","../src/background/core/questions/textbox.ts","../src/background/core/questions/atto.ts","../src/background/core/reply.ts","../src/background/core/create-question.ts","../src/background/core/get-response.ts","../src/background/utils/fixe-o1.ts","../src/background/core/modes/clipboard.ts","../src/background/core/modes/question-to-answer.ts","../src/background/core/modes/autocomplete.ts","../src/background/core/code-listener.ts","../src/background/index.ts"],"sourcesContent":[null,"/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol, Iterator */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === \"function\" ? Iterator : Object).prototype);\r\n return g.next = verb(0), g[\"throw\"] = verb(1), g[\"return\"] = verb(2), typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = Object.create((typeof AsyncIterator === \"function\" ? AsyncIterator : Object).prototype), verb(\"next\"), verb(\"throw\"), verb(\"return\", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }\r\n function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nvar ownKeys = function(o) {\r\n ownKeys = Object.getOwnPropertyNames || function (o) {\r\n var ar = [];\r\n for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;\r\n return ar;\r\n };\r\n return ownKeys(o);\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== \"default\") __createBinding(result, mod, k[i]);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\" && typeof value !== \"function\") throw new TypeError(\"Object expected.\");\r\n var dispose, inner;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n if (async) inner = dispose;\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n var r, s = 0;\r\n function next() {\r\n while (r = env.stack.pop()) {\r\n try {\r\n if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);\r\n if (r.dispose) {\r\n var result = r.dispose.call(r.value);\r\n if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n else s |= 1;\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport function __rewriteRelativeImportExtension(path, preserveJsx) {\r\n if (typeof path === \"string\" && /^\\.\\.?\\//.test(path)) {\r\n return path.replace(/\\.(tsx)$|((?:\\.d)?)((?:\\.[^./]+?)?)\\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {\r\n return tsx ? preserveJsx ? \".jsx\" : \".js\" : d && (!ext || !cm) ? m : (d + ext + \".\" + cm.toLowerCase() + \"js\");\r\n });\r\n }\r\n return path;\r\n}\r\n\r\nexport default {\r\n __extends: __extends,\r\n __assign: __assign,\r\n __rest: __rest,\r\n __decorate: __decorate,\r\n __param: __param,\r\n __esDecorate: __esDecorate,\r\n __runInitializers: __runInitializers,\r\n __propKey: __propKey,\r\n __setFunctionName: __setFunctionName,\r\n __metadata: __metadata,\r\n __awaiter: __awaiter,\r\n __generator: __generator,\r\n __createBinding: __createBinding,\r\n __exportStar: __exportStar,\r\n __values: __values,\r\n __read: __read,\r\n __spread: __spread,\r\n __spreadArrays: __spreadArrays,\r\n __spreadArray: __spreadArray,\r\n __await: __await,\r\n __asyncGenerator: __asyncGenerator,\r\n __asyncDelegator: __asyncDelegator,\r\n __asyncValues: __asyncValues,\r\n __makeTemplateObject: __makeTemplateObject,\r\n __importStar: __importStar,\r\n __importDefault: __importDefault,\r\n __classPrivateFieldGet: __classPrivateFieldGet,\r\n __classPrivateFieldSet: __classPrivateFieldSet,\r\n __classPrivateFieldIn: __classPrivateFieldIn,\r\n __addDisposableResource: __addDisposableResource,\r\n __disposeResources: __disposeResources,\r\n __rewriteRelativeImportExtension: __rewriteRelativeImportExtension,\r\n};\r\n",null,null,null,null,null,null,"export const default_format = 'RFC3986';\nexport const formatters = {\n RFC1738: (v) => String(v).replace(/%20/g, '+'),\n RFC3986: (v) => String(v),\n};\nexport const RFC1738 = 'RFC1738';\nexport const RFC3986 = 'RFC3986';\n//# sourceMappingURL=formats.mjs.map","import { RFC1738 } from \"./formats.mjs\";\nconst has = Object.prototype.hasOwnProperty;\nconst is_array = Array.isArray;\nconst hex_table = (() => {\n const array = [];\n for (let i = 0; i < 256; ++i) {\n array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase());\n }\n return array;\n})();\nfunction compact_queue(queue) {\n while (queue.length > 1) {\n const item = queue.pop();\n if (!item)\n continue;\n const obj = item.obj[item.prop];\n if (is_array(obj)) {\n const compacted = [];\n for (let j = 0; j < obj.length; ++j) {\n if (typeof obj[j] !== 'undefined') {\n compacted.push(obj[j]);\n }\n }\n // @ts-ignore\n item.obj[item.prop] = compacted;\n }\n }\n}\nfunction array_to_object(source, options) {\n const obj = options && options.plainObjects ? Object.create(null) : {};\n for (let i = 0; i < source.length; ++i) {\n if (typeof source[i] !== 'undefined') {\n obj[i] = source[i];\n }\n }\n return obj;\n}\nexport function merge(target, source, options = {}) {\n if (!source) {\n return target;\n }\n if (typeof source !== 'object') {\n if (is_array(target)) {\n target.push(source);\n }\n else if (target && typeof target === 'object') {\n if ((options && (options.plainObjects || options.allowPrototypes)) ||\n !has.call(Object.prototype, source)) {\n target[source] = true;\n }\n }\n else {\n return [target, source];\n }\n return target;\n }\n if (!target || typeof target !== 'object') {\n return [target].concat(source);\n }\n let mergeTarget = target;\n if (is_array(target) && !is_array(source)) {\n // @ts-ignore\n mergeTarget = array_to_object(target, options);\n }\n if (is_array(target) && is_array(source)) {\n source.forEach(function (item, i) {\n if (has.call(target, i)) {\n const targetItem = target[i];\n if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') {\n target[i] = merge(targetItem, item, options);\n }\n else {\n target.push(item);\n }\n }\n else {\n target[i] = item;\n }\n });\n return target;\n }\n return Object.keys(source).reduce(function (acc, key) {\n const value = source[key];\n if (has.call(acc, key)) {\n acc[key] = merge(acc[key], value, options);\n }\n else {\n acc[key] = value;\n }\n return acc;\n }, mergeTarget);\n}\nexport function assign_single_source(target, source) {\n return Object.keys(source).reduce(function (acc, key) {\n acc[key] = source[key];\n return acc;\n }, target);\n}\nexport function decode(str, _, charset) {\n const strWithoutPlus = str.replace(/\\+/g, ' ');\n if (charset === 'iso-8859-1') {\n // unescape never throws, no try...catch needed:\n return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape);\n }\n // utf-8\n try {\n return decodeURIComponent(strWithoutPlus);\n }\n catch (e) {\n return strWithoutPlus;\n }\n}\nconst limit = 1024;\nexport const encode = (str, _defaultEncoder, charset, _kind, format) => {\n // This code was originally written by Brian White for the io.js core querystring library.\n // It has been adapted here for stricter adherence to RFC 3986\n if (str.length === 0) {\n return str;\n }\n let string = str;\n if (typeof str === 'symbol') {\n string = Symbol.prototype.toString.call(str);\n }\n else if (typeof str !== 'string') {\n string = String(str);\n }\n if (charset === 'iso-8859-1') {\n return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) {\n return '%26%23' + parseInt($0.slice(2), 16) + '%3B';\n });\n }\n let out = '';\n for (let j = 0; j < string.length; j += limit) {\n const segment = string.length >= limit ? string.slice(j, j + limit) : string;\n const arr = [];\n for (let i = 0; i < segment.length; ++i) {\n let c = segment.charCodeAt(i);\n if (c === 0x2d || // -\n c === 0x2e || // .\n c === 0x5f || // _\n c === 0x7e || // ~\n (c >= 0x30 && c <= 0x39) || // 0-9\n (c >= 0x41 && c <= 0x5a) || // a-z\n (c >= 0x61 && c <= 0x7a) || // A-Z\n (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( )\n ) {\n arr[arr.length] = segment.charAt(i);\n continue;\n }\n if (c < 0x80) {\n arr[arr.length] = hex_table[c];\n continue;\n }\n if (c < 0x800) {\n arr[arr.length] = hex_table[0xc0 | (c >> 6)] + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n if (c < 0xd800 || c >= 0xe000) {\n arr[arr.length] =\n hex_table[0xe0 | (c >> 12)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)];\n continue;\n }\n i += 1;\n c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff));\n arr[arr.length] =\n hex_table[0xf0 | (c >> 18)] +\n hex_table[0x80 | ((c >> 12) & 0x3f)] +\n hex_table[0x80 | ((c >> 6) & 0x3f)] +\n hex_table[0x80 | (c & 0x3f)];\n }\n out += arr.join('');\n }\n return out;\n};\nexport function compact(value) {\n const queue = [{ obj: { o: value }, prop: 'o' }];\n const refs = [];\n for (let i = 0; i < queue.length; ++i) {\n const item = queue[i];\n // @ts-ignore\n const obj = item.obj[item.prop];\n const keys = Object.keys(obj);\n for (let j = 0; j < keys.length; ++j) {\n const key = keys[j];\n const val = obj[key];\n if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) {\n queue.push({ obj: obj, prop: key });\n refs.push(val);\n }\n }\n }\n compact_queue(queue);\n return value;\n}\nexport function is_regexp(obj) {\n return Object.prototype.toString.call(obj) === '[object RegExp]';\n}\nexport function is_buffer(obj) {\n if (!obj || typeof obj !== 'object') {\n return false;\n }\n return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj));\n}\nexport function combine(a, b) {\n return [].concat(a, b);\n}\nexport function maybe_map(val, fn) {\n if (is_array(val)) {\n const mapped = [];\n for (let i = 0; i < val.length; i += 1) {\n mapped.push(fn(val[i]));\n }\n return mapped;\n }\n return fn(val);\n}\n//# sourceMappingURL=utils.mjs.map","import { encode, is_buffer, maybe_map } from \"./utils.mjs\";\nimport { default_format, formatters } from \"./formats.mjs\";\nconst has = Object.prototype.hasOwnProperty;\nconst array_prefix_generators = {\n brackets(prefix) {\n return String(prefix) + '[]';\n },\n comma: 'comma',\n indices(prefix, key) {\n return String(prefix) + '[' + key + ']';\n },\n repeat(prefix) {\n return String(prefix);\n },\n};\nconst is_array = Array.isArray;\nconst push = Array.prototype.push;\nconst push_to_array = function (arr, value_or_array) {\n push.apply(arr, is_array(value_or_array) ? value_or_array : [value_or_array]);\n};\nconst to_ISO = Date.prototype.toISOString;\nconst defaults = {\n addQueryPrefix: false,\n allowDots: false,\n allowEmptyArrays: false,\n arrayFormat: 'indices',\n charset: 'utf-8',\n charsetSentinel: false,\n delimiter: '&',\n encode: true,\n encodeDotInKeys: false,\n encoder: encode,\n encodeValuesOnly: false,\n format: default_format,\n formatter: formatters[default_format],\n /** @deprecated */\n indices: false,\n serializeDate(date) {\n return to_ISO.call(date);\n },\n skipNulls: false,\n strictNullHandling: false,\n};\nfunction is_non_nullish_primitive(v) {\n return (typeof v === 'string' ||\n typeof v === 'number' ||\n typeof v === 'boolean' ||\n typeof v === 'symbol' ||\n typeof v === 'bigint');\n}\nconst sentinel = {};\nfunction inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) {\n let obj = object;\n let tmp_sc = sideChannel;\n let step = 0;\n let find_flag = false;\n while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) {\n // Where object last appeared in the ref tree\n const pos = tmp_sc.get(object);\n step += 1;\n if (typeof pos !== 'undefined') {\n if (pos === step) {\n throw new RangeError('Cyclic object value');\n }\n else {\n find_flag = true; // Break while\n }\n }\n if (typeof tmp_sc.get(sentinel) === 'undefined') {\n step = 0;\n }\n }\n if (typeof filter === 'function') {\n obj = filter(prefix, obj);\n }\n else if (obj instanceof Date) {\n obj = serializeDate?.(obj);\n }\n else if (generateArrayPrefix === 'comma' && is_array(obj)) {\n obj = maybe_map(obj, function (value) {\n if (value instanceof Date) {\n return serializeDate?.(value);\n }\n return value;\n });\n }\n if (obj === null) {\n if (strictNullHandling) {\n return encoder && !encodeValuesOnly ?\n // @ts-expect-error\n encoder(prefix, defaults.encoder, charset, 'key', format)\n : prefix;\n }\n obj = '';\n }\n if (is_non_nullish_primitive(obj) || is_buffer(obj)) {\n if (encoder) {\n const key_value = encodeValuesOnly ? prefix\n // @ts-expect-error\n : encoder(prefix, defaults.encoder, charset, 'key', format);\n return [\n formatter?.(key_value) +\n '=' +\n // @ts-expect-error\n formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)),\n ];\n }\n return [formatter?.(prefix) + '=' + formatter?.(String(obj))];\n }\n const values = [];\n if (typeof obj === 'undefined') {\n return values;\n }\n let obj_keys;\n if (generateArrayPrefix === 'comma' && is_array(obj)) {\n // we need to join elements in\n if (encodeValuesOnly && encoder) {\n // @ts-expect-error values only\n obj = maybe_map(obj, encoder);\n }\n obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }];\n }\n else if (is_array(filter)) {\n obj_keys = filter;\n }\n else {\n const keys = Object.keys(obj);\n obj_keys = sort ? keys.sort(sort) : keys;\n }\n const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\\./g, '%2E') : String(prefix);\n const adjusted_prefix = commaRoundTrip && is_array(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix;\n if (allowEmptyArrays && is_array(obj) && obj.length === 0) {\n return adjusted_prefix + '[]';\n }\n for (let j = 0; j < obj_keys.length; ++j) {\n const key = obj_keys[j];\n const value = \n // @ts-ignore\n typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key];\n if (skipNulls && value === null) {\n continue;\n }\n // @ts-ignore\n const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\\./g, '%2E') : key;\n const key_prefix = is_array(obj) ?\n typeof generateArrayPrefix === 'function' ?\n generateArrayPrefix(adjusted_prefix, encoded_key)\n : adjusted_prefix\n : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']');\n sideChannel.set(object, step);\n const valueSideChannel = new WeakMap();\n valueSideChannel.set(sentinel, sideChannel);\n push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, \n // @ts-ignore\n generateArrayPrefix === 'comma' && encodeValuesOnly && is_array(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel));\n }\n return values;\n}\nfunction normalize_stringify_options(opts = defaults) {\n if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') {\n throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided');\n }\n if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') {\n throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided');\n }\n if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') {\n throw new TypeError('Encoder has to be a function.');\n }\n const charset = opts.charset || defaults.charset;\n if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') {\n throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined');\n }\n let format = default_format;\n if (typeof opts.format !== 'undefined') {\n if (!has.call(formatters, opts.format)) {\n throw new TypeError('Unknown format option provided.');\n }\n format = opts.format;\n }\n const formatter = formatters[format];\n let filter = defaults.filter;\n if (typeof opts.filter === 'function' || is_array(opts.filter)) {\n filter = opts.filter;\n }\n let arrayFormat;\n if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) {\n arrayFormat = opts.arrayFormat;\n }\n else if ('indices' in opts) {\n arrayFormat = opts.indices ? 'indices' : 'repeat';\n }\n else {\n arrayFormat = defaults.arrayFormat;\n }\n if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') {\n throw new TypeError('`commaRoundTrip` must be a boolean, or absent');\n }\n const allowDots = typeof opts.allowDots === 'undefined' ?\n !!opts.encodeDotInKeys === true ?\n true\n : defaults.allowDots\n : !!opts.allowDots;\n return {\n addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix,\n // @ts-ignore\n allowDots: allowDots,\n allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays,\n arrayFormat: arrayFormat,\n charset: charset,\n charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel,\n commaRoundTrip: !!opts.commaRoundTrip,\n delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter,\n encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode,\n encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys,\n encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder,\n encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly,\n filter: filter,\n format: format,\n formatter: formatter,\n serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate,\n skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls,\n // @ts-ignore\n sort: typeof opts.sort === 'function' ? opts.sort : null,\n strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling,\n };\n}\nexport function stringify(object, opts = {}) {\n let obj = object;\n const options = normalize_stringify_options(opts);\n let obj_keys;\n let filter;\n if (typeof options.filter === 'function') {\n filter = options.filter;\n obj = filter('', obj);\n }\n else if (is_array(options.filter)) {\n filter = options.filter;\n obj_keys = filter;\n }\n const keys = [];\n if (typeof obj !== 'object' || obj === null) {\n return '';\n }\n const generateArrayPrefix = array_prefix_generators[options.arrayFormat];\n const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip;\n if (!obj_keys) {\n obj_keys = Object.keys(obj);\n }\n if (options.sort) {\n obj_keys.sort(options.sort);\n }\n const sideChannel = new WeakMap();\n for (let i = 0; i < obj_keys.length; ++i) {\n const key = obj_keys[i];\n if (options.skipNulls && obj[key] === null) {\n continue;\n }\n push_to_array(keys, inner_stringify(obj[key], key, \n // @ts-expect-error\n generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel));\n }\n const joined = keys.join(options.delimiter);\n let prefix = options.addQueryPrefix === true ? '?' : '';\n if (options.charsetSentinel) {\n if (options.charset === 'iso-8859-1') {\n // encodeURIComponent('✓'), the \"numeric entity\" representation of a checkmark\n prefix += 'utf8=%26%2310003%3B&';\n }\n else {\n // encodeURIComponent('✓')\n prefix += 'utf8=%E2%9C%93&';\n }\n }\n return joined.length > 0 ? prefix + joined : '';\n}\n//# sourceMappingURL=stringify.mjs.map","export const VERSION = '4.78.1'; // x-release-please-version\n//# sourceMappingURL=version.mjs.map","export let auto = false;\nexport let kind = undefined;\nexport let fetch = undefined;\nexport let Request = undefined;\nexport let Response = undefined;\nexport let Headers = undefined;\nexport let FormData = undefined;\nexport let Blob = undefined;\nexport let File = undefined;\nexport let ReadableStream = undefined;\nexport let getMultipartRequestOptions = undefined;\nexport let getDefaultAgent = undefined;\nexport let fileFromPath = undefined;\nexport let isFsReadStream = undefined;\nexport function setShims(shims, options = { auto: false }) {\n if (auto) {\n throw new Error(`you must \\`import 'openai/shims/${shims.kind}'\\` before importing anything else from openai`);\n }\n if (kind) {\n throw new Error(`can't \\`import 'openai/shims/${shims.kind}'\\` after \\`import 'openai/shims/${kind}'\\``);\n }\n auto = options.auto;\n kind = shims.kind;\n fetch = shims.fetch;\n Request = shims.Request;\n Response = shims.Response;\n Headers = shims.Headers;\n FormData = shims.FormData;\n Blob = shims.Blob;\n File = shims.File;\n ReadableStream = shims.ReadableStream;\n getMultipartRequestOptions = shims.getMultipartRequestOptions;\n getDefaultAgent = shims.getDefaultAgent;\n fileFromPath = shims.fileFromPath;\n isFsReadStream = shims.isFsReadStream;\n}\n//# sourceMappingURL=registry.mjs.map","/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nexport class MultipartBody {\n constructor(body) {\n this.body = body;\n }\n get [Symbol.toStringTag]() {\n return 'MultipartBody';\n }\n}\n//# sourceMappingURL=MultipartBody.mjs.map","/**\n * Disclaimer: modules in _shims aren't intended to be imported by SDK users.\n */\nimport * as shims from './registry.mjs';\nimport * as auto from 'openai/_shims/auto/runtime';\nif (!shims.kind) shims.setShims(auto.getRuntime(), { auto: true });\nexport * from './registry.mjs';\n","import { MultipartBody } from \"./MultipartBody.mjs\";\nexport function getRuntime({ manuallyImported } = {}) {\n const recommendation = manuallyImported ?\n `You may need to use polyfills`\n : `Add one of these imports before your first \\`import … from 'openai'\\`:\n- \\`import 'openai/shims/node'\\` (if you're running on Node)\n- \\`import 'openai/shims/web'\\` (otherwise)\n`;\n let _fetch, _Request, _Response, _Headers;\n try {\n // @ts-ignore\n _fetch = fetch;\n // @ts-ignore\n _Request = Request;\n // @ts-ignore\n _Response = Response;\n // @ts-ignore\n _Headers = Headers;\n }\n catch (error) {\n throw new Error(`this environment is missing the following Web Fetch API type: ${error.message}. ${recommendation}`);\n }\n return {\n kind: 'web',\n fetch: _fetch,\n Request: _Request,\n Response: _Response,\n Headers: _Headers,\n FormData: \n // @ts-ignore\n typeof FormData !== 'undefined' ? FormData : (class FormData {\n // @ts-ignore\n constructor() {\n throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${recommendation}`);\n }\n }),\n Blob: typeof Blob !== 'undefined' ? Blob : (class Blob {\n constructor() {\n throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${recommendation}`);\n }\n }),\n File: \n // @ts-ignore\n typeof File !== 'undefined' ? File : (class File {\n // @ts-ignore\n constructor() {\n throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${recommendation}`);\n }\n }),\n ReadableStream: \n // @ts-ignore\n typeof ReadableStream !== 'undefined' ? ReadableStream : (class ReadableStream {\n // @ts-ignore\n constructor() {\n throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${recommendation}`);\n }\n }),\n getMultipartRequestOptions: async (\n // @ts-ignore\n form, opts) => ({\n ...opts,\n body: new MultipartBody(form),\n }),\n getDefaultAgent: (url) => undefined,\n fileFromPath: () => {\n throw new Error('The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads');\n },\n isFsReadStream: (value) => false,\n };\n}\n//# sourceMappingURL=web-runtime.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { castToError } from \"./core.mjs\";\nexport class OpenAIError extends Error {\n}\nexport class APIError extends OpenAIError {\n constructor(status, error, message, headers) {\n super(`${APIError.makeMessage(status, error, message)}`);\n this.status = status;\n this.headers = headers;\n this.request_id = headers?.['x-request-id'];\n this.error = error;\n const data = error;\n this.code = data?.['code'];\n this.param = data?.['param'];\n this.type = data?.['type'];\n }\n static makeMessage(status, error, message) {\n const msg = error?.message ?\n typeof error.message === 'string' ?\n error.message\n : JSON.stringify(error.message)\n : error ? JSON.stringify(error)\n : message;\n if (status && msg) {\n return `${status} ${msg}`;\n }\n if (status) {\n return `${status} status code (no body)`;\n }\n if (msg) {\n return msg;\n }\n return '(no status code or body)';\n }\n static generate(status, errorResponse, message, headers) {\n if (!status || !headers) {\n return new APIConnectionError({ message, cause: castToError(errorResponse) });\n }\n const error = errorResponse?.['error'];\n if (status === 400) {\n return new BadRequestError(status, error, message, headers);\n }\n if (status === 401) {\n return new AuthenticationError(status, error, message, headers);\n }\n if (status === 403) {\n return new PermissionDeniedError(status, error, message, headers);\n }\n if (status === 404) {\n return new NotFoundError(status, error, message, headers);\n }\n if (status === 409) {\n return new ConflictError(status, error, message, headers);\n }\n if (status === 422) {\n return new UnprocessableEntityError(status, error, message, headers);\n }\n if (status === 429) {\n return new RateLimitError(status, error, message, headers);\n }\n if (status >= 500) {\n return new InternalServerError(status, error, message, headers);\n }\n return new APIError(status, error, message, headers);\n }\n}\nexport class APIUserAbortError extends APIError {\n constructor({ message } = {}) {\n super(undefined, undefined, message || 'Request was aborted.', undefined);\n }\n}\nexport class APIConnectionError extends APIError {\n constructor({ message, cause }) {\n super(undefined, undefined, message || 'Connection error.', undefined);\n // in some environments the 'cause' property is already declared\n // @ts-ignore\n if (cause)\n this.cause = cause;\n }\n}\nexport class APIConnectionTimeoutError extends APIConnectionError {\n constructor({ message } = {}) {\n super({ message: message ?? 'Request timed out.' });\n }\n}\nexport class BadRequestError extends APIError {\n}\nexport class AuthenticationError extends APIError {\n}\nexport class PermissionDeniedError extends APIError {\n}\nexport class NotFoundError extends APIError {\n}\nexport class ConflictError extends APIError {\n}\nexport class UnprocessableEntityError extends APIError {\n}\nexport class RateLimitError extends APIError {\n}\nexport class InternalServerError extends APIError {\n}\nexport class LengthFinishReasonError extends OpenAIError {\n constructor() {\n super(`Could not parse response content as the length limit was reached`);\n }\n}\nexport class ContentFilterFinishReasonError extends OpenAIError {\n constructor() {\n super(`Could not parse response content as the request was rejected by the content filter`);\n }\n}\n//# sourceMappingURL=error.mjs.map","import { OpenAIError } from \"../../error.mjs\";\n/**\n * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally\n * reading lines from text.\n *\n * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258\n */\nexport class LineDecoder {\n constructor() {\n this.buffer = [];\n this.trailingCR = false;\n }\n decode(chunk) {\n let text = this.decodeText(chunk);\n if (this.trailingCR) {\n text = '\\r' + text;\n this.trailingCR = false;\n }\n if (text.endsWith('\\r')) {\n this.trailingCR = true;\n text = text.slice(0, -1);\n }\n if (!text) {\n return [];\n }\n const trailingNewline = LineDecoder.NEWLINE_CHARS.has(text[text.length - 1] || '');\n let lines = text.split(LineDecoder.NEWLINE_REGEXP);\n // if there is a trailing new line then the last entry will be an empty\n // string which we don't care about\n if (trailingNewline) {\n lines.pop();\n }\n if (lines.length === 1 && !trailingNewline) {\n this.buffer.push(lines[0]);\n return [];\n }\n if (this.buffer.length > 0) {\n lines = [this.buffer.join('') + lines[0], ...lines.slice(1)];\n this.buffer = [];\n }\n if (!trailingNewline) {\n this.buffer = [lines.pop() || ''];\n }\n return lines;\n }\n decodeText(bytes) {\n if (bytes == null)\n return '';\n if (typeof bytes === 'string')\n return bytes;\n // Node:\n if (typeof Buffer !== 'undefined') {\n if (bytes instanceof Buffer) {\n return bytes.toString();\n }\n if (bytes instanceof Uint8Array) {\n return Buffer.from(bytes).toString();\n }\n throw new OpenAIError(`Unexpected: received non-Uint8Array (${bytes.constructor.name}) stream chunk in an environment with a global \"Buffer\" defined, which this library assumes to be Node. Please report this error.`);\n }\n // Browser\n if (typeof TextDecoder !== 'undefined') {\n if (bytes instanceof Uint8Array || bytes instanceof ArrayBuffer) {\n this.textDecoder ?? (this.textDecoder = new TextDecoder('utf8'));\n return this.textDecoder.decode(bytes);\n }\n throw new OpenAIError(`Unexpected: received non-Uint8Array/ArrayBuffer (${bytes.constructor.name}) in a web platform. Please report this error.`);\n }\n throw new OpenAIError(`Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.`);\n }\n flush() {\n if (!this.buffer.length && !this.trailingCR) {\n return [];\n }\n const lines = [this.buffer.join('')];\n this.buffer = [];\n this.trailingCR = false;\n return lines;\n }\n}\n// prettier-ignore\nLineDecoder.NEWLINE_CHARS = new Set(['\\n', '\\r']);\nLineDecoder.NEWLINE_REGEXP = /\\r\\n|[\\n\\r]/g;\n//# sourceMappingURL=line.mjs.map","import { ReadableStream } from \"./_shims/index.mjs\";\nimport { OpenAIError } from \"./error.mjs\";\nimport { LineDecoder } from \"./internal/decoders/line.mjs\";\nimport { APIError } from \"./error.mjs\";\nexport class Stream {\n constructor(iterator, controller) {\n this.iterator = iterator;\n this.controller = controller;\n }\n static fromSSEResponse(response, controller) {\n let consumed = false;\n async function* iterator() {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const sse of _iterSSEMessages(response, controller)) {\n if (done)\n continue;\n if (sse.data.startsWith('[DONE]')) {\n done = true;\n continue;\n }\n if (sse.event === null) {\n let data;\n try {\n data = JSON.parse(sse.data);\n }\n catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n if (data && data.error) {\n throw new APIError(undefined, data.error, undefined, undefined);\n }\n yield data;\n }\n else {\n let data;\n try {\n data = JSON.parse(sse.data);\n }\n catch (e) {\n console.error(`Could not parse message into JSON:`, sse.data);\n console.error(`From chunk:`, sse.raw);\n throw e;\n }\n // TODO: Is this where the error should be thrown?\n if (sse.event == 'error') {\n throw new APIError(undefined, data.error, data.message, undefined);\n }\n yield { event: sse.event, data: data };\n }\n }\n done = true;\n }\n catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError')\n return;\n throw e;\n }\n finally {\n // If the user `break`s, abort the ongoing request.\n if (!done)\n controller.abort();\n }\n }\n return new Stream(iterator, controller);\n }\n /**\n * Generates a Stream from a newline-separated ReadableStream\n * where each item is a JSON value.\n */\n static fromReadableStream(readableStream, controller) {\n let consumed = false;\n async function* iterLines() {\n const lineDecoder = new LineDecoder();\n const iter = readableStreamAsyncIterable(readableStream);\n for await (const chunk of iter) {\n for (const line of lineDecoder.decode(chunk)) {\n yield line;\n }\n }\n for (const line of lineDecoder.flush()) {\n yield line;\n }\n }\n async function* iterator() {\n if (consumed) {\n throw new Error('Cannot iterate over a consumed stream, use `.tee()` to split the stream.');\n }\n consumed = true;\n let done = false;\n try {\n for await (const line of iterLines()) {\n if (done)\n continue;\n if (line)\n yield JSON.parse(line);\n }\n done = true;\n }\n catch (e) {\n // If the user calls `stream.controller.abort()`, we should exit without throwing.\n if (e instanceof Error && e.name === 'AbortError')\n return;\n throw e;\n }\n finally {\n // If the user `break`s, abort the ongoing request.\n if (!done)\n controller.abort();\n }\n }\n return new Stream(iterator, controller);\n }\n [Symbol.asyncIterator]() {\n return this.iterator();\n }\n /**\n * Splits the stream into two streams which can be\n * independently read from at different speeds.\n */\n tee() {\n const left = [];\n const right = [];\n const iterator = this.iterator();\n const teeIterator = (queue) => {\n return {\n next: () => {\n if (queue.length === 0) {\n const result = iterator.next();\n left.push(result);\n right.push(result);\n }\n return queue.shift();\n },\n };\n };\n return [\n new Stream(() => teeIterator(left), this.controller),\n new Stream(() => teeIterator(right), this.controller),\n ];\n }\n /**\n * Converts this stream to a newline-separated ReadableStream of\n * JSON stringified values in the stream\n * which can be turned back into a Stream with `Stream.fromReadableStream()`.\n */\n toReadableStream() {\n const self = this;\n let iter;\n const encoder = new TextEncoder();\n return new ReadableStream({\n async start() {\n iter = self[Symbol.asyncIterator]();\n },\n async pull(ctrl) {\n try {\n const { value, done } = await iter.next();\n if (done)\n return ctrl.close();\n const bytes = encoder.encode(JSON.stringify(value) + '\\n');\n ctrl.enqueue(bytes);\n }\n catch (err) {\n ctrl.error(err);\n }\n },\n async cancel() {\n await iter.return?.();\n },\n });\n }\n}\nexport async function* _iterSSEMessages(response, controller) {\n if (!response.body) {\n controller.abort();\n throw new OpenAIError(`Attempted to iterate over a response with no body`);\n }\n const sseDecoder = new SSEDecoder();\n const lineDecoder = new LineDecoder();\n const iter = readableStreamAsyncIterable(response.body);\n for await (const sseChunk of iterSSEChunks(iter)) {\n for (const line of lineDecoder.decode(sseChunk)) {\n const sse = sseDecoder.decode(line);\n if (sse)\n yield sse;\n }\n }\n for (const line of lineDecoder.flush()) {\n const sse = sseDecoder.decode(line);\n if (sse)\n yield sse;\n }\n}\n/**\n * Given an async iterable iterator, iterates over it and yields full\n * SSE chunks, i.e. yields when a double new-line is encountered.\n */\nasync function* iterSSEChunks(iterator) {\n let data = new Uint8Array();\n for await (const chunk of iterator) {\n if (chunk == null) {\n continue;\n }\n const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk)\n : typeof chunk === 'string' ? new TextEncoder().encode(chunk)\n : chunk;\n let newData = new Uint8Array(data.length + binaryChunk.length);\n newData.set(data);\n newData.set(binaryChunk, data.length);\n data = newData;\n let patternIndex;\n while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) {\n yield data.slice(0, patternIndex);\n data = data.slice(patternIndex);\n }\n }\n if (data.length > 0) {\n yield data;\n }\n}\nfunction findDoubleNewlineIndex(buffer) {\n // This function searches the buffer for the end patterns (\\r\\r, \\n\\n, \\r\\n\\r\\n)\n // and returns the index right after the first occurrence of any pattern,\n // or -1 if none of the patterns are found.\n const newline = 0x0a; // \\n\n const carriage = 0x0d; // \\r\n for (let i = 0; i < buffer.length - 2; i++) {\n if (buffer[i] === newline && buffer[i + 1] === newline) {\n // \\n\\n\n return i + 2;\n }\n if (buffer[i] === carriage && buffer[i + 1] === carriage) {\n // \\r\\r\n return i + 2;\n }\n if (buffer[i] === carriage &&\n buffer[i + 1] === newline &&\n i + 3 < buffer.length &&\n buffer[i + 2] === carriage &&\n buffer[i + 3] === newline) {\n // \\r\\n\\r\\n\n return i + 4;\n }\n }\n return -1;\n}\nclass SSEDecoder {\n constructor() {\n this.event = null;\n this.data = [];\n this.chunks = [];\n }\n decode(line) {\n if (line.endsWith('\\r')) {\n line = line.substring(0, line.length - 1);\n }\n if (!line) {\n // empty line and we didn't previously encounter any messages\n if (!this.event && !this.data.length)\n return null;\n const sse = {\n event: this.event,\n data: this.data.join('\\n'),\n raw: this.chunks,\n };\n this.event = null;\n this.data = [];\n this.chunks = [];\n return sse;\n }\n this.chunks.push(line);\n if (line.startsWith(':')) {\n return null;\n }\n let [fieldname, _, value] = partition(line, ':');\n if (value.startsWith(' ')) {\n value = value.substring(1);\n }\n if (fieldname === 'event') {\n this.event = value;\n }\n else if (fieldname === 'data') {\n this.data.push(value);\n }\n return null;\n }\n}\n/** This is an internal helper function that's just used for testing */\nexport function _decodeChunks(chunks) {\n const decoder = new LineDecoder();\n const lines = [];\n for (const chunk of chunks) {\n lines.push(...decoder.decode(chunk));\n }\n return lines;\n}\nfunction partition(str, delimiter) {\n const index = str.indexOf(delimiter);\n if (index !== -1) {\n return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)];\n }\n return [str, '', ''];\n}\n/**\n * Most browsers don't yet have async iterable support for ReadableStream,\n * and Node has a very different way of reading bytes from its \"ReadableStream\".\n *\n * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490\n */\nexport function readableStreamAsyncIterable(stream) {\n if (stream[Symbol.asyncIterator])\n return stream;\n const reader = stream.getReader();\n return {\n async next() {\n try {\n const result = await reader.read();\n if (result?.done)\n reader.releaseLock(); // release lock when stream becomes closed\n return result;\n }\n catch (e) {\n reader.releaseLock(); // release lock when stream becomes errored\n throw e;\n }\n },\n async return() {\n const cancelPromise = reader.cancel();\n reader.releaseLock();\n await cancelPromise;\n return { done: true, value: undefined };\n },\n [Symbol.asyncIterator]() {\n return this;\n },\n };\n}\n//# sourceMappingURL=streaming.mjs.map","import { FormData, File, getMultipartRequestOptions, isFsReadStream, } from \"./_shims/index.mjs\";\nexport { fileFromPath } from \"./_shims/index.mjs\";\nexport const isResponseLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.url === 'string' &&\n typeof value.blob === 'function';\nexport const isFileLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.name === 'string' &&\n typeof value.lastModified === 'number' &&\n isBlobLike(value);\n/**\n * The BlobLike type omits arrayBuffer() because @types/node-fetch@^2.6.4 lacks it; but this check\n * adds the arrayBuffer() method type because it is available and used at runtime\n */\nexport const isBlobLike = (value) => value != null &&\n typeof value === 'object' &&\n typeof value.size === 'number' &&\n typeof value.type === 'string' &&\n typeof value.text === 'function' &&\n typeof value.slice === 'function' &&\n typeof value.arrayBuffer === 'function';\nexport const isUploadable = (value) => {\n return isFileLike(value) || isResponseLike(value) || isFsReadStream(value);\n};\n/**\n * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats\n * @param value the raw content of the file. Can be an {@link Uploadable}, {@link BlobLikePart}, or {@link AsyncIterable} of {@link BlobLikePart}s\n * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible\n * @param {Object=} options additional properties\n * @param {string=} options.type the MIME type of the content\n * @param {number=} options.lastModified the last modified timestamp\n * @returns a {@link File} with the given properties\n */\nexport async function toFile(value, name, options) {\n // If it's a promise, resolve it.\n value = await value;\n // If we've been given a `File` we don't need to do anything\n if (isFileLike(value)) {\n return value;\n }\n if (isResponseLike(value)) {\n const blob = await value.blob();\n name || (name = new URL(value.url).pathname.split(/[\\\\/]/).pop() ?? 'unknown_file');\n // we need to convert the `Blob` into an array buffer because the `Blob` class\n // that `node-fetch` defines is incompatible with the web standard which results\n // in `new File` interpreting it as a string instead of binary data.\n const data = isBlobLike(blob) ? [(await blob.arrayBuffer())] : [blob];\n return new File(data, name, options);\n }\n const bits = await getBytes(value);\n name || (name = getName(value) ?? 'unknown_file');\n if (!options?.type) {\n const type = bits[0]?.type;\n if (typeof type === 'string') {\n options = { ...options, type };\n }\n }\n return new File(bits, name, options);\n}\nasync function getBytes(value) {\n let parts = [];\n if (typeof value === 'string' ||\n ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc.\n value instanceof ArrayBuffer) {\n parts.push(value);\n }\n else if (isBlobLike(value)) {\n parts.push(await value.arrayBuffer());\n }\n else if (isAsyncIterableIterator(value) // includes Readable, ReadableStream, etc.\n ) {\n for await (const chunk of value) {\n parts.push(chunk); // TODO, consider validating?\n }\n }\n else {\n throw new Error(`Unexpected data type: ${typeof value}; constructor: ${value?.constructor\n ?.name}; props: ${propsForError(value)}`);\n }\n return parts;\n}\nfunction propsForError(value) {\n const props = Object.getOwnPropertyNames(value);\n return `[${props.map((p) => `\"${p}\"`).join(', ')}]`;\n}\nfunction getName(value) {\n return (getStringFromMaybeBuffer(value.name) ||\n getStringFromMaybeBuffer(value.filename) ||\n // For fs.ReadStream\n getStringFromMaybeBuffer(value.path)?.split(/[\\\\/]/).pop());\n}\nconst getStringFromMaybeBuffer = (x) => {\n if (typeof x === 'string')\n return x;\n if (typeof Buffer !== 'undefined' && x instanceof Buffer)\n return String(x);\n return undefined;\n};\nconst isAsyncIterableIterator = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function';\nexport const isMultipartBody = (body) => body && typeof body === 'object' && body.body && body[Symbol.toStringTag] === 'MultipartBody';\n/**\n * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value.\n * Otherwise returns the request as is.\n */\nexport const maybeMultipartFormRequestOptions = async (opts) => {\n if (!hasUploadableValue(opts.body))\n return opts;\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\nexport const multipartFormRequestOptions = async (opts) => {\n const form = await createForm(opts.body);\n return getMultipartRequestOptions(form, opts);\n};\nexport const createForm = async (body) => {\n const form = new FormData();\n await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value)));\n return form;\n};\nconst hasUploadableValue = (value) => {\n if (isUploadable(value))\n return true;\n if (Array.isArray(value))\n return value.some(hasUploadableValue);\n if (value && typeof value === 'object') {\n for (const k in value) {\n if (hasUploadableValue(value[k]))\n return true;\n }\n }\n return false;\n};\nconst addFormValue = async (form, key, value) => {\n if (value === undefined)\n return;\n if (value == null) {\n throw new TypeError(`Received null for \"${key}\"; to pass null in FormData, you must use the string 'null'`);\n }\n // TODO: make nested formats configurable\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n form.append(key, String(value));\n }\n else if (isUploadable(value)) {\n const file = await toFile(value);\n form.append(key, file);\n }\n else if (Array.isArray(value)) {\n await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry)));\n }\n else if (typeof value === 'object') {\n await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop)));\n }\n else {\n throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`);\n }\n};\n//# sourceMappingURL=uploads.mjs.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _AbstractPage_client;\nimport { VERSION } from \"./version.mjs\";\nimport { Stream } from \"./streaming.mjs\";\nimport { OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, } from \"./error.mjs\";\nimport { kind as shimsKind, getDefaultAgent, fetch, } from \"./_shims/index.mjs\";\nimport { isBlobLike, isMultipartBody } from \"./uploads.mjs\";\nexport { maybeMultipartFormRequestOptions, multipartFormRequestOptions, createForm, } from \"./uploads.mjs\";\nasync function defaultParseResponse(props) {\n const { response } = props;\n if (props.options.stream) {\n debug('response', response.status, response.url, response.headers, response.body);\n // Note: there is an invariant here that isn't represented in the type system\n // that if you set `stream: true` the response type must also be `Stream`\n if (props.options.__streamClass) {\n return props.options.__streamClass.fromSSEResponse(response, props.controller);\n }\n return Stream.fromSSEResponse(response, props.controller);\n }\n // fetch refuses to read the body when the status code is 204.\n if (response.status === 204) {\n return null;\n }\n if (props.options.__binaryResponse) {\n return response;\n }\n const contentType = response.headers.get('content-type');\n const isJSON = contentType?.includes('application/json') || contentType?.includes('application/vnd.api+json');\n if (isJSON) {\n const json = await response.json();\n debug('response', response.status, response.url, response.headers, json);\n return _addRequestID(json, response);\n }\n const text = await response.text();\n debug('response', response.status, response.url, response.headers, text);\n // TODO handle blob, arraybuffer, other content types, etc.\n return text;\n}\nfunction _addRequestID(value, response) {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n return value;\n }\n return Object.defineProperty(value, '_request_id', {\n value: response.headers.get('x-request-id'),\n enumerable: false,\n });\n}\n/**\n * A subclass of `Promise` providing additional helper methods\n * for interacting with the SDK.\n */\nexport class APIPromise extends Promise {\n constructor(responsePromise, parseResponse = defaultParseResponse) {\n super((resolve) => {\n // this is maybe a bit weird but this has to be a no-op to not implicitly\n // parse the response body; instead .then, .catch, .finally are overridden\n // to parse the response\n resolve(null);\n });\n this.responsePromise = responsePromise;\n this.parseResponse = parseResponse;\n }\n _thenUnwrap(transform) {\n return new APIPromise(this.responsePromise, async (props) => _addRequestID(transform(await this.parseResponse(props), props), props.response));\n }\n /**\n * Gets the raw `Response` instance instead of parsing the response\n * data.\n *\n * If you want to parse the response body but still get the `Response`\n * instance, you can use {@link withResponse()}.\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import … from 'openai'`:\n * - `import 'openai/shims/node'` (if you're running on Node)\n * - `import 'openai/shims/web'` (otherwise)\n */\n asResponse() {\n return this.responsePromise.then((p) => p.response);\n }\n /**\n * Gets the parsed response data, the raw `Response` instance and the ID of the request,\n * returned via the X-Request-ID header which is useful for debugging requests and reporting\n * issues to OpenAI.\n *\n * If you just want to get the raw `Response` instance without parsing it,\n * you can use {@link asResponse()}.\n *\n *\n * 👋 Getting the wrong TypeScript type for `Response`?\n * Try setting `\"moduleResolution\": \"NodeNext\"` if you can,\n * or add one of these imports before your first `import … from 'openai'`:\n * - `import 'openai/shims/node'` (if you're running on Node)\n * - `import 'openai/shims/web'` (otherwise)\n */\n async withResponse() {\n const [data, response] = await Promise.all([this.parse(), this.asResponse()]);\n return { data, response, request_id: response.headers.get('x-request-id') };\n }\n parse() {\n if (!this.parsedPromise) {\n this.parsedPromise = this.responsePromise.then(this.parseResponse);\n }\n return this.parsedPromise;\n }\n then(onfulfilled, onrejected) {\n return this.parse().then(onfulfilled, onrejected);\n }\n catch(onrejected) {\n return this.parse().catch(onrejected);\n }\n finally(onfinally) {\n return this.parse().finally(onfinally);\n }\n}\nexport class APIClient {\n constructor({ baseURL, maxRetries = 2, timeout = 600000, // 10 minutes\n httpAgent, fetch: overriddenFetch, }) {\n this.baseURL = baseURL;\n this.maxRetries = validatePositiveInteger('maxRetries', maxRetries);\n this.timeout = validatePositiveInteger('timeout', timeout);\n this.httpAgent = httpAgent;\n this.fetch = overriddenFetch ?? fetch;\n }\n authHeaders(opts) {\n return {};\n }\n /**\n * Override this to add your own default headers, for example:\n *\n * {\n * ...super.defaultHeaders(),\n * Authorization: 'Bearer 123',\n * }\n */\n defaultHeaders(opts) {\n return {\n Accept: 'application/json',\n 'Content-Type': 'application/json',\n 'User-Agent': this.getUserAgent(),\n ...getPlatformHeaders(),\n ...this.authHeaders(opts),\n };\n }\n /**\n * Override this to add your own headers validation:\n */\n validateHeaders(headers, customHeaders) { }\n defaultIdempotencyKey() {\n return `stainless-node-retry-${uuid4()}`;\n }\n get(path, opts) {\n return this.methodRequest('get', path, opts);\n }\n post(path, opts) {\n return this.methodRequest('post', path, opts);\n }\n patch(path, opts) {\n return this.methodRequest('patch', path, opts);\n }\n put(path, opts) {\n return this.methodRequest('put', path, opts);\n }\n delete(path, opts) {\n return this.methodRequest('delete', path, opts);\n }\n methodRequest(method, path, opts) {\n return this.request(Promise.resolve(opts).then(async (opts) => {\n const body = opts && isBlobLike(opts?.body) ? new DataView(await opts.body.arrayBuffer())\n : opts?.body instanceof DataView ? opts.body\n : opts?.body instanceof ArrayBuffer ? new DataView(opts.body)\n : opts && ArrayBuffer.isView(opts?.body) ? new DataView(opts.body.buffer)\n : opts?.body;\n return { method, path, ...opts, body };\n }));\n }\n getAPIList(path, Page, opts) {\n return this.requestAPIList(Page, { method: 'get', path, ...opts });\n }\n calculateContentLength(body) {\n if (typeof body === 'string') {\n if (typeof Buffer !== 'undefined') {\n return Buffer.byteLength(body, 'utf8').toString();\n }\n if (typeof TextEncoder !== 'undefined') {\n const encoder = new TextEncoder();\n const encoded = encoder.encode(body);\n return encoded.length.toString();\n }\n }\n else if (ArrayBuffer.isView(body)) {\n return body.byteLength.toString();\n }\n return null;\n }\n buildRequest(options, { retryCount = 0 } = {}) {\n const { method, path, query, headers: headers = {} } = options;\n const body = ArrayBuffer.isView(options.body) || (options.__binaryRequest && typeof options.body === 'string') ?\n options.body\n : isMultipartBody(options.body) ? options.body.body\n : options.body ? JSON.stringify(options.body, null, 2)\n : null;\n const contentLength = this.calculateContentLength(body);\n const url = this.buildURL(path, query);\n if ('timeout' in options)\n validatePositiveInteger('timeout', options.timeout);\n const timeout = options.timeout ?? this.timeout;\n const httpAgent = options.httpAgent ?? this.httpAgent ?? getDefaultAgent(url);\n const minAgentTimeout = timeout + 1000;\n if (typeof httpAgent?.options?.timeout === 'number' &&\n minAgentTimeout > (httpAgent.options.timeout ?? 0)) {\n // Allow any given request to bump our agent active socket timeout.\n // This may seem strange, but leaking active sockets should be rare and not particularly problematic,\n // and without mutating agent we would need to create more of them.\n // This tradeoff optimizes for performance.\n httpAgent.options.timeout = minAgentTimeout;\n }\n if (this.idempotencyHeader && method !== 'get') {\n if (!options.idempotencyKey)\n options.idempotencyKey = this.defaultIdempotencyKey();\n headers[this.idempotencyHeader] = options.idempotencyKey;\n }\n const reqHeaders = this.buildHeaders({ options, headers, contentLength, retryCount });\n const req = {\n method,\n ...(body && { body: body }),\n headers: reqHeaders,\n ...(httpAgent && { agent: httpAgent }),\n // @ts-ignore node-fetch uses a custom AbortSignal type that is\n // not compatible with standard web types\n signal: options.signal ?? null,\n };\n return { req, url, timeout };\n }\n buildHeaders({ options, headers, contentLength, retryCount, }) {\n const reqHeaders = {};\n if (contentLength) {\n reqHeaders['content-length'] = contentLength;\n }\n const defaultHeaders = this.defaultHeaders(options);\n applyHeadersMut(reqHeaders, defaultHeaders);\n applyHeadersMut(reqHeaders, headers);\n // let builtin fetch set the Content-Type for multipart bodies\n if (isMultipartBody(options.body) && shimsKind !== 'node') {\n delete reqHeaders['content-type'];\n }\n // Don't set the retry count header if it was already set or removed through default headers or by the\n // caller. We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to\n // account for the removal case.\n if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&\n getHeader(headers, 'x-stainless-retry-count') === undefined) {\n reqHeaders['x-stainless-retry-count'] = String(retryCount);\n }\n this.validateHeaders(reqHeaders, headers);\n return reqHeaders;\n }\n /**\n * Used as a callback for mutating the given `FinalRequestOptions` object.\n */\n async prepareOptions(options) { }\n /**\n * Used as a callback for mutating the given `RequestInit` object.\n *\n * This is useful for cases where you want to add certain headers based off of\n * the request properties, e.g. `method` or `url`.\n */\n async prepareRequest(request, { url, options }) { }\n parseHeaders(headers) {\n return (!headers ? {}\n : Symbol.iterator in headers ?\n Object.fromEntries(Array.from(headers).map((header) => [...header]))\n : { ...headers });\n }\n makeStatusError(status, error, message, headers) {\n return APIError.generate(status, error, message, headers);\n }\n request(options, remainingRetries = null) {\n return new APIPromise(this.makeRequest(options, remainingRetries));\n }\n async makeRequest(optionsInput, retriesRemaining) {\n const options = await optionsInput;\n const maxRetries = options.maxRetries ?? this.maxRetries;\n if (retriesRemaining == null) {\n retriesRemaining = maxRetries;\n }\n await this.prepareOptions(options);\n const { req, url, timeout } = this.buildRequest(options, { retryCount: maxRetries - retriesRemaining });\n await this.prepareRequest(req, { url, options });\n debug('request', url, options, req.headers);\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n const controller = new AbortController();\n const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError);\n if (response instanceof Error) {\n if (options.signal?.aborted) {\n throw new APIUserAbortError();\n }\n if (retriesRemaining) {\n return this.retryRequest(options, retriesRemaining);\n }\n if (response.name === 'AbortError') {\n throw new APIConnectionTimeoutError();\n }\n throw new APIConnectionError({ cause: response });\n }\n const responseHeaders = createResponseHeaders(response.headers);\n if (!response.ok) {\n if (retriesRemaining && this.shouldRetry(response)) {\n const retryMessage = `retrying, ${retriesRemaining} attempts remaining`;\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders);\n return this.retryRequest(options, retriesRemaining, responseHeaders);\n }\n const errText = await response.text().catch((e) => castToError(e).message);\n const errJSON = safeJSON(errText);\n const errMessage = errJSON ? undefined : errText;\n const retryMessage = retriesRemaining ? `(error; no more retries left)` : `(error; not retryable)`;\n debug(`response (error; ${retryMessage})`, response.status, url, responseHeaders, errMessage);\n const err = this.makeStatusError(response.status, errJSON, errMessage, responseHeaders);\n throw err;\n }\n return { response, options, controller };\n }\n requestAPIList(Page, options) {\n const request = this.makeRequest(options, null);\n return new PagePromise(this, request, Page);\n }\n buildURL(path, query) {\n const url = isAbsoluteURL(path) ?\n new URL(path)\n : new URL(this.baseURL + (this.baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path));\n const defaultQuery = this.defaultQuery();\n if (!isEmptyObj(defaultQuery)) {\n query = { ...defaultQuery, ...query };\n }\n if (typeof query === 'object' && query && !Array.isArray(query)) {\n url.search = this.stringifyQuery(query);\n }\n return url.toString();\n }\n stringifyQuery(query) {\n return Object.entries(query)\n .filter(([_, value]) => typeof value !== 'undefined')\n .map(([key, value]) => {\n if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {\n return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`;\n }\n if (value === null) {\n return `${encodeURIComponent(key)}=`;\n }\n throw new OpenAIError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);\n })\n .join('&');\n }\n async fetchWithTimeout(url, init, ms, controller) {\n const { signal, ...options } = init || {};\n if (signal)\n signal.addEventListener('abort', () => controller.abort());\n const timeout = setTimeout(() => controller.abort(), ms);\n const fetchOptions = {\n signal: controller.signal,\n ...options,\n };\n if (fetchOptions.method) {\n // Custom methods like 'patch' need to be uppercased\n // See https://github.com/nodejs/undici/issues/2294\n fetchOptions.method = fetchOptions.method.toUpperCase();\n }\n return (\n // use undefined this binding; fetch errors if bound to something else in browser/cloudflare\n this.fetch.call(undefined, url, fetchOptions).finally(() => {\n clearTimeout(timeout);\n }));\n }\n shouldRetry(response) {\n // Note this is not a standard header.\n const shouldRetryHeader = response.headers.get('x-should-retry');\n // If the server explicitly says whether or not to retry, obey.\n if (shouldRetryHeader === 'true')\n return true;\n if (shouldRetryHeader === 'false')\n return false;\n // Retry on request timeouts.\n if (response.status === 408)\n return true;\n // Retry on lock timeouts.\n if (response.status === 409)\n return true;\n // Retry on rate limits.\n if (response.status === 429)\n return true;\n // Retry internal errors.\n if (response.status >= 500)\n return true;\n return false;\n }\n async retryRequest(options, retriesRemaining, responseHeaders) {\n let timeoutMillis;\n // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it.\n const retryAfterMillisHeader = responseHeaders?.['retry-after-ms'];\n if (retryAfterMillisHeader) {\n const timeoutMs = parseFloat(retryAfterMillisHeader);\n if (!Number.isNaN(timeoutMs)) {\n timeoutMillis = timeoutMs;\n }\n }\n // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After\n const retryAfterHeader = responseHeaders?.['retry-after'];\n if (retryAfterHeader && !timeoutMillis) {\n const timeoutSeconds = parseFloat(retryAfterHeader);\n if (!Number.isNaN(timeoutSeconds)) {\n timeoutMillis = timeoutSeconds * 1000;\n }\n else {\n timeoutMillis = Date.parse(retryAfterHeader) - Date.now();\n }\n }\n // If the API asks us to wait a certain amount of time (and it's a reasonable amount),\n // just do what it says, but otherwise calculate a default\n if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) {\n const maxRetries = options.maxRetries ?? this.maxRetries;\n timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries);\n }\n await sleep(timeoutMillis);\n return this.makeRequest(options, retriesRemaining - 1);\n }\n calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) {\n const initialRetryDelay = 0.5;\n const maxRetryDelay = 8.0;\n const numRetries = maxRetries - retriesRemaining;\n // Apply exponential backoff, but not more than the max.\n const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay);\n // Apply some jitter, take up to at most 25 percent of the retry time.\n const jitter = 1 - Math.random() * 0.25;\n return sleepSeconds * jitter * 1000;\n }\n getUserAgent() {\n return `${this.constructor.name}/JS ${VERSION}`;\n }\n}\nexport class AbstractPage {\n constructor(client, response, body, options) {\n _AbstractPage_client.set(this, void 0);\n __classPrivateFieldSet(this, _AbstractPage_client, client, \"f\");\n this.options = options;\n this.response = response;\n this.body = body;\n }\n hasNextPage() {\n const items = this.getPaginatedItems();\n if (!items.length)\n return false;\n return this.nextPageInfo() != null;\n }\n async getNextPage() {\n const nextInfo = this.nextPageInfo();\n if (!nextInfo) {\n throw new OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.');\n }\n const nextOptions = { ...this.options };\n if ('params' in nextInfo && typeof nextOptions.query === 'object') {\n nextOptions.query = { ...nextOptions.query, ...nextInfo.params };\n }\n else if ('url' in nextInfo) {\n const params = [...Object.entries(nextOptions.query || {}), ...nextInfo.url.searchParams.entries()];\n for (const [key, value] of params) {\n nextInfo.url.searchParams.set(key, value);\n }\n nextOptions.query = undefined;\n nextOptions.path = nextInfo.url.toString();\n }\n return await __classPrivateFieldGet(this, _AbstractPage_client, \"f\").requestAPIList(this.constructor, nextOptions);\n }\n async *iterPages() {\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n let page = this;\n yield page;\n while (page.hasNextPage()) {\n page = await page.getNextPage();\n yield page;\n }\n }\n async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() {\n for await (const page of this.iterPages()) {\n for (const item of page.getPaginatedItems()) {\n yield item;\n }\n }\n }\n}\n/**\n * This subclass of Promise will resolve to an instantiated Page once the request completes.\n *\n * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\nexport class PagePromise extends APIPromise {\n constructor(client, request, Page) {\n super(request, async (props) => new Page(client, props.response, await defaultParseResponse(props), props.options));\n }\n /**\n * Allow auto-paginating iteration on an unawaited list call, eg:\n *\n * for await (const item of client.items.list()) {\n * console.log(item)\n * }\n */\n async *[Symbol.asyncIterator]() {\n const page = await this;\n for await (const item of page) {\n yield item;\n }\n }\n}\nexport const createResponseHeaders = (headers) => {\n return new Proxy(Object.fromEntries(\n // @ts-ignore\n headers.entries()), {\n get(target, name) {\n const key = name.toString();\n return target[key.toLowerCase()] || target[key];\n },\n });\n};\n// This is required so that we can determine if a given object matches the RequestOptions\n// type at runtime. While this requires duplication, it is enforced by the TypeScript\n// compiler such that any missing / extraneous keys will cause an error.\nconst requestOptionsKeys = {\n method: true,\n path: true,\n query: true,\n body: true,\n headers: true,\n maxRetries: true,\n stream: true,\n timeout: true,\n httpAgent: true,\n signal: true,\n idempotencyKey: true,\n __binaryRequest: true,\n __binaryResponse: true,\n __streamClass: true,\n};\nexport const isRequestOptions = (obj) => {\n return (typeof obj === 'object' &&\n obj !== null &&\n !isEmptyObj(obj) &&\n Object.keys(obj).every((k) => hasOwn(requestOptionsKeys, k)));\n};\nconst getPlatformProperties = () => {\n if (typeof Deno !== 'undefined' && Deno.build != null) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(Deno.build.os),\n 'X-Stainless-Arch': normalizeArch(Deno.build.arch),\n 'X-Stainless-Runtime': 'deno',\n 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown',\n };\n }\n if (typeof EdgeRuntime !== 'undefined') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': `other:${EdgeRuntime}`,\n 'X-Stainless-Runtime': 'edge',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n // Check if Node.js\n if (Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]') {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': normalizePlatform(process.platform),\n 'X-Stainless-Arch': normalizeArch(process.arch),\n 'X-Stainless-Runtime': 'node',\n 'X-Stainless-Runtime-Version': process.version,\n };\n }\n const browserInfo = getBrowserInfo();\n if (browserInfo) {\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': `browser:${browserInfo.browser}`,\n 'X-Stainless-Runtime-Version': browserInfo.version,\n };\n }\n // TODO add support for Cloudflare workers, etc.\n return {\n 'X-Stainless-Lang': 'js',\n 'X-Stainless-Package-Version': VERSION,\n 'X-Stainless-OS': 'Unknown',\n 'X-Stainless-Arch': 'unknown',\n 'X-Stainless-Runtime': 'unknown',\n 'X-Stainless-Runtime-Version': 'unknown',\n };\n};\n// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts\nfunction getBrowserInfo() {\n if (typeof navigator === 'undefined' || !navigator) {\n return null;\n }\n // NOTE: The order matters here!\n const browserPatterns = [\n { key: 'edge', pattern: /Edge(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie', pattern: /MSIE(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'ie', pattern: /Trident(?:.*rv\\:(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'chrome', pattern: /Chrome(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'firefox', pattern: /Firefox(?:\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?/ },\n { key: 'safari', pattern: /(?:Version\\W+(\\d+)\\.(\\d+)(?:\\.(\\d+))?)?(?:\\W+Mobile\\S*)?\\W+Safari/ },\n ];\n // Find the FIRST matching browser\n for (const { key, pattern } of browserPatterns) {\n const match = pattern.exec(navigator.userAgent);\n if (match) {\n const major = match[1] || 0;\n const minor = match[2] || 0;\n const patch = match[3] || 0;\n return { browser: key, version: `${major}.${minor}.${patch}` };\n }\n }\n return null;\n}\nconst normalizeArch = (arch) => {\n // Node docs:\n // - https://nodejs.org/api/process.html#processarch\n // Deno docs:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n if (arch === 'x32')\n return 'x32';\n if (arch === 'x86_64' || arch === 'x64')\n return 'x64';\n if (arch === 'arm')\n return 'arm';\n if (arch === 'aarch64' || arch === 'arm64')\n return 'arm64';\n if (arch)\n return `other:${arch}`;\n return 'unknown';\n};\nconst normalizePlatform = (platform) => {\n // Node platforms:\n // - https://nodejs.org/api/process.html#processplatform\n // Deno platforms:\n // - https://doc.deno.land/deno/stable/~/Deno.build\n // - https://github.com/denoland/deno/issues/14799\n platform = platform.toLowerCase();\n // NOTE: this iOS check is untested and may not work\n // Node does not work natively on IOS, there is a fork at\n // https://github.com/nodejs-mobile/nodejs-mobile\n // however it is unknown at the time of writing how to detect if it is running\n if (platform.includes('ios'))\n return 'iOS';\n if (platform === 'android')\n return 'Android';\n if (platform === 'darwin')\n return 'MacOS';\n if (platform === 'win32')\n return 'Windows';\n if (platform === 'freebsd')\n return 'FreeBSD';\n if (platform === 'openbsd')\n return 'OpenBSD';\n if (platform === 'linux')\n return 'Linux';\n if (platform)\n return `Other:${platform}`;\n return 'Unknown';\n};\nlet _platformHeaders;\nconst getPlatformHeaders = () => {\n return (_platformHeaders ?? (_platformHeaders = getPlatformProperties()));\n};\nexport const safeJSON = (text) => {\n try {\n return JSON.parse(text);\n }\n catch (err) {\n return undefined;\n }\n};\n// https://url.spec.whatwg.org/#url-scheme-string\nconst startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i;\nconst isAbsoluteURL = (url) => {\n return startsWithSchemeRegexp.test(url);\n};\nexport const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\nconst validatePositiveInteger = (name, n) => {\n if (typeof n !== 'number' || !Number.isInteger(n)) {\n throw new OpenAIError(`${name} must be an integer`);\n }\n if (n < 0) {\n throw new OpenAIError(`${name} must be a positive integer`);\n }\n return n;\n};\nexport const castToError = (err) => {\n if (err instanceof Error)\n return err;\n if (typeof err === 'object' && err !== null) {\n try {\n return new Error(JSON.stringify(err));\n }\n catch { }\n }\n return new Error(err);\n};\nexport const ensurePresent = (value) => {\n if (value == null)\n throw new OpenAIError(`Expected a value to be given but received ${value} instead.`);\n return value;\n};\n/**\n * Read an environment variable.\n *\n * Trims beginning and trailing whitespace.\n *\n * Will return undefined if the environment variable doesn't exist or cannot be accessed.\n */\nexport const readEnv = (env) => {\n if (typeof process !== 'undefined') {\n return process.env?.[env]?.trim() ?? undefined;\n }\n if (typeof Deno !== 'undefined') {\n return Deno.env?.get?.(env)?.trim();\n }\n return undefined;\n};\nexport const coerceInteger = (value) => {\n if (typeof value === 'number')\n return Math.round(value);\n if (typeof value === 'string')\n return parseInt(value, 10);\n throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\nexport const coerceFloat = (value) => {\n if (typeof value === 'number')\n return value;\n if (typeof value === 'string')\n return parseFloat(value);\n throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`);\n};\nexport const coerceBoolean = (value) => {\n if (typeof value === 'boolean')\n return value;\n if (typeof value === 'string')\n return value === 'true';\n return Boolean(value);\n};\nexport const maybeCoerceInteger = (value) => {\n if (value === undefined) {\n return undefined;\n }\n return coerceInteger(value);\n};\nexport const maybeCoerceFloat = (value) => {\n if (value === undefined) {\n return undefined;\n }\n return coerceFloat(value);\n};\nexport const maybeCoerceBoolean = (value) => {\n if (value === undefined) {\n return undefined;\n }\n return coerceBoolean(value);\n};\n// https://stackoverflow.com/a/34491287\nexport function isEmptyObj(obj) {\n if (!obj)\n return true;\n for (const _k in obj)\n return false;\n return true;\n}\n// https://eslint.org/docs/latest/rules/no-prototype-builtins\nexport function hasOwn(obj, key) {\n return Object.prototype.hasOwnProperty.call(obj, key);\n}\n/**\n * Copies headers from \"newHeaders\" onto \"targetHeaders\",\n * using lower-case for all properties,\n * ignoring any keys with undefined values,\n * and deleting any keys with null values.\n */\nfunction applyHeadersMut(targetHeaders, newHeaders) {\n for (const k in newHeaders) {\n if (!hasOwn(newHeaders, k))\n continue;\n const lowerKey = k.toLowerCase();\n if (!lowerKey)\n continue;\n const val = newHeaders[k];\n if (val === null) {\n delete targetHeaders[lowerKey];\n }\n else if (val !== undefined) {\n targetHeaders[lowerKey] = val;\n }\n }\n}\nexport function debug(action, ...args) {\n if (typeof process !== 'undefined' && process?.env?.['DEBUG'] === 'true') {\n console.log(`OpenAI:DEBUG:${action}`, ...args);\n }\n}\n/**\n * https://stackoverflow.com/a/2117523\n */\nconst uuid4 = () => {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n });\n};\nexport const isRunningInBrowser = () => {\n return (\n // @ts-ignore\n typeof window !== 'undefined' &&\n // @ts-ignore\n typeof window.document !== 'undefined' &&\n // @ts-ignore\n typeof navigator !== 'undefined');\n};\nexport const isHeadersProtocol = (headers) => {\n return typeof headers?.get === 'function';\n};\nexport const getRequiredHeader = (headers, header) => {\n const foundHeader = getHeader(headers, header);\n if (foundHeader === undefined) {\n throw new Error(`Could not find ${header} header`);\n }\n return foundHeader;\n};\nexport const getHeader = (headers, header) => {\n const lowerCasedHeader = header.toLowerCase();\n if (isHeadersProtocol(headers)) {\n // to deal with the case where the header looks like Stainless-Event-Id\n const intercapsHeader = header[0]?.toUpperCase() +\n header.substring(1).replace(/([^\\w])(\\w)/g, (_m, g1, g2) => g1 + g2.toUpperCase());\n for (const key of [header, lowerCasedHeader, header.toUpperCase(), intercapsHeader]) {\n const value = headers.get(key);\n if (value) {\n return value;\n }\n }\n }\n for (const [key, value] of Object.entries(headers)) {\n if (key.toLowerCase() === lowerCasedHeader) {\n if (Array.isArray(value)) {\n if (value.length <= 1)\n return value[0];\n console.warn(`Received ${value.length} entries for the ${header} header, using the first entry.`);\n return value[0];\n }\n return value;\n }\n }\n return undefined;\n};\n/**\n * Encodes a string to Base64 format.\n */\nexport const toBase64 = (str) => {\n if (!str)\n return '';\n if (typeof Buffer !== 'undefined') {\n return Buffer.from(str).toString('base64');\n }\n if (typeof btoa !== 'undefined') {\n return btoa(str);\n }\n throw new OpenAIError('Cannot generate b64 string; Expected `Buffer` or `btoa` to be defined');\n};\nexport function isObj(obj) {\n return obj != null && typeof obj === 'object' && !Array.isArray(obj);\n}\n//# sourceMappingURL=core.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { AbstractPage } from \"./core.mjs\";\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class Page extends AbstractPage {\n constructor(client, response, body, options) {\n super(client, response, body, options);\n this.data = body.data || [];\n this.object = body.object;\n }\n getPaginatedItems() {\n return this.data ?? [];\n }\n // @deprecated Please use `nextPageInfo()` instead\n /**\n * This page represents a response that isn't actually paginated at the API level\n * so there will never be any next page params.\n */\n nextPageParams() {\n return null;\n }\n nextPageInfo() {\n return null;\n }\n}\nexport class CursorPage extends AbstractPage {\n constructor(client, response, body, options) {\n super(client, response, body, options);\n this.data = body.data || [];\n }\n getPaginatedItems() {\n return this.data ?? [];\n }\n // @deprecated Please use `nextPageInfo()` instead\n nextPageParams() {\n const info = this.nextPageInfo();\n if (!info)\n return null;\n if ('params' in info)\n return info.params;\n const params = Object.fromEntries(info.url.searchParams);\n if (!Object.keys(params).length)\n return null;\n return params;\n }\n nextPageInfo() {\n const data = this.getPaginatedItems();\n if (!data.length) {\n return null;\n }\n const id = data[data.length - 1]?.id;\n if (!id) {\n return null;\n }\n return { params: { after: id } };\n }\n}\n//# sourceMappingURL=pagination.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nexport class APIResource {\n constructor(client) {\n this._client = client;\n }\n}\n//# sourceMappingURL=resource.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nexport class Completions extends APIResource {\n create(body, options) {\n return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false });\n }\n}\n//# sourceMappingURL=completions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as CompletionsAPI from \"./completions.mjs\";\nimport { Completions, } from \"./completions.mjs\";\nexport class Chat extends APIResource {\n constructor() {\n super(...arguments);\n this.completions = new CompletionsAPI.Completions(this._client);\n }\n}\nChat.Completions = Completions;\n//# sourceMappingURL=chat.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nexport class Speech extends APIResource {\n /**\n * Generates audio from the input text.\n */\n create(body, options) {\n return this._client.post('/audio/speech', {\n body,\n ...options,\n headers: { Accept: 'application/octet-stream', ...options?.headers },\n __binaryResponse: true,\n });\n }\n}\n//# sourceMappingURL=speech.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as Core from \"../../core.mjs\";\nexport class Transcriptions extends APIResource {\n create(body, options) {\n return this._client.post('/audio/transcriptions', Core.multipartFormRequestOptions({ body, ...options }));\n }\n}\n//# sourceMappingURL=transcriptions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as Core from \"../../core.mjs\";\nexport class Translations extends APIResource {\n create(body, options) {\n return this._client.post('/audio/translations', Core.multipartFormRequestOptions({ body, ...options }));\n }\n}\n//# sourceMappingURL=translations.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as SpeechAPI from \"./speech.mjs\";\nimport { Speech } from \"./speech.mjs\";\nimport * as TranscriptionsAPI from \"./transcriptions.mjs\";\nimport { Transcriptions, } from \"./transcriptions.mjs\";\nimport * as TranslationsAPI from \"./translations.mjs\";\nimport { Translations, } from \"./translations.mjs\";\nexport class Audio extends APIResource {\n constructor() {\n super(...arguments);\n this.transcriptions = new TranscriptionsAPI.Transcriptions(this._client);\n this.translations = new TranslationsAPI.Translations(this._client);\n this.speech = new SpeechAPI.Speech(this._client);\n }\n}\nAudio.Transcriptions = Transcriptions;\nAudio.Translations = Translations;\nAudio.Speech = Speech;\n//# sourceMappingURL=audio.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nimport { isRequestOptions } from \"../core.mjs\";\nimport { CursorPage } from \"../pagination.mjs\";\nexport class Batches extends APIResource {\n /**\n * Creates and executes a batch from an uploaded file of requests\n */\n create(body, options) {\n return this._client.post('/batches', { body, ...options });\n }\n /**\n * Retrieves a batch.\n */\n retrieve(batchId, options) {\n return this._client.get(`/batches/${batchId}`, options);\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/batches', BatchesPage, { query, ...options });\n }\n /**\n * Cancels an in-progress batch. The batch will be in status `cancelling` for up to\n * 10 minutes, before changing to `cancelled`, where it will have partial results\n * (if any) available in the output file.\n */\n cancel(batchId, options) {\n return this._client.post(`/batches/${batchId}/cancel`, options);\n }\n}\nexport class BatchesPage extends CursorPage {\n}\nBatches.BatchesPage = BatchesPage;\n//# sourceMappingURL=batches.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport { isRequestOptions } from \"../../core.mjs\";\nimport { CursorPage } from \"../../pagination.mjs\";\nexport class Assistants extends APIResource {\n /**\n * Create an assistant with a model and instructions.\n */\n create(body, options) {\n return this._client.post('/assistants', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves an assistant.\n */\n retrieve(assistantId, options) {\n return this._client.get(`/assistants/${assistantId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies an assistant.\n */\n update(assistantId, body, options) {\n return this._client.post(`/assistants/${assistantId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/assistants', AssistantsPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Delete an assistant.\n */\n del(assistantId, options) {\n return this._client.delete(`/assistants/${assistantId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\nexport class AssistantsPage extends CursorPage {\n}\nAssistants.AssistantsPage = AssistantsPage;\n//# sourceMappingURL=assistants.mjs.map","export function isRunnableFunctionWithParse(fn) {\n return typeof fn.parse === 'function';\n}\n/**\n * This is helper class for passing a `function` and `parse` where the `function`\n * argument type matches the `parse` return type.\n *\n * @deprecated - please use ParsingToolFunction instead.\n */\nexport class ParsingFunction {\n constructor(input) {\n this.function = input.function;\n this.parse = input.parse;\n this.parameters = input.parameters;\n this.description = input.description;\n this.name = input.name;\n }\n}\n/**\n * This is helper class for passing a `function` and `parse` where the `function`\n * argument type matches the `parse` return type.\n */\nexport class ParsingToolFunction {\n constructor(input) {\n this.type = 'function';\n this.function = input;\n }\n}\n//# sourceMappingURL=RunnableFunction.mjs.map","export const isAssistantMessage = (message) => {\n return message?.role === 'assistant';\n};\nexport const isFunctionMessage = (message) => {\n return message?.role === 'function';\n};\nexport const isToolMessage = (message) => {\n return message?.role === 'tool';\n};\nexport function isPresent(obj) {\n return obj != null;\n}\n//# sourceMappingURL=chatCompletionUtils.mjs.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError;\nimport { APIUserAbortError, OpenAIError } from \"../error.mjs\";\nexport class EventStream {\n constructor() {\n _EventStream_instances.add(this);\n this.controller = new AbortController();\n _EventStream_connectedPromise.set(this, void 0);\n _EventStream_resolveConnectedPromise.set(this, () => { });\n _EventStream_rejectConnectedPromise.set(this, () => { });\n _EventStream_endPromise.set(this, void 0);\n _EventStream_resolveEndPromise.set(this, () => { });\n _EventStream_rejectEndPromise.set(this, () => { });\n _EventStream_listeners.set(this, {});\n _EventStream_ended.set(this, false);\n _EventStream_errored.set(this, false);\n _EventStream_aborted.set(this, false);\n _EventStream_catchingPromiseCreated.set(this, false);\n __classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, \"f\");\n }), \"f\");\n __classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, \"f\");\n __classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, \"f\");\n }), \"f\");\n // Don't let these promises cause unhandled rejection errors.\n // we will manually cause an unhandled rejection error later\n // if the user hasn't registered any error listener or called\n // any promise-returning method.\n __classPrivateFieldGet(this, _EventStream_connectedPromise, \"f\").catch(() => { });\n __classPrivateFieldGet(this, _EventStream_endPromise, \"f\").catch(() => { });\n }\n _run(executor) {\n // Unfortunately if we call `executor()` immediately we get runtime errors about\n // references to `this` before the `super()` constructor call returns.\n setTimeout(() => {\n executor().then(() => {\n this._emitFinal();\n this._emit('end');\n }, __classPrivateFieldGet(this, _EventStream_instances, \"m\", _EventStream_handleError).bind(this));\n }, 0);\n }\n _connected() {\n if (this.ended)\n return;\n __classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, \"f\").call(this);\n this._emit('connect');\n }\n get ended() {\n return __classPrivateFieldGet(this, _EventStream_ended, \"f\");\n }\n get errored() {\n return __classPrivateFieldGet(this, _EventStream_errored, \"f\");\n }\n get aborted() {\n return __classPrivateFieldGet(this, _EventStream_aborted, \"f\");\n }\n abort() {\n this.controller.abort();\n }\n /**\n * Adds the listener function to the end of the listeners array for the event.\n * No checks are made to see if the listener has already been added. Multiple calls passing\n * the same combination of event and listener will result in the listener being added, and\n * called, multiple times.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n on(event, listener) {\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] = []);\n listeners.push({ listener });\n return this;\n }\n /**\n * Removes the specified listener from the listener array for the event.\n * off() will remove, at most, one instance of a listener from the listener array. If any single\n * listener has been added multiple times to the listener array for the specified event, then\n * off() must be called multiple times to remove each instance.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n off(event, listener) {\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event];\n if (!listeners)\n return this;\n const index = listeners.findIndex((l) => l.listener === listener);\n if (index >= 0)\n listeners.splice(index, 1);\n return this;\n }\n /**\n * Adds a one-time listener function for the event. The next time the event is triggered,\n * this listener is removed and then invoked.\n * @returns this ChatCompletionStream, so that calls can be chained\n */\n once(event, listener) {\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] || (__classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] = []);\n listeners.push({ listener, once: true });\n return this;\n }\n /**\n * This is similar to `.once()`, but returns a Promise that resolves the next time\n * the event is triggered, instead of calling a listener callback.\n * @returns a Promise that resolves the next time given event is triggered,\n * or rejects if an error is emitted. (If you request the 'error' event,\n * returns a promise that resolves with the error).\n *\n * Example:\n *\n * const message = await stream.emitted('message') // rejects if the stream errors\n */\n emitted(event) {\n return new Promise((resolve, reject) => {\n __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, \"f\");\n if (event !== 'error')\n this.once('error', reject);\n this.once(event, resolve);\n });\n }\n async done() {\n __classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, \"f\");\n await __classPrivateFieldGet(this, _EventStream_endPromise, \"f\");\n }\n _emit(event, ...args) {\n // make sure we don't emit any events after end\n if (__classPrivateFieldGet(this, _EventStream_ended, \"f\")) {\n return;\n }\n if (event === 'end') {\n __classPrivateFieldSet(this, _EventStream_ended, true, \"f\");\n __classPrivateFieldGet(this, _EventStream_resolveEndPromise, \"f\").call(this);\n }\n const listeners = __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event];\n if (listeners) {\n __classPrivateFieldGet(this, _EventStream_listeners, \"f\")[event] = listeners.filter((l) => !l.once);\n listeners.forEach(({ listener }) => listener(...args));\n }\n if (event === 'abort') {\n const error = args[0];\n if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _EventStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n return;\n }\n if (event === 'error') {\n // NOTE: _emit('error', error) should only be called from #handleError().\n const error = args[0];\n if (!__classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, \"f\") && !listeners?.length) {\n // Trigger an unhandled rejection if the user hasn't registered any error handlers.\n // If you are seeing stack traces here, make sure to handle errors via either:\n // - runner.on('error', () => ...)\n // - await runner.done()\n // - await runner.finalChatCompletion()\n // - etc.\n Promise.reject(error);\n }\n __classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, \"f\").call(this, error);\n __classPrivateFieldGet(this, _EventStream_rejectEndPromise, \"f\").call(this, error);\n this._emit('end');\n }\n }\n _emitFinal() { }\n}\n_EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) {\n __classPrivateFieldSet(this, _EventStream_errored, true, \"f\");\n if (error instanceof Error && error.name === 'AbortError') {\n error = new APIUserAbortError();\n }\n if (error instanceof APIUserAbortError) {\n __classPrivateFieldSet(this, _EventStream_aborted, true, \"f\");\n return this._emit('abort', error);\n }\n if (error instanceof OpenAIError) {\n return this._emit('error', error);\n }\n if (error instanceof Error) {\n const openAIError = new OpenAIError(error.message);\n // @ts-ignore\n openAIError.cause = error;\n return this._emit('error', openAIError);\n }\n return this._emit('error', new OpenAIError(String(error)));\n};\n//# sourceMappingURL=EventStream.mjs.map","import { ContentFilterFinishReasonError, LengthFinishReasonError, OpenAIError } from \"../error.mjs\";\nexport function makeParseableResponseFormat(response_format, parser) {\n const obj = { ...response_format };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-response-format',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableResponseFormat(response_format) {\n return response_format?.['$brand'] === 'auto-parseable-response-format';\n}\nexport function makeParseableTool(tool, { parser, callback, }) {\n const obj = { ...tool };\n Object.defineProperties(obj, {\n $brand: {\n value: 'auto-parseable-tool',\n enumerable: false,\n },\n $parseRaw: {\n value: parser,\n enumerable: false,\n },\n $callback: {\n value: callback,\n enumerable: false,\n },\n });\n return obj;\n}\nexport function isAutoParsableTool(tool) {\n return tool?.['$brand'] === 'auto-parseable-tool';\n}\nexport function maybeParseChatCompletion(completion, params) {\n if (!params || !hasAutoParseableInput(params)) {\n return {\n ...completion,\n choices: completion.choices.map((choice) => ({\n ...choice,\n message: { ...choice.message, parsed: null, tool_calls: choice.message.tool_calls ?? [] },\n })),\n };\n }\n return parseChatCompletion(completion, params);\n}\nexport function parseChatCompletion(completion, params) {\n const choices = completion.choices.map((choice) => {\n if (choice.finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n if (choice.finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n return {\n ...choice,\n message: {\n ...choice.message,\n tool_calls: choice.message.tool_calls?.map((toolCall) => parseToolCall(params, toolCall)) ?? [],\n parsed: choice.message.content && !choice.message.refusal ?\n parseResponseFormat(params, choice.message.content)\n : null,\n },\n };\n });\n return { ...completion, choices };\n}\nfunction parseResponseFormat(params, content) {\n if (params.response_format?.type !== 'json_schema') {\n return null;\n }\n if (params.response_format?.type === 'json_schema') {\n if ('$parseRaw' in params.response_format) {\n const response_format = params.response_format;\n return response_format.$parseRaw(content);\n }\n return JSON.parse(content);\n }\n return null;\n}\nfunction parseToolCall(params, toolCall) {\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return {\n ...toolCall,\n function: {\n ...toolCall.function,\n parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments)\n : null,\n },\n };\n}\nexport function shouldParseToolCall(params, toolCall) {\n if (!params) {\n return false;\n }\n const inputTool = params.tools?.find((inputTool) => inputTool.function?.name === toolCall.function.name);\n return isAutoParsableTool(inputTool) || inputTool?.function.strict || false;\n}\nexport function hasAutoParseableInput(params) {\n if (isAutoParsableResponseFormat(params.response_format)) {\n return true;\n }\n return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false);\n}\nexport function validateInputTools(tools) {\n for (const tool of tools ?? []) {\n if (tool.type !== 'function') {\n throw new OpenAIError(`Currently only \\`function\\` tool types support auto-parsing; Received \\`${tool.type}\\``);\n }\n if (tool.function.strict !== true) {\n throw new OpenAIError(`The \\`${tool.function.name}\\` tool is not marked with \\`strict: true\\`. Only strict function tools can be auto-parsed`);\n }\n }\n}\n//# sourceMappingURL=parser.mjs.map","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionCall, _AbstractChatCompletionRunner_getFinalFunctionCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult;\nimport { OpenAIError } from \"../error.mjs\";\nimport { isRunnableFunctionWithParse, } from \"./RunnableFunction.mjs\";\nimport { isAssistantMessage, isFunctionMessage, isToolMessage } from \"./chatCompletionUtils.mjs\";\nimport { EventStream } from \"./EventStream.mjs\";\nimport { isAutoParsableTool, parseChatCompletion } from \"../lib/parser.mjs\";\nconst DEFAULT_MAX_CHAT_COMPLETIONS = 10;\nexport class AbstractChatCompletionRunner extends EventStream {\n constructor() {\n super(...arguments);\n _AbstractChatCompletionRunner_instances.add(this);\n this._chatCompletions = [];\n this.messages = [];\n }\n _addChatCompletion(chatCompletion) {\n this._chatCompletions.push(chatCompletion);\n this._emit('chatCompletion', chatCompletion);\n const message = chatCompletion.choices[0]?.message;\n if (message)\n this._addMessage(message);\n return chatCompletion;\n }\n _addMessage(message, emit = true) {\n if (!('content' in message))\n message.content = null;\n this.messages.push(message);\n if (emit) {\n this._emit('message', message);\n if ((isFunctionMessage(message) || isToolMessage(message)) && message.content) {\n // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function.\n this._emit('functionCallResult', message.content);\n }\n else if (isAssistantMessage(message) && message.function_call) {\n this._emit('functionCall', message.function_call);\n }\n else if (isAssistantMessage(message) && message.tool_calls) {\n for (const tool_call of message.tool_calls) {\n if (tool_call.type === 'function') {\n this._emit('functionCall', tool_call.function);\n }\n }\n }\n }\n }\n /**\n * @returns a promise that resolves with the final ChatCompletion, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletion.\n */\n async finalChatCompletion() {\n await this.done();\n const completion = this._chatCompletions[this._chatCompletions.length - 1];\n if (!completion)\n throw new OpenAIError('stream ended without producing a ChatCompletion');\n return completion;\n }\n /**\n * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalContent() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalContent).call(this);\n }\n /**\n * @returns a promise that resolves with the the final assistant ChatCompletionMessage response,\n * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalMessage() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalMessage).call(this);\n }\n /**\n * @returns a promise that resolves with the content of the final FunctionCall, or rejects\n * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage.\n */\n async finalFunctionCall() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);\n }\n async finalFunctionCallResult() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);\n }\n async totalUsage() {\n await this.done();\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_calculateTotalUsage).call(this);\n }\n allChatCompletions() {\n return [...this._chatCompletions];\n }\n _emitFinal() {\n const completion = this._chatCompletions[this._chatCompletions.length - 1];\n if (completion)\n this._emit('finalChatCompletion', completion);\n const finalMessage = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalMessage).call(this);\n if (finalMessage)\n this._emit('finalMessage', finalMessage);\n const finalContent = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalContent).call(this);\n if (finalContent)\n this._emit('finalContent', finalContent);\n const finalFunctionCall = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionCall).call(this);\n if (finalFunctionCall)\n this._emit('finalFunctionCall', finalFunctionCall);\n const finalFunctionCallResult = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalFunctionCallResult).call(this);\n if (finalFunctionCallResult != null)\n this._emit('finalFunctionCallResult', finalFunctionCallResult);\n if (this._chatCompletions.some((c) => c.usage)) {\n this._emit('totalUsage', __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_calculateTotalUsage).call(this));\n }\n }\n async _createChatCompletion(client, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_validateParams).call(this, params);\n const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal });\n this._connected();\n return this._addChatCompletion(parseChatCompletion(chatCompletion, params));\n }\n async _runChatCompletion(client, params, options) {\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n return await this._createChatCompletion(client, params, options);\n }\n async _runFunctions(client, params, options) {\n const role = 'function';\n const { function_call = 'auto', stream, ...restParams } = params;\n const singleFunctionToCall = typeof function_call !== 'string' && function_call?.name;\n const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};\n const functionsByName = {};\n for (const f of params.functions) {\n functionsByName[f.name || f.function.name] = f;\n }\n const functions = params.functions.map((f) => ({\n name: f.name || f.function.name,\n parameters: f.parameters,\n description: f.description,\n }));\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n for (let i = 0; i < maxChatCompletions; ++i) {\n const chatCompletion = await this._createChatCompletion(client, {\n ...restParams,\n function_call,\n functions,\n messages: [...this.messages],\n }, options);\n const message = chatCompletion.choices[0]?.message;\n if (!message) {\n throw new OpenAIError(`missing message in ChatCompletion response`);\n }\n if (!message.function_call)\n return;\n const { name, arguments: args } = message.function_call;\n const fn = functionsByName[name];\n if (!fn) {\n const content = `Invalid function_call: ${JSON.stringify(name)}. Available options are: ${functions\n .map((f) => JSON.stringify(f.name))\n .join(', ')}. Please try again`;\n this._addMessage({ role, name, content });\n continue;\n }\n else if (singleFunctionToCall && singleFunctionToCall !== name) {\n const content = `Invalid function_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;\n this._addMessage({ role, name, content });\n continue;\n }\n let parsed;\n try {\n parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;\n }\n catch (error) {\n this._addMessage({\n role,\n name,\n content: error instanceof Error ? error.message : String(error),\n });\n continue;\n }\n // @ts-expect-error it can't rule out `never` type.\n const rawContent = await fn.function(parsed, this);\n const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);\n this._addMessage({ role, name, content });\n if (singleFunctionToCall)\n return;\n }\n }\n async _runTools(client, params, options) {\n const role = 'tool';\n const { tool_choice = 'auto', stream, ...restParams } = params;\n const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice?.function?.name;\n const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {};\n // TODO(someday): clean this logic up\n const inputTools = params.tools.map((tool) => {\n if (isAutoParsableTool(tool)) {\n if (!tool.$callback) {\n throw new OpenAIError('Tool given to `.runTools()` that does not have an associated function');\n }\n return {\n type: 'function',\n function: {\n function: tool.$callback,\n name: tool.function.name,\n description: tool.function.description || '',\n parameters: tool.function.parameters,\n parse: tool.$parseRaw,\n strict: true,\n },\n };\n }\n return tool;\n });\n const functionsByName = {};\n for (const f of inputTools) {\n if (f.type === 'function') {\n functionsByName[f.function.name || f.function.function.name] = f.function;\n }\n }\n const tools = 'tools' in params ?\n inputTools.map((t) => t.type === 'function' ?\n {\n type: 'function',\n function: {\n name: t.function.name || t.function.function.name,\n parameters: t.function.parameters,\n description: t.function.description,\n strict: t.function.strict,\n },\n }\n : t)\n : undefined;\n for (const message of params.messages) {\n this._addMessage(message, false);\n }\n for (let i = 0; i < maxChatCompletions; ++i) {\n const chatCompletion = await this._createChatCompletion(client, {\n ...restParams,\n tool_choice,\n tools,\n messages: [...this.messages],\n }, options);\n const message = chatCompletion.choices[0]?.message;\n if (!message) {\n throw new OpenAIError(`missing message in ChatCompletion response`);\n }\n if (!message.tool_calls?.length) {\n return;\n }\n for (const tool_call of message.tool_calls) {\n if (tool_call.type !== 'function')\n continue;\n const tool_call_id = tool_call.id;\n const { name, arguments: args } = tool_call.function;\n const fn = functionsByName[name];\n if (!fn) {\n const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName)\n .map((name) => JSON.stringify(name))\n .join(', ')}. Please try again`;\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n else if (singleFunctionToCall && singleFunctionToCall !== name) {\n const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`;\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n let parsed;\n try {\n parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args;\n }\n catch (error) {\n const content = error instanceof Error ? error.message : String(error);\n this._addMessage({ role, tool_call_id, content });\n continue;\n }\n // @ts-expect-error it can't rule out `never` type.\n const rawContent = await fn.function(parsed, this);\n const content = __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent);\n this._addMessage({ role, tool_call_id, content });\n if (singleFunctionToCall) {\n return;\n }\n }\n }\n return;\n }\n}\n_AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() {\n return __classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, \"m\", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null;\n}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() {\n let i = this.messages.length;\n while (i-- > 0) {\n const message = this.messages[i];\n if (isAssistantMessage(message)) {\n const { function_call, ...rest } = message;\n // TODO: support audio here\n const ret = {\n ...rest,\n content: message.content ?? null,\n refusal: message.refusal ?? null,\n };\n if (function_call) {\n ret.function_call = function_call;\n }\n return ret;\n }\n }\n throw new OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant');\n}, _AbstractChatCompletionRunner_getFinalFunctionCall = function _AbstractChatCompletionRunner_getFinalFunctionCall() {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (isAssistantMessage(message) && message?.function_call) {\n return message.function_call;\n }\n if (isAssistantMessage(message) && message?.tool_calls?.length) {\n return message.tool_calls.at(-1)?.function;\n }\n }\n return;\n}, _AbstractChatCompletionRunner_getFinalFunctionCallResult = function _AbstractChatCompletionRunner_getFinalFunctionCallResult() {\n for (let i = this.messages.length - 1; i >= 0; i--) {\n const message = this.messages[i];\n if (isFunctionMessage(message) && message.content != null) {\n return message.content;\n }\n if (isToolMessage(message) &&\n message.content != null &&\n typeof message.content === 'string' &&\n this.messages.some((x) => x.role === 'assistant' &&\n x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) {\n return message.content;\n }\n }\n return;\n}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() {\n const total = {\n completion_tokens: 0,\n prompt_tokens: 0,\n total_tokens: 0,\n };\n for (const { usage } of this._chatCompletions) {\n if (usage) {\n total.completion_tokens += usage.completion_tokens;\n total.prompt_tokens += usage.prompt_tokens;\n total.total_tokens += usage.total_tokens;\n }\n }\n return total;\n}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) {\n if (params.n != null && params.n > 1) {\n throw new OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.');\n }\n}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) {\n return (typeof rawContent === 'string' ? rawContent\n : rawContent === undefined ? 'undefined'\n : JSON.stringify(rawContent));\n};\n//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map","import { AbstractChatCompletionRunner, } from \"./AbstractChatCompletionRunner.mjs\";\nimport { isAssistantMessage } from \"./chatCompletionUtils.mjs\";\nexport class ChatCompletionRunner extends AbstractChatCompletionRunner {\n /** @deprecated - please use `runTools` instead. */\n static runFunctions(client, params, options) {\n const runner = new ChatCompletionRunner();\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' },\n };\n runner._run(() => runner._runFunctions(client, params, opts));\n return runner;\n }\n static runTools(client, params, options) {\n const runner = new ChatCompletionRunner();\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' },\n };\n runner._run(() => runner._runTools(client, params, opts));\n return runner;\n }\n _addMessage(message, emit = true) {\n super._addMessage(message, emit);\n if (isAssistantMessage(message) && message.content) {\n this._emit('content', message.content);\n }\n }\n}\n//# sourceMappingURL=ChatCompletionRunner.mjs.map","const STR = 0b000000001;\nconst NUM = 0b000000010;\nconst ARR = 0b000000100;\nconst OBJ = 0b000001000;\nconst NULL = 0b000010000;\nconst BOOL = 0b000100000;\nconst NAN = 0b001000000;\nconst INFINITY = 0b010000000;\nconst MINUS_INFINITY = 0b100000000;\nconst INF = INFINITY | MINUS_INFINITY;\nconst SPECIAL = NULL | BOOL | INF | NAN;\nconst ATOM = STR | NUM | SPECIAL;\nconst COLLECTION = ARR | OBJ;\nconst ALL = ATOM | COLLECTION;\nconst Allow = {\n STR,\n NUM,\n ARR,\n OBJ,\n NULL,\n BOOL,\n NAN,\n INFINITY,\n MINUS_INFINITY,\n INF,\n SPECIAL,\n ATOM,\n COLLECTION,\n ALL,\n};\n// The JSON string segment was unable to be parsed completely\nclass PartialJSON extends Error {\n}\nclass MalformedJSON extends Error {\n}\n/**\n * Parse incomplete JSON\n * @param {string} jsonString Partial JSON to be parsed\n * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details\n * @returns The parsed JSON\n * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter)\n * @throws {MalformedJSON} If the JSON is malformed\n */\nfunction parseJSON(jsonString, allowPartial = Allow.ALL) {\n if (typeof jsonString !== 'string') {\n throw new TypeError(`expecting str, got ${typeof jsonString}`);\n }\n if (!jsonString.trim()) {\n throw new Error(`${jsonString} is empty`);\n }\n return _parseJSON(jsonString.trim(), allowPartial);\n}\nconst _parseJSON = (jsonString, allow) => {\n const length = jsonString.length;\n let index = 0;\n const markPartialJSON = (msg) => {\n throw new PartialJSON(`${msg} at position ${index}`);\n };\n const throwMalformedError = (msg) => {\n throw new MalformedJSON(`${msg} at position ${index}`);\n };\n const parseAny = () => {\n skipBlank();\n if (index >= length)\n markPartialJSON('Unexpected end of input');\n if (jsonString[index] === '\"')\n return parseStr();\n if (jsonString[index] === '{')\n return parseObj();\n if (jsonString[index] === '[')\n return parseArr();\n if (jsonString.substring(index, index + 4) === 'null' ||\n (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) {\n index += 4;\n return null;\n }\n if (jsonString.substring(index, index + 4) === 'true' ||\n (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) {\n index += 4;\n return true;\n }\n if (jsonString.substring(index, index + 5) === 'false' ||\n (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) {\n index += 5;\n return false;\n }\n if (jsonString.substring(index, index + 8) === 'Infinity' ||\n (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) {\n index += 8;\n return Infinity;\n }\n if (jsonString.substring(index, index + 9) === '-Infinity' ||\n (Allow.MINUS_INFINITY & allow &&\n 1 < length - index &&\n length - index < 9 &&\n '-Infinity'.startsWith(jsonString.substring(index)))) {\n index += 9;\n return -Infinity;\n }\n if (jsonString.substring(index, index + 3) === 'NaN' ||\n (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) {\n index += 3;\n return NaN;\n }\n return parseNum();\n };\n const parseStr = () => {\n const start = index;\n let escape = false;\n index++; // skip initial quote\n while (index < length && (jsonString[index] !== '\"' || (escape && jsonString[index - 1] === '\\\\'))) {\n escape = jsonString[index] === '\\\\' ? !escape : false;\n index++;\n }\n if (jsonString.charAt(index) == '\"') {\n try {\n return JSON.parse(jsonString.substring(start, ++index - Number(escape)));\n }\n catch (e) {\n throwMalformedError(String(e));\n }\n }\n else if (Allow.STR & allow) {\n try {\n return JSON.parse(jsonString.substring(start, index - Number(escape)) + '\"');\n }\n catch (e) {\n // SyntaxError: Invalid escape sequence\n return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\\\')) + '\"');\n }\n }\n markPartialJSON('Unterminated string literal');\n };\n const parseObj = () => {\n index++; // skip initial brace\n skipBlank();\n const obj = {};\n try {\n while (jsonString[index] !== '}') {\n skipBlank();\n if (index >= length && Allow.OBJ & allow)\n return obj;\n const key = parseStr();\n skipBlank();\n index++; // skip colon\n try {\n const value = parseAny();\n Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true });\n }\n catch (e) {\n if (Allow.OBJ & allow)\n return obj;\n else\n throw e;\n }\n skipBlank();\n if (jsonString[index] === ',')\n index++; // skip comma\n }\n }\n catch (e) {\n if (Allow.OBJ & allow)\n return obj;\n else\n markPartialJSON(\"Expected '}' at end of object\");\n }\n index++; // skip final brace\n return obj;\n };\n const parseArr = () => {\n index++; // skip initial bracket\n const arr = [];\n try {\n while (jsonString[index] !== ']') {\n arr.push(parseAny());\n skipBlank();\n if (jsonString[index] === ',') {\n index++; // skip comma\n }\n }\n }\n catch (e) {\n if (Allow.ARR & allow) {\n return arr;\n }\n markPartialJSON(\"Expected ']' at end of array\");\n }\n index++; // skip final bracket\n return arr;\n };\n const parseNum = () => {\n if (index === 0) {\n if (jsonString === '-' && Allow.NUM & allow)\n markPartialJSON(\"Not sure what '-' is\");\n try {\n return JSON.parse(jsonString);\n }\n catch (e) {\n if (Allow.NUM & allow) {\n try {\n if ('.' === jsonString[jsonString.length - 1])\n return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.')));\n return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e')));\n }\n catch (e) { }\n }\n throwMalformedError(String(e));\n }\n }\n const start = index;\n if (jsonString[index] === '-')\n index++;\n while (jsonString[index] && !',]}'.includes(jsonString[index]))\n index++;\n if (index == length && !(Allow.NUM & allow))\n markPartialJSON('Unterminated number literal');\n try {\n return JSON.parse(jsonString.substring(start, index));\n }\n catch (e) {\n if (jsonString.substring(start, index) === '-' && Allow.NUM & allow)\n markPartialJSON(\"Not sure what '-' is\");\n try {\n return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e')));\n }\n catch (e) {\n throwMalformedError(String(e));\n }\n }\n };\n const skipBlank = () => {\n while (index < length && ' \\n\\r\\t'.includes(jsonString[index])) {\n index++;\n }\n };\n return parseAny();\n};\n// using this function with malformed JSON is undefined behavior\nconst partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM);\nexport { partialParse, PartialJSON, MalformedJSON };\n//# sourceMappingURL=parser.mjs.map","var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion;\nimport { OpenAIError, APIUserAbortError, LengthFinishReasonError, ContentFilterFinishReasonError, } from \"../error.mjs\";\nimport { AbstractChatCompletionRunner, } from \"./AbstractChatCompletionRunner.mjs\";\nimport { Stream } from \"../streaming.mjs\";\nimport { hasAutoParseableInput, isAutoParsableResponseFormat, isAutoParsableTool, maybeParseChatCompletion, shouldParseToolCall, } from \"../lib/parser.mjs\";\nimport { partialParse } from \"../_vendor/partial-json-parser/parser.mjs\";\nexport class ChatCompletionStream extends AbstractChatCompletionRunner {\n constructor(params) {\n super();\n _ChatCompletionStream_instances.add(this);\n _ChatCompletionStream_params.set(this, void 0);\n _ChatCompletionStream_choiceEventStates.set(this, void 0);\n _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0);\n __classPrivateFieldSet(this, _ChatCompletionStream_params, params, \"f\");\n __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], \"f\");\n }\n get currentChatCompletionSnapshot() {\n return __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, \"f\");\n }\n /**\n * Intended for use on the frontend, consuming a stream produced with\n * `.toReadableStream()` on the backend.\n *\n * Note that messages sent to the model do not appear in `.on('message')`\n * in this context.\n */\n static fromReadableStream(stream) {\n const runner = new ChatCompletionStream(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n static createChatCompletion(client, params, options) {\n const runner = new ChatCompletionStream(params);\n runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } }));\n return runner;\n }\n async _createChatCompletion(client, params, options) {\n super._createChatCompletion;\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_beginRequest).call(this);\n const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal });\n this._connected();\n for await (const chunk of stream) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_addChunk).call(this, chunk);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_endRequest).call(this));\n }\n async _fromReadableStream(readableStream, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_beginRequest).call(this);\n this._connected();\n const stream = Stream.fromReadableStream(readableStream, this.controller);\n let chatId;\n for await (const chunk of stream) {\n if (chatId && chatId !== chunk.id) {\n // A new request has been made.\n this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_endRequest).call(this));\n }\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_addChunk).call(this, chunk);\n chatId = chunk.id;\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addChatCompletion(__classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_endRequest).call(this));\n }\n [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, \"f\");\n }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) {\n let state = __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, \"f\")[choice.index];\n if (state) {\n return state;\n }\n state = {\n content_done: false,\n refusal_done: false,\n logprobs_content_done: false,\n logprobs_refusal_done: false,\n done_tool_calls: new Set(),\n current_tool_call_index: null,\n };\n __classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, \"f\")[choice.index] = state;\n return state;\n }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) {\n if (this.ended)\n return;\n const completion = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk);\n this._emit('chunk', chunk, completion);\n for (const choice of chunk.choices) {\n const choiceSnapshot = completion.choices[choice.index];\n if (choice.delta.content != null &&\n choiceSnapshot.message?.role === 'assistant' &&\n choiceSnapshot.message?.content) {\n this._emit('content', choice.delta.content, choiceSnapshot.message.content);\n this._emit('content.delta', {\n delta: choice.delta.content,\n snapshot: choiceSnapshot.message.content,\n parsed: choiceSnapshot.message.parsed,\n });\n }\n if (choice.delta.refusal != null &&\n choiceSnapshot.message?.role === 'assistant' &&\n choiceSnapshot.message?.refusal) {\n this._emit('refusal.delta', {\n delta: choice.delta.refusal,\n snapshot: choiceSnapshot.message.refusal,\n });\n }\n if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') {\n this._emit('logprobs.content.delta', {\n content: choice.logprobs?.content,\n snapshot: choiceSnapshot.logprobs?.content ?? [],\n });\n }\n if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') {\n this._emit('logprobs.refusal.delta', {\n refusal: choice.logprobs?.refusal,\n snapshot: choiceSnapshot.logprobs?.refusal ?? [],\n });\n }\n const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);\n if (choiceSnapshot.finish_reason) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);\n if (state.current_tool_call_index != null) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);\n }\n }\n for (const toolCall of choice.delta.tool_calls ?? []) {\n if (state.current_tool_call_index !== toolCall.index) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot);\n // new tool call started, the previous one is done\n if (state.current_tool_call_index != null) {\n __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index);\n }\n }\n state.current_tool_call_index = toolCall.index;\n }\n for (const toolCallDelta of choice.delta.tool_calls ?? []) {\n const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index];\n if (!toolCallSnapshot?.type) {\n continue;\n }\n if (toolCallSnapshot?.type === 'function') {\n this._emit('tool_calls.function.arguments.delta', {\n name: toolCallSnapshot.function?.name,\n index: toolCallDelta.index,\n arguments: toolCallSnapshot.function.arguments,\n parsed_arguments: toolCallSnapshot.function.parsed_arguments,\n arguments_delta: toolCallDelta.function?.arguments ?? '',\n });\n }\n else {\n assertNever(toolCallSnapshot?.type);\n }\n }\n }\n }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) {\n const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);\n if (state.done_tool_calls.has(toolCallIndex)) {\n // we've already fired the done event\n return;\n }\n const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex];\n if (!toolCallSnapshot) {\n throw new Error('no tool call snapshot');\n }\n if (!toolCallSnapshot.type) {\n throw new Error('tool call snapshot missing `type`');\n }\n if (toolCallSnapshot.type === 'function') {\n const inputTool = __classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\")?.tools?.find((tool) => tool.type === 'function' && tool.function.name === toolCallSnapshot.function.name);\n this._emit('tool_calls.function.arguments.done', {\n name: toolCallSnapshot.function.name,\n index: toolCallIndex,\n arguments: toolCallSnapshot.function.arguments,\n parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments)\n : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments)\n : null,\n });\n }\n else {\n assertNever(toolCallSnapshot.type);\n }\n }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) {\n const state = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot);\n if (choiceSnapshot.message.content && !state.content_done) {\n state.content_done = true;\n const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getAutoParseableResponseFormat).call(this);\n this._emit('content.done', {\n content: choiceSnapshot.message.content,\n parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null,\n });\n }\n if (choiceSnapshot.message.refusal && !state.refusal_done) {\n state.refusal_done = true;\n this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal });\n }\n if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) {\n state.logprobs_content_done = true;\n this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content });\n }\n if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) {\n state.logprobs_refusal_done = true;\n this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal });\n }\n }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n const snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, \"f\");\n if (!snapshot) {\n throw new OpenAIError(`request ended without sending any chunks`);\n }\n __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, \"f\");\n __classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], \"f\");\n return finalizeChatCompletion(snapshot, __classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\"));\n }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() {\n const responseFormat = __classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\")?.response_format;\n if (isAutoParsableResponseFormat(responseFormat)) {\n return responseFormat;\n }\n return null;\n }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) {\n var _a, _b, _c, _d;\n let snapshot = __classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, \"f\");\n const { choices, ...rest } = chunk;\n if (!snapshot) {\n snapshot = __classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, {\n ...rest,\n choices: [],\n }, \"f\");\n }\n else {\n Object.assign(snapshot, rest);\n }\n for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) {\n let choice = snapshot.choices[index];\n if (!choice) {\n choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other };\n }\n if (logprobs) {\n if (!choice.logprobs) {\n choice.logprobs = Object.assign({}, logprobs);\n }\n else {\n const { content, refusal, ...rest } = logprobs;\n assertIsEmpty(rest);\n Object.assign(choice.logprobs, rest);\n if (content) {\n (_a = choice.logprobs).content ?? (_a.content = []);\n choice.logprobs.content.push(...content);\n }\n if (refusal) {\n (_b = choice.logprobs).refusal ?? (_b.refusal = []);\n choice.logprobs.refusal.push(...refusal);\n }\n }\n }\n if (finish_reason) {\n choice.finish_reason = finish_reason;\n if (__classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\") && hasAutoParseableInput(__classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\"))) {\n if (finish_reason === 'length') {\n throw new LengthFinishReasonError();\n }\n if (finish_reason === 'content_filter') {\n throw new ContentFilterFinishReasonError();\n }\n }\n }\n Object.assign(choice, other);\n if (!delta)\n continue; // Shouldn't happen; just in case.\n const { content, refusal, function_call, role, tool_calls, ...rest } = delta;\n assertIsEmpty(rest);\n Object.assign(choice.message, rest);\n if (refusal) {\n choice.message.refusal = (choice.message.refusal || '') + refusal;\n }\n if (role)\n choice.message.role = role;\n if (function_call) {\n if (!choice.message.function_call) {\n choice.message.function_call = function_call;\n }\n else {\n if (function_call.name)\n choice.message.function_call.name = function_call.name;\n if (function_call.arguments) {\n (_c = choice.message.function_call).arguments ?? (_c.arguments = '');\n choice.message.function_call.arguments += function_call.arguments;\n }\n }\n }\n if (content) {\n choice.message.content = (choice.message.content || '') + content;\n if (!choice.message.refusal && __classPrivateFieldGet(this, _ChatCompletionStream_instances, \"m\", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) {\n choice.message.parsed = partialParse(choice.message.content);\n }\n }\n if (tool_calls) {\n if (!choice.message.tool_calls)\n choice.message.tool_calls = [];\n for (const { index, id, type, function: fn, ...rest } of tool_calls) {\n const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {}));\n Object.assign(tool_call, rest);\n if (id)\n tool_call.id = id;\n if (type)\n tool_call.type = type;\n if (fn)\n tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' });\n if (fn?.name)\n tool_call.function.name = fn.name;\n if (fn?.arguments) {\n tool_call.function.arguments += fn.arguments;\n if (shouldParseToolCall(__classPrivateFieldGet(this, _ChatCompletionStream_params, \"f\"), tool_call)) {\n tool_call.function.parsed_arguments = partialParse(tool_call.function.arguments);\n }\n }\n }\n }\n }\n return snapshot;\n }, Symbol.asyncIterator)]() {\n const pushQueue = [];\n const readQueue = [];\n let done = false;\n this.on('chunk', (chunk) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(chunk);\n }\n else {\n pushQueue.push(chunk);\n }\n });\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n return {\n next: async () => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift();\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n toReadableStream() {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n}\nfunction finalizeChatCompletion(snapshot, params) {\n const { id, choices, created, model, system_fingerprint, ...rest } = snapshot;\n const completion = {\n ...rest,\n id,\n choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => {\n if (!finish_reason) {\n throw new OpenAIError(`missing finish_reason for choice ${index}`);\n }\n const { content = null, function_call, tool_calls, ...messageRest } = message;\n const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine.\n if (!role) {\n throw new OpenAIError(`missing role for choice ${index}`);\n }\n if (function_call) {\n const { arguments: args, name } = function_call;\n if (args == null) {\n throw new OpenAIError(`missing function_call.arguments for choice ${index}`);\n }\n if (!name) {\n throw new OpenAIError(`missing function_call.name for choice ${index}`);\n }\n return {\n ...choiceRest,\n message: {\n content,\n function_call: { arguments: args, name },\n role,\n refusal: message.refusal ?? null,\n },\n finish_reason,\n index,\n logprobs,\n };\n }\n if (tool_calls) {\n return {\n ...choiceRest,\n index,\n finish_reason,\n logprobs,\n message: {\n ...messageRest,\n role,\n content,\n refusal: message.refusal ?? null,\n tool_calls: tool_calls.map((tool_call, i) => {\n const { function: fn, type, id, ...toolRest } = tool_call;\n const { arguments: args, name, ...fnRest } = fn || {};\n if (id == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].id\\n${str(snapshot)}`);\n }\n if (type == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].type\\n${str(snapshot)}`);\n }\n if (name == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\\n${str(snapshot)}`);\n }\n if (args == null) {\n throw new OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\\n${str(snapshot)}`);\n }\n return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } };\n }),\n },\n };\n }\n return {\n ...choiceRest,\n message: { ...messageRest, content, role, refusal: message.refusal ?? null },\n finish_reason,\n index,\n logprobs,\n };\n }),\n created,\n model,\n object: 'chat.completion',\n ...(system_fingerprint ? { system_fingerprint } : {}),\n };\n return maybeParseChatCompletion(completion, params);\n}\nfunction str(x) {\n return JSON.stringify(x);\n}\n/**\n * Ensures the given argument is an empty object, useful for\n * asserting that all known properties on an object have been\n * destructured.\n */\nfunction assertIsEmpty(obj) {\n return;\n}\nfunction assertNever(_x) { }\n//# sourceMappingURL=ChatCompletionStream.mjs.map","import { ChatCompletionStream } from \"./ChatCompletionStream.mjs\";\nexport class ChatCompletionStreamingRunner extends ChatCompletionStream {\n static fromReadableStream(stream) {\n const runner = new ChatCompletionStreamingRunner(null);\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n /** @deprecated - please use `runTools` instead. */\n static runFunctions(client, params, options) {\n const runner = new ChatCompletionStreamingRunner(null);\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runFunctions' },\n };\n runner._run(() => runner._runFunctions(client, params, opts));\n return runner;\n }\n static runTools(client, params, options) {\n const runner = new ChatCompletionStreamingRunner(\n // @ts-expect-error TODO these types are incompatible\n params);\n const opts = {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' },\n };\n runner._run(() => runner._runTools(client, params, opts));\n return runner;\n }\n}\n//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { ChatCompletionRunner } from \"../../../lib/ChatCompletionRunner.mjs\";\nimport { ChatCompletionStreamingRunner, } from \"../../../lib/ChatCompletionStreamingRunner.mjs\";\nimport { ChatCompletionStream } from \"../../../lib/ChatCompletionStream.mjs\";\nimport { parseChatCompletion, validateInputTools } from \"../../../lib/parser.mjs\";\nexport { ChatCompletionStreamingRunner, } from \"../../../lib/ChatCompletionStreamingRunner.mjs\";\nexport { ParsingFunction, ParsingToolFunction, } from \"../../../lib/RunnableFunction.mjs\";\nexport { ChatCompletionStream } from \"../../../lib/ChatCompletionStream.mjs\";\nexport { ChatCompletionRunner, } from \"../../../lib/ChatCompletionRunner.mjs\";\nexport class Completions extends APIResource {\n parse(body, options) {\n validateInputTools(body.tools);\n return this._client.chat.completions\n .create(body, {\n ...options,\n headers: {\n ...options?.headers,\n 'X-Stainless-Helper-Method': 'beta.chat.completions.parse',\n },\n })\n ._thenUnwrap((completion) => parseChatCompletion(completion, body));\n }\n runFunctions(body, options) {\n if (body.stream) {\n return ChatCompletionStreamingRunner.runFunctions(this._client, body, options);\n }\n return ChatCompletionRunner.runFunctions(this._client, body, options);\n }\n runTools(body, options) {\n if (body.stream) {\n return ChatCompletionStreamingRunner.runTools(this._client, body, options);\n }\n return ChatCompletionRunner.runTools(this._client, body, options);\n }\n /**\n * Creates a chat completion stream\n */\n stream(body, options) {\n return ChatCompletionStream.createChatCompletion(this._client, body, options);\n }\n}\n//# sourceMappingURL=completions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport * as CompletionsAPI from \"./completions.mjs\";\nexport class Chat extends APIResource {\n constructor() {\n super(...arguments);\n this.completions = new CompletionsAPI.Completions(this._client);\n }\n}\n(function (Chat) {\n Chat.Completions = CompletionsAPI.Completions;\n})(Chat || (Chat = {}));\n//# sourceMappingURL=chat.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nexport class Sessions extends APIResource {\n /**\n * Create an ephemeral API token for use in client-side applications with the\n * Realtime API. Can be configured with the same session parameters as the\n * `session.update` client event.\n *\n * It responds with a session object, plus a `client_secret` key which contains a\n * usable ephemeral API token that can be used to authenticate browser clients for\n * the Realtime API.\n */\n create(body, options) {\n return this._client.post('/realtime/sessions', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\n//# sourceMappingURL=sessions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport * as SessionsAPI from \"./sessions.mjs\";\nimport { Sessions, } from \"./sessions.mjs\";\nexport class Realtime extends APIResource {\n constructor() {\n super(...arguments);\n this.sessions = new SessionsAPI.Sessions(this._client);\n }\n}\nRealtime.Sessions = Sessions;\n//# sourceMappingURL=realtime.mjs.map","var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\n};\nvar __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) {\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\n};\nvar _AssistantStream_instances, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun;\nimport * as Core from \"../core.mjs\";\nimport { Stream } from \"../streaming.mjs\";\nimport { APIUserAbortError, OpenAIError } from \"../error.mjs\";\nimport { EventStream } from \"./EventStream.mjs\";\nexport class AssistantStream extends EventStream {\n constructor() {\n super(...arguments);\n _AssistantStream_instances.add(this);\n //Track all events in a single list for reference\n _AssistantStream_events.set(this, []);\n //Used to accumulate deltas\n //We are accumulating many types so the value here is not strict\n _AssistantStream_runStepSnapshots.set(this, {});\n _AssistantStream_messageSnapshots.set(this, {});\n _AssistantStream_messageSnapshot.set(this, void 0);\n _AssistantStream_finalRun.set(this, void 0);\n _AssistantStream_currentContentIndex.set(this, void 0);\n _AssistantStream_currentContent.set(this, void 0);\n _AssistantStream_currentToolCallIndex.set(this, void 0);\n _AssistantStream_currentToolCall.set(this, void 0);\n //For current snapshot methods\n _AssistantStream_currentEvent.set(this, void 0);\n _AssistantStream_currentRunSnapshot.set(this, void 0);\n _AssistantStream_currentRunStepSnapshot.set(this, void 0);\n }\n [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() {\n const pushQueue = [];\n const readQueue = [];\n let done = false;\n //Catch all for passing along all events\n this.on('event', (event) => {\n const reader = readQueue.shift();\n if (reader) {\n reader.resolve(event);\n }\n else {\n pushQueue.push(event);\n }\n });\n this.on('end', () => {\n done = true;\n for (const reader of readQueue) {\n reader.resolve(undefined);\n }\n readQueue.length = 0;\n });\n this.on('abort', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n this.on('error', (err) => {\n done = true;\n for (const reader of readQueue) {\n reader.reject(err);\n }\n readQueue.length = 0;\n });\n return {\n next: async () => {\n if (!pushQueue.length) {\n if (done) {\n return { value: undefined, done: true };\n }\n return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true }));\n }\n const chunk = pushQueue.shift();\n return { value: chunk, done: false };\n },\n return: async () => {\n this.abort();\n return { value: undefined, done: true };\n },\n };\n }\n static fromReadableStream(stream) {\n const runner = new AssistantStream();\n runner._run(() => runner._fromReadableStream(stream));\n return runner;\n }\n async _fromReadableStream(readableStream, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n this._connected();\n const stream = Stream.fromReadableStream(readableStream, this.controller);\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n toReadableStream() {\n const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller);\n return stream.toReadableStream();\n }\n static createToolAssistantStream(threadId, runId, runs, params, options) {\n const runner = new AssistantStream();\n runner._run(() => runner._runToolAssistantStream(threadId, runId, runs, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n async _createToolAssistantStream(run, threadId, runId, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n const body = { ...params, stream: true };\n const stream = await run.submitToolOutputs(threadId, runId, body, {\n ...options,\n signal: this.controller.signal,\n });\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n static createThreadAssistantStream(params, thread, options) {\n const runner = new AssistantStream();\n runner._run(() => runner._threadAssistantStream(params, thread, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n static createAssistantStream(threadId, runs, params, options) {\n const runner = new AssistantStream();\n runner._run(() => runner._runAssistantStream(threadId, runs, params, {\n ...options,\n headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' },\n }));\n return runner;\n }\n currentEvent() {\n return __classPrivateFieldGet(this, _AssistantStream_currentEvent, \"f\");\n }\n currentRun() {\n return __classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, \"f\");\n }\n currentMessageSnapshot() {\n return __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\");\n }\n currentRunStepSnapshot() {\n return __classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, \"f\");\n }\n async finalRunSteps() {\n await this.done();\n return Object.values(__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\"));\n }\n async finalMessages() {\n await this.done();\n return Object.values(__classPrivateFieldGet(this, _AssistantStream_messageSnapshots, \"f\"));\n }\n async finalRun() {\n await this.done();\n if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\"))\n throw Error('Final run was not received.');\n return __classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\");\n }\n async _createThreadAssistantStream(thread, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n const body = { ...params, stream: true };\n const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal });\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n async _createAssistantStream(run, threadId, params, options) {\n const signal = options?.signal;\n if (signal) {\n if (signal.aborted)\n this.controller.abort();\n signal.addEventListener('abort', () => this.controller.abort());\n }\n const body = { ...params, stream: true };\n const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal });\n this._connected();\n for await (const event of stream) {\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_addEvent).call(this, event);\n }\n if (stream.controller.signal?.aborted) {\n throw new APIUserAbortError();\n }\n return this._addRun(__classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_endRequest).call(this));\n }\n static accumulateDelta(acc, delta) {\n for (const [key, deltaValue] of Object.entries(delta)) {\n if (!acc.hasOwnProperty(key)) {\n acc[key] = deltaValue;\n continue;\n }\n let accValue = acc[key];\n if (accValue === null || accValue === undefined) {\n acc[key] = deltaValue;\n continue;\n }\n // We don't accumulate these special properties\n if (key === 'index' || key === 'type') {\n acc[key] = deltaValue;\n continue;\n }\n // Type-specific accumulation logic\n if (typeof accValue === 'string' && typeof deltaValue === 'string') {\n accValue += deltaValue;\n }\n else if (typeof accValue === 'number' && typeof deltaValue === 'number') {\n accValue += deltaValue;\n }\n else if (Core.isObj(accValue) && Core.isObj(deltaValue)) {\n accValue = this.accumulateDelta(accValue, deltaValue);\n }\n else if (Array.isArray(accValue) && Array.isArray(deltaValue)) {\n if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) {\n accValue.push(...deltaValue); // Use spread syntax for efficient addition\n continue;\n }\n for (const deltaEntry of deltaValue) {\n if (!Core.isObj(deltaEntry)) {\n throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`);\n }\n const index = deltaEntry['index'];\n if (index == null) {\n console.error(deltaEntry);\n throw new Error('Expected array delta entry to have an `index` property');\n }\n if (typeof index !== 'number') {\n throw new Error(`Expected array delta entry \\`index\\` property to be a number but got ${index}`);\n }\n const accEntry = accValue[index];\n if (accEntry == null) {\n accValue.push(deltaEntry);\n }\n else {\n accValue[index] = this.accumulateDelta(accEntry, deltaEntry);\n }\n }\n continue;\n }\n else {\n throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`);\n }\n acc[key] = accValue;\n }\n return acc;\n }\n _addRun(run) {\n return run;\n }\n async _threadAssistantStream(params, thread, options) {\n return await this._createThreadAssistantStream(thread, params, options);\n }\n async _runAssistantStream(threadId, runs, params, options) {\n return await this._createAssistantStream(runs, threadId, params, options);\n }\n async _runToolAssistantStream(threadId, runId, runs, params, options) {\n return await this._createToolAssistantStream(runs, threadId, runId, params, options);\n }\n}\n_AssistantStream_addEvent = function _AssistantStream_addEvent(event) {\n if (this.ended)\n return;\n __classPrivateFieldSet(this, _AssistantStream_currentEvent, event, \"f\");\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleEvent).call(this, event);\n switch (event.event) {\n case 'thread.created':\n //No action on this event.\n break;\n case 'thread.run.created':\n case 'thread.run.queued':\n case 'thread.run.in_progress':\n case 'thread.run.requires_action':\n case 'thread.run.completed':\n case 'thread.run.failed':\n case 'thread.run.cancelling':\n case 'thread.run.cancelled':\n case 'thread.run.expired':\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleRun).call(this, event);\n break;\n case 'thread.run.step.created':\n case 'thread.run.step.in_progress':\n case 'thread.run.step.delta':\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleRunStep).call(this, event);\n break;\n case 'thread.message.created':\n case 'thread.message.in_progress':\n case 'thread.message.delta':\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_handleMessage).call(this, event);\n break;\n case 'error':\n //This is included for completeness, but errors are processed in the SSE event processing so this should not occur\n throw new Error('Encountered an error event in event processing - errors should be processed earlier');\n }\n}, _AssistantStream_endRequest = function _AssistantStream_endRequest() {\n if (this.ended) {\n throw new OpenAIError(`stream has ended, this shouldn't happen`);\n }\n if (!__classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\"))\n throw Error('Final run has not been received');\n return __classPrivateFieldGet(this, _AssistantStream_finalRun, \"f\");\n}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) {\n const [accumulatedMessage, newContent] = __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_accumulateMessage).call(this, event, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, \"f\");\n __classPrivateFieldGet(this, _AssistantStream_messageSnapshots, \"f\")[accumulatedMessage.id] = accumulatedMessage;\n for (const content of newContent) {\n const snapshotContent = accumulatedMessage.content[content.index];\n if (snapshotContent?.type == 'text') {\n this._emit('textCreated', snapshotContent.text);\n }\n }\n switch (event.event) {\n case 'thread.message.created':\n this._emit('messageCreated', event.data);\n break;\n case 'thread.message.in_progress':\n break;\n case 'thread.message.delta':\n this._emit('messageDelta', event.data.delta, accumulatedMessage);\n if (event.data.delta.content) {\n for (const content of event.data.delta.content) {\n //If it is text delta, emit a text delta event\n if (content.type == 'text' && content.text) {\n let textDelta = content.text;\n let snapshot = accumulatedMessage.content[content.index];\n if (snapshot && snapshot.type == 'text') {\n this._emit('textDelta', textDelta, snapshot.text);\n }\n else {\n throw Error('The snapshot associated with this text delta is not text or missing');\n }\n }\n if (content.index != __classPrivateFieldGet(this, _AssistantStream_currentContentIndex, \"f\")) {\n //See if we have in progress content\n if (__classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\")) {\n switch (__classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\").type) {\n case 'text':\n this._emit('textDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\").text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n case 'image_file':\n this._emit('imageFileDone', __classPrivateFieldGet(this, _AssistantStream_currentContent, \"f\").image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n }\n }\n __classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, \"f\");\n }\n __classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], \"f\");\n }\n }\n break;\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n //We emit the latest content we were working on on completion (including incomplete)\n if (__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, \"f\") !== undefined) {\n const currentContent = event.data.content[__classPrivateFieldGet(this, _AssistantStream_currentContentIndex, \"f\")];\n if (currentContent) {\n switch (currentContent.type) {\n case 'image_file':\n this._emit('imageFileDone', currentContent.image_file, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n case 'text':\n this._emit('textDone', currentContent.text, __classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\"));\n break;\n }\n }\n }\n if (__classPrivateFieldGet(this, _AssistantStream_messageSnapshot, \"f\")) {\n this._emit('messageDone', event.data);\n }\n __classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, \"f\");\n }\n}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) {\n const accumulatedRunStep = __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_accumulateRunStep).call(this, event);\n __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, \"f\");\n switch (event.event) {\n case 'thread.run.step.created':\n this._emit('runStepCreated', event.data);\n break;\n case 'thread.run.step.delta':\n const delta = event.data.delta;\n if (delta.step_details &&\n delta.step_details.type == 'tool_calls' &&\n delta.step_details.tool_calls &&\n accumulatedRunStep.step_details.type == 'tool_calls') {\n for (const toolCall of delta.step_details.tool_calls) {\n if (toolCall.index == __classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, \"f\")) {\n this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]);\n }\n else {\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\")) {\n this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n }\n __classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, \"f\");\n __classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], \"f\");\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"))\n this._emit('toolCallCreated', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n }\n }\n }\n this._emit('runStepDelta', event.data.delta, accumulatedRunStep);\n break;\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n __classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, \"f\");\n const details = event.data.step_details;\n if (details.type == 'tool_calls') {\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\")) {\n this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, \"f\");\n }\n }\n this._emit('runStepDone', event.data, accumulatedRunStep);\n break;\n case 'thread.run.step.in_progress':\n break;\n }\n}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) {\n __classPrivateFieldGet(this, _AssistantStream_events, \"f\").push(event);\n this._emit('event', event);\n}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) {\n switch (event.event) {\n case 'thread.run.step.created':\n __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id] = event.data;\n return event.data;\n case 'thread.run.step.delta':\n let snapshot = __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id];\n if (!snapshot) {\n throw Error('Received a RunStepDelta before creation of a snapshot');\n }\n let data = event.data;\n if (data.delta) {\n const accumulated = AssistantStream.accumulateDelta(snapshot, data.delta);\n __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id] = accumulated;\n }\n return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id];\n case 'thread.run.step.completed':\n case 'thread.run.step.failed':\n case 'thread.run.step.cancelled':\n case 'thread.run.step.expired':\n case 'thread.run.step.in_progress':\n __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id] = event.data;\n break;\n }\n if (__classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id])\n return __classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, \"f\")[event.data.id];\n throw new Error('No snapshot available');\n}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) {\n let newContent = [];\n switch (event.event) {\n case 'thread.message.created':\n //On creation the snapshot is just the initial message\n return [event.data, newContent];\n case 'thread.message.delta':\n if (!snapshot) {\n throw Error('Received a delta with no existing snapshot (there should be one from message creation)');\n }\n let data = event.data;\n //If this delta does not have content, nothing to process\n if (data.delta.content) {\n for (const contentElement of data.delta.content) {\n if (contentElement.index in snapshot.content) {\n let currentContent = snapshot.content[contentElement.index];\n snapshot.content[contentElement.index] = __classPrivateFieldGet(this, _AssistantStream_instances, \"m\", _AssistantStream_accumulateContent).call(this, contentElement, currentContent);\n }\n else {\n snapshot.content[contentElement.index] = contentElement;\n // This is a new element\n newContent.push(contentElement);\n }\n }\n }\n return [snapshot, newContent];\n case 'thread.message.in_progress':\n case 'thread.message.completed':\n case 'thread.message.incomplete':\n //No changes on other thread events\n if (snapshot) {\n return [snapshot, newContent];\n }\n else {\n throw Error('Received thread message event with no existing snapshot');\n }\n }\n throw Error('Tried to accumulate a non-message event');\n}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) {\n return AssistantStream.accumulateDelta(currentContent, contentElement);\n}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) {\n __classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, \"f\");\n switch (event.event) {\n case 'thread.run.created':\n break;\n case 'thread.run.queued':\n break;\n case 'thread.run.in_progress':\n break;\n case 'thread.run.requires_action':\n case 'thread.run.cancelled':\n case 'thread.run.failed':\n case 'thread.run.completed':\n case 'thread.run.expired':\n __classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, \"f\");\n if (__classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\")) {\n this._emit('toolCallDone', __classPrivateFieldGet(this, _AssistantStream_currentToolCall, \"f\"));\n __classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, \"f\");\n }\n break;\n case 'thread.run.cancelling':\n break;\n }\n};\n//# sourceMappingURL=AssistantStream.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class Messages extends APIResource {\n /**\n * Create a message.\n */\n create(threadId, body, options) {\n return this._client.post(`/threads/${threadId}/messages`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieve a message.\n */\n retrieve(threadId, messageId, options) {\n return this._client.get(`/threads/${threadId}/messages/${messageId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies a message.\n */\n update(threadId, messageId, body, options) {\n return this._client.post(`/threads/${threadId}/messages/${messageId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(threadId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(threadId, {}, query);\n }\n return this._client.getAPIList(`/threads/${threadId}/messages`, MessagesPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Deletes a message.\n */\n del(threadId, messageId, options) {\n return this._client.delete(`/threads/${threadId}/messages/${messageId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\nexport class MessagesPage extends CursorPage {\n}\nMessages.MessagesPage = MessagesPage;\n//# sourceMappingURL=messages.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../../core.mjs\";\nimport { CursorPage } from \"../../../../pagination.mjs\";\nexport class Steps extends APIResource {\n retrieve(threadId, runId, stepId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.retrieve(threadId, runId, stepId, {}, query);\n }\n return this._client.get(`/threads/${threadId}/runs/${runId}/steps/${stepId}`, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(threadId, runId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(threadId, runId, {}, query);\n }\n return this._client.getAPIList(`/threads/${threadId}/runs/${runId}/steps`, RunStepsPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\nexport class RunStepsPage extends CursorPage {\n}\nSteps.RunStepsPage = RunStepsPage;\n//# sourceMappingURL=steps.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../../core.mjs\";\nimport { AssistantStream } from \"../../../../lib/AssistantStream.mjs\";\nimport { sleep } from \"../../../../core.mjs\";\nimport * as StepsAPI from \"./steps.mjs\";\nimport { RunStepsPage, Steps, } from \"./steps.mjs\";\nimport { CursorPage } from \"../../../../pagination.mjs\";\nexport class Runs extends APIResource {\n constructor() {\n super(...arguments);\n this.steps = new StepsAPI.Steps(this._client);\n }\n create(threadId, params, options) {\n const { include, ...body } = params;\n return this._client.post(`/threads/${threadId}/runs`, {\n query: { include },\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n stream: params.stream ?? false,\n });\n }\n /**\n * Retrieves a run.\n */\n retrieve(threadId, runId, options) {\n return this._client.get(`/threads/${threadId}/runs/${runId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies a run.\n */\n update(threadId, runId, body, options) {\n return this._client.post(`/threads/${threadId}/runs/${runId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(threadId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(threadId, {}, query);\n }\n return this._client.getAPIList(`/threads/${threadId}/runs`, RunsPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Cancels a run that is `in_progress`.\n */\n cancel(threadId, runId, options) {\n return this._client.post(`/threads/${threadId}/runs/${runId}/cancel`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * A helper to create a run an poll for a terminal state. More information on Run\n * lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async createAndPoll(threadId, body, options) {\n const run = await this.create(threadId, body, options);\n return await this.poll(threadId, run.id, options);\n }\n /**\n * Create a Run stream\n *\n * @deprecated use `stream` instead\n */\n createAndStream(threadId, body, options) {\n return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);\n }\n /**\n * A helper to poll a run status until it reaches a terminal state. More\n * information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async poll(threadId, runId, options) {\n const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };\n if (options?.pollIntervalMs) {\n headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();\n }\n while (true) {\n const { data: run, response } = await this.retrieve(threadId, runId, {\n ...options,\n headers: { ...options?.headers, ...headers },\n }).withResponse();\n switch (run.status) {\n //If we are in any sort of intermediate state we poll\n case 'queued':\n case 'in_progress':\n case 'cancelling':\n let sleepInterval = 5000;\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n }\n else {\n const headerInterval = response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n //We return the run in any terminal state.\n case 'requires_action':\n case 'incomplete':\n case 'cancelled':\n case 'completed':\n case 'failed':\n case 'expired':\n return run;\n }\n }\n }\n /**\n * Create a Run stream\n */\n stream(threadId, body, options) {\n return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options);\n }\n submitToolOutputs(threadId, runId, body, options) {\n return this._client.post(`/threads/${threadId}/runs/${runId}/submit_tool_outputs`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n stream: body.stream ?? false,\n });\n }\n /**\n * A helper to submit a tool output to a run and poll for a terminal run state.\n * More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async submitToolOutputsAndPoll(threadId, runId, body, options) {\n const run = await this.submitToolOutputs(threadId, runId, body, options);\n return await this.poll(threadId, run.id, options);\n }\n /**\n * Submit the tool outputs from a previous run and stream the run to a terminal\n * state. More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n submitToolOutputsStream(threadId, runId, body, options) {\n return AssistantStream.createToolAssistantStream(threadId, runId, this._client.beta.threads.runs, body, options);\n }\n}\nexport class RunsPage extends CursorPage {\n}\nRuns.RunsPage = RunsPage;\nRuns.Steps = Steps;\nRuns.RunStepsPage = RunStepsPage;\n//# sourceMappingURL=runs.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport { AssistantStream } from \"../../../lib/AssistantStream.mjs\";\nimport * as MessagesAPI from \"./messages.mjs\";\nimport { Messages, MessagesPage, } from \"./messages.mjs\";\nimport * as RunsAPI from \"./runs/runs.mjs\";\nimport { Runs, RunsPage, } from \"./runs/runs.mjs\";\nexport class Threads extends APIResource {\n constructor() {\n super(...arguments);\n this.runs = new RunsAPI.Runs(this._client);\n this.messages = new MessagesAPI.Messages(this._client);\n }\n create(body = {}, options) {\n if (isRequestOptions(body)) {\n return this.create({}, body);\n }\n return this._client.post('/threads', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves a thread.\n */\n retrieve(threadId, options) {\n return this._client.get(`/threads/${threadId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies a thread.\n */\n update(threadId, body, options) {\n return this._client.post(`/threads/${threadId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Delete a thread.\n */\n del(threadId, options) {\n return this._client.delete(`/threads/${threadId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n createAndRun(body, options) {\n return this._client.post('/threads/runs', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n stream: body.stream ?? false,\n });\n }\n /**\n * A helper to create a thread, start a run and then poll for a terminal state.\n * More information on Run lifecycles can be found here:\n * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps\n */\n async createAndRunPoll(body, options) {\n const run = await this.createAndRun(body, options);\n return await this.runs.poll(run.thread_id, run.id, options);\n }\n /**\n * Create a thread and stream the run back\n */\n createAndRunStream(body, options) {\n return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options);\n }\n}\nThreads.Runs = Runs;\nThreads.RunsPage = RunsPage;\nThreads.Messages = Messages;\nThreads.MessagesPage = MessagesPage;\n//# sourceMappingURL=threads.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { sleep, isRequestOptions } from \"../../../core.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class Files extends APIResource {\n /**\n * Create a vector store file by attaching a\n * [File](https://platform.openai.com/docs/api-reference/files) to a\n * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object).\n */\n create(vectorStoreId, body, options) {\n return this._client.post(`/vector_stores/${vectorStoreId}/files`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves a vector store file.\n */\n retrieve(vectorStoreId, fileId, options) {\n return this._client.get(`/vector_stores/${vectorStoreId}/files/${fileId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(vectorStoreId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(vectorStoreId, {}, query);\n }\n return this._client.getAPIList(`/vector_stores/${vectorStoreId}/files`, VectorStoreFilesPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Delete a vector store file. This will remove the file from the vector store but\n * the file itself will not be deleted. To delete the file, use the\n * [delete file](https://platform.openai.com/docs/api-reference/files/delete)\n * endpoint.\n */\n del(vectorStoreId, fileId, options) {\n return this._client.delete(`/vector_stores/${vectorStoreId}/files/${fileId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Attach a file to the given vector store and wait for it to be processed.\n */\n async createAndPoll(vectorStoreId, body, options) {\n const file = await this.create(vectorStoreId, body, options);\n return await this.poll(vectorStoreId, file.id, options);\n }\n /**\n * Wait for the vector store file to finish processing.\n *\n * Note: this will return even if the file failed to process, you need to check\n * file.last_error and file.status to handle these cases\n */\n async poll(vectorStoreId, fileId, options) {\n const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };\n if (options?.pollIntervalMs) {\n headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();\n }\n while (true) {\n const fileResponse = await this.retrieve(vectorStoreId, fileId, {\n ...options,\n headers,\n }).withResponse();\n const file = fileResponse.data;\n switch (file.status) {\n case 'in_progress':\n let sleepInterval = 5000;\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n }\n else {\n const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n case 'failed':\n case 'completed':\n return file;\n }\n }\n }\n /**\n * Upload a file to the `files` API and then attach it to the given vector store.\n *\n * Note the file will be asynchronously processed (you can use the alternative\n * polling helper method to wait for processing to complete).\n */\n async upload(vectorStoreId, file, options) {\n const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options);\n return this.create(vectorStoreId, { file_id: fileInfo.id }, options);\n }\n /**\n * Add a file to a vector store and poll until processing is complete.\n */\n async uploadAndPoll(vectorStoreId, file, options) {\n const fileInfo = await this.upload(vectorStoreId, file, options);\n return await this.poll(vectorStoreId, fileInfo.id, options);\n }\n}\nexport class VectorStoreFilesPage extends CursorPage {\n}\nFiles.VectorStoreFilesPage = VectorStoreFilesPage;\n//# sourceMappingURL=files.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport { sleep } from \"../../../core.mjs\";\nimport { allSettledWithThrow } from \"../../../lib/Util.mjs\";\nimport { VectorStoreFilesPage } from \"./files.mjs\";\nexport class FileBatches extends APIResource {\n /**\n * Create a vector store file batch.\n */\n create(vectorStoreId, body, options) {\n return this._client.post(`/vector_stores/${vectorStoreId}/file_batches`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves a vector store file batch.\n */\n retrieve(vectorStoreId, batchId, options) {\n return this._client.get(`/vector_stores/${vectorStoreId}/file_batches/${batchId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Cancel a vector store file batch. This attempts to cancel the processing of\n * files in this batch as soon as possible.\n */\n cancel(vectorStoreId, batchId, options) {\n return this._client.post(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/cancel`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Create a vector store batch and poll until all files have been processed.\n */\n async createAndPoll(vectorStoreId, body, options) {\n const batch = await this.create(vectorStoreId, body);\n return await this.poll(vectorStoreId, batch.id, options);\n }\n listFiles(vectorStoreId, batchId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.listFiles(vectorStoreId, batchId, {}, query);\n }\n return this._client.getAPIList(`/vector_stores/${vectorStoreId}/file_batches/${batchId}/files`, VectorStoreFilesPage, { query, ...options, headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers } });\n }\n /**\n * Wait for the given file batch to be processed.\n *\n * Note: this will return even if one of the files failed to process, you need to\n * check batch.file_counts.failed_count to handle this case.\n */\n async poll(vectorStoreId, batchId, options) {\n const headers = { ...options?.headers, 'X-Stainless-Poll-Helper': 'true' };\n if (options?.pollIntervalMs) {\n headers['X-Stainless-Custom-Poll-Interval'] = options.pollIntervalMs.toString();\n }\n while (true) {\n const { data: batch, response } = await this.retrieve(vectorStoreId, batchId, {\n ...options,\n headers,\n }).withResponse();\n switch (batch.status) {\n case 'in_progress':\n let sleepInterval = 5000;\n if (options?.pollIntervalMs) {\n sleepInterval = options.pollIntervalMs;\n }\n else {\n const headerInterval = response.headers.get('openai-poll-after-ms');\n if (headerInterval) {\n const headerIntervalMs = parseInt(headerInterval);\n if (!isNaN(headerIntervalMs)) {\n sleepInterval = headerIntervalMs;\n }\n }\n }\n await sleep(sleepInterval);\n break;\n case 'failed':\n case 'cancelled':\n case 'completed':\n return batch;\n }\n }\n }\n /**\n * Uploads the given files concurrently and then creates a vector store file batch.\n *\n * The concurrency limit is configurable using the `maxConcurrency` parameter.\n */\n async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) {\n if (files == null || files.length == 0) {\n throw new Error(`No \\`files\\` provided to process. If you've already uploaded files you should use \\`.createAndPoll()\\` instead`);\n }\n const configuredConcurrency = options?.maxConcurrency ?? 5;\n // We cap the number of workers at the number of files (so we don't start any unnecessary workers)\n const concurrencyLimit = Math.min(configuredConcurrency, files.length);\n const client = this._client;\n const fileIterator = files.values();\n const allFileIds = [...fileIds];\n // This code is based on this design. The libraries don't accommodate our environment limits.\n // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all\n async function processFiles(iterator) {\n for (let item of iterator) {\n const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options);\n allFileIds.push(fileObj.id);\n }\n }\n // Start workers to process results\n const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles);\n // Wait for all processing to complete.\n await allSettledWithThrow(workers);\n return await this.createAndPoll(vectorStoreId, {\n file_ids: allFileIds,\n });\n }\n}\nexport { VectorStoreFilesPage };\n//# sourceMappingURL=file-batches.mjs.map","/**\n * Like `Promise.allSettled()` but throws an error if any promises are rejected.\n */\nexport const allSettledWithThrow = async (promises) => {\n const results = await Promise.allSettled(promises);\n const rejected = results.filter((result) => result.status === 'rejected');\n if (rejected.length) {\n for (const result of rejected) {\n console.error(result.reason);\n }\n throw new Error(`${rejected.length} promise(s) failed - see the above errors`);\n }\n // Note: TS was complaining about using `.filter().map()` here for some reason\n const values = [];\n for (const result of results) {\n if (result.status === 'fulfilled') {\n values.push(result.value);\n }\n }\n return values;\n};\n//# sourceMappingURL=Util.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport * as FileBatchesAPI from \"./file-batches.mjs\";\nimport { FileBatches, } from \"./file-batches.mjs\";\nimport * as FilesAPI from \"./files.mjs\";\nimport { Files, VectorStoreFilesPage, } from \"./files.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class VectorStores extends APIResource {\n constructor() {\n super(...arguments);\n this.files = new FilesAPI.Files(this._client);\n this.fileBatches = new FileBatchesAPI.FileBatches(this._client);\n }\n /**\n * Create a vector store.\n */\n create(body, options) {\n return this._client.post('/vector_stores', {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Retrieves a vector store.\n */\n retrieve(vectorStoreId, options) {\n return this._client.get(`/vector_stores/${vectorStoreId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Modifies a vector store.\n */\n update(vectorStoreId, body, options) {\n return this._client.post(`/vector_stores/${vectorStoreId}`, {\n body,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/vector_stores', VectorStoresPage, {\n query,\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n /**\n * Delete a vector store.\n */\n del(vectorStoreId, options) {\n return this._client.delete(`/vector_stores/${vectorStoreId}`, {\n ...options,\n headers: { 'OpenAI-Beta': 'assistants=v2', ...options?.headers },\n });\n }\n}\nexport class VectorStoresPage extends CursorPage {\n}\nVectorStores.VectorStoresPage = VectorStoresPage;\nVectorStores.Files = Files;\nVectorStores.VectorStoreFilesPage = VectorStoreFilesPage;\nVectorStores.FileBatches = FileBatches;\n//# sourceMappingURL=vector-stores.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as AssistantsAPI from \"./assistants.mjs\";\nimport * as ChatAPI from \"./chat/chat.mjs\";\nimport { Assistants, AssistantsPage, } from \"./assistants.mjs\";\nimport * as RealtimeAPI from \"./realtime/realtime.mjs\";\nimport { Realtime } from \"./realtime/realtime.mjs\";\nimport * as ThreadsAPI from \"./threads/threads.mjs\";\nimport { Threads, } from \"./threads/threads.mjs\";\nimport * as VectorStoresAPI from \"./vector-stores/vector-stores.mjs\";\nimport { VectorStores, VectorStoresPage, } from \"./vector-stores/vector-stores.mjs\";\nimport { Chat } from \"./chat/chat.mjs\";\nexport class Beta extends APIResource {\n constructor() {\n super(...arguments);\n this.realtime = new RealtimeAPI.Realtime(this._client);\n this.vectorStores = new VectorStoresAPI.VectorStores(this._client);\n this.chat = new ChatAPI.Chat(this._client);\n this.assistants = new AssistantsAPI.Assistants(this._client);\n this.threads = new ThreadsAPI.Threads(this._client);\n }\n}\nBeta.Realtime = Realtime;\nBeta.VectorStores = VectorStores;\nBeta.VectorStoresPage = VectorStoresPage;\nBeta.Assistants = Assistants;\nBeta.AssistantsPage = AssistantsPage;\nBeta.Threads = Threads;\n//# sourceMappingURL=beta.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nexport class Completions extends APIResource {\n create(body, options) {\n return this._client.post('/completions', { body, ...options, stream: body.stream ?? false });\n }\n}\n//# sourceMappingURL=completions.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nexport class Embeddings extends APIResource {\n /**\n * Creates an embedding vector representing the input text.\n */\n create(body, options) {\n return this._client.post('/embeddings', { body, ...options });\n }\n}\n//# sourceMappingURL=embeddings.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nimport { isRequestOptions } from \"../core.mjs\";\nimport { sleep } from \"../core.mjs\";\nimport { APIConnectionTimeoutError } from \"../error.mjs\";\nimport * as Core from \"../core.mjs\";\nimport { CursorPage } from \"../pagination.mjs\";\nexport class Files extends APIResource {\n /**\n * Upload a file that can be used across various endpoints. Individual files can be\n * up to 512 MB, and the size of all files uploaded by one organization can be up\n * to 100 GB.\n *\n * The Assistants API supports files up to 2 million tokens and of specific file\n * types. See the\n * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) for\n * details.\n *\n * The Fine-tuning API only supports `.jsonl` files. The input also has certain\n * required formats for fine-tuning\n * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) or\n * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input)\n * models.\n *\n * The Batch API only supports `.jsonl` files up to 200 MB in size. The input also\n * has a specific required\n * [format](https://platform.openai.com/docs/api-reference/batch/request-input).\n *\n * Please [contact us](https://help.openai.com/) if you need to increase these\n * storage limits.\n */\n create(body, options) {\n return this._client.post('/files', Core.multipartFormRequestOptions({ body, ...options }));\n }\n /**\n * Returns information about a specific file.\n */\n retrieve(fileId, options) {\n return this._client.get(`/files/${fileId}`, options);\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/files', FileObjectsPage, { query, ...options });\n }\n /**\n * Delete a file.\n */\n del(fileId, options) {\n return this._client.delete(`/files/${fileId}`, options);\n }\n /**\n * Returns the contents of the specified file.\n */\n content(fileId, options) {\n return this._client.get(`/files/${fileId}/content`, {\n ...options,\n headers: { Accept: 'application/binary', ...options?.headers },\n __binaryResponse: true,\n });\n }\n /**\n * Returns the contents of the specified file.\n *\n * @deprecated The `.content()` method should be used instead\n */\n retrieveContent(fileId, options) {\n return this._client.get(`/files/${fileId}/content`, options);\n }\n /**\n * Waits for the given file to be processed, default timeout is 30 mins.\n */\n async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) {\n const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']);\n const start = Date.now();\n let file = await this.retrieve(id);\n while (!file.status || !TERMINAL_STATES.has(file.status)) {\n await sleep(pollInterval);\n file = await this.retrieve(id);\n if (Date.now() - start > maxWait) {\n throw new APIConnectionTimeoutError({\n message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`,\n });\n }\n }\n return file;\n }\n}\nexport class FileObjectsPage extends CursorPage {\n}\nFiles.FileObjectsPage = FileObjectsPage;\n//# sourceMappingURL=files.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class Checkpoints extends APIResource {\n list(fineTuningJobId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list(fineTuningJobId, {}, query);\n }\n return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/checkpoints`, FineTuningJobCheckpointsPage, { query, ...options });\n }\n}\nexport class FineTuningJobCheckpointsPage extends CursorPage {\n}\nCheckpoints.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;\n//# sourceMappingURL=checkpoints.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../../resource.mjs\";\nimport { isRequestOptions } from \"../../../core.mjs\";\nimport * as CheckpointsAPI from \"./checkpoints.mjs\";\nimport { Checkpoints, FineTuningJobCheckpointsPage, } from \"./checkpoints.mjs\";\nimport { CursorPage } from \"../../../pagination.mjs\";\nexport class Jobs extends APIResource {\n constructor() {\n super(...arguments);\n this.checkpoints = new CheckpointsAPI.Checkpoints(this._client);\n }\n /**\n * Creates a fine-tuning job which begins the process of creating a new model from\n * a given dataset.\n *\n * Response includes details of the enqueued job including job status and the name\n * of the fine-tuned models once complete.\n *\n * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)\n */\n create(body, options) {\n return this._client.post('/fine_tuning/jobs', { body, ...options });\n }\n /**\n * Get info about a fine-tuning job.\n *\n * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/fine-tuning)\n */\n retrieve(fineTuningJobId, options) {\n return this._client.get(`/fine_tuning/jobs/${fineTuningJobId}`, options);\n }\n list(query = {}, options) {\n if (isRequestOptions(query)) {\n return this.list({}, query);\n }\n return this._client.getAPIList('/fine_tuning/jobs', FineTuningJobsPage, { query, ...options });\n }\n /**\n * Immediately cancel a fine-tune job.\n */\n cancel(fineTuningJobId, options) {\n return this._client.post(`/fine_tuning/jobs/${fineTuningJobId}/cancel`, options);\n }\n listEvents(fineTuningJobId, query = {}, options) {\n if (isRequestOptions(query)) {\n return this.listEvents(fineTuningJobId, {}, query);\n }\n return this._client.getAPIList(`/fine_tuning/jobs/${fineTuningJobId}/events`, FineTuningJobEventsPage, {\n query,\n ...options,\n });\n }\n}\nexport class FineTuningJobsPage extends CursorPage {\n}\nexport class FineTuningJobEventsPage extends CursorPage {\n}\nJobs.FineTuningJobsPage = FineTuningJobsPage;\nJobs.FineTuningJobEventsPage = FineTuningJobEventsPage;\nJobs.Checkpoints = Checkpoints;\nJobs.FineTuningJobCheckpointsPage = FineTuningJobCheckpointsPage;\n//# sourceMappingURL=jobs.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as JobsAPI from \"./jobs/jobs.mjs\";\nimport { FineTuningJobEventsPage, FineTuningJobsPage, Jobs, } from \"./jobs/jobs.mjs\";\nexport class FineTuning extends APIResource {\n constructor() {\n super(...arguments);\n this.jobs = new JobsAPI.Jobs(this._client);\n }\n}\nFineTuning.Jobs = Jobs;\nFineTuning.FineTuningJobsPage = FineTuningJobsPage;\nFineTuning.FineTuningJobEventsPage = FineTuningJobEventsPage;\n//# sourceMappingURL=fine-tuning.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nimport * as Core from \"../core.mjs\";\nexport class Images extends APIResource {\n /**\n * Creates a variation of a given image.\n */\n createVariation(body, options) {\n return this._client.post('/images/variations', Core.multipartFormRequestOptions({ body, ...options }));\n }\n /**\n * Creates an edited or extended image given an original image and a prompt.\n */\n edit(body, options) {\n return this._client.post('/images/edits', Core.multipartFormRequestOptions({ body, ...options }));\n }\n /**\n * Creates an image given a prompt.\n */\n generate(body, options) {\n return this._client.post('/images/generations', { body, ...options });\n }\n}\n//# sourceMappingURL=images.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nimport { Page } from \"../pagination.mjs\";\nexport class Models extends APIResource {\n /**\n * Retrieves a model instance, providing basic information about the model such as\n * the owner and permissioning.\n */\n retrieve(model, options) {\n return this._client.get(`/models/${model}`, options);\n }\n /**\n * Lists the currently available models, and provides basic information about each\n * one such as the owner and availability.\n */\n list(options) {\n return this._client.getAPIList('/models', ModelsPage, options);\n }\n /**\n * Delete a fine-tuned model. You must have the Owner role in your organization to\n * delete a model.\n */\n del(model, options) {\n return this._client.delete(`/models/${model}`, options);\n }\n}\n/**\n * Note: no pagination actually occurs yet, this is for forwards-compatibility.\n */\nexport class ModelsPage extends Page {\n}\nModels.ModelsPage = ModelsPage;\n//# sourceMappingURL=models.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../resource.mjs\";\nexport class Moderations extends APIResource {\n /**\n * Classifies if text and/or image inputs are potentially harmful. Learn more in\n * the [moderation guide](https://platform.openai.com/docs/guides/moderation).\n */\n create(body, options) {\n return this._client.post('/moderations', { body, ...options });\n }\n}\n//# sourceMappingURL=moderations.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as Core from \"../../core.mjs\";\nexport class Parts extends APIResource {\n /**\n * Adds a\n * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object.\n * A Part represents a chunk of bytes from the file you are trying to upload.\n *\n * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload\n * maximum of 8 GB.\n *\n * It is possible to add multiple Parts in parallel. You can decide the intended\n * order of the Parts when you\n * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete).\n */\n create(uploadId, body, options) {\n return this._client.post(`/uploads/${uploadId}/parts`, Core.multipartFormRequestOptions({ body, ...options }));\n }\n}\n//# sourceMappingURL=parts.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nimport { APIResource } from \"../../resource.mjs\";\nimport * as PartsAPI from \"./parts.mjs\";\nimport { Parts } from \"./parts.mjs\";\nexport class Uploads extends APIResource {\n constructor() {\n super(...arguments);\n this.parts = new PartsAPI.Parts(this._client);\n }\n /**\n * Creates an intermediate\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object\n * that you can add\n * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to.\n * Currently, an Upload can accept at most 8 GB in total and expires after an hour\n * after you create it.\n *\n * Once you complete the Upload, we will create a\n * [File](https://platform.openai.com/docs/api-reference/files/object) object that\n * contains all the parts you uploaded. This File is usable in the rest of our\n * platform as a regular File object.\n *\n * For certain `purpose`s, the correct `mime_type` must be specified. Please refer\n * to documentation for the supported MIME types for your use case:\n *\n * - [Assistants](https://platform.openai.com/docs/assistants/tools/file-search#supported-files)\n *\n * For guidance on the proper filename extensions for each purpose, please follow\n * the documentation on\n * [creating a File](https://platform.openai.com/docs/api-reference/files/create).\n */\n create(body, options) {\n return this._client.post('/uploads', { body, ...options });\n }\n /**\n * Cancels the Upload. No Parts may be added after an Upload is cancelled.\n */\n cancel(uploadId, options) {\n return this._client.post(`/uploads/${uploadId}/cancel`, options);\n }\n /**\n * Completes the\n * [Upload](https://platform.openai.com/docs/api-reference/uploads/object).\n *\n * Within the returned Upload object, there is a nested\n * [File](https://platform.openai.com/docs/api-reference/files/object) object that\n * is ready to use in the rest of the platform.\n *\n * You can specify the order of the Parts by passing in an ordered list of the Part\n * IDs.\n *\n * The number of bytes uploaded upon completion must match the number of bytes\n * initially specified when creating the Upload object. No Parts may be added after\n * an Upload is completed.\n */\n complete(uploadId, body, options) {\n return this._client.post(`/uploads/${uploadId}/complete`, { body, ...options });\n }\n}\nUploads.Parts = Parts;\n//# sourceMappingURL=uploads.mjs.map","// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.\nvar _a;\nimport * as qs from \"./internal/qs/index.mjs\";\nimport * as Core from \"./core.mjs\";\nimport * as Errors from \"./error.mjs\";\nimport * as Pagination from \"./pagination.mjs\";\nimport * as Uploads from \"./uploads.mjs\";\nimport * as API from \"./resources/index.mjs\";\nimport { Batches, BatchesPage, } from \"./resources/batches.mjs\";\nimport { Completions, } from \"./resources/completions.mjs\";\nimport { Embeddings, } from \"./resources/embeddings.mjs\";\nimport { FileObjectsPage, Files, } from \"./resources/files.mjs\";\nimport { Images, } from \"./resources/images.mjs\";\nimport { Models, ModelsPage } from \"./resources/models.mjs\";\nimport { Moderations, } from \"./resources/moderations.mjs\";\nimport { Audio } from \"./resources/audio/audio.mjs\";\nimport { Beta } from \"./resources/beta/beta.mjs\";\nimport { Chat } from \"./resources/chat/chat.mjs\";\nimport { FineTuning } from \"./resources/fine-tuning/fine-tuning.mjs\";\nimport { Uploads as UploadsAPIUploads, } from \"./resources/uploads/uploads.mjs\";\n/**\n * API Client for interfacing with the OpenAI API.\n */\nexport class OpenAI extends Core.APIClient {\n /**\n * API Client for interfacing with the OpenAI API.\n *\n * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined]\n * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]\n * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null]\n * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.\n * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n */\n constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('OPENAI_API_KEY'), organization = Core.readEnv('OPENAI_ORG_ID') ?? null, project = Core.readEnv('OPENAI_PROJECT_ID') ?? null, ...opts } = {}) {\n if (apiKey === undefined) {\n throw new Errors.OpenAIError(\"The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).\");\n }\n const options = {\n apiKey,\n organization,\n project,\n ...opts,\n baseURL: baseURL || `https://api.openai.com/v1`,\n };\n if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {\n throw new Errors.OpenAIError(\"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\");\n }\n super({\n baseURL: options.baseURL,\n timeout: options.timeout ?? 600000 /* 10 minutes */,\n httpAgent: options.httpAgent,\n maxRetries: options.maxRetries,\n fetch: options.fetch,\n });\n this.completions = new API.Completions(this);\n this.chat = new API.Chat(this);\n this.embeddings = new API.Embeddings(this);\n this.files = new API.Files(this);\n this.images = new API.Images(this);\n this.audio = new API.Audio(this);\n this.moderations = new API.Moderations(this);\n this.models = new API.Models(this);\n this.fineTuning = new API.FineTuning(this);\n this.beta = new API.Beta(this);\n this.batches = new API.Batches(this);\n this.uploads = new API.Uploads(this);\n this._options = options;\n this.apiKey = apiKey;\n this.organization = organization;\n this.project = project;\n }\n defaultQuery() {\n return this._options.defaultQuery;\n }\n defaultHeaders(opts) {\n return {\n ...super.defaultHeaders(opts),\n 'OpenAI-Organization': this.organization,\n 'OpenAI-Project': this.project,\n ...this._options.defaultHeaders,\n };\n }\n authHeaders(opts) {\n return { Authorization: `Bearer ${this.apiKey}` };\n }\n stringifyQuery(query) {\n return qs.stringify(query, { arrayFormat: 'brackets' });\n }\n}\n_a = OpenAI;\nOpenAI.OpenAI = _a;\nOpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes\nOpenAI.OpenAIError = Errors.OpenAIError;\nOpenAI.APIError = Errors.APIError;\nOpenAI.APIConnectionError = Errors.APIConnectionError;\nOpenAI.APIConnectionTimeoutError = Errors.APIConnectionTimeoutError;\nOpenAI.APIUserAbortError = Errors.APIUserAbortError;\nOpenAI.NotFoundError = Errors.NotFoundError;\nOpenAI.ConflictError = Errors.ConflictError;\nOpenAI.RateLimitError = Errors.RateLimitError;\nOpenAI.BadRequestError = Errors.BadRequestError;\nOpenAI.AuthenticationError = Errors.AuthenticationError;\nOpenAI.InternalServerError = Errors.InternalServerError;\nOpenAI.PermissionDeniedError = Errors.PermissionDeniedError;\nOpenAI.UnprocessableEntityError = Errors.UnprocessableEntityError;\nOpenAI.toFile = Uploads.toFile;\nOpenAI.fileFromPath = Uploads.fileFromPath;\nOpenAI.Completions = Completions;\nOpenAI.Chat = Chat;\nOpenAI.Embeddings = Embeddings;\nOpenAI.Files = Files;\nOpenAI.FileObjectsPage = FileObjectsPage;\nOpenAI.Images = Images;\nOpenAI.Audio = Audio;\nOpenAI.Moderations = Moderations;\nOpenAI.Models = Models;\nOpenAI.ModelsPage = ModelsPage;\nOpenAI.FineTuning = FineTuning;\nOpenAI.Beta = Beta;\nOpenAI.Batches = Batches;\nOpenAI.BatchesPage = BatchesPage;\nOpenAI.Uploads = UploadsAPIUploads;\n/** API Client for interfacing with the Azure OpenAI API. */\nexport class AzureOpenAI extends OpenAI {\n /**\n * API Client for interfacing with the Azure OpenAI API.\n *\n * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined]\n * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/`\n * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined]\n * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`.\n * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null]\n * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`.\n * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out.\n * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections.\n * @param {Core.Fetch} [opts.fetch] - Specify a custom `fetch` function implementation.\n * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request.\n * @param {Core.Headers} opts.defaultHeaders - Default headers to include with every request to the API.\n * @param {Core.DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API.\n * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers.\n */\n constructor({ baseURL = Core.readEnv('OPENAI_BASE_URL'), apiKey = Core.readEnv('AZURE_OPENAI_API_KEY'), apiVersion = Core.readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) {\n if (!apiVersion) {\n throw new Errors.OpenAIError(\"The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).\");\n }\n if (typeof azureADTokenProvider === 'function') {\n dangerouslyAllowBrowser = true;\n }\n if (!azureADTokenProvider && !apiKey) {\n throw new Errors.OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.');\n }\n if (azureADTokenProvider && apiKey) {\n throw new Errors.OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.');\n }\n // define a sentinel value to avoid any typing issues\n apiKey ?? (apiKey = API_KEY_SENTINEL);\n opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion };\n if (!baseURL) {\n if (!endpoint) {\n endpoint = process.env['AZURE_OPENAI_ENDPOINT'];\n }\n if (!endpoint) {\n throw new Errors.OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable');\n }\n baseURL = `${endpoint}/openai`;\n }\n else {\n if (endpoint) {\n throw new Errors.OpenAIError('baseURL and endpoint are mutually exclusive');\n }\n }\n super({\n apiKey,\n baseURL,\n ...opts,\n ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}),\n });\n this.apiVersion = '';\n this._azureADTokenProvider = azureADTokenProvider;\n this.apiVersion = apiVersion;\n this._deployment = deployment;\n }\n buildRequest(options) {\n if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) {\n if (!Core.isObj(options.body)) {\n throw new Error('Expected request body to be an object');\n }\n const model = this._deployment || options.body['model'];\n if (model !== undefined && !this.baseURL.includes('/deployments')) {\n options.path = `/deployments/${model}${options.path}`;\n }\n }\n return super.buildRequest(options);\n }\n async _getAzureADToken() {\n if (typeof this._azureADTokenProvider === 'function') {\n const token = await this._azureADTokenProvider();\n if (!token || typeof token !== 'string') {\n throw new Errors.OpenAIError(`Expected 'azureADTokenProvider' argument to return a string but it returned ${token}`);\n }\n return token;\n }\n return undefined;\n }\n authHeaders(opts) {\n return {};\n }\n async prepareOptions(opts) {\n /**\n * The user should provide a bearer token provider if they want\n * to use Azure AD authentication. The user shouldn't set the\n * Authorization header manually because the header is overwritten\n * with the Azure AD token if a bearer token provider is provided.\n */\n if (opts.headers?.['api-key']) {\n return super.prepareOptions(opts);\n }\n const token = await this._getAzureADToken();\n opts.headers ?? (opts.headers = {});\n if (token) {\n opts.headers['Authorization'] = `Bearer ${token}`;\n }\n else if (this.apiKey !== API_KEY_SENTINEL) {\n opts.headers['api-key'] = this.apiKey;\n }\n else {\n throw new Errors.OpenAIError('Unable to handle auth');\n }\n return super.prepareOptions(opts);\n }\n}\nconst _deployments_endpoints = new Set([\n '/completions',\n '/chat/completions',\n '/embeddings',\n '/audio/transcriptions',\n '/audio/translations',\n '/audio/speech',\n '/images/generations',\n]);\nconst API_KEY_SENTINEL = '';\nexport { toFile, fileFromPath } from \"./uploads.mjs\";\nexport { OpenAIError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError, } from \"./error.mjs\";\nexport default OpenAI;\n//# sourceMappingURL=index.mjs.map",null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null,null],"names":["titleIndications","text","backTitle","document","title","setTimeout","__awaiter","thisArg","_arguments","P","generator","Promise","resolve","reject","fulfilled","value","step","next","e","rejected","result","done","then","apply","sentenceSimilarity","str1","str2","longerLength","length","matrix","str1WithoutSpaces","replace","str2WithoutSpaces","i","push","j","Math","min","levenshteinDistance","pickBestReponse","answer","arr","bestResponse","element","similarity","obj","SuppressedError","Logs","question","console","log","bestAnswer","round","toPourcentage","array","response","gptAnswer","normalizedResponse","normalizeText","toLowerCase","trim","SYSTEM_INSTRUCTION_MESSAGE","role","content","getContent","config","questionElement","imagesElements","querySelectorAll","includeImages","version","versionNumber","match","undefined","Number","isGPTModelGreaterOrEqualTo4","model","contentWithImages","base64Images","Array","from","map","imgEl","imageElement","quality","canvas","createElement","ctx","getContext","remove","img","Image","crossOrigin","onload","width","height","drawImage","base64","toDataURL","onerror","err","src","imageToBase64","base64ImagesResolved","allSettled","status","type","image_url","url","logs","error","reason","getContentWithHistory","message","history","messages","pastHistory","JSON","parse","_a","sessionStorage","moodleGPTHistory","loadPastHistory","newHistory","urlParams","URLSearchParams","location","search","host","cmid","get","attempt","_b","createNewHistory","a","b","KEYS_TO_COMPARE","key","areHistoryFromSameQuiz","saveResponse","stringify","default_format","formatters","RFC1738","v","String","RFC3986","is_array","isArray","hex_table","toString","toUpperCase","limit","maybe_map","val","fn","mapped","has","Object","prototype","hasOwnProperty","array_prefix_generators","brackets","prefix","comma","indices","repeat","push_to_array","value_or_array","to_ISO","Date","toISOString","defaults","addQueryPrefix","allowDots","allowEmptyArrays","arrayFormat","charset","charsetSentinel","delimiter","encode","encodeDotInKeys","encoder","str","_defaultEncoder","_kind","format","string","Symbol","call","escape","$0","parseInt","slice","out","segment","c","charCodeAt","charAt","join","encodeValuesOnly","formatter","serializeDate","date","skipNulls","strictNullHandling","sentinel","inner_stringify","object","generateArrayPrefix","commaRoundTrip","filter","sort","sideChannel","tmp_sc","find_flag","pos","RangeError","constructor","isBuffer","is_buffer","key_value","values","obj_keys","keys","encoded_prefix","adjusted_prefix","encoded_key","key_prefix","set","valueSideChannel","WeakMap","opts","options","TypeError","normalize_stringify_options","joined","VERSION","kind","fetch","FormData","File","ReadableStream","getMultipartRequestOptions","getDefaultAgent","fileFromPath","isFsReadStream","auto","MultipartBody","body","this","toStringTag","shims.kind","shims","Error","shims.setShims","manuallyImported","recommendation","_fetch","_Request","_Response","_Headers","Request","Response","Headers","Blob","async","form","auto.getRuntime","OpenAIError","APIError","headers","super","makeMessage","request_id","data","code","param","msg","generate","errorResponse","APIConnectionError","cause","castToError","BadRequestError","AuthenticationError","PermissionDeniedError","NotFoundError","ConflictError","UnprocessableEntityError","RateLimitError","InternalServerError","APIUserAbortError","APIConnectionTimeoutError","LengthFinishReasonError","ContentFilterFinishReasonError","LineDecoder","buffer","trailingCR","decode","chunk","decodeText","endsWith","trailingNewline","NEWLINE_CHARS","lines","split","NEWLINE_REGEXP","pop","bytes","Buffer","Uint8Array","name","TextDecoder","ArrayBuffer","textDecoder","flush","Set","Stream","iterator","controller","fromSSEResponse","consumed","sse","abort","sseDecoder","SSEDecoder","lineDecoder","iter","readableStreamAsyncIterable","sseChunk","binaryChunk","TextEncoder","patternIndex","newData","findDoubleNewlineIndex","iterSSEChunks","line","_iterSSEMessages","startsWith","event","raw","fromReadableStream","readableStream","iterLines","asyncIterator","tee","left","right","teeIterator","queue","shift","toReadableStream","self","start","pull","ctrl","close","enqueue","cancel","return","chunks","substring","fieldname","_","index","indexOf","partition","stream","reader","getReader","read","releaseLock","cancelPromise","isResponseLike","blob","isFileLike","lastModified","isBlobLike","size","arrayBuffer","toFile","URL","pathname","bits","parts","isView","isAsyncIterableIterator","props","getOwnPropertyNames","p","propsForError","getBytes","getStringFromMaybeBuffer","filename","path","getName","x","isMultipartBody","multipartFormRequestOptions","createForm","all","entries","addFormValue","append","isUploadable","file","entry","prop","_AbstractPage_client","__classPrivateFieldSet","receiver","state","f","__classPrivateFieldGet","defaultParseResponse","debug","__streamClass","__binaryResponse","contentType","includes","json","_addRequestID","defineProperty","enumerable","APIPromise","responsePromise","parseResponse","_thenUnwrap","transform","asResponse","withResponse","parsedPromise","onfulfilled","onrejected","catch","onfinally","finally","APIClient","baseURL","maxRetries","timeout","httpAgent","overriddenFetch","validatePositiveInteger","authHeaders","defaultHeaders","Accept","getUserAgent","getPlatformHeaders","validateHeaders","customHeaders","defaultIdempotencyKey","uuid4","methodRequest","post","patch","put","method","request","DataView","getAPIList","Page","requestAPIList","calculateContentLength","byteLength","buildRequest","retryCount","query","__binaryRequest","contentLength","buildURL","minAgentTimeout","idempotencyHeader","idempotencyKey","req","buildHeaders","agent","signal","reqHeaders","applyHeadersMut","shimsKind","getHeader","prepareOptions","prepareRequest","parseHeaders","fromEntries","header","makeStatusError","remainingRetries","makeRequest","optionsInput","retriesRemaining","aborted","AbortController","fetchWithTimeout","retryRequest","responseHeaders","createResponseHeaders","ok","shouldRetry","errText","errJSON","safeJSON","errMessage","PagePromise","isAbsoluteURL","defaultQuery","isEmptyObj","stringifyQuery","encodeURIComponent","init","ms","addEventListener","fetchOptions","clearTimeout","shouldRetryHeader","timeoutMillis","retryAfterMillisHeader","timeoutMs","parseFloat","isNaN","retryAfterHeader","timeoutSeconds","now","calculateDefaultRetryTimeoutMillis","sleep","numRetries","pow","random","AbstractPage","client","hasNextPage","getPaginatedItems","nextPageInfo","getNextPage","nextInfo","nextOptions","params","searchParams","iterPages","page","item","Proxy","target","requestOptionsKeys","isRequestOptions","every","k","hasOwn","getPlatformProperties","Deno","build","normalizePlatform","os","normalizeArch","arch","deno","EdgeRuntime","process","platform","browserInfo","navigator","browserPatterns","pattern","exec","userAgent","browser","getBrowserInfo","_platformHeaders","startsWithSchemeRegexp","test","n","isInteger","readEnv","env","_k","targetHeaders","newHeaders","lowerKey","action","args","r","lowerCasedHeader","isHeadersProtocol","intercapsHeader","_m","g1","g2","warn","isObj","nextPageParams","CursorPage","info","id","after","APIResource","_client","create","arguments","completions","CompletionsAPI.Completions","Chat$1","Completions","Speech","Transcriptions","Core.multipartFormRequestOptions","Translations","Audio","transcriptions","TranscriptionsAPI.Transcriptions","translations","TranslationsAPI.Translations","speech","SpeechAPI.Speech","Batches","retrieve","batchId","list","BatchesPage","Assistants","assistantId","update","AssistantsPage","del","delete","isRunnableFunctionWithParse","isAssistantMessage","isFunctionMessage","isToolMessage","_EventStream_instances","_EventStream_connectedPromise","_EventStream_resolveConnectedPromise","_EventStream_rejectConnectedPromise","_EventStream_endPromise","_EventStream_resolveEndPromise","_EventStream_rejectEndPromise","_EventStream_listeners","_EventStream_ended","_EventStream_errored","_EventStream_aborted","_EventStream_catchingPromiseCreated","_EventStream_handleError","EventStream","add","_run","executor","_emitFinal","_emit","bind","_connected","ended","errored","on","listener","off","listeners","findIndex","l","splice","once","emitted","forEach","isAutoParsableResponseFormat","response_format","isAutoParsableTool","tool","parseChatCompletion","completion","choices","choice","finish_reason","tool_calls","toolCall","inputTool","tools","find","function","parsed_arguments","$parseRaw","strict","parseToolCall","parsed","refusal","parseResponseFormat","shouldParseToolCall","hasAutoParseableInput","some","t","WeakSet","openAIError","_AbstractChatCompletionRunner_instances","_AbstractChatCompletionRunner_getFinalContent","_AbstractChatCompletionRunner_getFinalMessage","_AbstractChatCompletionRunner_getFinalFunctionCall","_AbstractChatCompletionRunner_getFinalFunctionCallResult","_AbstractChatCompletionRunner_calculateTotalUsage","_AbstractChatCompletionRunner_validateParams","_AbstractChatCompletionRunner_stringifyFunctionCallResult","DEFAULT_MAX_CHAT_COMPLETIONS","AbstractChatCompletionRunner","_chatCompletions","_addChatCompletion","chatCompletion","_addMessage","emit","function_call","tool_call","finalChatCompletion","finalContent","finalMessage","finalFunctionCall","finalFunctionCallResult","totalUsage","allChatCompletions","usage","_createChatCompletion","chat","_runChatCompletion","_runFunctions","restParams","singleFunctionToCall","maxChatCompletions","functionsByName","functions","parameters","description","rawContent","_runTools","tool_choice","inputTools","$callback","tool_call_id","rest","ret","at","y","total","completion_tokens","prompt_tokens","total_tokens","ChatCompletionRunner","runFunctions","runner","runTools","Allow","ATOM","PartialJSON","MalformedJSON","_parseJSON","jsonString","allow","markPartialJSON","throwMalformedError","parseAny","skipBlank","parseStr","parseObj","parseArr","Infinity","NaN","parseNum","lastIndexOf","writable","configurable","partialParse","input","allowPartial","parseJSON","_ChatCompletionStream_instances","_ChatCompletionStream_params","_ChatCompletionStream_choiceEventStates","_ChatCompletionStream_currentChatCompletionSnapshot","_ChatCompletionStream_beginRequest","_ChatCompletionStream_getChoiceEventState","_ChatCompletionStream_addChunk","_ChatCompletionStream_emitToolCallDoneEvent","_ChatCompletionStream_emitContentDoneEvents","_ChatCompletionStream_endRequest","_ChatCompletionStream_getAutoParseableResponseFormat","_ChatCompletionStream_accumulateChatCompletion","ChatCompletionStream","currentChatCompletionSnapshot","_fromReadableStream","createChatCompletion","chatId","content_done","refusal_done","logprobs_content_done","logprobs_refusal_done","done_tool_calls","current_tool_call_index","choiceSnapshot","delta","snapshot","logprobs","toolCallDelta","toolCallSnapshot","arguments_delta","toolCallIndex","responseFormat","created","system_fingerprint","choiceRest","messageRest","toolRest","fnRest","maybeParseChatCompletion","finalizeChatCompletion","_c","_d","assign","other","pushQueue","readQueue","ChatCompletionStreamingRunner","validateInputTools","Chat","Sessions","Realtime","sessions","SessionsAPI.Sessions","_AssistantStream_instances","_AssistantStream_events","_AssistantStream_runStepSnapshots","_AssistantStream_messageSnapshots","_AssistantStream_messageSnapshot","_AssistantStream_finalRun","_AssistantStream_currentContentIndex","_AssistantStream_currentContent","_AssistantStream_currentToolCallIndex","_AssistantStream_currentToolCall","_AssistantStream_currentEvent","_AssistantStream_currentRunSnapshot","_AssistantStream_currentRunStepSnapshot","_AssistantStream_addEvent","_AssistantStream_endRequest","_AssistantStream_handleMessage","_AssistantStream_handleRunStep","_AssistantStream_handleEvent","_AssistantStream_accumulateRunStep","_AssistantStream_accumulateMessage","_AssistantStream_accumulateContent","_AssistantStream_handleRun","AssistantStream","_addRun","createToolAssistantStream","threadId","runId","runs","_runToolAssistantStream","_createToolAssistantStream","run","submitToolOutputs","createThreadAssistantStream","thread","_threadAssistantStream","createAssistantStream","_runAssistantStream","currentEvent","currentRun","currentMessageSnapshot","currentRunStepSnapshot","finalRunSteps","finalMessages","finalRun","_createThreadAssistantStream","createAndRun","_createAssistantStream","accumulateDelta","acc","deltaValue","accValue","Core.isObj","deltaEntry","accEntry","accumulatedMessage","newContent","snapshotContent","textDelta","image_file","currentContent","accumulatedRunStep","step_details","accumulated","contentElement","Messages","messageId","MessagesPage","Steps","stepId","RunStepsPage","Runs","steps","StepsAPI.Steps","include","RunsPage","createAndPoll","poll","createAndStream","beta","threads","pollIntervalMs","sleepInterval","headerInterval","headerIntervalMs","submitToolOutputsAndPoll","submitToolOutputsStream","Threads","RunsAPI.Runs","MessagesAPI.Messages","createAndRunPoll","thread_id","createAndRunStream","vectorStoreId","fileId","VectorStoreFilesPage","fileResponse","upload","fileInfo","files","purpose","file_id","uploadAndPoll","Files$1","FileBatches","batch","listFiles","fileIds","configuredConcurrency","maxConcurrency","concurrencyLimit","fileIterator","allFileIds","workers","fill","fileObj","promises","results","allSettledWithThrow","file_ids","VectorStores","FilesAPI.Files","fileBatches","FileBatchesAPI.FileBatches","VectorStoresPage","Files","Beta","realtime","RealtimeAPI.Realtime","vectorStores","VectorStoresAPI.VectorStores","ChatAPI.Chat","assistants","AssistantsAPI.Assistants","ThreadsAPI.Threads","Embeddings","FileObjectsPage","retrieveContent","waitForProcessing","pollInterval","maxWait","TERMINAL_STATES","Checkpoints","fineTuningJobId","FineTuningJobCheckpointsPage","Jobs","checkpoints","CheckpointsAPI.Checkpoints","FineTuningJobsPage","listEvents","FineTuningJobEventsPage","FineTuning","jobs","JobsAPI.Jobs","Images","createVariation","edit","Models","ModelsPage","Moderations","Parts","uploadId","Uploads","PartsAPI.Parts","complete","OpenAI","Core.APIClient","Core.readEnv","apiKey","organization","project","Errors.OpenAIError","dangerouslyAllowBrowser","window","API.Completions","API.Chat","embeddings","API.Embeddings","API.Files","images","API.Images","audio","API.Audio","moderations","API.Moderations","models","API.Models","fineTuning","API.FineTuning","API.Beta","batches","API.Batches","uploads","API.Uploads","_options","Authorization","qs.stringify","htmlTableToString","table","tab","maxColumnsLength","cellsContent","cell","textContent","max","headerLineLength","lineSeparationSize","reduce","jointure","lineSeparation","mappedTab","padEnd","handleClipboard","clipboard","writeText","handleContentEditable","inputList","contenteditable","getAttribute","isContentEditable","typing","eventHandler","preventDefault","removeEventListener","focus","range","createRange","selectNodeContents","collapse","selection","getSelection","removeAllRanges","addRange","handleNumber","number","eventHanlder","handleRadio","firstInput","possibleAnswers","inp","parentElement","correctInput","mouseover","click","handleCheckbox","corrects","correctElements","correct","needAction","checked","handleSelect","tagName","opt","correctOption","currentSelect","closest","selected","handleTextbox","handleAtto","classList","contains","iframe","querySelector","contentDocument","contentWindow","textContainer","textNode","createTextNode","appendChild","reply","cursor","style","questionContainer","innerText","accesshideElements","useless","attoText","tables","createAndNormalizeQuestion","inputQuery","timeoutControler","contentHandler","max_tokens","max_completion_tokens","temperature","top_p","fixeO1","presence_penalty","getChatGPTResponse","haveError","infinite","mode","removeListener","clipboardMode","questionBackup","innerHTML","whiteSpace","contentIsResponse","questionToAnswerMode","handlers","handler","autoCompleteMode","DEFAULT_TIMEOUT","Errors.APIError","Errors.APIConnectionError","Errors.APIConnectionTimeoutError","Errors.APIUserAbortError","Errors.NotFoundError","Errors.ConflictError","Errors.RateLimitError","Errors.BadRequestError","Errors.AuthenticationError","Errors.InternalServerError","Errors.PermissionDeniedError","Errors.UnprocessableEntityError","Uploads.toFile","Uploads.fileFromPath","UploadsAPIUploads","pressedKeys","setUpMoodleGpt","forms","injectionFunction","chrome","storage","sync","moodleGPT","codeListener"],"mappings":"2FAIA,SAASA,EAAiBC,GACxB,MAAMC,EAAYC,SAASC,MAC3BD,SAASC,MAAQH,EACjBI,YAAW,IAAOF,SAASC,MAAQF,GAAY,IACjD,CC0GO,SAASI,EAAUC,EAASC,EAAYC,EAAGC,GAE9C,OAAO,IAAKD,IAAMA,EAAIE,WAAU,SAAUC,EAASC,GAC/C,S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WACrC,CCjFAunC,OAAOC,QAAQC,KAAKv/B,IAAI,CAAC,cAAc5G,MAAK,SAAUkmC,GACpD,MAAMvjC,EAAiBujC,EAAQE,UAE/B,IAAKzjC,EAAQ,MAAM,IAAI6L,MAAM,iDAEzB7L,EAAOmN,KDQb,SAAsBnN,GACpB9D,SAASsP,KAAKwQ,iBAAiB,WAAW,SAAU7K,GAClD+xB,GAAYjlC,KAAKkT,EAAM3M,KACnB0+B,GAAYvlC,OAASqC,EAAOmN,KAAMxP,QAAQulC,GAAYpxB,QACtDoxB,GAAY56B,KAAK,MAAQtI,EAAOmN,OAClC+1B,GAAYvlC,OAAS,EACrBwlC,GAAenjC,GAEnB,GACF,CChBI0jC,CAAa1jC,GAEbmjC,GAAenjC,EAEnB","x_google_ignoreList":[1,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65]} \ No newline at end of file diff --git a/extension/manifest.json b/extension/manifest.json index cfd06cd..5071053 100644 --- a/extension/manifest.json +++ b/extension/manifest.json @@ -1,7 +1,7 @@ { "manifest_version": 3, "name": "MoodleGPT", - "version": "1.1.1", + "version": "1.1.2", "description": "Hidden chat-gpt for your moodle quiz", "permissions": ["storage"], "action": { diff --git a/extension/popup/index.html b/extension/popup/index.html index 3871c91..86892d4 100644 --- a/extension/popup/index.html +++ b/extension/popup/index.html @@ -7,13 +7,7 @@ MoodleGPT - - - - - - - + MoodleGPT

-
- - + + +
+
+ + +
+
+ + + + +
-
- - - + + + -
- - + + + -
+ +

Mode:

@@ -69,9 +78,9 @@

MoodleGPT

-
+
-

Settings:

+

Options:

@@ -122,6 +131,7 @@

MoodleGPT