@nlux/openai
Advanced tools
Comparing version 0.4.8 to 0.4.9
@@ -1,1 +0,1 @@ | ||
"use strict";var e=require("@nlux/nlux"),t=require("openai");const s="gpt-4",a=e=>{if("object"==typeof e&&null!==e){if("invalid_api_key"===e.code)return"NX-NT-002";if(e.message?.toLowerCase().includes("connection error"))return"NX-NT-001"}return null},r=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}}),n=Object.freeze({id:"nlux-gpt-adapter",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]});class o{constructor({initialSystemMessage:s,apiKey:a,dataTransferMode:r,model:i}){this.theDataTransferMode="fetch",this.currentStatus="disconnected",this.initialSystemMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.theDataTransferMode=r,this.openai=new t({apiKey:a,dangerouslyAllowBrowser:!0}),this.model=i,s&&(this.initialSystemMessage=s),e.warn('OpenAI GPT 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 dataTransferMode(){return this.theDataTransferMode}get id(){return this.info.id}get info(){return n}get outputFormat(){throw new Error("Method not implemented.")}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 l extends o{constructor({apiKey:e,model:t,initialSystemMessage:s}){super({apiKey:e,model:t,initialSystemMessage:s,dataTransferMode:"fetch"}),void 0!==s&&s.length>0&&(this.initialSystemMessage=s)}get config(){return i}async send(t,s){if(s)throw new e.NluxUsageError({source:this.constructor.name,message:'Only one parameter "message" is allowed when using the fetch adapter!'});const r=t;if("string"!=typeof r||0===r.length)throw new e.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const i=this.initialSystemMessage?[{role:"system",content:this.initialSystemMessage}]:[];i.push({role:"user",content:r});try{const e=await this.openai.chat.completions.create({stream:!1,model:this.model,messages:i});return this.decode(e)}catch(t){throw e.warn("Error while making API call to OpenAI"),e.warn(t),new e.NluxUsageError({source:this.constructor.name,message:t?.message||"Error while making API call to OpenAI",exceptionId:a(t)??void 0})}}}class c extends o{constructor({apiKey:e,model:t,initialSystemMessage:s}){super({apiKey:e,model:t,initialSystemMessage:s,dataTransferMode:"stream"}),void 0!==s&&s.length>0&&(this.initialSystemMessage=s)}get config(){return r}send(t,s){if(!s)throw new e.NluxUsageError({source:this.constructor.name,message:"An observer must be provided as a second parameter when using the streaming adapter!"});const r=t;if("string"!=typeof r||0===r.length)throw new e.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const i=this.initialSystemMessage?[{role:"system",content:this.initialSystemMessage}]:[];i.push({role:"user",content:r}),this.openai.chat.completions.create({stream:!0,model:this.model,messages:i}).then((async t=>{let a=t[Symbol.asyncIterator](),r=await a.next();for(;!r.done;){const t=r.value;if("stop"===(t.choices?.length>0?t.choices[0].finish_reason:void 0))break;const i=await this.decode(t);void 0!==i?s.next(i):(e.warn("Undecodable message"),e.warn(t)),r=await a.next()}s.complete()})).catch((t=>{e.warn(t),s.error(new e.NluxUsageError({source:this.constructor.name,message:t.message,exceptionId:a(t)??void 0}))}))}}class d{constructor(e){this.apiKey=null,this.dataTransferMode="stream",this.initialSystemMessage=null,this.model=s,this.setApiKeyCalled=!1,this.setInitialSystemMessageCalled=!1,this.setModelCalled=!1,this.setStreamOrFetchCalled=!1,e&&(this.apiKey=e.apiKey,this.dataTransferMode=e.dataTransferMode,this.initialSystemMessage=e.initialSystemMessage,this.model=e.model??s,this.setApiKeyCalled=e.setApiKeyCalled,this.setInitialSystemMessageCalled=e.setInitialSystemMessageCalled,this.setModelCalled=e.setModelCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled)}create(){if(!this.apiKey)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to create OpenAI adapter. API key is missing. Make sure you are calling withApiKey() before calling create()."});const t={apiKey:this.apiKey,dataTransferMode:this.dataTransferMode,model:this.model,initialSystemMessage:this.initialSystemMessage??void 0};return"stream"===this.dataTransferMode?new c(t):new l(t)}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 withApiKey() twice."});return this.apiKey=t,this.setApiKeyCalled=!0,this}withDataTransferMode(t){if(this.setStreamOrFetchCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataTransferMode=t,this.setStreamOrFetchCalled=!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}withModel(t){if(this.setModelCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set model. Model setter has already been called by this builder. Make sure you are not calling withModel() twice."});return this.model=t,this.setModelCalled=!0,this}}exports.OpenAiFetchAdapter=l,exports.OpenAiStreamingAdapter=c,exports.createAdapter=()=>new d; | ||
"use strict";var e=require("@nlux/nlux"),s=require("openai");const t="gpt-4",a=e=>{if("object"==typeof e&&null!==e){if("invalid_api_key"===e.code)return"NX-NT-002";if(e.message?.toLowerCase().includes("connection error"))return"NX-NT-001"}return null},r=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const s=e.choices[0].delta.content;if("string"==typeof s)return s}}),o=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const s=e.choices[0].message.content;if("string"==typeof s)return s}}),n=Object.freeze({id:"nlux-gpt-adapter",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]});class i{constructor({systemMessage:t,apiKey:a,dataTransferMode:r,model:o}){this.theDataTransferMode="fetch",this.currentStatus="disconnected",this.systemMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.theDataTransferMode=r,this.openai=new s({apiKey:a,dangerouslyAllowBrowser:!0}),this.model=o,t&&(this.systemMessage=t),e.warn('OpenAI GPT 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 dataTransferMode(){return this.theDataTransferMode}get id(){return this.info.id}get info(){return n}get status(){return this.currentStatus}async decode(e){const{decodeMessage:s}=this.config;return s(e)}async encode(e){const{encodeMessage:s}=this.config;return s(e)}}class l extends i{constructor({apiKey:e,model:s,systemMessage:t}){super({apiKey:e,model:s,systemMessage:t,dataTransferMode:"fetch"}),void 0!==t&&t.length>0&&(this.systemMessage=t)}get config(){return o}async send(s,t){if(t)throw new e.NluxUsageError({source:this.constructor.name,message:'Only one parameter "message" is allowed when using the fetch adapter!'});const r=s;if("string"!=typeof r||0===r.length)throw new e.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const o=this.systemMessage?[{role:"system",content:this.systemMessage}]:[];o.push({role:"user",content:r});try{const e=await this.openai.chat.completions.create({stream:!1,model:this.model,messages:o});return this.decode(e)}catch(s){throw e.warn("Error while making API call to OpenAI"),e.warn(s),new e.NluxUsageError({source:this.constructor.name,message:s?.message||"Error while making API call to OpenAI",exceptionId:a(s)??void 0})}}}class c extends i{constructor({apiKey:e,model:s,systemMessage:t}){super({apiKey:e,model:s,systemMessage:t,dataTransferMode:"stream"}),void 0!==t&&t.length>0&&(this.systemMessage=t)}get config(){return r}send(s,t){if(!t)throw new e.NluxUsageError({source:this.constructor.name,message:"An observer must be provided as a second parameter when using the streaming adapter!"});const r=s;if("string"!=typeof r||0===r.length)throw new e.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const o=this.systemMessage?[{role:"system",content:this.systemMessage}]:[];o.push({role:"user",content:r}),this.openai.chat.completions.create({stream:!0,model:this.model,messages:o}).then((async s=>{let a=s[Symbol.asyncIterator](),r=await a.next();for(;!r.done;){const s=r.value;if("stop"===(s.choices?.length>0?s.choices[0].finish_reason:void 0))break;const o=await this.decode(s);void 0!==o?t.next(o):(e.warn("Undecodable message"),e.warn(s)),r=await a.next()}t.complete()})).catch((s=>{e.warn(s),t.error(new e.NluxUsageError({source:this.constructor.name,message:s.message,exceptionId:a(s)??void 0}))}))}}class d{constructor(e){this.apiKey=null,this.dataTransferMode="stream",this.model=t,this.setApiKeyCalled=!1,this.setInitialSystemMessageCalled=!1,this.setModelCalled=!1,this.setStreamOrFetchCalled=!1,this.systemMessage=null,e&&(this.apiKey=e.apiKey,this.dataTransferMode=e.dataTransferMode,this.systemMessage=e.systemMessage,this.model=e.model??t,this.setApiKeyCalled=e.setApiKeyCalled,this.setInitialSystemMessageCalled=e.setInitialSystemMessageCalled,this.setModelCalled=e.setModelCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled)}create(){if(!this.apiKey)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to create OpenAI adapter. API key is missing. Make sure you are calling withApiKey() before calling create()."});const s={apiKey:this.apiKey,dataTransferMode:this.dataTransferMode,model:this.model,systemMessage:this.systemMessage??void 0};return"stream"===this.dataTransferMode?new c(s):new l(s)}withApiKey(s){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 withApiKey() twice."});return this.apiKey=s,this.setApiKeyCalled=!0,this}withDataTransferMode(s){if(this.setStreamOrFetchCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataTransferMode=s,this.setStreamOrFetchCalled=!0,this}withModel(s){if(this.setModelCalled)throw new e.NluxUsageError({source:this.constructor.name,message:"Unable to set model. Model setter has already been called by this builder. Make sure you are not calling withModel() twice."});return this.model=s,this.setModelCalled=!0,this}withSystemMessage(s){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 withSystemMessage() twice."});return this.systemMessage=s??null,this.setInitialSystemMessageCalled=!0,this}}Object.defineProperty(exports,"debug",{enumerable:!0,get:function(){return e.debug}}),exports.OpenAiFetchAdapter=l,exports.OpenAiStreamingAdapter=c,exports.createAdapter=()=>new d; |
@@ -1,1 +0,1 @@ | ||
import{warn as e,NluxUsageError as t}from"@nlux/nlux";import s from"openai";const a="gpt-4",i=e=>{if("object"==typeof e&&null!==e){if("invalid_api_key"===e.code)return"NX-NT-002";if(e.message?.toLowerCase().includes("connection error"))return"NX-NT-001"}return null},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].delta.content;if("string"==typeof t)return t}}),r=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-gpt-adapter",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]});class l{constructor({initialSystemMessage:t,apiKey:a,dataTransferMode:i,model:n}){this.theDataTransferMode="fetch",this.currentStatus="disconnected",this.initialSystemMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.theDataTransferMode=i,this.openai=new s({apiKey:a,dangerouslyAllowBrowser:!0}),this.model=n,t&&(this.initialSystemMessage=t),e('OpenAI GPT 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 dataTransferMode(){return this.theDataTransferMode}get id(){return this.info.id}get info(){return o}get outputFormat(){throw new Error("Method not implemented.")}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 c extends l{constructor({apiKey:e,model:t,initialSystemMessage:s}){super({apiKey:e,model:t,initialSystemMessage:s,dataTransferMode:"fetch"}),void 0!==s&&s.length>0&&(this.initialSystemMessage=s)}get config(){return r}async send(s,a){if(a)throw new t({source:this.constructor.name,message:'Only one parameter "message" is allowed when using the fetch adapter!'});const n=s;if("string"!=typeof n||0===n.length)throw new t({source:this.constructor.name,message:"Cannot send empty messages"});const r=this.initialSystemMessage?[{role:"system",content:this.initialSystemMessage}]:[];r.push({role:"user",content:n});try{const e=await this.openai.chat.completions.create({stream:!1,model:this.model,messages:r});return this.decode(e)}catch(s){throw e("Error while making API call to OpenAI"),e(s),new t({source:this.constructor.name,message:s?.message||"Error while making API call to OpenAI",exceptionId:i(s)??void 0})}}}class d extends l{constructor({apiKey:e,model:t,initialSystemMessage:s}){super({apiKey:e,model:t,initialSystemMessage:s,dataTransferMode:"stream"}),void 0!==s&&s.length>0&&(this.initialSystemMessage=s)}get config(){return n}send(s,a){if(!a)throw new t({source:this.constructor.name,message:"An observer must be provided as a second parameter when using the streaming adapter!"});const n=s;if("string"!=typeof n||0===n.length)throw new t({source:this.constructor.name,message:"Cannot send empty messages"});const r=this.initialSystemMessage?[{role:"system",content:this.initialSystemMessage}]:[];r.push({role:"user",content:n}),this.openai.chat.completions.create({stream:!0,model:this.model,messages:r}).then((async t=>{let s=t[Symbol.asyncIterator](),i=await s.next();for(;!i.done;){const t=i.value;if("stop"===(t.choices?.length>0?t.choices[0].finish_reason:void 0))break;const n=await this.decode(t);void 0!==n?a.next(n):(e("Undecodable message"),e(t)),i=await s.next()}a.complete()})).catch((s=>{e(s),a.error(new t({source:this.constructor.name,message:s.message,exceptionId:i(s)??void 0}))}))}}class h{constructor(e){this.apiKey=null,this.dataTransferMode="stream",this.initialSystemMessage=null,this.model=a,this.setApiKeyCalled=!1,this.setInitialSystemMessageCalled=!1,this.setModelCalled=!1,this.setStreamOrFetchCalled=!1,e&&(this.apiKey=e.apiKey,this.dataTransferMode=e.dataTransferMode,this.initialSystemMessage=e.initialSystemMessage,this.model=e.model??a,this.setApiKeyCalled=e.setApiKeyCalled,this.setInitialSystemMessageCalled=e.setInitialSystemMessageCalled,this.setModelCalled=e.setModelCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled)}create(){if(!this.apiKey)throw new t({source:this.constructor.name,message:"Unable to create OpenAI adapter. API key is missing. Make sure you are calling withApiKey() before calling create()."});const e={apiKey:this.apiKey,dataTransferMode:this.dataTransferMode,model:this.model,initialSystemMessage:this.initialSystemMessage??void 0};return"stream"===this.dataTransferMode?new d(e):new c(e)}withApiKey(e){if(this.setApiKeyCalled)throw new t({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 withApiKey() twice."});return this.apiKey=e,this.setApiKeyCalled=!0,this}withDataTransferMode(e){if(this.setStreamOrFetchCalled)throw new t({source:this.constructor.name,message:"Unable to set data loading mode. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataTransferMode=e,this.setStreamOrFetchCalled=!0,this}withInitialSystemMessage(e){if(this.setInitialSystemMessageCalled)throw new t({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}withModel(e){if(this.setModelCalled)throw new t({source:this.constructor.name,message:"Unable to set model. Model setter has already been called by this builder. Make sure you are not calling withModel() twice."});return this.model=e,this.setModelCalled=!0,this}}const m=()=>new h;export{c as OpenAiFetchAdapter,d as OpenAiStreamingAdapter,m as createAdapter}; | ||
import{warn as e,NluxUsageError as s}from"@nlux/nlux";export{debug}from"@nlux/nlux";import t from"openai";const a="gpt-4",r=e=>{if("object"==typeof e&&null!==e){if("invalid_api_key"===e.code)return"NX-NT-002";if(e.message?.toLowerCase().includes("connection error"))return"NX-NT-001"}return null},o=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const s=e.choices[0].delta.content;if("string"==typeof s)return s}}),i=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const s=e.choices[0].message.content;if("string"==typeof s)return s}}),n=Object.freeze({id:"nlux-gpt-adapter",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]});class c{constructor({systemMessage:s,apiKey:a,dataTransferMode:r,model:o}){this.theDataTransferMode="fetch",this.currentStatus="disconnected",this.systemMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.theDataTransferMode=r,this.openai=new t({apiKey:a,dangerouslyAllowBrowser:!0}),this.model=o,s&&(this.systemMessage=s),e('OpenAI GPT 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 dataTransferMode(){return this.theDataTransferMode}get id(){return this.info.id}get info(){return n}get status(){return this.currentStatus}async decode(e){const{decodeMessage:s}=this.config;return s(e)}async encode(e){const{encodeMessage:s}=this.config;return s(e)}}class l extends c{constructor({apiKey:e,model:s,systemMessage:t}){super({apiKey:e,model:s,systemMessage:t,dataTransferMode:"fetch"}),void 0!==t&&t.length>0&&(this.systemMessage=t)}get config(){return i}async send(t,a){if(a)throw new s({source:this.constructor.name,message:'Only one parameter "message" is allowed when using the fetch adapter!'});const o=t;if("string"!=typeof o||0===o.length)throw new s({source:this.constructor.name,message:"Cannot send empty messages"});const i=this.systemMessage?[{role:"system",content:this.systemMessage}]:[];i.push({role:"user",content:o});try{const e=await this.openai.chat.completions.create({stream:!1,model:this.model,messages:i});return this.decode(e)}catch(t){throw e("Error while making API call to OpenAI"),e(t),new s({source:this.constructor.name,message:t?.message||"Error while making API call to OpenAI",exceptionId:r(t)??void 0})}}}class d extends c{constructor({apiKey:e,model:s,systemMessage:t}){super({apiKey:e,model:s,systemMessage:t,dataTransferMode:"stream"}),void 0!==t&&t.length>0&&(this.systemMessage=t)}get config(){return o}send(t,a){if(!a)throw new s({source:this.constructor.name,message:"An observer must be provided as a second parameter when using the streaming adapter!"});const o=t;if("string"!=typeof o||0===o.length)throw new s({source:this.constructor.name,message:"Cannot send empty messages"});const i=this.systemMessage?[{role:"system",content:this.systemMessage}]:[];i.push({role:"user",content:o}),this.openai.chat.completions.create({stream:!0,model:this.model,messages:i}).then((async s=>{let t=s[Symbol.asyncIterator](),r=await t.next();for(;!r.done;){const s=r.value;if("stop"===(s.choices?.length>0?s.choices[0].finish_reason:void 0))break;const o=await this.decode(s);void 0!==o?a.next(o):(e("Undecodable message"),e(s)),r=await t.next()}a.complete()})).catch((t=>{e(t),a.error(new s({source:this.constructor.name,message:t.message,exceptionId:r(t)??void 0}))}))}}class h{constructor(e){this.apiKey=null,this.dataTransferMode="stream",this.model=a,this.setApiKeyCalled=!1,this.setInitialSystemMessageCalled=!1,this.setModelCalled=!1,this.setStreamOrFetchCalled=!1,this.systemMessage=null,e&&(this.apiKey=e.apiKey,this.dataTransferMode=e.dataTransferMode,this.systemMessage=e.systemMessage,this.model=e.model??a,this.setApiKeyCalled=e.setApiKeyCalled,this.setInitialSystemMessageCalled=e.setInitialSystemMessageCalled,this.setModelCalled=e.setModelCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled)}create(){if(!this.apiKey)throw new s({source:this.constructor.name,message:"Unable to create OpenAI adapter. API key is missing. Make sure you are calling withApiKey() before calling create()."});const e={apiKey:this.apiKey,dataTransferMode:this.dataTransferMode,model:this.model,systemMessage:this.systemMessage??void 0};return"stream"===this.dataTransferMode?new d(e):new l(e)}withApiKey(e){if(this.setApiKeyCalled)throw new s({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 withApiKey() twice."});return this.apiKey=e,this.setApiKeyCalled=!0,this}withDataTransferMode(e){if(this.setStreamOrFetchCalled)throw new s({source:this.constructor.name,message:"Unable to set data loading mode. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataTransferMode=e,this.setStreamOrFetchCalled=!0,this}withModel(e){if(this.setModelCalled)throw new s({source:this.constructor.name,message:"Unable to set model. Model setter has already been called by this builder. Make sure you are not calling withModel() twice."});return this.model=e,this.setModelCalled=!0,this}withSystemMessage(e){if(this.setInitialSystemMessageCalled)throw new s({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 withSystemMessage() twice."});return this.systemMessage=e??null,this.setInitialSystemMessageCalled=!0,this}}const m=()=>new h;export{l as OpenAiFetchAdapter,d as OpenAiStreamingAdapter,m as createAdapter}; |
@@ -1,5 +0,14 @@ | ||
import { AdapterBuilder, StandardAdapter, DataTransferMode, StandardAdapterStatus, StandardAdapterConfig, StandardAdapterInfo, AdapterOutputFormat, Message, StreamingAdapterObserver } from '@nlux/nlux'; | ||
export { Adapter, DataTransferMode, StandardAdapter } from '@nlux/nlux'; | ||
import { DataTransferMode, AdapterBuilder, StandardAdapter, StandardAdapterStatus, StandardAdapterConfig, StandardAdapterInfo, Message, StreamingAdapterObserver } from '@nlux/nlux'; | ||
export { Adapter, DataTransferMode, SendInFetchMode, SendInStreamMode, StandardAdapter, debug } from '@nlux/nlux'; | ||
import OpenAI from 'openai'; | ||
type OpenAIModel = 'gpt-4' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-16k-0613'; | ||
type OpenAiAdapterOptions = { | ||
dataTransferMode: DataTransferMode; | ||
model: OpenAIModel; | ||
apiKey: string; | ||
systemMessage?: string; | ||
}; | ||
interface OpenAiAdapterBuilder extends AdapterBuilder<any, any> { | ||
@@ -35,10 +44,2 @@ /** | ||
/** | ||
* The initial system to send to ChatGPT API. | ||
* | ||
* @optional | ||
* @param {string} message | ||
* @returns {AdapterBuilder} | ||
*/ | ||
withInitialSystemMessage(message: string): OpenAiAdapterBuilder; | ||
/** | ||
* The model or the endpoint to use for ChatGPT Inference API. | ||
@@ -53,2 +54,10 @@ * You should provide either a model or an endpoint, but not both. | ||
withModel(model: string): OpenAiAdapterBuilder; | ||
/** | ||
* The initial system to send to ChatGPT API. | ||
* | ||
* @optional | ||
* @param {string} message | ||
* @returns {AdapterBuilder} | ||
*/ | ||
withSystemMessage(message: string): OpenAiAdapterBuilder; | ||
} | ||
@@ -58,11 +67,2 @@ | ||
type OpenAIModel = 'gpt-4' | 'gpt-4-0613' | 'gpt-4-32k' | 'gpt-4-32k-0613' | 'gpt-3.5-turbo' | 'gpt-3.5-turbo-0613' | 'gpt-3.5-turbo-16k' | 'gpt-3.5-turbo-16k-0613'; | ||
type OpenAiAdapterOptions = { | ||
dataTransferMode: DataTransferMode; | ||
model: OpenAIModel; | ||
apiKey: string; | ||
initialSystemMessage?: string; | ||
}; | ||
declare abstract class OpenAiAbstractAdapter<InboundPayload, OutboundPayload> implements StandardAdapter<InboundPayload, OutboundPayload> { | ||
@@ -73,4 +73,4 @@ protected readonly model: OpenAIModel; | ||
protected currentStatus: StandardAdapterStatus; | ||
protected initialSystemMessage: string | null; | ||
protected constructor({ initialSystemMessage, apiKey, dataTransferMode, model, }: OpenAiAdapterOptions); | ||
protected systemMessage: string | null; | ||
protected constructor({ systemMessage, apiKey, dataTransferMode, model, }: OpenAiAdapterOptions); | ||
abstract get config(): StandardAdapterConfig<InboundPayload, OutboundPayload>; | ||
@@ -80,3 +80,2 @@ get dataTransferMode(): DataTransferMode; | ||
get info(): StandardAdapterInfo; | ||
get outputFormat(): AdapterOutputFormat; | ||
get status(): StandardAdapterStatus; | ||
@@ -90,3 +89,3 @@ decode(payload: InboundPayload): Promise<Message>; | ||
declare class OpenAiStreamingAdapter extends OpenAiAbstractAdapter<OpenAI.Chat.Completions.ChatCompletionChunk, OpenAI.Chat.Completions.ChatCompletionMessageParam> { | ||
constructor({ apiKey, model, initialSystemMessage, }: OpenAiAdapterOptions); | ||
constructor({ apiKey, model, systemMessage, }: OpenAiAdapterOptions); | ||
get config(): Readonly<{ | ||
@@ -101,3 +100,3 @@ encodeMessage: (input: Message) => Promise<OpenAI.Chat.Completions.ChatCompletionMessageParam>; | ||
declare class OpenAiFetchAdapter extends OpenAiAbstractAdapter<OpenAI.Chat.Completions.ChatCompletion, OpenAI.Chat.Completions.ChatCompletionMessageParam> { | ||
constructor({ apiKey, model, initialSystemMessage, }: OpenAiAdapterOptions); | ||
constructor({ apiKey, model, systemMessage, }: OpenAiAdapterOptions); | ||
get config(): Readonly<{ | ||
@@ -104,0 +103,0 @@ encodeMessage: (input: Message) => Promise<OpenAI.Chat.Completions.ChatCompletionMessageParam>; |
{ | ||
"name": "@nlux/openai", | ||
"version": "0.4.8", | ||
"version": "0.4.9", | ||
"description": "The OpenAI adapters for NLUX, the javascript library for building conversational AI interfaces.", | ||
@@ -5,0 +5,0 @@ "keywords": [ |
@@ -1,1 +0,1 @@ | ||
!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="gpt-4",i=e=>{if("object"==typeof e&&null!==e){if("invalid_api_key"===e.code)return"NX-NT-002";if(e.message?.toLowerCase().includes("connection error"))return"NX-NT-001"}return null},r=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}}),o=Object.freeze({id:"nlux-gpt-adapter",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]});class l{constructor({initialSystemMessage:e,apiKey:a,dataTransferMode:i,model:r}){this.theDataTransferMode="fetch",this.currentStatus="disconnected",this.initialSystemMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.theDataTransferMode=i,this.openai=new s({apiKey:a,dangerouslyAllowBrowser:!0}),this.model=r,e&&(this.initialSystemMessage=e),t.warn('OpenAI GPT 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 dataTransferMode(){return this.theDataTransferMode}get id(){return this.info.id}get info(){return o}get outputFormat(){throw new Error("Method not implemented.")}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 c extends l{constructor({apiKey:e,model:t,initialSystemMessage:s}){super({apiKey:e,model:t,initialSystemMessage:s,dataTransferMode:"fetch"}),void 0!==s&&s.length>0&&(this.initialSystemMessage=s)}get config(){return n}async send(e,s){if(s)throw new t.NluxUsageError({source:this.constructor.name,message:'Only one parameter "message" is allowed when using the fetch adapter!'});const a=e;if("string"!=typeof a||0===a.length)throw new t.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const r=this.initialSystemMessage?[{role:"system",content:this.initialSystemMessage}]:[];r.push({role:"user",content:a});try{const e=await this.openai.chat.completions.create({stream:!1,model:this.model,messages:r});return this.decode(e)}catch(e){throw t.warn("Error while making API call to OpenAI"),t.warn(e),new t.NluxUsageError({source:this.constructor.name,message:e?.message||"Error while making API call to OpenAI",exceptionId:i(e)??void 0})}}}class d extends l{constructor({apiKey:e,model:t,initialSystemMessage:s}){super({apiKey:e,model:t,initialSystemMessage:s,dataTransferMode:"stream"}),void 0!==s&&s.length>0&&(this.initialSystemMessage=s)}get config(){return r}send(e,s){if(!s)throw new t.NluxUsageError({source:this.constructor.name,message:"An observer must be provided as a second parameter when using the streaming adapter!"});const a=e;if("string"!=typeof a||0===a.length)throw new t.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const r=this.initialSystemMessage?[{role:"system",content:this.initialSystemMessage}]:[];r.push({role:"user",content:a}),this.openai.chat.completions.create({stream:!0,model:this.model,messages:r}).then((async e=>{let a=e[Symbol.asyncIterator](),i=await a.next();for(;!i.done;){const e=i.value;if("stop"===(e.choices?.length>0?e.choices[0].finish_reason:void 0))break;const r=await this.decode(e);void 0!==r?s.next(r):(t.warn("Undecodable message"),t.warn(e)),i=await a.next()}s.complete()})).catch((e=>{t.warn(e),s.error(new t.NluxUsageError({source:this.constructor.name,message:e.message,exceptionId:i(e)??void 0}))}))}}class h{constructor(e){this.apiKey=null,this.dataTransferMode="stream",this.initialSystemMessage=null,this.model=a,this.setApiKeyCalled=!1,this.setInitialSystemMessageCalled=!1,this.setModelCalled=!1,this.setStreamOrFetchCalled=!1,e&&(this.apiKey=e.apiKey,this.dataTransferMode=e.dataTransferMode,this.initialSystemMessage=e.initialSystemMessage,this.model=e.model??a,this.setApiKeyCalled=e.setApiKeyCalled,this.setInitialSystemMessageCalled=e.setInitialSystemMessageCalled,this.setModelCalled=e.setModelCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled)}create(){if(!this.apiKey)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to create OpenAI adapter. API key is missing. Make sure you are calling withApiKey() before calling create()."});const e={apiKey:this.apiKey,dataTransferMode:this.dataTransferMode,model:this.model,initialSystemMessage:this.initialSystemMessage??void 0};return"stream"===this.dataTransferMode?new d(e):new c(e)}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 withApiKey() twice."});return this.apiKey=e,this.setApiKeyCalled=!0,this}withDataTransferMode(e){if(this.setStreamOrFetchCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataTransferMode=e,this.setStreamOrFetchCalled=!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}withModel(e){if(this.setModelCalled)throw new t.NluxUsageError({source:this.constructor.name,message:"Unable to set model. Model setter has already been called by this builder. Make sure you are not calling withModel() twice."});return this.model=e,this.setModelCalled=!0,this}}e.OpenAiFetchAdapter=c,e.OpenAiStreamingAdapter=d,e.createAdapter=()=>new h})); | ||
!function(e,s){"object"==typeof exports&&"undefined"!=typeof module?s(exports,require("@nlux/nlux"),require("openai")):"function"==typeof define&&define.amd?define(["exports","@nlux/nlux","openai"],s):s((e="undefined"!=typeof globalThis?globalThis:e||self)["@nlux/openai"]={},e.nlux,e.OpenAI)}(this,(function(e,s,t){"use strict";const a="gpt-4",r=e=>{if("object"==typeof e&&null!==e){if("invalid_api_key"===e.code)return"NX-NT-002";if(e.message?.toLowerCase().includes("connection error"))return"NX-NT-001"}return null},o=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const s=e.choices[0].delta.content;if("string"==typeof s)return s}}),n=Object.freeze({encodeMessage:async e=>({role:"user",content:e}),decodeMessage:async e=>{if(!e.choices||!e.choices[0])throw Error("Invalid payload");const s=e.choices[0].message.content;if("string"==typeof s)return s}}),i=Object.freeze({id:"nlux-gpt-adapter",capabilities:{textChat:!0,audio:!1,fileUpload:!1,replyToSingleMessage:!1},remote:{url:"https://api.openai.com/v1/chat/completion"},inputFormats:["text"],outputFormats:["text"]});class l{constructor({systemMessage:e,apiKey:a,dataTransferMode:r,model:o}){this.theDataTransferMode="fetch",this.currentStatus="disconnected",this.systemMessage="Act as a helpful assistant to the user",this.currentStatus="disconnected",this.theDataTransferMode=r,this.openai=new t({apiKey:a,dangerouslyAllowBrowser:!0}),this.model=o,e&&(this.systemMessage=e),s.warn('OpenAI GPT 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 dataTransferMode(){return this.theDataTransferMode}get id(){return this.info.id}get info(){return i}get status(){return this.currentStatus}async decode(e){const{decodeMessage:s}=this.config;return s(e)}async encode(e){const{encodeMessage:s}=this.config;return s(e)}}class c extends l{constructor({apiKey:e,model:s,systemMessage:t}){super({apiKey:e,model:s,systemMessage:t,dataTransferMode:"fetch"}),void 0!==t&&t.length>0&&(this.systemMessage=t)}get config(){return n}async send(e,t){if(t)throw new s.NluxUsageError({source:this.constructor.name,message:'Only one parameter "message" is allowed when using the fetch adapter!'});const a=e;if("string"!=typeof a||0===a.length)throw new s.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const o=this.systemMessage?[{role:"system",content:this.systemMessage}]:[];o.push({role:"user",content:a});try{const e=await this.openai.chat.completions.create({stream:!1,model:this.model,messages:o});return this.decode(e)}catch(e){throw s.warn("Error while making API call to OpenAI"),s.warn(e),new s.NluxUsageError({source:this.constructor.name,message:e?.message||"Error while making API call to OpenAI",exceptionId:r(e)??void 0})}}}class d extends l{constructor({apiKey:e,model:s,systemMessage:t}){super({apiKey:e,model:s,systemMessage:t,dataTransferMode:"stream"}),void 0!==t&&t.length>0&&(this.systemMessage=t)}get config(){return o}send(e,t){if(!t)throw new s.NluxUsageError({source:this.constructor.name,message:"An observer must be provided as a second parameter when using the streaming adapter!"});const a=e;if("string"!=typeof a||0===a.length)throw new s.NluxUsageError({source:this.constructor.name,message:"Cannot send empty messages"});const o=this.systemMessage?[{role:"system",content:this.systemMessage}]:[];o.push({role:"user",content:a}),this.openai.chat.completions.create({stream:!0,model:this.model,messages:o}).then((async e=>{let a=e[Symbol.asyncIterator](),r=await a.next();for(;!r.done;){const e=r.value;if("stop"===(e.choices?.length>0?e.choices[0].finish_reason:void 0))break;const o=await this.decode(e);void 0!==o?t.next(o):(s.warn("Undecodable message"),s.warn(e)),r=await a.next()}t.complete()})).catch((e=>{s.warn(e),t.error(new s.NluxUsageError({source:this.constructor.name,message:e.message,exceptionId:r(e)??void 0}))}))}}class h{constructor(e){this.apiKey=null,this.dataTransferMode="stream",this.model=a,this.setApiKeyCalled=!1,this.setInitialSystemMessageCalled=!1,this.setModelCalled=!1,this.setStreamOrFetchCalled=!1,this.systemMessage=null,e&&(this.apiKey=e.apiKey,this.dataTransferMode=e.dataTransferMode,this.systemMessage=e.systemMessage,this.model=e.model??a,this.setApiKeyCalled=e.setApiKeyCalled,this.setInitialSystemMessageCalled=e.setInitialSystemMessageCalled,this.setModelCalled=e.setModelCalled,this.setStreamOrFetchCalled=e.setStreamOrFetchCalled)}create(){if(!this.apiKey)throw new s.NluxUsageError({source:this.constructor.name,message:"Unable to create OpenAI adapter. API key is missing. Make sure you are calling withApiKey() before calling create()."});const e={apiKey:this.apiKey,dataTransferMode:this.dataTransferMode,model:this.model,systemMessage:this.systemMessage??void 0};return"stream"===this.dataTransferMode?new d(e):new c(e)}withApiKey(e){if(this.setApiKeyCalled)throw new s.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 withApiKey() twice."});return this.apiKey=e,this.setApiKeyCalled=!0,this}withDataTransferMode(e){if(this.setStreamOrFetchCalled)throw new s.NluxUsageError({source:this.constructor.name,message:"Unable to set data loading mode. Stream or fetch setter has already been called by this builder. Make sure you are not calling stream() or fetch() twice."});return this.dataTransferMode=e,this.setStreamOrFetchCalled=!0,this}withModel(e){if(this.setModelCalled)throw new s.NluxUsageError({source:this.constructor.name,message:"Unable to set model. Model setter has already been called by this builder. Make sure you are not calling withModel() twice."});return this.model=e,this.setModelCalled=!0,this}withSystemMessage(e){if(this.setInitialSystemMessageCalled)throw new s.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 withSystemMessage() twice."});return this.systemMessage=e??null,this.setInitialSystemMessageCalled=!0,this}}Object.defineProperty(e,"debug",{enumerable:!0,get:function(){return s.debug}}),e.OpenAiFetchAdapter=c,e.OpenAiStreamingAdapter=d,e.createAdapter=()=>new h})); |
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
0
25464
169