Web toolkit API

Updated

Web toolkit API reference for Conversational AI Engine.

Installation

Add the toolkit to your project using a package manager or by copying the source code.

Install the toolkit package for your project type:

  • Vanilla JS or TypeScript:

    pnpm add agora-agent-client-toolkit@2.9.0
  • React:

    pnpm add agora-agent-client-toolkit@2.9.0 agora-agent-client-toolkit-react@2.9.0

Copy the conversational-ai package into your project, then import the toolkit before calling its APIs.

The Web toolkit API provides the following classes and methods.

API overview

APIDescription
chatSend chat messages to a conversational agent.
getInstanceGets a singleton instance of ConversationalAIAPI.
initInitializes the ConversationalAIAPI singleton instance.
subscribeMessageSubscribes to the messaging channel to get real-time updates.
unsubscribeUnsubscribes from the message channel and cleans up resources.
interruptSends an interrupt message to the specified agent user.
manualSOSSends a manual Start of Speech (SoS) signal to the agent.
manualEOSSends a manual End of Speech (EoS) signal to the agent.
destroyDestroys the ConversationalAIAPI instance and cleans up resources.

ConversationalAIAPI class

Class for managing conversational AI engine interactions through Agora's RTC and RTM services.

chat

Send chat messages to a conversational agent.

Since v1.7

public async chat(agentUserId: string, message: IChatMessageText | IChatMessageImage)

Sample code

// Send an image message
const imageMessage: IChatMessageImage = {
  messageType: EChatMessageType.IMAGE,
  imageData: urlImageData
};
await api.chat("user123", imageMessage);
ParameterTypeDescription
agentUserIdstringUnique identifier of the agent.
messageIChatMessageText | IChatMessageImageChat message to be sent. Should be of type IChatMessageImage, see details in IChatMessageImage.

Return Value
If the method call succeeds, a Promise is returned, indicating the result of the message sending.

getInstance

Gets a singleton instance of ConversationalAIAPI. This method ensures that only one instance exists throughout the entire application lifecycle.

public static getInstance()
  • You must call init before using this method.
  • If not initialized, an error is thrown.

Return Value: If the method call succeeds, a ConversationalAIAPI instance is returned. If not initialized, a NotFoundError exception is thrown.

init

Initializes the ConversationalAIAPI singleton instance.

public static async init(cfg: IConversationalAIAPIConfig): Promise<ConversationalAIAPI>

This method sets the RTC and RTM engines, rendering mode, and logging options. You must call this method before calling other methods of ConversationalAIAPI. Awaiting this method returns the initialized instance directly, so a separate call to getInstance is not required immediately after initialization.

  • Only one instance can be initialized at a time.
  • If already initialized, an error is thrown.
ParameterTypeDescription
cfgIConversationalAIAPIConfigConfiguration object used to initialize the API. See IConversationalAIAPIConfig.

Return Value: If the method call succeeds, a Promise resolving to the initialized ConversationalAIAPI instance.

subscribeMessage

Subscribes to the messaging channel to get real-time updates.

public subscribeMessage(channel: string)

This method binds the necessary RTC and RTM events and starts CovSubRenderController to process received messages.

  • You must call init before using this method.
  • If not initialized, an error is thrown.
ParameterTypeDescription
channelstringThe channel to subscribe to for messages.

unsubscribe

Unsubscribes from the message channel and cleans up resources.

public unsubscribe()

This method unbinds RTC and RTM events, clears channels, and cleans up CovSubRenderController. You must call subscribeMessage before calling this method, otherwise an error is thrown.

interrupt

Sends an interrupt message to the specified agent user.

public async interrupt(agentUserId: string)
  • You must call init before using this method.
  • If not initialized or sending fails, an error is thrown.
ParameterTypeDescription
agentUserIdstringThe user ID of the agent user to be interrupted.

manualSOS

Sends a manual Start of Speech (SoS) signal to the agent over RTM, explicitly declaring that the current user has started speaking.

public async manualSOS(agentUserId: string): Promise<string>

