doomiaichat 7.1.29 → 7.1.31

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.
Files changed (65) hide show
  1. package/dist/index.esm.js +16 -0
  2. package/dist/index.js +16 -28
  3. package/dist/{aimp.d.ts → types/aimp.d.ts} +1 -0
  4. package/dist/types/aimp.d.ts.map +1 -0
  5. package/dist/{azureai.d.ts → types/azureai.d.ts} +1 -0
  6. package/dist/types/azureai.d.ts.map +1 -0
  7. package/dist/{corzauthorization.d.ts → types/corzauthorization.d.ts} +1 -0
  8. package/dist/types/corzauthorization.d.ts.map +1 -0
  9. package/dist/{corzbot.d.ts → types/corzbot.d.ts} +1 -0
  10. package/dist/types/corzbot.d.ts.map +1 -0
  11. package/dist/{declare.d.ts → types/declare.d.ts} +2 -1
  12. package/dist/types/declare.d.ts.map +1 -0
  13. package/dist/{doubaoai.d.ts → types/doubaoai.d.ts} +1 -0
  14. package/dist/types/doubaoai.d.ts.map +1 -0
  15. package/dist/{gptbase.d.ts → types/gptbase.d.ts} +1 -1
  16. package/dist/types/gptbase.d.ts.map +1 -0
  17. package/dist/{gptprovider.d.ts → types/gptprovider.d.ts} +2 -7
  18. package/dist/types/gptprovider.d.ts.map +1 -0
  19. package/dist/{index.d.ts → types/index.d.ts} +1 -0
  20. package/dist/types/index.d.ts.map +1 -0
  21. package/dist/{openai.d.ts → types/openai.d.ts} +1 -0
  22. package/dist/types/openai.d.ts.map +1 -0
  23. package/dist/{openaibase.d.ts → types/openaibase.d.ts} +1 -0
  24. package/dist/types/openaibase.d.ts.map +1 -0
  25. package/dist/{openaiproxy.d.ts → types/openaiproxy.d.ts} +1 -0
  26. package/dist/types/openaiproxy.d.ts.map +1 -0
  27. package/package.json +16 -4
  28. package/dist/aimp.js +0 -162
  29. package/dist/azureai.js +0 -220
  30. package/dist/baiduai.d.ts +0 -28
  31. package/dist/baiduai.js +0 -92
  32. package/dist/corzauthorization.js +0 -79
  33. package/dist/corzbot.js +0 -490
  34. package/dist/declare.js +0 -51
  35. package/dist/deepseek.d.ts +0 -5
  36. package/dist/deepseek.js +0 -16
  37. package/dist/doubaoai.js +0 -149
  38. package/dist/gptbase.js +0 -58
  39. package/dist/gptprovider.js +0 -80
  40. package/dist/openai.js +0 -184
  41. package/dist/openaibase.js +0 -20
  42. package/dist/openaiprovider.d.ts +0 -20
  43. package/dist/openaiprovider.js +0 -43
  44. package/dist/openaiproxy.js +0 -108
  45. package/dist/stabilityai.d.ts +0 -18
  46. package/dist/stabilityai.js +0 -75
  47. package/dist/stabilityplusai.d.ts +0 -11
  48. package/dist/stabilityplusai.js +0 -86
  49. package/src/aimp.ts +0 -125
  50. package/src/azureai.ts +0 -180
  51. package/src/baiduai.ts +0 -86
  52. package/src/corzauthorization.ts +0 -59
  53. package/src/corzbot.ts +0 -434
  54. package/src/declare.ts +0 -152
  55. package/src/deepseek.ts +0 -11
  56. package/src/doubaoai.ts +0 -129
  57. package/src/gptbase.ts +0 -52
  58. package/src/gptprovider.ts +0 -74
  59. package/src/index.ts +0 -2
  60. package/src/openai.ts +0 -136
  61. package/src/openaibase.ts +0 -30
  62. package/src/openaiproxy.ts +0 -97
  63. package/src/stabilityai.ts +0 -67
  64. package/src/stabilityplusai.ts +0 -77
  65. package/tsconfig.json +0 -31
