Handle events and messages in TypeScript
Subscribe to connection, state, and message events from the Convai Web SDK client and render the conversation in a framework-free page.
Subscribe to the client's events to keep a framework-free UI in step with the conversation. Use this page when you render state, messages, or live transcription yourself instead of using the chat widget.
Prerequisites
A
ConvaiClientcreated as shown in Get started with vanilla TypeScript.
Subscribe and unsubscribe
client.on(event, callback) returns a function that removes the subscription. client.off(event, callback) removes it by reference.
const unsubscribe = client.on('message', handleMessage);
// Later
unsubscribe();
// or
client.off('message', handleMessage);Subscribe before you call connect() so you do not miss the first events of the session.
Track connection state
stateChange fires whenever any field of ConvaiClientState changes. state.agentState combines the activity flags into one value: 'disconnected', 'connected', 'listening', 'thinking', or 'speaking'.
import type { ConvaiClientState } from '@convai/web-sdk/vanilla';
client.on('stateChange', (state: ConvaiClientState) => {
statusEl.textContent = state.isConnected ? state.agentState : 'disconnected';
});client.state returns the same state on demand.
Wait for the character before sending
connect fires when the transport is up. The character can take a moment longer to be ready, and sendUserTextMessage does nothing while the transport is not ready. Send the first message on botReady, or check client.isBotReady.
Render the conversation
message fires with the newest ChatMessage. messagesChange fires with the whole array, including updates to a message that is still streaming. For a chat log, re-render from messagesChange and filter by type:
The message types a chat UI usually shows:
user-llm-text
A text message you sent with sendUserTextMessage.
user-transcription
What the user said, transcribed from speech. Final segments accumulate in one message until the character replies.
bot-llm-text
The character's reply, streamed as it is generated. isStreaming is true until it is final.
bot-output
The character's reply, aggregated as it is spoken. The SDK adds it to the log only when the reply did not already arrive as bot-llm-text.
Other types carry emotions, actions, idle warnings, and no-response turns. See Configuration and type reference for the full list.
Show live transcription
userTranscriptionChange fires as the user speaks, with the transcription so far. It fires with an empty string when the utterance is final.
Handle errors
error fires for connection failures and when the character does not report ready in time. Its payload is whatever was thrown, so check the type before reading message.
Next steps
Web SDK event referenceBuild a custom UI in TypeScriptHandle errors and disconnectsLast updated
Was this helpful?