Keep the following in mind when calling this method:

  • The component generates requestId internally and resolves it in the returned Promise. Your app can store this value to correlate it with the server-side event.
  • A resolved Promise only indicates that the RTM publish succeeded — it does not indicate that the server processed the request successfully.
  • Whether the server successfully processed the request is determined by the subsequent USER_MANUAL_SOS_RESULT or USER_MANUAL_EOS_RESULT event. See EConversationalAIAPIEvents.
  • The client does not check locally whether manual mode is enabled. Mode validation is handled by the server.
  • Common failure reasons include: the current mode configuration does not allow manual signaling, there is no active user speech to mark, or a manual SoS or EoS that has already taken effect is resubmitted within the same turn.
ParameterTypeDescription
agentUserIdstringUnique identifier of the agent.

Return Value
If the method call succeeds, a Promise<string> is returned, resolving to the requestId for this request. This result only indicates that the RTM publish succeeded.

manualEOS

Sends a manual End of Speech (EoS) signal to the agent over RTM, explicitly declaring that the current user has finished speaking.

public async manualEOS(agentUserId: string): Promise<string>

Keep the following in mind when calling this method:

  • The component generates requestId internally and resolves it in the returned Promise. Your app can store this value to correlate it with the server-side event.
  • A resolved Promise only indicates that the RTM publish succeeded — it does not indicate that the server processed the request successfully.
  • Whether the server successfully processed the request is determined by the subsequent USER_MANUAL_SOS_RESULT or USER_MANUAL_EOS_RESULT event. See EConversationalAIAPIEvents.
  • The client does not check locally whether manual mode is enabled. Mode validation is handled by the server.
  • Common failure reasons include: the current mode configuration does not allow manual signaling, there is no active user speech to mark, or a manual SoS or EoS that has already taken effect is resubmitted within the same turn.
ParameterTypeDescription
agentUserIdstringUnique identifier of the agent.

Return Value
If the method call succeeds, a Promise<string> is returned, resolving to the requestId for this request. This result only indicates that the RTM publish succeeded.

destroy

Destroys the ConversationalAIAPI instance and cleans up resources.

public destroy(): void
  • You must call unsubscribe before calling this method.
  • If not initialized, an error is thrown.

IConversationalAIAPIEventHandlers interface

Event handler interface for the Conversational AI API module.

A set of event handlers that respond to various events emitted by the conversational AI system, including agent state changes, interruptions, performance metrics, errors, and transcription updates.

ParameterTypeDescription
agentUserIdstringUnique identifier for the AI agent.
eventTStateChangeEvent | { turnID: number; timestamp: number } | TUserManualSosEvent | TUserManualEosEvent | TAgentManualEosEventEvent data. The type depends on the event type. See TStateChangeEvent, TUserManualSosEvent, TUserManualEosEvent, and TAgentManualEosEvent.
metricsTAgentMetricPerformance indicator data of the agent. See TAgentMetric.
errorTModuleErrorError message when an error occurs in the agent. See TModuleError.
transcriptionISubtitleHelperItem<Partial<IUserTranscription | IAgentTranscription>>[]An array of transcripts of the conversation between the user and the agent. See ISubtitleHelperItem.
messagestringDebug log message string.

Types and Interfaces

TMessageReceipt

Message receipt type definition.

Since v1.7

export type TMessageReceipt = {
  moduleType: EModuleType
  messageType: EChatMessageType
  message: string
  turnId: number
}
ParameterTypeDescription
moduleTypeEModuleTypeThe type of module sending the message. See EModuleType.
messageTypeEChatMessageTypeThe type of message. See EChatMessageType.
messagestringThe content of the message.
turnIdnumberUnique identifier for the conversation turn.

TUserManualEventPayload

Common payload for manual SoS/EoS events.

export type TUserManualEventPayload = {
  success: boolean
  requestId: string
  turnId?: number
  errorMessage?: string
}
ParameterTypeDescription
successbooleanWhether the server successfully processed this manual signal.
requestIdstringRequest ID, corresponding to the requestId resolved by manualSOS or manualEOS.
turnIdnumberThe associated conversation turn ID. Omitted if the server's failure event does not include a turn_id.
errorMessagestringThe raw error message returned by the server. Usually omitted on success.

TUserManualSosEvent

Represents a manual SoS event.

