@imgly/plugin-ai-text-generation-web 0.1.9 → 0.2.0
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 +34 -0
- package/README.md +207 -28
- package/dist/anthropic/AnthropicProvider.d.ts +7 -3
- package/dist/anthropic/index.mjs +10 -197
- package/dist/anthropic/index.mjs.map +4 -4
- package/dist/anthropic/sendPrompt.d.ts +1 -1
- package/dist/constants.d.ts +5 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.mjs +196 -7
- package/dist/index.mjs.map +4 -4
- package/dist/open-ai/OpenAIProvider.d.ts +21 -0
- package/dist/open-ai/index.d.ts +5 -0
- package/dist/open-ai/index.mjs +20 -0
- package/dist/open-ai/index.mjs.map +7 -0
- package/dist/open-ai/sendPrompt.d.ts +15 -0
- package/dist/plugin.d.ts +4 -3
- package/dist/quickActions/ChangeTextTo.d.ts +29 -0
- package/dist/quickActions/ChangeTone.d.ts +29 -0
- package/dist/quickActions/Fix.d.ts +28 -0
- package/dist/quickActions/Improve.d.ts +28 -0
- package/dist/quickActions/Longer.d.ts +28 -0
- package/dist/quickActions/Shorter.d.ts +28 -0
- package/dist/quickActions/Translate.d.ts +29 -0
- package/dist/quickActions/types.d.ts +6 -0
- package/dist/types.d.ts +50 -10
- package/package.json +8 -3
- /package/dist/{anthropic/prompts → prompts}/changeTextTo.d.ts +0 -0
- /package/dist/{anthropic/prompts → prompts}/changeTone.d.ts +0 -0
- /package/dist/{anthropic/prompts → prompts}/fix.d.ts +0 -0
- /package/dist/{anthropic/prompts → prompts}/generateTextForSpeech.d.ts +0 -0
- /package/dist/{anthropic/prompts → prompts}/improve.d.ts +0 -0
- /package/dist/{anthropic/prompts → prompts}/longer.d.ts +0 -0
- /package/dist/{anthropic/prompts → prompts}/shorter.d.ts +0 -0
- /package/dist/{anthropic/prompts → prompts}/translate.d.ts +0 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import CreativeEditorSDK from '@cesdk/cesdk-js';
|
|
2
|
+
import { type CommonProviderConfiguration } from '@imgly/plugin-ai-generation-web';
|
|
3
|
+
import { TextProvider } from '../types';
|
|
4
|
+
type OpenAIInput = {
|
|
5
|
+
prompt: string;
|
|
6
|
+
temperature?: number;
|
|
7
|
+
maxTokens?: number;
|
|
8
|
+
blockId?: number;
|
|
9
|
+
initialText?: string;
|
|
10
|
+
};
|
|
11
|
+
type OpenAIOutput = {
|
|
12
|
+
kind: 'text';
|
|
13
|
+
text: string;
|
|
14
|
+
};
|
|
15
|
+
export interface OpenAIProviderConfig extends CommonProviderConfiguration<OpenAIInput, OpenAIOutput> {
|
|
16
|
+
model?: string;
|
|
17
|
+
}
|
|
18
|
+
export declare function OpenAIProvider(config: OpenAIProviderConfig): (context: {
|
|
19
|
+
cesdk: CreativeEditorSDK;
|
|
20
|
+
}) => Promise<TextProvider<OpenAIInput>>;
|
|
21
|
+
export {};
|
|
@@ -0,0 +1,20 @@
|
|
|
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
|
+
`):[]}};J=new WeakMap;Ue.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,"\r"]);Ue.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Hn(s,e){for(let n=e??0;n<s.length;n++){if(s[n]===10)return{preceding:n,index:n+1,carriage:!1};if(s[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Ws(s){for(let r=0;r<s.length-1;r++){if(s[r]===10&&s[r+1]===10||s[r]===13&&s[r+1]===13)return r+2;if(s[r]===13&&s[r+1]===10&&r+3<s.length&&s[r+2]===13&&s[r+3]===10)return r+4}return-1}function rs(s){if(s[Symbol.asyncIterator])return s;let e=s.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 te=class s{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let r=!1;async function*n(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(let i of Jn(e,t))if(!o){if(i.data.startsWith("[DONE]")){o=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let a;try{a=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(a&&a.error)throw new $(void 0,a.error,void 0,ns(e.headers));yield a}else{let a;try{a=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(i.event=="error")throw new $(void 0,a.error,a.message,void 0);yield{event:i.event,data:a}}}o=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{o||t.abort()}}return new s(n,t)}static fromReadableStream(e,t){let r=!1;async function*n(){let i=new Ue,a=rs(e);for await(let c of a)for(let f of i.decode(c))yield f;for(let c of i.flush())yield c}async function*o(){if(r)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let i=!1;try{for await(let a of n())i||a&&(yield JSON.parse(a));i=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{i||t.abort()}}return new s(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=o=>({next:()=>{if(o.length===0){let i=r.next();e.push(i),t.push(i)}return o.shift()}});return[new s(()=>n(e),this.controller),new s(()=>n(t),this.controller)]}toReadableStream(){let e=this,t,r=new TextEncoder;return new Qr({async start(){t=e[Symbol.asyncIterator]()},async pull(n){try{let{value:o,done:i}=await t.next();if(i)return n.close();let a=r.encode(JSON.stringify(o)+`
|
|
4
|
+
`);n.enqueue(a)}catch(o){n.error(o)}},async cancel(){await t.return?.()}})}};async function*Jn(s,e){if(!s.body)throw e.abort(),new h("Attempted to iterate over a response with no body");let t=new ss,r=new Ue,n=rs(s.body);for await(let o of Vn(n))for(let i of r.decode(o)){let a=t.decode(i);a&&(yield a)}for(let o of r.flush()){let i=t.decode(o);i&&(yield i)}}async function*Vn(s){let e=new Uint8Array;for await(let t of s){if(t==null)continue;let r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t,n=new Uint8Array(e.length+r.length);n.set(e),n.set(r,e.length),e=n;let o;for(;(o=Ws(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var ss=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 o={event:this.event,data:this.data.join(`
|
|
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
|
+
\r `.includes(s[r]);)r++};return i()},Is=s=>bo(s,B.ALL^B.NUM);var yt=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},P=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)},F,me,bt,Re,Rs,Br,Cs,Ss,Es,Lr,Os,wn,xt=class s extends wt{constructor(e){super(),F.add(this),me.set(this,void 0),bt.set(this,void 0),Re.set(this,void 0),yt(this,me,e,"f"),yt(this,bt,[],"f")}get currentChatCompletionSnapshot(){return P(this,Re,"f")}static fromReadableStream(e){let t=new s(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){let n=new s(t);return n._run(()=>n._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),n}async _createChatCompletion(e,t,r){super._createChatCompletion;let n=r?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),P(this,F,"m",Rs).call(this);let o=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(let i of o)P(this,F,"m",Cs).call(this,i);if(o.controller.signal?.aborted)throw new E;return this._addChatCompletion(P(this,F,"m",Lr).call(this))}async _fromReadableStream(e,t){let r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),P(this,F,"m",Rs).call(this),this._connected();let n=te.fromReadableStream(e,this.controller),o;for await(let i of n)o&&o!==i.id&&this._addChatCompletion(P(this,F,"m",Lr).call(this)),P(this,F,"m",Cs).call(this,i),o=i.id;if(n.controller.signal?.aborted)throw new E;return this._addChatCompletion(P(this,F,"m",Lr).call(this))}[(me=new WeakMap,bt=new WeakMap,Re=new WeakMap,F=new WeakSet,Rs=function(){this.ended||yt(this,Re,void 0,"f")},Br=function(t){let r=P(this,bt,"f")[t.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},P(this,bt,"f")[t.index]=r,r)},Cs=function(t){if(this.ended)return;let r=P(this,F,"m",wn).call(this,t);this._emit("chunk",t,r);for(let n of t.choices){let o=r.choices[n.index];n.delta.content!=null&&o.message?.role==="assistant"&&o.message?.content&&(this._emit("content",n.delta.content,o.message.content),this._emit("content.delta",{delta:n.delta.content,snapshot:o.message.content,parsed:o.message.parsed})),n.delta.refusal!=null&&o.message?.role==="assistant"&&o.message?.refusal&&this._emit("refusal.delta",{delta:n.delta.refusal,snapshot:o.message.refusal}),n.logprobs?.content!=null&&o.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:n.logprobs?.content,snapshot:o.logprobs?.content??[]}),n.logprobs?.refusal!=null&&o.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:n.logprobs?.refusal,snapshot:o.logprobs?.refusal??[]});let i=P(this,F,"m",Br).call(this,o);o.finish_reason&&(P(this,F,"m",Es).call(this,o),i.current_tool_call_index!=null&&P(this,F,"m",Ss).call(this,o,i.current_tool_call_index));for(let a of n.delta.tool_calls??[])i.current_tool_call_index!==a.index&&(P(this,F,"m",Es).call(this,o),i.current_tool_call_index!=null&&P(this,F,"m",Ss).call(this,o,i.current_tool_call_index)),i.current_tool_call_index=a.index;for(let a of n.delta.tool_calls??[]){let c=o.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))}}},Ss=function(t,r){if(P(this,F,"m",Br).call(this,t).done_tool_calls.has(r))return;let o=t.message.tool_calls?.[r];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let i=P(this,me,"f")?.tools?.find(a=>a.type==="function"&&a.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:r,arguments:o.function.arguments,parsed_arguments:Ve(i)?i.$parseRaw(o.function.arguments):i?.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Es=function(t){let r=P(this,F,"m",Br).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;let n=P(this,F,"m",Os).call(this);this._emit("content.done",{content:t.message.content,parsed:n?n.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Lr=function(){if(this.ended)throw new h("stream has ended, this shouldn't happen");let t=P(this,Re,"f");if(!t)throw new h("request ended without sending any chunks");return yt(this,Re,void 0,"f"),yt(this,bt,[],"f"),Ao(t,P(this,me,"f"))},Os=function(){let t=P(this,me,"f")?.response_format;return ur(t)?t:null},wn=function(t){var r,n,o,i;let a=P(this,Re,"f"),{choices:c,...f}=t;a?Object.assign(a,f):a=yt(this,Re,{...f,choices:[]},"f");for(let{delta:b,finish_reason:u,index:d,logprobs:p=null,...A}of t.choices){let g=a.choices[d];if(g||(g=a.choices[d]={finish_reason:u,index:d,message:{},logprobs:p,...A}),p)if(!g.logprobs)g.logprobs=Object.assign({},p);else{let{content:j,refusal:U,...M}=p;Object.assign(g.logprobs,M),j&&((r=g.logprobs).content??(r.content=[]),g.logprobs.content.push(...j)),U&&((n=g.logprobs).refusal??(n.refusal=[]),g.logprobs.refusal.push(...U))}if(u&&(g.finish_reason=u,P(this,me,"f")&&gs(P(this,me,"f")))){if(u==="length")throw new ct;if(u==="content_filter")throw new ut}if(Object.assign(g,A),!b)continue;let{content:C,refusal:O,function_call:_,role:L,tool_calls:R,...k}=b;if(Object.assign(g.message,k),O&&(g.message.refusal=(g.message.refusal||"")+O),L&&(g.message.role=L),_&&(g.message.function_call?(_.name&&(g.message.function_call.name=_.name),_.arguments&&((o=g.message.function_call).arguments??(o.arguments=""),g.message.function_call.arguments+=_.arguments)):g.message.function_call=_),C&&(g.message.content=(g.message.content||"")+C,!g.message.refusal&&P(this,F,"m",Os).call(this)&&(g.message.parsed=Is(g.message.content))),R){g.message.tool_calls||(g.message.tool_calls=[]);for(let{index:j,id:U,type:M,function:N,...S}of R){let v=(i=g.message.tool_calls)[j]??(i[j]={});Object.assign(v,S),U&&(v.id=U),M&&(v.type=M),N&&(v.function??(v.function={name:N.name??"",arguments:""})),N?.name&&(v.function.name=N.name),N?.arguments&&(v.function.arguments+=N.arguments,hn(P(this,me,"f"),v)&&(v.function.parsed_arguments=Is(v.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],r=!1;return this.on("chunk",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})}}toReadableStream(){return new te(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Ao(s,e){let{id:t,choices:r,created:n,model:o,system_fingerprint:i,...a}=s,c={...a,id:t,choices:r.map(({message:f,finish_reason:b,index:u,logprobs:d,...p})=>{if(!b)throw new h(`missing finish_reason for choice ${u}`);let{content:A=null,function_call:g,tool_calls:C,...O}=f,_=f.role;if(!_)throw new h(`missing role for choice ${u}`);if(g){let{arguments:L,name:R}=g;if(L==null)throw new h(`missing function_call.arguments for choice ${u}`);if(!R)throw new h(`missing function_call.name for choice ${u}`);return{...p,message:{content:A,function_call:{arguments:L,name:R},role:_,refusal:f.refusal??null},finish_reason:b,index:u,logprobs:d}}return C?{...p,index:u,finish_reason:b,logprobs:d,message:{...O,role:_,content:A,refusal:f.refusal??null,tool_calls:C.map((L,R)=>{let{function:k,type:j,id:U,...M}=L,{arguments:N,name:S,...v}=k||{};if(U==null)throw new h(`missing choices[${u}].tool_calls[${R}].id
|
|
7
|
+
${Dr(s)}`);if(j==null)throw new h(`missing choices[${u}].tool_calls[${R}].type
|
|
8
|
+
${Dr(s)}`);if(S==null)throw new h(`missing choices[${u}].tool_calls[${R}].function.name
|
|
9
|
+
${Dr(s)}`);if(N==null)throw new h(`missing choices[${u}].tool_calls[${R}].function.arguments
|
|
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.
|
|
11
|
+
|
|
12
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
13
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
14
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
15
|
+
|
|
16
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
17
|
+
|
|
18
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
19
|
+
`);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new Ke(this),this.chat=new de(this),this.embeddings=new Qe(this),this.files=new Ee(this),this.images=new nt(this),this.audio=new se(this),this.moderations=new it(this),this.models=new Te(this),this.fineTuning=new G(this),this.graders=new ve(this),this.vectorStores=new K(this),this.beta=new Y(this),this.batches=new Ae(this),this.uploads=new Me(this),this.responses=new ke(this),this.evals=new le(this),this.containers=new ae(this),this._options=i,this.apiKey=t,this.organization=r,this.project=n}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Gr(e,{arrayFormat:"brackets"})}};Rn=w;w.OpenAI=Rn;w.DEFAULT_TIMEOUT=6e5;w.OpenAIError=h;w.APIError=$;w.APIConnectionError=we;w.APIConnectionTimeoutError=ye;w.APIUserAbortError=E;w.NotFoundError=Gt;w.ConflictError=Kt;w.RateLimitError=Qt;w.BadRequestError=Jt;w.AuthenticationError=Vt;w.InternalServerError=Yt;w.PermissionDeniedError=Xt;w.UnprocessableEntityError=zt;w.toFile=as;w.fileFromPath=wr;w.Completions=Ke;w.Chat=de;w.ChatCompletionsPage=xe;w.Embeddings=Qe;w.Files=Ee;w.FileObjectsPage=et;w.Images=nt;w.Audio=se;w.Moderations=it;w.Models=Te;w.ModelsPage=ot;w.FineTuning=G;w.Graders=ve;w.VectorStores=K;w.VectorStoresPage=at;w.VectorStoreSearchResponsesPage=lt;w.Beta=Y;w.Batches=Ae;w.BatchesPage=qe;w.Uploads=Me;w.Responses=ke;w.Evals=le;w.EvalListResponsesPage=Ze;w.Containers=ae;w.ContainerListResponsesPage=ze;var Cn=w;var ti={model:"gpt-4o-mini",max_tokens:8192,temperature:.1,stream:!0},Sn={headers:{}};async function ri(s,e,t,r){let n={};e.model&&(n.model=e.model),e.maxTokens&&(n.max_tokens=e.maxTokens),e.temperature&&(n.temperature=e.temperature);let o=await s.chat.completions.create({...ti,...n,messages:[{role:"user",content:t}]},{signal:r,...Sn,headers:{...Sn.headers??{},...e.headers}});async function*i(){try{for await(let a of o)a.choices&&a.choices[0]?.delta?.content&&(yield a.choices[0].delta.content)}catch(a){throw console.error("Stream error:",a),a}}return i()}var En=ri;function On(s){return()=>{let e=null,t={kind:"text",id:"openai",name:"OpenAI",initialize:async()=>{e=new Cn({dangerouslyAllowBrowser:!0,baseURL:s.proxyUrl,apiKey:"dummy-key"})},input:{quickActions:{supported:{"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}}},output:{middleware:s.middlewares,generate:async(r,{engine:n,abortSignal:o})=>{if(e==null)throw new Error("OpenAI SDK is not initialized");if(r.blockId!=null&&n.block.getType(r.blockId)!=="//ly.img.ubq/text")throw new Error("If a block is provided to this generation, it must be a text block");s.debug&&console.log("Sending prompt to OpenAI:",JSON.stringify(r.prompt,void 0,2));let i=await En(e,{proxyUrl:s.proxyUrl,headers:s.headers,model:s.model??"gpt-4o-mini"},r.prompt,o);async function*a(){let c="";for await(let f of i){if(o?.aborted)break;c+=f,yield{kind:"text",text:c}}return{kind:"text",text:c}}return a()}}};return Promise.resolve(t)}}var si={OpenAIProvider:On},nf=si;export{nf as default};
|
|
20
|
+
//# sourceMappingURL=index.mjs.map
|