Android toolkit API

Updated

Android toolkit API reference for Conversational AI Engine.

Installation

Add the toolkit to your project using Maven or by copying the source code.

Add the following dependency to your app-level build.gradle file:

implementation 'io.agora.agents:agora-agent-client-toolkit:2.9.0'

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

If you encounter library conflicts when integrating multiple Agora SDKs in your Android project, see handle integration issues.

The Android toolkit API for Conversational AI Engine provides the following classes and methods.

IConversationalAIAPI class

APIDescription
chatSend chat messages to a conversational agent.
addHandlerRegisters an event handler to receive agent session events.
removeHandlerRemoves a registered event handler.
subscribeMessageSubscribes to a channel to receive agent conversation events.
unsubscribeMessageUnsubscribes from the channel and stops receiving events.
interruptInterrupts the agent’s speech.
manualSOSSends a manual Start of Speech (SoS) signal to the agent.
manualEOSSends a manual End of Speech (EoS) signal to the agent.
loadAudioSettingsSets audio parameters to optimize agent conversation performance.
destroyDestroys the API instance and releases resources.

chat

Send a message to the agent.

Support for sending different types of messages through the ChatMessage sealed class hierarchy:

  • ImageMessage: Used to send picture messages.
fun chat(agentUserId: String, message: ChatMessage, completion: (error: ConversationalAIAPIError?) -> Unit)
ParameterTypeDescription
agentUserIdStringAgent user ID.
messageChatMessageMessage object of type ImageMessage. See ChatMessage for details.
completion(error: ConversationalAIAPIError?) -> UnitCallback function. error is null if the call succeeds, and non-null if it fails.

addHandler

Registers an event handler to receive agent session events.

fun addHandler(handler: IConversationalAIAPIEventHandler)
ParameterTypeDescription
handlerIConversationalAIAPIEventHandlerEvent handler instance. See IConversationalAIAPIEventHandler.

removeHandler

Removes a registered event handler.

fun removeHandler(handler: IConversationalAIAPIEventHandler)
ParameterTypeDescription
handlerIConversationalAIAPIEventHandlerEvent handler instance. See IConversationalAIAPIEventHandler.

subscribeMessage

Subscribes to a channel to receive agent conversation events.

fun subscribeMessage(channelName: String, completion: (error: ConversationalAIAPIError?) -> Unit)
ParameterTypeDescription
channelNameStringChannel name.
completion(error: ConversationalAIAPIError?) -> UnitCallback. error is null on success, or non-null if the call fails. See ConversationalAIAPIError.

unsubscribeMessage

Unsubscribes from the channel and stops receiving events.

fun unsubscribeMessage(channelName: String, completion: (error: ConversationalAIAPIError?) -> Unit)
ParameterTypeDescription
channelNameStringChannel name.
completion(error: ConversationalAIAPIError?) -> UnitCallback for unsubscription result. error is null if successful, or non-null if failed. See ConversationalAIAPIError.

interrupt

Interrupts the agent’s speech.

fun interrupt(agentUserId: String, completion: (error: ConversationalAIAPIError?) -> Unit)
ParameterTypeDescription
agentUserIdStringAgent user ID.
completion(error: ConversationalAIAPIError?) -> UnitCallback. error is null on success or contains error info if the call fails. See ConversationalAIAPIError.

manualSOS

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

fun manualSOS(agentUserId: String, completion: (requestId: String, error: ConversationalAIAPIError?) -> Unit)

Keep the following in mind when calling this method:

  • The component generates requestId internally. After the request is sent, the component returns the requestId for this request in completion. Your app can store this value to correlate it with the server-side callback.
  • completion only indicates whether 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 onUserManualSosEvent or onUserManualEosEvent callback.
  • 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
agentUserIdStringAgent user ID.
completion(requestId: String, error: ConversationalAIAPIError?) -> UnitCallback function. requestId is the unique identifier for this request. error is null if the call succeeds, and non-null if it fails. This callback only indicates whether 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.

fun manualEOS(agentUserId: String, completion: (requestId: String, error: ConversationalAIAPIError?) -> Unit)

Keep the following in mind when calling this method:

  • The component generates requestId internally. After the request is sent, the component returns the requestId for this request in completion. Your app can store this value to correlate it with the server-side callback.
  • completion only indicates whether 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 onUserManualSosEvent or onUserManualEosEvent callback.
  • 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
