otherwise-cli 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +193 -0
- package/bin/otherwise.js +5 -0
- package/frontend/404.html +84 -0
- package/frontend/assets/OpenDyslexic3-Bold-CDyRs55Y.ttf +0 -0
- package/frontend/assets/OpenDyslexic3-Regular-CIBXa4WE.ttf +0 -0
- package/frontend/assets/__vite-browser-external-BIHI7g3E.js +1 -0
- package/frontend/assets/conversational-worker-CeKiciGk.js +2929 -0
- package/frontend/assets/dictation-worker-D0aYfq8b.js +29 -0
- package/frontend/assets/gemini-color-CgSQmmva.png +0 -0
- package/frontend/assets/index-BLux5ps4.js +21 -0
- package/frontend/assets/index-Blh8_TEM.js +5272 -0
- package/frontend/assets/index-BpQ1PuKu.js +18 -0
- package/frontend/assets/index-Df737c8w.css +1 -0
- package/frontend/assets/index-xaYHL6wb.js +113 -0
- package/frontend/assets/ort-wasm-simd-threaded.asyncify-BynIiDiv.wasm +0 -0
- package/frontend/assets/ort-wasm-simd-threaded.jsep-B0T3yYHD.wasm +0 -0
- package/frontend/assets/transformers-tULNc5V3.js +31 -0
- package/frontend/assets/tts-worker-DPJWqT7N.js +2899 -0
- package/frontend/assets/voice-mode-worker-GzvIE_uh.js +2927 -0
- package/frontend/assets/worker-2d5ABSLU.js +31 -0
- package/frontend/banner.png +0 -0
- package/frontend/favicon.svg +3 -0
- package/frontend/google55e5ec47ee14a5f8.html +1 -0
- package/frontend/index.html +234 -0
- package/frontend/manifest.json +17 -0
- package/frontend/pdf.worker.min.mjs +21 -0
- package/frontend/robots.txt +5 -0
- package/frontend/sitemap.xml +27 -0
- package/package.json +81 -0
- package/src/agent/index.js +1066 -0
- package/src/agent/location.js +51 -0
- package/src/agent/prompt.js +548 -0
- package/src/agent/tools.js +4372 -0
- package/src/browser/detect.js +68 -0
- package/src/browser/session.js +1109 -0
- package/src/config.js +137 -0
- package/src/email/client.js +503 -0
- package/src/index.js +557 -0
- package/src/inference/anthropic.js +113 -0
- package/src/inference/google.js +373 -0
- package/src/inference/index.js +81 -0
- package/src/inference/ollama.js +383 -0
- package/src/inference/openai.js +140 -0
- package/src/inference/openrouter.js +378 -0
- package/src/inference/xai.js +200 -0
- package/src/logBridge.js +9 -0
- package/src/models.js +146 -0
- package/src/remote/client.js +225 -0
- package/src/scheduler/cron.js +243 -0
- package/src/server.js +3876 -0
- package/src/storage/db.js +1135 -0
- package/src/storage/supabase.js +364 -0
- package/src/tunnel/cloudflare.js +241 -0
- package/src/ui/components/App.jsx +687 -0
- package/src/ui/components/BrowserSelect.jsx +111 -0
- package/src/ui/components/FilePicker.jsx +472 -0
- package/src/ui/components/Header.jsx +444 -0
- package/src/ui/components/HelpPanel.jsx +173 -0
- package/src/ui/components/HistoryPanel.jsx +158 -0
- package/src/ui/components/MessageList.jsx +235 -0
- package/src/ui/components/ModelSelector.jsx +304 -0
- package/src/ui/components/PromptInput.jsx +515 -0
- package/src/ui/components/StreamingResponse.jsx +134 -0
- package/src/ui/components/ThinkingIndicator.jsx +365 -0
- package/src/ui/components/ToolExecution.jsx +714 -0
- package/src/ui/components/index.js +82 -0
- package/src/ui/context/TerminalContext.jsx +150 -0
- package/src/ui/context/index.js +13 -0
- package/src/ui/hooks/index.js +16 -0
- package/src/ui/hooks/useChatState.js +675 -0
- package/src/ui/hooks/useCommands.js +280 -0
- package/src/ui/hooks/useFileAttachments.js +216 -0
- package/src/ui/hooks/useKeyboardShortcuts.js +173 -0
- package/src/ui/hooks/useNotifications.js +185 -0
- package/src/ui/hooks/useTerminalSize.js +151 -0
- package/src/ui/hooks/useWebSocket.js +273 -0
- package/src/ui/index.js +94 -0
- package/src/ui/ink-runner.js +22 -0
- package/src/ui/utils/formatters.js +424 -0
- package/src/ui/utils/index.js +6 -0
- package/src/ui/utils/markdown.js +166 -0
|
Binary file
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
function y(n,e,t,s,r){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function o(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)}let Ss=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return Ss=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))};function pt(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const mt=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class g extends Error{}class D extends g{constructor(e,t,s,r){super(`${D.makeMessage(e,t,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=t;const i=t;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,t,s){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,s,r){if(!e||!r)return new Ye({message:s,cause:mt(t)});const i=t?.error;return e===400?new xs(e,i,s,r):e===401?new As(e,i,s,r):e===403?new Rs(e,i,s,r):e===404?new Cs(e,i,s,r):e===409?new Is(e,i,s,r):e===422?new vs(e,i,s,r):e===429?new $s(e,i,s,r):e>=500?new Es(e,i,s,r):new D(e,i,s,r)}}class V extends D{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ye extends D{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class It extends Ye{constructor({message:e}={}){super({message:e??"Request timed out."})}}class xs extends D{}class As extends D{}class Rs extends D{}class Cs extends D{}class Is extends D{}class vs extends D{}class $s extends D{}class Es extends D{}class Os extends g{constructor(){super("Could not parse response content as the length limit was reached")}}class ks extends g{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}const Hn=/^[a-z][a-z0-9+.-]*:/i,Xn=n=>Hn.test(n);let q=n=>(q=Array.isArray,q(n)),zt=q;function Vn(n){return typeof n!="object"?{}:n??{}}function Kn(n){if(!n)return!0;for(const e in n)return!1;return!0}function zn(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function at(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const Qn=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new g(`${n} must be an integer`);if(e<0)throw new g(`${n} must be a positive integer`);return e},Gn=n=>{try{return JSON.parse(n)}catch{return}},Ie=n=>new Promise(e=>setTimeout(e,n)),ce="5.5.1",Yn=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Zn(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const er=()=>{const n=Zn();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":Gt(Deno.build.os),"X-Stainless-Arch":Qt(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":Gt(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Qt(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=tr();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":ce,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function tr(){if(typeof navigator>"u"||!navigator)return null;const n=[{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:e,pattern:t}of n){const s=t.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,a=s[3]||0;return{browser:e,version:`${r}.${i}.${a}`}}}return null}const Qt=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",Gt=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let Yt;const sr=()=>Yt??(Yt=er());function nr(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ps(...n){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function Ts(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Ps({start(){},async pull(t){const{done:s,value:r}=await e.next();s?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}function Ms(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function rr(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const ir=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Ns="RFC3986",Fs=n=>String(n),Zt={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:Fs},ar="RFC1738";let _t=(n,e)=>(_t=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),_t(n,e));const z=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),ot=1024,or=(n,e,t,s,r)=>{if(n.length===0)return n;let i=n;if(typeof n=="symbol"?i=Symbol.prototype.toString.call(n):typeof n!="string"&&(i=String(n)),t==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let a="";for(let l=0;l<i.length;l+=ot){const h=i.length>=ot?i.slice(l,l+ot):i,f=[];for(let S=0;S<h.length;++S){let u=h.charCodeAt(S);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||r===ar&&(u===40||u===41)){f[f.length]=h.charAt(S);continue}if(u<128){f[f.length]=z[u];continue}if(u<2048){f[f.length]=z[192|u>>6]+z[128|u&63];continue}if(u<55296||u>=57344){f[f.length]=z[224|u>>12]+z[128|u>>6&63]+z[128|u&63];continue}S+=1,u=65536+((u&1023)<<10|h.charCodeAt(S)&1023),f[f.length]=z[240|u>>18]+z[128|u>>12&63]+z[128|u>>6&63]+z[128|u&63]}a+=f.join("")}return a};function lr(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function es(n,e){if(q(n)){const t=[];for(let s=0;s<n.length;s+=1)t.push(e(n[s]));return t}return e(n)}const Ls={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},Ds=function(n,e){Array.prototype.push.apply(n,q(e)?e:[e])};let ts;const k={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:or,encodeValuesOnly:!1,format:Ns,formatter:Fs,indices:!1,serializeDate(n){return(ts??(ts=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function cr(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const lt={};function Bs(n,e,t,s,r,i,a,l,h,f,S,u,_,c,A,b,P,R){let p=n,T=R,C=0,X=!1;for(;(T=T.get(lt))!==void 0&&!X;){const $=T.get(n);if(C+=1,typeof $<"u"){if($===C)throw new RangeError("Cyclic object value");X=!0}typeof T.get(lt)>"u"&&(C=0)}if(typeof f=="function"?p=f(e,p):p instanceof Date?p=_?.(p):t==="comma"&&q(p)&&(p=es(p,function($){return $ instanceof Date?_?.($):$})),p===null){if(i)return h&&!b?h(e,k.encoder,P,"key",c):e;p=""}if(cr(p)||lr(p)){if(h){const $=b?e:h(e,k.encoder,P,"key",c);return[A?.($)+"="+A?.(h(p,k.encoder,P,"value",c))]}return[A?.(e)+"="+A?.(String(p))]}const U=[];if(typeof p>"u")return U;let I;if(t==="comma"&&q(p))b&&h&&(p=es(p,h)),I=[{value:p.length>0?p.join(",")||null:void 0}];else if(q(f))I=f;else{const $=Object.keys(p);I=S?$.sort(S):$}const F=l?String(e).replace(/\./g,"%2E"):String(e),M=s&&q(p)&&p.length===1?F+"[]":F;if(r&&q(p)&&p.length===0)return M+"[]";for(let $=0;$<I.length;++$){const E=I[$],Vt=typeof E=="object"&&typeof E.value<"u"?E.value:p[E];if(a&&Vt===null)continue;const it=u&&l?E.replace(/\./g,"%2E"):E,Jn=q(p)?typeof t=="function"?t(M,it):M:M+(u?"."+it:"["+it+"]");R.set(n,C);const Kt=new WeakMap;Kt.set(lt,R),Ds(U,Bs(Vt,Jn,t,s,r,i,a,l,t==="comma"&&b&&q(p)?null:h,f,S,u,_,c,A,b,P,Kt))}return U}function ur(n=k){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||k.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Ns;if(typeof n.format<"u"){if(!_t(Zt,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const s=Zt[t];let r=k.filter;(typeof n.filter=="function"||q(n.filter))&&(r=n.filter);let i;if(n.arrayFormat&&n.arrayFormat in Ls?i=n.arrayFormat:"indices"in n?i=n.indices?"indices":"repeat":i=k.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:k.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:k.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:k.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:k.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?k.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:k.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:k.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:k.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:k.encodeValuesOnly,filter:r,format:t,formatter:s,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:k.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:k.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:k.strictNullHandling}}function hr(n,e={}){let t=n;const s=ur(e);let r,i;typeof s.filter=="function"?(i=s.filter,t=i("",t)):q(s.filter)&&(i=s.filter,r=i);const a=[];if(typeof t!="object"||t===null)return"";const l=Ls[s.arrayFormat],h=l==="comma"&&s.commaRoundTrip;r||(r=Object.keys(t)),s.sort&&r.sort(s.sort);const f=new WeakMap;for(let _=0;_<r.length;++_){const c=r[_];s.skipNulls&&t[c]===null||Ds(a,Bs(t[c],c,l,h,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,f))}const S=a.join(s.delimiter);let u=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),S.length>0?u+S:""}function dr(n){let e=0;for(const r of n)e+=r.length;const t=new Uint8Array(e);let s=0;for(const r of n)t.set(r,s),s+=r.length;return t}let ss;function vt(n){let e;return(ss??(e=new globalThis.TextEncoder,ss=e.encode.bind(e)))(n)}let ns;function rs(n){let e;return(ns??(e=new globalThis.TextDecoder,ns=e.decode.bind(e)))(n)}var j,J;class Ze{constructor(){j.set(this,void 0),J.set(this,void 0),y(this,j,new Uint8Array),y(this,J,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?vt(e):e;y(this,j,dr([o(this,j,"f"),t]));const s=[];let r;for(;(r=fr(o(this,j,"f"),o(this,J,"f")))!=null;){if(r.carriage&&o(this,J,"f")==null){y(this,J,r.index);continue}if(o(this,J,"f")!=null&&(r.index!==o(this,J,"f")+1||r.carriage)){s.push(rs(o(this,j,"f").subarray(0,o(this,J,"f")-1))),y(this,j,o(this,j,"f").subarray(o(this,J,"f"))),y(this,J,null);continue}const i=o(this,J,"f")!==null?r.preceding-1:r.preceding,a=rs(o(this,j,"f").subarray(0,i));s.push(a),y(this,j,o(this,j,"f").subarray(r.index)),y(this,J,null)}return s}flush(){return o(this,j,"f").length?this.decode(`
|
|
2
|
+
`):[]}}j=new WeakMap,J=new WeakMap;Ze.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,"\r"]);Ze.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function fr(n,e){for(let r=e??0;r<n.length;r++){if(n[r]===10)return{preceding:r,index:r+1,carriage:!1};if(n[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function pr(n){for(let s=0;s<n.length-1;s++){if(n[s]===10&&n[s+1]===10||n[s]===13&&n[s+1]===13)return s+2;if(n[s]===13&&n[s+1]===10&&s+3<n.length&&n[s+2]===13&&n[s+3]===10)return s+4}return-1}class G{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let s=!1;async function*r(){if(s)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let i=!1;try{for await(const a of mr(e,t))if(!i){if(a.data.startsWith("[DONE]")){i=!0;continue}if(a.event===null||a.event.startsWith("response.")||a.event.startsWith("transcript.")){let l;try{l=JSON.parse(a.data)}catch(h){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),h}if(l&&l.error)throw new D(void 0,l.error,void 0,e.headers);yield l}else{let l;try{l=JSON.parse(a.data)}catch(h){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),h}if(a.event=="error")throw new D(void 0,l.error,l.message,void 0);yield{event:a.event,data:l}}}i=!0}catch(a){if(pt(a))return;throw a}finally{i||t.abort()}}return new G(r,t)}static fromReadableStream(e,t){let s=!1;async function*r(){const a=new Ze,l=Ms(e);for await(const h of l)for(const f of a.decode(h))yield f;for(const h of a.flush())yield h}async function*i(){if(s)throw new g("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(const l of r())a||l&&(yield JSON.parse(l));a=!0}catch(l){if(pt(l))return;throw l}finally{a||t.abort()}}return new G(i,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),r=i=>({next:()=>{if(i.length===0){const a=s.next();e.push(a),t.push(a)}return i.shift()}});return[new G(()=>r(e),this.controller),new G(()=>r(t),this.controller)]}toReadableStream(){const e=this;let t;return Ps({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:i}=await t.next();if(i)return s.close();const a=vt(JSON.stringify(r)+`
|
|
4
|
+
`);s.enqueue(a)}catch(r){s.error(r)}},async cancel(){await t.return?.()}})}}async function*mr(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new g("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new g("Attempted to iterate over a response with no body");const t=new gr,s=new Ze,r=Ms(n.body);for await(const i of _r(r))for(const a of s.decode(i)){const l=t.decode(a);l&&(yield l)}for(const i of s.flush()){const a=t.decode(i);a&&(yield a)}}async function*_r(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?vt(t):t;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=pr(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class gr{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,r]=yr(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function yr(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}const He={off:0,error:200,warn:300,info:400,debug:500},is=(n,e,t)=>{if(n){if(zn(He,n))return n;B(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(He))}`)}};function pe(){}function Oe(n,e,t){return!e||He[n]>He[t]?pe:e[n].bind(e)}const wr={error:pe,warn:pe,info:pe,debug:pe};let as=new WeakMap;function B(n){const e=n.logger,t=n.logLevel??"off";if(!e)return wr;const s=as.get(e);if(s&&s[0]===t)return s[1];const r={error:Oe("error",e,t),warn:Oe("warn",e,t),info:Oe("info",e,t),debug:Oe("debug",e,t)};return as.set(e,[t,r]),r}const se=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);async function Us(n,e){const{response:t,requestLogID:s,retryOfRequestLogID:r,startTime:i}=e,a=await(async()=>{if(e.options.stream)return B(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller):G.fromSSEResponse(t,e.controller);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const h=t.headers.get("content-type")?.split(";")[0]?.trim();if(h?.includes("application/json")||h?.endsWith("+json")){const u=await t.json();return Ws(u,t)}return await t.text()})();return B(n).debug(`[${s}] response parsed`,se({retryOfRequestLogID:r,url:t.url,status:t.status,body:a,durationMs:Date.now()-i})),a}function Ws(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var me;class et extends Promise{constructor(e,t,s=Us){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=s,me.set(this,void 0),y(this,me,e)}_thenUnwrap(e){return new et(o(this,me,"f"),this.responsePromise,async(t,s)=>Ws(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(o(this,me,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}me=new WeakMap;var ke;class qs{constructor(e,t,s,r){ke.set(this,void 0),y(this,ke,e),this.options=r,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await o(this,ke,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ke=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class br extends et{constructor(e,t,s){super(e,t,async(r,i)=>new s(r,i.response,await Us(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class tt extends qs{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class v extends qs{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Vn(this.options.query),after:t}}:null}}const js=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function xe(n,e,t){return js(),new File(n,e??"unknown_file",t)}function Le(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const Js=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",ae=async(n,e)=>({...n,body:await xr(n.body,e)}),os=new WeakMap;function Sr(n){const e=typeof n=="function"?n:n.fetch,t=os.get(e);if(t)return t;const s=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return os.set(e,s),s}const xr=async(n,e)=>{if(!await Sr(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([s,r])=>gt(t,s,r))),t},Ar=n=>n instanceof Blob&&"name"in n,gt=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,xe([await t.blob()],Le(t)));else if(Js(t))n.append(e,xe([await new Response(Ts(t)).blob()],Le(t)));else if(Ar(t))n.append(e,t,Le(t));else if(Array.isArray(t))await Promise.all(t.map(s=>gt(n,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,r])=>gt(n,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},Hs=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",Rr=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&Hs(n),Cr=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function Ir(n,e,t){if(js(),n=await n,Rr(n))return n instanceof File?n:xe([await n.arrayBuffer()],n.name);if(Cr(n)){const r=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),xe(await yt(r),e,t)}const s=await yt(n);if(e||(e=Le(n)),!t?.type){const r=s.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return xe(s,e,t)}async function yt(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(Hs(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(Js(n))for await(const t of n)e.push(...await yt(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${vr(n)}`)}return e}function vr(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class w{constructor(e){this._client=e}}function Xs(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const $r=(n=Xs)=>function(t,...s){if(t.length===1)return t[0];let r=!1;const i=t.reduce((S,u,_)=>(/[?#]/.test(u)&&(r=!0),S+u+(_===s.length?"":(r?encodeURIComponent:n)(String(s[_])))),""),a=i.split(/[?#]/,1)[0],l=[],h=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let f;for(;(f=h.exec(a))!==null;)l.push({start:f.index,length:f[0].length});if(l.length>0){let S=0;const u=l.reduce((_,c)=>{const A=" ".repeat(c.start-S),b="^".repeat(c.length);return S=c.start+c.length,_+A+b},"");throw new g(`Path parameters result in path with invalid segments:
|
|
6
|
+
${i}
|
|
7
|
+
${u}`)}return i},d=$r(Xs);let Vs=class extends w{list(e,t={},s){return this._client.getAPIList(d`/chat/completions/${e}/messages`,v,{query:t,...s})}};function Er(n){return typeof n.parse=="function"}const Xe=n=>n?.role==="assistant",Ks=n=>n?.role==="tool";var wt,De,Be,_e,ge,Ue,ye,Z,we,Ve,Ke,ue,zs;class $t{constructor(){wt.add(this),this.controller=new AbortController,De.set(this,void 0),Be.set(this,()=>{}),_e.set(this,()=>{}),ge.set(this,void 0),Ue.set(this,()=>{}),ye.set(this,()=>{}),Z.set(this,{}),we.set(this,!1),Ve.set(this,!1),Ke.set(this,!1),ue.set(this,!1),y(this,De,new Promise((e,t)=>{y(this,Be,e,"f"),y(this,_e,t,"f")})),y(this,ge,new Promise((e,t)=>{y(this,Ue,e,"f"),y(this,ye,t,"f")})),o(this,De,"f").catch(()=>{}),o(this,ge,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},o(this,wt,"m",zs).bind(this))},0)}_connected(){this.ended||(o(this,Be,"f").call(this),this._emit("connect"))}get ended(){return o(this,we,"f")}get errored(){return o(this,Ve,"f")}get aborted(){return o(this,Ke,"f")}abort(){this.controller.abort()}on(e,t){return(o(this,Z,"f")[e]||(o(this,Z,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=o(this,Z,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===t);return r>=0&&s.splice(r,1),this}once(e,t){return(o(this,Z,"f")[e]||(o(this,Z,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{y(this,ue,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){y(this,ue,!0),await o(this,ge,"f")}_emit(e,...t){if(o(this,we,"f"))return;e==="end"&&(y(this,we,!0),o(this,Ue,"f").call(this));const s=o(this,Z,"f")[e];if(s&&(o(this,Z,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!o(this,ue,"f")&&!s?.length&&Promise.reject(r),o(this,_e,"f").call(this,r),o(this,ye,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!o(this,ue,"f")&&!s?.length&&Promise.reject(r),o(this,_e,"f").call(this,r),o(this,ye,"f").call(this,r),this._emit("end")}}_emitFinal(){}}De=new WeakMap,Be=new WeakMap,_e=new WeakMap,ge=new WeakMap,Ue=new WeakMap,ye=new WeakMap,Z=new WeakMap,we=new WeakMap,Ve=new WeakMap,Ke=new WeakMap,ue=new WeakMap,wt=new WeakSet,zs=function(e){if(y(this,Ve,!0),e instanceof Error&&e.name==="AbortError"&&(e=new V),e instanceof V)return y(this,Ke,!0),this._emit("abort",e);if(e instanceof g)return this._emit("error",e);if(e instanceof Error){const t=new g(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new g(String(e)))};function Et(n){return n?.$brand==="auto-parseable-response-format"}function ve(n){return n?.$brand==="auto-parseable-tool"}function Or(n,e){return!e||!Qs(e)?{...n,choices:n.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Ot(n,e)}function Ot(n,e){const t=n.choices.map(s=>{if(s.finish_reason==="length")throw new Os;if(s.finish_reason==="content_filter")throw new ks;return{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>Pr(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?kr(e,s.message.content):null}}});return{...n,choices:t}}function kr(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function Pr(n,e){const t=n.tools?.find(s=>s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:ve(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function Tr(n,e){if(!n)return!1;const t=n.tools?.find(s=>s.function?.name===e.function.name);return ve(t)||t?.function.strict||!1}function Qs(n){return Et(n.response_format)?!0:n.tools?.some(e=>ve(e)||e.type==="function"&&e.function.strict===!0)??!1}function Mr(n){for(const e of n??[]){if(e.type!=="function")throw new g(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new g(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var W,bt,ze,St,xt,At,Gs,Ys;const Nr=10;class Zs extends $t{constructor(){super(...arguments),W.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),Ks(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Xe(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new g("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),o(this,W,"m",bt).call(this)}async finalMessage(){return await this.done(),o(this,W,"m",ze).call(this)}async finalFunctionToolCall(){return await this.done(),o(this,W,"m",St).call(this)}async finalFunctionToolCallResult(){return await this.done(),o(this,W,"m",xt).call(this)}async totalUsage(){return await this.done(),o(this,W,"m",At).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=o(this,W,"m",ze).call(this);t&&this._emit("finalMessage",t);const s=o(this,W,"m",bt).call(this);s&&this._emit("finalContent",s);const r=o(this,W,"m",St).call(this);r&&this._emit("finalFunctionToolCall",r);const i=o(this,W,"m",xt).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",o(this,W,"m",At).call(this))}async _createChatCompletion(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,W,"m",Gs).call(this,t);const i=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Ot(i,t))}async _runChatCompletion(e,t,s){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){const r="tool",{tool_choice:i="auto",stream:a,...l}=t,h=typeof i!="string"&&i?.function?.name,{maxChatCompletions:f=Nr}=s||{},S=t.tools.map(c=>{if(ve(c)){if(!c.$callback)throw new g("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:c.$callback,name:c.function.name,description:c.function.description||"",parameters:c.function.parameters,parse:c.$parseRaw,strict:!0}}}return c}),u={};for(const c of S)c.type==="function"&&(u[c.function.name||c.function.function.name]=c.function);const _="tools"in t?S.map(c=>c.type==="function"?{type:"function",function:{name:c.function.name||c.function.function.name,parameters:c.function.parameters,description:c.function.description,strict:c.function.strict}}:c):void 0;for(const c of t.messages)this._addMessage(c,!1);for(let c=0;c<f;++c){const b=(await this._createChatCompletion(e,{...l,tool_choice:i,tools:_,messages:[...this.messages]},s)).choices[0]?.message;if(!b)throw new g("missing message in ChatCompletion response");if(!b.tool_calls?.length)return;for(const P of b.tool_calls){if(P.type!=="function")continue;const R=P.id,{name:p,arguments:T}=P.function,C=u[p];if(C){if(h&&h!==p){const F=`Invalid tool_call: ${JSON.stringify(p)}. ${JSON.stringify(h)} requested. Please try again`;this._addMessage({role:r,tool_call_id:R,content:F});continue}}else{const F=`Invalid tool_call: ${JSON.stringify(p)}. Available options are: ${Object.keys(u).map(M=>JSON.stringify(M)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:R,content:F});continue}let X;try{X=Er(C)?await C.parse(T):T}catch(F){const M=F instanceof Error?F.message:String(F);this._addMessage({role:r,tool_call_id:R,content:M});continue}const U=await C.function(X,this),I=o(this,W,"m",Ys).call(this,U);if(this._addMessage({role:r,tool_call_id:R,content:I}),h)return}}}}W=new WeakSet,bt=function(){return o(this,W,"m",ze).call(this).content??null},ze=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Xe(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new g("stream ended without producing a ChatCompletionMessage with role=assistant")},St=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Xe(t)&&t?.tool_calls?.length)return t.tool_calls.at(-1)?.function}},xt=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ks(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(r=>r.type==="function"&&r.id===t.tool_call_id)))return t.content}},At=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Gs=function(e){if(e.n!=null&&e.n>1)throw new g("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Ys=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class kt extends Zs{static runTools(e,t,s){const r=new kt,i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}_addMessage(e,t=!0){super._addMessage(e,t),Xe(e)&&e.content&&this._emit("content",e.content)}}const en=1,tn=2,sn=4,nn=8,rn=16,an=32,on=64,ln=128,cn=256,un=ln|cn,hn=rn|an|un|on,dn=en|tn|hn,fn=sn|nn,Fr=dn|fn,N={STR:en,NUM:tn,ARR:sn,OBJ:nn,NULL:rn,BOOL:an,NAN:on,INFINITY:ln,MINUS_INFINITY:cn,INF:un,SPECIAL:hn,ATOM:dn,COLLECTION:fn,ALL:Fr};class Lr extends Error{}class Dr extends Error{}function Br(n,e=N.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return Ur(n.trim(),e)}const Ur=(n,e)=>{const t=n.length;let s=0;const r=_=>{throw new Lr(`${_} at position ${s}`)},i=_=>{throw new Dr(`${_} at position ${s}`)},a=()=>(u(),s>=t&&r("Unexpected end of input"),n[s]==='"'?l():n[s]==="{"?h():n[s]==="["?f():n.substring(s,s+4)==="null"||N.NULL&e&&t-s<4&&"null".startsWith(n.substring(s))?(s+=4,null):n.substring(s,s+4)==="true"||N.BOOL&e&&t-s<4&&"true".startsWith(n.substring(s))?(s+=4,!0):n.substring(s,s+5)==="false"||N.BOOL&e&&t-s<5&&"false".startsWith(n.substring(s))?(s+=5,!1):n.substring(s,s+8)==="Infinity"||N.INFINITY&e&&t-s<8&&"Infinity".startsWith(n.substring(s))?(s+=8,1/0):n.substring(s,s+9)==="-Infinity"||N.MINUS_INFINITY&e&&1<t-s&&t-s<9&&"-Infinity".startsWith(n.substring(s))?(s+=9,-1/0):n.substring(s,s+3)==="NaN"||N.NAN&e&&t-s<3&&"NaN".startsWith(n.substring(s))?(s+=3,NaN):S()),l=()=>{const _=s;let c=!1;for(s++;s<t&&(n[s]!=='"'||c&&n[s-1]==="\\");)c=n[s]==="\\"?!c:!1,s++;if(n.charAt(s)=='"')try{return JSON.parse(n.substring(_,++s-Number(c)))}catch(A){i(String(A))}else if(N.STR&e)try{return JSON.parse(n.substring(_,s-Number(c))+'"')}catch{return JSON.parse(n.substring(_,n.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},h=()=>{s++,u();const _={};try{for(;n[s]!=="}";){if(u(),s>=t&&N.OBJ&e)return _;const c=l();u(),s++;try{const A=a();Object.defineProperty(_,c,{value:A,writable:!0,enumerable:!0,configurable:!0})}catch(A){if(N.OBJ&e)return _;throw A}u(),n[s]===","&&s++}}catch{if(N.OBJ&e)return _;r("Expected '}' at end of object")}return s++,_},f=()=>{s++;const _=[];try{for(;n[s]!=="]";)_.push(a()),u(),n[s]===","&&s++}catch{if(N.ARR&e)return _;r("Expected ']' at end of array")}return s++,_},S=()=>{if(s===0){n==="-"&&N.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n)}catch(c){if(N.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}i(String(c))}}const _=s;for(n[s]==="-"&&s++;n[s]&&!",]}".includes(n[s]);)s++;s==t&&!(N.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(n.substring(_,s))}catch{n.substring(_,s)==="-"&&N.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n.substring(_,n.lastIndexOf("e")))}catch(A){i(String(A))}}},u=()=>{for(;s<t&&`
|
|
8
|
+
\r `.includes(n[s]);)s++};return a()},ls=n=>Br(n,N.ALL^N.NUM);var O,Y,oe,ee,ct,Pe,ut,ht,dt,Te,ft,cs;class Ce extends Zs{constructor(e){super(),O.add(this),Y.set(this,void 0),oe.set(this,void 0),ee.set(this,void 0),y(this,Y,e),y(this,oe,[])}get currentChatCompletionSnapshot(){return o(this,ee,"f")}static fromReadableStream(e){const t=new Ce(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const r=new Ce(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,s){super._createChatCompletion;const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,O,"m",ct).call(this);const i=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const a of i)o(this,O,"m",ut).call(this,a);if(i.controller.signal?.aborted)throw new V;return this._addChatCompletion(o(this,O,"m",Te).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),o(this,O,"m",ct).call(this),this._connected();const r=G.fromReadableStream(e,this.controller);let i;for await(const a of r)i&&i!==a.id&&this._addChatCompletion(o(this,O,"m",Te).call(this)),o(this,O,"m",ut).call(this,a),i=a.id;if(r.controller.signal?.aborted)throw new V;return this._addChatCompletion(o(this,O,"m",Te).call(this))}[(Y=new WeakMap,oe=new WeakMap,ee=new WeakMap,O=new WeakSet,ct=function(){this.ended||y(this,ee,void 0)},Pe=function(t){let s=o(this,oe,"f")[t.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},o(this,oe,"f")[t.index]=s,s)},ut=function(t){if(this.ended)return;const s=o(this,O,"m",cs).call(this,t);this._emit("chunk",t,s);for(const r of t.choices){const i=s.choices[r.index];r.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",r.delta.content,i.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),r.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:i.message.refusal}),r.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:i.logprobs?.content??[]}),r.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});const a=o(this,O,"m",Pe).call(this,i);i.finish_reason&&(o(this,O,"m",dt).call(this,i),a.current_tool_call_index!=null&&o(this,O,"m",ht).call(this,i,a.current_tool_call_index));for(const l of r.delta.tool_calls??[])a.current_tool_call_index!==l.index&&(o(this,O,"m",dt).call(this,i),a.current_tool_call_index!=null&&o(this,O,"m",ht).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=l.index;for(const l of r.delta.tool_calls??[]){const h=i.message.tool_calls?.[l.index];h?.type&&(h?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:h.function?.name,index:l.index,arguments:h.function.arguments,parsed_arguments:h.function.parsed_arguments,arguments_delta:l.function?.arguments??""}):(h?.type,void 0))}}},ht=function(t,s){if(o(this,O,"m",Pe).call(this,t).done_tool_calls.has(s))return;const i=t.message.tool_calls?.[s];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){const a=o(this,Y,"f")?.tools?.find(l=>l.type==="function"&&l.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:s,arguments:i.function.arguments,parsed_arguments:ve(a)?a.$parseRaw(i.function.arguments):a?.function.strict?JSON.parse(i.function.arguments):null})}else i.type},dt=function(t){const s=o(this,O,"m",Pe).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;const r=o(this,O,"m",ft).call(this);this._emit("content.done",{content:t.message.content,parsed:r?r.$parseRaw(t.message.content):null})}t.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Te=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");const t=o(this,ee,"f");if(!t)throw new g("request ended without sending any chunks");return y(this,ee,void 0),y(this,oe,[]),Wr(t,o(this,Y,"f"))},ft=function(){const t=o(this,Y,"f")?.response_format;return Et(t)?t:null},cs=function(t){var s,r,i,a;let l=o(this,ee,"f");const{choices:h,...f}=t;l?Object.assign(l,f):l=y(this,ee,{...f,choices:[]});for(const{delta:S,finish_reason:u,index:_,logprobs:c=null,...A}of t.choices){let b=l.choices[_];if(b||(b=l.choices[_]={finish_reason:u,index:_,message:{},logprobs:c,...A}),c)if(!b.logprobs)b.logprobs=Object.assign({},c);else{const{content:U,refusal:I,...F}=c;Object.assign(b.logprobs,F),U&&((s=b.logprobs).content??(s.content=[]),b.logprobs.content.push(...U)),I&&((r=b.logprobs).refusal??(r.refusal=[]),b.logprobs.refusal.push(...I))}if(u&&(b.finish_reason=u,o(this,Y,"f")&&Qs(o(this,Y,"f")))){if(u==="length")throw new Os;if(u==="content_filter")throw new ks}if(Object.assign(b,A),!S)continue;const{content:P,refusal:R,function_call:p,role:T,tool_calls:C,...X}=S;if(Object.assign(b.message,X),R&&(b.message.refusal=(b.message.refusal||"")+R),T&&(b.message.role=T),p&&(b.message.function_call?(p.name&&(b.message.function_call.name=p.name),p.arguments&&((i=b.message.function_call).arguments??(i.arguments=""),b.message.function_call.arguments+=p.arguments)):b.message.function_call=p),P&&(b.message.content=(b.message.content||"")+P,!b.message.refusal&&o(this,O,"m",ft).call(this)&&(b.message.parsed=ls(b.message.content))),C){b.message.tool_calls||(b.message.tool_calls=[]);for(const{index:U,id:I,type:F,function:M,...$}of C){const E=(a=b.message.tool_calls)[U]??(a[U]={});Object.assign(E,$),I&&(E.id=I),F&&(E.type=F),M&&(E.function??(E.function={name:M.name??"",arguments:""})),M?.name&&(E.function.name=M.name),M?.arguments&&(E.function.arguments+=M.arguments,Tr(o(this,Y,"f"),E)&&(E.function.parsed_arguments=ls(E.function.arguments)))}}}return l},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new G(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Wr(n,e){const{id:t,choices:s,created:r,model:i,system_fingerprint:a,...l}=n,h={...l,id:t,choices:s.map(({message:f,finish_reason:S,index:u,logprobs:_,...c})=>{if(!S)throw new g(`missing finish_reason for choice ${u}`);const{content:A=null,function_call:b,tool_calls:P,...R}=f,p=f.role;if(!p)throw new g(`missing role for choice ${u}`);if(b){const{arguments:T,name:C}=b;if(T==null)throw new g(`missing function_call.arguments for choice ${u}`);if(!C)throw new g(`missing function_call.name for choice ${u}`);return{...c,message:{content:A,function_call:{arguments:T,name:C},role:p,refusal:f.refusal??null},finish_reason:S,index:u,logprobs:_}}return P?{...c,index:u,finish_reason:S,logprobs:_,message:{...R,role:p,content:A,refusal:f.refusal??null,tool_calls:P.map((T,C)=>{const{function:X,type:U,id:I,...F}=T,{arguments:M,name:$,...E}=X||{};if(I==null)throw new g(`missing choices[${u}].tool_calls[${C}].id
|
|
9
|
+
${Me(n)}`);if(U==null)throw new g(`missing choices[${u}].tool_calls[${C}].type
|
|
10
|
+
${Me(n)}`);if($==null)throw new g(`missing choices[${u}].tool_calls[${C}].function.name
|
|
11
|
+
${Me(n)}`);if(M==null)throw new g(`missing choices[${u}].tool_calls[${C}].function.arguments
|
|
12
|
+
${Me(n)}`);return{...F,id:I,type:U,function:{...E,name:$,arguments:M}}})}}:{...c,message:{...R,content:A,role:p,refusal:f.refusal??null},finish_reason:S,index:u,logprobs:_}}),created:r,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Or(h,e)}function Me(n){return JSON.stringify(n)}class Qe extends Ce{static fromReadableStream(e){const t=new Qe(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){const r=new Qe(t),i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}}let Pt=class extends w{constructor(){super(...arguments),this.messages=new Vs(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(d`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(d`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",v,{query:e,...t})}delete(e,t){return this._client.delete(d`/chat/completions/${e}`,t)}parse(e,t){return Mr(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>Ot(s,e))}runTools(e,t){return e.stream?Qe.runTools(this._client,e,t):kt.runTools(this._client,e,t)}stream(e,t){return Ce.createChatCompletion(this._client,e,t)}};Pt.Messages=Vs;class Tt extends w{constructor(){super(...arguments),this.completions=new Pt(this._client)}}Tt.Completions=Pt;const pn=Symbol("brand.privateNullableHeaders");function*qr(n){if(!n)return;if(pn in n){const{values:s,nulls:r}=n;yield*s.entries();for(const i of r)yield[i,null];return}let e=!1,t;n instanceof Headers?t=n.entries():zt(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let s of t){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=zt(s[1])?s[1]:[s[1]];let a=!1;for(const l of i)l!==void 0&&(e&&!a&&(a=!0,yield[r,null]),yield[r,l])}}const m=n=>{const e=new Headers,t=new Set;for(const s of n){const r=new Set;for(const[i,a]of qr(s)){const l=i.toLowerCase();r.has(l)||(e.delete(i),r.add(l)),a===null?(e.delete(i),t.add(l)):(e.append(i,a),t.delete(l))}}return{[pn]:!0,values:e,nulls:t}};class mn extends w{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:m([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class _n extends w{create(e,t){return this._client.post("/audio/transcriptions",ae({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class gn extends w{create(e,t){return this._client.post("/audio/translations",ae({body:e,...t,__metadata:{model:e.model}},this._client))}}class $e extends w{constructor(){super(...arguments),this.transcriptions=new _n(this._client),this.translations=new gn(this._client),this.speech=new mn(this._client)}}$e.Transcriptions=_n;$e.Translations=gn;$e.Speech=mn;class yn extends w{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(d`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",v,{query:e,...t})}cancel(e,t){return this._client.post(d`/batches/${e}/cancel`,t)}}class wn extends w{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/assistants/${e}`,{...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(d`/assistants/${e}`,{body:t,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",v,{query:e,...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/assistants/${e}`,{...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class bn extends w{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Sn extends w{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class st extends w{constructor(){super(...arguments),this.sessions=new bn(this._client),this.transcriptionSessions=new Sn(this._client)}}st.Sessions=bn;st.TranscriptionSessions=Sn;class xn extends w{create(e,t,s){return this._client.post(d`/threads/${e}/messages`,{body:t,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(d`/threads/${r}/messages/${e}`,{...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(d`/threads/${r}/messages/${e}`,{body:i,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(d`/threads/${e}/messages`,v,{query:t,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{thread_id:r}=t;return this._client.delete(d`/threads/${r}/messages/${e}`,{...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class An extends w{retrieve(e,t,s){const{thread_id:r,run_id:i,...a}=t;return this._client.get(d`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){const{thread_id:r,...i}=t;return this._client.getAPIList(d`/threads/${r}/runs/${e}/steps`,v,{query:i,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const jr=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,s=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}};var Jr={};const fe=n=>{if(typeof globalThis.process<"u")return Jr?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var L,re,Rt,Q,We,K,ie,he,ne,Ge,H,qe,je,Ae,be,Se,us,hs,ds,fs,ps,ms,_s;class Re extends $t{constructor(){super(...arguments),L.add(this),Rt.set(this,[]),Q.set(this,{}),We.set(this,{}),K.set(this,void 0),ie.set(this,void 0),he.set(this,void 0),ne.set(this,void 0),Ge.set(this,void 0),H.set(this,void 0),qe.set(this,void 0),je.set(this,void 0),Ae.set(this,void 0)}[(Rt=new WeakMap,Q=new WeakMap,We=new WeakMap,K=new WeakMap,ie=new WeakMap,he=new WeakMap,ne=new WeakMap,Ge=new WeakMap,H=new WeakMap,qe=new WeakMap,je=new WeakMap,Ae=new WeakMap,L=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new re;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=G.fromReadableStream(e,this.controller);for await(const i of r)o(this,L,"m",be).call(this,i);if(r.controller.signal?.aborted)throw new V;return this._addRun(o(this,L,"m",Se).call(this))}toReadableStream(){return new G(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,r){const i=new re;return i._run(()=>i._runToolAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},l=await e.submitToolOutputs(t,a,{...r,signal:this.controller.signal});this._connected();for await(const h of l)o(this,L,"m",be).call(this,h);if(l.controller.signal?.aborted)throw new V;return this._addRun(o(this,L,"m",Se).call(this))}static createThreadAssistantStream(e,t,s){const r=new re;return r._run(()=>r._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,s,r){const i=new re;return i._run(()=>i._runAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return o(this,qe,"f")}currentRun(){return o(this,je,"f")}currentMessageSnapshot(){return o(this,K,"f")}currentRunStepSnapshot(){return o(this,Ae,"f")}async finalRunSteps(){return await this.done(),Object.values(o(this,Q,"f"))}async finalMessages(){return await this.done(),Object.values(o(this,We,"f"))}async finalRun(){if(await this.done(),!o(this,ie,"f"))throw Error("Final run was not received.");return o(this,ie,"f")}async _createThreadAssistantStream(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...t,stream:!0},a=await e.createAndRun(i,{...s,signal:this.controller.signal});this._connected();for await(const l of a)o(this,L,"m",be).call(this,l);if(a.controller.signal?.aborted)throw new V;return this._addRun(o(this,L,"m",Se).call(this))}async _createAssistantStream(e,t,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},l=await e.create(t,a,{...r,signal:this.controller.signal});this._connected();for await(const h of l)o(this,L,"m",be).call(this,h);if(l.controller.signal?.aborted)throw new V;return this._addRun(o(this,L,"m",Se).call(this))}static accumulateDelta(e,t){for(const[s,r]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let i=e[s];if(i==null){e[s]=r;continue}if(s==="index"||s==="type"){e[s]=r;continue}if(typeof i=="string"&&typeof r=="string")i+=r;else if(typeof i=="number"&&typeof r=="number")i+=r;else if(at(i)&&at(r))i=this.accumulateDelta(i,r);else if(Array.isArray(i)&&Array.isArray(r)){if(i.every(a=>typeof a=="string"||typeof a=="number")){i.push(...r);continue}for(const a of r){if(!at(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const l=a.index;if(l==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const h=i[l];h==null?i.push(a):i[l]=this.accumulateDelta(h,a)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${i}`);e[s]=i}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,r){return await this._createAssistantStream(t,e,s,r)}async _runToolAssistantStream(e,t,s,r){return await this._createToolAssistantStream(t,e,s,r)}}re=Re,be=function(e){if(!this.ended)switch(y(this,qe,e),o(this,L,"m",ds).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":o(this,L,"m",_s).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":o(this,L,"m",hs).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":o(this,L,"m",us).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Se=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");if(!o(this,ie,"f"))throw Error("Final run has not been received");return o(this,ie,"f")},us=function(e){const[t,s]=o(this,L,"m",ps).call(this,e,o(this,K,"f"));y(this,K,t),o(this,We,"f")[t.id]=t;for(const r of s){const i=t.content[r.index];i?.type=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let i=r.text,a=t.content[r.index];if(a&&a.type=="text")this._emit("textDelta",i,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=o(this,he,"f")){if(o(this,ne,"f"))switch(o(this,ne,"f").type){case"text":this._emit("textDone",o(this,ne,"f").text,o(this,K,"f"));break;case"image_file":this._emit("imageFileDone",o(this,ne,"f").image_file,o(this,K,"f"));break}y(this,he,r.index)}y(this,ne,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(o(this,he,"f")!==void 0){const r=e.data.content[o(this,he,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,o(this,K,"f"));break;case"text":this._emit("textDone",r.text,o(this,K,"f"));break}}o(this,K,"f")&&this._emit("messageDone",e.data),y(this,K,void 0)}},hs=function(e){const t=o(this,L,"m",fs).call(this,e);switch(y(this,Ae,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const i of s.step_details.tool_calls)i.index==o(this,Ge,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(o(this,H,"f")&&this._emit("toolCallDone",o(this,H,"f")),y(this,Ge,i.index),y(this,H,t.step_details.tool_calls[i.index]),o(this,H,"f")&&this._emit("toolCallCreated",o(this,H,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":y(this,Ae,void 0),e.data.step_details.type=="tool_calls"&&o(this,H,"f")&&(this._emit("toolCallDone",o(this,H,"f")),y(this,H,void 0)),this._emit("runStepDone",e.data,t);break}},ds=function(e){o(this,Rt,"f").push(e),this._emit("event",e)},fs=function(e){switch(e.event){case"thread.run.step.created":return o(this,Q,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=o(this,Q,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=re.accumulateDelta(t,s.delta);o(this,Q,"f")[e.data.id]=r}return o(this,Q,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":o(this,Q,"f")[e.data.id]=e.data;break}if(o(this,Q,"f")[e.data.id])return o(this,Q,"f")[e.data.id];throw new Error("No snapshot available")},ps=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const i of r.delta.content)if(i.index in t.content){let a=t.content[i.index];t.content[i.index]=o(this,L,"m",ms).call(this,i,a)}else t.content[i.index]=i,s.push(i);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},ms=function(e,t){return re.accumulateDelta(t,e)},_s=function(e){switch(y(this,je,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":y(this,ie,e.data),o(this,H,"f")&&(this._emit("toolCallDone",o(this,H,"f")),y(this,H,void 0));break}};let Mt=class extends w{constructor(){super(...arguments),this.steps=new An(this._client)}create(e,t,s){const{include:r,...i}=t;return this._client.post(d`/threads/${e}/runs`,{query:{include:r},body:i,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(d`/threads/${r}/runs/${e}`,{...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(d`/threads/${r}/runs/${e}`,{body:i,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(d`/threads/${e}/runs`,v,{query:t,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{thread_id:r}=t;return this._client.post(d`/threads/${r}/runs/${e}/cancel`,{...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(r.id,{thread_id:e},s)}createAndStream(e,t,s){return Re.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const r=m([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...r}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const h=a.headers.get("openai-poll-after-ms");if(h){const f=parseInt(h);isNaN(f)||(l=f)}}await Ie(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,s){return Re.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:r,...i}=t;return this._client.post(d`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,s){const r=await this.submitToolOutputs(e,t,s);return await this.poll(r.id,t,s)}submitToolOutputsStream(e,t,s){return Re.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};Mt.Steps=An;class nt extends w{constructor(){super(...arguments),this.runs=new Mt(this._client),this.messages=new xn(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/threads/${e}`,{...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(d`/threads/${e}`,{body:t,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(d`/threads/${e}`,{...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return Re.createThreadAssistantStream(e,this._client.beta.threads,t)}}nt.Runs=Mt;nt.Messages=xn;class Ee extends w{constructor(){super(...arguments),this.realtime=new st(this._client),this.assistants=new wn(this._client),this.threads=new nt(this._client)}}Ee.Realtime=st;Ee.Assistants=wn;Ee.Threads=nt;class Rn extends w{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Cn extends w{retrieve(e,t,s){const{container_id:r}=t;return this._client.get(d`/containers/${r}/files/${e}/content`,{...s,headers:m([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let Nt=class extends w{constructor(){super(...arguments),this.content=new Cn(this._client)}create(e,t,s){return this._client.post(d`/containers/${e}/files`,ae({body:t,...s},this._client))}retrieve(e,t,s){const{container_id:r}=t;return this._client.get(d`/containers/${r}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(d`/containers/${e}/files`,v,{query:t,...s})}delete(e,t,s){const{container_id:r}=t;return this._client.delete(d`/containers/${r}/files/${e}`,{...s,headers:m([{Accept:"*/*"},s?.headers])})}};Nt.Content=Cn;class Ft extends w{constructor(){super(...arguments),this.files=new Nt(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(d`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",v,{query:e,...t})}delete(e,t){return this._client.delete(d`/containers/${e}`,{...t,headers:m([{Accept:"*/*"},t?.headers])})}}Ft.Files=Nt;class In extends w{create(e,t){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&B(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const i=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return s?i:(B(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(a=>(a&&a.data&&a.data.forEach(l=>{const h=l.embedding;l.embedding=jr(h)}),a)))}}class vn extends w{retrieve(e,t,s){const{eval_id:r,run_id:i}=t;return this._client.get(d`/evals/${r}/runs/${i}/output_items/${e}`,s)}list(e,t,s){const{eval_id:r,...i}=t;return this._client.getAPIList(d`/evals/${r}/runs/${e}/output_items`,v,{query:i,...s})}}class Lt extends w{constructor(){super(...arguments),this.outputItems=new vn(this._client)}create(e,t,s){return this._client.post(d`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){const{eval_id:r}=t;return this._client.get(d`/evals/${r}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(d`/evals/${e}/runs`,v,{query:t,...s})}delete(e,t,s){const{eval_id:r}=t;return this._client.delete(d`/evals/${r}/runs/${e}`,s)}cancel(e,t,s){const{eval_id:r}=t;return this._client.post(d`/evals/${r}/runs/${e}`,s)}}Lt.OutputItems=vn;class Dt extends w{constructor(){super(...arguments),this.runs=new Lt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(d`/evals/${e}`,t)}update(e,t,s){return this._client.post(d`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",v,{query:e,...t})}delete(e,t){return this._client.delete(d`/evals/${e}`,t)}}Dt.Runs=Lt;let $n=class extends w{create(e,t){return this._client.post("/files",ae({body:e,...t},this._client))}retrieve(e,t){return this._client.get(d`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",v,{query:e,...t})}delete(e,t){return this._client.delete(d`/files/${e}`,t)}content(e,t){return this._client.get(d`/files/${e}/content`,{...t,headers:m([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=30*60*1e3}={}){const r=new Set(["processed","error","deleted"]),i=Date.now();let a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await Ie(t),a=await this.retrieve(e),Date.now()-i>s)throw new It({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}};class En extends w{}let On=class extends w{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Bt extends w{constructor(){super(...arguments),this.graders=new On(this._client)}}Bt.Graders=On;class kn extends w{create(e,t,s){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,tt,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.getAPIList(d`/fine_tuning/checkpoints/${e}/permissions`,v,{query:t,...s})}delete(e,t,s){const{fine_tuned_model_checkpoint:r}=t;return this._client.delete(d`/fine_tuning/checkpoints/${r}/permissions/${e}`,s)}}let Ut=class extends w{constructor(){super(...arguments),this.permissions=new kn(this._client)}};Ut.Permissions=kn;class Pn extends w{list(e,t={},s){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/checkpoints`,v,{query:t,...s})}}class Wt extends w{constructor(){super(...arguments),this.checkpoints=new Pn(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(d`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",v,{query:e,...t})}cancel(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(d`/fine_tuning/jobs/${e}/events`,v,{query:t,...s})}pause(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(d`/fine_tuning/jobs/${e}/resume`,t)}}Wt.Checkpoints=Pn;class de extends w{constructor(){super(...arguments),this.methods=new En(this._client),this.jobs=new Wt(this._client),this.checkpoints=new Ut(this._client),this.alpha=new Bt(this._client)}}de.Methods=En;de.Jobs=Wt;de.Checkpoints=Ut;de.Alpha=Bt;class Tn extends w{}class qt extends w{constructor(){super(...arguments),this.graderModels=new Tn(this._client)}}qt.GraderModels=Tn;class Mn extends w{createVariation(e,t){return this._client.post("/images/variations",ae({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",ae({body:e,...t},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Nn extends w{retrieve(e,t){return this._client.get(d`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",tt,e)}delete(e,t){return this._client.delete(d`/models/${e}`,t)}}class Fn extends w{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Hr(n,e){return!e||!Vr(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(s=>({...s,parsed:null}))}:t)}:Ln(n,e)}function Ln(n,e){const t=n.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:Qr(e,r)};if(r.type==="message"){const i=r.content.map(a=>a.type==="output_text"?{...a,parsed:Xr(e,a.text)}:a);return{...r,content:i}}return r}),s=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||Dn(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const i of r.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),s}function Xr(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function Vr(n){return!!Et(n.text?.format)}function Kr(n){return n?.$brand==="auto-parseable-tool"}function zr(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function Qr(n,e){const t=zr(n.tools??[],e.name);return{...e,...e,parsed_arguments:Kr(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function Dn(n){const e=[];for(const t of n.output)if(t.type==="message")for(const s of t.content)s.type==="output_text"&&e.push(s.text);n.output_text=e.join("")}var le,Ne,te,Fe,gs,ys,ws,bs;class jt extends $t{constructor(e){super(),le.add(this),Ne.set(this,void 0),te.set(this,void 0),Fe.set(this,void 0),y(this,Ne,e)}static createResponse(e,t,s){const r=new jt(t);return r._run(()=>r._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),o(this,le,"m",gs).call(this);let i,a=null;"response_id"in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const l of i)o(this,le,"m",ys).call(this,l,a);if(i.controller.signal?.aborted)throw new V;return o(this,le,"m",ws).call(this)}[(Ne=new WeakMap,te=new WeakMap,Fe=new WeakMap,le=new WeakSet,gs=function(){this.ended||y(this,te,void 0)},ys=function(t,s){if(this.ended)return;const r=(a,l)=>{(s==null||l.sequence_number>s)&&this._emit(a,l)},i=o(this,le,"m",bs).call(this,t);switch(r("event",t),t.type){case"response.output_text.delta":{const a=i.output[t.output_index];if(!a)throw new g(`missing output at index ${t.output_index}`);if(a.type==="message"){const l=a.content[t.content_index];if(!l)throw new g(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new g(`expected content to be 'output_text', got ${l.type}`);r("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const a=i.output[t.output_index];if(!a)throw new g(`missing output at index ${t.output_index}`);a.type==="function_call"&&r("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:r(t.type,t);break}},ws=function(){if(this.ended)throw new g("stream has ended, this shouldn't happen");const t=o(this,te,"f");if(!t)throw new g("request ended without sending any events");y(this,te,void 0);const s=Gr(t,o(this,Ne,"f"));return y(this,Fe,s),s},bs=function(t){let s=o(this,te,"f");if(!s){if(t.type!=="response.created")throw new g(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return s=y(this,te,t.response),s}switch(t.type){case"response.output_item.added":{s.output.push(t.item);break}case"response.content_part.added":{const r=s.output[t.output_index];if(!r)throw new g(`missing output at index ${t.output_index}`);r.type==="message"&&r.content.push(t.part);break}case"response.output_text.delta":{const r=s.output[t.output_index];if(!r)throw new g(`missing output at index ${t.output_index}`);if(r.type==="message"){const i=r.content[t.content_index];if(!i)throw new g(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new g(`expected content to be 'output_text', got ${i.type}`);i.text+=t.delta}break}case"response.function_call_arguments.delta":{const r=s.output[t.output_index];if(!r)throw new g(`missing output at index ${t.output_index}`);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.completed":{y(this,te,t.response);break}}return s},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=o(this,Fe,"f");if(!e)throw new g("stream ended without producing a ChatCompletion");return e}}function Gr(n,e){return Hr(n,e)}class Bn extends w{list(e,t={},s){return this._client.getAPIList(d`/responses/${e}/input_items`,v,{query:t,...s})}}class Jt extends w{constructor(){super(...arguments),this.inputItems=new Bn(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Dn(s),s))}retrieve(e,t={},s){return this._client.get(d`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})}delete(e,t){return this._client.delete(d`/responses/${e}`,{...t,headers:m([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>Ln(s,e))}stream(e,t){return jt.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(d`/responses/${e}/cancel`,t)}}Jt.InputItems=Bn;class Un extends w{create(e,t,s){return this._client.post(d`/uploads/${e}/parts`,ae({body:t,...s},this._client))}}class Ht extends w{constructor(){super(...arguments),this.parts=new Un(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(d`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(d`/uploads/${e}/complete`,{body:t,...s})}}Ht.Parts=Un;const Yr=async n=>{const e=await Promise.allSettled(n),t=e.filter(r=>r.status==="rejected");if(t.length){for(const r of t)console.error(r.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const s=[];for(const r of e)r.status==="fulfilled"&&s.push(r.value);return s};class Wn extends w{create(e,t,s){return this._client.post(d`/vector_stores/${e}/file_batches`,{body:t,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(d`/vector_stores/${r}/file_batches/${e}`,{...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{vector_store_id:r}=t;return this._client.post(d`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t);return await this.poll(e,r.id,s)}listFiles(e,t,s){const{vector_store_id:r,...i}=t;return this._client.getAPIList(d`/vector_stores/${r}/file_batches/${e}/files`,v,{query:i,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){const r=m([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse();switch(i.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const h=a.headers.get("openai-poll-after-ms");if(h){const f=parseInt(h);isNaN(f)||(l=f)}}await Ie(l);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},r){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const i=r?.maxConcurrency??5,a=Math.min(i,t.length),l=this._client,h=t.values(),f=[...s];async function S(_){for(let c of _){const A=await l.files.create({file:c,purpose:"assistants"},r);f.push(A.id)}}const u=Array(a).fill(h).map(S);return await Yr(u),await this.createAndPoll(e,{file_ids:f})}}class qn extends w{create(e,t,s){return this._client.post(d`/vector_stores/${e}/files`,{body:t,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(d`/vector_stores/${r}/files/${e}`,{...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{vector_store_id:r,...i}=t;return this._client.post(d`/vector_stores/${r}/files/${e}`,{body:i,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(d`/vector_stores/${e}/files`,v,{query:t,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{vector_store_id:r}=t;return this._client.delete(d`/vector_stores/${r}/files/${e}`,{...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(e,r.id,s)}async poll(e,t,s){const r=m([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const i=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse(),a=i.data;switch(a.status){case"in_progress":let l=5e3;if(s?.pollIntervalMs)l=s.pollIntervalMs;else{const h=i.response.headers.get("openai-poll-after-ms");if(h){const f=parseInt(h);isNaN(f)||(l=f)}}await Ie(l);break;case"failed":case"completed":return a}}}async upload(e,t,s){const r=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:r.id},s)}async uploadAndPoll(e,t,s){const r=await this.upload(e,t,s);return await this.poll(e,r.id,s)}content(e,t,s){const{vector_store_id:r}=t;return this._client.getAPIList(d`/vector_stores/${r}/files/${e}/content`,tt,{...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class rt extends w{constructor(){super(...arguments),this.files=new qn(this._client),this.fileBatches=new Wn(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(d`/vector_stores/${e}`,{...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(d`/vector_stores/${e}`,{body:t,...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",v,{query:e,...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(d`/vector_stores/${e}`,{...t,headers:m([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(d`/vector_stores/${e}/search`,tt,{body:t,method:"post",...s,headers:m([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}rt.Files=qn;rt.FileBatches=Wn;var Ct,Xt,Je,jn;class x{constructor({baseURL:e=fe("OPENAI_BASE_URL"),apiKey:t=fe("OPENAI_API_KEY"),organization:s=fe("OPENAI_ORG_ID")??null,project:r=fe("OPENAI_PROJECT_ID")??null,...i}={}){if(Ct.add(this),Je.set(this,void 0),this.completions=new Rn(this),this.chat=new Tt(this),this.embeddings=new In(this),this.files=new $n(this),this.images=new Mn(this),this.audio=new $e(this),this.moderations=new Fn(this),this.models=new Nn(this),this.fineTuning=new de(this),this.graders=new qt(this),this.vectorStores=new rt(this),this.beta=new Ee(this),this.batches=new yn(this),this.uploads=new Ht(this),this.responses=new Jt(this),this.evals=new Dt(this),this.containers=new Ft(this),t===void 0)throw new g("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 a={apiKey:t,organization:s,project:r,...i,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&Yn())throw new g(`It looks like you're running in a browser-like environment.
|
|
13
|
+
|
|
14
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
15
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
16
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
17
|
+
|
|
18
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
19
|
+
|
|
20
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
21
|
+
`);this.baseURL=a.baseURL,this.timeout=a.timeout??Xt.DEFAULT_TIMEOUT,this.logger=a.logger??console;const l="warn";this.logLevel=l,this.logLevel=is(a.logLevel,"ClientOptions.logLevel",this)??is(fe("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=a.fetchOptions,this.maxRetries=a.maxRetries??2,this.fetch=a.fetch??nr(),y(this,Je,ir),this._options=a,this.apiKey=t,this.organization=s,this.project=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}authHeaders(e){return m([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return hr(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${ce}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ss()}`}makeStatusError(e,t,s,r){return D.generate(e,t,s,r)}buildURL(e,t,s){const r=!o(this,Ct,"m",jn).call(this)&&s||this.baseURL,i=Xn(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Kn(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:s}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new et(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const r=await e,i=r.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(r);const{req:a,url:l,timeout:h}=this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:l,options:r});const f="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),S=s===void 0?"":`, retryOf: ${s}`,u=Date.now();if(B(this).debug(`[${f}] sending request`,se({retryOfRequestLogID:s,method:r.method,url:l,options:r,headers:a.headers})),r.signal?.aborted)throw new V;const _=new AbortController,c=await this.fetchWithTimeout(l,a,h,_).catch(mt),A=Date.now();if(c instanceof Error){const R=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new V;const p=pt(c)||/timed? ?out/i.test(String(c)+("cause"in c?String(c.cause):""));if(t)return B(this).info(`[${f}] connection ${p?"timed out":"failed"} - ${R}`),B(this).debug(`[${f}] connection ${p?"timed out":"failed"} (${R})`,se({retryOfRequestLogID:s,url:l,durationMs:A-u,message:c.message})),this.retryRequest(r,t,s??f);throw B(this).info(`[${f}] connection ${p?"timed out":"failed"} - error; no more retries left`),B(this).debug(`[${f}] connection ${p?"timed out":"failed"} (error; no more retries left)`,se({retryOfRequestLogID:s,url:l,durationMs:A-u,message:c.message})),p?new It:new Ye({cause:c})}const b=[...c.headers.entries()].filter(([R])=>R==="x-request-id").map(([R,p])=>", "+R+": "+JSON.stringify(p)).join(""),P=`[${f}${S}${b}] ${a.method} ${l} ${c.ok?"succeeded":"failed"} with status ${c.status} in ${A-u}ms`;if(!c.ok){const R=this.shouldRetry(c);if(t&&R){const I=`retrying, ${t} attempts remaining`;return await rr(c.body),B(this).info(`${P} - ${I}`),B(this).debug(`[${f}] response error (${I})`,se({retryOfRequestLogID:s,url:c.url,status:c.status,headers:c.headers,durationMs:A-u})),this.retryRequest(r,t,s??f,c.headers)}const p=R?"error; no more retries left":"error; not retryable";B(this).info(`${P} - ${p}`);const T=await c.text().catch(I=>mt(I).message),C=Gn(T),X=C?void 0:T;throw B(this).debug(`[${f}] response error (${p})`,se({retryOfRequestLogID:s,url:c.url,status:c.status,headers:c.headers,message:X,durationMs:Date.now()-u})),this.makeStatusError(c.status,C,X,c.headers)}return B(this).info(P),B(this).debug(`[${f}] response start`,se({retryOfRequestLogID:s,url:c.url,status:c.status,headers:c.headers,durationMs:A-u})),{response:c,options:r,controller:_,requestLogID:f,retryOfRequestLogID:s,startTime:u}}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new br(this,s,e)}async fetchWithTimeout(e,t,s,r){const{signal:i,method:a,...l}=t||{};i&&i.addEventListener("abort",()=>r.abort());const h=setTimeout(()=>r.abort(),s),f=globalThis.ReadableStream&&l.body instanceof globalThis.ReadableStream||typeof l.body=="object"&&l.body!==null&&Symbol.asyncIterator in l.body,S={signal:r.signal,...f?{duplex:"half"}:{},method:"GET",...l};a&&(S.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,S)}finally{clearTimeout(h)}}shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s,r){let i;const a=r?.get("retry-after-ms");if(a){const h=parseFloat(a);Number.isNaN(h)||(i=h)}const l=r?.get("retry-after");if(l&&!i){const h=parseFloat(l);Number.isNaN(h)?i=Date.parse(l)-Date.now():i=h*1e3}if(!(i&&0<=i&&i<60*1e3)){const h=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,h)}return await Ie(i),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,a=Math.min(.5*Math.pow(2,i),8),l=1-Math.random()*.25;return a*l*1e3}buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:l}=s,h=this.buildURL(i,a,l);"timeout"in s&&Qn("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:f,body:S}=this.buildBody({options:s}),u=this.buildHeaders({options:e,method:r,bodyHeaders:f,retryCount:t});return{req:{method:r,headers:u,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&S instanceof globalThis.ReadableStream&&{duplex:"half"},...S&&{body:S},...this.fetchOptions??{},...s.fetchOptions??{}},url:h,timeout:s.timeout}}buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=m([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...sr(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=m([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Ts(e)}:o(this,Je,"f").call(this,{body:e,headers:s})}}Xt=x,Je=new WeakMap,Ct=new WeakSet,jn=function(){return this.baseURL!=="https://api.openai.com/v1"};x.OpenAI=Xt;x.DEFAULT_TIMEOUT=6e5;x.OpenAIError=g;x.APIError=D;x.APIConnectionError=Ye;x.APIConnectionTimeoutError=It;x.APIUserAbortError=V;x.NotFoundError=Cs;x.ConflictError=Is;x.RateLimitError=$s;x.BadRequestError=xs;x.AuthenticationError=As;x.InternalServerError=Es;x.PermissionDeniedError=Rs;x.UnprocessableEntityError=vs;x.toFile=Ir;x.Completions=Rn;x.Chat=Tt;x.Embeddings=In;x.Files=$n;x.Images=Mn;x.Audio=$e;x.Moderations=Fn;x.Models=Nn;x.FineTuning=de;x.Graders=qt;x.VectorStores=rt;x.Beta=Ee;x.Batches=yn;x.Uploads=Ht;x.Responses=Jt;x.Evals=Dt;x.Containers=Ft;export{Ye as APIConnectionError,It as APIConnectionTimeoutError,D as APIError,et as APIPromise,V as APIUserAbortError,As as AuthenticationError,xs as BadRequestError,Is as ConflictError,Es as InternalServerError,Cs as NotFoundError,x as OpenAI,g as OpenAIError,br as PagePromise,Rs as PermissionDeniedError,$s as RateLimitError,vs as UnprocessableEntityError,x as default,Ir as toFile};
|