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