agentUserIdStringAgent user ID.
completion(requestId: String, error: ConversationalAIAPIError?) -> UnitCallback function. requestId is the unique identifier for this request. error is null if the call succeeds, and non-null if it fails. This callback only indicates whether the RTM publish succeeded.

loadAudioSettings

Sets audio parameters to optimize the agent’s conversation performance.

You must call this method before each joinChannel call to ensure optimal audio quality.

fun loadAudioSettings(scenario: Int = Constants.AUDIO_SCENARIO_AI_CLIENT)
ParameterTypeDescription
scenarioIntAudio scene. AUDIO_SCENARIO_AI_CLIENT is the default. Use it for Conversational AI agent dialogue scenarios to optimize audio quality for speech recognition and semantic understanding. If you enable the AI Avatar feature, set the scenario to AUDIO_SCENARIO_DEFAULT for better mixing results.

destroy

Destroys the API instance and releases resources.

Call this method when the instance is no longer needed. After calling, the instance becomes unusable.

fun destroy()

IConversationalAIAPIEventHandler class

APIDescription
onMessageErrorMessage processing error callback.
onMessageReceiptUpdatedMessage receipt update callback.
onUserManualSosEventManual SoS result callback.
onUserManualEosEventManual EoS result callback.
onAgentManualEosEventServer-triggered automatic EoS notification callback.
onAgentStateChangedCalled when the agent’s status changes.
onAgentListeningChangedCalled when the agent's listening state changes.
onAgentThinkingChangedCalled when the agent's thinking state changes.
onAgentSpeakingChangedCalled when the agent's speaking state changes.
onAgentInterruptedCalled when an interrupt event occurs.
onAgentMetricsCalled when performance metrics are available.
onAgentErrorCalled when an agent error occurs.
onTranscriptUpdatedCalled when transcription content is updated.
onDebugLogCalled for internal debug logging.

onMessageError

Message processing error callback.

This callback is triggered when an error occurs during message processing. For example, if a chat message fails to be sent, this callback is triggered and the error message is returned.

fun onMessageError(agentUserId: String, error: MessageError)
ParameterTypeDescription
agentUserIdStringAgent user ID.
errorMessageErrorMessage error information, including error type and content. See MessageError for details.

onMessageReceiptUpdated

Message receipt update callback.

fun onMessageReceiptUpdated(agentUserId: String, receipt: MessageReceipt)
ParameterTypeDescription
agentUserIdStringAgent user ID.
receiptMessageReceiptMessage receipt information. See MessageReceipt for details.

onUserManualSosEvent

Manual SoS result callback.

Receives the server's processing result for a manual SoS request. Both success and failure results are returned through this callback — check event.payload.success to determine the outcome.

This callback has a default empty implementation, so existing integrations do not need to implement it.

fun onUserManualSosEvent(agentUserId: String, event: UserManualSosEvent)
ParameterTypeDescription
agentUserIdStringAgent user ID.
eventUserManualSosEventManual SoS event object. See UserManualSosEvent.

onUserManualEosEvent

Manual EoS result callback.

Receives the server's processing result for a manual EoS request. Both success and failure results are returned through this callback — check event.payload.success to determine the outcome.

This callback has a default empty implementation, so existing integrations do not need to implement it.

fun onUserManualEosEvent(agentUserId: String, event: UserManualEosEvent)
ParameterTypeDescription
agentUserIdStringAgent user ID.
eventUserManualEosEventManual EoS event object. See UserManualEosEvent.

onAgentManualEosEvent

Server-triggered automatic EoS notification callback.

Triggered when a user's single speaking turn exceeds the server-side duration threshold. In this case, the server ends the current user's turn on its own and notifies the client through this callback. This event is not a result of calling manualEOS().

This callback has a default empty implementation, so existing integrations do not need to implement it.

fun onAgentManualEosEvent(agentUserId: String, event: AgentManualEosEvent)
ParameterTypeDescription
agentUserIdStringAgent user ID.
eventAgentManualEosEventServer-triggered automatic EoS event object. See AgentManualEosEvent.

onAgentStateChanged

Triggered when the agent’s state changes.

