@imgly/plugin-ai-text-generation-web 0.2.2 → 0.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +97 -0
- package/dist/anthropic/index.mjs +91 -9
- package/dist/anthropic/index.mjs.map +4 -4
- package/dist/index.mjs +14 -14
- package/dist/index.mjs.map +4 -4
- package/dist/open-ai/index.mjs +93 -11
- package/dist/open-ai/index.mjs.map +4 -4
- package/dist/quickActions/ChangeTextTo.d.ts +1 -1
- package/dist/quickActions/ChangeTone.d.ts +1 -1
- package/dist/quickActions/Fix.d.ts +1 -1
- package/dist/quickActions/Improve.d.ts +1 -1
- package/dist/quickActions/Longer.d.ts +1 -1
- package/dist/quickActions/Shorter.d.ts +1 -1
- package/dist/quickActions/Translate.d.ts +1 -1
- package/package.json +1 -1
package/dist/open-ai/index.mjs
CHANGED
|
@@ -1,13 +1,74 @@
|
|
|
1
|
-
var mr="RFC3986",gr={RFC1738:s=>String(s).replace(/%20/g,"+"),RFC3986:s=>String(s)},ks="RFC1738";var Tn=Array.isArray,Z=(()=>{let s=[];for(let e=0;e<256;++e)s.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return s})();var Jr=1024,Ms=(s,e,t,r,n)=>{if(s.length===0)return s;let o=s;if(typeof s=="symbol"?o=Symbol.prototype.toString.call(s):typeof s!="string"&&(o=String(s)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=Jr){let c=o.length>=Jr?o.slice(a,a+Jr):o,f=[];for(let b=0;b<c.length;++b){let u=c.charCodeAt(b);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||n===ks&&(u===40||u===41)){f[f.length]=c.charAt(b);continue}if(u<128){f[f.length]=Z[u];continue}if(u<2048){f[f.length]=Z[192|u>>6]+Z[128|u&63];continue}if(u<55296||u>=57344){f[f.length]=Z[224|u>>12]+Z[128|u>>6&63]+Z[128|u&63];continue}b+=1,u=65536+((u&1023)<<10|c.charCodeAt(b)&1023),f[f.length]=Z[240|u>>18]+Z[128|u>>12&63]+Z[128|u>>6&63]+Z[128|u&63]}i+=f.join("")}return i};function Ns(s){return!s||typeof s!="object"?!1:!!(s.constructor&&s.constructor.isBuffer&&s.constructor.isBuffer(s))}function Vr(s,e){if(Tn(s)){let t=[];for(let r=0;r<s.length;r+=1)t.push(e(s[r]));return t}return e(s)}var $n=Object.prototype.hasOwnProperty,Bs={brackets(s){return String(s)+"[]"},comma:"comma",indices(s,e){return String(s)+"["+e+"]"},repeat(s){return String(s)}},ee=Array.isArray,Fn=Array.prototype.push,Ls=function(s,e){Fn.apply(s,ee(e)?e:[e])},kn=Date.prototype.toISOString,T={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Ms,encodeValuesOnly:!1,format:mr,formatter:gr[mr],indices:!1,serializeDate(s){return kn.call(s)},skipNulls:!1,strictNullHandling:!1};function Mn(s){return typeof s=="string"||typeof s=="number"||typeof s=="boolean"||typeof s=="symbol"||typeof s=="bigint"}var Xr={};function Ds(s,e,t,r,n,o,i,a,c,f,b,u,d,p,A,g,C,O){let _=s,L=O,R=0,k=!1;for(;(L=L.get(Xr))!==void 0&&!k;){let S=L.get(s);if(R+=1,typeof S<"u"){if(S===R)throw new RangeError("Cyclic object value");k=!0}typeof L.get(Xr)>"u"&&(R=0)}if(typeof f=="function"?_=f(e,_):_ instanceof Date?_=d?.(_):t==="comma"&&ee(_)&&(_=Vr(_,function(S){return S instanceof Date?d?.(S):S})),_===null){if(o)return c&&!g?c(e,T.encoder,C,"key",p):e;_=""}if(Mn(_)||Ns(_)){if(c){let S=g?e:c(e,T.encoder,C,"key",p);return[A?.(S)+"="+A?.(c(_,T.encoder,C,"value",p))]}return[A?.(e)+"="+A?.(String(_))]}let j=[];if(typeof _>"u")return j;let U;if(t==="comma"&&ee(_))g&&c&&(_=Vr(_,c)),U=[{value:_.length>0?_.join(",")||null:void 0}];else if(ee(f))U=f;else{let S=Object.keys(_);U=b?S.sort(b):S}let M=a?String(e).replace(/\./g,"%2E"):String(e),N=r&&ee(_)&&_.length===1?M+"[]":M;if(n&&ee(_)&&_.length===0)return N+"[]";for(let S=0;S<U.length;++S){let v=U[S],$s=typeof v=="object"&&typeof v.value<"u"?v.value:_[v];if(i&&$s===null)continue;let Hr=u&&a?v.replace(/\./g,"%2E"):v,vn=ee(_)?typeof t=="function"?t(N,Hr):N:N+(u?"."+Hr:"["+Hr+"]");O.set(s,R);let Fs=new WeakMap;Fs.set(Xr,O),Ls(j,Ds($s,vn,t,r,n,o,i,a,t==="comma"&&g&&ee(_)?null:c,f,b,u,d,p,A,g,C,Fs))}return j}function Nn(s=T){if(typeof s.allowEmptyArrays<"u"&&typeof s.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof s.encodeDotInKeys<"u"&&typeof s.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(s.encoder!==null&&typeof s.encoder<"u"&&typeof s.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=s.charset||T.charset;if(typeof s.charset<"u"&&s.charset!=="utf-8"&&s.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=mr;if(typeof s.format<"u"){if(!$n.call(gr,s.format))throw new TypeError("Unknown format option provided.");t=s.format}let r=gr[t],n=T.filter;(typeof s.filter=="function"||ee(s.filter))&&(n=s.filter);let o;if(s.arrayFormat&&s.arrayFormat in Bs?o=s.arrayFormat:"indices"in s?o=s.indices?"indices":"repeat":o=T.arrayFormat,"commaRoundTrip"in s&&typeof s.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof s.allowDots>"u"?s.encodeDotInKeys?!0:T.allowDots:!!s.allowDots;return{addQueryPrefix:typeof s.addQueryPrefix=="boolean"?s.addQueryPrefix:T.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof s.allowEmptyArrays=="boolean"?!!s.allowEmptyArrays:T.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof s.charsetSentinel=="boolean"?s.charsetSentinel:T.charsetSentinel,commaRoundTrip:!!s.commaRoundTrip,delimiter:typeof s.delimiter>"u"?T.delimiter:s.delimiter,encode:typeof s.encode=="boolean"?s.encode:T.encode,encodeDotInKeys:typeof s.encodeDotInKeys=="boolean"?s.encodeDotInKeys:T.encodeDotInKeys,encoder:typeof s.encoder=="function"?s.encoder:T.encoder,encodeValuesOnly:typeof s.encodeValuesOnly=="boolean"?s.encodeValuesOnly:T.encodeValuesOnly,filter:n,format:t,formatter:r,serializeDate:typeof s.serializeDate=="function"?s.serializeDate:T.serializeDate,skipNulls:typeof s.skipNulls=="boolean"?s.skipNulls:T.skipNulls,sort:typeof s.sort=="function"?s.sort:null,strictNullHandling:typeof s.strictNullHandling=="boolean"?s.strictNullHandling:T.strictNullHandling}}function Gr(s,e={}){let t=s,r=Nn(e),n,o;typeof r.filter=="function"?(o=r.filter,t=o("",t)):ee(r.filter)&&(o=r.filter,n=o);let i=[];if(typeof t!="object"||t===null)return"";let a=Bs[r.arrayFormat],c=a==="comma"&&r.commaRoundTrip;n||(n=Object.keys(t)),r.sort&&n.sort(r.sort);let f=new WeakMap;for(let d=0;d<n.length;++d){let p=n[d];r.skipNulls&&t[p]===null||Ls(i,Ds(t[p],p,a,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,f))}let b=i.join(r.delimiter),u=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),b.length>0?u+b:""}var Le="4.104.0";var js=!1,De,Kr,Ln,Dn,jn,zr,Un,_r,Qr,Yr,Zr,wr,es;function Us(s,e={auto:!1}){if(js)throw new Error(`you must \`import 'openai/shims/${s.kind}'\` before importing anything else from openai`);if(De)throw new Error(`can't \`import 'openai/shims/${s.kind}'\` after \`import 'openai/shims/${De}'\``);js=e.auto,De=s.kind,Kr=s.fetch,Ln=s.Request,Dn=s.Response,jn=s.Headers,zr=s.FormData,Un=s.Blob,_r=s.File,Qr=s.ReadableStream,Yr=s.getMultipartRequestOptions,Zr=s.getDefaultAgent,wr=s.fileFromPath,es=s.isFsReadStream}var yr=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function qs({manuallyImported:s}={}){let e=s?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",t,r,n,o;try{t=fetch,r=Request,n=Response,o=Headers}catch(i){throw new Error(`this environment is missing the following Web Fetch API type: ${i.message}. ${e}`)}return{kind:"web",fetch:t,Request:r,Response:n,Headers:o,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(i,a)=>({...a,body:new yr(i)}),getDefaultAgent:i=>{},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:i=>!1}}var ts=()=>{De||Us(qs(),{auto:!0})};ts();var h=class extends Error{},$=class s extends h{constructor(e,t,r,n){super(`${s.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.request_id=n?.["x-request-id"],this.error=t;let o=t;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,t,r){let n=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){if(!e||!n)return new we({message:r,cause:br(t)});let o=t?.error;return e===400?new Jt(e,o,r,n):e===401?new Vt(e,o,r,n):e===403?new Xt(e,o,r,n):e===404?new Gt(e,o,r,n):e===409?new Kt(e,o,r,n):e===422?new zt(e,o,r,n):e===429?new Qt(e,o,r,n):e>=500?new Yt(e,o,r,n):new s(e,o,r,n)}},E=class extends ${constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},we=class extends ${constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},ye=class extends we{constructor({message:e}={}){super({message:e??"Request timed out."})}},Jt=class extends ${},Vt=class extends ${},Xt=class extends ${},Gt=class extends ${},Kt=class extends ${},zt=class extends ${},Qt=class extends ${},Yt=class extends ${},ct=class extends h{constructor(){super("Could not parse response content as the length limit was reached")}},ut=class extends h{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};var xr=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},je=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},J,Ue=class{constructor(){J.set(this,void 0),this.buffer=new Uint8Array,xr(this,J,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,r=new Uint8Array(this.buffer.length+t.length);r.set(this.buffer),r.set(t,this.buffer.length),this.buffer=r;let n=[],o;for(;(o=Hn(this.buffer,je(this,J,"f")))!=null;){if(o.carriage&&je(this,J,"f")==null){xr(this,J,o.index,"f");continue}if(je(this,J,"f")!=null&&(o.index!==je(this,J,"f")+1||o.carriage)){n.push(this.decodeText(this.buffer.slice(0,je(this,J,"f")-1))),this.buffer=this.buffer.slice(je(this,J,"f")),xr(this,J,null,"f");continue}let i=je(this,J,"f")!==null?o.preceding-1:o.preceding,a=this.decodeText(this.buffer.slice(0,i));n.push(a),this.buffer=this.buffer.slice(o.index),xr(this,J,null,"f")}return n}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new h(`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(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new h(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new h("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,n]=Xn(e,":");return n.startsWith(" ")&&(n=n.substring(1)),t==="event"?this.event=n:t==="data"&&this.data.push(n),null}};function Xn(s,e){let t=s.indexOf(e);return t!==-1?[s.substring(0,t),e,s.substring(t+e.length)]:[s,"",""]}var Hs=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function",Js=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Zt(s),Zt=s=>s!=null&&typeof s=="object"&&typeof s.size=="number"&&typeof s.type=="string"&&typeof s.text=="function"&&typeof s.slice=="function"&&typeof s.arrayBuffer=="function",Gn=s=>Js(s)||Hs(s)||es(s);async function as(s,e,t){if(s=await s,Js(s))return s;if(Hs(s)){let n=await s.blob();e||(e=new URL(s.url).pathname.split(/[\\/]/).pop()??"unknown_file");let o=Zt(n)?[await n.arrayBuffer()]:[n];return new _r(o,e,t)}let r=await Kn(s);if(e||(e=Qn(s)??"unknown_file"),!t?.type){let n=r[0]?.type;typeof n=="string"&&(t={...t,type:n})}return new _r(r,e,t)}async function Kn(s){let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Zt(s))e.push(await s.arrayBuffer());else if(Yn(s))for await(let t of s)e.push(t);else throw new Error(`Unexpected data type: ${typeof s}; constructor: ${s?.constructor?.name}; props: ${zn(s)}`);return e}function zn(s){return`[${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}function Qn(s){return os(s.name)||os(s.filename)||os(s.path)?.split(/[\\/]/).pop()}var os=s=>{if(typeof s=="string")return s;if(typeof Buffer<"u"&&s instanceof Buffer)return String(s)},Yn=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",ls=s=>s&&typeof s=="object"&&s.body&&s[Symbol.toStringTag]==="MultipartBody";var W=async s=>{let e=await Vs(s.body);return Yr(e,s)},Vs=async s=>{let e=new zr;return await Promise.all(Object.entries(s||{}).map(([t,r])=>is(e,t,r))),e};var is=async(s,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")s.append(e,String(t));else if(Gn(t)){let r=await as(t);s.append(e,r)}else if(Array.isArray(t))await Promise.all(t.map(r=>is(s,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,n])=>is(s,`${e}[${r}]`,n)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var eo=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},to=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},Ar;ts();async function Ys(s){let{response:e}=s;if(s.options.stream)return ue("response",e.status,e.url,e.headers,e.body),s.options.__streamClass?s.options.__streamClass.fromSSEResponse(e,s.controller):te.fromSSEResponse(e,s.controller);if(e.status===204)return null;if(s.options.__binaryResponse)return e;let r=e.headers.get("content-type")?.split(";")[0]?.trim();if(r?.includes("application/json")||r?.endsWith("+json")){let i=await e.json();return ue("response",e.status,e.url,e.headers,i),Zs(i,e)}let o=await e.text();return ue("response",e.status,e.url,e.headers,o),o}function Zs(s,e){return!s||typeof s!="object"||Array.isArray(s)?s:Object.defineProperty(s,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Ir=class s extends Promise{constructor(e,t=Ys){super(r=>{r(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new s(this.responsePromise,async t=>Zs(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[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)}},Rr=class{constructor({baseURL:e,maxRetries:t=2,timeout:r=6e5,httpAgent:n,fetch:o}){this.baseURL=e,this.maxRetries=cs("maxRetries",t),this.timeout=cs("timeout",r),this.httpAgent=n,this.fetch=o??Kr}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...oo(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${co()}`}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,r){return this.request(Promise.resolve(r).then(async n=>{let o=n&&Zt(n?.body)?new DataView(await n.body.arrayBuffer()):n?.body instanceof DataView?n.body:n?.body instanceof ArrayBuffer?new DataView(n.body):n&&ArrayBuffer.isView(n?.body)?new DataView(n.body.buffer):n?.body;return{method:e,path:t,...n,body:o}}))}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){let r={...e},{method:n,path:o,query:i,headers:a={}}=r,c=ArrayBuffer.isView(r.body)||r.__binaryRequest&&typeof r.body=="string"?r.body:ls(r.body)?r.body.body:r.body?JSON.stringify(r.body,null,2):null,f=this.calculateContentLength(c),b=this.buildURL(o,i);"timeout"in r&&cs("timeout",r.timeout),r.timeout=r.timeout??this.timeout;let u=r.httpAgent??this.httpAgent??Zr(b),d=r.timeout+1e3;typeof u?.options?.timeout=="number"&&d>(u.options.timeout??0)&&(u.options.timeout=d),this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let p=this.buildHeaders({options:r,headers:a,contentLength:f,retryCount:t});return{req:{method:n,...c&&{body:c},headers:p,...u&&{agent:u},signal:r.signal??null},url:b,timeout:r.timeout}}buildHeaders({options:e,headers:t,contentLength:r,retryCount:n}){let o={};r&&(o["content-length"]=r);let i=this.defaultHeaders(e);return zs(o,i),zs(o,t),ls(e.body)&&De!=="node"&&delete o["content-type"],Pr(i,"x-stainless-retry-count")===void 0&&Pr(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(n)),Pr(i,"x-stainless-timeout")===void 0&&Pr(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(o,t),o}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,r,n){return $.generate(e,t,r,n)}request(e,t=null){return new Ir(this.makeRequest(e,t))}async makeRequest(e,t){let r=await e,n=r.maxRetries??this.maxRetries;t==null&&(t=n),await this.prepareOptions(r);let{req:o,url:i,timeout:a}=this.buildRequest(r,{retryCount:n-t});if(await this.prepareRequest(o,{url:i,options:r}),ue("request",i,r,o.headers),r.signal?.aborted)throw new E;let c=new AbortController,f=await this.fetchWithTimeout(i,o,a,c).catch(br);if(f instanceof Error){if(r.signal?.aborted)throw new E;if(t)return this.retryRequest(r,t);throw f.name==="AbortError"?new ye:new we({cause:f})}let b=ns(f.headers);if(!f.ok){if(t&&this.shouldRetry(f)){let C=`retrying, ${t} attempts remaining`;return ue(`response (error; ${C})`,f.status,i,b),this.retryRequest(r,t,b)}let u=await f.text().catch(C=>br(C).message),d=io(u),p=d?void 0:u;throw ue(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,f.status,i,b,p),this.makeStatusError(f.status,d,p,b)}return{response:f,options:r,controller:c}}requestAPIList(e,t){let r=this.makeRequest(t,null);return new us(this,r,e)}buildURL(e,t){let r=lo(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return en(n)||(t={...n,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(r.search=this.stringifyQuery(t)),r.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,r])=>typeof r<"u").map(([t,r])=>{if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(r)}`;if(r===null)return`${encodeURIComponent(t)}=`;throw new h(`Cannot stringify type ${typeof r}; 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,r,n){let{signal:o,...i}=t||{};o&&o.addEventListener("abort",()=>n.abort());let a=setTimeout(()=>n.abort(),r),c={signal:n.signal,...i};return c.method&&(c.method=c.method.toUpperCase()),this.fetch.call(void 0,e,c).finally(()=>{clearTimeout(a)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r){let n,o=r?.["retry-after-ms"];if(o){let a=parseFloat(o);Number.isNaN(a)||(n=a)}let i=r?.["retry-after"];if(i&&!n){let a=parseFloat(i);Number.isNaN(a)?n=Date.parse(i)-Date.now():n=a*1e3}if(!(n&&0<=n&&n<60*1e3)){let a=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,a)}return await fe(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let o=t-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Le}`}},er=class{constructor(e,t,r,n){Ar.set(this,void 0),eo(this,Ar,e,"f"),this.options=n,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new h("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let r=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[n,o]of r)e.url.searchParams.set(n,o);t.query=void 0,t.path=e.url.toString()}return await to(this,Ar,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ar=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},us=class extends Ir{constructor(e,t,r){super(t,async n=>new r(e,n.response,await Ys(n),n.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},ns=s=>new Proxy(Object.fromEntries(s.entries()),{get(e,t){let r=t.toString();return e[r.toLowerCase()]||e[r]}}),ro={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},y=s=>typeof s=="object"&&s!==null&&!en(s)&&Object.keys(s).every(e=>tn(ro,e)),so=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Le,"X-Stainless-OS":Gs(Deno.build.os),"X-Stainless-Arch":Xs(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Le,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Le,"X-Stainless-OS":Gs(process.platform),"X-Stainless-Arch":Xs(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let s=no();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Le,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${s.browser}`,"X-Stainless-Runtime-Version":s.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Le,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function no(){if(typeof navigator>"u"||!navigator)return null;let s=[{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(let{key:e,pattern:t}of s){let r=t.exec(navigator.userAgent);if(r){let n=r[1]||0,o=r[2]||0,i=r[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var Xs=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Gs=s=>(s=s.toLowerCase(),s.includes("ios")?"iOS":s==="android"?"Android":s==="darwin"?"MacOS":s==="win32"?"Windows":s==="freebsd"?"FreeBSD":s==="openbsd"?"OpenBSD":s==="linux"?"Linux":s?`Other:${s}`:"Unknown"),Ks,oo=()=>Ks??(Ks=so()),io=s=>{try{return JSON.parse(s)}catch{return}},ao=/^[a-z][a-z0-9+.-]*:/i,lo=s=>ao.test(s),fe=s=>new Promise(e=>setTimeout(e,s)),cs=(s,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new h(`${s} must be an integer`);if(e<0)throw new h(`${s} must be a positive integer`);return e},br=s=>{if(s instanceof Error)return s;if(typeof s=="object"&&s!==null)try{return new Error(JSON.stringify(s))}catch{}return new Error(s)};var tr=s=>{if(typeof process<"u")return process.env?.[s]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(s)?.trim()};function en(s){if(!s)return!0;for(let e in s)return!1;return!0}function tn(s,e){return Object.prototype.hasOwnProperty.call(s,e)}function zs(s,e){for(let t in e){if(!tn(e,t))continue;let r=t.toLowerCase();if(!r)continue;let n=e[t];n===null?delete s[r]:n!==void 0&&(s[r]=n)}}var Qs=new Set(["authorization","api-key"]);function ue(s,...e){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let t=e.map(r=>{if(!r)return r;if(r.headers){let o={...r,headers:{...r.headers}};for(let i in r.headers)Qs.has(i.toLowerCase())&&(o.headers[i]="REDACTED");return o}let n=null;for(let o in r)Qs.has(o.toLowerCase())&&(n??(n={...r}),n[o]="REDACTED");return n??r});console.log(`OpenAI:DEBUG:${s}`,...t)}}var co=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{let e=Math.random()*16|0;return(s==="x"?e:e&3|8).toString(16)}),rn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",uo=s=>typeof s?.get=="function";var Pr=(s,e)=>{let t=e.toLowerCase();if(uo(s)){let r=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(n,o,i)=>o+i.toUpperCase());for(let n of[e,t,e.toUpperCase(),r]){let o=s.get(n);if(o)return o}}for(let[r,n]of Object.entries(s))if(r.toLowerCase()===t)return Array.isArray(n)?(n.length<=1||console.warn(`Received ${n.length} entries for the ${e} header, using the first entry.`),n[0]):n};var sn=s=>{if(typeof Buffer<"u"){let e=Buffer.from(s,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(s),t=e.length,r=new Uint8Array(t);for(let n=0;n<t;n++)r[n]=e.charCodeAt(n);return Array.from(new Float32Array(r.buffer))}};function rr(s){return s!=null&&typeof s=="object"&&!Array.isArray(s)}var re=class extends er{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}},x=class extends er{constructor(e,t,r,n){super(e,t,r,n),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){let e=this.getPaginatedItems();if(!e.length)return null;let t=e[e.length-1]?.id;return t?{params:{after:t}}:null}};var l=class{constructor(e){this._client=e}};var ft=class extends l{list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Cr,{query:t,...r})}};var be=class extends l{constructor(){super(...arguments),this.messages=new ft(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/chat/completions",xe,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}},xe=class extends x{},Cr=class extends x{};be.ChatCompletionsPage=xe;be.Messages=ft;var de=class extends l{constructor(){super(...arguments),this.completions=new be(this._client)}};de.Completions=be;de.ChatCompletionsPage=xe;var pt=class extends l{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}};var dt=class extends l{create(e,t){return this._client.post("/audio/transcriptions",W({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}};var ht=class extends l{create(e,t){return this._client.post("/audio/translations",W({body:e,...t,__metadata:{model:e.model}}))}};var se=class extends l{constructor(){super(...arguments),this.transcriptions=new dt(this._client),this.translations=new ht(this._client),this.speech=new pt(this._client)}};se.Transcriptions=dt;se.Translations=ht;se.Speech=pt;var Ae=class extends l{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 y(e)?this.list({},e):this._client.getAPIList("/batches",qe,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}},qe=class extends x{};Ae.BatchesPage=qe;var z=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},I=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},fs,Sr,Er,sr,nr,Or,or,he,ir,vr,Tr,mt,nn,Pe=class{constructor(){fs.add(this),this.controller=new AbortController,Sr.set(this,void 0),Er.set(this,()=>{}),sr.set(this,()=>{}),nr.set(this,void 0),Or.set(this,()=>{}),or.set(this,()=>{}),he.set(this,{}),ir.set(this,!1),vr.set(this,!1),Tr.set(this,!1),mt.set(this,!1),z(this,Sr,new Promise((e,t)=>{z(this,Er,e,"f"),z(this,sr,t,"f")}),"f"),z(this,nr,new Promise((e,t)=>{z(this,Or,e,"f"),z(this,or,t,"f")}),"f"),I(this,Sr,"f").catch(()=>{}),I(this,nr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},I(this,fs,"m",nn).bind(this))},0)}_connected(){this.ended||(I(this,Er,"f").call(this),this._emit("connect"))}get ended(){return I(this,ir,"f")}get errored(){return I(this,vr,"f")}get aborted(){return I(this,Tr,"f")}abort(){this.controller.abort()}on(e,t){return(I(this,he,"f")[e]||(I(this,he,"f")[e]=[])).push({listener:t}),this}off(e,t){let r=I(this,he,"f")[e];if(!r)return this;let n=r.findIndex(o=>o.listener===t);return n>=0&&r.splice(n,1),this}once(e,t){return(I(this,he,"f")[e]||(I(this,he,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{z(this,mt,!0,"f"),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){z(this,mt,!0,"f"),await I(this,nr,"f")}_emit(e,...t){if(I(this,ir,"f"))return;e==="end"&&(z(this,ir,!0,"f"),I(this,Or,"f").call(this));let r=I(this,he,"f")[e];if(r&&(I(this,he,"f")[e]=r.filter(n=>!n.once),r.forEach(({listener:n})=>n(...t))),e==="abort"){let n=t[0];!I(this,mt,"f")&&!r?.length&&Promise.reject(n),I(this,sr,"f").call(this,n),I(this,or,"f").call(this,n),this._emit("end");return}if(e==="error"){let n=t[0];!I(this,mt,"f")&&!r?.length&&Promise.reject(n),I(this,sr,"f").call(this,n),I(this,or,"f").call(this,n),this._emit("end")}}_emitFinal(){}};Sr=new WeakMap,Er=new WeakMap,sr=new WeakMap,nr=new WeakMap,Or=new WeakMap,or=new WeakMap,he=new WeakMap,ir=new WeakMap,vr=new WeakMap,Tr=new WeakMap,mt=new WeakMap,fs=new WeakSet,nn=function(e){if(z(this,vr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new E),e instanceof E)return z(this,Tr,!0,"f"),this._emit("abort",e);if(e instanceof h)return this._emit("error",e);if(e instanceof Error){let t=new h(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new h(String(e)))};var m=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},V=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},D,ps,ne,$r,Q,He,gt,We,Mr,X,Fr,kr,cr,ar,lr,on,an,ln,cn,un,fn,pn,oe=class s extends Pe{constructor(){super(...arguments),D.add(this),ps.set(this,[]),ne.set(this,{}),$r.set(this,{}),Q.set(this,void 0),He.set(this,void 0),gt.set(this,void 0),We.set(this,void 0),Mr.set(this,void 0),X.set(this,void 0),Fr.set(this,void 0),kr.set(this,void 0),cr.set(this,void 0)}[(ps=new WeakMap,ne=new WeakMap,$r=new WeakMap,Q=new WeakMap,He=new WeakMap,gt=new WeakMap,We=new WeakMap,Mr=new WeakMap,X=new WeakMap,Fr=new WeakMap,kr=new WeakMap,cr=new WeakMap,D=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new s;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();let n=te.fromReadableStream(e,this.controller);for await(let o of n)m(this,D,"m",ar).call(this,o);if(n.controller.signal?.aborted)throw new E;return this._addRun(m(this,D,"m",lr).call(this))}toReadableStream(){return new te(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,n,o){let i=new s;return i._run(()=>i._runToolAssistantStream(e,t,r,n,{...o,headers:{...o?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,r,n,o){let i=o?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let a={...n,stream:!0},c=await e.submitToolOutputs(t,r,a,{...o,signal:this.controller.signal});this._connected();for await(let f of c)m(this,D,"m",ar).call(this,f);if(c.controller.signal?.aborted)throw new E;return this._addRun(m(this,D,"m",lr).call(this))}static createThreadAssistantStream(e,t,r){let n=new s;return n._run(()=>n._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}static createAssistantStream(e,t,r,n){let o=new s;return o._run(()=>o._runAssistantStream(e,t,r,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return m(this,Fr,"f")}currentRun(){return m(this,kr,"f")}currentMessageSnapshot(){return m(this,Q,"f")}currentRunStepSnapshot(){return m(this,cr,"f")}async finalRunSteps(){return await this.done(),Object.values(m(this,ne,"f"))}async finalMessages(){return await this.done(),Object.values(m(this,$r,"f"))}async finalRun(){if(await this.done(),!m(this,He,"f"))throw Error("Final run was not received.");return m(this,He,"f")}async _createThreadAssistantStream(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort()));let o={...t,stream:!0},i=await e.createAndRun(o,{...r,signal:this.controller.signal});this._connected();for await(let a of i)m(this,D,"m",ar).call(this,a);if(i.controller.signal?.aborted)throw new E;return this._addRun(m(this,D,"m",lr).call(this))}async _createAssistantStream(e,t,r,n){let o=n?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...r,stream:!0},a=await e.create(t,i,{...n,signal:this.controller.signal});this._connected();for await(let c of a)m(this,D,"m",ar).call(this,c);if(a.controller.signal?.aborted)throw new E;return this._addRun(m(this,D,"m",lr).call(this))}static accumulateDelta(e,t){for(let[r,n]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=n;continue}let o=e[r];if(o==null){e[r]=n;continue}if(r==="index"||r==="type"){e[r]=n;continue}if(typeof o=="string"&&typeof n=="string")o+=n;else if(typeof o=="number"&&typeof n=="number")o+=n;else if(rr(o)&&rr(n))o=this.accumulateDelta(o,n);else if(Array.isArray(o)&&Array.isArray(n)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...n);continue}for(let i of n){if(!rr(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=o[a];c==null?o.push(i):o[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${n}, accValue: ${o}`);e[r]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,n){return await this._createAssistantStream(t,e,r,n)}async _runToolAssistantStream(e,t,r,n,o){return await this._createToolAssistantStream(r,e,t,n,o)}};ar=function(e){if(!this.ended)switch(V(this,Fr,e,"f"),m(this,D,"m",ln).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":m(this,D,"m",pn).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":m(this,D,"m",an).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":m(this,D,"m",on).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},lr=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");if(!m(this,He,"f"))throw Error("Final run has not been received");return m(this,He,"f")},on=function(e){let[t,r]=m(this,D,"m",un).call(this,e,m(this,Q,"f"));V(this,Q,t,"f"),m(this,$r,"f")[t.id]=t;for(let n of r){let o=t.content[n.index];o?.type=="text"&&this._emit("textCreated",o.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(let n of e.data.delta.content){if(n.type=="text"&&n.text){let o=n.text,i=t.content[n.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(n.index!=m(this,gt,"f")){if(m(this,We,"f"))switch(m(this,We,"f").type){case"text":this._emit("textDone",m(this,We,"f").text,m(this,Q,"f"));break;case"image_file":this._emit("imageFileDone",m(this,We,"f").image_file,m(this,Q,"f"));break}V(this,gt,n.index,"f")}V(this,We,t.content[n.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(m(this,gt,"f")!==void 0){let n=e.data.content[m(this,gt,"f")];if(n)switch(n.type){case"image_file":this._emit("imageFileDone",n.image_file,m(this,Q,"f"));break;case"text":this._emit("textDone",n.text,m(this,Q,"f"));break}}m(this,Q,"f")&&this._emit("messageDone",e.data),V(this,Q,void 0,"f")}},an=function(e){let t=m(this,D,"m",cn).call(this,e);switch(V(this,cr,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let o of r.step_details.tool_calls)o.index==m(this,Mr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(m(this,X,"f")&&this._emit("toolCallDone",m(this,X,"f")),V(this,Mr,o.index,"f"),V(this,X,t.step_details.tool_calls[o.index],"f"),m(this,X,"f")&&this._emit("toolCallCreated",m(this,X,"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":V(this,cr,void 0,"f"),e.data.step_details.type=="tool_calls"&&m(this,X,"f")&&(this._emit("toolCallDone",m(this,X,"f")),V(this,X,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},ln=function(e){m(this,ps,"f").push(e),this._emit("event",e)},cn=function(e){switch(e.event){case"thread.run.step.created":return m(this,ne,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=m(this,ne,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){let n=oe.accumulateDelta(t,r.delta);m(this,ne,"f")[e.data.id]=n}return m(this,ne,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":m(this,ne,"f")[e.data.id]=e.data;break}if(m(this,ne,"f")[e.data.id])return m(this,ne,"f")[e.data.id];throw new Error("No snapshot available")},un=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];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(let o of n.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=m(this,D,"m",fn).call(this,o,i)}else t.content[o.index]=o,r.push(o);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},fn=function(e,t){return oe.accumulateDelta(t,e)},pn=function(e){switch(V(this,kr,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;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":V(this,He,e.data,"f"),m(this,X,"f")&&(this._emit("toolCallDone",m(this,X,"f")),V(this,X,void 0,"f"));break;case"thread.run.cancelling":break}};var Je=class extends l{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,r){return this._client.post(`/assistants/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/assistants",_t,{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}})}},_t=class extends x{};Je.AssistantsPage=_t;function ds(s){return typeof s.parse=="function"}var Ie=s=>s?.role==="assistant",hs=s=>s?.role==="function",ms=s=>s?.role==="tool";function ur(s){return s?.$brand==="auto-parseable-response-format"}function Ve(s){return s?.$brand==="auto-parseable-tool"}function dn(s,e){return!e||!gs(e)?{...s,choices:s.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:fr(s,e)}function fr(s,e){let t=s.choices.map(r=>{if(r.finish_reason==="length")throw new ct;if(r.finish_reason==="content_filter")throw new ut;return{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(n=>yo(e,n))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?wo(e,r.message.content):null}}});return{...s,choices:t}}function wo(s,e){return s.response_format?.type!=="json_schema"?null:s.response_format?.type==="json_schema"?"$parseRaw"in s.response_format?s.response_format.$parseRaw(e):JSON.parse(e):null}function yo(s,e){let t=s.tools?.find(r=>r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Ve(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function hn(s,e){if(!s)return!1;let t=s.tools?.find(r=>r.function?.name===e.function.name);return Ve(t)||t?.function.strict||!1}function gs(s){return ur(s.response_format)?!0:s.tools?.some(e=>Ve(e)||e.type==="function"&&e.function.strict===!0)??!1}function mn(s){for(let e of s??[]){if(e.type!=="function")throw new h(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new h(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var H=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},q,_s,Nr,ws,ys,bs,_n,xs,gn=10,wt=class extends Pe{constructor(){super(...arguments),q.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let 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),(hs(e)||ms(e))&&e.content)this._emit("functionCallResult",e.content);else if(Ie(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(Ie(e)&&e.tool_calls)for(let r of e.tool_calls)r.type==="function"&&this._emit("functionCall",r.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new h("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),H(this,q,"m",_s).call(this)}async finalMessage(){return await this.done(),H(this,q,"m",Nr).call(this)}async finalFunctionCall(){return await this.done(),H(this,q,"m",ws).call(this)}async finalFunctionCallResult(){return await this.done(),H(this,q,"m",ys).call(this)}async totalUsage(){return await this.done(),H(this,q,"m",bs).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=H(this,q,"m",Nr).call(this);t&&this._emit("finalMessage",t);let r=H(this,q,"m",_s).call(this);r&&this._emit("finalContent",r);let n=H(this,q,"m",ws).call(this);n&&this._emit("finalFunctionCall",n);let o=H(this,q,"m",ys).call(this);o!=null&&this._emit("finalFunctionCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",H(this,q,"m",bs).call(this))}async _createChatCompletion(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),H(this,q,"m",_n).call(this,t);let o=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(fr(o,t))}async _runChatCompletion(e,t,r){for(let n of t.messages)this._addMessage(n,!1);return await this._createChatCompletion(e,t,r)}async _runFunctions(e,t,r){let n="function",{function_call:o="auto",stream:i,...a}=t,c=typeof o!="string"&&o?.name,{maxChatCompletions:f=gn}=r||{},b={};for(let d of t.functions)b[d.name||d.function.name]=d;let u=t.functions.map(d=>({name:d.name||d.function.name,parameters:d.parameters,description:d.description}));for(let d of t.messages)this._addMessage(d,!1);for(let d=0;d<f;++d){let A=(await this._createChatCompletion(e,{...a,function_call:o,functions:u,messages:[...this.messages]},r)).choices[0]?.message;if(!A)throw new h("missing message in ChatCompletion response");if(!A.function_call)return;let{name:g,arguments:C}=A.function_call,O=b[g];if(O){if(c&&c!==g){let k=`Invalid function_call: ${JSON.stringify(g)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:n,name:g,content:k});continue}}else{let k=`Invalid function_call: ${JSON.stringify(g)}. Available options are: ${u.map(j=>JSON.stringify(j.name)).join(", ")}. Please try again`;this._addMessage({role:n,name:g,content:k});continue}let _;try{_=ds(O)?await O.parse(C):C}catch(k){this._addMessage({role:n,name:g,content:k instanceof Error?k.message:String(k)});continue}let L=await O.function(_,this),R=H(this,q,"m",xs).call(this,L);if(this._addMessage({role:n,name:g,content:R}),c)return}}async _runTools(e,t,r){let n="tool",{tool_choice:o="auto",stream:i,...a}=t,c=typeof o!="string"&&o?.function?.name,{maxChatCompletions:f=gn}=r||{},b=t.tools.map(p=>{if(Ve(p)){if(!p.$callback)throw new h("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:p.$callback,name:p.function.name,description:p.function.description||"",parameters:p.function.parameters,parse:p.$parseRaw,strict:!0}}}return p}),u={};for(let p of b)p.type==="function"&&(u[p.function.name||p.function.function.name]=p.function);let d="tools"in t?b.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description,strict:p.function.strict}}:p):void 0;for(let p of t.messages)this._addMessage(p,!1);for(let p=0;p<f;++p){let g=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:d,messages:[...this.messages]},r)).choices[0]?.message;if(!g)throw new h("missing message in ChatCompletion response");if(!g.tool_calls?.length)return;for(let C of g.tool_calls){if(C.type!=="function")continue;let O=C.id,{name:_,arguments:L}=C.function,R=u[_];if(R){if(c&&c!==_){let M=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:n,tool_call_id:O,content:M});continue}}else{let M=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(u).map(N=>JSON.stringify(N)).join(", ")}. Please try again`;this._addMessage({role:n,tool_call_id:O,content:M});continue}let k;try{k=ds(R)?await R.parse(L):L}catch(M){let N=M instanceof Error?M.message:String(M);this._addMessage({role:n,tool_call_id:O,content:N});continue}let j=await R.function(k,this),U=H(this,q,"m",xs).call(this,j);if(this._addMessage({role:n,tool_call_id:O,content:U}),c)return}}}};q=new WeakSet,_s=function(){return H(this,q,"m",Nr).call(this).content??null},Nr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Ie(t)){let{function_call:r,...n}=t,o={...n,content:t.content??null,refusal:t.refusal??null};return r&&(o.function_call=r),o}}throw new h("stream ended without producing a ChatCompletionMessage with role=assistant")},ws=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Ie(t)&&t?.function_call)return t.function_call;if(Ie(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},ys=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(hs(t)&&t.content!=null||ms(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(n=>n.type==="function"&&n.id===t.tool_call_id)))return t.content}},bs=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{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},_n=function(e){if(e.n!=null&&e.n>1)throw new h("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},xs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var pr=class s extends wt{static runFunctions(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run(()=>n._runFunctions(e,t,o)),n}static runTools(e,t,r){let n=new s,o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}_addMessage(e,t=!0){super._addMessage(e,t),Ie(e)&&e.content&&this._emit("content",e.content)}};var B={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},As=class extends Error{},Ps=class extends Error{};function bo(s,e=B.ALL){if(typeof s!="string")throw new TypeError(`expecting str, got ${typeof s}`);if(!s.trim())throw new Error(`${s} is empty`);return xo(s.trim(),e)}var xo=(s,e)=>{let t=s.length,r=0,n=d=>{throw new As(`${d} at position ${r}`)},o=d=>{throw new Ps(`${d} at position ${r}`)},i=()=>(u(),r>=t&&n("Unexpected end of input"),s[r]==='"'?a():s[r]==="{"?c():s[r]==="["?f():s.substring(r,r+4)==="null"||B.NULL&e&&t-r<4&&"null".startsWith(s.substring(r))?(r+=4,null):s.substring(r,r+4)==="true"||B.BOOL&e&&t-r<4&&"true".startsWith(s.substring(r))?(r+=4,!0):s.substring(r,r+5)==="false"||B.BOOL&e&&t-r<5&&"false".startsWith(s.substring(r))?(r+=5,!1):s.substring(r,r+8)==="Infinity"||B.INFINITY&e&&t-r<8&&"Infinity".startsWith(s.substring(r))?(r+=8,1/0):s.substring(r,r+9)==="-Infinity"||B.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(s.substring(r))?(r+=9,-1/0):s.substring(r,r+3)==="NaN"||B.NAN&e&&t-r<3&&"NaN".startsWith(s.substring(r))?(r+=3,NaN):b()),a=()=>{let d=r,p=!1;for(r++;r<t&&(s[r]!=='"'||p&&s[r-1]==="\\");)p=s[r]==="\\"?!p:!1,r++;if(s.charAt(r)=='"')try{return JSON.parse(s.substring(d,++r-Number(p)))}catch(A){o(String(A))}else if(B.STR&e)try{return JSON.parse(s.substring(d,r-Number(p))+'"')}catch{return JSON.parse(s.substring(d,s.lastIndexOf("\\"))+'"')}n("Unterminated string literal")},c=()=>{r++,u();let d={};try{for(;s[r]!=="}";){if(u(),r>=t&&B.OBJ&e)return d;let p=a();u(),r++;try{let A=i();Object.defineProperty(d,p,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(B.OBJ&e)return d;throw A}u(),s[r]===","&&r++}}catch{if(B.OBJ&e)return d;n("Expected '}' at end of object")}return r++,d},f=()=>{r++;let d=[];try{for(;s[r]!=="]";)d.push(i()),u(),s[r]===","&&r++}catch{if(B.ARR&e)return d;n("Expected ']' at end of array")}return r++,d},b=()=>{if(r===0){s==="-"&&B.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s)}catch(p){if(B.NUM&e)try{return s[s.length-1]==="."?JSON.parse(s.substring(0,s.lastIndexOf("."))):JSON.parse(s.substring(0,s.lastIndexOf("e")))}catch{}o(String(p))}}let d=r;for(s[r]==="-"&&r++;s[r]&&!",]}".includes(s[r]);)r++;r==t&&!(B.NUM&e)&&n("Unterminated number literal");try{return JSON.parse(s.substring(d,r))}catch{s.substring(d,r)==="-"&&B.NUM&e&&n("Not sure what '-' is");try{return JSON.parse(s.substring(d,s.lastIndexOf("e")))}catch(A){o(String(A))}}},u=()=>{for(;r<t&&`
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
${Dr(s)}`);return{...M,id:U,type:j,function:{...v,name:S,arguments:N}}})}}:{...p,message:{...O,content:A,role:_,refusal:f.refusal??null},finish_reason:b,index:u,logprobs:d}}),created:n,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return dn(c,e)}function Dr(s){return JSON.stringify(s)}var dr=class s extends xt{static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,r){let n=new s(null),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return n._run(()=>n._runFunctions(e,t,o)),n}static runTools(e,t,r){let n=new s(t),o={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return n._run(()=>n._runTools(e,t,o)),n}};var hr=class extends l{parse(e,t){return mn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(r=>fr(r,e))}runFunctions(e,t){return e.stream?dr.runFunctions(this._client,e,t):pr.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?dr.runTools(this._client,e,t):pr.runTools(this._client,e,t)}stream(e,t){return xt.createChatCompletion(this._client,e,t)}};var At=class extends l{constructor(){super(...arguments),this.completions=new hr(this._client)}};(function(s){s.Completions=hr})(At||(At={}));var Pt=class extends l{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}};var It=class extends l{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}};var Ce=class extends l{constructor(){super(...arguments),this.sessions=new Pt(this._client),this.transcriptionSessions=new It(this._client)}};Ce.Sessions=Pt;Ce.TranscriptionSessions=It;var Xe=class extends l{create(e,t,r){return this._client.post(`/threads/${e}/messages`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/messages/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Rt,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/threads/${e}/messages/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}},Rt=class extends x{};Xe.MessagesPage=Rt;var Ge=class extends l{retrieve(e,t,r,n={},o){return y(n)?this.retrieve(e,t,r,{},n):this._client.get(`/threads/${e}/runs/${t}/steps/${r}`,{query:n,...o,headers:{"OpenAI-Beta":"assistants=v2",...o?.headers}})}list(e,t,r={},n){return y(r)?this.list(e,t,{},r):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Ct,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}},Ct=class extends x{};Ge.RunStepsPage=Ct;var ge=class extends l{constructor(){super(...arguments),this.steps=new Ge(this._client)}create(e,t,r){let{include:n,...o}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:n},body:o,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers},stream:t.stream??!1})}retrieve(e,t,r){return this._client.get(`/threads/${e}/runs/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,St,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}createAndStream(e,t,r){return oe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){let n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...n}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let f=parseInt(c);isNaN(f)||(a=f)}}await fe(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,r){return oe.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r,n){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:r.stream??!1})}async submitToolOutputsAndPoll(e,t,r,n){let o=await this.submitToolOutputs(e,t,r,n);return await this.poll(e,o.id,n)}submitToolOutputsStream(e,t,r,n){return oe.createToolAssistantStream(e,t,this._client.beta.threads.runs,r,n)}},St=class extends x{};ge.RunsPage=St;ge.Steps=Ge;ge.RunStepsPage=Ct;var ie=class extends l{constructor(){super(...arguments),this.runs=new ge(this._client),this.messages=new Xe(this._client)}create(e={},t){return y(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,r){return this._client.post(`/threads/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.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){let r=await this.createAndRun(e,t);return await this.runs.poll(r.thread_id,r.id,t)}createAndRunStream(e,t){return oe.createThreadAssistantStream(e,this._client.beta.threads,t)}};ie.Runs=ge;ie.RunsPage=St;ie.Messages=Xe;ie.MessagesPage=Rt;var Y=class extends l{constructor(){super(...arguments),this.realtime=new Ce(this._client),this.chat=new At(this._client),this.assistants=new Je(this._client),this.threads=new ie(this._client)}};Y.Realtime=Ce;Y.Assistants=Je;Y.AssistantsPage=_t;Y.Threads=ie;var Ke=class extends l{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var Et=class extends l{retrieve(e,t,r){return this._client.get(`/containers/${e}/files/${t}/content`,{...r,headers:{Accept:"application/binary",...r?.headers},__binaryResponse:!0})}};var Se=class extends l{constructor(){super(...arguments),this.content=new Et(this._client)}create(e,t,r){return this._client.post(`/containers/${e}/files`,W({body:t,...r}))}retrieve(e,t,r){return this._client.get(`/containers/${e}/files/${t}`,r)}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Ot,{query:t,...r})}del(e,t,r){return this._client.delete(`/containers/${e}/files/${t}`,{...r,headers:{Accept:"*/*",...r?.headers}})}},Ot=class extends x{};Se.FileListResponsesPage=Ot;Se.Content=Et;var ae=class extends l{constructor(){super(...arguments),this.files=new Se(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/containers",ze,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}},ze=class extends x{};ae.ContainerListResponsesPage=ze;ae.Files=Se;ae.FileListResponsesPage=Ot;var Qe=class extends l{create(e,t){let r=!!e.encoding_format,n=r?e.encoding_format:"base64";r&&ue("Request","User defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:n},...t});return r?o:(ue("response","Decoding base64 embeddings to float32 array"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=sn(c)}),i)))}};var Ye=class extends l{retrieve(e,t,r,n){return this._client.get(`/evals/${e}/runs/${t}/output_items/${r}`,n)}list(e,t,r={},n){return y(r)?this.list(e,t,{},r):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,vt,{query:r,...n})}},vt=class extends x{};Ye.OutputItemListResponsesPage=vt;var _e=class extends l{constructor(){super(...arguments),this.outputItems=new Ye(this._client)}create(e,t,r){return this._client.post(`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){return this._client.get(`/evals/${e}/runs/${t}`,r)}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Tt,{query:t,...r})}del(e,t,r){return this._client.delete(`/evals/${e}/runs/${t}`,r)}cancel(e,t,r){return this._client.post(`/evals/${e}/runs/${t}`,r)}},Tt=class extends x{};_e.RunListResponsesPage=Tt;_e.OutputItems=Ye;_e.OutputItemListResponsesPage=vt;var le=class extends l{constructor(){super(...arguments),this.runs=new _e(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,r){return this._client.post(`/evals/${e}`,{body:t,...r})}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/evals",Ze,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}},Ze=class extends x{};le.EvalListResponsesPage=Ze;le.Runs=_e;le.RunListResponsesPage=Tt;var Ee=class extends l{create(e,t){return this._client.post("/files",W({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/files",et,{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:r=30*60*1e3}={}){let n=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await fe(t),i=await this.retrieve(e),Date.now()-o>r)throw new ye({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}},et=class extends x{};Ee.FileObjectsPage=et;var $t=class extends l{};var Ft=class extends l{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})}};var tt=class extends l{constructor(){super(...arguments),this.graders=new Ft(this._client)}};tt.Graders=Ft;var rt=class extends l{create(e,t,r){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,kt,{body:t,method:"post",...r})}retrieve(e,t={},r){return y(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}del(e,t,r){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,r)}},kt=class extends re{};rt.PermissionCreateResponsesPage=kt;var Oe=class extends l{constructor(){super(...arguments),this.permissions=new rt(this._client)}};Oe.Permissions=rt;Oe.PermissionCreateResponsesPage=kt;var st=class extends l{list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Mt,{query:t,...r})}},Mt=class extends x{};st.FineTuningJobCheckpointsPage=Mt;var ce=class extends l{constructor(){super(...arguments),this.checkpoints=new st(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 y(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Nt,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return y(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Bt,{query:t,...r})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}},Nt=class extends x{},Bt=class extends x{};ce.FineTuningJobsPage=Nt;ce.FineTuningJobEventsPage=Bt;ce.Checkpoints=st;ce.FineTuningJobCheckpointsPage=Mt;var G=class extends l{constructor(){super(...arguments),this.methods=new $t(this._client),this.jobs=new ce(this._client),this.checkpoints=new Oe(this._client),this.alpha=new tt(this._client)}};G.Methods=$t;G.Jobs=ce;G.FineTuningJobsPage=Nt;G.FineTuningJobEventsPage=Bt;G.Checkpoints=Oe;G.Alpha=tt;var Lt=class extends l{};var ve=class extends l{constructor(){super(...arguments),this.graderModels=new Lt(this._client)}};ve.GraderModels=Lt;var nt=class extends l{createVariation(e,t){return this._client.post("/images/variations",W({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",W({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}};var Te=class extends l{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ot,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}},ot=class extends re{};Te.ModelsPage=ot;var it=class extends l{create(e,t){return this._client.post("/moderations",{body:e,...t})}};function yn(s,e){return!e||!Jo(e)?{...s,output_parsed:null,output:s.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:vs(s,e)}function vs(s,e){let t=s.output.map(n=>{if(n.type==="function_call")return{...n,parsed_arguments:Go(e,n)};if(n.type==="message"){let o=n.content.map(i=>i.type==="output_text"?{...i,parsed:Ho(e,i.text)}:i);return{...n,content:o}}return n}),r=Object.assign({},s,{output:t});return Object.getOwnPropertyDescriptor(s,"output_text")||Ts(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(let n of r.output)if(n.type==="message"){for(let o of n.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),r}function Ho(s,e){return s.text?.format?.type!=="json_schema"?null:"$parseRaw"in s.text?.format?(s.text?.format).$parseRaw(e):JSON.parse(e)}function Jo(s){return!!ur(s.text?.format)}function Vo(s){return s?.$brand==="auto-parseable-tool"}function Xo(s,e){return s.find(t=>t.type==="function"&&t.name===e)}function Go(s,e){let t=Xo(s.tools??[],e.name);return{...e,...e,parsed_arguments:Vo(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Ts(s){let e=[];for(let t of s.output)if(t.type==="message")for(let r of t.content)r.type==="output_text"&&e.push(r.text);s.output_text=e.join("")}var Dt=class extends l{list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,jr,{query:t,...r})}};var jt=function(s,e,t,r,n){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?s!==e||!n:!e.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?n.call(s,t):n?n.value=t:e.set(s,t),t},$e=function(s,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?s!==e||!r:!e.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(s):r?r.value:e.get(s)},Ut,Ur,Fe,qr,bn,xn,An,Pn,Wr=class s extends Pe{constructor(e){super(),Ut.add(this),Ur.set(this,void 0),Fe.set(this,void 0),qr.set(this,void 0),jt(this,Ur,e,"f")}static createResponse(e,t,r){let n=new s(t);return n._run(()=>n._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createOrRetrieveResponse(e,t,r){let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),$e(this,Ut,"m",bn).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(let a of o)$e(this,Ut,"m",xn).call(this,a,i);if(o.controller.signal?.aborted)throw new E;return $e(this,Ut,"m",An).call(this)}[(Ur=new WeakMap,Fe=new WeakMap,qr=new WeakMap,Ut=new WeakSet,bn=function(){this.ended||jt(this,Fe,void 0,"f")},xn=function(t,r){if(this.ended)return;let n=(i,a)=>{(r==null||a.sequence_number>r)&&this._emit(i,a)},o=$e(this,Ut,"m",Pn).call(this,t);switch(n("event",t),t.type){case"response.output_text.delta":{let i=o.output[t.output_index];if(!i)throw new h(`missing output at index ${t.output_index}`);if(i.type==="message"){let a=i.content[t.content_index];if(!a)throw new h(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new h(`expected content to be 'output_text', got ${a.type}`);n("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[t.output_index];if(!i)throw new h(`missing output at index ${t.output_index}`);i.type==="function_call"&&n("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:n(t.type,t);break}},An=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");let t=$e(this,Fe,"f");if(!t)throw new h("request ended without sending any events");jt(this,Fe,void 0,"f");let r=zo(t,$e(this,Ur,"f"));return jt(this,qr,r,"f"),r},Pn=function(t){let r=$e(this,Fe,"f");if(!r){if(t.type!=="response.created")throw new h(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=jt(this,Fe,t.response,"f"),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{let n=r.output[t.output_index];if(!n)throw new h(`missing output at index ${t.output_index}`);n.type==="message"&&n.content.push(t.part);break}case"response.output_text.delta":{let n=r.output[t.output_index];if(!n)throw new h(`missing output at index ${t.output_index}`);if(n.type==="message"){let o=n.content[t.content_index];if(!o)throw new h(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new h(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{let n=r.output[t.output_index];if(!n)throw new h(`missing output at index ${t.output_index}`);n.type==="function_call"&&(n.arguments+=t.delta);break}case"response.completed":{jt(this,Fe,t.response,"f");break}}return r},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("event",n=>{let o=t.shift();o?o.resolve(n):e.push(n)}),this.on("end",()=>{r=!0;for(let n of t)n.resolve(void 0);t.length=0}),this.on("abort",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),this.on("error",n=>{r=!0;for(let o of t)o.reject(n);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=$e(this,qr,"f");if(!e)throw new h("stream ended without producing a ChatCompletion");return e}};function zo(s,e){return yn(s,e)}var ke=class extends l{constructor(){super(...arguments),this.inputItems=new Dt(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Ts(r),r))}retrieve(e,t={},r){return this._client.get(`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>vs(r,e))}stream(e,t){return Wr.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t?.headers}})}},jr=class extends x{};ke.InputItems=Dt;var qt=class extends l{create(e,t,r){return this._client.post(`/uploads/${e}/parts`,W({body:t,...r}))}};var Me=class extends l{constructor(){super(...arguments),this.parts=new qt(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,r){return this._client.post(`/uploads/${e}/complete`,{body:t,...r})}};Me.Parts=qt;var In=async s=>{let e=await Promise.allSettled(s),t=e.filter(n=>n.status==="rejected");if(t.length){for(let n of t)console.error(n.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let r=[];for(let n of e)n.status==="fulfilled"&&r.push(n.value);return r};var Ne=class extends l{create(e,t,r){return this._client.post(`/vector_stores/${e}/files`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}update(e,t,r,n){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e,t={},r){return y(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,Be,{query:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}del(e,t,r){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){let n=await this.create(e,t,r);return await this.poll(e,n.id,r)}async poll(e,t,r){let n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let o=await this.retrieve(e,t,{...r,headers:n}).withResponse(),i=o.data;switch(i.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let c=o.response.headers.get("openai-poll-after-ms");if(c){let f=parseInt(c);isNaN(f)||(a=f)}}await fe(a);break;case"failed":case"completed":return i}}}async upload(e,t,r){let n=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:n.id},r)}async uploadAndPoll(e,t,r){let n=await this.upload(e,t,r);return await this.poll(e,n.id,r)}content(e,t,r){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Wt,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}},Be=class extends x{},Wt=class extends re{};Ne.VectorStoreFilesPage=Be;Ne.FileContentResponsesPage=Wt;var Ht=class extends l{create(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}retrieve(e,t,r){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}cancel(e,t,r){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}async createAndPoll(e,t,r){let n=await this.create(e,t);return await this.poll(e,n.id,r)}listFiles(e,t,r={},n){return y(r)?this.listFiles(e,t,{},r):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,Be,{query:r,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async poll(e,t,r){let n={...r?.headers,"X-Stainless-Poll-Helper":"true"};for(r?.pollIntervalMs&&(n["X-Stainless-Custom-Poll-Interval"]=r.pollIntervalMs.toString());;){let{data:o,response:i}=await this.retrieve(e,t,{...r,headers:n}).withResponse();switch(o.status){case"in_progress":let a=5e3;if(r?.pollIntervalMs)a=r.pollIntervalMs;else{let c=i.headers.get("openai-poll-after-ms");if(c){let f=parseInt(c);isNaN(f)||(a=f)}}await fe(a);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},n){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=n?.maxConcurrency??5,i=Math.min(o,t.length),a=this._client,c=t.values(),f=[...r];async function b(d){for(let p of d){let A=await a.files.create({file:p,purpose:"assistants"},n);f.push(A.id)}}let u=Array(i).fill(c).map(b);return await In(u),await this.createAndPoll(e,{file_ids:f})}};var K=class extends l{constructor(){super(...arguments),this.files=new Ne(this._client),this.fileBatches=new Ht(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,r){return this._client.post(`/vector_stores/${e}`,{body:t,...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}list(e={},t){return y(e)?this.list({},e):this._client.getAPIList("/vector_stores",at,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,r){return this._client.getAPIList(`/vector_stores/${e}/search`,lt,{body:t,method:"post",...r,headers:{"OpenAI-Beta":"assistants=v2",...r?.headers}})}},at=class extends x{},lt=class extends re{};K.VectorStoresPage=at;K.VectorStoreSearchResponsesPage=lt;K.Files=Ne;K.VectorStoreFilesPage=Be;K.FileContentResponsesPage=Wt;K.FileBatches=Ht;var Rn,w=class extends Rr{constructor({baseURL:e=tr("OPENAI_BASE_URL"),apiKey:t=tr("OPENAI_API_KEY"),organization:r=tr("OPENAI_ORG_ID")??null,project:n=tr("OPENAI_PROJECT_ID")??null,...o}={}){if(t===void 0)throw new h("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' }).");let i={apiKey:t,organization:r,project:n,...o,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&rn())throw new h(`It looks like you're running in a browser-like environment.
|
|
1
|
+
var ks=typeof global=="object"&&global&&global.Object===Object&&global,Ai=ks,Ss=typeof self=="object"&&self&&self.Object===Object&&self,Ps=Ai||Ss||Function("return this")(),de=Ps,Es=de.Symbol,ft=Es,vi=Object.prototype,Rs=vi.hasOwnProperty,$s=vi.toString,er=ft?ft.toStringTag:void 0;function Ms(r){var e=Rs.call(r,er),t=r[er];try{r[er]=void 0;var n=!0}catch{}var i=$s.call(r);return n&&(e?r[er]=t:delete r[er]),i}var Os=Ms,Ts=Object.prototype,Ns=Ts.toString;function js(r){return Ns.call(r)}var Ls=js,Fs="[object Null]",Ds="[object Undefined]",li=ft?ft.toStringTag:void 0;function Us(r){return r==null?r===void 0?Ds:Fs:li&&li in Object(r)?Os(r):Ls(r)}var ir=Us;function Bs(r){return r!=null&&typeof r=="object"}var bn=Bs,Ju=Array.isArray;function zs(r){var e=typeof r;return r!=null&&(e=="object"||e=="function")}var Ii=zs,qs="[object AsyncFunction]",Vs="[object Function]",Gs="[object GeneratorFunction]",Ws="[object Proxy]";function Hs(r){if(!Ii(r))return!1;var e=ir(r);return e==Vs||e==Gs||e==qs||e==Ws}var Qs=Hs,Js=de["__core-js_shared__"],cn=Js,ui=function(){var r=/[^.]+$/.exec(cn&&cn.keys&&cn.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""}();function Ys(r){return!!ui&&ui in r}var Ks=Ys,Xs=Function.prototype,Zs=Xs.toString;function eo(r){if(r!=null){try{return Zs.call(r)}catch{}try{return r+""}catch{}}return""}var Ue=eo,to=/[\\^$.*+?()[\]{}|]/g,ro=/^\[object .+?Constructor\]$/,no=Function.prototype,io=Object.prototype,so=no.toString,oo=io.hasOwnProperty,ao=RegExp("^"+so.call(oo).replace(to,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function lo(r){if(!Ii(r)||Ks(r))return!1;var e=Qs(r)?ao:ro;return e.test(Ue(r))}var uo=lo;function co(r,e){return r?.[e]}var po=co;function fo(r,e){var t=po(r,e);return uo(t)?t:void 0}var mt=fo,mo=mt(de,"WeakMap"),fn=mo;function ho(r,e){return r===e||r!==r&&e!==e}var go=ho,yo=9007199254740991;function bo(r){return typeof r=="number"&&r>-1&&r%1==0&&r<=yo}var wo=bo,Yu=Object.prototype,_o="[object Arguments]";function xo(r){return bn(r)&&ir(r)==_o}var ci=xo,Ci=Object.prototype,Ao=Ci.hasOwnProperty,vo=Ci.propertyIsEnumerable,Ku=ci(function(){return arguments}())?ci:function(r){return bn(r)&&Ao.call(r,"callee")&&!vo.call(r,"callee")},ki=typeof exports=="object"&&exports&&!exports.nodeType&&exports,di=ki&&typeof module=="object"&&module&&!module.nodeType&&module,Io=di&&di.exports===ki,pi=Io?de.Buffer:void 0,Xu=pi?pi.isBuffer:void 0,Co="[object Arguments]",ko="[object Array]",So="[object Boolean]",Po="[object Date]",Eo="[object Error]",Ro="[object Function]",$o="[object Map]",Mo="[object Number]",Oo="[object Object]",To="[object RegExp]",No="[object Set]",jo="[object String]",Lo="[object WeakMap]",Fo="[object ArrayBuffer]",Do="[object DataView]",Uo="[object Float32Array]",Bo="[object Float64Array]",zo="[object Int8Array]",qo="[object Int16Array]",Vo="[object Int32Array]",Go="[object Uint8Array]",Wo="[object Uint8ClampedArray]",Ho="[object Uint16Array]",Qo="[object Uint32Array]",I={};I[Uo]=I[Bo]=I[zo]=I[qo]=I[Vo]=I[Go]=I[Wo]=I[Ho]=I[Qo]=!0;I[Co]=I[ko]=I[Fo]=I[So]=I[Do]=I[Po]=I[Eo]=I[Ro]=I[$o]=I[Mo]=I[Oo]=I[To]=I[No]=I[jo]=I[Lo]=!1;function Jo(r){return bn(r)&&wo(r.length)&&!!I[ir(r)]}var Yo=Jo;function Ko(r){return function(e){return r(e)}}var Xo=Ko,Si=typeof exports=="object"&&exports&&!exports.nodeType&&exports,tr=Si&&typeof module=="object"&&module&&!module.nodeType&&module,Zo=tr&&tr.exports===Si,dn=Zo&&Ai.process,ea=function(){try{var r=tr&&tr.require&&tr.require("util").types;return r||dn&&dn.binding&&dn.binding("util")}catch{}}(),fi=ea,mi=fi&&fi.isTypedArray,Zu=mi?Xo(mi):Yo,ta=Object.prototype,ec=ta.hasOwnProperty;function ra(r,e){return function(t){return r(e(t))}}var na=ra,tc=na(Object.keys,Object),ia=Object.prototype,rc=ia.hasOwnProperty,sa=mt(Object,"create"),rr=sa;function oa(){this.__data__=rr?rr(null):{},this.size=0}var aa=oa;function la(r){var e=this.has(r)&&delete this.__data__[r];return this.size-=e?1:0,e}var ua=la,ca="__lodash_hash_undefined__",da=Object.prototype,pa=da.hasOwnProperty;function fa(r){var e=this.__data__;if(rr){var t=e[r];return t===ca?void 0:t}return pa.call(e,r)?e[r]:void 0}var ma=fa,ha=Object.prototype,ga=ha.hasOwnProperty;function ya(r){var e=this.__data__;return rr?e[r]!==void 0:ga.call(e,r)}var ba=ya,wa="__lodash_hash_undefined__";function _a(r,e){var t=this.__data__;return this.size+=this.has(r)?0:1,t[r]=rr&&e===void 0?wa:e,this}var xa=_a;function ht(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}ht.prototype.clear=aa;ht.prototype.delete=ua;ht.prototype.get=ma;ht.prototype.has=ba;ht.prototype.set=xa;var hi=ht;function Aa(){this.__data__=[],this.size=0}var va=Aa;function Ia(r,e){for(var t=r.length;t--;)if(go(r[t][0],e))return t;return-1}var Rr=Ia,Ca=Array.prototype,ka=Ca.splice;function Sa(r){var e=this.__data__,t=Rr(e,r);if(t<0)return!1;var n=e.length-1;return t==n?e.pop():ka.call(e,t,1),--this.size,!0}var Pa=Sa;function Ea(r){var e=this.__data__,t=Rr(e,r);return t<0?void 0:e[t][1]}var Ra=Ea;function $a(r){return Rr(this.__data__,r)>-1}var Ma=$a;function Oa(r,e){var t=this.__data__,n=Rr(t,r);return n<0?(++this.size,t.push([r,e])):t[n][1]=e,this}var Ta=Oa;function gt(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}gt.prototype.clear=va;gt.prototype.delete=Pa;gt.prototype.get=Ra;gt.prototype.has=Ma;gt.prototype.set=Ta;var $r=gt,Na=mt(de,"Map"),nr=Na;function ja(){this.size=0,this.__data__={hash:new hi,map:new(nr||$r),string:new hi}}var La=ja;function Fa(r){var e=typeof r;return e=="string"||e=="number"||e=="symbol"||e=="boolean"?r!=="__proto__":r===null}var Da=Fa;function Ua(r,e){var t=r.__data__;return Da(e)?t[typeof e=="string"?"string":"hash"]:t.map}var Mr=Ua;function Ba(r){var e=Mr(this,r).delete(r);return this.size-=e?1:0,e}var za=Ba;function qa(r){return Mr(this,r).get(r)}var Va=qa;function Ga(r){return Mr(this,r).has(r)}var Wa=Ga;function Ha(r,e){var t=Mr(this,r),n=t.size;return t.set(r,e),this.size+=t.size==n?0:1,this}var Qa=Ha;function yt(r){var e=-1,t=r==null?0:r.length;for(this.clear();++e<t;){var n=r[e];this.set(n[0],n[1])}}yt.prototype.clear=La;yt.prototype.delete=za;yt.prototype.get=Va;yt.prototype.has=Wa;yt.prototype.set=Qa;var Pi=yt;function Ja(){this.__data__=new $r,this.size=0}var Ya=Ja;function Ka(r){var e=this.__data__,t=e.delete(r);return this.size=e.size,t}var Xa=Ka;function Za(r){return this.__data__.get(r)}var el=Za;function tl(r){return this.__data__.has(r)}var rl=tl,nl=200;function il(r,e){var t=this.__data__;if(t instanceof $r){var n=t.__data__;if(!nr||n.length<nl-1)return n.push([r,e]),this.size=++t.size,this;t=this.__data__=new Pi(n)}return t.set(r,e),this.size=t.size,this}var sl=il;function sr(r){var e=this.__data__=new $r(r);this.size=e.size}sr.prototype.clear=Ya;sr.prototype.delete=Xa;sr.prototype.get=el;sr.prototype.has=rl;sr.prototype.set=sl;var ol=Object.prototype,nc=ol.propertyIsEnumerable,al=mt(de,"DataView"),mn=al,ll=mt(de,"Promise"),hn=ll,ul=mt(de,"Set"),gn=ul,gi="[object Map]",cl="[object Object]",yi="[object Promise]",bi="[object Set]",wi="[object WeakMap]",_i="[object DataView]",dl=Ue(mn),pl=Ue(nr),fl=Ue(hn),ml=Ue(gn),hl=Ue(fn),pt=ir;(mn&&pt(new mn(new ArrayBuffer(1)))!=_i||nr&&pt(new nr)!=gi||hn&&pt(hn.resolve())!=yi||gn&&pt(new gn)!=bi||fn&&pt(new fn)!=wi)&&(pt=function(r){var e=ir(r),t=e==cl?r.constructor:void 0,n=t?Ue(t):"";if(n)switch(n){case dl:return _i;case pl:return gi;case fl:return yi;case ml:return bi;case hl:return wi}return e});var ic=de.Uint8Array,gl="__lodash_hash_undefined__";function yl(r){return this.__data__.set(r,gl),this}var bl=yl;function wl(r){return this.__data__.has(r)}var _l=wl;function yn(r){var e=-1,t=r==null?0:r.length;for(this.__data__=new Pi;++e<t;)this.add(r[e])}yn.prototype.add=yn.prototype.push=bl;yn.prototype.has=_l;var xi=ft?ft.prototype:void 0,sc=xi?xi.valueOf:void 0,xl=Object.prototype,oc=xl.hasOwnProperty,Al=Object.prototype,ac=Al.hasOwnProperty,lc=new RegExp(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/,"i"),uc=new RegExp(/[A-Fa-f0-9]{1}/,"g"),cc=new RegExp(/[A-Fa-f0-9]{2}/,"g");function Ei(r,e){let t={...r};if(!e)return t;for(let[n,i]of Object.entries(e))i===!1||i===null||i===void 0?delete t[n]:i===!0?n in r||(t[n]=!0):t[n]=i;return t}var pn="@imgly/plugin-ai-generation",dc=`
|
|
2
|
+
<svg>
|
|
3
|
+
<symbol
|
|
4
|
+
fill="none"
|
|
5
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
6
|
+
viewBox="0 0 24 24"
|
|
7
|
+
id="@imgly/Sparkle"
|
|
8
|
+
>
|
|
9
|
+
<path d="M5.35545 2.06745C5.24149 1.72556 4.7579 1.72556 4.64394 2.06745L4.05898 3.82232C4.02166 3.93429 3.9338 4.02215 3.82184 4.05948L2.06694 4.64459C1.72506 4.75858 1.72509 5.24217 2.06699 5.3561L3.82179 5.9409C3.93378 5.97822 4.02166 6.06609 4.05899 6.17808L4.64394 7.93291C4.7579 8.2748 5.24149 8.2748 5.35545 7.93291L5.9404 6.17806C5.97773 6.06608 6.06559 5.97821 6.17757 5.94089L7.93242 5.35594C8.27431 5.24198 8.27431 4.75839 7.93242 4.64442L6.17757 4.05947C6.06559 4.02215 5.97773 3.93428 5.9404 3.8223L5.35545 2.06745Z" fill="currentColor"/>
|
|
10
|
+
<path d="M17.9632 3.23614C17.8026 2.80788 17.1968 2.80788 17.0362 3.23614L16.0787 5.78951C16.0285 5.92337 15.9229 6.02899 15.789 6.07918L13.2356 7.0367C12.8074 7.19729 12.8074 7.80307 13.2356 7.96366L15.789 8.92118C15.9229 8.97138 16.0285 9.077 16.0787 9.21085L17.0362 11.7642C17.1968 12.1925 17.8026 12.1925 17.9632 11.7642L18.9207 9.21086C18.9709 9.077 19.0765 8.97138 19.2104 8.92118L21.7637 7.96366C22.192 7.80307 22.192 7.1973 21.7637 7.0367L19.2104 6.07918C19.0765 6.02899 18.9709 5.92337 18.9207 5.78951L17.9632 3.23614Z" fill="currentColor"/>
|
|
11
|
+
<path d="M9.30058 7.82012C9.54712 7.1791 10.454 7.1791 10.7006 7.82012L12.3809 12.189C12.4571 12.3871 12.6136 12.5436 12.8117 12.6198L17.1806 14.3001C17.8216 14.5466 17.8216 15.4536 17.1806 15.7001L12.8117 17.3804C12.6136 17.4566 12.4571 17.6131 12.3809 17.8112L10.7006 22.1801C10.454 22.8211 9.54712 22.8211 9.30058 22.1801L7.62024 17.8112C7.54406 17.6131 7.38754 17.4566 7.18947 17.3804L2.82061 15.7001C2.17959 15.4536 2.17959 14.5466 2.82061 14.3001L7.18947 12.6198C7.38754 12.5436 7.54406 12.3871 7.62024 12.189L9.30058 7.82012Z" fill="currentColor"/>
|
|
12
|
+
|
|
13
|
+
</symbol>
|
|
14
|
+
|
|
15
|
+
<symbol
|
|
16
|
+
fill="none"
|
|
17
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
18
|
+
viewBox="0 0 24 24"
|
|
19
|
+
id="${pn}/image"
|
|
20
|
+
>
|
|
21
|
+
<path d="M3 16.5V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V6C21 4.34315 19.6569 3 18 3L17.999 5C18.5513 5 19 5.44772 19 6V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V16.5H3Z" fill="currentColor"/>
|
|
22
|
+
<path d="M13.0982 0.884877C12.9734 0.568323 12.5254 0.568322 12.4005 0.884876L11.7485 2.53819C11.7104 2.63483 11.6339 2.71134 11.5372 2.74945L9.8839 3.40151C9.56735 3.52636 9.56734 3.97436 9.8839 4.09921L11.5372 4.75126C11.6339 4.78938 11.7104 4.86588 11.7485 4.96253L12.4005 6.61584C12.5254 6.93239 12.9734 6.9324 13.0982 6.61584L13.7503 4.96253C13.7884 4.86588 13.8649 4.78938 13.9616 4.75126L15.6149 4.09921C15.9314 3.97436 15.9314 3.52636 15.6149 3.40151L13.9616 2.74945C13.8649 2.71134 13.7884 2.63483 13.7503 2.53819L13.0982 0.884877Z" fill="currentColor"/>
|
|
23
|
+
<path d="M6.40053 5.38488C6.52538 5.06832 6.97338 5.06832 7.09823 5.38488L8.17455 8.11392C8.21267 8.21057 8.28917 8.28707 8.38582 8.32519L11.1149 9.40151C11.4314 9.52636 11.4314 9.97436 11.1149 10.0992L8.38582 11.1755C8.28917 11.2136 8.21267 11.2901 8.17455 11.3868L7.09823 14.1158C6.97338 14.4324 6.52538 14.4324 6.40053 14.1158L5.32421 11.3868C5.2861 11.2901 5.20959 11.2136 5.11295 11.1755L2.3839 10.0992C2.06735 9.97436 2.06735 9.52636 2.3839 9.40151L5.11295 8.32519C5.20959 8.28707 5.2861 8.21057 5.32421 8.11392L6.40053 5.38488Z" fill="currentColor"/>
|
|
24
|
+
<path d="M18.9994 16.5008V18.0004C18.9994 18.5526 18.5517 19.0004 17.9994 19.0004H9.33302L14.3753 11.4369C14.6722 10.9916 15.3266 10.9916 15.6234 11.4369L18.9994 16.5008Z" fill="currentColor"/>
|
|
25
|
+
|
|
26
|
+
</symbol>
|
|
27
|
+
<symbol
|
|
28
|
+
fill="none"
|
|
29
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
30
|
+
viewBox="0 0 24 24"
|
|
31
|
+
id="${pn}/video"
|
|
32
|
+
>
|
|
33
|
+
<path d="M6 3C4.34315 3 3 4.34315 3 6V18C3 19.6569 4.34315 21 6 21H18C19.6569 21 21 19.6569 21 18V16.5H19V18C19 18.5523 18.5523 19 18 19H6C5.44772 19 5 18.5523 5 18V6C5 5.44772 5.44772 5 6 5V3Z" fill="currentColor"/>
|
|
34
|
+
<path d="M10.9025 0.8839C11.0273 0.567345 11.4753 0.567346 11.6002 0.883901L12.2522 2.53721C12.2904 2.63386 12.3669 2.71036 12.4635 2.74848L14.1168 3.40053C14.4334 3.52538 14.4334 3.97338 14.1168 4.09823L12.4635 4.75029C12.3669 4.7884 12.2904 4.86491 12.2522 4.96155L11.6002 6.61486C11.4753 6.93142 11.0273 6.93142 10.9025 6.61486L10.2504 4.96155C10.2123 4.86491 10.1358 4.7884 10.0392 4.75029L8.38585 4.09823C8.0693 3.97338 8.0693 3.52538 8.38585 3.40053L10.0392 2.74848C10.1358 2.71036 10.2123 2.63386 10.2504 2.53721L10.9025 0.8839Z" fill="currentColor"/>
|
|
35
|
+
<path d="M18.9019 3.3845C19.0267 3.06795 19.4747 3.06795 19.5996 3.3845L20.6759 6.11355C20.714 6.2102 20.7905 6.2867 20.8872 6.32482L23.6162 7.40114C23.9328 7.52598 23.9328 7.97399 23.6162 8.09883L20.8872 9.17515C20.7905 9.21327 20.714 9.28977 20.6759 9.38642L19.5996 12.1155C19.4747 12.432 19.0267 12.432 18.9019 12.1155L17.8255 9.38642C17.7874 9.28977 17.7109 9.21327 17.6143 9.17515L14.8852 8.09883C14.5687 7.97399 14.5687 7.52598 14.8852 7.40114L17.6143 6.32482C17.7109 6.2867 17.7874 6.2102 17.8255 6.11355L18.9019 3.3845Z" fill="currentColor"/>
|
|
36
|
+
<path d="M14.9994 13.2862C15.5089 12.8859 15.5089 12.1141 14.9995 11.7137L10.618 8.27047C9.96188 7.75485 9.00011 8.22225 9.00011 9.05673L9.00011 15.9429C9.00011 16.7773 9.96185 17.2448 10.618 16.7292L14.9994 13.2862Z" fill="currentColor"/>
|
|
37
|
+
</symbol>
|
|
38
|
+
<symbol
|
|
39
|
+
fill="none"
|
|
40
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
41
|
+
viewBox="0 0 24 24"
|
|
42
|
+
id="${pn}/audio"
|
|
43
|
+
>
|
|
44
|
+
<path d="M6 3.80273C4.2066 4.84016 3 6.77919 3 9.00004V12.8153C3 15.931 5.39501 18.4873 8.44444 18.7436V20.9645C8.44444 22.2198 9.89427 22.9198 10.8773 22.1392L15.1265 18.7647H15.5C17.8285 18.7647 19.8472 17.4384 20.8417 15.5H18.4187C17.6889 16.2784 16.6512 16.7647 15.5 16.7647H14.9522C14.6134 16.7647 14.2846 16.8794 14.0193 17.0901L10.4444 19.929V18.2597C10.4444 17.4341 9.77513 16.7647 8.9495 16.7647C7.80494 16.7647 6.77409 16.2779 6.05276 15.5H6V15.4419C5.37798 14.7439 5 13.8237 5 12.8153V9.00004C5 7.98559 5.37764 7.05935 6 6.35422V3.80273Z" fill="currentColor"/>
|
|
45
|
+
<path d="M11.6002 1.8839C11.4753 1.56735 11.0273 1.56735 10.9025 1.8839L10.2504 3.53721C10.2123 3.63386 10.1358 3.71036 10.0392 3.74848L8.38585 4.40053C8.0693 4.52538 8.0693 4.97338 8.38585 5.09823L10.0392 5.75029C10.1358 5.7884 10.2123 5.86491 10.2504 5.96155L10.9025 7.61486C11.0273 7.93142 11.4753 7.93142 11.6002 7.61486L12.2522 5.96155C12.2904 5.86491 12.3669 5.7884 12.4635 5.75029L14.1168 5.09823C14.4334 4.97338 14.4334 4.52538 14.1168 4.40053L12.4635 3.74848C12.3669 3.71036 12.2904 3.63386 12.2522 3.53721L11.6002 1.8839Z" fill="currentColor"/>
|
|
46
|
+
<path d="M19.5996 4.3845C19.4747 4.06795 19.0267 4.06795 18.9019 4.3845L17.8255 7.11355C17.7874 7.2102 17.7109 7.2867 17.6143 7.32482L14.8852 8.40114C14.5687 8.52598 14.5687 8.97399 14.8852 9.09883L17.6143 10.1752C17.7109 10.2133 17.7874 10.2898 17.8255 10.3864L18.9019 13.1155C19.0267 13.432 19.4747 13.432 19.5996 13.1155L20.6759 10.3864C20.714 10.2898 20.7905 10.2133 20.8872 10.1752L23.6162 9.09883C23.9328 8.97399 23.9328 8.52598 23.6162 8.40114L20.8872 7.32482C20.7905 7.2867 20.714 7.2102 20.6759 7.11355L19.5996 4.3845Z" fill="currentColor"/>
|
|
47
|
+
</symbol>
|
|
48
|
+
<symbol
|
|
49
|
+
fill="none"
|
|
50
|
+
xmlns="http://www.w3.org/2000/svg"
|
|
51
|
+
viewBox="0 0 24 24"
|
|
52
|
+
id="@imgly/MixingPlate"
|
|
53
|
+
>
|
|
54
|
+
<path d="M9.75 9C10.5784 9 11.25 8.32843 11.25 7.5C11.25 6.67157 10.5784 6 9.75 6C8.92157 6 8.25 6.67157 8.25 7.5C8.25 8.32843 8.92157 9 9.75 9Z" fill="currentColor"/>
|
|
55
|
+
<path d="M7 13C7.82843 13 8.5 12.3284 8.5 11.5C8.5 10.6716 7.82843 10 7 10C6.17157 10 5.5 10.6716 5.5 11.5C5.5 12.3284 6.17157 13 7 13Z" fill="currentColor"/>
|
|
56
|
+
<path d="M15.75 7.5C15.75 8.32843 15.0784 9 14.25 9C13.4216 9 12.75 8.32843 12.75 7.5C12.75 6.67157 13.4216 6 14.25 6C15.0784 6 15.75 6.67157 15.75 7.5Z" fill="currentColor"/>
|
|
57
|
+
<path d="M17 13C17.8284 13 18.5 12.3284 18.5 11.5C18.5 10.6716 17.8284 10 17 10C16.1716 10 15.5 10.6716 15.5 11.5C15.5 12.3284 16.1716 13 17 13Z" fill="currentColor"/>
|
|
58
|
+
<path fill-rule="evenodd" clip-rule="evenodd" d="M8.26309 2.77709C10.6681 1.77921 13.4829 1.7322 15.9209 2.64297C18.1572 3.47923 20.0876 5.09285 21.1766 7.28598C22.3395 9.62772 22.4889 13.1077 20.3864 15.2982C19.2693 16.4621 17.7657 16.9982 16.0026 16.9997C15.7897 16.9997 15.5555 16.9864 15.3497 16.9745C15.309 16.9722 15.2694 16.9699 15.2313 16.9679C14.9817 16.9542 14.761 16.9455 14.5569 16.9539C14.124 16.9718 13.9598 17.0612 13.89 17.1324C13.718 17.3081 13.6946 17.6672 13.8854 17.8895C14.2899 18.3608 14.5016 18.9277 14.5016 19.5497C14.5016 20.2206 14.3086 20.9011 13.7542 21.3896C13.2471 21.837 12.6082 21.9997 11.9635 21.9997C10.6049 21.9997 9.31155 21.7367 8.0934 21.2067C6.89058 20.6831 5.84501 19.9687 4.94363 19.0666C4.04281 18.1651 3.31836 17.107 2.79369 15.8978C1.72761 13.4409 1.72662 10.5261 2.81247 8.07034C3.88024 5.65548 5.84206 3.78161 8.26309 2.77709ZM15.2207 4.51639C13.2556 3.78239 10.9651 3.82132 9.02956 4.62439C7.06888 5.43791 5.49559 6.94785 4.64163 8.87914C3.78373 10.8194 3.78253 13.1522 4.62841 15.1017C5.05312 16.0805 5.63511 16.9291 6.35838 17.6529C7.08102 18.3761 7.91671 18.9484 8.89123 19.3728C9.8492 19.7895 10.87 19.9997 11.9635 19.9997C12.2815 19.9997 12.394 19.9225 12.431 19.8899L12.4319 19.8891C12.4367 19.8849 12.4487 19.8743 12.4631 19.8359C12.4799 19.7911 12.5016 19.7024 12.5016 19.5497C12.5016 19.4091 12.4633 19.3034 12.3677 19.192C11.5353 18.222 11.5272 16.6868 12.4611 15.7331C13.0741 15.1071 13.8844 14.98 14.4745 14.9556C14.7819 14.943 15.085 14.9568 15.3409 14.9709C15.3906 14.9736 15.4379 14.9763 15.4832 14.9788C15.6876 14.9904 15.8508 14.9997 16.0009 14.9997C17.3405 14.9986 18.2792 14.6054 18.9435 13.9133C20.2633 12.5382 20.3186 10.055 19.3853 8.1755C18.5436 6.48051 17.0293 5.19281 15.2207 4.51639Z" fill="currentColor"/>
|
|
59
|
+
|
|
60
|
+
</symbol>
|
|
61
|
+
</svg>
|
|
62
|
+
`;var Or="RFC3986",Tr={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},Ri="RFC1738";var vl=Array.isArray,ee=(()=>{let r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})();var wn=1024,$i=(r,e,t,n,i)=>{if(r.length===0)return r;let s=r;if(typeof r=="symbol"?s=Symbol.prototype.toString.call(r):typeof r!="string"&&(s=String(r)),t==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let o="";for(let a=0;a<s.length;a+=wn){let c=s.length>=wn?s.slice(a,a+wn):s,d=[];for(let _=0;_<c.length;++_){let u=c.charCodeAt(_);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||i===Ri&&(u===40||u===41)){d[d.length]=c.charAt(_);continue}if(u<128){d[d.length]=ee[u];continue}if(u<2048){d[d.length]=ee[192|u>>6]+ee[128|u&63];continue}if(u<55296||u>=57344){d[d.length]=ee[224|u>>12]+ee[128|u>>6&63]+ee[128|u&63];continue}_+=1,u=65536+((u&1023)<<10|c.charCodeAt(_)&1023),d[d.length]=ee[240|u>>18]+ee[128|u>>12&63]+ee[128|u>>6&63]+ee[128|u&63]}o+=d.join("")}return o};function Mi(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function _n(r,e){if(vl(r)){let t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}var Il=Object.prototype.hasOwnProperty,Oi={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},te=Array.isArray,Cl=Array.prototype.push,Ti=function(r,e){Cl.apply(r,te(e)?e:[e])},kl=Date.prototype.toISOString,M={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:$i,encodeValuesOnly:!1,format:Or,formatter:Tr[Or],indices:!1,serializeDate(r){return kl.call(r)},skipNulls:!1,strictNullHandling:!1};function Sl(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}var xn={};function Ni(r,e,t,n,i,s,o,a,c,d,_,u,f,p,A,g,S,R){let y=r,D=R,k=0,N=!1;for(;(D=D.get(xn))!==void 0&&!N;){let P=D.get(r);if(k+=1,typeof P<"u"){if(P===k)throw new RangeError("Cyclic object value");N=!0}typeof D.get(xn)>"u"&&(k=0)}if(typeof d=="function"?y=d(e,y):y instanceof Date?y=f?.(y):t==="comma"&&te(y)&&(y=_n(y,function(P){return P instanceof Date?f?.(P):P})),y===null){if(s)return c&&!g?c(e,M.encoder,S,"key",p):e;y=""}if(Sl(y)||Mi(y)){if(c){let P=g?e:c(e,M.encoder,S,"key",p);return[A?.(P)+"="+A?.(c(y,M.encoder,S,"value",p))]}return[A?.(e)+"="+A?.(String(y))]}let B=[];if(typeof y>"u")return B;let z;if(t==="comma"&&te(y))g&&c&&(y=_n(y,c)),z=[{value:y.length>0?y.join(",")||null:void 0}];else if(te(d))z=d;else{let P=Object.keys(y);z=_?P.sort(_):P}let j=a?String(e).replace(/\./g,"%2E"):String(e),L=n&&te(y)&&y.length===1?j+"[]":j;if(i&&te(y)&&y.length===0)return L+"[]";for(let P=0;P<z.length;++P){let $=z[P],oi=typeof $=="object"&&typeof $.value<"u"?$.value:y[$];if(o&&oi===null)continue;let un=u&&a?$.replace(/\./g,"%2E"):$,Cs=te(y)?typeof t=="function"?t(L,un):L:L+(u?"."+un:"["+un+"]");R.set(r,k);let ai=new WeakMap;ai.set(xn,R),Ti(B,Ni(oi,Cs,t,n,i,s,o,a,t==="comma"&&g&&te(y)?null:c,d,_,u,f,p,A,g,S,ai))}return B}function Pl(r=M){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=r.charset||M.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Or;if(typeof r.format<"u"){if(!Il.call(Tr,r.format))throw new TypeError("Unknown format option provided.");t=r.format}let n=Tr[t],i=M.filter;(typeof r.filter=="function"||te(r.filter))&&(i=r.filter);let s;if(r.arrayFormat&&r.arrayFormat in Oi?s=r.arrayFormat:"indices"in r?s=r.indices?"indices":"repeat":s=M.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:M.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:M.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:M.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:M.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?M.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:M.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:M.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:M.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:M.encodeValuesOnly,filter:i,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:M.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:M.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:M.strictNullHandling}}function An(r,e={}){let t=r,n=Pl(e),i,s;typeof n.filter=="function"?(s=n.filter,t=s("",t)):te(n.filter)&&(s=n.filter,i=s);let o=[];if(typeof t!="object"||t===null)return"";let a=Oi[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;i||(i=Object.keys(t)),n.sort&&i.sort(n.sort);let d=new WeakMap;for(let f=0;f<i.length;++f){let p=i[f];n.skipNulls&&t[p]===null||Ti(o,Ni(t[p],p,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,d))}let _=o.join(n.delimiter),u=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),_.length>0?u+_:""}var Be="4.104.0";var ji=!1,ze,vn,Rl,$l,Ml,In,Ol,Nr,Cn,kn,Sn,jr,Pn;function Li(r,e={auto:!1}){if(ji)throw new Error(`you must \`import 'openai/shims/${r.kind}'\` before importing anything else from openai`);if(ze)throw new Error(`can't \`import 'openai/shims/${r.kind}'\` after \`import 'openai/shims/${ze}'\``);ji=e.auto,ze=r.kind,vn=r.fetch,Rl=r.Request,$l=r.Response,Ml=r.Headers,In=r.FormData,Ol=r.Blob,Nr=r.File,Cn=r.ReadableStream,kn=r.getMultipartRequestOptions,Sn=r.getDefaultAgent,jr=r.fileFromPath,Pn=r.isFsReadStream}var Lr=class{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}};function Fi({manuallyImported:r}={}){let e=r?"You may need to use polyfills":"Add one of these imports before your first `import \u2026 from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n",t,n,i,s;try{t=fetch,n=Request,i=Response,s=Headers}catch(o){throw new Error(`this environment is missing the following Web Fetch API type: ${o.message}. ${e}`)}return{kind:"web",fetch:t,Request:n,Response:i,Headers:s,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(o,a)=>({...a,body:new Lr(o)}),getDefaultAgent:o=>{},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:o=>!1}}var En=()=>{ze||Li(Fi(),{auto:!0})};En();var m=class extends Error{},O=class r extends m{constructor(e,t,n,i){super(`${r.makeMessage(e,t,n)}`),this.status=e,this.headers=i,this.request_id=i?.["x-request-id"],this.error=t;let s=t;this.code=s?.code,this.param=s?.param,this.type=s?.type}static makeMessage(e,t,n){let i=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,t,n,i){if(!e||!i)return new _e({message:n,cause:Fr(t)});let s=t?.error;return e===400?new or(e,s,n,i):e===401?new ar(e,s,n,i):e===403?new lr(e,s,n,i):e===404?new ur(e,s,n,i):e===409?new cr(e,s,n,i):e===422?new dr(e,s,n,i):e===429?new pr(e,s,n,i):e>=500?new fr(e,s,n,i):new r(e,s,n,i)}},E=class extends O{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},_e=class extends O{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}},xe=class extends _e{constructor({message:e}={}){super({message:e??"Request timed out."})}},or=class extends O{},ar=class extends O{},lr=class extends O{},ur=class extends O{},cr=class extends O{},dr=class extends O{},pr=class extends O{},fr=class extends O{},bt=class extends m{constructor(){super("Could not parse response content as the length limit was reached")}},wt=class extends m{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};var Dr=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},qe=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},W,Ve=class{constructor(){W.set(this,void 0),this.buffer=new Uint8Array,Dr(this,W,null,"f")}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;let i=[],s;for(;(s=jl(this.buffer,qe(this,W,"f")))!=null;){if(s.carriage&&qe(this,W,"f")==null){Dr(this,W,s.index,"f");continue}if(qe(this,W,"f")!=null&&(s.index!==qe(this,W,"f")+1||s.carriage)){i.push(this.decodeText(this.buffer.slice(0,qe(this,W,"f")-1))),this.buffer=this.buffer.slice(qe(this,W,"f")),Dr(this,W,null,"f");continue}let o=qe(this,W,"f")!==null?s.preceding-1:s.preceding,a=this.decodeText(this.buffer.slice(0,o));i.push(a),this.buffer=this.buffer.slice(s.index),Dr(this,W,null,"f")}return i}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new m(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new m(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new m("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
|
|
63
|
+
`):[]}};W=new WeakMap;Ve.NEWLINE_CHARS=new Set([`
|
|
64
|
+
`,"\r"]);Ve.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function jl(r,e){for(let i=e??0;i<r.length;i++){if(r[i]===10)return{preceding:i,index:i+1,carriage:!1};if(r[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function Di(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}function Rn(r){if(r[Symbol.asyncIterator])return r;let e=r.getReader();return{async next(){try{let t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){let t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var re=class r{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let s=!1;try{for await(let o of Ll(e,t))if(!s){if(o.data.startsWith("[DONE]")){s=!0;continue}if(o.event===null||o.event.startsWith("response.")||o.event.startsWith("transcript.")){let a;try{a=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(a&&a.error)throw new O(void 0,a.error,void 0,Mn(e.headers));yield a}else{let a;try{a=JSON.parse(o.data)}catch(c){throw console.error("Could not parse message into JSON:",o.data),console.error("From chunk:",o.raw),c}if(o.event=="error")throw new O(void 0,a.error,a.message,void 0);yield{event:o.event,data:a}}}s=!0}catch(o){if(o instanceof Error&&o.name==="AbortError")return;throw o}finally{s||t.abort()}}return new r(i,t)}static fromReadableStream(e,t){let n=!1;async function*i(){let o=new Ve,a=Rn(e);for await(let c of a)for(let d of o.decode(c))yield d;for(let c of o.flush())yield c}async function*s(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(let a of i())o||a&&(yield JSON.parse(a));o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new r(s,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],n=this.iterator(),i=s=>({next:()=>{if(s.length===0){let o=n.next();e.push(o),t.push(o)}return s.shift()}});return[new r(()=>i(e),this.controller),new r(()=>i(t),this.controller)]}toReadableStream(){let e=this,t,n=new TextEncoder;return new Cn({async start(){t=e[Symbol.asyncIterator]()},async pull(i){try{let{value:s,done:o}=await t.next();if(o)return i.close();let a=n.encode(JSON.stringify(s)+`
|
|
65
|
+
`);i.enqueue(a)}catch(s){i.error(s)}},async cancel(){await t.return?.()}})}};async function*Ll(r,e){if(!r.body)throw e.abort(),new m("Attempted to iterate over a response with no body");let t=new $n,n=new Ve,i=Rn(r.body);for await(let s of Fl(i))for(let o of n.decode(s)){let a=t.decode(o);a&&(yield a)}for(let s of n.flush()){let o=t.decode(s);o&&(yield o)}}async function*Fl(r){let e=new Uint8Array;for await(let t of r){if(t==null)continue;let n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,i=new Uint8Array(e.length+n.length);i.set(e),i.set(n,e.length),e=i;let s;for(;(s=Di(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}var $n=class{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;let s={event:this.event,data:this.data.join(`
|
|
66
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,i]=Dl(e,":");return i.startsWith(" ")&&(i=i.substring(1)),t==="event"?this.event=i:t==="data"&&this.data.push(i),null}};function Dl(r,e){let t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}var Ui=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Bi=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&mr(r),mr=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Ul=r=>Bi(r)||Ui(r)||Pn(r);async function Nn(r,e,t){if(r=await r,Bi(r))return r;if(Ui(r)){let i=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");let s=mr(i)?[await i.arrayBuffer()]:[i];return new Nr(s,e,t)}let n=await Bl(r);if(e||(e=ql(r)??"unknown_file"),!t?.type){let i=n[0]?.type;typeof i=="string"&&(t={...t,type:i})}return new Nr(n,e,t)}async function Bl(r){let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(mr(r))e.push(await r.arrayBuffer());else if(Vl(r))for await(let t of r)e.push(t);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${r?.constructor?.name}; props: ${zl(r)}`);return e}function zl(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function ql(r){return On(r.name)||On(r.filename)||On(r.path)?.split(/[\\/]/).pop()}var On=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Vl=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",jn=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody";var V=async r=>{let e=await zi(r.body);return kn(e,r)},zi=async r=>{let e=new In;return await Promise.all(Object.entries(r||{}).map(([t,n])=>Tn(e,t,n))),e};var Tn=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(Ul(t)){let n=await Nn(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>Tn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,i])=>Tn(r,`${e}[${n}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Wl=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Hl=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Ur;En();async function Qi(r){let{response:e}=r;if(r.options.stream)return pe("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):re.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;let n=e.headers.get("content-type")?.split(";")[0]?.trim();if(n?.includes("application/json")||n?.endsWith("+json")){let o=await e.json();return pe("response",e.status,e.url,e.headers,o),Ji(o,e)}let s=await e.text();return pe("response",e.status,e.url,e.headers,s),s}function Ji(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var zr=class r extends Promise{constructor(e,t=Qi){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new r(this.responsePromise,async t=>Ji(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[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)}},qr=class{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:i,fetch:s}){this.baseURL=e,this.maxRetries=Ln("maxRetries",t),this.timeout=Ln("timeout",n),this.httpAgent=i,this.fetch=s??vn}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Kl(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${tu()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async i=>{let s=i&&mr(i?.body)?new DataView(await i.body.arrayBuffer()):i?.body instanceof DataView?i.body:i?.body instanceof ArrayBuffer?new DataView(i.body):i&&ArrayBuffer.isView(i?.body)?new DataView(i.body.buffer):i?.body;return{method:e,path:t,...i,body:s}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:i,path:s,query:o,headers:a={}}=n,c=ArrayBuffer.isView(n.body)||n.__binaryRequest&&typeof n.body=="string"?n.body:jn(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,d=this.calculateContentLength(c),_=this.buildURL(s,o);"timeout"in n&&Ln("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let u=n.httpAgent??this.httpAgent??Sn(_),f=n.timeout+1e3;typeof u?.options?.timeout=="number"&&f>(u.options.timeout??0)&&(u.options.timeout=f),this.idempotencyHeader&&i!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);let p=this.buildHeaders({options:n,headers:a,contentLength:d,retryCount:t});return{req:{method:i,...c&&{body:c},headers:p,...u&&{agent:u},signal:n.signal??null},url:_,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:i}){let s={};n&&(s["content-length"]=n);let o=this.defaultHeaders(e);return Wi(s,o),Wi(s,t),jn(e.body)&&ze!=="node"&&delete s["content-type"],Br(o,"x-stainless-retry-count")===void 0&&Br(t,"x-stainless-retry-count")===void 0&&(s["x-stainless-retry-count"]=String(i)),Br(o,"x-stainless-timeout")===void 0&&Br(t,"x-stainless-timeout")===void 0&&e.timeout&&(s["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(s,t),s}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,i){return O.generate(e,t,n,i)}request(e,t=null){return new zr(this.makeRequest(e,t))}async makeRequest(e,t){let n=await e,i=n.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(n);let{req:s,url:o,timeout:a}=this.buildRequest(n,{retryCount:i-t});if(await this.prepareRequest(s,{url:o,options:n}),pe("request",o,n,s.headers),n.signal?.aborted)throw new E;let c=new AbortController,d=await this.fetchWithTimeout(o,s,a,c).catch(Fr);if(d instanceof Error){if(n.signal?.aborted)throw new E;if(t)return this.retryRequest(n,t);throw d.name==="AbortError"?new xe:new _e({cause:d})}let _=Mn(d.headers);if(!d.ok){if(t&&this.shouldRetry(d)){let S=`retrying, ${t} attempts remaining`;return pe(`response (error; ${S})`,d.status,o,_),this.retryRequest(n,t,_)}let u=await d.text().catch(S=>Fr(S).message),f=Xl(u),p=f?void 0:u;throw pe(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,d.status,o,_,p),this.makeStatusError(d.status,f,p,_)}return{response:d,options:n,controller:c}}requestAPIList(e,t){let n=this.makeRequest(t,null);return new Fn(this,n,e)}buildURL(e,t){let n=eu(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Yi(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new m(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,i){let{signal:s,...o}=t||{};s&&s.addEventListener("abort",()=>i.abort());let a=setTimeout(()=>i.abort(),n),c={signal:i.signal,...o};return c.method&&(c.method=c.method.toUpperCase()),this.fetch.call(void 0,e,c).finally(()=>{clearTimeout(a)})}shouldRetry(e){let t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n){let i,s=n?.["retry-after-ms"];if(s){let a=parseFloat(s);Number.isNaN(a)||(i=a)}let o=n?.["retry-after"];if(o&&!i){let a=parseFloat(o);Number.isNaN(a)?i=Date.parse(o)-Date.now():i=a*1e3}if(!(i&&0<=i&&i<60*1e3)){let a=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,a)}return await fe(i),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){let s=t-e,o=Math.min(.5*Math.pow(2,s),8),a=1-Math.random()*.25;return o*a*1e3}getUserAgent(){return`${this.constructor.name}/JS ${Be}`}},hr=class{constructor(e,t,n,i){Ur.set(this,void 0),Wl(this,Ur,e,"f"),this.options=i,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){let e=this.nextPageInfo();if(!e)throw new m("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");let t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){let n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(let[i,s]of n)e.url.searchParams.set(i,s);t.query=void 0,t.path=e.url.toString()}return await Hl(this,Ur,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ur=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},Fn=class extends zr{constructor(e,t,n){super(t,async i=>new n(e,i.response,await Qi(i),i.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},Mn=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){let n=t.toString();return e[n.toLowerCase()]||e[n]}}),Ql={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},w=r=>typeof r=="object"&&r!==null&&!Yi(r)&&Object.keys(r).every(e=>Ki(Ql,e)),Jl=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Be,"X-Stainless-OS":Vi(Deno.build.os),"X-Stainless-Arch":qi(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Be,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Be,"X-Stainless-OS":Vi(process.platform),"X-Stainless-Arch":qi(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};let r=Yl();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Be,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Be,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Yl(){if(typeof navigator>"u"||!navigator)return null;let r=[{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(let{key:e,pattern:t}of r){let n=t.exec(navigator.userAgent);if(n){let i=n[1]||0,s=n[2]||0,o=n[3]||0;return{browser:e,version:`${i}.${s}.${o}`}}}return null}var qi=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Vi=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown"),Gi,Kl=()=>Gi??(Gi=Jl()),Xl=r=>{try{return JSON.parse(r)}catch{return}},Zl=/^[a-z][a-z0-9+.-]*:/i,eu=r=>Zl.test(r),fe=r=>new Promise(e=>setTimeout(e,r)),Ln=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new m(`${r} must be an integer`);if(e<0)throw new m(`${r} must be a positive integer`);return e},Fr=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(r)};var gr=r=>{if(typeof process<"u")return process.env?.[r]?.trim()??void 0;if(typeof Deno<"u")return Deno.env?.get?.(r)?.trim()};function Yi(r){if(!r)return!0;for(let e in r)return!1;return!0}function Ki(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Wi(r,e){for(let t in e){if(!Ki(e,t))continue;let n=t.toLowerCase();if(!n)continue;let i=e[t];i===null?delete r[n]:i!==void 0&&(r[n]=i)}}var Hi=new Set(["authorization","api-key"]);function pe(r,...e){if(typeof process<"u"&&process?.env?.DEBUG==="true"){let t=e.map(n=>{if(!n)return n;if(n.headers){let s={...n,headers:{...n.headers}};for(let o in n.headers)Hi.has(o.toLowerCase())&&(s.headers[o]="REDACTED");return s}let i=null;for(let s in n)Hi.has(s.toLowerCase())&&(i??(i={...n}),i[s]="REDACTED");return i??n});console.log(`OpenAI:DEBUG:${r}`,...t)}}var tu=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{let e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Xi=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",ru=r=>typeof r?.get=="function";var Br=(r,e)=>{let t=e.toLowerCase();if(ru(r)){let n=e[0]?.toUpperCase()+e.substring(1).replace(/([^\w])(\w)/g,(i,s,o)=>s+o.toUpperCase());for(let i of[e,t,e.toUpperCase(),n]){let s=r.get(i);if(s)return s}}for(let[n,i]of Object.entries(r))if(n.toLowerCase()===t)return Array.isArray(i)?(i.length<=1||console.warn(`Received ${i.length} entries for the ${e} header, using the first entry.`),i[0]):i};var Zi=r=>{if(typeof Buffer<"u"){let e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(r),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.charCodeAt(i);return Array.from(new Float32Array(n.buffer))}};function yr(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}var ne=class extends hr{constructor(e,t,n,i){super(e,t,n,i),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}},x=class extends hr{constructor(e,t,n,i){super(e,t,n,i),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){let e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;let t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){let e=this.getPaginatedItems();if(!e.length)return null;let t=e[e.length-1]?.id;return t?{params:{after:t}}:null}};var l=class{constructor(e){this._client=e}};var _t=class extends l{list(e,t={},n){return w(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Vr,{query:t,...n})}};var Ae=class extends l{constructor(){super(...arguments),this.messages=new _t(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return w(e)?this.list({},e):this._client.getAPIList("/chat/completions",ve,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}},ve=class extends x{},Vr=class extends x{};Ae.ChatCompletionsPage=ve;Ae.Messages=_t;var he=class extends l{constructor(){super(...arguments),this.completions=new Ae(this._client)}};he.Completions=Ae;he.ChatCompletionsPage=ve;var xt=class extends l{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t?.headers},__binaryResponse:!0})}};var At=class extends l{create(e,t){return this._client.post("/audio/transcriptions",V({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}};var vt=class extends l{create(e,t){return this._client.post("/audio/translations",V({body:e,...t,__metadata:{model:e.model}}))}};var ie=class extends l{constructor(){super(...arguments),this.transcriptions=new At(this._client),this.translations=new vt(this._client),this.speech=new xt(this._client)}};ie.Transcriptions=At;ie.Translations=vt;ie.Speech=xt;var Ie=class extends l{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 w(e)?this.list({},e):this._client.getAPIList("/batches",Ge,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}},Ge=class extends x{};Ie.BatchesPage=Ge;var K=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},C=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Dn,Gr,Wr,br,wr,Hr,_r,ge,xr,Qr,Jr,It,es,Ce=class{constructor(){Dn.add(this),this.controller=new AbortController,Gr.set(this,void 0),Wr.set(this,()=>{}),br.set(this,()=>{}),wr.set(this,void 0),Hr.set(this,()=>{}),_r.set(this,()=>{}),ge.set(this,{}),xr.set(this,!1),Qr.set(this,!1),Jr.set(this,!1),It.set(this,!1),K(this,Gr,new Promise((e,t)=>{K(this,Wr,e,"f"),K(this,br,t,"f")}),"f"),K(this,wr,new Promise((e,t)=>{K(this,Hr,e,"f"),K(this,_r,t,"f")}),"f"),C(this,Gr,"f").catch(()=>{}),C(this,wr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},C(this,Dn,"m",es).bind(this))},0)}_connected(){this.ended||(C(this,Wr,"f").call(this),this._emit("connect"))}get ended(){return C(this,xr,"f")}get errored(){return C(this,Qr,"f")}get aborted(){return C(this,Jr,"f")}abort(){this.controller.abort()}on(e,t){return(C(this,ge,"f")[e]||(C(this,ge,"f")[e]=[])).push({listener:t}),this}off(e,t){let n=C(this,ge,"f")[e];if(!n)return this;let i=n.findIndex(s=>s.listener===t);return i>=0&&n.splice(i,1),this}once(e,t){return(C(this,ge,"f")[e]||(C(this,ge,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{K(this,It,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){K(this,It,!0,"f"),await C(this,wr,"f")}_emit(e,...t){if(C(this,xr,"f"))return;e==="end"&&(K(this,xr,!0,"f"),C(this,Hr,"f").call(this));let n=C(this,ge,"f")[e];if(n&&(C(this,ge,"f")[e]=n.filter(i=>!i.once),n.forEach(({listener:i})=>i(...t))),e==="abort"){let i=t[0];!C(this,It,"f")&&!n?.length&&Promise.reject(i),C(this,br,"f").call(this,i),C(this,_r,"f").call(this,i),this._emit("end");return}if(e==="error"){let i=t[0];!C(this,It,"f")&&!n?.length&&Promise.reject(i),C(this,br,"f").call(this,i),C(this,_r,"f").call(this,i),this._emit("end")}}_emitFinal(){}};Gr=new WeakMap,Wr=new WeakMap,br=new WeakMap,wr=new WeakMap,Hr=new WeakMap,_r=new WeakMap,ge=new WeakMap,xr=new WeakMap,Qr=new WeakMap,Jr=new WeakMap,It=new WeakMap,Dn=new WeakSet,es=function(e){if(K(this,Qr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new E),e instanceof E)return K(this,Jr,!0,"f"),this._emit("abort",e);if(e instanceof m)return this._emit("error",e);if(e instanceof Error){let t=new m(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new m(String(e)))};var h=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},H=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},U,Un,se,Yr,X,He,Ct,We,Zr,Q,Kr,Xr,Ir,Ar,vr,ts,rs,ns,is,ss,os,as,oe=class r extends Ce{constructor(){super(...arguments),U.add(this),Un.set(this,[]),se.set(this,{}),Yr.set(this,{}),X.set(this,void 0),He.set(this,void 0),Ct.set(this,void 0),We.set(this,void 0),Zr.set(this,void 0),Q.set(this,void 0),Kr.set(this,void 0),Xr.set(this,void 0),Ir.set(this,void 0)}[(Un=new WeakMap,se=new WeakMap,Yr=new WeakMap,X=new WeakMap,He=new WeakMap,Ct=new WeakMap,We=new WeakMap,Zr=new WeakMap,Q=new WeakMap,Kr=new WeakMap,Xr=new WeakMap,Ir=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let s=t.shift();s?s.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let s of t)s.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let s of t)s.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,o)=>t.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new r;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let i=re.fromReadableStream(e,this.controller);for await(let s of i)h(this,U,"m",Ar).call(this,s);if(i.controller.signal?.aborted)throw new E;return this._addRun(h(this,U,"m",vr).call(this))}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,i,s){let o=new r;return o._run(()=>o._runToolAssistantStream(e,t,n,i,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,t,n,i,s){let o=s?.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let a={...i,stream:!0},c=await e.submitToolOutputs(t,n,a,{...s,signal:this.controller.signal});this._connected();for await(let d of c)h(this,U,"m",Ar).call(this,d);if(c.controller.signal?.aborted)throw new E;return this._addRun(h(this,U,"m",vr).call(this))}static createThreadAssistantStream(e,t,n){let i=new r;return i._run(()=>i._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,t,n,i){let s=new r;return s._run(()=>s._runAssistantStream(e,t,n,{...i,headers:{...i?.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return h(this,Kr,"f")}currentRun(){return h(this,Xr,"f")}currentMessageSnapshot(){return h(this,X,"f")}currentRunStepSnapshot(){return h(this,Ir,"f")}async finalRunSteps(){return await this.done(),Object.values(h(this,se,"f"))}async finalMessages(){return await this.done(),Object.values(h(this,Yr,"f"))}async finalRun(){if(await this.done(),!h(this,He,"f"))throw Error("Final run was not received.");return h(this,He,"f")}async _createThreadAssistantStream(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));let s={...t,stream:!0},o=await e.createAndRun(s,{...n,signal:this.controller.signal});this._connected();for await(let a of o)h(this,U,"m",Ar).call(this,a);if(o.controller.signal?.aborted)throw new E;return this._addRun(h(this,U,"m",vr).call(this))}async _createAssistantStream(e,t,n,i){let s=i?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...n,stream:!0},a=await e.create(t,o,{...i,signal:this.controller.signal});this._connected();for await(let c of a)h(this,U,"m",Ar).call(this,c);if(a.controller.signal?.aborted)throw new E;return this._addRun(h(this,U,"m",vr).call(this))}static accumulateDelta(e,t){for(let[n,i]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=i;continue}let s=e[n];if(s==null){e[n]=i;continue}if(n==="index"||n==="type"){e[n]=i;continue}if(typeof s=="string"&&typeof i=="string")s+=i;else if(typeof s=="number"&&typeof i=="number")s+=i;else if(yr(s)&&yr(i))s=this.accumulateDelta(s,i);else if(Array.isArray(s)&&Array.isArray(i)){if(s.every(o=>typeof o=="string"||typeof o=="number")){s.push(...i);continue}for(let o of i){if(!yr(o))throw new Error(`Expected array delta entry to be an object but got: ${o}`);let a=o.index;if(a==null)throw console.error(o),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=s[a];c==null?s.push(o):s[a]=this.accumulateDelta(c,o)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${i}, accValue: ${s}`);e[n]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,i){return await this._createAssistantStream(t,e,n,i)}async _runToolAssistantStream(e,t,n,i,s){return await this._createToolAssistantStream(n,e,t,i,s)}};Ar=function(e){if(!this.ended)switch(H(this,Kr,e,"f"),h(this,U,"m",ns).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":h(this,U,"m",as).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":h(this,U,"m",rs).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":h(this,U,"m",ts).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},vr=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");if(!h(this,He,"f"))throw Error("Final run has not been received");return h(this,He,"f")},ts=function(e){let[t,n]=h(this,U,"m",ss).call(this,e,h(this,X,"f"));H(this,X,t,"f"),h(this,Yr,"f")[t.id]=t;for(let i of n){let s=t.content[i.index];s?.type=="text"&&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(let i of e.data.delta.content){if(i.type=="text"&&i.text){let s=i.text,o=t.content[i.index];if(o&&o.type=="text")this._emit("textDelta",s,o.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=h(this,Ct,"f")){if(h(this,We,"f"))switch(h(this,We,"f").type){case"text":this._emit("textDone",h(this,We,"f").text,h(this,X,"f"));break;case"image_file":this._emit("imageFileDone",h(this,We,"f").image_file,h(this,X,"f"));break}H(this,Ct,i.index,"f")}H(this,We,t.content[i.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(h(this,Ct,"f")!==void 0){let i=e.data.content[h(this,Ct,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,h(this,X,"f"));break;case"text":this._emit("textDone",i.text,h(this,X,"f"));break}}h(this,X,"f")&&this._emit("messageDone",e.data),H(this,X,void 0,"f")}},rs=function(e){let t=h(this,U,"m",is).call(this,e);switch(H(this,Ir,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(let s of n.step_details.tool_calls)s.index==h(this,Zr,"f")?this._emit("toolCallDelta",s,t.step_details.tool_calls[s.index]):(h(this,Q,"f")&&this._emit("toolCallDone",h(this,Q,"f")),H(this,Zr,s.index,"f"),H(this,Q,t.step_details.tool_calls[s.index],"f"),h(this,Q,"f")&&this._emit("toolCallCreated",h(this,Q,"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":H(this,Ir,void 0,"f"),e.data.step_details.type=="tool_calls"&&h(this,Q,"f")&&(this._emit("toolCallDone",h(this,Q,"f")),H(this,Q,void 0,"f")),this._emit("runStepDone",e.data,t);break;case"thread.run.step.in_progress":break}},ns=function(e){h(this,Un,"f").push(e),this._emit("event",e)},is=function(e){switch(e.event){case"thread.run.step.created":return h(this,se,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=h(this,se,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let i=oe.accumulateDelta(t,n.delta);h(this,se,"f")[e.data.id]=i}return h(this,se,"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":h(this,se,"f")[e.data.id]=e.data;break}if(h(this,se,"f")[e.data.id])return h(this,se,"f")[e.data.id];throw new Error("No snapshot available")},ss=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(let s of i.delta.content)if(s.index in t.content){let o=t.content[s.index];t.content[s.index]=h(this,U,"m",os).call(this,s,o)}else t.content[s.index]=s,n.push(s);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},os=function(e,t){return oe.accumulateDelta(t,e)},as=function(e){switch(H(this,Xr,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;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":H(this,He,e.data,"f"),h(this,Q,"f")&&(this._emit("toolCallDone",h(this,Q,"f")),H(this,Q,void 0,"f"));break;case"thread.run.cancelling":break}};var Qe=class extends l{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return w(e)?this.list({},e):this._client.getAPIList("/assistants",kt,{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}})}},kt=class extends x{};Qe.AssistantsPage=kt;function Bn(r){return typeof r.parse=="function"}var ke=r=>r?.role==="assistant",zn=r=>r?.role==="function",qn=r=>r?.role==="tool";function Cr(r){return r?.$brand==="auto-parseable-response-format"}function Je(r){return r?.$brand==="auto-parseable-tool"}function ls(r,e){return!e||!Vn(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:kr(r,e)}function kr(r,e){let t=r.choices.map(n=>{if(n.finish_reason==="length")throw new bt;if(n.finish_reason==="content_filter")throw new wt;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:n.message.tool_calls?.map(i=>cu(e,i))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?uu(e,n.message.content):null}}});return{...r,choices:t}}function uu(r,e){return r.response_format?.type!=="json_schema"?null:r.response_format?.type==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function cu(r,e){let t=r.tools?.find(n=>n.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Je(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function us(r,e){if(!r)return!1;let t=r.tools?.find(n=>n.function?.name===e.function.name);return Je(t)||t?.function.strict||!1}function Vn(r){return Cr(r.response_format)?!0:r.tools?.some(e=>Je(e)||e.type==="function"&&e.function.strict===!0)??!1}function cs(r){for(let e of r??[]){if(e.type!=="function")throw new m(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new m(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var G=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},q,Gn,en,Wn,Hn,Qn,ps,Jn,ds=10,St=class extends Ce{constructor(){super(...arguments),q.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);let 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),(zn(e)||qn(e))&&e.content)this._emit("functionCallResult",e.content);else if(ke(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(ke(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new m("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),G(this,q,"m",Gn).call(this)}async finalMessage(){return await this.done(),G(this,q,"m",en).call(this)}async finalFunctionCall(){return await this.done(),G(this,q,"m",Wn).call(this)}async finalFunctionCallResult(){return await this.done(),G(this,q,"m",Hn).call(this)}async totalUsage(){return await this.done(),G(this,q,"m",Qn).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let t=G(this,q,"m",en).call(this);t&&this._emit("finalMessage",t);let n=G(this,q,"m",Gn).call(this);n&&this._emit("finalContent",n);let i=G(this,q,"m",Wn).call(this);i&&this._emit("finalFunctionCall",i);let s=G(this,q,"m",Hn).call(this);s!=null&&this._emit("finalFunctionCallResult",s),this._chatCompletions.some(o=>o.usage)&&this._emit("totalUsage",G(this,q,"m",Qn).call(this))}async _createChatCompletion(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),G(this,q,"m",ps).call(this,t);let s=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(kr(s,t))}async _runChatCompletion(e,t,n){for(let i of t.messages)this._addMessage(i,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){let i="function",{function_call:s="auto",stream:o,...a}=t,c=typeof s!="string"&&s?.name,{maxChatCompletions:d=ds}=n||{},_={};for(let f of t.functions)_[f.name||f.function.name]=f;let u=t.functions.map(f=>({name:f.name||f.function.name,parameters:f.parameters,description:f.description}));for(let f of t.messages)this._addMessage(f,!1);for(let f=0;f<d;++f){let A=(await this._createChatCompletion(e,{...a,function_call:s,functions:u,messages:[...this.messages]},n)).choices[0]?.message;if(!A)throw new m("missing message in ChatCompletion response");if(!A.function_call)return;let{name:g,arguments:S}=A.function_call,R=_[g];if(R){if(c&&c!==g){let N=`Invalid function_call: ${JSON.stringify(g)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:i,name:g,content:N});continue}}else{let N=`Invalid function_call: ${JSON.stringify(g)}. Available options are: ${u.map(B=>JSON.stringify(B.name)).join(", ")}. Please try again`;this._addMessage({role:i,name:g,content:N});continue}let y;try{y=Bn(R)?await R.parse(S):S}catch(N){this._addMessage({role:i,name:g,content:N instanceof Error?N.message:String(N)});continue}let D=await R.function(y,this),k=G(this,q,"m",Jn).call(this,D);if(this._addMessage({role:i,name:g,content:k}),c)return}}async _runTools(e,t,n){let i="tool",{tool_choice:s="auto",stream:o,...a}=t,c=typeof s!="string"&&s?.function?.name,{maxChatCompletions:d=ds}=n||{},_=t.tools.map(p=>{if(Je(p)){if(!p.$callback)throw new m("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:p.$callback,name:p.function.name,description:p.function.description||"",parameters:p.function.parameters,parse:p.$parseRaw,strict:!0}}}return p}),u={};for(let p of _)p.type==="function"&&(u[p.function.name||p.function.function.name]=p.function);let f="tools"in t?_.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description,strict:p.function.strict}}:p):void 0;for(let p of t.messages)this._addMessage(p,!1);for(let p=0;p<d;++p){let g=(await this._createChatCompletion(e,{...a,tool_choice:s,tools:f,messages:[...this.messages]},n)).choices[0]?.message;if(!g)throw new m("missing message in ChatCompletion response");if(!g.tool_calls?.length)return;for(let S of g.tool_calls){if(S.type!=="function")continue;let R=S.id,{name:y,arguments:D}=S.function,k=u[y];if(k){if(c&&c!==y){let j=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:i,tool_call_id:R,content:j});continue}}else{let j=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(u).map(L=>JSON.stringify(L)).join(", ")}. Please try again`;this._addMessage({role:i,tool_call_id:R,content:j});continue}let N;try{N=Bn(k)?await k.parse(D):D}catch(j){let L=j instanceof Error?j.message:String(j);this._addMessage({role:i,tool_call_id:R,content:L});continue}let B=await k.function(N,this),z=G(this,q,"m",Jn).call(this,B);if(this._addMessage({role:i,tool_call_id:R,content:z}),c)return}}}};q=new WeakSet,Gn=function(){return G(this,q,"m",en).call(this).content??null},en=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(ke(t)){let{function_call:n,...i}=t,s={...i,content:t.content??null,refusal:t.refusal??null};return n&&(s.function_call=n),s}}throw new m("stream ended without producing a ChatCompletionMessage with role=assistant")},Wn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(ke(t)&&t?.function_call)return t.function_call;if(ke(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},Hn=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(zn(t)&&t.content!=null||qn(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>n.role==="assistant"&&n.tool_calls?.some(i=>i.type==="function"&&i.id===t.tool_call_id)))return t.content}},Qn=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{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},ps=function(e){if(e.n!=null&&e.n>1)throw new m("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Jn=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Sr=class r extends St{static runFunctions(e,t,n){let i=new r,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return i._run(()=>i._runFunctions(e,t,s)),i}static runTools(e,t,n){let i=new r,s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,s)),i}_addMessage(e,t=!0){super._addMessage(e,t),ke(e)&&e.content&&this._emit("content",e.content)}};var F={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},Yn=class extends Error{},Kn=class extends Error{};function du(r,e=F.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return pu(r.trim(),e)}var pu=(r,e)=>{let t=r.length,n=0,i=f=>{throw new Yn(`${f} at position ${n}`)},s=f=>{throw new Kn(`${f} at position ${n}`)},o=()=>(u(),n>=t&&i("Unexpected end of input"),r[n]==='"'?a():r[n]==="{"?c():r[n]==="["?d():r.substring(n,n+4)==="null"||F.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||F.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||F.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||F.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||F.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||F.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):_()),a=()=>{let f=n,p=!1;for(n++;n<t&&(r[n]!=='"'||p&&r[n-1]==="\\");)p=r[n]==="\\"?!p:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(f,++n-Number(p)))}catch(A){s(String(A))}else if(F.STR&e)try{return JSON.parse(r.substring(f,n-Number(p))+'"')}catch{return JSON.parse(r.substring(f,r.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},c=()=>{n++,u();let f={};try{for(;r[n]!=="}";){if(u(),n>=t&&F.OBJ&e)return f;let p=a();u(),n++;try{let A=o();Object.defineProperty(f,p,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(F.OBJ&e)return f;throw A}u(),r[n]===","&&n++}}catch{if(F.OBJ&e)return f;i("Expected '}' at end of object")}return n++,f},d=()=>{n++;let f=[];try{for(;r[n]!=="]";)f.push(o()),u(),r[n]===","&&n++}catch{if(F.ARR&e)return f;i("Expected ']' at end of array")}return n++,f},_=()=>{if(n===0){r==="-"&&F.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(r)}catch(p){if(F.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}s(String(p))}}let f=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(F.NUM&e)&&i("Unterminated number literal");try{return JSON.parse(r.substring(f,n))}catch{r.substring(f,n)==="-"&&F.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(r.substring(f,r.lastIndexOf("e")))}catch(A){s(String(A))}}},u=()=>{for(;n<t&&`
|
|
67
|
+
\r `.includes(r[n]);)n++};return o()},Xn=r=>du(r,F.ALL^F.NUM);var Pt=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},v=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},T,ye,Et,Se,Zn,tn,ei,ti,ri,rn,ni,fs,Rt=class r extends St{constructor(e){super(),T.add(this),ye.set(this,void 0),Et.set(this,void 0),Se.set(this,void 0),Pt(this,ye,e,"f"),Pt(this,Et,[],"f")}get currentChatCompletionSnapshot(){return v(this,Se,"f")}static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){let i=new r(t);return i._run(()=>i._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion;let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),v(this,T,"m",Zn).call(this);let s=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let o of s)v(this,T,"m",ei).call(this,o);if(s.controller.signal?.aborted)throw new E;return this._addChatCompletion(v(this,T,"m",rn).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),v(this,T,"m",Zn).call(this),this._connected();let i=re.fromReadableStream(e,this.controller),s;for await(let o of i)s&&s!==o.id&&this._addChatCompletion(v(this,T,"m",rn).call(this)),v(this,T,"m",ei).call(this,o),s=o.id;if(i.controller.signal?.aborted)throw new E;return this._addChatCompletion(v(this,T,"m",rn).call(this))}[(ye=new WeakMap,Et=new WeakMap,Se=new WeakMap,T=new WeakSet,Zn=function(){this.ended||Pt(this,Se,void 0,"f")},tn=function(t){let n=v(this,Et,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},v(this,Et,"f")[t.index]=n,n)},ei=function(t){if(this.ended)return;let n=v(this,T,"m",fs).call(this,t);this._emit("chunk",t,n);for(let i of t.choices){let s=n.choices[i.index];i.delta.content!=null&&s.message?.role==="assistant"&&s.message?.content&&(this._emit("content",i.delta.content,s.message.content),this._emit("content.delta",{delta:i.delta.content,snapshot:s.message.content,parsed:s.message.parsed})),i.delta.refusal!=null&&s.message?.role==="assistant"&&s.message?.refusal&&this._emit("refusal.delta",{delta:i.delta.refusal,snapshot:s.message.refusal}),i.logprobs?.content!=null&&s.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:i.logprobs?.content,snapshot:s.logprobs?.content??[]}),i.logprobs?.refusal!=null&&s.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:i.logprobs?.refusal,snapshot:s.logprobs?.refusal??[]});let o=v(this,T,"m",tn).call(this,s);s.finish_reason&&(v(this,T,"m",ri).call(this,s),o.current_tool_call_index!=null&&v(this,T,"m",ti).call(this,s,o.current_tool_call_index));for(let a of i.delta.tool_calls??[])o.current_tool_call_index!==a.index&&(v(this,T,"m",ri).call(this,s),o.current_tool_call_index!=null&&v(this,T,"m",ti).call(this,s,o.current_tool_call_index)),o.current_tool_call_index=a.index;for(let a of i.delta.tool_calls??[]){let c=s.message.tool_calls?.[a.index];c?.type&&(c?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:c.function?.name,index:a.index,arguments:c.function.arguments,parsed_arguments:c.function.parsed_arguments,arguments_delta:a.function?.arguments??""}):(c?.type,void 0))}}},ti=function(t,n){if(v(this,T,"m",tn).call(this,t).done_tool_calls.has(n))return;let s=t.message.tool_calls?.[n];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){let o=v(this,ye,"f")?.tools?.find(a=>a.type==="function"&&a.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:n,arguments:s.function.arguments,parsed_arguments:Je(o)?o.$parseRaw(s.function.arguments):o?.function.strict?JSON.parse(s.function.arguments):null})}else s.type},ri=function(t){let n=v(this,T,"m",tn).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;let i=v(this,T,"m",ni).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},rn=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=v(this,Se,"f");if(!t)throw new m("request ended without sending any chunks");return Pt(this,Se,void 0,"f"),Pt(this,Et,[],"f"),fu(t,v(this,ye,"f"))},ni=function(){let t=v(this,ye,"f")?.response_format;return Cr(t)?t:null},fs=function(t){var n,i,s,o;let a=v(this,Se,"f"),{choices:c,...d}=t;a?Object.assign(a,d):a=Pt(this,Se,{...d,choices:[]},"f");for(let{delta:_,finish_reason:u,index:f,logprobs:p=null,...A}of t.choices){let g=a.choices[f];if(g||(g=a.choices[f]={finish_reason:u,index:f,message:{},logprobs:p,...A}),p)if(!g.logprobs)g.logprobs=Object.assign({},p);else{let{content:B,refusal:z,...j}=p;Object.assign(g.logprobs,j),B&&((n=g.logprobs).content??(n.content=[]),g.logprobs.content.push(...B)),z&&((i=g.logprobs).refusal??(i.refusal=[]),g.logprobs.refusal.push(...z))}if(u&&(g.finish_reason=u,v(this,ye,"f")&&Vn(v(this,ye,"f")))){if(u==="length")throw new bt;if(u==="content_filter")throw new wt}if(Object.assign(g,A),!_)continue;let{content:S,refusal:R,function_call:y,role:D,tool_calls:k,...N}=_;if(Object.assign(g.message,N),R&&(g.message.refusal=(g.message.refusal||"")+R),D&&(g.message.role=D),y&&(g.message.function_call?(y.name&&(g.message.function_call.name=y.name),y.arguments&&((s=g.message.function_call).arguments??(s.arguments=""),g.message.function_call.arguments+=y.arguments)):g.message.function_call=y),S&&(g.message.content=(g.message.content||"")+S,!g.message.refusal&&v(this,T,"m",ni).call(this)&&(g.message.parsed=Xn(g.message.content))),k){g.message.tool_calls||(g.message.tool_calls=[]);for(let{index:B,id:z,type:j,function:L,...P}of k){let $=(o=g.message.tool_calls)[B]??(o[B]={});Object.assign($,P),z&&($.id=z),j&&($.type=j),L&&($.function??($.function={name:L.name??"",arguments:""})),L?.name&&($.function.name=L.name),L?.arguments&&($.function.arguments+=L.arguments,us(v(this,ye,"f"),$)&&($.function.parsed_arguments=Xn($.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("chunk",i=>{let s=t.shift();s?s.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let s of t)s.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let s of t)s.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,o)=>t.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new re(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function fu(r,e){let{id:t,choices:n,created:i,model:s,system_fingerprint:o,...a}=r,c={...a,id:t,choices:n.map(({message:d,finish_reason:_,index:u,logprobs:f,...p})=>{if(!_)throw new m(`missing finish_reason for choice ${u}`);let{content:A=null,function_call:g,tool_calls:S,...R}=d,y=d.role;if(!y)throw new m(`missing role for choice ${u}`);if(g){let{arguments:D,name:k}=g;if(D==null)throw new m(`missing function_call.arguments for choice ${u}`);if(!k)throw new m(`missing function_call.name for choice ${u}`);return{...p,message:{content:A,function_call:{arguments:D,name:k},role:y,refusal:d.refusal??null},finish_reason:_,index:u,logprobs:f}}return S?{...p,index:u,finish_reason:_,logprobs:f,message:{...R,role:y,content:A,refusal:d.refusal??null,tool_calls:S.map((D,k)=>{let{function:N,type:B,id:z,...j}=D,{arguments:L,name:P,...$}=N||{};if(z==null)throw new m(`missing choices[${u}].tool_calls[${k}].id
|
|
68
|
+
${nn(r)}`);if(B==null)throw new m(`missing choices[${u}].tool_calls[${k}].type
|
|
69
|
+
${nn(r)}`);if(P==null)throw new m(`missing choices[${u}].tool_calls[${k}].function.name
|
|
70
|
+
${nn(r)}`);if(L==null)throw new m(`missing choices[${u}].tool_calls[${k}].function.arguments
|
|
71
|
+
${nn(r)}`);return{...j,id:z,type:B,function:{...$,name:P,arguments:L}}})}}:{...p,message:{...R,content:A,role:y,refusal:d.refusal??null},finish_reason:_,index:u,logprobs:f}}),created:i,model:s,object:"chat.completion",...o?{system_fingerprint:o}:{}};return ls(c,e)}function nn(r){return JSON.stringify(r)}var Pr=class r extends Rt{static fromReadableStream(e){let t=new r(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){let i=new r(null),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return i._run(()=>i._runFunctions(e,t,s)),i}static runTools(e,t,n){let i=new r(t),s={...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,t,s)),i}};var Er=class extends l{parse(e,t){return cs(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(n=>kr(n,e))}runFunctions(e,t){return e.stream?Pr.runFunctions(this._client,e,t):Sr.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?Pr.runTools(this._client,e,t):Sr.runTools(this._client,e,t)}stream(e,t){return Rt.createChatCompletion(this._client,e,t)}};var $t=class extends l{constructor(){super(...arguments),this.completions=new Er(this._client)}};(function(r){r.Completions=Er})($t||($t={}));var Mt=class extends l{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}};var Ot=class extends l{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}};var Pe=class extends l{constructor(){super(...arguments),this.sessions=new Mt(this._client),this.transcriptionSessions=new Ot(this._client)}};Pe.Sessions=Mt;Pe.TranscriptionSessions=Ot;var Ye=class extends l{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,i){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...i,headers:{"OpenAI-Beta":"assistants=v2",...i?.headers}})}list(e,t={},n){return w(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Tt,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}},Tt=class extends x{};Ye.MessagesPage=Tt;var Ke=class extends l{retrieve(e,t,n,i={},s){return w(i)?this.retrieve(e,t,n,{},i):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:i,...s,headers:{"OpenAI-Beta":"assistants=v2",...s?.headers}})}list(e,t,n={},i){return w(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Nt,{query:n,...i,headers:{"OpenAI-Beta":"assistants=v2",...i?.headers}})}},Nt=class extends x{};Ke.RunStepsPage=Nt;var be=class extends l{constructor(){super(...arguments),this.steps=new Ke(this._client)}create(e,t,n){let{include:i,...s}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:i},body:s,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,i){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...i,headers:{"OpenAI-Beta":"assistants=v2",...i?.headers}})}list(e,t={},n){return w(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,jt,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(e,i.id,n)}createAndStream(e,t,n){return oe.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let i={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(i["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){let{data:s,response:o}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...i}}).withResponse();switch(s.status){case"queued":case"in_progress":case"cancelling":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let d=parseInt(c);isNaN(d)||(a=d)}}await fe(a);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return s}}}stream(e,t,n){return oe.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,i){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...i,headers:{"OpenAI-Beta":"assistants=v2",...i?.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,i){let s=await this.submitToolOutputs(e,t,n,i);return await this.poll(e,s.id,i)}submitToolOutputsStream(e,t,n,i){return oe.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,i)}},jt=class extends x{};be.RunsPage=jt;be.Steps=Ke;be.RunStepsPage=Nt;var ae=class extends l{constructor(){super(...arguments),this.runs=new be(this._client),this.messages=new Ye(this._client)}create(e={},t){return w(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return oe.createThreadAssistantStream(e,this._client.beta.threads,t)}};ae.Runs=be;ae.RunsPage=jt;ae.Messages=Ye;ae.MessagesPage=Tt;var Z=class extends l{constructor(){super(...arguments),this.realtime=new Pe(this._client),this.chat=new $t(this._client),this.assistants=new Qe(this._client),this.threads=new ae(this._client)}};Z.Realtime=Pe;Z.Assistants=Qe;Z.AssistantsPage=kt;Z.Threads=ae;var Xe=class extends l{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}};var Lt=class extends l{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n?.headers},__binaryResponse:!0})}};var Ee=class extends l{constructor(){super(...arguments),this.content=new Lt(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,V({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return w(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Ft,{query:t,...n})}del(e,t,n){return this._client.delete(`/containers/${e}/files/${t}`,{...n,headers:{Accept:"*/*",...n?.headers}})}},Ft=class extends x{};Ee.FileListResponsesPage=Ft;Ee.Content=Lt;var le=class extends l{constructor(){super(...arguments),this.files=new Ee(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return w(e)?this.list({},e):this._client.getAPIList("/containers",Ze,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}},Ze=class extends x{};le.ContainerListResponsesPage=Ze;le.Files=Ee;le.FileListResponsesPage=Ft;var et=class extends l{create(e,t){let n=!!e.encoding_format,i=n?e.encoding_format:"base64";n&&pe("Request","User defined encoding_format:",e.encoding_format);let s=this._client.post("/embeddings",{body:{...e,encoding_format:i},...t});return n?s:(pe("response","Decoding base64 embeddings to float32 array"),s._thenUnwrap(o=>(o&&o.data&&o.data.forEach(a=>{let c=a.embedding;a.embedding=Zi(c)}),o)))}};var tt=class extends l{retrieve(e,t,n,i){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,i)}list(e,t,n={},i){return w(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Dt,{query:n,...i})}},Dt=class extends x{};tt.OutputItemListResponsesPage=Dt;var we=class extends l{constructor(){super(...arguments),this.outputItems=new tt(this._client)}create(e,t,n){return this._client.post(`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){return this._client.get(`/evals/${e}/runs/${t}`,n)}list(e,t={},n){return w(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Ut,{query:t,...n})}del(e,t,n){return this._client.delete(`/evals/${e}/runs/${t}`,n)}cancel(e,t,n){return this._client.post(`/evals/${e}/runs/${t}`,n)}},Ut=class extends x{};we.RunListResponsesPage=Ut;we.OutputItems=tt;we.OutputItemListResponsesPage=Dt;var ue=class extends l{constructor(){super(...arguments),this.runs=new we(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,n){return this._client.post(`/evals/${e}`,{body:t,...n})}list(e={},t){return w(e)?this.list({},e):this._client.getAPIList("/evals",rt,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}},rt=class extends x{};ue.EvalListResponsesPage=rt;ue.Runs=we;ue.RunListResponsesPage=Ut;var Re=class extends l{create(e,t){return this._client.post("/files",V({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return w(e)?this.list({},e):this._client.getAPIList("/files",nt,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t?.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=30*60*1e3}={}){let i=new Set(["processed","error","deleted"]),s=Date.now(),o=await this.retrieve(e);for(;!o.status||!i.has(o.status);)if(await fe(t),o=await this.retrieve(e),Date.now()-s>n)throw new xe({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return o}},nt=class extends x{};Re.FileObjectsPage=nt;var Bt=class extends l{};var zt=class extends l{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})}};var it=class extends l{constructor(){super(...arguments),this.graders=new zt(this._client)}};it.Graders=zt;var st=class extends l{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,qt,{body:t,method:"post",...n})}retrieve(e,t={},n){return w(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}del(e,t,n){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,n)}},qt=class extends ne{};st.PermissionCreateResponsesPage=qt;var $e=class extends l{constructor(){super(...arguments),this.permissions=new st(this._client)}};$e.Permissions=st;$e.PermissionCreateResponsesPage=qt;var ot=class extends l{list(e,t={},n){return w(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Vt,{query:t,...n})}},Vt=class extends x{};ot.FineTuningJobCheckpointsPage=Vt;var ce=class extends l{constructor(){super(...arguments),this.checkpoints=new ot(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 w(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Gt,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return w(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Wt,{query:t,...n})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}},Gt=class extends x{},Wt=class extends x{};ce.FineTuningJobsPage=Gt;ce.FineTuningJobEventsPage=Wt;ce.Checkpoints=ot;ce.FineTuningJobCheckpointsPage=Vt;var J=class extends l{constructor(){super(...arguments),this.methods=new Bt(this._client),this.jobs=new ce(this._client),this.checkpoints=new $e(this._client),this.alpha=new it(this._client)}};J.Methods=Bt;J.Jobs=ce;J.FineTuningJobsPage=Gt;J.FineTuningJobEventsPage=Wt;J.Checkpoints=$e;J.Alpha=it;var Ht=class extends l{};var Me=class extends l{constructor(){super(...arguments),this.graderModels=new Ht(this._client)}};Me.GraderModels=Ht;var at=class extends l{createVariation(e,t){return this._client.post("/images/variations",V({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",V({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}};var Oe=class extends l{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",lt,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}},lt=class extends ne{};Oe.ModelsPage=lt;var ut=class extends l{create(e,t){return this._client.post("/moderations",{body:e,...t})}};function ms(r,e){return!e||!ju(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:ii(r,e)}function ii(r,e){let t=r.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:Du(e,i)};if(i.type==="message"){let s=i.content.map(o=>o.type==="output_text"?{...o,parsed:Nu(e,o.text)}:o);return{...i,content:s}}return i}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||si(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let i of n.output)if(i.type==="message"){for(let s of i.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),n}function Nu(r,e){return r.text?.format?.type!=="json_schema"?null:"$parseRaw"in r.text?.format?(r.text?.format).$parseRaw(e):JSON.parse(e)}function ju(r){return!!Cr(r.text?.format)}function Lu(r){return r?.$brand==="auto-parseable-tool"}function Fu(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function Du(r,e){let t=Fu(r.tools??[],e.name);return{...e,...e,parsed_arguments:Lu(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function si(r){let e=[];for(let t of r.output)if(t.type==="message")for(let n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}var Qt=class extends l{list(e,t={},n){return w(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,sn,{query:t,...n})}};var Jt=function(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t},Te=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Yt,on,Ne,an,hs,gs,ys,bs,ln=class r extends Ce{constructor(e){super(),Yt.add(this),on.set(this,void 0),Ne.set(this,void 0),an.set(this,void 0),Jt(this,on,e,"f")}static createResponse(e,t,n){let i=new r(t);return i._run(()=>i._createOrRetrieveResponse(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,t,n){let i=n?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),Te(this,Yt,"m",hs).call(this);let s,o=null;"response_id"in t?(s=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),o=t.starting_after??null):s=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let a of s)Te(this,Yt,"m",gs).call(this,a,o);if(s.controller.signal?.aborted)throw new E;return Te(this,Yt,"m",ys).call(this)}[(on=new WeakMap,Ne=new WeakMap,an=new WeakMap,Yt=new WeakSet,hs=function(){this.ended||Jt(this,Ne,void 0,"f")},gs=function(t,n){if(this.ended)return;let i=(o,a)=>{(n==null||a.sequence_number>n)&&this._emit(o,a)},s=Te(this,Yt,"m",bs).call(this,t);switch(i("event",t),t.type){case"response.output_text.delta":{let o=s.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);if(o.type==="message"){let a=o.content[t.content_index];if(!a)throw new m(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new m(`expected content to be 'output_text', got ${a.type}`);i("response.output_text.delta",{...t,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let o=s.output[t.output_index];if(!o)throw new m(`missing output at index ${t.output_index}`);o.type==="function_call"&&i("response.function_call_arguments.delta",{...t,snapshot:o.arguments});break}default:i(t.type,t);break}},ys=function(){if(this.ended)throw new m("stream has ended, this shouldn't happen");let t=Te(this,Ne,"f");if(!t)throw new m("request ended without sending any events");Jt(this,Ne,void 0,"f");let n=Bu(t,Te(this,on,"f"));return Jt(this,an,n,"f"),n},bs=function(t){let n=Te(this,Ne,"f");if(!n){if(t.type!=="response.created")throw new m(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=Jt(this,Ne,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{let i=n.output[t.output_index];if(!i)throw new m(`missing output at index ${t.output_index}`);i.type==="message"&&i.content.push(t.part);break}case"response.output_text.delta":{let i=n.output[t.output_index];if(!i)throw new m(`missing output at index ${t.output_index}`);if(i.type==="message"){let s=i.content[t.content_index];if(!s)throw new m(`missing content at index ${t.content_index}`);if(s.type!=="output_text")throw new m(`expected content to be 'output_text', got ${s.type}`);s.text+=t.delta}break}case"response.function_call_arguments.delta":{let i=n.output[t.output_index];if(!i)throw new m(`missing output at index ${t.output_index}`);i.type==="function_call"&&(i.arguments+=t.delta);break}case"response.completed":{Jt(this,Ne,t.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on("event",i=>{let s=t.shift();s?s.resolve(i):e.push(i)}),this.on("end",()=>{n=!0;for(let i of t)i.resolve(void 0);t.length=0}),this.on("abort",i=>{n=!0;for(let s of t)s.reject(i);t.length=0}),this.on("error",i=>{n=!0;for(let s of t)s.reject(i);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((s,o)=>t.push({resolve:s,reject:o})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=Te(this,an,"f");if(!e)throw new m("stream ended without producing a ChatCompletion");return e}};function Bu(r,e){return ms(r,e)}var je=class extends l{constructor(){super(...arguments),this.inputItems=new Qt(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&si(n),n))}retrieve(e,t={},n){return this._client.get(`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t?.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>ii(n,e))}stream(e,t){return ln.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t?.headers}})}},sn=class extends x{};je.InputItems=Qt;var Kt=class extends l{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,V({body:t,...n}))}};var Le=class extends l{constructor(){super(...arguments),this.parts=new Kt(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}};Le.Parts=Kt;var ws=async r=>{let e=await Promise.allSettled(r),t=e.filter(i=>i.status==="rejected");if(t.length){for(let i of t)console.error(i.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}let n=[];for(let i of e)i.status==="fulfilled"&&n.push(i.value);return n};var Fe=class extends l{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}update(e,t,n,i){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...i,headers:{"OpenAI-Beta":"assistants=v2",...i?.headers}})}list(e,t={},n){return w(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,De,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){let i=await this.create(e,t,n);return await this.poll(e,i.id,n)}async poll(e,t,n){let i={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(i["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){let s=await this.retrieve(e,t,{...n,headers:i}).withResponse(),o=s.data;switch(o.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=s.response.headers.get("openai-poll-after-ms");if(c){let d=parseInt(c);isNaN(d)||(a=d)}}await fe(a);break;case"failed":case"completed":return o}}}async upload(e,t,n){let i=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:i.id},n)}async uploadAndPoll(e,t,n){let i=await this.upload(e,t,n);return await this.poll(e,i.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Xt,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}},De=class extends x{},Xt=class extends ne{};Fe.VectorStoreFilesPage=De;Fe.FileContentResponsesPage=Xt;var Zt=class extends l{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}async createAndPoll(e,t,n){let i=await this.create(e,t);return await this.poll(e,i.id,n)}listFiles(e,t,n={},i){return w(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,De,{query:n,...i,headers:{"OpenAI-Beta":"assistants=v2",...i?.headers}})}async poll(e,t,n){let i={...n?.headers,"X-Stainless-Poll-Helper":"true"};for(n?.pollIntervalMs&&(i["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){let{data:s,response:o}=await this.retrieve(e,t,{...n,headers:i}).withResponse();switch(s.status){case"in_progress":let a=5e3;if(n?.pollIntervalMs)a=n.pollIntervalMs;else{let c=o.headers.get("openai-poll-after-ms");if(c){let d=parseInt(c);isNaN(d)||(a=d)}}await fe(a);break;case"failed":case"cancelled":case"completed":return s}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},i){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let s=i?.maxConcurrency??5,o=Math.min(s,t.length),a=this._client,c=t.values(),d=[...n];async function _(f){for(let p of f){let A=await a.files.create({file:p,purpose:"assistants"},i);d.push(A.id)}}let u=Array(o).fill(c).map(_);return await ws(u),await this.createAndPoll(e,{file_ids:d})}};var Y=class extends l{constructor(){super(...arguments),this.files=new Fe(this._client),this.fileBatches=new Zt(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}update(e,t,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}list(e={},t){return w(e)?this.list({},e):this._client.getAPIList("/vector_stores",ct,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t?.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,dt,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n?.headers}})}},ct=class extends x{},dt=class extends ne{};Y.VectorStoresPage=ct;Y.VectorStoreSearchResponsesPage=dt;Y.Files=Fe;Y.VectorStoreFilesPage=De;Y.FileContentResponsesPage=Xt;Y.FileBatches=Zt;var _s,b=class extends qr{constructor({baseURL:e=gr("OPENAI_BASE_URL"),apiKey:t=gr("OPENAI_API_KEY"),organization:n=gr("OPENAI_ORG_ID")??null,project:i=gr("OPENAI_PROJECT_ID")??null,...s}={}){if(t===void 0)throw new m("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let o={apiKey:t,organization:n,project:i,...s,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Xi())throw new m(`It looks like you're running in a browser-like environment.
|
|
11
72
|
|
|
12
73
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
13
74
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -16,5 +77,26 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
16
77
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
17
78
|
|
|
18
79
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
19
|
-
`);super({baseURL:
|
|
80
|
+
`);super({baseURL:o.baseURL,timeout:o.timeout??6e5,httpAgent:o.httpAgent,maxRetries:o.maxRetries,fetch:o.fetch}),this.completions=new Xe(this),this.chat=new he(this),this.embeddings=new et(this),this.files=new Re(this),this.images=new at(this),this.audio=new ie(this),this.moderations=new ut(this),this.models=new Oe(this),this.fineTuning=new J(this),this.graders=new Me(this),this.vectorStores=new Y(this),this.beta=new Z(this),this.batches=new Ie(this),this.uploads=new Le(this),this.responses=new je(this),this.evals=new ue(this),this.containers=new le(this),this._options=o,this.apiKey=t,this.organization=n,this.project=i}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 An(e,{arrayFormat:"brackets"})}};_s=b;b.OpenAI=_s;b.DEFAULT_TIMEOUT=6e5;b.OpenAIError=m;b.APIError=O;b.APIConnectionError=_e;b.APIConnectionTimeoutError=xe;b.APIUserAbortError=E;b.NotFoundError=ur;b.ConflictError=cr;b.RateLimitError=pr;b.BadRequestError=or;b.AuthenticationError=ar;b.InternalServerError=fr;b.PermissionDeniedError=lr;b.UnprocessableEntityError=dr;b.toFile=Nn;b.fileFromPath=jr;b.Completions=Xe;b.Chat=he;b.ChatCompletionsPage=ve;b.Embeddings=et;b.Files=Re;b.FileObjectsPage=nt;b.Images=at;b.Audio=ie;b.Moderations=ut;b.Models=Oe;b.ModelsPage=lt;b.FineTuning=J;b.Graders=Me;b.VectorStores=Y;b.VectorStoresPage=ct;b.VectorStoreSearchResponsesPage=dt;b.Beta=Z;b.Batches=Ie;b.BatchesPage=Ge;b.Uploads=Le;b.Responses=je;b.Evals=ue;b.EvalListResponsesPage=rt;b.Containers=le;b.ContainerListResponsesPage=Ze;var xs=b;var Wu={model:"gpt-4o-mini",max_tokens:8192,temperature:.1,stream:!0},As={headers:{}};async function Hu(r,e,t,n){let i={};e.model&&(i.model=e.model),e.maxTokens&&(i.max_tokens=e.maxTokens),e.temperature&&(i.temperature=e.temperature);let s=await r.chat.completions.create({...Wu,...i,messages:[{role:"user",content:t}]},{signal:n,...As,headers:{...As.headers??{},...e.headers}});async function*o(){try{for await(let a of s)a.choices&&a.choices[0]?.delta?.content&&(yield a.choices[0].delta.content)}catch(a){throw console.error("Stream error:",a),a}}return o()}var vs=Hu;function Is(r){return()=>{let e=null,n=Ei({"ly.img.improve":!0,"ly.img.fix":!0,"ly.img.shorter":!0,"ly.img.longer":!0,"ly.img.changeTone":!0,"ly.img.translate":!0,"ly.img.changeTextTo":!0},r.supportedQuickActions),i={kind:"text",id:"openai",name:"OpenAI",initialize:async()=>{e=new xs({dangerouslyAllowBrowser:!0,baseURL:r.proxyUrl,apiKey:"dummy-key"})},input:{quickActions:{supported:n}},output:{middleware:r.middlewares,generate:async(s,{engine:o,abortSignal:a})=>{if(e==null)throw new Error("OpenAI SDK is not initialized");if(s.blockId!=null&&o.block.getType(s.blockId)!=="//ly.img.ubq/text")throw new Error("If a block is provided to this generation, it must be a text block");r.debug&&console.log("Sending prompt to OpenAI:",JSON.stringify(s.prompt,void 0,2));let c=await vs(e,{proxyUrl:r.proxyUrl,headers:r.headers,model:r.model??"gpt-4o-mini"},s.prompt,a);async function*d(){let _="";for await(let u of c){if(a?.aborted)break;_+=u,yield{kind:"text",text:_}}return{kind:"text",text:_}}return d()}}};return Promise.resolve(i)}}var Qu={OpenAIProvider:Is},hh=Qu;export{hh as default};
|
|
81
|
+
/*! Bundled license information:
|
|
82
|
+
|
|
83
|
+
@imgly/plugin-ai-generation-web/dist/index.mjs:
|
|
84
|
+
(*! Bundled license information:
|
|
85
|
+
|
|
86
|
+
@imgly/plugin-utils/dist/index.mjs:
|
|
87
|
+
(*! Bundled license information:
|
|
88
|
+
|
|
89
|
+
lodash-es/lodash.js:
|
|
90
|
+
(**
|
|
91
|
+
* @license
|
|
92
|
+
* Lodash (Custom Build) <https://lodash.com/>
|
|
93
|
+
* Build: `lodash modularize exports="es" -o ./`
|
|
94
|
+
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
|
|
95
|
+
* Released under MIT license <https://lodash.com/license>
|
|
96
|
+
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
|
|
97
|
+
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
|
98
|
+
*)
|
|
99
|
+
*)
|
|
100
|
+
*)
|
|
101
|
+
*/
|
|
20
102
|
//# sourceMappingURL=index.mjs.map
|