Files
yoannchb-pro 3591aceba1 v1.1.5
2025-10-01 09:28:48 +02:00

3 lines
109 KiB
JavaScript
Raw Permalink Blame History

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