package/dist/baiduai.js DELETED
@@ -1,92 +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 __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- const declare_1 = require("./declare");
16
- const gptbase_1 = __importDefault(require("./gptbase"));
17
- const TOKEN_CACHE_KEY = "key:_doomisoft:baiduwenxin:";
18
- class BaiduWenXinAI extends gptbase_1.default {
19
- /**
20
- *
21
- * @param credential 调用OpenAI 的key
22
- * @param cacher 用作accesstoken的缓存
23
- * @param apiOption 用作accesstoken的缓存
24
- */
25
- constructor(credential, cacher) {
26
- super();
27
- this.credential = credential;
28
- this.Cacher = cacher;
29
- }
30
- /**
31
- * 获取调用Api的Token
32
- */
33
- getAccessToken() {
34
- return __awaiter(this, void 0, void 0, function* () {
35
- ////如果当前应用是一个委托到第三方的
36
- ///公众号或小程序,则需要用关联的第三方平台来获取api调用的accesstoken
37
- ////如果是需要缓存token,则首先看缓存中是否有AccessToken
38
- const accesstoken = this.Cacher ? (yield this.Cacher.get(TOKEN_CACHE_KEY + this.credential.apikey)) : null;
39
- if (accesstoken)
40
- return { successed: true, access_token: accesstoken };
41
- const option = {
42
- url: `https://wenxin.baidu.com/moduleApi/portal/api/oauth/token?grant_type=client_credentials&client_id=${this.credential.apikey}&client_secret=${this.credential.securitykey}`,
43
- method: "post",
44
- };
45
- const tokenData = yield (0, declare_1.request)(option);
46
- if (tokenData.successed == true && !tokenData.data.code) {
47
- ///把api accesstoken缓存起来
48
- if (this.Cacher) {
49
- this.Cacher.set(TOKEN_CACHE_KEY + this.credential.apikey, tokenData.data.data, 3600 * 20);
50
- }
51
- return { successed: true, access_token: tokenData.data.data };
52
- }
53
- return { successed: false, error: tokenData.data.msg };
54
- });
55
- }
56
- /**
57
- * 请求GPT接口
58
- */
59
- chatRequest(chatText, _paramOption, axiosOption = {}) {
60
- return __awaiter(this, void 0, void 0, function* () {
61
- console.log('call baidu');
62
- if (!chatText)
63
- return { successed: false, error: { errcode: 2, errmsg: '缺失聊天的内容' } };
64
- const accessToken = yield this.getAccessToken();
65
- if (!accessToken.successed || !accessToken.access_token)
66
- return { successed: false, error: 'accesstoken get failed' };
67
- try {
68
- let param = Object.assign(Object.assign({}, axiosOption), { method: "post", data: {
69
- text: `问题:${chatText}\n回答:`,
70
- seq_len: 512,
71
- topp: 0.5,
72
- penalty_score: 1.2,
73
- min_dec_len: 12,
74
- min_dec_penalty_text: "。?:![<S>]",
75
- task_prompt: "qa",
76
- mask_type: "paragraph"
77
- }, url: `https://wenxin.baidu.com/moduleApi/portal/api/rest/1.0/ernie/3.0.25/zeus?access_token=${accessToken.access_token}` });
78
- console.log('param', param);
79
- const response = yield (0, declare_1.request)(param);
80
- if (response.successed && !response.data.code) {
81
- return Object.assign({ successed: true }, response.data);
82
- }
83
- return Object.assign({ successed: false }, response.data);
84
- }
85
- catch (error) {
86
- console.log('result is error ', error);
87
- return { successed: false, error };
88
- }
89
- });
90
- }
91
- }
92
- exports.default = BaiduWenXinAI;
@@ -1,79 +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 __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
- Object.defineProperty(exports, "__esModule", { value: true });
15
- exports.CorzAuthorization = void 0;
16
- const fs_1 = __importDefault(require("fs"));
17
- const path_1 = __importDefault(require("path"));
18
- const api_1 = require("@coze/api");
19
- class CorzAuthorization {
20
- constructor(appid, setting) {
21
- this.appid = appid;
22
- this.expiresAt = 0;
23
- this.secret = setting["keyid"];
24
- this.pemfile = setting["pemfile"] || "private.pem";
25
- this.sessionName = setting["sessionName"] || "default";
26
- }
27
- /**
28
- * 获取授权令牌
29
- * @returns
30
- */
31
- getAccessToken() {
32
- return __awaiter(this, void 0, void 0, function* () {
33
- // 检查令牌是否存在且未过期,如果有效直接放回
34
- if (this.accessToken && Date.now() < this.expiresAt)
35
- return this.accessToken;
36
- // 开始新的授权
37
- const result = yield this.doAuthorize();
38
- if (!result.successed)
39
- return null;
40
- // 缓存授权令牌和过期时间
41
- this.accessToken = result.accessToken;
42
- // 将 expires_in 转换为绝对时间戳
43
- this.expiresAt = result.expires_in * 1000; // 将秒转换为毫秒
44
- return this.accessToken;
45
- });
46
- }
47
- /**
48
- * 进行授权
49
- * @returns
50
- */
51
- doAuthorize() {
52
- return __awaiter(this, void 0, void 0, function* () {
53
- try {
54
- // 提取您的 COZE API 授权参数
55
- //const keyid = "H7rAk-5s0TPOs9-rXnCr7pvkPhpJZGArT__UuMyhbkg";
56
- const aud = "api.coze.cn";
57
- // 读取私钥
58
- const fileFullPath = path_1.default.join(process.cwd(), this.pemfile);
59
- if (!fs_1.default.existsSync(fileFullPath))
60
- return { successed: false, error: `${fileFullPath} not existed` };
61
- const privateKey = fs_1.default.readFileSync(fileFullPath).toString();
62
- // 获取JWT令牌
63
- const result = yield (0, api_1.getJWTToken)({
64
- baseURL: api_1.COZE_CN_BASE_URL,
65
- appId: this.appid,
66
- aud,
67
- keyid: this.secret,
68
- privateKey,
69
- sessionName: this.sessionName,
70
- });
71
- return { successed: true, accessToken: result.access_token, expires_in: result.expires_in };
72
- }
73
- catch (error) {
74
- return { successed: true, error };
75
- }
76
- });
77
- }
78
- }
79
- exports.CorzAuthorization = CorzAuthorization;
package/dist/corzbot.js DELETED
@@ -1,490 +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
- * 扣子智能体
24
- */
25
- const api_1 = require("@coze/api");
26
- const gptbase_1 = __importDefault(require("./gptbase"));
27
- const querystring_1 = require("querystring");
28
- const fs_1 = require("fs");
29
- const path_1 = require("path");
30
- // 定义深度思考的动作标签
31
- // 这是小鹭里面专用的几个思考动作标签
32
- const DeepThinkingAction = {
33
- thinking: { start: '<xiaolu-think>', end: '</xiaolu-think>', tag: 'xiaolu-think' },
34
- reasoning: { start: '<xiaolu-reason>', end: '</xiaolu-reason>', tag: 'xiaolu-reason' },
35
- card: { start: '<xiaolu-card>', end: '</xiaolu-card>', tag: 'xiaolu-card' },
36
- preresponse: { start: '<xiaolu-preresponse>', end: '</xiaolu-preresponse>', tag: 'xiaolu-preresponse' },
37
- };
38
- // 定义深度思考的状态
39
- var DeepThinkingStatus;
40
- (function (DeepThinkingStatus) {
41
- DeepThinkingStatus[DeepThinkingStatus["None"] = 0] = "None";
42
- DeepThinkingStatus[DeepThinkingStatus["Thinking"] = 1] = "Thinking";
43
- // ContentOutput,
44
- DeepThinkingStatus[DeepThinkingStatus["ThinkingOver"] = 2] = "ThinkingOver";
45
- })(DeepThinkingStatus || (DeepThinkingStatus = {}));
46
- // type TThinkingMessage = { action: string, textposition: number }
47
- class CorzBot extends gptbase_1.default {
48
- /**
49
- *
50
- * @param apikey 调用AI中台 的key
51
- * @param botid 智能体信息
52
- */
53
- constructor(authorizationProvider, setting = {}) {
54
- super();
55
- this.authorizationProvider = authorizationProvider;
56
- this.setting = setting;
57
- this.botid = null; // 智能体id
58
- this.workflowid = null; // 工作流id
59
- this.talkflowid = null; // 对话流id
60
- this.debugDir = '';
61
- this.debug = false;
62
- ////初始化扣子客户端
63
- if (this.setting.workflowid)
64
- this.workflowid = this.setting.workflowid;
65
- else if (this.setting.talkflowid)
66
- this.talkflowid = this.setting.talkflowid;
67
- else if (this.setting.botid || this.setting.botID)
68
- this.botid = this.setting.botid || this.setting.botID;
69
- else
70
- throw new Error('no botid or talkflowid or workflowid setting for coze');
71
- /// 如果开启debug模式,则创建记录日志的目录,将日志输出到该目录
72
- if (setting.debug === true) {
73
- this.debug = true;
74
- this.debugDir = (0, path_1.join)(setting.logPath || (0, path_1.resolve)(process.cwd(), './cozedebug'), this.setting.model || 'chat');
75
- (0, fs_1.mkdirSync)(this.debugDir, { recursive: true });
76
- }
77
- this.apiKey = this.setting['apiKey'];
78
- }
79
- createClient() {
80
- return __awaiter(this, void 0, void 0, function* () {
81
- // 存在AppKey则使用AppKey进行认证
82
- if (this.apiKey)
83
- return new api_1.CozeAPI({ baseURL: api_1.COZE_CN_BASE_URL, token: this.apiKey });
84
- const accessToken = yield this.authorizationProvider.getAccessToken();
85
- if (!accessToken)
86
- throw new Error('get access token failed');
87
- return new api_1.CozeAPI({ baseURL: api_1.COZE_CN_BASE_URL, token: accessToken });
88
- });
89
- }
90
- /**
91
- * 发起一次会话
92
- */
93
- createCoversation(client) {
94
- return __awaiter(this, void 0, void 0, function* () {
95
- try {
96
- const czApi = client !== null && client !== void 0 ? client : yield this.createClient();
97
- const params = this.botid ? { bot_id: this.botid } : {};
98
- const result = yield czApi.conversations.create(params);
99
- return result.id;
100
- }
101
- catch (error) {
102
- console.error('createCoversation error in coze api');
103
- return null;
104
- }
105
- });
106
- }
107
- /**
108
- * 设置Coze的变量
109
- * @param params
110
- * @returns
111
- */
112
- setVariables(params = {}) {
113
- return __awaiter(this, void 0, void 0, function* () {
114
- const client = yield this.createClient();
115
- !params.type && (params.type = 'app');
116
- const cozeParams = { data: params.data };
117
- params.type === 'app' && (cozeParams.app_id = this.authorizationProvider.appid);
118
- params.type === 'bot' && this.botid && (cozeParams.bot_id = this.botid);
119
- params.user_id && (cozeParams.connector_uid = params.user_id);
120
- //Object.assign({ connector_uid: params?.user_id||'123456' }, params.type==='app'?{app_id:this.authorizationProvider.appid}:(params.type==='bot' ? { bot_id: this.botid } : {}), params);
121
- const result = yield client.variables.update(cozeParams, { debug: true });
122
- console.log('setVariables result', result);
123
- return { successed: true };
124
- });
125
- }
126
- /**
127
- * 获取设置的变量
128
- * @returns
129
- */
130
- getVariables(params) {
131
- return __awaiter(this, void 0, void 0, function* () {
132
- const client = yield this.createClient();
133
- const cozeParams = Object.assign({}, { bot_id: this.botid }, params);
134
- const data = yield client.variables.retrieve(cozeParams);
135
- if (data)
136
- return Object.assign({ successed: true }, data);
137
- return { successed: false, error: 'get variables failed' };
138
- });
139
- }
140
- /**
141
- * 组装请求参数
142
- * @param message
143
- * @param callChatOption
144
- * @param attach
145
- * @param _axiosOption
146
- */
147
- getRequestStream(client, message, callChatOption = {}) {
148
- var _a, _b;
149
- return __awaiter(this, void 0, void 0, function* () {
150
- //简单的对话请求
151
- if (this.botid) {
152
- const req = {
153
- bot_id: this.botid,
154
- additional_messages: message,
155
- user_id: callChatOption.userid || callChatOption.cozeUserID,
156
- conversation_id: (_a = callChatOption.session_id) !== null && _a !== void 0 ? _a : yield this.createCoversation(client),
157
- parameters: Object.assign({ request_src: 1 }, callChatOption.parameters || {}),
158
- };
159
- req.custom_variables = Object.assign({}, this.setting.customVariables || {}, callChatOption.customVariables || {});
160
- return req;
161
- }
162
- if (this.workflowid) {
163
- const worflowreq = {
164
- ext: callChatOption.ext,
165
- workflow_id: this.workflowid,
166
- is_async: false,
167
- // parameters: Object.assign({ input: message[0]?.content }, this.setting.customVariables || {}, callChatOption.customVariables || {}),
168
- // parameters: Object.assign({ request_src: 1 }, callChatOption.parameters || {}, { input: message[0]?.content })
169
- parameters: Object.assign({ request_src: 1 }, callChatOption.parameters || {}, { input: message })
170
- };
171
- if (callChatOption.userid || callChatOption.cozeUserID)
172
- worflowreq.ext = Object.assign({}, worflowreq.ext || {}, { user_id: callChatOption.userid || callChatOption.cozeUserID });
173
- return worflowreq;
174
- }
175
- const worflowreq = {
176
- additional_messages: message,
177
- ext: { user_id: '12345678' },
178
- workflow_id: this.talkflowid,
179
- conversation_id: (_b = callChatOption.session_id) !== null && _b !== void 0 ? _b : yield this.createCoversation(client),
180
- parameters: Object.assign({ request_src: 1 }, callChatOption.parameters || {}) //Object.assign({}, this.setting.customVariables || {}, callChatOption.customVariables || {}),
181
- };
182
- if (callChatOption.userid || callChatOption.cozeUserID)
183
- worflowreq.ext = Object.assign({}, worflowreq.ext || {}, { user_id: callChatOption.userid || callChatOption.cozeUserID });
184
- return worflowreq;
185
- });
186
- }
187
- /**
188
- * 同步调用的问答请求需要获取会话详情
189
- * @param chatid
190
- * @param conversation_id
191
- */
192
- getChatDetail(client, conversation_id, chatid) {
193
- return __awaiter(this, void 0, void 0, function* () {
194
- const maxWaitTime = 120000; // 最大等待120秒
195
- const startTime = Date.now();
196
- while ((Date.now() - startTime) < maxWaitTime) {
197
- const chatinfo = yield client.chat.retrieve(conversation_id, chatid);
198
- // 状态已经是完成了,可以去获取对话的内容了
199
- if (chatinfo.status === api_1.ChatStatus.COMPLETED)
200
- return { usage: chatinfo.usage, messages: yield client.chat.messages.list(conversation_id, chatid) };
201
- yield new Promise(resolve => setTimeout(resolve, 1500)); // 等待1500ms
202
- }
203
- return null;
204
- });
205
- }
206
- /**
207
- * 非流式传输聊天请求
208
- * @param chatText
209
- * @param callChatOption
210
- * @param _axiosOption
211
- */
212
- chatRequest(message, callChatOption = {}, _axiosOption = {}) {
213
- return __awaiter(this, void 0, void 0, function* () {
214
- if (!message)
215
- this.emit('chaterror', { successed: false, error: 'no message in chat' });
216
- ///如果是字符,则组装成API需要的消息
217
- if (typeof message === 'string')
218
- message = [
219
- {
220
- role: api_1.RoleType.User,
221
- content_type: 'text',
222
- content: message
223
- }
224
- ];
225
- const client = yield this.createClient();
226
- const debugStream = this.debug ? (0, fs_1.createWriteStream)((0, path_1.join)(this.debugDir, `sync_${this.formatDateWithMs()}.log`), { flags: 'a' }) : null;
227
- ////如果参数中用的是Workflow,则调用对话流来输出结果
228
- ////否则用智能体的对话来输出结果
229
- const params = yield this.getRequestStream(client, message, callChatOption);
230
- if (debugStream) {
231
- debugStream.write(`callChatOption:${JSON.stringify(callChatOption)}\n`);
232
- debugStream.write(`parameters:${JSON.stringify(params)}\n`);
233
- }
234
- const response = this.botid ? yield client.chat.create(params) : yield client.workflows.runs.create(params);
235
- if (this.workflowid) {
236
- const workflowResp = response;
237
- if (workflowResp.msg === 'Success' || (!workflowResp.msg && workflowResp.data)) {
238
- const resp = workflowResp.data;
239
- debugStream && debugStream.end(resp);
240
- return { successed: true, message: [{ role: 'assistant', type: 'answer', content: resp }] };
241
- }
242
- debugStream && debugStream.end('workflow run failed');
243
- console.error('workflow run failed', workflowResp.msg, workflowResp);
244
- }
245
- if (!this.workflowid && response.conversation_id && response.id) {
246
- const ccd = response;
247
- const chatData = yield this.getChatDetail(client, ccd.conversation_id, ccd.id);
248
- if (chatData) {
249
- const message = chatData.messages.filter(x => x.type === 'answer').map(item => ({
250
- role: item.role,
251
- type: item.type,
252
- content: item.content,
253
- }));
254
- return { successed: true, message, usage: chatData.usage, session_id: ccd.conversation_id };
255
- }
256
- }
257
- debugStream && debugStream.end('聊天未完成');
258
- return { successed: false, error: { message: '聊天未完成' } };
259
- });
260
- }
261
- /**
262
- * 提取XML标签中间的内容,
263
- * @param xmlStr
264
- * @param tagName
265
- * @returns
266
- */
267
- extractXmlContent(xmlStr, tagName) {
268
- // 构建匹配标签的正则(支持任意空白字符和大小写)
269
- const regex = new RegExp(`<\\s*${tagName}\\s*>([\\s\\S]*?)<\\s*\\/\\s*${tagName}\\s*>`, 'i');
270
- const match = xmlStr.match(regex);
271
- if (match && match[1])
272
- return match[1].trim();
273
- return ''; // 未找到标签或内容
274
- }
275
- /**
276
- * 解析深度思考的JSON内容
277
- * @param content
278
- * @param status
279
- * @returns
280
- */
281
- parseDeepThinkingJson(content) {
282
- // const thinkingStartIndex = status === DeepThinkingStatus.Thinking ? content.indexOf("{\"process_msg") :
283
- // (status===DeepThinkingStatus.ReasonOutput ? content.indexOf("{\"reasoning_content") : content.indexOf("{\"card_resource")) ;
284
- const xmlTagLocation = [content.indexOf(DeepThinkingAction.thinking.start),
285
- content.indexOf(DeepThinkingAction.reasoning.start),
286
- content.indexOf(DeepThinkingAction.card.start),
287
- content.indexOf(DeepThinkingAction.preresponse.start)];
288
- let minLocation = 10000, minIndex = -1;
289
- // 找到最小的并且大于0 的位置的下标
290
- xmlTagLocation.forEach((x, index) => {
291
- if (x >= 0 && x < minLocation) {
292
- minLocation = x;
293
- minIndex = index;
294
- }
295
- });
296
- // const tagLocation = xmlTagLocation.filter(x => x >= 0);
297
- const thinkingStartIndex = minIndex >= 0 ? minLocation : -1; //tagLocation.length > 0 ? Math.min(...tagLocation) : -1;
298
- if (thinkingStartIndex < 0)
299
- return { content, status: DeepThinkingStatus.ThinkingOver };
300
- const currentAction = [DeepThinkingAction.thinking, DeepThinkingAction.reasoning, DeepThinkingAction.card, DeepThinkingAction.preresponse][minIndex];
301
- const currentActionIsOver = content.indexOf(currentAction.end, thinkingStartIndex);
302
- const thinkingEndIndex = currentActionIsOver >= 0 ? currentActionIsOver : content.indexOf('</', thinkingStartIndex);
303
- const thinkingContent = this.extractXmlContent(content.substring(thinkingStartIndex, thinkingEndIndex >= 0 ? thinkingEndIndex : undefined) + currentAction.end, currentAction.tag); //"\"}";
304
- if (currentActionIsOver >= 0)
305
- content = content.substring(currentActionIsOver + currentAction.end.length);
306
- return {
307
- thinking: {
308
- action: currentAction,
309
- text: thinkingContent,
310
- completed: currentActionIsOver >= 0
311
- }, content
312
- };
313
- }
314
- /**
315
- *
316
- * @param date
317
- * @returns
318
- */
319
- formatDateWithMs(date = new Date()) {
320
- // 获取各时间部分
321
- const year = date.getFullYear(); // 年(4位)
322
- const month = String(date.getMonth() + 1).padStart(2, '0'); // 月(补0,2位)
323
- const day = String(date.getDate()).padStart(2, '0'); // 日(补0,2位)
324
- const hours = String(date.getHours()).padStart(2, '0'); // 时(补0,2位)
325
- const minutes = String(date.getMinutes()).padStart(2, '0'); // 分(补0,2位)
326
- const seconds = String(date.getSeconds()).padStart(2, '0'); // 秒(补0,2位)
327
- const milliseconds = String(date.getMilliseconds()).padStart(3, '0'); // 毫秒(补0,3位)
328
- // 拼接成 yyyymmddhhmmssSSS 格式
329
- return `${year}${month}${day}${hours}${minutes}${seconds}${milliseconds}`;
330
- }
331
- /**
332
- * 流式传输聊天请求
333
- * @param chatText
334
- * @param callChatOption
335
- * @param attach
336
- * @param _axiosOption
337
- * @returns
338
- */
339
- chatRequestInStream(message, callChatOption = {}, attach, _axiosOption) {
340
- var _a, e_1, _b, _c;
341
- var _d, _e, _f;
342
- return __awaiter(this, void 0, void 0, function* () {
343
- if (!message)
344
- this.emit('chaterror', { successed: false, error: 'no message in chat' });
345
- ///如果是字符,则组装成API需要的消息
346
- if (typeof message === 'string')
347
- message = [
348
- {
349
- role: api_1.RoleType.User,
350
- content_type: 'text',
351
- content: message
352
- }
353
- ];
354
- const client = yield this.createClient();
355
- ////如果参数中用的是Workflow,则调用对话流来输出结果
356
- ////否则用智能体的对话来输出结果
357
- let requestid = Math.ceil(Math.random() * (new Date().getTime() * Math.random()) / 1000), index = 0;
358
- const debugStream = this.debug ? (0, fs_1.createWriteStream)((0, path_1.join)(this.debugDir, `${this.formatDateWithMs()}.log`), { flags: 'a' }) : null;
359
- const params = yield this.getRequestStream(client, message, callChatOption);
360
- if (debugStream) {
361
- debugStream.write(`callChatOption:${JSON.stringify(callChatOption)}\n`);
362
- debugStream.write(`attach:${attach ? JSON.stringify(attach) : 'null'}\n`);
363
- debugStream.write(`parameters:${JSON.stringify(params)}\n`);
364
- }
365
- const stream = this.botid ? client.chat.stream(params) :
366
- (this.workflowid ? client.workflows.runs.stream(params) :
367
- client.workflows.chat.stream(params));
368
- let deltaindex = 0, fullanswer = [], cardfollowup = [], followup = [], cardData = [];
369
- let deepThinking = '', thinkingStatus = DeepThinkingStatus.None, cardResource = '', preresponseText = ''; // 是否在深度思考中
370
- try {
371
- for (var _g = true, stream_1 = __asyncValues(stream), stream_1_1; stream_1_1 = yield stream_1.next(), _a = stream_1_1.done, !_a;) {
372
- _c = stream_1_1.value;
373
- _g = false;
374
- try {
375
- const part = _c;
376
- if (part.event === api_1.ChatEventType.ERROR) {
377
- if (debugStream)
378
- debugStream.write('chat error:');
379
- return this.emit('chaterror', { successed: false, error: 'call failed' });
380
- }
381
- if (part.event === api_1.ChatEventType.CONVERSATION_MESSAGE_DELTA ||
382
- part.event === api_1.WorkflowEventType.MESSAGE) {
383
- let { conversation_id, content_type, type = 'answer', role = 'assistant', content, reasoning_content: reasoning } = part.data;
384
- if (debugStream)
385
- debugStream.write(content);
386
- if (content === 'Default')
387
- continue;
388
- if (!content && reasoning) {
389
- this.emit('chatthinking', { text: reasoning, completed: false, action: 'deep-thinking' });
390
- continue;
391
- }
392
- // 如果存在深度思考,则一开始就会带有相关的关键信息
393
- if (deltaindex === 0 && content.startsWith("<xiaolu-")) {
394
- thinkingStatus = DeepThinkingStatus.Thinking;
395
- deltaindex++;
396
- }
397
- // 如果在深度思考中,则不输出消息
398
- if (thinkingStatus === DeepThinkingStatus.Thinking) {
399
- deepThinking += content;
400
- const result = this.parseDeepThinkingJson(deepThinking);
401
- const thinking = result.thinking;
402
- if (thinking) {
403
- deepThinking = result.content;
404
- if (thinking.action === DeepThinkingAction.card) {
405
- cardResource += result.thinking.text;
406
- // 卡片流结束,解析卡片资源数据
407
- if (result.thinking.completed) {
408
- const allCards = cardResource.replace(/[\x00-\x1F\x7F]/g, '').split('|');
409
- cardResource = '';
410
- for (const item of allCards) {
411
- const cardinfo = (0, querystring_1.parse)(item);
412
- if (cardinfo.type && cardinfo.tag) {
413
- if (cardinfo.type === 'follow_up')
414
- cardfollowup.push(cardinfo.tag);
415
- else {
416
- const tags = cardinfo.tag.split(',');
417
- for (const tag of tags)
418
- cardData.push({ type: cardinfo.type, tag });
419
- //cardData.push({ ...cardinfo })
420
- }
421
- }
422
- }
423
- // 将卡片资源返回给客户端
424
- this.emit('chatcard', cardData);
425
- }
426
- }
427
- else if (thinking.action === DeepThinkingAction.preresponse) {
428
- /// 当正文一样输出
429
- const spiltPreresponse = result.thinking.text.slice(preresponseText.length);
430
- preresponseText = result.thinking.text;
431
- fullanswer.push(spiltPreresponse); // = [result.thinking.text];// .push(result.thinking.text);
432
- let output = { successed: true, type, content_type, role, requestid, segment: spiltPreresponse, text: fullanswer.join(''), index: index++, session_id: conversation_id, preresponse: true, preresponseover: result.thinking.completed };
433
- if (attach)
434
- output = Object.assign({}, output, attach);
435
- this.emit('chattext', output);
436
- }
437
- else {
438
- this.emit('chatthinking', { text: result.thinking.text, completed: result.thinking.completed, action: (_d = thinking.action) === null || _d === void 0 ? void 0 : _d.tag });
439
- }
440
- }
441
- if (result.status != DeepThinkingStatus.ThinkingOver)
442
- continue;
443
- thinkingStatus = DeepThinkingStatus.ThinkingOver;
444
- // 将排除了thinking之后的消息内容要带下去成为正式的输出内容
445
- content = deepThinking;
446
- }
447
- fullanswer.push(content);
448
- let output = { successed: true, type, content_type, role, requestid, segment: content, text: fullanswer.join(''), index: index++, session_id: conversation_id };
449
- if (attach)
450
- output = Object.assign({}, output, attach);
451
- this.emit('chattext', output);
452
- }
453
- ////在流式传输中,提取相关推荐问题
454
- if (part.event === api_1.ChatEventType.CONVERSATION_MESSAGE_COMPLETED) {
455
- const { type, content } = (_e = part.data) !== null && _e !== void 0 ? _e : {};
456
- if (type === 'follow_up') {
457
- if (debugStream)
458
- debugStream.write('followup:' + content);
459
- followup.push(content);
460
- }
461
- }
462
- ///整个对话结束
463
- if (part.event === api_1.ChatEventType.CONVERSATION_CHAT_COMPLETED ||
464
- part.event === api_1.WorkflowEventType.DONE) {
465
- const { conversation_id, content } = (_f = (part.data)) !== null && _f !== void 0 ? _f : {};
466
- let output = { successed: true, cards: cardData.length ? cardData : null, cardfollowup: cardfollowup.filter(x => typeof x === 'string' && x.length > 0), followup, type: 'answer', content_type: 'text', role: api_1.RoleType.Assistant, requestid, segment: null, text: content !== null && content !== void 0 ? content : fullanswer.join(''), index: index++, session_id: conversation_id };
467
- if (attach)
468
- output = Object.assign({}, output, attach);
469
- if (debugStream)
470
- debugStream.end('chat completed');
471
- this.emit('chatdone', output);
472
- }
473
- }
474
- finally {
475
- _g = true;
476
- }
477
- }
478
- }
479
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
480
- finally {
481
- try {
482
- if (!_g && !_a && (_b = stream_1.return)) yield _b.call(stream_1);
483
- }
484
- finally { if (e_1) throw e_1.error; }
485
- }
486
- return { successed: true, requestid };
487
- });
488
- }
489
- }
490
- exports.default = CorzBot;