ctod 0.6.3 → 0.7.1
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/.api-key +1 -0
- package/.nyc_output/42919e68-b472-4a5d-b2d3-5d5153f28467.json +1 -0
- package/.nyc_output/processinfo/42919e68-b472-4a5d-b2d3-5d5153f28467.json +1 -0
- package/.nyc_output/processinfo/index.json +1 -0
- package/.output/.output/stores//344/270/200/345/240/264/346/234/237/345/276/205/345/267/262/344/271/205/347/232/204/345/222/214/350/247/243/cover-0.png +1 -0
- package/.output/.output/stores//344/270/200/345/240/264/346/234/237/345/276/205/345/267/262/344/271/205/347/232/204/345/222/214/350/247/243/cover-1.png +1 -0
- package/.output/.output/stores//344/270/200/345/240/264/346/234/237/345/276/205/345/267/262/344/271/205/347/232/204/345/222/214/350/247/243/story-config.json +4 -0
- package/.output/.output/stores//344/270/200/345/240/264/346/234/237/345/276/205/345/267/262/344/271/205/347/232/204/345/222/214/350/247/243/story.json +22 -0
- package/.output/.output/stores//345/276/236/351/273/221/346/232/227/350/265/260/345/220/221/345/205/211/346/230/216/cover-0.png +1 -0
- package/.output/.output/stores//345/276/236/351/273/221/346/232/227/350/265/260/345/220/221/345/205/211/346/230/216/cover-1.png +1 -0
- package/.output/.output/stores//345/276/236/351/273/221/346/232/227/350/265/260/345/220/221/345/205/211/346/230/216/story-config.json +4 -0
- package/.output/.output/stores//345/276/236/351/273/221/346/232/227/350/265/260/345/220/221/345/205/211/346/230/216/story.json +24 -0
- package/.output/.output/stores//347/240/264/347/242/216/347/232/204/345/271/273/350/261/241/cover-0.png +1 -0
- package/.output/.output/stores//347/240/264/347/242/216/347/232/204/345/271/273/350/261/241/cover-1.png +1 -0
- package/.output/.output/stores//347/240/264/347/242/216/347/232/204/345/271/273/350/261/241/story-config.json +4 -0
- package/.output/.output/stores//347/240/264/347/242/216/347/232/204/345/271/273/350/261/241/story.json +24 -0
- package/.output/.output/stores//350/227/235/350/241/223/345/256/266/347/232/204/351/235/210/346/204/237/cover-0.png +1 -0
- package/.output/.output/stores//350/227/235/350/241/223/345/256/266/347/232/204/351/235/210/346/204/237/cover-1.png +1 -0
- package/.output/.output/stores//350/227/235/350/241/223/345/256/266/347/232/204/351/235/210/346/204/237/story-config.json +4 -0
- package/.output/.output/stores//350/227/235/350/241/223/345/256/266/347/232/204/351/235/210/346/204/237/story.json +28 -0
- package/.output/.output/stores//350/250/230/346/206/266/345/225/206/344/272/272/cover-0.png +1 -0
- package/.output/.output/stores//350/250/230/346/206/266/345/225/206/344/272/272/cover-1.png +1 -0
- package/.output/.output/stores//350/250/230/346/206/266/345/225/206/344/272/272/story-config.json +4 -0
- package/.output/.output/stores//350/250/230/346/206/266/345/225/206/344/272/272/story.json +18 -0
- package/.output/.output/stores//350/250/255/350/250/210/350/210/207/351/226/213/347/231/274/347/232/204/346/214/221/346/210/260/content.json +22 -0
- package/.output/.output/talks//344/273/245/347/254/221/350/251/261/347/202/272/345/237/272/347/244/216/347/232/204/351/235/242/350/251/246/content.json +30 -0
- package/.output/.output/talks//344/273/245/347/254/221/350/251/261/347/202/272/345/237/272/347/244/216/347/232/204/351/235/242/350/251/246/cover-1684055229695.png +0 -0
- package/.output/.output/talks//345/234/250/346/224/277/346/262/273/345/200/231/351/201/270/344/272/272/350/276/257/350/253/226/344/270/255/347/232/204/350/252/252/346/234/215/346/200/247/346/272/235/351/200/232/content.json +30 -0
- package/.output/.output/talks//345/234/250/346/224/277/346/262/273/345/200/231/351/201/270/344/272/272/350/276/257/350/253/226/344/270/255/347/232/204/350/252/252/346/234/215/346/200/247/346/272/235/351/200/232/cover-1684056611678.png +0 -0
- package/.output/.output/talks//346/224/276/351/254/206/347/232/204/345/200/231/351/201/270/344/272/272/351/200/262/350/241/214/346/224/277/346/262/273/350/276/257/350/253/226/content.json +36 -0
- package/.output/.output/talks//346/224/276/351/254/206/347/232/204/345/200/231/351/201/270/344/272/272/351/200/262/350/241/214/346/224/277/346/262/273/350/276/257/350/253/226/cover-1684055140609.png +0 -0
- package/.output/.output/talks//346/224/277/346/262/273/347/254/221/350/251/261/content.json +30 -0
- package/.output/.output/talks//346/224/277/346/262/273/347/254/221/350/251/261/cover-1684056246465.png +0 -0
- package/.output/.output/talks//350/251/274/350/253/247/345/256/266/351/225/267/346/225/231/345/270/253/346/234/203/350/255/260/content.json +26 -0
- package/.output/.output/talks//350/251/274/350/253/247/345/256/266/351/225/267/346/225/231/345/270/253/346/234/203/350/255/260/cover-1685785935121.png +0 -0
- package/.output/.output/talks//350/262/241/345/213/231/351/241/247/345/225/217/350/253/256/350/251/242/content.json +26 -0
- package/.output/.output/talks//350/262/241/345/213/231/351/241/247/345/225/217/350/253/256/350/251/242/cover-1685785115833.png +0 -0
- package/.output/.output/talks//351/206/253/347/224/237/345/222/214/347/227/205/344/272/272/350/250/216/350/253/226/346/202/262/345/202/267/content.json +32 -0
- package/.output/.output/talks//351/206/253/347/224/237/345/222/214/347/227/205/344/272/272/350/250/216/350/253/226/346/202/262/345/202/267/cover-1684055075942.png +0 -0
- package/README.md +87 -84
- package/dist/index.js +1 -1
- package/package.json +4 -4
- package/examples/chat-demo.ts +0 -89
- package/examples/chat-for-llama.cpp-demo.ts +0 -57
- package/examples/plugin-demo.ts +0 -110
- package/examples/stream-for-llama.cpp-demo.ts +0 -33
- package/examples/vision-demo-ex.png +0 -0
- package/examples/vision-demo.png +0 -0
- package/examples/vision-demo.ts +0 -168
- package/lib/broker/chat.ts +0 -406
- package/lib/core/parser.ts +0 -62
- package/lib/core/plugin.ts +0 -46
- package/lib/core/translator.ts +0 -111
- package/lib/index.ts +0 -38
- package/lib/plugins/index.ts +0 -38
- package/lib/plugins/limiter.ts +0 -103
- package/lib/plugins/print-log.ts +0 -35
- package/lib/plugins/retry.ts +0 -25
- package/lib/plugins/role.ts +0 -28
- package/lib/service/llama3.cpp/completion.ts +0 -313
- package/lib/service/llama3.cpp/index.ts +0 -53
- package/lib/service/openai/chat.ts +0 -244
- package/lib/service/openai/images-generation.ts +0 -64
- package/lib/service/openai/index.ts +0 -97
- package/lib/service/openai/vision.ts +0 -111
- package/lib/shims.d.ts +0 -4
- package/lib/templates.ts +0 -71
- package/lib/types.ts +0 -4
- package/lib/utils/error.ts +0 -14
- package/lib/utils/validate.ts +0 -64
- package/logo.ai +2 -1141
- package/logo.png +0 -0
- package/types/examples/chat-demo.d.ts +0 -2
- package/types/examples/chat-for-llama.cpp-demo.d.ts +0 -2
- package/types/examples/chat-with-json-schema-demo.d.ts +0 -2
- package/types/examples/plugin-demo.d.ts +0 -2
- package/types/examples/stream-for-llama.cpp-demo.d.ts +0 -2
- package/types/examples/vision-demo.d.ts +0 -2
- package/types/lib/broker/chat.d.ts +0 -142
- package/types/lib/core/parser.d.ts +0 -32
- package/types/lib/core/plugin.d.ts +0 -34
- package/types/lib/core/translator.d.ts +0 -68
- package/types/lib/index.d.ts +0 -31
- package/types/lib/plugins/index.d.ts +0 -47
- package/types/lib/plugins/limiter.d.ts +0 -36
- package/types/lib/plugins/print-log.d.ts +0 -5
- package/types/lib/plugins/retry.d.ts +0 -6
- package/types/lib/plugins/role.d.ts +0 -5
- package/types/lib/service/llama3.cpp/completion.d.ts +0 -61
- package/types/lib/service/llama3.cpp/index.d.ts +0 -19
- package/types/lib/service/openai/chat.d.ts +0 -110
- package/types/lib/service/openai/completion.d.ts +0 -59
- package/types/lib/service/openai/images-generation.d.ts +0 -35
- package/types/lib/service/openai/index.d.ts +0 -29
- package/types/lib/service/openai/vision.d.ts +0 -74
- package/types/lib/templates.d.ts +0 -20
- package/types/lib/types.d.ts +0 -1
- package/types/lib/utils/error.d.ts +0 -11
- package/types/lib/utils/validate.d.ts +0 -16
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={177:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBroker=void 0;const r=n(306),a=n(572),o=n(235),s=n(165);t.ChatBroker=class{__hookType;log;hook=new a.Hook;params;plugins={};installed=!1;translator;event=new a.Event;constructor(e){this.log=new a.Log(e.name??"no name"),this.params=e,this.translator=new o.Translator({...e,parsers:[r.TextParser.JsonMessage()]})}_install(){if(!1===this.installed){this.installed=!0;const e={log:this.log,attach:this.hook.attach.bind(this.hook),attachAfter:this.hook.attachAfter.bind(this.hook),translator:this.translator};if(this.params.plugins){this.plugins="function"==typeof this.params.plugins?this.params.plugins():this.params.plugins;for(let t in this.plugins)this.plugins[t].instance._params.onInstall({...e,params:this.plugins[t].params,receive:this.plugins[t].receive})}this.params.install?.(e)}}async cancel(e){e?this.event.emit("cancel",{requestId:e}):this.event.emit("cancelAll",{})}requestWithId(e){this._install();let t=a.flow.createUuid(),n=null,r=!1,o=!1,i=[this.event.on("cancel",(({requestId:e})=>{e===t&&c()})),this.event.on("cancelAll",(()=>{c()}))],l=()=>i.forEach((e=>e.off())),c=()=>{!1===r&&(o&&n&&n(),r=!0,l())},u=e=>{n=e},p=async()=>{let i=this.translator.getValidate(),l=null,c={},p=await this.translator.compile(e,{schema:i}),h=[{role:"user",content:p.prompt}];for(let e in this.plugins)c[e]={send:n=>this.plugins[e].send({id:t,data:n})};return await this.hook.notify("start",{id:t,data:e,schema:i,plugins:c,messages:h,setPreMessages:e=>{const t=e.map((e=>({...e,content:Array.isArray(e.content)?e.content.join("\n"):e.content})));h=[...t,{role:"user",content:p.prompt}]},changeMessages:e=>{h=e}}),await a.flow.asyncWhile((async({count:a,doBreak:c})=>{if(a>=10)return c();let p="",d="",f=!1,m=h.filter((e=>"user"===e.role)).slice(-1)[0]?.content||"";try{await this.hook.notify("talkBefore",{id:t,data:e,messages:h,lastUserMessage:m});const g=this.params.request(h,{count:a,schema:i,onCancel:u,isRetry:f});if(r)n&&n();else try{o=!0,p=await g,d=p}finally{o=!1}!1===r&&(await this.hook.notify("talkAfter",{id:t,data:e,response:p,messages:h,parseText:d,lastUserMessage:m,parseFail:e=>{throw new s.ParserError(e,[])},changeParseText:e=>{d=e}}),l=(await this.translator.parse(d)).output,await this.hook.notify("succeeded",{id:t,output:l})),await this.hook.notify("done",{id:t}),c()}catch(e){if(!(e instanceof s.ParserError))throw await this.hook.notify("done",{id:t}),e;if(await this.hook.notify("parseFailed",{id:t,error:e.error,count:a,response:p,messages:h,lastUserMessage:m,parserFails:e.parserFails,retry:()=>{f=!0},changeMessages:e=>{h=e}}),!1===f)throw await this.hook.notify("done",{id:t}),e}})),l};return{id:t,request:(async()=>{try{return await p()}finally{l()}})()}}async request(e){const{request:t}=this.requestWithId(e);return await t}}},306: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.TextParser=void 0;const a=r(n(865));class o{params;static JsonMessage(){return new o({name:"JsonMessage",handler:async e=>{try{return JSON.parse(e)}catch(t){const n=/{(?:[^{}]|(?:{[^{}]*}))*}/,r=e.match(n)?.[0]||"";return a.default.parse(r)}}})}constructor(e){this.params=e}get name(){return this.params.name}async read(e){return await this.params.handler(e)}}t.TextParser=o},198:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBrokerPlugin=void 0;const r=n(572);t.ChatBrokerPlugin=class{_event=new r.Event;_params;constructor(e){this._params=e}use(e){return{instance:this,params:e,send:e=>{this._event.emit("receive",e)},receive:e=>{this._event.on("receive",e)},__receiveData:null}}}},235:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Translator=void 0;const r=n(357),a=n(165);t.Translator=class{params;constructor(e){this.params=e}get __schemeType(){return null}get __outputType(){return null}async compile(e,t){const n=(0,r.validate)(e,this.params.input),a=await this.params.question(n,t);return{scheme:n,prompt:Array.isArray(a)?a.join("\n"):a}}getValidate(){return{input:this.params.input,output:this.params.output}}async parse(e){let t,n="",o=[];for(let r of this.params.parsers)try{t=await r.read(e),n=r.name}catch(e){t=void 0,o.push({name:r.name,error:e})}try{return{output:(0,r.validate)(t,this.params.output),parserName:n,parserFails:o}}catch(e){throw new a.ParserError(e,o)}}}},665:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=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 a(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ctod=t.Translator=t.ChatBrokerPlugin=t.ChatBroker=t.TextParser=t.Llama3Cpp=t.OpenAI=t.defineYupSchema=t.validateToJsonSchema=t.templates=t.plugins=void 0,t.plugins=o(n(374)),t.templates=o(n(854));var s=n(357);Object.defineProperty(t,"validateToJsonSchema",{enumerable:!0,get:function(){return s.validateToJsonSchema}}),Object.defineProperty(t,"defineYupSchema",{enumerable:!0,get:function(){return s.defineYupSchema}});var i=n(984);Object.defineProperty(t,"OpenAI",{enumerable:!0,get:function(){return i.OpenAI}});var l=n(887);Object.defineProperty(t,"Llama3Cpp",{enumerable:!0,get:function(){return l.Llama3Cpp}});var c=n(306);Object.defineProperty(t,"TextParser",{enumerable:!0,get:function(){return c.TextParser}});var u=n(177);Object.defineProperty(t,"ChatBroker",{enumerable:!0,get:function(){return u.ChatBroker}});var p=n(198);Object.defineProperty(t,"ChatBrokerPlugin",{enumerable:!0,get:function(){return p.ChatBrokerPlugin}});var h=n(235);Object.defineProperty(t,"Translator",{enumerable:!0,get:function(){return h.Translator}});const d=o(n(374)),f=o(n(854)),m=n(984),g=n(887),y=n(235),_=n(306),v=n(177),b=n(198),w=n(357);t.ctod={OpenAI:m.OpenAI,Llama3Cpp:g.Llama3Cpp,plugins:d,templates:f,ChatBroker:v.ChatBroker,Translator:y.Translator,TextParser:_.TextParser,ChatBrokerPlugin:b.ChatBrokerPlugin,defineYupSchema:w.defineYupSchema,validateToJsonSchema:w.validateToJsonSchema},e.exports=t.ctod,e.exports.ctod=t.ctod,t.default=t.ctod},374: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;const a=r(n(92)),o=r(n(354)),s=r(n(270)),i=r(n(724));t.PrintLogPlugin=o.default,t.RetryPlugin=a.default,t.LimiterPlugin=s.default.plugin,t.LimiterPluginGlobState=s.default,t.RolePlugin=i.default},270:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(198),a=n(572),o={limit:3,interval:6e4},s={event:new a.Event,schedule:null,waitTimes:[],waitQueue:[]};t.default={event:s.event,config:o,closeSchedule:()=>{s.schedule&&(s.schedule.close(),s.schedule=null)},plugin:new r.ChatBrokerPlugin({name:"limiter",params:()=>({}),receiveData:()=>({}),onInstall({attach:e}){null==s.schedule&&(s.schedule=new a.Schedule,s.schedule.add("calc queue",1e3,(async()=>{const e=Date.now();if(s.waitTimes=s.waitTimes.filter((t=>e-t<o.interval)),s.waitTimes.length!==o.limit){let e=s.waitQueue.shift();e&&(s.waitTimes.push(Date.now()),s.event.emit("run",{id:e}))}else s.waitTimes[0]&&s.event.emit("waitTimeChange",{waitTime:Math.floor(60-(e-s.waitTimes[0])/1e3)})})),s.schedule.play()),e("talkBefore",(async()=>{const e=a.flow.createUuid();return s.waitQueue.push(e),new Promise((t=>{s.event.on("run",(({id:n},{off:r})=>{n===e&&(r(),t())}))}))}))}})}},354:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(198);t.default=new r.ChatBrokerPlugin({name:"print-log",params:e=>({detail:e.boolean().default(!1)}),receiveData:()=>({}),onInstall({params:e,log:t,attach:n}){n("talkBefore",(async({lastUserMessage:n,messages:r})=>{t.print("Send:",{color:"green"}),e.detail?t.print("\n"+JSON.stringify(r,null,4)):t.print("\n"+n)})),n("talkAfter",(async({parseText:e})=>{t.print("Receive:",{color:"cyan"}),t.print("\n"+e)})),n("succeeded",(async({output:e})=>{t.print("Output:",{color:"yellow"});try{t.print("\n"+JSON.stringify(e,null,4))}catch(n){t.print("\n"+e)}}))}})},92:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(198);t.default=new r.ChatBrokerPlugin({name:"retry",params:e=>({retry:e.number().required().default(1),printWarn:e.boolean().required().default(!0)}),receiveData:()=>({}),onInstall({log:e,attach:t,params:n}){t("parseFailed",(async({count:t,retry:r,messages:a,changeMessages:o})=>{t<=n.retry&&(n.printWarn&&e.print(`Is Failed, Retry ${t} times.`),o(a),r())}))}})},724:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=n(198);t.default=new r.ChatBrokerPlugin({name:"role",params:e=>({role:e.string().required()}),receiveData:()=>({}),onInstall({attach:e,params:t}){e("start",(async({messages:e,changeMessages:n})=>{n([{role:"user",content:`你現在是${t.role}。`},{role:"assistant",content:`沒問題,我現在是${t.role},有什麼可以幫你的嗎?`},...e])}))}})},129:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Llama3CppCompletion=void 0;const r=n(572),a=n(4);class o{core;streamAbortControllers=[];constructor(e){this.core=e}createAbortController(){const e=new AbortController,t=r.flow.createUuid();return this.streamAbortControllers.push({id:t,controller:e}),{signal:e.signal,controllerId:t}}removeAbortController(e){this.streamAbortControllers=this.streamAbortControllers.filter((t=>t.id!==e))}async stream(e){const{signal:t,controllerId:n}=this.createAbortController(),r=()=>{this.removeAbortController(n),e.onEnd()};fetch(`${this.core.config.baseUrl}/${e.path}`,{method:"POST",body:JSON.stringify(e.data),signal:t,headers:{"Content-Type":"application/json",...this.core.config.headers}}).then((async t=>{if(t.body){let n=t.body.getReader(),a=!1,o="";for(;!a;){const{value:t,done:r}=await n.read();if(t){o+=new TextDecoder("utf-8").decode(t);const n=o.split("\n\n");o=n.pop()||"",n.forEach((t=>{if(t.includes("[DONE]")&&(a=!0),t.startsWith("data:"))try{const n=JSON.parse(t.replace("data: ",""));e.onMessage(n)}catch(t){e.onWarn(t)}}))}r&&(a=!0)}r()}else e.onError(new Error("Body not found."))})).catch((t=>{t instanceof Error&&t.message.includes("The user aborted a request")?r():e.onError(t)}))}async fetch(e){const{signal:t,controllerId:n}=this.createAbortController();try{return{data:(await this.core.core._axios.post(`${this.core.config.baseUrl}/${e.path}`,e.data,{signal:t,headers:{"Content-Type":"application/json",...this.core.config.headers}})).data}}finally{this.removeAbortController(n)}}cancel(){this.streamAbortControllers.forEach((e=>e.controller.abort())),this.streamAbortControllers=[]}export(){return{cancel:this.cancel.bind(this)}}}t.Llama3CppCompletion=class{core;config={baseUrl:"",headers:{},autoConvertTraditionalChinese:!0};constructor(e){this.core=e}setConfig(e){this.config={...this.config,...e}}completion(e){const t=[];for(let{role:n,content:r}of e.messages)"system"===n&&t.push(`<|start_header_id|>system<|end_header_id|>\n\n${r}\n\n`),"user"===n&&t.push(`<|start_header_id|>user<|end_header_id|>\n\n${r?.replaceAll("\n","\\n")??""}`),"assistant"===n&&t.push("<|start_header_id|>assistant<|end_header_id|>\n\n"+r);const n=e.messages.at(-1)||"",r=new o(this);return{...r.export(),run:async()=>{const o=await r.fetch({path:"completion",data:{...e.options||{},prompt:this.config.autoConvertTraditionalChinese?(0,a.sify)(t.join("\n")):t.join("\n")}}),s=this.config.autoConvertTraditionalChinese?(0,a.tify)(o.data.content):o.data.content;return{message:s,fullMessage:`${n}${s}`}}}}completionStream(e){const t=[];for(let{role:n,content:r}of e.messages)"system"===n&&t.push(`<|start_header_id|>system<|end_header_id|>\n\n${r}\n\n`),"user"===n&&t.push(`<|start_header_id|>user<|end_header_id|>\n\n${r?.replaceAll("\n","\\n")??""}`),"assistant"===n&&t.push("<|start_header_id|>assistant<|end_header_id|>\n\n"+r);const n=new o(this);return n.stream({path:"completion",onEnd:e.onEnd||(()=>null),onMessage:t=>{e.onMessage({message:this.config.autoConvertTraditionalChinese?(0,a.tify)(t.content):t.content})},onWarn:e.onWarn||(()=>null),onError:e.onError||(()=>null),data:{...e.options||{},prompt:this.config.autoConvertTraditionalChinese?(0,a.sify)(t.join("\n")):t.join("\n"),stream:!0}}),n.export()}talk(e){const t=new o(this);return{...t.export(),run:async()=>{const n=(await t.fetch({path:"v1/chat/completions",data:{...e.options||{},response_format:e.response_format,messages:e.messages.map((e=>({role:e.role,content:this.config.autoConvertTraditionalChinese?(0,a.sify)(e.content):e.content})))}})).data.choices[0].message.content||"";return{message:this.config.autoConvertTraditionalChinese?(0,a.tify)(n):n}}}}talkStream(e){const t=new o(this);return t.stream({path:"v1/chat/completions",onEnd:e.onEnd||(()=>null),onMessage:t=>{let n=t.choices[0].delta.content;n&&e.onMessage({message:this.config.autoConvertTraditionalChinese?(0,a.tify)(n):n})},onWarn:e.onWarn||(()=>null),onError:e.onError||(()=>null),data:{...e.options||{},stream:!0,messages:e.messages.map((e=>({role:e.role,content:this.config.autoConvertTraditionalChinese?(0,a.sify)(e.content):e.content})))}}),t.export()}}},887: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.Llama3Cpp=void 0;const a=r(n(938)),o=n(4),s=n(357),i=n(129);class l{_axios=a.default.create();static createChatRequest(e){return async(t,{schema:n,onCancel:r})=>{const a=(new l).createCompletion(),i="function"==typeof e.config?await e.config():e.config;a.setConfig(i);let c=(0,s.validateToJsonSchema)(n.output);a.config.autoConvertTraditionalChinese&&(c=JSON.parse((0,o.sify)(JSON.stringify(c))));const{run:u,cancel:p}=a.talk({options:e.talkOptions,messages:t,response_format:{type:"json_object",schema:c}});r(p);const{message:h}=await u();return h}}setAxios(e){this._axios=e}createCompletion(){return new i.Llama3CppCompletion(this)}}t.Llama3Cpp=l},228:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIChat=void 0;const r=n(572);t.OpenAIChat=class{openai;config={n:1,model:"gpt-4o",temperature:1,maxTokens:void 0,forceJsonFormat:!0};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async moderations(e){const t=await this.openai._axios.post("https://api.openai.com/v1/moderations",{input:e},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}});return{isSafe:!1===t.data.results?.[0]?.flagged,result:t.data}}async talk(e=[],t){const n=r.json.jpjs(e),a=["gpt-4-turbo-preview","gpt-4-turbo","gpt-4o","gpt-4o-mini","gpt-3.5-turbo-1106"].includes(this.config.model);let o;a&&this.config.forceJsonFormat&&(o={type:"json_object"}),a&&this.config.forceJsonFormat&&t?.jsonSchema&&(o={type:"json_schema",json_schema:t.jsonSchema});const s=await this.openai._axios.post("https://api.openai.com/v1/chat/completions",{model:this.config.model,n:this.config.n,messages:n,response_format:o,temperature:this.config.temperature},{signal:t?.abortController?.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}}),i=s.data.choices||[],l=i[0]?.message||{role:"assistant",content:""};return n.push(l),{id:s?.data.id,text:l.content,newMessages:n,isDone:"stop"===i[0]?.finish_reason,apiReseponse:s.data}}talkStream(e){const t=new AbortController;return fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`},body:JSON.stringify({model:this.config.model,stream:!0,messages:e.messages}),signal:t.signal}).then((async t=>{const n=t.body?.pipeThrough(new TextDecoderStream).getReader();if(!n)throw new Error("Can not get reader");for(;;){const{value:t,done:r}=await n.read();if(r)break;const a=t.split("\n");for(let t of a)if(0!==t.length&&!t.startsWith(":")){if("data: [DONE]"===t){e.onEnd();break}try{const n=JSON.parse(t.substring(6)).choices[0].delta.content;e.onMessage(n)}catch(t){e.onWarn(t)}}}})).catch((t=>{"AbortError"===t.name?e.onEnd():e.onError(t)})),{cancel:()=>t.abort()}}async keepTalk(e,t=[]){const n=await this.talk([...t,{role:"user",content:Array.isArray(e)?e.join("\n"):e}]);return{result:n,nextTalk:e=>this.keepTalk(e,n.newMessages)}}}},11:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIImagesGeneration=void 0,t.OpenAIImagesGeneration=class{openai;config={model:"dall-e-2",size:"1024x1024"};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async create(e){return(await 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 ${this.openai._apiKey}`}})).data}}},984: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.OpenAI=void 0;const a=r(n(938)),o=n(38),s=n(228),i=n(11),l=n(357);class c{_axios=a.default.create();_apiKey="";static createChatRequest(e,t={},n){return async(r,{onCancel:a})=>{const o=new c("string"==typeof e?e:await e()),s=o.createChat(),i=new AbortController;n&&n.axios&&o.setAxios(n.axios),s.setConfig("function"==typeof t?await t():t),a((()=>i.abort()));const{text:l}=await s.talk(r,{abortController:i});return l}}static createChatRequestWithJsonSchema(e){return async(t,{schema:n,onCancel:r})=>{const a=new c("string"==typeof e.apiKey?e.apiKey:await e.apiKey()),o=a.createChat(),s=new AbortController;e.config&&o.setConfig("function"==typeof e.config?await e.config():e.config),e.axios&&a.setAxios(e.axios),r((()=>s.abort()));const i=(0,l.validateToJsonSchema)(n.output),{text:u}=await o.talk(t,{abortController:s,jsonSchema:{name:"data",strict:!0,schema:i}});return u}}constructor(e=""){this._apiKey=e}setAxios(e){this._axios=e}setConfiguration(e){this._apiKey=e}createChat(){return new s.OpenAIChat(this)}createVision(){return new o.OpenAIVision(this)}createImagesGeneration(){return new i.OpenAIImagesGeneration(this)}}t.OpenAI=c},38:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIVision=void 0,t.OpenAIVision=class{openai;config={model:"gpt-4-vision-preview",maxTokens:void 0,temperature:1};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async view(e){const t=await 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 ${this.openai._apiKey}`}}),n=t.data.choices||[],r=n[0]?.message||{role:"assistant",content:""};return{id:t?.data.id,text:r.content,apiReseponse:t.data}}}},854: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.requireJsonResponseWithJsonSchema=t.requireJsonResponseWithHandlebars=t.requireJsonResponse=void 0;const a=r(n(156)),o=n(572);t.requireJsonResponse=(e,t)=>[...Array.isArray(e)?e:[e],"Please respond using the following JSON format and minify the JSON without including any explanation: ","{",Object.entries(t).map((([e,t])=>[`/* ${t.desc} */`,`"${e}": ${JSON.stringify(t.example)}`].join("\n"))).join(",\n"),"}"].join("\n"),t.requireJsonResponseWithHandlebars=(e,n,r)=>{const s=a.default.create();return s.registerHelper("DATA",(function(e){return JSON.stringify(e)})),s.registerHelper("ENV",(function(e){return this.__envs&&e?this.__envs[e]:""})),s.registerHelper("INPUT",(function(){return JSON.stringify(o.record.omit(this,["__envs"]))})),s.registerHelper("JOIN",(function(e){return Array.isArray(e)?e.join():JSON.stringify(e)})),s.compile((0,t.requireJsonResponse)(n,r))(e)},t.requireJsonResponseWithJsonSchema=(e,t)=>[...Array.isArray(e)?e:[e],"Please provide JSON data according to the following JSON Schema format:",JSON.stringify(t)].join("\n")},165:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserError=void 0,t.ParserError=class{isParserError=!0;parserFails=[];error;constructor(e,t){this.error=e,this.parserFails=t}}},357:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){void 0===r&&(r=n);var a=Object.getOwnPropertyDescriptor(t,n);a&&!("get"in a?!t.__esModule:a.writable||a.configurable)||(a={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,a)}:function(e,t,n,r){void 0===r&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=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 a(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.validateToJsonSchema=t.defineYupSchema=t.validate=t.definedValidateSchema=void 0;const s=o(n(622)),i=n(250);t.definedValidateSchema=function(e){return e},t.validate=function(e,t){return s.object(t(s)).required().validateSync(e||{})},t.defineYupSchema=e=>e(s),t.validateToJsonSchema=e=>{const t=e=>{if(e.default&&delete e.default,e.properties)for(let n in e.properties)e.properties[n].default&&delete e.properties[n].default,t(e.properties[n]);e.items&&t(e.items)},n=e=>{if("object"===e.type){e.additionalProperties=!1;for(const t in e.properties)n(e.properties[t])}else"array"===e.type&&n(e.items)},r=(0,i.convertSchema)(s.object(e(s)));return t(r),n(r),r}},250:e=>{e.exports=require("@sodaru/yup-to-json-schema")},938:e=>{e.exports=require("axios")},4:e=>{e.exports=require("chinese-conv")},156:e=>{e.exports=require("handlebars")},865:e=>{e.exports=require("json5")},572:e=>{e.exports=require("power-helper")},622:e=>{e.exports=require("yup")}},t={};return function n(r){var a=t[r];if(void 0!==a)return a.exports;var o=t[r]={exports:{}};return e[r].call(o.exports,o,o.exports,n),o.exports}(665)})()));
|
|
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={177:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBroker=void 0;const n=a(306),r=a(572),o=a(235),s=a(165);t.ChatBroker=class{__hookType;log;hook=new r.Hook;params;plugins={};installed=!1;translator;event=new r.Event;constructor(e){this.log=new r.Log(e.name??"no name"),this.params=e,this.translator=new o.Translator({...e,parsers:[n.TextParser.JsonMessage()]})}_install(){if(!1===this.installed){this.installed=!0;const e={log:this.log,attach:this.hook.attach.bind(this.hook),attachAfter:this.hook.attachAfter.bind(this.hook),translator:this.translator};if(this.params.plugins){this.plugins="function"==typeof this.params.plugins?this.params.plugins():this.params.plugins;for(let t in this.plugins)this.plugins[t].instance._params.onInstall({...e,params:this.plugins[t].params,receive:this.plugins[t].receive})}this.params.install?.(e)}}async cancel(e){e?this.event.emit("cancel",{requestId:e}):this.event.emit("cancelAll",{})}requestWithId(e){this._install();let t=r.flow.createUuid(),a=null,n=!1,o=!1,i=[this.event.on("cancel",(({requestId:e})=>{e===t&&c()})),this.event.on("cancelAll",(()=>{c()}))],l=()=>i.forEach((e=>e.off())),c=()=>{!1===n&&(o&&a&&a(),n=!0,l())},u=e=>{a=e},p=async()=>{let i=this.translator.getValidate(),l=null,c={},p=new Map,d=await this.translator.compile(e,{schema:i}),h=[],f=[];d.prompt&&f.push({role:"user",content:d.prompt});for(let e in this.plugins)c[e]={send:a=>this.plugins[e].send({id:t,data:a})};return await this.hook.notify("start",{id:t,data:e,schema:i,plugins:c,messages:f,metadata:p,setPreMessages:e=>{h=e.map((e=>({...e,content:Array.isArray(e.content)?e.content.join("\n"):e.content})))},changeMessages:e=>{f=e},changeOutputSchema:e=>{this.translator.changeOutputSchema(e),i=this.translator.getValidate()}}),f=[...h,...f],await r.flow.asyncWhile((async({count:r,doBreak:c})=>{if(r>=99)return c();let d="",h="",m=!1,g=f.filter((e=>"user"===e.role)).slice(-1)[0]?.content||"";try{await this.hook.notify("talkBefore",{id:t,data:e,messages:f,metadata:p,lastUserMessage:g});const y=this.params.request(f,{id:t,count:r,schema:i,onCancel:u,metadata:p,isRetry:m});if(n)a&&a();else try{o=!0,d=await y,h=d}finally{o=!1}!1===n&&(await this.hook.notify("talkAfter",{id:t,data:e,response:d,messages:f,parseText:h,metadata:p,lastUserMessage:g,parseFail:e=>{throw new s.ParserError(e,[])},changeParseText:e=>{h=e}}),l=(await this.translator.parse(h)).output,await this.hook.notify("succeeded",{id:t,output:l,metadata:p})),await this.hook.notify("done",{id:t,metadata:p}),c()}catch(e){if(!(e instanceof s.ParserError))throw await this.hook.notify("done",{id:t,metadata:p}),e;if(await this.hook.notify("parseFailed",{id:t,error:e.error,count:r,response:d,messages:f,metadata:p,lastUserMessage:g,parserFails:e.parserFails,retry:()=>{m=!0},changeMessages:e=>{f=e}}),!1===m)throw await this.hook.notify("done",{id:t,metadata:p}),e}})),l};return{id:t,request:(async()=>{try{return await p()}finally{l()}})()}}async request(e){const{request:t}=this.requestWithId(e);return await t}}},306:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TextParser=void 0;const r=n(a(865));class o{params;static JsonMessage(){return new o({name:"JsonMessage",handler:async e=>{try{return JSON.parse(e)}catch(t){const a=/{(?:[^{}]|(?:{[^{}]*}))*}/,n=e.match(a)?.[0]||"";return r.default.parse(n)}}})}constructor(e){this.params=e}get name(){return this.params.name}async read(e){return await this.params.handler(e)}}t.TextParser=o},198:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBrokerPlugin=void 0;const n=a(572);t.ChatBrokerPlugin=class{_event=new n.Event;_params;constructor(e){this._params=e}use(e){return{instance:this,params:e,send:e=>{this._event.emit("receive",e)},receive:e=>{this._event.on("receive",e)},__receiveData:null}}}},235:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Translator=void 0;const n=a(357),r=a(165);t.Translator=class{params;constructor(e){this.params=e}get __schemeType(){return null}get __outputType(){return null}async compile(e,t){const a=this.params.input?(0,n.validate)(e,this.params.input):e,r=this.params.question?await this.params.question(a,t):"";return{scheme:a,prompt:Array.isArray(r)?r.join("\n"):r}}getValidate(){return{input:this.params.input,output:this.params.output}}changeOutputSchema(e){this.params.output=e}async parse(e){let t,a="",o=[];for(let n of this.params.parsers)try{t=await n.read(e),a=n.name}catch(e){t=void 0,o.push({name:n.name,error:e})}try{return{output:(0,n.validate)(t,this.params.output),parserName:a,parserFails:o}}catch(e){throw new r.ParserError(e,o)}}}},697:function(e,t,a){var n=this&&this.__createBinding||(Object.create?function(e,t,a,n){void 0===n&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}:function(e,t,a,n){void 0===n&&(n=a),e[n]=t[a]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&n(t,e,a);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CtoD=void 0;const s=a(177),i=o(a(622));t.CtoD=class{params;constructor(e){this.params=e}createBrokerBuilder(e){return{create:t=>new s.ChatBroker({output:()=>({}),install:a=>{e?.install?.(a),a.attach("start",(async({id:e,plugins:a,data:n,metadata:r,changeMessages:o,changeOutputSchema:s})=>{const l=await t({id:e,data:n,plugins:a,yup:i,setMessages:e=>{o(e.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.join("\n"):e.content}))))},metadata:r});s((()=>l))}))},plugins:this.params.plugins?()=>this.params.plugins():void 0,request:this.params.request})}}}},665:function(e,t,a){var n=this&&this.__createBinding||(Object.create?function(e,t,a,n){void 0===n&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}:function(e,t,a,n){void 0===n&&(n=a),e[n]=t[a]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&n(t,e,a);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ctod=t.Translator=t.ChatBrokerPlugin=t.ChatBroker=t.TextParser=t.Llama3Cpp=t.OpenAI=t.defineYupSchema=t.validateToJsonSchema=t.CtoD=t.templates=t.plugins=void 0,t.plugins=o(a(374)),t.templates=o(a(854));var s=a(697);Object.defineProperty(t,"CtoD",{enumerable:!0,get:function(){return s.CtoD}});var i=a(357);Object.defineProperty(t,"validateToJsonSchema",{enumerable:!0,get:function(){return i.validateToJsonSchema}}),Object.defineProperty(t,"defineYupSchema",{enumerable:!0,get:function(){return i.defineYupSchema}});var l=a(984);Object.defineProperty(t,"OpenAI",{enumerable:!0,get:function(){return l.OpenAI}});var c=a(887);Object.defineProperty(t,"Llama3Cpp",{enumerable:!0,get:function(){return c.Llama3Cpp}});var u=a(306);Object.defineProperty(t,"TextParser",{enumerable:!0,get:function(){return u.TextParser}});var p=a(177);Object.defineProperty(t,"ChatBroker",{enumerable:!0,get:function(){return p.ChatBroker}});var d=a(198);Object.defineProperty(t,"ChatBrokerPlugin",{enumerable:!0,get:function(){return d.ChatBrokerPlugin}});var h=a(235);Object.defineProperty(t,"Translator",{enumerable:!0,get:function(){return h.Translator}});const f=o(a(374)),m=o(a(854)),g=a(984),y=a(697),_=a(887),v=a(235),b=a(306),w=a(177),C=a(198),O=a(357);t.ctod={CtoD:y.CtoD,OpenAI:g.OpenAI,Llama3Cpp:_.Llama3Cpp,plugins:f,templates:m,ChatBroker:w.ChatBroker,Translator:v.Translator,TextParser:b.TextParser,ChatBrokerPlugin:C.ChatBrokerPlugin,defineYupSchema:O.defineYupSchema,validateToJsonSchema:O.validateToJsonSchema},e.exports=t.ctod,e.exports.ctod=t.ctod,t.default=t.ctod},374:function(e,t,a){var n=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;const r=n(a(92)),o=n(a(354)),s=n(a(270)),i=n(a(724));t.PrintLogPlugin=o.default,t.RetryPlugin=r.default,t.LimiterPlugin=s.default.plugin,t.LimiterPluginGlobState=s.default,t.RolePlugin=i.default},270:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198),r=a(572),o={limit:3,interval:6e4},s={event:new r.Event,schedule:null,waitTimes:[],waitQueue:[]};t.default={event:s.event,config:o,closeSchedule:()=>{s.schedule&&(s.schedule.close(),s.schedule=null)},plugin:new n.ChatBrokerPlugin({name:"limiter",params:()=>({}),receiveData:()=>({}),onInstall({attach:e}){null==s.schedule&&(s.schedule=new r.Schedule,s.schedule.add("calc queue",1e3,(async()=>{const e=Date.now();if(s.waitTimes=s.waitTimes.filter((t=>e-t<o.interval)),s.waitTimes.length!==o.limit){let e=s.waitQueue.shift();e&&(s.waitTimes.push(Date.now()),s.event.emit("run",{id:e}))}else s.waitTimes[0]&&s.event.emit("waitTimeChange",{waitTime:Math.floor(60-(e-s.waitTimes[0])/1e3)})})),s.schedule.play()),e("talkBefore",(async()=>{const e=r.flow.createUuid();return s.waitQueue.push(e),new Promise((t=>{s.event.on("run",(({id:a},{off:n})=>{a===e&&(n(),t())}))}))}))}})}},354:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198);t.default=new n.ChatBrokerPlugin({name:"print-log",params:e=>({detail:e.boolean().default(!1)}),receiveData:()=>({}),onInstall({params:e,log:t,attach:a}){a("talkBefore",(async({lastUserMessage:a,messages:n})=>{t.print("Send:",{color:"green"}),e.detail?t.print("\n"+JSON.stringify(n,null,4)):t.print("\n"+a)})),a("talkAfter",(async({parseText:e})=>{t.print("Receive:",{color:"cyan"}),t.print("\n"+e)})),a("succeeded",(async({output:e})=>{t.print("Output:",{color:"yellow"});try{t.print("\n"+JSON.stringify(e,null,4))}catch(a){t.print("\n"+e)}}))}})},92:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198);t.default=new n.ChatBrokerPlugin({name:"retry",params:e=>({retry:e.number().required().default(1),printWarn:e.boolean().required().default(!0)}),receiveData:()=>({}),onInstall({log:e,attach:t,params:a}){t("parseFailed",(async({count:t,retry:n,messages:r,changeMessages:o})=>{t<=a.retry&&(a.printWarn&&e.print(`Is Failed, Retry ${t} times.`),o(r),n())}))}})},724:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198);t.default=new n.ChatBrokerPlugin({name:"role",params:e=>({role:e.string().required()}),receiveData:()=>({}),onInstall({attach:e,params:t}){e("start",(async({messages:e,changeMessages:a})=>{a([{role:"user",content:`你現在是${t.role}。`},{role:"assistant",content:`沒問題,我現在是${t.role},有什麼可以幫你的嗎?`},...e])}))}})},129:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Llama3CppCompletion=void 0;const n=a(572),r=a(4);class o{core;streamAbortControllers=[];constructor(e){this.core=e}createAbortController(){const e=new AbortController,t=n.flow.createUuid();return this.streamAbortControllers.push({id:t,controller:e}),{signal:e.signal,controllerId:t}}removeAbortController(e){this.streamAbortControllers=this.streamAbortControllers.filter((t=>t.id!==e))}async stream(e){const{signal:t,controllerId:a}=this.createAbortController(),n=()=>{this.removeAbortController(a),e.onEnd()};fetch(`${this.core.config.baseUrl}/${e.path}`,{method:"POST",body:JSON.stringify(e.data),signal:t,headers:{"Content-Type":"application/json",...this.core.config.headers}}).then((async t=>{if(t.body){let a=t.body.getReader(),r=!1,o="";for(;!r;){const{value:t,done:n}=await a.read();if(t){o+=new TextDecoder("utf-8").decode(t);const a=o.split("\n\n");o=a.pop()||"",a.forEach((t=>{if(t.includes("[DONE]")&&(r=!0),t.startsWith("data:"))try{const a=JSON.parse(t.replace("data: ",""));e.onMessage(a)}catch(t){e.onWarn(t)}}))}n&&(r=!0)}n()}else e.onError(new Error("Body not found."))})).catch((t=>{t instanceof Error&&t.message.includes("The user aborted a request")?n():e.onError(t)}))}async fetch(e){const{signal:t,controllerId:a}=this.createAbortController();try{return{data:(await this.core.core._axios.post(`${this.core.config.baseUrl}/${e.path}`,e.data,{signal:t,headers:{"Content-Type":"application/json",...this.core.config.headers}})).data}}finally{this.removeAbortController(a)}}cancel(){this.streamAbortControllers.forEach((e=>e.controller.abort())),this.streamAbortControllers=[]}export(){return{cancel:this.cancel.bind(this)}}}t.Llama3CppCompletion=class{core;config={baseUrl:"",headers:{},autoConvertTraditionalChinese:!0};constructor(e){this.core=e}setConfig(e){this.config={...this.config,...e}}completion(e){const t=[];for(let{role:a,content:n}of e.messages)"system"===a&&t.push(`<|start_header_id|>system<|end_header_id|>\n\n${n}\n\n`),"user"===a&&t.push(`<|start_header_id|>user<|end_header_id|>\n\n${n?.replaceAll("\n","\\n")??""}`),"assistant"===a&&t.push("<|start_header_id|>assistant<|end_header_id|>\n\n"+n);const a=e.messages.at(-1)||"",n=new o(this);return{...n.export(),run:async()=>{const o=await n.fetch({path:"completion",data:{...e.options||{},prompt:this.config.autoConvertTraditionalChinese?(0,r.sify)(t.join("\n")):t.join("\n")}}),s=this.config.autoConvertTraditionalChinese?(0,r.tify)(o.data.content):o.data.content;return{message:s,fullMessage:`${a}${s}`}}}}completionStream(e){const t=[];for(let{role:a,content:n}of e.messages)"system"===a&&t.push(`<|start_header_id|>system<|end_header_id|>\n\n${n}\n\n`),"user"===a&&t.push(`<|start_header_id|>user<|end_header_id|>\n\n${n?.replaceAll("\n","\\n")??""}`),"assistant"===a&&t.push("<|start_header_id|>assistant<|end_header_id|>\n\n"+n);const a=new o(this);return a.stream({path:"completion",onEnd:e.onEnd||(()=>null),onMessage:t=>{e.onMessage({message:this.config.autoConvertTraditionalChinese?(0,r.tify)(t.content):t.content})},onWarn:e.onWarn||(()=>null),onError:e.onError||(()=>null),data:{...e.options||{},prompt:this.config.autoConvertTraditionalChinese?(0,r.sify)(t.join("\n")):t.join("\n"),stream:!0}}),a.export()}talk(e){const t=new o(this);return{...t.export(),run:async()=>{const a=(await t.fetch({path:"v1/chat/completions",data:{...e.options||{},response_format:e.response_format,messages:e.messages.map((e=>({role:e.role,content:this.config.autoConvertTraditionalChinese?(0,r.sify)(e.content):e.content})))}})).data.choices[0].message.content||"";return{message:this.config.autoConvertTraditionalChinese?(0,r.tify)(a):a}}}}talkStream(e){const t=new o(this);return t.stream({path:"v1/chat/completions",onEnd:e.onEnd||(()=>null),onMessage:t=>{let a=t.choices[0].delta.content;a&&e.onMessage({message:this.config.autoConvertTraditionalChinese?(0,r.tify)(a):a})},onWarn:e.onWarn||(()=>null),onError:e.onError||(()=>null),data:{...e.options||{},stream:!0,messages:e.messages.map((e=>({role:e.role,content:this.config.autoConvertTraditionalChinese?(0,r.sify)(e.content):e.content})))}}),t.export()}}},887:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Llama3Cpp=void 0;const r=n(a(938)),o=a(4),s=a(357),i=a(129);class l{_axios=r.default.create();static createChatRequest(e){return async(t,{schema:a,onCancel:n})=>{const r=(new l).createCompletion(),i="function"==typeof e.config?await e.config():e.config;r.setConfig(i);let c=(0,s.validateToJsonSchema)(a.output);r.config.autoConvertTraditionalChinese&&(c=JSON.parse((0,o.sify)(JSON.stringify(c))));const{run:u,cancel:p}=r.talk({options:e.talkOptions,messages:t,response_format:{type:"json_object",schema:c}});n(p);const{message:d}=await u();return d}}setAxios(e){this._axios=e}createCompletion(){return new i.Llama3CppCompletion(this)}}t.Llama3Cpp=l},228:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIChat=void 0;const n=a(572);t.OpenAIChat=class{openai;config={n:1,model:"gpt-4o",temperature:1,maxTokens:void 0,forceJsonFormat:!0};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async moderations(e){const t=await this.openai._axios.post("https://api.openai.com/v1/moderations",{input:e},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}});return{isSafe:!1===t.data.results?.[0]?.flagged,result:t.data}}async talk(e=[],t){const a=n.json.jpjs(e),r=["gpt-4-turbo-preview","gpt-4-turbo","gpt-4o","gpt-4o-mini","gpt-3.5-turbo-1106"].includes(this.config.model);let o;r&&this.config.forceJsonFormat&&(o={type:"json_object"}),r&&this.config.forceJsonFormat&&t?.jsonSchema&&(o={type:"json_schema",json_schema:t.jsonSchema});const s=await this.openai._axios.post("https://api.openai.com/v1/chat/completions",{model:this.config.model,n:this.config.n,messages:a,response_format:o,temperature:this.config.temperature},{signal:t?.abortController?.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}}),i=s.data.choices||[],l=i[0]?.message||{role:"assistant",content:""};return a.push(l),{id:s?.data.id,text:l.content,newMessages:a,isDone:"stop"===i[0]?.finish_reason,apiReseponse:s.data}}talkStream(e){const t=new AbortController;return fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`},body:JSON.stringify({model:this.config.model,stream:!0,messages:e.messages}),signal:t.signal}).then((async t=>{const a=t.body?.pipeThrough(new TextDecoderStream).getReader();if(!a)throw new Error("Can not get reader");for(;;){const{value:t,done:n}=await a.read();if(n)break;const r=t.split("\n");for(let t of r)if(0!==t.length&&!t.startsWith(":")){if("data: [DONE]"===t){e.onEnd();break}try{const a=JSON.parse(t.substring(6)).choices[0].delta.content;e.onMessage(a)}catch(t){e.onWarn(t)}}}})).catch((t=>{"AbortError"===t.name?e.onEnd():e.onError(t)})),{cancel:()=>t.abort()}}async keepTalk(e,t=[]){const a=await this.talk([...t,{role:"user",content:Array.isArray(e)?e.join("\n"):e}]);return{result:a,nextTalk:e=>this.keepTalk(e,a.newMessages)}}}},11:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIImagesGeneration=void 0,t.OpenAIImagesGeneration=class{openai;config={model:"dall-e-2",size:"1024x1024"};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async create(e){return(await 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 ${this.openai._apiKey}`}})).data}}},984:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAI=void 0;const r=n(a(938)),o=a(38),s=a(228),i=a(11),l=a(357);class c{_axios=r.default.create();_apiKey="";static createChatRequest(e,t={},a){return async(n,{onCancel:r})=>{const o=new c("string"==typeof e?e:await e()),s=o.createChat(),i=new AbortController;a&&a.axios&&o.setAxios(a.axios),s.setConfig("function"==typeof t?await t():t),r((()=>i.abort()));const{text:l}=await s.talk(n,{abortController:i});return l}}static createChatRequestWithJsonSchema(e){return async(t,{schema:a,onCancel:n})=>{const r=new c("string"==typeof e.apiKey?e.apiKey:await e.apiKey()),o=r.createChat(),s=new AbortController;e.config&&o.setConfig("function"==typeof e.config?await e.config():e.config),e.axios&&r.setAxios(e.axios),n((()=>s.abort()));const i=(0,l.validateToJsonSchema)(a.output),{text:u}=await o.talk(t,{abortController:s,jsonSchema:{name:"data",strict:!0,schema:i}});return u}}constructor(e=""){this._apiKey=e}setAxios(e){this._axios=e}setConfiguration(e){this._apiKey=e}createChat(){return new s.OpenAIChat(this)}createVision(){return new o.OpenAIVision(this)}createImagesGeneration(){return new i.OpenAIImagesGeneration(this)}}t.OpenAI=c},38:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIVision=void 0,t.OpenAIVision=class{openai;config={model:"gpt-4-vision-preview",maxTokens:void 0,temperature:1};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async view(e){const t=await 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 ${this.openai._apiKey}`}}),a=t.data.choices||[],n=a[0]?.message||{role:"assistant",content:""};return{id:t?.data.id,text:n.content,apiReseponse:t.data}}}},854:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.requireJsonResponseWithJsonSchema=t.requireJsonResponseWithHandlebars=t.requireJsonResponse=void 0;const r=n(a(156)),o=a(572);t.requireJsonResponse=(e,t)=>[...Array.isArray(e)?e:[e],"Please respond using the following JSON format and minify the JSON without including any explanation: ","{",Object.entries(t).map((([e,t])=>[`/* ${t.desc} */`,`"${e}": ${JSON.stringify(t.example)}`].join("\n"))).join(",\n"),"}"].join("\n"),t.requireJsonResponseWithHandlebars=(e,a,n)=>{const s=r.default.create();return s.registerHelper("DATA",(function(e){return JSON.stringify(e)})),s.registerHelper("ENV",(function(e){return this.__envs&&e?this.__envs[e]:""})),s.registerHelper("INPUT",(function(){return JSON.stringify(o.record.omit(this,["__envs"]))})),s.registerHelper("JOIN",(function(e){return Array.isArray(e)?e.join():JSON.stringify(e)})),s.compile((0,t.requireJsonResponse)(a,n))(e)},t.requireJsonResponseWithJsonSchema=(e,t)=>[...Array.isArray(e)?e:[e],"Please provide JSON data according to the following JSON Schema format:",JSON.stringify(t)].join("\n")},165:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserError=void 0,t.ParserError=class{isParserError=!0;parserFails=[];error;constructor(e,t){this.error=e,this.parserFails=t}}},357:function(e,t,a){var n=this&&this.__createBinding||(Object.create?function(e,t,a,n){void 0===n&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}:function(e,t,a,n){void 0===n&&(n=a),e[n]=t[a]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&n(t,e,a);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.validateToJsonSchema=t.defineYupSchema=t.validate=t.definedValidateSchema=void 0;const s=o(a(622)),i=a(250);t.definedValidateSchema=function(e){return e},t.validate=function(e,t){return s.object(t(s)).required().validateSync(e||{})},t.defineYupSchema=e=>e(s),t.validateToJsonSchema=e=>{const t=e=>{if(e.default&&delete e.default,e.properties)for(let a in e.properties)e.properties[a].default&&delete e.properties[a].default,t(e.properties[a]);e.items&&t(e.items)},a=e=>{if("object"===e.type){e.additionalProperties=!1;for(const t in e.properties)a(e.properties[t])}else"array"===e.type&&a(e.items)},n=(0,i.convertSchema)(s.object(e(s)));return t(n),a(n),n}},250:e=>{e.exports=require("@sodaru/yup-to-json-schema")},938:e=>{e.exports=require("axios")},4:e=>{e.exports=require("chinese-conv")},156:e=>{e.exports=require("handlebars")},865:e=>{e.exports=require("json5")},572:e=>{e.exports=require("power-helper")},622:e=>{e.exports=require("yup")}},t={};return function a(n){var r=t[n];if(void 0!==r)return r.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,a),o.exports}(665)})()));
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ctod",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "CtoD Is Chat To Data Utils.",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"scripts": {
|
|
@@ -42,24 +42,24 @@
|
|
|
42
42
|
"cross-env": "^7.0.3",
|
|
43
43
|
"eslint": "^8.25.0",
|
|
44
44
|
"eslint-webpack-plugin": "^3.2.0",
|
|
45
|
+
"esno": "^4.8.0",
|
|
45
46
|
"inquirer": "8.2.5",
|
|
46
47
|
"jsdom": "^18.1.1",
|
|
47
48
|
"mocha": "^9.1.3",
|
|
48
49
|
"nyc": "^15.1.0",
|
|
49
50
|
"ts-loader": "^9.3.1",
|
|
50
|
-
"ts-node": "^10.9.1",
|
|
51
51
|
"typescript": "^4.7.4",
|
|
52
52
|
"webpack": "^5.74.0",
|
|
53
53
|
"webpack-cli": "^4.10.0",
|
|
54
54
|
"webpack-node-externals": "^3.0.0"
|
|
55
55
|
},
|
|
56
56
|
"dependencies": {
|
|
57
|
-
"yup": "^1.4.0",
|
|
58
57
|
"@sodaru/yup-to-json-schema": "^2.0.1",
|
|
59
58
|
"axios": "^1.4.0",
|
|
60
59
|
"chinese-conv": "^1.1.0",
|
|
61
60
|
"handlebars": "^4.7.7",
|
|
62
61
|
"json5": "^2.2.3",
|
|
63
|
-
"power-helper": "^0.7.9"
|
|
62
|
+
"power-helper": "^0.7.9",
|
|
63
|
+
"yup": "^1.4.0"
|
|
64
64
|
}
|
|
65
65
|
}
|
package/examples/chat-demo.ts
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
|
|
2
|
-
/// <reference path="../lib/shims.d.ts" />
|
|
3
|
-
import { ChatBroker, OpenAI, plugins } from '../lib/index'
|
|
4
|
-
|
|
5
|
-
/**
|
|
6
|
-
* @test npx ts-node ./examples/chat-demo.ts
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
const API_KEY = ''
|
|
10
|
-
const broker = new ChatBroker({
|
|
11
|
-
input: yup => {
|
|
12
|
-
return {
|
|
13
|
-
indexs: yup.array(yup.string().required()).required(),
|
|
14
|
-
question: yup.string().required()
|
|
15
|
-
}
|
|
16
|
-
},
|
|
17
|
-
output: yup => {
|
|
18
|
-
const item = yup.object({
|
|
19
|
-
name: yup.string().required().meta({
|
|
20
|
-
jsonSchema: {
|
|
21
|
-
description: '索引名稱'
|
|
22
|
-
}
|
|
23
|
-
}),
|
|
24
|
-
score: yup.number().required().meta({
|
|
25
|
-
jsonSchema: {
|
|
26
|
-
description: '評比分數'
|
|
27
|
-
}
|
|
28
|
-
})
|
|
29
|
-
}).required()
|
|
30
|
-
return {
|
|
31
|
-
indexs: yup.array(item).required().meta({
|
|
32
|
-
jsonSchema: {
|
|
33
|
-
description: '由高到低排序的索引'
|
|
34
|
-
}
|
|
35
|
-
})
|
|
36
|
-
}
|
|
37
|
-
},
|
|
38
|
-
plugins: {
|
|
39
|
-
log: plugins.PrintLogPlugin.use({
|
|
40
|
-
detail: true
|
|
41
|
-
})
|
|
42
|
-
},
|
|
43
|
-
install({ attach }) {
|
|
44
|
-
attach('start', async({ setPreMessages }) => {
|
|
45
|
-
setPreMessages([
|
|
46
|
-
{
|
|
47
|
-
role: 'system',
|
|
48
|
-
content: '你現在是一位擅長分類索引的藥師'
|
|
49
|
-
}
|
|
50
|
-
])
|
|
51
|
-
})
|
|
52
|
-
},
|
|
53
|
-
request: OpenAI.createChatRequestWithJsonSchema({
|
|
54
|
-
apiKey: API_KEY,
|
|
55
|
-
config: {
|
|
56
|
-
model: 'gpt-4o-mini'
|
|
57
|
-
}
|
|
58
|
-
}),
|
|
59
|
-
question: async({ indexs, question }) => {
|
|
60
|
-
return [
|
|
61
|
-
'我有以下索引',
|
|
62
|
-
`${JSON.stringify(indexs)}`,
|
|
63
|
-
`請幫我解析"${question}"可能是哪個索引`,
|
|
64
|
-
'且相關性由高到低排序並給予分數,分數由 0 ~ 1'
|
|
65
|
-
]
|
|
66
|
-
}
|
|
67
|
-
})
|
|
68
|
-
|
|
69
|
-
broker.request({
|
|
70
|
-
indexs: ['胃痛', '腰痛', '頭痛', '喉嚨痛', '四肢疼痛'],
|
|
71
|
-
question: '喝咖啡,吃甜食,胃食道逆流'
|
|
72
|
-
}).then(e => {
|
|
73
|
-
console.log('輸出結果:', e.indexs)
|
|
74
|
-
/*
|
|
75
|
-
[
|
|
76
|
-
{
|
|
77
|
-
name: '胃痛',
|
|
78
|
-
score: 1
|
|
79
|
-
},
|
|
80
|
-
{
|
|
81
|
-
name: '喉嚨痛',
|
|
82
|
-
score: 0.7
|
|
83
|
-
},
|
|
84
|
-
...
|
|
85
|
-
]
|
|
86
|
-
*/
|
|
87
|
-
}).catch(error => {
|
|
88
|
-
console.error('Error:', error?.response?.data?.error?.message ?? error)
|
|
89
|
-
})
|
|
@@ -1,57 +0,0 @@
|
|
|
1
|
-
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
|
|
2
|
-
/// <reference path="../lib/shims.d.ts" />
|
|
3
|
-
import { ChatBroker, Llama3Cpp, plugins } from '../lib/index'
|
|
4
|
-
|
|
5
|
-
const gameDesignerBroker = new ChatBroker({
|
|
6
|
-
input: yup => {
|
|
7
|
-
return {
|
|
8
|
-
scene: yup.string()
|
|
9
|
-
}
|
|
10
|
-
},
|
|
11
|
-
output: yup => {
|
|
12
|
-
return {
|
|
13
|
-
next: yup.array().of(yup.string().required()).required()
|
|
14
|
-
}
|
|
15
|
-
},
|
|
16
|
-
plugins: {
|
|
17
|
-
log: plugins.PrintLogPlugin.use({
|
|
18
|
-
detail: true
|
|
19
|
-
})
|
|
20
|
-
},
|
|
21
|
-
install: ({ attach }) => {
|
|
22
|
-
attach('start', async({ setPreMessages }) => {
|
|
23
|
-
setPreMessages([
|
|
24
|
-
{
|
|
25
|
-
role: 'system',
|
|
26
|
-
content: '你現在是一個遊戲設計師'
|
|
27
|
-
},
|
|
28
|
-
{
|
|
29
|
-
role: 'user',
|
|
30
|
-
content: '我在設計一個互動式遊戲,但我現在對於劇情下一步要發生什麼事情遇到了困難'
|
|
31
|
-
},
|
|
32
|
-
{
|
|
33
|
-
role: 'assistant',
|
|
34
|
-
content: '沒問題,我來幫你想想看。'
|
|
35
|
-
}
|
|
36
|
-
])
|
|
37
|
-
})
|
|
38
|
-
},
|
|
39
|
-
/**
|
|
40
|
-
* @zh createChatRequest 可以透過 output 自動推斷出要回傳的類型,不需要再額外提供型態
|
|
41
|
-
* @en createChatRequest can infer the return type from output, no need to provide the type again
|
|
42
|
-
*/
|
|
43
|
-
request: Llama3Cpp.createChatRequest({
|
|
44
|
-
config: {
|
|
45
|
-
baseUrl: 'http://localhost:12333'
|
|
46
|
-
}
|
|
47
|
-
}),
|
|
48
|
-
question: async({ scene }) => {
|
|
49
|
-
return scene || '任意發揮'
|
|
50
|
-
}
|
|
51
|
-
})
|
|
52
|
-
|
|
53
|
-
gameDesignerBroker.request({
|
|
54
|
-
scene: '今天小紅帽遇到了大野狼,大野狼要吃掉小紅帽,小紅帽要怎麼辦?給我三個下一步要發生的事件'
|
|
55
|
-
}).then(result => {
|
|
56
|
-
console.log(result)
|
|
57
|
-
})
|
package/examples/plugin-demo.ts
DELETED
|
@@ -1,110 +0,0 @@
|
|
|
1
|
-
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
|
|
2
|
-
/// <reference path="../lib/shims.d.ts" />
|
|
3
|
-
|
|
4
|
-
import { flow } from 'power-helper'
|
|
5
|
-
import { prompt } from 'inquirer'
|
|
6
|
-
import { OpenAI, ChatBroker, plugins, ChatBrokerPlugin, templates } from '../lib'
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* @invoke npx ts-node ./examples/plugin-demo.ts
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
const API_KEY = ''
|
|
13
|
-
const characterPlugin = new ChatBrokerPlugin({
|
|
14
|
-
name: 'character',
|
|
15
|
-
params: () => {
|
|
16
|
-
return {}
|
|
17
|
-
},
|
|
18
|
-
receiveData: yup => {
|
|
19
|
-
return {
|
|
20
|
-
character: yup.string().required()
|
|
21
|
-
}
|
|
22
|
-
},
|
|
23
|
-
onInstall: ({ receive, attach }) => {
|
|
24
|
-
const characters = new Map<string, string>()
|
|
25
|
-
receive(({ id, data }) => {
|
|
26
|
-
characters.set(id, data.character)
|
|
27
|
-
})
|
|
28
|
-
attach('start', async({ id, setPreMessages }) => {
|
|
29
|
-
const character = characters.get(id)
|
|
30
|
-
setPreMessages([
|
|
31
|
-
{
|
|
32
|
-
role: 'user',
|
|
33
|
-
content: '請你扮演' + character
|
|
34
|
-
},
|
|
35
|
-
{
|
|
36
|
-
role: 'assistant',
|
|
37
|
-
content: '沒問題,我現在是' + character
|
|
38
|
-
}
|
|
39
|
-
])
|
|
40
|
-
})
|
|
41
|
-
attach('done', async({ id }) => {
|
|
42
|
-
characters.delete(id)
|
|
43
|
-
})
|
|
44
|
-
}
|
|
45
|
-
})
|
|
46
|
-
|
|
47
|
-
flow.run(async () => {
|
|
48
|
-
const { character, action } = await prompt([
|
|
49
|
-
{
|
|
50
|
-
type: 'input',
|
|
51
|
-
name: 'character',
|
|
52
|
-
message: '請輸入角色名稱.',
|
|
53
|
-
default: '派大星'
|
|
54
|
-
},
|
|
55
|
-
{
|
|
56
|
-
type: 'input',
|
|
57
|
-
name: 'action',
|
|
58
|
-
message: '你想對他問什麼?',
|
|
59
|
-
default: '你最好的朋友是誰?'
|
|
60
|
-
}
|
|
61
|
-
])
|
|
62
|
-
const broker = new ChatBroker({
|
|
63
|
-
input: yup => {
|
|
64
|
-
return {
|
|
65
|
-
action: yup.string().required(),
|
|
66
|
-
character: yup.string().required(),
|
|
67
|
-
}
|
|
68
|
-
},
|
|
69
|
-
output: yup => {
|
|
70
|
-
return {
|
|
71
|
-
message: yup.string().required()
|
|
72
|
-
}
|
|
73
|
-
},
|
|
74
|
-
plugins: {
|
|
75
|
-
character: characterPlugin.use({}),
|
|
76
|
-
print: plugins.PrintLogPlugin.use({
|
|
77
|
-
detail: false
|
|
78
|
-
})
|
|
79
|
-
},
|
|
80
|
-
install: ({ attach }) => {
|
|
81
|
-
attach('start', async({ data, plugins }) => {
|
|
82
|
-
plugins.character.send({
|
|
83
|
-
character: data.character
|
|
84
|
-
})
|
|
85
|
-
})
|
|
86
|
-
},
|
|
87
|
-
request: OpenAI.createChatRequest(API_KEY, {
|
|
88
|
-
model: 'gpt-4'
|
|
89
|
-
}),
|
|
90
|
-
question: async ({ action }) => {
|
|
91
|
-
return templates.requireJsonResponse([
|
|
92
|
-
'請基於你的角色個性,並依據以下指令進行回應:',
|
|
93
|
-
action
|
|
94
|
-
], {
|
|
95
|
-
message: {
|
|
96
|
-
desc: '回應內容',
|
|
97
|
-
example: 'string'
|
|
98
|
-
}
|
|
99
|
-
})
|
|
100
|
-
}
|
|
101
|
-
})
|
|
102
|
-
try {
|
|
103
|
-
await broker.request({
|
|
104
|
-
action,
|
|
105
|
-
character
|
|
106
|
-
})
|
|
107
|
-
} catch (error: any) {
|
|
108
|
-
console.error('Error:', error?.response?.data?.error?.message ?? error)
|
|
109
|
-
}
|
|
110
|
-
})
|
|
@@ -1,33 +0,0 @@
|
|
|
1
|
-
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
|
|
2
|
-
/// <reference path="../lib/shims.d.ts" />
|
|
3
|
-
|
|
4
|
-
import { Llama3Cpp } from '../lib/index'
|
|
5
|
-
import { flow } from 'power-helper'
|
|
6
|
-
|
|
7
|
-
flow.run(async() => {
|
|
8
|
-
const llama3Cpp = new Llama3Cpp()
|
|
9
|
-
const completion = llama3Cpp.createCompletion()
|
|
10
|
-
completion.setConfig({
|
|
11
|
-
baseUrl: 'http://localhost:12333'
|
|
12
|
-
})
|
|
13
|
-
completion.talkStream({
|
|
14
|
-
messages: [
|
|
15
|
-
{
|
|
16
|
-
role: 'user',
|
|
17
|
-
content: '你是誰'
|
|
18
|
-
}
|
|
19
|
-
],
|
|
20
|
-
onEnd: () => {
|
|
21
|
-
console.log('Is Done!')
|
|
22
|
-
},
|
|
23
|
-
onError: (error) => {
|
|
24
|
-
console.log('Error', error)
|
|
25
|
-
},
|
|
26
|
-
onWarn: (warn) => {
|
|
27
|
-
console.log('Warn', warn)
|
|
28
|
-
},
|
|
29
|
-
onMessage: (e) => {
|
|
30
|
-
console.log(e.message)
|
|
31
|
-
}
|
|
32
|
-
})
|
|
33
|
-
})
|
|
Binary file
|
package/examples/vision-demo.png
DELETED
|
Binary file
|
package/examples/vision-demo.ts
DELETED
|
@@ -1,168 +0,0 @@
|
|
|
1
|
-
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
|
|
2
|
-
/// <reference path="../lib/shims.d.ts" />
|
|
3
|
-
|
|
4
|
-
import fs from 'fs'
|
|
5
|
-
import Yup from 'yup'
|
|
6
|
-
import { flow } from 'power-helper'
|
|
7
|
-
import { prompt } from 'inquirer'
|
|
8
|
-
import { OpenAI, ChatBroker, plugins, templates } from '../lib'
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* @invoke npx ts-node ./examples/vision-demo.ts
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
const API_KEY = ''
|
|
15
|
-
const ImageUrl = 'data:image/png;base64,' + fs.readFileSync('./examples/vision-demo.png').toString('base64')
|
|
16
|
-
const ImageExUrl = 'data:image/png;base64,' + fs.readFileSync('./examples/vision-demo-ex.png').toString('base64')
|
|
17
|
-
|
|
18
|
-
flow.run(async () => {
|
|
19
|
-
const drinkRule = (yup: typeof Yup) => {
|
|
20
|
-
return yup.object({
|
|
21
|
-
name: yup.string().required(),
|
|
22
|
-
prices: yup.object({
|
|
23
|
-
M: yup.number().nullable(),
|
|
24
|
-
L: yup.number().nullable()
|
|
25
|
-
})
|
|
26
|
-
})
|
|
27
|
-
}
|
|
28
|
-
const broker = new ChatBroker({
|
|
29
|
-
input: yup => {
|
|
30
|
-
return {
|
|
31
|
-
exists: yup.array(drinkRule(yup)).required()
|
|
32
|
-
}
|
|
33
|
-
},
|
|
34
|
-
output: yup => {
|
|
35
|
-
return {
|
|
36
|
-
drinks: yup.array(drinkRule(yup)).required()
|
|
37
|
-
}
|
|
38
|
-
},
|
|
39
|
-
plugins: {
|
|
40
|
-
print: plugins.PrintLogPlugin.use({
|
|
41
|
-
detail: false
|
|
42
|
-
})
|
|
43
|
-
},
|
|
44
|
-
install: () => {
|
|
45
|
-
return null
|
|
46
|
-
},
|
|
47
|
-
request: async(messages) => {
|
|
48
|
-
const openai = new OpenAI(API_KEY)
|
|
49
|
-
const vision = openai.createVision()
|
|
50
|
-
vision.setConfig({
|
|
51
|
-
maxTokens: 4096
|
|
52
|
-
})
|
|
53
|
-
const result = await vision.view([
|
|
54
|
-
{
|
|
55
|
-
role: 'system',
|
|
56
|
-
content: '你現在是一個分析菜單的助手,你擅長從圖片中找到商品名稱與價格並歸納'
|
|
57
|
-
},
|
|
58
|
-
{
|
|
59
|
-
role: 'user',
|
|
60
|
-
content: [
|
|
61
|
-
{
|
|
62
|
-
type: 'text',
|
|
63
|
-
text: '以下是菜單的一部分,我主要需要藍色文字的商品部分,這部分你可以解讀出什麼?'
|
|
64
|
-
},
|
|
65
|
-
{
|
|
66
|
-
type: 'image_url',
|
|
67
|
-
image_url: {
|
|
68
|
-
url: ImageExUrl
|
|
69
|
-
}
|
|
70
|
-
}
|
|
71
|
-
]
|
|
72
|
-
},
|
|
73
|
-
{
|
|
74
|
-
role: 'assistant',
|
|
75
|
-
content: '我從圖片中知道熟成紅茶 中杯25元 大杯30元'
|
|
76
|
-
},
|
|
77
|
-
{
|
|
78
|
-
role: 'user',
|
|
79
|
-
content: [
|
|
80
|
-
{
|
|
81
|
-
type: 'text',
|
|
82
|
-
text: messages[0].content
|
|
83
|
-
},
|
|
84
|
-
{
|
|
85
|
-
type: 'image_url',
|
|
86
|
-
image_url: {
|
|
87
|
-
url: ImageUrl
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
]
|
|
91
|
-
}
|
|
92
|
-
])
|
|
93
|
-
return result.text
|
|
94
|
-
},
|
|
95
|
-
question: async ({ exists }) => {
|
|
96
|
-
const ex = exists.map(e => {
|
|
97
|
-
const prices = Object
|
|
98
|
-
.entries(e.prices)
|
|
99
|
-
.filter(e => e[1])
|
|
100
|
-
.map(([key, value]) => `${key}:${value}`)
|
|
101
|
-
return `* ${e.name}: ${prices.join('/')}`
|
|
102
|
-
})
|
|
103
|
-
return templates.requireJsonResponse([
|
|
104
|
-
'你的解讀完全正確,現在請幫我條列出菜單上所有商品,這個菜單中已知以下資料,你解讀的結果如果沒有以下資料代表你的解讀不對:',
|
|
105
|
-
'"""',
|
|
106
|
-
...ex,
|
|
107
|
-
'"""'
|
|
108
|
-
], {
|
|
109
|
-
drinks: {
|
|
110
|
-
desc: '商品清單,不要回傳已知商品',
|
|
111
|
-
example: [
|
|
112
|
-
{
|
|
113
|
-
name: '熟成紅茶',
|
|
114
|
-
prices: {
|
|
115
|
-
M: 25,
|
|
116
|
-
L: 30
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
]
|
|
120
|
-
}
|
|
121
|
-
})
|
|
122
|
-
}
|
|
123
|
-
})
|
|
124
|
-
try {
|
|
125
|
-
const exists = [
|
|
126
|
-
{
|
|
127
|
-
name: '熟成紅茶',
|
|
128
|
-
prices: {
|
|
129
|
-
M: 25,
|
|
130
|
-
L: 30
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
] as any[]
|
|
134
|
-
// eslint-disable-next-line no-constant-condition
|
|
135
|
-
while (true) {
|
|
136
|
-
const result = await broker.request({
|
|
137
|
-
exists
|
|
138
|
-
})
|
|
139
|
-
const keys: string[] = exists.map(e => e.name)
|
|
140
|
-
const { drinks } = await prompt([
|
|
141
|
-
{
|
|
142
|
-
type: 'checkbox',
|
|
143
|
-
name: 'drinks',
|
|
144
|
-
message: '請選擇正確的飲料',
|
|
145
|
-
choices: result.drinks.filter(e => !keys.includes(e.name)).map(e => {
|
|
146
|
-
return {
|
|
147
|
-
name: `${e.name} ${Object.entries(e.prices).map(([key, value]) => `${key}:${value}`).join(' ')}`,
|
|
148
|
-
value: e
|
|
149
|
-
}
|
|
150
|
-
})
|
|
151
|
-
},
|
|
152
|
-
])
|
|
153
|
-
exists.push(...drinks)
|
|
154
|
-
const { keep } = await prompt([
|
|
155
|
-
{
|
|
156
|
-
type: 'confirm',
|
|
157
|
-
name: 'keep',
|
|
158
|
-
message: '是否繼續?'
|
|
159
|
-
}
|
|
160
|
-
])
|
|
161
|
-
if (keep === false) {
|
|
162
|
-
break
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
} catch (error: any) {
|
|
166
|
-
console.error('Error:', error?.response?.data?.error?.message ?? error)
|
|
167
|
-
}
|
|
168
|
-
})
|