doomiaichat 7.0.0 → 7.0.2

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/aimp.d.ts ADDED
@@ -0,0 +1,33 @@
1
+ import GptBase from "./gptbase";
2
+ export default class AIMiddlePlatform extends GptBase {
3
+ protected apikey: string;
4
+ protected agent: {
5
+ endpoint: string;
6
+ agentid: string;
7
+ };
8
+ /**
9
+ *
10
+ * @param apikey 调用AI中台 的key
11
+ * @param agent 智能体信息
12
+ */
13
+ constructor(apikey: string, agent: {
14
+ endpoint: string;
15
+ agentid: string;
16
+ });
17
+ /**
18
+ * 非流式传输聊天请求
19
+ * @param chatText
20
+ * @param callChatOption
21
+ * @param axiosOption
22
+ */
23
+ chatRequest(chatText: string | any, callChatOption: any, axiosOption?: any): Promise<any>;
24
+ /**
25
+ * 流式传输聊天请求
26
+ * @param chatText
27
+ * @param callChatOption
28
+ * @param attach
29
+ * @param axiosOption
30
+ * @returns
31
+ */
32
+ chatRequestInStream(chatText: string | any, callChatOption: any, attach?: any, axiosOption?: any): Promise<any>;
33
+ }
package/dist/aimp.js ADDED
@@ -0,0 +1,161 @@
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
+ stream: false
63
+ } }, axiosOption);
64
+ console.log('Question===>', question);
65
+ const response = yield (0, declare_1.request)(opts);
66
+ if (!response.successed)
67
+ return { successed: false, error: 'failed' };
68
+ console.log('reponse===>', response.data);
69
+ const { answer: message, session_id } = response.data.data;
70
+ this.emit('chatdone', { successed: true, segment: message, text: message, finish_reason: 'stop', index: 0, session_id });
71
+ return { successed: true, message, session_id };
72
+ });
73
+ }
74
+ /**
75
+ * 流式传输聊天请求
76
+ * @param chatText
77
+ * @param callChatOption
78
+ * @param attach
79
+ * @param axiosOption
80
+ * @returns
81
+ */
82
+ chatRequestInStream(chatText, callChatOption, attach, axiosOption) {
83
+ var _a, e_1, _b, _c;
84
+ var _d;
85
+ return __awaiter(this, void 0, void 0, function* () {
86
+ if (!chatText)
87
+ this.emit('chaterror', { successed: false, error: 'no text in chat' });
88
+ // console.log('Question===>', chatText)
89
+ const question = typeof chatText === 'object' ? (_d = chatText.text) !== null && _d !== void 0 ? _d : chatText.content : chatText;
90
+ axiosOption = Object.assign({}, axiosOption || { timeout: 60000 });
91
+ let requestid = Math.ceil(Math.random() * (new Date().getTime() * Math.random()) / 1000);
92
+ try {
93
+ const opts = Object.assign({ headers: {
94
+ 'Content-Type': 'application/json',
95
+ 'authorization': `Bearer ${this.apikey}`
96
+ }, method: 'post', url: `${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`, data: {
97
+ question,
98
+ session_id: callChatOption.session_id,
99
+ stream: true,
100
+ optional: callChatOption.optional,
101
+ }, responseType: 'stream' }, axiosOption);
102
+ const response = yield (0, axios_1.default)(opts);
103
+ const readableStream = stream_1.Readable.from(response.data);
104
+ let index = 0, session_id, fullanswer = '', errorKeeped = [];
105
+ try {
106
+ for (var _e = true, readableStream_1 = __asyncValues(readableStream), readableStream_1_1; readableStream_1_1 = yield readableStream_1.next(), _a = readableStream_1_1.done, !_a;) {
107
+ _c = readableStream_1_1.value;
108
+ _e = false;
109
+ try {
110
+ const chunk = _c;
111
+ ///可能接收到的数据不完整,导致JSON.parse失败
112
+ let answerData = null, jsonStr = '';
113
+ try {
114
+ jsonStr = chunk.toString().split('data:');
115
+ if (jsonStr.length)
116
+ jsonStr = jsonStr[jsonStr.length - 1] + '';
117
+ answerData = JSON.parse(errorKeeped.join('') + jsonStr);
118
+ }
119
+ catch (e) {
120
+ ////如果发生了JSON解析错误,则当前的数据不完整,留着拼凑下一回数据
121
+ // console.log('json parse error===>', errorKeeped.join('') + jsonStr)
122
+ errorKeeped.push(jsonStr);
123
+ // console.log('After Push===>', errorKeeped.join('') )
124
+ continue;
125
+ }
126
+ errorKeeped = [];
127
+ const { answer, running_status } = answerData.data;
128
+ if (running_status === true)
129
+ continue;
130
+ const segment = answer ? answer.replace(fullanswer, '') : '';
131
+ fullanswer = answer !== null && answer !== void 0 ? answer : fullanswer;
132
+ if (!session_id)
133
+ session_id = answerData.data.session_id;
134
+ const finished = answerData.data === true;
135
+ let output = { successed: true, requestid, segment: segment, text: fullanswer, finish_reason: finished ? 'stop' : null, index: index++, session_id };
136
+ if (attach)
137
+ output = Object.assign({}, output, attach);
138
+ this.emit(finished ? 'chatdone' : 'chattext', output);
139
+ }
140
+ finally {
141
+ _e = true;
142
+ }
143
+ }
144
+ }
145
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
146
+ finally {
147
+ try {
148
+ if (!_e && !_a && (_b = readableStream_1.return)) yield _b.call(readableStream_1);
149
+ }
150
+ finally { if (e_1) throw e_1.error; }
151
+ }
152
+ return { successed: true, requestid };
153
+ }
154
+ catch (error) {
155
+ // this.emit('requesterror', { successed: false, requestid, error: 'call axios faied ' + error });
156
+ // return { successed: false, requestid }
157
+ }
158
+ });
159
+ }
160
+ }
161
+ exports.default = AIMiddlePlatform;
package/dist/doubaoai.js CHANGED
@@ -37,10 +37,8 @@ class DouBaoAI extends gptbase_1.default {
37
37
  const callParams = this.assembleApiParams(chatText, false, callChatOption, axiosOption);
38
38
  try {
39
39
  const response = yield (0, declare_1.request)(callParams);
40
- if (response.successed && !response.data.code) {
40
+ if (response.successed && !response.data.code)
41
41
  return { successed: true, message: response.data.choices, usage: response.data.usage };
42
- // return { successed: true, ...response.data };
43
- }
44
42
  return Object.assign({ successed: false }, response.data);
45
43
  }
46
44
  catch (error) {
@@ -7,6 +7,7 @@ export declare const GptProviderEnum: {
7
7
  readonly OPENAI: "openai";
8
8
  readonly OPENAIPROXY: "openaiproxy";
9
9
  readonly MICROSOFT: "microsoft";
10
+ readonly AIMP: "aimp";
10
11
  readonly BAIDU: "baidu";
11
12
  readonly DOUBAO: "doubao";
12
13
  readonly GOOGLE: "google";
@@ -14,6 +14,7 @@ const azureai_1 = __importDefault(require("./azureai"));
14
14
  const stabilityai_1 = __importDefault(require("./stabilityai"));
15
15
  const stabilityplusai_1 = __importDefault(require("./stabilityplusai"));
16
16
  const baiduai_1 = __importDefault(require("./baiduai"));
17
+ const aimp_1 = __importDefault(require("./aimp"));
17
18
  const doubaoai_1 = __importDefault(require("./doubaoai"));
18
19
  /**
19
20
  * OpenAI/NLP 的服务提供商 OpenAI,微软,百度文心(待接入),google(待接入)
@@ -22,6 +23,7 @@ exports.GptProviderEnum = {
22
23
  OPENAI: 'openai',
23
24
  OPENAIPROXY: 'openaiproxy',
24
25
  MICROSOFT: 'microsoft',
26
+ AIMP: 'aimp',
25
27
  BAIDU: 'baidu',
26
28
  DOUBAO: 'doubao',
27
29
  GOOGLE: 'google',
@@ -36,7 +38,7 @@ exports.GptProviderEnum = {
36
38
  * @returns
37
39
  */
38
40
  function createGpt(provider, apikey, setting) {
39
- let { model, maxtoken, temperature, serviceurl, endpoint, engine, version, embedding, top_p, presence_penalty, frequency_penalty } = setting || {};
41
+ let { model, agentid, maxtoken, temperature, serviceurl, endpoint, engine, version, embedding, top_p, presence_penalty, frequency_penalty } = setting || {};
40
42
  switch (provider) {
41
43
  case exports.GptProviderEnum.OPENAI:
42
44
  return new openai_1.default(apikey + '', { model, maxtoken, temperature, embedding, top_p, presence_penalty, frequency_penalty });
@@ -47,6 +49,8 @@ function createGpt(provider, apikey, setting) {
47
49
  case exports.GptProviderEnum.BAIDU:
48
50
  let cred = typeof (apikey) === 'string' ? { apikey, securitykey: apikey } : apikey;
49
51
  return new baiduai_1.default(cred);
52
+ case exports.GptProviderEnum.AIMP:
53
+ return new aimp_1.default(apikey + '', { endpoint, agentid });
50
54
  case exports.GptProviderEnum.DOUBAO:
51
55
  return new doubaoai_1.default(apikey + '', { model, maxtoken, temperature, top_p, presence_penalty, frequency_penalty });
52
56
  case exports.GptProviderEnum.STABILITY:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doomiaichat",
3
- "version": "7.0.0",
3
+ "version": "7.0.2",
4
4
  "description": "Doomisoft OpenAI",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
package/src/aimp.ts ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * 接入AI平台的中间层
3
+ */
4
+ import axios from 'axios';
5
+ import { request } from "./declare";
6
+ import GptBase from "./gptbase"
7
+ import { Readable } from 'stream';
8
+ // import { ChatReponse } from './declare';
9
+ export default class AIMiddlePlatform extends GptBase {
10
+
11
+ protected apikey: string;
12
+ protected agent: { endpoint: string, agentid: string };
13
+ /**
14
+ *
15
+ * @param apikey 调用AI中台 的key
16
+ * @param agent 智能体信息
17
+ */
18
+ constructor(apikey: string, agent: { endpoint: string, agentid: string }) {
19
+ super();
20
+ this.apikey = apikey;
21
+ this.agent = agent;
22
+ }
23
+
24
+ /**
25
+ * 非流式传输聊天请求
26
+ * @param chatText
27
+ * @param callChatOption
28
+ * @param axiosOption
29
+ */
30
+ public async chatRequest(chatText: string | any, callChatOption: any, axiosOption: any = {}): Promise<any> {
31
+ if (!chatText) {
32
+ this.emit('chaterror', { successed: false, error: 'no text in chat' });
33
+ return { successed: false, error: 'no text in chat' };
34
+ }
35
+ const question = typeof chatText === 'object' ? chatText.text ?? chatText.content : chatText;
36
+ axiosOption = Object.assign({}, axiosOption || { timeout: 60000 })
37
+ const opts: any = {
38
+ headers: {
39
+ 'Content-Type': 'application/json',
40
+ 'authorization': `Bearer ${this.apikey}`
41
+ },
42
+ method: 'post',
43
+ url: `${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`,
44
+ data: {
45
+ question,
46
+ session_id: callChatOption.session_id,
47
+ stream: false
48
+ },
49
+ ...axiosOption
50
+ }
51
+ console.log('Question===>', question)
52
+ const response = await request(opts);
53
+
54
+ if (!response.successed) return { successed: false, error: 'failed' };
55
+ console.log('reponse===>', response.data)
56
+ const {answer:message,session_id} = response.data.data;
57
+ this.emit('chatdone', { successed: true, segment: message, text: message, finish_reason: 'stop', index: 0, session_id })
58
+ return { successed: true, message,session_id };
59
+ }
60
+ /**
61
+ * 流式传输聊天请求
62
+ * @param chatText
63
+ * @param callChatOption
64
+ * @param attach
65
+ * @param axiosOption
66
+ * @returns
67
+ */
68
+ override async chatRequestInStream(chatText: string | any, callChatOption: any, attach?: any, axiosOption?: any): Promise<any> {
69
+ if (!chatText) this.emit('chaterror', { successed: false, error: 'no text in chat' });
70
+ // console.log('Question===>', chatText)
71
+ const question = typeof chatText === 'object' ? chatText.text??chatText.content : chatText;
72
+ axiosOption = Object.assign({}, axiosOption || { timeout: 60000 })
73
+ let requestid = Math.ceil(Math.random() * (new Date().getTime() * Math.random()) / 1000);
74
+ try {
75
+ const opts: any = {
76
+ headers: {
77
+ 'Content-Type': 'application/json',
78
+ 'authorization': `Bearer ${this.apikey}`
79
+ },
80
+ method: 'post',
81
+ url: `${this.agent.endpoint}/api/v1/agents/${this.agent.agentid}/completions`,
82
+ data: {
83
+ question,
84
+ session_id: callChatOption.session_id,
85
+ stream: true,
86
+ optional: callChatOption.optional,
87
+ },
88
+ responseType: 'stream',
89
+ ...axiosOption
90
+ }
91
+ const response = await axios(opts);
92
+ const readableStream = Readable.from(response.data);
93
+ let index = 0, session_id,fullanswer='',errorKeeped=[];
94
+ for await (const chunk of readableStream) {
95
+ ///可能接收到的数据不完整,导致JSON.parse失败
96
+ let answerData = null, jsonStr = '';
97
+ try{
98
+ jsonStr = chunk.toString().split('data:')
99
+ if (jsonStr.length) jsonStr = jsonStr[jsonStr.length-1]+''
100
+ answerData = JSON.parse(errorKeeped.join('') + jsonStr);
101
+ }catch(e){
102
+ ////如果发生了JSON解析错误,则当前的数据不完整,留着拼凑下一回数据
103
+ // console.log('json parse error===>', errorKeeped.join('') + jsonStr)
104
+ errorKeeped.push(jsonStr)
105
+ // console.log('After Push===>', errorKeeped.join('') )
106
+ continue;
107
+ }
108
+ errorKeeped = [];
109
+ const { answer, running_status } = answerData.data;
110
+ if (running_status === true) continue;
111
+ const segment = answer ? answer.replace(fullanswer,''):''
112
+ fullanswer = answer ?? fullanswer;
113
+ if (!session_id) session_id = answerData.data.session_id;
114
+ const finished = answerData.data === true;
115
+ let output = { successed: true, requestid, segment: segment, text: fullanswer, finish_reason: finished ? 'stop' : null, index: index++, session_id };
116
+ if (attach) output = Object.assign({}, output, attach);
117
+ this.emit(finished ? 'chatdone' : 'chattext', output)
118
+ }
119
+ return { successed: true, requestid }
120
+ } catch (error) {
121
+
122
+ // this.emit('requesterror', { successed: false, requestid, error: 'call axios faied ' + error });
123
+ // return { successed: false, requestid }
124
+ }
125
+ }
126
+ }
package/src/doubaoai.ts CHANGED
@@ -22,16 +22,12 @@ export default class DouBaoAI extends GptBase {
22
22
  const callParams = this.assembleApiParams(chatText, false, callChatOption, axiosOption);
23
23
  try {
24
24
  const response = await request(callParams)
25
- if (response.successed && !response.data.code) {
26
- return { successed: true, message: response.data.choices, usage: response.data.usage }
27
- // return { successed: true, ...response.data };
28
- }
25
+ if (response.successed && !response.data.code) return { successed: true, message: response.data.choices, usage: response.data.usage }
29
26
  return { successed: false, ...response.data };
30
27
  } catch (error) {
31
28
  console.log('result is error ', error)
32
29
  return { successed: false, error };
33
30
  }
34
-
35
31
  }
36
32
  /**
37
33
  * 组装最后的调用参数
@@ -8,6 +8,7 @@ import AzureAI from './azureai'
8
8
  import StabilityAI from './stabilityai'
9
9
  import StabilityPlusAI from './stabilityplusai'
10
10
  import BaiduWenXinAI, { ApiCredential } from './baiduai'
11
+ import AIMiddlePlatform from './aimp';
11
12
  import DouBaoAI from './doubaoai'
12
13
  import GptBase from './gptbase';
13
14
  /**
@@ -17,6 +18,7 @@ export const GptProviderEnum = {
17
18
  OPENAI: 'openai',
18
19
  OPENAIPROXY:'openaiproxy',
19
20
  MICROSOFT: 'microsoft',
21
+ AIMP: 'aimp', ///AI 中台业务
20
22
  BAIDU: 'baidu',
21
23
  DOUBAO:'doubao',
22
24
  GOOGLE:'google',
@@ -32,7 +34,7 @@ export type GptProviderEnum = typeof GptProviderEnum[keyof typeof GptProviderEnu
32
34
  * @returns
33
35
  */
34
36
  export function createGpt(provider: GptProviderEnum, apikey: string|ApiCredential, setting: any): GptBase | null {
35
- let { model, maxtoken, temperature, serviceurl,endpoint, engine, version, embedding, top_p, presence_penalty, frequency_penalty } = setting || {};
37
+ let { model,agentid, maxtoken, temperature, serviceurl,endpoint, engine, version, embedding, top_p, presence_penalty, frequency_penalty } = setting || {};
36
38
  switch (provider) {
37
39
  case GptProviderEnum.OPENAI:
38
40
  return new OpenAIGpt(apikey + '', { model, maxtoken, temperature, embedding, top_p, presence_penalty, frequency_penalty });
@@ -41,8 +43,10 @@ export function createGpt(provider: GptProviderEnum, apikey: string|ApiCredentia
41
43
  case GptProviderEnum.MICROSOFT:
42
44
  return new AzureAI(apikey + '', { endpoint, engine, version }, { model, maxtoken, temperature, embedding, top_p, presence_penalty, frequency_penalty }, );
43
45
  case GptProviderEnum.BAIDU:
44
- let cred: ApiCredential = typeof (apikey) === 'string' ? { apikey, securitykey: apikey } : apikey
46
+ let cred: ApiCredential = typeof (apikey) === 'string' ? { apikey, securitykey: apikey } : apikey;
45
47
  return new BaiduWenXinAI(cred);
48
+ case GptProviderEnum.AIMP:
49
+ return new AIMiddlePlatform(apikey+'',{ endpoint,agentid });
46
50
  case GptProviderEnum.DOUBAO:
47
51
  return new DouBaoAI(apikey + '', { model, maxtoken, temperature, top_p, presence_penalty, frequency_penalty })
48
52
  case GptProviderEnum.STABILITY: