doomiaichat 7.1.30 → 7.1.32
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.esm.js +1 -0
- package/dist/index.js +1 -28
- package/dist/{aimp.d.ts → types/aimp.d.ts} +1 -0
- package/dist/types/aimp.d.ts.map +1 -0
- package/dist/{azureai.d.ts → types/azureai.d.ts} +1 -0
- package/dist/types/azureai.d.ts.map +1 -0
- package/dist/{corzauthorization.d.ts → types/corzauthorization.d.ts} +1 -0
- package/dist/types/corzauthorization.d.ts.map +1 -0
- package/dist/{corzbot.d.ts → types/corzbot.d.ts} +1 -0
- package/dist/types/corzbot.d.ts.map +1 -0
- package/dist/{declare.d.ts → types/declare.d.ts} +2 -1
- package/dist/types/declare.d.ts.map +1 -0
- package/dist/{doubaoai.d.ts → types/doubaoai.d.ts} +1 -0
- package/dist/types/doubaoai.d.ts.map +1 -0
- package/dist/{gptbase.d.ts → types/gptbase.d.ts} +1 -1
- package/dist/types/gptbase.d.ts.map +1 -0
- package/dist/{gptprovider.d.ts → types/gptprovider.d.ts} +2 -7
- package/dist/types/gptprovider.d.ts.map +1 -0
- package/dist/{index.d.ts → types/index.d.ts} +1 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/{openai.d.ts → types/openai.d.ts} +1 -0
- package/dist/types/openai.d.ts.map +1 -0
- package/dist/{openaibase.d.ts → types/openaibase.d.ts} +1 -0
- package/dist/types/openaibase.d.ts.map +1 -0
- package/dist/{openaiproxy.d.ts → types/openaiproxy.d.ts} +1 -0
- package/dist/types/openaiproxy.d.ts.map +1 -0
- package/package.json +19 -5
- package/dist/aimp.js +0 -162
- package/dist/azureai.js +0 -220
- package/dist/baiduai.d.ts +0 -28
- package/dist/baiduai.js +0 -92
- package/dist/corzauthorization.js +0 -79
- package/dist/corzbot.js +0 -490
- package/dist/declare.js +0 -51
- package/dist/deepseek.d.ts +0 -5
- package/dist/deepseek.js +0 -16
- package/dist/doubaoai.js +0 -149
- package/dist/gptbase.js +0 -58
- package/dist/gptprovider.js +0 -80
- package/dist/openai.js +0 -184
- package/dist/openaibase.js +0 -20
- package/dist/openaiprovider.d.ts +0 -20
- package/dist/openaiprovider.js +0 -43
- package/dist/openaiproxy.js +0 -108
- package/dist/stabilityai.d.ts +0 -18
- package/dist/stabilityai.js +0 -75
- package/dist/stabilityplusai.d.ts +0 -11
- package/dist/stabilityplusai.js +0 -86
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{EventEmitter as e}from"events";import t from"openai";import{CozeAPI as n,COZE_CN_BASE_URL as s,ChatStatus as i,RoleType as r,ChatEventType as o,WorkflowEventType as a,getJWTToken as c}from"@coze/api";import{parse as l}from"querystring";import u,{mkdirSync as d,createWriteStream as p}from"fs";import h,{join as m,resolve as g}from"path";import f from"axios";import{OpenAIClient as y,AzureKeyCredential as v}from"@azure/openai";import{Readable as _}from"stream";function b(e,t,n,s){return new(n||(n=Promise))(function(i,r){function o(e){try{c(s.next(e))}catch(e){r(e)}}function a(e){try{c(s.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}function x(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],s=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function O(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=x(e),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(n){t[n]=e[n]&&function(t){return new Promise(function(s,i){(function(e,t,n,s){Promise.resolve(s).then(function(t){e({value:t,done:n})},t)})(s,i,(t=e[n](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;class k extends e{constructor(){super()}getTextEmbedding(e,t){return null}createCoversation(e){return b(this,void 0,void 0,function*(){return null})}setVariables(e){return b(this,void 0,void 0,function*(){return{successed:!0}})}getVariables(e){return b(this,void 0,void 0,function*(){return{successed:!1}})}chatRequestInStream(e,t,n,s){return null}}var w=Object.freeze({__proto__:null,default:k});class q extends k{constructor(e,t={}){super(),this.apiKey=e,this.chatModel=t.model||"gpt-3.5-turbo",this.maxtoken=t.maxtoken||2048,this.top_p=t.top_p||.95,this.temperature=t.temperature||.9,this.presence_penalty=t.presence_penalty||0,this.frequency_penalty=t.frequency_penalty||0,this.embeddingmodel=t.embedding||"text-embedding-ada-002"}}class S extends q{createOpenAI(e){return new t({apiKey:e})}getTextEmbedding(e,t){return b(this,void 0,void 0,function*(){if(!e)return{successed:!1,error:{errcode:2,errmsg:"content required"}};this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));try{return{successed:!0,embedding:(yield this.aiApi.embeddings.create({model:this.embeddingmodel,input:e},t)).data.data}}catch(e){return{successed:!1,error:e}}})}chatRequest(e,t){return b(this,arguments,void 0,function*(e,t,n={}){if(!e)return{successed:!1,error:{errcode:2,errmsg:"缺失聊天的内容"}};this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));let s="string"==typeof e?[{role:"user",content:e}]:e;try{const e=yield this.aiApi.chat.completions.create({model:(null==t?void 0:t.model)||this.chatModel,messages:s,temperature:Number((null==t?void 0:t.temperature)||this.temperature),max_tokens:Number((null==t?void 0:t.maxtoken)||this.maxtoken),top_p:Number((null==t?void 0:t.top_p)||this.top_p),presence_penalty:Number((null==t?void 0:t.presence_penalty)||this.presence_penalty),frequency_penalty:Number((null==t?void 0:t.frequency_penalty)||this.frequency_penalty),n:Number((null==t?void 0:t.replyCounts)||1)||1},n);return{successed:!0,message:e.choices,usage:e.usage}}catch(e){return console.log("result is error ",e),{successed:!1,error:e}}})}chatRequestInStream(e,t,n,s){return b(this,void 0,void 0,function*(){var i,r,o,a;e||this.emit("chaterror",{successed:!1,error:"no text in chat"}),this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));let c="string"==typeof e?[{role:"user",content:e}]:e;s=Object.assign({},s||{timeout:6e4});let l=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3);try{const e=yield this.aiApi.chat.completions.create({model:(null==t?void 0:t.model)||this.chatModel,messages:c,temperature:Number((null==t?void 0:t.temperature)||this.temperature),max_tokens:Number((null==t?void 0:t.maxtoken)||this.maxtoken),top_p:Number((null==t?void 0:t.top_p)||this.top_p),presence_penalty:Number((null==t?void 0:t.presence_penalty)||this.presence_penalty),frequency_penalty:Number((null==t?void 0:t.frequency_penalty)||this.frequency_penalty),n:Number((null==t?void 0:t.replyCounts)||1)||1,tools:1===(null==t?void 0:t.enableToolCall)&&(null==t?void 0:t.tools)?t.tools:void 0,tool_choice:1===(null==t?void 0:t.enableToolCall)?"auto":void 0,stream:!0},s);let h,m=[],g=0,f=-1,y=[];try{for(var u,d=!0,p=O(e);!(i=(u=yield p.next()).done);d=!0){a=u.value,d=!1;const e=a,[t]=e.choices,{finish_reason:s,index:i,usage:r}=t,{content:o,tool_calls:c}=t.delta;c&&c.length?(h=c[0].index,g=1,h!==f?(y.push({id:c[0].id,type:"function",function:{name:c[0].function.name,arguments:c[0].function.arguments}}),f=h):y[f].function.arguments+=c[0].function.arguments):m.push(o);let p={successed:!0,requestid:l,segment:o,text:m.join(""),finish_reason:s,index:i,usage:r,has_tool_calls:g,tool_calls:y};n&&(p=Object.assign({},p,n)),this.emit(s?"chatdone":"chattext",p)}}catch(e){r={error:e}}finally{try{d||i||!(o=p.return)||(yield o.call(p))}finally{if(r)throw r.error}}return{successed:!0,requestid:l}}catch(e){return this.emit("requesterror",{successed:!1,requestid:l,error:"call axios faied "+e}),{successed:!1,requestid:l}}})}}const T={thinking:{start:"<xiaolu-think>",end:"</xiaolu-think>",tag:"xiaolu-think"},reasoning:{start:"<xiaolu-reason>",end:"</xiaolu-reason>",tag:"xiaolu-reason"},card:{start:"<xiaolu-card>",end:"</xiaolu-card>",tag:"xiaolu-card"},preresponse:{start:"<xiaolu-preresponse>",end:"</xiaolu-preresponse>",tag:"xiaolu-preresponse"}};var N;!function(e){e[e.None=0]="None",e[e.Thinking=1]="Thinking",e[e.ThinkingOver=2]="ThinkingOver"}(N||(N={}));class A extends k{constructor(e,t={}){if(super(),this.authorizationProvider=e,this.setting=t,this.botid=null,this.workflowid=null,this.talkflowid=null,this.debugDir="",this.debug=!1,this.setting.workflowid)this.workflowid=this.setting.workflowid;else if(this.setting.talkflowid)this.talkflowid=this.setting.talkflowid;else{if(!this.setting.botid&&!this.setting.botID)throw new Error("no botid or talkflowid or workflowid setting for coze");this.botid=this.setting.botid||this.setting.botID}!0===t.debug&&(this.debug=!0,this.debugDir=m(t.logPath||g(process.cwd(),"./cozedebug"),this.setting.model||"chat"),d(this.debugDir,{recursive:!0})),this.apiKey=this.setting.apiKey}createClient(){return b(this,void 0,void 0,function*(){if(this.apiKey)return new n({baseURL:s,token:this.apiKey});const e=yield this.authorizationProvider.getAccessToken();if(!e)throw new Error("get access token failed");return new n({baseURL:s,token:e})})}createCoversation(e){return b(this,void 0,void 0,function*(){try{const t=null!=e?e:yield this.createClient(),n=this.botid?{bot_id:this.botid}:{};return(yield t.conversations.create(n)).id}catch(e){return console.error("createCoversation error in coze api"),null}})}setVariables(){return b(this,arguments,void 0,function*(e={}){const t=yield this.createClient();!e.type&&(e.type="app");const n={data:e.data};"app"===e.type&&(n.app_id=this.authorizationProvider.appid),"bot"===e.type&&this.botid&&(n.bot_id=this.botid),e.user_id&&(n.connector_uid=e.user_id);const s=yield t.variables.update(n,{debug:!0});return console.log("setVariables result",s),{successed:!0}})}getVariables(e){return b(this,void 0,void 0,function*(){const t=yield this.createClient(),n=Object.assign({},{bot_id:this.botid},e),s=yield t.variables.retrieve(n);return s?Object.assign({successed:!0},s):{successed:!1,error:"get variables failed"}})}getRequestStream(e,t){return b(this,arguments,void 0,function*(e,t,n={}){var s,i;if(this.botid){const i={bot_id:this.botid,additional_messages:t,user_id:n.userid||n.cozeUserID,conversation_id:null!==(s=n.session_id)&&void 0!==s?s:yield this.createCoversation(e),parameters:Object.assign({request_src:1},n.parameters||{})};return i.custom_variables=Object.assign({},this.setting.customVariables||{},n.customVariables||{}),i}if(this.workflowid){const e={ext:n.ext,workflow_id:this.workflowid,is_async:!1,parameters:Object.assign({request_src:1},n.parameters||{},{input:t})};return(n.userid||n.cozeUserID)&&(e.ext=Object.assign({},e.ext||{},{user_id:n.userid||n.cozeUserID})),e}const r={additional_messages:t,ext:{user_id:"12345678"},workflow_id:this.talkflowid,conversation_id:null!==(i=n.session_id)&&void 0!==i?i:yield this.createCoversation(e),parameters:Object.assign({request_src:1},n.parameters||{})};return(n.userid||n.cozeUserID)&&(r.ext=Object.assign({},r.ext||{},{user_id:n.userid||n.cozeUserID})),r})}getChatDetail(e,t,n){return b(this,void 0,void 0,function*(){const s=Date.now();for(;Date.now()-s<12e4;){const s=yield e.chat.retrieve(t,n);if(s.status===i.COMPLETED)return{usage:s.usage,messages:yield e.chat.messages.list(t,n)};yield new Promise(e=>setTimeout(e,1500))}return null})}chatRequest(e){return b(this,arguments,void 0,function*(e,t={},n={}){e||this.emit("chaterror",{successed:!1,error:"no message in chat"}),"string"==typeof e&&(e=[{role:r.User,content_type:"text",content:e}]);const s=yield this.createClient(),i=this.debug?p(m(this.debugDir,`sync_${this.formatDateWithMs()}.log`),{flags:"a"}):null,o=yield this.getRequestStream(s,e,t);i&&(i.write(`callChatOption:${JSON.stringify(t)}\n`),i.write(`parameters:${JSON.stringify(o)}\n`));const a=this.botid?yield s.chat.create(o):yield s.workflows.runs.create(o);if(this.workflowid){const e=a;if("Success"===e.msg||!e.msg&&e.data){const t=e.data;return i&&i.end(t),{successed:!0,message:[{role:"assistant",type:"answer",content:t}]}}i&&i.end("workflow run failed"),console.error("workflow run failed",e.msg,e)}if(!this.workflowid&&a.conversation_id&&a.id){const e=a,t=yield this.getChatDetail(s,e.conversation_id,e.id);if(t){return{successed:!0,message:t.messages.filter(e=>"answer"===e.type).map(e=>({role:e.role,type:e.type,content:e.content})),usage:t.usage,session_id:e.conversation_id}}}return i&&i.end("聊天未完成"),{successed:!1,error:{message:"聊天未完成"}}})}extractXmlContent(e,t){const n=new RegExp(`<\\s*${t}\\s*>([\\s\\S]*?)<\\s*\\/\\s*${t}\\s*>`,"i"),s=e.match(n);return s&&s[1]?s[1].trim():""}parseDeepThinkingJson(e){const t=[e.indexOf(T.thinking.start),e.indexOf(T.reasoning.start),e.indexOf(T.card.start),e.indexOf(T.preresponse.start)];let n=1e4,s=-1;t.forEach((e,t)=>{e>=0&&e<n&&(n=e,s=t)});const i=s>=0?n:-1;if(i<0)return{content:e,status:N.ThinkingOver};const r=[T.thinking,T.reasoning,T.card,T.preresponse][s],o=e.indexOf(r.end,i),a=o>=0?o:e.indexOf("</",i),c=this.extractXmlContent(e.substring(i,a>=0?a:void 0)+r.end,r.tag);return o>=0&&(e=e.substring(o+r.end.length)),{thinking:{action:r,text:c,completed:o>=0},content:e}}formatDateWithMs(e=new Date){return`${e.getFullYear()}${String(e.getMonth()+1).padStart(2,"0")}${String(e.getDate()).padStart(2,"0")}${String(e.getHours()).padStart(2,"0")}${String(e.getMinutes()).padStart(2,"0")}${String(e.getSeconds()).padStart(2,"0")}${String(e.getMilliseconds()).padStart(3,"0")}`}chatRequestInStream(e){return b(this,arguments,void 0,function*(e,t={},n,s){var i,c,u,d,h,g,f;e||this.emit("chaterror",{successed:!1,error:"no message in chat"}),"string"==typeof e&&(e=[{role:r.User,content_type:"text",content:e}]);const y=yield this.createClient();let v=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3),_=0;const b=this.debug?p(m(this.debugDir,`${this.formatDateWithMs()}.log`),{flags:"a"}):null,x=yield this.getRequestStream(y,e,t);b&&(b.write(`callChatOption:${JSON.stringify(t)}\n`),b.write(`attach:${n?JSON.stringify(n):"null"}\n`),b.write(`parameters:${JSON.stringify(x)}\n`));const k=this.botid?y.chat.stream(x):this.workflowid?y.workflows.runs.stream(x):y.workflows.chat.stream(x);let w=0,q=[],S=[],A=[],C=[],E="",j=N.None,R="",D="";try{for(var I,M=!0,z=O(k);!(i=(I=yield z.next()).done);M=!0){d=I.value,M=!1;const e=d;if(e.event===o.ERROR)return b&&b.write("chat error:"),this.emit("chaterror",{successed:!1,error:"call failed"});if(e.event===o.CONVERSATION_MESSAGE_DELTA||e.event===a.MESSAGE){let{conversation_id:t,content_type:s,type:i="answer",role:r="assistant",content:o,reasoning_content:a}=e.data;if(b&&b.write(o),"Default"===o)continue;if(!o&&a){this.emit("chatthinking",{text:a,completed:!1,action:"deep-thinking"});continue}if(0===w&&o.startsWith("<xiaolu-")&&(j=N.Thinking,w++),j===N.Thinking){E+=o;const e=this.parseDeepThinkingJson(E),a=e.thinking;if(a)if(E=e.content,a.action===T.card){if(R+=e.thinking.text,e.thinking.completed){const e=R.replace(/[\x00-\x1F\x7F]/g,"").split("|");R="";for(const t of e){const e=l(t);if(e.type&&e.tag)if("follow_up"===e.type)S.push(e.tag);else{const t=e.tag.split(",");for(const n of t)C.push({type:e.type,tag:n})}}this.emit("chatcard",C)}}else if(a.action===T.preresponse){const o=e.thinking.text.slice(D.length);D=e.thinking.text,q.push(o);let a={successed:!0,type:i,content_type:s,role:r,requestid:v,segment:o,text:q.join(""),index:_++,session_id:t,preresponse:!0,preresponseover:e.thinking.completed};n&&(a=Object.assign({},a,n)),this.emit("chattext",a)}else this.emit("chatthinking",{text:e.thinking.text,completed:e.thinking.completed,action:null===(h=a.action)||void 0===h?void 0:h.tag});if(e.status!=N.ThinkingOver)continue;j=N.ThinkingOver,o=E}q.push(o);let c={successed:!0,type:i,content_type:s,role:r,requestid:v,segment:o,text:q.join(""),index:_++,session_id:t};n&&(c=Object.assign({},c,n)),this.emit("chattext",c)}if(e.event===o.CONVERSATION_MESSAGE_COMPLETED){const{type:t,content:n}=null!==(g=e.data)&&void 0!==g?g:{};"follow_up"===t&&(b&&b.write("followup:"+n),A.push(n))}if(e.event===o.CONVERSATION_CHAT_COMPLETED||e.event===a.DONE){const{conversation_id:t,content:s}=null!==(f=e.data)&&void 0!==f?f:{};let i={successed:!0,cards:C.length?C:null,cardfollowup:S.filter(e=>"string"==typeof e&&e.length>0),followup:A,type:"answer",content_type:"text",role:r.Assistant,requestid:v,segment:null,text:null!=s?s:q.join(""),index:_++,session_id:t};n&&(i=Object.assign({},i,n)),b&&b.end("chat completed"),this.emit("chatdone",i)}}}catch(e){c={error:e}}finally{try{M||i||!(u=z.return)||(yield u.call(z))}finally{if(c)throw c.error}}return{successed:!0,requestid:v}})}}const C=["[AUTHORIZATION NEEDED]","[AUTHORIZATION ERROR]","[BODY ERROR]","[REQUEST ERROR]"];class E extends S{constructor(e,t,n={}){super(e,n),this.proxySetting=t}chatRequest(e,t,n){return b(this,void 0,void 0,function*(){const s=Object.assign({headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apiKey}`},method:"post",url:this.proxySetting.serviceurl,data:{chatText:e,option:t}},n);return(yield f(s)).data})}chatRequestInStream(e,t,n,s){return b(this,void 0,void 0,function*(){let i,r=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3);const o={headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apiKey}`},method:"post",url:this.proxySetting.serviceurl+"/stream",data:{messages:e,option:t,axiosOption:s},responseType:"stream"};let a="";f(o).then(e=>{e.data.on("data",e=>{if(i=e.toString(),i){if(C.includes(i))return this.emit("requesterror",{successed:!1,requestid:r,error:"Request Remote OpenAI Error : "+i});const e=(a+i).split("*&$");a="";for(const t of e)if(t)try{if(!t.endsWith("}")){a=t;break}const e=Object.assign(JSON.parse(t),n);this.emit(e.finish_reason?"chatdone":"chattext",e)}catch(e){break}}})}).catch(e=>{this.emit("requesterror",{successed:!1,requestid:r,error:"Axios Error : "+e})})})}}class j extends q{constructor(e,t,n={}){super(e,n),this.azureSetting=t,this.azureSetting.endpoint.toLowerCase().startsWith("https://")||(this.azureSetting.endpoint="https://"+this.azureSetting.endpoint)}createOpenAI(e){return new y(this.azureSetting.endpoint,new v(e))}get EmbeddingUrl(){return`${this.azureSetting.endpoint}/openai/deployments/${this.embeddingmodel||"openai-embedding-ada-002"}/embeddings?api-version=2022-12-01`}getTextEmbedding(e){return b(this,arguments,void 0,function*(e,t={}){if(!e)return{successed:!1,error:{errcode:2,errmsg:"content required"}};this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));try{return{successed:!0,embedding:(yield this.aiApi.getEmbeddings(this.embeddingmodel||"openai-embedding-ada-002","string"==typeof e?[e]:e,t)).data}}catch(e){return{successed:!1,error:e}}})}chatRequest(e,t){return b(this,arguments,void 0,function*(e,t,n={}){if(!e)return{successed:!1,error:{errcode:2,errmsg:"缺失聊天的内容"}};this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));let s="string"==typeof e?[{role:"user",content:e}]:e;try{const e=yield this.aiApi.getChatCompletions((null==t?void 0:t.model)||this.chatModel,s,{temperature:Number((null==t?void 0:t.temperature)||this.temperature),maxTokens:Number((null==t?void 0:t.maxtoken)||this.maxtoken),topP:Number((null==t?void 0:t.top_p)||this.top_p),presencePenalty:Number((null==t?void 0:t.presence_penalty)||this.presence_penalty),frequencyPenalty:Number((null==t?void 0:t.frequency_penalty)||this.frequency_penalty),n:Number((null==t?void 0:t.replyCounts)||1)||1,tools:1===(null==t?void 0:t.enableToolCall)&&(null==t?void 0:t.tools)?t.tools:void 0,toolChoice:1===(null==t?void 0:t.enableToolCall)?"auto":void 0}),{promptTokens:n,completionTokens:i,totalTokens:r}=e.usage;let o=[];for(const t of e.choices){const{index:e,finishReason:n,message:s}=t;o.push({index:e,finish_reason:n,message:s})}return{successed:!0,message:o,usage:{prompt_tokens:n,completion_tokens:i,total_tokens:r}}}catch(e){return console.log("result is error ",e),{successed:!1,error:e}}})}chatRequestInStream(e,t,n,s){return b(this,void 0,void 0,function*(){var i,r,o,a,c,l,u;e||this.emit("chaterror",{successed:!1,error:"no text in chat"}),this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));let d="string"==typeof e?[{role:"user",content:e}]:e;s=Object.assign({},s||{timeout:6e4});let p,h=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3),m=0,g=-1,f=[];try{const e=yield this.aiApi.streamChatCompletions((null==t?void 0:t.model)||this.chatModel,d,{temperature:Number((null==t?void 0:t.temperature)||this.temperature),maxTokens:Number((null==t?void 0:t.maxtoken)||this.maxtoken),topP:Number((null==t?void 0:t.top_p)||this.top_p),presencePenalty:Number((null==t?void 0:t.presence_penalty)||this.presence_penalty),frequencyPenalty:Number((null==t?void 0:t.frequency_penalty)||this.frequency_penalty),n:Number((null==t?void 0:t.replyCounts)||1)||1,tools:1===(null==t?void 0:t.enableToolCall)&&(null==t?void 0:t.tools)?t.tools:void 0,toolChoice:1===(null==t?void 0:t.enableToolCall)?"auto":void 0});let s=[];try{for(var y,v=!0,_=O(e);!(i=(y=yield _.next()).done);v=!0){a=y.value,v=!1;const e=a;for(const t of e.choices){const{finishReason:e,index:i}=t,r=null===(c=t.delta)||void 0===c?void 0:c.toolCalls;if(r&&r.length)p=r[0].index,m=1,p!==g?(f.push({id:r[0].id,type:"function",function:{name:r[0].function.name,arguments:r[0].function.arguments}}),g=p):f[g].function.arguments+=r[0].function.arguments;else{const e=null===(l=t.delta)||void 0===l?void 0:l.content;s.push(e)}let o={successed:!0,requestid:h,segment:null===(u=t.delta)||void 0===u?void 0:u.content,text:s.join(""),finish_reason:e,index:i,has_tool_calls:m,tool_calls:f};n&&(o=Object.assign({},o,n)),this.emit(e?"chatdone":"chattext",o)}}}catch(e){r={error:e}}finally{try{v||i||!(o=_.return)||(yield o.call(_))}finally{if(r)throw r.error}}return{successed:!0,requestid:h}}catch(e){return this.emit("requesterror",{successed:!1,requestid:h,error:"call axios faied "+e}),{successed:!1,requestid:h}}})}}function R(){return b(this,arguments,void 0,function*(e={}){e.data||(e.data=e.body);try{return{successed:!0,data:(yield f(e)).data}}catch(e){return{successed:!1,error:e,data:e}}})}class D extends k{constructor(e,t){super(),this.apikey=e,this.agent=t}chatRequest(e,t){return b(this,arguments,void 0,function*(e,t,n={}){var s;if(!e)return{successed:!1,error:"no text in chat"};const i="object"==typeof e?null!==(s=e.text)&&void 0!==s?s:e.content:e;n=Object.assign({},n||{timeout:6e4});const r=Object.assign({headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apikey}`},method:"post",url:`${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`,data:{question:i,session_id:t.session_id,optional:t.optional,stream:!1}},n),o=yield R(r);if(!o.successed||o.data.code)return{successed:!1,error:"failed"};const{answer:a,session_id:c}=o.data.data;return{successed:!0,message:[{message:{content:a}}],session_id:c}})}chatRequestInStream(e,t,n,s){return b(this,void 0,void 0,function*(){var i,r,o,a,c;e||this.emit("chaterror",{successed:!1,error:"no text in chat"});const l="object"==typeof e?null!==(c=e.text)&&void 0!==c?c:e.content:e;s=Object.assign({},s||{timeout:6e4});let u=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3);try{const e=Object.assign({headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apikey}`},method:"post",url:`${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`,data:{question:l,session_id:t.session_id,stream:!0,optional:t.optional},responseType:"stream"},s),c=yield f(e),m=_.from(c.data);let g,y=0,v="",b=[],x=[];try{for(var d,p=!0,h=O(m);!(i=(d=yield h.next()).done);p=!0){a=d.value,p=!1;const e=a;let t=null,s="";try{s=e.toString().split("data:"),s.length&&(s=s[s.length-1]+""),t=JSON.parse(b.join("")+s)}catch(e){b.push(s);continue}b=[];const{answer:i,running_status:r,reference:o}=t.data;if(!0===r)continue;const c=i?i.replace(v,""):"";v=null!=i?i:v,g||(g=t.data.session_id),o&&o.chunks&&o.chunks.length&&(x=x.concat(o.chunks));const l=!0===t.data;let h={successed:!0,requestid:u,segment:c,chunks:x,text:v,finish_reason:l?"stop":null,index:y++,session_id:g};n&&(h=Object.assign({},h,n)),this.emit(l?"chatdone":"chattext",h)}}catch(e){r={error:e}}finally{try{p||i||!(o=h.return)||(yield o.call(h))}finally{if(r)throw r.error}}return{successed:!0,requestid:u}}catch(e){}})}}class I extends k{constructor(e,t={}){super(),this.apiOption={},this.apiKey=e,this.apiOption=t}chatRequest(e,t){return b(this,arguments,void 0,function*(e,t,n={}){if(!e)return{successed:!1,error:{errcode:2,errmsg:"缺失聊天的内容"}};const s=this.assembleApiParams(e,!1,t,n);try{const e=yield R(s);return e.successed&&!e.data.code?{successed:!0,message:e.data.choices,usage:e.data.usage}:Object.assign({successed:!1},e.data)}catch(e){return console.log("result is error ",e),{successed:!1,error:e}}})}assembleApiParams(e,t=!1,n,s={}){let i="string"==typeof e?[{role:"user",content:e}]:e,r={};((null==n?void 0:n.temperature)||this.apiOption.temperature)&&(r.temperature=Number((null==n?void 0:n.temperature)||this.apiOption.temperature)),r.max_tokens=Number((null==n?void 0:n.maxtoken)||this.apiOption.maxtoken),((null==n?void 0:n.top_p)||this.apiOption.top_p)&&(r.top_p=Number((null==n?void 0:n.top_p)||this.apiOption.top_p)),((null==n?void 0:n.presence_penalty)||this.apiOption.presence_penalty)&&(r.presence_penalty=Number((null==n?void 0:n.presence_penalty)||this.apiOption.presence_penalty)),((null==n?void 0:n.frequency_penalty)||this.apiOption.frequency_penalty)&&(r.frequency_penalty=Number((null==n?void 0:n.frequency_penalty)||this.apiOption.frequency_penalty)),((null==n?void 0:n.top_logprobs)||this.apiOption.top_logprobs)&&(r.logprobs=!0,r.top_logprobs=Number((null==n?void 0:n.top_logprobs)||this.apiOption.top_logprobs)),r.tools=1===(null==n?void 0:n.enableToolCall)&&(null==n?void 0:n.tools)?n.tools:void 0,r.tool_choice=1===(null==n?void 0:n.enableToolCall)?"auto":void 0;const o=Object.assign(Object.assign({},s),{method:"post",headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apiKey}`},data:Object.assign(Object.assign({model:(null==n?void 0:n.model)||this.apiOption.model},r),{messages:i,stream:t}),url:"https://ark.cn-beijing.volces.com/api/v3/chat/completions"});return t&&(o.responseType="stream"),o}chatRequestInStream(e,t,n,s){return b(this,void 0,void 0,function*(){e||this.emit("chaterror",{successed:!1,error:"no text in chat"}),s=Object.assign({},s||{timeout:1e4});const i=this.assembleApiParams(e,!0,t,s);let r=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3),o=[];try{return function(e={},t){e.data||(e.data=e.body),f(e).then(e=>{e.data.on("data",e=>{t(e)})})}(i,e=>{let t=e.toString().replace("[DONE]","").replace(/[\r\n]+/gm,"");this.processChunkData(t.split(/data: /),r,o,n)}),{successed:!0,requestid:r}}catch(e){return this.emit("requesterror",{successed:!1,requestid:r,error:"call axios faied "+e}),{successed:!1,requestid:r}}})}processChunkData(e,t,n,s){let i,r=0,o=-1,a=[];for(const c of e){if(!c)continue;const e=JSON.parse(c),[l]=e.choices,{finish_reason:u,index:d,usage:p}=l,{content:h,tool_calls:m}=l.delta;m&&m.length?(i=m[0].index,r=1,i!==o?(a.push({id:m[0].id,type:"function",function:{name:m[0].function.name,arguments:m[0].function.arguments}}),o=i):a[o].function.arguments+=m[0].function.arguments):n.push(h);let g={successed:!0,requestid:t,segment:h,text:n.join(""),finish_reason:u,index:d,usage:p,has_tool_calls:r,tool_calls:a};s&&(g=Object.assign({},g,s)),this.emit(u?"chatdone":"chattext",g)}}}class M{constructor(e,t){this.appid=e,this.expiresAt=0,this.secret=t.keyid,this.pemfile=t.pemfile||"private.pem",this.sessionName=t.sessionName||"default"}getAccessToken(){return b(this,void 0,void 0,function*(){if(this.accessToken&&Date.now()<this.expiresAt)return this.accessToken;const e=yield this.doAuthorize();return e.successed?(this.accessToken=e.accessToken,this.expiresAt=1e3*e.expires_in,this.accessToken):null})}doAuthorize(){return b(this,void 0,void 0,function*(){try{const e="api.coze.cn",t=h.join(process.cwd(),this.pemfile);if(!u.existsSync(t))return{successed:!1,error:`${t} not existed`};const n=u.readFileSync(t).toString(),i=yield c({baseURL:s,appId:this.appid,aud:e,keyid:this.secret,privateKey:n,sessionName:this.sessionName});return{successed:!0,accessToken:i.access_token,expires_in:i.expires_in}}catch(e){return{successed:!0,error:e}}})}}const z=new Map,P={OPENAI:"openai",OPENAIPROXY:"openaiproxy",MICROSOFT:"microsoft",AIMP:"aimp",COZE:"coze",DOUBAO:"doubao"};var $=Object.freeze({__proto__:null,GptProviderEnum:P,createGpt:function(e,t,n){let{model:s,agentid:i,maxtoken:r,temperature:o,serviceurl:a,endpoint:c,engine:l,version:u,embedding:d,top_p:p,presence_penalty:h,frequency_penalty:m}=n||{};switch(e){case P.OPENAI:return new S(t+"",{model:s,maxtoken:r,temperature:o,embedding:d,top_p:p,presence_penalty:h,frequency_penalty:m});case P.OPENAIPROXY:return new E(t+"",{serviceurl:a},{model:s,maxtoken:r,temperature:o,embedding:d,top_p:p,presence_penalty:h,frequency_penalty:m});case P.MICROSOFT:return new j(t+"",{endpoint:c,engine:l,version:u},{model:s,maxtoken:r,temperature:o,embedding:d,top_p:p,presence_penalty:h,frequency_penalty:m});case P.AIMP:return new D(t+"",{endpoint:c,agentid:i});case P.COZE:let e=z.get(t+"");return e||(e=new M(t+"",n),z.set(t+"",e)),new A(e,n);case P.DOUBAO:return new I(t+"",{model:s,maxtoken:r,temperature:o,top_p:p,presence_penalty:h,frequency_penalty:m});default:return null}}});export{w as GptBase,$ as GptFactory};
|
package/dist/index.js
CHANGED
|
@@ -1,28 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
-
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
-
}) : function(o, v) {
|
|
16
|
-
o["default"] = v;
|
|
17
|
-
});
|
|
18
|
-
var __importStar = (this && this.__importStar) || function (mod) {
|
|
19
|
-
if (mod && mod.__esModule) return mod;
|
|
20
|
-
var result = {};
|
|
21
|
-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
|
22
|
-
__setModuleDefault(result, mod);
|
|
23
|
-
return result;
|
|
24
|
-
};
|
|
25
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
26
|
-
exports.GptBase = exports.GptFactory = void 0;
|
|
27
|
-
exports.GptFactory = __importStar(require("./gptprovider"));
|
|
28
|
-
exports.GptBase = __importStar(require("./gptbase"));
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("events"),t=require("openai"),n=require("@coze/api"),s=require("querystring"),i=require("fs"),r=require("path"),o=require("axios"),a=require("@azure/openai"),c=require("stream");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var u=l(t),d=l(i),p=l(r),h=l(o);function m(e,t,n,s){return new(n||(n=Promise))(function(i,r){function o(e){try{c(s.next(e))}catch(e){r(e)}}function a(e){try{c(s.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}function g(e){var t="function"==typeof Symbol&&Symbol.iterator,n=t&&e[t],s=0;if(n)return n.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&s>=e.length&&(e=void 0),{value:e&&e[s++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function f(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,n=e[Symbol.asyncIterator];return n?n.call(e):(e=g(e),t={},s("next"),s("throw"),s("return"),t[Symbol.asyncIterator]=function(){return this},t);function s(n){t[n]=e[n]&&function(t){return new Promise(function(s,i){(function(e,t,n,s){Promise.resolve(s).then(function(t){e({value:t,done:n})},t)})(s,i,(t=e[n](t)).done,t.value)})}}}"function"==typeof SuppressedError&&SuppressedError;class y extends e.EventEmitter{constructor(){super()}getTextEmbedding(e,t){return null}createCoversation(e){return m(this,void 0,void 0,function*(){return null})}setVariables(e){return m(this,void 0,void 0,function*(){return{successed:!0}})}getVariables(e){return m(this,void 0,void 0,function*(){return{successed:!1}})}chatRequestInStream(e,t,n,s){return null}}var v=Object.freeze({__proto__:null,default:y});class _ extends y{constructor(e,t={}){super(),this.apiKey=e,this.chatModel=t.model||"gpt-3.5-turbo",this.maxtoken=t.maxtoken||2048,this.top_p=t.top_p||.95,this.temperature=t.temperature||.9,this.presence_penalty=t.presence_penalty||0,this.frequency_penalty=t.frequency_penalty||0,this.embeddingmodel=t.embedding||"text-embedding-ada-002"}}class b extends _{createOpenAI(e){return new u.default({apiKey:e})}getTextEmbedding(e,t){return m(this,void 0,void 0,function*(){if(!e)return{successed:!1,error:{errcode:2,errmsg:"content required"}};this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));try{return{successed:!0,embedding:(yield this.aiApi.embeddings.create({model:this.embeddingmodel,input:e},t)).data.data}}catch(e){return{successed:!1,error:e}}})}chatRequest(e,t){return m(this,arguments,void 0,function*(e,t,n={}){if(!e)return{successed:!1,error:{errcode:2,errmsg:"缺失聊天的内容"}};this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));let s="string"==typeof e?[{role:"user",content:e}]:e;try{const e=yield this.aiApi.chat.completions.create({model:(null==t?void 0:t.model)||this.chatModel,messages:s,temperature:Number((null==t?void 0:t.temperature)||this.temperature),max_tokens:Number((null==t?void 0:t.maxtoken)||this.maxtoken),top_p:Number((null==t?void 0:t.top_p)||this.top_p),presence_penalty:Number((null==t?void 0:t.presence_penalty)||this.presence_penalty),frequency_penalty:Number((null==t?void 0:t.frequency_penalty)||this.frequency_penalty),n:Number((null==t?void 0:t.replyCounts)||1)||1},n);return{successed:!0,message:e.choices,usage:e.usage}}catch(e){return console.log("result is error ",e),{successed:!1,error:e}}})}chatRequestInStream(e,t,n,s){return m(this,void 0,void 0,function*(){var i,r,o,a;e||this.emit("chaterror",{successed:!1,error:"no text in chat"}),this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));let c="string"==typeof e?[{role:"user",content:e}]:e;s=Object.assign({},s||{timeout:6e4});let l=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3);try{const e=yield this.aiApi.chat.completions.create({model:(null==t?void 0:t.model)||this.chatModel,messages:c,temperature:Number((null==t?void 0:t.temperature)||this.temperature),max_tokens:Number((null==t?void 0:t.maxtoken)||this.maxtoken),top_p:Number((null==t?void 0:t.top_p)||this.top_p),presence_penalty:Number((null==t?void 0:t.presence_penalty)||this.presence_penalty),frequency_penalty:Number((null==t?void 0:t.frequency_penalty)||this.frequency_penalty),n:Number((null==t?void 0:t.replyCounts)||1)||1,tools:1===(null==t?void 0:t.enableToolCall)&&(null==t?void 0:t.tools)?t.tools:void 0,tool_choice:1===(null==t?void 0:t.enableToolCall)?"auto":void 0,stream:!0},s);let h,m=[],g=0,y=-1,v=[];try{for(var u,d=!0,p=f(e);!(i=(u=yield p.next()).done);d=!0){a=u.value,d=!1;const e=a,[t]=e.choices,{finish_reason:s,index:i,usage:r}=t,{content:o,tool_calls:c}=t.delta;c&&c.length?(h=c[0].index,g=1,h!==y?(v.push({id:c[0].id,type:"function",function:{name:c[0].function.name,arguments:c[0].function.arguments}}),y=h):v[y].function.arguments+=c[0].function.arguments):m.push(o);let p={successed:!0,requestid:l,segment:o,text:m.join(""),finish_reason:s,index:i,usage:r,has_tool_calls:g,tool_calls:v};n&&(p=Object.assign({},p,n)),this.emit(s?"chatdone":"chattext",p)}}catch(e){r={error:e}}finally{try{d||i||!(o=p.return)||(yield o.call(p))}finally{if(r)throw r.error}}return{successed:!0,requestid:l}}catch(e){return this.emit("requesterror",{successed:!1,requestid:l,error:"call axios faied "+e}),{successed:!1,requestid:l}}})}}const x={thinking:{start:"<xiaolu-think>",end:"</xiaolu-think>",tag:"xiaolu-think"},reasoning:{start:"<xiaolu-reason>",end:"</xiaolu-reason>",tag:"xiaolu-reason"},card:{start:"<xiaolu-card>",end:"</xiaolu-card>",tag:"xiaolu-card"},preresponse:{start:"<xiaolu-preresponse>",end:"</xiaolu-preresponse>",tag:"xiaolu-preresponse"}};var O;!function(e){e[e.None=0]="None",e[e.Thinking=1]="Thinking",e[e.ThinkingOver=2]="ThinkingOver"}(O||(O={}));class k extends y{constructor(e,t={}){if(super(),this.authorizationProvider=e,this.setting=t,this.botid=null,this.workflowid=null,this.talkflowid=null,this.debugDir="",this.debug=!1,this.setting.workflowid)this.workflowid=this.setting.workflowid;else if(this.setting.talkflowid)this.talkflowid=this.setting.talkflowid;else{if(!this.setting.botid&&!this.setting.botID)throw new Error("no botid or talkflowid or workflowid setting for coze");this.botid=this.setting.botid||this.setting.botID}!0===t.debug&&(this.debug=!0,this.debugDir=r.join(t.logPath||r.resolve(process.cwd(),"./cozedebug"),this.setting.model||"chat"),i.mkdirSync(this.debugDir,{recursive:!0})),this.apiKey=this.setting.apiKey}createClient(){return m(this,void 0,void 0,function*(){if(this.apiKey)return new n.CozeAPI({baseURL:n.COZE_CN_BASE_URL,token:this.apiKey});const e=yield this.authorizationProvider.getAccessToken();if(!e)throw new Error("get access token failed");return new n.CozeAPI({baseURL:n.COZE_CN_BASE_URL,token:e})})}createCoversation(e){return m(this,void 0,void 0,function*(){try{const t=null!=e?e:yield this.createClient(),n=this.botid?{bot_id:this.botid}:{};return(yield t.conversations.create(n)).id}catch(e){return console.error("createCoversation error in coze api"),null}})}setVariables(){return m(this,arguments,void 0,function*(e={}){const t=yield this.createClient();!e.type&&(e.type="app");const n={data:e.data};"app"===e.type&&(n.app_id=this.authorizationProvider.appid),"bot"===e.type&&this.botid&&(n.bot_id=this.botid),e.user_id&&(n.connector_uid=e.user_id);const s=yield t.variables.update(n,{debug:!0});return console.log("setVariables result",s),{successed:!0}})}getVariables(e){return m(this,void 0,void 0,function*(){const t=yield this.createClient(),n=Object.assign({},{bot_id:this.botid},e),s=yield t.variables.retrieve(n);return s?Object.assign({successed:!0},s):{successed:!1,error:"get variables failed"}})}getRequestStream(e,t){return m(this,arguments,void 0,function*(e,t,n={}){var s,i;if(this.botid){const i={bot_id:this.botid,additional_messages:t,user_id:n.userid||n.cozeUserID,conversation_id:null!==(s=n.session_id)&&void 0!==s?s:yield this.createCoversation(e),parameters:Object.assign({request_src:1},n.parameters||{})};return i.custom_variables=Object.assign({},this.setting.customVariables||{},n.customVariables||{}),i}if(this.workflowid){const e={ext:n.ext,workflow_id:this.workflowid,is_async:!1,parameters:Object.assign({request_src:1},n.parameters||{},{input:t})};return(n.userid||n.cozeUserID)&&(e.ext=Object.assign({},e.ext||{},{user_id:n.userid||n.cozeUserID})),e}const r={additional_messages:t,ext:{user_id:"12345678"},workflow_id:this.talkflowid,conversation_id:null!==(i=n.session_id)&&void 0!==i?i:yield this.createCoversation(e),parameters:Object.assign({request_src:1},n.parameters||{})};return(n.userid||n.cozeUserID)&&(r.ext=Object.assign({},r.ext||{},{user_id:n.userid||n.cozeUserID})),r})}getChatDetail(e,t,s){return m(this,void 0,void 0,function*(){const i=Date.now();for(;Date.now()-i<12e4;){const i=yield e.chat.retrieve(t,s);if(i.status===n.ChatStatus.COMPLETED)return{usage:i.usage,messages:yield e.chat.messages.list(t,s)};yield new Promise(e=>setTimeout(e,1500))}return null})}chatRequest(e){return m(this,arguments,void 0,function*(e,t={},s={}){e||this.emit("chaterror",{successed:!1,error:"no message in chat"}),"string"==typeof e&&(e=[{role:n.RoleType.User,content_type:"text",content:e}]);const o=yield this.createClient(),a=this.debug?i.createWriteStream(r.join(this.debugDir,`sync_${this.formatDateWithMs()}.log`),{flags:"a"}):null,c=yield this.getRequestStream(o,e,t);a&&(a.write(`callChatOption:${JSON.stringify(t)}\n`),a.write(`parameters:${JSON.stringify(c)}\n`));const l=this.botid?yield o.chat.create(c):yield o.workflows.runs.create(c);if(this.workflowid){const e=l;if("Success"===e.msg||!e.msg&&e.data){const t=e.data;return a&&a.end(t),{successed:!0,message:[{role:"assistant",type:"answer",content:t}]}}a&&a.end("workflow run failed"),console.error("workflow run failed",e.msg,e)}if(!this.workflowid&&l.conversation_id&&l.id){const e=l,t=yield this.getChatDetail(o,e.conversation_id,e.id);if(t){return{successed:!0,message:t.messages.filter(e=>"answer"===e.type).map(e=>({role:e.role,type:e.type,content:e.content})),usage:t.usage,session_id:e.conversation_id}}}return a&&a.end("聊天未完成"),{successed:!1,error:{message:"聊天未完成"}}})}extractXmlContent(e,t){const n=new RegExp(`<\\s*${t}\\s*>([\\s\\S]*?)<\\s*\\/\\s*${t}\\s*>`,"i"),s=e.match(n);return s&&s[1]?s[1].trim():""}parseDeepThinkingJson(e){const t=[e.indexOf(x.thinking.start),e.indexOf(x.reasoning.start),e.indexOf(x.card.start),e.indexOf(x.preresponse.start)];let n=1e4,s=-1;t.forEach((e,t)=>{e>=0&&e<n&&(n=e,s=t)});const i=s>=0?n:-1;if(i<0)return{content:e,status:O.ThinkingOver};const r=[x.thinking,x.reasoning,x.card,x.preresponse][s],o=e.indexOf(r.end,i),a=o>=0?o:e.indexOf("</",i),c=this.extractXmlContent(e.substring(i,a>=0?a:void 0)+r.end,r.tag);return o>=0&&(e=e.substring(o+r.end.length)),{thinking:{action:r,text:c,completed:o>=0},content:e}}formatDateWithMs(e=new Date){return`${e.getFullYear()}${String(e.getMonth()+1).padStart(2,"0")}${String(e.getDate()).padStart(2,"0")}${String(e.getHours()).padStart(2,"0")}${String(e.getMinutes()).padStart(2,"0")}${String(e.getSeconds()).padStart(2,"0")}${String(e.getMilliseconds()).padStart(3,"0")}`}chatRequestInStream(e){return m(this,arguments,void 0,function*(e,t={},o,a){var c,l,u,d,p,h,m;e||this.emit("chaterror",{successed:!1,error:"no message in chat"}),"string"==typeof e&&(e=[{role:n.RoleType.User,content_type:"text",content:e}]);const g=yield this.createClient();let y=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3),v=0;const _=this.debug?i.createWriteStream(r.join(this.debugDir,`${this.formatDateWithMs()}.log`),{flags:"a"}):null,b=yield this.getRequestStream(g,e,t);_&&(_.write(`callChatOption:${JSON.stringify(t)}\n`),_.write(`attach:${o?JSON.stringify(o):"null"}\n`),_.write(`parameters:${JSON.stringify(b)}\n`));const k=this.botid?g.chat.stream(b):this.workflowid?g.workflows.runs.stream(b):g.workflows.chat.stream(b);let w=0,q=[],T=[],S=[],C=[],A="",E=O.None,N="",j="";try{for(var R,I=!0,D=f(k);!(c=(R=yield D.next()).done);I=!0){d=R.value,I=!1;const e=d;if(e.event===n.ChatEventType.ERROR)return _&&_.write("chat error:"),this.emit("chaterror",{successed:!1,error:"call failed"});if(e.event===n.ChatEventType.CONVERSATION_MESSAGE_DELTA||e.event===n.WorkflowEventType.MESSAGE){let{conversation_id:t,content_type:n,type:i="answer",role:r="assistant",content:a,reasoning_content:c}=e.data;if(_&&_.write(a),"Default"===a)continue;if(!a&&c){this.emit("chatthinking",{text:c,completed:!1,action:"deep-thinking"});continue}if(0===w&&a.startsWith("<xiaolu-")&&(E=O.Thinking,w++),E===O.Thinking){A+=a;const e=this.parseDeepThinkingJson(A),c=e.thinking;if(c)if(A=e.content,c.action===x.card){if(N+=e.thinking.text,e.thinking.completed){const e=N.replace(/[\x00-\x1F\x7F]/g,"").split("|");N="";for(const t of e){const e=s.parse(t);if(e.type&&e.tag)if("follow_up"===e.type)T.push(e.tag);else{const t=e.tag.split(",");for(const n of t)C.push({type:e.type,tag:n})}}this.emit("chatcard",C)}}else if(c.action===x.preresponse){const s=e.thinking.text.slice(j.length);j=e.thinking.text,q.push(s);let a={successed:!0,type:i,content_type:n,role:r,requestid:y,segment:s,text:q.join(""),index:v++,session_id:t,preresponse:!0,preresponseover:e.thinking.completed};o&&(a=Object.assign({},a,o)),this.emit("chattext",a)}else this.emit("chatthinking",{text:e.thinking.text,completed:e.thinking.completed,action:null===(p=c.action)||void 0===p?void 0:p.tag});if(e.status!=O.ThinkingOver)continue;E=O.ThinkingOver,a=A}q.push(a);let l={successed:!0,type:i,content_type:n,role:r,requestid:y,segment:a,text:q.join(""),index:v++,session_id:t};o&&(l=Object.assign({},l,o)),this.emit("chattext",l)}if(e.event===n.ChatEventType.CONVERSATION_MESSAGE_COMPLETED){const{type:t,content:n}=null!==(h=e.data)&&void 0!==h?h:{};"follow_up"===t&&(_&&_.write("followup:"+n),S.push(n))}if(e.event===n.ChatEventType.CONVERSATION_CHAT_COMPLETED||e.event===n.WorkflowEventType.DONE){const{conversation_id:t,content:s}=null!==(m=e.data)&&void 0!==m?m:{};let i={successed:!0,cards:C.length?C:null,cardfollowup:T.filter(e=>"string"==typeof e&&e.length>0),followup:S,type:"answer",content_type:"text",role:n.RoleType.Assistant,requestid:y,segment:null,text:null!=s?s:q.join(""),index:v++,session_id:t};o&&(i=Object.assign({},i,o)),_&&_.end("chat completed"),this.emit("chatdone",i)}}}catch(e){l={error:e}}finally{try{I||c||!(u=D.return)||(yield u.call(D))}finally{if(l)throw l.error}}return{successed:!0,requestid:y}})}}const w=["[AUTHORIZATION NEEDED]","[AUTHORIZATION ERROR]","[BODY ERROR]","[REQUEST ERROR]"];class q extends b{constructor(e,t,n={}){super(e,n),this.proxySetting=t}chatRequest(e,t,n){return m(this,void 0,void 0,function*(){const s=Object.assign({headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apiKey}`},method:"post",url:this.proxySetting.serviceurl,data:{chatText:e,option:t}},n);return(yield h.default(s)).data})}chatRequestInStream(e,t,n,s){return m(this,void 0,void 0,function*(){let i,r=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3);const o={headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apiKey}`},method:"post",url:this.proxySetting.serviceurl+"/stream",data:{messages:e,option:t,axiosOption:s},responseType:"stream"};let a="";h.default(o).then(e=>{e.data.on("data",e=>{if(i=e.toString(),i){if(w.includes(i))return this.emit("requesterror",{successed:!1,requestid:r,error:"Request Remote OpenAI Error : "+i});const e=(a+i).split("*&$");a="";for(const t of e)if(t)try{if(!t.endsWith("}")){a=t;break}const e=Object.assign(JSON.parse(t),n);this.emit(e.finish_reason?"chatdone":"chattext",e)}catch(e){break}}})}).catch(e=>{this.emit("requesterror",{successed:!1,requestid:r,error:"Axios Error : "+e})})})}}class T extends _{constructor(e,t,n={}){super(e,n),this.azureSetting=t,this.azureSetting.endpoint.toLowerCase().startsWith("https://")||(this.azureSetting.endpoint="https://"+this.azureSetting.endpoint)}createOpenAI(e){return new a.OpenAIClient(this.azureSetting.endpoint,new a.AzureKeyCredential(e))}get EmbeddingUrl(){return`${this.azureSetting.endpoint}/openai/deployments/${this.embeddingmodel||"openai-embedding-ada-002"}/embeddings?api-version=2022-12-01`}getTextEmbedding(e){return m(this,arguments,void 0,function*(e,t={}){if(!e)return{successed:!1,error:{errcode:2,errmsg:"content required"}};this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));try{return{successed:!0,embedding:(yield this.aiApi.getEmbeddings(this.embeddingmodel||"openai-embedding-ada-002","string"==typeof e?[e]:e,t)).data}}catch(e){return{successed:!1,error:e}}})}chatRequest(e,t){return m(this,arguments,void 0,function*(e,t,n={}){if(!e)return{successed:!1,error:{errcode:2,errmsg:"缺失聊天的内容"}};this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));let s="string"==typeof e?[{role:"user",content:e}]:e;try{const e=yield this.aiApi.getChatCompletions((null==t?void 0:t.model)||this.chatModel,s,{temperature:Number((null==t?void 0:t.temperature)||this.temperature),maxTokens:Number((null==t?void 0:t.maxtoken)||this.maxtoken),topP:Number((null==t?void 0:t.top_p)||this.top_p),presencePenalty:Number((null==t?void 0:t.presence_penalty)||this.presence_penalty),frequencyPenalty:Number((null==t?void 0:t.frequency_penalty)||this.frequency_penalty),n:Number((null==t?void 0:t.replyCounts)||1)||1,tools:1===(null==t?void 0:t.enableToolCall)&&(null==t?void 0:t.tools)?t.tools:void 0,toolChoice:1===(null==t?void 0:t.enableToolCall)?"auto":void 0}),{promptTokens:n,completionTokens:i,totalTokens:r}=e.usage;let o=[];for(const t of e.choices){const{index:e,finishReason:n,message:s}=t;o.push({index:e,finish_reason:n,message:s})}return{successed:!0,message:o,usage:{prompt_tokens:n,completion_tokens:i,total_tokens:r}}}catch(e){return console.log("result is error ",e),{successed:!1,error:e}}})}chatRequestInStream(e,t,n,s){return m(this,void 0,void 0,function*(){var i,r,o,a,c,l,u;e||this.emit("chaterror",{successed:!1,error:"no text in chat"}),this.aiApi||(this.aiApi=this.createOpenAI(this.apiKey));let d="string"==typeof e?[{role:"user",content:e}]:e;s=Object.assign({},s||{timeout:6e4});let p,h=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3),m=0,g=-1,y=[];try{const e=yield this.aiApi.streamChatCompletions((null==t?void 0:t.model)||this.chatModel,d,{temperature:Number((null==t?void 0:t.temperature)||this.temperature),maxTokens:Number((null==t?void 0:t.maxtoken)||this.maxtoken),topP:Number((null==t?void 0:t.top_p)||this.top_p),presencePenalty:Number((null==t?void 0:t.presence_penalty)||this.presence_penalty),frequencyPenalty:Number((null==t?void 0:t.frequency_penalty)||this.frequency_penalty),n:Number((null==t?void 0:t.replyCounts)||1)||1,tools:1===(null==t?void 0:t.enableToolCall)&&(null==t?void 0:t.tools)?t.tools:void 0,toolChoice:1===(null==t?void 0:t.enableToolCall)?"auto":void 0});let s=[];try{for(var v,_=!0,b=f(e);!(i=(v=yield b.next()).done);_=!0){a=v.value,_=!1;const e=a;for(const t of e.choices){const{finishReason:e,index:i}=t,r=null===(c=t.delta)||void 0===c?void 0:c.toolCalls;if(r&&r.length)p=r[0].index,m=1,p!==g?(y.push({id:r[0].id,type:"function",function:{name:r[0].function.name,arguments:r[0].function.arguments}}),g=p):y[g].function.arguments+=r[0].function.arguments;else{const e=null===(l=t.delta)||void 0===l?void 0:l.content;s.push(e)}let o={successed:!0,requestid:h,segment:null===(u=t.delta)||void 0===u?void 0:u.content,text:s.join(""),finish_reason:e,index:i,has_tool_calls:m,tool_calls:y};n&&(o=Object.assign({},o,n)),this.emit(e?"chatdone":"chattext",o)}}}catch(e){r={error:e}}finally{try{_||i||!(o=b.return)||(yield o.call(b))}finally{if(r)throw r.error}}return{successed:!0,requestid:h}}catch(e){return this.emit("requesterror",{successed:!1,requestid:h,error:"call axios faied "+e}),{successed:!1,requestid:h}}})}}function S(){return m(this,arguments,void 0,function*(e={}){e.data||(e.data=e.body);try{return{successed:!0,data:(yield h.default(e)).data}}catch(e){return{successed:!1,error:e,data:e}}})}class C extends y{constructor(e,t){super(),this.apikey=e,this.agent=t}chatRequest(e,t){return m(this,arguments,void 0,function*(e,t,n={}){var s;if(!e)return{successed:!1,error:"no text in chat"};const i="object"==typeof e?null!==(s=e.text)&&void 0!==s?s:e.content:e;n=Object.assign({},n||{timeout:6e4});const r=Object.assign({headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apikey}`},method:"post",url:`${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`,data:{question:i,session_id:t.session_id,optional:t.optional,stream:!1}},n),o=yield S(r);if(!o.successed||o.data.code)return{successed:!1,error:"failed"};const{answer:a,session_id:c}=o.data.data;return{successed:!0,message:[{message:{content:a}}],session_id:c}})}chatRequestInStream(e,t,n,s){return m(this,void 0,void 0,function*(){var i,r,o,a,l;e||this.emit("chaterror",{successed:!1,error:"no text in chat"});const u="object"==typeof e?null!==(l=e.text)&&void 0!==l?l:e.content:e;s=Object.assign({},s||{timeout:6e4});let d=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3);try{const e=Object.assign({headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apikey}`},method:"post",url:`${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`,data:{question:u,session_id:t.session_id,stream:!0,optional:t.optional},responseType:"stream"},s),l=yield h.default(e),y=c.Readable.from(l.data);let v,_=0,b="",x=[],O=[];try{for(var p,m=!0,g=f(y);!(i=(p=yield g.next()).done);m=!0){a=p.value,m=!1;const e=a;let t=null,s="";try{s=e.toString().split("data:"),s.length&&(s=s[s.length-1]+""),t=JSON.parse(x.join("")+s)}catch(e){x.push(s);continue}x=[];const{answer:i,running_status:r,reference:o}=t.data;if(!0===r)continue;const c=i?i.replace(b,""):"";b=null!=i?i:b,v||(v=t.data.session_id),o&&o.chunks&&o.chunks.length&&(O=O.concat(o.chunks));const l=!0===t.data;let u={successed:!0,requestid:d,segment:c,chunks:O,text:b,finish_reason:l?"stop":null,index:_++,session_id:v};n&&(u=Object.assign({},u,n)),this.emit(l?"chatdone":"chattext",u)}}catch(e){r={error:e}}finally{try{m||i||!(o=g.return)||(yield o.call(g))}finally{if(r)throw r.error}}return{successed:!0,requestid:d}}catch(e){}})}}class A extends y{constructor(e,t={}){super(),this.apiOption={},this.apiKey=e,this.apiOption=t}chatRequest(e,t){return m(this,arguments,void 0,function*(e,t,n={}){if(!e)return{successed:!1,error:{errcode:2,errmsg:"缺失聊天的内容"}};const s=this.assembleApiParams(e,!1,t,n);try{const e=yield S(s);return e.successed&&!e.data.code?{successed:!0,message:e.data.choices,usage:e.data.usage}:Object.assign({successed:!1},e.data)}catch(e){return console.log("result is error ",e),{successed:!1,error:e}}})}assembleApiParams(e,t=!1,n,s={}){let i="string"==typeof e?[{role:"user",content:e}]:e,r={};((null==n?void 0:n.temperature)||this.apiOption.temperature)&&(r.temperature=Number((null==n?void 0:n.temperature)||this.apiOption.temperature)),r.max_tokens=Number((null==n?void 0:n.maxtoken)||this.apiOption.maxtoken),((null==n?void 0:n.top_p)||this.apiOption.top_p)&&(r.top_p=Number((null==n?void 0:n.top_p)||this.apiOption.top_p)),((null==n?void 0:n.presence_penalty)||this.apiOption.presence_penalty)&&(r.presence_penalty=Number((null==n?void 0:n.presence_penalty)||this.apiOption.presence_penalty)),((null==n?void 0:n.frequency_penalty)||this.apiOption.frequency_penalty)&&(r.frequency_penalty=Number((null==n?void 0:n.frequency_penalty)||this.apiOption.frequency_penalty)),((null==n?void 0:n.top_logprobs)||this.apiOption.top_logprobs)&&(r.logprobs=!0,r.top_logprobs=Number((null==n?void 0:n.top_logprobs)||this.apiOption.top_logprobs)),r.tools=1===(null==n?void 0:n.enableToolCall)&&(null==n?void 0:n.tools)?n.tools:void 0,r.tool_choice=1===(null==n?void 0:n.enableToolCall)?"auto":void 0;const o=Object.assign(Object.assign({},s),{method:"post",headers:{"Content-Type":"application/json",authorization:`Bearer ${this.apiKey}`},data:Object.assign(Object.assign({model:(null==n?void 0:n.model)||this.apiOption.model},r),{messages:i,stream:t}),url:"https://ark.cn-beijing.volces.com/api/v3/chat/completions"});return t&&(o.responseType="stream"),o}chatRequestInStream(e,t,n,s){return m(this,void 0,void 0,function*(){e||this.emit("chaterror",{successed:!1,error:"no text in chat"}),s=Object.assign({},s||{timeout:1e4});const i=this.assembleApiParams(e,!0,t,s);let r=Math.ceil(Math.random()*((new Date).getTime()*Math.random())/1e3),o=[];try{return function(e={},t){e.data||(e.data=e.body),h.default(e).then(e=>{e.data.on("data",e=>{t(e)})})}(i,e=>{let t=e.toString().replace("[DONE]","").replace(/[\r\n]+/gm,"");this.processChunkData(t.split(/data: /),r,o,n)}),{successed:!0,requestid:r}}catch(e){return this.emit("requesterror",{successed:!1,requestid:r,error:"call axios faied "+e}),{successed:!1,requestid:r}}})}processChunkData(e,t,n,s){let i,r=0,o=-1,a=[];for(const c of e){if(!c)continue;const e=JSON.parse(c),[l]=e.choices,{finish_reason:u,index:d,usage:p}=l,{content:h,tool_calls:m}=l.delta;m&&m.length?(i=m[0].index,r=1,i!==o?(a.push({id:m[0].id,type:"function",function:{name:m[0].function.name,arguments:m[0].function.arguments}}),o=i):a[o].function.arguments+=m[0].function.arguments):n.push(h);let g={successed:!0,requestid:t,segment:h,text:n.join(""),finish_reason:u,index:d,usage:p,has_tool_calls:r,tool_calls:a};s&&(g=Object.assign({},g,s)),this.emit(u?"chatdone":"chattext",g)}}}class E{constructor(e,t){this.appid=e,this.expiresAt=0,this.secret=t.keyid,this.pemfile=t.pemfile||"private.pem",this.sessionName=t.sessionName||"default"}getAccessToken(){return m(this,void 0,void 0,function*(){if(this.accessToken&&Date.now()<this.expiresAt)return this.accessToken;const e=yield this.doAuthorize();return e.successed?(this.accessToken=e.accessToken,this.expiresAt=1e3*e.expires_in,this.accessToken):null})}doAuthorize(){return m(this,void 0,void 0,function*(){try{const e="api.coze.cn",t=p.default.join(process.cwd(),this.pemfile);if(!d.default.existsSync(t))return{successed:!1,error:`${t} not existed`};const s=d.default.readFileSync(t).toString(),i=yield n.getJWTToken({baseURL:n.COZE_CN_BASE_URL,appId:this.appid,aud:e,keyid:this.secret,privateKey:s,sessionName:this.sessionName});return{successed:!0,accessToken:i.access_token,expires_in:i.expires_in}}catch(e){return{successed:!0,error:e}}})}}const N=new Map,j={OPENAI:"openai",OPENAIPROXY:"openaiproxy",MICROSOFT:"microsoft",AIMP:"aimp",COZE:"coze",DOUBAO:"doubao"};var R=Object.freeze({__proto__:null,GptProviderEnum:j,createGpt:function(e,t,n){let{model:s,agentid:i,maxtoken:r,temperature:o,serviceurl:a,endpoint:c,engine:l,version:u,embedding:d,top_p:p,presence_penalty:h,frequency_penalty:m}=n||{};switch(e){case j.OPENAI:return new b(t+"",{model:s,maxtoken:r,temperature:o,embedding:d,top_p:p,presence_penalty:h,frequency_penalty:m});case j.OPENAIPROXY:return new q(t+"",{serviceurl:a},{model:s,maxtoken:r,temperature:o,embedding:d,top_p:p,presence_penalty:h,frequency_penalty:m});case j.MICROSOFT:return new T(t+"",{endpoint:c,engine:l,version:u},{model:s,maxtoken:r,temperature:o,embedding:d,top_p:p,presence_penalty:h,frequency_penalty:m});case j.AIMP:return new C(t+"",{endpoint:c,agentid:i});case j.COZE:let e=N.get(t+"");return e||(e=new E(t+"",n),N.set(t+"",e)),new k(e,n);case j.DOUBAO:return new A(t+"",{model:s,maxtoken:r,temperature:o,top_p:p,presence_penalty:h,frequency_penalty:m});default:return null}}});exports.GptBase=v,exports.GptFactory=R;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"aimp.d.ts","sourceRoot":"","sources":["../../src/aimp.ts"],"names":[],"mappings":"AAKA,OAAO,OAAO,MAAM,WAAW,CAAA;AAG/B,MAAM,CAAC,OAAO,OAAO,gBAAiB,SAAQ,OAAO;IAEjD,SAAS,CAAC,MAAM,EAAE,MAAM,CAAC;IACzB,SAAS,CAAC,KAAK,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE,CAAC;IACvD;;;;OAIG;gBACS,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE;QAAE,QAAQ,EAAE,MAAM,CAAC;QAAC,OAAO,EAAE,MAAM,CAAA;KAAE;IAMxE;;;;;QAKI;IACS,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,GAAG,EAAE,cAAc,EAAE,GAAG,EAAE,WAAW,GAAE,GAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;IA4B1G;;;;;;;OAOG;IACY,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,GAAG,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,WAAW,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;CA2DjI"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"azureai.d.ts","sourceRoot":"","sources":["../../src/azureai.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,qBAAqB,EAAE,WAAW,EAAE,eAAe,EAAE,mBAAmB,EAAC,MAAM,WAAW,CAAC;AACpG,OAAO,EAAE,YAAY,EAAsB,MAAM,eA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;;;;;OAKG;IACU,WAAW,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,MAAM,EAAE,cAAc,GAAE,GAAQ,EAAE,YAAY,GAAE,GAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;IA8CjH;;;;;OAKG;IACH,iBAAiB,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM;IAO1D;;;;;OAKG;IACH,OAAO,CAAC,qBAAqB;IAgC7B;;;;OAIG;IACH,OAAO,CAAC,gBAAgB;IAaxB;;;;;;;OAOG;IACY,mBAAmB,CAAC,OAAO,EAAE,GAAG,EAAE,GAAG,MAAM,EAAE,cAAc,GAAE,GAAQ,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;CAsHxI"}
|
|
@@ -78,7 +78,7 @@ export declare function request(opts?: any): Promise<RpcResult>;
|
|
|
78
78
|
* @param opts
|
|
79
79
|
* @returns
|
|
80
80
|
*/
|
|
81
|
-
export declare function requestStream(opts: any, processChunkData: Function): void;
|
|
81
|
+
export declare function requestStream(opts: any | undefined, processChunkData: Function): void;
|
|
82
82
|
/**
|
|
83
83
|
* 数据缓存提供者接口
|
|
84
84
|
*/
|
|
@@ -119,3 +119,4 @@ export interface StabilityResult extends ApiResult {
|
|
|
119
119
|
'data'?: any;
|
|
120
120
|
'type'?: string;
|
|
121
121
|
}
|
|
122
|
+
//# sourceMappingURL=declare.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"declare.d.ts","sourceRoot":"","sources":["../../src/declare.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAG9C,MAAM,WAAW,SAAS;IACtB;;;OAGG;IACH,WAAW,EAAE,OAAO,CAAA;IACpB;;;;OAIG;IACH,OAAO,CAAC,EAAE,GAAG,CAAC;CACjB;AACD;;GAEG;AACH,MAAM,WAAW,WA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EAAE,GAAG,CAAK;IAC7B;;OAEG;gBACS,MAAM,EAAE,MAAM,EAAE,SAAS,GAAE,GAAQ;IAK/C;;OAEG;IACU,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,cAAc,EAAE,GAAG,EAAE,WAAW,GAAE,GAAQ,GAAG,OAAO,CAAC,GAAG,CAAC;IAYjH;;;;OAIG;IACH,OAAO,CAAC,iBAAiB;IAgCzB;;;;;OAKG;IACY,mBAAmB,CAAC,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,cAAc,EAAE,GAAG,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,WAAW,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAgBrI;;;;;;OAMG;IACH,gBAAgB,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,SAAS,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,GAAG;CA+BzF"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
1
|
import { EventEmitter } from "events";
|
|
3
2
|
import { ApiResult } from './declare';
|
|
4
3
|
export default abstract class GptBase extends EventEmitter {
|
|
@@ -41,3 +40,4 @@ export default abstract class GptBase extends EventEmitter {
|
|
|
41
40
|
*/
|
|
42
41
|
chatRequestInStream(_chatText: string | Array<any>, _paramOption: any, _attach?: any, _axiosOption?: any): any;
|
|
43
42
|
}
|
|
43
|
+
//# sourceMappingURL=gptbase.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gptbase.d.ts","sourceRoot":"","sources":["../../src/gptbase.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,MAAM,QAAQ,CAAA;AACrC,OAAO,EAAE,SAAS,EAAE,MAAM,WAAW,CAAA;AAErC,MAAM,CAAC,OAAO,CAAC,QAAQ,OAAO,OAAQ,SAAQ,YAAY;IACtD;;OAEG;;IAIH;;;OAGG;IACH,gBAAgB,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,GAAG,GAAE,GAAG;IACtD;;;;;OAKG;IACH,QAAQ,CAAC,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,YAAY,EAAE,GAAG,EAAE,WAAW,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,SAAS,CAAC;IAE7G;;;OAGG;IACG,iBAAiB,CAAC,OAAO,CAAC,EAAC,GAAG,GAAE,OAAO,CAAC,MAAM,GAAC,IAAI,CAAC;IAI1D;;;OAGG;IACG,YAAY,CAAC,OAAO,EAAE,GAAG,GAAE,OAAO,CAAC,SAAS,CAAC;IAGnD;;;OAGG;IACG,YAAY,CAAC,OAAO,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;IAC9C;;;;;OAKG;IACH,mBAAmB,CAAC,SAAS,EAAE,MAAM,GAAG,KAAK,CAAC,GAAG,CAAC,EAAE,YAAY,EAAE,GAAG,EAAE,OAAO,CAAC,EAAE,GAAG,EAAE,YAAY,CAAC,EAAE,GAAG,GAAG,GAAG;CAC7G"}
|
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { ApiCredential } from './baiduai';
|
|
2
1
|
import GptBase from './gptbase';
|
|
3
2
|
/**
|
|
4
3
|
* OpenAI/NLP 的服务提供商 OpenAI,微软,百度文心(待接入),google(待接入)
|
|
@@ -9,12 +8,7 @@ export declare const GptProviderEnum: {
|
|
|
9
8
|
readonly MICROSOFT: "microsoft";
|
|
10
9
|
readonly AIMP: "aimp";
|
|
11
10
|
readonly COZE: "coze";
|
|
12
|
-
readonly BAIDU: "baidu";
|
|
13
11
|
readonly DOUBAO: "doubao";
|
|
14
|
-
readonly DEEPSEEK: "deepseek";
|
|
15
|
-
readonly GOOGLE: "google";
|
|
16
|
-
readonly STABILITY: "stability";
|
|
17
|
-
readonly STABILITY2: "stability2";
|
|
18
12
|
};
|
|
19
13
|
export type GptProviderEnum = typeof GptProviderEnum[keyof typeof GptProviderEnum];
|
|
20
14
|
/**
|
|
@@ -24,4 +18,5 @@ export type GptProviderEnum = typeof GptProviderEnum[keyof typeof GptProviderEnu
|
|
|
24
18
|
* @param {*} setting
|
|
25
19
|
* @returns
|
|
26
20
|
*/
|
|
27
|
-
export declare function createGpt(provider: GptProviderEnum, apikey: string
|
|
21
|
+
export declare function createGpt(provider: GptProviderEnum, apikey: string, setting: any): GptBase | null;
|
|
22
|
+
//# sourceMappingURL=gptprovider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"gptprovider.d.ts","sourceRoot":"","sources":["../../src/gptprovider.ts"],"names":[],"mappings":"AAaA,OAAO,OAAO,MAAM,WAAW,CAAC;AAIhC;;GAEG;AACH,eAAO,MAAM,eAAe;;;;;;;CAYlB,CAAC;AACX,MAAM,MAAM,eAAe,GAAG,OAAO,eAAe,CAAC,MAAM,OAAO,eAAe,CAAC,CAAC;AACnF;;;;;;GAMG;AACH,wBAAgB,SAAS,CAAC,QAAQ,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,GAAG,OAAO,GAAG,IAAI,CA+BjG"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,UAAU,MAAM,eAAe,CAAC;AAC5C,OAAO,KAAK,OAAO,MAAM,WAAW,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openai.d.ts","sourceRoot":"","sources":["../../src/openai.ts"],"names":[],"mappings":"AACA;;GAEG;AACH,OAAO,UAAU,MAAM,cAAc,CAAA;AACrC,OAAO,EAAE,mBAAmB,EAAE,WAAW,EAAE,eAAe,EAAE,MAAM,WAAW,CAAA;AAC7E,OAAO,MAAM,MAAM,QAAQ,CAAC;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MAAM,CAAC;IAC7C,SAAS,CAAC,QAAQ,CAAC,WAAW,EAAE,MAAM,CAAC;IACvC,SAAS,CAAC,QAAQ,CAAC,cAAc,EAAE,MAAM,CAAC;IAC1C,SAAS,CAAC,KAAK,EAAE,CAAC,GAAG,SAAS,CAAC;gBACnB,MAAM,EAAE,MAAM,EAAE,SAAS,GAAE,mBAAwB;IAW/D;;OAEG;IACH,QAAQ,CAAC,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG,CAAC;CAE3C"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openaiproxy.d.ts","sourceRoot":"","sources":["../../src/openaiproxy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,mBAAmB,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAC5E,OAAO,SAAS,MAAM,UAAU,CAAC;AAGjC,MAAM,CAAC,OAAO,OAAO,WAAY,SAAQ,SAAS;IAC9C,SAAS,CAAC,QAAQ,CAAC,YAAY,EAAE,eAAe,CAAC;gBACrC,MAAM,EAAE,MAAM,EAAE,WAAW,EAAE,eAAe,EAAE,SAAS,GAAE,mBAAwB;IAI7F;;;;;OAKG;IACY,WAAW,CAAC,QAAQ,EAAE,MAAM,GAAG,GAAG,EAAE,EAAE,YAAY,EAAE,GAAG,EAAE,WAAW,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,SAAS,CAAC;IAiB9G;;;;;;OAMG;IACY,mBAAmB,CAAC,QAAQ,EAAC,KAAK,CAAC,GAAG,CAAC,EAAE,cAAc,EAAE,mBAAmB,EAAE,MAAM,CAAC,EAAE,GAAG,EAAE,WAAW,CAAC,EAAE,GAAG,GAAG,OAAO,CAAC,GAAG,CAAC;CAwD9I"}
|
package/package.json
CHANGED
|
@@ -1,11 +1,16 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "doomiaichat",
|
|
3
|
-
"version": "7.1.
|
|
3
|
+
"version": "7.1.32",
|
|
4
4
|
"description": "Doomisoft OpenAI",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
|
-
"
|
|
6
|
+
"module": "dist/index.esm.js",
|
|
7
|
+
"types": "dist/index.d.ts",
|
|
8
|
+
"files": [
|
|
9
|
+
"dist"
|
|
10
|
+
],
|
|
7
11
|
"scripts": {
|
|
8
|
-
"build": "tsc"
|
|
12
|
+
"build:tsc": "rm -rf dist && tsc --project ./tsconfig-tsc.json --outDir dist",
|
|
13
|
+
"build:rollup": "rm -rf dist && rollup -c"
|
|
9
14
|
},
|
|
10
15
|
"keywords": [
|
|
11
16
|
"ChatGpt"
|
|
@@ -13,13 +18,22 @@
|
|
|
13
18
|
"author": "Stephen.Shen",
|
|
14
19
|
"license": "ISC",
|
|
15
20
|
"devDependencies": {
|
|
21
|
+
"@rollup/plugin-commonjs": "^29.0.0",
|
|
22
|
+
"@rollup/plugin-json": "^6.1.0",
|
|
23
|
+
"@rollup/plugin-node-resolve": "^16.0.3",
|
|
24
|
+
"@rollup/plugin-typescript": "^12.3.0",
|
|
16
25
|
"@types/node": "^18.19.1",
|
|
17
|
-
"
|
|
26
|
+
"rollup": "^2.79.2",
|
|
27
|
+
"rollup-plugin-terser": "^7.0.2",
|
|
28
|
+
"rollup-plugin-typescript2": "^0.32.1",
|
|
29
|
+
"typescript": "^5.9.3"
|
|
18
30
|
},
|
|
19
31
|
"dependencies": {
|
|
20
32
|
"@azure/openai": "^1.0.0-beta.11",
|
|
21
33
|
"@coze/api": "^1.3.6",
|
|
22
|
-
"axios": "^1.12.0",
|
|
23
34
|
"openai": "^5.19.1"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"axios": "*"
|
|
24
38
|
}
|
|
25
39
|
}
|
package/dist/aimp.js
DELETED
|
@@ -1,162 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
|
|
3
|
-
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
|
|
4
|
-
return new (P || (P = Promise))(function (resolve, reject) {
|
|
5
|
-
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
|
|
6
|
-
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
|
|
7
|
-
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
|
|
8
|
-
step((generator = generator.apply(thisArg, _arguments || [])).next());
|
|
9
|
-
});
|
|
10
|
-
};
|
|
11
|
-
var __asyncValues = (this && this.__asyncValues) || function (o) {
|
|
12
|
-
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
|
|
13
|
-
var m = o[Symbol.asyncIterator], i;
|
|
14
|
-
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
|
|
15
|
-
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
|
|
16
|
-
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
|
|
17
|
-
};
|
|
18
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
19
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
20
|
-
};
|
|
21
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
22
|
-
/**
|
|
23
|
-
* 接入AI平台的中间层
|
|
24
|
-
*/
|
|
25
|
-
const axios_1 = __importDefault(require("axios"));
|
|
26
|
-
const declare_1 = require("./declare");
|
|
27
|
-
const gptbase_1 = __importDefault(require("./gptbase"));
|
|
28
|
-
const stream_1 = require("stream");
|
|
29
|
-
// import { ChatReponse } from './declare';
|
|
30
|
-
class AIMiddlePlatform extends gptbase_1.default {
|
|
31
|
-
/**
|
|
32
|
-
*
|
|
33
|
-
* @param apikey 调用AI中台 的key
|
|
34
|
-
* @param agent 智能体信息
|
|
35
|
-
*/
|
|
36
|
-
constructor(apikey, agent) {
|
|
37
|
-
super();
|
|
38
|
-
this.apikey = apikey;
|
|
39
|
-
this.agent = agent;
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* 非流式传输聊天请求
|
|
43
|
-
* @param chatText
|
|
44
|
-
* @param callChatOption
|
|
45
|
-
* @param axiosOption
|
|
46
|
-
*/
|
|
47
|
-
chatRequest(chatText, callChatOption, axiosOption = {}) {
|
|
48
|
-
var _a;
|
|
49
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
50
|
-
if (!chatText) {
|
|
51
|
-
// this.emit('chaterror', { successed: false, error: 'no text in chat' });
|
|
52
|
-
return { successed: false, error: 'no text in chat' };
|
|
53
|
-
}
|
|
54
|
-
const question = typeof chatText === 'object' ? (_a = chatText.text) !== null && _a !== void 0 ? _a : chatText.content : chatText;
|
|
55
|
-
axiosOption = Object.assign({}, axiosOption || { timeout: 60000 });
|
|
56
|
-
const opts = Object.assign({ headers: {
|
|
57
|
-
'Content-Type': 'application/json',
|
|
58
|
-
'authorization': `Bearer ${this.apikey}`
|
|
59
|
-
}, method: 'post', url: `${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`, data: {
|
|
60
|
-
question,
|
|
61
|
-
session_id: callChatOption.session_id,
|
|
62
|
-
optional: callChatOption.optional,
|
|
63
|
-
stream: false
|
|
64
|
-
} }, axiosOption);
|
|
65
|
-
const response = yield (0, declare_1.request)(opts);
|
|
66
|
-
if (!response.successed || response.data.code)
|
|
67
|
-
return { successed: false, error: 'failed' };
|
|
68
|
-
const { answer: message, session_id } = response.data.data;
|
|
69
|
-
// this.emit('chatdone', { successed: true, segment: message, text: message, finish_reason: 'stop', index: 0, session_id })
|
|
70
|
-
return { successed: true, message: [{ message: { content: message } }], session_id };
|
|
71
|
-
});
|
|
72
|
-
}
|
|
73
|
-
/**
|
|
74
|
-
* 流式传输聊天请求
|
|
75
|
-
* @param chatText
|
|
76
|
-
* @param callChatOption
|
|
77
|
-
* @param attach
|
|
78
|
-
* @param axiosOption
|
|
79
|
-
* @returns
|
|
80
|
-
*/
|
|
81
|
-
chatRequestInStream(chatText, callChatOption, attach, axiosOption) {
|
|
82
|
-
var _a, e_1, _b, _c;
|
|
83
|
-
var _d;
|
|
84
|
-
return __awaiter(this, void 0, void 0, function* () {
|
|
85
|
-
if (!chatText)
|
|
86
|
-
this.emit('chaterror', { successed: false, error: 'no text in chat' });
|
|
87
|
-
// console.log('Question===>', chatText)
|
|
88
|
-
const question = typeof chatText === 'object' ? (_d = chatText.text) !== null && _d !== void 0 ? _d : chatText.content : chatText;
|
|
89
|
-
axiosOption = Object.assign({}, axiosOption || { timeout: 60000 });
|
|
90
|
-
let requestid = Math.ceil(Math.random() * (new Date().getTime() * Math.random()) / 1000);
|
|
91
|
-
try {
|
|
92
|
-
const opts = Object.assign({ headers: {
|
|
93
|
-
'Content-Type': 'application/json',
|
|
94
|
-
'authorization': `Bearer ${this.apikey}`
|
|
95
|
-
}, method: 'post', url: `${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`, data: {
|
|
96
|
-
question,
|
|
97
|
-
session_id: callChatOption.session_id,
|
|
98
|
-
stream: true,
|
|
99
|
-
optional: callChatOption.optional,
|
|
100
|
-
}, responseType: 'stream' }, axiosOption);
|
|
101
|
-
const response = yield (0, axios_1.default)(opts);
|
|
102
|
-
const readableStream = stream_1.Readable.from(response.data);
|
|
103
|
-
let index = 0, session_id, fullanswer = '', errorKeeped = [], chunks = [];
|
|
104
|
-
try {
|
|
105
|
-
for (var _e = true, readableStream_1 = __asyncValues(readableStream), readableStream_1_1; readableStream_1_1 = yield readableStream_1.next(), _a = readableStream_1_1.done, !_a;) {
|
|
106
|
-
_c = readableStream_1_1.value;
|
|
107
|
-
_e = false;
|
|
108
|
-
try {
|
|
109
|
-
const chunk = _c;
|
|
110
|
-
///可能接收到的数据不完整,导致JSON.parse失败
|
|
111
|
-
let answerData = null, jsonStr = '';
|
|
112
|
-
try {
|
|
113
|
-
jsonStr = chunk.toString().split('data:');
|
|
114
|
-
if (jsonStr.length)
|
|
115
|
-
jsonStr = jsonStr[jsonStr.length - 1] + '';
|
|
116
|
-
answerData = JSON.parse(errorKeeped.join('') + jsonStr);
|
|
117
|
-
}
|
|
118
|
-
catch (e) {
|
|
119
|
-
////如果发生了JSON解析错误,则当前的数据不完整,留着拼凑下一回数据
|
|
120
|
-
// console.log('json parse error===>', errorKeeped.join('') + jsonStr)
|
|
121
|
-
errorKeeped.push(jsonStr);
|
|
122
|
-
// console.log('After Push===>', errorKeeped.join('') )
|
|
123
|
-
continue;
|
|
124
|
-
}
|
|
125
|
-
errorKeeped = [];
|
|
126
|
-
const { answer, running_status, reference } = answerData.data;
|
|
127
|
-
if (running_status === true)
|
|
128
|
-
continue;
|
|
129
|
-
const segment = answer ? answer.replace(fullanswer, '') : '';
|
|
130
|
-
fullanswer = answer !== null && answer !== void 0 ? answer : fullanswer;
|
|
131
|
-
if (!session_id)
|
|
132
|
-
session_id = answerData.data.session_id;
|
|
133
|
-
if (reference && reference.chunks && reference.chunks.length)
|
|
134
|
-
chunks = chunks.concat(reference.chunks);
|
|
135
|
-
const finished = answerData.data === true;
|
|
136
|
-
let output = { successed: true, requestid, segment: segment, chunks, text: fullanswer, finish_reason: finished ? 'stop' : null, index: index++, session_id };
|
|
137
|
-
if (attach)
|
|
138
|
-
output = Object.assign({}, output, attach);
|
|
139
|
-
this.emit(finished ? 'chatdone' : 'chattext', output);
|
|
140
|
-
}
|
|
141
|
-
finally {
|
|
142
|
-
_e = true;
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
catch (e_1_1) { e_1 = { error: e_1_1 }; }
|
|
147
|
-
finally {
|
|
148
|
-
try {
|
|
149
|
-
if (!_e && !_a && (_b = readableStream_1.return)) yield _b.call(readableStream_1);
|
|
150
|
-
}
|
|
151
|
-
finally { if (e_1) throw e_1.error; }
|
|
152
|
-
}
|
|
153
|
-
return { successed: true, requestid };
|
|
154
|
-
}
|
|
155
|
-
catch (error) {
|
|
156
|
-
// this.emit('requesterror', { successed: false, requestid, error: 'call axios faied ' + error });
|
|
157
|
-
// return { successed: false, requestid }
|
|
158
|
-
}
|
|
159
|
-
});
|
|
160
|
-
}
|
|
161
|
-
}
|
|
162
|
-
exports.default = AIMiddlePlatform;
|