export type TUserManualSosEvent = {
  eventId: string
  timestamp: number
  payload: TUserManualEventPayload
}
ParameterTypeDescription
eventIdstringUnique event ID.
timestampnumberEvent timestamp in milliseconds.
payloadTUserManualEventPayloadEvent payload. See TUserManualEventPayload.

TUserManualEosEvent

Represents a manual EoS event.

export type TUserManualEosEvent = {
  eventId: string
  timestamp: number
  payload: TUserManualEventPayload
}
ParameterTypeDescription
eventIdstringUnique event ID.
timestampnumberEvent timestamp in milliseconds.
payloadTUserManualEventPayloadEvent payload. See TUserManualEventPayload.

TAgentManualEosPayload

Payload for a server-triggered automatic EoS event.

export type TAgentManualEosPayload = {
  reason: string
  maxDurationMs: number
  turnId: number
}
ParameterTypeDescription
reasonstringThe reason the server automatically ended the current user's turn.
maxDurationMsnumberThe configured maximum duration, in milliseconds, for a single speaking turn.
turnIdnumberThe associated conversation turn ID.

TAgentManualEosEvent

Represents a server-triggered automatic EoS event.

export type TAgentManualEosEvent = {
  eventId: string
  timestamp: number
  payload: TAgentManualEosPayload
}
ParameterTypeDescription
eventIdstringUnique event ID.
timestampnumberEvent timestamp in milliseconds.
payloadTAgentManualEosPayloadEvent payload. See TAgentManualEosPayload.

IChatMessageBase

The IChatMessageBase interface that contains the properties of the underlying message type.

Since v1.7

export interface IChatMessageBase {
  messageType: EChatMessageType
}
ParameterTypeDescription
messageTypeEChatMessageTypeType of message. See EChatMessageType for details.

IChatMessageImage

Represents an image-based chat message, which can contain URL image data.

Since v1.7

export interface IChatMessageImage extends IChatMessageBase {
  messageType: EChatMessageType.IMAGE
  uuid: string
  url?: string
}
ParameterTypeDescription
messageTypeEChatMessageType.IMAGEMessage type, must be IMAGE. See EChatMessageType.
uuidstringUnique identifier for the image message.
urlstringOptional. URL pointing to the image resource.

IConversationalAIAPIConfig

Parameters used to configure the interface.

export interface IConversationalAIAPIConfig {
 rtcEngine: IAgoraRTCClient;
 rtmEngine: RTMClient;
 renderMode?: ETranscriptHelperMode;
 enableLog?: boolean;
 enableRenderModeFallback?: boolean;
}
ParameterTypeDescription
rtcEngineIAgoraRTCClientAgora RTC engine instance. See IAgoraRTCClient.
rtmEngineRTMClientAgora RTM engine instance. See the Signaling Web API reference.
renderModeETranscriptHelperModeRendering mode. See ETranscriptHelperMode.
enableLogbooleanWhether to enable logging: true enables logging, false disables logging.
enableRenderModeFallbackbooleanWhether to automatically fall back to text rendering when renderMode is set to word-level but the server doesn't provide word-level timing data. If true (default), falls back to text mode automatically. If false, stays in word mode regardless — this can result in no transcript being displayed if the server doesn't support word-level transcription.

TStateChangeEvent

Event type used to describe a change in the state of a voice agent.

export type TStateChangeEvent = {
 state: EAgentState
 turnID: number
 timestamp: number
 reason: string
}

The state change event is triggered when the state of the voice agent changes. The timestamp uses the UNIX timestamp in milliseconds.

ParameterTypeDescription
stateEAgentStateThe current state of the voice agent. See EAgentState.
turnIDnumberUnique identifier for the current session turn.
timestampnumberTimestamp in milliseconds when the state change occurred.
reasonstringDescription of the reason for the status change.

TAgentMetric

Used to store metric data during agent runtime.

export type TAgentMetric = {
 type: EModuleType
 name: string
 value: number
 timestamp: number
}
ParameterTypeDescription
typeEModuleTypeIndicator module type. See EModuleType.
namestringThe name of the indicator.
valuenumberThe indicator value.
timestampnumberTimestamp in milliseconds since Unix epoch (January 1, 1970 UTC).

TModuleError

Used to represent error messages from different AI modules, including error type, error code, error message, and timestamp.

