doomiaichat 7.1.7 → 7.1.8

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/corzbot.js CHANGED
@@ -37,9 +37,8 @@ var DeepThinkingStatus;
37
37
  (function (DeepThinkingStatus) {
38
38
  DeepThinkingStatus[DeepThinkingStatus["None"] = 0] = "None";
39
39
  DeepThinkingStatus[DeepThinkingStatus["Thinking"] = 1] = "Thinking";
40
- DeepThinkingStatus[DeepThinkingStatus["ReasonOutput"] = 2] = "ReasonOutput";
41
- DeepThinkingStatus[DeepThinkingStatus["CardResource"] = 3] = "CardResource";
42
- DeepThinkingStatus[DeepThinkingStatus["ThinkingOver"] = 4] = "ThinkingOver";
40
+ DeepThinkingStatus[DeepThinkingStatus["ContentOutput"] = 2] = "ContentOutput";
41
+ DeepThinkingStatus[DeepThinkingStatus["ThinkingOver"] = 3] = "ThinkingOver";
43
42
  })(DeepThinkingStatus || (DeepThinkingStatus = {}));
44
43
  class CorzBot extends gptbase_1.default {
45
44
  // protected client: CozeAPI;
@@ -173,13 +172,13 @@ class CorzBot extends gptbase_1.default {
173
172
  * @returns
174
173
  */
175
174
  parseDeepThinkingJson(content, status) {
176
- var _a;
177
- const thinkingEndIndex = content.indexOf("\"}");
178
175
  // const thinkingStartIndex = status === DeepThinkingStatus.Thinking ? content.indexOf("{\"process_msg") :
179
176
  // (status===DeepThinkingStatus.ReasonOutput ? content.indexOf("{\"reasoning_content") : content.indexOf("{\"card_resource")) ;
180
- const thinkingStartIndex = (_a = [content.indexOf("{\"process_msg"),
177
+ const tagLocation = [content.indexOf("{\"process_msg"),
181
178
  content.indexOf("{\"reasoning_content"),
182
- content.indexOf("{\"card_resource")].find(x => x >= 0)) !== null && _a !== void 0 ? _a : -1;
179
+ content.indexOf("{\"card_resource")].filter(x => x >= 0);
180
+ const thinkingStartIndex = tagLocation.length > 0 ? Math.min(...tagLocation) : -1;
181
+ const thinkingEndIndex = content.indexOf("\"}");
183
182
  // 如果没有找到相关的JSON内容,则直接返回
184
183
  if (thinkingStartIndex < 0)
185
184
  return { successed: true, content, status: DeepThinkingStatus.ThinkingOver };
@@ -195,14 +194,12 @@ class CorzBot extends gptbase_1.default {
195
194
  if (thinkingEndIndex >= 0)
196
195
  content = content.substring(thinkingEndIndex + 2);
197
196
  // 如果正常输出了卡片资源,并且json结束 card_resource 只有一个,所以一旦结束,则整个思考过程完毕
198
- if (status === DeepThinkingStatus.CardResource && thinkingEndIndex >= 0)
199
- status = DeepThinkingStatus.ThinkingOver;
197
+ // if (status === DeepThinkingStatus.ContentOutput && thinkingEndIndex >= 0) status = DeepThinkingStatus.ThinkingOver;
200
198
  // 判断整个思考过程是否到达等待卡片资源(有可能智能体输出不了卡片资源) reasoning_content 只有一个,所以一旦结束,则进入下一个阶段 card_resource
201
- if (status === DeepThinkingStatus.ReasonOutput && thinkingEndIndex >= 0)
202
- status = DeepThinkingStatus.CardResource;
199
+ //if (status === DeepThinkingStatus.ContentOutput && thinkingEndIndex >= 0) status = DeepThinkingStatus.ContentOutput;
203
200
  // 判断当前是否从前期思考切换到思考内容输出
204
- if (status === DeepThinkingStatus.Thinking && thinkingAction === DeepThinkingAction.content)
205
- status = DeepThinkingStatus.ReasonOutput;
201
+ if (status === DeepThinkingStatus.Thinking && thinkingAction !== DeepThinkingAction.process)
202
+ status = DeepThinkingStatus.ContentOutput;
206
203
  //if (status === DeepThinkingStatus.Thinking && content.indexOf("{\"reasoning_content") >= 0) status=DeepThinkingStatus.ReasonOutput;
207
204
  //const removeOutputContent = content.replace(originalContent!.substring(1, originalContent!.length - 2),"")
208
205
  let thinkingContent = originalContent === null || originalContent === void 0 ? void 0 : originalContent.substring(0, originalContent.length - 2);
@@ -212,15 +209,17 @@ class CorzBot extends gptbase_1.default {
212
209
  thinkingContent = thinkingContent.substring(this.lastThinkingMessage.textposition);
213
210
  }
214
211
  this.lastThinkingMessage = thinkingEndIndex >= 0 ? { action: thinkingAction, textposition: 0 } : { action: thinkingAction, textposition: outputLength };
215
- return { successed: true, thinking: {
212
+ return {
213
+ successed: true, thinking: {
216
214
  action: thinkingAction,
217
215
  text: thinkingContent,
218
216
  completed: thinkingEndIndex >= 0
219
- }, content, status };
217
+ }, content, status
218
+ };
220
219
  }
221
220
  catch (error) {
222
221
  // 如果在content之后发生了错误,可能该智能体输出不了卡片类型的数据,则输出的内容已经是正文了
223
- if (status === DeepThinkingStatus.CardResource) {
222
+ if (status === DeepThinkingStatus.ContentOutput) {
224
223
  status = DeepThinkingStatus.ThinkingOver;
225
224
  return { successed: true, content, status };
226
225
  }
@@ -239,7 +238,6 @@ class CorzBot extends gptbase_1.default {
239
238
  */
240
239
  chatRequestInStream(message, callChatOption = {}, attach, _axiosOption) {
241
240
  var _a, e_1, _b, _c;
242
- var _d, _e;
243
241
  return __awaiter(this, void 0, void 0, function* () {
244
242
  if (!message)
245
243
  this.emit('chaterror', { successed: false, error: 'no message in chat' });
@@ -258,12 +256,12 @@ class CorzBot extends gptbase_1.default {
258
256
  let requestid = Math.ceil(Math.random() * (new Date().getTime() * Math.random()) / 1000), index = 0;
259
257
  const params = yield this.getRequestStream(client, message, callChatOption);
260
258
  const stream = !callChatOption.workflowid ? client.chat.stream(params) : client.workflows.chat.stream(params);
261
- let deltaindex = 0, fullanswer = [], followup = [];
259
+ let deltaindex = 0, fullanswer = [], followup = [], cardData = [];
262
260
  let deepThinking = '', thinkingStatus = DeepThinkingStatus.None, cardResource = ''; // 是否在深度思考中
263
261
  try {
264
- for (var _f = true, stream_1 = __asyncValues(stream), stream_1_1; stream_1_1 = yield stream_1.next(), _a = stream_1_1.done, !_a;) {
262
+ for (var _d = true, stream_1 = __asyncValues(stream), stream_1_1; stream_1_1 = yield stream_1.next(), _a = stream_1_1.done, !_a;) {
265
263
  _c = stream_1_1.value;
266
- _f = false;
264
+ _d = false;
267
265
  try {
268
266
  const part = _c;
269
267
  if (part.event === api_1.ChatEventType.ERROR)
@@ -281,20 +279,40 @@ class CorzBot extends gptbase_1.default {
281
279
  deepThinking += content;
282
280
  const result = this.parseDeepThinkingJson(deepThinking, thinkingStatus);
283
281
  if (result.successed) {
284
- // 如果不是卡片资源,则发送thinking事件,并更新thinkingStatus
285
- if (thinkingStatus !== DeepThinkingStatus.CardResource) {
282
+ const thinking = result.thinking;
283
+ if (thinking) {
286
284
  deepThinking = result.content;
287
- this.emit('chatthinking', result.thinking);
288
- }
289
- else if (thinkingStatus === DeepThinkingStatus.CardResource) {
290
- cardResource += (_d = result.thinking) === null || _d === void 0 ? void 0 : _d.text;
291
- // 卡片流结束,解析卡片资源数据
292
- if ((_e = result.thinking) === null || _e === void 0 ? void 0 : _e.completed) {
293
- const cardData = cardResource.replace(/[\x00-\x1F\x7F]/g, '').split('|').map((item) => (0, querystring_1.parse)(item));
294
- // 将卡片资源返回给客户端
295
- this.emit('chatcard', cardData);
285
+ if (thinking.action === DeepThinkingAction.card) {
286
+ cardResource += result.thinking.text;
287
+ // 卡片流结束,解析卡片资源数据
288
+ if (result.thinking.completed) {
289
+ const allCards = cardResource.replace(/[\x00-\x1F\x7F]/g, '').split('|');
290
+ for (const item of allCards) {
291
+ const cardinfo = (0, querystring_1.parse)(item);
292
+ if (cardinfo.type && cardinfo.tag)
293
+ cardData.push({ type: Number(cardinfo.type), tag: cardinfo.tag });
294
+ }
295
+ // 将卡片资源返回给客户端
296
+ this.emit('chatcard', cardData);
297
+ }
298
+ }
299
+ else {
300
+ this.emit('chatthinking', result.thinking);
296
301
  }
297
302
  }
303
+ // 如果不是卡片资源,则发送thinking事件,并更新thinkingStatus
304
+ // if(thinkingStatus !== DeepThinkingStatus.CardResource){
305
+ // deepThinking = result.content;
306
+ // this.emit('chatthinking', result.thinking);
307
+ // } else if (thinkingStatus === DeepThinkingStatus.CardResource) {
308
+ // cardResource += result.thinking?.text;
309
+ // // 卡片流结束,解析卡片资源数据
310
+ // if (result.thinking?.completed){
311
+ // const cardData:any[] = cardResource.replace(/[\x00-\x1F\x7F]/g, '').split('|').map((item:string)=>parse(item));
312
+ // // 将卡片资源返回给客户端
313
+ // this.emit('chatcard', cardData);
314
+ // }
315
+ // }
298
316
  thinkingStatus = result.status;
299
317
  }
300
318
  if (thinkingStatus != DeepThinkingStatus.ThinkingOver)
@@ -318,21 +336,21 @@ class CorzBot extends gptbase_1.default {
318
336
  ///整个对话结束
319
337
  if (part.event === api_1.ChatEventType.CONVERSATION_CHAT_COMPLETED) {
320
338
  const { conversation_id } = part.data;
321
- let output = { successed: true, followup, type: 'answer', content_type: 'text', role: api_1.RoleType.Assistant, requestid, segment: null, text: fullanswer.join(''), index: index++, session_id: conversation_id };
339
+ let output = { successed: true, cards: cardData.length ? cardData : null, followup, type: 'answer', content_type: 'text', role: api_1.RoleType.Assistant, requestid, segment: null, text: fullanswer.join(''), index: index++, session_id: conversation_id };
322
340
  if (attach)
323
341
  output = Object.assign({}, output, attach);
324
342
  this.emit('chatdone', output);
325
343
  }
326
344
  }
327
345
  finally {
328
- _f = true;
346
+ _d = true;
329
347
  }
330
348
  }
331
349
  }
332
350
  catch (e_1_1) { e_1 = { error: e_1_1 }; }
333
351
  finally {
334
352
  try {
335
- if (!_f && !_a && (_b = stream_1.return)) yield _b.call(stream_1);
353
+ if (!_d && !_a && (_b = stream_1.return)) yield _b.call(stream_1);
336
354
  }
337
355
  finally { if (e_1) throw e_1.error; }
338
356
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "doomiaichat",
3
- "version": "7.1.7",
3
+ "version": "7.1.8",
4
4
  "description": "Doomisoft OpenAI",
5
5
  "main": "dist/index.js",
6
6
  "scripts": {
package/src/corzbot.ts CHANGED
@@ -1,47 +1,48 @@
1
1
  /**
2
2
  * 扣子智能体
3
3
  */
4
- import { CozeAPI,
4
+ import {
5
+ CozeAPI,
5
6
  COZE_CN_BASE_URL,
6
7
  ChatEventType,
7
- RoleType,
8
+ RoleType,
8
9
  StreamChatReq,
9
10
  EnterMessage,
10
11
  ChatWorkflowReq,
11
12
  CreateChatReq,
12
- ChatStatus} from '@coze/api';
13
+ ChatStatus
14
+ } from '@coze/api';
13
15
  import GptBase from "./gptbase"
14
16
  import { CorzAuthorization } from './corzauthorization';
15
17
  import { parse } from 'querystring'
16
18
 
17
19
  // 定义深度思考的动作
18
20
  enum DeepThinkingAction {
19
- process = 'process_msg',
20
- content ='reasoning_content',
21
+ process = 'process_msg',
22
+ content = 'reasoning_content',
21
23
  card = 'card_resource'
22
24
  }
23
25
  // 定义深度思考的状态
24
26
  enum DeepThinkingStatus {
25
27
  None,
26
28
  Thinking,
27
- ReasonOutput,
28
- CardResource,
29
+ ContentOutput,
29
30
  ThinkingOver
30
31
  }
31
32
  // 智能体思考时输出的动作
32
-
33
+ type CardType = { type: number, tag: string }
33
34
  type TThinkingMessage = { action: string, textposition: number }
34
35
  export default class CorzBot extends GptBase {
35
36
  protected botid: string;
36
- private apiKey:string;
37
- private lastThinkingMessage: TThinkingMessage = { action: '', textposition:0 };
37
+ private apiKey: string;
38
+ private lastThinkingMessage: TThinkingMessage = { action: '', textposition: 0 };
38
39
  // protected client: CozeAPI;
39
40
  /**
40
41
  *
41
42
  * @param apikey 调用AI中台 的key
42
43
  * @param botid 智能体信息
43
44
  */
44
- constructor(private authorizationProvider: CorzAuthorization,private setting: any={}) {
45
+ constructor(private authorizationProvider: CorzAuthorization, private setting: any = {}) {
45
46
  super();
46
47
  ////初始化扣子客户端
47
48
  this.botid = this.setting['botid'] || this.setting['botID'];
@@ -57,12 +58,12 @@ export default class CorzBot extends GptBase {
57
58
  /**
58
59
  * 发起一次会话
59
60
  */
60
- override async createCoversation(client?: CozeAPI):Promise<string|null>{
61
- try{
62
- const czApi = client?? await this.createClient();
63
- const result = await czApi.conversations.create({ bot_id: this.botid})
61
+ override async createCoversation(client?: CozeAPI): Promise<string | null> {
62
+ try {
63
+ const czApi = client ?? await this.createClient();
64
+ const result = await czApi.conversations.create({ bot_id: this.botid })
64
65
  return result.id;
65
- }catch(error){
66
+ } catch (error) {
66
67
  console.error('createCoversation error in coze api');
67
68
  return null;
68
69
  }
@@ -84,7 +85,7 @@ export default class CorzBot extends GptBase {
84
85
  user_id: callChatOption.userid || callChatOption.cozeUserID,
85
86
  conversation_id
86
87
  }
87
- req.custom_variables = Object.assign({}, this.setting.customVariables || {}, callChatOption.customVariables || {});
88
+ req.custom_variables = Object.assign({}, this.setting.customVariables || {}, callChatOption.customVariables || {});
88
89
  return req as T;
89
90
  }
90
91
  const worflowreq: ChatWorkflowReq = {
@@ -92,7 +93,7 @@ export default class CorzBot extends GptBase {
92
93
  additional_messages: message,
93
94
  workflow_id: callChatOption.workflowid,
94
95
  conversation_id,
95
- parameters: Object.assign({}, this.setting.customVariables || {}, callChatOption.customVariables || {}),
96
+ parameters: Object.assign({}, this.setting.customVariables || {}, callChatOption.customVariables || {}),
96
97
  }
97
98
  return worflowreq as T;
98
99
  }
@@ -102,23 +103,23 @@ export default class CorzBot extends GptBase {
102
103
  * @param callChatOption
103
104
  * @param _axiosOption
104
105
  */
105
- public async chatRequest(message: any[]|string, callChatOption: any={}, _axiosOption: any = {}): Promise<any> {
106
+ public async chatRequest(message: any[] | string, callChatOption: any = {}, _axiosOption: any = {}): Promise<any> {
106
107
  if (!message) this.emit('chaterror', { successed: false, error: 'no message in chat' });
107
108
  ///如果是字符,则组装成API需要的消息
108
109
  if (typeof message === 'string') message = [
109
110
  {
110
111
  role: RoleType.User,
111
- content_type:'text' ,
112
+ content_type: 'text',
112
113
  content: message
113
114
  }
114
115
  ];
115
116
  const client = await this.createClient();
116
117
  ////如果参数中用的是Workflow,则调用对话流来输出结果
117
118
  ////否则用智能体的对话来输出结果
118
- const params = await this.getRequestStream(client,message, callChatOption);
119
+ const params = await this.getRequestStream(client, message, callChatOption);
119
120
  const response = await client.chat.createAndPoll(params as CreateChatReq);
120
121
  if (response.chat.status === ChatStatus.COMPLETED && response.messages) {
121
- const message = response.messages.filter(x=>x.type==='answer').map(item => ({
122
+ const message = response.messages.filter(x => x.type === 'answer').map(item => ({
122
123
  role: item.role,
123
124
  type: item.type,
124
125
  content: item.content,
@@ -128,7 +129,7 @@ export default class CorzBot extends GptBase {
128
129
  type: item.type,
129
130
  content: item.content,
130
131
  }));
131
- return { successed: true, message, follow_up,usage: response.chat.usage };
132
+ return { successed: true, message, follow_up, usage: response.chat.usage };
132
133
  }
133
134
  return { successed: false, error: { message: '聊天未完成', status: response.chat.status } };
134
135
  // for await (const part of stream) {
@@ -148,53 +149,58 @@ export default class CorzBot extends GptBase {
148
149
  * @param status
149
150
  * @returns
150
151
  */
151
- private parseDeepThinkingJson(content: string,status: DeepThinkingStatus) {
152
- const thinkingEndIndex = content.indexOf("\"}");
152
+ private parseDeepThinkingJson(content: string, status: DeepThinkingStatus) {
153
+
153
154
  // const thinkingStartIndex = status === DeepThinkingStatus.Thinking ? content.indexOf("{\"process_msg") :
154
155
  // (status===DeepThinkingStatus.ReasonOutput ? content.indexOf("{\"reasoning_content") : content.indexOf("{\"card_resource")) ;
155
- const thinkingStartIndex = [content.indexOf("{\"process_msg"),
156
- content.indexOf("{\"reasoning_content"),
157
- content.indexOf("{\"card_resource")].find(x=>x>=0)??-1;
156
+ const tagLocation = [content.indexOf("{\"process_msg"),
157
+ content.indexOf("{\"reasoning_content"),
158
+ content.indexOf("{\"card_resource")].filter(x => x >= 0);
159
+ const thinkingStartIndex = tagLocation.length > 0 ? Math.min(...tagLocation) : -1;
160
+ const thinkingEndIndex = content.indexOf("\"}");
158
161
  // 如果没有找到相关的JSON内容,则直接返回
159
- if (thinkingStartIndex < 0) return { successed: true, content, status: DeepThinkingStatus.ThinkingOver};
162
+ if (thinkingStartIndex < 0) return { successed: true, content, status: DeepThinkingStatus.ThinkingOver };
160
163
  let jsonStr = null;
161
- try{
162
- jsonStr = content.substring(thinkingStartIndex, thinkingEndIndex >= 0 ? thinkingEndIndex : undefined) +"\"}";
164
+ try {
165
+ jsonStr = content.substring(thinkingStartIndex, thinkingEndIndex >= 0 ? thinkingEndIndex : undefined) + "\"}";
163
166
  // 转换JSON的时候需要将非法字符过滤掉
164
167
  const thinkingObject = JSON.parse(jsonStr.replace(/[\x00-\x1F\x7F]/g, ''));
165
168
  const thinkingAction = Object.keys(thinkingObject)[0];
166
169
  // 需要将内容的原文返回
167
170
  const originalContent = jsonStr.split('":"')[1];
168
171
  // 如果正确的解析JSON,并且当前有包含JSON结束的字符,则把当前思考的JSON内容替换掉
169
- if (thinkingEndIndex >= 0) content = content.substring(thinkingEndIndex+2);
172
+ if (thinkingEndIndex >= 0) content = content.substring(thinkingEndIndex + 2);
170
173
  // 如果正常输出了卡片资源,并且json结束 card_resource 只有一个,所以一旦结束,则整个思考过程完毕
171
- if (status === DeepThinkingStatus.CardResource && thinkingEndIndex >= 0) status = DeepThinkingStatus.ThinkingOver;
174
+ // if (status === DeepThinkingStatus.ContentOutput && thinkingEndIndex >= 0) status = DeepThinkingStatus.ThinkingOver;
172
175
  // 判断整个思考过程是否到达等待卡片资源(有可能智能体输出不了卡片资源) reasoning_content 只有一个,所以一旦结束,则进入下一个阶段 card_resource
173
- if (status === DeepThinkingStatus.ReasonOutput && thinkingEndIndex >= 0) status = DeepThinkingStatus.CardResource;
176
+ //if (status === DeepThinkingStatus.ContentOutput && thinkingEndIndex >= 0) status = DeepThinkingStatus.ContentOutput;
174
177
  // 判断当前是否从前期思考切换到思考内容输出
175
- if (status === DeepThinkingStatus.Thinking && thinkingAction === DeepThinkingAction.content) status = DeepThinkingStatus.ReasonOutput;
178
+ if (status === DeepThinkingStatus.Thinking && thinkingAction !== DeepThinkingAction.process)
179
+ status = DeepThinkingStatus.ContentOutput;
176
180
  //if (status === DeepThinkingStatus.Thinking && content.indexOf("{\"reasoning_content") >= 0) status=DeepThinkingStatus.ReasonOutput;
177
181
  //const removeOutputContent = content.replace(originalContent!.substring(1, originalContent!.length - 2),"")
178
182
  let thinkingContent = originalContent?.substring(0, originalContent.length - 2)
179
183
  const outputLength = thinkingContent?.length || 0;
180
-
184
+
181
185
  // 用lastThinkingMessage来记录上一次的思考内容,避免重复输出内容,导致的网络传输内容过多
182
- if (this.lastThinkingMessage.action === thinkingAction && this.lastThinkingMessage.textposition){
186
+ if (this.lastThinkingMessage.action === thinkingAction && this.lastThinkingMessage.textposition) {
183
187
  thinkingContent = thinkingContent!.substring(this.lastThinkingMessage.textposition)
184
188
  }
185
- this.lastThinkingMessage = thinkingEndIndex >= 0 ? { action: thinkingAction!, textposition:0 } : { action: thinkingAction!, textposition: outputLength }
189
+ this.lastThinkingMessage = thinkingEndIndex >= 0 ? { action: thinkingAction!, textposition: 0 } : { action: thinkingAction!, textposition: outputLength }
186
190
 
187
- return { successed: true,thinking:{
188
- action: thinkingAction,
189
- text: thinkingContent,//Object.values(thinkingObject)[0]
190
- completed: thinkingEndIndex >= 0
191
- }, content, status}
191
+ return {
192
+ successed: true, thinking: {
193
+ action: thinkingAction,
194
+ text: thinkingContent,//Object.values(thinkingObject)[0]
195
+ completed: thinkingEndIndex >= 0
196
+ }, content, status
197
+ }
192
198
  }
193
- catch(error){
199
+ catch (error) {
194
200
  // 如果在content之后发生了错误,可能该智能体输出不了卡片类型的数据,则输出的内容已经是正文了
195
- if (status === DeepThinkingStatus.CardResource) {
201
+ if (status === DeepThinkingStatus.ContentOutput) {
196
202
  status = DeepThinkingStatus.ThinkingOver;
197
- return {successed: true, content, status};
203
+ return { successed: true, content, status };
198
204
  }
199
205
  console.error('解析JSON出错了:', jsonStr, status)
200
206
  // 当前解析出错,等待下一次解析
@@ -209,7 +215,7 @@ export default class CorzBot extends GptBase {
209
215
  * @param _axiosOption
210
216
  * @returns
211
217
  */
212
- override async chatRequestInStream(message: any[]|string, callChatOption: any={}, attach?: any, _axiosOption?: any): Promise<any> {
218
+ override async chatRequestInStream(message: any[] | string, callChatOption: any = {}, attach?: any, _axiosOption?: any): Promise<any> {
213
219
  if (!message) this.emit('chaterror', { successed: false, error: 'no message in chat' });
214
220
  ///如果是字符,则组装成API需要的消息
215
221
  if (typeof message === 'string') message = [
@@ -222,40 +228,59 @@ export default class CorzBot extends GptBase {
222
228
  const client = await this.createClient();
223
229
  ////如果参数中用的是Workflow,则调用对话流来输出结果
224
230
  ////否则用智能体的对话来输出结果
225
- let requestid = Math.ceil(Math.random() * (new Date().getTime() * Math.random()) / 1000), index=0;
226
- const params = await this.getRequestStream(client,message, callChatOption);
227
- const stream = !callChatOption.workflowid? client.chat.stream(params as StreamChatReq) : client.workflows.chat.stream(params as ChatWorkflowReq);
228
- let deltaindex = 0, fullanswer: string[] = [], followup: string[] = [];
229
- let deepThinking = '', thinkingStatus = DeepThinkingStatus.None,cardResource=''; // 是否在深度思考中
231
+ let requestid = Math.ceil(Math.random() * (new Date().getTime() * Math.random()) / 1000), index = 0;
232
+ const params = await this.getRequestStream(client, message, callChatOption);
233
+ const stream = !callChatOption.workflowid ? client.chat.stream(params as StreamChatReq) : client.workflows.chat.stream(params as ChatWorkflowReq);
234
+ let deltaindex = 0, fullanswer: string[] = [], followup: string[] = [], cardData: CardType[] = [];
235
+ let deepThinking = '', thinkingStatus = DeepThinkingStatus.None, cardResource = ''; // 是否在深度思考中
230
236
  for await (const part of stream) {
231
237
  if (part.event === ChatEventType.ERROR) return this.emit('chaterror', { successed: false, error: 'call failed' });
232
238
  if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
233
- let { conversation_id, content_type,type, role, content } = part.data;
239
+ let { conversation_id, content_type, type, role, content } = part.data;
234
240
  // 如果存在深度思考,则一开始就会带有相关的关键信息
235
241
  if (deltaindex === 0 && content.startsWith("{\"process_msg")) {
236
- thinkingStatus=DeepThinkingStatus.Thinking;
242
+ thinkingStatus = DeepThinkingStatus.Thinking;
237
243
  deltaindex++;
238
244
  }
239
245
  // 如果在深度思考中,则不输出消息
240
- if (thinkingStatus !== DeepThinkingStatus.None
246
+ if (thinkingStatus !== DeepThinkingStatus.None
241
247
  && thinkingStatus !== DeepThinkingStatus.ThinkingOver
242
- ){
248
+ ) {
243
249
  deepThinking += content;
244
250
  const result = this.parseDeepThinkingJson(deepThinking, thinkingStatus)
245
- if (result.successed ){
246
- // 如果不是卡片资源,则发送thinking事件,并更新thinkingStatus
247
- if(thinkingStatus !== DeepThinkingStatus.CardResource){
251
+ if (result.successed) {
252
+ const thinking = result.thinking;
253
+ if (thinking) {
248
254
  deepThinking = result.content;
249
- this.emit('chatthinking', result.thinking);
250
- } else if (thinkingStatus === DeepThinkingStatus.CardResource) {
251
- cardResource += result.thinking?.text;
252
- // 卡片流结束,解析卡片资源数据
253
- if (result.thinking?.completed){
254
- const cardData:any[] = cardResource.replace(/[\x00-\x1F\x7F]/g, '').split('|').map((item:string)=>parse(item));
255
- // 将卡片资源返回给客户端
256
- this.emit('chatcard', cardData);
255
+ if (thinking.action === DeepThinkingAction.card) {
256
+ cardResource += result.thinking.text;
257
+ // 卡片流结束,解析卡片资源数据
258
+ if (result.thinking.completed) {
259
+ const allCards = cardResource.replace(/[\x00-\x1F\x7F]/g, '').split('|')
260
+ for (const item of allCards) {
261
+ const cardinfo: any = parse(item);
262
+ if (cardinfo.type && cardinfo.tag) cardData.push({ type: Number(cardinfo.type), tag: cardinfo.tag })
263
+ }
264
+ // 将卡片资源返回给客户端
265
+ this.emit('chatcard', cardData);
266
+ }
267
+ } else {
268
+ this.emit('chatthinking', result.thinking);
257
269
  }
258
270
  }
271
+ // 如果不是卡片资源,则发送thinking事件,并更新thinkingStatus
272
+ // if(thinkingStatus !== DeepThinkingStatus.CardResource){
273
+ // deepThinking = result.content;
274
+ // this.emit('chatthinking', result.thinking);
275
+ // } else if (thinkingStatus === DeepThinkingStatus.CardResource) {
276
+ // cardResource += result.thinking?.text;
277
+ // // 卡片流结束,解析卡片资源数据
278
+ // if (result.thinking?.completed){
279
+ // const cardData:any[] = cardResource.replace(/[\x00-\x1F\x7F]/g, '').split('|').map((item:string)=>parse(item));
280
+ // // 将卡片资源返回给客户端
281
+ // this.emit('chatcard', cardData);
282
+ // }
283
+ // }
259
284
  thinkingStatus = result.status;
260
285
  }
261
286
  if (thinkingStatus != DeepThinkingStatus.ThinkingOver) continue;
@@ -270,13 +295,13 @@ export default class CorzBot extends GptBase {
270
295
  }
271
296
  ////在流式传输中,提取相关推荐问题
272
297
  if (part.event === ChatEventType.CONVERSATION_MESSAGE_COMPLETED) {
273
- const { type, content} = part.data;
274
- if (type ==='follow_up') followup.push(content);
298
+ const { type, content } = part.data;
299
+ if (type === 'follow_up') followup.push(content);
275
300
  }
276
301
  ///整个对话结束
277
302
  if (part.event === ChatEventType.CONVERSATION_CHAT_COMPLETED) {
278
- const { conversation_id} = part.data;
279
- let output = { successed: true, followup, type: 'answer', content_type: 'text', role:RoleType.Assistant, requestid, segment: null, text: fullanswer.join(''), index: index++, session_id: conversation_id };
303
+ const { conversation_id } = part.data;
304
+ let output = { successed: true, cards: cardData.length ? cardData : null, followup, type: 'answer', content_type: 'text', role: RoleType.Assistant, requestid, segment: null, text: fullanswer.join(''), index: index++, session_id: conversation_id };
280
305
  if (attach) output = Object.assign({}, output, attach);
281
306
  this.emit('chatdone', output)
282
307
  }