fun onAgentStateChanged(agentUserId: String, event: StateChangeEvent)
ParameterTypeDescription
agentUserIdStringAgent user ID.
eventStateChangeEventState change event. See StateChangeEvent.

onAgentListeningChanged

Triggered when the agent's listening state changes.

This callback is a fine-grained complement to onAgentStateChanged, used to monitor whether the agent is actively listening to user input.

fun onAgentListeningChanged(agentUserId: String, isListening: Boolean)
ParameterTypeDescription
agentUserIdStringAgent user ID.
isListeningBooleanWhether the agent is currently in a listening state.

onAgentThinkingChanged

Triggered when the agent's thinking state changes.

This callback is a fine-grained complement to onAgentStateChanged, used to monitor whether the agent is actively processing a request.

fun onAgentThinkingChanged(agentUserId: String, isThinking: Boolean)
ParameterTypeDescription
agentUserIdStringAgent user ID.
isThinkingBooleanWhether the agent is currently in a thinking state.

onAgentSpeakingChanged

Triggered when the agent's speaking state changes.

This callback is a fine-grained complement to onAgentStateChanged, used to monitor whether the agent is actively playing back speech.

fun onAgentSpeakingChanged(agentUserId: String, isSpeaking: Boolean)
ParameterTypeDescription
agentUserIdStringAgent user ID.
isSpeakingBooleanWhether the agent is currently in a speaking state.

onAgentInterrupted

Triggered when an interrupt event occurs.

fun onAgentInterrupted(agentUserId: String, event: InterruptEvent)
ParameterTypeDescription
agentUserIdStringAgent user ID.
eventInterruptEventInterrupt event. See InterruptEvent.

onAgentMetrics

Triggered when performance metrics become available.

fun onAgentMetrics(agentUserId: String, metric: Metric)
ParameterTypeDescription
agentUserIdStringAgent user ID.
metricMetricPerformance metric. See Metric.

onAgentError

Triggered when an agent error occurs.

fun onAgentError(agentUserId: String, error: ModuleError)
ParameterTypeDescription
agentUserIdStringAgent user ID.
errorModuleErrorError details. See ModuleError.

onTranscriptUpdated

Triggered when the transcription content is updated.

fun onTranscriptUpdated(agentUserId: String, transcript: Transcript)

This callback may trigger frequently. If deduplication is needed, handle it in your business logic.

ParameterTypeDescription
agentUserIdStringAgent user ID.
transcriptTranscriptTranscript data. See Transcript.

onDebugLog

Triggered for internal debug logs.

fun onDebugLog(log: String)
ParameterTypeDescription
logStringDebug log information.

Structures

StateChangeEvent

Represents an agent state change event.
Tracks session flow and updates status indications in the UI, including the event timestamp.

data class StateChangeEvent(
    val state: AgentState,
    val turnId: Long,
    val timestamp: Long,
)
ParameterTypeDescription
stateAgentStateCurrent agent status: silent, listening, thinking, speaking. See AgentState.
turnIdLongConversation turn ID.
timestampLongTimestamp in milliseconds since Unix epoch (January 1, 1970 UTC).

InterruptEvent

Indicates an interrupt event.
Triggered when the user or system interrupts the agent or when the system detects a high-priority message. Used for logging and handling.

data class InterruptEvent(
    val turnId: Long,
    val timestamp: Long
)
ParameterTypeDescription
turnIdLongID of the interrupted conversation turn.
timestampLongTimestamp in milliseconds since Unix epoch (January 1, 1970 UTC).

Metric

Used to record and transmit system performance data. This data can be used for performance monitoring, system optimization, and user experience improvement.

data class Metric(
    val type: ModuleType,
    val name: String,
    val value: Double,
    val timestamp: Long
)
ParameterTypeDescription
typeModuleTypeType of indicator. See ModuleType.
nameStringDescriptive name of the metric.
valueDoubleMetric value (e.g., latency in ms).
timestampLongTimestamp when metric was recorded in milliseconds since Unix epoch (January 1, 1970 UTC).

ModuleError

Processes and reports agent-related error information.

