forked from coze-dev/coze-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.ts
82 lines (78 loc) · 1.96 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import {
ChatEventType,
ChatStatus,
type CozeAPI,
type CreateChatData,
RoleType,
} from '@coze/api';
export async function nonStreamingChat({
client,
botId,
query,
}: {
client: CozeAPI;
botId: string;
query: string;
}) {
const v = await client.chat.createAndPoll({
bot_id: botId,
additional_messages: [
{
role: RoleType.User,
content: query,
content_type: 'text',
},
],
});
if (v.chat.status === ChatStatus.COMPLETED) {
for (const item of v.messages || []) {
console.log('[%s]:[%s]:%s', item.role, item.type, item.content);
}
console.log('usage', v.chat.usage);
}
}
export async function streamingChat({
client,
botId,
query,
callback,
}: {
client: CozeAPI;
botId: string;
query: string;
callback?: (v: CreateChatData) => void;
}) {
const v = await client.chat.stream({
bot_id: botId,
auto_save_history: false,
additional_messages: [
{
role: RoleType.User,
content: query,
content_type: 'text',
},
],
});
for await (const part of v) {
if (part.event === ChatEventType.CONVERSATION_CHAT_CREATED) {
console.log('[START]');
callback && callback(part.data);
} else if (part.event === ChatEventType.CONVERSATION_MESSAGE_DELTA) {
process.stdout.write(part.data.content);
} else if (part.event === ChatEventType.CONVERSATION_MESSAGE_COMPLETED) {
const { role, type, content } = part.data;
if (role === 'assistant' && type === 'answer') {
process.stdout.write('\n');
} else {
console.log('[%s]:[%s]:%s', role, type, content);
}
} else if (part.event === ChatEventType.CONVERSATION_CHAT_COMPLETED) {
console.log(part.data.usage);
} else if (part.event === ChatEventType.DONE) {
console.log(part.data);
} else if (part.event === ChatEventType.ERROR) {
console.error(part.data);
}
}
console.log('=== End of Streaming Chat ===');
}