export type TModuleError = {
 type: EModuleType
 code: number
 message: string
 timestamp: number
}
ParameterTypeDescription
typeEModuleTypeThe module type where the error occurred. See EModuleType.
codenumberModule-specific error code.
messagestringReadable error description that makes it easier to understand and handle.
timestampnumberTimestamp in milliseconds since Unix epoch (January 1, 1970 UTC).

ISubtitleHelperItem

Transcript auxiliary item interface.

The data structure for a single transcript item in the transcription system. This includes information such as user ID, stream ID, turn ID, timestamp, text content, status, and metadata.

export interface ISubtitleHelperItem<T> {
 uid: string;
 stream_id: number;
 turn_id: number;
 _time: number;
 text: string;
 status: ETurnStatus;
 metadata: T | null;
}
ParameterTypeDescription
uidstringUnique user identifier.
stream_idnumberStream identifier.
turn_idnumberThe turn identifier within the session.
_timenumberTimestamp in milliseconds since Unix epoch (January 1, 1970 UTC).
textstringTranscript text content.
statusETurnStatusThe status of the transcript item. See ETurnStatus.
metadataT | nullAdditional metadata information.

Enum classes

EConversationalAIAPIEvents

Event types that can be triggered by the Conversational AI API.

Since v1.6.0

ValueDescription
AGENT_STATE_CHANGED"agent-state-changed": Agent state change event.
AGENT_LISTENING_CHANGED"agent-listening-changed": Agent listening state change event.
AGENT_THINKING_CHANGED"agent-thinking-changed": Agent thinking state change event.
AGENT_SPEAKING_CHANGED"agent-speaking-changed": Agent speaking state change event.
AGENT_INTERRUPTED"agent-interrupted": Agent interrupted event.
AGENT_METRICS"agent-metrics": Agent metrics event.
AGENT_ERROR"agent-error": Agent error event.
TRANSCRIPT_UPDATED"transcript-updated": Transcript updated event.
DEBUG_LOG"debug-log": Debug log event.
MESSAGE_RECEIPT_UPDATED"message-receipt-updated": Message receipt updated event.
MESSAGE_ERROR"message-error": Message error event.
USER_MANUAL_SOS_RESULT"user.manual_sos.result": Manual SoS result event.
USER_MANUAL_EOS_RESULT"user.manual_eos.result": Manual EoS result event.
AGENT_MANUAL_EOS_RESULT"assistant.manual_eos.result": Server-triggered automatic EoS notification event.

EChatMessagePriority

Since v1.7

Used to set the chat message processing priority.

Valuedescription
INTERRUPTED('interrupted'): Interrupts current processing and immediately handles this message.
APPEND('append'): Adds the message to the processing queue to be handled in order.
IGNORE('ignore'): Discards the message without processing.

EChatMessageType

Chat message types supported in conversational AI.

Since v1.7

ValueDescription
TEXT('text'): Text message.
IMAGE('image'): Image message.
UNKNOWN('unknown'): Unknown message type.

EAgentState

Agent state enumeration.

export enum EAgentState {
 IDLE = "idle",
 LISTENING = "listening", 
 THINKING = "thinking",
 SPEAKING = "speaking",
 SILENT = "silent"
}
ValueDescription
IDLE("idle"): The agent is idle and ready for new interactions.
LISTENING("listening"): The agent is receiving user input.
THINKING("thinking"): The agent is processing the input it receives.
SPEAKING("speaking"): The agent is outputting a response.
SILENT("silent"): The agent intentionally does not respond.

EModuleType

Enumeration of module types for AI capabilities.

ValueDescription
LLM("llm"): Large Language Model.
MLLM("mllm"): Multimodal Large Language Model.
TTS("tts"): Text-to-speech module.
CONTEXT("context"): Context management module.
UNKNOWN("unknown"): Unknown module type.

ETranscriptHelperMode

The mode type for transcript processing.

ValueDescription
TEXTProcesses transcript in text mode.
WORDProcesses transcript in word mode.
UNKNOWNUnknown transcript processing mode.

ETurnStatus

TURN connection status enumeration.

ValueDescription
IN_PROGRESS(0): TURN connection in progress.
END(1): TURN connection has ended.
INTERRUPTED(2): TURN connection has been disconnected.