ctod 0.3.2 → 0.3.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ctod=t():e.ctod=t()}(this||("undefined"!=typeof window?window:global),(()=>(()=>{"use strict";var e={37:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},r.apply(this,arguments)},o=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},a=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a},u=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBroker=void 0;var s=n(15),l=n(470),c=n(87),f=function(){function e(e){var t;this.hook=new l.Hook,this.plugins={},this.installed=!1,this.log=new l.Log(null!==(t=e.name)&&void 0!==t?t:"no name"),this.params=e,this.translator=new c.Translator(r(r({},e),{parsers:[s.TextParser.JsonMessage()]}))}return e.prototype._install=function(){if(!1===this.installed){this.installed=!0;var e={log:this.log,attach:this.hook.attach.bind(this.hook),attachAfter:this.hook.attachAfter.bind(this.hook),translator:this.translator};if(this.params.install(e),this.params.plugins)for(var t in this.plugins="function"==typeof this.params.plugins?this.params.plugins():this.params.plugins,this.plugins)this.plugins[t].instance._params.onInstall(r(r({},e),{params:this.plugins[t].params,receive:this.plugins[t].receive}))}},e.prototype.request=function(e){return o(this,void 0,void 0,(function(){var t,n,r,s,c,f,p,h=this;return i(this,(function(d){switch(d.label){case 0:return this._install(),t=l.flow.createUuid(),n=null,r={},[4,this.translator.compile(e)];case 1:for(p in s=d.sent(),c=[{role:"user",content:s.prompt}],f=function(e){r[e]={send:function(n){return h.plugins[e].send({id:t,data:n})}}},this.plugins)f(p);return[4,this.hook.notify("start",{id:t,data:e,plugins:r,messages:c,setPreMessages:function(e){c=u(u([],a(e),!1),[{role:"user",content:s.prompt}],!1)},changeMessages:function(e){c=e}})];case 2:return d.sent(),[4,l.flow.asyncWhile((function(r){var a=r.count,u=r.doBreak;return o(h,void 0,void 0,(function(){var r,o,s,l,f,p;return i(this,(function(i){switch(i.label){case 0:if(a>=10)return[2,u()];r="",o="",s=!1,l=(null===(p=c.filter((function(e){return"user"===e.role})).slice(-1)[0])||void 0===p?void 0:p.content)||"",i.label=1;case 1:return i.trys.push([1,8,,15]),[4,this.hook.notify("talkBefore",{id:t,data:e,messages:c,lastUserMessage:l})];case 2:return i.sent(),[4,this.params.request(c)];case 3:return r=i.sent(),o=r,[4,this.hook.notify("talkAfter",{id:t,data:e,response:r,messages:c,parseText:o,lastUserMessage:l,changeParseText:function(e){o=e}})];case 4:return i.sent(),[4,this.translator.parse(o)];case 5:return n=i.sent().output,[4,this.hook.notify("succeeded",{id:t,output:n})];case 6:return i.sent(),[4,this.hook.notify("done",{id:t})];case 7:return i.sent(),u(),[3,15];case 8:return(f=i.sent()).isParserError?[4,this.hook.notify("parseFailed",{id:t,error:f.error,count:a,response:r,messages:c,lastUserMessage:l,parserFails:f.parserFails,retry:function(){s=!0},changeMessages:function(e){c=e}})]:[3,12];case 9:return i.sent(),!1!==s?[3,11]:[4,this.hook.notify("done",{id:t})];case 10:throw i.sent(),f;case 11:return[3,14];case 12:return[4,this.hook.notify("done",{id:t})];case 13:throw i.sent(),f;case 14:return[3,15];case 15:return[2]}}))}))}))];case 3:return d.sent(),[2,n]}}))}))},e}();t.ChatBroker=f},15:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TextParser=void 0;var a=i(n(959)),u=function(){function e(e){this.params=e}return e.JsonMessage=function(){var t=this;return new e({name:"JsonMessage",handler:function(e){return r(t,void 0,void 0,(function(){var t,n,r;return o(this,(function(o){return t=/{(?:[^{}]|(?:{[^{}]*}))*}/,n=(null===(r=e.match(t))||void 0===r?void 0:r[0])||"",[2,a.default.parse(n)]}))}))}})},Object.defineProperty(e.prototype,"name",{get:function(){return this.params.name},enumerable:!1,configurable:!0}),e.prototype.read=function(e){return r(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.params.handler(e)];case 1:return[2,t.sent()]}}))}))},e}();t.TextParser=u},241:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBrokerPlugin=void 0;var r=n(470),o=function(){function e(e){this._event=new r.Event,this._params=e}return e.prototype.use=function(e){var t=this;return{instance:this,params:e,send:function(e){t._event.emit("receive",e)},receive:function(e){t._event.on("receive",e)},__receiveData:null}},e}();t.ChatBrokerPlugin=o},87:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.Translator=void 0;var a=n(293),u=function(){function e(e){this.params=e}return Object.defineProperty(e.prototype,"__schemeType",{get:function(){return null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"__outputType",{get:function(){return null},enumerable:!1,configurable:!0}),e.prototype.compile=function(e){return r(this,void 0,void 0,(function(){var t,n;return o(this,(function(r){switch(r.label){case 0:return t=(0,a.validate)(e,this.params.input),[4,this.params.question(t)];case 1:return n=r.sent(),[2,{scheme:t,prompt:n}]}}))}))},e.prototype.parse=function(e){return r(this,void 0,void 0,(function(){var t,n,r,u,s,l,c,f,p,h;return o(this,(function(o){switch(o.label){case 0:t=void 0,n="",r=[],o.label=1;case 1:o.trys.push([1,8,9,10]),u=i(this.params.parsers),s=u.next(),o.label=2;case 2:if(s.done)return[3,7];l=s.value,o.label=3;case 3:return o.trys.push([3,5,,6]),[4,l.read(e)];case 4:return t=o.sent(),n=l.name,[3,6];case 5:return c=o.sent(),t=void 0,r.push({name:l.name,error:c}),[3,6];case 6:return s=u.next(),[3,2];case 7:return[3,10];case 8:return f=o.sent(),p={error:f},[3,10];case 9:try{s&&!s.done&&(h=u.return)&&h.call(u)}finally{if(p)throw p.error}return[7];case 10:try{return[2,{output:(0,a.validate)(t,this.params.output),parserName:n,parserFails:r}]}catch(e){throw{isParserError:!0,error:e,parserFails:r}}return[2]}}))}))},e}();t.Translator=u},620:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ctod=t.templates=t.plugins=t.ChatBrokerPlugin=t.ChatBroker=t.Translator=t.TextParser=t.OpenAI=void 0;var a=i(n(218)),u=i(n(298)),s=i(n(87)),l=n(616),c=n(15),f=n(37),p=n(241);t.OpenAI=l.OpenAI,t.TextParser=c.TextParser,t.Translator=s.Translator,t.ChatBroker=f.ChatBroker,t.ChatBrokerPlugin=p.ChatBrokerPlugin,t.plugins=a,t.templates=u,t.ctod={OpenAI:t.OpenAI,plugins:t.plugins,templates:t.templates,ChatBroker:t.ChatBroker,Translator:t.Translator,TextParser:t.TextParser,ChatBrokerPlugin:t.ChatBrokerPlugin},e.exports=t.ctod,e.exports.ctod=t.ctod,t.default=t.ctod},218:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RolePlugin=t.LimiterPluginGlobState=t.LimiterPlugin=t.RetryPlugin=t.PrintLogPlugin=void 0;var o=r(n(894)),i=r(n(829)),a=r(n(626)),u=r(n(1));t.PrintLogPlugin=i.default,t.RetryPlugin=o.default,t.LimiterPlugin=a.default.plugin,t.LimiterPluginGlobState=a.default,t.RolePlugin=u.default},626:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(241),a=n(470),u={limit:3,interval:6e4},s={event:new a.Event,schedule:null,waitTimes:[],waitQueue:[]};t.default={event:s.event,config:u,closeSchedule:function(){s.schedule&&(s.schedule.close(),s.schedule=null)},plugin:new i.ChatBrokerPlugin({name:"limiter",params:function(){return{}},receiveData:function(){return{}},onInstall:function(e){var t=this,n=e.attach;null==s.schedule&&(s.schedule=new a.Schedule,s.schedule.add("calc queue",1e3,(function(){return r(t,void 0,void 0,(function(){var e,t;return o(this,(function(n){return e=Date.now(),s.waitTimes=s.waitTimes.filter((function(t){return e-t<u.interval})),s.waitTimes.length!==u.limit?(t=s.waitQueue.shift())&&(s.waitTimes.push(Date.now()),s.event.emit("run",{id:t})):s.waitTimes[0]&&s.event.emit("waitTimeChange",{waitTime:Math.floor(60-(e-s.waitTimes[0])/1e3)}),[2]}))}))})),s.schedule.play()),n("talkBefore",(function(){return r(t,void 0,void 0,(function(){var e;return o(this,(function(t){return e=a.flow.createUuid(),s.waitQueue.push(e),[2,new Promise((function(t){s.event.on("run",(function(n,r){var o=n.id,i=r.off;o===e&&(i(),t())}))}))]}))}))}))}})}},829:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(241);t.default=new i.ChatBrokerPlugin({name:"print-log",params:function(e){return{detail:e.boolean().required().default(!1)}},receiveData:function(){return{}},onInstall:function(e){var t=this,n=e.params,i=e.log,a=e.attach;a("talkBefore",(function(e){var a=e.lastUserMessage,u=e.messages;return r(t,void 0,void 0,(function(){return o(this,(function(e){return i.print("Send:",{color:"green"}),n.detail?i.print("\n"+JSON.stringify(u,null,4)):i.print("\n"+a),[2]}))}))})),a("talkAfter",(function(e){var n=e.parseText;return r(t,void 0,void 0,(function(){return o(this,(function(e){return i.print("Receive:",{color:"cyan"}),i.print("\n"+n),[2]}))}))})),a("succeeded",(function(e){var n=e.output;return r(t,void 0,void 0,(function(){return o(this,(function(e){i.print("Output:",{color:"yellow"});try{i.print("\n"+JSON.stringify(n,null,4))}catch(e){i.print("\n"+n)}return[2]}))}))}))}})},894:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(241);t.default=new i.ChatBrokerPlugin({name:"retry",params:function(e){return{retry:e.number().required().default(1),printWarn:e.boolean().required().default(!0)}},receiveData:function(){return{}},onInstall:function(e){var t=this,n=e.log,i=e.attach,a=e.params;i("parseFailed",(function(e){var i=e.count,u=e.retry,s=e.response,l=e.changeMessages;return r(t,void 0,void 0,(function(){return o(this,(function(e){return i<=a.retry&&(a.printWarn&&n.print("Is Failed, Retry ".concat(i," times.")),l(s.newMessages.slice(0,-1)),u()),[2]}))}))}))}})},1:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a},a=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0});var u=n(241);t.default=new u.ChatBrokerPlugin({name:"role",params:function(e){return{role:e.string().required()}},receiveData:function(){return{}},onInstall:function(e){var t=this,n=e.attach,u=e.params;n("start",(function(e){var n=e.messages,s=e.changeMessages;return r(t,void 0,void 0,(function(){return o(this,(function(e){return s(a([{role:"user",content:"你現在是".concat(u.role,"。")},{role:"assistant",content:"沒問題,我現在是".concat(u.role,",有什麼可以幫你的嗎?")}],i(n),!1)),[2]}))}))}))}})},203:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a},a=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIChat=void 0;var u=n(470),s=function(){function e(e){this.config={n:1,model:"gpt-3.5-turbo",temperature:1,forceJsonFormat:!0},this.openai=e}return e.prototype.setConfig=function(e){Object.assign(this.config,e)},e.prototype.talk=function(e){var t,n;return void 0===e&&(e=[]),r(this,void 0,void 0,(function(){var r,i,a,s,l;return o(this,(function(o){switch(o.label){case 0:return r=u.json.jpjs(e),i=["gpt-4-1106-preview","gpt-3.5-turbo-1106"].includes(this.config.model),[4,this.openai._axios.post("https://api.openai.com/v1/chat/completions",{model:this.config.model,n:this.config.n,messages:r,response_format:!1===i||!1===this.config.forceJsonFormat?void 0:{type:"json_object"},temperature:this.config.temperature},{headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.openai._apiKey)}})];case 1:return a=o.sent(),s=a.data.choices||[],l=(null===(t=s[0])||void 0===t?void 0:t.message)||{role:"assistant",content:""},r.push(l),[2,{id:null==a?void 0:a.data.id,text:l.content,newMessages:r,isDone:"stop"===(null===(n=s[0])||void 0===n?void 0:n.finish_reason),apiReseponse:a.data}]}}))}))},e.prototype.keepTalk=function(e,t){return void 0===t&&(t=[]),r(this,void 0,void 0,(function(){var n,r=this;return o(this,(function(o){switch(o.label){case 0:return[4,this.talk(a(a([],i(t),!1),[{role:"user",content:Array.isArray(e)?e.join("\n"):e}],!1))];case 1:return[2,{result:n=o.sent(),nextTalk:function(e){return r.keepTalk(e,n.newMessages)}}]}}))}))},e}();t.OpenAIChat=s},919:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAICompletion=void 0;var o=function(){function e(e){this.config={n:1,maxTokens:2048,temperature:1},this.openai=e}return e.prototype.setConfig=function(e){Object.assign(this.config,e)},e.prototype.run=function(e){var t,o;return n(this,void 0,void 0,(function(){var n,i;return r(this,(function(r){switch(r.label){case 0:return[4,this.openai._axios.post("https://api.openai.com/v1/completions",{model:"text-davinci-003",n:this.config.n,prompt:Array.isArray(e)?e.join("\n"):e,max_tokens:this.config.maxTokens,temperature:this.config.temperature},{headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.openai._apiKey)}})];case 1:return n=r.sent(),i=n.data.choices||[],[2,{id:n.data.id,text:(null===(t=i[0])||void 0===t?void 0:t.text)||"",isDone:"stop"===(null===(o=i[0])||void 0===o?void 0:o.finish_reason),apiReseponse:n.data}]}}))}))},e}();t.OpenAICompletion=o},725:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIImagesGeneration=void 0;var o=function(){function e(e){this.config={n:1,size:"1024x1024"},this.openai=e}return e.prototype.setConfig=function(e){Object.assign(this.config,e)},e.prototype.create=function(e){return n(this,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,this.openai._axios.post("https://api.openai.com/v1/images/generations",{prompt:e,n:this.config.n,size:this.config.size,response_format:"b64_json"},{timeout:3e5,headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.openai._apiKey)}})];case 1:return[2,t.sent().data]}}))}))},e}();t.OpenAIImagesGeneration=o},616:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAI=void 0;var a=n(203),u=n(919),s=n(725),l=i(n(167)),c=function(){function e(e){void 0===e&&(e=""),this._axios=l.default.create(),this._apiKey="",this._apiKey=e}return e.createChatRequest=function(t,n){var i=this;return void 0===n&&(n={}),function(a){return r(i,void 0,void 0,(function(){var r,i;return o(this,(function(o){switch(o.label){case 0:return r=new e(t),(i=r.createChat()).setConfig(n),[4,i.talk(a)];case 1:return[2,o.sent().text]}}))}))}},e.prototype.setAxios=function(e){this._axios=e},e.prototype.setConfiguration=function(e){this._apiKey=e},e.prototype.createChat=function(){return new a.OpenAIChat(this)},e.prototype.createCompletion=function(){return new u.OpenAICompletion(this)},e.prototype.createImagesGeneration=function(){return new s.OpenAIImagesGeneration(this)},e}();t.OpenAI=c},298:function(e,t,n){var r=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a},o=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.requireJsonResponseWithHandlebars=t.requireJsonResponse=void 0;var a=i(n(97)),u=n(470);t.requireJsonResponse=function(e,t){return o(o([],r(Array.isArray(e)?e:[e]),!1),["Please respond using the following JSON format and minify the JSON without including any explanation: ","{",Object.entries(t).map((function(e){var t=r(e,2),n=t[0],o=t[1];return["/* ".concat(o.desc," */"),'"'.concat(n,'": ').concat(JSON.stringify(o.example))].join("\n")})).join(",\n"),"}"],!1).join("\n")},t.requireJsonResponseWithHandlebars=function(e,n,r){var o=a.default.create();return o.registerHelper("DATA",(function(e){return JSON.stringify(e)})),o.registerHelper("ENV",(function(e){return this.__envs&&e?this.__envs[e]:""})),o.registerHelper("INPUT",(function(){return JSON.stringify(u.record.omit(this,["__envs"]))})),o.registerHelper("JOIN",(function(e){return Array.isArray(e)?e.join():JSON.stringify(e)})),o.compile((0,t.requireJsonResponse)(n,r))(e)}},293:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.validate=t.definedValidateSchema=void 0;var a=i(n(609));t.definedValidateSchema=function(e){return e},t.validate=function(e,t){return a.object(t(a)).required().validateSync(e||{})}},167:e=>{e.exports=require("axios")},97:e=>{e.exports=require("handlebars")},959:e=>{e.exports=require("json5")},470:e=>{e.exports=require("power-helper")},609:e=>{e.exports=require("yup")}},t={};return function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r].call(i.exports,i,i.exports,n),i.exports}(620)})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ctod=t():e.ctod=t()}(this||("undefined"!=typeof window?window:global),(()=>(()=>{"use strict";var e={37:function(e,t,n){var r=this&&this.__assign||function(){return r=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var o in t=arguments[n])Object.prototype.hasOwnProperty.call(t,o)&&(e[o]=t[o]);return e},r.apply(this,arguments)},o=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},i=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},a=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a},u=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBroker=void 0;var s=n(15),c=n(470),l=n(87),f=function(){function e(e){var t;this.hook=new c.Hook,this.plugins={},this.installed=!1,this.log=new c.Log(null!==(t=e.name)&&void 0!==t?t:"no name"),this.params=e,this.translator=new l.Translator(r(r({},e),{parsers:[s.TextParser.JsonMessage()]}))}return e.prototype._install=function(){if(!1===this.installed){this.installed=!0;var e={log:this.log,attach:this.hook.attach.bind(this.hook),attachAfter:this.hook.attachAfter.bind(this.hook),translator:this.translator};if(this.params.install(e),this.params.plugins)for(var t in this.plugins="function"==typeof this.params.plugins?this.params.plugins():this.params.plugins,this.plugins)this.plugins[t].instance._params.onInstall(r(r({},e),{params:this.plugins[t].params,receive:this.plugins[t].receive}))}},e.prototype.request=function(e){return o(this,void 0,void 0,(function(){var t,n,r,s,l,f,p,h=this;return i(this,(function(d){switch(d.label){case 0:return this._install(),t=c.flow.createUuid(),n=null,r={},[4,this.translator.compile(e)];case 1:for(p in s=d.sent(),l=[{role:"user",content:s.prompt}],f=function(e){r[e]={send:function(n){return h.plugins[e].send({id:t,data:n})}}},this.plugins)f(p);return[4,this.hook.notify("start",{id:t,data:e,plugins:r,messages:l,setPreMessages:function(e){l=u(u([],a(e),!1),[{role:"user",content:s.prompt}],!1)},changeMessages:function(e){l=e}})];case 2:return d.sent(),[4,c.flow.asyncWhile((function(r){var a=r.count,u=r.doBreak;return o(h,void 0,void 0,(function(){var r,o,s,c,f,p;return i(this,(function(i){switch(i.label){case 0:if(a>=10)return[2,u()];r="",o="",s=!1,c=(null===(p=l.filter((function(e){return"user"===e.role})).slice(-1)[0])||void 0===p?void 0:p.content)||"",i.label=1;case 1:return i.trys.push([1,8,,15]),[4,this.hook.notify("talkBefore",{id:t,data:e,messages:l,lastUserMessage:c})];case 2:return i.sent(),[4,this.params.request(l,{count:a,isRetry:s})];case 3:return r=i.sent(),o=r,[4,this.hook.notify("talkAfter",{id:t,data:e,response:r,messages:l,parseText:o,lastUserMessage:c,changeParseText:function(e){o=e}})];case 4:return i.sent(),[4,this.translator.parse(o)];case 5:return n=i.sent().output,[4,this.hook.notify("succeeded",{id:t,output:n})];case 6:return i.sent(),[4,this.hook.notify("done",{id:t})];case 7:return i.sent(),u(),[3,15];case 8:return(f=i.sent()).isParserError?[4,this.hook.notify("parseFailed",{id:t,error:f.error,count:a,response:r,messages:l,lastUserMessage:c,parserFails:f.parserFails,retry:function(){s=!0},changeMessages:function(e){l=e}})]:[3,12];case 9:return i.sent(),!1!==s?[3,11]:[4,this.hook.notify("done",{id:t})];case 10:throw i.sent(),f;case 11:return[3,14];case 12:return[4,this.hook.notify("done",{id:t})];case 13:throw i.sent(),f;case 14:return[3,15];case 15:return[2]}}))}))}))];case 3:return d.sent(),[2,n]}}))}))},e}();t.ChatBroker=f},15:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TextParser=void 0;var a=i(n(959)),u=function(){function e(e){this.params=e}return e.JsonMessage=function(){var t=this;return new e({name:"JsonMessage",handler:function(e){return r(t,void 0,void 0,(function(){var t,n,r;return o(this,(function(o){try{return[2,JSON.parse(e)]}catch(o){return t=/{(?:[^{}]|(?:{[^{}]*}))*}/,n=(null===(r=e.match(t))||void 0===r?void 0:r[0])||"",[2,a.default.parse(n)]}return[2]}))}))}})},Object.defineProperty(e.prototype,"name",{get:function(){return this.params.name},enumerable:!1,configurable:!0}),e.prototype.read=function(e){return r(this,void 0,void 0,(function(){return o(this,(function(t){switch(t.label){case 0:return[4,this.params.handler(e)];case 1:return[2,t.sent()]}}))}))},e}();t.TextParser=u},241:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBrokerPlugin=void 0;var r=n(470),o=function(){function e(e){this._event=new r.Event,this._params=e}return e.prototype.use=function(e){var t=this;return{instance:this,params:e,send:function(e){t._event.emit("receive",e)},receive:function(e){t._event.on("receive",e)},__receiveData:null}},e}();t.ChatBrokerPlugin=o},87:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__values||function(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")};Object.defineProperty(t,"__esModule",{value:!0}),t.Translator=void 0;var a=n(293),u=function(){function e(e){this.params=e}return Object.defineProperty(e.prototype,"__schemeType",{get:function(){return null},enumerable:!1,configurable:!0}),Object.defineProperty(e.prototype,"__outputType",{get:function(){return null},enumerable:!1,configurable:!0}),e.prototype.compile=function(e){return r(this,void 0,void 0,(function(){var t,n;return o(this,(function(r){switch(r.label){case 0:return t=(0,a.validate)(e,this.params.input),[4,this.params.question(t)];case 1:return n=r.sent(),[2,{scheme:t,prompt:n}]}}))}))},e.prototype.parse=function(e){return r(this,void 0,void 0,(function(){var t,n,r,u,s,c,l,f,p,h;return o(this,(function(o){switch(o.label){case 0:t=void 0,n="",r=[],o.label=1;case 1:o.trys.push([1,8,9,10]),u=i(this.params.parsers),s=u.next(),o.label=2;case 2:if(s.done)return[3,7];c=s.value,o.label=3;case 3:return o.trys.push([3,5,,6]),[4,c.read(e)];case 4:return t=o.sent(),n=c.name,[3,6];case 5:return l=o.sent(),t=void 0,r.push({name:c.name,error:l}),[3,6];case 6:return s=u.next(),[3,2];case 7:return[3,10];case 8:return f=o.sent(),p={error:f},[3,10];case 9:try{s&&!s.done&&(h=u.return)&&h.call(u)}finally{if(p)throw p.error}return[7];case 10:try{return[2,{output:(0,a.validate)(t,this.params.output),parserName:n,parserFails:r}]}catch(e){throw{isParserError:!0,error:e,parserFails:r}}return[2]}}))}))},e}();t.Translator=u},620:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ctod=t.templates=t.plugins=t.ChatBrokerPlugin=t.ChatBroker=t.Translator=t.TextParser=t.OpenAI=void 0;var a=i(n(218)),u=i(n(298)),s=i(n(87)),c=n(616),l=n(15),f=n(37),p=n(241);t.OpenAI=c.OpenAI,t.TextParser=l.TextParser,t.Translator=s.Translator,t.ChatBroker=f.ChatBroker,t.ChatBrokerPlugin=p.ChatBrokerPlugin,t.plugins=a,t.templates=u,t.ctod={OpenAI:t.OpenAI,plugins:t.plugins,templates:t.templates,ChatBroker:t.ChatBroker,Translator:t.Translator,TextParser:t.TextParser,ChatBrokerPlugin:t.ChatBrokerPlugin},e.exports=t.ctod,e.exports.ctod=t.ctod,t.default=t.ctod},218:function(e,t,n){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RolePlugin=t.LimiterPluginGlobState=t.LimiterPlugin=t.RetryPlugin=t.PrintLogPlugin=void 0;var o=r(n(894)),i=r(n(829)),a=r(n(626)),u=r(n(1));t.PrintLogPlugin=i.default,t.RetryPlugin=o.default,t.LimiterPlugin=a.default.plugin,t.LimiterPluginGlobState=a.default,t.RolePlugin=u.default},626:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(241),a=n(470),u={limit:3,interval:6e4},s={event:new a.Event,schedule:null,waitTimes:[],waitQueue:[]};t.default={event:s.event,config:u,closeSchedule:function(){s.schedule&&(s.schedule.close(),s.schedule=null)},plugin:new i.ChatBrokerPlugin({name:"limiter",params:function(){return{}},receiveData:function(){return{}},onInstall:function(e){var t=this,n=e.attach;null==s.schedule&&(s.schedule=new a.Schedule,s.schedule.add("calc queue",1e3,(function(){return r(t,void 0,void 0,(function(){var e,t;return o(this,(function(n){return e=Date.now(),s.waitTimes=s.waitTimes.filter((function(t){return e-t<u.interval})),s.waitTimes.length!==u.limit?(t=s.waitQueue.shift())&&(s.waitTimes.push(Date.now()),s.event.emit("run",{id:t})):s.waitTimes[0]&&s.event.emit("waitTimeChange",{waitTime:Math.floor(60-(e-s.waitTimes[0])/1e3)}),[2]}))}))})),s.schedule.play()),n("talkBefore",(function(){return r(t,void 0,void 0,(function(){var e;return o(this,(function(t){return e=a.flow.createUuid(),s.waitQueue.push(e),[2,new Promise((function(t){s.event.on("run",(function(n,r){var o=n.id,i=r.off;o===e&&(i(),t())}))}))]}))}))}))}})}},829:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(241);t.default=new i.ChatBrokerPlugin({name:"print-log",params:function(e){return{detail:e.boolean().required().default(!1)}},receiveData:function(){return{}},onInstall:function(e){var t=this,n=e.params,i=e.log,a=e.attach;a("talkBefore",(function(e){var a=e.lastUserMessage,u=e.messages;return r(t,void 0,void 0,(function(){return o(this,(function(e){return i.print("Send:",{color:"green"}),n.detail?i.print("\n"+JSON.stringify(u,null,4)):i.print("\n"+a),[2]}))}))})),a("talkAfter",(function(e){var n=e.parseText;return r(t,void 0,void 0,(function(){return o(this,(function(e){return i.print("Receive:",{color:"cyan"}),i.print("\n"+n),[2]}))}))})),a("succeeded",(function(e){var n=e.output;return r(t,void 0,void 0,(function(){return o(this,(function(e){i.print("Output:",{color:"yellow"});try{i.print("\n"+JSON.stringify(n,null,4))}catch(e){i.print("\n"+n)}return[2]}))}))}))}})},894:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0});var i=n(241);t.default=new i.ChatBrokerPlugin({name:"retry",params:function(e){return{retry:e.number().required().default(1),printWarn:e.boolean().required().default(!0)}},receiveData:function(){return{}},onInstall:function(e){var t=this,n=e.log,i=e.attach,a=e.params;i("parseFailed",(function(e){var i=e.count,u=e.retry,s=e.messages,c=e.changeMessages;return r(t,void 0,void 0,(function(){return o(this,(function(e){return i<=a.retry&&(a.printWarn&&n.print("Is Failed, Retry ".concat(i," times.")),c(s),u()),[2]}))}))}))}})},1:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a},a=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0});var u=n(241);t.default=new u.ChatBrokerPlugin({name:"role",params:function(e){return{role:e.string().required()}},receiveData:function(){return{}},onInstall:function(e){var t=this,n=e.attach,u=e.params;n("start",(function(e){var n=e.messages,s=e.changeMessages;return r(t,void 0,void 0,(function(){return o(this,(function(e){return s(a([{role:"user",content:"你現在是".concat(u.role,"。")},{role:"assistant",content:"沒問題,我現在是".concat(u.role,",有什麼可以幫你的嗎?")}],i(n),!1)),[2]}))}))}))}})},203:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a},a=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIChat=void 0;var u=n(470),s=function(){function e(e){this.config={n:1,model:"gpt-3.5-turbo",temperature:1,maxTokens:void 0,forceJsonFormat:!0},this.openai=e}return e.prototype.setConfig=function(e){Object.assign(this.config,e)},e.prototype.moderations=function(e){var t,n;return r(this,void 0,void 0,(function(){var r;return o(this,(function(o){switch(o.label){case 0:return[4,this.openai._axios.post("https://api.openai.com/v1/moderations",{input:e},{headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.openai._apiKey)}})];case 1:return r=o.sent(),[2,{isSafe:!1===(null===(n=null===(t=r.data.results)||void 0===t?void 0:t[0])||void 0===n?void 0:n.flagged),result:r.data}]}}))}))},e.prototype.talk=function(e){var t,n;return void 0===e&&(e=[]),r(this,void 0,void 0,(function(){var r,i,a,s,c;return o(this,(function(o){switch(o.label){case 0:return r=u.json.jpjs(e),i=["gpt-4-1106-preview","gpt-3.5-turbo-1106"].includes(this.config.model),[4,this.openai._axios.post("https://api.openai.com/v1/chat/completions",{model:this.config.model,n:this.config.n,messages:r,response_format:!1===i||!1===this.config.forceJsonFormat?void 0:{type:"json_object"},temperature:this.config.temperature},{headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.openai._apiKey)}})];case 1:return a=o.sent(),s=a.data.choices||[],c=(null===(t=s[0])||void 0===t?void 0:t.message)||{role:"assistant",content:""},r.push(c),[2,{id:null==a?void 0:a.data.id,text:c.content,newMessages:r,isDone:"stop"===(null===(n=s[0])||void 0===n?void 0:n.finish_reason),apiReseponse:a.data}]}}))}))},e.prototype.keepTalk=function(e,t){return void 0===t&&(t=[]),r(this,void 0,void 0,(function(){var n,r=this;return o(this,(function(o){switch(o.label){case 0:return[4,this.talk(a(a([],i(t),!1),[{role:"user",content:Array.isArray(e)?e.join("\n"):e}],!1))];case 1:return[2,{result:n=o.sent(),nextTalk:function(e){return r.keepTalk(e,n.newMessages)}}]}}))}))},e}();t.OpenAIChat=s},919:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAICompletion=void 0;var o=function(){function e(e){this.config={n:1,maxTokens:2048,temperature:1},this.openai=e}return e.prototype.setConfig=function(e){Object.assign(this.config,e)},e.prototype.run=function(e){var t,o;return n(this,void 0,void 0,(function(){var n,i;return r(this,(function(r){switch(r.label){case 0:return[4,this.openai._axios.post("https://api.openai.com/v1/completions",{model:"text-davinci-003",n:this.config.n,prompt:Array.isArray(e)?e.join("\n"):e,max_tokens:this.config.maxTokens,temperature:this.config.temperature},{headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.openai._apiKey)}})];case 1:return n=r.sent(),i=n.data.choices||[],[2,{id:n.data.id,text:(null===(t=i[0])||void 0===t?void 0:t.text)||"",isDone:"stop"===(null===(o=i[0])||void 0===o?void 0:o.finish_reason),apiReseponse:n.data}]}}))}))},e}();t.OpenAICompletion=o},725:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIImagesGeneration=void 0;var o=function(){function e(e){this.config={model:"dall-e-2",size:"1024x1024"},this.openai=e}return e.prototype.setConfig=function(e){Object.assign(this.config,e)},e.prototype.create=function(e){return n(this,void 0,void 0,(function(){return r(this,(function(t){switch(t.label){case 0:return[4,this.openai._axios.post("https://api.openai.com/v1/images/generations",{prompt:e,n:1,size:this.config.size,model:this.config.model,response_format:"b64_json"},{timeout:3e5,headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.openai._apiKey)}})];case 1:return[2,t.sent().data]}}))}))},e}();t.OpenAIImagesGeneration=o},616:function(e,t,n){var r=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},o=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAI=void 0;var a=n(710),u=n(919),s=n(203),c=n(725),l=i(n(167)),f=function(){function e(e){void 0===e&&(e=""),this._axios=l.default.create(),this._apiKey="",this._apiKey=e}return e.createChatRequest=function(t,n){var i=this;return void 0===n&&(n={}),function(a){return r(i,void 0,void 0,(function(){var r,i;return o(this,(function(o){switch(o.label){case 0:return r=new e(t),(i=r.createChat()).setConfig(n),[4,i.talk(a)];case 1:return[2,o.sent().text]}}))}))}},e.prototype.setAxios=function(e){this._axios=e},e.prototype.setConfiguration=function(e){this._apiKey=e},e.prototype.createChat=function(){return new s.OpenAIChat(this)},e.prototype.createVision=function(){return new a.OpenAIVision(this)},e.prototype.createCompletion=function(){return new u.OpenAICompletion(this)},e.prototype.createImagesGeneration=function(){return new c.OpenAIImagesGeneration(this)},e}();t.OpenAI=f},710:function(e,t){var n=this&&this.__awaiter||function(e,t,n,r){return new(n||(n=Promise))((function(o,i){function a(e){try{s(r.next(e))}catch(e){i(e)}}function u(e){try{s(r.throw(e))}catch(e){i(e)}}function s(e){var t;e.done?o(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(a,u)}s((r=r.apply(e,t||[])).next())}))},r=this&&this.__generator||function(e,t){var n,r,o,i,a={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function u(i){return function(u){return function(i){if(n)throw new TypeError("Generator is already executing.");for(;a;)try{if(n=1,r&&(o=2&i[0]?r.return:i[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,i[1])).done)return o;switch(r=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return a.label++,{value:i[1],done:!1};case 5:a.label++,r=i[1],i=[0];continue;case 7:i=a.ops.pop(),a.trys.pop();continue;default:if(!((o=(o=a.trys).length>0&&o[o.length-1])||6!==i[0]&&2!==i[0])){a=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){a.label=i[1];break}if(6===i[0]&&a.label<o[1]){a.label=o[1],o=i;break}if(o&&a.label<o[2]){a.label=o[2],a.ops.push(i);break}o[2]&&a.ops.pop(),a.trys.pop();continue}i=t.call(e,a)}catch(e){i=[6,e],r=0}finally{n=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,u])}}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIVision=void 0;var o=function(){function e(e){this.config={model:"gpt-4-vision-preview",maxTokens:void 0,temperature:1},this.openai=e}return e.prototype.setConfig=function(e){Object.assign(this.config,e)},e.prototype.view=function(e){var t;return n(this,void 0,void 0,(function(){var n,o,i;return r(this,(function(r){switch(r.label){case 0:return[4,this.openai._axios.post("https://api.openai.com/v1/chat/completions",{model:this.config.model,n:1,messages:e,max_tokens:this.config.maxTokens,temperature:this.config.temperature},{headers:{"Content-Type":"application/json",Authorization:"Bearer ".concat(this.openai._apiKey)}})];case 1:return n=r.sent(),o=n.data.choices||[],i=(null===(t=o[0])||void 0===t?void 0:t.message)||{role:"assistant",content:""},[2,{id:null==n?void 0:n.data.id,text:i.content,apiReseponse:n.data}]}}))}))},e}();t.OpenAIVision=o},298:function(e,t,n){var r=this&&this.__read||function(e,t){var n="function"==typeof Symbol&&e[Symbol.iterator];if(!n)return e;var r,o,i=n.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(e){o={error:e}}finally{try{r&&!r.done&&(n=i.return)&&n.call(i)}finally{if(o)throw o.error}}return a},o=this&&this.__spreadArray||function(e,t,n){if(n||2===arguments.length)for(var r,o=0,i=t.length;o<i;o++)!r&&o in t||(r||(r=Array.prototype.slice.call(t,0,o)),r[o]=t[o]);return e.concat(r||Array.prototype.slice.call(t))},i=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.requireJsonResponseWithHandlebars=t.requireJsonResponse=void 0;var a=i(n(97)),u=n(470);t.requireJsonResponse=function(e,t){return o(o([],r(Array.isArray(e)?e:[e]),!1),["Please respond using the following JSON format and minify the JSON without including any explanation: ","{",Object.entries(t).map((function(e){var t=r(e,2),n=t[0],o=t[1];return["/* ".concat(o.desc," */"),'"'.concat(n,'": ').concat(JSON.stringify(o.example))].join("\n")})).join(",\n"),"}"],!1).join("\n")},t.requireJsonResponseWithHandlebars=function(e,n,r){var o=a.default.create();return o.registerHelper("DATA",(function(e){return JSON.stringify(e)})),o.registerHelper("ENV",(function(e){return this.__envs&&e?this.__envs[e]:""})),o.registerHelper("INPUT",(function(){return JSON.stringify(u.record.omit(this,["__envs"]))})),o.registerHelper("JOIN",(function(e){return Array.isArray(e)?e.join():JSON.stringify(e)})),o.compile((0,t.requireJsonResponse)(n,r))(e)}},293:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var o=Object.getOwnPropertyDescriptor(t,n);o&&!("get"in o?!t.__esModule:o.writable||o.configurable)||(o={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,o)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),i=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var n in e)"default"!==n&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return o(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.validate=t.definedValidateSchema=void 0;var a=i(n(609));t.definedValidateSchema=function(e){return e},t.validate=function(e,t){return a.object(t(a)).required().validateSync(e||{})}},167:e=>{e.exports=require("axios")},97:e=>{e.exports=require("handlebars")},959:e=>{e.exports=require("json5")},470:e=>{e.exports=require("power-helper")},609:e=>{e.exports=require("yup")}},t={};return function n(r){var o=t[r];if(void 0!==o)return o.exports;var i=t[r]={exports:{}};return e[r].call(i.exports,i,i.exports,n),i.exports}(620)})()));
Binary file
Binary file
@@ -0,0 +1,165 @@
1
+ import fs from 'fs'
2
+ import Yup from 'yup'
3
+ import { flow } from 'power-helper'
4
+ import { prompt } from 'inquirer'
5
+ import { OpenAI, ChatBroker, plugins, templates } from '../lib'
6
+
7
+ /**
8
+ * @invoke npx ts-node ./examples/vision-demo.ts
9
+ */
10
+
11
+ const API_KEY = ''
12
+ const ImageUrl = 'data:image/png;base64,' + fs.readFileSync('./examples/vision-demo.png').toString('base64')
13
+ const ImageExUrl = 'data:image/png;base64,' + fs.readFileSync('./examples/vision-demo-ex.png').toString('base64')
14
+
15
+ flow.run(async () => {
16
+ const drinkRule = (yup: typeof Yup) => {
17
+ return yup.object({
18
+ name: yup.string().required(),
19
+ prices: yup.object({
20
+ M: yup.number().nullable(),
21
+ L: yup.number().nullable()
22
+ })
23
+ })
24
+ }
25
+ const broker = new ChatBroker({
26
+ input: yup => {
27
+ return {
28
+ exists: yup.array(drinkRule(yup)).required()
29
+ }
30
+ },
31
+ output: yup => {
32
+ return {
33
+ drinks: yup.array(drinkRule(yup)).required()
34
+ }
35
+ },
36
+ plugins: {
37
+ print: plugins.PrintLogPlugin.use({
38
+ detail: false
39
+ })
40
+ },
41
+ install: () => {
42
+ return null
43
+ },
44
+ request: async(messages) => {
45
+ const openai = new OpenAI(API_KEY)
46
+ const vision = openai.createVision()
47
+ vision.setConfig({
48
+ maxTokens: 4096
49
+ })
50
+ const result = await vision.view([
51
+ {
52
+ role: 'system',
53
+ content: '你現在是一個分析菜單的助手,你擅長從圖片中找到商品名稱與價格並歸納'
54
+ },
55
+ {
56
+ role: 'user',
57
+ content: [
58
+ {
59
+ type: 'text',
60
+ text: '以下是菜單的一部分,我主要需要藍色文字的商品部分,這部分你可以解讀出什麼?'
61
+ },
62
+ {
63
+ type: 'image_url',
64
+ image_url: {
65
+ url: ImageExUrl
66
+ }
67
+ }
68
+ ]
69
+ },
70
+ {
71
+ role: 'assistant',
72
+ content: '我從圖片中知道熟成紅茶 中杯25元 大杯30元'
73
+ },
74
+ {
75
+ role: 'user',
76
+ content: [
77
+ {
78
+ type: 'text',
79
+ text: messages[0].content
80
+ },
81
+ {
82
+ type: 'image_url',
83
+ image_url: {
84
+ url: ImageUrl
85
+ }
86
+ }
87
+ ]
88
+ }
89
+ ])
90
+ return result.text
91
+ },
92
+ question: async ({ exists }) => {
93
+ const ex = exists.map(e => {
94
+ const prices = Object
95
+ .entries(e.prices)
96
+ .filter(e => e[1])
97
+ .map(([key, value]) => `${key}:${value}`)
98
+ return `* ${e.name}: ${prices.join('/')}`
99
+ })
100
+ return templates.requireJsonResponse([
101
+ '你的解讀完全正確,現在請幫我條列出菜單上所有商品,這個菜單中已知以下資料,你解讀的結果如果沒有以下資料代表你的解讀不對:',
102
+ '"""',
103
+ ...ex,
104
+ '"""'
105
+ ], {
106
+ drinks: {
107
+ desc: '商品清單,不要回傳已知商品',
108
+ example: [
109
+ {
110
+ name: '熟成紅茶',
111
+ prices: {
112
+ M: 25,
113
+ L: 30
114
+ }
115
+ }
116
+ ]
117
+ }
118
+ })
119
+ }
120
+ })
121
+ try {
122
+ const exists = [
123
+ {
124
+ name: '熟成紅茶',
125
+ prices: {
126
+ M: 25,
127
+ L: 30
128
+ }
129
+ }
130
+ ] as any[]
131
+ // eslint-disable-next-line no-constant-condition
132
+ while (true) {
133
+ const result = await broker.request({
134
+ exists
135
+ })
136
+ const keys: string[] = exists.map(e => e.name)
137
+ const { drinks } = await prompt([
138
+ {
139
+ type: 'checkbox',
140
+ name: 'drinks',
141
+ message: '請選擇正確的飲料',
142
+ choices: result.drinks.filter(e => !keys.includes(e.name)).map(e => {
143
+ return {
144
+ name: `${e.name} ${Object.entries(e.prices).map(([key, value]) => `${key}:${value}`).join(' ')}`,
145
+ value: e
146
+ }
147
+ })
148
+ },
149
+ ])
150
+ exists.push(...drinks)
151
+ const { keep } = await prompt([
152
+ {
153
+ type: 'confirm',
154
+ name: 'keep',
155
+ message: '是否繼續?'
156
+ }
157
+ ])
158
+ if (keep === false) {
159
+ break
160
+ }
161
+ }
162
+ } catch (error: any) {
163
+ console.error('Error:', error?.response?.data?.error?.message ?? error)
164
+ }
165
+ })
@@ -99,6 +99,11 @@ export type ChatBrokerHooks<
99
99
  }
