Files
MoodleGPT/extension/popup/popup.js
T
Adrian Schauer e793cbd0b2 #57 addtion of o3
2025-07-10 17:01:10 +02:00

3 lines
88 KiB
JavaScript

!function(e){"function"==typeof define&&define.amd?define(e):e()}((function(){"use strict";const e={actualMode:"autocomplete"},t=["logs","title","cursor","typing","mouseover","infinite","timeout","history","includeImages"],s=document.querySelector("#mode").querySelectorAll("button");function n(e,t,s,n){return new(s||(s=Promise))((function(r,o){function a(e){try{l(n.next(e))}catch(e){o(e)}}function i(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(a,i)}l((n=n.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;const r="RFC3986",o={RFC1738:e=>String(e).replace(/%20/g,"+"),RFC3986:e=>String(e)},a=Array.isArray,i=(()=>{const e=[];for(let t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e})(),l=1024;function c(e,t){if(a(e)){const s=[];for(let n=0;n<e.length;n+=1)s.push(t(e[n]));return s}return t(e)}const u=Object.prototype.hasOwnProperty,h={brackets:e=>String(e)+"[]",comma:"comma",indices:(e,t)=>String(e)+"["+t+"]",repeat:e=>String(e)},d=Array.isArray,f=Array.prototype.push,p=function(e,t){f.apply(e,d(t)?t:[t])},m=Date.prototype.toISOString,g={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 a="";for(let e=0;e<o.length;e+=l){const t=o.length>=l?o.slice(e,e+l):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]=i[n]:n<2048?s[s.length]=i[192|n>>6]+i[128|63&n]:n<55296||n>=57344?s[s.length]=i[224|n>>12]+i[128|n>>6&63]+i[128|63&n]:(e+=1,n=65536+((1023&n)<<10|1023&t.charCodeAt(e)),s[s.length]=i[240|n>>18]+i[128|n>>12&63]+i[128|n>>6&63]+i[128|63&n])}a+=s.join("")}return a},encodeValuesOnly:!1,format:r,formatter:o[r],indices:!1,serializeDate:e=>m.call(e),skipNulls:!1,strictNullHandling:!1};const y={};function w(e,t,s,n,r,o,a,i,l,u,h,f,m,b,_,v,x,S){let A=e,E=S,R=0,I=!1;for(;void 0!==(E=E.get(y))&&!I;){const t=E.get(e);if(R+=1,void 0!==t){if(t===R)throw new RangeError("Cyclic object value");I=!0}void 0===E.get(y)&&(R=0)}if("function"==typeof u?A=u(t,A):A instanceof Date?A=m?.(A):"comma"===s&&d(A)&&(A=c(A,(function(e){return e instanceof Date?m?.(e):e}))),null===A){if(o)return l&&!v?l(t,g.encoder,x,"key",b):t;A=""}if("string"==typeof(P=A)||"number"==typeof P||"boolean"==typeof P||"symbol"==typeof P||"bigint"==typeof P||function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))}(A)){if(l){const e=v?t:l(t,g.encoder,x,"key",b);return[_?.(e)+"="+_?.(l(A,g.encoder,x,"value",b))]}return[_?.(t)+"="+_?.(String(A))]}var P;const C=[];if(void 0===A)return C;let k;if("comma"===s&&d(A))v&&l&&(A=c(A,l)),k=[{value:A.length>0?A.join(",")||null:void 0}];else if(d(u))k=u;else{const e=Object.keys(A);k=h?e.sort(h):e}const $=i?String(t).replace(/\./g,"%2E"):String(t),O=n&&d(A)&&1===A.length?$+"[]":$;if(r&&d(A)&&0===A.length)return O+"[]";for(let t=0;t<k.length;++t){const c=k[t],g="object"==typeof c&&void 0!==c.value?c.value:A[c];if(a&&null===g)continue;const E=f&&i?c.replace(/\./g,"%2E"):c,I=d(A)?"function"==typeof s?s(O,E):O:O+(f?"."+E:"["+E+"]");S.set(e,R);const P=new WeakMap;P.set(y,S),p(C,w(g,I,s,n,r,o,a,i,"comma"===s&&v&&d(A)?null:l,u,h,f,m,b,_,v,x,P))}return C}function b(e,t={}){let s=e;const n=function(e=g){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||g.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=r;if(void 0!==e.format){if(!u.call(o,e.format))throw new TypeError("Unknown format option provided.");s=e.format}const n=o[s];let a,i=g.filter;if(("function"==typeof e.filter||d(e.filter))&&(i=e.filter),a=e.arrayFormat&&e.arrayFormat in h?e.arrayFormat:"indices"in e?e.indices?"indices":"repeat":g.arrayFormat,"commaRoundTrip"in e&&"boolean"!=typeof e.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const l=void 0===e.allowDots?1==!!e.encodeDotInKeys||g.allowDots:!!e.allowDots;return{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:g.addQueryPrefix,allowDots:l,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:g.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:g.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:void 0===e.delimiter?g.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:g.encode,encodeDotInKeys:"boolean"==typeof e.encodeDotInKeys?e.encodeDotInKeys:g.encodeDotInKeys,encoder:"function"==typeof e.encoder?e.encoder:g.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:g.encodeValuesOnly,filter:i,format:s,formatter:n,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:g.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:g.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:g.strictNullHandling}}(t);let a,i;"function"==typeof n.filter?(i=n.filter,s=i("",s)):d(n.filter)&&(i=n.filter,a=i);const l=[];if("object"!=typeof s||null===s)return"";const c=h[n.arrayFormat],f="comma"===c&&n.commaRoundTrip;a||(a=Object.keys(s)),n.sort&&a.sort(n.sort);const m=new WeakMap;for(let e=0;e<a.length;++e){const t=a[e];n.skipNulls&&null===s[t]||p(l,w(s[t],t,c,f,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,m))}const y=l.join(n.delimiter);let b=!0===n.addQueryPrefix?"?":"";return n.charsetSentinel&&("iso-8859-1"===n.charset?b+="utf8=%26%2310003%3B&":b+="utf8=%E2%9C%93&"),y.length>0?b+y:""}const _="4.82.0";let v,x,S,A,E,R,I,P,C,k=!1;class ${constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}v||function(e,t={auto:!1}){if(k)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(v)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${v}'\``);k=t.auto,v=e.kind,x=e.fetch,S=e.FormData,A=e.File,E=e.ReadableStream,R=e.getMultipartRequestOptions,I=e.getDefaultAgent,P=e.fileFromPath,C=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let s,n,r,o;try{s=fetch,n=Request,r=Response,o=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:s,Request:n,Response:r,Headers:o,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new $(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class O extends Error{}class T extends O{constructor(e,t,s,n){super(`${T.makeMessage(e,t,s)}`),this.status=e,this.headers=n,this.request_id=n?.["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 M({message:s,cause:ke(t)});const r=t?.error;return 400===e?new q(e,r,s,n):401===e?new D(e,r,s,n):403===e?new B(e,r,s,n):404===e?new L(e,r,s,n):409===e?new F(e,r,s,n):422===e?new W(e,r,s,n):429===e?new U(e,r,s,n):e>=500?new X(e,r,s,n):new T(e,r,s,n)}}class j extends T{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class M extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class N extends M{constructor({message:e}={}){super({message:e??"Request timed out."})}}class q extends T{}class D extends T{}class B extends T{}class L extends T{}class F extends T{}class W extends T{}class U extends T{}class X extends T{}class J extends O{constructor(){super("Could not parse response content as the length limit was reached")}}class H extends O{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class V{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];const s=V.NEWLINE_CHARS.has(t[t.length-1]||"");let n=t.split(V.NEWLINE_REGEXP);return s&&n.pop(),1!==n.length||s?(this.buffer.length>0&&(n=[this.buffer.join("")+n[0],...n.slice(1)],this.buffer=[]),s||(this.buffer=[n.pop()||""]),n):(this.buffer.push(n[0]),[])}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new O(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new O(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new O("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}function K(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}}}V.NEWLINE_CHARS=new Set(["\n","\r"]),V.NEWLINE_REGEXP=/\r\n|[\n\r]/g;class z{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let s=!1;return new z((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(const s of async function*(e,t){if(!e.body)throw t.abort(),new O("Attempted to iterate over a response with no body");const s=new Q,n=new V,r=K(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?(new TextEncoder).encode(s):s;let n,r=new Uint8Array(t.length+e.length);for(r.set(t),r.set(e,t.length),t=r;-1!==(n=G(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(!n)if(s.data.startsWith("[DONE]"))n=!0;else if(null===s.event){let e;try{e=JSON.parse(s.data)}catch(e){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),e}if(e&&e.error)throw new T(void 0,e.error,void 0,void 0);yield e}else{let e;try{e=JSON.parse(s.data)}catch(e){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),e}if("error"==s.event)throw new T(void 0,e.error,e.message,void 0);yield{event:s.event,data:e}}n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}static fromReadableStream(e,t){let s=!1;return new z((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(const t of async function*(){const t=new V,s=K(e);for await(const e of s)for(const s of t.decode(e))yield s;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[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 z((()=>n(e)),this.controller),new z((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const s=new TextEncoder;return new E({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:r}=await t.next();if(r)return e.close();const o=s.encode(JSON.stringify(n)+"\n");e.enqueue(o)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}function G(e){for(let t=0;t<e.length-2;t++){if(10===e[t]&&10===e[t+1])return t+2;if(13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return-1}class Q{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}}const Y=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,Z=e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&ee(e),ee=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 te(e,t,s){if(e=await e,Z(e))return e;if(Y(e)){const n=await e.blob();t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file");const r=ee(n)?[await n.arrayBuffer()]:[n];return new A(r,t,s)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(ee(e))t.push(await e.arrayBuffer());else{if(!ne(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const s of e)t.push(s)}return t}(e);if(t||(t=function(e){return se(e.name)||se(e.filename)||se(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!s?.type){const e=n[0]?.type;"string"==typeof e&&(s={...s,type:e})}return new A(n,t,s)}const se=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,ne=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],re=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],oe=async e=>{const t=await ae(e.body);return R(t,e)},ae=async e=>{const t=new S;return await Promise.all(Object.entries(e||{}).map((([e,s])=>ie(t,e,s)))),t},ie=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((e=>Z(e)||Y(e)||C(e))(s)){const n=await te(s);e.append(t,n)}else if(Array.isArray(s))await Promise.all(s.map((s=>ie(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])=>ie(e,`${t}[${s}]`,n))))}}};var le,ce=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},ue=function(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)};async function he(e){const{response:t}=e;if(e.options.stream)return Ne("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):z.fromSSEResponse(t,e.controller);if(204===t.status)return null;if(e.options.__binaryResponse)return t;const s=t.headers.get("content-type");if(s?.includes("application/json")||s?.includes("application/vnd.api+json")){const e=await t.json();return Ne("response",t.status,t.url,t.headers,e),de(e,t)}const n=await t.text();return Ne("response",t.status,t.url,t.headers,n),n}function de(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 fe extends Promise{constructor(e,t=he){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new fe(this.responsePromise,(async t=>de(e(await this.parseResponse(t),t),t.response)))}asResponse(){return this.responsePromise.then((e=>e.response))}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class pe{constructor({baseURL:e,maxRetries:t=2,timeout:s=6e5,httpAgent:n,fetch:r}){this.baseURL=e,this.maxRetries=Ce("maxRetries",t),this.timeout=Ce("timeout",s),this.httpAgent=n,this.fetch=r??x}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Ae(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${qe()}`}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((async s=>{const n=s&&ee(s?.body)?new DataView(await s.body.arrayBuffer()):s?.body instanceof DataView?s.body:s?.body instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s?.body)?new DataView(s.body.buffer):s?.body;return{method:e,path:t,...s,body:n}})))}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){const{method:s,path:n,query:r,headers:o={}}=e,a=ArrayBuffer.isView(e.body)||e.__binaryRequest&&"string"==typeof e.body?e.body:re(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,i=this.calculateContentLength(a),l=this.buildURL(n,r);"timeout"in e&&Ce("timeout",e.timeout);const c=e.timeout??this.timeout,u=e.httpAgent??this.httpAgent??I(l),h=c+1e3;"number"==typeof u?.options?.timeout&&h>(u.options.timeout??0)&&(u.options.timeout=h),this.idempotencyHeader&&"get"!==s&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);return{req:{method:s,...a&&{body:a},headers:this.buildHeaders({options:e,headers:o,contentLength:i,retryCount:t}),...u&&{agent:u},signal:e.signal??null},url:l,timeout:c}}buildHeaders({options:e,headers:t,contentLength:s,retryCount:n}){const r={};s&&(r["content-length"]=s);const o=this.defaultHeaders(e);return je(r,o),je(r,t),re(e.body)&&"node"!==v&&delete r["content-type"],void 0===De(o,"x-stainless-retry-count")&&void 0===De(t,"x-stainless-retry-count")&&(r["x-stainless-retry-count"]=String(n)),this.validateHeaders(r,t),r}async prepareOptions(e){}async prepareRequest(e,{url:t,options:s}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,s,n){return T.generate(e,t,s,n)}request(e,t=null){return new fe(this.makeRequest(e,t))}async makeRequest(e,t){const s=await e,n=s.maxRetries??this.maxRetries;null==t&&(t=n),await this.prepareOptions(s);const{req:r,url:o,timeout:a}=this.buildRequest(s,{retryCount:n-t});if(await this.prepareRequest(r,{url:o,options:s}),Ne("request",o,s,r.headers),s.signal?.aborted)throw new j;const i=new AbortController,l=await this.fetchWithTimeout(o,r,a,i).catch(ke);if(l instanceof Error){if(s.signal?.aborted)throw new j;if(t)return this.retryRequest(s,t);if("AbortError"===l.name)throw new N;throw new M({cause:l})}const c=ye(l.headers);if(!l.ok){if(t&&this.shouldRetry(l)){return Ne(`response (error; ${`retrying, ${t} attempts remaining`})`,l.status,o,c),this.retryRequest(s,t,c)}const e=await l.text().catch((e=>ke(e).message)),n=Ee(e),r=n?void 0:e;Ne(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,l.status,o,c,r);throw this.makeStatusError(l.status,n,r,c)}return{response:l,options:s,controller:i}}requestAPIList(e,t){const s=this.makeRequest(t,null);return new ge(this,s,e)}buildURL(e,t){const s=Ie(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return Oe(n)||(t={...n,...t}),"object"==typeof t&&t&&!Array.isArray(t)&&(s.search=this.stringifyQuery(t)),s.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new O(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,s,n){const{signal:r,...o}=t||{};r&&r.addEventListener("abort",(()=>n.abort()));const a=setTimeout((()=>n.abort()),s),i={signal:n.signal,...o};return i.method&&(i.method=i.method.toUpperCase()),this.fetch.call(void 0,e,i).finally((()=>{clearTimeout(a)}))}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){let n;const r=s?.["retry-after-ms"];if(r){const e=parseFloat(r);Number.isNaN(e)||(n=e)}const o=s?.["retry-after"];if(o&&!n){const e=parseFloat(o);n=Number.isNaN(e)?Date.parse(o)-Date.now():1e3*e}if(!(n&&0<=n&&n<6e4)){const s=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,s)}return await Pe(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${_}`}}class me{constructor(e,t,s,n){le.set(this,void 0),ce(this,le,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new O("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&"object"==typeof t.query)t.query={...t.query,...e.params};else if("url"in e){const s=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of s)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await ue(this,le,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(le=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class ge extends fe{constructor(e,t,s){super(t,(async t=>new s(e,t.response,await he(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const ye=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const s=t.toString();return e[s.toLowerCase()]||e[s]}}),we={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},be=e=>"object"==typeof e&&null!==e&&!Oe(e)&&Object.keys(e).every((e=>Te(we,e))),_e=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_,"X-Stainless-OS":xe(Deno.build.os),"X-Stainless-Arch":ve(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":_,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_,"X-Stainless-OS":xe(process.platform),"X-Stainless-Arch":ve(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern: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 e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const ve=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",xe=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 Se;const Ae=()=>Se??(Se=_e()),Ee=e=>{try{return JSON.parse(e)}catch(e){return}},Re=/^[a-z][a-z0-9+.-]*:/i,Ie=e=>Re.test(e),Pe=e=>new Promise((t=>setTimeout(t,e))),Ce=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new O(`${e} must be an integer`);if(t<0)throw new O(`${e} must be a positive integer`);return t},ke=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e)try{return new Error(JSON.stringify(e))}catch{}return new Error(e)},$e=e=>"undefined"!=typeof process?process.env?.[e]?.trim()??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e)?.trim():void 0;function Oe(e){if(!e)return!0;for(const t in e)return!1;return!0}function Te(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function je(e,t){for(const s in t){if(!Te(t,s))continue;const n=s.toLowerCase();if(!n)continue;const r=t[s];null===r?delete e[n]:void 0!==r&&(e[n]=r)}}const Me=new Set(["authorization","api-key"]);function Ne(e,...t){if("undefined"!=typeof process&&"true"===process?.env?.DEBUG){const s=t.map((e=>{if(!e)return e;if(e.headers){const t={...e,headers:{...e.headers}};for(const s in e.headers)Me.has(s.toLowerCase())&&(t.headers[s]="REDACTED");return t}let t=null;for(const s in e)Me.has(s.toLowerCase())&&(t??(t={...e}),t[s]="REDACTED");return t??e}));console.log(`OpenAI:DEBUG:${e}`,...s)}}const qe=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})),De=(e,t)=>{const s=t.toLowerCase();if((e=>"function"==typeof e?.get)(e)){const n=t[0]?.toUpperCase()+t.substring(1).replace(/([^\w])(\w)/g,((e,t,s)=>t+s.toUpperCase()));for(const r of[t,s,t.toUpperCase(),n]){const t=e.get(r);if(t)return t}}for(const[n,r]of Object.entries(e))if(n.toLowerCase()===s)return Array.isArray(r)?(r.length<=1||console.warn(`Received ${r.length} entries for the ${t} header, using the first entry.`),r[0]):r};function Be(e){return null!=e&&"object"==typeof e&&!Array.isArray(e)}class Le extends me{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class Fe extends me{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data||[]}getPaginatedItems(){return this.data??[]}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){const e=this.getPaginatedItems();if(!e.length)return null;const t=e[e.length-1]?.id;return t?{params:{after:t}}:null}}class We{constructor(e){this._client=e}}let Ue=class extends We{create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}},Xe=class extends We{constructor(){super(...arguments),this.completions=new Ue(this._client)}};Xe.Completions=Ue;class Je extends We{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}}class He extends We{create(e,t){return this._client.post("/audio/transcriptions",oe({body:e,...t}))}}class Ve extends We{create(e,t){return this._client.post("/audio/translations",oe({body:e,...t}))}}class Ke extends We{constructor(){super(...arguments),this.transcriptions=new He(this._client),this.translations=new Ve(this._client),this.speech=new Je(this._client)}}Ke.Transcriptions=He,Ke.Translations=Ve,Ke.Speech=Je;class ze extends We{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return be(e)?this.list({},e):this._client.getAPIList("/batches",Ge,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class Ge extends Fe{}ze.BatchesPage=Ge;class Qe extends We{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,s){return this._client.post(`/assistants/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e={},t){return be(e)?this.list({},e):this._client.getAPIList("/assistants",Ye,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class Ye extends Fe{}function Ze(e){return"function"==typeof e.parse}Qe.AssistantsPage=Ye;const et=e=>"assistant"===e?.role,tt=e=>"function"===e?.role,st=e=>"tool"===e?.role;var nt,rt,ot,at,it,lt,ct,ut,ht,dt,ft,pt,mt,gt=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},yt=function(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)};class wt{constructor(){nt.add(this),this.controller=new AbortController,rt.set(this,void 0),ot.set(this,(()=>{})),at.set(this,(()=>{})),it.set(this,void 0),lt.set(this,(()=>{})),ct.set(this,(()=>{})),ut.set(this,{}),ht.set(this,!1),dt.set(this,!1),ft.set(this,!1),pt.set(this,!1),gt(this,rt,new Promise(((e,t)=>{gt(this,ot,e,"f"),gt(this,at,t,"f")})),"f"),gt(this,it,new Promise(((e,t)=>{gt(this,lt,e,"f"),gt(this,ct,t,"f")})),"f"),yt(this,rt,"f").catch((()=>{})),yt(this,it,"f").catch((()=>{}))}_run(e){setTimeout((()=>{e().then((()=>{this._emitFinal(),this._emit("end")}),yt(this,nt,"m",mt).bind(this))}),0)}_connected(){this.ended||(yt(this,ot,"f").call(this),this._emit("connect"))}get ended(){return yt(this,ht,"f")}get errored(){return yt(this,dt,"f")}get aborted(){return yt(this,ft,"f")}abort(){this.controller.abort()}on(e,t){return(yt(this,ut,"f")[e]||(yt(this,ut,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=yt(this,ut,"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(yt(this,ut,"f")[e]||(yt(this,ut,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise(((t,s)=>{gt(this,pt,!0,"f"),"error"!==e&&this.once("error",s),this.once(e,t)}))}async done(){gt(this,pt,!0,"f"),await yt(this,it,"f")}_emit(e,...t){if(yt(this,ht,"f"))return;"end"===e&&(gt(this,ht,!0,"f"),yt(this,lt,"f").call(this));const s=yt(this,ut,"f")[e];if(s&&(yt(this,ut,"f")[e]=s.filter((e=>!e.once)),s.forEach((({listener:e})=>e(...t)))),"abort"===e){const e=t[0];return yt(this,pt,"f")||s?.length||Promise.reject(e),yt(this,at,"f").call(this,e),yt(this,ct,"f").call(this,e),void this._emit("end")}if("error"===e){const e=t[0];yt(this,pt,"f")||s?.length||Promise.reject(e),yt(this,at,"f").call(this,e),yt(this,ct,"f").call(this,e),this._emit("end")}}_emitFinal(){}}function bt(e){return"auto-parseable-response-format"===e?.$brand}function _t(e){return"auto-parseable-tool"===e?.$brand}function vt(e,t){const s=e.choices.map((e=>{if("length"===e.finish_reason)throw new J;if("content_filter"===e.finish_reason)throw new H;return{...e,message:{...e.message,tool_calls:e.message.tool_calls?.map((e=>function(e,t){const s=e.tools?.find((e=>e.function?.name===t.function.name));return{...t,function:{...t.function,parsed_arguments:_t(s)?s.$parseRaw(t.function.arguments):s?.function.strict?JSON.parse(t.function.arguments):null}}}(t,e)))??[],parsed:e.message.content&&!e.message.refusal?xt(t,e.message.content):null}}}));return{...e,choices:s}}function xt(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)return!1;const s=e.tools?.find((e=>e.function?.name===t.function.name));return _t(s)||s?.function.strict||!1}function At(e){return!!bt(e.response_format)||(e.tools?.some((e=>_t(e)||"function"===e.type&&!0===e.function.strict))??!1)}rt=new WeakMap,ot=new WeakMap,at=new WeakMap,it=new WeakMap,lt=new WeakMap,ct=new WeakMap,ut=new WeakMap,ht=new WeakMap,dt=new WeakMap,ft=new WeakMap,pt=new WeakMap,nt=new WeakSet,mt=function(e){if(gt(this,dt,!0,"f"),e instanceof Error&&"AbortError"===e.name&&(e=new j),e instanceof j)return gt(this,ft,!0,"f"),this._emit("abort",e);if(e instanceof O)return this._emit("error",e);if(e instanceof Error){const t=new O(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new O(String(e)))};var Et,Rt,It,Pt,Ct,kt,$t,Ot,Tt=function(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)};const jt=10;class Mt extends wt{constructor(){super(...arguments),Et.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t)if(this._emit("message",e),(tt(e)||st(e))&&e.content)this._emit("functionCallResult",e.content);else if(et(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(et(e)&&e.tool_calls)for(const t of e.tool_calls)"function"===t.type&&this._emit("functionCall",t.function)}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new O("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Tt(this,Et,"m",Rt).call(this)}async finalMessage(){return await this.done(),Tt(this,Et,"m",It).call(this)}async finalFunctionCall(){return await this.done(),Tt(this,Et,"m",Pt).call(this)}async finalFunctionCallResult(){return await this.done(),Tt(this,Et,"m",Ct).call(this)}async totalUsage(){return await this.done(),Tt(this,Et,"m",kt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Tt(this,Et,"m",It).call(this);t&&this._emit("finalMessage",t);const s=Tt(this,Et,"m",Rt).call(this);s&&this._emit("finalContent",s);const n=Tt(this,Et,"m",Pt).call(this);n&&this._emit("finalFunctionCall",n);const r=Tt(this,Et,"m",Ct).call(this);null!=r&&this._emit("finalFunctionCallResult",r),this._chatCompletions.some((e=>e.usage))&&this._emit("totalUsage",Tt(this,Et,"m",kt).call(this))}async _createChatCompletion(e,t,s){const n=s?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",(()=>this.controller.abort()))),Tt(this,Et,"m",$t).call(this,t);const r=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(vt(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 _runFunctions(e,t,s){const n="function",{function_call:r="auto",stream:o,...a}=t,i="string"!=typeof r&&r?.name,{maxChatCompletions:l=jt}=s||{},c={};for(const e of t.functions)c[e.name||e.function.name]=e;const u=t.functions.map((e=>({name:e.name||e.function.name,parameters:e.parameters,description:e.description})));for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<l;++t){const t=await this._createChatCompletion(e,{...a,function_call:r,functions:u,messages:[...this.messages]},s),o=t.choices[0]?.message;if(!o)throw new O("missing message in ChatCompletion response");if(!o.function_call)return;const{name:l,arguments:h}=o.function_call,d=c[l];if(!d){const e=`Invalid function_call: ${JSON.stringify(l)}. Available options are: ${u.map((e=>JSON.stringify(e.name))).join(", ")}. Please try again`;this._addMessage({role:n,name:l,content:e});continue}if(i&&i!==l){const e=`Invalid function_call: ${JSON.stringify(l)}. ${JSON.stringify(i)} requested. Please try again`;this._addMessage({role:n,name:l,content:e});continue}let f;try{f=Ze(d)?await d.parse(h):h}catch(e){this._addMessage({role:n,name:l,content:e instanceof Error?e.message:String(e)});continue}const p=await d.function(f,this),m=Tt(this,Et,"m",Ot).call(this,p);if(this._addMessage({role:n,name:l,content:m}),i)return}}async _runTools(e,t,s){const n="tool",{tool_choice:r="auto",stream:o,...a}=t,i="string"!=typeof r&&r?.function?.name,{maxChatCompletions:l=jt}=s||{},c=t.tools.map((e=>{if(_t(e)){if(!e.$callback)throw new O("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:e.$callback,name:e.function.name,description:e.function.description||"",parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e})),u={};for(const e of c)"function"===e.type&&(u[e.function.name||e.function.function.name]=e.function);const h="tools"in t?c.map((e=>"function"===e.type?{type:"function",function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e)):void 0;for(const e of t.messages)this._addMessage(e,!1);for(let t=0;t<l;++t){const t=await this._createChatCompletion(e,{...a,tool_choice:r,tools:h,messages:[...this.messages]},s),o=t.choices[0]?.message;if(!o)throw new O("missing message in ChatCompletion response");if(!o.tool_calls?.length)return;for(const e of o.tool_calls){if("function"!==e.type)continue;const t=e.id,{name:s,arguments:r}=e.function,o=u[s];if(!o){const e=`Invalid tool_call: ${JSON.stringify(s)}. Available options are: ${Object.keys(u).map((e=>JSON.stringify(e))).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}if(i&&i!==s){const e=`Invalid tool_call: ${JSON.stringify(s)}. ${JSON.stringify(i)} requested. Please try again`;this._addMessage({role:n,tool_call_id:t,content:e});continue}let a;try{a=Ze(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(a,this),c=Tt(this,Et,"m",Ot).call(this,l);if(this._addMessage({role:n,tool_call_id:t,content:c}),i)return}}}}Et=new WeakSet,Rt=function(){return Tt(this,Et,"m",It).call(this).content??null},It=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(et(t)){const{function_call:e,...s}=t,n={...s,content:t.content??null,refusal:t.refusal??null};return e&&(n.function_call=e),n}}throw new O("stream ended without producing a ChatCompletionMessage with role=assistant")},Pt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(et(t)&&t?.function_call)return t.function_call;if(et(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Ct=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(tt(t)&&null!=t.content)return t.content;if(st(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}},kt=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},$t=function(e){if(null!=e.n&&e.n>1)throw new O("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ot=function(e){return"string"==typeof e?e:void 0===e?"undefined":JSON.stringify(e)};class Nt extends Mt{static runFunctions(e,t,s){const n=new Nt,r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,r))),n}static runTools(e,t,s){const n=new Nt,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),et(e)&&e.content&&this._emit("content",e.content)}}const qt=1,Dt=2,Bt=4,Lt=8,Ft=16,Wt=32,Ut=64,Xt=128,Jt=256,Ht=511;class Vt extends Error{}class Kt extends Error{}const zt=(e,t)=>{const s=e.length;let n=0;const r=e=>{throw new Vt(`${e} at position ${n}`)},o=e=>{throw new Kt(`${e} at position ${n}`)},a=()=>(h(),n>=s&&r("Unexpected end of input"),'"'===e[n]?i():"{"===e[n]?l():"["===e[n]?c():"null"===e.substring(n,n+4)||Ft&t&&s-n<4&&"null".startsWith(e.substring(n))?(n+=4,null):"true"===e.substring(n,n+4)||Wt&t&&s-n<4&&"true".startsWith(e.substring(n))?(n+=4,!0):"false"===e.substring(n,n+5)||Wt&t&&s-n<5&&"false".startsWith(e.substring(n))?(n+=5,!1):"Infinity"===e.substring(n,n+8)||Xt&t&&s-n<8&&"Infinity".startsWith(e.substring(n))?(n+=8,1/0):"-Infinity"===e.substring(n,n+9)||Jt&t&&1<s-n&&s-n<9&&"-Infinity".startsWith(e.substring(n))?(n+=9,-1/0):"NaN"===e.substring(n,n+3)||Ut&t&&s-n<3&&"NaN".startsWith(e.substring(n))?(n+=3,NaN):u()),i=()=>{const a=n;let i=!1;for(n++;n<s&&('"'!==e[n]||i&&"\\"===e[n-1]);)i="\\"===e[n]&&!i,n++;if('"'==e.charAt(n))try{return JSON.parse(e.substring(a,++n-Number(i)))}catch(e){o(String(e))}else if(qt&t)try{return JSON.parse(e.substring(a,n-Number(i))+'"')}catch(t){return JSON.parse(e.substring(a,e.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{n++,h();const o={};try{for(;"}"!==e[n];){if(h(),n>=s&&Lt&t)return o;const r=i();h(),n++;try{const e=a();Object.defineProperty(o,r,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(Lt&t)return o;throw e}h(),","===e[n]&&n++}}catch(e){if(Lt&t)return o;r("Expected '}' at end of object")}return n++,o},c=()=>{n++;const s=[];try{for(;"]"!==e[n];)s.push(a()),h(),","===e[n]&&n++}catch(e){if(Bt&t)return s;r("Expected ']' at end of array")}return n++,s},u=()=>{if(0===n){"-"===e&&Dt&t&&r("Not sure what '-' is");try{return JSON.parse(e)}catch(s){if(Dt&t)try{return"."===e[e.length-1]?JSON.parse(e.substring(0,e.lastIndexOf("."))):JSON.parse(e.substring(0,e.lastIndexOf("e")))}catch(e){}o(String(s))}}const a=n;for("-"===e[n]&&n++;e[n]&&!",]}".includes(e[n]);)n++;n!=s||Dt&t||r("Unterminated number literal");try{return JSON.parse(e.substring(a,n))}catch(s){"-"===e.substring(a,n)&&Dt&t&&r("Not sure what '-' is");try{return JSON.parse(e.substring(a,e.lastIndexOf("e")))}catch(e){o(String(e))}}},h=()=>{for(;n<s&&" \n\r\t".includes(e[n]);)n++};return a()},Gt=e=>function(e,t=Ht){if("string"!=typeof e)throw new TypeError("expecting str, got "+typeof e);if(!e.trim())throw new Error(`${e} is empty`);return zt(e.trim(),t)}(e,Ht^Dt);var Qt,Yt,Zt,es,ts,ss,ns,rs,os,as,is,ls,cs=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},us=function(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)};class hs extends Mt{constructor(e){super(),Qt.add(this),Yt.set(this,void 0),Zt.set(this,void 0),es.set(this,void 0),cs(this,Yt,e,"f"),cs(this,Zt,[],"f")}get currentChatCompletionSnapshot(){return us(this,es,"f")}static fromReadableStream(e){const t=new hs(null);return t._run((()=>t._fromReadableStream(e))),t}static createChatCompletion(e,t,s){const n=new hs(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()))),us(this,Qt,"m",ts).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)us(this,Qt,"m",ns).call(this,e);if(r.controller.signal?.aborted)throw new j;return this._addChatCompletion(us(this,Qt,"m",as).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",(()=>this.controller.abort()))),us(this,Qt,"m",ts).call(this),this._connected();const n=z.fromReadableStream(e,this.controller);let r;for await(const e of n)r&&r!==e.id&&this._addChatCompletion(us(this,Qt,"m",as).call(this)),us(this,Qt,"m",ns).call(this,e),r=e.id;if(n.controller.signal?.aborted)throw new j;return this._addChatCompletion(us(this,Qt,"m",as).call(this))}[(Yt=new WeakMap,Zt=new WeakMap,es=new WeakMap,Qt=new WeakSet,ts=function(){this.ended||cs(this,es,void 0,"f")},ss=function(e){let t=us(this,Zt,"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},us(this,Zt,"f")[e.index]=t,t)},ns=function(e){if(this.ended)return;const t=us(this,Qt,"m",ls).call(this,e);this._emit("chunk",e,t);for(const s of e.choices){const e=t.choices[s.index];null!=s.delta.content&&"assistant"===e.message?.role&&e.message?.content&&(this._emit("content",s.delta.content,e.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),null!=s.delta.refusal&&"assistant"===e.message?.role&&e.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:e.message.refusal}),null!=s.logprobs?.content&&"assistant"===e.message?.role&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:e.logprobs?.content??[]}),null!=s.logprobs?.refusal&&"assistant"===e.message?.role&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});const n=us(this,Qt,"m",ss).call(this,e);e.finish_reason&&(us(this,Qt,"m",os).call(this,e),null!=n.current_tool_call_index&&us(this,Qt,"m",rs).call(this,e,n.current_tool_call_index));for(const t of s.delta.tool_calls??[])n.current_tool_call_index!==t.index&&(us(this,Qt,"m",os).call(this,e),null!=n.current_tool_call_index&&us(this,Qt,"m",rs).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??""}))}}},rs=function(e,t){if(us(this,Qt,"m",ss).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=us(this,Yt,"f")?.tools?.find((e=>"function"===e.type&&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:_t(e)?e.$parseRaw(s.function.arguments):e?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},os=function(e){const t=us(this,Qt,"m",ss).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;const s=us(this,Qt,"m",is).call(this);this._emit("content.done",{content:e.message.content,parsed:s?s.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit("refusal.done",{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:e.logprobs.refusal}))},as=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");const e=us(this,es,"f");if(!e)throw new O("request ended without sending any chunks");return cs(this,es,void 0,"f"),cs(this,Zt,[],"f"),function(e,t){const{id:s,choices:n,created:r,model:o,system_fingerprint:a,...i}=e,l={...i,id:s,choices:n.map((({message:t,finish_reason:s,index:n,logprobs:r,...o})=>{if(!s)throw new O(`missing finish_reason for choice ${n}`);const{content:a=null,function_call:i,tool_calls:l,...c}=t,u=t.role;if(!u)throw new O(`missing role for choice ${n}`);if(i){const{arguments:e,name:l}=i;if(null==e)throw new O(`missing function_call.arguments for choice ${n}`);if(!l)throw new O(`missing function_call.name for choice ${n}`);return{...o,message:{content:a,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:a,refusal:t.refusal??null,tool_calls:l.map(((t,s)=>{const{function:r,type:o,id:a,...i}=t,{arguments:l,name:c,...u}=r||{};if(null==a)throw new O(`missing choices[${n}].tool_calls[${s}].id\n${ds(e)}`);if(null==o)throw new O(`missing choices[${n}].tool_calls[${s}].type\n${ds(e)}`);if(null==c)throw new O(`missing choices[${n}].tool_calls[${s}].function.name\n${ds(e)}`);if(null==l)throw new O(`missing choices[${n}].tool_calls[${s}].function.arguments\n${ds(e)}`);return{...i,id:a,type:o,function:{...u,name:c,arguments:l}}}))}}:{...o,message:{...c,content:a,role:u,refusal:t.refusal??null},finish_reason:s,index:n,logprobs:r}})),created:r,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return function(e,t){return t&&At(t)?vt(e,t):{...e,choices:e.choices.map((e=>({...e,message:{...e.message,parsed:null,tool_calls:e.message.tool_calls??[]}})))}}(l,t)}(e,us(this,Yt,"f"))},is=function(){const e=us(this,Yt,"f")?.response_format;return bt(e)?e:null},ls=function(e){var t,s,n,r;let o=us(this,es,"f");const{choices:a,...i}=e;o?Object.assign(o,i):o=cs(this,es,{...i,choices:[]},"f");for(const{delta:a,finish_reason:i,index:l,logprobs:c=null,...u}of e.choices){let e=o.choices[l];if(e||(e=o.choices[l]={finish_reason:i,index:l,message:{},logprobs:c,...u}),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(i&&(e.finish_reason=i,us(this,Yt,"f")&&At(us(this,Yt,"f")))){if("length"===i)throw new J;if("content_filter"===i)throw new H}if(Object.assign(e,u),!a)continue;const{content:h,refusal:d,function_call:f,role:p,tool_calls:m,...g}=a;if(Object.assign(e.message,g),d&&(e.message.refusal=(e.message.refusal||"")+d),p&&(e.message.role=p),f&&(e.message.function_call?(f.name&&(e.message.function_call.name=f.name),f.arguments&&((n=e.message.function_call).arguments??(n.arguments=""),e.message.function_call.arguments+=f.arguments)):e.message.function_call=f),h&&(e.message.content=(e.message.content||"")+h,!e.message.refusal&&us(this,Qt,"m",is).call(this)&&(e.message.parsed=Gt(e.message.content))),m){e.message.tool_calls||(e.message.tool_calls=[]);for(const{index:t,id:s,type:n,function:o,...a}of m){const i=(r=e.message.tool_calls)[t]??(r[t]={});Object.assign(i,a),s&&(i.id=s),n&&(i.type=n),o&&(i.function??(i.function={name:o.name??"",arguments:""})),o?.name&&(i.function.name=o.name),o?.arguments&&(i.function.arguments+=o.arguments,St(us(this,Yt,"f"),i)&&(i.function.parsed_arguments=Gt(i.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 z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function ds(e){return JSON.stringify(e)}class fs extends hs{static fromReadableStream(e){const t=new fs(null);return t._run((()=>t._fromReadableStream(e))),t}static runFunctions(e,t,s){const n=new fs(null),r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run((()=>n._runFunctions(e,t,r))),n}static runTools(e,t,s){const n=new fs(t),r={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run((()=>n._runTools(e,t,r))),n}}let ps=class extends We{parse(e,t){return function(e){for(const t of e??[]){if("function"!==t.type)throw new O(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(!0!==t.function.strict)throw new O(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap((t=>vt(t,e)))}runFunctions(e,t){return e.stream?fs.runFunctions(this._client,e,t):Nt.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?fs.runTools(this._client,e,t):Nt.runTools(this._client,e,t)}stream(e,t){return hs.createChatCompletion(this._client,e,t)}};class ms extends We{constructor(){super(...arguments),this.completions=new ps(this._client)}}!function(e){e.Completions=ps}(ms||(ms={}));class gs extends We{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class ys extends We{constructor(){super(...arguments),this.sessions=new gs(this._client)}}ys.Sessions=gs;var ws,bs,_s,vs,xs,Ss,As,Es,Rs,Is,Ps,Cs,ks,$s,Os,Ts,js,Ms,Ns,qs,Ds,Bs,Ls=function(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)},Fs=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s};class Ws extends wt{constructor(){super(...arguments),ws.add(this),bs.set(this,[]),_s.set(this,{}),vs.set(this,{}),xs.set(this,void 0),Ss.set(this,void 0),As.set(this,void 0),Es.set(this,void 0),Rs.set(this,void 0),Is.set(this,void 0),Ps.set(this,void 0),Cs.set(this,void 0),ks.set(this,void 0)}[(bs=new WeakMap,_s=new WeakMap,vs=new WeakMap,xs=new WeakMap,Ss=new WeakMap,As=new WeakMap,Es=new WeakMap,Rs=new WeakMap,Is=new WeakMap,Ps=new WeakMap,Cs=new WeakMap,ks=new WeakMap,ws=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 Ws;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=z.fromReadableStream(e,this.controller);for await(const e of n)Ls(this,ws,"m",$s).call(this,e);if(n.controller.signal?.aborted)throw new j;return this._addRun(Ls(this,ws,"m",Os).call(this))}toReadableStream(){return new z(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,n,r){const o=new Ws;return o._run((()=>o._runToolAssistantStream(e,t,s,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}}))),o}async _createToolAssistantStream(e,t,s,n,r){const o=r?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",(()=>this.controller.abort())));const a={...n,stream:!0},i=await e.submitToolOutputs(t,s,a,{...r,signal:this.controller.signal});this._connected();for await(const e of i)Ls(this,ws,"m",$s).call(this,e);if(i.controller.signal?.aborted)throw new j;return this._addRun(Ls(this,ws,"m",Os).call(this))}static createThreadAssistantStream(e,t,s){const n=new Ws;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 Ws;return r._run((()=>r._runAssistantStream(e,t,s,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}}))),r}currentEvent(){return Ls(this,Ps,"f")}currentRun(){return Ls(this,Cs,"f")}currentMessageSnapshot(){return Ls(this,xs,"f")}currentRunStepSnapshot(){return Ls(this,ks,"f")}async finalRunSteps(){return await this.done(),Object.values(Ls(this,_s,"f"))}async finalMessages(){return await this.done(),Object.values(Ls(this,vs,"f"))}async finalRun(){if(await this.done(),!Ls(this,Ss,"f"))throw Error("Final run was not received.");return Ls(this,Ss,"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)Ls(this,ws,"m",$s).call(this,e);if(o.controller.signal?.aborted)throw new j;return this._addRun(Ls(this,ws,"m",Os).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},a=await e.create(t,o,{...n,signal:this.controller.signal});this._connected();for await(const e of a)Ls(this,ws,"m",$s).call(this,e);if(a.controller.signal?.aborted)throw new j;return this._addRun(Ls(this,ws,"m",Os).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(!Be(t)||!Be(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(!Be(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,r){return await this._createToolAssistantStream(s,e,t,n,r)}}$s=function(e){if(!this.ended)switch(Fs(this,Ps,e,"f"),Ls(this,ws,"m",Ms).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":Ls(this,ws,"m",Bs).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":Ls(this,ws,"m",js).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":Ls(this,ws,"m",Ts).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Os=function(){if(this.ended)throw new O("stream has ended, this shouldn't happen");if(!Ls(this,Ss,"f"))throw Error("Final run has not been received");return Ls(this,Ss,"f")},Ts=function(e){const[t,s]=Ls(this,ws,"m",qs).call(this,e,Ls(this,xs,"f"));Fs(this,xs,t,"f"),Ls(this,vs,"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!=Ls(this,As,"f")){if(Ls(this,Es,"f"))switch(Ls(this,Es,"f").type){case"text":this._emit("textDone",Ls(this,Es,"f").text,Ls(this,xs,"f"));break;case"image_file":this._emit("imageFileDone",Ls(this,Es,"f").image_file,Ls(this,xs,"f"))}Fs(this,As,s.index,"f")}Fs(this,Es,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(void 0!==Ls(this,As,"f")){const t=e.data.content[Ls(this,As,"f")];if(t)switch(t.type){case"image_file":this._emit("imageFileDone",t.image_file,Ls(this,xs,"f"));break;case"text":this._emit("textDone",t.text,Ls(this,xs,"f"))}}Ls(this,xs,"f")&&this._emit("messageDone",e.data),Fs(this,xs,void 0,"f")}},js=function(e){const t=Ls(this,ws,"m",Ns).call(this,e);switch(Fs(this,ks,t,"f"),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==Ls(this,Rs,"f")?this._emit("toolCallDelta",e,t.step_details.tool_calls[e.index]):(Ls(this,Is,"f")&&this._emit("toolCallDone",Ls(this,Is,"f")),Fs(this,Rs,e.index,"f"),Fs(this,Is,t.step_details.tool_calls[e.index],"f"),Ls(this,Is,"f")&&this._emit("toolCallCreated",Ls(this,Is,"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":Fs(this,ks,void 0,"f");"tool_calls"==e.data.step_details.type&&Ls(this,Is,"f")&&(this._emit("toolCallDone",Ls(this,Is,"f")),Fs(this,Is,void 0,"f")),this._emit("runStepDone",e.data,t)}},Ms=function(e){Ls(this,bs,"f").push(e),this._emit("event",e)},Ns=function(e){switch(e.event){case"thread.run.step.created":return Ls(this,_s,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=Ls(this,_s,"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=Ws.accumulateDelta(t,s.delta);Ls(this,_s,"f")[e.data.id]=n}return Ls(this,_s,"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":Ls(this,_s,"f")[e.data.id]=e.data}if(Ls(this,_s,"f")[e.data.id])return Ls(this,_s,"f")[e.data.id];throw new Error("No snapshot available")},qs=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]=Ls(this,ws,"m",Ds).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")},Ds=function(e,t){return Ws.accumulateDelta(t,e)},Bs=function(e){switch(Fs(this,Cs,e.data,"f"),e.event){case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":Fs(this,Ss,e.data,"f"),Ls(this,Is,"f")&&(this._emit("toolCallDone",Ls(this,Is,"f")),Fs(this,Is,void 0,"f"))}};class Us extends We{create(e,t,s){return this._client.post(`/threads/${e}/messages`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}retrieve(e,t,s){return this._client.get(`/threads/${e}/messages/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}update(e,t,s,n){return this._client.post(`/threads/${e}/messages/${t}`,{body:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},s){return be(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Xs,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}del(e,t,s){return this._client.delete(`/threads/${e}/messages/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}}class Xs extends Fe{}Us.MessagesPage=Xs;class Js extends We{retrieve(e,t,s,n={},r){return be(n)?this.retrieve(e,t,s,{},n):this._client.get(`/threads/${e}/runs/${t}/steps/${s}`,{query:n,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e,t,s={},n){return be(s)?this.list(e,t,{},s):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Hs,{query:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}}class Hs extends Fe{}Js.RunStepsPage=Hs;class Vs extends We{constructor(){super(...arguments),this.steps=new Js(this._client)}create(e,t,s){const{include:n,...r}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:n},body:r,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers},stream:t.stream??!1})}retrieve(e,t,s){return this._client.get(`/threads/${e}/runs/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}update(e,t,s,n){return this._client.post(`/threads/${e}/runs/${t}`,{body:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},s){return be(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Ks,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}cancel(e,t,s){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...s,headers:{"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)}createAndStream(e,t,s){return Ws.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const n={...s?.headers,"X-Stainless-Poll-Helper":"true"};for(s?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){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 Pe(e);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return r}}}stream(e,t,s){return Ws.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s,n){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:s.stream??!1})}async submitToolOutputsAndPoll(e,t,s,n){const r=await this.submitToolOutputs(e,t,s,n);return await this.poll(e,r.id,n)}submitToolOutputsStream(e,t,s,n){return Ws.createToolAssistantStream(e,t,this._client.beta.threads.runs,s,n)}}class Ks extends Fe{}Vs.RunsPage=Ks,Vs.Steps=Js,Vs.RunStepsPage=Hs;class zs extends We{constructor(){super(...arguments),this.runs=new Vs(this._client),this.messages=new Us(this._client)}create(e={},t){return be(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,s){return this._client.post(`/threads/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.thread_id,s.id,t)}createAndRunStream(e,t){return Ws.createThreadAssistantStream(e,this._client.beta.threads,t)}}zs.Runs=Vs,zs.RunsPage=Ks,zs.Messages=Us,zs.MessagesPage=Xs;let Gs=class extends We{create(e,t,s){return this._client.post(`/vector_stores/${e}/files`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}retrieve(e,t,s){return this._client.get(`/vector_stores/${e}/files/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t={},s){return be(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,Qs,{query:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}del(e,t,s){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...s,headers:{"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={...s?.headers,"X-Stainless-Poll-Helper":"true"};for(s?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){const r=await this.retrieve(e,t,{...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 Pe(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)}};class Qs extends Fe{}Gs.VectorStoreFilesPage=Qs;class Ys extends We{create(e,t,s){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}retrieve(e,t,s){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}cancel(e,t,s){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...s,headers:{"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={},n){return be(s)?this.listFiles(e,t,{},s):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,Qs,{query:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async poll(e,t,s){const n={...s?.headers,"X-Stainless-Poll-Helper":"true"};for(s?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=s.pollIntervalMs.toString());;){const{data:r,response:o}=await this.retrieve(e,t,{...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 Pe(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),a=this._client,i=t.values(),l=[...s];const c=Array(o).fill(i).map((async function(e){for(let t of e){const e=await a.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 Zs extends We{constructor(){super(...arguments),this.files=new Gs(this._client),this.fileBatches=new Ys(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,s){return this._client.post(`/vector_stores/${e}`,{body:t,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e={},t){return be(e)?this.list({},e):this._client.getAPIList("/vector_stores",en,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}}class en extends Fe{}Zs.VectorStoresPage=en,Zs.Files=Gs,Zs.VectorStoreFilesPage=Qs,Zs.FileBatches=Ys;class tn extends We{constructor(){super(...arguments),this.realtime=new ys(this._client),this.vectorStores=new Zs(this._client),this.chat=new ms(this._client),this.assistants=new Qe(this._client),this.threads=new zs(this._client)}}tn.Realtime=ys,tn.VectorStores=Zs,tn.VectorStoresPage=en,tn.Assistants=Qe,tn.AssistantsPage=Ye,tn.Threads=zs;class sn extends We{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class nn extends We{create(e,t){return this._client.post("/embeddings",{body:e,...t})}}class rn extends We{create(e,t){return this._client.post("/files",oe({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return be(e)?this.list({},e):this._client.getAPIList("/files",on,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait: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 Pe(t),o=await this.retrieve(e),Date.now()-r>s)throw new N({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return o}}class on extends Fe{}rn.FileObjectsPage=on;class an extends We{list(e,t={},s){return be(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,ln,{query:t,...s})}}class ln extends Fe{}an.FineTuningJobCheckpointsPage=ln;class cn extends We{constructor(){super(...arguments),this.checkpoints=new an(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return be(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",un,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return be(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,hn,{query:t,...s})}}class un extends Fe{}class hn extends Fe{}cn.FineTuningJobsPage=un,cn.FineTuningJobEventsPage=hn,cn.Checkpoints=an,cn.FineTuningJobCheckpointsPage=ln;class dn extends We{constructor(){super(...arguments),this.jobs=new cn(this._client)}}dn.Jobs=cn,dn.FineTuningJobsPage=un,dn.FineTuningJobEventsPage=hn;class fn extends We{createVariation(e,t){return this._client.post("/images/variations",oe({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",oe({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class pn extends We{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",mn,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class mn extends Le{}pn.ModelsPage=mn;class gn extends We{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class yn extends We{create(e,t,s){return this._client.post(`/uploads/${e}/parts`,oe({body:t,...s}))}}class wn extends We{constructor(){super(...arguments),this.parts=new yn(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(`/uploads/${e}/complete`,{body:t,...s})}}var bn;wn.Parts=yn;class _n extends pe{constructor({baseURL:e=$e("OPENAI_BASE_URL"),apiKey:t=$e("OPENAI_API_KEY"),organization:s=$e("OPENAI_ORG_ID")??null,project:n=$e("OPENAI_PROJECT_ID")??null,...r}={}){if(void 0===t)throw new O("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const o={apiKey:t,organization:s,project:n,...r,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new O("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new sn(this),this.chat=new Xe(this),this.embeddings=new nn(this),this.files=new rn(this),this.images=new fn(this),this.audio=new Ke(this),this.moderations=new gn(this),this.models=new pn(this),this.fineTuning=new dn(this),this.beta=new tn(this),this.batches=new ze(this),this.uploads=new wn(this),this._options=o,this.apiKey=t,this.organization=s,this.project=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return b(e,{arrayFormat:"brackets"})}}function vn({msg:e,isError:t,isInfinite:s}){const n=document.querySelector("#message");n.style.color=t?"red":"limegreen",n.textContent=e,n.style.display="block",s||setTimeout((()=>n.style.display="none"),5e3)}bn=_n,_n.OpenAI=bn,_n.DEFAULT_TIMEOUT=6e5,_n.OpenAIError=O,_n.APIError=T,_n.APIConnectionError=M,_n.APIConnectionTimeoutError=N,_n.APIUserAbortError=j,_n.NotFoundError=L,_n.ConflictError=F,_n.RateLimitError=U,_n.BadRequestError=q,_n.AuthenticationError=D,_n.InternalServerError=X,_n.PermissionDeniedError=B,_n.UnprocessableEntityError=W,_n.toFile=te,_n.fileFromPath=P,_n.Completions=sn,_n.Chat=Xe,_n.Embeddings=nn,_n.Files=rn,_n.FileObjectsPage=on,_n.Images=fn,_n.Audio=Ke,_n.Moderations=gn,_n.Models=pn,_n.ModelsPage=mn,_n.FineTuning=dn,_n.Beta=tn,_n.Batches=ze,_n.BatchesPage=Ge,_n.Uploads=wn;const xn=document.querySelector("#apiKey"),Sn=document.querySelector("#model"),An=document.querySelector("#models"),En=document.querySelector("#includeImages-line"),Rn=document.querySelector("#baseURL");function In(){!function(e){const t=e.match(/gpt-(\d+)/);return!!(null==t?void 0:t[1])&&Number(t[1])>=4}(Sn.value)?En.style.display="none":En.style.display="flex"}Sn.addEventListener("input",In),Sn.addEventListener("focus",(function(){return n(this,void 0,void 0,(function*(){var e,t;const s=null===(e=xn.value)||void 0===e?void 0:e.trim(),n=null===(t=Rn.value)||void 0===t?void 0:t.trim();if(s){Sn.innerHTML="";try{const e=new _n({apiKey:s,baseURL:n,dangerouslyAllowBrowser:!0}),t=(yield e.models.list()).data.filter((e=>e.id.startsWith("gpt")||e.id.startsWith("o1")||e.id.startsWith("chatgpt")));t.sort(((e,t)=>t.id.localeCompare(e.id)));for(const e of t){const t=document.createElement("option");t.value=e.id,t.textContent=e.id,An.appendChild(t)}In()}catch(e){console.error(e),vn({msg:e,isError:!0})}}}))}));document.querySelector("#check-model").addEventListener("click",(function(){return n(this,void 0,void 0,(function*(){var e,t,s;const n=null===(e=Sn.value)||void 0===e?void 0:e.trim(),r=null===(t=xn.value)||void 0===t?void 0:t.trim(),o=null===(s=Rn.value)||void 0===s?void 0:s.trim();try{vn({msg:"Checking GPT version...",isInfinite:!0,isError:!1});const e=new _n({apiKey:r,baseURL:o,dangerouslyAllowBrowser:!0});yield e.chat.completions.create({model:n,messages:[{role:"user",content:"reply just pong"}]}),vn({msg:"The model is valid!"})}catch(e){vn({msg:e,isError:!0})}}))}));const Pn=["includeImages"],Cn={autocomplete:[],clipboard:["typing","mouseover"],"question-to-answer":["typing","infinite","mouseover"]};function kn(){const s=Cn[e.actualMode],n=t.filter((e=>!s.includes(e)&&!Pn.includes(e)));for(const e of s)document.querySelector("#"+e).parentElement.style.display="none";for(const e of n)document.querySelector("#"+e).parentElement.style.display=""}for(const t of s)t.addEventListener("click",(function(){const n=t.value;e.actualMode=n;for(const e of s)e.value!==n?e.classList.add("not-selected"):e.classList.remove("not-selected");kn()}));const $n="1.1.3",On=document.querySelector("#version");function Tn(e,t=!0){if(t)return void(On.textContent="v"+e);const s=document.createElement("a");s.href="https://github.com/yoannchb-pro/MoodleGPT",s.rel="noopener noreferrer",s.target="_blank",s.textContent="v"+e,On.appendChild(s),On.appendChild(document.createTextNode(" is now available !"))}!function(){n(this,void 0,void 0,(function*(){const e=yield function(){return n(this,void 0,void 0,(function*(){const e=yield fetch("https://raw.githubusercontent.com/yoannchb-pro/MoodleGPT/main/package.json");return(yield e.json()).version}))}().catch((e=>(console.error(e),$n))),t=e.split("."),s=$n.split("."),r=Math.min(t.length,s.length);for(let n=0;n<r;++n){if(parseInt(t[n])>parseInt(s[n]))return Tn(e,!1);if(parseInt(s[n])>parseInt(t[n]))return Tn($n)}Tn($n)}))}();const jn=document.querySelector("#settings"),Mn=document.querySelector("#advanced-settings"),Nn=document.querySelector("#switch-settings");Nn.addEventListener("click",(function(e){e.preventDefault(),"flex"===Mn.style.display?(jn.style.display="flex",Mn.style.display="none",Nn.textContent="Advanced settings"):(jn.style.display="none",Mn.style.display="flex",Nn.textContent="Go back to settings")}));const qn=document.querySelector(".save"),Dn=["apiKey","code","model","baseURL","maxTokens"];qn.addEventListener("click",(function(){const[s,n,r,o,a]=Dn.map((e=>document.querySelector("#"+e).value.trim())),[i,l,c,u,h,d,f,p,m]=t.map((e=>{const t=document.querySelector("#"+e);return t.checked&&"none"!==t.parentElement.style.display}));s&&r?n.length>0&&n.length<2?vn({msg:"The code should at least contain 2 characters",isError:!0}):(chrome.storage.sync.set({moodleGPT:{apiKey:s,code:n,model:r,baseURL:o,maxTokens:a?parseInt(a):void 0,logs:i,title:l,cursor:c,typing:u,mouseover:h,infinite:d,timeout:f,history:p,includeImages:m,mode:e.actualMode}}),vn({msg:"Configuration saved"})):vn({msg:"Please complete all the form",isError:!0})})),chrome.storage.sync.get(["moodleGPT"]).then((function(n){const r=n.moodleGPT;if(r){if(r.mode){e.actualMode=r.mode;for(const e of s)e.value===r.mode?e.classList.remove("not-selected"):e.classList.add("not-selected")}Dn.forEach((e=>r[e]?document.querySelector("#"+e).value=r[e]:null)),t.forEach((e=>document.querySelector("#"+e).checked=r[e]||""))}kn(),In()}))}));
//# sourceMappingURL=popup.js.map