@nlux/openai
Advanced tools
Comparing version 0.1.2-beta to 0.1.3-beta
@@ -1,1 +0,1 @@ | ||
"use strict";var e=require("@nlux/nlux");const t=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].delta.content;if("string"==typeof t)return t}}),s=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].message.content;if("string"==typeof t)return t}}),n=Object.freeze({id:"nlux-gpt4-adapter",connectionType:"http",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]}),r="4.14.1";let i,o,a,u,c,l,h,d,p,f=!1;class m{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}i||function(e,t={auto:!1}){if(f)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(i)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${i}'\``);f=t.auto,i=e.kind,o=e.fetch,a=e.FormData,u=e.File,c=e.ReadableStream,l=e.getMultipartRequestOptions,h=e.getDefaultAgent,d=e.fileFromPath,p=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let s,n,r,i;try{s=fetch,n=Request,r=Response,i=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:s,Request:n,Response:r,Headers:i,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new m(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class y extends Error{}class g extends y{constructor(e,t,s,n){super(`${g.makeMessage(e,t,s)}`),this.status=e,this.headers=n;const r=t;this.error=r,this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,s){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e)return new b({cause:le(t)});const r=t?.error;return 400===e?new S(e,r,s,n):401===e?new v(e,r,s,n):403===e?new A(e,r,s,n):404===e?new E(e,r,s,n):409===e?new P(e,r,s,n):422===e?new R(e,r,s,n):429===e?new I(e,r,s,n):e>=500?new M(e,r,s,n):new g(e,r,s,n)}}class w extends g{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}}class b extends g{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}}class x extends b{constructor({message:e}={}){super({message:e??"Request timed out."})}}class S extends g{constructor(){super(...arguments),this.status=400}}class v extends g{constructor(){super(...arguments),this.status=401}}class A extends g{constructor(){super(...arguments),this.status=403}}class E extends g{constructor(){super(...arguments),this.status=404}}class P extends g{constructor(){super(...arguments),this.status=409}}class R extends g{constructor(){super(...arguments),this.status=422}}class I extends g{constructor(){super(...arguments),this.status=429}}class M extends g{}class k{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let s=!1;const n=new T;return new k((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let r=!1;try{for await(const s of async function*(){if(!e.body)throw t.abort(),new y("Attempted to iterate over a response with no body");const s=new O,r=C(e.body);for await(const e of r)for(const t of s.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of s.flush()){const t=n.decode(e);t&&(yield t)}}())if(!r)if(s.data.startsWith("[DONE]"))r=!0;else if(null===s.event){let e;try{e=JSON.parse(s.data)}catch(e){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),e}if(e&&e.error)throw new g(void 0,e.error,void 0,void 0);yield e}r=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{r||t.abort()}}),t)}static fromReadableStream(e,t){let s=!1;return new k((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(const t of async function*(){const t=new O,s=C(e);for await(const e of s)for(const s of t.decode(e))yield s;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=s.next();e.push(n),t.push(n)}return n.shift()}});return[new k((()=>n(e)),this.controller),new k((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const s=new TextEncoder;return new c({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:r}=await t.next();if(r)return e.close();const i=s.encode(JSON.stringify(n)+"\n");e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class T{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=function(e,t){const s=e.indexOf(t);if(-1!==s)return[e.substring(0,s),t,e.substring(s+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}class O{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];const s=O.NEWLINE_CHARS.has(t[t.length-1]||"");let n=t.split(O.NEWLINE_REGEXP);return 1!==n.length||s?(this.buffer.length>0&&(n=[this.buffer.join("")+n[0],...n.slice(1)],this.buffer=[]),s||(this.buffer=[n.pop()||""]),n):(this.buffer.push(n[0]),[])}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new y(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new y(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new y("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}function C(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}O.NEWLINE_CHARS=new Set(["\n","\r","\v","\f","","",""," ","\u2028","\u2029"]),O.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;const U=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,D=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,$=e=>(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&D(e))(e)||U(e)||p(e);async function j(e,t,s={}){if(e=await e,U(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new u([n],t,s)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(D(e))t.push(await e.arrayBuffer());else{if(!F(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const s of e)t.push(s)}return t}(e);if(t||(t=function(e){return N(e.name)||N(e.filename)||N(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!s.type){const e=n[0]?.type;"string"==typeof e&&(s={...s,type:e})}return new u(n,t,s)}const N=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,F=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],q=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],L=async e=>{const t=await K(e.body);return l(t,e)},K=async e=>{const t=new a;return await Promise.all(Object.entries(e||{}).map((([e,s])=>X(t,e,s)))),t},X=async(e,t,s)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if($(s)){const n=await j(s);e.append(t,n)}else if(Array.isArray(s))await Promise.all(s.map((s=>X(e,t+"[]",s))));else{if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map((([s,n])=>X(e,`${t}[${s}]`,n))))}}};var B,H=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},W=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)};async function _(e){const{response:t}=e;if(e.options.stream)return k.fromSSEResponse(t,e.controller);if(204===t.status)return null;const s=t.headers.get("content-type");if(s?.includes("application/json")){return await t.json()}return await t.text()}class J extends Promise{constructor(e,t=_){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new J(this.responsePromise,(async t=>e(await this.parseResponse(t))))}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}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class z{constructor({baseURL:e,maxRetries:t=2,timeout:s=6e5,httpAgent:n,fetch:r}){this.baseURL=e,this.maxRetries=ce("maxRetries",t),this.timeout=ce("timeout",s),this.httpAgent=n,this.fetch=r??o}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...re(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${pe()}`}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((s=>({method:e,path:t,...s}))))}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}return null}buildRequest(e){const{method:t,path:s,query:n,headers:r={}}=e,o=q(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,a=this.calculateContentLength(o),u=this.buildURL(s,n);"timeout"in e&&ce("timeout",e.timeout);const c=e.timeout??this.timeout,l=e.httpAgent??this.httpAgent??h(u),d=c+1e3;"number"==typeof l?.options?.timeout&&d>(l.options.timeout??0)&&(l.options.timeout=d),this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);const p={...a&&{"Content-Length":a},...this.defaultHeaders(e),...r};q(e.body)&&"node"!==i&&delete p["Content-Type"],Object.keys(p).forEach((e=>null===p[e]&&delete p[e]));const f={method:t,...o&&{body:o},headers:p,...l&&{agent:l},signal:e.signal??null};return this.validateHeaders(p,r),{req:f,url:u,timeout:c}}async prepareRequest(e,{url:t,options:s}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,s,n){return g.generate(e,t,s,n)}request(e,t=null){return new J(this.makeRequest(e,t))}async makeRequest(e,t){const s=await e;null==t&&(t=s.maxRetries??this.maxRetries);const{req:n,url:r,timeout:i}=this.buildRequest(s);if(await this.prepareRequest(n,{url:r,options:s}),s.signal?.aborted)throw new w;const o=new AbortController,a=await this.fetchWithTimeout(r,n,i,o).catch(le);if(a instanceof Error){if(s.signal?.aborted)throw new w;if(t)return this.retryRequest(s,t);if("AbortError"===a.name)throw new x;throw new b({cause:a})}const u=Y(a.headers);if(!a.ok){if(t&&this.shouldRetry(a))return this.retryRequest(s,t,u);const e=await a.text().catch((e=>le(e).message)),n=ie(e),r=n?void 0:e;throw this.makeStatusError(a.status,n,r,u)}return{response:a,options:s,controller:o}}requestAPIList(e,t){const s=this.makeRequest(t,null);return new G(this,s,e)}buildURL(e,t){const s=ae(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return de(n)||(t={...n,...t}),t&&(s.search=this.stringifyQuery(t)),s.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new y(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,s,n){const{signal:r,...i}=t||{};r&&r.addEventListener("abort",(()=>n.abort()));const o=setTimeout((()=>n.abort()),s);return this.getRequestClient().fetch.call(void 0,e,{signal:n.signal,...i}).finally((()=>{clearTimeout(o)}))}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,s){let n;const r=s?.["retry-after"];if(r){const e=parseInt(r);n=Number.isNaN(e)?Date.parse(r)-Date.now():1e3*e}if(!n||!Number.isInteger(n)||n<=0||n>6e4){const s=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,s)}return await ue(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${r}`}}class V{constructor(e,t,s,n){B.set(this,void 0),H(this,B,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e)t.query={...t.query,...e.params};else if("url"in e){const s=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of s)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await W(this,B,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(B=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class G extends J{constructor(e,t,s){super(t,(async t=>new s(e,t.response,await _(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const Y=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const s=t.toString();return e[s.toLowerCase()]||e[s]}}),Q={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0},Z=e=>"object"==typeof e&&null!==e&&!de(e)&&Object.keys(e).every((e=>function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(Q,e))),ee=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r,"X-Stainless-OS":se(Deno.build.os),"X-Stainless-Arch":te(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":Deno.version};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r,"X-Stainless-OS":se(process.platform),"X-Stainless-Arch":te(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const e=s.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":r,"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":r,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const te=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",se=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let ne;const re=()=>ne??(ne=ee()),ie=e=>{try{return JSON.parse(e)}catch(e){return}},oe=new RegExp("^(?:[a-z]+:)?//","i"),ae=e=>oe.test(e),ue=e=>new Promise((t=>setTimeout(t,e))),ce=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new y(`${e} must be an integer`);if(t<0)throw new y(`${e} must be a positive integer`);return t},le=e=>e instanceof Error?e:new Error(e),he=e=>"undefined"!=typeof process?process.env?.[e]??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e):void 0;function de(e){if(!e)return!0;for(const t in e)return!1;return!0}const pe=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));class fe extends V{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data,this.object=s.object}getPaginatedItems(){return this.data}nextPageParams(){return null}nextPageInfo(){return null}}class me extends V{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data}getPaginatedItems(){return this.data}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(!this.data?.length)return null;const e=this.data[this.data.length-1]?.id;return e?{params:{after:e}}:null}}class ye{constructor(e){this.client=e,this.get=e.get.bind(e),this.post=e.post.bind(e),this.patch=e.patch.bind(e),this.put=e.put.bind(e),this.delete=e.delete.bind(e),this.getAPIList=e.getAPIList.bind(e)}}let ge=class extends ye{create(e,t){return this.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}};ge||(ge={});class we extends ye{constructor(){super(...arguments),this.completions=new ge(this.client)}}!function(e){e.Completions=ge}(we||(we={}));class be extends ye{create(e,t){return this.post("/audio/transcriptions",L({body:e,...t}))}}be||(be={});class xe extends ye{create(e,t){return this.post("/audio/translations",L({body:e,...t}))}}xe||(xe={});class Se extends ye{constructor(){super(...arguments),this.transcriptions=new be(this.client),this.translations=new xe(this.client)}}!function(e){e.Transcriptions=be,e.Translations=xe}(Se||(Se={}));class ve extends ye{create(e,t){return this.post("/completions",{body:e,...t,stream:e.stream??!1})}}ve||(ve={});class Ae extends ye{create(e,t){return this.post("/embeddings",{body:e,...t})}}Ae||(Ae={});class Ee extends ye{create(e,t){return this.post("/edits",{body:e,...t})}}Ee||(Ee={});class Pe extends ye{create(e,t){return this.post("/files",L({body:e,...t}))}retrieve(e,t){return this.get(`/files/${e}`,t)}list(e){return this.getAPIList("/files",Re,e)}del(e,t){return this.delete(`/files/${e}`,t)}retrieveContent(e,t){return this.get(`/files/${e}/content`,{...t,headers:{Accept:"application/json",...t?.headers}})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){const n=new Set(["processed","error","deleted"]),r=Date.now();let i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await ue(t),i=await this.retrieve(e),Date.now()-r>s)throw new x({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}}class Re extends fe{}!function(e){e.FileObjectsPage=Re}(Pe||(Pe={}));class Ie extends ye{create(e,t){return this.post("/fine-tunes",{body:e,...t})}retrieve(e,t){return this.get(`/fine-tunes/${e}`,t)}list(e){return this.getAPIList("/fine-tunes",Me,e)}cancel(e,t){return this.post(`/fine-tunes/${e}/cancel`,t)}listEvents(e,t,s){return this.get(`/fine-tunes/${e}/events`,{query:t,timeout:864e5,...s,stream:t?.stream??!1})}}class Me extends fe{}!function(e){e.FineTunesPage=Me}(Ie||(Ie={}));class ke extends ye{create(e,t){return this.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return Z(e)?this.list({},e):this.getAPIList("/fine_tuning/jobs",Te,{query:e,...t})}cancel(e,t){return this.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return Z(t)?this.listEvents(e,{},t):this.getAPIList(`/fine_tuning/jobs/${e}/events`,Oe,{query:t,...s})}}class Te extends me{}class Oe extends me{}!function(e){e.FineTuningJobsPage=Te,e.FineTuningJobEventsPage=Oe}(ke||(ke={}));class Ce extends ye{constructor(){super(...arguments),this.jobs=new ke(this.client)}}!function(e){e.Jobs=ke,e.FineTuningJobsPage=Te,e.FineTuningJobEventsPage=Oe}(Ce||(Ce={}));class Ue extends ye{createVariation(e,t){return this.post("/images/variations",L({body:e,...t}))}edit(e,t){return this.post("/images/edits",L({body:e,...t}))}generate(e,t){return this.post("/images/generations",{body:e,...t})}}Ue||(Ue={});class De extends ye{retrieve(e,t){return this.get(`/models/${e}`,t)}list(e){return this.getAPIList("/models",$e,e)}del(e,t){return this.delete(`/models/${e}`,t)}}class $e extends fe{}!function(e){e.ModelsPage=$e}(De||(De={}));class je extends ye{create(e,t){return this.post("/moderations",{body:e,...t})}}var Ne;je||(je={});class Fe extends z{constructor({apiKey:e=he("OPENAI_API_KEY"),organization:t=he("OPENAI_ORG_ID")??null,...s}={}){if(void 0===e)throw new y("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const n={apiKey:e,organization:t,...s,baseURL:s.baseURL??"https://api.openai.com/v1"};if(!n.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new y("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:n.baseURL,timeout:n.timeout??6e5,httpAgent:n.httpAgent,maxRetries:n.maxRetries,fetch:n.fetch}),this.completions=new ve(this),this.chat=new we(this),this.edits=new Ee(this),this.embeddings=new Ae(this),this.files=new Pe(this),this.images=new Ue(this),this.audio=new Se(this),this.moderations=new je(this),this.models=new De(this),this.fineTuning=new Ce(this),this.fineTunes=new Ie(this),this._options=n,this.apiKey=e,this.organization=t}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}}Ne=Fe,Fe.OpenAI=Ne,Fe.OpenAIError=y,Fe.APIError=g,Fe.APIConnectionError=b,Fe.APIConnectionTimeoutError=x,Fe.APIUserAbortError=w,Fe.NotFoundError=E,Fe.ConflictError=P,Fe.RateLimitError=I,Fe.BadRequestError=S,Fe.AuthenticationError=v,Fe.InternalServerError=M,Fe.PermissionDeniedError=A,Fe.UnprocessableEntityError=R,function(e){e.toFile=j,e.fileFromPath=d,e.Page=fe,e.CursorPage=me,e.Completions=ve,e.Chat=we,e.Edits=Ee,e.Embeddings=Ae,e.Files=Pe,e.FileObjectsPage=Re,e.Images=Ue,e.Audio=Se,e.Moderations=je,e.Models=De,e.ModelsPage=$e,e.FineTuning=Ce,e.FineTunes=Ie,e.FineTunesPage=Me}(Fe||(Fe={}));var qe=Fe;class Le{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,dataExchangeMode:r}){this.actAsMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.dataExchangeMode="fetch",this.currentStatus="disconnected",this.historyDepthToInclude=n??2,this.timeout=s,this.dataExchangeMode=r,this.openai=new qe({apiKey:t,dangerouslyAllowBrowser:!0}),e&&(this.actAsMessage=e),console.warn('GPT-4 adapter has been initialized in browser mode using option "dangerouslyAllowBrowser". This is not recommended for production use. We recommend that you implement a server-side proxy and configure a customized adapter for it. Read more at https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety')}get id(){return this.info.id}get info(){return n}get status(){return this.currentStatus}async decode(e){const{decodeMessage:t}=this.config;return t(e)}async encode(e){const{encodeMessage:t}=this.config;return t(e)}}class Ke extends Le{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,dataExchangeMode:"fetch"})}get config(){return s}send(t){if("string"!=typeof t||0===t.length)throw new e.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const s=new e.Observable,n=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return n.push({role:"user",content:t}),this.openai.chat.completions.create({stream:!1,model:"gpt-4",messages:n}).then((async e=>{const t=await this.decode(e);void 0!==t&&s.next(t),s.complete()})),s}}const Xe=class t{constructor(e){this.apiKey=null,this.dataExchangeMode="fetch",this.historyDepth="max",this.timeout=t.defaultTimeout,this.initialSystemMessage=null,this.setApiKeyCalled=!1,this.setHistoryDepthCalled=!1,this.setInitialSystemMessageCalled=!1,this.setStreamOrFetchCalled=!1,this.setTimeOutCalled=!1,e&&(this.apiKey=e.apiKey,this.dataExchangeMode=e.dataExchangeMode,this.historyDepth=e.historyDepth,this.timeout=e.timeout,this.setApiKeyCalled=e.setApiKeyCalled,this.setHistoryDepthCalled=e.setHistoryDepthCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled,this.setTimeOutCalled=e.setTimeOutCalled)}withApiKey(t){if(this.setApiKeyCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set API key. API key setter has already been called by this builder. Make sure you are not calling useApiKey() twice."});return this.apiKey=t,this.setApiKeyCalled=!0,this}withHistoryDepth(t="max"){if(this.setHistoryDepthCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set history depth. History depth setter has already been called by this builder. Make sure you are not calling includeHistoryDepth() twice."});return this.historyDepth=t,this.setHistoryDepthCalled=!0,this}withInitialSystemMessage(t){if(this.setInitialSystemMessageCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set initial system message. Initial system message setter has already been called by this builder. Make sure you are not calling withInitialSystemMessage() twice."});return this.initialSystemMessage=t??null,this.setInitialSystemMessageCalled=!0,this}withTimeout(t){if(this.setTimeOutCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set timeout. Timeout setter has already been called by this builder. Make sure you are not calling withTimeout() twice."});return this.timeout=t,this.setTimeOutCalled=!0,this}};Xe.defaultTimeout=3e4;let Be=Xe;class He extends Le{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,initialSystemMessage:r}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,dataExchangeMode:"fetch"}),this.initialSystemMessage=null,this.shouldSendInitialSystemMessage=!1,void 0!==r&&r.length>0&&(this.initialSystemMessage=r,this.shouldSendInitialSystemMessage=!0)}get config(){return t}send(t){if("string"!=typeof t||0===t.length)throw new e.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const s=new e.Observable,n=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return console.dir(this.shouldSendInitialSystemMessage),this.shouldSendInitialSystemMessage&&(n.push({role:"system",content:this.initialSystemMessage}),this.shouldSendInitialSystemMessage=!1),n.push({role:"user",content:t}),this.openai.chat.completions.create({stream:!0,model:"gpt-4",messages:n}).then((async e=>{let t=e[Symbol.asyncIterator](),n=await t.next();for(;!n.done;){const e=n.value,r=await this.decode(e);void 0!==r&&s.next(r),n=await t.next()}s.complete()})),s}}class We extends Be{constructor(e){super(e),this.dataExchangeMode="stream"}create(){if(!this.apiKey)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});return new He({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth,initialSystemMessage:this.initialSystemMessage??void 0})}useFetchingMode(){throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to fetch. This builder is configured to use the stream API. You cannot change it to use the fetch API."})}useStreamingMode(){throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to stream. This builder is already configured to use the stream API."})}}class _e extends Be{constructor(){super()}create(){if(!this.apiKey)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});if("stream"===this.dataExchangeMode)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. This builder is configured to use the stream API because useStreamingMode() was called. You should call use the builder instance returned by useStreamingMode() to create the builder."});return new Ke({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth})}useFetchingMode(){if(this.setStreamOrFetchCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to fetch. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="fetch",this.setStreamOrFetchCalled=!0,this}useStreamingMode(){if(this.setStreamOrFetchCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to stream. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="stream",this.setStreamOrFetchCalled=!0,new We(this)}}exports.Gpt4FetchAdapter=Ke,exports.Gpt4StreamingAdapter=He,exports.createAdapter=t=>{if("openai/gpt4"!==t)throw new e.NluxUsageError({source:"createAdapter",message:"Adapter type not supported"});return new _e}; | ||
"use strict";var e=require("@nlux/nlux"),t=require("openai");const s=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].delta.content;if("string"==typeof t)return t}}),a=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].message.content;if("string"==typeof t)return t}}),i=Object.freeze({id:"nlux-gpt4-adapter",connectionType:"http",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]});class r{constructor({actAs:e,apiKey:s,timeout:a,historyDepthToInclude:i,dataExchangeMode:r}){this.actAsMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.dataExchangeMode="fetch",this.currentStatus="disconnected",this.historyDepthToInclude=i??2,this.timeout=a,this.dataExchangeMode=r,this.openai=new t({apiKey:s,dangerouslyAllowBrowser:!0}),e&&(this.actAsMessage=e),console.warn('GPT-4 adapter has been initialized in browser mode using option "dangerouslyAllowBrowser". This is not recommended for production use. We recommend that you implement a server-side proxy and configure a customized adapter for it. Read more at https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety')}get id(){return this.info.id}get info(){return i}get status(){return this.currentStatus}async decode(e){const{decodeMessage:t}=this.config;return t(e)}async encode(e){const{encodeMessage:t}=this.config;return t(e)}}class o extends r{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a,dataExchangeMode:"fetch"})}get config(){return a}send(t){if("string"!=typeof t||0===t.length)throw new e.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const s=new e.Observable,a=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return a.push({role:"user",content:t}),this.openai.chat.completions.create({stream:!1,model:"gpt-4",messages:a}).then((async e=>{const t=await this.decode(e);void 0!==t&&s.next(t),s.complete()})),s}}const n=class t{constructor(e){this.apiKey=null,this.dataExchangeMode="fetch",this.historyDepth="max",this.timeout=t.defaultTimeout,this.initialSystemMessage=null,this.setApiKeyCalled=!1,this.setHistoryDepthCalled=!1,this.setInitialSystemMessageCalled=!1,this.setStreamOrFetchCalled=!1,this.setTimeOutCalled=!1,e&&(this.apiKey=e.apiKey,this.dataExchangeMode=e.dataExchangeMode,this.historyDepth=e.historyDepth,this.timeout=e.timeout,this.setApiKeyCalled=e.setApiKeyCalled,this.setHistoryDepthCalled=e.setHistoryDepthCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled,this.setTimeOutCalled=e.setTimeOutCalled)}withApiKey(t){if(this.setApiKeyCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set API key. API key setter has already been called by this builder. Make sure you are not calling useApiKey() twice."});return this.apiKey=t,this.setApiKeyCalled=!0,this}withHistoryDepth(t="max"){if(this.setHistoryDepthCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set history depth. History depth setter has already been called by this builder. Make sure you are not calling includeHistoryDepth() twice."});return this.historyDepth=t,this.setHistoryDepthCalled=!0,this}withInitialSystemMessage(t){if(this.setInitialSystemMessageCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set initial system message. Initial system message setter has already been called by this builder. Make sure you are not calling withInitialSystemMessage() twice."});return this.initialSystemMessage=t??null,this.setInitialSystemMessageCalled=!0,this}withTimeout(t){if(this.setTimeOutCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set timeout. Timeout setter has already been called by this builder. Make sure you are not calling withTimeout() twice."});return this.timeout=t,this.setTimeOutCalled=!0,this}};n.defaultTimeout=3e4;let h=n;class c extends r{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a,initialSystemMessage:i}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a,dataExchangeMode:"fetch"}),this.initialSystemMessage=null,this.shouldSendInitialSystemMessage=!1,void 0!==i&&i.length>0&&(this.initialSystemMessage=i,this.shouldSendInitialSystemMessage=!0)}get config(){return s}send(t){if("string"!=typeof t||0===t.length)throw new e.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const s=new e.Observable,a=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return console.dir(this.shouldSendInitialSystemMessage),this.shouldSendInitialSystemMessage&&(a.push({role:"system",content:this.initialSystemMessage}),this.shouldSendInitialSystemMessage=!1),a.push({role:"user",content:t}),this.openai.chat.completions.create({stream:!0,model:"gpt-4",messages:a}).then((async e=>{let t=e[Symbol.asyncIterator](),a=await t.next();for(;!a.done;){const e=a.value,i=await this.decode(e);void 0!==i&&s.next(i),a=await t.next()}s.complete()})),s}}class l extends h{constructor(e){super(e),this.dataExchangeMode="stream"}create(){if(!this.apiKey)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});return new c({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth,initialSystemMessage:this.initialSystemMessage??void 0})}useFetchingMode(){throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to fetch. This builder is configured to use the stream API. You cannot change it to use the fetch API."})}useStreamingMode(){throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to stream. This builder is already configured to use the stream API."})}}class u extends h{constructor(){super()}create(){if(!this.apiKey)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});if("stream"===this.dataExchangeMode)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. This builder is configured to use the stream API because useStreamingMode() was called. You should call use the builder instance returned by useStreamingMode() to create the builder."});return new o({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth})}useFetchingMode(){if(this.setStreamOrFetchCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to fetch. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="fetch",this.setStreamOrFetchCalled=!0,this}useStreamingMode(){if(this.setStreamOrFetchCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to stream. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="stream",this.setStreamOrFetchCalled=!0,new l(this)}}exports.Gpt4FetchAdapter=o,exports.Gpt4StreamingAdapter=c,exports.createAdapter=t=>{if("openai/gpt4"!==t)throw new e.NluxUsageError({source:"createAdapter",message:"Adapter type not supported"});return new u}; |
@@ -1,1 +0,1 @@ | ||
import{NluxUsageError as e,Observable as t}from"@nlux/nlux";const s=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].delta.content;if("string"==typeof t)return t}}),n=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].message.content;if("string"==typeof t)return t}}),r=Object.freeze({id:"nlux-gpt4-adapter",connectionType:"http",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]}),i="4.14.1";let o,a,u,c,l,h,d,p,f,m=!1;class y{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}o||function(e,t={auto:!1}){if(m)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(o)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${o}'\``);m=t.auto,o=e.kind,a=e.fetch,u=e.FormData,c=e.File,l=e.ReadableStream,h=e.getMultipartRequestOptions,d=e.getDefaultAgent,p=e.fileFromPath,f=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let s,n,r,i;try{s=fetch,n=Request,r=Response,i=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:s,Request:n,Response:r,Headers:i,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new y(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class g extends Error{}class w extends g{constructor(e,t,s,n){super(`${w.makeMessage(e,t,s)}`),this.status=e,this.headers=n;const r=t;this.error=r,this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,s){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e)return new x({cause:he(t)});const r=t?.error;return 400===e?new v(e,r,s,n):401===e?new A(e,r,s,n):403===e?new P(e,r,s,n):404===e?new R(e,r,s,n):409===e?new E(e,r,s,n):422===e?new I(e,r,s,n):429===e?new M(e,r,s,n):e>=500?new k(e,r,s,n):new w(e,r,s,n)}}class b extends w{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}}class x extends w{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}}class S extends x{constructor({message:e}={}){super({message:e??"Request timed out."})}}class v extends w{constructor(){super(...arguments),this.status=400}}class A extends w{constructor(){super(...arguments),this.status=401}}class P extends w{constructor(){super(...arguments),this.status=403}}class R extends w{constructor(){super(...arguments),this.status=404}}class E extends w{constructor(){super(...arguments),this.status=409}}class I extends w{constructor(){super(...arguments),this.status=422}}class M extends w{constructor(){super(...arguments),this.status=429}}class k extends w{}class T{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let s=!1;const n=new C;return new T((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let r=!1;try{for await(const s of async function*(){if(!e.body)throw t.abort(),new g("Attempted to iterate over a response with no body");const s=new O,r=D(e.body);for await(const e of r)for(const t of s.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of s.flush()){const t=n.decode(e);t&&(yield t)}}())if(!r)if(s.data.startsWith("[DONE]"))r=!0;else if(null===s.event){let e;try{e=JSON.parse(s.data)}catch(e){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),e}if(e&&e.error)throw new w(void 0,e.error,void 0,void 0);yield e}r=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{r||t.abort()}}),t)}static fromReadableStream(e,t){let s=!1;return new T((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(const t of async function*(){const t=new O,s=D(e);for await(const e of s)for(const s of t.decode(e))yield s;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=s.next();e.push(n),t.push(n)}return n.shift()}});return[new T((()=>n(e)),this.controller),new T((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const s=new TextEncoder;return new l({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:r}=await t.next();if(r)return e.close();const i=s.encode(JSON.stringify(n)+"\n");e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class C{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=function(e,t){const s=e.indexOf(t);if(-1!==s)return[e.substring(0,s),t,e.substring(s+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}class O{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];const s=O.NEWLINE_CHARS.has(t[t.length-1]||"");let n=t.split(O.NEWLINE_REGEXP);return 1!==n.length||s?(this.buffer.length>0&&(n=[this.buffer.join("")+n[0],...n.slice(1)],this.buffer=[]),s||(this.buffer=[n.pop()||""]),n):(this.buffer.push(n[0]),[])}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new g(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new g(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new g("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}function D(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}O.NEWLINE_CHARS=new Set(["\n","\r","\v","\f","","",""," ","\u2028","\u2029"]),O.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;const $=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,j=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,F=e=>(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&j(e))(e)||$(e)||f(e);async function q(e,t,s={}){if(e=await e,$(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new c([n],t,s)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(j(e))t.push(await e.arrayBuffer());else{if(!L(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const s of e)t.push(s)}return t}(e);if(t||(t=function(e){return U(e.name)||U(e.filename)||U(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!s.type){const e=n[0]?.type;"string"==typeof e&&(s={...s,type:e})}return new c(n,t,s)}const U=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,L=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],K=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],N=async e=>{const t=await X(e.body);return h(t,e)},X=async e=>{const t=new u;return await Promise.all(Object.entries(e||{}).map((([e,s])=>B(t,e,s)))),t},B=async(e,t,s)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if(F(s)){const n=await q(s);e.append(t,n)}else if(Array.isArray(s))await Promise.all(s.map((s=>B(e,t+"[]",s))));else{if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map((([s,n])=>B(e,`${t}[${s}]`,n))))}}};var H,W=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},_=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)};async function J(e){const{response:t}=e;if(e.options.stream)return T.fromSSEResponse(t,e.controller);if(204===t.status)return null;const s=t.headers.get("content-type");if(s?.includes("application/json")){return await t.json()}return await t.text()}class z extends Promise{constructor(e,t=J){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new z(this.responsePromise,(async t=>e(await this.parseResponse(t))))}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}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class V{constructor({baseURL:e,maxRetries:t=2,timeout:s=6e5,httpAgent:n,fetch:r}){this.baseURL=e,this.maxRetries=le("maxRetries",t),this.timeout=le("timeout",s),this.httpAgent=n,this.fetch=r??a}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...ie(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${fe()}`}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((s=>({method:e,path:t,...s}))))}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}return null}buildRequest(e){const{method:t,path:s,query:n,headers:r={}}=e,i=K(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,a=this.calculateContentLength(i),u=this.buildURL(s,n);"timeout"in e&&le("timeout",e.timeout);const c=e.timeout??this.timeout,l=e.httpAgent??this.httpAgent??d(u),h=c+1e3;"number"==typeof l?.options?.timeout&&h>(l.options.timeout??0)&&(l.options.timeout=h),this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);const p={...a&&{"Content-Length":a},...this.defaultHeaders(e),...r};K(e.body)&&"node"!==o&&delete p["Content-Type"],Object.keys(p).forEach((e=>null===p[e]&&delete p[e]));const f={method:t,...i&&{body:i},headers:p,...l&&{agent:l},signal:e.signal??null};return this.validateHeaders(p,r),{req:f,url:u,timeout:c}}async prepareRequest(e,{url:t,options:s}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,s,n){return w.generate(e,t,s,n)}request(e,t=null){return new z(this.makeRequest(e,t))}async makeRequest(e,t){const s=await e;null==t&&(t=s.maxRetries??this.maxRetries);const{req:n,url:r,timeout:i}=this.buildRequest(s);if(await this.prepareRequest(n,{url:r,options:s}),s.signal?.aborted)throw new b;const o=new AbortController,a=await this.fetchWithTimeout(r,n,i,o).catch(he);if(a instanceof Error){if(s.signal?.aborted)throw new b;if(t)return this.retryRequest(s,t);if("AbortError"===a.name)throw new S;throw new x({cause:a})}const u=Q(a.headers);if(!a.ok){if(t&&this.shouldRetry(a))return this.retryRequest(s,t,u);const e=await a.text().catch((e=>he(e).message)),n=oe(e),r=n?void 0:e;throw this.makeStatusError(a.status,n,r,u)}return{response:a,options:s,controller:o}}requestAPIList(e,t){const s=this.makeRequest(t,null);return new Y(this,s,e)}buildURL(e,t){const s=ue(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return pe(n)||(t={...n,...t}),t&&(s.search=this.stringifyQuery(t)),s.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new g(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,s,n){const{signal:r,...i}=t||{};r&&r.addEventListener("abort",(()=>n.abort()));const o=setTimeout((()=>n.abort()),s);return this.getRequestClient().fetch.call(void 0,e,{signal:n.signal,...i}).finally((()=>{clearTimeout(o)}))}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,s){let n;const r=s?.["retry-after"];if(r){const e=parseInt(r);n=Number.isNaN(e)?Date.parse(r)-Date.now():1e3*e}if(!n||!Number.isInteger(n)||n<=0||n>6e4){const s=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,s)}return await ce(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${i}`}}class G{constructor(e,t,s,n){H.set(this,void 0),W(this,H,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e)t.query={...t.query,...e.params};else if("url"in e){const s=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of s)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await _(this,H,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(H=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Y extends z{constructor(e,t,s){super(t,(async t=>new s(e,t.response,await J(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const Q=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const s=t.toString();return e[s.toLowerCase()]||e[s]}}),Z={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0},ee=e=>"object"==typeof e&&null!==e&&!pe(e)&&Object.keys(e).every((e=>function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(Z,e))),te=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i,"X-Stainless-OS":ne(Deno.build.os),"X-Stainless-Arch":se(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":Deno.version};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i,"X-Stainless-OS":ne(process.platform),"X-Stainless-Arch":se(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const e=s.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i,"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":i,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const se=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ne=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let re;const ie=()=>re??(re=te()),oe=e=>{try{return JSON.parse(e)}catch(e){return}},ae=new RegExp("^(?:[a-z]+:)?//","i"),ue=e=>ae.test(e),ce=e=>new Promise((t=>setTimeout(t,e))),le=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new g(`${e} must be an integer`);if(t<0)throw new g(`${e} must be a positive integer`);return t},he=e=>e instanceof Error?e:new Error(e),de=e=>"undefined"!=typeof process?process.env?.[e]??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e):void 0;function pe(e){if(!e)return!0;for(const t in e)return!1;return!0}const fe=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));class me extends G{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data,this.object=s.object}getPaginatedItems(){return this.data}nextPageParams(){return null}nextPageInfo(){return null}}class ye extends G{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data}getPaginatedItems(){return this.data}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(!this.data?.length)return null;const e=this.data[this.data.length-1]?.id;return e?{params:{after:e}}:null}}class ge{constructor(e){this.client=e,this.get=e.get.bind(e),this.post=e.post.bind(e),this.patch=e.patch.bind(e),this.put=e.put.bind(e),this.delete=e.delete.bind(e),this.getAPIList=e.getAPIList.bind(e)}}let we=class extends ge{create(e,t){return this.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}};we||(we={});class be extends ge{constructor(){super(...arguments),this.completions=new we(this.client)}}!function(e){e.Completions=we}(be||(be={}));class xe extends ge{create(e,t){return this.post("/audio/transcriptions",N({body:e,...t}))}}xe||(xe={});class Se extends ge{create(e,t){return this.post("/audio/translations",N({body:e,...t}))}}Se||(Se={});class ve extends ge{constructor(){super(...arguments),this.transcriptions=new xe(this.client),this.translations=new Se(this.client)}}!function(e){e.Transcriptions=xe,e.Translations=Se}(ve||(ve={}));class Ae extends ge{create(e,t){return this.post("/completions",{body:e,...t,stream:e.stream??!1})}}Ae||(Ae={});class Pe extends ge{create(e,t){return this.post("/embeddings",{body:e,...t})}}Pe||(Pe={});class Re extends ge{create(e,t){return this.post("/edits",{body:e,...t})}}Re||(Re={});class Ee extends ge{create(e,t){return this.post("/files",N({body:e,...t}))}retrieve(e,t){return this.get(`/files/${e}`,t)}list(e){return this.getAPIList("/files",Ie,e)}del(e,t){return this.delete(`/files/${e}`,t)}retrieveContent(e,t){return this.get(`/files/${e}/content`,{...t,headers:{Accept:"application/json",...t?.headers}})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){const n=new Set(["processed","error","deleted"]),r=Date.now();let i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await ce(t),i=await this.retrieve(e),Date.now()-r>s)throw new S({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}}class Ie extends me{}!function(e){e.FileObjectsPage=Ie}(Ee||(Ee={}));class Me extends ge{create(e,t){return this.post("/fine-tunes",{body:e,...t})}retrieve(e,t){return this.get(`/fine-tunes/${e}`,t)}list(e){return this.getAPIList("/fine-tunes",ke,e)}cancel(e,t){return this.post(`/fine-tunes/${e}/cancel`,t)}listEvents(e,t,s){return this.get(`/fine-tunes/${e}/events`,{query:t,timeout:864e5,...s,stream:t?.stream??!1})}}class ke extends me{}!function(e){e.FineTunesPage=ke}(Me||(Me={}));class Te extends ge{create(e,t){return this.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return ee(e)?this.list({},e):this.getAPIList("/fine_tuning/jobs",Ce,{query:e,...t})}cancel(e,t){return this.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return ee(t)?this.listEvents(e,{},t):this.getAPIList(`/fine_tuning/jobs/${e}/events`,Oe,{query:t,...s})}}class Ce extends ye{}class Oe extends ye{}!function(e){e.FineTuningJobsPage=Ce,e.FineTuningJobEventsPage=Oe}(Te||(Te={}));class De extends ge{constructor(){super(...arguments),this.jobs=new Te(this.client)}}!function(e){e.Jobs=Te,e.FineTuningJobsPage=Ce,e.FineTuningJobEventsPage=Oe}(De||(De={}));class $e extends ge{createVariation(e,t){return this.post("/images/variations",N({body:e,...t}))}edit(e,t){return this.post("/images/edits",N({body:e,...t}))}generate(e,t){return this.post("/images/generations",{body:e,...t})}}$e||($e={});class je extends ge{retrieve(e,t){return this.get(`/models/${e}`,t)}list(e){return this.getAPIList("/models",Fe,e)}del(e,t){return this.delete(`/models/${e}`,t)}}class Fe extends me{}!function(e){e.ModelsPage=Fe}(je||(je={}));class qe extends ge{create(e,t){return this.post("/moderations",{body:e,...t})}}var Ue;qe||(qe={});class Le extends V{constructor({apiKey:e=de("OPENAI_API_KEY"),organization:t=de("OPENAI_ORG_ID")??null,...s}={}){if(void 0===e)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 n={apiKey:e,organization:t,...s,baseURL:s.baseURL??"https://api.openai.com/v1"};if(!n.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new g("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:n.baseURL,timeout:n.timeout??6e5,httpAgent:n.httpAgent,maxRetries:n.maxRetries,fetch:n.fetch}),this.completions=new Ae(this),this.chat=new be(this),this.edits=new Re(this),this.embeddings=new Pe(this),this.files=new Ee(this),this.images=new $e(this),this.audio=new ve(this),this.moderations=new qe(this),this.models=new je(this),this.fineTuning=new De(this),this.fineTunes=new Me(this),this._options=n,this.apiKey=e,this.organization=t}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}}Ue=Le,Le.OpenAI=Ue,Le.OpenAIError=g,Le.APIError=w,Le.APIConnectionError=x,Le.APIConnectionTimeoutError=S,Le.APIUserAbortError=b,Le.NotFoundError=R,Le.ConflictError=E,Le.RateLimitError=M,Le.BadRequestError=v,Le.AuthenticationError=A,Le.InternalServerError=k,Le.PermissionDeniedError=P,Le.UnprocessableEntityError=I,function(e){e.toFile=q,e.fileFromPath=p,e.Page=me,e.CursorPage=ye,e.Completions=Ae,e.Chat=be,e.Edits=Re,e.Embeddings=Pe,e.Files=Ee,e.FileObjectsPage=Ie,e.Images=$e,e.Audio=ve,e.Moderations=qe,e.Models=je,e.ModelsPage=Fe,e.FineTuning=De,e.FineTunes=Me,e.FineTunesPage=ke}(Le||(Le={}));var Ke=Le;class Ne{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,dataExchangeMode:r}){this.actAsMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.dataExchangeMode="fetch",this.currentStatus="disconnected",this.historyDepthToInclude=n??2,this.timeout=s,this.dataExchangeMode=r,this.openai=new Ke({apiKey:t,dangerouslyAllowBrowser:!0}),e&&(this.actAsMessage=e),console.warn('GPT-4 adapter has been initialized in browser mode using option "dangerouslyAllowBrowser". This is not recommended for production use. We recommend that you implement a server-side proxy and configure a customized adapter for it. Read more at https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety')}get id(){return this.info.id}get info(){return r}get status(){return this.currentStatus}async decode(e){const{decodeMessage:t}=this.config;return t(e)}async encode(e){const{encodeMessage:t}=this.config;return t(e)}}class Xe extends Ne{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,dataExchangeMode:"fetch"})}get config(){return n}send(s){if("string"!=typeof s||0===s.length)throw new e({source:this.constructor.name,message:"Cannot send empty messages"});const n=new t,r=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return r.push({role:"user",content:s}),this.openai.chat.completions.create({stream:!1,model:"gpt-4",messages:r}).then((async e=>{const t=await this.decode(e);void 0!==t&&n.next(t),n.complete()})),n}}const Be=class t{constructor(e){this.apiKey=null,this.dataExchangeMode="fetch",this.historyDepth="max",this.timeout=t.defaultTimeout,this.initialSystemMessage=null,this.setApiKeyCalled=!1,this.setHistoryDepthCalled=!1,this.setInitialSystemMessageCalled=!1,this.setStreamOrFetchCalled=!1,this.setTimeOutCalled=!1,e&&(this.apiKey=e.apiKey,this.dataExchangeMode=e.dataExchangeMode,this.historyDepth=e.historyDepth,this.timeout=e.timeout,this.setApiKeyCalled=e.setApiKeyCalled,this.setHistoryDepthCalled=e.setHistoryDepthCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled,this.setTimeOutCalled=e.setTimeOutCalled)}withApiKey(t){if(this.setApiKeyCalled)throw new e({source:this.constructor.name,message:"Unable to set API key. API key setter has already been called by this builder. Make sure you are not calling useApiKey() twice."});return this.apiKey=t,this.setApiKeyCalled=!0,this}withHistoryDepth(t="max"){if(this.setHistoryDepthCalled)throw new e({source:this.constructor.name,message:"Unable to set history depth. History depth setter has already been called by this builder. Make sure you are not calling includeHistoryDepth() twice."});return this.historyDepth=t,this.setHistoryDepthCalled=!0,this}withInitialSystemMessage(t){if(this.setInitialSystemMessageCalled)throw new e({source:this.constructor.name,message:"Unable to set initial system message. Initial system message setter has already been called by this builder. Make sure you are not calling withInitialSystemMessage() twice."});return this.initialSystemMessage=t??null,this.setInitialSystemMessageCalled=!0,this}withTimeout(t){if(this.setTimeOutCalled)throw new e({source:this.constructor.name,message:"Unable to set timeout. Timeout setter has already been called by this builder. Make sure you are not calling withTimeout() twice."});return this.timeout=t,this.setTimeOutCalled=!0,this}};Be.defaultTimeout=3e4;let He=Be;class We extends Ne{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,initialSystemMessage:r}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,dataExchangeMode:"fetch"}),this.initialSystemMessage=null,this.shouldSendInitialSystemMessage=!1,void 0!==r&&r.length>0&&(this.initialSystemMessage=r,this.shouldSendInitialSystemMessage=!0)}get config(){return s}send(s){if("string"!=typeof s||0===s.length)throw new e({source:this.constructor.name,message:"Cannot send empty messages"});const n=new t,r=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return console.dir(this.shouldSendInitialSystemMessage),this.shouldSendInitialSystemMessage&&(r.push({role:"system",content:this.initialSystemMessage}),this.shouldSendInitialSystemMessage=!1),r.push({role:"user",content:s}),this.openai.chat.completions.create({stream:!0,model:"gpt-4",messages:r}).then((async e=>{let t=e[Symbol.asyncIterator](),s=await t.next();for(;!s.done;){const e=s.value,r=await this.decode(e);void 0!==r&&n.next(r),s=await t.next()}n.complete()})),n}}class _e extends He{constructor(e){super(e),this.dataExchangeMode="stream"}create(){if(!this.apiKey)throw new e({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});return new We({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth,initialSystemMessage:this.initialSystemMessage??void 0})}useFetchingMode(){throw new e({source:this.constructor.name,message:"Unable to set data loading mode to fetch. This builder is configured to use the stream API. You cannot change it to use the fetch API."})}useStreamingMode(){throw new e({source:this.constructor.name,message:"Unable to set data loading mode to stream. This builder is already configured to use the stream API."})}}class Je extends He{constructor(){super()}create(){if(!this.apiKey)throw new e({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});if("stream"===this.dataExchangeMode)throw new e({source:this.constructor.name,message:"Unable to create GPT4 adapter. This builder is configured to use the stream API because useStreamingMode() was called. You should call use the builder instance returned by useStreamingMode() to create the builder."});return new Xe({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth})}useFetchingMode(){if(this.setStreamOrFetchCalled)throw new e({source:this.constructor.name,message:"Unable to set data loading mode to fetch. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="fetch",this.setStreamOrFetchCalled=!0,this}useStreamingMode(){if(this.setStreamOrFetchCalled)throw new e({source:this.constructor.name,message:"Unable to set data loading mode to stream. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="stream",this.setStreamOrFetchCalled=!0,new _e(this)}}const ze=t=>{if("openai/gpt4"!==t)throw new e({source:"createAdapter",message:"Adapter type not supported"});return new Je};export{Xe as Gpt4FetchAdapter,We as Gpt4StreamingAdapter,ze as createAdapter}; | ||
import{NluxUsageError as e,Observable as t}from"@nlux/nlux";import s from"openai";const a=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].delta.content;if("string"==typeof t)return t}}),i=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].message.content;if("string"==typeof t)return t}}),o=Object.freeze({id:"nlux-gpt4-adapter",connectionType:"http",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]});class n{constructor({actAs:e,apiKey:t,timeout:a,historyDepthToInclude:i,dataExchangeMode:o}){this.actAsMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.dataExchangeMode="fetch",this.currentStatus="disconnected",this.historyDepthToInclude=i??2,this.timeout=a,this.dataExchangeMode=o,this.openai=new s({apiKey:t,dangerouslyAllowBrowser:!0}),e&&(this.actAsMessage=e),console.warn('GPT-4 adapter has been initialized in browser mode using option "dangerouslyAllowBrowser". This is not recommended for production use. We recommend that you implement a server-side proxy and configure a customized adapter for it. Read more at https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety')}get id(){return this.info.id}get info(){return o}get status(){return this.currentStatus}async decode(e){const{decodeMessage:t}=this.config;return t(e)}async encode(e){const{encodeMessage:t}=this.config;return t(e)}}class r extends n{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a,dataExchangeMode:"fetch"})}get config(){return i}send(s){if("string"!=typeof s||0===s.length)throw new e({source:this.constructor.name,message:"Cannot send empty messages"});const a=new t,i=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return i.push({role:"user",content:s}),this.openai.chat.completions.create({stream:!1,model:"gpt-4",messages:i}).then((async e=>{const t=await this.decode(e);void 0!==t&&a.next(t),a.complete()})),a}}const h=class t{constructor(e){this.apiKey=null,this.dataExchangeMode="fetch",this.historyDepth="max",this.timeout=t.defaultTimeout,this.initialSystemMessage=null,this.setApiKeyCalled=!1,this.setHistoryDepthCalled=!1,this.setInitialSystemMessageCalled=!1,this.setStreamOrFetchCalled=!1,this.setTimeOutCalled=!1,e&&(this.apiKey=e.apiKey,this.dataExchangeMode=e.dataExchangeMode,this.historyDepth=e.historyDepth,this.timeout=e.timeout,this.setApiKeyCalled=e.setApiKeyCalled,this.setHistoryDepthCalled=e.setHistoryDepthCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled,this.setTimeOutCalled=e.setTimeOutCalled)}withApiKey(t){if(this.setApiKeyCalled)throw new e({source:this.constructor.name,message:"Unable to set API key. API key setter has already been called by this builder. Make sure you are not calling useApiKey() twice."});return this.apiKey=t,this.setApiKeyCalled=!0,this}withHistoryDepth(t="max"){if(this.setHistoryDepthCalled)throw new e({source:this.constructor.name,message:"Unable to set history depth. History depth setter has already been called by this builder. Make sure you are not calling includeHistoryDepth() twice."});return this.historyDepth=t,this.setHistoryDepthCalled=!0,this}withInitialSystemMessage(t){if(this.setInitialSystemMessageCalled)throw new e({source:this.constructor.name,message:"Unable to set initial system message. Initial system message setter has already been called by this builder. Make sure you are not calling withInitialSystemMessage() twice."});return this.initialSystemMessage=t??null,this.setInitialSystemMessageCalled=!0,this}withTimeout(t){if(this.setTimeOutCalled)throw new e({source:this.constructor.name,message:"Unable to set timeout. Timeout setter has already been called by this builder. Make sure you are not calling withTimeout() twice."});return this.timeout=t,this.setTimeOutCalled=!0,this}};h.defaultTimeout=3e4;let c=h;class l extends n{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a,initialSystemMessage:i}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a,dataExchangeMode:"fetch"}),this.initialSystemMessage=null,this.shouldSendInitialSystemMessage=!1,void 0!==i&&i.length>0&&(this.initialSystemMessage=i,this.shouldSendInitialSystemMessage=!0)}get config(){return a}send(s){if("string"!=typeof s||0===s.length)throw new e({source:this.constructor.name,message:"Cannot send empty messages"});const a=new t,i=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return console.dir(this.shouldSendInitialSystemMessage),this.shouldSendInitialSystemMessage&&(i.push({role:"system",content:this.initialSystemMessage}),this.shouldSendInitialSystemMessage=!1),i.push({role:"user",content:s}),this.openai.chat.completions.create({stream:!0,model:"gpt-4",messages:i}).then((async e=>{let t=e[Symbol.asyncIterator](),s=await t.next();for(;!s.done;){const e=s.value,i=await this.decode(e);void 0!==i&&a.next(i),s=await t.next()}a.complete()})),a}}class d extends c{constructor(e){super(e),this.dataExchangeMode="stream"}create(){if(!this.apiKey)throw new e({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});return new l({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth,initialSystemMessage:this.initialSystemMessage??void 0})}useFetchingMode(){throw new e({source:this.constructor.name,message:"Unable to set data loading mode to fetch. This builder is configured to use the stream API. You cannot change it to use the fetch API."})}useStreamingMode(){throw new e({source:this.constructor.name,message:"Unable to set data loading mode to stream. This builder is already configured to use the stream API."})}}class u extends c{constructor(){super()}create(){if(!this.apiKey)throw new e({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});if("stream"===this.dataExchangeMode)throw new e({source:this.constructor.name,message:"Unable to create GPT4 adapter. This builder is configured to use the stream API because useStreamingMode() was called. You should call use the builder instance returned by useStreamingMode() to create the builder."});return new r({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth})}useFetchingMode(){if(this.setStreamOrFetchCalled)throw new e({source:this.constructor.name,message:"Unable to set data loading mode to fetch. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="fetch",this.setStreamOrFetchCalled=!0,this}useStreamingMode(){if(this.setStreamOrFetchCalled)throw new e({source:this.constructor.name,message:"Unable to set data loading mode to stream. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="stream",this.setStreamOrFetchCalled=!0,new d(this)}}const m=t=>{if("openai/gpt4"!==t)throw new e({source:"createAdapter",message:"Adapter type not supported"});return new u};export{r as Gpt4FetchAdapter,l as Gpt4StreamingAdapter,m as createAdapter}; |
{ | ||
"name": "@nlux/openai", | ||
"version": "0.1.2-beta", | ||
"version": "0.1.3-beta", | ||
"description": "The OpenAI adapters for NLUX, the javascript library for building conversational AI interfaces.", | ||
@@ -54,3 +54,3 @@ "keywords": [ | ||
"dependencies": { | ||
"@nlux/nlux": "0.1.2-beta", | ||
"@nlux/nlux": "0.1.3-beta", | ||
"openai": "^4.11.1" | ||
@@ -57,0 +57,0 @@ }, |
@@ -1,1 +0,1 @@ | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@nlux/nlux")):"function"==typeof define&&define.amd?define(["exports","@nlux/nlux"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@nlux/openai"]={},e.nlux)}(this,(function(e,t){"use strict";const s=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].delta.content;if("string"==typeof t)return t}}),n=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].message.content;if("string"==typeof t)return t}}),r=Object.freeze({id:"nlux-gpt4-adapter",connectionType:"http",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]}),i="4.14.1";let o,a,u,c,l,h,d,p,f,m=!1;class y{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}o||function(e,t={auto:!1}){if(m)throw new Error(`you must \`import 'openai/shims/${e.kind}'\` before importing anything else from openai`);if(o)throw new Error(`can't \`import 'openai/shims/${e.kind}'\` after \`import 'openai/shims/${o}'\``);m=t.auto,o=e.kind,a=e.fetch,u=e.FormData,c=e.File,l=e.ReadableStream,h=e.getMultipartRequestOptions,d=e.getDefaultAgent,p=e.fileFromPath,f=e.isFsReadStream}(function({manuallyImported:e}={}){const t=e?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let s,n,r,i;try{s=fetch,n=Request,r=Response,i=Headers}catch(e){throw new Error(`this environment is missing the following Web Fetch API type: ${e.message}. ${t}`)}return{kind:"web",fetch:s,Request:n,Response:r,Headers:i,FormData:"undefined"!=typeof FormData?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${t}`)}},Blob:"undefined"!=typeof Blob?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${t}`)}},File:"undefined"!=typeof File?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${t}`)}},ReadableStream:"undefined"!=typeof ReadableStream?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${t}`)}},getMultipartRequestOptions:async(e,t)=>({...t,body:new y(e)}),getDefaultAgent:e=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:e=>!1}}(),{auto:!0});class g extends Error{}class w extends g{constructor(e,t,s,n){super(`${w.makeMessage(e,t,s)}`),this.status=e,this.headers=n;const r=t;this.error=r,this.code=r?.code,this.param=r?.param,this.type=r?.type}static makeMessage(e,t,s){const n=t?.message?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,s,n){if(!e)return new x({cause:he(t)});const r=t?.error;return 400===e?new A(e,r,s,n):401===e?new v(e,r,s,n):403===e?new E(e,r,s,n):404===e?new P(e,r,s,n):409===e?new R(e,r,s,n):422===e?new I(e,r,s,n):429===e?new M(e,r,s,n):e>=500?new k(e,r,s,n):new w(e,r,s,n)}}class b extends w{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0),this.status=void 0}}class x extends w{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),this.status=void 0,t&&(this.cause=t)}}class S extends x{constructor({message:e}={}){super({message:e??"Request timed out."})}}class A extends w{constructor(){super(...arguments),this.status=400}}class v extends w{constructor(){super(...arguments),this.status=401}}class E extends w{constructor(){super(...arguments),this.status=403}}class P extends w{constructor(){super(...arguments),this.status=404}}class R extends w{constructor(){super(...arguments),this.status=409}}class I extends w{constructor(){super(...arguments),this.status=422}}class M extends w{constructor(){super(...arguments),this.status=429}}class k extends w{}class T{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let s=!1;const n=new O;return new T((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let r=!1;try{for await(const s of async function*(){if(!e.body)throw t.abort(),new g("Attempted to iterate over a response with no body");const s=new C,r=U(e.body);for await(const e of r)for(const t of s.decode(e)){const e=n.decode(t);e&&(yield e)}for(const e of s.flush()){const t=n.decode(e);t&&(yield t)}}())if(!r)if(s.data.startsWith("[DONE]"))r=!0;else if(null===s.event){let e;try{e=JSON.parse(s.data)}catch(e){throw console.error("Could not parse message into JSON:",s.data),console.error("From chunk:",s.raw),e}if(e&&e.error)throw new w(void 0,e.error,void 0,void 0);yield e}r=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{r||t.abort()}}),t)}static fromReadableStream(e,t){let s=!1;return new T((async function*(){if(s)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let n=!1;try{for await(const t of async function*(){const t=new C,s=U(e);for await(const e of s)for(const s of t.decode(e))yield s;for(const e of t.flush())yield e}())n||t&&(yield JSON.parse(t));n=!0}catch(e){if(e instanceof Error&&"AbortError"===e.name)return;throw e}finally{n||t.abort()}}),t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),n=n=>({next:()=>{if(0===n.length){const n=s.next();e.push(n),t.push(n)}return n.shift()}});return[new T((()=>n(e)),this.controller),new T((()=>n(t)),this.controller)]}toReadableStream(){const e=this;let t;const s=new TextEncoder;return new l({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{const{value:n,done:r}=await t.next();if(r)return e.close();const i=s.encode(JSON.stringify(n)+"\n");e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await(t.return?.())}})}}class O{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,n]=function(e,t){const s=e.indexOf(t);if(-1!==s)return[e.substring(0,s),t,e.substring(s+t.length)];return[e,"",""]}(e,":");return n.startsWith(" ")&&(n=n.substring(1)),"event"===t?this.event=n:"data"===t&&this.data.push(n),null}}class C{constructor(){this.buffer=[],this.trailingCR=!1}decode(e){let t=this.decodeText(e);if(this.trailingCR&&(t="\r"+t,this.trailingCR=!1),t.endsWith("\r")&&(this.trailingCR=!0,t=t.slice(0,-1)),!t)return[];const s=C.NEWLINE_CHARS.has(t[t.length-1]||"");let n=t.split(C.NEWLINE_REGEXP);return 1!==n.length||s?(this.buffer.length>0&&(n=[this.buffer.join("")+n[0],...n.slice(1)],this.buffer=[]),s||(this.buffer=[n.pop()||""]),n):(this.buffer.push(n[0]),[])}decodeText(e){if(null==e)return"";if("string"==typeof e)return e;if("undefined"!=typeof Buffer){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new g(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if("undefined"!=typeof TextDecoder){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new g(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new g("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){if(!this.buffer.length&&!this.trailingCR)return[];const e=[this.buffer.join("")];return this.buffer=[],this.trailingCR=!1,e}}function U(e){if(e[Symbol.asyncIterator])return e;const t=e.getReader();return{async next(){try{const e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){const e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}C.NEWLINE_CHARS=new Set(["\n","\r","\v","\f","","",""," ","\u2028","\u2029"]),C.NEWLINE_REGEXP=/\r\n|[\n\r\x0b\x0c\x1c\x1d\x1e\x85\u2028\u2029]/g;const D=e=>null!=e&&"object"==typeof e&&"string"==typeof e.url&&"function"==typeof e.blob,$=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer,j=e=>(e=>null!=e&&"object"==typeof e&&"string"==typeof e.name&&"number"==typeof e.lastModified&&$(e))(e)||D(e)||f(e);async function N(e,t,s={}){if(e=await e,D(e)){const n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()??"unknown_file"),new c([n],t,s)}const n=await async function(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if($(e))t.push(await e.arrayBuffer());else{if(!q(e))throw new Error(`Unexpected data type: ${typeof e}; constructor: ${e?.constructor?.name}; props: ${function(e){const t=Object.getOwnPropertyNames(e);return`[${t.map((e=>`"${e}"`)).join(", ")}]`}(e)}`);for await(const s of e)t.push(s)}return t}(e);if(t||(t=function(e){return F(e.name)||F(e.filename)||F(e.path)?.split(/[\\/]/).pop()}(e)??"unknown_file"),!s.type){const e=n[0]?.type;"string"==typeof e&&(s={...s,type:e})}return new c(n,t,s)}const F=e=>"string"==typeof e?e:"undefined"!=typeof Buffer&&e instanceof Buffer?String(e):void 0,q=e=>null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator],L=e=>e&&"object"==typeof e&&e.body&&"MultipartBody"===e[Symbol.toStringTag],K=async e=>{const t=await X(e.body);return h(t,e)},X=async e=>{const t=new u;return await Promise.all(Object.entries(e||{}).map((([e,s])=>B(t,e,s)))),t},B=async(e,t,s)=>{if(void 0!==s){if(null==s)throw new TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)e.append(t,String(s));else if(j(s)){const n=await N(s);e.append(t,n)}else if(Array.isArray(s))await Promise.all(s.map((s=>B(e,t+"[]",s))));else{if("object"!=typeof s)throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${s} instead`);await Promise.all(Object.entries(s).map((([s,n])=>B(e,`${t}[${s}]`,n))))}}};var H,W=function(e,t,s,n,r){if("m"===n)throw new TypeError("Private method is not writable");if("a"===n&&!r)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof t?e!==t||!r:!t.has(e))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===n?r.call(e,s):r?r.value=s:t.set(e,s),s},_=function(e,t,s,n){if("a"===s&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?n:"a"===s?n.call(e):n?n.value:t.get(e)};async function J(e){const{response:t}=e;if(e.options.stream)return T.fromSSEResponse(t,e.controller);if(204===t.status)return null;const s=t.headers.get("content-type");if(s?.includes("application/json")){return await t.json()}return await t.text()}class z extends Promise{constructor(e,t=J){super((e=>{e(null)})),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new z(this.responsePromise,(async t=>e(await this.parseResponse(t))))}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}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class V{constructor({baseURL:e,maxRetries:t=2,timeout:s=6e5,httpAgent:n,fetch:r}){this.baseURL=e,this.maxRetries=le("maxRetries",t),this.timeout=le("timeout",s),this.httpAgent=n,this.fetch=r??a}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...ie(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${fe()}`}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((s=>({method:e,path:t,...s}))))}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}calculateContentLength(e){if("string"==typeof e){if("undefined"!=typeof Buffer)return Buffer.byteLength(e,"utf8").toString();if("undefined"!=typeof TextEncoder){return(new TextEncoder).encode(e).length.toString()}}return null}buildRequest(e){const{method:t,path:s,query:n,headers:r={}}=e,i=L(e.body)?e.body.body:e.body?JSON.stringify(e.body,null,2):null,a=this.calculateContentLength(i),u=this.buildURL(s,n);"timeout"in e&&le("timeout",e.timeout);const c=e.timeout??this.timeout,l=e.httpAgent??this.httpAgent??d(u),h=c+1e3;"number"==typeof l?.options?.timeout&&h>(l.options.timeout??0)&&(l.options.timeout=h),this.idempotencyHeader&&"get"!==t&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),r[this.idempotencyHeader]=e.idempotencyKey);const p={...a&&{"Content-Length":a},...this.defaultHeaders(e),...r};L(e.body)&&"node"!==o&&delete p["Content-Type"],Object.keys(p).forEach((e=>null===p[e]&&delete p[e]));const f={method:t,...i&&{body:i},headers:p,...l&&{agent:l},signal:e.signal??null};return this.validateHeaders(p,r),{req:f,url:u,timeout:c}}async prepareRequest(e,{url:t,options:s}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map((e=>[...e]))):{...e}:{}}makeStatusError(e,t,s,n){return w.generate(e,t,s,n)}request(e,t=null){return new z(this.makeRequest(e,t))}async makeRequest(e,t){const s=await e;null==t&&(t=s.maxRetries??this.maxRetries);const{req:n,url:r,timeout:i}=this.buildRequest(s);if(await this.prepareRequest(n,{url:r,options:s}),s.signal?.aborted)throw new b;const o=new AbortController,a=await this.fetchWithTimeout(r,n,i,o).catch(he);if(a instanceof Error){if(s.signal?.aborted)throw new b;if(t)return this.retryRequest(s,t);if("AbortError"===a.name)throw new S;throw new x({cause:a})}const u=Q(a.headers);if(!a.ok){if(t&&this.shouldRetry(a))return this.retryRequest(s,t,u);const e=await a.text().catch((e=>he(e).message)),n=oe(e),r=n?void 0:e;throw this.makeStatusError(a.status,n,r,u)}return{response:a,options:s,controller:o}}requestAPIList(e,t){const s=this.makeRequest(t,null);return new Y(this,s,e)}buildURL(e,t){const s=ue(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),n=this.defaultQuery();return pe(n)||(t={...n,...t}),t&&(s.search=this.stringifyQuery(t)),s.toString()}stringifyQuery(e){return Object.entries(e).filter((([e,t])=>void 0!==t)).map((([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new g(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)})).join("&")}async fetchWithTimeout(e,t,s,n){const{signal:r,...i}=t||{};r&&r.addEventListener("abort",(()=>n.abort()));const o=setTimeout((()=>n.abort()),s);return this.getRequestClient().fetch.call(void 0,e,{signal:n.signal,...i}).finally((()=>{clearTimeout(o)}))}getRequestClient(){return{fetch:this.fetch}}shouldRetry(e){const t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||(409===e.status||(429===e.status||e.status>=500)))}async retryRequest(e,t,s){let n;const r=s?.["retry-after"];if(r){const e=parseInt(r);n=Number.isNaN(e)?Date.parse(r)-Date.now():1e3*e}if(!n||!Number.isInteger(n)||n<=0||n>6e4){const s=e.maxRetries??this.maxRetries;n=this.calculateDefaultRetryTimeoutMillis(t,s)}return await ce(n),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const s=t-e;return Math.min(.5*Math.pow(2,s),8)*(1-.25*Math.random())*1e3}getUserAgent(){return`${this.constructor.name}/JS ${i}`}}class G{constructor(e,t,s,n){H.set(this,void 0),W(this,H,e,"f"),this.options=n,this.response=t,this.body=s}hasNextPage(){return!!this.getPaginatedItems().length&&null!=this.nextPageInfo()}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new g("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e)t.query={...t.query,...e.params};else if("url"in e){const s=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[t,n]of s)e.url.searchParams.set(t,n);t.query=void 0,t.path=e.url.toString()}return await _(this,H,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(H=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Y extends z{constructor(e,t,s){super(t,(async t=>new s(e,t.response,await J(t),t.options)))}async*[Symbol.asyncIterator](){const e=await(this);for await(const t of e)yield t}}const Q=e=>new Proxy(Object.fromEntries(e.entries()),{get(e,t){const s=t.toString();return e[s.toLowerCase()]||e[s]}}),Z={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0},ee=e=>"object"==typeof e&&null!==e&&!pe(e)&&Object.keys(e).every((e=>function(e,t){return Object.prototype.hasOwnProperty.call(e,t)}(Z,e))),te=()=>{if("undefined"!=typeof Deno&&null!=Deno.build)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i,"X-Stainless-OS":ne(Deno.build.os),"X-Stainless-Arch":se(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":Deno.version};if("undefined"!=typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if("[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0))return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i,"X-Stainless-OS":ne(process.platform),"X-Stainless-Arch":se(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const e=function(){if("undefined"==typeof navigator||!navigator)return null;const e=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:t,pattern:s}of e){const e=s.exec(navigator.userAgent);if(e){return{browser:t,version:`${e[1]||0}.${e[2]||0}.${e[3]||0}`}}}return null}();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":i,"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":i,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};const se=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",ne=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";let re;const ie=()=>re??(re=te()),oe=e=>{try{return JSON.parse(e)}catch(e){return}},ae=new RegExp("^(?:[a-z]+:)?//","i"),ue=e=>ae.test(e),ce=e=>new Promise((t=>setTimeout(t,e))),le=(e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new g(`${e} must be an integer`);if(t<0)throw new g(`${e} must be a positive integer`);return t},he=e=>e instanceof Error?e:new Error(e),de=e=>"undefined"!=typeof process?process.env?.[e]??void 0:"undefined"!=typeof Deno?Deno.env?.get?.(e):void 0;function pe(e){if(!e)return!0;for(const t in e)return!1;return!0}const fe=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(e=>{const t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)}));class me extends G{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data,this.object=s.object}getPaginatedItems(){return this.data}nextPageParams(){return null}nextPageInfo(){return null}}class ye extends G{constructor(e,t,s,n){super(e,t,s,n),this.data=s.data}getPaginatedItems(){return this.data}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){if(!this.data?.length)return null;const e=this.data[this.data.length-1]?.id;return e?{params:{after:e}}:null}}class ge{constructor(e){this.client=e,this.get=e.get.bind(e),this.post=e.post.bind(e),this.patch=e.patch.bind(e),this.put=e.put.bind(e),this.delete=e.delete.bind(e),this.getAPIList=e.getAPIList.bind(e)}}let we=class extends ge{create(e,t){return this.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}};we||(we={});class be extends ge{constructor(){super(...arguments),this.completions=new we(this.client)}}!function(e){e.Completions=we}(be||(be={}));class xe extends ge{create(e,t){return this.post("/audio/transcriptions",K({body:e,...t}))}}xe||(xe={});class Se extends ge{create(e,t){return this.post("/audio/translations",K({body:e,...t}))}}Se||(Se={});class Ae extends ge{constructor(){super(...arguments),this.transcriptions=new xe(this.client),this.translations=new Se(this.client)}}!function(e){e.Transcriptions=xe,e.Translations=Se}(Ae||(Ae={}));class ve extends ge{create(e,t){return this.post("/completions",{body:e,...t,stream:e.stream??!1})}}ve||(ve={});class Ee extends ge{create(e,t){return this.post("/embeddings",{body:e,...t})}}Ee||(Ee={});class Pe extends ge{create(e,t){return this.post("/edits",{body:e,...t})}}Pe||(Pe={});class Re extends ge{create(e,t){return this.post("/files",K({body:e,...t}))}retrieve(e,t){return this.get(`/files/${e}`,t)}list(e){return this.getAPIList("/files",Ie,e)}del(e,t){return this.delete(`/files/${e}`,t)}retrieveContent(e,t){return this.get(`/files/${e}/content`,{...t,headers:{Accept:"application/json",...t?.headers}})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=18e5}={}){const n=new Set(["processed","error","deleted"]),r=Date.now();let i=await this.retrieve(e);for(;!i.status||!n.has(i.status);)if(await ce(t),i=await this.retrieve(e),Date.now()-r>s)throw new S({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return i}}class Ie extends me{}!function(e){e.FileObjectsPage=Ie}(Re||(Re={}));class Me extends ge{create(e,t){return this.post("/fine-tunes",{body:e,...t})}retrieve(e,t){return this.get(`/fine-tunes/${e}`,t)}list(e){return this.getAPIList("/fine-tunes",ke,e)}cancel(e,t){return this.post(`/fine-tunes/${e}/cancel`,t)}listEvents(e,t,s){return this.get(`/fine-tunes/${e}/events`,{query:t,timeout:864e5,...s,stream:t?.stream??!1})}}class ke extends me{}!function(e){e.FineTunesPage=ke}(Me||(Me={}));class Te extends ge{create(e,t){return this.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return ee(e)?this.list({},e):this.getAPIList("/fine_tuning/jobs",Oe,{query:e,...t})}cancel(e,t){return this.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return ee(t)?this.listEvents(e,{},t):this.getAPIList(`/fine_tuning/jobs/${e}/events`,Ce,{query:t,...s})}}class Oe extends ye{}class Ce extends ye{}!function(e){e.FineTuningJobsPage=Oe,e.FineTuningJobEventsPage=Ce}(Te||(Te={}));class Ue extends ge{constructor(){super(...arguments),this.jobs=new Te(this.client)}}!function(e){e.Jobs=Te,e.FineTuningJobsPage=Oe,e.FineTuningJobEventsPage=Ce}(Ue||(Ue={}));class De extends ge{createVariation(e,t){return this.post("/images/variations",K({body:e,...t}))}edit(e,t){return this.post("/images/edits",K({body:e,...t}))}generate(e,t){return this.post("/images/generations",{body:e,...t})}}De||(De={});class $e extends ge{retrieve(e,t){return this.get(`/models/${e}`,t)}list(e){return this.getAPIList("/models",je,e)}del(e,t){return this.delete(`/models/${e}`,t)}}class je extends me{}!function(e){e.ModelsPage=je}($e||($e={}));class Ne extends ge{create(e,t){return this.post("/moderations",{body:e,...t})}}var Fe;Ne||(Ne={});class qe extends V{constructor({apiKey:e=de("OPENAI_API_KEY"),organization:t=de("OPENAI_ORG_ID")??null,...s}={}){if(void 0===e)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 n={apiKey:e,organization:t,...s,baseURL:s.baseURL??"https://api.openai.com/v1"};if(!n.dangerouslyAllowBrowser&&"undefined"!=typeof window&&void 0!==window.document&&"undefined"!=typeof navigator)throw new g("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n");super({baseURL:n.baseURL,timeout:n.timeout??6e5,httpAgent:n.httpAgent,maxRetries:n.maxRetries,fetch:n.fetch}),this.completions=new ve(this),this.chat=new be(this),this.edits=new Pe(this),this.embeddings=new Ee(this),this.files=new Re(this),this.images=new De(this),this.audio=new Ae(this),this.moderations=new Ne(this),this.models=new $e(this),this.fineTuning=new Ue(this),this.fineTunes=new Me(this),this._options=n,this.apiKey=e,this.organization=t}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}}Fe=qe,qe.OpenAI=Fe,qe.OpenAIError=g,qe.APIError=w,qe.APIConnectionError=x,qe.APIConnectionTimeoutError=S,qe.APIUserAbortError=b,qe.NotFoundError=P,qe.ConflictError=R,qe.RateLimitError=M,qe.BadRequestError=A,qe.AuthenticationError=v,qe.InternalServerError=k,qe.PermissionDeniedError=E,qe.UnprocessableEntityError=I,function(e){e.toFile=N,e.fileFromPath=p,e.Page=me,e.CursorPage=ye,e.Completions=ve,e.Chat=be,e.Edits=Pe,e.Embeddings=Ee,e.Files=Re,e.FileObjectsPage=Ie,e.Images=De,e.Audio=Ae,e.Moderations=Ne,e.Models=$e,e.ModelsPage=je,e.FineTuning=Ue,e.FineTunes=Me,e.FineTunesPage=ke}(qe||(qe={}));var Le=qe;class Ke{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,dataExchangeMode:r}){this.actAsMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.dataExchangeMode="fetch",this.currentStatus="disconnected",this.historyDepthToInclude=n??2,this.timeout=s,this.dataExchangeMode=r,this.openai=new Le({apiKey:t,dangerouslyAllowBrowser:!0}),e&&(this.actAsMessage=e),console.warn('GPT-4 adapter has been initialized in browser mode using option "dangerouslyAllowBrowser". This is not recommended for production use. We recommend that you implement a server-side proxy and configure a customized adapter for it. Read more at https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety')}get id(){return this.info.id}get info(){return r}get status(){return this.currentStatus}async decode(e){const{decodeMessage:t}=this.config;return t(e)}async encode(e){const{encodeMessage:t}=this.config;return t(e)}}class Xe extends Ke{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,dataExchangeMode:"fetch"})}get config(){return n}send(e){if("string"!=typeof e||0===e.length)throw new t.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const s=new t.Observable,n=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return n.push({role:"user",content:e}),this.openai.chat.completions.create({stream:!1,model:"gpt-4",messages:n}).then((async e=>{const t=await this.decode(e);void 0!==t&&s.next(t),s.complete()})),s}}const Be=class e{constructor(t){this.apiKey=null,this.dataExchangeMode="fetch",this.historyDepth="max",this.timeout=e.defaultTimeout,this.initialSystemMessage=null,this.setApiKeyCalled=!1,this.setHistoryDepthCalled=!1,this.setInitialSystemMessageCalled=!1,this.setStreamOrFetchCalled=!1,this.setTimeOutCalled=!1,t&&(this.apiKey=t.apiKey,this.dataExchangeMode=t.dataExchangeMode,this.historyDepth=t.historyDepth,this.timeout=t.timeout,this.setApiKeyCalled=t.setApiKeyCalled,this.setHistoryDepthCalled=t.setHistoryDepthCalled,this.setStreamOrFetchCalled=t.setStreamOrFetchCalled,this.setTimeOutCalled=t.setTimeOutCalled)}withApiKey(e){if(this.setApiKeyCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set API key. API key setter has already been called by this builder. Make sure you are not calling useApiKey() twice."});return this.apiKey=e,this.setApiKeyCalled=!0,this}withHistoryDepth(e="max"){if(this.setHistoryDepthCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set history depth. History depth setter has already been called by this builder. Make sure you are not calling includeHistoryDepth() twice."});return this.historyDepth=e,this.setHistoryDepthCalled=!0,this}withInitialSystemMessage(e){if(this.setInitialSystemMessageCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set initial system message. Initial system message setter has already been called by this builder. Make sure you are not calling withInitialSystemMessage() twice."});return this.initialSystemMessage=e??null,this.setInitialSystemMessageCalled=!0,this}withTimeout(e){if(this.setTimeOutCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set timeout. Timeout setter has already been called by this builder. Make sure you are not calling withTimeout() twice."});return this.timeout=e,this.setTimeOutCalled=!0,this}};Be.defaultTimeout=3e4;let He=Be;class We extends Ke{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,initialSystemMessage:r}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:n,dataExchangeMode:"fetch"}),this.initialSystemMessage=null,this.shouldSendInitialSystemMessage=!1,void 0!==r&&r.length>0&&(this.initialSystemMessage=r,this.shouldSendInitialSystemMessage=!0)}get config(){return s}send(e){if("string"!=typeof e||0===e.length)throw new t.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const s=new t.Observable,n=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return console.dir(this.shouldSendInitialSystemMessage),this.shouldSendInitialSystemMessage&&(n.push({role:"system",content:this.initialSystemMessage}),this.shouldSendInitialSystemMessage=!1),n.push({role:"user",content:e}),this.openai.chat.completions.create({stream:!0,model:"gpt-4",messages:n}).then((async e=>{let t=e[Symbol.asyncIterator](),n=await t.next();for(;!n.done;){const e=n.value,r=await this.decode(e);void 0!==r&&s.next(r),n=await t.next()}s.complete()})),s}}class _e extends He{constructor(e){super(e),this.dataExchangeMode="stream"}create(){if(!this.apiKey)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});return new We({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth,initialSystemMessage:this.initialSystemMessage??void 0})}useFetchingMode(){throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to fetch. This builder is configured to use the stream API. You cannot change it to use the fetch API."})}useStreamingMode(){throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to stream. This builder is already configured to use the stream API."})}}class Je extends He{constructor(){super()}create(){if(!this.apiKey)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});if("stream"===this.dataExchangeMode)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. This builder is configured to use the stream API because useStreamingMode() was called. You should call use the builder instance returned by useStreamingMode() to create the builder."});return new Xe({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth})}useFetchingMode(){if(this.setStreamOrFetchCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to fetch. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="fetch",this.setStreamOrFetchCalled=!0,this}useStreamingMode(){if(this.setStreamOrFetchCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to stream. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="stream",this.setStreamOrFetchCalled=!0,new _e(this)}}e.Gpt4FetchAdapter=Xe,e.Gpt4StreamingAdapter=We,e.createAdapter=e=>{if("openai/gpt4"!==e)throw new t.NluxUsageError({source:"createAdapter",message:"Adapter type not supported"});return new Je}})); | ||
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports,require("@nlux/nlux"),require("openai")):"function"==typeof define&&define.amd?define(["exports","@nlux/nlux","openai"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self)["@nlux/openai"]={},e.nlux,e.OpenAI)}(this,(function(e,t,s){"use strict";const a=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].delta.content;if("string"==typeof t)return t}}),i=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const t=e.choices[0].message.content;if("string"==typeof t)return t}}),o=Object.freeze({id:"nlux-gpt4-adapter",connectionType:"http",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]});class r{constructor({actAs:e,apiKey:t,timeout:a,historyDepthToInclude:i,dataExchangeMode:o}){this.actAsMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.dataExchangeMode="fetch",this.currentStatus="disconnected",this.historyDepthToInclude=i??2,this.timeout=a,this.dataExchangeMode=o,this.openai=new s({apiKey:t,dangerouslyAllowBrowser:!0}),e&&(this.actAsMessage=e),console.warn('GPT-4 adapter has been initialized in browser mode using option "dangerouslyAllowBrowser". This is not recommended for production use. We recommend that you implement a server-side proxy and configure a customized adapter for it. Read more at https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety')}get id(){return this.info.id}get info(){return o}get status(){return this.currentStatus}async decode(e){const{decodeMessage:t}=this.config;return t(e)}async encode(e){const{encodeMessage:t}=this.config;return t(e)}}class n extends r{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a,dataExchangeMode:"fetch"})}get config(){return i}send(e){if("string"!=typeof e||0===e.length)throw new t.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const s=new t.Observable,a=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return a.push({role:"user",content:e}),this.openai.chat.completions.create({stream:!1,model:"gpt-4",messages:a}).then((async e=>{const t=await this.decode(e);void 0!==t&&s.next(t),s.complete()})),s}}const h=class e{constructor(t){this.apiKey=null,this.dataExchangeMode="fetch",this.historyDepth="max",this.timeout=e.defaultTimeout,this.initialSystemMessage=null,this.setApiKeyCalled=!1,this.setHistoryDepthCalled=!1,this.setInitialSystemMessageCalled=!1,this.setStreamOrFetchCalled=!1,this.setTimeOutCalled=!1,t&&(this.apiKey=t.apiKey,this.dataExchangeMode=t.dataExchangeMode,this.historyDepth=t.historyDepth,this.timeout=t.timeout,this.setApiKeyCalled=t.setApiKeyCalled,this.setHistoryDepthCalled=t.setHistoryDepthCalled,this.setStreamOrFetchCalled=t.setStreamOrFetchCalled,this.setTimeOutCalled=t.setTimeOutCalled)}withApiKey(e){if(this.setApiKeyCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set API key. API key setter has already been called by this builder. Make sure you are not calling useApiKey() twice."});return this.apiKey=e,this.setApiKeyCalled=!0,this}withHistoryDepth(e="max"){if(this.setHistoryDepthCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set history depth. History depth setter has already been called by this builder. Make sure you are not calling includeHistoryDepth() twice."});return this.historyDepth=e,this.setHistoryDepthCalled=!0,this}withInitialSystemMessage(e){if(this.setInitialSystemMessageCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set initial system message. Initial system message setter has already been called by this builder. Make sure you are not calling withInitialSystemMessage() twice."});return this.initialSystemMessage=e??null,this.setInitialSystemMessageCalled=!0,this}withTimeout(e){if(this.setTimeOutCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set timeout. Timeout setter has already been called by this builder. Make sure you are not calling withTimeout() twice."});return this.timeout=e,this.setTimeOutCalled=!0,this}};h.defaultTimeout=3e4;let c=h;class l extends r{constructor({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a,initialSystemMessage:i}){super({actAs:e,apiKey:t,timeout:s,historyDepthToInclude:a,dataExchangeMode:"fetch"}),this.initialSystemMessage=null,this.shouldSendInitialSystemMessage=!1,void 0!==i&&i.length>0&&(this.initialSystemMessage=i,this.shouldSendInitialSystemMessage=!0)}get config(){return a}send(e){if("string"!=typeof e||0===e.length)throw new t.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const s=new t.Observable,a=this.actAsMessage?[{role:"system",content:this.actAsMessage}]:[];return console.dir(this.shouldSendInitialSystemMessage),this.shouldSendInitialSystemMessage&&(a.push({role:"system",content:this.initialSystemMessage}),this.shouldSendInitialSystemMessage=!1),a.push({role:"user",content:e}),this.openai.chat.completions.create({stream:!0,model:"gpt-4",messages:a}).then((async e=>{let t=e[Symbol.asyncIterator](),a=await t.next();for(;!a.done;){const e=a.value,i=await this.decode(e);void 0!==i&&s.next(i),a=await t.next()}s.complete()})),s}}class u extends c{constructor(e){super(e),this.dataExchangeMode="stream"}create(){if(!this.apiKey)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});return new l({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth,initialSystemMessage:this.initialSystemMessage??void 0})}useFetchingMode(){throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to fetch. This builder is configured to use the stream API. You cannot change it to use the fetch API."})}useStreamingMode(){throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to stream. This builder is already configured to use the stream API."})}}class d extends c{constructor(){super()}create(){if(!this.apiKey)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. API key is not set. You should call useApiKey() on instance to set the API key."});if("stream"===this.dataExchangeMode)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to create GPT4 adapter. This builder is configured to use the stream API because useStreamingMode() was called. You should call use the builder instance returned by useStreamingMode() to create the builder."});return new n({apiKey:this.apiKey,timeout:this.timeout,historyDepthToInclude:this.historyDepth})}useFetchingMode(){if(this.setStreamOrFetchCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to fetch. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="fetch",this.setStreamOrFetchCalled=!0,this}useStreamingMode(){if(this.setStreamOrFetchCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode to stream. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataExchangeMode="stream",this.setStreamOrFetchCalled=!0,new u(this)}}e.Gpt4FetchAdapter=n,e.Gpt4StreamingAdapter=l,e.createAdapter=e=>{if("openai/gpt4"!==e)throw new t.NluxUsageError({source:"createAdapter",message:"Adapter type not supported"});return new d}})); |
Major refactor
Supply chain riskPackage has recently undergone a major refactor. It may be unstable or indicate significant internal changes. Use caution when updating to versions that include significant changes.
Found 1 instance in 1 package
Network access
Supply chain riskThis module accesses the network.
Found 1 instance in 1 package
Environment variable access
Supply chain riskPackage accesses environment variables, which may be a sign of credential stuffing or data theft.
Found 1 instance in 1 package
0
1
29296
172
Updated@nlux/nlux@0.1.3-beta