100
100
  }
101
101
 
102
+ type RequestContext = {
103
+ count: number
104
+ isRetry: boolean
105
+ }
106
+
102
107
  export type Params<
103
108
  S extends ValidateCallback<any>,
104
109
  O extends ValidateCallback<any>,
@@ -108,7 +113,7 @@ export type Params<
108
113
  > = Omit<TranslatorParams<S, O>, 'parsers'> & {
109
114
  name?: string
110
115
  plugins?: PS | (() => PS)
111
- request: (messages: Message[]) => Promise<string>
116
+ request: (messages: Message[], context: RequestContext) => Promise<string>
112
117
  install: (context: {
113
118
  log: Log
114
119
  attach: Hook<C>['attach']
@@ -224,7 +229,10 @@ export class ChatBroker<
224
229
  messages,
225
230
  lastUserMessage
226
231
  })
227
- response = await this.params.request(messages)
232
+ response = await this.params.request(messages, {
233
+ count,
234
+ isRetry: retryFlag
235
+ })
228
236
  parseText = response
229
237
  await this.hook.notify('talkAfter', {
230
238
  id,
@@ -25,9 +25,14 @@ export class TextParser {
25
25
  return new TextParser({
26
26
  name: 'JsonMessage',
27
27
  handler: async (text) => {
28
- const jsonRegex = /{(?:[^{}]|(?:{[^{}]*}))*}/
29
- const matchedText = text.match(jsonRegex)?.[0] || ''
30
- return JSON5.parse(matchedText)
28
+ try {
29
+ const result = JSON.parse(text)
30
+ return result
31
+ } catch (error) {
32
+ const jsonRegex = /{(?:[^{}]|(?:{[^{}]*}))*}/
33
+ const matchedText = text.match(jsonRegex)?.[0] || ''
34
+ return JSON5.parse(matchedText)
35
+ }
31
36
  }
32
37
  })
33
38
  }
@@ -59,7 +59,7 @@ export class Translator<
59
59
  }
60
60
 
61
61
  /**
62
- * @zh 將文字轉換成序列化資量。
62
+ * @zh 將文字轉換成序列化資料。
63
63
  * @en Convert text to serialized data.
64
64
  */
65
65
 
@@ -12,12 +12,12 @@ export default new ChatBrokerPlugin({
12
12
  return {}
13
13
  },
14
14
  onInstall({ log, attach, params }) {
15
- attach('parseFailed', async({ count, retry, response, changeMessages }) => {
15
+ attach('parseFailed', async({ count, retry, messages, changeMessages }) => {
16
16
  if (count <= params.retry) {
17
17
  if (params.printWarn) {
18
18
  log.print(`Is Failed, Retry ${count} times.`)
19
19
  }
20
- changeMessages(response.newMessages.slice(0, -1))
20
+ changeMessages(messages)
21
21
  retry()
22
22
  }
23
23
  })
@@ -49,6 +49,11 @@ export type Config = {
49
49
  * @en Whether to force the return of JSON format data
50
50
  */
51
51
  forceJsonFormat: boolean
52
+ /**
53
+ * @zh 每次對話最多產生幾個 tokens。
54
+ * @en How many tokens to complete to.
55
+ */
56
+ maxTokens?: number
52
57
  }
53
58
 
54
59
  export class OpenAIChat {
@@ -57,6 +62,7 @@ export class OpenAIChat {
57
62
  n: 1,
58
63
  model: 'gpt-3.5-turbo',
59
64
  temperature: 1,
65
+ maxTokens: undefined,
60
66
  forceJsonFormat: true
61
67
  }
62
68
 
@@ -73,6 +79,26 @@ export class OpenAIChat {
73
79
  Object.assign(this.config, options)
74
80
  }
75
81
 
82
+ /**
83
+ * @zh 檢視內容是否符合 OpenAI 的審查
84
+ * @en View content for OpenAI moderation
85
+ */
86
+
87
+ async moderations(input: string) {
88
+ const result = await this.openai._axios.post<any>('https://api.openai.com/v1/moderations', {
89
+ input: input
90
+ }, {
91
+ headers: {
92
+ 'Content-Type': 'application/json',
93
+ 'Authorization': `Bearer ${this.openai._apiKey}`
94
+ }
95
+ })
96
+ return {
97
+ isSafe: result.data.results?.[0]?.flagged === false,
98
+ result: result.data
99
+ }
100
+ }
101
+
76
102
  /**
77
103
  * @zh 進行對話
78
104
  * @en Talk to the AI
@@ -9,10 +9,10 @@ type ApiResponse = {
9
9
 
10
10
  type Config = {
11
11
  /**
12
- * @zh 一次圖片回應數量
13
- * @en Number of image responses at a time
12
+ * @zh 模型,支援 dall-e-2 和 dall-e-3
13
+ * @en Model, support dall-e-2 and dall-e-3
14
14
  */
15
- n: number
15
+ model: 'dall-e-2' | 'dall-e-3'
16
16
  /**
17
17
  * @zh 解析度,例如 1024x1024
18
18
  * @en Resolution, for example 1024x1024
@@ -23,7 +23,7 @@ type Config = {
23
23
  export class OpenAIImagesGeneration {
24
24
  private openai: OpenAI
25
25
  private config: Config = {
26
- n: 1,
26
+ model: 'dall-e-2',
27
27
  size: '1024x1024'
28
28
  }
29
29
 
@@ -48,8 +48,9 @@ export class OpenAIImagesGeneration {
48
48
  async create(prompt: string) {
49
49
  const result = await this.openai._axios.post<ApiResponse>('https://api.openai.com/v1/images/generations', {
50
50
  prompt,
51
- n: this.config.n,
51
+ n: 1,
52
52
  size: this.config.size,
53
+ model: this.config.model,
53
54
  response_format: 'b64_json'
54
55
  }, {
55
56
  timeout: 1000 * 60 * 5,
@@ -1,5 +1,6 @@
1
- import { OpenAIChat, Config } from './chat'
1
+ import { OpenAIVision } from './vision'
2
2
  import { OpenAICompletion } from './completion'
3
+ import { OpenAIChat, Config } from './chat'
3
4
  import { OpenAIImagesGeneration } from './images-generation'
4
5
  import axios, { AxiosInstance } from 'axios'
5
6
 
@@ -43,6 +44,10 @@ export class OpenAI {
43
44
  return new OpenAIChat(this)
44
45
  }
45
46
 
47
+ createVision() {
48
+ return new OpenAIVision(this)
49
+ }
50
+
46
51
  createCompletion() {
47
52
  return new OpenAICompletion(this)
48
53
  }
@@ -0,0 +1,111 @@
1
+ import { OpenAI } from './index'
2
+ import { PromiseResponseType } from '../../types'
3
+
4
+ type ImageContent = {
5
+ type: 'image_url' | 'text'
6
+ text?: string
7
+ image_url?: {
8
+ url: string
9
+ detail?: string
10
+ }
11
+ }
12
+
13
+ type VisionMessage = {
14
+ role: 'system' | 'user' | 'assistant'
15
+ name?: string
16
+ content: string | ImageContent[]
17
+ }
18
+
19
+ type ApiResponse = {
20
+ id: string
21
+ object: string
22
+ created: number
23
+ model: string
24
+ usage: {
25
+ prompt_tokens: number
26
+ completion_tokens: number
27
+ total_tokens: number
28
+ }
29
+ choices: Array<{
30
+ message: {
31
+ role: string
32
+ content: string
33
+ }
34
+ finish_details: {
35
+ type: string
36
+ }
37
+ index: number
38
+ }>
39
+ }
40
+
41
+ export type Config = {
42
+ /**
43
+ * @zh 選擇運行的模型。
44
+ * @en How many chat completion choices to generate for each input message.
45
+ */
46
+ model: 'gpt-4-vision-preview'
47
+ /**
48
+ * @zh 冒險指數,數值由 0 ~ 2 之間。
49
+ * @en What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
50
+ */
51
+ temperature: number
52
+ /**
53
+ * @zh 每次對話最多產生幾個 tokens。
54
+ * @en How many tokens to complete to.
55
+ */
56
+ maxTokens?: number
57
+ }
58
+
59
+ export class OpenAIVision {
60
+ openai: OpenAI
61
+ config: Config = {
62
+ model: 'gpt-4-vision-preview',
63
+ maxTokens: undefined,
64
+ temperature: 1
65
+ }
66
+
67
+ constructor(openai: OpenAI) {
68
+ this.openai = openai
69
+ }
70
+
71
+ /**
72
+ * @zh 改變對話的一些設定
73
+ * @en Change some settings of the conversation
74
+ */
75
+
76
+ setConfig(options: Partial<Config>) {
77
+ Object.assign(this.config, options)
78
+ }
79
+
80
+ /**
81
+ * @zh 辨識圖片
82
+ * @en Recognize images
83
+ */
84
+
85
+ async view(messages: VisionMessage[]) {
86
+ const result = await this.openai._axios.post<ApiResponse>('https://api.openai.com/v1/chat/completions', {
87
+ model: this.config.model,
88
+ n: 1,
89
+ messages,
90
+ max_tokens: this.config.maxTokens,
91
+ temperature: this.config.temperature
92
+ }, {
93
+ headers: {
94
+ 'Content-Type': 'application/json',
95
+ 'Authorization': `Bearer ${this.openai._apiKey}`
96
+ }
97
+ })
98
+ const choices = result.data.choices || []
99
+ const message = choices[0]?.message || {
100
+ role: 'assistant',
101
+ content: ''
102
+ }
103
+ return {
104
+ id: result?.data.id as string,
105
+ text: message.content as string,
106
+ apiReseponse: result.data
107
+ }
108
+ }
109
+ }
110
+
111
+ export type OpenAIChatVisionResponse = PromiseResponseType<OpenAIVision['view']>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ctod",
3
- "version": "0.3.2",
3
+ "version": "0.3.4",
4
4
  "description": "CtoD Is Chat To Data Utils.",
5
5
  "main": "./dist/index.js",
6
6
  "scripts": {
@@ -57,7 +57,7 @@
57
57
  "axios": "^1.4.0",
58
58
  "handlebars": "^4.7.7",
59
59
  "json5": "^2.2.3",
60
- "power-helper": "^0.6.0",
60
+ "power-helper": "^0.6.5",
61
61
  "yup": "^1.1.1"
62
62
  }
63
63
  }
@@ -81,10 +81,14 @@ export declare type ChatBrokerHooks<S extends ValidateCallback<any>, O extends V
81
81
  id: string;
82
82
  };
83
83
  };
84
+ declare type RequestContext = {
85
+ count: number;
86
+ isRetry: boolean;
87
+ };
84
88
  export declare type Params<S extends ValidateCallback<any>, O extends ValidateCallback<any>, C extends Record<string, any>, P extends ChatBrokerPlugin<any, any>, PS extends Record<string, ReturnType<P['use']>>> = Omit<TranslatorParams<S, O>, 'parsers'> & {
85
89
  name?: string;
86
90
  plugins?: PS | (() => PS);
87
- request: (messages: Message[]) => Promise<string>;
91
+ request: (messages: Message[], context: RequestContext) => Promise<string>;
88
92
  install: (context: {
89
93
  log: Log;
90
94
  attach: Hook<C>['attach'];
@@ -38,7 +38,7 @@ export declare class Translator<S extends ValidateCallback<any>, O extends Valid
38
38
  prompt: string;
39
39
  }>;
40
40
  /**
41
- * @zh 將文字轉換成序列化資量。
41
+ * @zh 將文字轉換成序列化資料。
42
42
  * @en Convert text to serialized data.
43
43
  */
44
44
  parse(text: string): Promise<{
@@ -45,6 +45,11 @@ export declare type Config = {
45
45
  * @en Whether to force the return of JSON format data
46
46
  */
47
47
  forceJsonFormat: boolean;
48
+ /**
49
+ * @zh 每次對話最多產生幾個 tokens。
50
+ * @en How many tokens to complete to.
51
+ */
52
+ maxTokens?: number;
48
53
  };
49
54
  export declare class OpenAIChat {
50
55
  openai: OpenAI;
@@ -55,6 +60,14 @@ export declare class OpenAIChat {
55
60
  * @en Change some settings of the conversation
56
61
  */
57
62
  setConfig(options: Partial<Config>): void;
63
+ /**
64
+ * @zh 檢視內容是否符合 OpenAI 的審查
65
+ * @en View content for OpenAI moderation
66
+ */
67
+ moderations(input: string): Promise<{
68
+ isSafe: boolean;
69
+ result: any;
70
+ }>;
58
71
  /**
59
72
  * @zh 進行對話
60
73
  * @en Talk to the AI
@@ -7,10 +7,10 @@ declare type ApiResponse = {
7
7
  };
8
8
  declare type Config = {
9
9
  /**
10
- * @zh 一次圖片回應數量
11
- * @en Number of image responses at a time
10
+ * @zh 模型,支援 dall-e-2 和 dall-e-3
11
+ * @en Model, support dall-e-2 and dall-e-3
12
12
  */
13
- n: number;
13
+ model: 'dall-e-2' | 'dall-e-3';
14
14
  /**
15
15
  * @zh 解析度,例如 1024x1024
16
16
  * @en Resolution, for example 1024x1024
@@ -1,5 +1,6 @@
1
- import { OpenAIChat, Config } from './chat';
1
+ import { OpenAIVision } from './vision';
2
2
  import { OpenAICompletion } from './completion';
3
+ import { OpenAIChat, Config } from './chat';
3
4
  import { OpenAIImagesGeneration } from './images-generation';
4
5
  import { AxiosInstance } from 'axios';
5
6
  export declare class OpenAI {
@@ -18,6 +19,7 @@ export declare class OpenAI {
18
19
  */
19
20
  setConfiguration(apiKey: string): void;
20
21
  createChat(): OpenAIChat;
22
+ createVision(): OpenAIVision;
21
23
  createCompletion(): OpenAICompletion;
22
24
  createImagesGeneration(): OpenAIImagesGeneration;
23
25
  }
@@ -0,0 +1,74 @@
1
+ import { OpenAI } from './index';
2
+ import { PromiseResponseType } from '../../types';
3
+ declare type ImageContent = {
4
+ type: 'image_url' | 'text';
5
+ text?: string;
6
+ image_url?: {
7
+ url: string;
8
+ detail?: string;
9
+ };
10
+ };
11
+ declare type VisionMessage = {
12
+ role: 'system' | 'user' | 'assistant';
13
+ name?: string;
14
+ content: string | ImageContent[];
15
+ };
16
+ declare type ApiResponse = {
17
+ id: string;
18
+ object: string;
19
+ created: number;
20
+ model: string;
21
+ usage: {
22
+ prompt_tokens: number;
23
+ completion_tokens: number;
24
+ total_tokens: number;
25
+ };
26
+ choices: Array<{
27
+ message: {
28
+ role: string;
29
+ content: string;
30
+ };
31
+ finish_details: {
32
+ type: string;
33
+ };
34
+ index: number;
35
+ }>;
36
+ };
37
+ export declare type Config = {
38
+ /**
39
+ * @zh 選擇運行的模型。
40
+ * @en How many chat completion choices to generate for each input message.
41
+ */
42
+ model: 'gpt-4-vision-preview';
43
+ /**
44
+ * @zh 冒險指數,數值由 0 ~ 2 之間。
45
+ * @en What sampling temperature to use, between 0 and 2. Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic.
46
+ */
47
+ temperature: number;
48
+ /**
49
+ * @zh 每次對話最多產生幾個 tokens。
50
+ * @en How many tokens to complete to.
51
+ */
52
+ maxTokens?: number;
53
+ };
54
+ export declare class OpenAIVision {
55
+ openai: OpenAI;
56
+ config: Config;
57
+ constructor(openai: OpenAI);
58
+ /**
59
+ * @zh 改變對話的一些設定
60
+ * @en Change some settings of the conversation
61
+ */
62
+ setConfig(options: Partial<Config>): void;
63
+ /**
64
+ * @zh 辨識圖片
65
+ * @en Recognize images
66
+ */
67
+ view(messages: VisionMessage[]): Promise<{
68
+ id: string;
69
+ text: string;
70
+ apiReseponse: ApiResponse;
71
+ }>;
72
+ }
73
+ export declare type OpenAIChatVisionResponse = PromiseResponseType<OpenAIVision['view']>;
74
+ export {};