data class ModuleError(
    val type: ModuleType,
    val code: Int,
    val message: String,
    val timestamp: Long,
    val turnId: Long? = null
)
ParameterTypeDescription
typeModuleTypeError type (e.g., LLM failure, TTS exception). See ModuleType.
codeIntSpecific error code.
messageStringDescription of the error.
timestampLongTimestamp of the error in milliseconds since Unix epoch (January 1, 1970 UTC).
turnIdLong?(Optional) turnId corresponding to the image upload error.

ChatMessage

Sealed base class for all message types sent to agents.

This sealed class hierarchy provides a type-safe way to handle messages of different content types.

sealed class ChatMessage

ImageMessage

Used to send image content to the agent.

Supports specifying image files via HTTP/HTTPS links.

data class ImageMessage(
    val uuid: String,
    val imageUrl: String,
) : ChatMessage()
ParameterTypeDescription
uuidStringUnique identifier for the image message.
imageUrlString?HTTP/HTTPS image file link.

MessageReceipt

MessageReceipt represents message receipt information and supports processing multiple media types through MediaInfo.

data class MessageReceipt(
    val type: ModuleType,
    val chatMessageType: ChatMessageType,
    val turnId: Long,
    val message: String
)
ParameterTypeDescription
typeModuleTypeModule type. See ModuleType, for example: llm, mllm, tts, context.
chatMessageTypeChatMessageTypeMessage error type. See ChatMessageType.
turnIdLongTurn ID of the message.
messageStringMessage content. Must be parsed according to the type field. For context, this is usually a JSON string containing resource information.

ChatMessageType

Used to distinguish different types of messages in the session system.

enum class ChatMessageType(val value: String) {
    Text("text"),
    Image("picture"),
    UNKNOWN("unknown");

    companion object {
        fun fromValue(value: String): ChatMessageType {
            return ChatMessageType.entries.find { it.value == value } ?: UNKNOWN
        }
    }
}
ParameterTypeDescription
valueStringThe string value to match against.

MessageError

Used to process and report message error information.

data class MessageError(
    val chatMessageType: ChatMessageType,
    val code: Int,
    val message: String,
    val timestamp: Long
)
ParameterTypeDescription
chatMessageTypeChatMessageTypeMessage error type. See ChatMessageType for details.
codeIntError code used to identify specific error scenarios.
messageStringError description providing detailed explanation, usually a JSON string containing resource information.
timestampLongTimestamp of when the event occurred (milliseconds since January 1, 1970 UTC).

UserManualEventPayload

Common payload for manual SoS/EoS events.

data class UserManualEventPayload(
    val success: Boolean,
    val requestId: String,
    val turnId: Long?,
    val errorMessage: String?
)
ParameterTypeDescription
successBooleanWhether the server successfully processed this manual signal.
requestIdStringRequest ID, corresponding to the requestId returned in completion after calling manualSOS or manualEOS.
turnIdLong?The associated conversation turn ID. null if the server's failure callback does not include a turn_id.
errorMessageString?The raw error message returned by the server. Usually null on success.

UserManualSosEvent

Represents a manual SoS event.

data class UserManualSosEvent(
    val eventId: String,
    val timestamp: Long,
    val payload: UserManualEventPayload
)
ParameterTypeDescription
eventIdStringUnique event ID.
timestampLongEvent timestamp in milliseconds.
payloadUserManualEventPayloadEvent payload. See UserManualEventPayload.

UserManualEosEvent

Represents a manual EoS event.

data class UserManualEosEvent(
    val eventId: String,
    val timestamp: Long,
    val payload: UserManualEventPayload
)
ParameterTypeDescription
eventIdStringUnique event ID.
timestampLongEvent timestamp in milliseconds.
payloadUserManualEventPayloadEvent payload. See UserManualEventPayload.

AgentManualEosPayload

Payload for a server-triggered automatic EoS event.

data class AgentManualEosPayload(
    val reason: String,
    val maxDurationMs: Long,
    val turnId: Long
)
ParameterTypeDescription
reasonStringThe reason the server automatically ended the current user's turn.
maxDurationMsLongThe configured maximum duration, in milliseconds, for a single speaking turn.
turnIdLongThe associated conversation turn ID.

AgentManualEosEvent

Represents a server-triggered automatic EoS event.

data class AgentManualEosEvent(
    val eventId: String,
    val timestamp: Long,
    val payload: AgentManualEosPayload
)
ParameterTypeDescription
eventIdStringUnique event ID.
timestampLongEvent timestamp in milliseconds.
payloadAgentManualEosPayloadEvent payload. See AgentManualEosPayload.

Transcript

Represents a full transcribed message used to render the UI.

data class Transcript(
    val turnId: Long,
    val userId: String = "",
    val text: String,
    var status: TranscriptStatus,
    var type: TranscriptType
)
ParameterTypeDescription
turnIdLongSession turn identifier.
userIdStringUser ID linked to the transcript.
textStringTranscribed message content.
statusTranscriptStatusCurrent status of transcription. See TranscriptStatus.
typeTranscriptTypeTranscript type (e.g., AGENT, USER). See TranscriptType.

ConversationalAIAPIConfig

Holds configuration parameters for initializing the Conversational AI API.

data class ConversationalAIAPIConfig(
    val rtcEngine: RtcEngine,
    val rtmClient: RtmClient,
    val renderMode: TranscriptRenderMode = TranscriptRenderMode.Word,
    val enableLog: Boolean = true,
    val enableRenderModeFallback: Boolean = true
)
ParameterTypeDescription
rtcEngineRtcEngineAudio/video engine instance. See RtcEngine.
rtmClientRtmClientReal-time messaging client. See the Signaling Android API reference.
renderModeTranscriptRenderModeTranscript rendering style. Default: word-by-word. See TranscriptRenderMode.
enableLogBooleanEnables logging if true. When true, logs are written to the RTC SDK log file. Default is true.
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), the component falls back to text mode automatically. If false, the component stays in word mode regardless — this can result in no transcript being displayed if the server doesn't support word-level transcription.

ConversationalAIAPIError

Represents an error type in the Conversational AI API.

sealed class ConversationalAIAPIError : Exception() {
    data class RtmError(val code: Int, val msg: String) : ConversationalAIAPIError()
    data class RtcError(val code: Int, val msg: String) : ConversationalAIAPIError()
    data class UnknownError(val msg: String) : ConversationalAIAPIError()

    val errorCode: Int
        get() = when (this) {
            is RtmError -> this.code
            is RtcError -> this.code
            is UnknownError -> -100
        }

    val errorMessage: String
        get() = when (this) {
            is RtmError -> this.msg
            is RtcError -> this.msg
            is UnknownError -> this.msg
        }
}
PropertyTypeDescription
errorCodeIntRtmError/RtcError: specific code; UnknownError: returns -100.
errorMessageStringHuman-readable description of the error.

Enum classes

Priority

Controls the priority with which the agent handles incoming messages during an interaction.

ValueDescription
INTERRUPTHigh priority: Immediately interrupt the current interaction and process the message. Suitable for urgent or time-sensitive content.
APPENDMedium priority: The message is queued for processing after the current interaction is completed and is suitable for subsequent questions.
IGNORELow priority: This message is only processed when the agent is idle, and will be discarded during ongoing interactions. Suitable for optional content.

AgentState

Represents the current state of the agent.

ValueDescription
SILENTAgent is silent.
LISTENINGAgent is listening.
THINKINGAgent is processing or thinking.
SPEAKINGAgent is speaking.
UNKNOWNUnknown state.

ModuleType

Performance module type enumeration.

ValueDescription
LLMLLM inference latency measurement.
MLLMMLLM inference latency measurement.
TTSText-to-speech synthesis latency measurement.
UNKNOWNUnknown type.

MessageType

Used to distinguish different types of messages in the system.

ValueDescription
ASSISTANTAI assistant transcript message.
USERUser transcript message.
ERRORError message.
METRICSPerformance metrics message.
INTERRUPTInterrupt message.
UNKNOWNUnknown message type.
MESSAGE_RECEIPTMessage receipt.

TranscriptRenderMode

Transcript rendering mode.

ValueDescription
WordWord-by-word transcription and rendering.
TextFull text transcription and rendering.

TranscriptType

Transcript source type.

ValueDescription
AGENTAgent transcript.
USERUser transcript.

TranscriptStatus

Indicates the current status of the transcription.

ValueDescription
IN_PROGRESSThe transcript is still being generated or the speech is still in progress.
ENDThe transcription completed normally.
INTERRUPTEDTranscription was interrupted before completion.
UNKNOWNUnknown status.