For low-latency, bidirectional communication, use client.websockets.chat.create. This provides a standard WebSocket interface where you can send CHAT_UPDATE events to configure the session and CONVERSATION_MESSAGE_CREATE events to send user messages. You can listen for CONVERSATION_MESSAGE_DELTA for real-time text streaming and CONVERSATION_CHAT_COMPLETED when the session ends.
import { CozeAPI, RoleType, WebsocketsEventType } from '@coze/api';
async function wsChat() {
const ws = await client.websockets.chat.create('your_bot_id');
ws.onopen = () => {
// Configure chat
ws.send({
id: 'event_id',
event_type: WebsocketsEventType.CHAT_UPDATE,
data: {
chat_config: {
auto_save_history: true,
user_id: 'uuid',
meta_data: {},
custom_variables: {},
extra_params: {},
},
},
});
// Send message
ws.send({
id: 'event_id',
event_type: WebsocketsEventType.CONVERSATION_MESSAGE_CREATE,
data: {
role: RoleType.User,
content: 'tell me a joke',
content_type: 'text',
},
});
};
ws.onmessage = (data, event) => {
if (data.event_type === WebsocketsEventType.ERROR) {
// Handle error codes like 4100 (Unauthorized) or 4101 (Forbidden)
ws.close();
return;
}
if (data.event_type === WebsocketsEventType.CONVERSATION_MESSAGE_DELTA) {
console.log('on message delta', data.data);
} else if (data.event_type === WebsocketsEventType.CONVERSATION_CHAT_COMPLETED) {
console.log('on chat completed', data.data);
}
};
}