Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@focus-reactive/sanity-ai-sdk

Package Overview
Dependencies
Maintainers
6
Versions
5
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@focus-reactive/sanity-ai-sdk - npm Package Compare versions

Comparing version 0.0.4 to 0.0.5

2

dist/features/index.d.ts

@@ -1,3 +0,3 @@

export { transalateSelectedDocumentFields, translateFullDocument, } from "./translations";
export { transalateSelectedDocumentFields } from "./translations";
export { findRelevantTags } from "./categorisation";
export { summariseDocument } from "./summarisation";

@@ -1,2 +0,1 @@

export * from "./translateFullDocument";
export * from "./translateSelectedDocumentFields";

@@ -1,9 +0,9 @@

(function($,D){typeof exports=="object"&&typeof module<"u"?D(exports):typeof define=="function"&&define.amd?define(["exports"],D):($=typeof globalThis<"u"?globalThis:$||self,D($["sanity-ai-sdk"]={}))})(this,function($){"use strict";let D=null;const is=s=>{D=s},tt=()=>D,L="4.18.0";let fe=!1,U,pe,me,Mt,ge,ye,we,be,ve;function as(s,t={auto:!1}){if(fe)throw new Error(`you must \`import 'openai/shims/${s.kind}'\` before importing anything else from openai`);if(U)throw new Error(`can't \`import 'openai/shims/${s.kind}'\` after \`import 'openai/shims/${U}'\``);fe=t.auto,U=s.kind,pe=s.fetch,s.Request,s.Response,s.Headers,me=s.FormData,s.Blob,Mt=s.File,ge=s.ReadableStream,ye=s.getMultipartRequestOptions,we=s.getDefaultAgent,be=s.fileFromPath,ve=s.isFsReadStream}class cs{constructor(t){this.body=t}get[Symbol.toStringTag](){return"MultipartBody"}}function ls({manuallyImported:s}={}){const t=s?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let e,n,r,o;try{e=fetch,n=Request,r=Response,o=Headers}catch(c){throw new Error(`this environment is missing the following Web Fetch API type: ${c.message}. ${t}`)}return{kind:"web",fetch:e,Request:n,Response:r,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. ${t}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(c,a)=>({...a,body:new cs(c)}),getDefaultAgent:c=>{},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:c=>!1}}U||as(ls(),{auto:!0});class y extends Error{}class _ extends y{constructor(t,e,n,r){super(`${_.makeMessage(t,e,n)}`),this.status=t,this.headers=r;const o=e;this.error=o,this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(t,e,n){const r=e!=null&&e.message?typeof e.message=="string"?e.message:JSON.stringify(e.message):e?JSON.stringify(e):n;return t&&r?`${t} ${r}`:t?`${t} status code (no body)`:r||"(no status code or body)"}static generate(t,e,n,r){if(!t)return new et({cause:Jt(e)});const o=e==null?void 0:e.error;return t===400?new _e(t,o,n,r):t===401?new xe(t,o,n,r):t===403?new Se(t,o,n,r):t===404?new Oe(t,o,n,r):t===409?new Ae(t,o,n,r):t===422?new Ee(t,o,n,r):t===429?new Pe(t,o,n,r):t>=500?new Re(t,o,n,r):new _(t,o,n,r)}}class M extends _{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0),this.status=void 0}}class et extends _{constructor({message:t,cause:e}){super(void 0,void 0,t||"Connection error.",void 0),this.status=void 0,e&&(this.cause=e)}}class Bt extends et{constructor({message:t}={}){super({message:t??"Request timed out."})}}class _e extends _{constructor(){super(...arguments),this.status=400}}class xe extends _{constructor(){super(...arguments),this.status=401}}class Se extends _{constructor(){super(...arguments),this.status=403}}class Oe extends _{constructor(){super(...arguments),this.status=404}}class Ae extends _{constructor(){super(...arguments),this.status=409}}class Ee extends _{constructor(){super(...arguments),this.status=422}}class Pe extends _{constructor(){super(...arguments),this.status=429}}class Re extends _{}class F{constructor(t,e){this.iterator=t,this.controller=e}static fromSSEResponse(t,e){let n=!1;const r=new us;async function*o(){if(!t.body)throw e.abort(),new y("Attempted to iterate over a response with no body");const a=new B,d=$e(t.body);for await(const u of d)for(const l of a.decode(u)){const i=r.decode(l);i&&(yield i)}for(const u of a.flush()){const l=r.decode(u);l&&(yield l)}}async function*c(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(const d of o())if(!a){if(d.data.startsWith("[DONE]")){a=!0;continue}if(d.event===null){let u;try{u=JSON.parse(d.data)}catch(l){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),l}if(u&&u.error)throw new _(void 0,u.error,void 0,void 0);yield u}}a=!0}catch(d){if(d instanceof Error&&d.name==="AbortError")return;throw d}finally{a||e.abort()}}return new F(c,e)}static fromReadableStream(t,e){let n=!1;async function*r(){const c=new B,a=$e(t);for await(const d of a)for(const u of c.decode(d))yield u;for(const d of c.flush())yield d}async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let c=!1;try{for await(const a of r())c||a&&(yield JSON.parse(a));c=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{c||e.abort()}}return new F(o,e)}[Symbol.asyncIterator](){return this.iterator()}tee(){const t=[],e=[],n=this.iterator(),r=o=>({next:()=>{if(o.length===0){const c=n.next();t.push(c),e.push(c)}return o.shift()}});return[new F(()=>r(t),this.controller),new F(()=>r(e),this.controller)]}toReadableStream(){const t=this;let e;const n=new TextEncoder;return new ge({async start(){e=t[Symbol.asyncIterator]()},async pull(r){try{const{value:o,done:c}=await e.next();if(c)return r.close();const a=n.encode(JSON.stringify(o)+`
`);r.enqueue(a)}catch(o){r.error(o)}},async cancel(){var r;await((r=e.return)==null?void 0:r.call(e))}})}}class us{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(t),t.startsWith(":"))return null;let[e,n,r]=hs(t,":");return r.startsWith(" ")&&(r=r.substring(1)),e==="event"?this.event=r:e==="data"&&this.data.push(r),null}}class B{constructor(){this.buffer=[],this.trailingCR=!1}decode(t){let e=this.decodeText(t);if(this.trailingCR&&(e="\r"+e,this.trailingCR=!1),e.endsWith("\r")&&(this.trailingCR=!0,e=e.slice(0,-1)),!e)return[];const n=B.NEWLINE_CHARS.has(e[e.length-1]||"");let r=e.split(B.NEWLINE_REGEXP);return r.length===1&&!n?(this.buffer.push(r[0]),[]):(this.buffer.length>0&&(r=[this.buffer.join("")+r[0],...r.slice(1)],this.buffer=[]),n||(this.buffer=[r.pop()||""]),r)}decodeText(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof Buffer<"u"){if(t instanceof Buffer)return t.toString();if(t instanceof Uint8Array)return Buffer.from(t).toString();throw new y(`Unexpected: received non-Uint8Array (${t.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(t instanceof Uint8Array||t instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(t);throw new y(`Unexpected: received non-Uint8Array/ArrayBuffer (${t.constructor.name}) in a web platform. Please report this error.`)}throw new y("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const t=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,t}}B.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","…","\u2028","\u2029"]),B.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function hs(s,t){const e=s.indexOf(t);return e!==-1?[s.substring(0,e),t,s.substring(e+t.length)]:[s,"",""]}function $e(s){if(s[Symbol.asyncIterator])return s;const t=s.getReader();return{async next(){try{const e=await t.read();return e!=null&&e.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const je=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function",ds=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&Ce(s),Ce=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",fs=s=>ds(s)||je(s)||ve(s);async function Ie(s,t,e={}){var n;if(s=await s,je(s)){const o=await s.blob();return t||(t=new URL(s.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new Mt([o],t,e)}const r=await ps(s);if(t||(t=gs(s)??"unknown_file"),!e.type){const o=(n=r[0])==null?void 0:n.type;typeof o=="string"&&(e={...e,type:o})}return new Mt(r,t,e)}async function ps(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(Ce(s))e.push(await s.arrayBuffer());else if(ys(s))for await(const n of s)e.push(n);else throw new Error(`Unexpected data type: ${typeof s}; constructor: ${(t=s==null?void 0:s.constructor)==null?void 0:t.name}; props: ${ms(s)}`);return e}function ms(s){return`[${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}function gs(s){var t;return qt(s.name)||qt(s.filename)||((t=qt(s.path))==null?void 0:t.split(/[\\/]/).pop())}const qt=s=>{if(typeof s=="string")return s;if(typeof Buffer<"u"&&s instanceof Buffer)return String(s)},ys=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",Te=s=>s&&typeof s=="object"&&s.body&&s[Symbol.toStringTag]==="MultipartBody",X=async s=>{const t=await ws(s.body);return ye(t,s)},ws=async s=>{const t=new me;return await Promise.all(Object.entries(s||{}).map(([e,n])=>Dt(t,e,n))),t},Dt=async(s,t,e)=>{if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")s.append(t,String(e));else if(fs(e)){const n=await Ie(e);s.append(t,n)}else if(Array.isArray(e))await Promise.all(e.map(n=>Dt(s,t+"[]",n)));else if(typeof e=="object")await Promise.all(Object.entries(e).map(([n,r])=>Dt(s,`${t}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}};var bs=globalThis&&globalThis.__classPrivateFieldSet||function(s,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?s!==t||!r:!t.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(s,e):r?r.value=e:t.set(s,e),e},vs=globalThis&&globalThis.__classPrivateFieldGet||function(s,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?s!==t||!n:!t.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(s):n?n.value:t.get(s)},st;async function ke(s){const{response:t}=s;if(s.options.stream)return K("response",t.status,t.url,t.headers,t.body),F.fromSSEResponse(t,s.controller);if(t.status===204)return null;if(s.options.__binaryResponse)return t;const e=t.headers.get("content-type");if(e!=null&&e.includes("application/json")){const r=await t.json();return K("response",t.status,t.url,t.headers,r),r}const n=await t.text();return K("response",t.status,t.url,t.headers,n),n}class nt extends Promise{constructor(t,e=ke){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=e}_thenUnwrap(t){return new nt(this.responsePromise,async e=>t(await this.parseResponse(e)))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,e]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:e}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(t,e){return this.parse().then(t,e)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}class _s{constructor({baseURL:t,maxRetries:e=2,timeout:n=6e5,httpAgent:r,fetch:o}){this.baseURL=t,this.maxRetries=Lt("maxRetries",e),this.timeout=Lt("timeout",n),this.httpAgent=r,this.fetch=o??pe}authHeaders(t){return{}}defaultHeaders(t){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Ps(),...this.authHeaders(t)}}validateHeaders(t,e){}defaultIdempotencyKey(){return`stainless-node-retry-${Is()}`}get(t,e){return this.methodRequest("get",t,e)}post(t,e){return this.methodRequest("post",t,e)}patch(t,e){return this.methodRequest("patch",t,e)}put(t,e){return this.methodRequest("put",t,e)}delete(t,e){return this.methodRequest("delete",t,e)}methodRequest(t,e,n){return this.request(Promise.resolve(n).then(r=>({method:t,path:e,...r})))}getAPIList(t,e,n){return this.requestAPIList(e,{method:"get",path:t,...n})}calculateContentLength(t){if(typeof t=="string"){if(typeof Buffer<"u")return Buffer.byteLength(t,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(t).length.toString()}return null}buildRequest(t){var e;const{method:n,path:r,query:o,headers:c={}}=t,a=Te(t.body)?t.body.body:t.body?JSON.stringify(t.body,null,2):null,d=this.calculateContentLength(a),u=this.buildURL(r,o);"timeout"in t&&Lt("timeout",t.timeout);const l=t.timeout??this.timeout,i=t.httpAgent??this.httpAgent??we(u),f=l+1e3;typeof((e=i==null?void 0:i.options)==null?void 0:e.timeout)=="number"&&f>(i.options.timeout??0)&&(i.options.timeout=f),this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),c[this.idempotencyHeader]=t.idempotencyKey);const h={...d&&{"Content-Length":d},...this.defaultHeaders(t),...c};Te(t.body)&&U!=="node"&&delete h["Content-Type"],Object.keys(h).forEach(g=>h[g]===null&&delete h[g]);const p={method:n,...a&&{body:a},headers:h,...i&&{agent:i},signal:t.signal??null};return this.validateHeaders(h,c),{req:p,url:u,timeout:l}}async prepareRequest(t,{url:e,options:n}){}parseHeaders(t){return t?Symbol.iterator in t?Object.fromEntries(Array.from(t).map(e=>[...e])):{...t}:{}}makeStatusError(t,e,n,r){return _.generate(t,e,n,r)}request(t,e=null){return new nt(this.makeRequest(t,e))}async makeRequest(t,e){var n,r;const o=await t;e==null&&(e=o.maxRetries??this.maxRetries);const{req:c,url:a,timeout:d}=this.buildRequest(o);if(await this.prepareRequest(c,{url:a,options:o}),K("request",a,o,c.headers),(n=o.signal)!=null&&n.aborted)throw new M;const u=new AbortController,l=await this.fetchWithTimeout(a,c,d,u).catch(Jt);if(l instanceof Error){if((r=o.signal)!=null&&r.aborted)throw new M;if(e)return this.retryRequest(o,e);throw l.name==="AbortError"?new Bt:new et({cause:l})}const i=Ss(l.headers);if(!l.ok){if(e&&this.shouldRetry(l))return this.retryRequest(o,e,i);const f=await l.text().catch(g=>Jt(g).message),h=Rs(f),p=h?void 0:f;throw K("response",l.status,a,i,p),this.makeStatusError(l.status,h,p,i)}return{response:l,options:o,controller:u}}requestAPIList(t,e){const n=this.makeRequest(e,null);return new xs(this,n,t)}buildURL(t,e){const n=js(t)?new URL(t):new URL(this.baseURL+(this.baseURL.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),r=this.defaultQuery();return Le(r)||(e={...r,...e}),e&&(n.search=this.stringifyQuery(e)),n.toString()}stringifyQuery(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new y(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(t,e,n,r){const{signal:o,...c}=e||{};o&&o.addEventListener("abort",()=>r.abort());const a=setTimeout(()=>r.abort(),n);return this.getRequestClient().fetch.call(void 0,t,{signal:r.signal,...c}).finally(()=>{clearTimeout(a)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(t){const e=t.headers.get("x-should-retry");return e==="true"?!0:e==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,e,n){let r;const o=n==null?void 0:n["retry-after"];if(o){const c=parseInt(o);Number.isNaN(c)?r=Date.parse(o)-Date.now():r=c*1e3}if(!r||!Number.isInteger(r)||r<=0||r>60*1e3){const c=t.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(e,c)}return await qe(r),this.makeRequest(t,e-1)}calculateDefaultRetryTimeoutMillis(t,e){const n=e-t,r=Math.min(.5*Math.pow(2,n),8),o=1-Math.random()*.25;return r*o*1e3}getUserAgent(){return`${this.constructor.name}/JS ${L}`}}class Fe{constructor(t,e,n,r){st.set(this,void 0),bs(this,st,t,"f"),this.options=r,this.response=e,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const t=this.nextPageInfo();if(!t)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const e={...this.options};if("params"in t)e.query={...e.query,...t.params};else if("url"in t){const n=[...Object.entries(e.query||{}),...t.url.searchParams.entries()];for(const[r,o]of n)t.url.searchParams.set(r,o);e.query=void 0,e.path=t.url.toString()}return await vs(this,st,"f").requestAPIList(this.constructor,e)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(st=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const e of t.getPaginatedItems())yield e}}class xs extends nt{constructor(t,e,n){super(e,async r=>new n(t,r.response,await ke(r),r.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const e of t)yield e}}const Ss=s=>new Proxy(Object.fromEntries(s.entries()),{get(t,e){const n=e.toString();return t[n.toLowerCase()]||t[n]}}),Os={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryResponse:!0},j=s=>typeof s=="object"&&s!==null&&!Le(s)&&Object.keys(s).every(t=>Cs(Os,t)),As=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"X-Stainless-OS":Me(Deno.build.os),"X-Stainless-Arch":Ne(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":Deno.version};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"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":L,"X-Stainless-OS":Me(process.platform),"X-Stainless-Arch":Ne(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const s=Es();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":L,"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":L,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Es(){if(typeof navigator>"u"||!navigator)return null;const 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(const{key:t,pattern:e}of s){const n=e.exec(navigator.userAgent);if(n){const r=n[1]||0,o=n[2]||0,c=n[3]||0;return{browser:t,version:`${r}.${o}.${c}`}}}return null}const Ne=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Me=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");let Be;const Ps=()=>Be??(Be=As()),Rs=s=>{try{return JSON.parse(s)}catch{return}},$s=new RegExp("^(?:[a-z]+:)?//","i"),js=s=>$s.test(s),qe=s=>new Promise(t=>setTimeout(t,s)),Lt=(s,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new y(`${s} must be an integer`);if(t<0)throw new y(`${s} must be a positive integer`);return t},Jt=s=>s instanceof Error?s:new Error(s),De=s=>{var t,e,n;if(typeof process<"u")return((t=process.env)==null?void 0:t[s])??void 0;if(typeof Deno<"u")return(n=(e=Deno.env)==null?void 0:e.get)==null?void 0:n.call(e,s)};function Le(s){if(!s)return!0;for(const t in s)return!1;return!0}function Cs(s,t){return Object.prototype.hasOwnProperty.call(s,t)}function K(s,...t){typeof process<"u"&&process.env.DEBUG==="true"&&console.log(`OpenAI:DEBUG:${s}`,...t)}const Is=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const t=Math.random()*16|0;return(s==="x"?t:t&3|8).toString(16)}),Ts=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";class rt extends Fe{constructor(t,e,n,r){super(t,e,n,r),this.data=n.data,this.object=n.object}getPaginatedItems(){return this.data}nextPageParams(){return null}nextPageInfo(){return null}}class T extends Fe{constructor(t,e,n,r){super(t,e,n,r),this.data=n.data}getPaginatedItems(){return this.data}nextPageParams(){const t=this.nextPageInfo();if(!t)return null;if("params"in t)return t.params;const e=Object.fromEntries(t.url.searchParams);return Object.keys(e).length?e:null}nextPageInfo(){var t,e;if(!((t=this.data)!=null&&t.length))return null;const n=(e=this.data[this.data.length-1])==null?void 0:e.id;return n?{params:{after:n}}:null}}class w{constructor(t){this.client=t,this.get=t.get.bind(t),this.post=t.post.bind(t),this.patch=t.patch.bind(t),this.put=t.put.bind(t),this.delete=t.delete.bind(t),this.getAPIList=t.getAPIList.bind(t)}}let ot=class extends w{create(s,t){return this.post("/chat/completions",{body:s,...t,stream:s.stream??!1})}};ot||(ot={});let it=class extends w{constructor(){super(...arguments),this.completions=new ot(this.client)}};(function(s){s.Completions=ot})(it||(it={}));class at extends w{create(t,e){return this.post("/audio/speech",{body:t,...e,__binaryResponse:!0})}}at||(at={});class ct extends w{create(t,e){return this.post("/audio/transcriptions",X({body:t,...e}))}}ct||(ct={});class lt extends w{create(t,e){return this.post("/audio/translations",X({body:t,...e}))}}lt||(lt={});class ut extends w{constructor(){super(...arguments),this.transcriptions=new ct(this.client),this.translations=new lt(this.client),this.speech=new at(this.client)}}(function(s){s.Transcriptions=ct,s.Translations=lt,s.Speech=at})(ut||(ut={}));let ht=class extends w{create(s,t,e){return this.post(`/assistants/${s}/files`,{body:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}retrieve(s,t,e){return this.get(`/assistants/${s}/files/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}list(s,t={},e){return j(t)?this.list(s,{},t):this.getAPIList(`/assistants/${s}/files`,Wt,{query:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}del(s,t,e){return this.delete(`/assistants/${s}/files/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}};class Wt extends T{}(function(s){s.AssistantFilesPage=Wt})(ht||(ht={}));class dt extends w{constructor(){super(...arguments),this.files=new ht(this.client)}create(t,e){return this.post("/assistants",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}retrieve(t,e){return this.get(`/assistants/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}update(t,e,n){return this.post(`/assistants/${t}`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}list(t={},e){return j(t)?this.list({},t):this.getAPIList("/assistants",Ut,{query:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}del(t,e){return this.delete(`/assistants/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}}class Ut extends T{}(function(s){s.AssistantsPage=Ut,s.Files=ht,s.AssistantFilesPage=Wt})(dt||(dt={}));function Je(s){return typeof s.parse=="function"}const H=s=>(s==null?void 0:s.role)==="assistant",We=s=>(s==null?void 0:s.role)==="function",ks=s=>(s==null?void 0:s.role)==="tool";var P=globalThis&&globalThis.__classPrivateFieldSet||function(s,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?s!==t||!r:!t.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(s,e):r?r.value=e:t.set(s,e),e},m=globalThis&&globalThis.__classPrivateFieldGet||function(s,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?s!==t||!n:!t.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(s):n?n.value:t.get(s)},x,ft,pt,V,z,mt,G,k,Q,gt,yt,J,Xt,Kt,Ht,Vt,zt,Gt,Ue,Qt;const Xe=10;class Ke{constructor(){x.add(this),this.controller=new AbortController,ft.set(this,void 0),pt.set(this,()=>{}),V.set(this,()=>{}),z.set(this,void 0),mt.set(this,()=>{}),G.set(this,()=>{}),k.set(this,{}),this._chatCompletions=[],this.messages=[],Q.set(this,!1),gt.set(this,!1),yt.set(this,!1),J.set(this,!1),Gt.set(this,t=>{if(P(this,gt,!0,"f"),t instanceof Error&&t.name==="AbortError"&&(t=new M),t instanceof M)return P(this,yt,!0,"f"),this._emit("abort",t);if(t instanceof y)return this._emit("error",t);if(t instanceof Error){const e=new y(t.message);return e.cause=t,this._emit("error",e)}return this._emit("error",new y(String(t)))}),P(this,ft,new Promise((t,e)=>{P(this,pt,t,"f"),P(this,V,e,"f")}),"f"),P(this,z,new Promise((t,e)=>{P(this,mt,t,"f"),P(this,G,e,"f")}),"f"),m(this,ft,"f").catch(()=>{}),m(this,z,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},m(this,Gt,"f"))},0)}_addChatCompletion(t){var e;this._chatCompletions.push(t),this._emit("chatCompletion",t);const n=(e=t.choices[0])==null?void 0:e.message;return n&&this._addMessage(n),t}_addMessage(t,e=!0){if(this.messages.push(t),e){if(this._emit("message",t),(We(t)||ks(t))&&t.content)this._emit("functionCallResult",t.content);else if(H(t)&&t.function_call)this._emit("functionCall",t.function_call);else if(H(t)&&t.tool_calls)for(const n of t.tool_calls)n.type==="function"&&this._emit("functionCall",n.function)}}_connected(){this.ended||(m(this,pt,"f").call(this),this._emit("connect"))}get ended(){return m(this,Q,"f")}get errored(){return m(this,gt,"f")}get aborted(){return m(this,yt,"f")}abort(){this.controller.abort()}on(t,e){return(m(this,k,"f")[t]||(m(this,k,"f")[t]=[])).push({listener:e}),this}off(t,e){const n=m(this,k,"f")[t];if(!n)return this;const r=n.findIndex(o=>o.listener===e);return r>=0&&n.splice(r,1),this}once(t,e){return(m(this,k,"f")[t]||(m(this,k,"f")[t]=[])).push({listener:e,once:!0}),this}emitted(t){return new Promise((e,n)=>{P(this,J,!0,"f"),t!=="error"&&this.once("error",n),this.once(t,e)})}async done(){P(this,J,!0,"f"),await m(this,z,"f")}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new y("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),m(this,x,"m",Xt).call(this)}async finalMessage(){return await this.done(),m(this,x,"m",Kt).call(this)}async finalFunctionCall(){return await this.done(),m(this,x,"m",Ht).call(this)}async finalFunctionCallResult(){return await this.done(),m(this,x,"m",Vt).call(this)}async totalUsage(){return await this.done(),m(this,x,"m",zt).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emit(t,...e){if(m(this,Q,"f"))return;t==="end"&&(P(this,Q,!0,"f"),m(this,mt,"f").call(this));const n=m(this,k,"f")[t];if(n&&(m(this,k,"f")[t]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...e))),t==="abort"){const r=e[0];!m(this,J,"f")&&!(n!=null&&n.length)&&Promise.reject(r),m(this,V,"f").call(this,r),m(this,G,"f").call(this,r),this._emit("end");return}if(t==="error"){const r=e[0];!m(this,J,"f")&&!(n!=null&&n.length)&&Promise.reject(r),m(this,V,"f").call(this,r),m(this,G,"f").call(this,r),this._emit("end")}}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const e=this.messages[this.messages.length-1];e&&this._emit("finalMessage",e);const n=m(this,x,"m",Xt).call(this);n&&this._emit("finalContent",n);const r=m(this,x,"m",Ht).call(this);r&&this._emit("finalFunctionCall",r);const o=m(this,x,"m",Vt).call(this);o!=null&&this._emit("finalFunctionCallResult",o),this._chatCompletions.some(c=>c.usage)&&this._emit("totalUsage",m(this,x,"m",zt).call(this))}async _createChatCompletion(t,e,n){const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),m(this,x,"m",Ue).call(this,e);const o=await t.create({...e,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(o)}async _runChatCompletion(t,e,n){for(const r of e.messages)this._addMessage(r,!1);return await this._createChatCompletion(t,e,n)}async _runFunctions(t,e,n){var r;const o="function",{function_call:c="auto",stream:a,...d}=e,u=typeof c!="string"&&(c==null?void 0:c.name),{maxChatCompletions:l=Xe}=n||{},i={};for(const h of e.functions)i[h.name||h.function.name]=h;const f=e.functions.map(h=>({name:h.name||h.function.name,parameters:h.parameters,description:h.description}));for(const h of e.messages)this._addMessage(h,!1);for(let h=0;h<l;++h){const p=(r=(await this._createChatCompletion(t,{...d,function_call:c,functions:f,messages:[...this.messages]},n)).choices[0])==null?void 0:r.message;if(!p)throw new y("missing message in ChatCompletion response");if(!p.function_call)return;const{name:g,arguments:b}=p.function_call,S=i[g];if(S){if(u&&u!==g){const I=`Invalid function_call: ${JSON.stringify(g)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:o,name:g,content:I});continue}}else{const I=`Invalid function_call: ${JSON.stringify(g)}. Available options are: ${f.map(he=>JSON.stringify(he.name)).join(", ")}. Please try again`;this._addMessage({role:o,name:g,content:I});continue}let O;try{O=Je(S)?await S.parse(b):b}catch(I){this._addMessage({role:o,name:g,content:I instanceof Error?I.message:String(I)});continue}const E=await S.function(O,this),A=m(this,x,"m",Qt).call(this,E);if(this._addMessage({role:o,name:g,content:A}),u)return}}async _runTools(t,e,n){var r,o;const c="tool",{tool_choice:a="auto",stream:d,...u}=e,l=typeof a!="string"&&((r=a==null?void 0:a.function)==null?void 0:r.name),{maxChatCompletions:i=Xe}=n||{},f={};for(const p of e.tools)p.type==="function"&&(f[p.function.name||p.function.function.name]=p.function);const h="tools"in e?e.tools.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description}}:p):void 0;for(const p of e.messages)this._addMessage(p,!1);for(let p=0;p<i;++p){const g=(o=(await this._createChatCompletion(t,{...u,tool_choice:a,tools:h,messages:[...this.messages]},n)).choices[0])==null?void 0:o.message;if(!g)throw new y("missing message in ChatCompletion response");if(!g.tool_calls)return;for(const b of g.tool_calls){if(b.type!=="function")continue;const S=b.id,{name:O,arguments:E}=b.function,A=f[O];if(A){if(l&&l!==O){const q=`Invalid tool_call: ${JSON.stringify(O)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:c,tool_call_id:S,content:q});continue}}else{const q=`Invalid tool_call: ${JSON.stringify(O)}. Available options are: ${h.map(de=>JSON.stringify(de.function.name)).join(", ")}. Please try again`;this._addMessage({role:c,tool_call_id:S,content:q});continue}let I;try{I=Je(A)?await A.parse(E):E}catch(q){const de=q instanceof Error?q.message:String(q);this._addMessage({role:c,tool_call_id:S,content:de});continue}const he=await A.function(I,this),Hs=m(this,x,"m",Qt).call(this,he);if(this._addMessage({role:c,tool_call_id:S,content:Hs}),l)return}}}}ft=new WeakMap,pt=new WeakMap,V=new WeakMap,z=new WeakMap,mt=new WeakMap,G=new WeakMap,k=new WeakMap,Q=new WeakMap,gt=new WeakMap,yt=new WeakMap,J=new WeakMap,Gt=new WeakMap,x=new WeakSet,Xt=function(){return m(this,x,"m",Kt).call(this).content},Kt=function(){let s=this.messages.length;for(;s-- >0;){const t=this.messages[s];if(H(t))return t}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},Ht=function(){for(let s=this.messages.length-1;s>=0;s--){const t=this.messages[s];if(H(t)&&t!=null&&t.function_call)return t.function_call}},Vt=function(){for(let s=this.messages.length-1;s>=0;s--){const t=this.messages[s];if(We(t)&&t.content!=null)return t.content}},zt=function(){const s={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(s.completion_tokens+=t.completion_tokens,s.prompt_tokens+=t.prompt_tokens,s.total_tokens+=t.total_tokens);return s},Ue=function(s){if(s.n!=null&&s.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Qt=function(s){return typeof s=="string"?s:s===void 0?"undefined":JSON.stringify(s)};class Y extends Ke{static runFunctions(t,e,n){const r=new Y;return r._run(()=>r._runFunctions(t,e,n)),r}static runTools(t,e,n){const r=new Y;return r._run(()=>r._runTools(t,e,n)),r}_addMessage(t){super._addMessage(t),H(t)&&t.content&&this._emit("content",t.content)}}var R=globalThis&&globalThis.__classPrivateFieldGet||function(s,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?s!==t||!n:!t.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(s):n?n.value:t.get(s)},Yt=globalThis&&globalThis.__classPrivateFieldSet||function(s,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?s!==t||!r:!t.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(s,e):r?r.value=e:t.set(s,e),e},C,N,Zt,te,wt,He;class Z extends Ke{constructor(){super(...arguments),C.add(this),N.set(this,void 0)}get currentChatCompletionSnapshot(){return R(this,N,"f")}static fromReadableStream(t){const e=new Z;return e._run(()=>e._fromReadableStream(t)),e}static createChatCompletion(t,e,n){const r=new Z;return r._run(()=>r._runChatCompletion(t,{...e,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(t,e,n){var r;const o=n==null?void 0:n.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort())),R(this,C,"m",Zt).call(this);const c=await t.create({...e,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const a of c)R(this,C,"m",te).call(this,a);if((r=c.controller.signal)!=null&&r.aborted)throw new M;return this._addChatCompletion(R(this,C,"m",wt).call(this))}async _fromReadableStream(t,e){var n;const r=e==null?void 0:e.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),R(this,C,"m",Zt).call(this),this._connected();const o=F.fromReadableStream(t,this.controller);let c;for await(const a of o)c&&c!==a.id&&this._addChatCompletion(R(this,C,"m",wt).call(this)),R(this,C,"m",te).call(this,a),c=a.id;if((n=o.controller.signal)!=null&&n.aborted)throw new M;return this._addChatCompletion(R(this,C,"m",wt).call(this))}[(N=new WeakMap,C=new WeakSet,Zt=function(){this.ended||Yt(this,N,void 0,"f")},te=function(t){var e,n,r;if(this.ended)return;const o=R(this,C,"m",He).call(this,t);this._emit("chunk",t,o);const c=(n=(e=t.choices[0])==null?void 0:e.delta)==null?void 0:n.content,a=(r=o.choices[0])==null?void 0:r.message;c!=null&&(a==null?void 0:a.role)==="assistant"&&a!=null&&a.content&&this._emit("content",c,a.content)},wt=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");const t=R(this,N,"f");if(!t)throw new y("request ended without sending any chunks");return Yt(this,N,void 0,"f"),Fs(t)},He=function(t){var e,n;let r=R(this,N,"f");const{choices:o,...c}=t;r?Object.assign(r,c):r=Yt(this,N,{...c,choices:[]},"f");for(const{delta:a,finish_reason:d,index:u,...l}of t.choices){let i=r.choices[u];if(!i){r.choices[u]={finish_reason:d,index:u,message:a,...l};continue}if(d&&(i.finish_reason=d),Object.assign(i,l),!a)continue;const{content:f,function_call:h,role:p,tool_calls:g}=a;if(f&&(i.message.content=(i.message.content||"")+f),p&&(i.message.role=p),h&&(i.message.function_call?(h.name&&(i.message.function_call.name=h.name),h.arguments&&((e=i.message.function_call).arguments??(e.arguments=""),i.message.function_call.arguments+=h.arguments)):i.message.function_call=h),g){i.message.tool_calls||(i.message.tool_calls=[]);for(const{index:b,id:S,type:O,function:E}of g){const A=(n=i.message.tool_calls)[b]??(n[b]={});S&&(A.id=S),O&&(A.type=O),E&&(A.function??(A.function={arguments:""})),E!=null&&E.name&&(A.function.name=E.name),E!=null&&E.arguments&&(A.function.arguments+=E.arguments)}}}return r},Symbol.asyncIterator)](){const t=[],e=[];let n=!1;return this.on("chunk",r=>{const o=e.shift();o?o(r):t.push(r)}),this.on("end",()=>{n=!0;for(const r of e)r(void 0);e.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise(r=>e.push(r)).then(r=>r?{value:r,done:!1}:{value:void 0,done:!0})}}toReadableStream(){return new F(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Fs(s){const{id:t,choices:e,created:n,model:r}=s;return{id:t,choices:e.map(({message:o,finish_reason:c,index:a})=>{if(!c)throw new y(`missing finish_reason for choice ${a}`);const{content:d=null,function_call:u,tool_calls:l}=o,i=o.role;if(!i)throw new y(`missing role for choice ${a}`);if(u){const{arguments:f,name:h}=u;if(f==null)throw new y(`missing function_call.arguments for choice ${a}`);if(!h)throw new y(`missing function_call.name for choice ${a}`);return{message:{content:d,function_call:{arguments:f,name:h},role:i},finish_reason:c,index:a}}return l?{index:a,finish_reason:c,message:{role:i,content:d,tool_calls:l.map((f,h)=>{const{function:p,type:g,id:b}=f,{arguments:S,name:O}=p||{};if(b==null)throw new y(`missing choices[${a}].tool_calls[${h}].id
${bt(s)}`);if(g==null)throw new y(`missing choices[${a}].tool_calls[${h}].type
${bt(s)}`);if(O==null)throw new y(`missing choices[${a}].tool_calls[${h}].function.name
${bt(s)}`);if(S==null)throw new y(`missing choices[${a}].tool_calls[${h}].function.arguments
${bt(s)}`);return{id:b,type:g,function:{name:O,arguments:S}}})}}:{message:{content:d,role:i},finish_reason:c,index:a}}),created:n,model:r,object:"chat.completion"}}function bt(s){return JSON.stringify(s)}class W extends Z{static fromReadableStream(t){const e=new W;return e._run(()=>e._fromReadableStream(t)),e}static runFunctions(t,e,n){const r=new W;return r._run(()=>r._runFunctions(t,e,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}})),r}static runTools(t,e,n){const r=new W;return r._run(()=>r._runTools(t,e,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}})),r}}let Ve=class extends w{runFunctions(s,t){return s.stream?W.runFunctions(this.client.chat.completions,s,t):Y.runFunctions(this.client.chat.completions,s,t)}runTools(s,t){return s.stream?W.runTools(this.client.chat.completions,s,t):Y.runTools(this.client.chat.completions,s,t)}stream(s,t){return Z.createChatCompletion(this.client.chat.completions,s,t)}};class vt extends w{constructor(){super(...arguments),this.completions=new Ve(this.client)}}(function(s){s.Completions=Ve})(vt||(vt={}));let _t=class extends w{retrieve(s,t,e,n){return this.get(`/threads/${s}/messages/${t}/files/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}list(s,t,e={},n){return j(e)?this.list(s,t,{},e):this.getAPIList(`/threads/${s}/messages/${t}/files`,ee,{query:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}};class ee extends T{}(function(s){s.MessageFilesPage=ee})(_t||(_t={}));class xt extends w{constructor(){super(...arguments),this.files=new _t(this.client)}create(t,e,n){return this.post(`/threads/${t}/messages`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}retrieve(t,e,n){return this.get(`/threads/${t}/messages/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}update(t,e,n,r){return this.post(`/threads/${t}/messages/${e}`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(t,e={},n){return j(e)?this.list(t,{},e):this.getAPIList(`/threads/${t}/messages`,se,{query:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}}class se extends T{}(function(s){s.ThreadMessagesPage=se,s.Files=_t,s.MessageFilesPage=ee})(xt||(xt={}));class St extends w{retrieve(t,e,n,r){return this.get(`/threads/${t}/runs/${e}/steps/${n}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(t,e,n={},r){return j(n)?this.list(t,e,{},n):this.getAPIList(`/threads/${t}/runs/${e}/steps`,ne,{query:n,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}}class ne extends T{}(function(s){s.RunStepsPage=ne})(St||(St={}));class Ot extends w{constructor(){super(...arguments),this.steps=new St(this.client)}create(t,e,n){return this.post(`/threads/${t}/runs`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}retrieve(t,e,n){return this.get(`/threads/${t}/runs/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}update(t,e,n,r){return this.post(`/threads/${t}/runs/${e}`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(t,e={},n){return j(e)?this.list(t,{},e):this.getAPIList(`/threads/${t}/runs`,re,{query:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}cancel(t,e,n){return this.post(`/threads/${t}/runs/${e}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}submitToolOutputs(t,e,n,r){return this.post(`/threads/${t}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}}class re extends T{}(function(s){s.RunsPage=re,s.Steps=St,s.RunStepsPage=ne})(Ot||(Ot={}));class At extends w{constructor(){super(...arguments),this.runs=new Ot(this.client),this.messages=new xt(this.client)}create(t={},e){return j(t)?this.create({},t):this.post("/threads",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}retrieve(t,e){return this.get(`/threads/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}update(t,e,n){return this.post(`/threads/${t}`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}del(t,e){return this.delete(`/threads/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}createAndRun(t,e){return this.post("/threads/runs",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}}(function(s){s.Runs=Ot,s.RunsPage=re,s.Messages=xt,s.ThreadMessagesPage=se})(At||(At={}));class Et extends w{constructor(){super(...arguments),this.chat=new vt(this.client),this.assistants=new dt(this.client),this.threads=new At(this.client)}}(function(s){s.Chat=vt,s.Assistants=dt,s.AssistantsPage=Ut,s.Threads=At})(Et||(Et={}));class Pt extends w{create(t,e){return this.post("/completions",{body:t,...e,stream:t.stream??!1})}}Pt||(Pt={});class Rt extends w{create(t,e){return this.post("/embeddings",{body:t,...e})}}Rt||(Rt={});class $t extends w{create(t,e){return this.post("/edits",{body:t,...e})}}$t||($t={});class jt extends w{create(t,e){return this.post("/files",X({body:t,...e}))}retrieve(t,e){return this.get(`/files/${t}`,e)}list(t={},e){return j(t)?this.list({},t):this.getAPIList("/files",oe,{query:t,...e})}del(t,e){return this.delete(`/files/${t}`,e)}content(t,e){return this.get(`/files/${t}/content`,{...e,__binaryResponse:!0})}retrieveContent(t,e){return this.get(`/files/${t}/content`,{...e,headers:{Accept:"application/json",...e==null?void 0:e.headers}})}async waitForProcessing(t,{pollInterval:e=5e3,maxWait:n=30*60*1e3}={}){const r=new Set(["processed","error","deleted"]),o=Date.now();let c=await this.retrieve(t);for(;!c.status||!r.has(c.status);)if(await qe(e),c=await this.retrieve(t),Date.now()-o>n)throw new Bt({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return c}}class oe extends rt{}(function(s){s.FileObjectsPage=oe})(jt||(jt={}));class Ct extends w{create(t,e){return this.post("/fine-tunes",{body:t,...e})}retrieve(t,e){return this.get(`/fine-tunes/${t}`,e)}list(t){return this.getAPIList("/fine-tunes",ie,t)}cancel(t,e){return this.post(`/fine-tunes/${t}/cancel`,e)}listEvents(t,e,n){return this.get(`/fine-tunes/${t}/events`,{query:e,timeout:864e5,...n,stream:(e==null?void 0:e.stream)??!1})}}class ie extends rt{}(function(s){s.FineTunesPage=ie})(Ct||(Ct={}));class It extends w{create(t,e){return this.post("/fine_tuning/jobs",{body:t,...e})}retrieve(t,e){return this.get(`/fine_tuning/jobs/${t}`,e)}list(t={},e){return j(t)?this.list({},t):this.getAPIList("/fine_tuning/jobs",ae,{query:t,...e})}cancel(t,e){return this.post(`/fine_tuning/jobs/${t}/cancel`,e)}listEvents(t,e={},n){return j(e)?this.listEvents(t,{},e):this.getAPIList(`/fine_tuning/jobs/${t}/events`,ce,{query:e,...n})}}class ae extends T{}class ce extends T{}(function(s){s.FineTuningJobsPage=ae,s.FineTuningJobEventsPage=ce})(It||(It={}));class Tt extends w{constructor(){super(...arguments),this.jobs=new It(this.client)}}(function(s){s.Jobs=It,s.FineTuningJobsPage=ae,s.FineTuningJobEventsPage=ce})(Tt||(Tt={}));class kt extends w{createVariation(t,e){return this.post("/images/variations",X({body:t,...e}))}edit(t,e){return this.post("/images/edits",X({body:t,...e}))}generate(t,e){return this.post("/images/generations",{body:t,...e})}}kt||(kt={});class Ft extends w{retrieve(t,e){return this.get(`/models/${t}`,e)}list(t){return this.getAPIList("/models",le,t)}del(t,e){return this.delete(`/models/${t}`,e)}}class le extends rt{}(function(s){s.ModelsPage=le})(Ft||(Ft={}));class Nt extends w{create(t,e){return this.post("/moderations",{body:t,...e})}}Nt||(Nt={});var ze;class v extends _s{constructor({apiKey:t=De("OPENAI_API_KEY"),organization:e=De("OPENAI_ORG_ID")??null,...n}={}){if(t===void 0)throw new y("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const r={apiKey:t,organization:e,...n,baseURL:n.baseURL??"https://api.openai.com/v1"};if(!r.dangerouslyAllowBrowser&&Ts())throw new y(`It looks like you're running in a browser-like environment.
(function(T,$){typeof exports=="object"&&typeof module<"u"?$(exports):typeof define=="function"&&define.amd?define(["exports"],$):(T=typeof globalThis<"u"?globalThis:T||self,$(T["sanity-ai-sdk"]={}))})(this,function(T){"use strict";const $="4.18.0";let de=!1,W,fe,pe,Ft,me,ge,ye,we,be;function is(s,t={auto:!1}){if(de)throw new Error(`you must \`import 'openai/shims/${s.kind}'\` before importing anything else from openai`);if(W)throw new Error(`can't \`import 'openai/shims/${s.kind}'\` after \`import 'openai/shims/${W}'\``);de=t.auto,W=s.kind,fe=s.fetch,s.Request,s.Response,s.Headers,pe=s.FormData,s.Blob,Ft=s.File,me=s.ReadableStream,ge=s.getMultipartRequestOptions,ye=s.getDefaultAgent,we=s.fileFromPath,be=s.isFsReadStream}class os{constructor(t){this.body=t}get[Symbol.toStringTag](){return"MultipartBody"}}function as({manuallyImported:s}={}){const t=s?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let e,n,r,i;try{e=fetch,n=Request,r=Response,i=Headers}catch(c){throw new Error(`this environment is missing the following Web Fetch API type: ${c.message}. ${t}`)}return{kind:"web",fetch:e,Request:n,Response:r,Headers:i,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(c,a)=>({...a,body:new os(c)}),getDefaultAgent:c=>{},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:c=>!1}}W||is(as(),{auto:!0});class y extends Error{}class _ extends y{constructor(t,e,n,r){super(`${_.makeMessage(t,e,n)}`),this.status=t,this.headers=r;const i=e;this.error=i,this.code=i==null?void 0:i.code,this.param=i==null?void 0:i.param,this.type=i==null?void 0:i.type}static makeMessage(t,e,n){const r=e!=null&&e.message?typeof e.message=="string"?e.message:JSON.stringify(e.message):e?JSON.stringify(e):n;return t&&r?`${t} ${r}`:t?`${t} status code (no body)`:r||"(no status code or body)"}static generate(t,e,n,r){if(!t)return new Z({cause:Lt(e)});const i=e==null?void 0:e.error;return t===400?new ve(t,i,n,r):t===401?new _e(t,i,n,r):t===403?new xe(t,i,n,r):t===404?new Se(t,i,n,r):t===409?new Oe(t,i,n,r):t===422?new Ae(t,i,n,r):t===429?new Pe(t,i,n,r):t>=500?new Re(t,i,n,r):new _(t,i,n,r)}}class M extends _{constructor({message:t}={}){super(void 0,void 0,t||"Request was aborted.",void 0),this.status=void 0}}class Z extends _{constructor({message:t,cause:e}){super(void 0,void 0,t||"Connection error.",void 0),this.status=void 0,e&&(this.cause=e)}}class Nt extends Z{constructor({message:t}={}){super({message:t??"Request timed out."})}}class ve extends _{constructor(){super(...arguments),this.status=400}}class _e extends _{constructor(){super(...arguments),this.status=401}}class xe extends _{constructor(){super(...arguments),this.status=403}}class Se extends _{constructor(){super(...arguments),this.status=404}}class Oe extends _{constructor(){super(...arguments),this.status=409}}class Ae extends _{constructor(){super(...arguments),this.status=422}}class Pe extends _{constructor(){super(...arguments),this.status=429}}class Re extends _{}class N{constructor(t,e){this.iterator=t,this.controller=e}static fromSSEResponse(t,e){let n=!1;const r=new cs;async function*i(){if(!t.body)throw e.abort(),new y("Attempted to iterate over a response with no body");const a=new q,d=Ee(t.body);for await(const u of d)for(const l of a.decode(u)){const o=r.decode(l);o&&(yield o)}for(const u of a.flush()){const l=r.decode(u);l&&(yield l)}}async function*c(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(const d of i())if(!a){if(d.data.startsWith("[DONE]")){a=!0;continue}if(d.event===null){let u;try{u=JSON.parse(d.data)}catch(l){throw console.error("Could not parse message into JSON:",d.data),console.error("From chunk:",d.raw),l}if(u&&u.error)throw new _(void 0,u.error,void 0,void 0);yield u}}a=!0}catch(d){if(d instanceof Error&&d.name==="AbortError")return;throw d}finally{a||e.abort()}}return new N(c,e)}static fromReadableStream(t,e){let n=!1;async function*r(){const c=new q,a=Ee(t);for await(const d of a)for(const u of c.decode(d))yield u;for(const d of c.flush())yield d}async function*i(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let c=!1;try{for await(const a of r())c||a&&(yield JSON.parse(a));c=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{c||e.abort()}}return new N(i,e)}[Symbol.asyncIterator](){return this.iterator()}tee(){const t=[],e=[],n=this.iterator(),r=i=>({next:()=>{if(i.length===0){const c=n.next();t.push(c),e.push(c)}return i.shift()}});return[new N(()=>r(t),this.controller),new N(()=>r(e),this.controller)]}toReadableStream(){const t=this;let e;const n=new TextEncoder;return new me({async start(){e=t[Symbol.asyncIterator]()},async pull(r){try{const{value:i,done:c}=await e.next();if(c)return r.close();const a=n.encode(JSON.stringify(i)+`
`);r.enqueue(a)}catch(i){r.error(i)}},async cancel(){var r;await((r=e.return)==null?void 0:r.call(e))}})}}class cs{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(t){if(t.endsWith("\r")&&(t=t.substring(0,t.length-1)),!t){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(t),t.startsWith(":"))return null;let[e,n,r]=ls(t,":");return r.startsWith(" ")&&(r=r.substring(1)),e==="event"?this.event=r:e==="data"&&this.data.push(r),null}}class q{constructor(){this.buffer=[],this.trailingCR=!1}decode(t){let e=this.decodeText(t);if(this.trailingCR&&(e="\r"+e,this.trailingCR=!1),e.endsWith("\r")&&(this.trailingCR=!0,e=e.slice(0,-1)),!e)return[];const n=q.NEWLINE_CHARS.has(e[e.length-1]||"");let r=e.split(q.NEWLINE_REGEXP);return r.length===1&&!n?(this.buffer.push(r[0]),[]):(this.buffer.length>0&&(r=[this.buffer.join("")+r[0],...r.slice(1)],this.buffer=[]),n||(this.buffer=[r.pop()||""]),r)}decodeText(t){if(t==null)return"";if(typeof t=="string")return t;if(typeof Buffer<"u"){if(t instanceof Buffer)return t.toString();if(t instanceof Uint8Array)return Buffer.from(t).toString();throw new y(`Unexpected: received non-Uint8Array (${t.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(t instanceof Uint8Array||t instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(t);throw new y(`Unexpected: received non-Uint8Array/ArrayBuffer (${t.constructor.name}) in a web platform. Please report this error.`)}throw new y("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const t=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,t}}q.NEWLINE_CHARS=new Set([`
`,"\r","\v","\f","","","","…","\u2028","\u2029"]),q.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;function ls(s,t){const e=s.indexOf(t);return e!==-1?[s.substring(0,e),t,s.substring(e+t.length)]:[s,"",""]}function Ee(s){if(s[Symbol.asyncIterator])return s;const t=s.getReader();return{async next(){try{const e=await t.read();return e!=null&&e.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}const $e=s=>s!=null&&typeof s=="object"&&typeof s.url=="string"&&typeof s.blob=="function",us=s=>s!=null&&typeof s=="object"&&typeof s.name=="string"&&typeof s.lastModified=="number"&&je(s),je=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",hs=s=>us(s)||$e(s)||be(s);async function Ce(s,t,e={}){var n;if(s=await s,$e(s)){const i=await s.blob();return t||(t=new URL(s.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new Ft([i],t,e)}const r=await ds(s);if(t||(t=ps(s)??"unknown_file"),!e.type){const i=(n=r[0])==null?void 0:n.type;typeof i=="string"&&(e={...e,type:i})}return new Ft(r,t,e)}async function ds(s){var t;let e=[];if(typeof s=="string"||ArrayBuffer.isView(s)||s instanceof ArrayBuffer)e.push(s);else if(je(s))e.push(await s.arrayBuffer());else if(ms(s))for await(const n of s)e.push(n);else throw new Error(`Unexpected data type: ${typeof s}; constructor: ${(t=s==null?void 0:s.constructor)==null?void 0:t.name}; props: ${fs(s)}`);return e}function fs(s){return`[${Object.getOwnPropertyNames(s).map(t=>`"${t}"`).join(", ")}]`}function ps(s){var t;return Bt(s.name)||Bt(s.filename)||((t=Bt(s.path))==null?void 0:t.split(/[\\/]/).pop())}const Bt=s=>{if(typeof s=="string")return s;if(typeof Buffer<"u"&&s instanceof Buffer)return String(s)},ms=s=>s!=null&&typeof s=="object"&&typeof s[Symbol.asyncIterator]=="function",Ie=s=>s&&typeof s=="object"&&s.body&&s[Symbol.toStringTag]==="MultipartBody",U=async s=>{const t=await gs(s.body);return ge(t,s)},gs=async s=>{const t=new pe;return await Promise.all(Object.entries(s||{}).map(([e,n])=>Mt(t,e,n))),t},Mt=async(s,t,e)=>{if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")s.append(t,String(e));else if(hs(e)){const n=await Ce(e);s.append(t,n)}else if(Array.isArray(e))await Promise.all(e.map(n=>Mt(s,t+"[]",n)));else if(typeof e=="object")await Promise.all(Object.entries(e).map(([n,r])=>Mt(s,`${t}[${n}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}};var ys=globalThis&&globalThis.__classPrivateFieldSet||function(s,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?s!==t||!r:!t.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(s,e):r?r.value=e:t.set(s,e),e},ws=globalThis&&globalThis.__classPrivateFieldGet||function(s,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?s!==t||!n:!t.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(s):n?n.value:t.get(s)},tt;async function Te(s){const{response:t}=s;if(s.options.stream)return X("response",t.status,t.url,t.headers,t.body),N.fromSSEResponse(t,s.controller);if(t.status===204)return null;if(s.options.__binaryResponse)return t;const e=t.headers.get("content-type");if(e!=null&&e.includes("application/json")){const r=await t.json();return X("response",t.status,t.url,t.headers,r),r}const n=await t.text();return X("response",t.status,t.url,t.headers,n),n}class et extends Promise{constructor(t,e=Te){super(n=>{n(null)}),this.responsePromise=t,this.parseResponse=e}_thenUnwrap(t){return new et(this.responsePromise,async e=>t(await this.parseResponse(e)))}asResponse(){return this.responsePromise.then(t=>t.response)}async withResponse(){const[t,e]=await Promise.all([this.parse(),this.asResponse()]);return{data:t,response:e}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(t,e){return this.parse().then(t,e)}catch(t){return this.parse().catch(t)}finally(t){return this.parse().finally(t)}}class bs{constructor({baseURL:t,maxRetries:e=2,timeout:n=6e5,httpAgent:r,fetch:i}){this.baseURL=t,this.maxRetries=qt("maxRetries",e),this.timeout=qt("timeout",n),this.httpAgent=r,this.fetch=i??fe}authHeaders(t){return{}}defaultHeaders(t){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...As(),...this.authHeaders(t)}}validateHeaders(t,e){}defaultIdempotencyKey(){return`stainless-node-retry-${js()}`}get(t,e){return this.methodRequest("get",t,e)}post(t,e){return this.methodRequest("post",t,e)}patch(t,e){return this.methodRequest("patch",t,e)}put(t,e){return this.methodRequest("put",t,e)}delete(t,e){return this.methodRequest("delete",t,e)}methodRequest(t,e,n){return this.request(Promise.resolve(n).then(r=>({method:t,path:e,...r})))}getAPIList(t,e,n){return this.requestAPIList(e,{method:"get",path:t,...n})}calculateContentLength(t){if(typeof t=="string"){if(typeof Buffer<"u")return Buffer.byteLength(t,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(t).length.toString()}return null}buildRequest(t){var e;const{method:n,path:r,query:i,headers:c={}}=t,a=Ie(t.body)?t.body.body:t.body?JSON.stringify(t.body,null,2):null,d=this.calculateContentLength(a),u=this.buildURL(r,i);"timeout"in t&&qt("timeout",t.timeout);const l=t.timeout??this.timeout,o=t.httpAgent??this.httpAgent??ye(u),f=l+1e3;typeof((e=o==null?void 0:o.options)==null?void 0:e.timeout)=="number"&&f>(o.options.timeout??0)&&(o.options.timeout=f),this.idempotencyHeader&&n!=="get"&&(t.idempotencyKey||(t.idempotencyKey=this.defaultIdempotencyKey()),c[this.idempotencyHeader]=t.idempotencyKey);const h={...d&&{"Content-Length":d},...this.defaultHeaders(t),...c};Ie(t.body)&&W!=="node"&&delete h["Content-Type"],Object.keys(h).forEach(g=>h[g]===null&&delete h[g]);const p={method:n,...a&&{body:a},headers:h,...o&&{agent:o},signal:t.signal??null};return this.validateHeaders(h,c),{req:p,url:u,timeout:l}}async prepareRequest(t,{url:e,options:n}){}parseHeaders(t){return t?Symbol.iterator in t?Object.fromEntries(Array.from(t).map(e=>[...e])):{...t}:{}}makeStatusError(t,e,n,r){return _.generate(t,e,n,r)}request(t,e=null){return new et(this.makeRequest(t,e))}async makeRequest(t,e){var n,r;const i=await t;e==null&&(e=i.maxRetries??this.maxRetries);const{req:c,url:a,timeout:d}=this.buildRequest(i);if(await this.prepareRequest(c,{url:a,options:i}),X("request",a,i,c.headers),(n=i.signal)!=null&&n.aborted)throw new M;const u=new AbortController,l=await this.fetchWithTimeout(a,c,d,u).catch(Lt);if(l instanceof Error){if((r=i.signal)!=null&&r.aborted)throw new M;if(e)return this.retryRequest(i,e);throw l.name==="AbortError"?new Nt:new Z({cause:l})}const o=_s(l.headers);if(!l.ok){if(e&&this.shouldRetry(l))return this.retryRequest(i,e,o);const f=await l.text().catch(g=>Lt(g).message),h=Ps(f),p=h?void 0:f;throw X("response",l.status,a,o,p),this.makeStatusError(l.status,h,p,o)}return{response:l,options:i,controller:u}}requestAPIList(t,e){const n=this.makeRequest(e,null);return new vs(this,n,t)}buildURL(t,e){const n=Es(t)?new URL(t):new URL(this.baseURL+(this.baseURL.endsWith("/")&&t.startsWith("/")?t.slice(1):t)),r=this.defaultQuery();return Le(r)||(e={...r,...e}),e&&(n.search=this.stringifyQuery(e)),n.toString()}stringifyQuery(t){return Object.entries(t).filter(([e,n])=>typeof n<"u").map(([e,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(e)}=`;throw new y(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(t,e,n,r){const{signal:i,...c}=e||{};i&&i.addEventListener("abort",()=>r.abort());const a=setTimeout(()=>r.abort(),n);return this.getRequestClient().fetch.call(void 0,t,{signal:r.signal,...c}).finally(()=>{clearTimeout(a)})}getRequestClient(){return{fetch:this.fetch}}shouldRetry(t){const e=t.headers.get("x-should-retry");return e==="true"?!0:e==="false"?!1:t.status===408||t.status===409||t.status===429||t.status>=500}async retryRequest(t,e,n){let r;const i=n==null?void 0:n["retry-after"];if(i){const c=parseInt(i);Number.isNaN(c)?r=Date.parse(i)-Date.now():r=c*1e3}if(!r||!Number.isInteger(r)||r<=0||r>60*1e3){const c=t.maxRetries??this.maxRetries;r=this.calculateDefaultRetryTimeoutMillis(e,c)}return await Me(r),this.makeRequest(t,e-1)}calculateDefaultRetryTimeoutMillis(t,e){const n=e-t,r=Math.min(.5*Math.pow(2,n),8),i=1-Math.random()*.25;return r*i*1e3}getUserAgent(){return`${this.constructor.name}/JS ${$}`}}class ke{constructor(t,e,n,r){tt.set(this,void 0),ys(this,tt,t,"f"),this.options=r,this.response=e,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const t=this.nextPageInfo();if(!t)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const e={...this.options};if("params"in t)e.query={...e.query,...t.params};else if("url"in t){const n=[...Object.entries(e.query||{}),...t.url.searchParams.entries()];for(const[r,i]of n)t.url.searchParams.set(r,i);e.query=void 0,e.path=t.url.toString()}return await ws(this,tt,"f").requestAPIList(this.constructor,e)}async*iterPages(){let t=this;for(yield t;t.hasNextPage();)t=await t.getNextPage(),yield t}async*[(tt=new WeakMap,Symbol.asyncIterator)](){for await(const t of this.iterPages())for(const e of t.getPaginatedItems())yield e}}class vs extends et{constructor(t,e,n){super(e,async r=>new n(t,r.response,await Te(r),r.options))}async*[Symbol.asyncIterator](){const t=await this;for await(const e of t)yield e}}const _s=s=>new Proxy(Object.fromEntries(s.entries()),{get(t,e){const n=e.toString();return t[n.toLowerCase()]||t[n]}}),xs={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__binaryResponse:!0},j=s=>typeof s=="object"&&s!==null&&!Le(s)&&Object.keys(s).every(t=>$s(xs,t)),Ss=()=>{if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$,"X-Stainless-OS":Ne(Deno.build.os),"X-Stainless-Arch":Fe(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":Deno.version};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$,"X-Stainless-OS":Ne(process.platform),"X-Stainless-Arch":Fe(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const s=Os();return s?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":$,"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":$,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Os(){if(typeof navigator>"u"||!navigator)return null;const 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(const{key:t,pattern:e}of s){const n=e.exec(navigator.userAgent);if(n){const r=n[1]||0,i=n[2]||0,c=n[3]||0;return{browser:t,version:`${r}.${i}.${c}`}}}return null}const Fe=s=>s==="x32"?"x32":s==="x86_64"||s==="x64"?"x64":s==="arm"?"arm":s==="aarch64"||s==="arm64"?"arm64":s?`other:${s}`:"unknown",Ne=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");let Be;const As=()=>Be??(Be=Ss()),Ps=s=>{try{return JSON.parse(s)}catch{return}},Rs=new RegExp("^(?:[a-z]+:)?//","i"),Es=s=>Rs.test(s),Me=s=>new Promise(t=>setTimeout(t,s)),qt=(s,t)=>{if(typeof t!="number"||!Number.isInteger(t))throw new y(`${s} must be an integer`);if(t<0)throw new y(`${s} must be a positive integer`);return t},Lt=s=>s instanceof Error?s:new Error(s),qe=s=>{var t,e,n;if(typeof process<"u")return((t=process.env)==null?void 0:t[s])??void 0;if(typeof Deno<"u")return(n=(e=Deno.env)==null?void 0:e.get)==null?void 0:n.call(e,s)};function Le(s){if(!s)return!0;for(const t in s)return!1;return!0}function $s(s,t){return Object.prototype.hasOwnProperty.call(s,t)}function X(s,...t){typeof process<"u"&&process.env.DEBUG==="true"&&console.log(`OpenAI:DEBUG:${s}`,...t)}const js=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,s=>{const t=Math.random()*16|0;return(s==="x"?t:t&3|8).toString(16)}),Cs=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";class st extends ke{constructor(t,e,n,r){super(t,e,n,r),this.data=n.data,this.object=n.object}getPaginatedItems(){return this.data}nextPageParams(){return null}nextPageInfo(){return null}}class k extends ke{constructor(t,e,n,r){super(t,e,n,r),this.data=n.data}getPaginatedItems(){return this.data}nextPageParams(){const t=this.nextPageInfo();if(!t)return null;if("params"in t)return t.params;const e=Object.fromEntries(t.url.searchParams);return Object.keys(e).length?e:null}nextPageInfo(){var t,e;if(!((t=this.data)!=null&&t.length))return null;const n=(e=this.data[this.data.length-1])==null?void 0:e.id;return n?{params:{after:n}}:null}}class w{constructor(t){this.client=t,this.get=t.get.bind(t),this.post=t.post.bind(t),this.patch=t.patch.bind(t),this.put=t.put.bind(t),this.delete=t.delete.bind(t),this.getAPIList=t.getAPIList.bind(t)}}let nt=class extends w{create(s,t){return this.post("/chat/completions",{body:s,...t,stream:s.stream??!1})}};nt||(nt={});let rt=class extends w{constructor(){super(...arguments),this.completions=new nt(this.client)}};(function(s){s.Completions=nt})(rt||(rt={}));class it extends w{create(t,e){return this.post("/audio/speech",{body:t,...e,__binaryResponse:!0})}}it||(it={});class ot extends w{create(t,e){return this.post("/audio/transcriptions",U({body:t,...e}))}}ot||(ot={});class at extends w{create(t,e){return this.post("/audio/translations",U({body:t,...e}))}}at||(at={});class ct extends w{constructor(){super(...arguments),this.transcriptions=new ot(this.client),this.translations=new at(this.client),this.speech=new it(this.client)}}(function(s){s.Transcriptions=ot,s.Translations=at,s.Speech=it})(ct||(ct={}));let lt=class extends w{create(s,t,e){return this.post(`/assistants/${s}/files`,{body:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}retrieve(s,t,e){return this.get(`/assistants/${s}/files/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}list(s,t={},e){return j(t)?this.list(s,{},t):this.getAPIList(`/assistants/${s}/files`,Dt,{query:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}del(s,t,e){return this.delete(`/assistants/${s}/files/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}};class Dt extends k{}(function(s){s.AssistantFilesPage=Dt})(lt||(lt={}));class ut extends w{constructor(){super(...arguments),this.files=new lt(this.client)}create(t,e){return this.post("/assistants",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}retrieve(t,e){return this.get(`/assistants/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}update(t,e,n){return this.post(`/assistants/${t}`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}list(t={},e){return j(t)?this.list({},t):this.getAPIList("/assistants",Jt,{query:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}del(t,e){return this.delete(`/assistants/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}}class Jt extends k{}(function(s){s.AssistantsPage=Jt,s.Files=lt,s.AssistantFilesPage=Dt})(ut||(ut={}));function De(s){return typeof s.parse=="function"}const K=s=>(s==null?void 0:s.role)==="assistant",Je=s=>(s==null?void 0:s.role)==="function",Is=s=>(s==null?void 0:s.role)==="tool";var R=globalThis&&globalThis.__classPrivateFieldSet||function(s,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?s!==t||!r:!t.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(s,e):r?r.value=e:t.set(s,e),e},m=globalThis&&globalThis.__classPrivateFieldGet||function(s,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?s!==t||!n:!t.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(s):n?n.value:t.get(s)},x,ht,dt,H,V,ft,z,F,G,pt,mt,D,Wt,Ut,Xt,Kt,Ht,Vt,We,zt;const Ue=10;class Xe{constructor(){x.add(this),this.controller=new AbortController,ht.set(this,void 0),dt.set(this,()=>{}),H.set(this,()=>{}),V.set(this,void 0),ft.set(this,()=>{}),z.set(this,()=>{}),F.set(this,{}),this._chatCompletions=[],this.messages=[],G.set(this,!1),pt.set(this,!1),mt.set(this,!1),D.set(this,!1),Vt.set(this,t=>{if(R(this,pt,!0,"f"),t instanceof Error&&t.name==="AbortError"&&(t=new M),t instanceof M)return R(this,mt,!0,"f"),this._emit("abort",t);if(t instanceof y)return this._emit("error",t);if(t instanceof Error){const e=new y(t.message);return e.cause=t,this._emit("error",e)}return this._emit("error",new y(String(t)))}),R(this,ht,new Promise((t,e)=>{R(this,dt,t,"f"),R(this,H,e,"f")}),"f"),R(this,V,new Promise((t,e)=>{R(this,ft,t,"f"),R(this,z,e,"f")}),"f"),m(this,ht,"f").catch(()=>{}),m(this,V,"f").catch(()=>{})}_run(t){setTimeout(()=>{t().then(()=>{this._emitFinal(),this._emit("end")},m(this,Vt,"f"))},0)}_addChatCompletion(t){var e;this._chatCompletions.push(t),this._emit("chatCompletion",t);const n=(e=t.choices[0])==null?void 0:e.message;return n&&this._addMessage(n),t}_addMessage(t,e=!0){if(this.messages.push(t),e){if(this._emit("message",t),(Je(t)||Is(t))&&t.content)this._emit("functionCallResult",t.content);else if(K(t)&&t.function_call)this._emit("functionCall",t.function_call);else if(K(t)&&t.tool_calls)for(const n of t.tool_calls)n.type==="function"&&this._emit("functionCall",n.function)}}_connected(){this.ended||(m(this,dt,"f").call(this),this._emit("connect"))}get ended(){return m(this,G,"f")}get errored(){return m(this,pt,"f")}get aborted(){return m(this,mt,"f")}abort(){this.controller.abort()}on(t,e){return(m(this,F,"f")[t]||(m(this,F,"f")[t]=[])).push({listener:e}),this}off(t,e){const n=m(this,F,"f")[t];if(!n)return this;const r=n.findIndex(i=>i.listener===e);return r>=0&&n.splice(r,1),this}once(t,e){return(m(this,F,"f")[t]||(m(this,F,"f")[t]=[])).push({listener:e,once:!0}),this}emitted(t){return new Promise((e,n)=>{R(this,D,!0,"f"),t!=="error"&&this.once("error",n),this.once(t,e)})}async done(){R(this,D,!0,"f"),await m(this,V,"f")}async finalChatCompletion(){await this.done();const t=this._chatCompletions[this._chatCompletions.length-1];if(!t)throw new y("stream ended without producing a ChatCompletion");return t}async finalContent(){return await this.done(),m(this,x,"m",Wt).call(this)}async finalMessage(){return await this.done(),m(this,x,"m",Ut).call(this)}async finalFunctionCall(){return await this.done(),m(this,x,"m",Xt).call(this)}async finalFunctionCallResult(){return await this.done(),m(this,x,"m",Kt).call(this)}async totalUsage(){return await this.done(),m(this,x,"m",Ht).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emit(t,...e){if(m(this,G,"f"))return;t==="end"&&(R(this,G,!0,"f"),m(this,ft,"f").call(this));const n=m(this,F,"f")[t];if(n&&(m(this,F,"f")[t]=n.filter(r=>!r.once),n.forEach(({listener:r})=>r(...e))),t==="abort"){const r=e[0];!m(this,D,"f")&&!(n!=null&&n.length)&&Promise.reject(r),m(this,H,"f").call(this,r),m(this,z,"f").call(this,r),this._emit("end");return}if(t==="error"){const r=e[0];!m(this,D,"f")&&!(n!=null&&n.length)&&Promise.reject(r),m(this,H,"f").call(this,r),m(this,z,"f").call(this,r),this._emit("end")}}_emitFinal(){const t=this._chatCompletions[this._chatCompletions.length-1];t&&this._emit("finalChatCompletion",t);const e=this.messages[this.messages.length-1];e&&this._emit("finalMessage",e);const n=m(this,x,"m",Wt).call(this);n&&this._emit("finalContent",n);const r=m(this,x,"m",Xt).call(this);r&&this._emit("finalFunctionCall",r);const i=m(this,x,"m",Kt).call(this);i!=null&&this._emit("finalFunctionCallResult",i),this._chatCompletions.some(c=>c.usage)&&this._emit("totalUsage",m(this,x,"m",Ht).call(this))}async _createChatCompletion(t,e,n){const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),m(this,x,"m",We).call(this,e);const i=await t.create({...e,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(i)}async _runChatCompletion(t,e,n){for(const r of e.messages)this._addMessage(r,!1);return await this._createChatCompletion(t,e,n)}async _runFunctions(t,e,n){var r;const i="function",{function_call:c="auto",stream:a,...d}=e,u=typeof c!="string"&&(c==null?void 0:c.name),{maxChatCompletions:l=Ue}=n||{},o={};for(const h of e.functions)o[h.name||h.function.name]=h;const f=e.functions.map(h=>({name:h.name||h.function.name,parameters:h.parameters,description:h.description}));for(const h of e.messages)this._addMessage(h,!1);for(let h=0;h<l;++h){const p=(r=(await this._createChatCompletion(t,{...d,function_call:c,functions:f,messages:[...this.messages]},n)).choices[0])==null?void 0:r.message;if(!p)throw new y("missing message in ChatCompletion response");if(!p.function_call)return;const{name:g,arguments:b}=p.function_call,S=o[g];if(S){if(u&&u!==g){const I=`Invalid function_call: ${JSON.stringify(g)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:i,name:g,content:I});continue}}else{const I=`Invalid function_call: ${JSON.stringify(g)}. Available options are: ${f.map(ue=>JSON.stringify(ue.name)).join(", ")}. Please try again`;this._addMessage({role:i,name:g,content:I});continue}let O;try{O=De(S)?await S.parse(b):b}catch(I){this._addMessage({role:i,name:g,content:I instanceof Error?I.message:String(I)});continue}const P=await S.function(O,this),A=m(this,x,"m",zt).call(this,P);if(this._addMessage({role:i,name:g,content:A}),u)return}}async _runTools(t,e,n){var r,i;const c="tool",{tool_choice:a="auto",stream:d,...u}=e,l=typeof a!="string"&&((r=a==null?void 0:a.function)==null?void 0:r.name),{maxChatCompletions:o=Ue}=n||{},f={};for(const p of e.tools)p.type==="function"&&(f[p.function.name||p.function.function.name]=p.function);const h="tools"in e?e.tools.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description}}:p):void 0;for(const p of e.messages)this._addMessage(p,!1);for(let p=0;p<o;++p){const g=(i=(await this._createChatCompletion(t,{...u,tool_choice:a,tools:h,messages:[...this.messages]},n)).choices[0])==null?void 0:i.message;if(!g)throw new y("missing message in ChatCompletion response");if(!g.tool_calls)return;for(const b of g.tool_calls){if(b.type!=="function")continue;const S=b.id,{name:O,arguments:P}=b.function,A=f[O];if(A){if(l&&l!==O){const L=`Invalid tool_call: ${JSON.stringify(O)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:c,tool_call_id:S,content:L});continue}}else{const L=`Invalid tool_call: ${JSON.stringify(O)}. Available options are: ${h.map(he=>JSON.stringify(he.function.name)).join(", ")}. Please try again`;this._addMessage({role:c,tool_call_id:S,content:L});continue}let I;try{I=De(A)?await A.parse(P):P}catch(L){const he=L instanceof Error?L.message:String(L);this._addMessage({role:c,tool_call_id:S,content:he});continue}const ue=await A.function(I,this),Ks=m(this,x,"m",zt).call(this,ue);if(this._addMessage({role:c,tool_call_id:S,content:Ks}),l)return}}}}ht=new WeakMap,dt=new WeakMap,H=new WeakMap,V=new WeakMap,ft=new WeakMap,z=new WeakMap,F=new WeakMap,G=new WeakMap,pt=new WeakMap,mt=new WeakMap,D=new WeakMap,Vt=new WeakMap,x=new WeakSet,Wt=function(){return m(this,x,"m",Ut).call(this).content},Ut=function(){let s=this.messages.length;for(;s-- >0;){const t=this.messages[s];if(K(t))return t}throw new y("stream ended without producing a ChatCompletionMessage with role=assistant")},Xt=function(){for(let s=this.messages.length-1;s>=0;s--){const t=this.messages[s];if(K(t)&&t!=null&&t.function_call)return t.function_call}},Kt=function(){for(let s=this.messages.length-1;s>=0;s--){const t=this.messages[s];if(Je(t)&&t.content!=null)return t.content}},Ht=function(){const s={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(s.completion_tokens+=t.completion_tokens,s.prompt_tokens+=t.prompt_tokens,s.total_tokens+=t.total_tokens);return s},We=function(s){if(s.n!=null&&s.n>1)throw new y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},zt=function(s){return typeof s=="string"?s:s===void 0?"undefined":JSON.stringify(s)};class Q extends Xe{static runFunctions(t,e,n){const r=new Q;return r._run(()=>r._runFunctions(t,e,n)),r}static runTools(t,e,n){const r=new Q;return r._run(()=>r._runTools(t,e,n)),r}_addMessage(t){super._addMessage(t),K(t)&&t.content&&this._emit("content",t.content)}}var E=globalThis&&globalThis.__classPrivateFieldGet||function(s,t,e,n){if(e==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof t=="function"?s!==t||!n:!t.has(s))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?n:e==="a"?n.call(s):n?n.value:t.get(s)},Gt=globalThis&&globalThis.__classPrivateFieldSet||function(s,t,e,n,r){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof t=="function"?s!==t||!r:!t.has(s))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?r.call(s,e):r?r.value=e:t.set(s,e),e},C,B,Qt,Yt,gt,Ke;class Y extends Xe{constructor(){super(...arguments),C.add(this),B.set(this,void 0)}get currentChatCompletionSnapshot(){return E(this,B,"f")}static fromReadableStream(t){const e=new Y;return e._run(()=>e._fromReadableStream(t)),e}static createChatCompletion(t,e,n){const r=new Y;return r._run(()=>r._runChatCompletion(t,{...e,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(t,e,n){var r;const i=n==null?void 0:n.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),E(this,C,"m",Qt).call(this);const c=await t.create({...e,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const a of c)E(this,C,"m",Yt).call(this,a);if((r=c.controller.signal)!=null&&r.aborted)throw new M;return this._addChatCompletion(E(this,C,"m",gt).call(this))}async _fromReadableStream(t,e){var n;const r=e==null?void 0:e.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),E(this,C,"m",Qt).call(this),this._connected();const i=N.fromReadableStream(t,this.controller);let c;for await(const a of i)c&&c!==a.id&&this._addChatCompletion(E(this,C,"m",gt).call(this)),E(this,C,"m",Yt).call(this,a),c=a.id;if((n=i.controller.signal)!=null&&n.aborted)throw new M;return this._addChatCompletion(E(this,C,"m",gt).call(this))}[(B=new WeakMap,C=new WeakSet,Qt=function(){this.ended||Gt(this,B,void 0,"f")},Yt=function(t){var e,n,r;if(this.ended)return;const i=E(this,C,"m",Ke).call(this,t);this._emit("chunk",t,i);const c=(n=(e=t.choices[0])==null?void 0:e.delta)==null?void 0:n.content,a=(r=i.choices[0])==null?void 0:r.message;c!=null&&(a==null?void 0:a.role)==="assistant"&&a!=null&&a.content&&this._emit("content",c,a.content)},gt=function(){if(this.ended)throw new y("stream has ended, this shouldn't happen");const t=E(this,B,"f");if(!t)throw new y("request ended without sending any chunks");return Gt(this,B,void 0,"f"),Ts(t)},Ke=function(t){var e,n;let r=E(this,B,"f");const{choices:i,...c}=t;r?Object.assign(r,c):r=Gt(this,B,{...c,choices:[]},"f");for(const{delta:a,finish_reason:d,index:u,...l}of t.choices){let o=r.choices[u];if(!o){r.choices[u]={finish_reason:d,index:u,message:a,...l};continue}if(d&&(o.finish_reason=d),Object.assign(o,l),!a)continue;const{content:f,function_call:h,role:p,tool_calls:g}=a;if(f&&(o.message.content=(o.message.content||"")+f),p&&(o.message.role=p),h&&(o.message.function_call?(h.name&&(o.message.function_call.name=h.name),h.arguments&&((e=o.message.function_call).arguments??(e.arguments=""),o.message.function_call.arguments+=h.arguments)):o.message.function_call=h),g){o.message.tool_calls||(o.message.tool_calls=[]);for(const{index:b,id:S,type:O,function:P}of g){const A=(n=o.message.tool_calls)[b]??(n[b]={});S&&(A.id=S),O&&(A.type=O),P&&(A.function??(A.function={arguments:""})),P!=null&&P.name&&(A.function.name=P.name),P!=null&&P.arguments&&(A.function.arguments+=P.arguments)}}}return r},Symbol.asyncIterator)](){const t=[],e=[];let n=!1;return this.on("chunk",r=>{const i=e.shift();i?i(r):t.push(r)}),this.on("end",()=>{n=!0;for(const r of e)r(void 0);e.length=0}),{next:async()=>t.length?{value:t.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise(r=>e.push(r)).then(r=>r?{value:r,done:!1}:{value:void 0,done:!0})}}toReadableStream(){return new N(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Ts(s){const{id:t,choices:e,created:n,model:r}=s;return{id:t,choices:e.map(({message:i,finish_reason:c,index:a})=>{if(!c)throw new y(`missing finish_reason for choice ${a}`);const{content:d=null,function_call:u,tool_calls:l}=i,o=i.role;if(!o)throw new y(`missing role for choice ${a}`);if(u){const{arguments:f,name:h}=u;if(f==null)throw new y(`missing function_call.arguments for choice ${a}`);if(!h)throw new y(`missing function_call.name for choice ${a}`);return{message:{content:d,function_call:{arguments:f,name:h},role:o},finish_reason:c,index:a}}return l?{index:a,finish_reason:c,message:{role:o,content:d,tool_calls:l.map((f,h)=>{const{function:p,type:g,id:b}=f,{arguments:S,name:O}=p||{};if(b==null)throw new y(`missing choices[${a}].tool_calls[${h}].id
${yt(s)}`);if(g==null)throw new y(`missing choices[${a}].tool_calls[${h}].type
${yt(s)}`);if(O==null)throw new y(`missing choices[${a}].tool_calls[${h}].function.name
${yt(s)}`);if(S==null)throw new y(`missing choices[${a}].tool_calls[${h}].function.arguments
${yt(s)}`);return{id:b,type:g,function:{name:O,arguments:S}}})}}:{message:{content:d,role:o},finish_reason:c,index:a}}),created:n,model:r,object:"chat.completion"}}function yt(s){return JSON.stringify(s)}class J extends Y{static fromReadableStream(t){const e=new J;return e._run(()=>e._fromReadableStream(t)),e}static runFunctions(t,e,n){const r=new J;return r._run(()=>r._runFunctions(t,e,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}})),r}static runTools(t,e,n){const r=new J;return r._run(()=>r._runTools(t,e,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}})),r}}let He=class extends w{runFunctions(s,t){return s.stream?J.runFunctions(this.client.chat.completions,s,t):Q.runFunctions(this.client.chat.completions,s,t)}runTools(s,t){return s.stream?J.runTools(this.client.chat.completions,s,t):Q.runTools(this.client.chat.completions,s,t)}stream(s,t){return Y.createChatCompletion(this.client.chat.completions,s,t)}};class wt extends w{constructor(){super(...arguments),this.completions=new He(this.client)}}(function(s){s.Completions=He})(wt||(wt={}));let bt=class extends w{retrieve(s,t,e,n){return this.get(`/threads/${s}/messages/${t}/files/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}list(s,t,e={},n){return j(e)?this.list(s,t,{},e):this.getAPIList(`/threads/${s}/messages/${t}/files`,Zt,{query:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}};class Zt extends k{}(function(s){s.MessageFilesPage=Zt})(bt||(bt={}));class vt extends w{constructor(){super(...arguments),this.files=new bt(this.client)}create(t,e,n){return this.post(`/threads/${t}/messages`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}retrieve(t,e,n){return this.get(`/threads/${t}/messages/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}update(t,e,n,r){return this.post(`/threads/${t}/messages/${e}`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(t,e={},n){return j(e)?this.list(t,{},e):this.getAPIList(`/threads/${t}/messages`,te,{query:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}}class te extends k{}(function(s){s.ThreadMessagesPage=te,s.Files=bt,s.MessageFilesPage=Zt})(vt||(vt={}));class _t extends w{retrieve(t,e,n,r){return this.get(`/threads/${t}/runs/${e}/steps/${n}`,{...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(t,e,n={},r){return j(n)?this.list(t,e,{},n):this.getAPIList(`/threads/${t}/runs/${e}/steps`,ee,{query:n,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}}class ee extends k{}(function(s){s.RunStepsPage=ee})(_t||(_t={}));class xt extends w{constructor(){super(...arguments),this.steps=new _t(this.client)}create(t,e,n){return this.post(`/threads/${t}/runs`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}retrieve(t,e,n){return this.get(`/threads/${t}/runs/${e}`,{...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}update(t,e,n,r){return this.post(`/threads/${t}/runs/${e}`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}list(t,e={},n){return j(e)?this.list(t,{},e):this.getAPIList(`/threads/${t}/runs`,se,{query:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}cancel(t,e,n){return this.post(`/threads/${t}/runs/${e}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}submitToolOutputs(t,e,n,r){return this.post(`/threads/${t}/runs/${e}/submit_tool_outputs`,{body:n,...r,headers:{"OpenAI-Beta":"assistants=v1",...r==null?void 0:r.headers}})}}class se extends k{}(function(s){s.RunsPage=se,s.Steps=_t,s.RunStepsPage=ee})(xt||(xt={}));class St extends w{constructor(){super(...arguments),this.runs=new xt(this.client),this.messages=new vt(this.client)}create(t={},e){return j(t)?this.create({},t):this.post("/threads",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}retrieve(t,e){return this.get(`/threads/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}update(t,e,n){return this.post(`/threads/${t}`,{body:e,...n,headers:{"OpenAI-Beta":"assistants=v1",...n==null?void 0:n.headers}})}del(t,e){return this.delete(`/threads/${t}`,{...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}createAndRun(t,e){return this.post("/threads/runs",{body:t,...e,headers:{"OpenAI-Beta":"assistants=v1",...e==null?void 0:e.headers}})}}(function(s){s.Runs=xt,s.RunsPage=se,s.Messages=vt,s.ThreadMessagesPage=te})(St||(St={}));class Ot extends w{constructor(){super(...arguments),this.chat=new wt(this.client),this.assistants=new ut(this.client),this.threads=new St(this.client)}}(function(s){s.Chat=wt,s.Assistants=ut,s.AssistantsPage=Jt,s.Threads=St})(Ot||(Ot={}));class At extends w{create(t,e){return this.post("/completions",{body:t,...e,stream:t.stream??!1})}}At||(At={});class Pt extends w{create(t,e){return this.post("/embeddings",{body:t,...e})}}Pt||(Pt={});class Rt extends w{create(t,e){return this.post("/edits",{body:t,...e})}}Rt||(Rt={});class Et extends w{create(t,e){return this.post("/files",U({body:t,...e}))}retrieve(t,e){return this.get(`/files/${t}`,e)}list(t={},e){return j(t)?this.list({},t):this.getAPIList("/files",ne,{query:t,...e})}del(t,e){return this.delete(`/files/${t}`,e)}content(t,e){return this.get(`/files/${t}/content`,{...e,__binaryResponse:!0})}retrieveContent(t,e){return this.get(`/files/${t}/content`,{...e,headers:{Accept:"application/json",...e==null?void 0:e.headers}})}async waitForProcessing(t,{pollInterval:e=5e3,maxWait:n=30*60*1e3}={}){const r=new Set(["processed","error","deleted"]),i=Date.now();let c=await this.retrieve(t);for(;!c.status||!r.has(c.status);)if(await Me(e),c=await this.retrieve(t),Date.now()-i>n)throw new Nt({message:`Giving up on waiting for file ${t} to finish processing after ${n} milliseconds.`});return c}}class ne extends st{}(function(s){s.FileObjectsPage=ne})(Et||(Et={}));class $t extends w{create(t,e){return this.post("/fine-tunes",{body:t,...e})}retrieve(t,e){return this.get(`/fine-tunes/${t}`,e)}list(t){return this.getAPIList("/fine-tunes",re,t)}cancel(t,e){return this.post(`/fine-tunes/${t}/cancel`,e)}listEvents(t,e,n){return this.get(`/fine-tunes/${t}/events`,{query:e,timeout:864e5,...n,stream:(e==null?void 0:e.stream)??!1})}}class re extends st{}(function(s){s.FineTunesPage=re})($t||($t={}));class jt extends w{create(t,e){return this.post("/fine_tuning/jobs",{body:t,...e})}retrieve(t,e){return this.get(`/fine_tuning/jobs/${t}`,e)}list(t={},e){return j(t)?this.list({},t):this.getAPIList("/fine_tuning/jobs",ie,{query:t,...e})}cancel(t,e){return this.post(`/fine_tuning/jobs/${t}/cancel`,e)}listEvents(t,e={},n){return j(e)?this.listEvents(t,{},e):this.getAPIList(`/fine_tuning/jobs/${t}/events`,oe,{query:e,...n})}}class ie extends k{}class oe extends k{}(function(s){s.FineTuningJobsPage=ie,s.FineTuningJobEventsPage=oe})(jt||(jt={}));class Ct extends w{constructor(){super(...arguments),this.jobs=new jt(this.client)}}(function(s){s.Jobs=jt,s.FineTuningJobsPage=ie,s.FineTuningJobEventsPage=oe})(Ct||(Ct={}));class It extends w{createVariation(t,e){return this.post("/images/variations",U({body:t,...e}))}edit(t,e){return this.post("/images/edits",U({body:t,...e}))}generate(t,e){return this.post("/images/generations",{body:t,...e})}}It||(It={});class Tt extends w{retrieve(t,e){return this.get(`/models/${t}`,e)}list(t){return this.getAPIList("/models",ae,t)}del(t,e){return this.delete(`/models/${t}`,e)}}class ae extends st{}(function(s){s.ModelsPage=ae})(Tt||(Tt={}));class kt extends w{create(t,e){return this.post("/moderations",{body:t,...e})}}kt||(kt={});var Ve;class v extends bs{constructor({apiKey:t=qe("OPENAI_API_KEY"),organization:e=qe("OPENAI_ORG_ID")??null,...n}={}){if(t===void 0)throw new y("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const r={apiKey:t,organization:e,...n,baseURL:n.baseURL??"https://api.openai.com/v1"};if(!r.dangerouslyAllowBrowser&&Cs())throw new y(`It looks like you're running in a browser-like environment.

@@ -17,2 +17,2 @@ This is disabled by default, as it risks exposing your secret API credentials to attackers.

https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);super({baseURL:r.baseURL,timeout:r.timeout??6e5,httpAgent:r.httpAgent,maxRetries:r.maxRetries,fetch:r.fetch}),this.completions=new Pt(this),this.chat=new it(this),this.edits=new $t(this),this.embeddings=new Rt(this),this.files=new jt(this),this.images=new kt(this),this.audio=new ut(this),this.moderations=new Nt(this),this.models=new Ft(this),this.fineTuning=new Tt(this),this.fineTunes=new Ct(this),this.beta=new Et(this),this._options=r,this.apiKey=t,this.organization=e}defaultQuery(){return this._options.defaultQuery}defaultHeaders(t){return{...super.defaultHeaders(t),"OpenAI-Organization":this.organization,...this._options.defaultHeaders}}authHeaders(t){return{Authorization:`Bearer ${this.apiKey}`}}}ze=v,v.OpenAI=ze,v.OpenAIError=y,v.APIError=_,v.APIConnectionError=et,v.APIConnectionTimeoutError=Bt,v.APIUserAbortError=M,v.NotFoundError=Oe,v.ConflictError=Ae,v.RateLimitError=Pe,v.BadRequestError=_e,v.AuthenticationError=xe,v.InternalServerError=Re,v.PermissionDeniedError=Se,v.UnprocessableEntityError=Ee,function(s){s.toFile=Ie,s.fileFromPath=be,s.Page=rt,s.CursorPage=T,s.Completions=Pt,s.Chat=it,s.Edits=$t,s.Embeddings=Rt,s.Files=jt,s.FileObjectsPage=oe,s.Images=kt,s.Audio=ut,s.Moderations=Nt,s.Models=Ft,s.ModelsPage=le,s.FineTuning=Tt,s.FineTunes=Ct,s.FineTunesPage=ie,s.Beta=Et}(v||(v={}));const Ns=v;let Ge="";const Ms=s=>{Ge=s},ue=()=>new Ns({apiKey:Ge,dangerouslyAllowBrowser:!0}),Bs=s=>{if(!s.openAiToken)throw new Error("OpenAI token is required");Ms(s.openAiToken)};function Qe(s){return s&&s.constructor&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)}function Ye(s){return s}function Ze(s,t){t=t||{};const e=t.delimiter||".",n=t.maxDepth,r=t.transformKey||Ye,o={};function c(a,d,u){u=u||1,Object.keys(a).forEach(function(l){const i=a[l],f=t.safe&&Array.isArray(i),h=Object.prototype.toString.call(i),p=Qe(i),g=h==="[object Object]"||h==="[object Array]",b=d?d+e+r(l):r(l);if(!f&&!p&&g&&Object.keys(i).length&&(!t.maxDepth||u<n))return c(i,b,u+1);o[b]=i})}return c(s),o}function ts(s,t){t=t||{};const e=t.delimiter||".",n=t.overwrite||!1,r=t.transformKey||Ye,o={};if(Qe(s)||Object.prototype.toString.call(s)!=="[object Object]")return s;function c(u){const l=Number(u);return isNaN(l)||u.indexOf(".")!==-1||t.object?u:l}function a(u,l,i){return Object.keys(i).reduce(function(f,h){return f[u+e+h]=i[h],f},l)}function d(u){const l=Object.prototype.toString.call(u),i=l==="[object Array]",f=l==="[object Object]";if(u){if(i)return!u.length;if(f)return!Object.keys(u).length}else return!0}return s=Object.keys(s).reduce(function(u,l){const i=Object.prototype.toString.call(s[l]);return!(i==="[object Object]"||i==="[object Array]")||d(s[l])?(u[l]=s[l],u):a(l,u,Ze(s[l],t))},{}),Object.keys(s).forEach(function(u){const l=u.split(e).map(r);let i=c(l.shift()),f=c(l[0]),h=o;for(;f!==void 0;){if(i==="__proto__")return;const p=Object.prototype.toString.call(h[i]),g=p==="[object Object]"||p==="[object Array]";if(!n&&!g&&typeof h[i]<"u")return;(n&&!g||!n&&h[i]==null)&&(h[i]=typeof f=="number"&&!t.object?[]:{}),h=h[i],l.length>0&&(i=c(l.shift()),f=c(l[0]))}h[i]=ts(s[u],t)}),o}const qs=async({currentLanguage:s,targetLanguage:t,valuesToTranslate:e,promptModifier:n=""})=>{const r=ue();if(!r)throw new Error("OpenAI client is not configurated");return await r.chat.completions.create({messages:[{role:"system",content:`Translate the values from the JSON array that the user will send you ${s?" from "+s:""} into ${t}. Return a new array containing only the translations, with their order remaining unchanged. Result should follow this structure: {translations: [string, string, string]}.`},{role:"system",content:n},{role:"user",content:JSON.stringify(e)}],model:"gpt-3.5-turbo-1106",temperature:0,top_p:1,frequency_penalty:0,presence_penalty:0,response_format:{type:"json_object"}}).then(o=>JSON.parse(o.choices[0].message.content).translations)},es=async({targetLanguage:s,currentLanguage:t,content:e,isFlat:n=!1,promptModifier:r=""})=>{let o;if(typeof e=="object"&&!n&&(o=Ze(e)),!o&&!n)throw new Error("The provided data is not a valid");n&&(o=e);const c=Object.values(o);console.log("valuesToTranslate",c);const a=Object.keys(o);console.log("keys",a);try{const d=await qs({currentLanguage:t,targetLanguage:s,valuesToTranslate:c,promptModifier:r});console.log("chatCompletion",d);const u=a.reduce((l,i,f)=>({...l,[i]:d[f]}),{});return console.log("translatedObject",u),JSON.stringify(n?u:ts(u))}catch{throw new Error("Failed to translate JSON")}},Ds=async({content:s,contentTitle:t,promptModifier:e=""})=>{const n=ue();if(!n)throw new Error("OpenAI client is not configurated");let r=!1;try{JSON.parse(JSON.stringify(s)),r=!0}catch{console.info("Content is not a valid JSON")}try{return(await n.chat.completions.create({messages:[{role:"system",content:`You will be provided with ${r?"a JSON titled":"an text titled"} '${t}'. Could you provide a detailed summary focusing on the main described things and with an attention to details? Maintain the original text style without alterations. Result should not contain any information about the content type itself. ${e}`},{role:"user",content:JSON.stringify(s)}],model:"gpt-3.5-turbo-1106",temperature:.3,top_p:1,frequency_penalty:0,presence_penalty:0,response_format:{type:"text"}})).choices[0].message.content}catch{throw new Error("Failed to translate JSON")}},Ls=async({content:s,contentTitle:t,tags:e,promptModifier:n="",resultAmount:r=5})=>{const o=ue();if(!o)throw new Error("OpenAI client is not configurated");let c=!1;try{JSON.parse(JSON.stringify(s)),c=!0}catch{console.info("Content is not a valid JSON")}try{const a=await o.chat.completions.create({messages:[{role:"system",content:`You will be provided with ${c?"a JSON titled":"a text titled"} '${t}'. ${n}`},{role:"user",content:JSON.stringify(s)},{role:"user",content:`Find all tags relevant to the provided text from the following list: ${JSON.stringify(e)}. Then sort these tags based on their relevance. Return a JSON object with only one key "tags", this should be an array of sorted tags. Tags should have exact the same format as they were provided. Return maximum ${r} tags.`}],model:"gpt-3.5-turbo-1106",temperature:0,top_p:1,frequency_penalty:0,presence_penalty:0,response_format:{type:"json_object"}});try{return JSON.parse(a.choices[0].message.content).tags.filter(d=>e.some(u=>u.id===d.id))}catch{throw new Error("Failed to parse result JSON")}}catch{throw new Error("Failed to apply tags")}},Js=async s=>{const t=tt();if(!t)throw new Error("Sanity client is not initialized");try{const e=await t.getDocument(s.documentId);if(!e)throw new Error("Document not found");const{_createdAt:n,_id:r,_rev:o,_type:c,_updatedAt:a,...d}=e;try{const u=await es({targetLanguage:s.targetLanguage,content:d,promptModifier:"Do not translate technical fields, they starts with a _ symbol. Translate only values with more than 1 word."});try{return JSON.parse(u)}catch{throw new Error("Failed to parse translated document")}}catch{throw new Error("Failed to translate document")}}catch{throw new Error("Document not found")}};function ss(s){return s&&s.constructor&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)}function ns(s){return s}function rs(s,t){t=t||{};const e=t.delimiter||".",n=t.maxDepth,r=t.transformKey||ns,o={};function c(a,d,u){u=u||1,Object.keys(a).forEach(function(l){const i=a[l],f=t.safe&&Array.isArray(i),h=Object.prototype.toString.call(i),p=ss(i),g=h==="[object Object]"||h==="[object Array]",b=d?d+e+r(l):r(l);if(!f&&!p&&g&&Object.keys(i).length&&(!t.maxDepth||u<n))return c(i,b,u+1);o[b]=i})}return c(s),o}function os(s,t){t=t||{};const e=t.delimiter||".",n=t.overwrite||!1,r=t.transformKey||ns,o={};if(ss(s)||Object.prototype.toString.call(s)!=="[object Object]")return s;function a(l){const i=Number(l);return isNaN(i)||l.indexOf(".")!==-1||t.object?l:i}function d(l,i,f){return Object.keys(f).reduce(function(h,p){return h[l+e+p]=f[p],h},i)}function u(l){const i=Object.prototype.toString.call(l),f=i==="[object Array]",h=i==="[object Object]";if(l){if(f)return!l.length;if(h)return!Object.keys(l).length}else return!0}return s=Object.keys(s).reduce(function(l,i){const f=Object.prototype.toString.call(s[i]);return!(f==="[object Object]"||f==="[object Array]")||u(s[i])?(l[i]=s[i],l):d(i,l,rs(s[i],t))},{}),Object.keys(s).forEach(function(l){const i=l.split(e).map(r);let f=a(i.shift()),h=a(i[0]),p=o;for(;h!==void 0;){if(f==="__proto__")return;const g=Object.prototype.toString.call(p[f]),b=g==="[object Object]"||g==="[object Array]";if(!n&&!b&&typeof p[f]<"u")return;(n&&!b||!n&&p[f]==null)&&(p[f]=typeof h=="number"&&!t.object?[]:{}),p=p[f],i.length>0&&(f=a(i.shift()),h=a(i[0]))}p[f]=os(s[l],t)}),o}const Ws=async({fieldNames:s,documentId:t,targetLanguage:e,newDocumentConfig:n})=>{const r=tt();if(!r)throw new Error("SDK not initialised");const o=await r.getDocument(t);if(!o)throw new Error(`Document with id ${t} not found`);const c=s.reduce((a,d)=>({...a,[d]:o[d]}),{});try{const a=rs(c),d=Object.keys(a).reduce((l,i)=>typeof a[i]=="string"&&(a[i].split(" ").length>1||i.split(".").pop()==="text"&&i.split(".").length>3)?{...l,[i]:a[i]}:l,{}),u=os({...a,...JSON.parse(await es({targetLanguage:e,content:d}))});if(n){const{_id:l,...i}=o;await r.create({...i,...u,[n.titleFieldName]:`${o[n.titleFieldName]} (${e})`,...n.additionalFields})}try{return u}catch{throw new Error("Failed to parse translated document")}}catch(a){throw console.error(a),new Error("Failed to translate document")}},Us=async s=>{const t=tt();if(!t)throw new Error("Sanity client is not initialized");try{const e=await t.getDocument(s.documentId);if(!e)throw new Error("Document not found");const{_createdAt:n,_id:r,_rev:o,_type:c,_updatedAt:a,...d}=e;try{return await Ls({content:d,promptModifier:"Do not work with technical fields of the data, they starts with a _ symbol.",tags:s.tags,contentTitle:s.contentTitle})}catch{throw new Error("Something went wrong")}}catch{throw new Error("Document not found")}},Xs=async s=>{const t=tt();if(!t)throw new Error("Sanity client is not initialized");try{const e=await t.getDocument(s.documentId);if(!e)throw new Error("Document not found");const{_createdAt:n,_id:r,_rev:o,_type:c,_updatedAt:a,...d}=e;try{return await Ds({content:d,promptModifier:"Do not work with technical fields of the data, they starts with a _ symbol. The content you provided with is a movie overview.",contentTitle:s.contentTitle})}catch{throw new Error("Failed to summarise document")}}catch{throw new Error("Document not found")}},Ks=s=>{is(s.client),Bs({openAiToken:s.openAiKey})};$.findRelevantTags=Us,$.initSDK=Ks,$.summariseDocument=Xs,$.transalateSelectedDocumentFields=Ws,$.translateFullDocument=Js,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})});
`);super({baseURL:r.baseURL,timeout:r.timeout??6e5,httpAgent:r.httpAgent,maxRetries:r.maxRetries,fetch:r.fetch}),this.completions=new At(this),this.chat=new rt(this),this.edits=new Rt(this),this.embeddings=new Pt(this),this.files=new Et(this),this.images=new It(this),this.audio=new ct(this),this.moderations=new kt(this),this.models=new Tt(this),this.fineTuning=new Ct(this),this.fineTunes=new $t(this),this.beta=new Ot(this),this._options=r,this.apiKey=t,this.organization=e}defaultQuery(){return this._options.defaultQuery}defaultHeaders(t){return{...super.defaultHeaders(t),"OpenAI-Organization":this.organization,...this._options.defaultHeaders}}authHeaders(t){return{Authorization:`Bearer ${this.apiKey}`}}}Ve=v,v.OpenAI=Ve,v.OpenAIError=y,v.APIError=_,v.APIConnectionError=Z,v.APIConnectionTimeoutError=Nt,v.APIUserAbortError=M,v.NotFoundError=Se,v.ConflictError=Oe,v.RateLimitError=Pe,v.BadRequestError=ve,v.AuthenticationError=_e,v.InternalServerError=Re,v.PermissionDeniedError=xe,v.UnprocessableEntityError=Ae,function(s){s.toFile=Ce,s.fileFromPath=we,s.Page=st,s.CursorPage=k,s.Completions=At,s.Chat=rt,s.Edits=Rt,s.Embeddings=Pt,s.Files=Et,s.FileObjectsPage=ne,s.Images=It,s.Audio=ct,s.Moderations=kt,s.Models=Tt,s.ModelsPage=ae,s.FineTuning=Ct,s.FineTunes=$t,s.FineTunesPage=re,s.Beta=Ot}(v||(v={}));const ks=v;let ze="";const Fs=s=>{ze=s},ce=()=>new ks({apiKey:ze,dangerouslyAllowBrowser:!0}),Ns=s=>{if(!s.openAiToken)throw new Error("OpenAI token is required");Fs(s.openAiToken)};function Ge(s){return s&&s.constructor&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)}function Qe(s){return s}function Ye(s,t){t=t||{};const e=t.delimiter||".",n=t.maxDepth,r=t.transformKey||Qe,i={};function c(a,d,u){u=u||1,Object.keys(a).forEach(function(l){const o=a[l],f=t.safe&&Array.isArray(o),h=Object.prototype.toString.call(o),p=Ge(o),g=h==="[object Object]"||h==="[object Array]",b=d?d+e+r(l):r(l);if(!f&&!p&&g&&Object.keys(o).length&&(!t.maxDepth||u<n))return c(o,b,u+1);i[b]=o})}return c(s),i}function Ze(s,t){t=t||{};const e=t.delimiter||".",n=t.overwrite||!1,r=t.transformKey||Qe,i={};if(Ge(s)||Object.prototype.toString.call(s)!=="[object Object]")return s;function c(u){const l=Number(u);return isNaN(l)||u.indexOf(".")!==-1||t.object?u:l}function a(u,l,o){return Object.keys(o).reduce(function(f,h){return f[u+e+h]=o[h],f},l)}function d(u){const l=Object.prototype.toString.call(u),o=l==="[object Array]",f=l==="[object Object]";if(u){if(o)return!u.length;if(f)return!Object.keys(u).length}else return!0}return s=Object.keys(s).reduce(function(u,l){const o=Object.prototype.toString.call(s[l]);return!(o==="[object Object]"||o==="[object Array]")||d(s[l])?(u[l]=s[l],u):a(l,u,Ye(s[l],t))},{}),Object.keys(s).forEach(function(u){const l=u.split(e).map(r);let o=c(l.shift()),f=c(l[0]),h=i;for(;f!==void 0;){if(o==="__proto__")return;const p=Object.prototype.toString.call(h[o]),g=p==="[object Object]"||p==="[object Array]";if(!n&&!g&&typeof h[o]<"u")return;(n&&!g||!n&&h[o]==null)&&(h[o]=typeof f=="number"&&!t.object?[]:{}),h=h[o],l.length>0&&(o=c(l.shift()),f=c(l[0]))}h[o]=Ze(s[u],t)}),i}const Bs=async({currentLanguage:s,targetLanguage:t,valuesToTranslate:e,promptModifier:n=""})=>{const r=ce();if(!r)throw new Error("OpenAI client is not configurated");return await r.chat.completions.create({messages:[{role:"system",content:`Translate the values from the JSON array that the user will send you ${s?" from "+s:""} into ${t}. Return a new array containing only the translations, with their order remaining unchanged. Result should follow this structure: {translations: [string, string, string]}.`},{role:"system",content:n},{role:"user",content:JSON.stringify(e)}],model:"gpt-3.5-turbo-1106",temperature:0,top_p:1,frequency_penalty:0,presence_penalty:0,response_format:{type:"json_object"}}).then(i=>JSON.parse(i.choices[0].message.content).translations)},Ms=async({targetLanguage:s,currentLanguage:t,content:e,isFlat:n=!1,promptModifier:r=""})=>{let i;if(typeof e=="object"&&!n&&(i=Ye(e)),!i&&!n)throw new Error("The provided data is not a valid");n&&(i=e);const c=Object.values(i);console.log("valuesToTranslate",c);const a=Object.keys(i);console.log("keys",a);try{const d=await Bs({currentLanguage:t,targetLanguage:s,valuesToTranslate:c,promptModifier:r});console.log("chatCompletion",d);const u=a.reduce((l,o,f)=>({...l,[o]:d[f]}),{});return console.log("translatedObject",u),JSON.stringify(n?u:Ze(u))}catch{throw new Error("Failed to translate JSON")}},qs=async({content:s,contentTitle:t,promptModifier:e=""})=>{const n=ce();if(!n)throw new Error("OpenAI client is not configurated");let r=!1;try{JSON.parse(JSON.stringify(s)),r=!0}catch{console.info("Content is not a valid JSON")}try{return(await n.chat.completions.create({messages:[{role:"system",content:`You will be provided with ${r?"a JSON titled":"an text titled"} '${t}'. Could you provide a detailed summary focusing on the main described things and with an attention to details? Maintain the original text style without alterations. Result should not contain any information about the content type itself. ${e}`},{role:"user",content:JSON.stringify(s)}],model:"gpt-3.5-turbo-1106",temperature:.3,top_p:1,frequency_penalty:0,presence_penalty:0,response_format:{type:"text"}})).choices[0].message.content}catch{throw new Error("Failed to translate JSON")}},Ls=async({content:s,contentTitle:t,tags:e,promptModifier:n="",resultAmount:r=5})=>{const i=ce();if(!i)throw new Error("OpenAI client is not configurated");let c=!1;try{JSON.parse(JSON.stringify(s)),c=!0}catch{console.info("Content is not a valid JSON")}try{const a=await i.chat.completions.create({messages:[{role:"system",content:`You will be provided with ${c?"a JSON titled":"a text titled"} '${t}'. ${n}`},{role:"user",content:JSON.stringify(s)},{role:"user",content:`Find all tags relevant to the provided text from the following list: ${JSON.stringify(e)}. Then sort these tags based on their relevance. Return a JSON object with only one key "tags", this should be an array of sorted tags. Tags should have exact the same format as they were provided. Return maximum ${r} tags.`}],model:"gpt-3.5-turbo-1106",temperature:0,top_p:1,frequency_penalty:0,presence_penalty:0,response_format:{type:"json_object"}});try{return JSON.parse(a.choices[0].message.content).tags.filter(d=>e.some(u=>u.id===d.id))}catch{throw new Error("Failed to parse result JSON")}}catch{throw new Error("Failed to apply tags")}};function ts(s){return s&&s.constructor&&typeof s.constructor.isBuffer=="function"&&s.constructor.isBuffer(s)}function es(s){return s}function ss(s,t){t=t||{};const e=t.delimiter||".",n=t.maxDepth,r=t.transformKey||es,i={};function c(a,d,u){u=u||1,Object.keys(a).forEach(function(l){const o=a[l],f=t.safe&&Array.isArray(o),h=Object.prototype.toString.call(o),p=ts(o),g=h==="[object Object]"||h==="[object Array]",b=d?d+e+r(l):r(l);if(!f&&!p&&g&&Object.keys(o).length&&(!t.maxDepth||u<n))return c(o,b,u+1);i[b]=o})}return c(s),i}function ns(s,t){t=t||{};const e=t.delimiter||".",n=t.overwrite||!1,r=t.transformKey||es,i={};if(ts(s)||Object.prototype.toString.call(s)!=="[object Object]")return s;function a(l){const o=Number(l);return isNaN(o)||l.indexOf(".")!==-1||t.object?l:o}function d(l,o,f){return Object.keys(f).reduce(function(h,p){return h[l+e+p]=f[p],h},o)}function u(l){const o=Object.prototype.toString.call(l),f=o==="[object Array]",h=o==="[object Object]";if(l){if(f)return!l.length;if(h)return!Object.keys(l).length}else return!0}return s=Object.keys(s).reduce(function(l,o){const f=Object.prototype.toString.call(s[o]);return!(f==="[object Object]"||f==="[object Array]")||u(s[o])?(l[o]=s[o],l):d(o,l,ss(s[o],t))},{}),Object.keys(s).forEach(function(l){const o=l.split(e).map(r);let f=a(o.shift()),h=a(o[0]),p=i;for(;h!==void 0;){if(f==="__proto__")return;const g=Object.prototype.toString.call(p[f]),b=g==="[object Object]"||g==="[object Array]";if(!n&&!b&&typeof p[f]<"u")return;(n&&!b||!n&&p[f]==null)&&(p[f]=typeof h=="number"&&!t.object?[]:{}),p=p[f],o.length>0&&(f=a(o.shift()),h=a(o[0]))}p[f]=ns(s[l],t)}),i}let rs=null;const Ds=s=>{rs=s},le=()=>rs,Js=async({fieldNames:s,documentId:t,targetLanguage:e,newDocumentConfig:n})=>{const r=le();if(!r)throw new Error("SDK not initialised");const i=await r.getDocument(t);if(!i)throw new Error(`Document with id ${t} not found`);const c=s.reduce((a,d)=>({...a,[d]:i[d]}),{});try{const a=ss(c),d=Object.keys(a).reduce((l,o)=>typeof a[o]=="string"&&(a[o].split(" ").length>1||o.split(".").pop()==="text"&&o.split(".").length>3)?{...l,[o]:a[o]}:l,{}),u=ns({...a,...JSON.parse(await Ms({targetLanguage:e,content:d}))});if(n){const{_id:l,...o}=i;await r.create({...o,...u,[n.titleFieldName]:`${i[n.titleFieldName]} (${e})`,...n.additionalFields})}try{return u}catch{throw new Error("Failed to parse translated document")}}catch(a){throw console.error(a),new Error("Failed to translate document")}},Ws=async s=>{const t=le();if(!t)throw new Error("Sanity client is not initialized");try{const e=await t.getDocument(s.documentId);if(!e)throw new Error("Document not found");const{_createdAt:n,_id:r,_rev:i,_type:c,_updatedAt:a,...d}=e;try{return await Ls({content:d,promptModifier:"Do not work with technical fields of the data, they starts with a _ symbol.",tags:s.tags,contentTitle:s.contentTitle})}catch{throw new Error("Something went wrong")}}catch{throw new Error("Document not found")}},Us=async s=>{const t=le();if(!t)throw new Error("Sanity client is not initialized");try{const e=await t.getDocument(s.documentId);if(!e)throw new Error("Document not found");const{_createdAt:n,_id:r,_rev:i,_type:c,_updatedAt:a,...d}=e;try{return await qs({content:d,promptModifier:"Do not work with technical fields of the data, they starts with a _ symbol. The content you provided with is a movie overview.",contentTitle:s.contentTitle})}catch{throw new Error("Failed to summarise document")}}catch{throw new Error("Document not found")}},Xs=s=>{Ds(s.client),Ns({openAiToken:s.openAiKey})};T.findRelevantTags=Ws,T.initSDK=Xs,T.summariseDocument=Us,T.transalateSelectedDocumentFields=Js,Object.defineProperty(T,Symbol.toStringTag,{value:"Module"})});
{
"name": "@focus-reactive/sanity-ai-sdk",
"version": "0.0.4",
"version": "0.0.5",
"private": false,

@@ -5,0 +5,0 @@ "scripts": {

@@ -81,29 +81,2 @@ <a href="https://focusreactive.com/" align="center">

#### Function **`translateFullDocument`**
**Parameters**
```typescript
interface TranslateFullDocumentProps {
documentId: string;
targetLanguage: string;
}
```
- `documentId` - Id of the document that we need to process.
- `targetLanguage` - Language to which we need to translate the content.
**Usage**
```javascript
// 1. Import the function
import { translateFullDocument } from "@focus-reactive/sanity-ai-sdk";
// 2. Call the function
const translatedDocument = await translateFullDocument({
targetLanguage: "german",
documentId: DOCUMENT_ID,
});
```
### Categorisation

@@ -110,0 +83,0 @@

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc