# Conversational AI — Main > Only Main documentation is included in this export. # Voice Agent overview (/en/ai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). A Voice Agent is a real-time system that listens to a user, reasons over the conversation, and responds with speech. On Agora, that experience is built from a shared foundation: real-time transport, an agent runtime, AI models, and the endpoint where the conversation is delivered. Agora supports three Voice Agent paths: **in apps**, **Agent Studio**, and **on dedicated devices**. Choose **In apps** if your agent lives in a web, mobile, desktop, or backend-assisted app experience that you build with code. Choose **Agent Studio** if you want to build, deploy, and monitor agents in Agora Console without writing integration code, including agents that handle phone calls. Choose **On dedicated devices** if your endpoint is embedded or hardware-first, such as a toy, wearable, kiosk, or companion. Use the quickstart that matches your path to jump directly into the right implementation workflow. **[In apps quickstart](/en/ai/get-started/quickstart)** Build the minimal backend-plus-client flow and get a working voice agent running quickly. **[Agent Studio quickstart](/en/ai/studio/quickstart)** Create and test your first agent in Agora Console from a pre-built template. **[Dedicated devices quickstart](/en/ai/device-kit/start-here/quickstart)** Bring up the Convo AI Device Kit quickly and verify the end-to-end device workflow. ## Capabilities No matter where you ship it, a Voice Agent usually has the same core layers: - **Real-time transport**: moves audio, events, and conversation state between the user and the agent with low latency. - **Agent runtime**: manages the session lifecycle, turn taking, interruptions, memory, and tool orchestration. - **Models**: provide ASR, LLM, TTS, and optional multimodal capabilities. - **Endpoint**: presents the experience to the user, either through an app or a dedicated device. The first three layers stay conceptually similar across the docs. The sidebar splits by how you build the agent and where it runs, because app teams, Agent Studio users, and device teams need different implementation workflows. ## How this section is organized The AI sidebar is structured in three paths: - **In apps**: for web, mobile, desktop, and backend-assisted app experiences that you build with code. - **Agent Studio**: for building, deploying, and monitoring agents in Agora Console, including inbound and outbound phone calls through Elastic SIP Trunk. - **On dedicated devices**: for embedded or hardware-first endpoints such as toys, wearables, kiosks, and companions. All three paths share the same Voice Agent idea, but they differ in what teams need to build next. App teams usually care first about session orchestration, UI, model behavior, and runtime events. Agent Studio users usually care first about prompts, model configuration, telephony, and call analytics. Device teams usually care first about bring-up, networking, firmware, controls, and hardware integration. # Optimize audio quality (/en/ai/best-practices/audio-setup) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). In real-time audio interactions, the rhythm, continuity, and intonation of conversations between humans and AI often differ from those between humans. To improve the AI–human conversation experience, it's important to optimize audio settings. When using the Android, iOS, or Web RTC SDK with the Conversational AI Engine, follow the best practices in this guide to improve conversation fluency and reliability, especially in complex network environments. ## Server configuration When calling the server API to create a conversational AI agent, use the default values for audio-related parameters to ensure the best audio experience. ## Client configuration To configure the client app, implement the following: ### Integrate the required dynamic libraries For the best Conversational AI Engine audio experience, integrate and load the following dynamic libraries in your project: **Android** - AI noise suppression plugin: `libagora_ai_noise_suppression_extension.so` - AI echo cancellation plug-in: `libagora_ai_echo_cancellation_extension.so` For integration details, refer to [App size optimization](/en/realtime-media/rtc/build/optimize-and-operate/app-size-optimization/android). **iOS** - AI noise suppression plugin: `AgoraAiNoiseSuppressionExtension.xcframework` - AI echo cancellation plug-in: `AgoraAiEchoCancellationExtension.xcframework` For integration details, refer to [App size optimization](/en/realtime-media/rtc/build/optimize-and-operate/app-size-optimization/ios). **Web** - Integrate the `agora-extension-ai-denoiser` extension. Refer to [AI Noise Suppression](/en/realtime-media/rtc/build/enhance-the-audio-experience/ai-noise-suppression/web). > **Info** > > Optimizing audio uses AI Noise Suppression, which is a paid feature. ## Optimize audio for optimal performance You can optimize audio settings in the following ways: - **(Recommended) Use the Toolkit APIs** Supported in Video/Voice SDK version 4.5.1 and above. - **Use the Video/Voice SDK APIs directly** Supported in SDK version 4.3.1 and above. ### Use the toolkit APIs In this solution, you use the toolkit APIs to optimize audio settings. **Android** 1. **Integrate the toolkit** Add the toolkit to your project using Maven or source code. See [Install the Android toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#installation). 2. **Create a toolkit instance** ```kotlin val config = ConversationalAIAPIConfig( rtcEngine = rtcEngine, rtmClient = rtmClient, renderMode = TranscriptRenderMode.Word, enableLog = true, enableRenderModeFallback = true ) val api = ConversationalAIAPIImpl(config) ``` 3. **Set optimal audio settings** Before joining the RTC channel, call `loadAudioSettings()` to apply the optimal audio parameters. ```kotlin api.loadAudioSettings() rtcEngine.joinChannel(token, channelName, null, userId) ``` 4. **Release resources** ```kotlin api.destroy() ``` **iOS** 1. **Integrate the toolkit** Add the toolkit to your project using CocoaPods, Swift Package Manager, or source code. See [Install the iOS toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#installation). 2. **Create a toolkit instance** ```swift let config = ConversationalAIAPIConfig( rtcEngine: rtcEngine, rtmEngine: rtmEngine, renderMode: .words, enableLog: true, enableRenderModeFallback: true ) convoAIAPI = ConversationalAIAPIImpl(config: config) ``` 3. **Set optimal audio settings** Before joining the RTC channel, call `loadAudioSettings()` to apply the optimal audio parameters. ```swift convoAIAPI.loadAudioSettings() rtcEngine.joinChannel(rtcToken: token, channelName: channelName, uid: uid, isIndependent: independent) ``` 4. **Release resources** ```swift convoAIAPI.destroy() ``` **Web** - **Integrate the transcript processing toolkit** Add the toolkit to your project using a package manager or source code. See [Install the Web toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#installation). Refer to [Folder structure](#folder-structure) to understand the role of each file. ### Use the SDK APIs In this solution, you use the RTC SDK to optimize audio settings. #### Set audio parameters The settings in this section apply to Video/Voice SDK versions 4.3.1 and above. If you are using an earlier version, upgrade to version 4.5.1 or above or [Contact Technical Support](mailto:support@agora.io). **Android** For the best conversational AI audio experience, apply the following settings: 1. **Set the audio scenario**: When initializing the engine, set the audio scenario to the AI client scenario. You can also set the scenario before joining a channel by calling the `setAudioScenario` method. 2. **Configure audio parameters**: Call `setParameters` before joining a channel and whenever the `onAudioRouteChanged` callback is triggered. This configuration sets audio 3A plug-ins (acoustic echo cancellation, noise suppression, and automatic gain control), the audio sampling rate, the audio processing mode, and other settings. For recommended parameter values, refer to the sample code. > **Info** > > Since Video/Voice SDK versions 4.3.1 to 4.5.0 do not support the AI client audio scenario, set the scenario to `AUDIO_SCENARIO_CHORUS` to improve the audio experience. However, the audio experience cannot be aligned with versions 4.5.1 and above. To get the best audio experience, upgrade the SDK to version 4.5.1 or higher. The following sample code defines a `setAudioConfigParameters` function to configure audio parameters. Call this function before joining a channel and whenever the audio route changes. ```kotlin private var rtcEngine: RtcEngineEx? = null private var mAudioRouting = Constants.AUDIO_ROUTE_DEFAULT // highlight-start // Set audio configuration parameters private fun setAudioConfigParameters(routing: Int) { mAudioRouting = routing rtcEngine?.apply { setParameters("{\"che.audio.aec.split_srate_for_48k\":16000}") setParameters("{\"che.audio.sf.enabled\":true}") setParameters("{\"che.audio.sf.stftType\":6}") setParameters("{\"che.audio.sf.ainlpLowLatencyFlag\":1}") setParameters("{\"che.audio.sf.ainsLowLatencyFlag\":1}") setParameters("{\"che.audio.sf.procChainMode\":1}") setParameters("{\"che.audio.sf.nlpDynamicMode\":1}") if (routing == Constants.AUDIO_ROUTE_HEADSET // 0 || routing == Constants.AUDIO_ROUTE_EARPIECE // 1 || routing == Constants.AUDIO_ROUTE_HEADSETNOMIC // 2 || routing == Constants.AUDIO_ROUTE_BLUETOOTH_DEVICE_HFP // 5 || routing == Constants.AUDIO_ROUTE_BLUETOOTH_DEVICE_A2DP) { // 10 setParameters("{\"che.audio.sf.nlpAlgRoute\":0}") } else { setParameters("{\"che.audio.sf.nlpAlgRoute\":1}") } setParameters("{\"che.audio.sf.ainlpModelPref\":10}") setParameters("{\"che.audio.sf.nsngAlgRoute\":12}") setParameters("{\"che.audio.sf.ainsModelPref\":10}") setParameters("{\"che.audio.sf.nsngPredefAgg\":11}") setParameters("{\"che.audio.agc.enable\":false}") } } // highlight-end // Create and initialize the RTC engine fun createRtcEngine(rtcCallback: IRtcEngineEventHandler): RtcEngineEx { val config = RtcEngineConfig() config.mContext = AgentApp.instance() config.mAppId = ServerConfig.rtcAppId config.mChannelProfile = Constants.CHANNEL_PROFILE_LIVE_BROADCASTING // highlight-start // Set the audio scene to AI dialogue scene (supported by 4.5.1 and above) // Version 4.3.1 ~ 4.5.0 is set to chorus scene AUDIO_SCENARIO_CHORUS config.mAudioScenario = Constants.AUDIO_SCENARIO_AI_CLIENT // Register audio route change callback config.mEventHandler = object : IRtcEngineEventHandler() { override fun onAudioRouteChanged(routing: Int) { super.onAudioRouteChanged(routing) // Set audio related parameters setAudioConfigParameters(routing) } } // highlight-end try { rtcEngine = (RtcEngine.create(config) as RtcEngineEx).apply { // highlight-start // Load the audio plugin loadExtensionProvider("ai_echo_cancellation_extension") loadExtensionProvider("ai_noise_suppression_extension") // highlight-end } } catch (e: Exception) { Log.e("CovAgoraManager", "createRtcEngine error: $e") } return rtcEngine!! } // Join the channel fun joinChannel(rtcToken: String, channelName: String, uid: Int, isIndependent: Boolean = false) { // highlight-start // Initialize audio configuration parameters setAudioConfigParameters(mAudioRouting) // highlight-end // Configure channel options and join the channel val options = ChannelMediaOptions() options.clientRoleType = CLIENT_ROLE_BROADCASTER options.publishMicrophoneTrack = true options.publishCameraTrack = false options.autoSubscribeAudio = true options.autoSubscribeVideo = false val ret = rtcEngine?.joinChannel(rtcToken, channelName, uid, options) } ``` **iOS** For the best conversational AI audio experience, apply the following settings: 1. **Set the audio scenario**: When initializing the engine, set the audio scenario to the AI client scenario. You can also set the scenario before joining a channel by calling the `setAudioScenario` method. 2. **Configure audio parameters**: Call `setParameters` before joining a channel and whenever the `rtcEngine:didAudioRouteChanged:` callback is triggered. This configuration sets audio 3A plug-ins (acoustic echo cancellation, noise suppression, and automatic gain control), the audio sampling rate, the audio processing mode, and other settings. For recommended parameter values, refer to the sample code. > **Info** > > Since Video/Voice SDK versions 4.3.1 to 4.5.0 do not support the AI client audio scenario, set the scenario to `AgoraAudioScenarioChorus` to improve the audio experience. However, the audio experience cannot be aligned with versions 4.5.1 and above. To get the best audio experience, upgrade the SDK to version 4.5.1 or higher. The following sample code defines a `setAudioConfigParameters` function to configure audio parameters. Call this function before joining a channel and whenever the audio route changes. ```swift class RTCManager: NSObject { private var rtcEngine: AgoraRtcEngineKit! private var audioDumpEnabled: Bool = false private var audioRouting = AgoraAudioOutputRouting.default // highlight-start // Set audio related parameters private func setAudioConfigParameters(routing: AgoraAudioOutputRouting) { audioRouting = routing rtcEngine.setParameters("{\"che.audio.aec.split_srate_for_48k\":16000}") rtcEngine.setParameters("{\"che.audio.sf.enabled\":true}") rtcEngine.setParameters("{\"che.audio.sf.stftType\":6}") rtcEngine.setParameters("{\"che.audio.sf.ainlpLowLatencyFlag\":1}") rtcEngine.setParameters("{\"che.audio.sf.ainsLowLatencyFlag\":1}") rtcEngine.setParameters("{\"che.audio.sf.procChainMode\":1}") rtcEngine.setParameters("{\"che.audio.sf.nlpDynamicMode\":1}") if routing == .headset || routing == .earpiece || routing == .headsetNoMic || routing == .bluetoothDeviceHfp || routing == .bluetoothDeviceA2dp { rtcEngine.setParameters("{\"che.audio.sf.nlpAlgRoute\":0}") } else { rtcEngine.setParameters("{\"che.audio.sf.nlpAlgRoute\":1}") } rtcEngine.setParameters("{\"che.audio.sf.ainlpModelPref\":10}") rtcEngine.setParameters("{\"che.audio.sf.nsngAlgRoute\":12}") rtcEngine.setParameters("{\"che.audio.sf.ainsModelPref\":10}") rtcEngine.setParameters("{\"che.audio.sf.nsngPredefAgg\":11}") rtcEngine.setParameters("{\"che.audio.agc.enable\":false}") } // highlight-end } extension RTCManager: RTCManagerProtocol { func createRtcEngine(delegate: AgoraRtcEngineDelegate) -> AgoraRtcEngineKit { let config = AgoraRtcEngineConfig() config.appId = AppContext.shared.appId config.channelProfile = .liveBroadcasting // highlight-start // Set the audio scene to AI dialogue scene (supported by 4.5.1 and above) // Versions 4.3.1 ~ 4.5.0 support chorus scenes .chorus config.audioScenario = .aiClient rtcEngine = AgoraRtcEngineKit.sharedEngine(with: config, delegate: delegate) // Register audio route change callback rtcEngine.addDelegate(self) // highlight-end return rtcEngine } func joinChannel(rtcToken: String, channelName: String, uid: String) { // highlight-start // Initialize audio configuration parameters setAudioConfigParameters(routing: audioRouting) // highlight-end // Configure channel options and join the channel let options = AgoraRtcChannelMediaOptions() options.clientRoleType = .broadcaster options.publishMicrophoneTrack = true options.publishCameraTrack = false options.autoSubscribeAudio = true options.autoSubscribeVideo = false let ret = rtcEngine.joinChannel(byToken: rtcToken, channelId: channelName, uid: UInt(uid) ?? 0, mediaOptions: options) } } // highlight-start // Implement the AgoraRtcEngineDelegate interface to handle audio route change callbacks extension RTCManager: AgoraRtcEngineDelegate { public func rtcEngine(_ engine: AgoraRtcEngineKit, didAudioRouteChanged routing: AgoraAudioOutputRouting) { setAudioConfigParameters(routing: routing) } } // highlight-end ``` **Web** Integrate the `agora-extension-ai-denoiser` extension. Refer to [AI Noise Suppression](/en/realtime-media/rtc/build/enhance-the-audio-experience/ai-noise-suppression/web). > **Info** > > Use Web SDK version 4.15.0 or later. ## Reference This section contains content that completes the information on this page, or points you to documentation that explains other aspects to this product. ### Sample project Refer to the following open-source sample code to set audio-related parameters. **Android** - [`CovRtcManager.kt`](https://github.com/AgoraIO-Community/Conversational-AI-Demo/blob/main/Android/scenes/convoai/src/main/java/io/agora/scene/convoai/rtc/CovRtcManager.kt) **iOS** - [`RTCManager.swift`](https://github.com/AgoraIO-Community/Conversational-AI-Demo/blob/main/iOS/Scenes/ConvoAI/ConvoAI/ConvoAI/Classes/Manager/RTCManager.swift) ### Folder structure **Android** - `IConversationalAIAPI.kt`: API interface and related data structures and enumerations - `ConversationalAIAPIImpl.kt`: ConversationalAI API main implementation logic - `ConversationalAIUtils.kt`: Tool functions and event callback management - `subRender/` - `v3/`: Transcript module - `TranscriptionController.kt`: Transcript Controller - `MessageParser.kt`: Message Parser **iOS** - `ConversationalAIAPI.swift`: API interface and related data structures and enumerations - `ConversationalAIAPIImpl.swift`: ConversationalAI API main implementation logic - `Transcription/` - `TranscriptionController.swift`: Transcript Controller **Web** - `index.ts`: API Class - `type.ts`: API interface and related data structures and enumerations - `utils/` - `index.ts`: API utility functions - `events.ts`: Event management class, which can be extended to easily implement event monitoring and broadcasting - `sub-render.ts`: Transcript module ### API reference **Android** - SDK - `setAudioScenario` - `setParameters` - `onAudioRouteChanged` - Toolkit - [`loadAudioSettings`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#loadaudiosettings) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#destroy) **iOS** - SDK - `setAudioScenario` - `setParameters` - `rtcEngine:didAudioRouteChanged:` - Toolkit - [`loadAudioSettings`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#loadaudiosettings12) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#destroy) **web** - Toolkit - [`IConversationalAIAPIEventHandlers interface`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#iconversationalaiapieventhandlers-interface) - [`EConversationalAIAPIEvents`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#econversationalaiapievents) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#unsubscribe) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#destroy) # Get agent state (/en/ai/best-practices/get-agent-state) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). If you need to track agent state changes in your client app, you can use either Signaling (RTM) Message or RTM Presence. This guide explains how to get agent state using RTM Message and describes [how the two approaches differ](#rtm-message-vs-rtm-presence). > **Info** > > - To monitor state changes using client components, see [Listen to agent events](/en/ai/build/handle-runtime-events/webhooks). > - To get agent state through RTM Presence, continue using your existing Presence implementation. ## Understand the tech The Conversational AI Engine pushes agent state change events to the client as individual RTM messages through the `onMessageEvent` callback. Unlike RTM Presence, which synchronizes state as key-value pairs, RTM Message wraps each state change in a separate event message. This makes it easier to record state change timestamps, process events sequentially, or consume state events together with other RTM Message events. The inner `message` field of each RTM message is a JSON string that requires a second parse to access the state event data. Use the `event_type` field in the inner message to identify the event type. The following agent states are pushed through RTM Message: - `state.listening` - `state.thinking` - `state.speaking` The flow works as follows: ```text Agent state change ├─ listening -> true / false ├─ thinking -> true / false └─ speaking -> true / false ↓ RTM Message ↓ Client parses inner payload and identifies event by event_type ``` ### State event types The Conversational AI Engine sends an RTM Message each time the agent state changes. Each message corresponds to a single state change event. | `event_type` | Description | | :---------------- | :-------------------------------------------------- | | `state.listening` | The agent starts or stops listening for user input. | | `state.thinking` | The agent starts or stops processing user input. | | `state.speaking` | The agent starts or stops speaking. | ### Message structure The inner `message` field is a JSON string. After deserialization, the structure is as follows: ```json { "event_id": "xxxx", "event_type": "state.listening", "event_ms": 1611566412672, "payload": { "value": true, "timestamp": 1611566412600 } } ``` | Field | Type | Description | | :------------------ | :------ | :-------------------------------------------------------------------------------------- | | `event_id` | string | Unique event ID. | | `event_type` | string | State event type. One of `state.listening`, `state.thinking`, or `state.speaking`. | | `event_ms` | integer | Timestamp when the event was sent, in milliseconds. | | `payload.value` | boolean | Current state value. `true` means the agent entered the state; `false` means it exited. | | `payload.timestamp` | integer | Timestamp when the state change actually occurred, in milliseconds. | ## Prerequisites Before you begin, ensure that you have: - Completed the basic agent integration. See [Quickstart](/en/ai/get-started/quickstart). - Integrated the RTM SDK and implemented message listener logic. See [RTM quickstart](https://docs.agora.io/en/signaling/get-started/sdk-quickstart). - Enabled the RTM service and set `data_channel` to `rtm` when starting the agent. ## Implementation ### Enable RTM when starting the agent When calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), include the following configuration: ```json { "properties": { "advanced_features": { "enable_rtm": true }, "parameters": { "data_channel": "rtm" } } } ``` ### Listen for and parse state messages After logging in to RTM and subscribing to the channel with the same name as the agent, parse state messages in the RTM message callback. The handling logic consists of the following steps: 1. Deserialize the RTM `message` field into a state event object. 2. Check that the deserialized result contains `event_type` and `payload`. 3. Dispatch handling based on `event_type`, and use `payload.value` to update your app state. In the following examples: - The inner `message` field is a JSON string and must be deserialized again to obtain `event_type` and `payload`. - `event_type` identifies the specific state type. - `payload.value` indicates whether the agent is entering (`true`) or exiting (`false`) the state. - `payload.timestamp` can be used for precise ordering or logging. **Android** ```kotlin val rtmConfig = RtmConfig() rtmConfig.eventListener = object : RtmEventListener { override fun onMessageEvent(event: MessageEvent) { // 1. Deserialize the inner message (JSON string) val payload = JSONObject(event.message.data) if (!payload.has("event_type") || !payload.has("payload")) { return } val eventType = payload.getString("event_type") val statePayload = payload.getJSONObject("payload") val value = statePayload.getBoolean("value") val timestamp = statePayload.getLong("timestamp") // 2. Dispatch based on event_type when (eventType) { "state.listening" -> handleListeningChanged(value, timestamp) "state.thinking" -> handleThinkingChanged(value, timestamp) "state.speaking" -> handleSpeakingChanged(value, timestamp) } } } mRtmClient = RtmClient.create(rtmConfig) ``` **iOS** ```swift func rtmKit(_ rtmKit: AgoraRtmClientKit, didReceiveMessageEvent event: AgoraRtmMessageEvent) { // 1. Deserialize the inner message (JSON string) guard let jsonString = event.message.stringData, let data = jsonString.data(using: .utf8), let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let eventType = payload["event_type"] as? String, let statePayload = payload["payload"] as? [String: Any] else { return } let value = statePayload["value"] as? Bool ?? false let timestamp = statePayload["timestamp"] as? Int ?? 0 // 2. Dispatch based on event_type switch eventType { case "state.listening": handleListeningChanged(value, timestamp) case "state.thinking": handleThinkingChanged(value, timestamp) case "state.speaking": handleSpeakingChanged(value, timestamp) default: break } } ``` **Web** ```typescript rtm.addEventListener("message", (event) => { // 1. Deserialize the inner message (JSON string) const payload = JSON.parse(event.message as string); if (!payload.event_type || !payload.payload) { return; } const { event_type, payload: statePayload } = payload; // 2. Dispatch based on event_type switch (event_type) { case "state.listening": handleListeningChanged(statePayload.value, statePayload.timestamp); break; case "state.thinking": handleThinkingChanged(statePayload.value, statePayload.timestamp); break; case "state.speaking": handleSpeakingChanged(statePayload.value, statePayload.timestamp); break; } }); ``` ### Update app state Use the received events to update your UI or internal state machine. For example: - When `state.listening` with `payload.value = true` is received, display "Listening". - When `state.thinking` with `payload.value = true` is received, display "Thinking". - When `state.speaking` with `payload.value = true` is received, display "Speaking". ## RTM Message vs RTM Presence The Conversational AI Engine supports getting agent state through both RTM Message and RTM Presence. The key differences are: | | RTM Presence | RTM Message | | :---------- | :------------------------------- | :------------------------------------------------------- | | Return form | State key-value pairs | State event messages | | Granularity | Better for reading current state | Better for handling each state change | | Timing info | Relies on message arrival time | Includes explicit `event_ms` and `payload.timestamp` | | Use case | Simple UI state display | Event-driven logic, logging, unified message consumption | Choose based on your needs: - If you only need to update the UI based on whether the agent is currently `listening`, `thinking`, or `speaking`, RTM Presence is simpler to integrate. - If you want to process state changes together with captions, interruptions, or performance metrics in a unified RTM Message handler, use RTM Message. - If you need to record the timestamp of each state change or analyze state transitions in sequence, use RTM Message. ## Considerations Keep the following in mind when implementing this feature: - **Double deserialization**: The inner `message` field is a JSON string and must be deserialized a second time to access `event_type` and `payload`. - **Avoid duplicate UI updates**: If you are already driving UI state through RTM Presence, avoid having both implementations update the same UI state simultaneously, as this can cause redundant updates or state flickering. - **`state.speaking` end timing**: A `state.speaking` value of `false` does not guarantee that the client has finished playing audio. The server estimates the speaking end time based on TTS audio length, so there may be a delay between the state switching to `false` and the client completing playback. - **Scope of state messages**: State messages cover only `listening`, `thinking`, and `speaking` agent state events. Manual SoS and EoS signals and their callbacks are not included. # Manually control start and end of speech (/en/ai/best-practices/manual-turn-control) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). When your business scenario isn't a good fit for letting the server automatically determine when a user starts or stops speaking, use manual Start of Speech (SoS) and End of Speech (EoS) to have the client explicitly declare the user's turn boundaries. This is useful for AI interviews, interactive quizzes, walkie-talkie style push-to-talk, and other "press to start, tap to submit" interactions. This guide explains how to implement manual control over user speech boundaries by configuring the agent and using the client toolkit. ## Understand the tech Manual turn control consists of two independent capabilities: - **Manual SoS**: The client explicitly declares that the user has started speaking. - **Manual EoS**: The client explicitly declares that the user has finished speaking. `start_of_speech.mode` and `end_of_speech.mode` are independent settings. Choose which boundary needs manual control based on your use case: | Business scenario | `start_of_speech.mode` | `end_of_speech.mode` | Client call | | --------------------------------------------------------------------------------------------- | ---------------------- | -------------------- | ---------------------------------------- | | The user can start speaking freely, but must tap "submit answer" | `vad` | `manual` | Call only `manualEOS` | | The user taps or holds a button to start speaking, and the server determines when speech ends | `manual` | `vad` | Call only `manualSOS` | | Press-and-hold to talk, release to send (walkie-talkie mode) | `manual` | `manual` | Call `manualSOS` first, then `manualEOS` | - If only `end_of_speech.mode` is `manual`, the server still uses VAD to automatically detect when the user starts speaking. Your app only needs to call `manualEOS` when the user taps submit. - If only `start_of_speech.mode` is `manual`, the server starts accepting audio for the current turn only after your app calls `manualSOS`. End of speech is still detected automatically by VAD, so your app does not need to call `manualEOS`. - If both `start_of_speech.mode` and `end_of_speech.mode` are `manual`, the server starts accepting audio for the current turn only after your app calls `manualSOS`, and submits the turn only after your app calls `manualEOS`. ## Prerequisites Before you begin, ensure that you have: - Completed the basic steps for interacting with an agent. See [Quickstart](/en/ai/get-started/quickstart). - Integrated Video SDK v4.5.1 or later and followed the [Quickstart](/en/realtime-media/rtc/get-started-sdk) guide to implement basic real-time audio and video features. - Enabled Signaling for your project in the Agora Console and followed the [Signaling Quickstart](/en/realtime-media/rtm/quickstart) to implement real-time messaging. - Made sure the RTC engine instance is initialized and the app is logged in to Signaling. The client toolkit does not handle initialization, lifecycle management, authentication, or login for Video SDK or Signaling. ## Implement manual control Manual turn control requires configuring both the agent and the client toolkit: 1. Configure manual mode when you start the agent. 2. Initialize the client toolkit and subscribe to channel messages. 3. Register handlers for the manual SoS/EoS result events. 4. Call `manualSOS`/`manualEOS` when the user taps start or submit. ### Enable manual turn control when starting the agent When calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), use the following parameter settings: - `advanced_features.enable_rtm: true`: Start Signaling (Required) - `parameters.data_channel: "rtm"`: Enable the RTM data transmission channel (Required) - `parameters.enable_metrics: true`: Receive agent performance data (Enable on demand) - `parameters.enable_error_message: true`: Receive agent error events (Enable on demand) Then set the boundary or boundaries you want to control manually to `"manual"`. The following `curl` examples show three common configurations: **Manual EoS only** If you only need to manually control end of speech, keep automatic SoS and set only `end_of_speech.mode` to `manual`. ```shell curl --request POST \ --url https://api.agora.io/api/conversational-ai-agent/v2/projects//join \ --header 'Authorization: agora token="007abcxxxxxxx123"' \ --data ' { "name": "manual-eos-agent", "properties": { "channel": "channel_name", "token": "token", "agent_rtc_uid": "0", "remote_rtc_uids": [ "123" ], "advanced_features": { "enable_rtm": true }, "asr": { "language": "en-US" }, "llm": { "url": "https://api.xxxx/v1/xxxx", "api_key": "xxx", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "greeting_message": "Hello, how can I help you?", "failure_message": "Sorry, I am unable to answer that question.", "max_history": 10, "params": { "model": "xxxx" } }, "tts": { "vendor": "minimax", "params": { "key": "your-minimax-key", "model": "speech-01-turbo", "voice_setting": { "voice_id": "female-shaonv", "speed": 1, "vol": 1, "pitch": 0, "emotion": "happy" }, "audio_setting": { "sample_rate": 16000 } } }, "turn_detection": { "mode": "default", "config": { "start_of_speech": { "mode": "vad", "vad_config": { "interrupt_duration_ms": 160, "speaking_interrupt_duration_ms": 320, "prefix_padding_ms": 800 } }, "end_of_speech": { "mode": "manual" } } }, "parameters": { "data_channel": "rtm" } } } ' ``` **Manual SoS only** If you only need to manually control start of speech, set `start_of_speech.mode` to `manual` and keep automatic EoS. ```shell curl --request POST \ --url https://api.agora.io/api/conversational-ai-agent/v2/projects//join \ --header 'Authorization: agora token="007abcxxxxxxx123"' \ --data ' { "name": "manual-sos-agent", "properties": { "channel": "channel_name", "token": "token", "agent_rtc_uid": "0", "remote_rtc_uids": [ "123" ], "advanced_features": { "enable_rtm": true }, "asr": { "language": "en-US" }, "llm": { "url": "https://api.xxxx/v1/xxxx", "api_key": "xxx", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "greeting_message": "Hello, how can I help you?", "failure_message": "Sorry, I am unable to answer that question.", "max_history": 10, "params": { "model": "xxxx" } }, "tts": { "vendor": "minimax", "params": { "key": "your-minimax-key", "model": "speech-01-turbo", "voice_setting": { "voice_id": "female-shaonv", "speed": 1, "vol": 1, "pitch": 0, "emotion": "happy" }, "audio_setting": { "sample_rate": 16000 } } }, "turn_detection": { "mode": "default", "config": { "start_of_speech": { "mode": "manual" }, "end_of_speech": { "mode": "vad", "vad_config": { "silence_duration_ms": 480 } } } }, "parameters": { "data_channel": "rtm" } } } ' ``` **Manual SoS + EoS** If you need a complete push-to-talk experience, set both `start_of_speech.mode` and `end_of_speech.mode` to `manual`. ```shell curl --request POST \ --url https://api.agora.io/api/conversational-ai-agent/v2/projects//join \ --header 'Authorization: agora token="007abcxxxxxxx123"' \ --data ' { "name": "manual-sos-eos-agent", "properties": { "channel": "channel_name", "token": "token", "agent_rtc_uid": "0", "remote_rtc_uids": [ "123" ], "advanced_features": { "enable_rtm": true }, "asr": { "language": "en-US" }, "llm": { "url": "https://api.xxxx/v1/xxxx", "api_key": "xxx", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "greeting_message": "Hello, how can I help you?", "failure_message": "Sorry, I am unable to answer that question.", "max_history": 10, "params": { "model": "xxxx" } }, "tts": { "vendor": "minimax", "params": { "key": "your-minimax-key", "model": "speech-01-turbo", "voice_setting": { "voice_id": "female-shaonv", "speed": 1, "vol": 1, "pitch": 0, "emotion": "happy" }, "audio_setting": { "sample_rate": 16000 } } }, "turn_detection": { "mode": "default", "config": { "start_of_speech": { "mode": "manual" }, "end_of_speech": { "mode": "manual" } } }, "parameters": { "data_channel": "rtm" } } } ' ``` After a successful response, the agent joins the specified RTC channel and is ready to interact with the user. ### Integrate and initialize the client toolkit **Android** 1. Add the toolkit to your project using Maven or source code. See [Install the Android toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#installation). Refer to the [component structure](#component-structure) to understand the role of each file. 2. Create a configuration object for the RTC engine and Signaling client instances, then use it to initialize the component instance. ```kotlin val config = ConversationalAIAPIConfig( rtcEngine = rtcEngine, rtmClient = rtmClient, renderMode = TranscriptRenderMode.Word, enableLog = true, enableRenderModeFallback = true ) val api = ConversationalAIAPIImpl(config) ``` 3. Register a handler for the manual SoS/EoS result events, then subscribe to the agent's channel. ```kotlin api.addHandler(object : IConversationalAIAPIEventHandler { override fun onUserManualSosEvent(agentUserId: String, event: UserManualSosEvent) { // Handle the manual SoS result. event.payload.success indicates whether the server accepted it. } override fun onUserManualEosEvent(agentUserId: String, event: UserManualEosEvent) { // Handle the manual EoS result. } override fun onAgentManualEosEvent(agentUserId: String, event: AgentManualEosEvent) { // Handle the server-triggered automatic EoS notification. } }) api.subscribeMessage("channelName") { error -> if (error != null) { // Handle subscription failure. } } ``` **iOS** 1. Add the toolkit to your project using CocoaPods, Swift Package Manager, or source code. See [Install the iOS toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#installation). Refer to the [component structure](#component-structure) to understand the role of each file. 2. Create a configuration object for the RTC engine and Signaling client instances, then use it to initialize the component instance. ```swift let config = ConversationalAIAPIConfig( rtcEngine: rtcEngine, rtmEngine: rtmEngine, renderMode: .words, enableLog: true, enableRenderModeFallback: true ) convoAIAPI = ConversationalAIAPIImpl(config: config) ``` 3. Register a handler for the manual SoS/EoS result events, then subscribe to the agent's channel. ```swift convoAIAPI.addHandler(handler: self) func onUserManualSosEvent(agentUserId: String, event: UserManualSosEvent) { // Handle the manual SoS result. event.payload.success indicates whether the server accepted it. } func onUserManualEosEvent(agentUserId: String, event: UserManualEosEvent) { // Handle the manual EoS result. } func onAgentManualEosEvent(agentUserId: String, event: AgentManualEosEvent) { // Handle the server-triggered automatic EoS notification. } convoAIAPI.subscribeMessage(channelName: channelName) { error in if let error = error { // Handle subscription failure. } } ``` **Web** 1. Add the toolkit to your project using a package manager or source code. See [Install the Web toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#installation). Refer to the [component structure](#component-structure) to understand the role of each file. 2. Create a configuration object for the RTC engine and Signaling client instances, then use it to initialize the component instance. ```ts const config: IConversationalAIAPIConfig = { rtcEngine, rtmEngine, renderMode: ETranscriptHelperMode.WORD, enableLog: true, enableRenderModeFallback: true, } const conversationalAIAPI = await ConversationalAIAPI.init(config) ``` 3. Register a handler for the manual SoS/EoS result events, then subscribe to the agent's channel. ```ts conversationalAIAPI.on(EConversationalAIAPIEvents.USER_MANUAL_SOS_RESULT, (agentUserId, event) => { // Handle the manual SoS result. event.payload.success indicates whether the server accepted it. }) conversationalAIAPI.on(EConversationalAIAPIEvents.USER_MANUAL_EOS_RESULT, (agentUserId, event) => { // Handle the manual EoS result. }) conversationalAIAPI.on(EConversationalAIAPIEvents.AGENT_MANUAL_EOS_RESULT, (agentUserId, event) => { // Handle the server-triggered automatic EoS notification. }) conversationalAIAPI.subscribeMessage(channelName) ``` > **Info** > > These handlers receive the server's processing result for your manual SoS/EoS requests. Use the `event`, `requestId`, and error information to implement your own business logic. See the [client toolkit API reference](#toolkit) for details. ### Send manual SoS when the user starts speaking Call `manualSOS` only when `start_of_speech.mode` is `"manual"`. If you use automatic SoS through VAD, skip this step. **Android** ```kotlin api.manualSOS(agentUserId = "agentUserId") { requestId, error -> if (error != null) { Log.e("ManualSOS", "Send failed: ${error.errorMessage}, requestId=$requestId") } else { Log.i("ManualSOS", "SoS sent, requestId=$requestId") } } ``` **iOS** ```swift convoAIAPI.manualSOS(agentUserId: agentUid) { requestId, error in if let error = error { print("Send failed: \(error.message), requestId=\(requestId)") } else { print("SoS sent, requestId=\(requestId)") } } ``` **Web** ```ts const requestId = await conversationalAIAPI.manualSOS(agentUserId) ``` Once manual SoS takes effect, the server starts counting subsequent audio toward the current user turn. Audio that arrives before this point is not counted. ### Send manual EoS when the user finishes speaking Call `manualEOS` only when `end_of_speech.mode` is `"manual"`. If you use automatic EoS through VAD, skip this step. **Android** ```kotlin api.manualEOS(agentUserId = "agentUserId") { requestId, error -> if (error != null) { Log.e("ManualEOS", "Send failed: ${error.errorMessage}, requestId=$requestId") } else { Log.i("ManualEOS", "EoS sent, requestId=$requestId") } } ``` **iOS** ```swift convoAIAPI.manualEOS(agentUserId: agentUid) { requestId, error in if let error = error { print("Send failed: \(error.message), requestId=\(requestId)") } else { print("EoS sent, requestId=\(requestId)") } } ``` **Web** ```ts const requestId = await conversationalAIAPI.manualEOS(agentUserId) ``` Once manual EoS takes effect, the agent submits the turn for ASR and LLM inference as usual. This signal only marks the end of the user's current speech segment — it does not immediately end the entire turn. ### Destroy the component instance When the agent interaction ends, destroy the component instance to release all resources. **Android** ```kotlin api.destroy() ``` **iOS** ```swift convoAIAPI.destroy() ``` **Web** ```ts conversationalAIAPI.destroy() ``` ## Reference ### API reference #### RESTful API - [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) #### Toolkit **Android** - [`addHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#addhandler) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#subscribemessage) - [`manualSOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#manualsos) - [`manualEOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#manualeos) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#destroy) - [`onUserManualSosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onusermanualsosevent) - [`onUserManualEosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onusermanualeosevent) - [`onAgentManualEosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagentmanualeosevent) **iOS** - [`addHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#addhandler) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#subscribemessage) - [`manualSOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#manualsos) - [`manualEOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#manualeos) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#destroy) - [`onUserManualSosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onusermanualsosevent) - [`onUserManualEosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onusermanualeosevent) - [`onAgentManualEosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagentmanualeosevent) **Web** - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#subscribemessage) - [`manualSOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#manualsos) - [`manualEOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#manualeos) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#destroy) - [`EConversationalAIAPIEvents`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#econversationalaiapievents) # Optimize latency (/en/ai/best-practices/optimize-latency) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Latency is a key factor affecting user experience in conversational AI agent scenarios. This guide helps you understand and optimize conversation latency to improve user experience. ## How latency works Understanding latency composition helps you identify optimization opportunities. ### Cascaded architecture latency When using the cascaded architecture with ASR, LLM, and TTS components, end-to-end latency consists of the following: ```text End-to-end latency = RTC latency + Algorithm preprocessing latency + ASR latency + LLM latency + TTS latency (+ Avatar latency) ``` ### Latency for each component The following table shows typical latency ranges for each component based on actual test data: | Component | Latency metric | Description | Typical latency range (ms) | | ----------------------- | ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------- | | RTC | Audio and video latency | Includes audio capture, encoding, network transmission, decoding, and playback | 150-300 | | Algorithm preprocessing | Preprocessing latency | Includes VAD (Voice Activity Detection), intelligent interruption handling (AIVAD), and other algorithm processing time | 720-940\* | | ASR | `asr_ttlw` | Time To Last Word. The latency from when the user stops speaking to when ASR outputs the last word. | 400-700 | | LLM | `llm_ttfb` / `llm_ttfs` | TTFB: Time To First Byte, the first byte latency.; TTFS: Time To First Sentence, the first sentence latency. | 250-1000 | | TTS | `tts_ttfb` | Time To First Byte. The response latency from when the TTS request starts to when the first byte is received. | 100-350 | | Avatar rendering | Rendering latency | The latency from when the avatar module receives the first frame of TTS audio to when it generates and synchronizes the first frame of audio and video (if enabled) | 50-200 | \* Algorithm preprocessing latency is based on `silence_duration_ms` set to 640 ms. Adjusting this parameter affects preprocessing latency. > **Info** > > Test data shows that LLM typically contributes the most to overall latency. Optimizing LLM selection and configuration is key to reducing end-to-end latency. ### Real-world latency example The following example shows latency data from three conversation turns in an actual conversation. This data comes from the [`111 agent metrics`](../reference/event-types#111-agent-metrics) event in Agora's [message notification service](../build/handle-runtime-events/webhooks): ```json { "metrics": [ { "turn_id": 1, "tts_ttfb": 61 }, { "turn_id": 2, "asr_ttlw": 141, "llm_ttfb": 270, "llm_ttfs": 482, "tts_ttfb": 90 }, { "turn_id": 3, "asr_ttlw": 103, "llm_ttfb": 306, "llm_ttfs": 948, "tts_ttfb": 106 } ] } ``` ## Monitor latency metrics The Conversational AI engine provides two ways to monitor latency metrics for each conversation turn: ### Use client components If you use client components (Android, iOS, or Web), you can listen to agent performance metrics in real time by registering the `onAgentMetrics` callback. **Android** ```kotlin api.addHandler(object : IConversationalAIAPIEventHandler { override fun onAgentMetrics(agentUserId: String, metric: Metric) { when (metric.type) { ModuleType.ASR -> { Log.d("Metrics", "ASR TTLW: \${metric.value}ms") } ModuleType.LLM -> { // metric.name can be "ttfb" or "ttfs" Log.d("Metrics", "LLM \${metric.name}: \${metric.value}ms") } ModuleType.TTS -> { Log.d("Metrics", "TTS TTFB: \${metric.value}ms") } ModuleType.TOTAL -> { Log.d("Metrics", "Total Delay: \${metric.value}ms") } else -> { Log.d("Metrics", "\${metric.type}: \${metric.name} = \${metric.value}ms") } } } }) ``` **iOS** ```swift func onAgentMetrics(agentUserId: String, metrics: Metric) { switch metrics.type { case .asr: print("ASR TTLW: \(metrics.value)ms") case .llm: print("LLM \(metrics.name): \(metrics.value)ms") case .tts: print("TTS TTFB: \(metrics.value)ms") case .total: print("Total Delay: \(metrics.value)ms") case .unknown: print("Unknown metric: \(metrics.name) = \(metrics.value)ms") } } ``` **Web** ```ts conversationalAIAPI.on( EConversationalAIAPIEvents.AGENT_METRICS, (agentUserId: string, metrics: Metric) => { console.log(`[\${metrics.type}] \${metrics.name}: \${metrics.value}ms`); if (metrics.type === 'TOTAL') { console.log(`Total delay for turn: \${metrics.value}ms`); } } ); ``` For detailed integration steps and API reference, see [Webhooks](../build/handle-runtime-events/webhooks). ### Use Message Notification Service If you have enabled Agora's Message Notification Service, you can obtain agent performance metrics by receiving the `agent metrics` event where `eventType` is `111`. **Event callback example** ```json { "noticeId": "2000001428:4330:107", "productId": 17, "eventType": 111, "notifyMs": 1611566412672, "payload": { "agent_id": "A42AC47Hxxxxxxxx4PK27ND25E", "start_ts": 1000, "stop_ts": 1672531200, "channel": "test-channel", "metrics": [ { "turn_id": 1, "tts_ttfb": 61 }, { "turn_id": 2, "asr_ttlw": 141, "llm_ttfb": 270, "llm_ttfs": 482, "tts_ttfb": 90, } ] } } ``` For detailed event field descriptions, see [Notification event 111 agent metrics](../reference/event-types#111-agent-metrics). ## Optimize cascaded architecture latency To reduce latency in cascaded architecture, focus on optimizing individual components, geographic deployment, and RTC settings. ### Optimize LLM, ASR, and TTS components LLM is typically the component that contributes the most to latency. Optimizing LLM can significantly reduce overall latency. **Choose low-latency vendors** LLM, ASR, and TTS vendors and models vary significantly in response speed. Refer to the [Conversational AI Performance Lab](https://www.agora.io/en/conversational-ai-performance-lab) to compare performance metrics across vendors. **Optimize parameter configuration** When creating an agent, read the vendor documentation for ASR, LLM, and TTS to understand available parameters and tune them for your use case. The following are general optimization approaches: - **LLM** - **Choose smaller models**: Models such as `gpt-4o-mini` and `gemini-2.5-flash` typically respond faster than larger models. - **Limit `max_tokens`**: Reducing the maximum number of tokens generated can lower TTFS (first sentence latency). - **Enable streaming response**: Ensure `stream: true` so the agent can start speaking as soon as possible. - **ASR** - **Use vendor-recommended sampling rate**: Use the sampling rate recommended by the vendor, such as 16 kHz, to avoid unnecessary resampling. - **Limit language model**: Use the `phrases` or `context` parameter to provide domain-specific vocabulary and improve recognition speed. - **Disable non-essential features**: Some ASR vendors provide advanced parameters such as punctuation and tone output. You can disable these based on your use case to improve response speed. - **TTS** - **Choose faster modes**: Some TTS providers offer modes such as turbo or low-latency, which typically respond faster than default mode. - **Choose simpler voices**: Some TTS providers offer voices with varying complexity. Choosing less complex voices can reduce generation time. - **Disable non-essential features**: Some TTS vendors provide advanced parameters such as profanity\_filter, punctuation\_filter, and diarization. You can disable these based on your use case to improve response speed. The following example shows how to optimize LLM parameters: ```json { "properties": { "llm": { "url": "https://api.openai.com/v1/chat/completions", "api_key": "your_api_key", "params": { "model": "gpt-4o-mini", // Select the faster-responding model "temperature": 0.7, "max_tokens": 150, // Limit the generation length to reduce latency "stream": true // Enable streaming response } } } } ``` ### Optimize RTC latency RTC latency includes audio capture, encoding, network transmission, decoding, and playback. To optimize RTC latency, configure audio settings on the client side. **Use AI conversation scenario** Agora RTC SDK 4.5.1 and later supports the AI conversation scenario (`AUDIO_SCENARIO_AI_CLIENT`), which is specifically optimized for AI conversations and includes: - Optimized audio 3A algorithms (echo cancellation, noise reduction, and gain control) - Lower audio capture and playback latency - Audio processing tailored to AI voice characteristics **Android** **Use the client-side component API (recommended)** ```kotlin val config = ConversationalAIAPIConfig( rtcEngine = rtcEngine, rtmClient = rtmClient, renderMode = TranscriptRenderMode.Word, enableLog = true, enableRenderModeFallback = true ) val api = ConversationalAIAPIImpl(config) // Load optimal audio settings api.loadAudioSettings() ``` **Configure the RTC SDK directly** ```kotlin val config = RtcEngineConfig() config.mAudioScenario = Constants.AUDIO_SCENARIO_AI_CLIENT rtcEngine = RtcEngine.create(config) ``` **iOS** **Use the client-side component API (recommended)** ```swift let config = ConversationalAIAPIConfig( rtcEngine: rtcEngine, rtmEngine: rtmEngine, renderMode: .words, enableLog: true, enableRenderModeFallback: true ) convoAIAPI = ConversationalAIAPIImpl(config: config) // Load optimal audio settings convoAIAPI.loadAudioSettings() ``` **Configure the RTC SDK directly** ```swift let config = AgoraRtcEngineConfig() config.audioScenario = .aiClient rtcEngine = AgoraRtcEngineKit.sharedEngine(with: config, delegate: delegate) ``` For detailed audio setting optimization, see [Optimize audio](audio-setup). ## Latency optimization checklist Use the following checklist to systematically optimize your conversational AI agent latency: ### Server-side optimization - **Choose low-latency LLM models**: Refer to [Conversational AI Performance Lab](https://www.agora.io/en/conversational-ai-performance-lab) to select models with excellent TTFT and throughput performance. - **Enable streaming response**: Ensure `stream: true`. - **Choose low-latency ASR and TTS vendors**: Enable low-latency or turbo modes when available. Refer to [Conversational AI Performance Lab](https://www.agora.io/en/conversational-ai-performance-lab) to select models with low latency and high throughput performance. - **Optimize geographic deployment**: Deploy ASR, LLM, and TTS in the same region. ### Client-side optimization - **Use AI conversation scenario**: Set `AUDIO_SCENARIO_AI_CLIENT` (RTC SDK 4.5.1 and later). - **Load optimal audio settings**: Call the `loadAudioSettings()` method of the client component. - **Integrate required audio plugins**: Ensure integration of AI noise reduction and AI echo cancellation plugins. - **Optimize network conditions**: Ensure stable user network connection and consider using SD-RTN™ to optimize network transmission. ### Monitoring and analysis - **Monitor latency metrics in real time**: Obtain latency data for each conversation turn through client components or NCS. - **Identify latency bottlenecks**: Analyze which component contributes the most to latency. - **Continuously optimize**: Adjust configuration based on actual data and conduct A/B testing. ## Balance latency and quality When optimizing latency, find a balance between response speed and conversation quality: | Optimization strategy | Latency impact | Quality impact | Recommended scenario | | ---------------------------- | ----------------------- | -------------------------- | ---------------------------------------------------------------- | | Use smaller LLM models | ✅ Significantly reduces | ⚠️ May reduce | Latency-sensitive scenarios with relatively simple conversations | | Limit `max_tokens` | ✅ Moderately reduces | ⚠️ May affect completeness | Scenarios requiring short responses | | Regional access restrictions | ✅ Moderately reduces | No impact | Users concentrated in a specific region | | Optimize RTC settings | ✅ Moderately reduces | No impact | All scenarios | > **Tip** > > Monitor latency metrics to identify bottlenecks, then optimize the highest-contributing component rather than pursuing minimal latency across all components. ## References Refer to the following resources for further details. - [Webhooks](../build/handle-runtime-events/webhooks) - [Optimize audio](audio-setup) - [Notification event types](../reference/event-types) - [Conversational AI Performance Lab](https://www.agora.io/en/conversational-ai-performance-lab) # Record agent conversations (/en/ai/best-practices/record-agent-conversation) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). This guide explains how to configure Agora [Cloud Recording](/en/api-reference/api-ref/cloud-recording) for Voice Agent conversations and avoid audio-scene conflicts when recording starts. ## Why this needs special handling When you run a Voice Agent and Cloud Recording in the same channel, recording startup can briefly interrupt audio. The issue is usually caused by the agent audio scene falling back to a default mode when Cloud Recording joins the channel. To keep audio stable, set the agent `audio_scenario` to `"chorus"` when you start the agent. ## Configure the agent Set the agent's RTC audio scenario to `chorus` when you configure the agent: **Python SDK** ```python from agora_agent import Agent # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor .with_audio_scenario('chorus') ) ``` **TypeScript SDK** ```typescript import { Agent } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */) .withAudioScenario('chorus'); ``` **Go SDK** ```go import "github.com/AgoraIO/agora-agents-go/v2/agentkit" // client is your configured *agentkit.AgoraClient agent := agentkit.NewAgent(client). WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */). WithAudioScenario(agentkit.AudioScenarioChorus) ``` **REST API** Add or modify the `audio_scenario` field in the agent startup parameters: ```json { "properties": { "parameters": { "audio_scenario": "chorus" } } } ``` ## Complete example The following example shows an agent launch request with the recommended recording-safe configuration: ```json { "name": "TestConvoAgent", "properties": { "channel": "{{AccessChannel}}", "token": "{{token}}", "agent_rtc_uid": "0", "remote_rtc_uids": [ "*" ], "idle_timeout": 30, "advanced_features": { "enable_bhvs": true }, "llm": { "url": "https://api.openai.com/v1/chat/completions", "api_key": "", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "greeting_message": "Hello, how can I help you?", "failure_message": "Sorry, I don't know how to answer this question.", "max_history": 10, "params": { "model": "gpt-4o-mini" } }, "tts": { "vendor": "microsoft", "params": { "key": "", "region": "eastus", "voice_name": "en-US-AndrewMultilingualNeural" } }, "turn_detection": { "silence_duration_ms": 640 }, "parameters": { "enable_dump": true, "enable_error_message": true, "audio_scenario": "chorus", "enable_delay": true } } } ``` ## Start recording After the agent is running, call the [Start Cloud Recording API](/en/api-reference/api-ref/cloud-recording/start) to begin recording. Example Cloud Recording request body: ```json { "cname": "{{AccessChannel}}", "uid": "{{RecordingUID}}", "clientRequest": { "token": "{{token}}", "recordingConfig": { "maxIdleTime": 120, "streamTypes": 0, "audioProfile": 1, "channelType": 1 }, "recordingFileConfig": { "avFileType": [ "hls", "mp4" ] }, "storageConfig": { "vendor": "{{Vendor}}", "region": "{{Region}}", "bucket": "{{Bucket}}", "accessKey": "{{AccessKey}}", "secretKey": "{{SecretKey}}" } } } ``` ## Related pages - [Start and stop an agent](../build/start-stop-agent) - [Cloud Recording API reference](/en/api-reference/api-ref/cloud-recording) # Restrict where agent can run (/en/ai/best-practices/regional-restrictions) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). To comply with laws and regulations in different countries and regions, the Conversational AI Engine supports regional access restrictions. When you enable regional access restrictions, the Conversational AI Engine only accesses Agora servers in the designated region, regardless of the user's location. For example, if you specify North America as the access region, two users who initiate calls from North America and Singapore have different experiences: | Specified access region | User location | Actual access region | User experience | | :---------------------- | :------------ | :------------------- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | North America | North America | North America | Normal quality. | | North America | Singapore | North America | Quality may be significantly impacted. Cross-regional public internet connections between the designated region and the user's location can result in poor network quality. If all servers in the specified region are unavailable, the service returns an error. | ## Understand the tech When regional access restrictions are disabled, the Conversational AI Engine automatically selects the nearest server to deploy the agent based on the IP address of the LLM URL and supports failover: 1. **Intelligent deployment**: The system automatically deploys the Conversational AI Engine service in the region that corresponds to the IP address of the configured LLM URL. 2. **Nearest available region**: If no server is available in the corresponding region, the system automatically selects the nearest available region. 3. **Failover**: When a service becomes unavailable in a region, the system automatically switches to another available region. > **Caution** > > When you enable regional access restrictions, the system strictly limits access to the specified region and does not perform cross-regional failover. ## Implementation ### Configure regional access To configure region access restrictions, set `properties.geofence` when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). **properties.geofence** **`area` (string) required** Possible values: `GLOBAL, NORTH_AMERICA, EUROPE, ASIA, INDIA, JAPAN` The allowed region for server access. **`exclude_area` (string) optional** Possible values: `NORTH_AMERICA, EUROPE, ASIA, INDIA, JAPAN` The excluded region. Only available when `area` is set to `GLOBAL`. ### Configuration examples Refer to the following examples to understand `geofence` configuration. #### Restrict access to North America only **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit import GeofenceConfig # client is your configured Agora client agent = ( Agent(client) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor .with_geofence(GeofenceConfig( area='NORTH_AMERICA', )) ) ``` **TypeScript SDK** ```typescript import { Agent } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */) .withGeofence({ area: 'NORTH_AMERICA', }); ``` **Go SDK** ```go import "github.com/AgoraIO/agora-agents-go/v2/agentkit" // client is your configured *agentkit.AgoraClient agent := agentkit.NewAgent(client). WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */). WithGeofence(&agentkit.GeofenceConfig{ Area: agentkit.GeofenceAreaNorthAmerica, }) ``` **REST API** Use the following request body when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join): ```json { "name": "customer_service", "properties": { "channel": "test_channel", "token": "your_rtc_token", "agent_rtc_uid": "123", "remote_rtc_uids": ["456"], "geofence": { "area": "NORTH_AMERICA" }, "llm": { // ... LLM configuration }, "tts": { // ... TTS configuration } } } ``` #### Allow global access but exclude India **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit import GeofenceConfig # client is your configured Agora client agent = ( Agent(client) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor .with_geofence(GeofenceConfig( area='GLOBAL', exclude_area='INDIA', )) ) ``` **TypeScript SDK** ```typescript import { Agent } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */) .withGeofence({ area: 'GLOBAL', exclude_area: 'INDIA', }); ``` **Go SDK** ```go import "github.com/AgoraIO/agora-agents-go/v2/agentkit" // client is your configured *agentkit.AgoraClient agent := agentkit.NewAgent(client). WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */). WithGeofence(&agentkit.GeofenceConfig{ Area: agentkit.GeofenceAreaGlobal, ExcludeArea: agentkit.GeofenceExcludeAreaIndia.Ptr(), }) ``` **REST API** Use the following request body when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join): ```json { "name": "customer_service", "properties": { "channel": "test_channel", "token": "your_rtc_token", "agent_rtc_uid": "123", "remote_rtc_uids": ["456"], "geofence": { "area": "GLOBAL", "exclude_area": "INDIA" }, "llm": { // ... LLM configuration }, "tts": { // ... TTS configuration } } } ``` ### Configure RTC regional access \[#configure-rtc-regional-access] The Conversational AI Engine and Agora RTC services are independent, and their regional access restriction configurations are separate. To implement complete end-to-end regional access restrictions and ensure that the entire call chain with the agent is confined to a specified region, you must also configure RTC regional access restrictions. For more information, see [Restrict media zones](../../realtime-media/rtc/build/manage-connection-and-quality/geofencing). ## Data residency In addition to configuring regional access restrictions for the Conversational AI Engine, some LLM, TTS, and ASR vendors offer data residency services in different regions. You can ensure that data is not transferred across regions by configuring the URLs used by the LLM, TTS, and ASR modules. For example, ElevenLabs supports selecting data processing regions through different URL endpoints. For more information, see the [ElevenLabs documentation](https://elevenlabs.io/docs/overview/administration/data-residency). The following example shows how to configure the ElevenLabs TTS service using a URL endpoint for the European region: ```json { "properties": { "tts": { "vendor": { "name": "elevenlabs" }, "url": "wss://api.eu.elevenlabs.io/v1/text-to-speech/{voice_id}/stream-input" } } } ``` ## Best practices To ensure that data remains entirely within the designated region, follow these recommendations: 1. **Configure regional restrictions for the Conversational AI Engine**: Use the `geofence` object to restrict server access regions. 2. **Configure RTC regional restrictions**: Configure the corresponding regional access restrictions in the RTC SDK. 3. **Select regional AI services**: When configuring LLM, TTS, and ASR services, select a provider that supports regional data residency and use the corresponding regional URL endpoint. 4. **Verify the configuration**: Before deploying to production, thoroughly test that regional access restrictions work correctly and that data is not transferred across regions. ## Considerations Keep the following in mind when implementing regional access restrictions: - **Performance impact**: Regional access restrictions may affect user experience. If a user's location is far from the designated region, network latency may increase. - **Service availability**: When regional access restrictions are enabled and the server in the specified region is unavailable or lacks sufficient resources, the service returns an error and does not automatically switch to another region. - **Configuration consistency**: Ensure that the regional configurations of the Conversational AI Engine, RTC SDK, and LLM, TTS, and ASR services are consistent to prevent data transfer across regions. - **Compliance requirements**: Before configuring regional access restrictions, understand the legal and regulatory requirements of the target region to ensure that the configuration complies with local data protection and privacy regulations. # Build a backend and client from scratch (/en/ai/build/build-server-client) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). This guide walks through building the full Conversational AI stack from scratch: a server that issues tokens and manages agent sessions, and a browser client that captures microphone audio and streams live transcripts. You end up with the same structure as the official [Next.js](https://github.com/AgoraIO-Conversational-AI/agent-quickstart-nextjs) and [Python](https://github.com/AgoraIO-Conversational-AI/agent-quickstart-python) starter repos, but with every step explained. If you want to hear an agent speak in under five minutes, follow the [Voice AI quickstart](../get-started/quickstart) guide. > **Info** > > This project uses Agora-managed presets, so no vendor API keys are required to complete this tutorial. If you prefer to switch to your own vendor accounts, see the documentation for your chosen [ASR](../models/asr/deepgram), [LLM](../models/llm/openai), and [TTS](../models/tts/minimax) providers. ## What you will build A complete client-server app: - **Backend**: Three HTTP endpoints: - `POST /api/token`: Issues RTC and RTM tokens for a given channel and UID - `POST /api/invite-agent`: Starts the agent using the Agora Agent SDK - `POST /api/stop-conversation`: Stops the agent by ID - **Frontend**: A Next.js page that: - Requests microphone permission - Joins the Agora channel using the RTC SDK - Fetches a token from your backend - Calls `invite-agent` to bring the agent into the channel - Renders live transcripts from RTM - Calls `stop-conversation` on page unload The architecture looks like this: ![](https://assets-docs.agora.io/images/conversational-ai/server-sdk-flow.png) The backend never touches audio, and the browser never embeds your App Certificate. This clean separation is the reason you need a backend. ## Prerequisites - An active [Agora account](https://console.agora.io). - `git` and a terminal. - One of the following language runtimes: - **Node.js 20 LTS or later** with `pnpm` for TypeScript - **Python 3.11 or later** with `uv` or `pip` - **Go 1.22 or later** - A modern browser with microphone access ## Set up your environment This section walks you through installing the Agora CLI and scaffolding your project. ### Install the Agora CLI The Agora CLI is the recommended way to bootstrap a new Agora project. Use it to create projects, enable features, write credentials to `.env` files, and run diagnostics. To install the Agora CLI, log in, and create a project with Conversational AI enabled: ```bash npm install -g agoraio-cli agora login agora project create conv-ai-tutorial agora project use conv-ai-tutorial ``` Confirm that the CLI can read your credentials: ```bash agora project env --shell ``` ```bash AGORA_APP_ID=your_app_id_here AGORA_APP_CERTIFICATE=your_certificate_here ``` Keep this terminal open. You will reuse these credentials in both the backend and frontend steps. ### Scaffold the repo Select the tab for your preferred language. **TypeScript** For TypeScript, the backend and frontend live in the same Next.js app. 1. Scaffold a Next.js app with TypeScript, the App Router, Tailwind CSS, and ESLint, then install the required Agora packages: ```bash pnpm dlx create-next-app@latest conv-ai-tutorial --typescript --app --tailwind --eslint --src-dir=false --import-alias='@/*' cd conv-ai-tutorial pnpm add agora-agents agora-rtc-sdk-ng agora-rtm-sdk agora-token ``` - `agora-agents`: Starts and stops agent sessions from the backend - `agora-rtc-sdk-ng`: Handles mic capture and RTC channel joining in the browser - `agora-rtm-sdk`: Receives live transcript messages from the agent - `agora-token`: Generates RTC and RTM tokens 2. Write your Agora credentials to `.env.local`: ```bash eval "$(agora project env --shell)" cat > .env.local < server-python/.env < web-client/.env.local < **Info: Coming soon** > > The Go backend walkthrough is not yet available. It will mirror the Python path: a standalone backend on port 8000, a Next.js web client on port 3000, and the same three HTTP endpoints. In the meantime, use the [Voice AI quickstart](../get-started/quickstart) for a Go agent walkthrough that runs as a single process without a frontend. ## Build the backend The backend exposes three endpoints, one for each operation the frontend needs. **TypeScript** ### Generate tokens Endpoint: `POST /api/token` This endpoint builds an RTC token and an RTM token for the browser client. It is the only place the App Certificate is used. ```ts // app/api/token/route.ts import { NextRequest, NextResponse } from 'next/server'; import { RtcTokenBuilder, RtcRole, RtmTokenBuilder } from 'agora-token'; const APP_ID = process.env.NEXT_PUBLIC_AGORA_APP_ID!; const APP_CERTIFICATE = process.env.NEXT_AGORA_APP_CERTIFICATE!; const TOKEN_TTL_SECONDS = 60 * 60; // 1 hour export async function POST(req: NextRequest) { const { channel, uid } = await req.json(); if (!channel || typeof uid !== 'number') { return NextResponse.json({ error: 'channel and numeric uid required' }, { status: 400 }); } const expireAt = Math.floor(Date.now() / 1000) + TOKEN_TTL_SECONDS; const rtcToken = RtcTokenBuilder.buildTokenWithUid( APP_ID, APP_CERTIFICATE, channel, uid, RtcRole.PUBLISHER, expireAt, expireAt, ); const rtmToken = RtmTokenBuilder.buildToken( APP_ID, APP_CERTIFICATE, String(uid), expireAt, ); return NextResponse.json({ rtcToken, rtmToken, expireAt }); } ``` ### Start an agent session Endpoint: `POST /api/invite-agent` This endpoint uses the Agora Agent SDK to configure an agent and start a session. The STT, LLM, and TTS configurations use Agora-managed presets and therefore do not require an `apiKey`. ```ts // app/api/invite-agent/route.ts import { NextRequest, NextResponse } from 'next/server'; import { AgoraClient, Agent, Area, DeepgramSTT, ExpiresIn, MiniMaxTTS, OpenAI, } from 'agora-agents'; const client = new AgoraClient({ area: Area.US, appId: process.env.NEXT_PUBLIC_AGORA_APP_ID!, appCertificate: process.env.NEXT_AGORA_APP_CERTIFICATE!, }); const AGENT_UID = 123456; export async function POST(req: NextRequest) { const { channel } = await req.json(); if (!channel) { return NextResponse.json({ error: 'channel required' }, { status: 400 }); } const agent = new Agent({ client, instructions: 'You are a friendly support agent for Acme Corp. Keep answers under 30 seconds.', greeting: 'Hi there! How can I help you today?', failureMessage: 'Sorry, I had trouble hearing that. Could you repeat?', maxHistory: 50, advancedFeatures: { enable_rtm: true, enable_tools: false }, parameters: { data_channel: 'rtm', enable_error_message: true }, }) .withStt(new DeepgramSTT({ model: 'nova-3', language: 'en' })) .withLlm(new OpenAI({ model: 'gpt-4o-mini', maxHistory: 15 })) .withTts( new MiniMaxTTS({ model: 'speech_2_6_turbo', voiceId: 'English_captivating_female1', }), ); const session = agent.createSession({ channel, agentUid: AGENT_UID, remoteUids: ['*'], name: 'support-agent', idleTimeout: 30, expiresIn: ExpiresIn.hours(1), }); try { const { agentId } = await session.start(); return NextResponse.json({ agentId, agentUid: AGENT_UID }); } catch (err: unknown) { const message = err instanceof Error ? err.message : String(err); return NextResponse.json({ error: `start failed: ${message}` }, { status: 502 }); } } ``` ### Stop an agent session Endpoint: `POST /api/stop-conversation` This endpoint stops a running agent session by ID. ```ts // app/api/stop-conversation/route.ts import { NextRequest, NextResponse } from 'next/server'; import { AgoraClient, Area } from 'agora-agents'; const client = new AgoraClient({ area: Area.US, appId: process.env.NEXT_PUBLIC_AGORA_APP_ID!, appCertificate: process.env.NEXT_AGORA_APP_CERTIFICATE!, }); export async function POST(req: NextRequest) { const { agentId } = await req.json(); if (!agentId) { return NextResponse.json({ error: 'agentId required' }, { status: 400 }); } try { await client.agents.leave(agentId); return NextResponse.json({ stopped: true }); } catch (err: unknown) { const message = err instanceof Error ? err.message : String(err); return NextResponse.json({ error: `stop failed: ${message}` }, { status: 502 }); } } ``` **Python** All backend code lives in `server-python/main.py`. ### Generate tokens Endpoint: `POST /api/token` This endpoint generates an RTC token and an RTM token for the browser client. It is the only place the App Certificate is used. ```python # server-python/main.py import os import time from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from dotenv import load_dotenv from agora_token_builder import RtcTokenBuilder, RtmTokenBuilder load_dotenv() APP_ID = os.environ["APP_ID"] APP_CERTIFICATE = os.environ["APP_CERTIFICATE"] TOKEN_TTL_SECONDS = 60 * 60 app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000"], allow_methods=["POST"], allow_headers=["*"], ) class TokenRequest(BaseModel): channel: str uid: int @app.post("/api/token") def token(body: TokenRequest): expire_at = int(time.time()) + TOKEN_TTL_SECONDS rtc_token = RtcTokenBuilder.buildTokenWithUid( APP_ID, APP_CERTIFICATE, body.channel, body.uid, role=1, privilegeExpiredTs=expire_at, ) rtm_token = RtmTokenBuilder.buildToken( APP_ID, APP_CERTIFICATE, str(body.uid), role=1, privilegeExpiredTs=expire_at, ) return {"rtcToken": rtc_token, "rtmToken": rtm_token, "expireAt": expire_at} ``` ### Start an agent session Endpoint: `POST /api/invite-agent` This endpoint uses the Agora Agent SDK to configure an agent and start a session in the caller's channel. The STT, LLM, and TTS configurations use Agora-managed presets and therefore do not require an `api_key`. Add the following to `main.py`: ```python from agora_agent import ( Agora, Agent, Area, DeepgramSTT, MiniMaxTTS, OpenAI, expires_in_hours, ) agora_client = Agora( area=Area.US, app_id=APP_ID, app_certificate=APP_CERTIFICATE, ) AGENT_UID = 123456 class InviteRequest(BaseModel): channel: str @app.post("/api/invite-agent") def invite_agent(body: InviteRequest): agent = ( Agent( agora_client, instructions="You are a friendly support agent for Acme Corp. Keep answers under 30 seconds.", greeting="Hi there! How can I help you today?", failure_message="Sorry, I had trouble hearing that. Could you repeat?", max_history=50, advanced_features={"enable_rtm": True, "enable_tools": False}, parameters={"data_channel": "rtm", "enable_error_message": True}, ) .with_stt(DeepgramSTT(model="nova-3", language="en")) .with_llm(OpenAI(model="gpt-4o-mini", max_history=15)) .with_tts( MiniMaxTTS( model="speech_2_6_turbo", voice_id="English_captivating_female1", ) ) ) session = agent.create_session( channel=body.channel, agent_uid=AGENT_UID, remote_uids=["*"], name="support-agent", idle_timeout=30, expires_in=expires_in_hours(1), ) try: result = session.start() return {"agentId": result.agent_id, "agentUid": AGENT_UID} except Exception as exc: raise HTTPException(status_code=502, detail=f"start failed: {exc}") ``` ### Stop an agent session Endpoint: `POST /api/stop-conversation` This endpoint stops a running agent session by ID. Add the following to `main.py`: ```python class StopRequest(BaseModel): agentId: str @app.post("/api/stop-conversation") def stop_conversation(body: StopRequest): try: agora_client.agents.leave(body.agentId) return {"stopped": True} except Exception as exc: raise HTTPException(status_code=502, detail=f"stop failed: {exc}") ``` To start the backend: ```bash cd server-python uvicorn main:app --reload --port 8000 ``` Swagger docs are available at `http://localhost:8000/docs`. **Go** > **Info: Coming soon** > > The Go backend walkthrough is not yet available. It will mirror the Python path: a standalone backend on port 8000, a Next.js web client on port 3000, and the same three HTTP endpoints. In the meantime, see the [Voice AI quickstart](../get-started/quickstart) guide to get started with Go. ## Build the frontend The frontend is the same Next.js app for all three backends. The only difference is whether it calls its own API routes for TypeScript or a separate backend on port `8000` for Python and Go. ### A basic API client Create `lib/api.ts` to give the frontend a single place to manage the backend URL and endpoint calls. ```ts // lib/api.ts const BACKEND = process.env.NEXT_PUBLIC_BACKEND_URL ?? ''; async function post(path: string, body: object): Promise { const res = await fetch(`${BACKEND}${path}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), }); if (!res.ok) { throw new Error(`${path} failed: ${res.status} ${await res.text()}`); } return res.json() as Promise; } export type TokenResponse = { rtcToken: string; rtmToken: string; expireAt: number; }; export type InviteResponse = { agentId: string; agentUid: number; }; export const api = { token: (channel: string, uid: number) => post('/api/token', { channel, uid }), invite: (channel: string) => post('/api/invite-agent', { channel }), stop: (agentId: string) => post<{ stopped: boolean }>('/api/stop-conversation', { agentId }), }; ``` For TypeScript, `NEXT_PUBLIC_BACKEND_URL` is not set in `.env.local`, so calls go to same-origin routes like `/api/token`. For Python and Go, it is set to `http://localhost:8000` in the scaffold step, so calls go to the external backend. ### Create the RTC and RTM hook Create `hooks/useConvoAgent.ts`. This hook joins the RTC channel for audio, connects to RTM for transcripts, and exposes `start()` and `stop()` functions to the UI. ```ts // hooks/useConvoAgent.ts 'use client'; import { useCallback, useRef, useState } from 'react'; import AgoraRTC, { IAgoraRTCClient, IMicrophoneAudioTrack, } from 'agora-rtc-sdk-ng'; import { RTMClient, RTMEvents } from 'agora-rtm-sdk'; import { api } from '@/lib/api'; type TranscriptLine = { role: 'user' | 'agent'; text: string; final: boolean }; export function useConvoAgent(channel: string, uid: number) { const rtcRef = useRef(null); const micRef = useRef(null); const rtmRef = useRef(null); const agentIdRef = useRef(null); const [connected, setConnected] = useState(false); const [transcripts, setTranscripts] = useState([]); const [error, setError] = useState(null); const start = useCallback(async () => { try { const { rtcToken, rtmToken } = await api.token(channel, uid); const appId = process.env.NEXT_PUBLIC_AGORA_APP_ID!; // 1. Join RTC and publish the mic const rtc = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' }); await rtc.join(appId, channel, rtcToken, uid); const mic = await AgoraRTC.createMicrophoneAudioTrack(); await rtc.publish(mic); rtc.on('user-published', async (user, mediaType) => { if (mediaType === 'audio') { await rtc.subscribe(user, mediaType); user.audioTrack?.play(); } }); rtcRef.current = rtc; micRef.current = mic; // 2. Join RTM for transcripts const rtm = new RTMClient({ appId, userId: String(uid) }); await rtm.login({ token: rtmToken }); await rtm.subscribe(channel); rtm.addEventListener('message', (e: RTMEvents.MessageEvent) => { try { const payload = JSON.parse(e.message as string); if (payload.type === 'transcript') { setTranscripts((prev) => [ ...prev, { role: payload.role, text: payload.text, final: payload.final }, ]); } } catch { // Ignore non-JSON RTM messages for this tutorial. } }); rtmRef.current = rtm; // 3. Ask the backend to bring the agent into the channel const { agentId } = await api.invite(channel); agentIdRef.current = agentId; setConnected(true); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } }, [channel, uid]); const stop = useCallback(async () => { try { if (agentIdRef.current) { await api.stop(agentIdRef.current); } } finally { micRef.current?.stop(); micRef.current?.close(); await rtcRef.current?.leave(); await rtmRef.current?.logout(); agentIdRef.current = null; rtcRef.current = null; micRef.current = null; rtmRef.current = null; setConnected(false); } }, []); return { connected, transcripts, error, start, stop }; } ``` The hook follows the same structure as `components/ConversationComponent.tsx` in the [Next.js starter repo](https://github.com/AgoraIO-Conversational-AI/agent-quickstart-nextjs). ### Build the client UI Create `app/page.tsx` as the main UI. It renders a start and stop button plus a live transcript list. ```tsx // app/page.tsx 'use client'; import { useConvoAgent } from '@/hooks/useConvoAgent'; const CHANNEL = 'support-room-123'; const USER_UID = 111222; export default function Home() { const { connected, transcripts, error, start, stop } = useConvoAgent( CHANNEL, USER_UID, ); return (

Conv AI Tutorial

{!connected ? ( ) : ( )}
{error &&

Error: {error}

}
    {transcripts.map((line, i) => (
  1. {line.role === 'agent' ? 'Agent' : 'You'}: {' '} {line.text} {!line.final && ...}
  2. ))}
); } ``` The page has no state library or design system. It provides just enough UI to verify that the backend is working. ### Handle page unload (optional) Add this effect inside `app/page.tsx` to stop the agent cleanly when the user closes the tab, rather than waiting for the 30-second idle timeout. ```ts // Inside the page, after useConvoAgent(...) useEffect(() => { const onUnload = () => { if (connected) stop(); }; window.addEventListener('beforeunload', onUnload); return () => window.removeEventListener('beforeunload', onUnload); }, [connected, stop]); ``` ## Test and validate Start the app and verify that the agent joins, responds, and stops cleanly. ### Run the app **TypeScript** ```bash pnpm dev ``` Open `http://localhost:3000`, click **Start conversation**, allow microphone access, and speak. **Python** Start the backend and frontend in two separate terminals: ```bash # Terminal 1: Backend cd server-python source .venv/bin/activate uvicorn main:app --reload --port 8000 ``` ```bash # Terminal 2: Frontend cd web-client pnpm dev ``` Open `http://localhost:3000`. **Go** > **Info: Coming soon** > > The Go walkthrough is not yet available. See the [Voice AI quickstart](../get-started/quickstart) guide in the meantime. ### Verify the integration A healthy run passes all three checks: | Check | How to verify | Time budget | | ------------------------ | ------------------------------------------------------------------------------------------------------------------ | ------------------------ | | Agent joined the channel | The `invite-agent` response resolves with an `agentId`, and the agent emits a greeting in RTC within two seconds. | < 2 s | | Transcripts stream | `transcripts` state updates as you speak, and partial lines are marked `final: false`. | < 500 ms partial latency | | Stop is clean | After **Stop**, the backend returns `{ stopped: true }`, and the Convo AI engine logs `STATE=STOPPED, reason=API`. | Immediate | If you run into problems, first run the CLI diagnostic: ```bash agora project doctor ``` This checks for credential errors, feature-enablement issues, and network reachability problems. ## Troubleshooting | Symptom | Likely cause | Fix | | ---------------------------------------------- | ------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | | `Error: /api/token failed: 500` in the browser | Backend cannot read the `APP_CERTIFICATE` environment variable. | Confirm `.env.local` for TypeScript or `server-python/.env` for Python contains the variable and that the server loaded the file on startup. | | `invalid token` from the RTC join | Clock skew between token generation and channel join. | RTC tokens are time-sensitive. Regenerate a token on each `start()` call to avoid expiry issues. | | Agent never speaks but `agentId` is returned | Conversational AI feature is not enabled on the Agora project. | Run `agora project feature list`. If `convoai` is missing, rerun `agora project create --feature convoai` or enable it in the Agora Console. | | No transcripts in RTM | `enable_rtm` is not set, or `data_channel` is set to `stream` instead of `rtm`. | Confirm `advancedFeatures.enable_rtm: true` and `parameters.data_channel: 'rtm'` in the agent config. | | CORS error in the browser for Python | FastAPI CORS middleware does not include your frontend origin. | Add `http://localhost:3000` to `allow_origins` in `main.py`. | | Agent greets itself in a loop | No echo cancellation on the device. | Use headphones, or set `parameters.enable_aec: true`. | | `unauthorized` error on `agora login` in CI | The SSO browser flow cannot open on a headless machine. | Use `agora login --device` for the device-code flow. | | Chrome blocks microphone access | `getUserMedia` is not available on non-localhost HTTP origins. | Test on `http://localhost:3000` exactly, not `http://127.0.0.1` or a LAN IP. | ## Next steps Now that you have a working agent, explore the following topics: - [Integrate an MLLM](../models/mllm/openai): Replace the cascading STT -> LLM -> TTS pipeline with a single real-time model. - [Transmit custom information](shape-the-conversation/custom-information): Guide the agent with user-specific context to personalize responses. - [Integrate short-term memory](shape-the-conversation/short-term-memory): Help the agent maintain context across a conversation. - [Webhooks](handle-runtime-events/webhooks): Receive agent event notifications in real time. - [Use managed mode](managed-mode): Use Agora-managed provider credentials instead of configuring API keys for each model. - [Optimize conversation latency](../best-practices/optimize-latency): Tune LLM, ASR, and TTS components for lower end-to-end latency. # Direct LLM audio output (/en/ai/build/custom-model-integration/audio-output) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). In addition to text output, the Agora Conversational AI Engine can deliver responses in audio format, allowing for more natural and immersive user interactions. This page describes how to configure the agent for audio output and modify the interface to support features such as context management, subtitle alignment, and agent broadcasting. ## Prerequisites - A reference implementation of a conversational AI agent that includes the [basic logic](../../get-started/quickstart) for interacting with an AI agent. - If you plan to implement subtitles for audio output, read the [Display live subtitles](../transcripts) documentation and complete the required configuration. ## Implement audio output Take the following steps to set up and configure the audio output mode. ### Select the output mode To configure the output mode, set the `llm.output_modalities` field when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), as follows: - `["audio"]`: Sets the output to audio-only mode. In this configuration, you don't need to set up a text-to-speech (TTS) module. The agent directly plays the audio returned by the custom LLM. This page focuses on how to use this audio-only mode. - `["text", "audio"]`: Sets the output to both text and audio modes. In this configuration, two types of audio are returned: one generated by the TTS module and one provided by the custom LLM. ### Modify the LLM interface To use the Agora Conversational AI Engine with the [OpenAI Chat Completions API](https://platform.openai.com/docs/api-reference/chat), ensure that your LLM service is compatible with the expected request and response formats. Agora uses an extended API that supports multiple response types, including text, audio, subtitles, and verbatim subtitle timestamps. It also introduces an additional `words` field for real-time subtitle alignment. To adapt your LLM service, refer to [Custom LLM](custom-llm) for guidance on transforming your API to meet these requirements. ### Request format Compared with `text` requests, `audio` requests include two additional optional fields: - `modalities`: Specifies the output mode. - `audio`: Specifies the output timbre (`voice`) and `format`. Include these fields in the `llm.params` object of the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) request. The following example shows the format of an audio request: ```json { "model": "gpt-4o-audio-preview", "modalities": ["audio"], "audio": { "voice": "alloy", "format": "wav" }, "messages": [ { "role": "user", "content": "Is a golden retriever a good family dog?" } ] } ``` ### Response format The `audio` response includes three types of content. You can send each type to the agent independently for processing: | Audio type | Description | Source | Agent processing | | :---------------------------------- | :--------------------------------------------------- | :-------------------------------------------------------------------------------------- | :--------------------------------------------- | | Audio data; `data` | Base64-encoded PCM byte stream array | LLM generation with audio processing capabilities, or a custom audio processing service | Plays the audio directly | | Transcription content; `transcript` | The complete text content corresponding to the audio | LLM generation | Stores the text in short-term memory (context) | | Verbatim subtitles; `words` | Subtitle content with word-by-word timestamps | Supports LLM generation with verbatim output | Processes into verbatim real-time subtitles | The specific data structure of a streaming response is as follows: ```json {"choices":[{"index":0,"delta":{"role":"assistant","audio":{"data": ""}},"logprobs":null,"finish_reason":null}]} // Audio data {"choices":[{"index":0,"delta":{"audio":{"data": "base64 encoded pcm data"}},"logprobs":null,"finish_reason":null}]} // Transcribe subtitles {"choices":[{"index":0,"delta":{"audio":{"transcript": "Hello world!", "words":[{"text":"Hello", "start_ts":100, "end_ts":140, "duration":40}]}},"logprobs":null,"finish_reason":null}]} // Word-by-word subtitles {"choices":[{"index":0,"delta":{"audio":{"words":[{"text":"world", "start_ts":150, "end_ts":190, "duration":40}, {"text":"!", "start_ts":190, "end_ts":200, "duration":10}]}},"logprobs":null,"finish_reason":null}]} .... {"choices":[{"index":0,"delta":{},"logprobs":null,"finish_reason":"stop"}]} ``` The conversational AI agent summarizes different types of responses in the following format: ```json { "choices": [ { "delta": { "audio": { "data": "base64 encoded pcm data", "transcript": "Hello world!", "words": [ { "text": "Hello", "start_ts": 100, "end_ts": 140, "duration": 40 }, { "text": "world", "start_ts": 150, "end_ts": 190, "duration": 40 }, { "text": "!", "start_ts": 190, "end_ts": 200, "duration": 10 } ] } } } ] } ``` The `audio` object contains the following fields: **audio** **`data` (string)** Audio data as a Base64-encoded PCM byte stream. **`transcript` (string)** Subtitle content corresponding to the audio. **`words` (array)** An array of word-level subtitle objects. The LLM must support word-level output. **`text` (string)** The spoken word. **`start_ts` (number)** Start time in milliseconds relative to the beginning of the PCM audio data. **`end_ts` (number)** End time in milliseconds relative to the beginning of the PCM audio data. **`duration` (number)** Duration in milliseconds that the word is played. Depending on your application use-case, configure your custom large model to selectively process and return the relevant fields: - **Audio-only output**: Only the `data` field is required. - **Subtitle-only output**: Only the `transcript` field is required. The agent displays the subtitle but does not play it using the TTS module. - **Audio with verbatim subtitles**: The `data` and words fields are required. Each item in the words array must include the `text`, `start_ts`, `end_ts`, and `duration` fields. ## Advanced features Conversational AI Engine supports the following advanced features: ### Context management When the response contains the `audio.transcript` field, the agent automatically stores the subtitle content in its context manager for use in subsequent interactions. If the `audio.transcript` field is not included, the content is not stored. To ensure the agent retains the audio modality output in short-term memory, include the `audio.transcript` field in the response. ### Subtitle alignment When you [Display live subtitles](../transcripts), the Conversational AI Engine can use the `audio.words` field to segment the audio. The engine aligns subtitles based on the `start_ts`, `end_ts`, and `duration` fields within `audio.words`. To enable the agent to segment the audio based on subtitle content during playback, make sure that the LLM sends both the `audio.data` and `audio.words` fields in the response. ### Agent message broadcasts If the agent isn't configured with a TTS module but has `output_modalities` set to `["audio"]`, you can enable it to broadcast custom messages by adapting your LLM as follows: In the `messages` list received by the agent and passed to the LLM, the model should handle the last message based on its `role`: - `assistant`: The model treats the message as a directive that doesn't require reasoning. It converts the message to audio and returns it to the agent. The agent plays the audio directly. - `user`: The model treats the message as a prompt that requires reasoning. The agent decides whether to broadcast the message based on whether the model’s response includes audio. This corresponds to a typical user–agent conversation. > **Info** > > The following agent broadcasts also adopt this protocol: > > - When the agent announces a greeting `greeting_message` or a processing failure prompt `failure_message`. > - When you [Broadcast a custom message using the TTS module](/en/api-reference/api-ref/conversational-ai/speak). ## Reference This section contains content that completes the information on this page, or points you to documentation that explains other aspects to this product. ### Sample project Agora provides an open-source [Conversational AI sample server project](https://github.com/AgoraIO-Community/Conversational-AI-Server-Sample) for your reference. Download the project or view the source code for a complete example. # Connect your own LLM service (/en/ai/build/custom-model-integration/custom-llm) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). In Conversational AI Engine interaction scenarios, your use case may require a custom large language model (Custom LLM). This document explains how to integrate a custom LLM into Agora's Conversational AI Engine. ## Understand the tech Agora's Conversational AI Engine interacts with LLM services using the OpenAI API protocol. To integrate a custom LLM, you need to provide an HTTP service compatible with the OpenAI API, capable of handling requests and responses in the OpenAI API format. This approach enables you to implement additional custom functionalities, including but not limited to: - **Retrieval-Augmented Generation (RAG)**: Allows the model to retrieve information from a specific knowledge base. - **Multimodal Capabilities**: Enables the model to generate output in both text and audio formats. - **Tool Invocation**: Allows the model to call external tools. - **Function Calling**: Enables the model to return structured data in the form of function calls. ## Prerequisites - Implemented the basic logic for interacting with a conversational AI agent by following the [quickstart](../../get-started/quickstart). - Set up access to a custom LLM service. - Prepared a vector database or retrieval system if using Retrieval-Augmented Generation (RAG). ## Implementation Take the following steps to integrate your custom LLM into Agora's Conversational AI Engine. ### Create an OpenAI API-compatible service To integrate successfully with Agora's Conversational AI Engine, your custom LLM service must provide an interface compatible with the OpenAI Chat Completions API. The key requirements include: - **Endpoint**: A request-handling endpoint, such as `https://your-custom-llm-service/chat/completions`. - **Request format**: Must accept request parameters adhering to the OpenAI API protocol. - **Response format**: Should return OpenAI API-compatible responses and support the Server-Sent Events (SSE) standard for streaming. The following example demonstrates how to implement an OpenAI API-compliant interface: **Python** ```python name=1 class TextContent(BaseModel): type: str = "text" text: str class ImageContent(BaseModel): type: str = "image" image_url: HttpUrl class AudioContent(BaseModel): type: str = "input_audio" input_audio: Dict[str, str] class ToolFunction(BaseModel): name: str description: Optional[str] parameters: Optional[Dict] strict: bool = False class Tool(BaseModel): type: str = "function" function: ToolFunction class ToolChoice(BaseModel): type: str = "function" function: Optional[Dict] class ResponseFormat(BaseModel): type: str = "json_schema" json_schema: Optional[Dict[str, str]] class SystemMessage(BaseModel): role: str = "system" content: Union[str, List[str]] class UserMessage(BaseModel): role: str = "user" content: Union[str, List[Union[TextContent, ImageContent, AudioContent]]] class AssistantMessage(BaseModel): role: str = "assistant" content: Union[str, List[TextContent]] = None audio: Optional[Dict[str, str]] = None tool_calls: Optional[List[Dict]] = None class ToolMessage(BaseModel): role: str = "tool" content: Union[str, List[str]] tool_call_id: str # Define the complete request format class ChatCompletionRequest(BaseModel): context: Optional[Dict] = None # Context information model: Optional[str] = None # Model name being used messages: List[Union[SystemMessage, UserMessage, AssistantMessage, ToolMessage]] # List of messages response_format: Optional[ResponseFormat] = None # Response format modalities: List[str] = ["text"] # Default modality is text audio: Optional[Dict[str, str]] = None # Assistant's audio response tools: Optional[List[Tool]] = None # List of tools tool_choice: Optional[Union[str, ToolChoice]] = "auto" # Tool selection parallel_tool_calls: bool = True # Whether to call tools in parallel stream: bool = True # Default to streaming response stream_options: Optional[Dict] = None # Streaming options @app.post("/chat/completions") async def create_chat_completion(request: ChatCompletionRequest): try: logger.info(f"Received request: {request.model_dump_json()}") client = AsyncOpenAI(api_key=os.getenv("YOUR_LLM_API_KEY")) response = await client.chat.completions.create( model=request.model, messages=request.messages, # Directly use request messages tool_choice=( request.tool_choice if request.tools and request.tool_choice else None ), tools=request.tools if request.tools else None, modalities=request.modalities, audio=request.audio, response_format=request.response_format, stream=request.stream, stream_options=request.stream_options, ) if not request.stream: raise HTTPException( status_code=400, detail="chat completions require streaming" ) async def generate(): try: async for chunk in response: logger.debug(f"Received chunk: {chunk}") yield f"data: {json.dumps(chunk.to_dict())}\n\n" yield "data: [DONE]\n\n" except asyncio.CancelledError: logger.info("Request was cancelled") raise return StreamingResponse(generate(), media_type="text/event-stream") except asyncio.CancelledError: logger.info("Request was cancelled") raise HTTPException(status_code=499, detail="Request was cancelled") except Exception as e: traceback_str = "".join(traceback.format_tb(e.__traceback__)) error_message = f"{str(e)}\ {traceback_str}" logger.error(error_message) raise HTTPException(status_code=500, detail=error_message) ``` **Go** ```go name=2 type ( AudioContent struct { InputAudio map[string]string `json:"input_audio"` Type string `json:"type"` } // Complete request format ChatCompletionRequest struct { // Assistant's audio reply Audio map[string]string `json:"audio,omitempty"` // Context information Context map[string]any `json:"context,omitempty"` // Message list Messages []Message `json:"messages"` // Default uses text modality Modalities []string `json:"modalities"` // Model name to use Model string `json:"model,omitempty"` // Whether to call tools in parallel ParallelToolCalls bool `json:"parallel_tool_calls"` // Response format ResponseFormat *ResponseFormat `json:"response_format,omitempty"` // Whether to use streaming response Stream bool `json:"stream"` // Streaming options StreamOptions map[string]any `json:"stream_options,omitempty"` // Tool selection strategy, default value is "auto" ToolChoice any `json:"tool_choice,omitempty"` // Tool list Tools []Tool `json:"tools,omitempty"` } ImageContent struct { ImageURL string `json:"image_url"` Type string `json:"type"` } Message struct { Audio map[string]string `json:"audio,omitempty"` Content any `json:"content"` Role string `json:"role"` ToolCallID string `json:"tool_call_id,omitempty"` ToolCalls []map[string]any `json:"tool_calls,omitempty"` } ResponseFormat struct { JSONSchema map[string]string `json:"json_schema,omitempty"` Type string `json:"type"` } TextContent struct { Text string `json:"text"` Type string `json:"type"` } Tool struct { Function ToolFunction `json:"function"` Type string `json:"type"` } ToolChoice struct { Function map[string]any `json:"function,omitempty"` Type string `json:"type"` } ToolFunction struct { Description string `json:"description,omitempty"` Name string `json:"name"` Parameters map[string]any `json:"parameters,omitempty"` Strict bool `json:"strict"` } ) var waitingMessages = []string{ "Just a moment, I'm thinking...", "Let me think about that for a second...", "Good question, let me find out...", } // Chat Completion Server type Server struct { client *openai.Client logger *slog.Logger } // Create a new server instance func NewServer(apiKey string) *Server { return &Server{ client: openai.NewClient(apiKey), logger: slog.New(slog.NewJSONHandler(os.Stdout, nil)), } } // Handle Chat Completion endpoint func (s *Server) handleChatCompletion(c *gin.Context) { var request ChatCompletionRequest if err := c.ShouldBindJSON(&request); err != nil { s.sendError(c, http.StatusBadRequest, err) return } if !request.Stream { s.sendError(c, http.StatusBadRequest, fmt.Errorf("chat completions require streaming")) return } // Set SSE headers c.Header("Content-Type", "text/event-stream") responseChan := make(chan any, 100) errorChan := make(chan error, 1) go func() { messages := make([]openai.ChatCompletionMessage, len(request.Messages)) for i, msg := range request.Messages { if strContent, ok := msg.Content.(string); ok { messages[i] = openai.ChatCompletionMessage{ Role: msg.Role, Content: strContent, } } } req := openai.ChatCompletionRequest{ Model: request.Model, Messages: messages, Stream: true, } if len(request.Tools) > 0 { tools := make([]openai.Tool, len(request.Tools)) for i, tool := range request.Tools { tools[i] = openai.Tool{ Type: openai.ToolTypeFunction, Function: &openai.FunctionDefinition{ Name: tool.Function.Name, Description: tool.Function.Description, Parameters: tool.Function.Parameters, }, } } req.Tools = tools } stream, err := s.client.CreateChatCompletionStream(c.Request.Context(), req) if err != nil { errorChan <- err return } defer stream.Close() for { response, err := stream.Recv() if err == io.EOF { break } if err != nil { errorChan <- err return } responseChan <- response } close(responseChan) }() for { select { case chunk, ok := <-responseChan: if !ok { c.SSEvent("data", "[DONE]") return } data, _ := json.Marshal(chunk) c.SSEvent("data", string(data)) case err := <-errorChan: s.logger.Error("Error in chat completion stream", "err", err) s.sendError(c, http.StatusInternalServerError, err) return } } } // Send error response to client func (s *Server) sendError(c *gin.Context, status int, err error) { c.JSON(status, gin.H{"detail": err.Error()}) } func main() { // Initialize server server := NewServer(os.Getenv("YOUR_LLM_API_KEY")) // Initialize Gin router r := gin.Default() // Set routes r.POST("/chat/completions", server.handleChatCompletion) // Start server r.Run(":8000") } ``` **Node.js** ```js const express = require('express'); const OpenAI = require('openai'); // Initialize OpenAI client const openai = new OpenAI({ apiKey: process.env.YOUR_LLM_API_KEY, }); // Initialize Express app const app = express(); app.use(express.json()); // Configure logging const logger = { info: (message) => console.log('INFO: ' + message), debug: (message) => console.log('DEBUG: ' + message), error: (message, error) => console.error('ERROR: ' + message, error), }; // Chat Completions endpoint app.post('/chat/completions', async (req, res) => { try { logger.info('Received request: ' + JSON.stringify(req.body)); const { model, messages, modalities = ['text'], tools, tool_choice, response_format, audio, stream = true, stream_options, } = req.body; if (!stream) { return res .status(400) .json({ detail: 'chat completions require streaming' }); } // Set SSE headers res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); // Create OpenAI streaming completion const completion = await openai.chat.completions.create({ model, messages, tools: tools ? tools : undefined, tool_choice: tools && tool_choice ? tool_choice : undefined, modalities, audio, response_format, stream: true, stream_options, }); // Stream the response for await (const chunk of completion) { logger.debug('Received chunk: ' + JSON.stringify(chunk)); res.write('data: ' + JSON.stringify(chunk) + '\n\n'); } // End the stream res.write('data: [DONE]\n\n'); res.end(); } catch (error) { logger.error('Chat completion error:', error); if (!res.headersSent) { const errorDetail = error.message + '\n' + (error.stack || ''); return res.status(500).json({ detail: errorDetail }); } res.write('data: ' + JSON.stringify({ error: error.message }) + '\n\n'); res.write('data: [DONE]\n\n'); res.end(); } }); // Start server const PORT = process.env.PORT || 8000; app.listen(PORT, () => { logger.info('Server running on port ' + PORT); }); ``` ### Configure Conversational AI Engine To configure the agent to use your custom LLM service, update the LLM configuration as follows: **Python SDK** ```python from agora_agent import CustomLLM # ... other agent configuration ... .with_llm(CustomLLM( api_key='your-llm-api-key', base_url='https://your-custom-llm-service/chat/completions', model='your-model-name', system_messages=[{'role': 'system', 'content': 'You are a helpful assistant.'}], )) # ... continue with .with_tts() and .create_session() ... ``` **TypeScript SDK** ```typescript import { CustomLLM } from 'agora-agents'; // ... other agent configuration ... .withLlm(new CustomLLM({ apiKey: 'your-llm-api-key', url: 'https://your-custom-llm-service/chat/completions', model: 'your-model-name', systemMessages: [{ role: 'system', content: 'You are a helpful assistant.' }], })) // ... continue with .withTts() and .createSession() ... ``` **Go SDK** ```go // ... other agent configuration ... .WithLlm( vendors.NewCustomLLM(vendors.CustomLLMOptions{ APIKey: "your-llm-api-key", BaseURL: "https://your-custom-llm-service/chat/completions", Model: "your-model-name", SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful assistant."}, }, }), ) // ... continue with .WithTts() and .CreateSession() ... ``` **REST API** ```json { "llm": { "url": "https://your-custom-llm-service/chat/completions", "api_key": "your-llm-api-key", "system_messages": [ { "role": "system", "content": "You are a helpful assistant." } ] } } ``` > **Info** > > If accessing your custom LLM service requires identity verification, provide the authentication information in the `api_key` field. ## Advanced features To integrate advanced features such as Retrieval-Augmented Generation and generating outputs in multimodal forms, refer to the following sections. ### Retrieval-Augmented Generation To improve the accuracy and relevance of the agent's responses, use the Retrieval-Augmented Generation (RAG) feature. This feature allows your custom LLM to retrieve information from a specific knowledge base and use the retrieved results as context for generating responses. The following example simulates the process of retrieving and returning content from a knowledge base and creates the `/rag/chat/completions` endpoint to incorporate RAG retrieval results when generating responses with the LLM. **Python** ```python async def perform_rag_retrieval(messages: Optional[Dict]) -> str: """ Retrieve relevant content from the knowledge base using the RAG model. Args: messages: The original message list. Returns: str: The retrieved text content. """ # TODO: Implement the actual RAG retrieval logic. # You can choose the first or last message from the message list as the query, # then send the query to the RAG model to retrieve relevant content. # Return the retrieval result. return "This is relevant content retrieved from the knowledge base." def refact_messages(context: str, messages: Optional[Dict] = None) -> Optional[Dict]: """ Modify the message list by adding the retrieved context to the original messages. Args: context: The retrieved context. messages: The original message list. Returns: List: The modified message list. """ # TODO: Implement the actual message modification logic. # This should add the retrieved context to the original message list. return messages # Random waiting messages. waiting_messages = [ "Just a moment, I'm thinking...", "Let me think about that for a second...", "Good question, let me find out...", ] @app.post("/rag/chat/completions") async def create_rag_chat_completion(request: ChatCompletionRequest): try: logger.info(f"Received RAG request: {request.model_dump_json()}") if not request.stream: raise HTTPException( status_code=400, detail="chat completions require streaming" ) async def generate(): # First, send a "please wait" prompt. waiting_message = { "id": "waiting_msg", "choices": [ { "index": 0, "delta": { "role": "assistant", "content": random.choice(waiting_messages), }, "finish_reason": None, } ], } yield f"data: {json.dumps(waiting_message)}\n\n" # Perform RAG retrieval. retrieved_context = await perform_rag_retrieval(request.messages) # Modify messages. refacted_messages = refact_messages(retrieved_context, request.messages) # Request LLM completion. client = AsyncOpenAI(api_key=os.getenv("")) response = await client.chat.completions.create( model=request.model, messages=refacted_messages, tool_choice=( request.tool_choice if request.tools and request.tool_choice else None ), tools=request.tools if request.tools else None, modalities=request.modalities, audio=request.audio, response_format=request.response_format, stream=True, # Force streaming. stream_options=request.stream_options, ) try: async for chunk in response: logger.debug(f"Received RAG chunk: {chunk}") yield f"data: {json.dumps(chunk.to_dict())}\n\n" yield "data: [DONE]\n\n" except asyncio.CancelledError: logger.info("RAG stream was cancelled") raise return StreamingResponse(generate(), media_type="text/event-stream") except asyncio.CancelledError: logger.info("RAG request was cancelled") raise HTTPException(status_code=499, detail="Request was cancelled") except Exception as e: traceback_str = "".join(traceback.format_tb(e.__traceback__)) error_message = f"{str(e)}\ {traceback_str}" logger.error(error_message) raise HTTPException(status_code=500, detail=error_message) ``` **Go** ```go // Handle RAG Chat Completion endpoint func (s *Server) handleRAGChatCompletion(c *gin.Context) { var request ChatCompletionRequest if err := c.ShouldBindJSON(&request); err != nil { s.sendError(c, http.StatusBadRequest, err) return } if !request.Stream { s.sendError(c, http.StatusBadRequest, fmt.Errorf("chat completions require streaming")) return } // Set SSE headers c.Header("Content-Type", "text/event-stream") // First send a "please wait" prompt waitingMsg := map[string]any{ "id": "waiting_msg", "choices": []map[string]any{ { "index": 0, "delta": map[string]any{ "role": "assistant", "content": waitingMessages[rand.Intn(len(waitingMessages))], }, "finish_reason": nil, }, }, } data, _ := json.Marshal(waitingMsg) c.SSEvent("data", string(data)) // Perform RAG retrieval retrievedContext, err := s.performRAGRetrieval(request.Messages) if err != nil { s.logger.Error("Failed to perform RAG retrieval", "err", err) s.sendError(c, http.StatusInternalServerError, err) return } // Adjust messages refactedMessages := s.refactMessages(retrievedContext, request.Messages) // Convert messages to OpenAI format messages := make([]openai.ChatCompletionMessage, len(refactedMessages)) for i, msg := range refactedMessages { if strContent, ok := msg.Content.(string); ok { messages[i] = openai.ChatCompletionMessage{ Role: msg.Role, Content: strContent, } } } req := openai.ChatCompletionRequest{ Model: request.Model, Messages: messages, Stream: true, } stream, err := s.client.CreateChatCompletionStream(c.Request.Context(), req) if err != nil { s.sendError(c, http.StatusInternalServerError, err) return } defer stream.Close() for { response, err := stream.Recv() if err == io.EOF { break } if err != nil { s.sendError(c, http.StatusInternalServerError, err) return } data, _ := json.Marshal(response) c.SSEvent("data", string(data)) } c.SSEvent("data", "[DONE]") } // performRAGRetrieval uses the RAG model to retrieve relevant content from the knowledge base based on the message list. // // messages: Contains the original message list. // // Returns the retrieved text content and any errors that occurred during retrieval. func (s *Server) performRAGRetrieval(messages []Message) (string, error) { // TODO: Implement actual RAG retrieval logic // You may need to select the first or last message from the message list as a query based on specific requirements, then send the query to the RAG model to retrieve relevant content // Return retrieval results return "This is relevant content retrieved from the knowledge base.", nil } // refactMessages adjusts the message list, adding the retrieved context to the original message list. // // context: Contains the retrieved context. // messages: Contains the original message list. // // Returns the adjusted message list. func (s *Server) refactMessages(context string, messages []Message) []Message { // TODO: Implement actual message adjustment logic // This should add the retrieved context to the original message list // Only return original messages return messages } ``` **Node.js** ```js /** * Retrieve relevant content from the knowledge base using the RAG model. * * @param {Array} messages - The original message list. * @returns {Promise} The retrieved text content. */ async function performRagRetrieval(messages) { // TODO: Implement the actual RAG retrieval logic. // You can choose the first or last message from the message list as the query, // then send the query to the RAG model to retrieve relevant content. // Return the retrieval result. return 'This is relevant content retrieved from the knowledge base.'; } /** * Modify the message list by adding the retrieved context to the original messages. * * @param {string} context - The retrieved context. * @param {Array} messages - The original message list. * @returns {Array} The modified message list. */ function refactMessages(context, messages) { // TODO: Implement the actual message modification logic. // This should add the retrieved context to the original message list. return messages; } // Random waiting messages const waitingMessages = [ "Just a moment, I'm thinking...", 'Let me think about that for a second...', 'Good question, let me find out...', ]; // RAG Chat Completions endpoint app.post('/rag/chat/completions', async (req, res) => { try { logger.info('Received RAG request: ' + JSON.stringify(req.body)); const { model, messages, modalities = ['text'], tools, tool_choice, response_format, audio, stream = true, stream_options, } = req.body; if (!stream) { return res .status(400) .json({ detail: 'chat completions require streaming' }); } // Set SSE headers res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); // First, send a "please wait" prompt const waitingMessage = { id: 'waiting_msg', choices: [ { index: 0, delta: { role: 'assistant', content: waitingMessages[ Math.floor(Math.random() * waitingMessages.length) ], }, finish_reason: null, }, ], }; res.write('data: ' + JSON.stringify(waitingMessage) + '\n\n'); // Perform RAG retrieval const retrievedContext = await performRagRetrieval(messages); // Modify messages const refactedMessages = refactMessages(retrievedContext, messages); // Request LLM completion const completion = await openai.chat.completions.create({ model, messages: refactedMessages, tools: tools ? tools : undefined, tool_choice: tools && tool_choice ? tool_choice : undefined, modalities, audio, response_format, stream: true, stream_options, }); // Stream the response for await (const chunk of completion) { logger.debug('Received RAG chunk: ' + JSON.stringify(chunk)); res.write('data: ' + JSON.stringify(chunk) + '\n\n'); } // End the stream res.write('data: [DONE]\n\n'); res.end(); } catch (error) { logger.error('RAG chat completion error:', error); if (!res.headersSent) { const errorDetail = error.message + '\n' + (error.stack || ''); return res.status(500).json({ detail: errorDetail }); } res.write('data: ' + JSON.stringify({ error: error.message }) + '\n\n'); res.write('data: [DONE]\n\n'); res.end(); } }); ``` When calling the POST method to [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), simply point the LLM URL to your RAG interface: ```json { "llm": { "url": "http://your-custom-llm-service/rag/chat/completions", "api_key": "" "system_messages": [ { "role": "system", "content": "Please answer the user's question based on the following retrieved information: ..." } ] } } ``` > **Info** > > If accessing your custom LLM service requires identity verification, provide the authentication information in the `api_key` field. ### Multimodal capabilities Conversational AI Engine supports LLMs in generating output in multimodal formats, including text and audio. You can create dedicated multimodal interfaces to meet personalized requirements. For more information about using audio output, see [Audio output mode](audio-output). The following example demonstrates how to read text and audio files and send them to an LLM to generate an audio response. **Python** ```python async def read_text_file(file_path: str) -> str: """ Read a text file and return its content Args: file_path: Path to the text file Returns: str: Content of the text file """ async with aiofiles.open(file_path, "r") as file: content = await file.read() return content async def read_pcm_file( file_path: str, sample_rate: int, duration_ms: int ) -> List[bytes]: """ Read a PCM file and return a list of audio chunks Args: file_path: Path to the PCM file sample_rate: Sampling rate of the audio duration_ms: Duration of each audio chunk in milliseconds Returns: List: List of audio chunks """ async with aiofiles.open(file_path, "rb") as file: content = await file.read() chunk_size = int(sample_rate * 2 * (duration_ms / 1000)) return [content[i : i + chunk_size] for i in range(0, len(content), chunk_size)] @app.post("/audio/chat/completions") async def create_audio_chat_completion(request: ChatCompletionRequest): try: logger.info(f"Received audio request: {request.model_dump_json()}") if not request.stream: raise HTTPException( status_code=400, detail="chat completions require streaming" ) # Example usage, reading text and audio files # Please replace with your actual logic text_file_path = "./file.txt" pcm_file_path = "./file.pcm" sample_rate = 16000 # Example sampling rate duration_ms = 40 # 40ms audio chunk text_content = await read_text_file(text_file_path) audio_chunks = await read_pcm_file(pcm_file_path, sample_rate, duration_ms) async def generate(): try: # Send text content audio_id = uuid.uuid4().hex text_message = { "id": uuid.uuid4().hex, "choices": [ { "index": 0, "delta": { "audio": { "id": audio_id, "transcript": text_content, }, }, "finish_reason": None, } ], } yield f"data: {json.dumps(text_message)}\n\n" # Send audio chunks for chunk in audio_chunks: audio_message = { "id": uuid.uuid4().hex, "choices": [ { "index": 0, "delta": { "audio": { "id": audio_id, "data": base64.b64encode(chunk).decode("utf-8"), }, }, "finish_reason": None, } ], } yield f"data: {json.dumps(audio_message)}\n\n" yield "data: [DONE]\n\n" except asyncio.CancelledError: logger.info("Audio stream was cancelled") raise return StreamingResponse(generate(), media_type="text/event-stream") except asyncio.CancelledError: logger.info("Audio request was cancelled") raise HTTPException(status_code=499, detail="Request was cancelled") except Exception as e: traceback_str = "".join(traceback.format_tb(e.__traceback__)) error_message = f"{str(e)}\ {traceback_str}" logger.error(error_message) raise HTTPException(status_code=500, detail=error_message) ``` **Go** ```go // Handle Audio Chat Completion endpoint func (s *Server) handleAudioChatCompletion(c *gin.Context) { var request ChatCompletionRequest if err := c.ShouldBindJSON(&request); err != nil { s.sendError(c, http.StatusBadRequest, err) return } if !request.Stream { s.sendError(c, http.StatusBadRequest, fmt.Errorf("chat completions require streaming")) return } // Set SSE headers c.Header("Content-Type", "text/event-stream") // Read text and audio files textContent, err := s.readTextFile("./file.txt") if err != nil { s.logger.Error("Failed to read text file", "err", err) s.sendError(c, http.StatusInternalServerError, err) return } sampleRate := 16000 // Example sample rate durationMs := 40 // 40ms chunks audioChunks, err := s.readPCMFile("./file.pcm", sampleRate, durationMs) if err != nil { s.logger.Error("Failed to read PCM file", "err", err) s.sendError(c, http.StatusInternalServerError, err) return } // Send text content audioID := uuid.New().String() textMessage := map[string]any{ "id": uuid.New().String(), "choices": []map[string]any{ { "index": 0, "delta": map[string]any{ "audio": map[string]any{ "id": audioID, "transcript": textContent, }, }, "finish_reason": nil, }, }, } data, _ := json.Marshal(textMessage) c.SSEvent("data", string(data)) // Send audio chunks for _, chunk := range audioChunks { audioMessage := map[string]any{ "id": uuid.New().String(), "choices": []map[string]any{ { "index": 0, "delta": map[string]any{ "audio": map[string]any{ "id": audioID, "data": base64.StdEncoding.EncodeToString(chunk), }, }, "finish_reason": nil, }, }, } data, _ := json.Marshal(audioMessage) c.SSEvent("data", string(data)) } c.SSEvent("data", "[DONE]") } // readPCMFile reads a PCM file and returns audio chunks. // // filePath: Specifies the path to the PCM file. // sampleRate: Specifies the sampling rate of the audio. // durationMs: Specifies the duration of each audio chunk in milliseconds. // // Returns a list of audio chunks and any errors that occurred during reading. func (s *Server) readPCMFile(filePath string, sampleRate int, durationMs int) ([][]byte, error) { data, err := os.ReadFile(filePath) if err != nil { return nil, fmt.Errorf("failed to read PCM file: %w", err) } chunkSize := int(float64(sampleRate) * 2 * float64(durationMs) / 1000.0) if chunkSize == 0 { return nil, fmt.Errorf("invalid chunk size: sample rate %d, duration %dms", sampleRate, durationMs) } chunks := make([][]byte, 0, len(data)/chunkSize+1) for i := 0; i < len(data); i += chunkSize { end := i + chunkSize if end > len(data) { end = len(data) } chunks = append(chunks, data[i:end]) } return chunks, nil } // readTextFile reads a text file and returns its content. // // filePath: Specifies the path to the text file. // // Returns the content of the text file and any errors that occurred during reading. func (s *Server) readTextFile(filePath string) (string, error) { data, err := os.ReadFile(filePath) if err != nil { return "", fmt.Errorf("failed to read text file: %w", err) } return string(data), nil } ``` **Node.js** ```js const fs = require('fs').promises; const { randomUUID } = require('crypto'); /** * Read a text file and return its content * @param {string} filePath - Path to the text file * @returns {Promise} Content of the text file */ async function readTextFile(filePath) { const content = await fs.readFile(filePath, 'utf8'); return content; } /** * Read a PCM file and return a list of audio chunks * @param {string} filePath - Path to the PCM file * @param {number} sampleRate - Sampling rate of the audio * @param {number} durationMs - Duration of each audio chunk in milliseconds * @returns {Promise} List of audio chunks */ async function readPCMFile(filePath, sampleRate, durationMs) { const content = await fs.readFile(filePath); const chunkSize = Math.floor(sampleRate * 2 * (durationMs / 1000)); const chunks = []; for (let i = 0; i < content.length; i += chunkSize) { chunks.push(content.slice(i, i + chunkSize)); } return chunks; } // Audio Chat Completions endpoint app.post('/audio/chat/completions', async (req, res) => { try { logger.info('Received audio request: ' + JSON.stringify(req.body)); const { model, messages, modalities = ['text'], tools, tool_choice, response_format, audio, stream = true, stream_options, } = req.body; if (!stream) { return res .status(400) .json({ detail: 'chat completions require streaming' }); } // Set SSE headers res.setHeader('Content-Type', 'text/event-stream'); res.setHeader('Cache-Control', 'no-cache'); res.setHeader('Connection', 'keep-alive'); // Example usage, reading text and audio files // Please replace with your actual logic const textFilePath = './file.txt'; const pcmFilePath = './file.pcm'; const sampleRate = 16000; // Example sampling rate const durationMs = 40; // 40ms audio chunk const textContent = await readTextFile(textFilePath); const audioChunks = await readPCMFile(pcmFilePath, sampleRate, durationMs); // Generate audio ID for this response const audioId = randomUUID(); // Send text content const textMessage = { id: randomUUID(), choices: [ { index: 0, delta: { audio: { id: audioId, transcript: textContent, }, }, finish_reason: null, }, ], }; res.write('data: ' + JSON.stringify(textMessage) + '\n\n'); // Send audio chunks for (const chunk of audioChunks) { const audioMessage = { id: randomUUID(), choices: [ { index: 0, delta: { audio: { id: audioId, data: chunk.toString('base64'), }, }, finish_reason: null, }, ], }; res.write('data: ' + JSON.stringify(audioMessage) + '\n\n'); } res.write('data: [DONE]\n\n'); res.end(); } catch (error) { logger.error('Audio chat completion error:', error); if (!res.headersSent) { const errorDetail = error.message + '\n' + (error.stack || ''); return res.status(500).json({ detail: errorDetail }); } res.write('data: ' + JSON.stringify({ error: error.message }) + '\n\n'); res.write('data: [DONE]\n\n'); res.end(); } }); ``` To configure the agent to use your audio endpoint, update the LLM configuration as follows: **Python SDK** ```python from agora_agent import CustomLLM # ... other agent configuration ... .with_llm(CustomLLM( api_key='your-llm-api-key', base_url='https://your-custom-llm-service/audio/chat/completions', model='your-model-name', input_modalities=['text'], output_modalities=['text', 'audio'], system_messages=[{'role': 'system', 'content': 'You are a helpful assistant.'}], )) # ... continue with .with_tts() and .create_session() ... ``` **TypeScript SDK** ```typescript import { CustomLLM } from 'agora-agents'; // ... other agent configuration ... .withLlm(new CustomLLM({ apiKey: 'your-llm-api-key', url: 'https://your-custom-llm-service/audio/chat/completions', model: 'your-model-name', inputModalities: ['text'], outputModalities: ['text', 'audio'], systemMessages: [{ role: 'system', content: 'You are a helpful assistant.' }], })) // ... continue with .withTts() and .createSession() ... ``` **Go SDK** ```go // ... other agent configuration ... .WithLlm( vendors.NewCustomLLM(vendors.CustomLLMOptions{ APIKey: "your-llm-api-key", BaseURL: "https://your-custom-llm-service/audio/chat/completions", Model: "your-model-name", InputModalities: []string{"text"}, OutputModalities: []string{"text", "audio"}, SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful assistant."}, }, }), ) // ... continue with .WithTts() and .CreateSession() ... ``` **REST API** ```json { "llm": { "url": "https://your-custom-llm-service/audio/chat/completions", "api_key": "your-llm-api-key", "input_modalities": ["text"], "output_modalities": ["text", "audio"], "system_messages": [ { "role": "system", "content": "You are a helpful assistant." } ] } } ``` ### Control agent behavior using first-packet metadata In streaming response (SSE) scenarios, a single LLM response is segmented into multiple chunks for transmission. Agora's Conversational AI Engine supports processing a special first-chunk response where `object` is `chat.completion.custom_metadata`, and uses the `metadata` field in that response to control the following agent behaviors: - [Configure whether the TTS broadcast can be interrupted](#configure-llm-response-interruption) - [Update TTS parameters in real time](#update-tts-parameters-in-real-time) To use these features, modify your custom LLM service to output a special first-chunk response that meets the Conversational AI Engine's requirements. The diagram below shows how the engine processes this metadata chunk before handling the rest of the response. ![](https://assets-docs.agora.io/images/conversational-ai/custom-llm-metadata-flow.svg) #### Configure LLM response interruption The Conversational AI Engine supports letting the custom LLM determine whether a response can be interrupted by the user. This is particularly useful for long-running tasks, such as querying a database or calling an external API, where the agent must remain responsive while the task completes in the background. When the custom LLM initiates a long-running task, it sends a `custom_metadata` packet to the Conversational AI Engine with `interruptable` set to `false`, followed by a `chat.completion.chunk` response containing a filler phrase, for example "Just a moment, I'm processing your request". The Conversational AI Engine passes the filler phrase to TTS and plays it to the user while the task completes in the background. Setting `interruptable` to `false` prevents user speech from interrupting the TTS broadcast of the filler phrase. In your custom LLM service, output a first-chunk response with the following structure: ```json { "id": "response-id", "object": "chat.completion.custom_metadata", "choices": [], "metadata": { "interruptable": false } } ``` The `interruptable` field configures whether the TTS broadcast of this LLM response can be interrupted by user speech. Set it to `false` to prevent interruption, `true` to allow it, or omit it to leave the current interruption mode unchanged. > **Caution** > > The Conversational AI Engine only processes the first chunk response where `object` is `chat.completion.custom_metadata` and ignores the content in `choices`. Subsequent responses are treated as normal responses and do not support metadata configuration. Ensure that the content requiring TTS broadcast is generated in the second and subsequent responses. **ASR behavior during non-interruptible responses** Setting `interruptable` to `false` does not disable automatic speech recognition (ASR). The engine continues to capture and transcribe user speech during TTS playback, but holds the transcript and does not process it until TTS finishes. This means: - If a user speaks during a non-interruptible TTS broadcast, their speech is not lost. It is queued and processed after playback ends. - For long-running tasks, you are responsible for managing the agent's state outside the response lifecycle. Consider how your application should handle queued speech: for example, whether to process it normally, discard it, or use it to cancel the background task. #### Update TTS parameters in real time The Conversational AI Engine supports real-time TTS parameter updates during a conversation, enabling a more immersive interactive experience. This feature is useful when the agent needs to adjust its voice dynamically based on user input, for example when a user requests a different voice or when the LLM detects a change in the user's mood and adjusts volume, pitch, or speech rate accordingly. When the LLM determines that TTS parameters need to be updated, modify your custom LLM service to output a first-chunk response with the following structure: ```json { "id": "response-id", "object": "chat.completion.custom_metadata", "choices": [], "metadata": { "tts_params": { "params": { "voice_type": "female_1", "rate": 1.1 } } } } ``` The `tts_params.params` field specifies the TTS parameters to update. For the available parameters, refer to your TTS vendor's official documentation. ## Reference This section contains content that completes the information on this page, or points you to documentation that explains other aspects to this product. ### Sample project Agora provides open source sample projects on GitHub for your reference. Download the project or view the source code for a more complete example. - [Python](https://github.com/AgoraIO-Community/Conversational-AI-Server-Sample/tree/main/python/custom_llm) - [Go](https://github.com/AgoraIO-Community/Conversational-AI-Server-Sample/tree/main/golang/custom_llm) - [Node.js](https://github.com/AgoraIO-Community/Conversational-AI-Server-Sample/tree/main/node/custom_llm) ### Interface standards Custom LLM services must be compatible with the OpenAI Chat Completions API interface standard: - **Request format**: Contains parameters such as model, message, and tool call configuration. - **Response format**: Contains the response generated by the model, metadata, and other information - **Streaming response**: Compliant with the SSE (Server-Sent Events) specification For detailed interface standards, please refer to: - [OpenAI Chat Completions API documentation](https://platform.openai.com/docs/api-reference/chat) - [Conversational AI Engine API Documentation](/en/api-reference/api-ref/conversational-ai/join) # Connect your own TTS service (/en/ai/build/custom-model-integration/custom-tts) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). By integrating a custom text-to-speech (TTS) service, you can use a self-built, privately deployed, or third-party TTS service as the speech synthesis module for your conversational AI agent. This page explains how to prepare an HTTP service compatible with the OpenAI TTS protocol, and how to connect it using the Agent SDK's `GenericTTS` vendor or directly through the REST API's `generic_http` TTS configuration. ## Understand the tech The Agent SDK constructs your custom TTS configuration through `GenericTTS`. When you start an agent session, the SDK serializes this configuration to `tts.vendor = "generic_http"`, and Agora's Conversational AI Engine sends an HTTP request to your TTS service whenever it needs to synthesize speech. If you call the REST API directly instead of using the SDK, you can configure the same `generic_http` TTS vendor without `GenericTTS`. ## Prerequisites Before you begin, ensure that you have: - Implemented the basic logic for interacting with a conversational AI agent. See the [quickstart](../../get-started/quickstart). - Prepared a TTS HTTP service that Agora's Conversational AI Engine can reach. - Confirmed your TTS service supports HTTP/1.1 or later. - Confirmed your TTS service can return audio data in PCM format. - If you're using the Agent SDK, installed a version that supports `GenericTTS`: Go and TypeScript SDK v2.4.0 or later, or Python SDK v2.4.1 or later. > **Tip: Best practices** > > Use HTTPS for your TTS service in production. > **Caution** > > `GenericTTS` only supports HTTP and HTTPS endpoints. Passing a `ws://` or `wss://` address causes the SDK to throw an error when constructing the TTS vendor. ## Implementation Take the following steps to connect your custom TTS service to Agora's Conversational AI Engine. ### Prepare your TTS service interface Your TTS service must provide an HTTP interface compatible with the OpenAI TTS protocol. The basic requirements are: - **Request method**: `POST` - **Request path**: `/audio/speech` - **Request headers**: Authentication via an `Authorization: Bearer ` header - **Request body**: JSON - **Response body**: A stream of PCM audio data Example request body: ```json { "model": "your-tts-model", "input": "Welcome to Agora's Conversational AI service.", "voice": "alloy", "speed": 1.0, "sample_rate": 16000, "response_format": "pcm", "instructions": "calm" } ``` Request body fields: | Field | Type | Description | | ----------------- | ------- | ---------------------------------------------------------------------------------------------------------------------- | | `input` | String | The text to synthesize. Agora's Conversational AI Engine automatically populates this field from the agent's response. | | `model` | String | The TTS model name. Omit this field if your TTS service doesn't distinguish between models. | | `voice` | String | The voice name. Omit this field if your TTS service doesn't distinguish between voices. | | `speed` | Number | The speech rate. | | `sample_rate` | Integer | The sample rate, in Hz, of the output audio. Default: `16000`. | | `response_format` | String | The output audio format. Default: `pcm`. Only `pcm` is supported. | | `instructions` | String | Instructions for voice style, emotion, or other playback directives. | > **Info** > > If your TTS service doesn't support multiple sample rates, make sure the sample rate of the audio it returns matches the `sample_rate` you configure in the next step. ### Verify your TTS service's response Use `curl` to confirm your TTS service returns a valid PCM audio stream: ```bash curl --request POST \ --url https://your-tts-service.example.com/v1/audio/speech \ --header 'Authorization: Bearer ' \ --header 'Content-Type: application/json' \ --data '{ "model": "your-tts-model", "input": "Welcome to the Agora Conversational AI service.", "voice": "alloy", "speed": 1.0, "sample_rate": 16000, "response_format": "pcm" }' \ --output test.pcm ``` When the request succeeds, your service should stream the synthesized PCM audio back using HTTP chunked transfer encoding. If a request fails, your TTS service should return a standard HTTP error status code along with a JSON error body, for example: ```json { "error": { "message": "Incorrect API key provided.", "type": "invalid_request_error", "param": null, "code": "invalid_api_key" } } ``` ### Configure the agent to use your custom TTS service The following examples show `sttVendor`/`stt_vendor` and `llmVendor`/`llm_vendor` as placeholders for STT and LLM vendors you've already configured — select the services that fit your use case. The examples focus on connecting your custom TTS service using `GenericTTS`. **Python SDK** ```python from agora_agent import Agent, GenericTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(stt_vendor) # configure your STT vendor .with_llm(llm_vendor) # configure your LLM vendor .with_tts(GenericTTS( url='https://your-tts-service.example.com/v1/audio/speech', headers={ 'Authorization': 'Bearer ', }, model='your-tts-model', voice='alloy', speed=1.0, sample_rate=16000, response_format='pcm', instruction='calm', )) ) ``` **TypeScript SDK** ```typescript import { Agent, GenericTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(sttVendor) // configure your STT vendor .withLlm(llmVendor) // configure your LLM vendor .withTts(new GenericTTS({ url: 'https://your-tts-service.example.com/v1/audio/speech', headers: { Authorization: 'Bearer ', }, model: 'your-tts-model', voice: 'alloy', speed: 1.0, sampleRate: 16000, responseFormat: 'pcm', instruction: 'calm', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client speed := 1.0 sampleRate := vendors.SampleRate16kHz agent := agentkit.NewAgent(client). WithStt(sttVendor). // configure your STT vendor WithLlm(llmVendor). // configure your LLM vendor WithTts( vendors.NewGenericTTS(vendors.GenericTTSOptions{ URL: "https://your-tts-service.example.com/v1/audio/speech", Headers: map[string]string{ "Authorization": "Bearer ", }, Model: "your-tts-model", Voice: "alloy", Speed: &speed, SampleRate: &sampleRate, ResponseFormat: "pcm", Instruction: "calm", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json { "tts": { "vendor": "generic_http", "url": "https://your-tts-service.example.com/v1/audio/speech", "headers": { "Authorization": "Bearer " }, "params": { "model": "your-tts-model", "voice": "alloy", "speed": 1.0, "sample_rate": 16000, "response_format": "pcm", "instructions": "calm", "enable_request_id": false } } } ``` `generic_http` configuration reference: | Field | Type | Required | Default | Description | | ------------------------------ | ------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tts.vendor` | String | Yes | - | Set to `generic_http` to use a custom TTS service. | | `tts.url` | String | Yes | - | The TTS service address. Must be compatible with the OpenAI TTS protocol. | | `tts.headers` | Object | No | - | Request headers to include when calling the TTS service, typically used to configure `Authorization`. | | `tts.params` | Object | No | - | TTS request parameters. In addition to the fields listed below, `params` supports other fields as needed. The system passes them through to the TTS service. | | `tts.params.api_key` | String | No | - | The API key used to authenticate with the TTS service. If set, the system automatically includes `Authorization: Bearer ` when calling the TTS service. | | `tts.params.model` | String | No | - | The TTS model name. | | `tts.params.voice` | String | No | - | The voice name. Omit this parameter if your TTS service doesn't support multiple voices. | | `tts.params.speed` | Number | No | - | The speech rate. | | `tts.params.sample_rate` | Integer | No | `16000` | The sample rate, in Hz, of the output audio. If your TTS service doesn't support multiple sample rates, make sure the sample rate of the returned audio matches this value. | | `tts.params.response_format` | String | No | `pcm` | The output audio format. Only `pcm` is supported. | | `tts.params.instructions` | String | No | - | Instructions for voice style, emotion, or other playback directives. | | `tts.params.enable_request_id` | Boolean | No | `false` | Whether to include `request_id`, `request_seq_id`, and `request_end` in the TTS request body. | For the exact field names in each Agent SDK language, see the `GenericTTS` reference for [Go](/en/api-reference/api-ref/server-sdk/go#newgenerictts), [Python](/en/api-reference/api-ref/server-sdk/python#generictts), and [TypeScript](/en/api-reference/api-ref/server-sdk/typescript#generictts), or the full parameter reference at [Generic TTS](../../models/tts/generic-http). > **Info** > > Provide at least one of `tts.headers.Authorization` or `tts.params.api_key`. If you provide both, the system uses `tts.headers.Authorization`. After configuring `GenericTTS`, continue with `create_session()`/`createSession()`/`CreateSession()` and `session.start()` as shown in the [quickstart](../../get-started/quickstart). ### Receive request identifiers on demand If your TTS service needs to distinguish between multiple requests within the same playback turn, pass `enable_request_id` as an additional parameter: **Python SDK** ```python GenericTTS( # ... other options ... additional_params={ 'enable_request_id': True, }, ) ``` **TypeScript SDK** ```typescript new GenericTTS({ // ... other options ... additionalParams: { enable_request_id: true, }, }); ``` **Go SDK** ```go vendors.GenericTTSOptions{ // ... other options ... AdditionalParams: map[string]interface{}{ "enable_request_id": true, }, } ``` **REST API** ```json "tts": { "vendor": "generic_http", "params": { "enable_request_id": true } } ``` When enabled, the system includes the following fields in the request body it sends to your TTS service: | Field | Type | Description | | ---------------- | ------- | -------------------------------------------------------------------------------- | | `request_id` | String | A unique identifier for this TTS request. | | `request_seq_id` | Integer | The request sequence number within the current playback turn, starting from `0`. | | `request_end` | Boolean | Whether this is the last request in the current playback turn. | ## Reference - [Quickstart](../../get-started/quickstart) - SDK API Reference - [Go: NewGenericTTS](/en/api-reference/api-ref/server-sdk/go#newgenerictts) - [Python: GenericTTS](/en/api-reference/api-ref/server-sdk/python#generictts) - [TypeScript: GenericTTS](/en/api-reference/api-ref/server-sdk/typescript#generictts) - [Generic TTS](../../models/tts/generic-http) # Debug agent failures (/en/ai/build/handle-runtime-events/debug-agent-failures) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). When an agent session fails, the explanation may span more than one event. This page shows which events to check first and how to correlate them. A useful debugging flow combines: - Client callbacks for live reproduction - Webhook events for durable backend records - Turn-level data for post-session analysis ## Start with the right event | Symptom | Check first | Then check | | ------------------------------------------------------------- | -------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | The agent stopped unexpectedly | [`102 agent left`](../../reference/event-types#102-agent-left) | [`110 agent error`](../../reference/event-types#110-agent-error), [`101 agent joined`](../../reference/event-types#101-agent-joined) | | The agent reported a module failure during a live session | `onAgentError` | [`110 agent error`](../../reference/event-types#110-agent-error), `onDebugLog` or `DEBUG_LOG` | | The response was slow or degraded before failure | [`111 agent metrics`](../../reference/event-types#111-agent-metrics) | [`Query conversation turn information`](/en/api-reference/api-ref/conversational-ai/turns) | | A specific turn failed | `turn_id` from `onAgentError` or `110` | [`Query conversation turn information`](/en/api-reference/api-ref/conversational-ai/turns) | | The UI displayed incorrect state but the session did not fail | `onAgentStateChanged` and fine-grained state callbacks | `onDebugLog` or `DEBUG_LOG` | ## Choose a debugging path **Client-side debugging** Use the client path when you are reproducing the issue live and the app must react immediately: - Start with `onAgentError` - Capture `onDebugLog` or `DEBUG_LOG` - Inspect state changes such as `onAgentStateChanged` **Server-side debugging** Use the server path when you need to investigate the issue after the session ends: - Start with [`102 agent left`](../../reference/event-types#102-agent-left) - Inspect [`110 agent error`](../../reference/event-types#110-agent-error) - Review [`111 agent metrics`](../../reference/event-types#111-agent-metrics) - Query [`turns`](/en/api-reference/api-ref/conversational-ai/turns) when you need turn-level timing and completion data ## Enable events before you debug For client-side runtime debugging, start the agent with RTM and the relevant event outputs enabled: ```json { "advanced_features": { "enable_rtm": true }, "parameters": { "data_channel": "rtm", "enable_metrics": true, "enable_error_message": true } } ``` For backend debugging, configure [webhooks](webhooks) and subscribe to the following events: - `101 agent joined` - `102 agent left` - `104 agent expire` - `110 agent error` - `111 agent metrics` ## Build a failure timeline In production, checking the events in the following order usually surfaces the cause fastest: 1. Confirm the session existed with [`101 agent joined`](../../reference/event-types#101-agent-joined). 2. Check how it ended with [`102 agent left`](../../reference/event-types#102-agent-left). 3. Look for module failures in [`110 agent error`](../../reference/event-types#110-agent-error). 4. Inspect latency and degradation in [`111 agent metrics`](../../reference/event-types#111-agent-metrics). 5. If the problem happened on a specific turn, query [`turns`](/en/api-reference/api-ref/conversational-ai/turns). This sequence helps you separate a session that ended badly from one that slowed down first and then failed. ## Interpret the most important fields ### `102 agent left` This event tells you how the session ended: - `status` tells you whether the session stopped normally or failed. - `message` explains why the session left, for example, idle timeout or connection failure. - `stop_ts` gives you the session end time for correlation. ### `110 agent error` This event tells you which module failed: - `errors[].module` tells you where the problem occurred, such as `llm`, `tts`, or `sip`. - `errors[].code` is the vendor-specific error code. - `errors[].message` gives the error text returned for that failure. - `turn_id` helps you correlate the failure with a specific user-agent exchange. ### `111 agent metrics` This event tells you whether the session degraded before failure: - Track latency trends for LLM and TTS - Compare healthy and failed sessions by `labels` - Isolate whether the problem is model-side, telephony-side, or client-perceived only For performance-focused analysis, also see [Optimize conversation latency](../../best-practices/optimize-latency). ## Correlate client and server records When you combine local reproduction with backend evidence, match records by: - `agent_id` - `name` - `channel` - `turn_id` - `labels` (useful when debugging by tenant, environment, campaign, or experiment) ## Recommended debugging workflow 1. Reproduce the issue with toolkit callbacks enabled in the client. 2. Capture `onAgentError`, `onDebugLog`, or `DEBUG_LOG` during the live session. 3. Confirm the same session in webhook data with `101`, `102`, `110`, and `111`. 4. If needed, query [`turns`](/en/api-reference/api-ref/conversational-ai/turns) for per-turn timing and completion data. 5. Group repeated failures by `labels` to decide whether the issue is session-specific or systemic. ## Related resources - [Monitor agent status, errors, and performance](monitor-agent-runtime) - [Get runtime events](get-runtime-events) - [Client-side events](event-notifications) - [Webhooks](webhooks) - [Notification event types](../../reference/event-types) - [Query conversation turn information](/en/api-reference/api-ref/conversational-ai/turns) # Client-side events (/en/ai/build/handle-runtime-events/event-notifications) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Real-time Conversational AI applications require responsive user interfaces that react to agent events. This page explains how to implement client-side event handling with the Conversational AI Engine toolkit. Use this page when you need in-session events in a mobile or web client. If you need backend monitoring, alerting, or post-session analysis, use [Webhooks](webhooks) instead. For an overview that compares client toolkit and webhook delivery, see [Get runtime events](get-runtime-events). ## Understand the tech Agora provides a flexible, scalable, and standardized Conversational AI Engine toolkit. The toolkit supports **Android**, **iOS**, and **Web** platforms, and encapsulates scenario-based APIs. You can use these APIs to integrate Agora Signaling SDK and RTC SDK capabilities to enable the following features: - [Interrupt agents](../shape-the-conversation/interrupt-agent) - [Display live transcripts](../transcripts) - [Monitor agent status, errors, and performance](monitor-agent-runtime) - [Set optimal audio parameters](../../best-practices/audio-setup) for iOS and Android The toolkit exposes callback methods that let you listen for various agent-related events and system information: - **`onAgentStateChanged`**: Listen for agent state changes such as `silent`, `listening`, `thinking`, and `speaking`. - **`onAgentListeningChanged`**: Track when the agent starts or stops listening. - **`onAgentThinkingChanged`**: Track when the agent starts or stops processing. - **`onAgentSpeakingChanged`**: Track when the agent starts or stops playing speech. - **`onAgentInterrupted`**: Handle interruption events triggered during a conversation. - **`onAgentMetrics`**: Observe performance metrics such as LLM and TTS latency. - **`onAgentError`**: Handle module-level failures such as LLM or TTS errors. ## Prerequisites - Implemented the Conversational AI Engine [quickstart](../../get-started/quickstart). - Your app integrates Agora RTC SDK v4.5.1 or later and includes the [RTC SDK quickstart](../../../realtime-media/rtc/get-started-sdk). - Enabled Signaling in the Agora Console and completed the [Signaling quickstart](/en/realtime-media/rtm/quickstart) for basic messaging. - Maintain active and authenticated RTC and Signaling instances that persist beyond the component lifecycle. The toolkit does not manage RTC or Signaling initialization, lifecycle, or authentication. ## Implementation **Android** 1. **Integrate the toolkit** Add the toolkit to your project using Maven or source code. See [Install the Android toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#installation). Refer to [Folder structure](#folder-structure) to understand the role of each file. 2. **Create a toolkit instance** ```kotlin val config = ConversationalAIAPIConfig( rtcEngine = rtcEngine, rtmClient = rtmClient, renderMode = TranscriptRenderMode.Word, enableLog = true, enableRenderModeFallback = true ) val api = ConversationalAIAPIImpl(config) ``` 3. **Register events** ```kotlin api.addHandler(object : IConversationalAIAPIEventHandler { override fun onAgentStateChanged(agentUserId: String, event: StateChangeEvent) { when (event.state) { AgentState.SILENT -> updateAgentStatus("Waiting...") AgentState.LISTENING -> updateAgentStatus("Listening...") AgentState.THINKING -> updateAgentStatus("Thinking...") AgentState.SPEAKING -> updateAgentStatus("Speaking...") AgentState.UNKNOWN -> Log.w("AgentState", "Unknown agent state: $event") } } override fun onAgentInterrupted(agentUserId: String, event: InterruptEvent) { Log.d("AgentInterrupt", "Agent $agentUserId interrupted at turn ${event.turnId}") showInterruptNotification() } override fun onAgentMetrics(agentUserId: String, metric: Metric) { when (metric.type) { ModuleType.LLM -> Log.d("Metrics", "LLM latency: ${metric.value} ms") ModuleType.TTS -> Log.d("Metrics", "TTS latency: ${metric.value} ms") else -> Log.d("Metrics", "${metric.type}: ${metric.name} = ${metric.value}") } } override fun onAgentError(agentUserId: String, error: ModuleError) { Log.e("AgentError", "Error in ${error.type}: ${error.message} (code: ${error.code})") } }) ``` 4. **Subscribe to the channel** ```kotlin api.subscribeMessage("channelName") { error -> if (error != null) { // Handle error } } ``` 5. **Add a conversational AI agent to the channel** To [start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), configure: | Parameter | Description | Required | | --------------------------------------- | -------------------------------------------------- | -------- | | `advanced_features.enable_rtm: true` | Starts the Signaling service | Yes | | `parameters.data_channel: "rtm"` | Enables Signaling as the data transmission channel | Yes | | `parameters.enable_metrics: true` | Enables agent performance data collection | Optional | | `parameters.enable_error_message: true` | Enables reporting of agent error events | Optional | 6. **Unsubscribe and release resources** ```kotlin api.unsubscribeMessage("channelName") { error -> if (error != null) { // Handle the error } } api.destroy() ``` **iOS** 1. **Integrate the toolkit** Add the toolkit to your project using CocoaPods, Swift Package Manager, or source code. See [Install the iOS toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#installation). Refer to [Folder structure](#folder-structure) to understand the role of each file. 2. **Create a toolkit instance** ```swift let config = ConversationalAIAPIConfig( rtcEngine: rtcEngine, rtmEngine: rtmEngine, renderMode: .words, enableLog: true, enableRenderModeFallback: true ) convoAIAPI = ConversationalAIAPIImpl(config: config) ``` 3. **Register events** ```swift class ConversationViewController: UIViewController, ConversationalAIAPIEventHandler { func onAgentStateChanged(agentUserId: String, event: StateChangeEvent) { DispatchQueue.main.async { self.updateAgentStatus(event.state) } } func onAgentInterrupted(agentUserId: String, event: InterruptEvent) { print("Agent \(agentUserId) interrupted at turn \(event.turnId)") } func onAgentMetrics(agentUserId: String, metrics: Metric) { switch metrics.type { case .llm: print("LLM latency: \(metrics.value)ms") case .tts: print("TTS latency: \(metrics.value)ms") case .unknown: print("Unknown metric: \(metrics.name) = \(metrics.value)") } } func onAgentError(agentUserId: String, error: ModuleError) { print("Error in \(error.type): \(error.message) (code: \(error.code))") } } convoAIAPI.addHandler(handler: self) ``` 4. **Subscribe to the channel** ```swift convoAIAPI.subscribeMessage(channelName: channelName) { error in if let error = error { print("Subscription failed: \(error.message)") } else { print("Subscription successful") } } ``` 5. **Add a conversational AI agent to the channel** To [start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), configure: | Parameter | Description | Required | | --------------------------------------- | -------------------------------------------------- | -------- | | `advanced_features.enable_rtm: true` | Starts the Signaling service | Yes | | `parameters.data_channel: "rtm"` | Enables Signaling as the data transmission channel | Yes | | `parameters.enable_metrics: true` | Enables collection of agent performance data | Optional | | `parameters.enable_error_message: true` | Enables reporting of agent error events | Optional | 6. **Unsubscribe and release resources** ```swift convoAIAPI.unsubscribeMessage(channelName: channelName) { error in if let error = error { print("Unsubscription failed: \(error.message)") } else { print("Unsubscribed successfully") } } convoAIAPI.destroy() ``` **Web** 1. **Integrate the toolkit** Add the toolkit to your project using a package manager or source code. See [Install the Web toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#installation). Refer to [Folder structure](#folder-structure) to understand the role of each file. 2. **Create a toolkit instance** ```tsx const config: IConversationalAIAPIConfig = { rtcEngine, rtmEngine, renderMode: ETranscriptHelperMode.WORD, enableLog: true, enableRenderModeFallback: true, } const conversationalAIAPI = await ConversationalAIAPI.init(config) ``` 3. **Register events** ```tsx conversationalAIAPI.on(EConversationalAIAPIEvents.AGENT_STATE_CHANGED, onAgentStateChanged) conversationalAIAPI.on(EConversationalAIAPIEvents.AGENT_METRICS, onAgentMetricsChanged) conversationalAIAPI.on(EConversationalAIAPIEvents.AGENT_ERROR, onAgentError) ``` 4. **Subscribe to the channel** ```ts conversationalAIAPI.subscribeMessage(channel_name) ``` 5. **Add a conversational AI agent to the channel** To [start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), configure: | Parameter | Description | Required | | --------------------------------------- | -------------------------------------------------- | -------- | | `advanced_features.enable_rtm: true` | Starts the Signaling service | Yes | | `parameters.data_channel: "rtm"` | Enables Signaling as the data transmission channel | Yes | | `parameters.enable_metrics: true` | Enables agent performance data collection | Optional | | `parameters.enable_error_message: true` | Enables reporting of agent error events | Optional | 6. **Unsubscribe and release resources** ```ts conversationalAIAPI.unsubscribeMessage(channel_name) conversationalAIAPI.destroy() ``` ## Reference ### Sample project - [Conversational-AI-Demo](https://github.com/AgoraIO-Community/Conversational-AI-Demo/) ### Related guides - [Monitor agent status, errors, and performance](monitor-agent-runtime) - [Webhooks](webhooks) ### Folder structure **Android** - `IConversationalAIAPI.kt`: API interface, data structures, and enumerations - `ConversationalAIAPIImpl.kt`: main implementation logic - `ConversationalAIUtils.kt`: utility functions and event callback management - `v3/` - `TranscriptionController.kt`: transcript rendering and synchronization - `MessageParser.kt`: transcription and message parsing **iOS** - `ConversationalAIAPI.swift`: API interface, data structures, and enumerations - `ConversationalAIAPIImpl.swift`: main implementation logic - `Transcription/` - `TranscriptionController.swift`: transcript rendering and control **Web** - `index.ts`: main API class - `type.ts`: API interfaces, data structures, and enumerations - `utils/` - `index.ts`: general utility functions - `events.ts`: event management class - `sub-render.ts`: transcript rendering module ### API reference **Android** - [`addHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#addhandler) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#unsubscribemessage) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#destroy) - [`onAgentStateChanged`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagentstatechanged) - [`onAgentListeningChanged`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagentlisteningchanged) - [`onAgentThinkingChanged`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagentthinkingchanged) - [`onAgentSpeakingChanged`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagentspeakingchanged) - [`onAgentInterrupted`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagentinterrupted) - [`onAgentMetrics`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagentmetrics) - [`onAgentError`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagenterror) **iOS** - [`addHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#addhandler) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#unsubscribemessage) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#destroy) - [`onAgentStateChanged`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagentstatechanged) - [`onAgentListeningChanged`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagentlisteningchanged) - [`onAgentThinkingChanged`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagentthinkingchanged) - [`onAgentSpeakingChanged`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagentspeakingchanged) - [`onAgentInterrupted`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagentinterrupted) - [`onAgentMetrics`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagentmetrics) - [`onAgentError`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagenterror) **Web** - [`IConversationalAIAPIEventHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#iconversationalaiapieventhandlers-interface) - [`EConversationalAIAPIEvents`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#econversationalaiapievents) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#unsubscribe) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#destroy) # Get runtime events (/en/ai/build/handle-runtime-events/get-runtime-events) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). This page explains how to receive runtime events from Conversational AI Engine. It compares the delivery paths so you can choose the one that fits your use case, or use both approaches together. You can receive runtime events through the following paths: - **Client toolkit**: for live, in-session interaction events - **Webhook**: for backend monitoring, durable records, and post-session processing The paths don't deliver identical events. Some events overlap semantically, but many are exclusive to one path. ## Event coverage | Runtime event | Client toolkit | Webhook | | ------------------------------------------------------------------- | -------------- | ------- | | Agent state changes such as `listening`, `thinking`, and `speaking` | Yes | No | | Interrupt events during a live session | Yes | No | | Module errors during a live session | Yes | Yes | | Runtime metrics and latency data | Yes | Yes | | Agent joined and left lifecycle records | No | Yes | | Conversation history after a session ends | No | Yes | | Telephony call state | No | Yes | | Debug logs and message-level client diagnostics | Yes | No | If you only need current UI state, use the client path. If you need monitoring, history, or backend analytics, use the webhook path. If you need live UX with production observability, use both. ## Choose how to receive events **Client toolkit** Use the client toolkit when the app must react during the current session. ### What you get - `onAgentStateChanged` - `onAgentListeningChanged` - `onAgentThinkingChanged` - `onAgentSpeakingChanged` - `onAgentInterrupted` - `onAgentMetrics` - `onAgentError` - `onTranscriptUpdated` - `onDebugLog` or `DEBUG_LOG` ### What you need - RTC integrated in the client - RTM enabled for the project - Authenticated RTC and RTM instances with lifecycle managed by your app ### How to receive events 1. Start the agent with RTM enabled. 2. Set `parameters.data_channel` to `rtm`. 3. Enable optional outputs such as metrics and error messages when needed. 4. Register toolkit event handlers. 5. Subscribe to channel messages before the session starts. ```json { "advanced_features": { "enable_rtm": true }, "parameters": { "data_channel": "rtm", "enable_metrics": true, "enable_error_message": true } } ``` This path is best for: - Updating in-call UI state - Reacting to interruptions - Surfacing errors immediately in the app - Observing client-side runtime behavior during live debugging For the full client setup and platform examples, see [Client-side events](event-notifications). **Webhook** Use webhooks when your backend must receive and persist runtime events. ### What you get - `101 agent joined` - `102 agent left` - `103 agent history` - `104 agent expire` - `110 agent error` - `111 agent metrics` - `112 turns finished` - `201 inbound call state` - `202 outbound call state` ### What you need - A public HTTPS callback endpoint - Access to the Agora Console project notification settings - Server-side storage for the generated secret ### How to receive events 1. Open the project's notification settings in Agora Console. 2. Choose the Conversational AI event types you want to subscribe to. 3. Configure your HTTPS callback URL. 4. Save the generated secret. 5. Verify `Agora-Signature` or `Agora-Signature-V2` on your server. 6. Return `200 OK` quickly after receiving the callback. This path is best for: - Alerting and dashboards - Session lifecycle records - Post-session history processing - Backend debugging and incident review - Turn and metric aggregation across many sessions For the full webhook setup, request format, and signature verification steps, see [Webhooks](webhooks). ## How to achieve your goals You can achieve some goals through either path; others work with only one: - **Status UI**: mainly client toolkit - **Errors**: client toolkit and webhook - **Performance**: client toolkit and webhook - **Debugging failures**: client toolkit for live reproduction, webhook for backend investigation - **Conversation history**: webhook and REST APIs, not client toolkit ## Related resources - If you want to understand what the webhook event numbers mean, see [Notification event types](../../reference/event-types). - If you want to decide which events to use for state, errors, and performance, see [Monitor agent status, errors, and performance](monitor-agent-runtime). - If you want to receive server-side webhook callbacks, see [Webhooks](webhooks). - If you want to investigate failures, see [Debug agent failures with runtime events](debug-agent-failures). - If you want post-session history and turn data, see [Retrieve conversation history after a session ends](retrieve-session-history). # Monitor agent status, errors, and performance (/en/ai/build/handle-runtime-events/monitor-agent-runtime) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). This page helps you choose the right path for common monitoring goals, then links you to the detailed setup guides. Runtime event handling on client apps usually serves one of the following goals: - Update the app UI according to the agent's current state - Capture errors and debug logs during a live session - Collect lifecycle and latency data on your server ## Choose a path for each goal | Goal | Best path | Use these events | | ----------------------------------------------------------- | --------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Update the in-call UI with the agent's current state | Toolkit callbacks in the client | `onAgentStateChanged`, `onAgentListeningChanged`, `onAgentThinkingChanged`, `onAgentSpeakingChanged` | | Handle interruptions during a live session | Toolkit callbacks in the client | `onAgentInterrupted` | | Show immediate failures in the app | Toolkit callbacks in the client | `onAgentError`, `onDebugLog` (Android), `DEBUG_LOG` (Web) | | Alert on agent failures from your backend | Webhooks | [`110 agent error`](../../reference/event-types#110-agent-error), [`102 agent left`](../../reference/event-types#102-agent-left) | | Monitor latency and runtime health | Toolkit for live UX, webhooks for aggregation | `onAgentMetrics`, [`111 agent metrics`](../../reference/event-types#111-agent-metrics) | | Track when sessions start and stop | Webhooks | [`101 agent joined`](../../reference/event-types#101-agent-joined), [`102 agent left`](../../reference/event-types#102-agent-left) | | Retrieve conversation history and turn data after a session | Webhooks or REST API | [`103 agent history`](../../reference/event-types#103-agent-history), [`112 turns finished`](../../reference/event-types#112-turns-finished), `history`, `turns` | ## Use client callbacks for live state and local debugging Use the toolkit when the event must arrive during the current session: - `onAgentStateChanged` is the main UI state callback for `silent`, `listening`, `thinking`, and `speaking`. - `onAgentListeningChanged`, `onAgentThinkingChanged`, and `onAgentSpeakingChanged` are better when you need separate loading, waveform, or avatar behaviors. - `onAgentInterrupted` is useful for turn-level UX, for example when you need to stop playback or show that a user barged in. - `onAgentError` is the primary callback for module failures such as LLM or TTS errors. - `onDebugLog` on Android and `DEBUG_LOG` on Web are useful when you want extra client-side diagnostics while reproducing issues. To receive these events, start the agent with RTM enabled and subscribe to channel messages before the session starts: ```json { "advanced_features": { "enable_rtm": true }, "properties": { "channel": "voice-demo" }, "parameters": { "data_channel": "rtm", "enable_metrics": true, "enable_error_message": true } } ``` For the first-step setup of both client and server paths, see [Get runtime events](get-runtime-events). For the full client integration flow, see [Client-side events](event-notifications). ## Use webhooks for durable monitoring and alerting Use webhook events when the data must leave the device and be available for dashboards, alerts, and post-session analysis: - `101 agent joined` confirms that the agent started successfully. - `102 agent left` tells you how the session ended, including failed or idle-timeout exits. - `103 agent history` and `112 turns finished` deliver post-session records for history, archiving, and turn analytics. - `104 agent expire` warns your backend that the agent's RTC token is about to expire. - `110 agent error` captures structured module errors with vendor-specific codes and messages. - `111 agent metrics` reports latency and other runtime metrics that are better suited to backend aggregation. If you need to answer questions such as why a session failed, which customers are seeing LLM errors, or how long TTS takes in production, webhook events are the better primary source. For the first-step setup of both client and server paths, see [Get runtime events](get-runtime-events). For the full server integration flow, setup steps, request headers, request body, and signature verification, see [Webhooks](webhooks). For complete webhook payloads, see [Notification event types](../../reference/event-types). ## Choose the right path for shared goals Some runtime goals are available through both client and server paths. Use the tabs below to choose the implementation that matches your use case. ### Errors **Client toolkit** Use client events when you need to react during the current session: - `onAgentError` for immediate module failures such as LLM or TTS errors - `onDebugLog` on Android and `DEBUG_LOG` on Web for local diagnostics during reproduction - UI updates, retries, graceful degradation, and session-local logging This path is best when the user is still in the call and the app needs to respond immediately. **Webhook** Use webhook events when you need durable backend observability: - [`110 agent error`](../../reference/event-types#110-agent-error) for structured module failures - [`102 agent left`](../../reference/event-types#102-agent-left) to understand whether the session terminated abnormally - Alerting, dashboards, incident review, and cross-session aggregation This path is best when the problem must be visible outside the current device or session. ### Performance **Client toolkit** Use `onAgentMetrics` when performance must shape the live experience: - Show current latency or quality indicators in the UI - React to degraded experience during the session - Compare what the user feels with what the client observes **Webhook** Use [`111 agent metrics`](../../reference/event-types#111-agent-metrics) when performance must be monitored over time: - Store metrics for dashboards and alerts - Compare cohorts by `labels` - Analyze regression patterns across sessions and environments ## Recommended monitoring pattern For most production apps, use both channels together: 1. Use toolkit callbacks to update the local UI and react during the live session. 2. Use webhooks to store durable records for alerts, analytics, and debugging. 3. Correlate both streams with shared fields such as `agent_id`, `name`, `channel`, `turn_id`, and `labels`. `labels` are especially useful when you want to group runtime data by customer segment, campaign, environment, or experiment. ## Related resources - [Debug agent failures with runtime events](debug-agent-failures) - [Retrieve conversation history after a session ends](retrieve-session-history) - [Get runtime events](get-runtime-events) - [Client-side events](event-notifications) - [Webhooks](webhooks) - [Notification event types](../../reference/event-types) - [Android toolkit API](/en/api-reference/api-ref/conversational-ai/client-toolkit/android) - [iOS toolkit API](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios) - [Web toolkit API](/en/api-reference/api-ref/conversational-ai/client-toolkit/web) # Retrieve conversation history (/en/ai/build/handle-runtime-events/retrieve-session-history) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). After a session ends, you may need to answer questions such as: - What did the user and agent say? - When did the session start and stop? - Which turn was slow or incomplete? Conversational AI Engine provides separate retrieval paths for pushed history, pulled history, and turn analytics. Choose the one that matches your needs. ## Choose the retrieval method | Goal | Best source | Use this | | --------------------------------------------------------- | ------------- | ------------------------------------------------------------------------------------------ | | Receive history automatically when the session ends | Webhook event | [`103 agent history`](../../reference/event-types#103-agent-history) | | Receive post-session turn data automatically | Webhook event | [`112 turns finished`](../../reference/event-types#112-turns-finished) | | Pull the agent's stored memory from your backend workflow | REST API | [`Retrieve agent history`](/en/api-reference/api-ref/conversational-ai/history) | | Analyze start, end, and latency for each turn | REST API | [`Query conversation turn information`](/en/api-reference/api-ref/conversational-ai/turns) | ## Use the history webhook for automatic delivery The [`103 agent history`](../../reference/event-types#103-agent-history) webhook event is the best fit when you want the platform to push session history to your server after the agent stops. This event includes: - `agent_id` - `name` - `channel` - `start_ts` - `stop_ts` - `contents` - `labels` Each `contents` item includes the message sender and content, which is enough for common transcript-style archiving and post-session review. For sessions that use `llm.vendor` set to `custom`, each `contents` item can also include speech timing fields: - `speech_start_ms`: Unix timestamp in milliseconds indicating when the user started speaking or the agent started TTS playback. - `speech_end_ms`: Unix timestamp in milliseconds indicating when the user stopped speaking, or when TTS playback completed or was interrupted. - `speech_algorithmic_delay`: Total delay in milliseconds introduced by audio processing algorithms after audio is captured from the user's microphone. This field is returned only when `contents[].role` is `user` and actual voice input is present. Use these timing fields when you need to align transcript entries with cloud recording audio or analyze the actual speech timeline. ## Use `112 turns finished` for pushed turn analytics [`112 turns finished`](../../reference/event-types#112-turns-finished) is the best fit when you want Agora to push conversation turn data after the session ends. This event includes turn start and end metadata, latency metrics, `total_turn_count`, and `is_truncated`, which help with post-session analysis and archiving. ## Use the history API when you need to pull data Use [`Retrieve agent history`](/en/api-reference/api-ref/conversational-ai/history) when: - Your backend needs to fetch history on demand - You need a pull-based workflow instead of webhook delivery - The session is still running and you want the current stored memory This path is often better for internal tools and admin workflows where users open a session record and fetch the latest stored memory explicitly. ## Use the turns API for diagnostics Use [`Query conversation turn information`](/en/api-reference/api-ref/conversational-ai/turns) when you care about turn lifecycle and timing more than message text. This API is the better choice for questions such as: - Which turn was slow? - Which turn ended abnormally? - How many turns completed successfully? If you need both transcript content and timing analysis, store the `103 agent history` event and query the turns API for deeper diagnostics. ## Set the history limit before you start the agent The number of stored history items in [`103 agent history`](../../reference/event-types#103-agent-history) depends on `llm.max_history` when you start the agent. The default is `32`. If your sessions are longer, increase that value when creating the agent: ```json { "llm": { "max_history": 64 } } ``` Choose a value that matches your retention and payload-size expectations. ## Recommended storage pattern When your server receives history after the session ends: 1. Store the raw `103` payload for traceability. 2. Index records by `agent_id`, `channel`, and `stop_ts`. 3. Preserve `labels` so you can filter by tenant, campaign, environment, or experiment. 4. Link the stored history to turn-level analytics from [`turns`](/en/api-reference/api-ref/conversational-ai/turns) when needed. ## Common decision rules Use these rules to quickly choose a retrieval option: - For immediate delivery when the session ends, use `103 agent history`. - For pushed turn data after the session ends, use `112 turns finished`. - For on-demand fetching, use the history API. - For timing and completion analysis, use the turns API. - For complete postmortems, combine all three. ## Related resources - [Monitor agent status, errors, and performance](monitor-agent-runtime) - [Get runtime events](get-runtime-events) - [Webhooks](webhooks) - [Notification event types](../../reference/event-types#103-agent-history) - [Keep conversation context across turns](../shape-the-conversation/short-term-memory) - [Retrieve agent history](/en/api-reference/api-ref/conversational-ai/history) - [Query conversation turn information](/en/api-reference/api-ref/conversational-ai/turns) # Handle webhook (/en/ai/build/handle-runtime-events/webhooks) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). A webhook is a user-defined HTTPS callback that lets your backend receive notifications when Conversational AI events occur. Agora sends POST requests to your webhook endpoint so your system can react to agent lifecycle changes, history delivery, errors, and performance metrics in real time. For the combined entry point that compares client toolkit and webhook delivery, see [Get runtime events](get-runtime-events). Use this page when you need durable backend records for monitoring, alerting, or analytics. If you need live UI state inside the app, use [Client-side events](event-notifications). ## Understand the tech Using Agora Console, you subscribe to specific events for your project and configure the URL of the webhook endpoint that receives them. Agora sends event notifications to that endpoint whenever the subscribed events occur. Your server verifies the request signature, processes the JSON payload, and returns `200 OK` to confirm receipt. ## Common uses Webhooks are typically used to: - Track when an agent joins or leaves a channel - Receive short-term memory history after an agent session ends - Capture module-level errors for monitoring and debugging - Collect performance metrics such as LLM and TTS latency ## Prerequisites Before you begin, make sure you have: - An Agora account - An active Agora project with Conversational AI enabled - A public HTTPS endpoint that can receive webhook callbacks - Server-side access to store and validate the secret used for signature verification ## Enable notifications To enable Agora notifications for Conversational AI: 1. Sign in to the [Agora Console](https://console.agora.io). 2. Open **Projects** and locate the target project. 3. Open the **Notifications** configuration area for the project. 4. Select the Conversational AI event types you want to subscribe to. 5. Enter the HTTPS callback URL of your receiving server. 6. Save the generated **Secret**. You need it for signature verification. 7. Run the console-side health check and confirm your server responds with `200 OK`. ### Recommended webhook endpoint settings - Use HTTPS only. - Enable HTTP keep-alive if possible. - Make sure your server responds within 10 seconds. ## Request header The header of notification callbacks contains the following fields: | Field name | Value | | -------------------- | ----------------------------------------------------- | | `Content-Type` | `application/json` | | `Agora-Signature` | Signature generated with the secret using HMAC/SHA1 | | `Agora-Signature-V2` | Signature generated with the secret using HMAC/SHA256 | ## Request body The request body of notification callbacks contains the following fields: | Field name | Type | Description | | ----------- | ----------- | ------------------------------------------------------------ | | `noticeId` | String | Notification ID that uniquely identifies this callback | | `productId` | Number | Product ID of the notification source | | `eventType` | Number | Type of event being notified | | `notifyMs` | Number | Unix timestamp in milliseconds when Agora sends the callback | | `payload` | JSON object | Event-specific data | The following example shows a sample request body: ```json { "noticeId": "2000001428:4330:107", "productId": 1, "eventType": 101, "notifyMs": 1611566412672, "payload": {} } ``` ## Conversational AI event types Agora can notify your server of the following Conversational AI events: | eventType | Description | | --------- | ----------------------------- | | `101` | Agent joined a channel | | `102` | Agent left a channel | | `103` | Dialogue history notification | | `110` | Agent error | | `111` | Agent performance metrics | | `201` | Incoming call status change | | `202` | Outgoing call status change | For payload details, see [Notification event types](../../reference/event-types). ## Signature verification To communicate securely between Agora and your webhook, Agora uses signatures for identity verification: 1. When you configure notifications in Agora Console, Agora generates a secret for your project. 2. When sending a notification, Agora generates `Agora-Signature` and `Agora-Signature-V2` values using HMAC/SHA1 and HMAC/SHA256. 3. When your server receives the callback, verify one of those signatures against the raw request body. The following Go example calculates a signature and compares it with the received value: ```go import ( "crypto/hmac" "crypto/sha1" "encoding/hex" "net/http" ) const secret = "" func calcSignatureV1(secret, payload string) string { mac := hmac.New(sha1.New, []byte(secret)) mac.Write([]byte(payload)) return hex.EncodeToString(mac.Sum(nil)) } func verify(requestBody, signature string) bool { calculatedSignature := calcSignatureV1(secret, requestBody) return calculatedSignature == signature } ``` After reading the request body in your handler, verify the signature: ```go if !verify(string(body), agoraSignature) { http.Error(w, "Invalid signature", http.StatusUnauthorized) return } ``` ## Best practices - Keep the webhook secret on the server side only. - Store raw payloads for troubleshooting when useful. - Design webhook processing to be idempotent, because retries can happen. - Return `200 OK` quickly and move heavier processing to async workers if needed. ## Related resources - [Monitor agent status, errors, and performance](monitor-agent-runtime) - [Debug agent failures with runtime events](debug-agent-failures) - [Retrieve conversation history after a session ends](retrieve-session-history) - [Client-side events](event-notifications) - [Notification event types](../../reference/event-types) - [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) - [Retrieve agent history](/en/api-reference/api-ref/conversational-ai/history) # Use managed mode (/en/ai/build/managed-mode) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Managed mode lets you use supported ASR, LLM, and TTS providers with Agora-managed credentials, without supplying your own API keys. You can use managed mode for any or all of the three provider categories. ## Prerequisites Before you begin, ensure that you have: - An Agora [account and project](/en/introduction/account). Conversational AI Engine is enabled by default for new projects. - A valid Agora app ID and app certificate. - For REST API only, one of the following to authenticate requests: - A customer ID and customer secret, to use [Basic HTTP authentication](/en/api-reference/api-ref/conversational-ai/authentication#basic-http-authentication). - A token generated from your app ID and app certificate, to use [token authentication](/en/api-reference/api-ref/conversational-ai/authentication#token-authentication). ## Understand the tech In managed mode, Agora supplies the credentials and endpoint configuration for the selected provider, so you do not need to provide your own API keys. You still need to identify the provider and model you want to use. You can also supply additional settings such as a system prompt, a specific voice ID, or keyword hints. You can enable managed mode independently for any combination of ASR, LLM, and TTS. To enable it for a category, set `credential_mode` to `"managed"` within its `asr`, `llm`, or `tts` block. Categories that omit `credential_mode` default to `"byok"`, which requires you to bring your own provider credentials. ## Start an agent using managed mode The following example starts an agent using Deepgram for ASR, OpenAI for LLM, and MiniMax for TTS, with no BYOK credentials required for any provider. **Python SDK** ```python from agora_agent import Agent, Agora, Area, DeepgramSTT, OpenAI, MiniMaxTTS client = Agora( area=Area.US, app_id='your-app-id', app_certificate='your-app-certificate', ) # Omit API keys to use Agora-managed models for ASR, LLM, and TTS. agent = ( Agent(client=client) .with_stt(DeepgramSTT(model='nova-3', language='en-US')) .with_llm(OpenAI( model='gpt-4o-mini', system_messages=[{'role': 'system', 'content': 'You are a helpful assistant.'}], greeting_message='Hello! How can I help you today?', failure_message='Sorry, I could not process your request.', max_history=32, )) .with_tts(MiniMaxTTS( model='speech_2_6_turbo', voice_id='English_captivating_female1', )) ) session = agent.create_session( name='my-managed-agent', channel='my-channel', agent_uid='1001', remote_uids=['1002'], idle_timeout=120, ) agent_id = session.start() print(f'Agent started: {agent_id}') ``` **TypeScript SDK** ```typescript import { Agent, AgoraClient, Area, DeepgramSTT, OpenAI, MiniMaxTTS } from 'agora-agents'; const client = new AgoraClient({ area: Area.US, appId: 'your-app-id', appCertificate: 'your-app-certificate', }); // Omit API keys to use Agora-managed models for ASR, LLM, and TTS. const agent = new Agent({ client }) .withStt(new DeepgramSTT({ model: 'nova-3', language: 'en-US' })) .withLlm(new OpenAI({ model: 'gpt-4o-mini', systemMessages: [{ role: 'system', content: 'You are a helpful assistant.' }], greetingMessage: 'Hello! How can I help you today?', failureMessage: 'Sorry, I could not process your request.', maxHistory: 32, })) .withTts(new MiniMaxTTS({ model: 'speech_2_6_turbo', voiceId: 'English_captivating_female1', })); const session = agent.createSession({ name: 'my-managed-agent', channel: 'my-channel', agentUid: '1001', remoteUids: ['1002'], idleTimeout: 120, }); const agentId = await session.start(); console.log('Agent started:', agentId); ``` **Go SDK** ```go package main import ( "context" "fmt" "log" Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" "github.com/AgoraIO/agora-agents-go/v2/option" ) func main() { ctx := context.Background() client := agentkit.NewAgoraClient(agentkit.AgoraClientOptions{ Area: option.AreaUS, AppID: "your-app-id", AppCertificate: "your-app-certificate", }) // Omit API keys to use Agora-managed models for ASR, LLM, and TTS. agent := agentkit.NewAgent(client).WithStt( vendors.NewDeepgramSTT(vendors.DeepgramSTTOptions{ Model: "nova-3", Language: "en-US", }), ).WithLlm( vendors.NewOpenAI(vendors.OpenAIOptions{ Model: "gpt-4o-mini", SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful assistant."}, }, GreetingMessage: "Hello! How can I help you today?", FailureMessage: "Sorry, I could not process your request.", MaxHistory: Agora.Int(32), }), ).WithTts( vendors.NewMiniMaxTTS(vendors.MiniMaxTTSOptions{ Model: "speech_2_6_turbo", VoiceID: "English_captivating_female1", }), ) session := agent.CreateSession(agentkit.CreateSessionOptions{ Name: "my-managed-agent", Channel: "my-channel", AgentUID: "1001", RemoteUIDs: []string{"1002"}, IdleTimeout: Agora.Int(120), }) agentID, err := session.Start(ctx) if err != nil { log.Fatal(err) } fmt.Println("Agent started:", agentID) } ``` **REST API** Set `credential_mode` to `"managed"` inside each provider block and include the required diagnostic parameters. You can use managed mode for any or all provider categories independently. ```bash curl --request POST \ --url https://api.agora.io/api/conversational-ai-agent/v2/projects//join \ --header 'Authorization: agora token=""' \ --header 'Content-Type: application/json' \ --data '{ "name": "my-managed-agent", "properties": { "channel": "my-channel", "token": "", "agent_rtc_uid": "1001", "remote_rtc_uids": ["1002"], "idle_timeout": 120, "asr": { "credential_mode": "managed", "vendor": "deepgram", "params": { "url": "wss://api.deepgram.com/v1/listen", "model": "nova-3", "language": "en-US", "keyterm": "agora" } }, "llm": { "credential_mode": "managed", "vendor": "openai", "style": "openai", "url": "https://api.openai.com/v1/chat/completions", "params": { "model": "gpt-4.1-mini" }, "system_messages": [ { "role": "system", "content": "You are a helpful assistant." } ], "greeting_message": "Hello! How can I help you today?", "failure_message": "Sorry, I could not process your request.", "max_history": 32 }, "tts": { "credential_mode": "managed", "vendor": "minimax", "params": { "url": "wss://api.minimax.io/ws/v1/t2a_v2", "model": "speech-2.6-turbo", "voice_setting": { "voice_id": "English_captivating_female1" } } } } }' ``` In this example: - `credential_mode: "managed"` is set on each provider block. Agora supplies the credentials for each category. - The `asr` block uses Deepgram Nova 3 with a keyword hint. - The `llm` block uses OpenAI GPT-4.1 Mini with a system prompt, greeting, and history length. - The `tts` block uses MiniMax Speech 2.6 Turbo with a voice selection override. ## Supported vendors The following vendors and models are available in managed mode. ### ASR | Vendor | Models | | -------------------------------------- | ------------------- | | [ARES](/en/ai/models/asr/ares) | Built-in ASR engine | | [Deepgram](/en/ai/models/asr/deepgram) | `nova-2`, `nova-3` | ### LLM | Vendor | Models | | ---------------------------------- | --------------------------------------------------------- | | [OpenAI](/en/ai/models/llm/openai) | `gpt-4o-mini`, `gpt-4.1-mini`, `gpt-5-nano`, `gpt-5-mini` | ### TTS | Vendor | Models | | ------------------------------------------ | -------------------------------------- | | [Cartesia](/en/ai/models/tts/cartesia) | `sonic-3.5`, `sonic-3.6` | | [Fish Audio](/en/ai/models/tts/fish-audio) | `s2.1-pro` | | [MiniMax](/en/ai/models/tts/minimax) | `speech-2.6-turbo`, `speech-2.8-turbo` | | [OpenAI](/en/ai/models/tts/openai) | `tts-1` | ## Reference For the full list of request parameters, see [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). For provider-specific configuration options available within [`asr`](/en/ai/models/asr/deepgram), [`llm`](/en/ai/models/llm/openai), and [`tts`](/en/ai/models/tts/minimax) fields, see the relevant provider page. # Send images to the agent (/en/ai/build/send-multimodal-messages) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). When interacting with an agent, you may need to upload images or send image messages from the client to help the agent better understand the user's intent. This page describes how to use the Conversational AI Engine toolkit to send image messages to the large language model from your app. The LLM can then automatically reference the image content in subsequent conversations and generate more relevant responses. ## Understand the tech Agora provides a flexible, scalable, and standardized conversational AI engine toolkit. The toolkit supports **iOS**, **Android**, and **Web** platforms, and encapsulates scenario-based APIs. You can use these APIs to integrate the capabilities of the [Agora Signaling SDK](/en/realtime-media/rtm) and [Agora RTC SDK](../../realtime-media/rtc/get-started-sdk) to enable the following features: - [Interrupt agents](shape-the-conversation/interrupt-agent) - [Display live transcripts](transcripts) - [Client-side events](handle-runtime-events/event-notifications) - [Set optimal audio parameters](../best-practices/audio-setup) for iOS and Android - [Send picture messages](send-multimodal-messages) Call the toolkit's `chat` API to send a picture message, and listen to `onMessageReceiptUpdated` to receive the picture message receipt. ## Prerequisites Before you begin, ensure the following: - You have implemented the Conversational AI Engine [quickstart](../get-started/quickstart). - Your app integrates Agora RTC SDK v4.5.1 or later and includes the [RTC SDK quickstart](../../realtime-media/rtc/get-started-sdk). - You have enabled Signaling in the Agora Console and completed the [Signaling quickstart](/en/realtime-media/rtm/quickstart) for basic messaging. - You maintain active and authenticated RTC and Signaling instances that persist beyond the component lifecycle. The toolkit does not manage RTC or Signaling initialization, lifecycle, or authentication. > **Info** > > - Picture messaging is currently in beta and free for a limited time. > - Image processing depends on the capabilities of the integrated LLM. Make sure the LLM you connect to Conversational AI Engine supports image input. ## Implementation This section explains how to send a picture message from your app. **Android** 1. **Integrate the toolkit** Add the toolkit to your project using Maven or source code. See [Install the Android toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#installation). Refer to [Folder structure](#reference) to understand the role of each file. 2. **Create a toolkit instance** Create a configuration object with the RTC SDK and Signaling engine instances. Use the configuration to create a toolkit instance. ```kotlin // Create configuration objects for the RTC and RTM instances val config = ConversationalAIAPIConfig( rtcEngine = rtcEngine, rtmClient = rtmClient, renderMode = TranscriptRenderMode.Word, enableLog = true, enableRenderModeFallback = true ) // Create component instance val api = ConversationalAIAPIImpl(config) ``` 3. **Register callback** ```kotlin api.addHandler(covEventHandler) ``` 4. **Subscribe to the channel** Agent-related events are delivered through Signaling channel messages. To receive these events, call `subscribeMessage` before starting the agent session. ```kotlin api.subscribeMessage("channelName") { error -> if (error != null) { // Handle error } } ``` 5. **Add a conversational AI agent to the channel** To [start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), configure the following parameters in your `POST` request: | Parameter | Description | Required | | --------------------------------------- | -------------------------------------------------- | -------- | | `advanced_features.enable_rtm: true` | Starts the Signaling service | Yes | | `parameters.data_channel: "rtm"` | Enables Signaling as the data transmission channel | Yes | | `parameters.enable_metrics: true` | Enables agent performance data collection | Optional | | `parameters.enable_error_message: true` | Enables reporting of agent error events | Optional | After a successful response, the agent joins the specified RTC channel and is ready to interact with the user. 6. **Send an image** ```kotlin val uuid = "unique-image-id-123" val imageUrl = "https://example.com/image.jpg" api.chat("agentUserId", ImageMessage(uuid = uuid, imageUrl = imageUrl)) { error -> if (error != null) { Log.e("Chat", "Failed to send image: ${error.errorMessage}") } else { Log.d("Chat", "Image send request successful") } } ``` > **Info** > > The `chat` completion callback only indicates whether the sending request is successful, and does not reflect the actual processing status of the message. 7. **Handle image sending status** Image send success is confirmed by `onMessageReceiptUpdated`. If sending fails, `onMessageError` is triggered. Use the `uuid` value in the callback to identify the uploaded picture. Image sent successfully: ```kotlin override fun onMessageReceiptUpdated(agentUserId: String, receipt: MessageReceipt) { if (receipt.chatMessageType == ChatMessageType.Image) { try { val json = JSONObject(receipt.message) if (json.has("uuid")) { val receivedUuid = json.getString("uuid") if (receivedUuid == "your-sent-uuid") { Log.d("ImageSend", "Image sent successfully: $receivedUuid") } } } catch (e: Exception) { Log.e("ImageSend", "Failed to parse message receipt: ${e.message}") } } } ``` Image sending failed: ```kotlin override fun onMessageError(agentUserId: String, error: MessageError) { if (error.chatMessageType == ChatMessageType.Image) { try { val json = JSONObject(error.message) if (json.has("uuid")) { val failedUuid = json.getString("uuid") if (failedUuid == "your-sent-uuid") { Log.e("ImageSend", "Image send failed: $failedUuid") } } } catch (e: Exception) { Log.e("ImageSend", "Failed to parse error message: ${e.message}") } } } ``` 8. **Unsubscribe from the channel** ```kotlin api.unsubscribeMessage("channelName") { error -> if (error != null) { // Handle the error } } ``` 9. **Release resources** ```kotlin api.destroy() ``` **iOS** 1. **Integrate the toolkit** Add the toolkit to your project using CocoaPods, Swift Package Manager, or source code. See [Install the iOS toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#installation). Refer to [Folder structure](#reference) to understand the role of each file. 2. **Create a toolkit instance** Create a configuration object with the RTC SDK and Signaling engine instances, then use the configuration to create a toolkit instance. ```swift let config = ConversationalAIAPIConfig( rtcEngine: rtcEngine, rtmEngine: rtmEngine, renderMode: .words, enableLog: true, enableRenderModeFallback: true ) convoAIAPI = ConversationalAIAPIImpl(config: config) ``` 3. **Subscribe to the channel** Agent-related events are delivered through Signaling channel messages. To receive these events, call `subscribeMessage` before starting the agent session. ```swift convoAIAPI.subscribeMessage(channelName: channelName) { error in if let error = error { print("Subscription failed: \(error.message)") } else { print("Subscription successful") } } ``` 4. **Register callback** ```swift convoAIAPI.addHandler(handler: self) ``` 5. **Add a conversational AI agent to the channel** To [start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), configure the following parameters in your `POST` request: | Parameter | Description | Required | | --------------------------------------- | -------------------------------------------------- | -------- | | `advanced_features.enable_rtm: true` | Starts the Signaling service | Yes | | `parameters.data_channel: "rtm"` | Enables Signaling as the data transmission channel | Yes | | `parameters.enable_metrics: true` | Enables agent performance data collection | Optional | | `parameters.enable_error_message: true` | Enables reporting of agent error events | Optional | 6. **Send an image** ```swift let uuid = UUID().uuidString let imageUrl = "https://example.com/image.jpg" let message = ImageMessage(uuid: uuid, url: imageUrl) self.convoAIAPI.chat(agentUserId: "\(agentUid)", message: message) { [weak self] error in if let error = error { print("send image failed, error: \(error.message)") } else { print("send image success") } } ``` > **Info** > > The `chat` completion callback only indicates whether the sending request is successful, and does not reflect the actual processing status of the message. 7. **Receive image sending response** Success is confirmed by `onMessageReceiptUpdated`. If sending fails, `onMessageError` is triggered. Image sent successfully: ```swift struct PictureInfo: Codable { let uuid: String } public func onMessageReceiptUpdated(agentUserId: String, messageReceipt: MessageReceipt) { if messageReceipt.type == .context { guard let messageData = messageReceipt.message.data(using: .utf8) else { return } do { let imageInfo = try JSONDecoder().decode(PictureInfo.self, from: messageData) self.messageView.viewModel.updateImageMessage(uuid: imageInfo.uuid, state: .success) } catch { print("Failed to decode PictureInfo: \(error)") } } } ``` Image sending failed: ```swift struct ImageUploadError: Codable { let code: Int let message: String } struct ImageUploadErrorResponse: Codable { let uuid: String let success: Bool let error: ImageUploadError? } public func onMessageError(agentUserId: String, error: MessageError) { if let messageData = error.message.data(using: .utf8) { do { let errorResponse = try JSONDecoder().decode(ImageUploadErrorResponse.self, from: messageData) if !errorResponse.success { DispatchQueue.main.async { [weak self] in self?.messageView.viewModel.updateImageMessage(uuid: errorResponse.uuid, state: .failed) } } } catch { addLog("Failed to parse error message JSON: \(error)") } } } ``` 8. **Unsubscribe from the channel** ```swift convoAIAPI.unsubscribeMessage(channelName: channelName) { error in if let error = error { print("Unsubscription failed: \(error.message)") } else { print("Unsubscribed successfully") } } ``` 9. **Release resources** ```swift convoAIAPI.destroy() ``` **Web** 1. **Integrate the toolkit** Add the toolkit to your project using a package manager or source code. See [Install the Web toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#installation). Refer to [Folder structure](#reference) to understand the role of each file. 2. **Create a toolkit instance** Before joining an RTC channel, create RTC SDK and Signaling engine instances and pass them into the toolkit instance. ```ts const config: IConversationalAIAPIConfig = { rtcEngine, rtmEngine, renderMode: ETranscriptHelperMode.WORD, enableLog: true, enableRenderModeFallback: true, } const conversationalAIAPI = await ConversationalAIAPI.init(config) ``` 3. **Subscribe to the channel** Agent-related events are delivered through Signaling messages. Before starting an agent session, call `subscribeMessage` to receive these events. ```ts conversationalAIAPI.subscribeMessage(channel_name) ``` 4. **Register callbacks** ```ts conversationalAIAPI.on(EConversationalAIAPIEvents.MESSAGE_RECEIPT_UPDATED, handleMessageReceiptUpdated) conversationalAIAPI.on(EConversationalAIAPIEvents.MESSAGE_ERROR, onAgentError) ``` 5. **Add a conversational AI agent to the channel** To [start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), configure the following parameters in your `POST` request: | Parameter | Description | Required | | --------------------------------------- | -------------------------------------------------- | -------- | | `advanced_features.enable_rtm: true` | Starts the Signaling service | Yes | | `parameters.data_channel: "rtm"` | Enables Signaling as the data transmission channel | Yes | | `parameters.enable_metrics: true` | Enables agent performance data collection | Optional | | `parameters.enable_error_message: true` | Enables reporting of agent error events | Optional | 6. **Send an image** ```ts import { EChatMessageType } from '@/conversational-ai-api/type' await conversationalAIAPI.chat(`${agent_rtc_uid}`, { messageType: EChatMessageType.IMAGE, url: 'https://example.com/image.jpg', uuid: genUUID() }) ``` > **Info** > > The `chat` completion callback only indicates whether the sending request is successful, and does not reflect the actual processing status of the message. 7. **Receive image sending response** Image sent successfully: ```ts conversationalAIAPI.on(EConversationalAIAPIEvents.MESSAGE_RECEIPT_UPDATED, (agentUserId: string, messageReceipt: TMessageReceipt) => { if (messageReceipt.moduleType !== EModuleType.CONTEXT) { return } try { const receiptMessage = JSON.parse(messageReceipt.message) const uuid = receiptMessage.uuid if (!uuid) return console.log(`Message sent successfully, UUID: ${uuid}`) } catch (error) { console.error('Failed to parse message:', error) } }) ``` Image sending failed: ```ts conversationalAIAPI.on(EConversationalAIAPIEvents.MESSAGE_ERROR, (agentUserId, error) => { console.error(`Message error for agent ${agentUserId}:`, error) if (error.type === EChatMessageType.IMAGE) { try { const errorData = JSON.parse(error.message) if (errorData?.uuid) { console.warn(`Image error for agent ${agentUserId} with UUID: ${errorData.uuid}`) } } catch (e) { console.error(`Failed to handle image error for agent ${agentUserId}:`, e) } } }) ``` 8. **Unsubscribe from the channel** ```ts conversationalAIAPI.unsubscribeMessage(channel_name) ``` 9. **Release resources** ```ts conversationalAIAPI.destroy() ``` ## Reference This section contains supporting information that completes the guidance on this page. **Android** **Folder structure** - `IConversationalAIAPI.kt`: API interface, related data structures, and enumerations - `ConversationalAIAPIImpl.kt`: main implementation logic - `ConversationalAIUtils.kt`: utility functions and callback management - `v3/` - `TranscriptionController.kt`: transcript rendering and synchronization - `MessageParser.kt`: transcription and message parsing **API reference** - [`addHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#addhandler) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#unsubscribemessage) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#destroy) - [`onMessageReceiptUpdated`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onmessagereceiptupdated) - [`onMessageError`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onmessageerror) - [`chat`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#chat) **iOS** **Folder structure** - `ConversationalAIAPI.swift`: API interface, data structures, and enumerations - `ConversationalAIAPIImpl.swift`: main implementation logic - `Transcription/` - `TranscriptionController.swift`: transcript rendering and transcription control **API reference** - [`addHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#addhandler) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#unsubscribemessage) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#destroy) - [`onMessageReceiptUpdated`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onmessagereceiptupdated) - [`onMessageError`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onmessageerror) - [`chat`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#chat) **Web** **Folder structure** - `index.ts`: main API class - `type.ts`: API interfaces, data structures, and enumerations - `utils/` - `index.ts`: general utility functions - `events.ts`: event management - `sub-render.ts`: transcript rendering module **API reference** - [`IConversationalAIAPIEventHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#iconversationalaiapieventhandlers-interface) - [`EConversationalAIAPIEvents`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#econversationalaiapievents) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#unsubscribe) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#destroy) - [`chat`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#chat) # Improve ASR accuracy with keywords (/en/ai/build/shape-the-conversation/asr-keywords) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). In a conversational AI scenario, users may say non-dictionary words such as brand names, product names, personal names, place names, or industry-specific terms. You can configure ASR keywords when starting a conversational AI agent to improve ARES's recognition accuracy for these terms. ## Prerequisites Before you start, make sure you have: - Implemented the basic logic for talking with an agent, as described in [Quickstart](../../get-started/quickstart). - If you configure keywords through the Agent SDK, installed Agent SDK `v2.6.0` or later. ## Implementation The following examples show how to configure ASR keywords for ARES using the Agent SDK or the REST API. **Python SDK** Pass a list of keywords to `AresSTT`'s `keywords` parameter: ```python from agora_agent.agentkit.vendors import AresSTT agent = agent.with_stt( AresSTT( keywords=[ 'Agora', 'Conversational AI', 'RTC', ], ) ) ``` **TypeScript SDK** Pass a list of keywords to the `AresSTT` constructor's `keywords` option: ```typescript import { AresSTT } from 'agora-agents'; const agentWithKeywords = agent.withStt( new AresSTT({ keywords: [ 'Agora', 'Conversational AI', 'RTC', ], }) ); ``` **Go SDK** Pass a list of keywords to `AresSTTOptions.Keywords`: ```go agent := agentkit.NewAgent(client).WithStt( vendors.NewAresSTT(vendors.AresSTTOptions{ Keywords: []string{ "Agora", "Conversational AI", "RTC", }, }), ) ``` **REST API** When you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), pass a list of keywords in the request body's `properties.asr.keywords` field: ```json { "asr": { "language": "en-US", "vendor": "ares", "keywords": [ "Agora", "Conversational AI", "RTC" ] } } ``` > **Info** > > - With the REST API, you can only set `properties.asr.keywords` when you use ARES or when `properties.asr.vendor` is not set. > - Setting keywords while explicitly using another ASR vendor causes the request to fail. > - You can configure up to 128 keywords. ## ASR keywords versus keyword interruption ASR keywords and keyword interruption are separate features that each use their own list of keywords: | Feature | Configuration field | Purpose | | :------------------- | :--------------------------------------------------------- | :-------------------------------------------------------------------------------------------------------------------- | | ASR keywords | `properties.asr.keywords` | Improves speech recognition accuracy for specific terms. | | Keyword interruption | `properties.interruption.keywords_config.trigger_keywords` | Interrupts the agent when the user says a specified keyword. See [Interrupt the agent mid-response](interrupt-agent). | ## Best practices - Prioritize configuring brand names, product names, personal names, place names, model numbers, and abbreviations that are prone to misrecognition. - Avoid configuring too many common words, short words, or overly generic terms, such as "okay" or "start." - For mixed-language scenarios, you can configure terms in multiple languages together, such as a product's name in its local language, its English name, and its abbreviation. - Validate recognition results with real production audio before going live, and check both the target keywords and similar-sounding words. # Pass information to the agent (/en/ai/build/shape-the-conversation/custom-information) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). When interacting with a conversational AI agent, you can transmit custom context information from the client, such as the user's speaking status, selected text, personal signature, or score, enabling the agent to generate responses tailored to the user's needs. This document explains how to use the capabilities of the [Signaling SDK](/en/realtime-media/rtm) to include custom information in interactions with the conversational AI agent. ## Understand the tech [Agora Signaling SDK](/en/realtime-media/rtm) allows users in a channel to set custom temporary status information and notifies other online users in the channel through event notifications. If your app integrates both the Voice SDK and Signaling services, you can leverage Signaling features when creating a conversational AI agent. This allows the agent to retrieve temporary status information from the Signaling channel before invoking the LLM. The information is used as context to guide the agent in generating responses that better align with user needs. ## Prerequisites - Implemented the basic logic for interacting with a conversational AI agent by following the [Quickstart](../../get-started/quickstart). - Integrated the Signaling SDK into your app and implemented basic messaging functionality by following the [Signaling SDK Quickstart](/en/realtime-media/rtm/quickstart). ## Implementation Take the following steps to transmit custom context information from the client to the LLM. ### Enable Signaling To enable Signaling integration, set `advanced_features.enable_rtm` to `true` in the [POST request](/en/api-reference/api-ref/conversational-ai/join) when creating a conversational AI agent. Refer to the following sample request: **Python SDK** ```python # ... other agent configuration ... .with_advanced_features({'enable_rtm': True}) # ... continue with .create_session() ... ``` **TypeScript SDK** ```typescript // ... other agent configuration ... .withAdvancedFeatures({ enable_rtm: true }) // ... continue with .createSession() ... ``` **Go SDK** ```go // ... other agent configuration ... .WithAdvancedFeatures(&agentkit.AdvancedFeatures{ EnableRtm: Agora.Bool(true), }) // ... continue with .CreateSession() ... ``` **REST API** ```bash curl --request post \ --url https://api.agora.io/api/conversational-ai-agent/v2/projects//join \ --header 'Authorization: Basic ' \ --data ' { "name": "unique_name", "properties": { "channel": "channel_name", "token": "token", "agent_rtc_uid": "friday", "advanced_features": { "enable_rtm": true }, "remote_rtc_uids": [ "*" ], "enable_string_uid": true, "llm": { "url": "https://api.openai.com/v1/chat/completions", "api_key": "", "params": { "model": "gpt-4o-mini" } }, "tts": { "vendor": "microsoft", "params": { "key": "", "voice_id": "en-US-AndrewMultilingualNeural" } } } }' ``` ### Set Custom Information Refer to Signaling [User status management](/en/realtime-media/rtm/build/manage-presence-and-metadata/presence#user-status-management) to set status information for users in the channel. ### Transmit Custom Information Before invoking the LLM, the agent automatically retrieves the active user's temporary status information and transmits it as context to the model. This temporary status information is stored in the `context.presence` field. The following example illustrates a scenario where UserA selects the text "Pythagorean theorem" in the app and asks the agent, "What does this mean?". The JSON example shows how the agent retrieves a temporary status field named `selection` from Signaling before calling the LLM. The request structure is as follows: ```json { "messages": [ { "role": "user", "content": "What does this mean?" } ], "context": { "presence": { "userA": { "selection": "Pythagorean Theorem" } } }, "model": "openai" } ``` ### LLM Adaptation Adapt the LLM to process the temporary status information in the `context.presence` field and generate content that better meets user needs. For implementation details, refer to the [Custom LLM](../custom-model-integration/custom-llm) documentation. # Talking while waiting (/en/ai/build/shape-the-conversation/filler-words) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). In conversational AI, delays in LLM responses may cause users to wonder if the agent is still processing, repeat their question, or disengage entirely. Filler words address this by playing short phrases while the agent waits for the LLM to generate a response. This keeps the conversation flowing, reduces user anxiety, and creates a more human-like interaction. Common use cases for filler words include: - **MCP tool calls**: When the agent invokes tools through an [MCP server](../tools/mcp-tools), response times can increase significantly. Filler words bridge this gap while the agent waits for tool results. - **Complex queries**: Queries that require more LLM processing time benefit from a brief acknowledgment to signal that the agent is working on a response. - **Customer service scenarios**: In support interactions, filler words such as "Let me look into that for you" reassure users that their request is being handled. ## Understand the tech You configure filler words as part of the agent's configuration. Their behavior depends on the content mode you choose and how the engine times playback against the main LLM response. ### Filler word modes Specify where filler word content comes from: - **Static** (default): Selects a phrase from a predefined list. This is also the behavior when no mode is set. - **Generated**: Dynamically generates a filler phrase from the recent conversation. You can use only the message that triggered the current turn or widen the window to multiple recent messages. If generation doesn't produce a usable phrase in time, the agent plays a static phrase instead. > **Info** > > Generated mode must be set explicitly, and you still need to configure a static fallback list. The filler-word generation service is Agora-hosted, and you don't need to configure an additional model, endpoint, or credentials. ### Filler word selection and playback For qualifying speech input or a [custom instruction](/en/api-reference/api-ref/conversational-ai/think), the engine starts the main LLM request and dynamic filler word generation at the same time: 1. If the main LLM produces playable content before the response wait threshold elapses, the agent plays the main reply directly, without playing a filler word. 2. If the main LLM is still waiting when the threshold elapses and a dynamic filler word is already ready, the agent plays the dynamic filler word. 3. If the dynamic filler word isn't ready, generation failed, or the content is invalid, the agent plays a static fallback filler word instead. The same fallback applies when the current message has no usable text, the engine can't locate the current message, or the input exceeds the effective capacity of the hosted generation model. 4. Playing a filler word doesn't cancel, discard, or restart the main LLM request. The agent continues into the main reply once it's ready. The agent plays at most one filler word per turn. A dynamic filler word that arrives late doesn't replace content that's already been selected, and it doesn't trigger a second playback. Prefetch turns don't trigger filler words. When you use static mode, or don't set a mode, the engine doesn't start dynamic filler word generation at all. Once the main LLM's wait time reaches the response wait threshold, the agent selects and plays a static phrase directly. ## Prerequisites - Use the [Agora CLI](/en/introduction/agora-cli) to create or select an Agora project, and verify project readiness: ```bash agora login agora project create conv-ai-tutorial agora project use conv-ai-tutorial agora project doctor ``` - Implemented the basic logic for interacting with a conversational AI agent by following the [quickstart](../../get-started/quickstart). ## Implementation Configure static or generated filler words, depending on the mode you want to use. ### Configure static filler words The following example configures filler words to play a random phrase when the LLM takes longer than 1.5 seconds to respond: **Python SDK** ```python from agora_agent import ( FillerWordsConfig, FillerWordsContent, FillerWordsContentStaticConfig, FillerWordsTrigger, FillerWordsTriggerFixedTimeConfig, ) # ... other agent configuration ... .with_filler_words(FillerWordsConfig( enable=True, trigger=FillerWordsTrigger( fixed_time_config=FillerWordsTriggerFixedTimeConfig(response_wait_ms=1500), ), content=FillerWordsContent( mode='static', static_config=FillerWordsContentStaticConfig( phrases=[ 'Let me look into that.', 'One moment, please.', 'Sure, give me a second.', 'Hmmm, let me check.', ], selection_rule='shuffle', ), ), )) ``` **TypeScript SDK** ```typescript import type { FillerWordsConfig } from 'agora-agents'; const fillerWords: FillerWordsConfig = { enable: true, trigger: { fixed_time_config: { response_wait_ms: 1500 }, }, content: { mode: 'static', static_config: { phrases: [ 'Let me look into that.', 'One moment, please.', 'Sure, give me a second.', 'Hmmm, let me check.', ], selection_rule: 'shuffle', }, }, }; // ... other agent configuration ... .withFillerWords(fillerWords); ``` **Go SDK** ```go fillerWords := &agentkit.FillerWordsConfig{ Enable: Agora.Bool(true), Trigger: &agentkit.FillerWordsTrigger{ FixedTimeConfig: &agentkit.FillerWordsTriggerFixedTimeConfig{ ResponseWaitMs: Agora.Int(1500), }, }, Content: &agentkit.FillerWordsContent{ Mode: agentkit.FillerWordsContentModeStatic.Ptr(), StaticConfig: &agentkit.FillerWordsContentStaticConfig{ Phrases: []string{ "Let me look into that.", "One moment, please.", "Sure, give me a second.", "Hmmm, let me check.", }, SelectionRule: agentkit.FillerWordsSelectionRuleShuffle.Ptr(), }, }, } // ... other agent configuration ... WithFillerWords(fillerWords) ``` **REST API** Add the following `filler_words` object to `properties` in your [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) request body: ```json "filler_words": { "enable": true, "trigger": { "fixed_time_config": { "response_wait_ms": 1500 } }, "content": { "mode": "static", "static_config": { "phrases": [ "Let me look into that.", "One moment, please.", "Sure, give me a second.", "Hmmm, let me check." ], "selection_rule": "shuffle" } } } ``` **Field reference** | Parameter | Type | Required | Description | | -------------------------------------------- | --------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | | `enable` | Boolean | No | Whether to enable filler words. Requires `content.static_config` when set to `true`. Defaults to `false`. | | `trigger.fixed_time_config.response_wait_ms` | Integer | No | LLM response wait threshold in milliseconds, from `100` to `10000`. Defaults to `1500`. | | `content.mode` | String | No | Content mode. Set to `static` or omit for static filler words. Defaults to `static`. | | `content.static_config` | Object | Yes | Static filler word configuration. Required whenever filler words are enabled. | | `content.static_config.phrases` | Array of String | Yes | List of static filler words. Supports 1 to 100 non-empty strings, each up to 20 words or 20 non-Latin characters. | | `content.static_config.selection_rule` | String | No | Selection rule for choosing phrases. Accepts `shuffle` or `round_robin`. Defaults to `shuffle`. | The static phrase list supports 1 to 100 non-empty strings. Each phrase supports up to 20 words (Latin scripts) or 20 characters (Chinese and other non-Latin scripts). Choose a response wait threshold based on your use case: - **Lower values** (500-1000 ms): Better for fast-paced interactions where silence is more noticeable. - **Higher values** (1500-3000 ms): Suitable for scenarios where users expect some processing time, such as complex queries or data lookups. ### Configure generated filler words Set the content mode to generated, and keep a static fallback configured: **Python SDK** ```python from agora_agent import ( FillerWordsConfig, FillerWordsContent, FillerWordsContentGeneratedConfig, FillerWordsContentStaticConfig, FillerWordsTrigger, FillerWordsTriggerFixedTimeConfig, ) # ... other agent configuration ... .with_filler_words(FillerWordsConfig( enable=True, trigger=FillerWordsTrigger( fixed_time_config=FillerWordsTriggerFixedTimeConfig(response_wait_ms=1500), ), content=FillerWordsContent( mode='generated', static_config=FillerWordsContentStaticConfig( phrases=['Let me look into that.', "I'm on it."], selection_rule='shuffle', ), generated_config=FillerWordsContentGeneratedConfig( prompt='Generate a short, natural filler phrase indicating you are processing the request. Do not answer the question directly.', context_message_limit=4, history_character_limit=1000, ), ), )) ``` **TypeScript SDK** ```typescript import type { FillerWordsConfig } from 'agora-agents'; const fillerWords: FillerWordsConfig = { enable: true, trigger: { fixed_time_config: { response_wait_ms: 1500 }, }, content: { mode: 'generated', static_config: { phrases: ['Let me look into that.', "I'm on it."], selection_rule: 'shuffle', }, generated_config: { prompt: 'Generate a short, natural filler phrase indicating you are processing the request. Do not answer the question directly.', context_message_limit: 4, history_character_limit: 1000, }, }, }; // ... other agent configuration ... .withFillerWords(fillerWords); ``` **Go SDK** ```go fillerWords := &agentkit.FillerWordsConfig{ Enable: Agora.Bool(true), Trigger: &agentkit.FillerWordsTrigger{ FixedTimeConfig: &agentkit.FillerWordsTriggerFixedTimeConfig{ ResponseWaitMs: Agora.Int(1500), }, }, Content: &agentkit.FillerWordsContent{ Mode: agentkit.FillerWordsContentModeGenerated.Ptr(), StaticConfig: &agentkit.FillerWordsContentStaticConfig{ Phrases: []string{"Let me look into that.", "I'm on it."}, SelectionRule: agentkit.FillerWordsSelectionRuleShuffle.Ptr(), }, GeneratedConfig: &agentkit.FillerWordsContentGeneratedConfig{ Prompt: Agora.String("Generate a short, natural filler phrase indicating you are processing the request. Do not answer the question directly."), ContextMessageLimit: Agora.Int(4), HistoryCharacterLimit: Agora.Int(1000), }, }, } // ... other agent configuration ... WithFillerWords(fillerWords) ``` **REST API** Add the following `filler_words` object to `properties` in your [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) request body: ```json "filler_words": { "enable": true, "trigger": { "fixed_time_config": { "response_wait_ms": 1500 } }, "content": { "mode": "generated", "static_config": { "phrases": [ "Let me look into that.", "I'm on it." ], "selection_rule": "shuffle" }, "generated_config": { "prompt": "Generate a short, natural filler phrase indicating you are processing the request. Do not answer the question directly.", "context_message_limit": 4, "history_character_limit": 1000 } } } ``` **Field reference** | Parameter | Type | Required | Description | | -------------------------------------------------- | --------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `enable` | Boolean | No | Whether to enable filler words. Requires a static fallback phrase list when set to `true`. Defaults to `false`. | | `trigger.fixed_time_config.response_wait_ms` | Integer | No | LLM response wait threshold in milliseconds, from `100` to `10000`. Defaults to `1500`. | | `content.mode` | String | Yes | Set to `generated` to enable generated filler words. | | `content.static_config` | Object | Yes | Static fallback configuration. Used whenever the generated filler word isn't available. | | `content.static_config.phrases` | Array of String | Yes | Static fallback phrases, supporting 1 to 100 non-empty strings, each up to 20 words or 20 non-Latin characters. | | `content.generated_config` | Object | No | Generated filler word configuration. Uses the default prompt and context limits when omitted. | | `content.generated_config.prompt` | String | No | Prompt used to generate the filler word. Fully replaces Agora's default prompt, and applies over the same conversation context window. | | `content.generated_config.context_message_limit` | Integer | No | How many of the most recent conversation messages to use for generation, counting the current turn's message. Accepts `1` to `6`. Defaults to `1`. | | `content.generated_config.history_character_limit` | Integer | No | Maximum combined characters of the earlier messages in the window. Accepts `0` to `10000`. Defaults to `1000`. | Filler-word generation is Agora-hosted, so there's no model provider field to configure. Generation runs in parallel with the main LLM request, and falls back to the static phrase list if it isn't ready by the response wait threshold. Providing `generated_config` while `content.mode` is `static` or omitted returns `InvalidFieldValue`. #### Widen the conversation window By default, the generator reads only the message that triggered the current turn. Use `context_message_limit` and `history_character_limit` together to widen that window: - `context_message_limit` sets how many of the most recent conversation messages the generator receives, counting the current turn's message. It accepts `1` to `6` and defaults to `1`. Earlier user and agent messages are only included when you set it to `2` or higher. - `history_character_limit` caps the combined length of the earlier messages in the window. It counts Unicode code points, and doesn't count the current turn's message against the limit. It accepts `0` to `10000` and defaults to `1000`. Set it to `0` to leave the earlier messages uncapped, which still leaves the complete input bounded by the generation model's effective input capacity. - When the input exceeds either limit, the oldest messages in the window are dropped whole, and messages are never truncated. If a filler phrase still can't be generated, the agent plays a static fallback phrase. > **Info** > > Widening the window sends earlier messages to the generation service. This increases the volume of input text, and the generated phrase may be less accurate or restate earlier parts of the conversation. Omit `context_message_limit` or set it to `1` to send the current turn's message only. ## Best practices Keep the following tips in mind when configuring filler words: - **Keep phrases short and natural**: Use brief, conversational phrases that sound like something a person would say. - **Match phrasing to your use case**: For customer support agents, use reassuring phrases like "Let me look into that for you." For casual assistants, use informal phrases like "Hmm, one sec." - **Tune the trigger threshold**: Start with a response wait threshold of 1500 ms and adjust based on your LLM's typical response time. If your agent frequently invokes tools, consider a lower threshold to cover longer processing times. - **Provide enough variety**: Include at least 4-6 phrases to avoid sounding repetitive. Use `shuffle` selection to maximize variety across conversation turns. - **Keep a solid static fallback**: When using generated mode, still provide a well-chosen static phrase list, since it plays whenever generation isn't ready in time. - **Widen the context window only when you need it**: The default single-message window suits most agents and keeps the generation input small. Raise `context_message_limit` when filler phrases need to reflect an ongoing multi-turn exchange, such as a support agent working through a troubleshooting sequence. ## References - [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) # Interrupt the agent mid-response (/en/ai/build/shape-the-conversation/interrupt-agent) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). When interacting with an agent, you may need to interrupt the agent to begin a new round of conversation. The Agora Conversational AI Engine supports agent interruption in the following ways: - **Voice interruption**: The engine detects user voice input and automatically stops the agent’s response. - **Manual interruption**: Your app can explicitly stop the agent by calling a REST API or client SDK method—typically triggered by a button tap or custom command. This page describes how to implement agent interruption in your app. ## Voice interruption Conversational AI Engine supports an intelligent interruption feature that allows a user's voice input to automatically interrupt the speaking agent. This enables quicker response times and more natural, fluid interactions. To customize interruption behavior, configure turn detection when starting a conversational AI agent. To enable AIVAD-based interruption, set the end of speech mode to `"semantic"`. The following example shows how to configure turn detection: **Python SDK** ```python # ... other agent configuration ... .with_turn_detection({ 'mode': 'default', 'config': { 'speech_threshold': 0.5, 'start_of_speech': { 'mode': 'vad', 'vad_config': { 'interrupt_duration_ms': 160, 'speaking_interrupt_duration_ms': 320, 'prefix_padding_ms': 800, }, }, 'end_of_speech': { 'mode': 'semantic', 'semantic_config': { 'silence_duration_ms': 320, 'max_wait_ms': 3000, }, }, }, }) # ... continue with .create_session() ... ``` **TypeScript SDK** ```typescript // ... other agent configuration ... .withTurnDetection({ mode: 'default', config: { speech_threshold: 0.5, start_of_speech: { mode: 'vad', vad_config: { interrupt_duration_ms: 160, speaking_interrupt_duration_ms: 320, prefix_padding_ms: 800, }, }, end_of_speech: { mode: 'semantic', semantic_config: { silence_duration_ms: 320, max_wait_ms: 3000, }, }, }, }) // ... continue with .createSession() ... ``` **Go SDK** ```go // ... other agent configuration ... .WithTurnDetection(&agentkit.TurnDetectionConfig{ Mode: Agora.String("default"), Config: &agentkit.TurnDetectionNestedConfig{ SpeechThreshold: Agora.Float64(0.5), StartOfSpeech: &agentkit.StartOfSpeechConfig{ Mode: Agora.StartAgentsRequestPropertiesTurnDetectionConfigStartOfSpeechModeVad, VadConfig: &agentkit.StartOfSpeechVadConfig{ InterruptDurationMs: Agora.Int(160), SpeakingInterruptDurationMs: Agora.Int(320), PrefixPaddingMs: Agora.Int(800), }, }, EndOfSpeech: &agentkit.EndOfSpeechConfig{ Mode: Agora.StartAgentsRequestPropertiesTurnDetectionConfigEndOfSpeechModeSemantic.Ptr(), SemanticConfig: &agentkit.EndOfSpeechSemanticConfig{ SilenceDurationMs: Agora.Int(320), MaxWaitMs: Agora.Int(3000), }, }, }, }) // ... continue with .CreateSession() ... ``` **REST API** ```bash curl --request post \ --url https://api.agora.io/api/conversational-ai-agent/v2/projects/:appid/join \ --header 'Authorization: Basic ' \ --data ' { "name": "unique_name", "properties": { "channel": "channel_name", "token": "token", "agent_rtc_uid": "1001", "remote_rtc_uids": ["1002"], "turn_detection": { "mode": "default", "config": { "speech_threshold": 0.5, "start_of_speech": { "mode": "vad", "vad_config": { "interrupt_duration_ms": 160, "speaking_interrupt_duration_ms": 320, "prefix_padding_ms": 800 } }, "end_of_speech": { "mode": "semantic", "semantic_config": { "silence_duration_ms": 320, "max_wait_ms": 3000 } } } }, "llm": { "url": "https://api.openai.com/v1/chat/completions", "api_key": "", "system_messages": [ { "role": "system", "content": "You are a helpful assistant." } ], "params": { "model": "gpt-4o-mini" } }, "tts": { "vendor": "microsoft", "params": { "key": "", "region": "eastus", "voice_name": "en-US-AndrewMultilingualNeural" } }, "asr": { "language": "en-US" } } }' ``` If the request succeeds, the API returns a `200` status code and a response body like the following: ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "create_ts": 1737111452, "status": "RUNNING" } ``` ## Manual interruption Conversational AI Engine supports actively triggering an interruption by calling RESTful APIs or client component APIs. This allows users to interrupt the agent through a button click or a specific command. ### Server-side interruption Use the [Interrupt agent](/en/api-reference/api-ref/conversational-ai/interrupt) API to manually initiate an interruption request. **Python SDK** ```python session.interrupt() ``` **TypeScript SDK** ```typescript await session.interrupt(); ``` **Go SDK** ```go if err := session.Interrupt(ctx); err != nil { log.Fatal(err) } ``` **REST API** ```bash curl --request post \ --url https://api.agora.io/api/conversational-ai-agent/v2/projects/:appid/agents/:agentId/interrupt \ --header 'Authorization: Basic ' \ --data '{}' ``` If the request is successful, the API returns a 200 status code and the following response body: ```json { "agent_id": "1NT29XxxxxxxxxELWEHC8OS", "channel": "test_channel", "start_ts": 1744877089 } ``` ### Call the client toolkit API Agora provides a set of flexible, scalable and standardized client components for its conversational AI engine. These components support iOS, Android, and Web platforms and encapsulate scenario-based APIs. You can use them to integrate Agora Real-Time Communication (RTC) and Signaling capabilities, enabling the following features: - Interrupt the agent - Display real-time transcript - Receive event notifications - Optimize audio (Android and iOS only) Before you begin, make sure you: - Integrate RTC SDK v4.5.1 or later and follow the [Quickstart](../../../realtime-media/rtc/get-started-sdk) guide to implement basic real-time audio and video features. - Enable Signaling for your project in the Agora Console and follow the [Signaling Quickstart](/en/realtime-media/rtm/quickstart) to implement real-time messaging. - Implement the basic logic to communicate with a conversational AI agent. - Ensure that the RTC engine instance is initialized and the app is logged in to Signaling. The toolkit does not handle initialization, lifecycle management, authentication, or login for RTC SDK or Signaling. **Android** 1. Add the toolkit to your project using Maven or source code. See [Install the Android toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#installation). 2. Create a configuration object for the RTC engine and Signaling client instances, then use it to initialize the component instance. ```kotlin // Create a configuration object for the RTC and RTM instances val config = ConversationalAIAPIConfig( rtcEngine = rtcEngine, rtmClient = rtmClient, renderMode = TranscriptRenderMode.Word, enableLog = true, enableRenderModeFallback = true ) // Create the component instance val api = ConversationalAIAPIImpl(config) ``` 3. Call [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) using the following parameter settings: - `advanced_features.enable_rtm: true`: Start Signaling (Required) - `parameters.data_channel: "rtm"`: Enable the RTM data transmission channel (Required) - `parameters.enable_metrics: true`: Receive agent performance data (Enabled on demand) - `parameters.enable_error_message: true`: Receive agent error events (Enable on demand) After the call is successful, the agent joins the specified RTC channel and the user can start interacting with the agent. 4. Call the `interrupt` method to interrupt the agent. ```kotlin api.interrupt("agentId") { error -> /* ... */ } ``` 5. When the agent interaction ends, destroy the component instance to release all resources. ```kotlin api.destroy() ``` **iOS** 1. Add the toolkit to your project using CocoaPods, Swift Package Manager, or source code. See [Install the iOS toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#installation). 2. Create a configuration object for the RTC engine and Signaling client instances, then use it to initialize the component instance. ```swift // Create a configuration object for the RTC and RTM instances let config = ConversationalAIAPIConfig( rtcEngine: rtcEngine, rtmEngine: rtmEngine, renderMode: .words, enableLog: true, enableRenderModeFallback: true ) // Create the component instance convoAIAPI = ConversationalAIAPIImpl(config: config) ``` 3. Call [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) using the following parameter settings: - `advanced_features.enable_rtm: true`: Start Signaling (Required) - `parameters.data_channel: "rtm"`: Enable the RTM data transmission channel (Required) - `parameters.enable_metrics: true`: Receive agent performance data (Enabled on demand) - `parameters.enable_error_message: true`: Receive agent error events (Enable on demand) After the call is successful, the agent joins the specified RTC channel and the user can start interacting with the agent. 4. Call the `interrupt` method to interrupt the agent. ```swift convoAIAPI.interrupt(agentUserId: "\(agentUid)") { error in if let error = error { print("Interruption failed: \(error.message)") } else { print("Interruption succeeded") } } ``` 5. When the agent interaction ends, destroy the component instance to release all resources. ```swift convoAIAPI.destroy() ``` **Web** 1. Add the toolkit to your project using a package manager or source code. See [Install the Web toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#installation). 2. Create a configuration object for the RTC engine and Signaling client instances, then use it to initialize the component instance. ```ts // Create a configuration object for the RTC and RTM instances const config: IConversationalAIAPIConfig = { rtcEngine, rtmEngine, renderMode: ETranscriptHelperMode.WORD, enableLog: true, enableRenderModeFallback: true, } // Initialize the component instance const conversationalAIAPI = await ConversationalAIAPI.init(config) ``` 3. Call [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) using the following parameter settings: - `advanced_features.enable_rtm: true`: Start Signaling (Required) - `parameters.data_channel: "rtm"`: Enable the RTM data transmission channel (Required) - `parameters.enable_metrics: true`: Receive agent performance data (Enabled on demand) - `parameters.enable_error_message: true`: Receive agent error events (Enable on demand) After the call is successful, the agent joins the specified RTC channel and the user can start interacting with the agent. 4. Call the `interrupt` method to interrupt the agent. ```ts await conversationalAIAPI.interrupt(`${agent_rtc_uid}`) ``` 5. When the agent interaction ends, destroy the component instance to release all resources. ```ts conversationalAIAPI.destroy() ``` ## Reference ### Sample project Agora provides a [sample project](https://github.com/AgoraIO-Community/Conversational-AI-Demo/) for your reference. Download or view the source code for a complete example. ### API reference #### RESTful API - [Start a conversational AI Agent](/en/api-reference/api-ref/conversational-ai/join) - [Interrupt the Agent](/en/api-reference/api-ref/conversational-ai/interrupt) #### Toolkit **Android** - [`interrupt`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#interrupt) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#destroy) **iOS** - [`interrupt`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#interrupt) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#destroy) **Web** - [`interrupt`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#interrupt) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#destroy) # Memory for Multi-Turn Conversations (/en/ai/build/shape-the-conversation/short-term-memory) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Short-term memory enables your conversational agent to maintain context and coherence by storing structured conversation data during a session. This includes not only message content and roles, but also turn tracking, interruption handling, timestamps, and source metadata. Built on the OpenAI Chat Completions format with conversational AI extensions, short-term memory integrates seamlessly with large language models while providing flexibility for custom implementations, long-term storage, and dynamic memory updates. This guide shows you how to access, use, and implement short-term memory in your applications. > **Info** > > This guide applies to Conversational AI Engine version 1.4 and above. ## Understand the tech Conversational AI Engine stores short-term memory in JSON format, following the [OpenAI Chat Completions](https://platform.openai.com/docs/api-reference/chat) structure. The following example shows the data structure: ```json { "contents": [ { "role": "assistant", "content": "How can I help you today?", "turn_id": 1, "timestamp": 1678901234, "metadata": { "source": "greeting" } }, { "role": "user", "content": "Can you tell me a joke?", "turn_id": 2, "timestamp": 1678901235, "metadata": { "source": "asr", "user": "user123" } }, { "role": "assistant", "content": "Why did the scarecrow ", "turn_id": 2, "timestamp": 1678901236, "metadata": { "interrupted": true, "interrupt_timestamp": 1678905225, "original": "Why did the scarecrow win an award? Because he was outstanding in his field!", "source": "llm" } }, { "role": "user", "content": "You know what? Tell me a story instead.", "turn_id": 3, "timestamp": 1678905235, "metadata": { "source": "asr", "user": "user123" } }, { "role": "assistant", "content": "Once upon a time in a land far away, there lived a brave knight who fought dragons and saved princesses.", "turn_id": 3, "timestamp": 1678905236, "metadata": { "source": "llm" } }, { "role": "assistant", "content": "Are you still there?", "turn_id": 4, "timestamp": 1678905236, "metadata": { "source": "command" } } ] } ``` Each message contains both standard OpenAI fields and enhanced fields that provide additional context for conversational AI scenarios: - **OpenAI standard fields**: - `role`: Specifies the message sender's role in the conversation. Only `user` and `assistant` (agent) are supported in short-term memory. `system` messages are not included. - `content`: The specific text content. Currently, short-term memory does not consider multimodal input. - **Conversational AI Engine extensions**: - `turn_id`: Dialogue turn identifier. Starts from `0` and increments with each dialogue turn between the user and agent. - `timestamp`: The timestamp of the corresponding message, with millisecond accuracy. - `metadata`: Metadata of the message containing the following fields: - `source`: Indicates how the message was generated: | Value | Description | `user`; message | `assistant`; message | | ------------- | -------------------------------------- | :-------------: | :------------------: | | `asr` | Speech recognition result | ✓ | ✗ | | `message` | Text message | ✓ | ✗ | | `command` | Messages generated by RESTful API call | ✓ | ✓ | | `llm` | Large Language Model | ✗ | ✓ | | `greeting` | Greeting message | ✗ | ✓ | | `llm_failure` | LLM call failed | ✗ | ✓ | | `silence` | Silent reminder message | ✗ | ✓ | - `interrupted`: Whether this `assistant` message was interrupted by human voice: - `true`: This message was interrupted. - `false` (default): This message was not interrupted. The field is hidden when `false`. - `interrupt_timestamp`: The timestamp when the agent message was interrupted, with millisecond precision. Only exists when `interrupted` is `true`. - `original`: The complete content actually generated by the LLM. Only exists when `interrupted` is `true`. ## Access short-term memory Conversational AI Engine provides the following methods to access short-term memory: - **During agent runtime**: Call the [Retrieve agent history](/en/api-reference/api-ref/conversational-ai/history) API to retrieve the agent's complete short-term memory in JSON format. This API returns all short-term memory stored during the agent's lifecycle. - **After agent stops**: Agora sends short-term memory to your business server through the message notification service. For details, see [Notification event types](../../reference/event-types#103-agent-history). ## Pass memory content to the LLM Depending on the `llm.vendor` field you specify when creating the agent, Conversational AI Engine uses different strategies to pass memory content to the LLM. ![Pass memory content to the LLM](https://assets-docs.agora.io/images/conversational-ai/short-term-memory.png) ### Non-custom scenario When `llm.vendor` is not `"custom"`, the engine only transfers the OpenAI standard fields (`role` and `content`) from short-term memory to ensure compatibility. ```json { "messages": [ { "role": "assistant", "content": "How can I help you today?" }, { "role": "user", "content": "Can you tell me a joke?" }, { "role": "assistant", "content": "Why did the scarecrow " }, { "role": "user", "content": "You know what? Tell me a story instead." }, { "role": "assistant", "content": "Once upon a time in a land far away, there lived a brave knight who fought dragons and saved princesses." }, { "role": "assistant", "content": "Are you still there?" } ] } ``` ### Custom scenario When `llm.vendor` is set to `"custom"`, the engine transmits all fields in short-term memory to the LLM. You can implement a wrapper to filter or merge extended fields as needed. For implementation details, see [Custom LLM](../custom-model-integration/custom-llm). **Example use cases:** - **Add timestamps**: Include message timestamps in the `content` field - **Add user context**: Prepend user information to the `content` field - **Handle interruptions**: Provide the complete `original` content for interrupted messages Combine these enhancements with `system_messages` to give your LLM deeper conversational awareness, allowing it to maintain user context and gracefully handle interrupted responses. ```json { "messages": [ { "role": "assistant", "content": "How can I help you today?", "turn_id": 1, "timestamp": 1678901234, "metadata": { "source": "greeting" } }, { "role": "user", "content": "Can you tell me a joke?", "turn_id": 2, "timestamp": 1678901235, "metadata": { "source": "asr", "user": "user123" } }, { "role": "assistant", "content": "Why did the scarecrow ", "turn_id": 2, "timestamp": 1678901236, "metadata": { "interrupted": true, "interrupt_timestamp": 1678905225, "original": "Why did the scarecrow win an award? Because he was outstanding in his field!", "source": "llm" } }, { "role": "user", "content": "You know what? Tell me a story instead.", "turn_id": 3, "timestamp": 1678905235, "metadata": { "source": "asr", "user": "user123" } }, { "role": "assistant", "content": "Once upon a time in a land far away, there lived a brave knight who fought dragons and saved princesses.", "turn_id": 3, "timestamp": 1678905236, "metadata": { "source": "llm" } }, { "role": "assistant", "content": "Are you still there?", "turn_id": 4, "timestamp": 1678905236, "metadata": { "source": "command" } } ], "turn_id": 4, "timestamp": 1678905236, "interruptable": true, "model": "xxxx" } ``` ## Convert to long-term memory Short-term memory disappears when the agent stops. To preserve this data: 1. **Store short-term memory**: Save the short-term memory to your server after the agent stops. 2. **Inject into new sessions**: When creating a new agent, use `llm.system_messages` to inject either the original memory content or a summarized version. The following example shows how to inject summarized memory content using the `system_messages` array: ```json [ { "role": "system", "content": "You are a helpful assistant. xxx" }, { "role": "system", "content": "Previously, user has talked about their favorite hobbies with some key topics: xxx" } ] ``` ## Update memory at runtime Starting with version 1.4, you can call the [Update agent configuration](/en/api-reference/api-ref/conversational-ai/update) API to update the agent's `llm.system_messages` field while the agent is running. This enables you to update the memory content dynamically. # Start and stop an agent (/en/ai/build/start-stop-agent) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). This page describes how to call the Conversational AI Engine APIs to start and stop an AI agent. ## Understand the tech A user joins a channel and triggers your business server to start an agent via the Conversational AI Engine API. The agent joins the same channel and communicates with the user through voice, using the specified LLM, TTS service, and Agora’s low-latency Software-Defined Real-Time Network (SDRTN®). When the conversation ends, the business server stops the agent and the user leaves the channel. **Conversational AI Engine workflow** ![Conversational AI Engine workflow](https://assets-docs.agora.io/images/conversational-ai/ai-agent-tech.svg) ## Prerequisites Use the [Agora CLI](/en/introduction/agora-cli) to create or select an Agora project, verify project readiness, and export local credentials: ```bash agora login agora project create conv-ai-tutorial agora project use conv-ai-tutorial agora project doctor agora project env --format shell --with-secrets ``` You also need: - A client app that can join an Agora RTC channel, such as the [Voice Calling](../../realtime-media/rtc/voice-quickstart) or [Video Calling](../../realtime-media/rtc/get-started-sdk) quickstart. ## Install the SDK Select your preferred language and install the corresponding SDK. **Python SDK** ```sh pip install agora-agents ``` **TypeScript SDK** ```sh npm install agora-agents ``` **Go SDK** ```sh go get github.com/AgoraIO/agora-agents-go/v2@v2.2.0 ``` ## Implementation This section introduces the basic RESTful API requests you use to start and stop a conversational AI agent. In a production environment, implement these requests on your business server. ### Start a conversational AI agent Call the `join` endpoint to create an agent instance that joins an Agora channel. This example uses [managed mode](/en/ai/build/managed-mode) for ASR, LLM, and TTS, so you don't need to supply your own provider API keys. If you want to use your own API key (BYOK) instead, see the vendor pages under Models, for example [Deepgram](/en/ai/models/asr/deepgram). **Python SDK** ```python from agora_agent import Agent, Agora, Area, DeepgramSTT, OpenAI, MiniMaxTTS client = Agora( area=Area.US, app_id='your-app-id', app_certificate='your-app-certificate', ) # Omit API keys to use Agora-managed models for ASR, LLM, and TTS. agent = ( Agent(client) .with_stt(DeepgramSTT( model='nova-3', language='en-US', )) .with_llm(OpenAI( model='gpt-4o-mini', system_messages=[{'role': 'system', 'content': 'You are a helpful chatbot.'}], greeting_message='Hello, how can I help you?', failure_message="Sorry, I don't know how to answer this question.", max_history=10, )) .with_tts(MiniMaxTTS( model='speech-2.6-turbo', voice_id='English_captivating_female1', )) ) session = agent.create_session( channel='your_channel_name', agent_uid='0', remote_uids=['1002'], name='unique_name', idle_timeout=120, ) agent_id = session.start() print(f'Agent started: {agent_id}') ``` **TypeScript SDK** ```typescript import { Agent, AgoraClient, Area, DeepgramSTT, OpenAI, MiniMaxTTS } from 'agora-agents'; const client = new AgoraClient({ area: Area.US, appId: 'your-app-id', appCertificate: 'your-app-certificate', }); // Omit API keys to use Agora-managed models for ASR, LLM, and TTS. const agent = new Agent({ client }) .withStt(new DeepgramSTT({ model: 'nova-3', language: 'en-US', })) .withLlm(new OpenAI({ model: 'gpt-4o-mini', systemMessages: [{ role: 'system', content: 'You are a helpful chatbot.' }], greetingMessage: 'Hello, how can I help you?', failureMessage: 'Sorry, I don't know how to answer this question.', maxHistory: 10, })) .withTts(new MiniMaxTTS({ model: 'speech-2.6-turbo', voiceId: 'English_captivating_female1', })); const session = agent.createSession({ channel: 'your_channel_name', agentUid: '0', remoteUids: ['1002'], name: 'unique_name', idleTimeout: 120, }); const agentId = await session.start(); console.log('Agent started:', agentId); ``` **Go SDK** ```go package main import ( "context" "fmt" "log" Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" "github.com/AgoraIO/agora-agents-go/v2/option" ) func main() { ctx := context.Background() idleTimeout := 120 client := agentkit.NewAgoraClient(agentkit.AgoraClientOptions{ Area: option.AreaUS, AppID: "your-app-id", AppCertificate: "your-app-certificate", }) // Omit API keys to use Agora-managed models for ASR, LLM, and TTS. agent := agentkit.NewAgent(client).WithStt( vendors.NewDeepgramSTT(vendors.DeepgramSTTOptions{ Model: "nova-3", Language: "en-US", }), ).WithLlm( vendors.NewOpenAI(vendors.OpenAIOptions{ Model: "gpt-4o-mini", SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful chatbot."}, }, GreetingMessage: "Hello, how can I help you?", FailureMessage: "Sorry, I don't know how to answer this question.", MaxHistory: Agora.Int(10), }), ).WithTts( vendors.NewMiniMaxTTS(vendors.MiniMaxTTSOptions{ Model: "speech-2.6-turbo", VoiceID: "English_captivating_female1", }), ) session := agent.CreateSession(agentkit.CreateSessionOptions{ Channel: "your_channel_name", AgentUID: "0", RemoteUIDs: []string{"1002"}, Name: "unique_name", IdleTimeout: &idleTimeout, }) agentID, err := session.Start(ctx) if err != nil { log.Fatal(err) } fmt.Println("Agent started:", agentID) } ``` **REST API** For the Curl request, pass in the `channel` name and `token` for agent authentication. To generate your base64-encoded credentials, see [RESTful authentication](/en/api-reference/api-ref/conversational-ai/authentication). Set `credential_mode` to `"managed"` in the `asr`, `llm`, and `tts` blocks to use Agora-managed credentials instead of your own API keys. ```bash curl --request POST \ --url https://api.agora.io/api/conversational-ai-agent/v2/projects/:appid/join \ --header 'Authorization: Basic ' \ --header 'Content-Type: application/json' \ --data ' { "name": "unique_name", "properties": { "channel": "", "token": "", "agent_rtc_uid": "0", "remote_rtc_uids": ["1002"], "enable_string_uid": false, "idle_timeout": 120, "asr": { "credential_mode": "managed", "vendor": "deepgram", "params": { "url": "wss://api.deepgram.com/v1/listen", "model": "nova-3", "language": "en-US" } }, "llm": { "credential_mode": "managed", "vendor": "openai", "style": "openai", "url": "https://api.openai.com/v1/chat/completions", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "greeting_message": "Hello, how can I help you?", "failure_message": "Sorry, I don't know how to answer this question.", "max_history": 10, "params": { "model": "gpt-4o-mini" } }, "tts": { "credential_mode": "managed", "vendor": "minimax", "params": { "url": "wss://api.minimax.io/ws/v1/t2a_v2", "model": "speech-2.6-turbo", "voice_setting": { "voice_id": "English_captivating_female1" } } } } }' ``` If the request is successful, you receive the following response: ```json // 200 OK { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "create_ts": 1737111452, "status": "RUNNING" } ``` If the request is successful, the agent ID is returned. Store the agent ID to manage the agent in subsequent calls. ### Stop the conversational AI agent To end the conversation with the AI agent, call the `leave` endpoint. This causes the agent to leave the Agora channel. **Python SDK** ```python session.stop() ``` **TypeScript SDK** ```typescript await session.stop(); ``` **Go SDK** ```go if err := session.Stop(ctx); err != nil { log.Fatal(err) } ``` **REST API** ```bash curl --request POST \ --url https://api.agora.io/api/conversational-ai-agent/v2/projects/:appid/agents/:agentId/leave \ --header 'Authorization: Basic ' ``` If the request is successful, the server responds with a `200 OK` status and an empty JSON object. ```json // 200 OK {} ``` > **Info** > > The number of Peak Concurrent Users (PCU) allowed to call the server API under a single App ID is limited to 20. If you need to increase this limit, please [contact technical support](mailto:support@agora.io). ## Reference This section contains content that completes the information on this page, or points you to documentation that explains other aspects of this product. - [Use managed mode](/en/ai/build/managed-mode) ### API reference - [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) - [Stop a conversational AI agent](/en/api-reference/api-ref/conversational-ai/leave) - [Update agent configuration](/en/api-reference/api-ref/conversational-ai/update) - [Query agent status](/en/api-reference/api-ref/conversational-ai/query) - [Retrieve a list of agents](/en/api-reference/api-ref/conversational-ai/list) # Call custom tools (/en/ai/build/tools/custom-tools) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). To look up data or take action in your systems, you can set up a Conversational AI agent to use custom tools through your own HTTPS endpoints. When the LLM needs a tool call, it generates the tool's parameters from the conversation. The Conversational AI Engine validates those parameters, makes one synchronous request to your endpoint, and returns the result to the LLM so it can continue generating a response. Only the LLM's reply is sent to TTS, never the raw HTTP response. Common use cases include: - **Looking up business data**: Query order status, account balances, or inventory from your own systems. - **Performing actions**: Create a support ticket, schedule an appointment, or update a record. - **Grounding responses**: Pull current, business-specific information into the conversation without retraining the model. ## Understand the tech Each custom tool declares a `function` block with a name, description, and a JSON Schema for its parameters. It also declares a `server` block that describes the HTTPS request the Conversational AI Engine sends once the LLM has generated valid parameters. Tool calling supports only synchronous `GET` and `POST` requests to a single endpoint per tool. Custom tools, [MCP tools](mcp-tools), built-in tools, and model-native tools all share one tool namespace. Names are not case-sensitive. An agent can expose at most 32 tools to the LLM. If tool names conflict or the limit is exceeded, the agent fails to start. MLLM agents support custom tools as well. Declare them in `mllm.tools`, which takes the same tool definitions as `llm.tools`, so the rest of this page applies to both. For an MLLM agent, read `llm.tools` as `mllm.tools` and the LLM as the MLLM. The following aren't supported: - `PUT`, `PATCH`, or `DELETE` requests, automatic retries, or following HTTP redirects. - Asynchronous tools, callbacks, polling, or stored/reusable tool references. - OAuth token exchange, dynamic request signing, or mTLS for authenticating to your endpoint. ## Prerequisites - Implemented the basic logic for interacting with a conversational AI agent by following the [quickstart](../../get-started/quickstart). - A text LLM or MLLM that supports function calling. Custom LLMs and Dify aren't supported. - An HTTPS endpoint your agent can call to fulfill the tool. ## Implementation You declare tools when creating the agent, using either an Agora Agents SDK or the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-tools) REST API. ### Configure a GET tool The following example configures a `GET` tool that looks up order status: **Python SDK** ```python from agora_agent import OpenAI # ... other agent configuration ... .with_llm(OpenAI( api_key='your-llm-api-key', model='gpt-4o-mini', base_url='https://api.openai.com/v1/chat/completions', template_variables={ 'api_key': 'Bearer your-order-service-key', }, tools=[ { 'type': 'function', 'function': { 'name': 'getOrderStatus', 'description': "Get the shipping status for a customer's order by order ID.", 'parameters': { 'type': 'object', 'properties': { 'order_id': { 'type': 'string', 'description': 'The order ID, for example ORD-10293.', }, }, 'required': ['order_id'], 'additionalProperties': False, }, }, 'execution': {'mode': 'sync'}, 'server': { 'method': 'GET', 'url': 'https://api.example.com/orders/{{args.order_id}}/status', 'headers': { 'Authorization': '{{template_variables.api_key}}', }, 'timeout_ms': 5000, }, }, ], )) .with_tools(True) # ... continue with .with_tts() and .create_session() ... ``` **TypeScript SDK** ```typescript import { OpenAI, type LlmTool } from 'agora-agents'; const orderStatusTool: LlmTool = { type: 'function', function: { name: 'getOrderStatus', description: "Get the shipping status for a customer's order by order ID.", parameters: { type: 'object', properties: { order_id: { type: 'string', description: 'The order ID, for example ORD-10293.', }, }, required: ['order_id'], additionalProperties: false, }, }, execution: { mode: 'sync' }, server: { method: 'GET', url: 'https://api.example.com/orders/{{args.order_id}}/status', headers: { Authorization: '{{template_variables.api_key}}', }, timeout_ms: 5000, }, }; // ... other agent configuration ... .withLlm(new OpenAI({ apiKey: 'your-llm-api-key', model: 'gpt-4o-mini', url: 'https://api.openai.com/v1/chat/completions', templateVariables: { api_key: 'Bearer your-order-service-key', }, tools: [orderStatusTool], })) .withTools(true) // ... continue with .withTts() and .createSession() ... ``` **Go SDK** ```go orderStatusTool := &Agora.LlmTool{ Function: &Agora.LlmToolFunction{ Name: "getOrderStatus", Description: Agora.String("Get the shipping status for a customer's order by order ID."), Parameters: &Agora.LlmToolFunctionParameters{ Properties: map[string]interface{}{ "order_id": map[string]interface{}{ "type": "string", "description": "The order ID, for example ORD-10293.", }, }, Required: []string{"order_id"}, }, }, Execution: &Agora.LlmToolExecution{ Mode: Agora.LlmToolExecutionModeSync.Ptr(), }, Server: &Agora.LlmToolServer{ Method: Agora.LlmToolServerMethodGet, URL: "https://api.example.com/orders/{{args.order_id}}/status", Headers: map[string]string{ "Authorization": "{{template_variables.api_key}}", }, TimeoutMs: Agora.Int(5000), }, } // ... other agent configuration ... .WithLlm( vendors.NewOpenAI(vendors.OpenAIOptions{ APIKey: "your-llm-api-key", Model: "gpt-4o-mini", BaseURL: "https://api.openai.com/v1/chat/completions", TemplateVariables: map[string]string{ "api_key": "Bearer your-order-service-key", }, Tools: []*Agora.LlmTool{orderStatusTool}, }), ) .WithTools(true) // ... continue with .WithTts() and .CreateSession() ... ``` **REST API** ```json { "properties": { "advanced_features": { "enable_tools": true }, "llm": { "url": "https://api.openai.com/v1/chat/completions", "api_key": "your-llm-api-key", "params": { "model": "gpt-4o-mini" }, "template_variables": { "api_key": "Bearer your-order-service-key" }, "tools": [ { "type": "function", "function": { "name": "getOrderStatus", "description": "Get the shipping status for a customer's order by order ID.", "parameters": { "type": "object", "properties": { "order_id": { "type": "string", "description": "The order ID, for example ORD-10293." } }, "required": ["order_id"], "additionalProperties": false } }, "execution": { "mode": "sync" }, "server": { "method": "GET", "url": "https://api.example.com/orders/{{args.order_id}}/status", "headers": { "Authorization": "{{template_variables.api_key}}" }, "timeout_ms": 5000 } } ] } } } ``` To create the agent, enable tool calling. With the REST API, set `properties.advanced_features.enable_tools` to `true`. With an Agora Agents SDK, call `with_tools(True)` (Python), `withTools(true)` (TypeScript), or `WithTools(true)` (Go). If you don't enable tool calling, the engine doesn't expose tools to the model and never calls their endpoints. Once this is configured, a user can ask something like "What's the status of order ORD-10293?" After the model generates `order_id`, the engine sends: ```http GET https://api.example.com/orders/ORD-10293/status Authorization: Bearer your-order-service-key ``` **Field reference** Use the following fields to configure tool calling: **Python SDK** Configure tools using the `tools` parameter on the LLM vendor class, and enable tool calling with `with_tools(True)`. Each tool can be a dictionary or an `LlmToolConfig` object. | Parameter | Required | Description | | ------------------------------ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tools` | No | The custom tool array on the LLM vendor class. | | `with_tools(True)` | Yes | Enables calling both custom tools and MCP tools. | | `tools[].type` | Yes | Fixed as `function`. | | `tools[].function` | Yes | The tool definition visible to the model, including its name, description, and parameter schema. | | `tools[].function.name` | Yes | Must start with a letter, contain only letters and numbers, and be no more than 64 characters long. Can't use the `mcp` prefix or the value `ragsearch_tool`. | | `tools[].function.description` | Yes | Explains the tool's purpose, when to call it, and what it returns. Don't include secrets. | | `tools[].function.parameters` | Yes | A JSON Schema object. The root `type` must be `object`. Passed using OpenAI's non-strict function-calling mode. | | `tools[].execution.mode` | No | Defaults to `sync` when omitted. Only `sync` is supported. | | `tools[].server.method` | Yes | Only `GET` and `POST` are supported. A `GET` tool can't include `body`. | | `tools[].server.url` | Yes | An absolute HTTPS URL. The path and query parameters can use template variables. | | `tools[].server.headers` | No | Up to 32 entries. Can't use `{{args.}}`; pass authentication only as a complete header value. | | `tools[].server.body` | Optional for `POST` | `POST` only, supports nested JSON. Template placeholders must be complete, not concatenated with other text. | | `tools[].server.timeout_ms` | No | Defaults to `10000`, in the range `1000` to `100000`. | **TypeScript SDK** Configure tools using the `tools` option on the LLM vendor class, and enable tool calling with `withTools(true)`. | Parameter | Required | Description | | ------------------------------ | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `tools` | No | The custom tool array on the LLM vendor class, of type `LlmTool[]`. | | `withTools(true)` | Yes | Enables calling both custom tools and MCP tools. | | `tools[].type` | Yes | Fixed as `function`. | | `tools[].function` | Yes | The tool definition visible to the model, including its name, description, and parameter schema. | | `tools[].function.name` | Yes | Must start with a letter, contain only letters and numbers, and be no more than 64 characters long. Can't use the `mcp` prefix or the value `ragsearch_tool`. | | `tools[].function.description` | Yes | Explains the tool's purpose, when to call it, and what it returns. Don't include secrets. | | `tools[].function.parameters` | Yes | A JSON Schema object. The root `type` must be `object`. Passed using OpenAI's non-strict function-calling mode. | | `tools[].execution.mode` | No | Defaults to `sync` when omitted. Only `sync` is supported. | | `tools[].server.method` | Yes | Only `GET` and `POST` are supported. A `GET` tool can't include `body`. | | `tools[].server.url` | Yes | An absolute HTTPS URL. The path and query parameters can use template variables. | | `tools[].server.headers` | No | Up to 32 entries. Can't use `{{args.}}`; pass authentication only as a complete header value. | | `tools[].server.body` | Optional for `POST` | `POST` only, supports nested JSON. Template placeholders must be complete, not concatenated with other text. | | `tools[].server.timeout_ms` | No | Defaults to `10000`, in the range `1000` to `100000`. | **Go SDK** Configure tools using the `Tools` field on the LLM vendor options, and enable tool calling with `WithTools(true)`. | Parameter | Required | Description | | ----------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `Tools` | No | The custom tool array on the LLM vendor options, of type `[]*Agora.LlmTool`. | | `WithTools(true)` | Yes | Enables calling both custom tools and MCP tools. | | `LlmTool.Function` | Yes | The tool definition visible to the model, including its name, description, and parameter schema. | | `LlmToolFunction.Name` | Yes | Must start with a letter, contain only letters and numbers, and be no more than 64 characters long. Can't use the `mcp` prefix or the value `ragsearch_tool`. | | `LlmToolFunction.Description` | Yes | Explains the tool's purpose, when to call it, and what it returns. Don't include secrets. | | `LlmToolFunction.Parameters` | Yes | A JSON Schema object with `Properties` and `Required`. The SDK serializes the root type as `object`. Passed using OpenAI's non-strict function-calling mode. | | `LlmToolExecution.Mode` | No | Defaults to `sync` when omitted. Only `Agora.LlmToolExecutionModeSync` is supported. | | `LlmToolServer.Method` | Yes | Accepts `Agora.LlmToolServerMethodGet` or `Agora.LlmToolServerMethodPost`. A `GET` tool can't include `Body`. | | `LlmToolServer.URL` | Yes | An absolute HTTPS URL. The path and query parameters can use template variables. | | `LlmToolServer.Headers` | No | Up to 32 entries. Can't use `{{args.}}`; pass authentication only as a complete header value. | | `LlmToolServer.Body` | Optional for `POST` | `POST` only, supports nested JSON. Template placeholders must be complete, not concatenated with other text. | | `LlmToolServer.TimeoutMs` | No | Defaults to `10000`, in the range `1000` to `100000`. | **REST API** Configure tools in the `properties.llm.tools` array, and set `properties.advanced_features.enable_tools` to `true`. | Parameter | Required | Description | | ------------------------------------------- | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `properties.advanced_features.enable_tools` | Yes | Set to `true` so the agent can expose custom tools and MCP tools to the model. If omitted or `false`, the agent doesn't call any tool endpoints. | | `properties.llm.tools` | No | The custom tool array. Custom tools, MCP tools, built-in tools, and model-native tools share one model-visible tool namespace. | | `tools[].type` | Yes | Fixed as `function`. | | `tools[].function` | Yes | The tool definition visible to the model, including its name, description, and parameter schema. | | `tools[].function.name` | Yes | Must start with a letter, contain only letters and numbers, and be no more than 64 characters long. Can't use the `mcp` prefix or the value `ragsearch_tool`. | | `tools[].function.description` | Yes | Explains the tool's purpose, when to call it, and what it returns. Don't include secrets. | | `tools[].function.parameters` | Yes | A JSON Schema object. The root `type` must be `object`. Passed using OpenAI's non-strict function-calling mode. | | `tools[].execution` | No | Defaults to `{ "mode": "sync" }` when omitted. Only `sync` is supported. | | `tools[].server` | Yes | The actual HTTP request configuration. | | `tools[].server.method` | Yes | Only `GET` and `POST` are supported. A `GET` tool can't include `body`. | | `tools[].server.url` | Yes | An absolute HTTPS URL. The path and query parameters can use template variables. | | `tools[].server.headers` | No | Up to 32 entries. Can't use `{{args.}}`; pass authentication only as a complete header value. | | `tools[].server.body` | Optional for `POST` | `POST` only, supports nested JSON. Template placeholders must be complete, not concatenated with other text. | | `tools[].server.timeout_ms` | No | Defaults to `10000`, in the range `1000` to `100000`. | > **Info** > > Even if tool calling isn't enabled, any tools you declare are still validated for field type, size, template syntax, and duplicate names. ### Configure a POST tool Use a `POST` tool to perform actions, such as creating a ticket or sending a message. A request body can only be used with `POST`; configuring one for a `GET` tool causes validation to fail. The following example sends a confirmed delivery address to a phone number: **Python SDK** ```python sms_tool = { 'type': 'function', 'function': { 'name': 'sendFollowUpSms', 'description': "Send the customer's confirmed delivery address to a phone number. Only call this after the customer has confirmed both the address and the phone number.", 'parameters': { 'type': 'object', 'properties': { 'phone_number': { 'type': 'string', 'description': 'The recipient phone number, in E.164 format.', }, 'address': { 'type': 'string', 'description': "The customer's confirmed delivery address.", }, }, 'required': ['phone_number', 'address'], 'additionalProperties': False, }, }, 'execution': {'mode': 'sync'}, 'server': { 'method': 'POST', 'url': 'https://api.example.com/messages/sms', 'headers': { 'Authorization': '{{template_variables.api_key}}', 'Content-Type': 'application/json', }, 'body': { 'to': '{{args.phone_number}}', 'message': '{{args.address}}', 'idempotency_key': '{{tool_call_id}}', }, 'timeout_ms': 10000, }, } # ... other agent configuration ... .with_llm(OpenAI( api_key='your-llm-api-key', model='gpt-4o-mini', base_url='https://api.openai.com/v1/chat/completions', template_variables={ 'api_key': 'Bearer your-messaging-service-key', }, tools=[sms_tool], )) .with_tools(True) # ... continue with .with_tts() and .create_session() ... ``` **TypeScript SDK** ```typescript const smsTool: LlmTool = { type: 'function', function: { name: 'sendFollowUpSms', description: "Send the customer's confirmed delivery address to a phone number. Only call this after the customer has confirmed both the address and the phone number.", parameters: { type: 'object', properties: { phone_number: { type: 'string', description: 'The recipient phone number, in E.164 format.', }, address: { type: 'string', description: "The customer's confirmed delivery address.", }, }, required: ['phone_number', 'address'], additionalProperties: false, }, }, execution: { mode: 'sync' }, server: { method: 'POST', url: 'https://api.example.com/messages/sms', headers: { Authorization: '{{template_variables.api_key}}', 'Content-Type': 'application/json', }, body: { to: '{{args.phone_number}}', message: '{{args.address}}', idempotency_key: '{{tool_call_id}}', }, timeout_ms: 10000, }, }; // ... other agent configuration ... .withLlm(new OpenAI({ apiKey: 'your-llm-api-key', model: 'gpt-4o-mini', url: 'https://api.openai.com/v1/chat/completions', templateVariables: { api_key: 'Bearer your-messaging-service-key', }, tools: [smsTool], })) .withTools(true) // ... continue with .withTts() and .createSession() ... ``` **Go SDK** ```go smsTool := &Agora.LlmTool{ Function: &Agora.LlmToolFunction{ Name: "sendFollowUpSms", Description: Agora.String("Send the customer's confirmed delivery address to a phone number. Only call this after the customer has confirmed both the address and the phone number."), Parameters: &Agora.LlmToolFunctionParameters{ Properties: map[string]interface{}{ "phone_number": map[string]interface{}{ "type": "string", "description": "The recipient phone number, in E.164 format.", }, "address": map[string]interface{}{ "type": "string", "description": "The customer's confirmed delivery address.", }, }, Required: []string{"phone_number", "address"}, }, }, Execution: &Agora.LlmToolExecution{ Mode: Agora.LlmToolExecutionModeSync.Ptr(), }, Server: &Agora.LlmToolServer{ Method: Agora.LlmToolServerMethodPost, URL: "https://api.example.com/messages/sms", Headers: map[string]string{ "Authorization": "{{template_variables.api_key}}", "Content-Type": "application/json", }, Body: map[string]interface{}{ "to": "{{args.phone_number}}", "message": "{{args.address}}", "idempotency_key": "{{tool_call_id}}", }, TimeoutMs: Agora.Int(10000), }, } // ... other agent configuration ... .WithLlm( vendors.NewOpenAI(vendors.OpenAIOptions{ APIKey: "your-llm-api-key", Model: "gpt-4o-mini", BaseURL: "https://api.openai.com/v1/chat/completions", TemplateVariables: map[string]string{ "api_key": "Bearer your-messaging-service-key", }, Tools: []*Agora.LlmTool{smsTool}, }), ) .WithTools(true) // ... continue with .WithTts() and .CreateSession() ... ``` **REST API** The following JSON shows only the `POST` tool entry in the `properties.llm.tools` array: ```json { "type": "function", "function": { "name": "sendFollowUpSms", "description": "Send the customer's confirmed delivery address to a phone number. Only call this after the customer has confirmed both the address and the phone number.", "parameters": { "type": "object", "properties": { "phone_number": { "type": "string", "description": "The recipient phone number, in E.164 format." }, "address": { "type": "string", "description": "The customer's confirmed delivery address." } }, "required": ["phone_number", "address"], "additionalProperties": false } }, "execution": { "mode": "sync" }, "server": { "method": "POST", "url": "https://api.example.com/messages/sms", "headers": { "Authorization": "{{template_variables.api_key}}", "Content-Type": "application/json" }, "body": { "to": "{{args.phone_number}}", "message": "{{args.address}}", "idempotency_key": "{{tool_call_id}}" }, "timeout_ms": 10000 } } ``` `{{tool_call_id}}` is the system-generated ID correlating this tool call. You can pass it to your own service to correlate logs or detect a repeated call, but passing it alone doesn't stop your service from processing the same request twice, and Agora doesn't automatically retry requests. Your service is still responsible for handling duplicate requests and unknown outcomes. **Field reference** `function` and `execution` are the same as for a `GET` tool. The following fields are specific to a `POST` tool's server configuration: **Python SDK** | Parameter | Required | Description | | --------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- | | `tools[].server.method` | Yes | Fixed as `POST`. | | `tools[].server.url` | Yes | An absolute HTTPS URL. The path and query parameters can use template variables. | | `tools[].server.headers` | No | Configure authentication and `Content-Type`. Can't use `{{args.}}`; pass authentication only as a complete header value. | | `tools[].server.body` | No | The `POST` request body. Supports nested JSON. Values can be constants or complete template placeholders, not concatenated text. | | `tools[].server.timeout_ms` | No | Defaults to `10000`, in the range `1000` to `100000`. | **TypeScript SDK** | Parameter | Required | Description | | --------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- | | `tools[].server.method` | Yes | Fixed as `POST`. | | `tools[].server.url` | Yes | An absolute HTTPS URL. The path and query parameters can use template variables. | | `tools[].server.headers` | No | Configure authentication and `Content-Type`. Can't use `{{args.}}`; pass authentication only as a complete header value. | | `tools[].server.body` | No | The `POST` request body. Supports nested JSON. Values can be constants or complete template placeholders, not concatenated text. | | `tools[].server.timeout_ms` | No | Defaults to `10000`, in the range `1000` to `100000`. | **Go SDK** | Parameter | Required | Description | | ------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- | | `LlmToolServer.Method` | Yes | Fixed as `Agora.LlmToolServerMethodPost`. | | `LlmToolServer.URL` | Yes | An absolute HTTPS URL. The path and query parameters can use template variables. | | `LlmToolServer.Headers` | No | Configure authentication and `Content-Type`. Can't use `{{args.}}`; pass authentication only as a complete header value. | | `LlmToolServer.Body` | No | The `POST` request body. Supports nested JSON. Values can be constants or complete template placeholders, not concatenated text. | | `LlmToolServer.TimeoutMs` | No | Defaults to `10000`, in the range `1000` to `100000`. | **REST API** | Parameter | Required | Description | | --------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------- | | `tools[].server.method` | Yes | Fixed as `POST`. | | `tools[].server.url` | Yes | An absolute HTTPS URL. The path and query parameters can use template variables. | | `tools[].server.headers` | No | Configure authentication and `Content-Type`. Can't use `{{args.}}`; pass authentication only as a complete header value. | | `tools[].server.body` | No | The `POST` request body. Supports nested JSON. Values can be constants or complete template placeholders, not concatenated text. | | `tools[].server.timeout_ms` | No | Defaults to `10000`, in the range `1000` to `100000`. | For `POST` tools that change data or trigger an action: - State the conditions for calling the tool in its description and in your system prompt, such as requiring the user to confirm first. - Perform the final authorization check on your own server. Don't rely on the LLM's judgment alone. - Only have the agent tell the user the request succeeded after your endpoint returns a `2xx` status. - If a request has already been sent, a user interruption doesn't guarantee the remote action is canceled or rolled back. ### Configure template variables Template variables let you fill an HTTP request with either LLM-generated parameters or fixed values known when you create the agent. The following example puts a tenant ID in a header and a customer ID in the request body: **Python SDK** ```python profile_tool = { 'type': 'function', 'function': { 'name': 'getCustomerProfile', 'description': "Look up the current customer's profile.", 'parameters': { 'type': 'object', 'properties': {}, 'additionalProperties': False, }, }, 'execution': {'mode': 'sync'}, 'server': { 'method': 'POST', 'url': 'https://api.example.com/customers/profile', 'headers': { 'X-Tenant-ID': '{{template_variables.tenant_id}}', }, 'body': { 'customer_id': '{{template_variables.customer_id}}', }, }, } # ... other agent configuration ... .with_llm(OpenAI( api_key='your-llm-api-key', model='gpt-4o-mini', base_url='https://api.openai.com/v1/chat/completions', template_variables={ 'tenant_id': 'acme-corp', 'customer_id': 'cust-4471', }, tools=[profile_tool], )) .with_tools(True) # ... continue with .with_tts() and .create_session() ... ``` **TypeScript SDK** ```typescript const profileTool: LlmTool = { type: 'function', function: { name: 'getCustomerProfile', description: "Look up the current customer's profile.", parameters: { type: 'object', properties: {}, additionalProperties: false }, }, execution: { mode: 'sync' }, server: { method: 'POST', url: 'https://api.example.com/customers/profile', headers: { 'X-Tenant-ID': '{{template_variables.tenant_id}}', }, body: { customer_id: '{{template_variables.customer_id}}', }, }, }; // ... other agent configuration ... .withLlm(new OpenAI({ apiKey: 'your-llm-api-key', model: 'gpt-4o-mini', url: 'https://api.openai.com/v1/chat/completions', templateVariables: { tenant_id: 'acme-corp', customer_id: 'cust-4471', }, tools: [profileTool], })) .withTools(true) // ... continue with .withTts() and .createSession() ... ``` **Go SDK** ```go profileTool := &Agora.LlmTool{ Function: &Agora.LlmToolFunction{ Name: "getCustomerProfile", Description: Agora.String("Look up the current customer's profile."), Parameters: &Agora.LlmToolFunctionParameters{ Properties: map[string]interface{}{}, }, }, Execution: &Agora.LlmToolExecution{ Mode: Agora.LlmToolExecutionModeSync.Ptr(), }, Server: &Agora.LlmToolServer{ Method: Agora.LlmToolServerMethodPost, URL: "https://api.example.com/customers/profile", Headers: map[string]string{ "X-Tenant-ID": "{{template_variables.tenant_id}}", }, Body: map[string]interface{}{ "customer_id": "{{template_variables.customer_id}}", }, }, } // ... other agent configuration ... .WithLlm( vendors.NewOpenAI(vendors.OpenAIOptions{ APIKey: "your-llm-api-key", Model: "gpt-4o-mini", BaseURL: "https://api.openai.com/v1/chat/completions", TemplateVariables: map[string]string{ "tenant_id": "acme-corp", "customer_id": "cust-4471", }, Tools: []*Agora.LlmTool{profileTool}, }), ) .WithTools(true) // ... continue with .WithTts() and .CreateSession() ... ``` **REST API** ```json { "properties": { "llm": { "template_variables": { "tenant_id": "acme-corp", "customer_id": "cust-4471" }, "tools": [ { "type": "function", "function": { "name": "getCustomerProfile", "description": "Look up the current customer's profile.", "parameters": { "type": "object", "properties": {}, "additionalProperties": false } }, "execution": { "mode": "sync" }, "server": { "method": "POST", "url": "https://api.example.com/customers/profile", "headers": { "X-Tenant-ID": "{{template_variables.tenant_id}}" }, "body": { "customer_id": "{{template_variables.customer_id}}" } } } ] } } } ``` **Field reference** **Python SDK** | Parameter | Description | | ---------------------------------- | ------------------------------------------------------------------------------------------------ | | `template_variables` | Fixed string values known when the agent is created, set on the LLM vendor class. | | `server.headers` and `server.body` | Read a fixed value with `{{template_variables.}}`. | | `server.body` | Can also use `{{args.}}` and `{{tool_call_id}}`, which don't require `template_variables`. | **TypeScript SDK** | Parameter | Description | | ---------------------------------- | ----------------------------------------------------------------------------------------------- | | `templateVariables` | Fixed string values known when the agent is created, set on the LLM vendor class. | | `server.headers` and `server.body` | Read a fixed value with `{{template_variables.}}`. | | `server.body` | Can also use `{{args.}}` and `{{tool_call_id}}`, which don't require `templateVariables`. | **Go SDK** | Parameter | Description | | ------------------------------------------------ | ----------------------------------------------------------------------------------------------- | | `TemplateVariables` | Fixed string values known when the agent is created, set on the LLM vendor options. | | `LlmToolServer.Headers` and `LlmToolServer.Body` | Read a fixed value with `{{template_variables.}}`. | | `LlmToolServer.Body` | Can also use `{{args.}}` and `{{tool_call_id}}`, which don't require `TemplateVariables`. | **REST API** | Parameter | Description | | -------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | `properties.llm.template_variables` | Fixed string values known when the agent is created. | | `properties.llm.tools[].server.headers` and `body` | Read a fixed value with `{{template_variables.}}`. | | `properties.llm.tools[].server.body` | Can also use `{{args.}}` and `{{tool_call_id}}`, which don't require `template_variables`. | Keep the following rules in mind when using template variables: - Placeholders are substituted once; they aren't expanded recursively. - A template must reference a complete variable. Concatenating text, such as `order-{{args.order_id}}`, isn't supported. - Nested fields, array indexes, and shorthand forms like `{{name}}` aren't supported. - `{{args.}}` can't be used in headers. - Header names, the HTTP method, and the URL's scheme, host, and port can't be templated. - Variables used in the URL path and query parameters are encoded for their respective part of the URL. A variable can't inject a new host, path segment, or query key. - If a variable doesn't exist, is `null`, or has a type that doesn't fit its target location, the tool call fails without calling your endpoint. - Always pass authentication information as a complete header value. Don't put it in the URL, request body, tool parameters, or tool description. ## Reference The following reference material covers the tool parameter schema, response handling, configuration limits, and common issues. ### Parameter schema A tool's parameters use JSON Schema and are passed to the LLM using OpenAI's non-strict function-calling mode. The root must be `object`, with parameters typically declared under `properties`. For details, see [OpenAI's Function Calling guide](https://platform.openai.com/docs/guides/function-calling). ```json { "type": "object", "properties": { "order_id": { "type": "string", "description": "The order ID." }, "include_items": { "type": "boolean", "description": "Whether to also return line-item details." }, "region": { "type": "string", "enum": ["us", "eu"], "description": "The order's region." } }, "required": ["order_id"], "additionalProperties": false } ``` `additionalProperties: false` in this example only demonstrates disallowing undeclared parameters. It isn't required, and setting it doesn't itself enable strict mode. To allow extra parameters, omit this field or set it to `true`. Practical rules: - Common JSON Schema types are supported: `object`, `array`, `string`, `integer`, `number`, `boolean`, and `null`. - Standard JSON Schema keywords relevant to tool parameters are supported, such as `type`, `description`, `enum`, `properties`, `required`, `additionalProperties`, and `items`. The actual effect depends on your LLM's function-calling support. - The root `type` must be `object`. Declare array elements with `items`. - Don't add optional parameters to `required`. If you omit `additionalProperties`, extra properties are allowed per JSON Schema semantics. Set it to `false` explicitly to disallow undeclared parameters. - Don't rely on a specific model's support for advanced keywords such as `$ref`, `$defs`, `format`, `pattern`, range constraints, or composition schemas. Confirm compatibility with your LLM before using them. - The serialized schema size is capped at 64 KiB. ### Response and runtime behavior The Conversational AI Engine passes your endpoint's response back to the LLM. The exact behavior depends on the response status and content: | Endpoint result | Tool result | Conversation behavior | | ---------------------------------------------------------------- | -------------------------------------------------------------------- | --------------------------------------------------------------------------------------------- | | Non-empty `2xx`, valid JSON | JSON is parsed, then serialized back to a string | The model generates a reply based on the full result | | Non-empty `2xx`, UTF-8 text | The raw text is used | The model generates a reply based on the full result | | Empty `2xx`, such as `204` | Reported as success, result is `[]` | The model continues based on the success result | | Non-`2xx`, valid JSON | Reported as failed; JSON is parsed, then serialized back to a string | The full response is still returned to the model, but it shouldn't claim the action succeeded | | Non-`2xx`, UTF-8 text | Reported as failed; the raw text is used | The full response is still returned to the model, but it shouldn't claim the action succeeded | | Non-`2xx`, empty body | Reported as failed, result is `[]` | The model gets a failure result and shouldn't claim the action succeeded | | `3xx` | Reported as failed, following the non-`2xx` rules | The engine doesn't follow `Location` or forward the request to the redirect target | | Timeout, network error, or parameter/template validation failure | Reported as failed | The request isn't retried automatically | | Response over 1 MiB or not valid, safe UTF-8 text | Reported as failed | The partial response isn't passed to the model | A few other runtime behaviors to keep in mind: - If a single model response submits multiple tool calls, the engine runs them concurrently. One call failing doesn't block the others. - The engine waits for every submitted call to reach a final result or error before starting the next LLM turn, and writes the results back in the order the model returned them. - Interrupting the agent stops its current response, but it doesn't cancel an in-flight HTTP request or guarantee that the remote action is rolled back. - While waiting for a tool call, the agent uses your existing [filler words](../shape-the-conversation/filler-words) configuration. Custom tools don't add a separate, tool-specific filler word trigger. - Only the model's final generated text is sent to TTS, never the raw tool response. ### Security and configuration limits - The request URL must be an absolute HTTPS URL. Usernames and passwords in the URL aren't supported. - Header values are treated as sensitive: they aren't passed to the model, and aren't written to regular logs, subtitles, or TTS output. OAuth token exchange, dynamic request signing, mTLS, and reusable credential resources aren't provided. - The final rendered URL is capped at 8192 UTF-8 bytes: each path variable at 1024 bytes, and each query variable at 4096 bytes. - Headers are capped at 32 entries, totaling up to 16 KiB. - The request body is `POST` only. Both the configured value and the rendered result are capped at 64 KiB. - The request timeout defaults to `10000` ms, in the range `1000` to `100000`. - A non-empty response body can't exceed 1 MiB. Extracting specific fields, JSONPath, or custom truncation aren't supported. - Custom tools, MCP tools, built-in tools, and model-native tools share one namespace. Tool names must start with a letter, contain only letters and numbers, and be no more than 64 characters, and comparisons aren't case-sensitive. - Tool names can't use the `mcp` prefix or the value `ragsearch_tool`. After discovery and filtering, the engine exposes at most 32 tools to the model. - Stored tools, asynchronous tasks, callbacks, polling, automatic retries, `PUT`/`PATCH`/`DELETE`, and configurable serial tool scheduling aren't supported. ### Troubleshooting If a custom tool isn't behaving as expected, start with these checks. | Symptom | Check | | ----------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | The model never calls the tool | Check that `enable_tools` is set to `true`, the tool description explains when to call it and what it returns, and the current LLM supports function calling. | | Agent creation fails | Check that the tool type is `function`, the parameters' root type is `object`, the request method is `GET` or `POST`, and no tool name is duplicated. | | Your endpoint never receives a request | Check that `server` is a sibling of `function` rather than nested inside it, the URL is an absolute HTTPS URL, the referenced template variables exist, and `body` isn't configured on a `GET` tool. | | A header doesn't contain the model's parameter | Check for `{{args.}}` in a header. Headers don't support it; use a fixed value directly, or use `template_variables` or `tool_call_id` instead. | | Your endpoint returns a parameter validation error | Check the body field names, parameter types, and `Content-Type`. Template placeholders in the request body can't be concatenated with other text. | | The tool call times out | Check your endpoint's response time against `timeout_ms`. Timed-out calls aren't retried automatically. | | Your endpoint returns success, but the model can't use the result | Confirm your endpoint returned a `2xx` status. A non-empty response must be safe UTF-8 text under 1 MiB. The engine doesn't support extracting specific fields from a JSON response. | | A `POST` action runs more than once | Use `tool_call_id` to correlate the call on your side, and handle duplicate requests in your own service. Don't assume Agora will roll back or retry the request for you. | # Use MCP tools (/en/ai/build/tools/mcp-tools) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). MCP is an open protocol for connecting LLMs to external tools and data sources. When you attach an MCP server to a Conversational AI agent and enable tool calling, the LLM can invoke the tools that the server exposes, such as looking up account data, running a search, or triggering an action in another system, and use the results to generate its response. This page explains how to attach an MCP server to an agent using the REST API and Agent SDKs. > **Info** > > Building your agent in Agent Studio? See [Manage integrations](../../studio/build/integrations#mcp-servers). ## Understand the tech During a conversation, the LLM decides when a tool call is useful, the engine forwards that call to the configured MCP server over HTTP, and the server's response is fed back to the LLM as context for its next reply. Agora's Conversational AI Engine acts as the MCP client. To configure MCP tool-use: - **Specify an array of MCP servers**: Each entry defines the server's endpoint, transport, and which of its tools the agent can call. - **Enable tool invocation**: This allows the agent to call the available tools on the specified servers. ## Prerequisites - Implemented the basic logic for interacting with a conversational AI agent. See the [quickstart](../../get-started/quickstart). - An MCP server reachable over HTTP or HTTPS. ## Implementation Take the following steps to give your agent access to an MCP server. ### Attach an MCP server and enable tool calling Add one or more servers then enable tool calling. > **Note** > > MLLM agents support MCP tool-use. For an MLLM agent, add `mcp_servers` under `mllm` instead of `llm`. All three Agents SDKs accept MCP servers on every MLLM vendor class. In the Go SDK, use the `McpServers` field, except on `NewOpenAIGPTLive`, where the equivalent field is `McpServerConfigs`. **Python SDK** ```python from agora_agent import OpenAI # ... other agent configuration ... .with_llm(OpenAI( api_key='your-llm-api-key', model='gpt-4o-mini', base_url='https://api.openai.com/v1/chat/completions', mcp_servers=[ { 'name': 'deepwiki', 'endpoint': 'https://mcp.deepwiki.com/mcp', # Replace with your own MCP server 'transport': 'streamable_http', 'allowed_tools': ['ask_question'], # Replace with your server's tool names 'timeout_ms': 10000, }, ], )) .with_tools(True) # ... continue with .with_tts() and .create_session() ... ``` **TypeScript SDK** ```typescript import { OpenAI } from 'agora-agents'; // ... other agent configuration ... .withLlm(new OpenAI({ apiKey: 'your-llm-api-key', model: 'gpt-4o-mini', url: 'https://api.openai.com/v1/chat/completions', mcpServers: [ { name: 'deepwiki', endpoint: 'https://mcp.deepwiki.com/mcp', // Replace with your own MCP server transport: 'streamable_http', allowed_tools: ['ask_question'], // Replace with your server's tool names timeout_ms: 10000, }, ], })) .withTools(true) // ... continue with .withTts() and .createSession() ... ``` **Go SDK** ```go // ... other agent configuration ... .WithLlm( vendors.NewOpenAI(vendors.OpenAIOptions{ APIKey: "your-llm-api-key", Model: "gpt-4o-mini", BaseURL: "https://api.openai.com/v1/chat/completions", McpServers: []map[string]interface{}{ { "name": "deepwiki", "endpoint": "https://mcp.deepwiki.com/mcp", // Replace with your own MCP server "transport": "streamable_http", "allowed_tools": []string{"ask_question"}, // Replace with your server's tool names "timeout_ms": 10000, }, }, }), ) .WithTools(true) // ... continue with .WithTts() and .CreateSession() ... ``` **REST API** ```json { "llm": { "url": "https://api.openai.com/v1/chat/completions", "api_key": "your-llm-api-key", "params": { "model": "gpt-4o-mini" }, "mcp_servers": [ { "name": "deepwiki", "endpoint": "https://mcp.deepwiki.com/mcp", "transport": "streamable_http", "allowed_tools": ["ask_question"], "timeout_ms": 10000 } ] }, "advanced_features": { "enable_tools": true } } ``` Update `endpoint` with your own MCP server's URL, and `allowed_tools` with the MCP tool names you want your agent to use. > **Info** > > Attaching MCP servers and enabling tool invocation are independent settings. If you configure servers without enabling tool invocation, the LLM never calls any tools, with no error to signal the mismatch. ### Configure an MCP server Each item in the MCP servers array accepts the following fields. **mcp_servers item** **`name` (string) required** A unique identifier for the MCP server. Maximum 48 characters. Accepts only English letters and numbers. **`endpoint` (string) required** The MCP server's endpoint address. **`transport` (string) optional** Transport protocol. Currently only `streamable_http` is supported. **`headers` (object) optional** HTTP headers to send with requests to the MCP server. If your MCP server requires authentication, use it to pass credentials. For example: ```json { "Authorization": "Bearer your-mcp-server-token" } ``` **`allowed_tools` (array) optional** The tools the agent is allowed to call: - Omit `allowed_tools`, or set it to `["*"]`: all tools on the server are enabled. - Set `allowed_tools` to a list of tool names, for example `["search_docs", "get_weather"]`: only those tools are enabled. Strings in `allowed_tools` must match the tool names the MCP server actually registers, not names from another integration's docs or a client config file. An empty array or a name that doesn't match any real tool doesn't fail cleanly: the agent can hang mid-response with no error, rather than answering or falling back. Confirm the exact names by calling the server's `tools/list` method directly, for example: ```bash curl --request POST \ --url https://your-mcp-server.example.com/mcp \ --header 'Content-Type: application/json' \ --header 'Accept: application/json, text/event-stream' \ --data '{"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {}}' ``` **`timeout_ms` (integer) optional** Request timeout for the MCP server. After the timeout, the agent stops waiting for a response and continues with subsequent logic. To connect multiple MCP servers, add multiple entries to the MCP servers array. Each server must have a unique `name`. > **Tip: Filler words during tool calls** > > Tool calls add latency while the MCP server processes the request. Configure [filler words](../shape-the-conversation/filler-words) so the agent acknowledges the user's request while it waits for a tool result. ## Reference - [`llm.mcp_servers`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-mcp-servers) - [`mllm.mcp_servers`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-mcp-servers) - [`advanced_features.enable_tools`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-advanced-features-enable-tools) - [`with_tools()` / `withTools()` / `WithTools()`](/en/api-reference/api-ref/server-sdk/python#other-builder-methods) # Display live transcripts (/en/ai/build/transcripts) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). When interacting with conversational AI in real time, you can enable live transcripts to display the conversation content. This page explains how to implement live transcripts in your app. ## Understand the tech Agora provides a flexible, scalable, and standardized conversational AI engine toolkit. The toolkit supports **iOS**, **Android**, and **Web** platforms, and encapsulates scenario-based APIs. You can use these APIs to integrate the capabilities of the [Agora Signaling SDK](/en/realtime-media/rtm) and [Agora RTC SDK](../../realtime-media/rtc/get-started-sdk) to enable the following features: - [Interrupt agents](shape-the-conversation/interrupt-agent) - [Display live transcripts](transcripts) - [Client-side events](handle-runtime-events/event-notifications) - [Set optimal audio parameters](../best-practices/audio-setup) for iOS and Android - [Send picture messages](send-multimodal-messages) The toolkit receives transcript content through the `onTranscriptUpdated` callback and supports monitoring the following transcript data types: - **Agent transcript**: The agent's speech, including streaming updates and final results. - **User transcript**: The user's speech, including real-time display and status management. - **Transcript status**: State changes such as in progress, completed, or interrupted. The following diagram outlines the step-by-step process to integrate live transcript functionality into your application: **Transcript rendering workflow** ![](https://assets-docs.agora.io/images/conversational-ai/transcript-workflow.svg) ## Prerequisites Before you begin, ensure the following: - You have implemented the Conversational AI Engine [quickstart](../get-started/quickstart). - Your app integrates Agora RTC SDK v4.5.1 or later and includes the [RTC SDK quickstart](../../realtime-media/rtc/get-started-sdk). - You have enabled Signaling in the Agora Console and completed the [Signaling quickstart](/en/realtime-media/rtm/quickstart) for basic messaging. - You maintain active and authenticated RTC and Signaling instances that persist beyond the component lifecycle. The toolkit does not manage RTC or Signaling initialization, lifecycle, or authentication. ## Implementation This section describes how to receive transcript content from the transcript processing module and display it in your app UI. **Android** 1. **Integrate the toolkit** Add the toolkit to your project using Maven or source code. See [Install the Android toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#installation). Refer to [Folder structure](#reference) to understand the role of each file. 2. **Create a toolkit instance** Create a configuration object with the RTC SDK and Signaling engine instances. Set the transcript rendering mode, then use the configuration to create a toolkit instance. ```kotlin // Create configuration objects for the RTC and RTM instances val config = ConversationalAIAPIConfig( rtcEngine = rtcEngineInstance, rtmClient = rtmClientInstance, // Set the transcript rendering mode. Options: // - TranscriptRenderMode.Word: render transcript word by word. // - TranscriptRenderMode.Text: render the full sentence at once. renderMode = TranscriptRenderMode.Word, enableLog = true ) // Create component instance val api = ConversationalAIAPIImpl(config) ``` 3. **Subscribe to the channel** Transcript data is delivered through Signaling channel messages. To receive transcript data, call `subscribeMessage` before starting the agent session. ```kotlin api.subscribeMessage("channelName") { error -> if (error != null) { // Handle error } } ``` 4. **Receive transcript** Call the `addHandler` method to register your implementation of the transcription callback. ```kotlin api.addHandler(covEventHandler) ``` 5. **Implement UI rendering logic** Inherit your UI module from the `IConversationalAIAPIEventHandler` interface. Implement the `onTranscriptUpdated` method to handle transcript rendering to the UI. ```kotlin private val covEventHandler = object : IConversationalAIAPIEventHandler { override fun onTranscriptUpdated(agentUserId: String, transcript: Transcript) { // Handle transcript data and update the UI here } } ``` 6. **Add a conversational AI agent to the channel** To [start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), configure the following parameters in your `POST` request: | Parameter | Description | Required | | --------------------------------------- | -------------------------------------------------- | -------- | | `advanced_features.enable_rtm: true` | Starts the Signaling service | Yes | | `parameters.data_channel: "rtm"` | Enables Signaling as the data transmission channel | Yes | | `parameters.enable_metrics: true` | Enables agent performance data collection | Optional | | `parameters.enable_error_message: true` | Enables reporting of agent error events | Optional | After a successful response, the agent joins the specified RTC channel and is ready to interact with the user. 7. **Unsubscribe from the channel** After an agent session ends, unsubscribe from channel messages to release transcription resources. ```kotlin api.unsubscribeMessage("channelName") { error -> if (error != null) { // Handle the error } } ``` 8. **Release resources** At the end of each call, use the `destroy` method to clean up the cache. ```kotlin api.destroy() ``` **iOS** 1. **Integrate the toolkit** Add the toolkit to your project using CocoaPods, Swift Package Manager, or source code. See [Install the iOS toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#installation). Refer to [Folder structure](#reference) to understand the role of each file. 2. **Create a toolkit instance** Create a configuration object with the RTC SDK and Signaling engine instances. Set the transcript rendering mode, then use the configuration to create a toolkit instance. ```swift // Create a configuration object for the RTC and RTM instances let config = ConversationalAIAPIConfig( rtcEngine: rtcEngine, rtmEngine: rtmEngine, /** * Set the transcript rendering mode. Available options: * - .words: Word-by-word rendering mode. * - .text: Sentence-by-sentence rendering mode. */ renderMode: .words, enableLog: true ) // Create the component instance convoAIAPI = ConversationalAIAPIImpl(config: config) ``` 3. **Subscribe to the channel** Transcript data is delivered through Signaling channel messages. To receive transcript data, call `subscribeMessage` before starting the agent session. ```swift convoAIAPI.subscribeMessage(channelName: channelName) { error in if let error = error { print("Subscription failed: \(error.message)") } else { print("Subscription successful") } } ``` 4. **Receive transcript** Call the `addHandler` method to register and implement the transcript callback. ```swift convoAIAPI.addHandler(handler: self) ``` 5. **Implement UI rendering logic** Implement the `ConversationalAIAPIEventHandler` protocol in your UI module, and use `onTranscriptUpdated` to handle and render transcript updates. ```swift extension ChatViewController: ConversationalAIAPIEventHandler { public func onTranscriptUpdated(agentUserId: String, transcript: Transcript) { // Handle transcript data and update the UI here } } ``` 6. **Add a conversational AI agent to the channel** To [start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), configure the following parameters in your `POST` request: | Parameter | Description | Required | | --------------------------------------- | -------------------------------------------------- | -------- | | `advanced_features.enable_rtm: true` | Starts the Signaling service | Yes | | `parameters.data_channel: "rtm"` | Enables Signaling as the data transmission channel | Yes | | `parameters.enable_metrics: true` | Enables agent performance data collection | Optional | | `parameters.enable_error_message: true` | Enables reporting of agent error events | Optional | After a successful response, the agent joins the specified RTC channel and is ready to interact with the user. 7. **Unsubscribe from the channel** After each agent session ends, unsubscribe from channel messages to release transcript-related resources. ```swift convoAIAPI.unsubscribeMessage(channelName: channelName) { error in if let error = error { print("Unsubscription failed: \(error.message)") } else { print("Unsubscribed successfully") } } ``` 8. **Release resources** At the end of each call, use the `destroy` method to clean up the cache. ```swift convoAIAPI.destroy() ``` **Web** 1. **Integrate the toolkit** Add the toolkit to your project using a package manager or source code. See [Install the Web toolkit](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#installation). Refer to [Folder structure](#reference) to understand the role of each file. 2. **Create a toolkit instance** Before joining an RTC channel, create RTC SDK and Signaling engine instances and pass them into the toolkit instance. ```ts // Initialize the component ConversationalAIAPI.init({ rtcEngine, rtmEngine, /** * Set the rendering mode for transcript. Available options: * - ETranscriptHelperMode.WORD: render transcript word by word. * - ETranscriptHelperMode.TEXT: render the full transcript at once. */ renderMode: ETranscriptHelperMode.WORD, }) // Get the API instance (singleton) const conversationalAIAPI = ConversationalAIAPI.getInstance() ``` 3. **Set audio parameters** In word-by-word rendering mode, you must receive audio timestamp metadata from RTC to synchronize subtitles with speech. Before creating the client object, configure the following parameter: ```ts AgoraRTC.setParameter('ENABLE_AUDIO_PTS_METADATA', true) const client = AgoraRTC.createClient({ mode: 'rtc', codec: 'vp8' }) ``` 4. **Subscribe to the channel** Agent-related events are delivered through Signaling messages. Before starting an agent session, call `subscribeMessage` to receive these events: ```ts conversationalAIAPI.subscribeMessage(channel_name) ``` 5. **Receive transcript** Register an event listener to receive transcript updates: ```tsx import * as React from 'react' import { type IUserTranscription, type IAgentTranscription, type ISubtitleHelperItem, EConversationalAIAPIEvents, } from '@/conversational-ai-api/type' import { ConversationalAIAPI } from '@/conversational-ai-api' export const ChatHistory = () => { const [chatHistory, setChatHistory] = React.useState< ISubtitleHelperItem>[] >([]) const conversationalAIAPI = ConversationalAIAPI.getInstance() conversationalAIAPI.on( EConversationalAIAPIEvents.TRANSCRIPT_UPDATED, setChatHistory ) return ( <> {chatHistory.map((message) => (
{message.uid}: {message.text}
))} ) } ``` 6. **Add a conversational AI agent to the channel** To [start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join), configure the following parameters in your `POST` request: | Parameter | Description | Required | | --------------------------------------- | -------------------------------------------------- | -------- | | `advanced_features.enable_rtm: true` | Starts the Signaling service | Yes | | `parameters.data_channel: "rtm"` | Enables Signaling as the data transmission channel | Yes | | `parameters.enable_metrics: true` | Enables agent performance data collection | Optional | | `parameters.enable_error_message: true` | Enables reporting of agent error events | Optional | After a successful response, the agent joins the specified RTC channel and is ready to interact with the user. 7. **Unsubscribe from the channel** After each agent session ends, unsubscribe from channel messages to release resources associated with callback events. ```ts conversationalAIAPI.unsubscribeMessage(channel_name) ``` 8. **Release resources** At the end of each call, use the `destroy` method to clean up the cache. ```ts conversationalAIAPI.destroy() ``` ## Reference This section contains supporting information that completes the guidance on this page. **Android** **Folder structure** - `IConversationalAIAPI.kt`: API interface and related data structures and enumerations - `ConversationalAIAPIImpl.kt`: ConversationalAI API main implementation logic - `ConversationalAIUtils.kt`: tool functions and event callback management - `subRender/` - `v3/`: transcription module - `TranscriptionController.kt`: transcription controller - `MessageParser.kt`: message parser **API reference** - [`addHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#addhandler) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#unsubscribemessage) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#destroy) - [`onTranscriptUpdated`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#ontranscriptupdated) **iOS** **Folder structure** - `ConversationalAIAPI.swift`: API interface and related data structures and enumerations - `ConversationalAIAPIImpl.swift`: ConversationalAI API main implementation logic - `Transcription/` - `TranscriptionController.swift`: transcription controller **API reference** - [`addHandler`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#addhandler) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#unsubscribemessage) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#destroy) - [`onTranscriptUpdated`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#ontranscriptupdated) **Web** **Folder structure** - `index.ts`: API class - `type.ts`: API interface and related data structures and enumerations - `utils/` - `index.ts`: API utility functions - `events.ts`: event management class - `sub-render.ts`: transcription module **API reference** - [`IConversationalAIAPIEventHandler interface`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#iconversationalaiapieventhandlers-interface) - [`EConversationalAIAPIEvents`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#econversationalaiapievents) - [`subscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#subscribemessage) - [`unsubscribeMessage`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#unsubscribe) - [`destroy`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#destroy) # Voice agent quickstart (/en/ai/get-started/quickstart) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Set up a working voice agent in under five minutes. This page walks you through installing Agora Skills to give your AI coding assistant the official quickstarts and Agora CLI workflows. You then use the CLI to sign in, clone the official starter, and run it locally. You can follow the CLI steps yourself or paste the sample prompt and let your assistant handle setup for you. If you are new to Agora, read [Core concepts](/en/introduction/core-concepts) first to understand how RTC, Signaling, channels, UIDs, and tokens fit together. ### Install Agora Skills Agora Skills teach your AI coding assistant how to work with Conversational AI projects using official starter repos and the Agora CLI, including signing in, project binding, generating environment files, and running diagnostics. Install the CLI in the next section, or ask your assistant to run the installer for you. ```bash npx skills add AgoraIO/skills ``` Paste the following prompt into your assistant's chat. You can replace Python with TypeScript or Go depending on your language preference: ```text Set up and run the Agora Conversational AI Python starter project locally. ``` Your assistant installs the CLI, signs you in, scaffolds the official starter, and guides you through the remaining steps. Follow the manual CLI steps below if you prefer to run each command yourself. ### Install the Agora CLI The Agora CLI is a native Go binary available at [AgoraIO-Community/cli](https://github.com/AgoraIO-Community/cli). **macOS and Linux** ```bash curl -fsSL https://dl.agora.io/cli/install.sh | sh agora --help ``` If the `agora` command is not found after installation, re-run with `--add-to-path` or manually add the install directory to your shell profile. **Windows (PowerShell)** ```powershell irm https://dl.agora.io/cli/install.ps1 | iex agora --help ``` If your execution policy blocks inline scripts, download `install.ps1` and run: ```powershell powershell -ExecutionPolicy Bypass -File .\install.ps1 ``` ## Sign in, scaffold, and run Sign in with the Agora CLI, clone the starter project, and configure it for your chosen language. 1. Sign in to Agora Console. ```bash agora login ``` 2. Use `agora init` to clone the official starter for your chosen template, bind it to your Agora project, and write the runtime-specific environment file. **Python** ```bash agora init my-python-demo --template python cd my-python-demo # Set up the web client and Python backend. bun run setup # Start the web client and Python backend. bun run dev ``` **TypeScript** ```bash agora init my-nextjs-demo --template nextjs cd my-nextjs-demo pnpm install pnpm dev ``` **Go** ```bash agora init my-go-demo --template go cd my-go-demo make setup make dev ``` 3. Open `http://localhost:3000` and click **Start conversation**. If the agent does not join or transcripts do not appear, run `agora project doctor` to check credential validity, feature enablement, and network reachability. > **Info** > > Conversational AI Engine is enabled by default for new projects and can't be disabled. If you're using an older project and the agent fails to start, verify that Conversational AI Engine is enabled on the **RTC Services** page in [Agora Console](https://console.agora.io/). ## What just happened The CLI cloned the selected starter, connected it to your Agora project, and wrote the environment configuration required to run the demo locally. The demo runs a local browser app and server-side agent controls: - **Browser app**: Captures microphone audio and plays the agent response. - **Server-side controls**: Generate tokens and start or stop the agent session. Agora provides the real-time path between the user and the agent. The user and agent join the same Agora channel, and Agora transports low-latency audio and session events between them. The configured models handle the speech pipeline: 1. ASR converts user speech to text. 2. The LLM reasons over the conversation and generates a response. 3. TTS converts the response back to speech. ## Next steps ### Build and customize - **[Manage agent sessions](../build/start-stop-agent)**: Start and stop agents with the SDKs or REST API. - **[Customize models](../build/managed-mode)**: Use managed mode, or connect your own LLM and TTS providers. - **[Improve conversation quality](../best-practices/optimize-latency)**: Tune latency, audio settings, interruptions, and turn taking. - **[Optimize audio setup](../best-practices/audio-setup)**: Set audio profiles, scenarios, and capture behavior for your target clients. - **[Review the API reference](/en/api-reference/api-ref/conversational-ai)**: Check REST and SDK parameters when you move beyond the starter. ### Observe and troubleshoot - **[Observe runtime behavior](../build/handle-runtime-events/monitor-agent-runtime)**: Monitor events, transcripts, session history, and failures. - **[Debug agent failures](../build/handle-runtime-events/debug-agent-failures)**: Correlate client callbacks, webhook events, and turn-level data. ### Prepare for production - **[Review security and privacy](/en/introduction/security-privacy)**: Check authentication, encryption, geofencing, compliance, and operational safeguards. - **[Restrict where agents run](../best-practices/regional-restrictions)**: Keep agent traffic within the regions your deployment requires. # Amazon Transcribe (/en/ai/models/asr/amazon) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Amazon provides advanced automatic speech recognition with high accuracy and support for multiple languages, designed for real-time conversational AI applications. ### Sample configuration The following example shows how to configure Amazon Transcribe ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, AmazonSTT # client is your configured Agora client agent = ( Agent(client) .with_stt(AmazonSTT( access_key='your-aws-access-key-id', secret_key='your-aws-secret-access-key', region='us-east-1', language='en-US', )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, AmazonSTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new AmazonSTT({ accessKey: 'your-aws-access-key-id', secretKey: 'your-aws-secret-access-key', region: 'us-east-1', language: 'en-US', })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewAmazonSTT(vendors.AmazonSTTOptions{ AccessKey: "your-aws-access-key-id", SecretKey: "your-aws-secret-access-key", Region: "us-east-1", Language: "en-US", }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** ```json "asr": { "vendor": "amazon", "params": { "region": "", "access_key_id": "", "secret_access_key": "", "language_code": "en-US", "media_sample_rate_hz": 16000, "media_encoding": "pcm" } } ``` ### Key parameters **params required** **`region` (string) required** The AWS region where the Transcribe service is hosted, for example, `us-east-1`, `us-west-2`, or `eu-west-1`. See [AWS regions](https://docs.aws.amazon.com/general/latest/gr/transcribe.html) for available regions. **`access_key_id` (string) required** The AWS access key ID used for authentication. Get your access key from the [AWS IAM Console](https://console.aws.amazon.com/iam/). **`secret_access_key` (string) required** The AWS secret access key used for authentication. Get your secret key from the [AWS IAM Console](https://console.aws.amazon.com/iam/). **`language_code` (string) required** The language code for speech recognition, for example, `en-US`, `es-US`, or `fr-FR`. See [supported languages](https://docs.aws.amazon.com/transcribe/latest/dg/supported-languages.html) for available language codes. **`media_sample_rate_hz` (integer) optional** The sample rate in Hertz for the audio input, for example, `16000` or `8000`. **`media_encoding` (string) optional** The encoding format of the audio input, for example, `pcm`, `opus`, or `flac`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Amazon official documentation](https://docs.aws.amazon.com/transcribe/latest/dg/streaming.html). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # ARES (/en/ai/models/asr/ares) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Adaptive Recognition Engine for Speech (ARES) provides built-in real-time speech-to-text, offering seamless integration with low latency and reliable performance for conversational AI applications. ### Sample configuration The following example shows how to configure ARES ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, AresSTT # client is your configured Agora client agent = ( Agent(client) .with_stt(AresSTT( keywords=['Agora', 'Conversational AI', 'RTC'], )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` `AresSTT` has no `language` parameter. ARES uses the recognition language set through the agent's turn detection configuration, using `with_turn_detection()`, which defaults to `en-US`. **TypeScript SDK** ```typescript import { Agent, AresSTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new AresSTT({ keywords: ['Agora', 'Conversational AI', 'RTC'], })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` `AresSTT` has no `language` option. ARES uses the recognition language set through the agent's turn detection configuration, using `withTurnDetection()`, which defaults to `en-US`. **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewAresSTT(vendors.AresSTTOptions{ Keywords: []string{"Agora", "Conversational AI", "RTC"}, }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` `AresSTTOptions` has no `Language` field. ARES uses the recognition language set through the agent's turn detection configuration, using `WithTurnDetection()`, which defaults to `en-US`. **REST API** Use the following `asr` configuration in your request: ```json "asr": { "vendor": "ares", "language": "en-US", "keywords": ["Agora", "Conversational AI", "RTC"] } ``` ### Key parameters **asr required** **`vendor` (string) required** ASR provider. Set to `ares` to use Adaptive Recognition Engine for Speech. **`language` (string) required** The BCP-47 language tag identifying the primary language used for agent interaction. See [Supported languages](/en/realtime-media/speech-to-text/reference/supported-languages#real-time-transcription) for the complete list. **`keywords` (array[string]) optional** Keywords used to improve ASR recognition accuracy for specific terms, such as brand names, product names, or industry jargon. Supports up to 128 keywords. See [Configure ASR keywords](../../build/shape-the-conversation/asr-keywords) for details. # AssemblyAI (/en/ai/models/asr/assembly-ai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). AssemblyAI provides advanced automatic speech recognition with high accuracy and support for multiple languages, designed for real-time conversational AI applications. ### Sample configuration The following example shows how to configure AssemblyAI ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, AssemblyAISTT # client is your configured Agora client agent = ( Agent(client) .with_stt(AssemblyAISTT( api_key='your-assemblyai-key', language='en-US', ws_url='wss://streaming.assemblyai.com/v3/ws', )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, AssemblyAISTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new AssemblyAISTT({ apiKey: 'your-assemblyai-key', language: 'en-US', uri: 'wss://streaming.assemblyai.com/v3/ws', })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewAssemblyAISTT(vendors.AssemblyAISTTOptions{ APIKey: "your-assemblyai-key", Language: "en-US", URI: "wss://streaming.assemblyai.com/v3/ws", }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `asr` configuration in your request: ```json "asr": { "vendor": "assemblyai", "language": "en-US", "params": { "api_key": "", "language": "en-US", "uri": "wss://streaming.assemblyai.com/v3/ws" } } ``` ### Key parameters **params required** **`api_key` (string) required** The API key used for authentication. Get your API key from the [AssemblyAI Dashboard](https://www.assemblyai.com/dashboard/signup). **`language` (string) required** The language code for speech recognition. **`ws_url` (string) optional** The WebSocket URL for the AssemblyAI's streaming API. Specify this to target a particular region. For example, `wss://streaming.assemblyai.com/v3/ws`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [AssemblyAI official documentation](https://www.assemblyai.com/docs/universal-streaming). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Deepgram (/en/ai/models/asr/deepgram) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Deepgram provides fast, accurate automatic speech recognition with advanced AI models optimized for real-time streaming and conversational applications across multiple languages. ### Sample configuration The following example shows how to configure Deepgram ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, DeepgramSTT # client is your configured Agora client agent = ( Agent(client) .with_stt(DeepgramSTT( api_key='your-deepgram-key', # omit to use Agora-managed mode model='nova-3', language='en', )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, DeepgramSTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new DeepgramSTT({ apiKey: 'your-deepgram-key', // omit to use Agora-managed mode model: 'nova-3', language: 'en', })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewDeepgramSTT(vendors.DeepgramSTTOptions{ APIKey: "your-deepgram-key", // omit to use Agora-managed mode Model: "nova-3", Language: "en", }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** - **Managed mode** To use Deepgram ASR with Agora-managed credentials, set `credential_mode` to `"managed"` in the `asr` block. When using managed mode, `params.key` is not required. You can still use the `asr` field to configure additional settings such as `language` and `keyterm`. For more information, see [Use managed mode](/en/ai/build/managed-mode). ```json "asr": { "credential_mode": "managed", "vendor": "deepgram", "params": { "url": "wss://api.deepgram.com/v1/listen", "model": "nova-3", "language": "en", "keyterm": "agora%20convo" } } ``` - **BYOK** ```json "asr": { "vendor": "deepgram", "params": { "url": "wss://api.deepgram.com/v1/listen", "api_key": "", "model": "nova-3", "language": "en", "keyterm": "term1%20term2" } } ``` ### Key parameters **params required** **`url` (string) required** The WebSocket URL for Deepgram's streaming API. **`api_key` (string) optional** The API key used for authentication. Required when using your own API key (BYOK). Get your API key from the [Deepgram Console](https://console.deepgram.com/). **`model` (string) optional** The speech recognition model to use. For managed mode, use `nova-2` or `nova-3`. **`language` (string) optional** The language code for speech recognition (For example, `en`, `es`, `fr`). See [supported languages](https://developers.deepgram.com/docs/models-languages-overview) for language codes. **`keyterm` (string) optional** Boost specialized terms and brands. Only compatible with the `nova-3` model. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Deepgram API documentation](https://developers.deepgram.com/docs/getting-started-with-live-streaming-audio). > > The following parameters are not passed through and instead use default values set by Agora: > `callback`, `callback_method`, `channels`, `encoding`, `multichannel`, `sample_rate` # Gemini (/en/ai/models/asr/gemini) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Google Gemini provides real-time streaming transcription. Use it as the ASR component in a cascading pipeline with any supported LLM and TTS vendor. ### Sample configuration The following example shows how to configure Gemini ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, GeminiSTT # client is your configured Agora client agent = ( Agent(client) .with_stt(GeminiSTT( api_key='your-google-api-key', model='gemini-3.5-transcribe-live', language='en-US', sample_rate=16000, word_timestamp=True, )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, GeminiSTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new GeminiSTT({ apiKey: 'your-google-api-key', model: 'gemini-3.5-transcribe-live', language: 'en-US', sampleRate: 16000, wordTimestamp: true, })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewGeminiSTT(vendors.GeminiSTTOptions{ APIKey: "your-google-api-key", Model: "gemini-3.5-transcribe-live", Language: "en-US", SampleRate: 16000, WordTimestamp: Agora.Bool(true), }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `asr` configuration in your request: ```json "asr": { "vendor": "gemini", "language": "en-US", "params": { "api_key": "", "model": "gemini-3.5-transcribe-live", "sample_rate": 16000, "language": "en-US", "word_timestamp": true } } ``` ### Key parameters **asr required** **`vendor` (string) required** ASR provider. Set to `gemini` to use Google Gemini. **`language` (string) required** The BCP-47 language tag identifying the primary language used for agent interaction. **`params` (object) required** Configuration object for the Gemini ASR model. **`api_key` (string) required** The Google Gemini API key used to authenticate requests. You can generate an API key in [Google AI Studio](https://aistudio.google.com/apikey). **`model` (string) required** The Gemini transcription model identifier. Set to `gemini-3.5-transcribe-live` to use Gemini 3.5 Transcribe Live. **`sample_rate` (integer) optional** The audio sample rate in Hz. For example, `16000`. **`language` (string) optional** The language code for speech recognition, for example, `en-US`. If set, this takes precedence over the top-level `asr.language` value. **`word_timestamp` (boolean) optional** Whether to include word-level timestamps in the transcription results. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Google Gemini API documentation](https://ai.google.dev/api/live). # Google (/en/ai/models/asr/google) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Google provides advanced automatic speech recognition with high accuracy and support for multiple languages, designed for real-time conversational AI applications. ### Sample configuration The following example shows how to configure Google ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, GoogleSTT # client is your configured Agora client agent = ( Agent(client) .with_stt(GoogleSTT( project_id='your-google-project-id', location='global', adc_credentials_string='your-google-credentials-json-string', language='en-US', model='long', )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, GoogleSTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new GoogleSTT({ projectId: 'your-google-project-id', location: 'global', adcCredentialsString: 'your-google-credentials-json-string', language: 'en-US', model: 'long', })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewGoogleSTT(vendors.GoogleSTTOptions{ ProjectID: "your-google-project-id", Location: "global", ADCCredentialsString: "your-google-credentials-json-string", Language: "en-US", Model: "long", }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `asr` configuration in your request: ```json "asr": { "vendor": "google", "language": "en-US", "params": { "project_id": "", "location": "global", "adc_credentials_string": "", "language": "en-US", "model": "long" } } ``` ### Key parameters **params required** **`project_id` (string) required** The Google Cloud project ID where the Speech-to-Text API is enabled. Get your project ID from the [Google Cloud Console](https://console.cloud.google.com/). **`location` (string) required** The Google Cloud region where the speech service is hosted, for example, `global`, `us-central1`, or `europe-west1`. **`adc_credentials_string` (string) required** The Google Cloud service account credentials JSON string used for authentication. Get your credentials from the [Google Cloud Console](https://console.cloud.google.com/). **`language` (string) required** The language code for speech recognition, for example, `en-US`, `es-ES`, or `fr-FR`. See [supported languages](https://cloud.google.com/speech-to-text/docs/speech-to-text-supported-languages) for available language codes. **`model` (string) optional** The recognition model to use. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Google official documentation](https://docs.cloud.google.com/speech-to-text/v2/docs). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Microsoft Azure (/en/ai/models/asr/microsoft) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Microsoft Azure provides enterprise-grade automatic speech recognition with support for multiple languages and robust noise handling capabilities, optimized for real-time conversational applications. ### Sample configuration The following example shows how to configure Microsoft Azure ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, MicrosoftSTT # client is your configured Agora client agent = ( Agent(client) .with_stt(MicrosoftSTT( key='your-azure-key', region='eastus', language='en-US', )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, MicrosoftSTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new MicrosoftSTT({ key: 'your-azure-key', region: 'eastus', language: 'en-US', })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewMicrosoftSTT(vendors.MicrosoftSTTOptions{ Key: "your-azure-key", Region: "eastus", Language: "en-US", }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `asr` configuration in your request: ```json "asr": { "vendor": "microsoft", "language": "en-US", "params": { "key": "", "region": "eastus", "language": "en-US", "phrase_list": ["agora", "conversational", "ai", "engine"] } } ``` ### Key parameters **params required** **`key` (string) required** The API key used for authentication. Get your API key from the [Azure Portal](https://portal.azure.com/). **`region` (string) required** The Azure region where the speech service is hosted (For example, `eastus`, `westus2`). **`language` (string) required** The language code for speech recognition (For example, `en-US`, `es-ES`, `fr-FR`). See [supported languages](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/language-support?tabs=stt) for language codes. **`phrase_list` (array[string]) optional** A list of words or phrases provided in advance to improve recognition accuracy. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Microsoft Azure Speech-to-Text documentation](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/speech-to-text). # OpenAI (/en/ai/models/asr/openai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). OpenAI provides real-time speech-to-text with low latency and reliable performance, making it ideal for conversational AI applications. ### Sample configuration The following example shows how to configure OpenAI ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, OpenAISTT # client is your configured Agora client agent = ( Agent(client) .with_stt(OpenAISTT( api_key='your-openai-key', model='gpt-4o-mini-transcribe', language='en', prompt='Please transcribe the following audio into text. Output in English.', )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, OpenAISTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new OpenAISTT({ apiKey: 'your-openai-key', model: 'gpt-4o-mini-transcribe', language: 'en', prompt: 'Please transcribe the following audio into text. Output in English.', })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewOpenAISTT(vendors.OpenAISTTOptions{ APIKey: "your-openai-key", Model: "gpt-4o-mini-transcribe", Language: "en", Prompt: "Please transcribe the following audio into text. Output in English.", }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `asr` configuration in your request: ```json "asr": { "vendor": "openai", "language": "en-US", "params": { "api_key": "", "input_audio_transcription": { "model": "gpt-4o-mini-transcribe", "prompt": "Please transcribe the following audio into text. Output in English.", "language": "en" } } } ``` ### Key parameters **params required** **`api_key` (string) required** The OpenAI API key used to authenticate requests. You must provide a valid key for the service to function. **`input_audio_transcription` (object) required** The configuration object for audio transcription. Use this object to specify the model, prompt, and language for the transcription task. **`model` (string) required** The OpenAI ASR model to use for transcription. For example, `gpt-4o-mini-transcribe`. **`prompt` (string) required** A prompt that guides the transcription process. Use this parameter to provide context or instructions for how the audio should be transcribed. **`language` (string) required** The language code to use for transcription. For example, use `en` for English. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [OpenAI documentation](https://platform.openai.com/docs/guides/speech-to-text). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Sarvam (/en/ai/models/asr/sarvam) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Sarvam ASR provides real-time speech-to-text with low latency and reliable performance for Indian languages. ### Sample configuration The following example shows how to configure Sarvam ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, SarvamSTT # client is your configured Agora client agent = ( Agent(client) .with_stt(SarvamSTT( api_key='your-sarvam-key', language='hi-IN', )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, SarvamSTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new SarvamSTT({ apiKey: 'your-sarvam-key', language: 'hi-IN', })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewSarvamSTT(vendors.SarvamSTTOptions{ APIKey: "your-sarvam-key", Language: "hi-IN", }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `asr` configuration in your request: ```json "asr": { "vendor": "sarvam", "language": "en-US", "params": { "api_key": "SARVAM_KEY", "language": "hi-IN" } } ``` ### Key parameters **params required** **`api_key` (string) required** Your Sarvam API key. Get your API key from the [Sarvam dashboard](https://dashboard.sarvam.ai/signin). **`language` (string) required** The language code for transcription. Set to `unknown` for automatic language detection. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Sarvam documentation](https://docs.sarvam.ai/api-reference-docs/speech-to-text/transcribe). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Smallest AI (/en/ai/models/asr/smallest-ai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Smallest AI provides real-time streaming transcription through its Pulse model. Use it as the ASR component in a cascading pipeline with any supported LLM and TTS vendor. ### Sample configuration The following example shows how to configure Smallest AI ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import SmallestAISTT # client is your configured Agora client agent = ( Agent(client) .with_stt(SmallestAISTT( api_key='your-smallest-ai-key', url='wss://api.us.smallest.ai/waves/v1/stt/live', language='zh', sample_rate=16000, encoding='linear16', word_timestamps=True, sentence_timestamps=True, diarize=True, vad_events=True, endpointing=True, eou_timeout_ms=480, format=True, finalize_on_words=True, max_words='100', punctuate=True, capitalize=True, itn_normalize=True, full_transcript=True, keywords='Codex:2,Smallest AI:2', redact_pii=False, redact_pci=False, )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, SmallestAISTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new SmallestAISTT({ apiKey: 'your-smallest-ai-key', url: 'wss://api.us.smallest.ai/waves/v1/stt/live', language: 'zh', sampleRate: 16000, encoding: 'linear16', wordTimestamps: true, sentenceTimestamps: true, diarize: true, vadEvents: true, endpointing: true, eouTimeoutMs: 480, format: true, finalizeOnWords: true, maxWords: '100', punctuate: true, capitalize: true, itnNormalize: true, fullTranscript: true, keywords: 'Codex:2,Smallest AI:2', redactPii: false, redactPci: false, })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewSmallestAISTT(vendors.SmallestAISTTOptions{ APIKey: "your-smallest-ai-key", URL: "wss://api.us.smallest.ai/waves/v1/stt/live", Language: "zh", SampleRate: Agora.Int(16000), Encoding: "linear16", WordTimestamps: true, SentenceTimestamps: true, Diarize: true, VADEvents: true, Endpointing: true, EOUTimeoutMs: Agora.Int(480), Format: true, FinalizeOnWords: true, MaxWords: "100", Punctuate: true, Capitalize: true, ITNNormalize: true, FullTranscript: true, Keywords: "Codex:2,Smallest AI:2", RedactPII: false, RedactPCI: false, }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `asr` configuration in your request. Only `params.api_key` is required: ```json "asr": { "vendor": "smallestai", "language": "zh", "params": { "language": "zh", "url": "wss://api.us.smallest.ai/waves/v1/stt/live", "api_key": "", "sample_rate": 16000, "encoding": "linear16", "word_timestamps": "true", "sentence_timestamps": "true", "diarize": "true", "vad_events": "true", "endpointing": "true", "eou_timeout_ms": 480, "format": "true", "finalize_on_words": "true", "max_words": "100", "punctuate": "true", "capitalize": "true", "itn_normalize": "true", "full_transcript": "true", "keywords": "Codex:2,Smallest AI:2", "redact_pii": "false", "redact_pci": "false" } } ``` > **Info** > > Smallest AI expects its boolean options as the strings `"true"` and `"false"`, as shown in the REST example. The Agora Agents SDKs accept real boolean values and convert them for you. ### Key parameters **asr required** **`vendor` (string) required** ASR provider. Set to `smallestai` to use Smallest AI. **`language` (string) optional** The language tag identifying the primary language used for agent interaction. **`params` (object) required** Configuration object for the Smallest AI ASR model. **`api_key` (string) required** The Smallest AI API key used to authenticate requests. You must provide a valid key for the service to function. **`url` (string) optional** The Smallest AI streaming ASR WebSocket endpoint. For example, `wss://api.us.smallest.ai/waves/v1/stt/live`. **`language` (string) optional** The language code for speech recognition, for example, `zh`. If set, this takes precedence over the top-level `asr.language` value. **`sample_rate` (integer) optional** Input audio sample rate in Hz. Defaults to `16000`. **`encoding` (string) optional** Input audio encoding. Defaults to `linear16`. **`word_timestamps` (string) optional** Whether to include word-level timestamps in the transcription results. **`sentence_timestamps` (string) optional** Whether to include sentence-level timestamps in the transcription results. **`diarize` (string) optional** Whether to enable speaker diarization. Speaker labels are emitted on final transcription results. **`vad_events` (string) optional** Whether to emit voice activity detection events. **`endpointing` (string) optional** Whether to enable automatic end-of-utterance detection. **`eou_timeout_ms` (integer) optional** End-of-utterance timeout in milliseconds. For example, `480`. **`format` (string) optional** Whether to enable Smallest AI's transcript formatting. Smallest AI defines the formatting applied. **`finalize_on_words` (string) optional** Whether to finalize transcription results based on word count, together with `max_words`. **`max_words` (string) optional** Maximum number of words per transcription result, passed as a string. For example, `"100"`. **`punctuate` (string) optional** Whether to add punctuation to transcription results. **`capitalize` (string) optional** Whether to apply capitalization to transcription results. **`itn_normalize` (string) optional** Whether to apply inverse text normalization, which converts spoken forms such as numbers and dates into written form. Smallest AI applies it only to finalized transcripts, before redaction. **`full_transcript` (string) optional** Whether to return the full accumulated transcript. **`keywords` (string) optional** Keyword boosts that improve recognition accuracy for specific terms, as a comma-separated list in `keyword:weight` format. For example, `Codex:2,Smallest AI:2`. **`redact_pii` (string) optional** Whether to redact personally identifiable information from transcription results. **`redact_pci` (string) optional** Whether to redact payment card information from transcription results. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Smallest AI documentation](https://docs.smallest.ai/models/documentation/speech-to-text-pulse/overview). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Speechmatics (/en/ai/models/asr/speechmatics) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Speechmatics provides real-time automatic speech recognition (ASR) with flexible language support and reliable performance for conversational AI applications. ### Sample configuration The following example shows how to configure Speechmatics ASR when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, SpeechmaticsSTT # client is your configured Agora client agent = ( Agent(client) .with_stt(SpeechmaticsSTT( key='your-speechmatics-key', language='en', uri='wss://eu2.rt.speechmatics.com/v2', )) .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, SpeechmaticsSTT } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(new SpeechmaticsSTT({ key: 'your-speechmatics-key', language: 'en', uri: 'wss://eu2.rt.speechmatics.com/v2', })) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt( vendors.NewSpeechmaticsSTT(vendors.SpeechmaticsSTTOptions{ Key: "your-speechmatics-key", Language: "en", URI: "wss://eu2.rt.speechmatics.com/v2", }), ).WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `asr` configuration in your request: ```json "asr": { "vendor": "speechmatics", "language": "en-US", "params": { "key": "", "language": "en", "uri": "wss://eu2.rt.speechmatics.com/v2" } } ``` ### Key parameters **params required** **`key` (string) required** The Speechmatics API key used to authenticate requests. You must provide a valid key for the service to function. **`language` (string) required** The language code to use for transcription. For example, use `en` for English. **`uri` (string) optional** The WebSocket URL for the Speechmatics streaming API. Specify this to target a particular region. For example, `wss://eu2.rt.speechmatics.com/v2`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Speechmatics documentation](https://docs.speechmatics.com/api-ref/realtime-transcription-websocket). # xAI (/en/ai/models/asr/xai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). xAI provides real-time automatic speech recognition (ASR) over WebSocket for conversational AI applications. ### Sample configuration The following example shows a starting `asr` parameter configuration you can use when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). **Python SDK** ```python from agora_agent import XaiSTT # ... other agent configuration ... .with_stt(XaiSTT( api_key='your-xai-api-key', base_url='wss://api.x.ai/v1/stt', sample_rate=16000, language='en', )) ``` **TypeScript SDK** ```typescript import { XAiSTT } from 'agora-agents'; // ... other agent configuration ... .withStt(new XAiSTT({ apiKey: 'your-xai-api-key', baseUrl: 'wss://api.x.ai/v1/stt', sampleRate: 16000, language: 'en', })); ``` **Go SDK** ```go sampleRate := vendors.SampleRate16kHz // ... other agent configuration ... WithStt( vendors.NewXaiSTT(vendors.XaiSTTOptions{ APIKey: "your-xai-api-key", BaseURL: "wss://api.x.ai/v1/stt", SampleRate: &sampleRate, Language: "en", }), ) ``` **REST API** ```json "asr": { "vendor": "xai", "params": { "api_key": "${env:XAI_API_KEY}", "base_url": "wss://api.x.ai/v1/stt", "sample_rate": 16000, "language": "en" } } ``` ### Key parameters **params required** **`api_key` (string) required** The xAI API key used to authenticate requests. You must provide a valid key for the service to function. **`base_url` (string) optional** The WebSocket endpoint URL for the xAI streaming STT API. Defaults to `wss://api.x.ai/v1/stt`. **`sample_rate` (integer) optional** The audio sample rate in Hz. Supported values: `8000`, `16000`, `22050`, `24000`, `44100`, `48000`. **`language` (string) optional** The language code to use for transcription. For example, use `en` for English. Setting this enables text formatting of numbers, currencies, and units. For supported language codes, refer to the [xAI documentation](https://docs.x.ai/developers/model-capabilities/audio/speech-to-text#supported-languages). > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [xAI Speech to Text documentation](https://docs.x.ai/developers/model-capabilities/audio/speech-to-text#streaming-speech-to-text-websocket). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Akool (/en/ai/models/avatar/akool) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Akool provides AI-powered avatars with realistic facial expressions and lip-sync capabilities, enabling natural video conversations with your AI agents. Their platform offers a variety of pre-built avatars and supports custom avatar creation. ### Sample configuration The following examples show how to configure an Akool avatar when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import AkoolAvatar # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(...) # configure a TTS vendor at 16000 Hz .with_avatar(AkoolAvatar( api_key='your-akool-key', avatar_id='', )) ) ``` **TypeScript SDK** ```typescript import { Agent, AkoolAvatar } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(/* configure a TTS vendor at 16000 Hz */) .withAvatar(new AkoolAvatar({ apiKey: 'your-akool-key', avatarId: '', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts(/* configure a TTS vendor at 16000 Hz */). WithAvatar( vendors.NewAkoolAvatar(vendors.AkoolAvatarOptions{ APIKey: "your-akool-key", AvatarID: "", }), ) ``` **REST API** Use the following `avatar` configuration in your request: ```json "avatar": { "vendor": "akool", "enable": true, "params": { "api_key": "", "agora_uid": "", "agora_token": "", "avatar_id": "" } } ``` > **Info** > > Akool avatars only support audio with a sample rate of 16,000 Hz. Using a TTS model configured with a different sample rate will result in an error. Ensure your TTS configuration matches this requirement. ### Key parameters **params required** **`api_key` (string) required** The API key used for authentication with Akool's services. > **Info** > > To purchase an Akool API key, contact [Agora sales](mailto:sales@agora.io). **`agora_uid` (string) required** The unique identifier for the avatar's RTC connection. This must be different from other participants in the channel. **`agora_token` (string) optional** The RTC token that authorizes the avatar to join the video channel. Generate this token using your Agora project credentials. **`avatar_id` (string) required** The unique identifier for the specific Akool avatar you want to use. Find available avatar IDs in your Akool dashboard. This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Anam (/en/ai/models/avatar/anam) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Anam provides AI-powered avatars with real-time video rendering, enabling natural video conversations with your AI agents. ### Sample configuration The following examples show how to configure an Anam avatar when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import AnamAvatar # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor .with_avatar(AnamAvatar( api_key='your-anam-key', avatar_id='', )) ) ``` **TypeScript SDK** ```typescript import { Agent, AnamAvatar } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */) .withAvatar(new AnamAvatar({ apiKey: 'your-anam-key', avatarId: '', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */). WithAvatar( vendors.NewAnamAvatar(vendors.AnamAvatarOptions{ APIKey: "your-anam-key", AvatarID: "", }), ) ``` **REST API** Use the following `avatar` configuration in your request: ```json "avatar": { "vendor": "anam", "enable": true, "params": { "api_key": "", "avatar_id": "960f614f-ea88-47c3-9883-f02094f70874", "agora_uid": "", "agora_token": "", "sample_rate": 24000, "quality": "high", "video_encoding": "H264" } } ``` ### Key parameters **params required** **`api_key` (string) required** The API key used for authentication with Anam's services. Get your API key from the Anam console. **`avatar_id` (string) required** The unique identifier for the Anam avatar you want to use. **`agora_uid` (string) required** The unique identifier for the avatar's RTC connection. This must be different from other participants in the channel. **`agora_token` (string) required** The RTC token that authorizes the avatar to join the video channel. Generate this token using your Agora project credentials. **`sample_rate` (number) optional** Default value: `24000` Possible values: `16000, 24000, 48000` The audio sample rate in Hz. **`quality` (string) optional** Default value: `high` Possible values: `high, medium, low` The video quality level. **`video_encoding` (string) optional** Default value: `H264` Possible values: `H264, AV1` The video encoding format. **`avatar_model` (string) optional** The Anam avatar model. For example, `cara-4` for Cara 4. If not set, Anam selects the model based on `avatar_id`. **`video_width` (number) optional** The output video width in pixels. Set together with `video_height`. For supported resolutions, see [Portrait video](#portrait-video). **`video_height` (number) optional** The output video height in pixels. Set together with `video_width`. For supported resolutions, see [Portrait video](#portrait-video). > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to Anam without validation. For a full list of supported options, refer to the [Anam documentation](https://docs.anam.ai/). ### Portrait video For mobile apps, configure portrait video as follows: 1. Set `avatar_model` to `cara-4`. 2. Set `video_width` and `video_height` to a portrait resolution, such as 768 x 1152. The following resolutions are supported: | Resolution (width x height) | Orientation | Model | | --------------------------- | ----------- | ------ | | 720 x 480 | Landscape | Cara 3 | | 1152 x 768 | Landscape | Cara 4 | | 768 x 1152 | Portrait | Cara 4 | Set `video_width` and `video_height` together, or omit both to use the default resolution of the avatar model. **Python SDK** ```python AnamAvatar( api_key='your-anam-key', avatar_id='', avatar_model='cara-4', video_width=768, video_height=1152, ) ``` **TypeScript SDK** ```typescript new AnamAvatar({ apiKey: 'your-anam-key', avatarId: '', avatarModel: 'cara-4', videoWidth: 768, videoHeight: 1152, }); ``` **Go SDK** ```go width, height := 768, 1152 vendors.NewAnamAvatar(vendors.AnamAvatarOptions{ APIKey: "your-anam-key", AvatarID: "", AvatarModel: "cara-4", VideoWidth: &width, VideoHeight: &height, }) ``` **REST API** ```json "avatar": { "vendor": "anam", "enable": true, "params": { "api_key": "", "avatar_id": "", "agora_uid": "", "agora_token": "", "avatar_model": "cara-4", "video_width": 768, "video_height": 1152 } } ``` This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Generic avatar (/en/ai/models/avatar/generic) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). The `generic` avatar vendor allows you to integrate a custom avatar provider into the Conversational AI Engine. ### Sample configuration The following examples show how to configure a generic avatar provider when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import GenericAvatar # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor .with_avatar(GenericAvatar( api_key='', api_base_url='', avatar_id='', agora_uid='', )) ) ``` **TypeScript SDK** ```typescript import { Agent, GenericAvatar } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */) .withAvatar(new GenericAvatar({ apiKey: '', apiBaseUrl: '', avatarId: '', agoraUid: '', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */). WithAvatar( vendors.NewGenericAvatar(vendors.GenericAvatarOptions{ APIKey: "", APIBaseURL: "", AvatarID: "", AgoraUID: "", }), ) ``` **REST API** Use the following `avatar` configuration in your request: ```json "avatar": { "vendor": "generic", "params": { "api_key": "", "api_base_url": "", "avatar_id": "", "agora_token": "", "agora_uid": "" } } ``` ### Key parameters **params required** **`api_key` (string) required** The API key used for authentication with the avatar provider. **`api_base_url` (string) required** The base URL of the avatar provider's API endpoint. **`avatar_id` (string) required** The unique identifier for the avatar to use. **`agora_token` (string) optional** The RTC token that authorizes the avatar to join the video channel. Generate this token using your Agora project credentials. **`agora_uid` (string) required** The unique identifier for the avatar's RTC connection. This must be different from other participants in the channel. This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # LiveAvatar (/en/ai/models/avatar/heygen) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). LiveAvatar by HeyGen provides AI-powered avatars with high-quality video rendering and customizable video quality settings, enabling professional video conversations with your AI agents. ### Sample configuration The following examples show how to configure a LiveAvatar avatar when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import LiveAvatarAvatar # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(...) # configure a TTS vendor at 24000 Hz .with_avatar(LiveAvatarAvatar( api_key='your-liveavatar-key', quality='high', agora_uid='', avatar_id='65f9e3c9-d48b-4118-b73a-4ae2e3cbb8f0', )) ) ``` **TypeScript SDK** ```typescript import { Agent, LiveAvatarAvatar } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(/* configure a TTS vendor at 24000 Hz */) .withAvatar(new LiveAvatarAvatar({ apiKey: 'your-liveavatar-key', quality: 'high', agoraUid: '', avatarId: '65f9e3c9-d48b-4118-b73a-4ae2e3cbb8f0', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts(/* configure a TTS vendor at 24000 Hz */). WithAvatar( vendors.NewLiveAvatarAvatar(vendors.LiveAvatarAvatarOptions{ APIKey: "your-liveavatar-key", Quality: "high", AgoraUID: "", AvatarID: "65f9e3c9-d48b-4118-b73a-4ae2e3cbb8f0", }), ) ``` **REST API** Use the following `avatar` configuration in your request: ```json "avatar": { "vendor": "liveavatar", "enable": true, "params": { "agora_token": "", "agora_uid": "", "quality": "high", "avatar_id": "65f9e3c9-d48b-4118-b73a-4ae2e3cbb8f0", "api_key": "" } } ``` > **Info** > > LiveAvatar only support audio with a sample rate of 24,000 Hz. Using a TTS model configured with a different sample rate will result in an error. Ensure your TTS configuration matches this requirement. ### Key parameters **params required** **`api_key` (string) required** The API key used for authentication with LiveAvatar's services. Get your API key from the LiveAvatar console. **`quality` (string) required** Possible values: `low, medium high` The video quality for the avatar rendering. - `"high"` (720p) - `"medium"` (480p) - `"low"` (360p). Higher quality provides better visual experience but requires more bandwidth. **`agora_uid` (string) required** The unique identifier for the avatar's RTC connection. This must be different from other participants in the channel. **`agora_token` (string) optional** The RTC token that authorizes the avatar to join the video channel. Generate this token using your Agora project credentials. **`avatar_id` (string) optional** The unique identifier for the avatar you want to use. **`disable_idle_timeout` (boolean) optional** Default value: `false` Whether to disable the idle timeout feature. **`activity_idle_timeout` (integer) optional** Default value: `120` The number of seconds of inactivity before the avatar session times out. Only applies when `disable_idle_timeout` is `false`. For advanced configuration options, refer to the [LiveAvatar official documentation](https://docs.liveavatar.com/reference/create_session_token_v1_sessions_token_post). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # LemonSlice (/en/ai/models/avatar/lemonslice) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). LemonSlice provides AI-powered avatar agents that generate synchronized video and audio responses in real time, enabling natural video conversations with your AI agents. ### Sample configuration The following examples show how to configure a LemonSlice avatar when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import LemonSlice # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor .with_avatar(LemonSlice( api_key='', api_base_url='https://lemonslice.com/api/liveai/agora', avatar_id='lemonslice', agora_uid='', additional_params={ 'agent_image_url': '', # or agent_id, or agent_image_base64 'aspect_ratio': '2x3', }, )) ) ``` **TypeScript SDK** ```typescript import { Agent, LemonSlice } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */) .withAvatar(new LemonSlice({ apiKey: '', apiBaseUrl: 'https://lemonslice.com/api/liveai/agora', avatarId: 'lemonslice', agoraUid: '', additionalParams: { agent_image_url: '', // or agent_id, or agent_image_base64 aspect_ratio: '2x3', }, })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */). WithAvatar( vendors.NewLemonSlice(vendors.LemonSliceOptions{ APIKey: "", APIBaseURL: "https://lemonslice.com/api/liveai/agora", AvatarID: "lemonslice", AgoraUID: "", AdditionalParams: map[string]interface{}{ "agent_image_url": "", // or agent_id, or agent_image_base64 "aspect_ratio": "2x3", }, }), ) ``` **REST API** Set `vendor` to `generic` and use the following `avatar` configuration in your request: ```json "avatar": { "vendor": "generic", "params": { "api_key": "", "api_base_url": "https://lemonslice.com/api/liveai/agora", "avatar_id": "lemonslice", "agent_image_url": "", "agora_token": "", "agora_uid": "", "aspect_ratio": "2x3" } } ``` ### Key parameters **params required** **`api_key` (string) required** The API key used for authentication with LemonSlice. Get your API key from your LemonSlice account. **`api_base_url` (string) required** The base URL of the LemonSlice API endpoint. Set to `https://lemonslice.com/api/liveai/agora`. **`avatar_id` (string) required** Fixed value that identifies the vendor integration. Always set to `lemonslice`. **`agent_image_url` (string) optional** A publicly accessible URL to the avatar image. Provide exactly one of `agent_id`, `agent_image_url`, or `agent_image_base64`. **`agent_id` (string) optional** The ID of a LemonSlice agent to use as the avatar. Provide exactly one of `agent_id`, `agent_image_url`, or `agent_image_base64`. If you provide `agent_id`, LemonSlice also uses that agent's configured settings as defaults for `agent_prompt` and `agent_idle_prompt`. **`agent_image_base64` (string) optional** A base64-encoded avatar image. Provide exactly one of `agent_id`, `agent_image_url`, or `agent_image_base64`. **`aspect_ratio` (string) optional** The output aspect ratio for the avatar video. One of `2x3`, `9x16`, or `1x1`. Defaults to `2x3`. **`agora_token` (string) optional** The RTC token that authorizes the avatar to join the video channel. Generate this token using your Agora project credentials. **`agora_uid` (string) required** The unique identifier for the avatar's RTC connection. This must be different from other participants in the channel. For advanced configuration options, refer to the [LemonSlice Agora integration](https://lemonslice.com/docs/agora) page or the [LemonSlice API documentation](https://lemonslice.com/docs/api-reference/create-self-managed-session). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Protoface (/en/ai/models/avatar/protoface) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Protoface provides real-time AI avatars that add a talking, lip-synced face to your voice agents, enabling natural video conversations with your AI agents. ### Sample configuration The following examples show how to configure a Protoface avatar when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import Protoface # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor .with_avatar(Protoface( api_key='', api_base_url='https://api.protoface.com/v1/agora', avatar_id='', agora_uid='', )) ) ``` **TypeScript SDK** ```typescript import { Agent, Protoface } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */) .withAvatar(new Protoface({ apiKey: '', apiBaseUrl: 'https://api.protoface.com/v1/agora', avatarId: '', agoraUid: '', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */). WithAvatar( vendors.NewProtoface(vendors.ProtofaceOptions{ APIKey: "", APIBaseURL: "https://api.protoface.com/v1/agora", AvatarID: "", AgoraUID: "", }), ) ``` **REST API** Set `vendor` to `generic` and use the following `avatar` configuration in your request: ```json "avatar": { "vendor": "generic", "params": { "api_key": "", "api_base_url": "https://api.protoface.com/v1/agora", "avatar_id": "", "agora_token": "", "agora_uid": "" } } ``` ### Key parameters **params required** **`api_key` (string) required** The API key used for authentication with Protoface. Get your API key from the [Protoface dashboard](https://app.protoface.com). **`api_base_url` (string) required** The base URL of the Protoface API endpoint. Set to `https://api.protoface.com/v1/agora`. **`avatar_id` (string) required** The ID of the Protoface avatar to use, for example, `av_stock_001`. Find a stock avatar or create your own in the [Protoface dashboard](https://app.protoface.com). **`agora_token` (string) optional** The RTC token that authorizes the avatar to join the video channel. Generate this token using your Agora project credentials. **`agora_uid` (string) required** The unique identifier for the avatar's RTC connection. This must be different from other participants in the channel. For more information about avatars, refer to the [Protoface avatar documentation](https://docs.protoface.com/guides/avatars). For a complete working project, see the [Protoface Agora quickstart](https://github.com/protoface-ai/protoface-quickstart-agora). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Tavus (/en/ai/models/avatar/tavus) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Tavus provides lifelike AI avatars that see, hear, and respond in real time, enabling natural video conversations with your AI agents. ### Sample configuration The following examples show how to configure a Tavus avatar when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import Tavus # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(...) # configure your TTS vendor .with_avatar(Tavus( api_key='', api_base_url='https://tavusapi.com/v2/conversations/agora', avatar_id='', agora_uid='', )) ) ``` **TypeScript SDK** ```typescript import { Agent, Tavus } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(/* configure your TTS vendor */) .withAvatar(new Tavus({ apiKey: '', apiBaseUrl: 'https://tavusapi.com/v2/conversations/agora', avatarId: '', agoraUid: '', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts(/* configure your TTS vendor */). WithAvatar( vendors.NewTavus(vendors.TavusOptions{ APIKey: "", APIBaseURL: "https://tavusapi.com/v2/conversations/agora", AvatarID: "", AgoraUID: "", }), ) ``` **REST API** Set `vendor` to `generic` and use the following `avatar` configuration in your request: ```json "avatar": { "vendor": "generic", "params": { "api_key": "", "api_base_url": "https://tavusapi.com/v2/conversations/agora", "avatar_id": "", "agora_token": "", "agora_uid": "" } } ``` ### Key parameters **params required** **`api_key` (string) required** The API key used for authentication with Tavus. Get your API key from your Tavus account. For details, refer to [Tavus authentication](https://docs.tavus.io/api-reference/authentication). **`api_base_url` (string) required** The base URL of the Tavus API endpoint. Set to `https://tavusapi.com/v2/conversations/agora`. **`avatar_id` (string) required** The ID of the Tavus face (formerly called a replica) to render the avatar. Find or create a face in the [Tavus Developer Portal](https://maker.tavus.io/dev/faces). **`agora_token` (string) optional** The RTC token that authorizes the avatar to join the video channel. Generate this token using your Agora project credentials. **`agora_uid` (string) required** The unique identifier for the avatar's RTC connection. This must be different from other participants in the channel. For more information about Tavus faces and conversations, refer to the [Tavus documentation](https://docs.tavus.io). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Amazon Bedrock (/en/ai/models/llm/amazon) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Amazon Bedrock provides access to a variety of foundation models (FMs) from leading AI providers through a fully managed AWS service. ### Sample configuration The following example shows how to configure Amazon Bedrock LLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, AmazonBedrock # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(AmazonBedrock( access_key='your-aws-access-key-id', secret_key='your-aws-secret-access-key', region='us-east-1', model='us.anthropic.claude-sonnet-4-20250514-v1:0', system_messages=[{'role': 'system', 'content': 'You are a helpful chatbot.'}], )) .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, AmazonBedrock } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(new AmazonBedrock({ accessKey: 'your-aws-access-key-id', secretKey: 'your-aws-secret-access-key', region: 'us-east-1', model: 'us.anthropic.claude-sonnet-4-20250514-v1:0', systemMessages: [{ role: 'system', content: 'You are a helpful chatbot.' }], })) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm( vendors.NewAmazonBedrock(vendors.AmazonBedrockOptions{ AccessKey: "your-aws-access-key-id", SecretKey: "your-aws-secret-access-key", Region: "us-east-1", Model: "us.anthropic.claude-sonnet-4-20250514-v1:0", SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful chatbot."}, }, }), ).WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `llm` configuration in your request: ```json "llm": { "url": "https://bedrock-runtime.us-east-1.amazonaws.com/model/us.anthropic.claude-sonnet-4-20250514-v1:0/converse-stream", "api_key": "", "access_key": "", "secret_key": "", "region": "us-east-1", "model": "us.anthropic.claude-sonnet-4-20250514-v1:0", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "style": "bedrock" } ``` ### Key parameters **llm required** **`url` (string) required** The Amazon Bedrock runtime endpoint for the target region and model. See [Amazon Bedrock endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/bedrock.html#bedrock_region) for the correct endpoint format. **`api_key` (string) optional** Your Bedrock API key for authentication. Use either `api_key` alone, or both `access_key` and `secret_key` together for authentication. **`access_key` (string) optional** Your AWS Access Key ID for authenticating Bedrock API calls. Required if not using `api_key`. Must be used together with `secret_key`. Get your access key from the [AWS IAM Console](https://console.aws.amazon.com/iam/). **`secret_key` (string) optional** Your AWS Secret Access Key for authenticating Bedrock API calls. Required if not using `api_key`. Must be used together with `access_key`. Get your secret key from the [AWS IAM Console](https://console.aws.amazon.com/iam/). **`region` (string) required** The AWS region hosting the Bedrock model, for example, `us-east-1` or `us-west-2`. See [Supported Regions and models](https://docs.aws.amazon.com/bedrock/latest/userguide/inference-profiles-support.html) for available regions. **`style` (string) required** The API style to use. Set to `bedrock` for Amazon Bedrock models. For advanced configuration options, model capabilities, and detailed parameter descriptions, see the [Amazon Bedrock documentation](https://docs.aws.amazon.com/bedrock/latest/userguide/what-is-bedrock.html). # Azure OpenAI (/en/ai/models/llm/azure-openai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Azure OpenAI service provides REST API access to OpenAI's powerful language models through Microsoft Azure's secure infrastructure. ### Sample configuration The following example shows how to configure Azure OpenAI LLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, AzureOpenAI # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(AzureOpenAI( api_key='your-azure-api-key', endpoint='https://your-resource-name.openai.azure.com', deployment_name='your-deployment-name', # the name given to your model deployment in Azure OpenAI Studio model='gpt-4o-mini', system_messages=[{'role': 'system', 'content': 'You are a helpful chatbot.'}], greeting_message='Hello, how can I assist you today?', failure_message='Please hold on a second.', max_history=32, )) .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, AzureOpenAI } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(new AzureOpenAI({ apiKey: 'your-azure-api-key', resourceName: 'your-resource-name', deploymentName: 'your-deployment-name', // the name given to your model deployment in Azure OpenAI Studio model: 'gpt-4o-mini', systemMessages: [{ role: 'system', content: 'You are a helpful chatbot.' }], greetingMessage: 'Hello, how can I assist you today?', failureMessage: 'Please hold on a second.', maxHistory: 32, })) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm( vendors.NewAzureOpenAI(vendors.AzureOpenAIOptions{ APIKey: "your-azure-api-key", Endpoint: "https://your-resource-name.openai.azure.com", DeploymentName: "your-deployment-name", // the name given to your model deployment in Azure OpenAI Studio Model: "gpt-4o-mini", SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful chatbot."}, }, GreetingMessage: "Hello, how can I assist you today?", FailureMessage: "Please hold on a second.", MaxHistory: Agora.Int(32), }), ).WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `llm` configuration in your request: ```json "llm": { "url": "https://YOUR_RESOURCE_NAME.openai.azure.com/openai/deployments/YOUR_DEPLOYMENT_NAME/chat/completions?api-version=AZURE_API_VERSION", "api_key": "", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "max_history": 32, "greeting_message": "Hello, how can I assist you today?", "failure_message": "Please hold on a second.", "style": "openai", "vendor": "azure", "params": { "model": "gpt-4o-mini" } } ``` ### Key parameters **llm required** **`api_key` (string) required** Find your API key in the Azure portal under your OpenAI resource. **`url` (string) required** Replace `YOUR_RESOURCE_NAME` with your Azure resource name and `YOUR_DEPLOYMENT_NAME` with your model deployment name. **`params` (object) required** **`model` (string) required** Use the deployment name you created in Azure, not the base model name. For advanced configuration options, deployment setup, and detailed parameter descriptions, see the [Azure OpenAI API documentation](https://learn.microsoft.com/en-us/azure/ai-services/openai/reference). # Claude Anthropic (/en/ai/models/llm/claude) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Claude from Anthropic provides helpful, harmless, and honest AI assistance with strong reasoning capabilities and natural conversational abilities. ### Sample configuration The following examples show how to configure Claude (Anthropic) LLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, Anthropic # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(Anthropic( api_key='your-anthropic-key', url='https://api.anthropic.com/v1/messages', model='claude-opus-4-8', max_tokens=1024, headers={'anthropic-version': '2023-06-01'}, system_messages=[{'role': 'system', 'content': 'You are a helpful chatbot.'}], greeting_message='Hello, how can I assist you?', failure_message='Please hold on a second.', max_history=32, )) .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, Anthropic } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(new Anthropic({ apiKey: 'your-anthropic-key', url: 'https://api.anthropic.com/v1/messages', model: 'claude-opus-4-8', headers: { 'anthropic-version': '2023-06-01' }, params: { max_tokens: 1024 }, systemMessages: [{ role: 'system', content: 'You are a helpful chatbot.' }], greetingMessage: 'Hello, how can I assist you?', failureMessage: 'Please hold on a second.', maxHistory: 32, })) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm( vendors.NewAnthropic(vendors.AnthropicOptions{ APIKey: "your-anthropic-key", URL: "https://api.anthropic.com/v1/messages", Model: "claude-opus-4-8", MaxTokens: Agora.Int(1024), Headers: map[string]string{"anthropic-version": "2023-06-01"}, SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful chatbot."}, }, GreetingMessage: "Hello, how can I assist you?", FailureMessage: "Please hold on a second.", }), ).WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `llm` configuration in your request: ```json "llm": { "url": "https://api.anthropic.com/v1/messages", "api_key": "", "headers": "{\"anthropic-version\":\"2023-06-01\"}", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "max_history": 32, "greeting_message": "Hello, how can I assist you?", "failure_message": "Please hold on a second.", "params": { "model": "claude-opus-4-8", "max_tokens": 1024 }, "style": "anthropic" } ``` ### Key parameters The following parameters are required when using your own API key (BYOK). **llm** **`api_key` (string) required** Get your API key from the [Anthropic Console](https://console.anthropic.com/). **`url` (string) required** Use Anthropic's messages endpoint. **`headers` (string) required** Must include the `anthropic-version` header for API compatibility. **`style` (string) required** Set to `anthropic` to use Claude's message format. **`params` (object) required** **`model` (string) required** Refer to [Claude models](https://docs.anthropic.com/en/docs/about-claude/models) for available models. **`max_tokens` (integer) required** The maximum number of tokens to generate in the response. For complete `llm` configuration options, see [LLM parameters](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm). For Claude-specific options and model capabilities, see the [Claude API documentation](https://docs.anthropic.com/en/api/messages). # Dify (/en/ai/models/llm/dify) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Dify is an open-source LLM application development platform that provides a unified API for multiple LLM providers with workflow orchestration and advanced features. ### Setup and Configuration To integrate Dify with Agora Conversational AI, install the plugin, configure your Agora project, and create an endpoint: 1. **Install the Dify plugin** 1. Log in to the [Dify Console](https://cloud.dify.ai). 2. Click on **Plugins** in the top navigation bar to open the Marketplace. 3. Search for the **Agora Conversational AI** plugin. 4. Click **Install** to install the plugin. 5. After installation, confirm that the plugin status is **Active** in the Installed Plugins list. 2. **Configure the Agora Console** 1. Log in to the [Agora Console](https://console.agora.io). 2. Create a new project or select an existing one. 3. Enable the **Conversational AI** feature within the selected project. 4. Record the following information for later use: - **App ID** (unique project identifier) - **Certificate** (optional, if enabled for enhanced security) 5. Navigate to the **RESTful API** page and generate a **Customer ID** and **Customer Secret** (required for HTTP Basic Authentication). 3. **Create an Endpoint in Dify** 1. In the Dify console's left-hand navigation panel, click on the **Agora Conversational AI** plugin you just installed. 2. Click **Create a new API endpoint** to open the configuration page. 3. Fill in the following details: - **App ID** (copied from the Agora Console) - **Customer ID and Customer Secret** (copied from the Agora Console) - **TTS** (Text-to-Speech) configuration (e.g., Azure or ElevenLabs) 4. **Save and note the endpoint details** 1. Save the endpoint configuration. Dify generates an **Endpoint URL**. 2. Note down this **Dify Endpoint URL** and **Dify endpoint API key** for use in the `llm` configuration. ![](https://assets-docs.agora.io/images/conversational-ai/dify-endpoint.png) ### Sample configuration The following examples show how to configure Dify LLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, Dify # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(Dify( api_key='your-dify-api-key', url='https://xxxxxx.ai-plugin.io/convoai/dify-completion', model='default', system_messages=[{'role': 'system', 'content': 'You are a helpful voice assistant.'}], greeting_message='Hello, how can I assist you today?', failure_message='Hold on a moment.', max_history=32, )) .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, Dify } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(new Dify({ apiKey: 'your-dify-api-key', url: 'https://xxxxxx.ai-plugin.io/convoai/dify-completion', model: 'default', systemMessages: [{ role: 'system', content: 'You are a helpful voice assistant.' }], greetingMessage: 'Hello, how can I assist you today?', failureMessage: 'Hold on a moment.', maxHistory: 32, })) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm( vendors.NewDify(vendors.DifyOptions{ APIKey: "your-dify-api-key", URL: "https://xxxxxx.ai-plugin.io/convoai/dify-completion", Model: "default", SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful voice assistant."}, }, GreetingMessage: "Hello, how can I assist you today?", FailureMessage: "Hold on a moment.", MaxHistory: Agora.Int(32), }), ).WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `llm` configuration in your request: ```json "llm": { "url": "https://xxxxxx.ai-plugin.io/convoai/dify-completion", "api_key": "", "system_messages": [ { "role": "system", "content": "You are a helpful voice assistant." } ], "max_history": 32, "greeting_message": "Hello, how can I assist you today?", "failure_message": "Hold on a moment.", "params": { "model": "default" }, "style": "dify" } ``` ### Key parameters **llm required** **`api_key` (string) required** Use the same API key configured in your Dify endpoint setup. **`url` (string) required** Use the custom endpoint URL from your Dify marketplace integration. **`style` (string) required** Set to `dify` to use Dify's message format and workflow processing. **`params` (object) required** **`model` (string) required** Set to `default` to use the model configured in your Dify application. For advanced configuration options, workflow setup, and detailed parameter descriptions, see the [Agora Conversational AI - Dify Marketplace](https://marketplace.dify.ai/plugins/plutoless/convoai) documentation. # Google Gemini (/en/ai/models/llm/gemini) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Google Gemini provides advanced multimodal AI capabilities with fast performance and efficient processing for conversational AI applications. ### Sample configuration The following example shows how to configure Google Gemini LLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, Gemini # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(Gemini( api_key='your-google-api-key', model='gemini-3.6-flash', system_messages=[{'parts': [{'text': 'You are a helpful chatbot.'}], 'role': 'user'}], greeting_message='Good to see you!', failure_message='Hold on a second.', max_history=32, )) .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, Gemini } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(new Gemini({ apiKey: 'your-google-api-key', model: 'gemini-3.6-flash', systemMessages: [{ parts: [{ text: 'You are a helpful chatbot.' }], role: 'user' }], greetingMessage: 'Good to see you!', failureMessage: 'Hold on a second.', maxHistory: 32, })) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm( vendors.NewGemini(vendors.GeminiOptions{ APIKey: "your-google-api-key", Model: "gemini-3.6-flash", SystemMessages: []map[string]interface{}{ {"parts": []map[string]interface{}{{"text": "You are a helpful chatbot."}}, "role": "user"}, }, GreetingMessage: "Good to see you!", FailureMessage: "Hold on a second.", MaxHistory: Agora.Int(32), }), ).WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `llm` configuration in your request: ```json "llm": { "url": "https://generativelanguage.googleapis.com/v1beta/models/gemini-3.6-flash:streamGenerateContent?alt=sse&key=", "system_messages": [ { "parts": [ { "text": "You are a helpful chatbot" } ], "role": "user" } ], "max_history": 32, "greeting_message": "Good to see you!", "failure_message": "Hold on a second.", "params": { "model": "gemini-3.6-flash" }, "style": "gemini" } ``` ### Key parameters **llm required** **`url` (string) required** Note that the API key is passed in the URL query parameter. Get your API key from [Google AI Studio](https://aistudio.google.com/app/apikey). **`system_messages` (array[object]) optional** Use `parts` array with `text` objects instead of simple `content` string. **`style` (string) required** Set to `gemini` to use Gemini's message format. **`ignore_empty` (boolean) optional** Set to `true` to handle empty responses appropriately. **`params` (object) required** **`model` (string) required** Refer to [Gemini models](https://ai.google.dev/gemini-api/docs/models/gemini) for available models. For advanced configuration options, model capabilities, and detailed parameter descriptions, see the [Google Gemini API documentation](https://ai.google.dev/api/generate-content#method:-models.streamgeneratecontent). # Google Vertex AI (/en/ai/models/llm/google-vertex-ai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Google Vertex AI provides enterprise-grade access to Google's generative AI models with enhanced security, scaling capabilities, and integration with Google Cloud services. ### Sample configuration The following examples show how to configure Google Vertex AI LLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, VertexAILLM # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(VertexAILLM( api_key='your-gcp-access-token', project_id='your-gcp-project-id', location='us-central1', model='gemini-2.0-flash-001', system_messages=[{'parts': [{'text': 'You are a helpful chatbot.'}], 'role': 'user'}], greeting_message='Good to see you!', failure_message='Hold on a second.', max_history=32, )) .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, VertexAILLM } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(new VertexAILLM({ apiKey: 'your-gcp-access-token', projectId: 'your-gcp-project-id', location: 'us-central1', model: 'gemini-2.0-flash-001', systemMessages: [{ parts: [{ text: 'You are a helpful chatbot.' }], role: 'user' }], greetingMessage: 'Good to see you!', failureMessage: 'Hold on a second.', maxHistory: 32, })) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm( vendors.NewVertexAILLM(vendors.VertexAILLMOptions{ ProjectID: "your-gcp-project-id", Location: "us-central1", GeminiOptions: vendors.GeminiOptions{ APIKey: "your-gcp-access-token", Model: "gemini-2.0-flash-001", SystemMessages: []map[string]interface{}{ {"parts": []map[string]interface{}{{"text": "You are a helpful chatbot."}}, "role": "user"}, }, GreetingMessage: "Good to see you!", FailureMessage: "Hold on a second.", MaxHistory: Agora.Int(32), }, }), ).WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `llm` configuration in your request: ```json "llm": { "url": "https://{region}-aiplatform.googleapis.com/v1/projects/{project}/locations/{region}/publishers/google/models/{model}:streamGenerateContent?alt=sse", "api_key": "$(gcloud auth print-access-token)", "system_messages": [ { "role": "user", "parts": [ {"text": "You are a helpful chatbot."} ] } ], "max_history": 32, "greeting_message": "Good to see you!", "failure_message": "Hold on a second.", "params": { "model": "gemini-2.0-flash-001" }, "style": "gemini" } ``` ### Key parameters **llm required** **`api_key` (string) required** Refer to Google Cloud [REST authentication](https://cloud.google.com/docs/authentication/rest) to get your GCP credentials. **`url` (string) required** Use the Vertex AI endpoint with your Google Cloud project ID and region in the URL path. Refer to the [Google Vertex AI API documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations) for details. **`system_messages` (array[object]) optional** Use a `parts` array with `text` objects instead of a simple `content` string. **`style` (string) required** Set to `gemini` to use Gemini's message format. **`params` (object) required** **`model` (string) required** Refer to [Vertex AI models](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/models) for available models. For advanced configuration options, model capabilities, and detailed parameter descriptions, see the [Google Vertex AI API documentation](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/prompts/system-instructions). # Groq (/en/ai/models/llm/groq) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Groq provides state-of-the-art language models optimized for different use cases. ### Sample configuration The following example shows how to configure Groq LLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, Groq # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(Groq( api_key='your-groq-key', base_url='https://api.groq.com/openai/v1/chat/completions', model='llama-3.3-70b-versatile', system_messages=[{'role': 'system', 'content': 'You are a helpful chatbot.'}], greeting_message='Hello, how can I assist you?', failure_message='Please hold on a second.', max_history=32, )) .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, Groq } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(new Groq({ apiKey: 'your-groq-key', url: 'https://api.groq.com/openai/v1/chat/completions', model: 'llama-3.3-70b-versatile', systemMessages: [{ role: 'system', content: 'You are a helpful chatbot.' }], greetingMessage: 'Hello, how can I assist you?', failureMessage: 'Please hold on a second.', maxHistory: 32, })) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm( vendors.NewGroq(vendors.GroqOptions{ APIKey: "your-groq-key", BaseURL: "https://api.groq.com/openai/v1/chat/completions", Model: "llama-3.3-70b-versatile", SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful chatbot."}, }, GreetingMessage: "Hello, how can I assist you?", FailureMessage: "Please hold on a second.", MaxHistory: Agora.Int(32), }), ).WithTts(/* configure your TTS vendor */) ``` **REST API** Use the following `llm` configuration in your request: ```json "llm": { "url": "https://api.groq.com/openai/v1/chat/completions", "api_key": "", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "max_history": 32, "greeting_message": "Hello, how can I assist you?", "failure_message": "Please hold on a second.", "params": { "model": "llama-3.3-70b-versatile" } } ``` ### Key parameters **llm required** **`api_key` (string) required** Create and manage your API key from [Groq console](https://console.groq.com/keys). **`url` (string) required** Use the completions endpoint. **`params` (object) required** **`model` (string) required** Refer to [Groq models](https://console.groq.com/docs/models) for available models. For advanced configuration options, model capabilities, and detailed parameter descriptions, see the [Groq API Documentation](https://console.groq.com/docs/api-reference). # OpenAI (/en/ai/models/llm/openai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). OpenAI provides frontier models ranging from lightweight to high-capability. ### Sample configuration The following examples show how to configure OpenAI LLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, OpenAI # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(OpenAI( api_key='your-openai-key', # omit api_key and base_url to use Agora-managed mode base_url='https://api.openai.com/v1/chat/completions', model='gpt-4o-mini', system_messages=[{'role': 'system', 'content': 'You are a helpful chatbot.'}], greeting_message='Hello, how can I assist you?', failure_message='Please hold on a second.', max_history=32, )) .with_tts(...) # configure your TTS vendor ) ``` **TypeScript SDK** ```typescript import { Agent, OpenAI } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(new OpenAI({ apiKey: 'your-openai-key', // omit apiKey and url to use Agora-managed mode url: 'https://api.openai.com/v1/chat/completions', model: 'gpt-4o-mini', systemMessages: [{ role: 'system', content: 'You are a helpful chatbot.' }], greetingMessage: 'Hello, how can I assist you?', failureMessage: 'Please hold on a second.', maxHistory: 32, })) .withTts(/* configure your TTS vendor */); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm( vendors.NewOpenAI(vendors.OpenAIOptions{ APIKey: "your-openai-key", // omit APIKey and BaseURL to use Agora-managed mode BaseURL: "https://api.openai.com/v1/chat/completions", Model: "gpt-4o-mini", SystemMessages: []map[string]interface{}{ {"role": "system", "content": "You are a helpful chatbot."}, }, GreetingMessage: "Hello, how can I assist you?", FailureMessage: "Please hold on a second.", MaxHistory: Agora.Int(32), }), ).WithTts(/* configure your TTS vendor */) ``` **REST API** - **Managed mode** To use an OpenAI LLM with Agora-managed credentials, set `credential_mode` to `"managed"` in the `llm` block. When using managed mode, `api_key` is not required. You can still use the `llm` field to configure additional settings such as `system_messages` and `greeting_message`. For more information, see [Use managed mode](/en/ai/build/managed-mode). ```json "llm": { "credential_mode": "managed", "vendor": "openai", "style": "openai", "url": "https://api.openai.com/v1/chat/completions", "params": { "model": "gpt-4.1-mini" }, "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "max_history": 32, "greeting_message": "Hello, how can I assist you?", "failure_message": "Please hold on a second." } ``` - **BYOK** ```json "llm": { "url": "https://api.openai.com/v1/chat/completions", "api_key": "", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "max_history": 32, "greeting_message": "Hello, how can I assist you?", "failure_message": "Please hold on a second.", "params": { "model": "gpt-4o-mini" } } ``` ### Key parameters The following parameters are required when using your own API key (BYOK). When using managed mode, `api_key` is not required. For more information, see [Use managed mode](/en/ai/build/managed-mode). **llm** **`api_key` (string)** Create or manage your API key from [OpenAI organization settings](https://platform.openai.com/settings/organization/api-keys). Required when using your own API key (BYOK). **`url` (string)** Use the completions endpoint. **`params` (object)** **`model` (string)** Refer to [OpenAI models](https://platform.openai.com/docs/models) for available models. For managed mode, use `gpt-4o-mini`, `gpt-4.1-mini`, `gpt-5-nano`, or `gpt-5-mini`. For complete `llm` configuration options, see [LLM parameters](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm). For OpenAI-specific options and model capabilities, see the [OpenAI API documentation](https://platform.openai.com/docs/api-reference/chat). # xAI Grok (/en/ai/models/llm/xai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). xAI provides access to Grok large language models through an OpenAI-compatible chat completions API for conversational AI applications. ### Sample configuration The following example shows a starting `llm` parameter configuration you can use when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). ```json "llm": { "url": "https://api.x.ai/v1/chat/completions", "api_key": "", "system_messages": [ { "role": "system", "content": "You are a helpful chatbot." } ], "max_history": 32, "greeting_message": "Hello, how can I assist you?", "failure_message": "Please hold on a second.", "params": { "model": "grok-4.3" }, "vendor": "xai" } ``` ### Key parameters **required** **`url` (string) required** The xAI chat completions endpoint. Set to `https://api.x.ai/v1/chat/completions`. **`api_key` (string) required** The xAI API key used to authenticate requests. **`vendor` (string) required** The LLM vendor. Set to `xai`. **`params` (object) optional** Additional parameters passed directly to the xAI API. **params** **`model` (string) required** The Grok model to use. For example, `grok-4.3`. For available models, refer to the [xAI models documentation](https://docs.x.ai/developers/models). For more information, refer to the [xAI Chat Completions documentation](https://docs.x.ai/developers/model-capabilities/legacy/chat-completions). # Azure OpenAI Realtime API (/en/ai/models/mllm/azure) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Azure OpenAI Realtime API provides multimodal large language model capabilities with real-time audio processing through Microsoft Azure's infrastructure, enabling natural voice conversations without separate ASR/TTS components. Enabling MLLM automatically disables ASR, LLM, and TTS since the MLLM handles end-to-end voice processing directly. ### Sample configuration The following examples show how to configure Azure OpenAI Realtime MLLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import AzureOpenAIRealtime # client is your configured Agora client agent = ( Agent(client) .with_mllm(AzureOpenAIRealtime( api_key='your-azure-api-key', url='wss://your-resource-name.openai.azure.com/openai/v1/realtime?model=gpt-realtime-2', model='gpt-realtime-2', voice='alloy', instructions='You are a Conversational AI Agent, developed by Agora.', output_modalities=['audio'], turn_detection={'mode': 'server_vad'}, )) ) ``` **TypeScript SDK** ```typescript import { Agent, AzureOpenAIRealtime } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withMllm(new AzureOpenAIRealtime({ apiKey: 'your-azure-api-key', url: 'wss://your-resource-name.openai.azure.com/openai/v1/realtime?model=gpt-realtime-2', model: 'gpt-realtime-2', voice: 'alloy', instructions: 'You are a Conversational AI Agent, developed by Agora.', outputModalities: ['audio'], turnDetection: { mode: 'server_vad' }, })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithMllm( vendors.NewAzureOpenAIRealtime(vendors.AzureOpenAIRealtimeOptions{ APIKey: "your-azure-api-key", URL: "wss://your-resource-name.openai.azure.com/openai/v1/realtime?model=gpt-realtime-2", Model: "gpt-realtime-2", Voice: "alloy", Instructions: "You are a Conversational AI Agent, developed by Agora.", OutputModalities: []string{"audio"}, TurnDetection: &agora.MllmTurnDetection{ Mode: agora.MllmTurnDetectionModeServerVad.Ptr(), }, }), ) ``` **REST API** Use the following `mllm` configuration in your request: ```json "mllm": { "enable": true, "vendor": "azure", "url": "wss://your-resource-name.openai.azure.com/openai/v1/realtime?model=gpt-realtime-2", "api_key": "", "output_modalities": ["audio"], "turn_detection": { "mode": "server_vad" }, "params": { "model": "gpt-realtime-2", "voice": "alloy", "instructions": "You are a Conversational AI Agent, developed by Agora." } } ``` ### Turn detection Add a `turn_detection` block inside the `mllm` object when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unlike other MLLM vendors, `turn_detection` is required for Azure OpenAI Realtime API. > **Info** > > When `mllm.turn_detection` is defined, the top-level `turn_detection` object has no effect. The following examples show the supported `turn_detection` configurations for Azure OpenAI Realtime API. - **Server VAD** ```json "turn_detection": { "mode": "server_vad", "server_vad_config": { "prefix_padding_ms": 800, "silence_duration_ms": 640, "threshold": 0.5 } } ``` - **Semantic VAD** ```json "turn_detection": { "mode": "semantic_vad", "semantic_vad_config": { "eagerness": "auto" } } ``` - **Agora VAD** ```json "turn_detection": { "mode": "agora_vad", "agora_vad_config": { "interrupt_duration_ms": 160, "prefix_padding_ms": 800, "silence_duration_ms": 640, "threshold": 0.5 } } ``` ### Key parameters **mllm required** **`api_key` (string) required** The API key used to authenticate with your Azure OpenAI resource. **`url` (string) required** The WebSocket URL for your Azure OpenAI Realtime deployment. For example, `wss://your-resource-name.openai.azure.com/openai/v1/realtime?model=gpt-realtime-2`. **`messages` (array[object]) optional** An array of conversation history items passed to the model as context. Each item represents a single message in the conversation history. **`role` (string) required** The role of the message author. For example, `system` or `user`. **`content` (string) required** The content of the message. **`params` (object) optional** Additional Azure OpenAI Realtime configuration parameters. - **Modalities override**: The `modalities` setting in params is overridden by `output_modalities`. - **Turn detection override**: The `turn_detection` setting in `params` is overridden by [`mllm.turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection). **`model` (string) optional** The model or deployment name. For example, `gpt-realtime-2`. **`voice` (string) optional** The voice identifier for audio output. For example, `alloy`. **`instructions` (string) optional** System instructions that define the assistant's behavior and personality. **`input_audio_transcription` (object) optional** Configuration for audio input transcription. **`language` (string) optional** The language of the input audio. Supplying the input language in ISO-639-1 format (For example `en`) improves accuracy and latency. **`model` (string) optional** The model to use for transcription. **`prompt` (string) optional** An optional text to guide the model's style or continue a previous audio segment. **`turn_detection` (object) required** Turn detection configuration for the MLLM module. Required for Azure OpenAI Realtime API. For a full list of `turn_detection` parameters, see [`mllm.turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection). **`mode` (string) optional** Possible values: `agora_vad, server_vad, semantic_vad` - `agora_vad`: Agora VAD-based detection. - `server_vad`: Vendor-side VAD-based detection. - `semantic_vad`: Semantic-based detection. **`agora_vad_config` (object) optional** Configuration for Agora VAD-based turn detection. Applicable when `mode` is `agora_vad`. **`interrupt_duration_ms` (integer) optional** Minimum duration of speech in milliseconds required to trigger an interruption. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`threshold` (number) optional** VAD sensitivity threshold. A higher value reduces false positives. **`server_vad_config` (object) optional** Configuration for vendor-side VAD-based turn detection. Applicable when `mode` is `server_vad`. Parameters are passed through to the vendor. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`threshold` (number) optional** VAD sensitivity threshold. **`semantic_vad_config` (object) optional** Configuration for semantic-based turn detection. Applicable when `mode` is `semantic_vad`. **`eagerness` (string) optional** Possible values: `auto, low, medium, high` Controls how eagerly the model ends its turn. **`output_modalities` (array[string]) optional** Default value: `["text", "audio"]` Output format options: `["text", "audio"]` for both text and voice responses. **`max_history` (integer) optional** The number of conversation history messages to cache. **`greeting_message` (string) optional** Initial message the agent speaks when a user joins the channel. **`failure_message` (string) optional** The message the agent speaks when an error occurs. **`vendor` (string) required** MLLM provider identifier. Set to `azure` for Azure OpenAI Realtime API. For comprehensive API reference, real-time capabilities, and detailed parameter descriptions, see the [Azure OpenAI Realtime API documentation](https://learn.microsoft.com/en-us/azure/ai-foundry/openai/how-to/realtime-audio). # Google Gemini Live (/en/ai/models/mllm/gemini) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Agora has [partnered with Google Gemini Live](https://ai.google.dev/gemini-api/docs/live-api#partner-integrations) to bring frontier multimodal large language model capabilities to your app. Gemini Live provides real-time audio processing, enabling natural voice conversations without separate ASR and TTS components. This page explains how to integrate Gemini Live through the Gemini Developer API. Enabling MLLM automatically disables ASR, LLM, and TTS since the MLLM handles end-to-end voice processing directly. ### Supported models The following Gemini Live models are supported: | Model | Description | | ------------------------------------------ | ------------------------------------------------------ | | `models/gemini-3.8-live` | General-purpose Gemini Live model. | | `models/gemini-3.8-live-extended-thinking` | Gemini Live model with an adjustable reasoning budget. | Use `models/gemini-3.8-live-extended-thinking` when the conversation benefits from additional reasoning. Set `thinking_level` to `low`, `medium`, or `high`. Omit `thinking_level` when using `models/gemini-3.8-live`. ### Sample configuration The following examples show how to configure Google Gemini Live MLLM (Gemini Developer API) when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import GeminiLive # client is your configured Agora client agent = ( Agent(client) .with_mllm(GeminiLive( api_key='your-google-api-key', model='models/gemini-3.8-live-extended-thinking', thinking_level='medium', voice='Charon', instructions='You are a friendly assistant.', transcribe_agent=True, transcribe_user=True, )) ) ``` **TypeScript SDK** ```typescript import { Agent, GeminiLive } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withMllm(new GeminiLive({ apiKey: 'your-google-api-key', model: 'models/gemini-3.8-live-extended-thinking', thinkingLevel: 'medium', voice: 'Charon', instructions: 'You are a friendly assistant.', transcribeAgent: true, transcribeUser: true, })); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithMllm( vendors.NewGeminiLive(vendors.GeminiLiveOptions{ APIKey: "your-google-api-key", Model: "models/gemini-3.8-live-extended-thinking", ThinkingLevel: vendors.GeminiThinkingLevelMedium, Voice: "Charon", Instructions: "You are a friendly assistant.", TranscribeAgent: Agora.Bool(true), TranscribeUser: Agora.Bool(true), }), ) ``` **REST API** Use the following `mllm` configuration in your request: ```json "mllm": { "enable": true, "api_key": "", "messages": [ { "role": "user", "content": "" } ], "params": { "model": "models/gemini-3.8-live-extended-thinking", "thinking_level": "medium", "instructions": "You are a friendly assistant.", "voice": "Charon", "affective_dialog": false, "proactive_audio": false, "transcribe_agent": true, "transcribe_user": true, "http_options": { "api_version": "v1beta" } }, "turn_detection": { // see details below }, "input_modalities": [ "audio" ], "output_modalities": [ "audio" ], "greeting_message": "Hi, how can I assist you today?", "failure_message": "Sorry, I encountered an issue. Please try again.", "vendor": "gemini" } ``` ### Turn detection To set up turn detection, add a `turn_detection` block inside the `mllm` object when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). > **Info** > > When `mllm.turn_detection` is defined, the top-level `turn_detection` object has no effect. The following examples show the supported configurations for Google Gemini Live. - **Server VAD** ```json "turn_detection": { "mode": "server_vad", "server_vad_config": { "prefix_padding_ms": 800, "silence_duration_ms": 640, "start_of_speech_sensitivity": "START_SENSITIVITY_HIGH", "end_of_speech_sensitivity": "END_SENSITIVITY_HIGH" } } ``` - **Agora VAD** ```json "turn_detection": { "mode": "agora_vad", "agora_vad_config": { "interrupt_duration_ms": 160, "prefix_padding_ms": 800, "silence_duration_ms": 640, "threshold": 0.5 } } ``` ### Key parameters **mllm required** **`enable` (boolean) optional** Enables the MLLM module. Replaces the deprecated `advanced_features.enable_mllm`. **`api_key` (string) required** The Google Gemini API key used to authenticate requests. You can generate an API key in [Google AI Studio](https://aistudio.google.com/apikey). **`messages` (array[object]) optional** An array of conversation history items passed to the model as context. Each item represents a single message in the conversation history. **`role` (string) required** The role of the message author. For example, `system` or `user`. **`content` (string) required** The content of the message. **`params` (object) required** Configuration object for the Gemini Live model. **`model` (string) required** Possible values: `models/gemini-3.8-live, models/gemini-3.8-live-extended-thinking` The Gemini Live model identifier. Set to `models/gemini-3.8-live-extended-thinking` to enable Extended Thinking. See [Supported models](#supported-models) for all available options. **`thinking_level` (string) optional** Possible values: `low, medium, high` The reasoning budget for `models/gemini-3.8-live-extended-thinking`. Do not set this parameter with `models/gemini-3.8-live`. **`instructions` (string) optional** System instructions that define the agent's behavior or tone. **`voice` (string) optional** The voice identifier for audio output. For example, `Aoede`, `Puck`, `Charon`, `Kore`, `Fenrir`, `Leda`, `Orus`, or `Zephyr`. **`affective_dialog` (boolean) optional** Whether to enable affective dialog, which allows the model to adapt its tone based on the user's emotional cues. **`proactive_audio` (boolean) optional** When enabled, the model may choose not to respond if the user's input does not require a reply, such as background speech or incomplete requests. **`transcribe_agent` (boolean) optional** Whether to transcribe the agent's speech in real time. **`transcribe_user` (boolean) optional** Whether to transcribe the user's speech in real time. **`http_options` (object) optional** HTTP request options for the Gemini Live API. **`api_version` (string) optional** The API version to use. For example, `v1beta`. **`turn_detection` (object) optional** Turn detection configuration for the MLLM module. For a full list of `turn_detection` parameters, see [`mllm.turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection). **`mode` (string) optional** Possible values: `agora_vad, server_vad` - `agora_vad`: Agora VAD-based detection. - `server_vad`: Vendor-side VAD-based detection. **`agora_vad_config` (object) optional** Configuration for Agora VAD-based turn detection. Applicable when `mode` is `agora_vad`. **`interrupt_duration_ms` (integer) optional** Minimum duration of speech in milliseconds required to trigger an interruption. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`threshold` (number) optional** VAD sensitivity threshold. A higher value reduces false positives. **`server_vad_config` (object) optional** Configuration for vendor-side VAD-based turn detection. Applicable when `mode` is `server_vad`. Parameters are passed through to the vendor. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`start_of_speech_sensitivity` (string) optional** Possible values: `START_SENSITIVITY_HIGH,START_SENSITIVITY_LOW` Sensitivity for start of speech detection. **`end_of_speech_sensitivity` (string) optional** Possible values: `END_SENSITIVITY_HIGH,END_SENSITIVITY_LOW` Sensitivity for end of speech detection. **`input_modalities` (array[string]) optional** Default value: `["audio"]` Input modalities for the MLLM. - `["audio"]`: Audio-only input - `["audio", "text"]`: Accept both audio and text input **`output_modalities` (array[string]) optional** Default value: `["audio"]` Output modalities for the MLLM. - `["audio"]`: Audio-only output - `["text", "audio"]`: Combined text and audio output **`greeting_message` (string) optional** The message the agent speaks when a user joins the channel. **`failure_message` (string) optional** The message the agent speaks when an error occurs. **`vendor` (string) required** The MLLM provider identifier. Set to `"gemini"` to use Google Gemini Live with the Gemini Developer API. For comprehensive API reference, real-time capabilities, and detailed parameter descriptions, see the [Google Gemini Live API](https://ai.google.dev/api/live). # Google Gemini Live (Vertex AI) (/en/ai/models/mllm/google-vertex-ai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Google Gemini Live provides multimodal large language model capabilities with real-time audio processing, enabling natural voice conversations without separate ASR/TTS components. This page covers integration using Vertex AI, authenticated with Google Cloud Application Default Credentials (ADC). Enabling MLLM automatically disables ASR, LLM, and TTS since the MLLM handles end-to-end voice processing directly. ### Sample configuration The following examples show how to configure Google Gemini Live (Vertex AI) MLLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import VertexAI # client is your configured Agora client agent = ( Agent(client) .with_mllm(VertexAI( model='gemini-live-2.5-flash-native-audio', project_id='', location='', adc_credentials_string='', voice='Aoede', instructions='You are a friendly assistant.', transcribe_agent=True, transcribe_user=True, )) ) ``` **TypeScript SDK** ```typescript import { Agent, VertexAI } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withMllm(new VertexAI({ model: 'gemini-live-2.5-flash-native-audio', projectId: '', location: '', adcCredentialsString: '', voice: 'Aoede', instructions: 'You are a friendly assistant.', transcribeAgent: true, transcribeUser: true, })); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithMllm( vendors.NewVertexAI(vendors.VertexAIOptions{ Model: "gemini-live-2.5-flash-native-audio", ProjectID: "", Location: "", ADCredentialsString: "", Voice: "Aoede", Instructions: "You are a friendly assistant.", TranscribeAgent: Agora.Bool(true), TranscribeUser: Agora.Bool(true), }), ) ``` **REST API** Use the following `mllm` configuration in your request: ```json "mllm": { "enable": true, "messages": [ { "role": "user", "content": "" } ], "params": { "model": "gemini-live-2.5-flash-native-audio", "instructions": "", "voice": "Aoede", "adc_credentials_string": "", "project_id": "", "location": "", "transcribe_agent": true, "transcribe_user": true }, "turn_detection": { // see details below }, "greeting_message": "Hi, how can I assist you today?", "input_modalities": [ "audio" ], "output_modalities": [ "audio" ], "vendor": "vertexai" } ``` ### Turn detection To set up turn detection, add a `turn_detection` block inside the `mllm` object when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). > **Info** > > When `mllm.turn_detection` is defined, the top-level `turn_detection` object has no effect. The following examples show the supported configurations for Google Gemini Live (Vertex AI). - **Server VAD** ```json "turn_detection": { "mode": "server_vad", "server_vad_config": { "prefix_padding_ms": 800, "silence_duration_ms": 640, "start_of_speech_sensitivity": "START_SENSITIVITY_HIGH", "end_of_speech_sensitivity": "END_SENSITIVITY_HIGH" } } ``` - **Agora VAD** ```json "turn_detection": { "mode": "agora_vad", "agora_vad_config": { "interrupt_duration_ms": 160, "prefix_padding_ms": 800, "silence_duration_ms": 640, "threshold": 0.5 } } ``` ### Key parameters **mllm required** **`enable` (boolean) optional** Enables the MLLM module. Replaces the deprecated `advanced_features.enable_mllm`. **`messages` (array[object]) optional** An array of conversation history items passed to the model as context. Each item represents a single message in the conversation history. **`role` (string) required** The role of the message author. For example, `user`. **`content` (string) required** The content of the message. **`params` (object) required** Main configuration object for the Gemini Live model. **`model` (string) required** The Gemini Live model identifier. See [supported models](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api#supported-models). **`instructions` (string) optional** System instructions that define the agent’s behavior or tone. **`voice` (string) optional** The voice identifier for audio output. For example, `Aoede`, `Puck`, `Charon`, `Kore`, `Fenrir`, `Leda`, `Orus`, or `Zephyr`. **`adc_credentials_string` (string) required** Base64-encoded Google Cloud Application Default Credentials (ADC). **`project_id` (string) required** Your Google Cloud project ID for Vertex AI access. **`location` (string) required** The Google Cloud region hosting the Gemini Live model. Check the Google Cloud documentation for the full list of available regions. **`transcribe_agent` (boolean) optional** Whether to transcribe the agent’s speech in real time. **`transcribe_user` (boolean) optional** Whether to transcribe the user’s speech in real time. **`turn_detection` (object) optional** Turn detection configuration for the MLLM module. For a full list of `turn_detection` parameters, see [`mllm.turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection). **`mode` (string) optional** Possible values: `agora_vad, server_vad` - `agora_vad`: Agora VAD-based detection. - `server_vad`: Vendor-side VAD-based detection. **`agora_vad_config` (object) optional** Configuration for Agora VAD-based turn detection. Applicable when `mode` is `agora_vad`. **`interrupt_duration_ms` (integer) optional** Minimum duration of speech in milliseconds required to trigger an interruption. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`threshold` (number) optional** VAD sensitivity threshold. A higher value reduces false positives. **`server_vad_config` (object) optional** Configuration for vendor-side VAD-based turn detection. Applicable when `mode` is `server_vad`. Parameters are passed through to the vendor. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`start_of_speech_sensitivity` (string) optional** Possible values: `START_SENSITIVITY_HIGH,START_SENSITIVITY_LOW` Sensitivity for start of speech detection. **`end_of_speech_sensitivity` (string) optional** Possible values: `END_SENSITIVITY_HIGH,END_SENSITIVITY_LOW` Sensitivity for end of speech detection. **`input_modalities` (array[string]) optional** Default value: `["audio"]` Input modalities for the MLLM. - `["audio"]`: Audio-only input - `["audio", "text"]`: Accept both audio and text input **`output_modalities` (array[string]) optional** Default value: `["audio"]` Output modalities for the MLLM. - `["audio"]`: Audio-only response - `["text", "audio"]`: Combined text and audio output **`greeting_message` (string) optional** The message the agent speaks when a user joins the channel. **`vendor` (string) required** The MLLM provider identifier. Set to `"vertexai"` to use Google Gemini Live with Vertex AI. For comprehensive API reference, real-time capabilities, and detailed parameter descriptions, see the [Google Gemini Live API](https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/live-api). # OpenAI Realtime API (/en/ai/models/mllm/openai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). OpenAI Realtime provides multimodal large language model capabilities with real-time audio processing, enabling natural voice conversations without separate ASR/TTS components. Enabling MLLM automatically disables ASR, LLM, and TTS since the MLLM handles end-to-end voice processing directly. ### Sample configuration The following examples show how to configure OpenAI Realtime MLLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import OpenAIRealtime # client is your configured Agora client agent = ( Agent(client) .with_mllm(OpenAIRealtime( api_key='your-openai-key', url='wss://api.openai.com/v1/realtime', model='gpt-realtime', voice='coral', instructions='You are a Conversational AI Agent, developed by Agora.', )) ) ``` **TypeScript SDK** ```typescript import { Agent, OpenAIRealtime } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withMllm(new OpenAIRealtime({ apiKey: 'your-openai-key', url: 'wss://api.openai.com/v1/realtime', model: 'gpt-realtime', voice: 'coral', instructions: 'You are a Conversational AI Agent, developed by Agora.', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithMllm( vendors.NewOpenAIRealtime(vendors.OpenAIRealtimeOptions{ APIKey: "your-openai-key", URL: "wss://api.openai.com/v1/realtime", Model: "gpt-realtime", Voice: "coral", Instructions: "You are a Conversational AI Agent, developed by Agora.", }), ) ``` **REST API** Use the following `mllm` configuration in your request: ```json "mllm": { "enable": true, "url": "wss://api.openai.com/v1/realtime", "api_key": "", "params": { "model": "gpt-realtime", "voice": "coral", "instructions": "You are a Conversational AI Agent, developed by Agora.", "input_audio_transcription": { "language": "", "model": "gpt-4o-mini-transcribe", "prompt": "expect words related to real-time engagement" } }, "turn_detection": { // see details below }, "greeting_message": "", "output_modalities": ["text", "audio"], "vendor": "openai" } ``` ### Turn detection To set up turn detection, add a `turn_detection` block inside the `mllm` object when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). > **Info** > > When `mllm.turn_detection` is defined, the top-level `turn_detection` object has no effect. The following examples show the supported `turn_detection` configurations for OpenAI Realtime API. - **Server VAD** ```json "turn_detection": { "mode": "server_vad", "server_vad_config": { "prefix_padding_ms": 800, "silence_duration_ms": 640, "threshold": 0.5 } } ``` - **Semantic VAD** ```json "turn_detection": { "mode": "semantic_vad", "semantic_vad_config": { "eagerness": "auto" } } ``` - **Agora VAD** ```json "turn_detection": { "mode": "agora_vad", "agora_vad_config": { "interrupt_duration_ms": 160, "prefix_padding_ms": 800, "silence_duration_ms": 640, "threshold": 0.5 } } ``` ### Key parameters **mllm required** **`enable` (boolean) optional** Enables the MLLM module. Replaces the deprecated `advanced_features.enable_mllm`. **`url` (string) required** The WebSocket URL for OpenAI Realtime API. **`api_key` (string) required** The API key used for authentication. Get your API key from the [OpenAI Console](https://platform.openai.com/api-keys). **`messages` (array[object]) optional** An array of conversation history items passed to the model as context. Each item represents a single message in the conversation history. **`role` (string) required** The role of the message author. For example, `system` or `user`. **`content` (string) required** The content of the message. **`params` (object) optional** Additional MLLM configuration parameters. See the MLLM provider pages in this section for details. - **Modalities override**: The `modalities` setting in params is overridden by `input_modalities` and `output_modalities`. - **Turn detection override**: The `turn_detection` setting in `params` is overridden by [`mllm.turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection). **`model` (string) optional** The model identifier. **`voice` (string) optional** The voice identifier for audio output. **`instructions` (string) optional** System instructions that define the assistant's behavior and personality. **`input_audio_transcription` (object) optional** Configuration for audio input transcription. **`language` (string) optional** The language of the input audio. Supplying the input language in ISO-639-1 format (For example `en`) improves accuracy and latency. **`model` (string) optional** The model to use for transcription. Current options are `gpt-4o-transcribe`, `gpt-4o-mini-transcribe`, and `whisper-1`. **`prompt` (string) optional** An optional text to guide the model's style or continue a previous audio segment. For `whisper-1`, the prompt is a list of keywords. For `gpt-4o-transcribe` models, the prompt is a free text string, for example "expect words related to technology". **`turn_detection` (object) optional** Turn detection configuration for the MLLM module. For a full list of `turn_detection` parameters, see [`mllm.turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection). **`mode` (string) optional** Possible values: `agora_vad, server_vad, semantic_vad` - `agora_vad`: Agora VAD-based detection. - `server_vad`: Vendor-side VAD-based detection. - `semantic_vad`: Semantic-based detection. **`agora_vad_config` (object) optional** Configuration for Agora VAD-based turn detection. Applicable when `mode` is `agora_vad`. **`interrupt_duration_ms` (integer) optional** Minimum duration of speech in milliseconds required to trigger an interruption. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`threshold` (number) optional** VAD sensitivity threshold. A higher value reduces false positives. **`server_vad_config` (object) optional** Configuration for vendor-side VAD-based turn detection. Applicable when `mode` is `server_vad`. Parameters are passed through to the vendor. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`threshold` (number) optional** VAD sensitivity threshold. **`idle_timeout_ms` (integer) optional** Idle timeout in milliseconds. **`semantic_vad_config` (object) optional** Configuration for semantic-based turn detection. Applicable when `mode` is `semantic_vad`. **`eagerness` (string) optional** Possible values: `auto, low, medium, high` Controls how eagerly the model ends its turn. **`input_modalities` (array[string]) optional** Default value: `["audio"]` MLLM input modalities: - `["audio"]`: Audio only - `["audio", "text"]`: Audio plus text **`output_modalities` (array[string]) optional** Default value: `["text", "audio"]` Output format options: `["text", "audio"]` for both text and voice responses. **`greeting_message` (string) optional** Initial message the agent speaks when a user joins the channel. **`vendor` (string) optional** MLLM provider identifier. Set to `openai` for OpenAI Realtime API. For comprehensive API reference, real-time capabilities, and detailed parameter descriptions, see the [OpenAI Realtime API documentation](https://platform.openai.com/docs/guides/realtime). # OpenAI GPT-Live (/en/ai/models/mllm/openai-gpt-live) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). OpenAI GPT-Live provides multimodal large language model capabilities with real-time audio processing, enabling natural voice conversations without separate ASR/TTS components. Enabling MLLM automatically disables ASR, LLM, and TTS since the MLLM handles end-to-end voice processing directly. ### Sample configuration The following examples show how to configure OpenAI GPT-Live MLLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, OpenAIGPTLive # client is your configured Agora client agent = ( Agent(client) .with_mllm(OpenAIGPTLive( api_key='your-openai-key', greeting="Hello! I'm GPT-live. How can I help you today?", model='gpt-live-1', voice='marin', prompt='your-system-prompt', )) ) ``` **TypeScript SDK** ```typescript import { Agent, OpenAIGPTLive } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withMllm(new OpenAIGPTLive({ apiKey: 'your-openai-key', greeting: "Hello! I'm GPT-live. How can I help you today?", model: 'gpt-live-1', voice: 'marin', prompt: 'your-system-prompt', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithMllm( vendors.NewOpenAIGPTLive(vendors.OpenAIGPTLiveOptions{ APIKey: "your-openai-key", GreetingMessage: "Hello! I'm GPT-live. How can I help you today?", Model: "gpt-live-1", Voice: "marin", Prompt: "your-system-prompt", }), ) ``` **REST API** Use the following `mllm` configuration in your request: ```json "mllm": { "enable": true, "vendor": "openai_gpt_live", "api_key": "", "url": "wss://api.openai.com/v1/live/sessions", "greeting_message": "Hello! I'm GPT-live. How can I help you today?", "params": { "model": "gpt-live-1", "voice": "marin", "prompt": "" } } ``` ### Tool calling GPT-Live can call tools defined directly on the MLLM configuration. Set `mllm.mcp_servers`, enable `advanced_features.enable_tools`, and set `params.tool_enabled` to `true` to advertise those tools to GPT-Live: ```json "mllm": { "mcp_servers": [ { "name": "lookup", "endpoint": "https://tools.example/mcp", "transport": "streamable_http" } ], "params": { "tool_enabled": true } }, "advanced_features": { "enable_tools": true } ``` ### Key parameters **mllm required** **`enable` (boolean) optional** Enables the MLLM module. Replaces the deprecated `advanced_features.enable_mllm`. **`vendor` (string) required** MLLM provider identifier. Set to `openai_gpt_live` for OpenAI GPT-Live. **`api_key` (string) required** The OpenAI API key used for authentication. **`url` (string) optional** Default value: `wss://api.openai.com/v1/live/sessions` The WebSocket URL for OpenAI GPT-Live. **`messages` (array[object]) optional** An array of conversation history items passed to the model as context. Each item represents a single message in the conversation history. **`role` (string) required** The role of the message author. For example, `system` or `user`. **`content` (string) required** The content of the message. **`input_modalities` (array[string]) optional** Default value: `["audio"]` MLLM input modalities: - `["audio"]`: Audio only - `["audio", "text"]`: Audio plus text **`output_modalities` (array[string]) optional** Default value: `["text", "audio"]` Output format options: `["text", "audio"]` for both text and voice responses. **`greeting_message` (string) optional** Initial message the agent speaks when a user joins the channel. **`failure_message` (string) optional** The message the agent speaks when an error occurs. **`mcp_servers` (array[object]) optional** MCP servers whose tools GPT-Live can call. See [Tool calling](#tool-calling). **`params` (object) optional** Additional MLLM configuration parameters. **`model` (string) optional** Default value: `gpt-live-1` The model identifier. Specify another supported model to override the default. **`voice` (string) optional** Default value: `marin` The voice identifier for audio output. **`prompt` (string) optional** Session instructions that define the assistant's behavior and personality. **`tool_enabled` (boolean) optional** Default value: `false` Advertises the agent's graph tools to GPT-Live for tool calling. See [Tool calling](#tool-calling). Does not control delegate built-in tools. > **Caution: Limitations** > > GPT-Live doesn't support turn detection or input audio transcription. > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Additional parameters are passed through directly to the underlying vendor without validation. # xAI Grok (/en/ai/models/mllm/xai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). xAI Grok provides multimodal large language model capabilities with real-time audio processing, enabling natural voice conversations without separate ASR/TTS components. This page covers integration using the xAI Realtime API, authenticated with an API key obtained from the xAI developer console. Enabling MLLM automatically disables ASR, LLM, and TTS since the MLLM handles end-to-end voice processing directly. ### Sample configuration The following examples show how to configure xAI Grok MLLM when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import XaiGrok # client is your configured Agora client agent = ( Agent(client) .with_mllm(XaiGrok( api_key='your-xai-key', voice='eve', language='en', sample_rate=24000, )) ) ``` **TypeScript SDK** ```typescript import { Agent, XaiGrok } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withMllm(new XaiGrok({ apiKey: 'your-xai-key', voice: 'eve', language: 'en', sampleRate: 24000, })); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithMllm( vendors.NewXaiGrok(vendors.XaiGrokOptions{ APIKey: "your-xai-key", Voice: "eve", Language: "en", SampleRate: Agora.Int(24000), }), ) ``` **REST API** Use the following `mllm` configuration in your request: ```json "mllm": { "enable": true, "vendor": "xai", "url": "wss://api.x.ai/v1/realtime", "api_key": "", "messages": [ { "role": "user", "content": "" } ], "output_modalities": [ "audio", "text" ], "params": { "voice": "eve", "language": "en", "sample_rate": 24000 }, "turn_detection": { // see details below }, "greeting_message": "Hello, how can I help?" } ``` ### Turn detection To set up turn detection, add a `turn_detection` block inside the `mllm` object when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). > **Info** > > When `mllm.turn_detection` is defined, the top-level `turn_detection` object has no effect. The following examples show the supported configurations for xAI Grok. - **Server VAD** ```json "turn_detection": { "mode": "server_vad", "server_vad_config": { "threshold": 0.5, "prefix_padding_ms": 640, "silence_duration_ms": 900 } } ``` - **Agora VAD** ```json "turn_detection": { "mode": "agora_vad", "agora_vad_config": { "threshold": 0.5, "interrupt_duration_ms": 160, "prefix_padding_ms": 800, "silence_duration_ms": 640 } } ``` ### Key parameters **mllm required** **`enable` (boolean) optional** Enables the MLLM module. Replaces the deprecated `advanced_features.enable_mllm`. **`vendor` (string) required** The MLLM provider identifier. Set to `"xai"` to use xAI Grok. **`url` (string) required** The WebSocket endpoint for the xAI Realtime API. Set to `"wss://api.x.ai/v1/realtime"`. **`api_key` (string) required** The xAI API key used to authenticate requests. Get your API key from the [xAI Console](https://console.x.ai/home). **`messages` (array[object]) optional** An array of conversation history items passed to the model as context. Each item represents a single message in the conversation history. **`role` (string) required** The role of the message author. For example, `system` or `user`. **`content` (string) required** The content of the message. **`params` (object) required** Configuration object for the xAI Grok model. **`voice` (string) optional** The voice identifier for audio output. For example, `eve` or `rex`. **`language` (string) optional** The language code for speech recognition and synthesis. For example, `en`. **`sample_rate` (integer) optional** The audio sample rate in Hz. For example, `24000`. **`turn_detection` (object) optional** Turn detection configuration for the MLLM module. For a full list of `turn_detection` parameters, see [`mllm.turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection). **`mode` (string) optional** Possible values: `agora_vad, server_vad` - `agora_vad`: Agora VAD-based detection. - `server_vad`: Vendor-side VAD-based detection. **`agora_vad_config` (object) optional** Configuration for Agora VAD-based turn detection. Applicable when `mode` is `agora_vad`. **`interrupt_duration_ms` (integer) optional** Minimum duration of speech in milliseconds required to trigger an interruption. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`threshold` (number) optional** VAD sensitivity threshold. A higher value reduces false positives. **`server_vad_config` (object) optional** Configuration for vendor-side VAD-based turn detection. Applicable when `mode` is `server_vad`. Parameters are passed through to the vendor. **`threshold` (number) optional** VAD sensitivity threshold. A higher value reduces false positives. **`prefix_padding_ms` (integer) optional** Duration of audio in milliseconds to include before the detected speech start. **`silence_duration_ms` (integer) optional** Duration of silence in milliseconds required to determine end of speech. **`output_modalities` (array[string]) optional** Default value: `["audio"]` Output modalities for the MLLM. - `["audio"]`: Audio-only output - `["text", "audio"]`: Combined text and audio output **`greeting_message` (string) optional** The message the agent speaks when a user joins the channel. **`failure_message` (string) optional** The message the agent speaks when an error occurs. For comprehensive API reference, real-time capabilities, and detailed parameter descriptions, see the [xAI Voice Agent API](https://docs.x.ai/developers/model-capabilities/audio/voice-agent). # Amazon Polly (/en/ai/models/tts/amazon) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Amazon provides natural-sounding text-to-speech with customizable voice instructions and multiple voice options. ### Sample configuration The following examples show how to configure Amazon Polly TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import AmazonTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(AmazonTTS( access_key='your-aws-access-key', secret_key='your-aws-secret-key', region='us-east-1', voice_id='Joanna', engine='neural', )) ) ``` **TypeScript SDK** ```typescript import { Agent, AmazonTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new AmazonTTS({ accessKey: 'your-aws-access-key', secretKey: 'your-aws-secret-key', region: 'us-east-1', voiceId: 'Joanna', engine: 'neural', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewAmazonTTS(vendors.AmazonTTSOptions{ AccessKey: "your-aws-access-key", SecretKey: "your-aws-secret-key", Region: "us-east-1", VoiceID: "Joanna", Engine: "neural", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "amazon", "params": { "aws_access_key_id": "", "aws_secret_access_key": "", "region_name": "", "voice": "Joanna", "engine": "neural" } } ``` ### Key parameters **params required** **`aws_access_key_id` (string) required** The AWS access key ID used for authentication. Get your access key from the [AWS IAM Console](https://console.aws.amazon.com/iam/). **`aws_secret_access_key` (string) required** The AWS secret access key used for authentication. Get your secret key from the [AWS IAM Console](https://console.aws.amazon.com/iam/). **`region_name` (string) required** The AWS region where the Polly service is hosted, for example, `us-east-1`, `us-west-2`, or `eu-west-1`. See [AWS regions](https://docs.aws.amazon.com/general/latest/gr/pol.html) for available regions. **`voice` (string) required** The voice ID to use for speech synthesis, for example, `Joanna`, `Matthew`, or `Ivy`. See [available voices](https://docs.aws.amazon.com/polly/latest/dg/voicelist.html) for supported voice IDs. **`engine` (string) required** The engine type to use for speech synthesis. Supported values: `standard`, `neural`, `long-form`, `generative`. See [engine documentation](https://docs.aws.amazon.com/polly/latest/dg/voicelist.html) for details on each engine type. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Amazon Polly documentation](https://docs.aws.amazon.com/polly/latest/dg/what-is.html). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Cartesia (/en/ai/models/tts/cartesia) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Cartesia provides ultra-fast, low-latency text-to-speech with real-time streaming capabilities, optimized for interactive conversational AI applications. ### Sample configuration The following examples show how to configure Cartesia TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import CartesiaTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(CartesiaTTS( api_key='your-cartesia-key', # omit api_key and set credential_mode='managed' to use Agora-managed mode model_id='sonic-2', voice_id='', )) ) ``` **TypeScript SDK** ```typescript import { Agent, CartesiaTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new CartesiaTTS({ apiKey: 'your-cartesia-key', // omit apiKey and set credentialMode: CredentialMode.Managed to use Agora-managed mode modelId: 'sonic-2', voiceId: '', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewCartesiaTTS(vendors.CartesiaTTSOptions{ APIKey: "your-cartesia-key", // omit APIKey and set CredentialMode: agentkit.CredentialModeManaged to use Agora-managed mode ModelID: "sonic-2", VoiceID: "", }), ) ``` **REST API** - **Managed mode** To use Cartesia TTS with Agora-managed credentials, set `credential_mode` to `"managed"` in the `tts` block. When using managed mode, `params.api_key` is not required. Set `params.model_id` to `sonic-3.5` or `sonic-3.6`. You can still configure settings such as `voice`, `output_format`, and `language`. For more information, see [Use managed mode](/en/ai/build/managed-mode). ```json "tts": { "credential_mode": "managed", "vendor": "cartesia", "params": { "model_id": "sonic-3.6", "voice": { "mode": "id", "id": "" }, "output_format": { "container": "raw", "sample_rate": 16000 }, "language": "en" } } ``` - **BYOK** ```json "tts": { "vendor": "cartesia", "params": { "api_key": "", "model_id": "sonic-2", "base_url": "wss://api.cartesia.ai", "voice": { "mode": "id", "id": "" }, "output_format": { "container": "raw", "sample_rate": 16000 }, "language": "en" } } ``` ### Key parameters The following parameters are required when using your own API key (BYOK). When using managed mode, `api_key` is not required. For more information, see [Use managed mode](/en/ai/build/managed-mode). **params required** **`api_key` (string) optional** The Cartesia API key used to authenticate requests. Required when using your own API key (BYOK). Get your API key from the [Cartesia Console](https://play.cartesia.ai/sign-up). **`model_id` (string) required** The identifier of the TTS model to use. For example, `sonic-2`. For managed mode, use `sonic-3.5` or `sonic-3.6`. **`base_url` (string) optional** The WebSocket URL for the Cartesia streaming API. For example, `wss://api.cartesia.ai`. **`voice` (object) required** Voice configuration object. **`mode` (string) required** Voice selection mode. Use `id` to select by voice identifier. **`id` (string) required** The identifier of the selected voice for speech synthesis. **`output_format` (object) optional** Audio output format configuration **`container` (string) optional** Audio container format for the output stream. **`sample_rate` (number) optional** Default value: `16000` Possible values: `8000, 16000, 22050, 24000, 44100, 48000` Audio sampling rate in Hz **`language` (string) optional** Target language for speech synthesis. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Cartesia TTS documentation](https://docs.cartesia.ai/). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Deepgram (/en/ai/models/tts/deepgram) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Deepgram provides low-latency text-to-speech with a wide range of voices, optimized for real-time conversational AI applications. ### Sample configuration The following examples show how to configure Deepgram TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import DeepgramTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(DeepgramTTS( api_key='your-deepgram-key', model='aura-2-thalia-en', )) ) ``` **TypeScript SDK** ```typescript import { Agent, DeepgramTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new DeepgramTTS({ apiKey: 'your-deepgram-key', model: 'aura-2-thalia-en', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewDeepgramTTS(vendors.DeepgramTTSOptions{ APIKey: "your-deepgram-key", Model: "aura-2-thalia-en", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "deepgram", "params": { "api_key": "", "base_url": "wss://api.deepgram.com/v1/speak", "model": "aura-2-thalia-en", "sample_rate": 24000 } } ``` ### Key parameters **params required** **`api_key` (string) required** The Deepgram API key used to authenticate requests. Get your API key from the [Deepgram Console](https://console.deepgram.com/). **`model` (string) required** The identifier of the TTS model to use. See [Deepgram voices and languages](https://developers.deepgram.com/docs/tts-models). **`base_url` (string) optional** The WebSocket URL for the Deepgram streaming API. Defaults to `wss://api.deepgram.com/v1/speak`. **`sample_rate` (number) optional** The audio sampling rate in Hz. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Deepgram TTS documentation](https://developers.deepgram.com/docs/text-to-speech). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # ElevenLabs (/en/ai/models/tts/elevenlabs) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). ElevenLabs provides highly realistic AI voices with advanced prosody and natural speech patterns, delivering lifelike audio synthesis with emotional nuance and conversational flow. > **Caution: Paid plan required** > > You need a **paid ElevenLabs plan** for reliable TTS integration. > > ElevenLabs may restrict or disable free-tier accounts due to abuse-detection mechanisms, even if free credits are available. To avoid missing audio responses during testing and production, ensure you use a paid plan. ### Sample configuration The following examples show how to configure ElevenLabs TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import ElevenLabsTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(ElevenLabsTTS( key='your-elevenlabs-key', model_id='eleven_flash_v2_5', voice_id='pNInz6obpgDQGcFmaJgB', base_url='wss://api.elevenlabs.io/v1', )) ) ``` **TypeScript SDK** ```typescript import { Agent, ElevenLabsTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new ElevenLabsTTS({ key: 'your-elevenlabs-key', modelId: 'eleven_flash_v2_5', voiceId: 'pNInz6obpgDQGcFmaJgB', baseUrl: 'wss://api.elevenlabs.io/v1', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewElevenLabsTTS(vendors.ElevenLabsTTSOptions{ Key: "your-elevenlabs-key", ModelID: "eleven_flash_v2_5", VoiceID: "pNInz6obpgDQGcFmaJgB", BaseURL: "wss://api.elevenlabs.io/v1", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "elevenlabs", "params": { "base_url": "wss://api.elevenlabs.io/v1", "key": "", "model_id": "eleven_flash_v2_5", "voice_id": "pNInz6obpgDQGcFmaJgB", "sample_rate": 24000 } } ``` ### Key parameters **params required** **`base_url` (string) required** The endpoint URL for the ElevenLabs TTS service. See [Data residency](https://elevenlabs.io/docs/product-guides/administration/data-residency). **`key` (string) required** The API key used for authentication. Get your API key from the [ElevenLabs Console](https://elevenlabs.io/). **`model_id` (string) required** Identifier of the model to be used. Popular options include `eleven_flash_v2_5` for speed or `eleven_multilingual_v2` for quality. **`voice_id` (string) required** The identifier for the selected voice for speech synthesis. Browse available voices in the [Voice Library](https://elevenlabs.io/voice-library). **`sample_rate` (number) optional** Default value: `24000` Audio sampling rate in Hz. Common values: `16000`, `22050`, `24000`, `44100`. **`speed` (number) optional** Default value: `1.0` Speed up or slow down the speed of the generated speech. Range `0.7` to `1.2` inclusive. **`stability` (number) optional** Controls voice stability. Higher values `(0.8-1.0)` produce more consistent speech, lower values `(0.0-0.5)` add more variation. **`similarity_boost` (number) optional** Enhances similarity to the original voice. Range: `0.0-1.0`. Higher values stick closer to the training voice. **`style` (number) optional** Controls speaking style and expressiveness. Higher values increase emotional range and variation. **`use_speaker_boost` (boolean) optional** Improves voice quality and similarity when enabled. Recommended for most use cases. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [ElevenLabs TTS documentation](https://elevenlabs.io/docs/capabilities/text-to-speech). # Fish Audio (/en/ai/models/tts/fish-audio) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Fish Audio provides text-to-speech (TTS) with flexible models and high-quality synthetic voices. ### Sample configuration The following examples show how to configure Fish Audio TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import FishAudioTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(FishAudioTTS( key='your-fishaudio-key', # omit key and set credential_mode='managed' to use Agora-managed mode reference_id='', backend='speech-1.5', )) ) ``` **TypeScript SDK** ```typescript import { Agent, FishAudioTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new FishAudioTTS({ key: 'your-fishaudio-key', // omit key and set credentialMode: CredentialMode.Managed to use Agora-managed mode referenceId: '', backend: 'speech-1.5', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewFishAudioTTS(vendors.FishAudioTTSOptions{ Key: "your-fishaudio-key", // omit Key and set CredentialMode: agentkit.CredentialModeManaged to use Agora-managed mode ReferenceID: "", Backend: "speech-1.5", }), ) ``` **REST API** - **Managed mode** To use Fish Audio TTS with Agora-managed credentials, set `credential_mode` to `"managed"` in the `tts` block. When using managed mode, `params.api_key` is not required. Set `params.backend` to `s2.1-pro`. For more information, see [Use managed mode](/en/ai/build/managed-mode). ```json "tts": { "credential_mode": "managed", "vendor": "fishaudio", "params": { "reference_id": "", "backend": "s2.1-pro" } } ``` - **BYOK** ```json "tts": { "vendor": "fishaudio", "params": { "api_key": "", "reference_id": "", "backend": "speech-1.5" } } ``` ### Key parameters The following parameters are required when using your own API key (BYOK). When using managed mode, `api_key` is not required. For more information, see [Use managed mode](/en/ai/build/managed-mode). **params required** **`api_key` (string) optional** The Fish Audio API key used to authenticate requests. Required when using your own API key (BYOK). **`reference_id` (string) required** The identifier of the voice model to use for speech synthesis. **`backend` (string) required** The backend model version to use. For example, `speech-1.5`. For managed mode, use `s2.1-pro`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Fish Audio documentation](https://docs.fish.audio/sdk-reference/python/api-reference). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Gemini (/en/ai/models/tts/gemini) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Google Gemini provides text-to-speech (TTS) with expressive voices that you can steer using natural-language style instructions. Use it as the TTS component in a cascading pipeline with any supported ASR and LLM vendor. ### Sample configuration The following examples show how to configure Gemini TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent, GeminiTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(GeminiTTS( api_key='your-google-api-key', model='gemini-3.8-flash-tts', voice='Puck', style='warm and reassuring', )) ) ``` **TypeScript SDK** ```typescript import { Agent, GeminiTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new GeminiTTS({ apiKey: 'your-google-api-key', model: 'gemini-3.8-flash-tts', voice: 'Puck', style: 'warm and reassuring', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewGeminiTTS(vendors.GeminiTTSOptions{ APIKey: "your-google-api-key", Model: "gemini-3.8-flash-tts", Voice: "Puck", Style: "warm and reassuring", }), ) ``` **REST API** > **Info: Preview endpoint** > > Gemini TTS is available as an early access preview. Send your [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) request to the following preview endpoint instead of the standard endpoint, and include the required header: > > - **URL**: `https://partner.ai.agora.io/preview/api/conversational-ai-agent/v2/projects//join` > - **Header**: `agora-feature: gemini-live` > > Send all later requests for the same agent, such as stopping the agent, to the preview endpoint with the same header. Use the following `tts` configuration in your request: ```json "tts": { "vendor": "gemini", "params": { "api_key": "", "model": "gemini-3.8-flash-tts", "voice": "Puck", "style": "warm and reassuring" } } ``` ### Key parameters **params required** **`api_key` (string) required** The Google Gemini API key used to authenticate requests. You can generate an API key in [Google AI Studio](https://aistudio.google.com/apikey). **`model` (string) required** The Gemini TTS model identifier. Set to `gemini-3.8-flash-tts` to use Gemini 3.8 Flash TTS. **`voice` (string) required** The name of the prebuilt voice to use. For example, `Puck`. For the full list of voices, see [Voice options](https://ai.google.dev/gemini-api/docs/speech-generation#voices) in the Gemini API documentation. **`style` (string) optional** A natural-language instruction that controls how the agent speaks, such as its tone, pace, accent, or whether it whispers. For example, `warm and reassuring`. If you don't set this parameter, the model uses its default delivery. For guidance on writing style instructions, see [Control speech style with prompts](https://ai.google.dev/gemini-api/docs/speech-generation#controllable). > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Gemini API speech generation documentation](https://ai.google.dev/gemini-api/docs/speech-generation). ### Add vocal sounds and pauses Gemini TTS supports inline tags for momentary vocal sounds and pauses, such as ``, ``, ``, ``, and ``. Gemini TTS interprets these tags instead of reading them aloud. To use them, instruct your LLM in its system prompt to include tags sparingly in its replies. Don't use tags for sound effects, such as applause, or to change how the agent speaks, such as whispering. To set the delivery style, use the `style` parameter. > **Info** > > The vocal tags inserted by the LLM remain in the agent's text transcript. If your app displays the transcript, remove the tags before showing it to users. # Generic TTS (/en/ai/models/tts/generic-http) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). The `generic_http` TTS vendor lets you integrate a custom TTS service that implements the OpenAI TTS protocol into the Conversational AI Engine. For a walkthrough of preparing and verifying a compatible TTS service, see [Connect your own TTS service](/en/ai/build/custom-model-integration/custom-tts). ### Sample configuration Use the following `tts` configuration when starting a conversational AI agent using the REST API. `generic_http` requires `tts.url`, and at least one of `tts.headers.Authorization` or `tts.params.api_key` for authentication. - **Authenticate using `headers`** (recommended) ```json "tts": { "vendor": "generic_http", "url": "https://your-tts-service.example.com/v1/audio/speech", "headers": { "Authorization": "Bearer your_tts_api_key" }, "params": { "model": "gpt-4o-mini-tts", "voice": "alloy", "speed": 1.0, "sample_rate": 16000, "response_format": "pcm", "instructions": "calm", "enable_request_id": false } } ``` - **Authenticate using `params.api_key`** ```json "tts": { "vendor": "generic_http", "url": "https://your-tts-service.example.com/v1/audio/speech", "params": { "api_key": "your_tts_api_key", "model": "gpt-4o-mini-tts", "voice": "alloy", "speed": 1.0, "sample_rate": 16000, "response_format": "pcm", "instructions": "calm", "enable_request_id": false } } ``` If you provide both `tts.headers.Authorization` and `tts.params.api_key`, the Conversational AI Engine uses `tts.headers.Authorization`. ### Key parameters **tts required** **`url` (string) required** The OpenAI TTS protocol compatible service endpoint. **`headers` (object) optional** Custom request headers to include in requests to the TTS service, such as authentication credentials. Provide at least one of `headers.Authorization` or `params.api_key`. If you provide both, the Conversational AI Engine uses `headers.Authorization`. **`params` (object) required** **`api_key` (string) optional** The API key used to authenticate with the TTS service. Provide at least one of `headers.Authorization` or `params.api_key`. If you provide both, the Conversational AI Engine uses `headers.Authorization`. **`model` (string) optional** The name of the TTS model. **`voice` (string) optional** The voice name. Omit this parameter if your TTS service does not support multiple voices. **`speed` (number) optional** The speech rate. **`sample_rate` (integer) optional** Default value: `16000` The sample rate, in Hz, of the output audio. If your TTS service does not support multiple sample rates, make sure the sample rate of the returned audio matches this value. **`response_format` (string) optional** Default value: `pcm` The output audio format. Currently only `pcm` is supported. **`instructions` (string) optional** Instructions for voice style, emotion, or other playback directives. **`enable_request_id` (boolean) optional** Default value: `false` Whether to include `request_id`, `request_seq_id`, and `request_end` in the TTS request body. > **Caution** > > Your TTS service must implement the OpenAI TTS protocol. The parameters listed on this page are validated for use with Conversational AI Engine. Any additional fields in `params` are passed through directly to your TTS service without validation. This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Google (/en/ai/models/tts/google) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Google provides fast, reliable text-to-speech (TTS) with customizable voices. ### Sample configuration The following examples show how to configure Google TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import GoogleTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(GoogleTTS( key='', voice_name='en-US-Chirp3-HD-Charon', )) ) ``` **TypeScript SDK** ```typescript import { Agent, GoogleTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new GoogleTTS({ key: '', voiceName: 'en-US-Chirp3-HD-Charon', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewGoogleTTS(vendors.GoogleTTSOptions{ Key: "", VoiceName: "en-US-Chirp3-HD-Charon", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "google", "params": { "credentials": "", "VoiceSelectionParams": { "name": "en-US-Chirp3-HD-Charon" }, "AudioConfig": { "speaking_rate": 1.0, "sample_rate_hertz": 24000 } } } ``` ### Key parameters **params required** **`credentials` (string) required** The Google Cloud service account credentials JSON string used for authentication. Get your credentials from the [Google Cloud Console](https://console.cloud.google.com/). **`VoiceSelectionParams` (object) required** **`name` (string) required** The name of the voice to use, for example, `en-US-Chirp3-HD-Charon` or `en-US-Neural2-A`. See [supported voices](https://cloud.google.com/text-to-speech/docs/voices) for available voice names. **`AudioConfig` (object) optional** **`speaking_rate` (number) optional** The speed of speech. Valid range is `0.25` to `2.0`, where `1.0` is the normal speed. Values less than `1.0` slow down the speech, while values greater than `1.0` speed it up. **`sample_rate_hertz` (integer) optional** The sample rate in Hertz for the audio output, for example, `24000` or `16000`. The default value depends on the selected voice. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Google documentation](https://cloud.google.com/text-to-speech/docs/create-audio-text-streaming). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Gradium (/en/ai/models/tts/gradium) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Gradium provides enterprise-grade AI voice generation with text-to-speech (TTS) models. ### Sample configuration The following examples show how to configure Gradium TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import GradiumTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(GradiumTTS( api_key='', url='wss://api.gradium.ai/api/speech/tts', model_name='default', voice_id='', sample_rate=16000, )) ) ``` **TypeScript SDK** ```typescript import { Agent, GradiumTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new GradiumTTS({ apiKey: '', url: 'wss://api.gradium.ai/api/speech/tts', modelName: 'default', voiceId: '', sampleRate: 16000, })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client sampleRate := vendors.SampleRate16kHz agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewGradiumTTS(vendors.GradiumTTSOptions{ APIKey: "", URL: "wss://api.gradium.ai/api/speech/tts", ModelName: "default", VoiceID: "", SampleRate: &sampleRate, }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "gradium", "params": { "api_key": "", "url": "wss://api.gradium.ai/api/speech/tts", "model_name": "default", "voice_id": "", "sample_rate": 16000 } } ``` ### Key parameters **params required** **`api_key` (string) required** The Gradium API key used to authenticate requests. You must provide a valid key for the service to function. **`url` (string) optional** The WebSocket endpoint for streaming TTS output. For example, `wss://api.gradium.ai/api/speech/tts`. **`model_name` (string) optional** The TTS model to use. For example, `default`. **`voice_id` (string) optional** The voice identifier to use. **`sample_rate` (number) optional** The audio sample rate in Hz. For example, `16000`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Gradium documentation](https://docs.gradium.ai/guides/text-to-speech). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Hume AI (/en/ai/models/tts/humeai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Hume AI provides emotion-aware text-to-speech technology that generates natural, expressive voices with emotional intelligence. The platform offers both curated voices from the Voice Library and support for custom voice creation, enabling personalized audio experiences. ### Sample configuration The following examples show how to configure Hume AI TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import HumeAITTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(HumeAITTS( key='your-hume-key', voice_id='your-voice-id', provider='HUME_AI', )) ) ``` **TypeScript SDK** ```typescript import { Agent, HumeAITTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new HumeAITTS({ key: 'your-hume-key', voiceId: 'your-voice-id', provider: 'HUME_AI', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewHumeAITTS(vendors.HumeAITTSOptions{ Key: "your-hume-key", VoiceID: "your-voice-id", Provider: "HUME_AI", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "humeai", "params": { "key": "", "voice_id": "", "base_url": "https://api.hume.ai", "provider": "HUME_AI", "speed": 1, "trailing_silence": 0.35 } } ``` ### Key parameters **params required** **`key` (string) required** The API key used for authentication with Hume AI's services. Get your API key from the Hume AI console. **`voice_id` (string) required** The identifier of the voice to use for speech synthesis. Choose from available voices in your Hume AI dashboard. **`base_url` (string) optional** The base URL for the Hume AI API. For example, `https://api.hume.ai`. **`provider` (string) required** Default value: `CUSTOM_VOICE` Possible values: `HUME_AI, CUSTOM_VOICE` The voice provider type. - `"HUME_AI"`: Use a pre-built voice from Hume's curated Voice Library. - `"CUSTOM_VOICE"`: Use your own custom-trained voice. **`speed` (number) optional** Default value: `1` Possible values: `0.25 to 3.0` Controls the playback speed of the generated speech. Higher values increase speech rate. **`trailing_silence` (number) optional** Default value: `0.35` Possible values: `0 to 5` Duration of silence (in seconds) to add at the end of each utterance. Useful for natural conversation pacing. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Hume AI TTS documentation](https://dev.hume.ai/docs/text-to-speech-tts/overview). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Microsoft Azure (/en/ai/models/tts/microsoft) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Microsoft Azure offers neural voices in multiple languages with options for different speaking styles and emotions, providing enterprise-grade text-to-speech capabilities with high-quality audio output. ### Sample configuration The following examples show how to configure Microsoft Azure TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import MicrosoftTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(MicrosoftTTS( key='your-azure-key', region='eastus', voice_name='en-US-AndrewMultilingualNeural', speed=1.0, volume=70, )) ) ``` **TypeScript SDK** ```typescript import { Agent, MicrosoftTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new MicrosoftTTS({ key: 'your-azure-key', region: 'eastus', voiceName: 'en-US-AndrewMultilingualNeural', speed: 1.0, volume: 70, })); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewMicrosoftTTS(vendors.MicrosoftTTSOptions{ Key: "your-azure-key", Region: "eastus", VoiceName: "en-US-AndrewMultilingualNeural", Speed: Agora.Float64(1.0), Volume: Agora.Float64(70), }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "microsoft", "params": { "key": "", "region": "eastus", "voice_name": "en-US-AndrewMultilingualNeural", "speed": 1.0, "volume": 70, "sample_rate": 24000 } } ``` ### Key parameters **params required** **`key` (string) required** The API key used for authentication. Get your API key from the [Azure Portal](https://portal.azure.com/). **`region` (string) required** The Azure region where the speech service is hosted (For example, `eastus`, `westus2`). **`voice_name` (string) required** The identifier for the selected voice for speech synthesis. See [available voices](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/language-support?tabs=tts) for options. **`speed` (number) optional** Default value: `1.0` Speaking rate of the text. Values between `0.5` and `2.0` times the original audio speed. **`volume` (number) optional** Default value: `100` Audio volume as a number between `0.0` and `100.0`, where `0.0` is quietest and `100.0` is loudest. **`sample_rate` (integer) optional** Default value: `24000` Audio sampling rate in Hz. Common values: `16000`, `24000`, `48000`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Microsoft Azure TTS documentation](https://learn.microsoft.com/en-us/azure/ai-services/speech-service/text-to-speech). # MiniMax (/en/ai/models/tts/minimax) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). MiniMax provides text-to-speech (TTS) with multiple voice styles and low-latency streaming output. ### Sample configuration The following examples show how to configure MiniMax TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import MiniMaxTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(MiniMaxTTS( key='your-minimax-key', # omit key, group_id, voice_id, and url to use Agora-managed mode group_id='your-minimax-group-id', model='speech-2.8-turbo', voice_id='English_captivating_female1', url='wss://api-uw.minimax.io/ws/v1/t2a_v2', )) ) ``` **TypeScript SDK** ```typescript import { Agent, MiniMaxTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new MiniMaxTTS({ key: 'your-minimax-key', // omit key, groupId, voiceId, and url to use Agora-managed mode groupId: 'your-minimax-group-id', model: 'speech-2.8-turbo', voiceId: 'English_captivating_female1', url: 'wss://api-uw.minimax.io/ws/v1/t2a_v2', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewMiniMaxTTS(vendors.MiniMaxTTSOptions{ Key: "your-minimax-key", // omit Key, GroupID, VoiceID, and URL to use Agora-managed mode GroupID: "your-minimax-group-id", Model: "speech-2.8-turbo", VoiceID: "English_captivating_female1", URL: "wss://api-uw.minimax.io/ws/v1/t2a_v2", }), ) ``` **REST API** - **Managed mode** To use MiniMax TTS with Agora-managed credentials, set `credential_mode` to `"managed"` in the `tts` block. When using managed mode, `params.key` and `params.group_id` are not required. You can still use the `tts` field to configure additional settings such as `voice_setting`. For more information, see [Use managed mode](/en/ai/build/managed-mode). ```json "tts": { "credential_mode": "managed", "vendor": "minimax", "params": { "url": "wss://api.minimax.io/ws/v1/t2a_v2", "model": "speech-2.8-turbo", "voice_setting": { "voice_id": "English_captivating_female1", "speed": 1.0 }, "audio_setting": { "sample_rate": 44100 } } } ``` - **BYOK** ```json "tts": { "vendor": "minimax", "params": { "key": "", "group_id": "", "model": "speech-2.8-turbo", "url": "wss://api-uw.minimax.io/ws/v1/t2a_v2", "voice_setting": { "voice_id": "English_captivating_female1", "speed": 1.0 }, "audio_setting": { "sample_rate": 44100 } } } ``` ### Key parameters The following parameters are required when using your own API key (BYOK). When using managed mode, `key` and `group_id` are not required. For more information, see [Use managed mode](/en/ai/build/managed-mode). **params** **`key` (string) optional** The MiniMax API key used to authenticate requests. Required when using your own API key (BYOK). **`group_id` (string) optional** The MiniMax group identifier. Required when using your own API key (BYOK). **`url` (string) required** The WebSocket endpoint for streaming TTS output. For example, `wss://api-uw.minimax.io/ws/v1/t2a_v2`. **`model` (string) required** The TTS model to use. For example, `speech-02-turbo`. For managed mode, use `speech-2.6-turbo` or `speech-2.8-turbo`. **`voice_setting.voice_id` (string) required** The voice style identifier to use. For example, `English_captivating_female1`. **`audio_setting.sample_rate` (number) required** The audio sampling rate in Hz. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [MiniMax documentation](https://www.minimax.io/platform/document/t2a_http). # Mistral (/en/ai/models/tts/mistral) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Mistral provides enterprise-grade AI voice generation with text-to-speech (TTS) models. ### Sample configuration The following examples show how to configure Mistral TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import MistralTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(MistralTTS( api_key='', model='voxtral-mini-tts-2603', voice='', )) ) ``` **TypeScript SDK** ```typescript import { Agent, MistralTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new MistralTTS({ apiKey: '', model: 'voxtral-mini-tts-2603', voice: '', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewMistralTTS(vendors.MistralTTSOptions{ APIKey: "", Model: "voxtral-mini-tts-2603", Voice: "", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "mistral", "params": { "api_key": "", "model": "voxtral-mini-tts-2603", "voice": "" } } ``` ### Key parameters **params required** **`api_key` (string) required** The Mistral API key used to authenticate requests. You must provide a valid key for the service to function. **`model` (string) optional** The TTS model to use. For example, `voxtral-mini-tts-2603`. **`voice` (string) optional** The voice identifier to use. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Mistral documentation](https://docs.mistral.ai/api/endpoint/audio/speech). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Murf (/en/ai/models/tts/murf) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Murf provides enterprise-grade AI voice generation with text-to-speech (TTS) models. ### Sample configuration The following examples show how to configure Murf TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import MurfTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(MurfTTS( key='your-murf-key', voice_id='Matthew', base_url='wss://global.api.murf.ai/v1/speech/stream-input', locale='en-US', rate=0, pitch=0, model='FALCON', sample_rate=24000, )) ) ``` **TypeScript SDK** ```typescript import { Agent, MurfTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new MurfTTS({ key: 'your-murf-key', voiceId: 'Matthew', baseUrl: 'wss://global.api.murf.ai/v1/speech/stream-input', locale: 'en-US', rate: 0, pitch: 0, model: 'FALCON', sampleRate: 24000, })); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewMurfTTS(vendors.MurfTTSOptions{ Key: "your-murf-key", VoiceID: "Matthew", BaseURL: "wss://global.api.murf.ai/v1/speech/stream-input", Locale: "en-US", Rate: Agora.Float64(0), Pitch: Agora.Float64(0), Model: "FALCON", SampleRate: Agora.Int(24000), }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "murf", "params": { "api_key": "", "base_url": "wss://global.api.murf.ai/v1/speech/stream-input", "voiceId": "Matthew", "locale": "en-US", "rate": 0, "pitch": 0, "model": "FALCON", "sample_rate": 24000 } } ``` ### Key parameters **params required** **`api_key` (string) required** The Murf API key used to authenticate requests. You must provide a valid key for the service to function. **`base_url` (string) optional** The WebSocket endpoint for streaming TTS output. For example, `wss://global.api.murf.ai/v1/speech/stream-input`. **`voiceId` (string) optional** The voice identifier to use. For example, `Matthew`. **`locale` (string) optional** The locale for the selected voice. For example, `en-US`. **`rate` (number) optional** The speech rate adjustment. A value of `0` applies the default rate. **`pitch` (number) optional** The pitch adjustment. A value of `0` applies the default pitch. **`model` (string) optional** The TTS model to use. For example, `FALCON`. **`sample_rate` (number) optional** The audio sample rate in Hz. For example, `24000`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Murf documentation](https://murf.ai/api/docs/api-reference/text-to-speech/stream-input). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # OpenAI (/en/ai/models/tts/openai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). OpenAI provides natural-sounding text-to-speech with customizable voice instructions and multiple voice options. ### Sample configuration The following examples show how to configure OpenAI TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import OpenAITTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(OpenAITTS( api_key='your-openai-key', # to use Agora-managed mode, omit api_key and base_url and set model to 'tts-1' base_url='https://api.openai.com/v1', model='gpt-4o-mini-tts', voice='coral', instructions='Please use standard American English, natural tone, moderate pace, and steady intonation', speed=1, )) ) ``` **TypeScript SDK** ```typescript import { Agent, OpenAITTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new OpenAITTS({ apiKey: 'your-openai-key', // to use Agora-managed mode, omit apiKey and baseUrl and set model to 'tts-1' baseUrl: 'https://api.openai.com/v1', model: 'gpt-4o-mini-tts', voice: 'coral', instructions: 'Please use standard American English, natural tone, moderate pace, and steady intonation', speed: 1, })); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewOpenAITTS(vendors.OpenAITTSOptions{ APIKey: "your-openai-key", // to use Agora-managed mode, omit APIKey and BaseURL and set Model to "tts-1" BaseURL: "https://api.openai.com/v1", Model: "gpt-4o-mini-tts", Voice: "coral", Instructions: "Please use standard American English, natural tone, moderate pace, and steady intonation", Speed: Agora.Float64(1), }), ) ``` **REST API** - **Managed mode** To use OpenAI TTS with Agora-managed credentials, set `credential_mode` to `"managed"` in the `tts` block. When using managed mode, `params.api_key` is not required. You can still use the `tts` field to configure additional settings such as `voice` and `instructions`. For more information, see [Use managed mode](/en/ai/build/managed-mode). ```json "tts": { "credential_mode": "managed", "vendor": "openai", "params": { "url": "https://api.openai.com/v1/audio/speech", "model": "tts-1", "voice": "coral", "instructions": "Please use standard American English, natural tone, moderate pace, and steady intonation", "speed": 1 } } ``` - **BYOK** ```json "tts": { "vendor": "openai", "params": { "url": "https://api.openai.com/v1/audio/speech", "api_key": "", "model": "gpt-4o-mini-tts", "voice": "coral", "instructions": "Please use standard American English, natural tone, moderate pace, and steady intonation", "speed": 1 } } ``` ### Key parameters The following parameters are required when using your own API key (BYOK). When using managed mode, `api_key` is not required. For more information, see [Use managed mode](/en/ai/build/managed-mode). **params** **`url` (string) required** The full endpoint URL for the OpenAI speech API, for example `https://api.openai.com/v1/audio/speech`. See [How to use data residency](https://platform.openai.com/docs/guides/your-data#how-to-use-data-residency). **`api_key` (string) optional** The API key used for authentication. Required when using your own API key (BYOK). Get your API key from the [OpenAI Console](https://platform.openai.com/api-keys). **`model` (string) required** Identifier of the model to be used. For managed mode, use `tts-1`. **`voice` (string) required** The voice identifier for speech synthesis. **`instructions` (string) optional** Custom instructions for voice style, accent, pace, and tone. Helps fine-tune the speech characteristics. **`speed` (number) optional** Default value: `1.0` Speaking rate multiplier. Values between `0.25` and `4.0`, where `1.0` is normal speed. > **Info** > > OpenAI TTS models do not support changing the sample rate. The audio output is fixed at 24,000 Hz. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [OpenAI TTS documentation](https://platform.openai.com/docs/guides/text-to-speech). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Rime (/en/ai/models/tts/rime) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Rime provides high-quality text-to-speech (TTS) with low latency, supporting multiple speakers and models. ### Sample configuration The following examples show how to configure Rime TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import RimeTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(RimeTTS( key='your-rime-key', speaker='cove', model_id='mistv2', )) ) ``` **TypeScript SDK** ```typescript import { Agent, RimeTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new RimeTTS({ key: 'your-rime-key', speaker: 'cove', modelId: 'mistv2', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewRimeTTS(vendors.RimeTTSOptions{ Key: "your-rime-key", Speaker: "cove", ModelID: "mistv2", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "rime", "params": { "api_key": "", "speaker": "cove", "modelId": "mistv2", "base_url": "wss://users.rime.ai/ws2" } } ``` ### Key parameters **params required** **`api_key` (string) required** The Rime API key used to authenticate requests. You must provide a valid key for the service to function. **`speaker` (string) required** The speaker voice to use for TTS output. For example, `cove`. **`modelId` (string) required** The Rime TTS model to use. For example, `mistv2`. Different models provide different voice qualities and capabilities. **`base_url` (string) optional** The WebSocket URL for the Rime streaming API. For example, `wss://users.rime.ai/ws2`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the Rime documentation for [Arcana](https://docs.rime.ai/api-reference/arcana/streaming-pcm) and [Mist v2](https://docs.rime.ai/api-reference/endpoint/streaming-pcm). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Sarvam (/en/ai/models/tts/sarvam) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Sarvam provides fast, reliable text-to-speech (TTS) with support for Indian languages and customizable voices. ### Sample configuration The following examples show how to configure Sarvam TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import SarvamTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(SarvamTTS( key='your-sarvam-key', speaker='anushka', target_language_code='en-IN', )) ) ``` **TypeScript SDK** ```typescript import { Agent, SarvamTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new SarvamTTS({ key: 'your-sarvam-key', speaker: 'anushka', targetLanguageCode: 'en-IN', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewSarvamTTS(vendors.SarvamTTSOptions{ Key: "your-sarvam-key", Speaker: "anushka", TargetLanguageCode: "en-IN", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "sarvam", "params": { "api_subscription_key": "", "speaker": "anushka", "target_language_code": "en-IN" } } ``` ### Key parameters **params required** **`api_subscription_key` (string) required** The API key used for authentication. Get your API key from the [Sarvam dashboard](https://dashboard.sarvam.ai/signin). **`speaker` (string) required** The voice ID to use for speech generation. - Female voices: `anushka`, `manisha`, `vidya`, `arya`. - Male voices: `abhilash`, `karun`, `hitesh`. **`target_language_code` (string) required** The language code for speech synthesis. Supported values: - `en-IN` English (India) - `hi-IN`: Hindi - `bn-IN`: Bengali - `ta-IN`: Tamil - `te-IN`: Telugu - `kn-IN`: Kannada - `ml-IN`: Malayalam - `mr-IN`: Marathi - `gu-IN`: Gujarati - `pa-IN`: Punjabi - `or-IN`: Odia **`pitch` (number) optional** Possible values: `[-0.75,0.75]` The pitch adjustment for the voice. Positive values make the voice sharper; negative values make it deeper. **`pace` (number) optional** Possible values: `[0.3,3.0]` The speed of speech. `1.0` is the normal speed. Values less than `1.0` slow down the speech; values greater than `1.0` speed it up. **`loudness` (number) optional** Possible values: `[0.1,3.0]` The volume level of the speech. Higher values increase the loudness. **`sample_rate` (number) optional** Possible values: `8000, 16000, 22050, 24000` The audio sample rate in Hz. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Sarvam documentation](https://docs.sarvam.ai/api-reference-docs/text-to-speech/convert). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Smallest AI (/en/ai/models/tts/smallest-ai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Smallest AI provides low-latency streaming text-to-speech (TTS) through its Lightning model family, with voices across a broad set of languages. ### Sample configuration The following examples show how to configure Smallest AI TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import SmallestAITTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(SmallestAITTS( url='https://api.smallest.ai/waves/v1/tts/live', api_key='your-smallest-ai-key', model='lightning_v3.1_pro', voice_id='hazel', sample_rate=16000, speed=1.0, language='zh', number_pronunciation_language='zh', math_notation=True, pronunciation_dicts=[], session_id='session_001', request_id='request_001', )) ) ``` **TypeScript SDK** ```typescript import { Agent, SmallestAITTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new SmallestAITTS({ url: 'https://api.smallest.ai/waves/v1/tts/live', apiKey: 'your-smallest-ai-key', model: 'lightning_v3.1_pro', voiceId: 'hazel', sampleRate: 16000, speed: 1.0, language: 'zh', numberPronunciationLanguage: 'zh', mathNotation: true, pronunciationDicts: [], sessionId: 'session_001', requestId: 'request_001', })); ``` **Go SDK** ```go import ( Agora "github.com/AgoraIO/agora-agents-go/v2" "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewSmallestAITTS(vendors.SmallestAITTSOptions{ URL: "https://api.smallest.ai/waves/v1/tts/live", APIKey: "your-smallest-ai-key", Model: "lightning_v3.1_pro", VoiceID: "hazel", SampleRate: Agora.Int(16000), Speed: Agora.Float64(1.0), Language: "zh", NumberPronunciationLanguage: "zh", MathNotation: Agora.Bool(true), PronunciationDicts: []string{}, SessionID: "session_001", RequestID: "request_001", }), ) ``` **REST API** Use the following `tts` configuration in your request. Only `api_key` is required: ```json "tts": { "vendor": "smallestai", "params": { "url": "https://api.smallest.ai/waves/v1/tts/live", "api_key": "", "model": "lightning_v3.1_pro", "voice_id": "hazel", "sample_rate": 16000, "speed": 1.0, "language": "zh", "number_pronunciation_language": "zh", "math_notation": true, "pronunciation_dicts": [], "session_id": "session_001", "request_id": "request_001" } } ``` ### Key parameters **params required** **`api_key` (string) required** The Smallest AI API key used to authenticate requests. You must provide a valid key for the service to function. **`url` (string) optional** The Smallest AI streaming TTS endpoint. For example, `https://api.smallest.ai/waves/v1/tts/live`. **`model` (string) optional** The Smallest AI TTS model to use, such as `lightning_v3.1_pro` or `lightning_v3.1`. Voice identifiers are model-specific, so `voice_id` must belong to the model you select. **`voice_id` (string) optional** The Smallest AI voice identifier to use. For example, `hazel`. **`sample_rate` (integer) optional** Output audio sample rate in Hz. For example, `16000`. **`speed` (number) optional** Speech rate multiplier, where `1.0` is the model's default pace. **`language` (string) optional** Language code used for speech synthesis. For example, `zh`. **`number_pronunciation_language` (string) optional** Language code used when reading numbers aloud. Set this when numbers should be spoken in a different language from the surrounding text. **`math_notation` (boolean) optional** Whether to read mathematical notation as spoken mathematics rather than as literal symbols. **`pronunciation_dicts` (array[string]) optional** Identifiers of Smallest AI pronunciation dictionaries to apply, used to override how specific terms are spoken. **`session_id` (string) optional** Caller-supplied session identifier, passed through to Smallest AI for tracing. **`request_id` (string) optional** Caller-supplied request identifier, passed through to Smallest AI for tracing. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Smallest AI documentation](https://docs.smallest.ai/models/documentation/text-to-speech-lightning/overview). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Typecast (/en/ai/models/tts/typecast) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). Typecast provides text-to-speech (TTS) with expressive, natural-sounding voices. ### Sample configuration The following examples show how to configure Typecast TTS when starting a conversational AI agent. **Python SDK** ```python from agora_agent import Agent from agora_agent.agentkit.vendors import TypecastTTS # client is your configured Agora client agent = ( Agent(client) .with_stt(...) # configure your STT vendor .with_llm(...) # configure your LLM vendor .with_tts(TypecastTTS( api_key='your-typecast-key', voice_id='tc_60e5426de8b95f1d3000d7b5', model='ssfm-v30', )) ) ``` **TypeScript SDK** ```typescript import { Agent, TypecastTTS } from 'agora-agents'; // client is your configured Agora client const agent = new Agent({ client }) .withStt(/* configure your STT vendor */) .withLlm(/* configure your LLM vendor */) .withTts(new TypecastTTS({ apiKey: 'your-typecast-key', voiceId: 'tc_60e5426de8b95f1d3000d7b5', model: 'ssfm-v30', })); ``` **Go SDK** ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) // client is your configured Agora client agent := agentkit.NewAgent(client).WithStt(/* configure your STT vendor */). WithLlm(/* configure your LLM vendor */). WithTts( vendors.NewTypecastTTS(vendors.TypecastTTSOptions{ APIKey: "your-typecast-key", VoiceID: "tc_60e5426de8b95f1d3000d7b5", Model: "ssfm-v30", }), ) ``` **REST API** Use the following `tts` configuration in your request: ```json "tts": { "vendor": "typecast", "params": { "api_key": "", "voice_id": "tc_60e5426de8b95f1d3000d7b5", "model": "ssfm-v30" } } ``` ### Key parameters **params required** **`api_key` (string) required** The Typecast API key used to authenticate requests. You must provide a valid key for the service to function. **`voice_id` (string) required** The Typecast voice identifier to use. For example, `tc_60e5426de8b95f1d3000d7b5`. **`model` (string) required** The Typecast TTS model to use. For example, `ssfm-v30`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [Typecast documentation](https://typecast.ai/docs/api-reference/text-to-speech/text-to-speech). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # xAI (/en/ai/models/tts/xai) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). xAI provides text-to-speech (TTS) with a range of expressive voices for conversational AI applications. ### Sample configuration The following example shows a starting `tts` parameter configuration you can use when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). **Python SDK** ```python from agora_agent import XaiTTS # ... other agent configuration ... .with_tts(XaiTTS( api_key='your-xai-api-key', voice_id='eve', language='en', sample_rate=16000, )) ``` **TypeScript SDK** ```typescript import { XAiTTS } from 'agora-agents'; // ... other agent configuration ... .withTts(new XAiTTS({ apiKey: 'your-xai-api-key', voiceId: 'eve', language: 'en', sampleRate: 16000, })); ``` **Go SDK** ```go sampleRate := vendors.SampleRate16kHz // ... other agent configuration ... WithTts( vendors.NewXaiTTS(vendors.XaiTTSOptions{ APIKey: "your-xai-api-key", VoiceID: "eve", Language: "en", SampleRate: &sampleRate, }), ) ``` **REST API** ```json "tts": { "vendor": "xai", "params": { "api_key": "${env:XAI_API_KEY}", "voice_id": "eve", "language": "en", "sample_rate": 16000 } } ``` ### Key parameters **params required** **`api_key` (string) required** The xAI API key used to authenticate requests. You must provide a valid key for the service to function. **`voice_id` (string) optional** The voice to use for speech synthesis. For voice IDs and samples, refer to the [xAI documentation](https://docs.x.ai/developers/model-capabilities/audio/text-to-speech#voices). **`language` (string) required** The BCP-47 language code for speech synthesis. For example, use `en` for English. For supported language codes, refer to the [xAI documentation](https://docs.x.ai/developers/model-capabilities/audio/text-to-speech#supported-languages). **`sample_rate` (integer) optional** The audio sample rate in Hz. Supported values: `8000`, `16000`, `22050`, `24000`, `44100`, `48000`. > **Caution** > > The parameters listed on this page are validated for use with Conversational AI Engine. Required parameters must be provided as documented. Any additional parameters are passed through directly to the underlying vendor without validation. For a full list of supported options, refer to the [xAI Text to Speech documentation](https://docs.x.ai/developers/model-capabilities/audio/text-to-speech). This integration is fully supported for use with Conversational AI Engine. While it has completed functional validation, it is newer to the platform, and additional provider-specific edge cases may be identified as usage scales across a broader range of applications and workloads. # Notification event types (/en/ai/reference/event-types) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). After enabling Agora message notifications, the Agora notification server sends channel event notifications to your server through HTTPS POST requests. The data format is `JSON`, the character encoding is `UTF-8`, and the signature algorithm can be either `HMAC/SHA1` or `HMAC/SHA256`. This page explains the types of events returned in channel event callbacks and their meanings. If you are starting from a product goal instead of an event number, begin with [Monitor agent status, errors, and performance](../build/handle-runtime-events/monitor-agent-runtime). For webhook setup, request format, and signature verification, see [Webhooks](../build/handle-runtime-events/webhooks). ## Choose event types by goal | Goal | Use these event types | What they help you answer | | --------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | Confirm that a session started or ended | [`101 agent joined`](#101-agent-joined), [`102 agent left`](#102-agent-left) | Did the agent enter the channel? How did the session end? | | Retrieve conversation history after a session | [`103 agent history`](#103-agent-history) | What was said during the session? See [Retrieve conversation history after a session ends](../build/handle-runtime-events/retrieve-session-history). | | Investigate failures and alert on production issues | [`110 agent error`](#110-agent-error), [`102 agent left`](#102-agent-left) | Which module failed? Did the session terminate because of that failure? See [Debug agent failures with runtime events](../build/handle-runtime-events/debug-agent-failures). | | Measure latency and runtime health | [`111 agent metrics`](#111-agent-metrics) | How long do LLM and TTS stages take? Are there regressions? | | Track telephony call progress | [`201 inbound call state`](#201-inbound-call-state), [`202 outbound call state`](#202-outbound-call-state) | Where is the SIP call in its lifecycle? | ## Request header The message notification callback header contains the following fields: **Header** **`Content-Type` (string)** Application/json **`Agora-Signature` (string)** The signature value generated by Agora using the customer key and `HMAC/SHA1` algorithm. Use the customer key and `HMAC/SHA1` algorithm to verify the signature value. See Verify the signature for details. **`Agora-Signature-V2` (string)** The signature value generated by Agora using the customer key and `HMAC/SHA256` algorithm. Use the customer key and `HMAC/SHA256` algorithm to verify the signature value. See Verify the signature for details. ## Request body The message notification callback request body contains the following fields: **`noticeId` (string)** Notification ID. Identifies an event notification from the Agora server. **`productId` (integer)** Business ID. A value of `17` indicates a Conversational AI Engine notification. **`eventType` (integer)** The event type of the notification. See [Event types](#event-types) for details. **`notifyMs` (integer)** The Unix timestamp (ms) indicating when the Agora message server sent the event notification to your server. This value is updated when the notification is retried. **`sid` (string)** The session ID. **`payload` (object)** The specific content of the notification event. `payload` varies depending on the event type. For details, see [Event types](#event-types). Following is an example of a message notification callback request body: ```json { "sid": "C866467GVJJ54687", "noticeId": "2000001428:4330:107", "productId": 17, "eventType": 101, "notifyMs": 1611566412672, "payload": {} } ``` ## Event types The Agora message notification service notifies the following Conversational AI Engine events: | Event Type | Event name | Event description | | :------------------------------ | :------------------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | [101](#101-agent-joined) | agent joined | The agent joins the channel. | | [102](#102-agent-left) | agent left | The agent leaves the channel. | | [103](#103-agent-history) | agent history | After an agent stops, this event notifies the stored history, which includes messages exchanged between the user and the agent and timestamps indicating when the agent was created and stopped. The maximum number of entries is determined by the `llm.max_history` parameter you can set when starting the agent. The default value is `32`. | | [104](#104-agent-expire) | agent expire | The agent's RTC token is about to expire. | | [110](#110-agent-error) | agent error | Agent error. | | [111](#111-agent-metrics) | agent metrics | The performance metrics of an agent. | | [112](#112-turns-finished) | turns finished | Batch callback of dialogue round data after the session ends. | | [201](#201-inbound-call-state) | inbound call state | Changes in the status of an incoming call. | | [202](#202-outbound-call-state) | outbound call state | Changes in the status of an outgoing call. | ### 101 agent joined An `eventType` of `101` indicates that an agent has joined a channel. The `payload` contains the following fields: **payload** **`agent_id` (string)** Unique identifier of the agent. **`name` (string)** The agent name provided when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unique within a channel. **`start_ts` (integer)** Timestamp indicating when the agent was created. **`channel` (string)** The name of the channel the agent was in. **`labels` (object) optional** Custom labels in key-value pair format. Contains the same labels that were set when starting the agent. #### Payload example ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "start_ts": 1737111452, "channel": "xxxxx", "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` ### 102 agent left An `eventType` of `102` indicates that an agent has left a channel. The `payload` contains the following fields: **payload** **`agent_id` (string)** Unique identifier of the agent. **`name` (string)** The agent name provided when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unique within a channel. **`start_ts` (integer)** Timestamp indicating when the agent was created. **`stop_ts` (integer)** Timestamp indicating when the agent left the channel. **`channel` (string)** The name of the channel the agent was in. **`status` (string)** Agent status. **`message` (string)** The reason why the agent left the channel. **`labels` (object) optional** Custom labels in key-value pair format. Contains the same labels that were set when starting the agent. #### Payload examples Following are some examples of the `payload` when an agent leaves a channel for different reasons. **Agent manually stopped** ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "start_ts": 1737111452, "stop_ts": 1737111455, "channel": "xxxxx", "status": "STOPPED", "message": "OK", "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` **Agent idle timeout** ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "start_ts": 1737111452, "stop_ts": 1737111455, "channel": "xxxxx", "status": "STOPPED", "message": "Idle for too long", "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` **Agent error** ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "start_ts": 1737111452, "stop_ts": 1737111455, "channel": "xxxxx", "status": "FAILED", "message": "Connecting for too long", "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` **RTC connection error** ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "start_ts": 1737111452, "stop_ts": 1737111455, "channel": "xxxxx", "status": "FAILED", "message": "RTC connection error", "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` **Task lifetime limit exceeded** ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "start_ts": 1737111452, "stop_ts": 1737111455, "channel": "xxxxx", "status": "STOPPED", "message": "Task lifetime limit exceeded", "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` ### 103 agent history An `eventType` of `103` notifies the history of a user and agent dialogue. The notification `payload` contains the following fields: **payload** **`agent_id` (string)** Unique identifier of the agent. **`name` (string)** The agent name provided when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unique within a channel. **`channel` (string)** The name of the channel the agent was in. **`start_ts` (integer)** The timestamp indicating when the agent started and joined the channel. **`stop_ts` (integer)** The timestamp indicating when the agent stopped and left the channel. **`contents` (array)** Agent history. **`role` (string)** The message sender. - `user`: User - `assistant`: AI agent **`content` (string)** Message content. **`speech_start_ms` (integer) optional** Unix timestamp in milliseconds indicating when the user started speaking or the agent started TTS playback. Only returned when `llm.vendor` is `custom`. **`speech_end_ms` (integer) optional** Unix timestamp in milliseconds indicating when the user stopped speaking, or when TTS playback completed or was interrupted. Only returned when `llm.vendor` is `custom`. **`speech_algorithmic_delay` (integer) optional** The total delay in milliseconds introduced by audio processing algorithms, including noise reduction, background voice suppression, and voiceprint locking, after audio is captured from the user's microphone. Use this value to align timestamps with cloud recording audio. Only returned when: - `llm.vendor` is `custom` - `contents[].role` is `user` - Actual voice input is present **`labels` (object) optional** Custom labels in key-value pair format. Contains the same labels that were set when starting the agent. > **Info** > > `speech_start_ms`, `speech_end_ms`, and `speech_algorithmic_delay` are returned only in `103 agent history` events for sessions that use `llm.vendor` set to `custom`. #### Payload examples **Basic** ```json { "agent_id": "xxxx", "name": "my-agent", "channel": "xxxx", "start_ts": 123, "stop_ts": 123, "contents": [ { "role": "user", "content": "hello." }, { "role": "assistant", "content": "hi, how can I help you?" } ], "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` **Custom LLM** ```json { "agent_id": "xxxx", "name": "my-agent", "channel": "xxxx", "start_ts": 123, "stop_ts": 123, "contents": [ { "role": "user", "content": "Hello, I need help with my recent order.", "speech_start_ms": 1715000001200, "speech_end_ms": 1715000003400, "speech_algorithmic_delay": 120 }, { "role": "assistant", "content": "Sure, could you please provide your order number?", "speech_start_ms": 1715000004100, "speech_end_ms": 1715000005000 }, { "role": "user", "content": "I'd like to check the status of my package, tracking number 12345.", "speech_start_ms": 1715000005200, "speech_end_ms": 1715000007600, "speech_algorithmic_delay": 120 }, { "role": "assistant", "content": "Your package with tracking number 12345 is currently out for delivery.", "speech_start_ms": 1715000009500, "speech_end_ms": 1715000013200 }, { "role": "user", "content": "[think API injected] User level: VIP" } ], "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` ### 104 agent expire An `eventType` of `104` indicates that the agent's RTC token is about to expire. The `payload` contains the following fields: **payload** **`agent_id` (string)** Unique identifier of the agent. **`name` (string)** The agent name provided when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unique within a channel. **`start_ts` (integer)** Timestamp indicating when the agent was created. **`channel` (string)** The name of the channel the agent is in. **`message` (string)** Token expiry warning message. Fixed value: `Task exceeded maximum lifetime`. > **Info** > > This event is a warning only. The agent does not exit the channel or interrupt the session when this event is triggered. Upon receiving this event, call the [Update agent](/en/api-reference/api-ref/conversational-ai/update) API with a new `properties.token` to refresh the token before it expires. #### Payload example ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "start_ts": 1737111452, "channel": "xxxxx", "message": "Task exceeded maximum lifetime" } ``` ### 110 agent error An `eventType` of `110` indicates that an agent has encountered an error. The `payload` contains the following fields: **payload** **`agent_id` (string)** Unique identifier of the agent. **`name` (string)** The agent name provided when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unique within a channel. **`start_ts` (integer)** Timestamp indicating when the agent was created. **`channel` (string)** The name of the channel the agent was in. **`turn_id` (string)** Transcript conversation turn. For details, see [Display live transcripts](../build/transcripts#reference). **`errors` (array)** An array of error messages. Each object contains the following fields: **`module` (string)** The module where the error occurred. **`turn_id` (integer)** Transcript dialogue turn. **`code` (integer)** Error code. Refer to the error code document of the vendor corresponding to the error module for detailed information. **`message` (string)** The error message. **`labels` (object) optional** Custom labels in key-value pair format. Contains the same labels that were set when starting the agent. #### Payload examples **LLM module error** ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "start_ts": 1737111452, "channel": "xxxxx", "turn_id": 2, "errors": [{"module": "llm", "turn_id":2, "code":503, "message": "Insufficient balance."}], "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` **Greeting audio URL error** When the greeting audio file fails to download, times out, is in an unsupported format, or fails to decode, the system reports the error via a `110 agent error` event and automatically falls back to TTS synthesis using `greeting_message`. In these errors, `errors[].module` is `agent`. ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "outbound_voice_agent", "start_ts": 1737111452, "channel": "outbound_call_channel_001", "turn_id": 0, "errors": [ { "module": "agent", "turn_id": 0, "code": 4001, "message": "Greeting audio URL unreachable, fallback to TTS. audio_url: https://cdn.example.com/audio/welcome.mp3" } ], "labels": {} } ``` > **Info** > > If `parameters.enable_error_message` is set to `true` when starting the agent, greeting audio URL errors are also delivered to the client via the `onMessageError` RTM callback, in addition to the server-side webhook event. ### 111 agent metrics An `eventType` of `111` notifies the performance metrics of an agent. The `payload` contains the following fields: **payload** **`agent_id` (string)** Unique identifier of the agent. **`name` (string)** The agent name provided when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unique within a channel. **`start_ts` (integer)** Timestamp indicating when the agent was created and joined the channel. **`stop_ts` (integer)** Timestamp indicating when the agent stopped and left the channel. **`channel` (string)** The name of the channel where the agent is located. **`metrics` (array)** An array of performance metrics. Each object contains the following fields: **`turn_id` (string)** Dialogue round ID. **`asr_ttlw` (integer)** The ttlw (Time To Last Word) metric of the ASR module. Represents the delay (in milliseconds) from when the user finishes speaking until the last word is output by the ASR. **`llm_ttfb` (integer)** The ttfb (Time To First Byte) metric for the LLM module. Represents the latency (in milliseconds) from the start of an LLM request to the receipt of the first byte of the response. **`llm_ttfs` (integer)** The ttfs (Time To First Sentence) metric for the LLM module. Represents the time (in milliseconds) elapsed from the start of an LLM request to the receipt of the first complete sentence response. **`tts_ttfb` (integer)** The ttfb (Time To First Byte) metric for the TTS module. Represents the latency (in milliseconds) from the start of a TTS request to the receipt of the first byte of the response. **`labels` (object) optional** Custom labels in key-value pair format. Contains the same labels that were set when starting the agent. #### Payload example ```json { "agent_id": "A42AC47Hxxxxxxxx4PK27ND25E", "name": "my-agent", "start_ts": 1000, "stop_ts": 1672531200, "channel": "test-channel", "metrics": [ { "turn_id": 1, "asr_ttlw": 503, "llm_ttfb": 1104, "tts_ttfb": 85 }, { "turn_id": 2, "asr_ttlw": 2385, "llm_ttfb": 980, "tts_ttfb": 78 } ], "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` ### 112 turns finished An `eventType` of `112` indicates a batch callback of conversation turn data after the session ends. This event returns the conversation turns for the current session in a single callback, making it convenient for post-session analysis, archiving, or offline processing. When a session has more than 200 turns, the callback data may be truncated. Use the `is_truncated` field to check whether the current callback contains the complete turn data. The `payload` contains the following fields: **payload** **`agent_id` (string)** Unique identifier of the agent. **`name` (string)** The agent name provided when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unique within a channel. **`channel` (string)** The name of the channel where the agent is located. **`start_ts` (number)** Timestamp indicating when the agent was created and joined the channel. **`stop_ts` (number)** Timestamp indicating when the agent stopped and left the channel. **`total_turn_count` (number)** The total number of conversation turns in the session. **`is_truncated` (boolean)** Whether the turn data in the current callback is truncated. A value of `true` indicates that the current callback did not return all turns. **`labels` (object) optional** Custom labels in key-value pair format. Contains the same labels that were set when starting the agent. Only returned if labels were passed in when creating the agent. **`turns` (array[object])** A list of conversation turns for the session. **`agent_id` (string)** Unique identifier of the agent. **`channel` (string)** The name of the channel where the agent is located. **`turn_id` (number)** The sequential index of the turn within the session. Starts at `1`. **`start` (object)** Details about the start of the turn. **`start_at` (number)** The Unix timestamp in milliseconds (UTC time) when the turn started. **`type` (string)** Possible values: `voice_input, greeting, silence_timeout, api_speak, api_think` The type of event that initiated the turn. **`metadata` (object)** Additional context about the turn start event. Included fields depend on the value of the `type` field. **`speech_duration_ms` (integer)** The duration of the user's voice input in milliseconds. Included only when `type` is `voice_input`. **`interrupt_duration_ms` (integer)** The minimum voice duration in milliseconds required to trigger an interruption. Included only when `type` is `voice_input`. **`end` (object)** Details about the end of the turn. **`end_at` (number)** The Unix timestamp in milliseconds (UTC time) when the turn ended. **`type` (string)** Possible values: `ok, error, ignored, interrupted` The type of event that ended the turn. **`metadata` (object)** Additional context about the turn end event. Included fields depend on the value of the `type` field. **`playback_duration_ms` (integer)** The audio playback duration in milliseconds. Included when `type` is `ok` or `interrupted`. For an interrupted turn, this is the PCM audio actually played before the interruption, and it doesn't exceed `intended_playback_duration_ms`. **`intended_playback_duration_ms` (integer)** The total duration in milliseconds of PCM audio the engine received and scheduled to play for the turn, including queued audio that hadn't played yet. Included only when `type` is `interrupted`. **`caused_by` (string)** The cause of the turn ending. Included when `type` is `interrupted` or `ignored`. For possible values, see [Query conversation turn information](/en/api-reference/api-ref/conversational-ai/turns). **`metrics` (object)** Latency metrics for the turn. **`e2e_latency_ms` (number)** The end-to-end latency in milliseconds for the turn. Represents the time from when the user finishes speaking to when the agent starts speaking. **`segmented_latency_ms` (object)** A breakdown of latency by segment. **`algorithm_processing` (number)** Algorithm processing delay in milliseconds. **`asr_ttlw` (number)** The ASR Time To Last Word (TTLW) in milliseconds. Represents the delay from when the user finishes speaking to when the ASR module outputs the last word. **`llm_ttft` (number)** The LLM Time To First Token (TTFT) in milliseconds. Represents the delay from when the LLM receives the request to when it outputs the first token. **`llm_ftfs` (number)** The LLM First Token To First Sentence (FTFS) in milliseconds. Represents the delay from when the LLM outputs the first token to when it outputs the first complete sentence. **`tts_ttfb` (number)** The TTS Time To First Byte (TTFB) in milliseconds. Represents the delay from when the TTS module receives a text request to when it outputs the first audio byte. **`transport` (number)** Network transmission delay in milliseconds. Not returned when the user is connected using the RTC Web SDK. #### Payload example ```json { "agent_id": "xxxx", "name": "support_agent_001", "channel": "xxxx", "start_ts": 1715000000000, "stop_ts": 1715000015000, "total_turn_count": 250, "is_truncated": true, "labels": { "campaign_id": "test_campaign", "customer_group": "vip" }, "turns": [ { "agent_id": "xxxx", "channel": "xxxx", "turn_id": 1, "start": { "start_at": 1774579820147, "type": "voice_input" }, "end": { "end_at": 1774579822412, "type": "ok" }, "metrics": { "e2e_latency_ms": 1500, "segmented_latency_ms": { "algorithm_processing": 300, "asr_ttlw": 200, "llm_ttft": 600, "tts_ttfb": 200, "transport": 300 } } } ] } ``` The following example shows the `end` object of an interrupted turn: ```json { "end_at": 1774579822412, "type": "interrupted", "metadata": { "caused_by": "api_interrupt", "playback_duration_ms": 1200, "intended_playback_duration_ms": 2400 } } ``` ### 201 inbound call state An `eventType` of `201` notifies changes in the status of an incoming call. The `payload` contains the following fields: **payload** **`agent_id` (string)** Unique identifier of the agent. **`name` (string)** The agent name provided when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unique within a channel. **`channel` (string)** The name of the channel where the agent is located. **`state` (string)** Possible values: `START, ANSWERED, TRANSFERED, HANGUP` Incoming call status: - `START`: Call received - `ANSWERED`: Call answered - `TRANSFERED`: Transfer to human operator - `HANGUP`: Call hung up **`report_ms` (integer)** Timestamp (in milliseconds) of the state change. **`labels` (object) optional** Custom labels in key-value pair format. Contains the same labels that were set when starting the agent. #### Payload example ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "channel": "xxxxx", "state": "START", "report_ms": 1737111452000, "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` ### 202 outbound call state An `eventType` of `202` notifies changes in the status of an outgoing call. The `payload` contains the following fields: **payload** **`agent_id` (string)** Unique identifier of the agent. **`name` (string)** The agent name provided when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). Unique within a channel. **`channel` (string)** The name of the channel where the agent is located. **`state` (string)** Possible values: `START, CALLING, RINGING, ANSWERED, HANGUP` Outgoing call status: - `START`: Call begins - `CALLING`: Making a phone call - `RINGING`: The telephone is ringing - `ANSWERED`: The call was connected - `HANGUP`: Call hung up **`report_ms` (integer)** Timestamp (in milliseconds) of the state change. **`labels` (object) optional** Custom labels in key-value pair format. Contains the same labels that were set when starting the agent. #### Payload example ```json { "agent_id": "1NT29X10YHxxxxxWJOXLYHNYB", "name": "my-agent", "channel": "xxxxx", "state": "CALLING", "report_ms": 1737111452000, "labels": { "campaign_id": "test_campaign", "customer_group": "vip" } } ``` # Pricing (/en/ai/reference/pricing) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). This page describes how Agora calculates and bills for Conversational AI Engine usage. When you use Conversational AI Engine in your project, Agora charges a monthly fee based on your usage across all projects under your developer account. At the end of each month, the free quota is subtracted from your total usage, and the remaining minutes are multiplied by the unit price to calculate your bill, rounded to two decimal places. For general billing information, see [Billing](../../introduction/billing). > **Info** > > If you have signed a sales contract with Agora, your billing follows the terms in your contract. ## Unit price Creating a Conversational AI Engine instance using the REST API and joining a channel incurs an audio task fee at the following rate: | Usage Type | Pricing (USD / minute) | Free Minutes | | ----------------------------------- | ---------------------: | -------------------------- | | Conversational AI Engine Audio Task | 0.10\* | First 300 minutes are free | \* The unit price includes usage of selected ASR, LLM, and TTS models. You are charged the same price even if you bring your own key (BYOK). Usage of ASR, LLM, and TTS providers is included in the unit price when using an Agora managed key. Agora provides and manages the API keys for the following providers: - **ASR** - ARES - Deepgram nova-2 - Deepgram nova-3 - **LLM** - OpenAI GPT-4o-mini - OpenAI GPT-4.1-mini - OpenAI GPT-5-nano - OpenAI GPT-5-mini - **TTS** - MiniMax 2.6 Turbo - MiniMax 2.8 Turbo - OpenAI TTS-1 ## Examples The following examples demonstrate how billing is calculated for different Conversational AI Engine configurations. ### Using ASR, LLM, and TTS managed by Agora User A joins a channel and starts a voice conversation with an instance created by Conversational AI Engine. The interaction lasts for 10 minutes. User A and the Conversational AI Engine instance exit the channel at the same time. Agora calculates the cost for this session as follows: | Usage Type | Duration (minutes) | Unit Price | Service Cost (USD) | | ---------------------------------------------------------- | -----------------: | ---------: | -----------------: | | User A: Audio RTC | 10 | 0.00099 | 0.0099 | | Conversational AI Engine Audio Task | 10 | 0.10 | 1.00 | | ASR: ARES, LLM: OpenAI GPT-4o-mini, TTS: MiniMax 2.8 Turbo | 10 | 0.00 | 0.00 | Total cost: 1.0099 USD # Contribute an ASR extension (/en/ai/reference/ten-agent/create-asr-extension) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). This guide shows how to scaffold an ASR extension project, install its dependencies, and review the generated files before you implement vendor-specific transcription logic. In a voice agent graph, an ASR extension receives real-time audio frames and emits transcribed text for downstream LLM or dialog-processing extensions. ## When to use this guide Use this guide when you are starting a new Python ASR extension from the default template. For the complete extension lifecycle, see [Development workflow](../../ten-agent/develop/development-workflow). For metadata and schema concepts, see [Schema system](../../ten-agent/architecture/schema-system). ## Prerequisites - Understand the development and testing process of TEN extensions. See [Development workflow](../../ten-agent/develop/development-workflow). - Master Python asynchronous programming (`asyncio`, `async/await`). - Have the `tman` command-line tool installed and be familiar with its basic usage. - Have an API key from an ASR vendor ready (for testing). ## What an ASR extension does The ASR Extension is one of the standard building blocks of the TEN Framework, responsible for **transcribing audio streams into text** in corresponding languages in **real-time**. ### Position in the Conversation Flow ```json [RTC Extension] ──audio stream──> [ASR Extension] ──text stream──> [LLM Extension] ``` ## Create the project ### Prepare the repository > **Info** > > If you haven't cloned the TEN Framework repository yet, please clone it first: > > ```bash > git clone https://github.com/TEN-framework/ten-framework.git > cd ten-framework > ``` > > This tutorial assumes you are developing in the root directory of the TEN Framework repository. ### Create with the template Use the `tman` command-line tool to create a project from the ASR extension template: ```bash cd ai_agents/agents/ten_packages/extension tman create extension my_asr_extension --template default_asr_python --template-data class_name_prefix=MyAsr ``` **Command Parameter Explanation**: - `extension my_asr_extension`: Create an extension with the directory name and plugin name `my_asr_extension`. - `--template default_asr_python`: Use the ASR Python extension template. - `--template-data class_name_prefix=MyAsr`: Set the class name prefix for the Python Extension class to `MyAsr` (the generated class name will be `MyAsrExtension`). ### Install TEN package dependencies ```bash cd my_asr_extension tman install --standalone ``` > **Info** > > This command uses the dependency calculation and download capabilities of the `tman` tool to calculate the dependency tree based on the dependencies declared in `manifest.json`. Since these are development dependencies, the `--standalone` parameter is required. Dependencies will be installed in the `.ten` directory, including Python modules for development and system packages for standalone testing. ### Review the project structure ```text my_asr_extension/ ├── manifest.json # Extension metadata ├── property.json # Default configuration ├── requirements.txt # Python dependencies ├── extension.py # Main implementation file ├── addon.py # Extension entry point ├── __init__.py # Python package initialization ├── docs/ # Documentation directory ├── .vscode/ # VS Code debug configuration └── tests/ # Test files ``` #### File descriptions **manifest.json and property.json** are standard metadata files for TEN Extensions: - `manifest.json`: Contains the extension's **name, version, description, dependencies, and schema definitions**. - `property.json`: Defines the extension's **default property values**. > **Info** > > For details about TEN Framework metadata and schemas, see [Schema system](../../ten-agent/architecture/schema-system). **requirements.txt** is unique to Python extensions and is used to declare the extension's **dependencies on third-party pip packages**. **extension.py** is the **core source code** of the extension, containing all business logic implementation. **tests/** folder is used for **standalone extension testing**, including unit tests and test configurations. # Contribute a TTS extension (/en/ai/reference/ten-agent/create-tts-extension) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). This guide explains how a TTS extension fits into a voice agent graph and how to choose an implementation path for a vendor text-to-speech service. In a voice agent graph, a TTS extension receives generated text and streams synthesized audio to downstream RTC, playback, or audio-processing extensions. ## What a TTS extension does The TTS Extension is a **standard extension building block** in the TEN Framework ecosystem, designed specifically for text-to-speech functionality. ### Core responsibilities The TTS Extension is mainly responsible for: 1. **Receiving text**: Continuously receiving text from upstream extensions that needs to be turned into speech, usually from an LLM. 2. **Real-time synthesis**: Converting the text into an audio stream in real time. 3. **Sending audio**: Passing the synthesized audio to downstream extensions for further processing. ### Position in the Conversation Flow As a standard building block, the TTS Extension plays the key role of converting text into audio inside a voice agent conversation flow: ```json [Upstream Extension] ──text stream──> [TTS Extension] ──audio stream──> [Downstream Extension] ``` **Typical upstream extensions**: - **LLM Extension**: Generates reply text. - **Translation Extension**: Produces translated text. - **Text Processing Extension**: Outputs preprocessed text. **Typical downstream extensions**: - **RTC Extension**: Pushes audio into an RTC channel. - **Audio Playback Extension**: Plays audio locally. - **Audio Processing Extension**: Applies post-processing such as mixing or effects. ## Implementation modes TTS implementations usually fall into two categories: [HTTP mode](#http-mode) and [WebSocket mode](#websocket-mode). Most TTS vendors support one or both of these. Some vendors also provide SDKs, but the underlying behavior is still usually HTTP or WebSocket, so choose the implementation path based on how the SDK actually works. HTTP is the more basic implementation approach. If this is your first TTS Extension, it is recommended to start with the [HTTP mode](#http-mode), and then move on to the more advanced [WebSocket mode](#websocket-mode). ### HTTP mode Use HTTP mode when the vendor API accepts text requests and returns synthesized audio data through request-response calls. This is usually the simplest path for a first TTS extension. ### WebSocket mode Use WebSocket mode when the vendor API streams synthesis results incrementally or requires a long-lived session. This path is better for low-latency streaming, but it usually needs more client lifecycle and reconnection handling. ### Architecture overview Two base classes are available today for developers: `AsyncTTS2BaseExtension` and `AsyncTTS2HttpExtension`. Inheriting from these classes makes TTS Extension implementation much easier. ### Basic implementation paths **Path 1: Inherit directly from `AsyncTTS2BaseExtension` (WebSocket mode)** ```text ┌─────────────────────────────────────────────────────────────┐ │ AsyncTTS2BaseExtension │ │ [Generic base class] Provides TTS Extension infrastructure│ │ - Message queue management │ │ - Lifecycle management │ │ - Audio data sending │ │ - Metrics reporting │ │ - Error handling │ └─────────────────────────────────────────────────────────────┘ ↑ Inheritance (Path 1) ┌─────────────────────────────────────────────────────────────┐ │ VendorTTSExtension (WebSocket/SDK subclass) │ │ [Subclass implementation] Vendor-specific logic │ │ - Full request_tts() implementation │ │ - WebSocket/SDK client implementation │ │ - Config class implementation │ │ - Vendor metadata │ │ - Sample rate configuration │ └─────────────────────────────────────────────────────────────┘ ``` **Path 2: Inherit from `AsyncTTS2HttpExtension` (HTTP mode)** ```text ┌─────────────────────────────────────────────────────────────┐ │ AsyncTTS2BaseExtension │ │ [Generic base class] Provides TTS Extension infrastructure│ │ - Message queue management │ │ - Lifecycle management │ │ - Audio data sending │ │ - Metrics reporting │ │ - Error handling │ └─────────────────────────────────────────────────────────────┘ ↑ Inheritance ┌─────────────────────────────────────────────────────────────┐ │ AsyncTTS2HttpExtension (HTTP mode) │ │ [Mode base class] Full HTTP-mode implementation │ │ - Config loading and validation │ │ - Client management │ │ - Request handling logic (full request_tts()) │ │ - TTFB calculation and reporting │ │ - PCMWriter management │ └─────────────────────────────────────────────────────────────┘ ↑ Inheritance (Path 2) ┌─────────────────────────────────────────────────────────────┐ │ VendorTTSExtension (HTTP subclass) │ │ [Subclass implementation] Vendor-specific logic │ │ - Config class implementation (create_config()) │ │ - Client implementation (create_client()) │ │ - Vendor metadata (vendor()) │ │ - Sample rate config (synthesize_audio_sample_rate()) │ └─────────────────────────────────────────────────────────────┘ ``` # Release notes (/en/ai/release-notes) > Documentation: Conversational AI. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-guides-v1.txt). This document tracks notable changes and improvements to the Conversational AI Engine. ## Versions #### v2.14 Released on November 6, 2026. #### New features Included in this release: - **ConvoAI token service** Tokens can include a dedicated ConvoAI service for REST API authentication. Use the same token for REST authentication and for the agent's channel access. For details, see [RESTful authentication](/en/api-reference/api-ref/conversational-ai/authentication#token-authentication). - **Managed mode for Fish Audio and Cartesia TTS** You can use [Fish Audio](models/tts/fish-audio) and [Cartesia](models/tts/cartesia) TTS with Agora-managed credentials, so you don't need your own API key for these providers. Available in the Agora Agents SDKs and the RESTful API. For details, see [Use managed mode](build/managed-mode). #### Improvements This release includes the following enhancements. - **More complete turn latency metrics** This release fixes an issue where performance metrics could be missing for some turns when the agent processes several turns concurrently. To view the end-to-end and per-stage latency of each turn, see [Query conversation turn information](/en/api-reference/api-ref/conversational-ai/turns). - **Playback duration for interrupted turns** Turn data for an interrupted turn now records how much of the agent's reply audio actually played before the interruption, and how much was scheduled to play. Use this data to analyze how far the agent got before users interrupted it. It's available from [Query conversation turn information](/en/api-reference/api-ref/conversational-ai/turns) and the [112 turns finished](/en/ai/reference/event-types#112-turns-finished) event. Playback duration for turns that end normally is unchanged. #### API changes This release introduces the following changes for managed mode and interrupted-turn playback data. **Python SDK** - [`CartesiaTTS`](/en/ai/models/tts/cartesia) and [`FishAudioTTS`](/en/ai/models/tts/fish-audio): New `credential_mode` option. To use Agora-managed credentials, set `credential_mode='managed'` and omit the API key. **TypeScript SDK** - [`CartesiaTTS`](/en/ai/models/tts/cartesia) and [`FishAudioTTS`](/en/ai/models/tts/fish-audio): New `credentialMode` option. To use Agora-managed credentials, set `credentialMode: CredentialMode.Managed` and omit the API key. **Go SDK** - [`CartesiaTTSOptions`](/en/ai/models/tts/cartesia) and [`FishAudioTTSOptions`](/en/ai/models/tts/fish-audio): New `CredentialMode` field. To use Agora-managed credentials, set `CredentialMode: agentkit.CredentialModeManaged` and omit the API key. **REST API** - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **Updated parameters** - [`tts.credential_mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-credential-mode): Now accepts `"managed"` when `tts.vendor` is `fishaudio` or `cartesia`. In managed mode, `tts.params.api_key` is not required. For supported models, see [Use managed mode](/en/ai/build/managed-mode#tts). - Changes to [**Query conversation turn information**](/en/api-reference/api-ref/conversational-ai/turns) and the [**112 turns finished**](/en/ai/reference/event-types#112-turns-finished) event - **New fields** in `turns[].end.metadata` when `end.type` is `interrupted` - `playback_duration_ms`: The PCM audio actually played before the interruption, in milliseconds. - `intended_playback_duration_ms`: The total PCM audio the engine received and scheduled to play for the turn, in milliseconds. #### v2.13 Released on September 25, 2026. #### New features Included in this release: - **Custom tools for MLLM agents** MLLM agents can call your own HTTPS endpoints as tools. Tool definitions use the same format as for cascading LLM agents, so an existing tool works with either agent type. Available in the Agora Agents SDKs and the RESTful API. For details, see [Call custom tools](build/tools/custom-tools). - **New ASR provider** - [Smallest AI](models/asr/smallest-ai) - **New TTS provider** - [Smallest AI](models/tts/smallest-ai) - **New MLLM provider** - [OpenAI GPT-Live](models/mllm/openai-gpt-live) #### Improvements This release includes the following enhancements. - **MCP tool-use for MLLM agents in the Agora Agents SDKs** MLLM agents have supported MCP tool-use through the RESTful API since v2.12. This release adds the same support to the Agora Agents SDKs, which accept MCP servers on their MLLM vendor classes, so you can configure MCP tool-use without calling the RESTful API directly. For details, see [Use MCP tools](build/tools/mcp-tools). - **Generated filler words use conversation context** This release improves generated filler words so that they reflect the recent exchange, not just the current turn. You can set the conversation context for the generation service using a message count and a character budget. For details, see [Talking while waiting](build/shape-the-conversation/filler-words). #### API changes This release introduces the following changes for the new Smallest AI and OpenAI GPT-Live providers, Gemini ASR, MLLM tool-use, and generated filler words. **Python SDK** - [`SmallestAISTT`](/en/api-reference/api-ref/server-sdk/python#stt-vendors): New ASR vendor class for Smallest AI. - [`GeminiSTT`](/en/api-reference/api-ref/server-sdk/python#stt-vendors): New ASR vendor class for Gemini. - [`OpenAIGPTLive`](/en/api-reference/api-ref/server-sdk/python#mllm-vendors): New MLLM vendor class for OpenAI GPT-Live. - [MLLM vendor classes](/en/api-reference/api-ref/server-sdk/python#mllm-vendors): New `tools` option for custom tool definitions, and new `mcp_servers` option for MCP tool-use. - [`SmallestAITTS`](/en/api-reference/api-ref/server-sdk/python#tts-vendors): New TTS vendor class for Smallest AI. - **New fields** on [`FillerWordsContentGeneratedConfig`](/en/api-reference/api-ref/server-sdk/python#type-aliases) - `context_message_limit`: How many of the most recent conversation messages to use, counting the current turn's message. Accepts `1` to `6`, and defaults to `1`. - `history_character_limit`: Maximum combined characters of the earlier messages in the window. Accepts `0` to `10000`, and defaults to `1000`. - **Updated behavior** - `prompt`: A custom prompt fully replaces Agora's default prompt, and applies over the same conversation context window. **TypeScript SDK** - [`SmallestAISTT`](/en/api-reference/api-ref/server-sdk/typescript#stt-vendors): New ASR vendor class for Smallest AI. - [`GeminiSTT`](/en/api-reference/api-ref/server-sdk/typescript#stt-vendors): New ASR vendor class for Gemini. - [`OpenAIGPTLive`](/en/api-reference/api-ref/server-sdk/typescript#mllm-vendors): New MLLM vendor class for OpenAI GPT-Live. - [MLLM vendor classes](/en/api-reference/api-ref/server-sdk/typescript#mllm-vendors): New `tools` option for custom tool definitions, and new `mcpServers` option for MCP tool-use. - [`SmallestAITTS`](/en/api-reference/api-ref/server-sdk/typescript#tts-vendors): New TTS vendor class for Smallest AI. - **New fields** on [`FillerWordsContentGeneratedConfig`](/en/api-reference/api-ref/server-sdk/typescript#type-aliases) - `context_message_limit`: How many of the most recent conversation messages to use, counting the current turn's message. Accepts `1` to `6`, and defaults to `1`. - `history_character_limit`: Maximum combined characters of the earlier messages in the window. Accepts `0` to `10000`, and defaults to `1000`. - **Updated behavior** - `prompt`: A custom prompt fully replaces Agora's default prompt, and applies over the same conversation context window. **Go SDK** - [`NewSmallestAISTT`](/en/api-reference/api-ref/server-sdk/go#stt-vendors): New ASR vendor class for Smallest AI. - [`NewGeminiSTT`](/en/api-reference/api-ref/server-sdk/go#stt-vendors): New ASR vendor class for Gemini. - [`NewOpenAIGPTLive`](/en/api-reference/api-ref/server-sdk/go#mllm-vendors): New MLLM vendor class for OpenAI GPT-Live. - [MLLM vendor classes](/en/api-reference/api-ref/server-sdk/go#mllm-vendors): New `Tools` option for custom tool definitions, and new `McpServers` option for MCP tool-use. `NewOpenAIGPTLive` uses `McpServerConfigs` for the same purpose. - [`NewSmallestAITTS`](/en/api-reference/api-ref/server-sdk/go#tts-vendors): New TTS vendor class for Smallest AI. - **New fields** on [`FillerWordsContentGeneratedConfig`](/en/api-reference/api-ref/server-sdk/go#type-aliases), both `*int` - `ContextMessageLimit`: How many of the most recent conversation messages to use, counting the current turn's message. Accepts `1` to `6`, and defaults to `1`. - `HistoryCharacterLimit`: Maximum combined characters of the earlier messages in the window. Accepts `0` to `10000`, and defaults to `1000`. - **Updated behavior** - `Prompt`: A custom prompt fully replaces Agora's default prompt, and applies over the same conversation context window. **REST API** - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters** - [`filler_words.content.generated_config.context_message_limit`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-filler-words-content-generated-config-context-message-limit): How many of the most recent conversation messages to use to generate a filler phrase, counting the current turn's message. Accepts `1` to `6`, and defaults to `1`. - [`filler_words.content.generated_config.history_character_limit`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-filler-words-content-generated-config-history-character-limit): Maximum combined characters of the earlier messages in the window. Accepts `0` to `10000`, and defaults to `1000`. - [`mllm.tools`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-tools): Custom tool definitions an MLLM agent can call. Takes the same format as `llm.tools`, and requires `advanced_features.enable_tools`. - **Updated parameters** - [`asr.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-asr-vendor) value `smallestai`: Use Smallest AI as the ASR provider. See [Smallest AI](/en/ai/models/asr/smallest-ai). - [`asr.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-asr-vendor) value `gemini`: Use Gemini as the ASR provider. See [Gemini](/en/ai/models/asr/gemini). - [`mllm.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-vendor) value `openai_gpt_live`: Use OpenAI GPT-Live as the MLLM provider. See [OpenAI GPT-Live](/en/ai/models/mllm/openai-gpt-live). - [`tts.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-vendor) value `smallestai`: Use Smallest AI as the TTS provider. See [Smallest AI](/en/ai/models/tts/smallest-ai). - [`filler_words.content.generated_config.prompt`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-filler-words-content-generated-config-prompt): A custom prompt fully replaces Agora's default prompt, and applies over the same conversation context window. #### v2.12 Released on September 10, 2026. #### New features Included in this release: - **Call custom tools** Agents can now call your own HTTPS endpoints as tools during a conversation. The LLM decides when to call a tool and generates its parameters from the conversation. The Conversational AI Engine then calls your endpoint and returns the result to the LLM to continue generating a response. Available in the Agora Agents SDKs and the RESTful API. For details, see [Call custom tools](build/tools/custom-tools). - **Generated filler words** Agents can now generate filler words from the current conversation instead of selecting them from a fixed phrase list. Agora hosts the generation service, so you don't need your own model, endpoint, or credentials. You can optionally keep a static phrase list as a fallback. Available in the Agora Agents SDKs and the RESTful API. For details, see [Talking while waiting](build/shape-the-conversation/filler-words). - **Defer custom instructions** Custom instructions now support an `append` action. Instead of interrupting the current interaction, the agent waits for the current turn to finish, then adds the instruction to the conversation and starts a new turn. Available in the Agora Agents SDKs and the RESTful API. For details, see [Send custom instructions](/en/api-reference/api-ref/conversational-ai/think). - **Client component support for direct speech and instruction injection** The [Android](/en/api-reference/api-ref/conversational-ai/client-toolkit/android), [iOS](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios), and [Web](/en/api-reference/api-ref/conversational-ai/client-toolkit/web) client toolkits add `speak` and `think` methods. Use `speak` to bypass the LLM and make the agent speak text directly, or `think` to inject text as user input for the LLM to process. Both methods send messages over RTM and support message priority, interruption behavior, and per-state Think actions. - **MCP tool-use for MLLM agents** MLLM agents now support MCP tool-use, in addition to cascading LLM agents. Available only in the RESTful API. For details, see [Use MCP tools](build/tools/mcp-tools). - **New ASR provider** - [Gemini](models/asr/gemini) #### API changes This release introduces the following changes for custom tool calling, generated filler words, MCP tool-use for MLLM agents, and the `think` API's `append` action. **Python SDK** - [`OpenAI`](/en/api-reference/api-ref/server-sdk/python#openai) and other LLM vendor classes: New `tools` parameter for custom tool definitions. - [`with_tools()`](/en/api-reference/api-ref/server-sdk/python#other-builder-methods): Now also enables custom tools declared in `tools`, in addition to MCP tools. - [`FillerWordsConfig`](/en/api-reference/api-ref/server-sdk/python#type-aliases): New `generated` content mode and `FillerWordsContentGeneratedConfig` for generated filler words. - [`AgentSession.think()`](/en/api-reference/api-ref/server-sdk/python#thinktext): `on_listening_action`, `on_thinking_action`, and `on_speaking_action` accept the new value `append`. - New custom tool type aliases: `LlmToolConfig`, `LlmToolFunctionConfig`, `LlmToolFunctionParametersConfig`, `LlmToolExecutionConfig`, and `LlmToolServerConfig`. **TypeScript SDK** - [`OpenAI`](/en/api-reference/api-ref/server-sdk/typescript#openai) and other LLM vendor classes: New `tools` option for custom tool definitions. - [`withTools()`](/en/api-reference/api-ref/server-sdk/typescript#other-builder-methods): Now also enables custom tools declared in `tools`, in addition to MCP tools. - [`FillerWordsConfig`](/en/api-reference/api-ref/server-sdk/typescript#type-aliases): New `generated` content mode and `FillerWordsContentGeneratedConfig` for generated filler words. - [`AgentSession.think()`](/en/api-reference/api-ref/server-sdk/typescript#thinktext-options): `on_listening_action`, `on_thinking_action`, and `on_speaking_action` accept the new value `append`. - New custom tool type aliases: `LlmTool`, `LlmToolFunction`, `LlmToolServer`, and `LlmToolExecution`. **Go SDK** - [`NewOpenAI`](/en/api-reference/api-ref/server-sdk/go#newopenai) and other LLM vendor constructors: New `Tools` field for custom tool definitions. - [`WithTools()`](/en/api-reference/api-ref/server-sdk/go#other-builder-methods): Now also enables custom tools declared in `Tools`, in addition to MCP tools. - [`FillerWordsConfig`](/en/api-reference/api-ref/server-sdk/go#type-aliases): New `FillerWordsContentModeGenerated` content mode and `FillerWordsContentGeneratedConfig` for generated filler words. - [`Think()`](/en/api-reference/api-ref/server-sdk/go#thinkctx): Each state action accepts the new value `append`. - New type aliases: `LlmTool`, `LlmToolFunction`, `LlmToolFunctionParameters`, `LlmToolExecution`, `LlmToolServer`, `FillerWordsContentMode`, and `FillerWordsContentGeneratedConfig`. **REST API** - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters** - [`llm.tools`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-tools): Custom tool definitions the LLM can call. Requires `advanced_features.enable_tools`. - [`filler_words.content.generated_config`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-filler-words-content-generated-config): Prompt and fallback strategy for generated filler words. Used when `filler_words.content.mode` is `generated`. - [`mllm.mcp_servers`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-mcp-servers): MCP server connections for MLLM agents. Requires `advanced_features.enable_tools`. - **Updated parameters** - [`advanced_features.enable_tools`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-advanced-features-enable-tools): Now also enables custom tools declared in `llm.tools` and MCP tools declared in `mllm.mcp_servers`, in addition to MCP tools configured in `llm.mcp_servers`. - [`filler_words.content.mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-filler-words-content-mode) value `generated`: Generate a filler phrase from the current context, with an optional `filler_words.content.static_config` fallback. - [`filler_words.content.static_config`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-filler-words-content-static-config): Now a named sibling property of `content` instead of the `"{mode}_config"` key. - Changes to [**Send custom instructions**](/en/api-reference/api-ref/conversational-ai/think) - **Updated parameters** - [`on_listening_action`](/en/api-reference/api-ref/conversational-ai/think#request-body-properties-on-listening-action), [`on_thinking_action`](/en/api-reference/api-ref/conversational-ai/think#request-body-properties-on-thinking-action), and [`on_speaking_action`](/en/api-reference/api-ref/conversational-ai/think#request-body-properties-on-speaking-action) value `append`: Don't interrupt the current interaction; append the instruction as a separate user message once the current turn's LLM output finishes. #### Toolkit API This release adds `speak` and `think` methods to the client toolkit, so you can bypass the LLM to play text directly or inject text as user input: **Android** - [`speak`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#speak) - [`think`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#think) - `SpeakMessage`, `ThinkMessage`, `ThinkListeningAction`, `ThinkThinkingAction`, `ThinkSpeakingAction` **iOS** - [`speak`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#speak) - [`think`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#think) - `SpeakMessage`, `ThinkMessage`, `ThinkListeningAction`, `ThinkThinkingAction`, `ThinkSpeakingAction` **Web** - [`speak`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#speak) - [`think`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#think) - `SpeakMessage`, `ThinkMessage`, `EThinkListeningAction`, `EThinkThinkingAction`, `EThinkSpeakingAction` #### Deprecation notice > **Warning: Important** > > These changes may affect your existing integration. Review each change and update your integration as needed. - **`asr.params` becomes required for non-default ASR vendors in v2.13.** Starting in v2.13, a request that sets [`asr.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-asr-vendor) to a vendor other than `ares` and omits [`asr.params`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-asr-params) fails. Configure `asr.params` for your vendor, or omit `asr.vendor` to keep the default `ares` vendor. - **Legacy `turn_detection` fields and the `keywords`/`disabled` start-of-speech modes lose their support guarantee in a future release.** Migrate to [`turn_detection.config`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config) and [`interruption`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-interruption), introduced in v2.6. - **`advanced_features.enable_mllm` loses its support guarantee in a future release.** The MLLM switch may stop working. Migrate to [`mllm.enable`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-enable), introduced in v2.6. #### v2.11 Released on August 11, 2026. #### New features Included in this release: - **ASR keywords** You can now configure keywords to improve ARES's recognition accuracy for specific terms, such as brand names, product names, or industry jargon. Configure keywords using the `AresSTT` vendor in the Agora Agents SDKs, or the `keywords` parameter within the `asr` block directly through the RESTful API. For details, see [Improve ASR accuracy with keywords](build/shape-the-conversation/asr-keywords). - **New TTS provider** - [Typecast](models/tts/typecast) - **New MLLM provider** - [Azure OpenAI Realtime API](models/mllm/azure) #### Improvements This release includes the following enhancements. - **Improved stability for long audio replies** This release improves resource protection and error-recovery logic for long streaming audio replies, reducing the likelihood of an abnormal disconnect or failed recovery. As a result, service stability improves for long replies and free-form conversation scenarios. - **Cara 4 model and portrait video for Anam avatars** Anam avatars support the Cara 4 model and custom output resolutions, including portrait video for mobile apps. For details, see [Portrait video](models/avatar/anam#portrait-video). #### API changes This release introduces the following changes for ASR keywords, the new TTS and MLLM providers, and Anam avatars. **Python SDK** - [`AresSTT`](/en/api-reference/api-ref/server-sdk/python#aresstt): New `keywords` parameter. - [`TypecastTTS`](/en/api-reference/api-ref/server-sdk/python#typecasttts): New TTS vendor class. - [`AzureOpenAIRealtime`](/en/api-reference/api-ref/server-sdk/python#azureopenairealtime): New MLLM vendor class. **TypeScript SDK** - [`AresSTT`](/en/api-reference/api-ref/server-sdk/typescript#other-stt-vendors): New `keywords` option. - [`TypecastTTS`](/en/api-reference/api-ref/server-sdk/typescript#other-tts-vendors): New TTS vendor class. - [`AzureOpenAIRealtime`](/en/api-reference/api-ref/server-sdk/typescript#azureopenairealtime): New MLLM vendor class. **Go SDK** - [`NewAresSTT`](/en/api-reference/api-ref/server-sdk/go#newaresstt): New `Keywords` field. - [`NewTypecastTTS`](/en/api-reference/api-ref/server-sdk/go#newtypecasttts): New TTS vendor constructor. - [`NewAzureOpenAIRealtime`](/en/api-reference/api-ref/server-sdk/go#newazureopenairealtime): New MLLM vendor constructor. **REST API** - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters** - [`asr.keywords`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-asr-keywords): ASR keywords used to improve recognition accuracy for specific terms. Only available when `asr.vendor` is not set or `ares`. - [`avatar.params`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-avatar-params) fields for Anam: `avatar_model` selects the avatar model, such as `cara-4`, and `video_width` and `video_height` set the output resolution. See [Anam](/en/ai/models/avatar/anam#portrait-video). - **Updated parameters** - [`tts.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-vendor) value `typecast`: Use Typecast as the TTS provider. See [Typecast](/en/ai/models/tts/typecast). - [`mllm.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-vendor) value `azure`: Use Azure OpenAI Realtime API as the MLLM provider. See [Azure OpenAI Realtime API](/en/ai/models/mllm/azure). #### v2.10 Released on July 30, 2026. #### New features Included in this release: - **Connect custom TTS services using the OpenAI protocol** You can now use a self-built, privately deployed, or third-party TTS service that implements the OpenAI TTS protocol as your agent's speech synthesis module. Configure it using the `GenericTTS` vendor in the Agora Agents SDKs (Go and TypeScript v2.4.0 or later, Python v2.4.1 or later), or the `generic_http` TTS vendor directly through the RESTful API. For details, see [Connect your own TTS service](/en/ai/build/custom-model-integration/custom-tts) and [Generic TTS](/en/ai/models/tts/generic-http). - **Client toolkit support for manual turn control** The Android, iOS, and Web client toolkits now provide dedicated APIs for manual Start of Speech (SoS) and End of Speech (EoS) control, so you no longer need to construct raw Signaling (RTM) messages by hand. Call `manualSOS`/`manualEOS` to send requests, and register the new result callbacks to handle the server's response. This capability is suitable for scenarios that require explicit control of the user turn boundary from the client side, such as AI interviews, interactive quizzes, and walkie-talkie apps. For details, see [Manually control start and end of speech](/en/ai/best-practices/manual-turn-control). - **New TTS providers** - [Gradium](models/tts/gradium) - [Mistral](models/tts/mistral) - **New Avatar provider** - [LemonSlice](models/avatar/lemonslice) #### Toolkit API This release adds the following APIs to the client toolkit for manual turn control: **Android** - [`manualSOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#manualsos) - [`manualEOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#manualeos) - [`onUserManualSosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onusermanualsosevent) - [`onUserManualEosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onusermanualeosevent) - [`onAgentManualEosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagentmanualeosevent) - `UserManualEventPayload`, `UserManualSosEvent`, `UserManualEosEvent`, `AgentManualEosPayload`, `AgentManualEosEvent` **iOS** - [`manualSOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#manualsos) - [`manualEOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#manualeos) - [`onUserManualSosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onusermanualsosevent) - [`onUserManualEosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onusermanualeosevent) - [`onAgentManualEosEvent`](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagentmanualeosevent) - `UserManualEventPayload`, `UserManualSosEvent`, `UserManualEosEvent`, `AgentManualEosPayload`, `AgentManualEosEvent` **Web** - [`manualSOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#manualsos) - [`manualEOS`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#manualeos) - [`EConversationalAIAPIEvents`](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#econversationalaiapievents) values `USER_MANUAL_SOS_RESULT`, `USER_MANUAL_EOS_RESULT`, and `AGENT_MANUAL_EOS_RESULT` - `TUserManualEventPayload`, `TUserManualSosEvent`, `TUserManualEosEvent`, `TAgentManualEosPayload`, `TAgentManualEosEvent` #### API changes This release introduces the following changes for connecting TTS services. **Python SDK** This release adds the following TTS vendor classes: - [`GenericTTS`](/en/api-reference/api-ref/server-sdk/python#generictts): Connect a custom TTS service using the OpenAI TTS protocol. - [`GradiumTTS`](/en/api-reference/api-ref/server-sdk/python#gradiumtts) - [`MistralTTS`](/en/api-reference/api-ref/server-sdk/python#mistraltts) **TypeScript SDK** This release adds the following TTS vendor classes: - [`GenericTTS`](/en/api-reference/api-ref/server-sdk/typescript#generictts): Connect a custom TTS service using the OpenAI TTS protocol. - [`GradiumTTS` and `MistralTTS`](/en/api-reference/api-ref/server-sdk/typescript#other-tts-vendors) **Go SDK** This release adds the following TTS vendor constructors: - [`NewGenericTTS`](/en/api-reference/api-ref/server-sdk/go#newgenerictts): Connect a custom TTS service using the OpenAI TTS protocol. - [`NewGradiumTTS`](/en/api-reference/api-ref/server-sdk/go#newgradiumtts) - [`NewMistralTTS`](/en/api-reference/api-ref/server-sdk/go#newmistraltts) **REST API** - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters** - [`tts.url`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-url): The OpenAI TTS protocol compatible service endpoint. Required only when `tts.vendor` is `generic_http`. - [`tts.headers`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-headers): Custom request headers to include in requests to the TTS service. Required only when `tts.vendor` is `generic_http`. - **Updated parameters** - [`tts.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-vendor) value `generic_http`: Integrate a custom TTS service using the OpenAI TTS protocol. See [Generic TTS](/en/ai/models/tts/generic-http). - [`tts.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-vendor) value `gradium`: Use Gradium as the TTS provider. See [Gradium](/en/ai/models/tts/gradium). - [`tts.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-vendor) value `mistral`: Use Mistral as the TTS provider. See [Mistral](/en/ai/models/tts/mistral). - [`tts.params`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-params): Now required when `tts.vendor` is `generic_http`. #### v2.9 Released on July 1, 2026. #### New features Included in this release: - **Manual turn control** You can now explicitly control when a user's speech starts and ends by sending manual Start of Speech (SoS) and End of Speech (EoS) requests over Signaling (RTM), instead of relying on automatic detection. This supports scenarios with strict turn-boundary requirements, such as AI interviews, interactive quizzes, or push-to-talk. Set [`start_of_speech.mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config-start-of-speech-mode) and [`end_of_speech.mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config-end-of-speech-mode) to `manual` when starting the agent. For details, see [Manually control start and end of speech](/en/ai/best-practices/manual-turn-control). - **Agent state notifications over RTM Message** You can now track agent state changes in real time using Signaling (RTM) Message events. The agent pushes `state.listening`, `state.thinking`, and `state.speaking` events as individual RTM messages, making it easier to record state change timestamps, process events sequentially, or consume state events alongside other RTM Message events. For details, see [Get agent state](/en/ai/best-practices/get-agent-state). - **Pre-recorded greeting audio** You can now play a pre-recorded audio file as the agent's greeting instead of synthesizing it with TTS. Set [`properties.llm.greeting_audio_url`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-greeting-audio-url) to the URL of an `mp3`, `wav`, or `pcm` file when starting the agent. If the audio fails to download, decode, or is in an unsupported format, the agent automatically falls back to TTS synthesis using `greeting_message`. - **Managed mode** You can now use supported ASR, LLM, and TTS providers with Agora-managed credentials, without supplying your own API keys. Set [`credential_mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-asr-credential-mode) to `"managed"` within the `asr`, `llm`, or `tts` block when starting an agent. Managed mode replaces the deprecated `preset` parameter. For details, see [Use managed mode](/en/ai/build/managed-mode). #### Improvements This release includes the following enhancements. - **Speech captured during an uninterruptible greeting** When [`properties.llm.greeting_configs.interruptable`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-greeting-configs-interruptable) is set to `false`, the agent now silently collects the user's ASR results while the greeting plays. After the greeting ends, the system concatenates the collected speech segments into a single user message and sends it to the LLM for a unified response, instead of discarding speech that occurs during playback. #### API changes This release introduces the following changes to the RESTful API. - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters** - [`properties.llm.greeting_audio_url`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-greeting-audio-url): The URL of a pre-recorded audio file (`mp3`, `wav`, or `pcm`) to play as the agent's greeting instead of synthesizing it with TTS. - [`properties.llm.greeting_configs.audio_download_timeout_ms`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-greeting-configs-audio-download-timeout-ms): The timeout in milliseconds for downloading the greeting audio file. Defaults to `1000`. - [`properties.llm.greeting_configs.audio_pcm_sample_rate`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-greeting-configs-audio-pcm-sample-rate): The sample rate in Hz of the greeting audio file when the format is PCM. Defaults to `16000`. - [`properties.asr.credential_mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-asr-credential-mode), [`properties.llm.credential_mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-credential-mode), and [`properties.tts.credential_mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-tts-credential-mode): Set to `"managed"` to use Agora-managed credentials for the provider without supplying your own API key. - **Updated parameters** - [`properties.turn_detection.config.start_of_speech.mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config-start-of-speech-mode): Now accepts `manual`, which disables automatic start-of-speech detection so the client can explicitly signal the start of user speech over RTM. - [`properties.turn_detection.config.end_of_speech.mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config-end-of-speech-mode): Now accepts `manual`, which disables automatic end-of-speech detection so the client can explicitly signal the end of user speech over RTM. - [`properties.llm.greeting_message`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-greeting-message): In addition to serving as a standalone greeting, this field is now required as a fallback when `greeting_audio_url` is configured, and is used to maintain conversation context when an audio greeting is interrupted. - **Deprecated parameters** - [`preset`](/en/api-reference/api-ref/conversational-ai/join#preset): Deprecated in favor of setting `credential_mode` to `"managed"` within the `asr`, `llm`, or `tts` block. See [Use managed mode](/en/ai/build/managed-mode). - Changes to [**Notification event types**](/en/ai/reference/event-types) - **Updated events** - [`110 agent error`](/en/ai/reference/event-types#110-agent-error): Now reports greeting audio URL errors when the greeting audio file fails to download, times out, is in an unsupported format, or fails to decode. The agent automatically falls back to TTS synthesis using `greeting_message`. When `parameters.enable_error_message` is `true`, these errors are also delivered to the client via the `onMessageError` RTM callback. #### v2.8 Released on June 11, 2026. #### New features Included in this release: - **Session data retention control** By default, session interaction text and audio are temporarily retained for the minimum necessary period to support service operation, agent optimization, and troubleshooting. To disable data retention for a session, set [`properties.parameters.opt_out`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-parameters-opt-out) to `true` when starting an agent. - **RTC token expiry warning** A new [`104 agent expire`](reference/event-types#104-agent-expire) event is triggered when the agent's RTC token is about to expire. Upon receiving this event, call the [Update agent](/en/api-reference/api-ref/conversational-ai/update) API with a new token to refresh it. The agent does not exit the channel or interrupt the session when this event is triggered. - **New ASR provider** - [xAI](models/asr/xai) - **New LLM provider** - [xAI Grok](models/llm/xai) - **New TTS provider** - [xAI](models/tts/xai) #### Improvements This release includes the following enhancements. > **Warning: Important** > > These changes may affect your existing integration. Review each change and update your integration as needed. - **Idle timeout behavior change** Setting `properties.idle_timeout` to `0` no longer means the agent runs indefinitely. From this release, `0` only disables the channel idle timeout. Regardless of the `idle_timeout` value, the maximum running time for a single session is 72 hours, after which the agent automatically exits. If your integration previously relied on `idle_timeout = 0` to keep an agent running until manually stopped, update your task scheduling and lifecycle management logic to account for the 72-hour limit. #### API changes This release introduces the following changes to the RESTful API. - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters** - [`properties.parameters.opt_out`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-parameters-opt-out): Set to `true` to disable data retention for the current session. - **Updated parameters** - [`properties.idle_timeout`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-idle-timeout): Valid range is now `0` to `259200` seconds (72 hours). Regardless of the value set, the maximum running time for a single session is 72 hours. - Changes to [**Retrieve agent history**](/en/api-reference/api-ref/conversational-ai/history) - **New response fields** - [`contents[].speech_start_ms`](/en/api-reference/api-ref/conversational-ai/history#contents-speech-start-ms): Unix timestamp in milliseconds indicating when the user started speaking or the agent started TTS playback. Only returned when `llm.vendor` is `custom`. - [`contents[].speech_end_ms`](/en/api-reference/api-ref/conversational-ai/history#contents-speech-end-ms): Unix timestamp in milliseconds indicating when the user stopped speaking, or when TTS playback completed or was interrupted. Only returned when `llm.vendor` is `custom`. - [`contents[].speech_algorithmic_delay`](/en/api-reference/api-ref/conversational-ai/history#contents-speech-algorithmic-delay): The total delay in milliseconds introduced by audio processing algorithms after audio is captured from the user's microphone. Only returned when `llm.vendor` is `custom`, `contents[].role` is `user`, and actual voice input is present. - Changes to [**Notification event types**](reference/event-types) - **New events** - [`104 agent expire`](reference/event-types#104-agent-expire): Triggered when the agent's RTC token is about to expire. Call the Update agent API with a new token upon receiving this event. - **Updated events** - [`102 agent left`](reference/event-types#102-agent-left): Added `Task lifetime limit exceeded` as a new exit reason when the 72-hour session limit is reached. - [`103 agent history`](reference/event-types#103-agent-history): Added `contents[].speech_start_ms`, `contents[].speech_end_ms`, and `contents[].speech_algorithmic_delay`. Only returned when `llm.vendor` is `custom`. - Changes to [**Retrieve a list of agents**](/en/api-reference/api-ref/conversational-ai/list) - **Updated parameters** - `state`: Now accepts a comma-separated list of values to filter by multiple agent states in a single request. For example, `state=0,1,2`. #### v2.7 Released on May 20, 2026. #### New features Included in this release: - **New MLLM provider** - [xAI Grok](models/mllm/xai) - **New Avatar providers** - [Generic avatar (Beta)](models/avatar/generic) - **Greeting interruption control** The `properties.llm.greeting_configs` object in the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API now supports an `interruptable` parameter, which controls whether user speech can interrupt a greeting during playback. #### Improvements This release includes the following enhancements: > **Warning: Important** > > These changes may affect your existing integration. Review each change and update your integration as needed. - **Response status codes updated** This release adjusts the HTTP response status codes and `reason` values returned by the RESTful API. New status codes `401`, `429`, and `500` are added. New `reason` values `ServiceNotEnabled`, `AccountSuspended`, and `ResourceAllocationFailed` are introduced. The existing `InvalidRequest` reason is replaced by `InvalidRequestBody`, `MissingRequiredField`, and `InvalidFieldValue`. For details, see [Status codes and error messages](/en/api-reference/api-ref/conversational-ai/status-codes). If your integration relies on `reason` values for error handling, retry logic, or alerting, update your logic to handle the new values accordingly. - **Query conversation turns API now returns paginated results** The [Query conversation turn information](/en/api-reference/api-ref/conversational-ai/turns) API no longer returns all turns in a single response. Results are now paginated, defaulting to page 1 with up to 50 turns per page. This affects sessions with more than 50 conversation turns. Update your integration to handle the new `total_turn_count` and `pagination` fields in the response, and retrieve subsequent pages as needed. This release also adds the [112 turns finished](reference/event-types#112-turns-finished) notification event, which delivers conversation turn data in batches after a session ends as an alternative way to retrieve turn data. - **`on_listening_action` default behavior change** The default value of `on_listening_action` in the [Send a custom instruction](/en/api-reference/api-ref/conversational-ai/think) API has changed from `inject` to `interrupt`. When set to `interrupt`, the API immediately interrupts the current flow and initiates a new round of dialogue. If you rely on the previous default behavior, explicitly set `on_listening_action` to `inject` in your requests. #### API changes This release introduces the following changes to the RESTful API. - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters** - [`properties.llm.greeting_configs.interruptable`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-greeting-configs-interruptable): Controls whether user speech can interrupt a greeting during playback. - Changes to [**Query conversation turn information**](/en/api-reference/api-ref/conversational-ai/turns) - **New query parameters** Adds `page_index` and `page_size` fields to [query parameters](/en/api-reference/api-ref/conversational-ai/turns#query-parameters). - **New response parameters** The [response](/en/api-reference/api-ref/conversational-ai/turns#response) now includes additional top-level fields: - `agent_id`: The unique identifier of the agent. - `name`: The name of the agent. - `channel`: The name of the RTC channel the agent joined. - `total_turn_count`: The total number of dialogue turns in the session. - `pagination`: Pagination details for the response, including `page_index`, `total_pages`, and `is_last_page`. - Changes to [**Send a custom instruction**](/en/api-reference/api-ref/conversational-ai/think) - **Behavior changes** - [`on_listening_action`](/en/api-reference/api-ref/conversational-ai/think#on-listening-action): The default value has changed from `inject` to `interrupt`. When set to `interrupt`, the API immediately interrupts the current flow and initiates a new round of dialogue. - Changes to [**Notification event types**](reference/event-types) - **New events** - `112 turns finished`: Triggered after a session ends, delivering conversation turn data in batches for post-session analysis and processing. #### v2.6 Released on April 22, 2026. #### New features Included in this release: - **New TTS provider** - [Deepgram](models/tts/deepgram) - **New endpoint: Send a custom instruction** Adds a new endpoint to inject a custom text instruction into the agent's current conversation pipeline. The instruction is processed as user input, enabling scenarios such as implicit instruction injection, client-side event triggering, and voice and text collaboration. For details, see [Send a custom instruction](/en/api-reference/api-ref/conversational-ai/think). - **MLLM turn detection refactoring** Introduces a new [`mllm.turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection) object for configuring turn detection when using MLLM. When defined, this overrides the top-level `turn_detection` object. Supported modes vary by vendor: - OpenAI Realtime API: `agora_vad`, `server_vad`, `semantic_vad` - Google Gemini Live: `agora_vad`, `server_vad` - **Interruption control** Adds a new top-level [`interruption`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-interruption) object for unified management of agent interruption behavior. Supports `start_of_speech` and `keywords` trigger modes, and configurable handling strategies when interruption is disabled. #### Improvements This release includes the following enhancements: - **New agent state callbacks** Adds three callbacks to the [Android](/en/api-reference/api-ref/conversational-ai/client-toolkit/android#onagentlisteningchanged), [iOS](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios#onagentlisteningchanged), and [web](/en/api-reference/api-ref/conversational-ai/client-toolkit/web#econversationalaiapievents) Toolkit event handler interface: - `onAgentListeningChanged`: Listen for changes in the agent's listening state to monitor when the agent starts or stops listening to user input. - `onAgentThinkingChanged`: Listen for changes in the agent's thinking state to monitor when the agent starts or stops processing a request. - `onAgentSpeakingChanged`: Listen for changes in the agent's speaking state to monitor when the agent starts or stops playing back speech. - **Added `name` field to all [NCS event](reference/event-types) payloads** Returns the agent name provided when starting the agent. #### API changes This release introduces the following changes to the RESTful API. - **New endpoint** - [Send a custom instruction](/en/api-reference/api-ref/conversational-ai/think): `POST /v2/projects/{appid}/agents/{agentId}/think` - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters** - [`interruption`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-interruption): Unified interruption control configuration. Supports `start_of_speech` and `keywords` trigger modes, and configurable handling strategies when interruption is disabled. - [`greeting_configs.delay_ms`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-greeting-configs-delay-ms): Specifies the delay in milliseconds before the agent plays the greeting message after the user joins the channel. - [`llm.headers`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-headers): Lets you pass custom headers in LLM requests, such as business-specific fields or tenant identifiers. - [`mllm.enable`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-enable): Enables the MLLM module. Replaces the deprecated `advanced_features.enable_mllm`. - [`mllm.turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection): Turn detection configuration for the MLLM module. When defined, overrides the top-level `turn_detection` object. - [`mllm.turn_detection.server_vad_config.idle_timeout_ms`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-turn-detection-server-vad-config-idle-timeout-ms): Idle timeout in milliseconds for server VAD mode. Applicable to OpenAI Realtime API only. - [`mllm.vendor`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-mllm-vendor) value `gemini`: Enables Google Gemini Live integration using the Gemini Developer API. - **Behavior changes** - `turn_detection` now handles SoS and EoS detection only. Interruption handling strategies have moved to the new top-level `interruption` field. - `turn_detection.config.start_of_speech.mode` values `keywords` and `disabled` are deprecated. Use the new `interruption` field instead. - When `turn_detection.end_of_speech.mode` is set to `semantic`, EOS detection supports English and Chinese only. For unsupported languages, the engine automatically falls back to VAD. - **Deprecated fields** - `advanced_features.enable_mllm`: Use `mllm.enable` instead. - `turn_detection.config.start_of_speech.mode` value `keywords`: Use `interruption.mode = "keywords"` instead. - `turn_detection.config.start_of_speech.mode` value `disabled`: Use `interruption.enable = false` with `interruption.disabled_config.strategy` instead. - **Removed fields** - `mllm.style` - `mllm.create_response` and `mllm.interrupt_response` for OpenAI Realtime API. - Changes to [**Notification event types**](reference/event-types) - **New fields** - Added `name` to all [NCS event payloads](reference/event-types). Returns the agent name provided when starting the agent. #### v2.5 Released on March 31, 2026. #### New features Included in this release: - **Preset model configurations** Adds a [`preset`](/en/api-reference/api-ref/conversational-ai/join#preset) parameter to the Join API. Pass a comma-separated list of preset names to apply predefined configurations for ASR, LLM, and TTS providers. When you use a preset, you do not need to provide the endpoint URL, API key, or model for the preset provider. Use the `asr`, `llm`, and `tts` fields to configure additional settings. When you use a preset, the corresponding ASR, LLM, or TTS service is provided through Agora-managed accounts. For details, see the [pricing](reference/pricing) page. Available presets: - ASR: `deepgram_nova_2`, `deepgram_nova_3` - LLM: `openai_gpt_4o_mini`, `openai_gpt_4_1_mini`, `openai_gpt_5_nano`, `openai_gpt_5_mini` - TTS: `minimax_speech_2_6_turbo`, `minimax_speech_2_8_turbo`, `openai_tts_1` - **Pause state detection** When enabled, the agent uses semantic understanding to detect when a user intends to pause the conversation. For example, if the user says "hold on" or "just a moment", the agent waits for further input instead of forwarding the utterance to the LLM. Controlled by the new [`pause_state_enabled`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config-end-of-speech--mode-config-pause-state-enabled) parameter. - **Conversation turn insights** You can now query per-turn start, end, and latency metrics for completed agent sessions. See [Query conversation turn information](/en/api-reference/api-ref/conversational-ai/turns). - **Real-time TTS parameter updates with custom LLM** In scenarios with a custom LLM integrated, this release adds support for real-time TTS parameter updates during conversations, enabling a more natural conversational experience. This feature applies to the following use cases: - The custom LLM detects a user request for the agent to change its voice or speaking style. - The custom LLM identifies a user's positive emotion and adjusts TTS volume, pitch, speech rate, and other parameters in real time to better match the user's mood. For implementation details, refer to [Real-time TTS parameter updates](build/custom-model-integration/custom-llm#update-tts-parameters-in-real-time). - **New TTS provider** - [Murf (Beta)](models/tts/murf) - **New Avatar provider** - [Anam (Beta)](models/avatar/anam) #### Improvements This release includes the following enhancements: - **Migration from HeyGen API to LiveAvatar (Beta) API** Updates the HeyGen avatar model configuration to use the [LiveAvatar (Beta)](models/avatar/heygen) API. #### API changes This release introduces the following changes to the RESTful API. - **New endpoint: Query conversation turns** Adds a new GET endpoint to query conversation turn information for an agent session. After a conversation ends, use this endpoint to retrieve the start event, end event, and latency metrics for each turn within the session. For details, see [Query conversation turn information](/en/api-reference/api-ref/conversational-ai/turns). - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters added** - [`preset`](/en/api-reference/api-ref/conversational-ai/join#preset) - [`pause_state_enabled`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config-end-of-speech--mode-config-pause-state-enabled) - **Deprecated fields deleted** The following deprecated fields are deleted: - `properties.silence_timeout` - `properties.advanced_features.enable_aivad` - `properties.llm.silence_message` #### v2.4 Released on February 2, 2026. #### New features Included in this release: - **MCP integration** Adds a [`llm.mcp_servers`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-mcp-servers) field to the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API to connect the LLM to an MCP (Model Context Protocol) server. Set [`advanced_features.enable_tools`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-advanced-features-enable-tools) to `true` to enable tool calls. This allows the agent to call tools provided by external services to extend functionality. For details, see [Use MCP tools](build/tools/mcp-tools). - **Filler phrases** Adds a [`properties.filler_words`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-filler-words) field to insert pre-set or LLM-generated filler phrases during conversations to fill periods of silence while waiting for LLM output. This feature smooths dialogue flow, reduces user anxiety, and makes agent speech sound more natural. #### Improvements This release includes the following enhancements: - **Turn detection configuration optimization** The `turn_detection` parameter structure has been updated to provide more flexible conversation turn detection. The new structure uses a `mode` + `config` pattern with separate Start of Speech (SoS) and End of Speech (EoS) detection configurations. **Basic configuration** - `mode`: Conversation turn detection mode (currently supports `default`) - `config.speech_threshold`: Voice activity detection sensitivity **Start of Speech (SoS) detection** Detects when the user begins speaking. When SoS is detected while the agent is speaking, an interruption occurs. The [`config.start_of_speech`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config-start-of-speech) parameter supports three detection modes: - **VAD mode** (`vad`): Triggered by voice activity detection. Supports configuration of interruption threshold, prefix padding, and ignore word list. - **Keyword mode (Beta)** (`keywords`): Based on keyword triggering. The agent begins conversation after detecting a specified keyword. - **Disabled mode** (`disabled`): Disables interruption. Supports append or ignore strategies. **End of Speech (EoS) detection** Detects when the user finishes speaking. When EoS is detected, the agent generates a response. The [`config.end_of_speech`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config-end-of-speech) parameter supports two detection modes: - **VAD mode** (`vad`): Determines conversation end based on silence duration. - **Semantic mode** (`semantic`): Determines conversation end based on semantic understanding. Supports configurable maximum wait time. #### API changes This release introduces the following changes to the RESTful API. - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **[`turn_detection`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection) has a revamped structure** All previous fields under `turn_detection` have been deprecated and replaced with a new data structure. - Deprecated - `turn_detection.interrupt_mode` - `turn_detection.interrupt_keywords` - `turn_detection.interrupt_duration_ms` - `turn_detection.prefix_padding_ms` - `turn_detection.silence_duration_ms` - `turn_detection.threshold` - **AIVAD activation** The `advanced_features.enable_aivad` field is now deprecated; to configure AIVAD activation use [`turn_detection.config.end_of_speech.mode = "semantic"`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config-end-of-speech-mode). - **New parameters added** - [`advanced_features.enable_tools`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-advanced-features-enable-tools) - [`llm.mcp_servers`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-llm-mcp-servers) - [`properties.filler_words`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-filler-words) - [`turn_detection.mode`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-mode) - [`turn_detection.config`](/en/api-reference/api-ref/conversational-ai/join#request-body-properties-turn-detection-config) #### v2.3 Released on January 7, 2026. #### New features Included in this release: - **Control LLM response interruption in custom LLM scenarios** Adds a `metadata.interruptable` field in the first chunk of the `chat.completion.custom_metadata` object to control whether user speech can interrupt the agent's TTS output when using custom LLMs with streaming response (SSE). Use this to prevent interruptions when delivering critical information such as regulations, policies, or pricing. For more information, see [Configure LLM response interruption](build/custom-model-integration/custom-llm#configure-llm-response-interruption). - **RTC media content encryption** Adds an `rtc` parameter to the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API for configuring RTC encryption. - **New ASR provider** - [Sarvam (Beta)](models/asr/sarvam) #### Improvements This release includes the following enhancements: - **ElevenLabs TTS compatibility optimization** Supports SSML parsing and forwarding to ensure ElevenLabs TTS correctly renders intended speech effects such as pauses, emphasis, and pronunciation. - **Latency optimization best practices** Adds a guide to [Optimize conversation latency](best-practices/optimize-latency). - **Cloud Recording best practices** Adds a guide to [Record conversations with Cloud Recording](best-practices/record-agent-conversation). #### API changes This release introduces the following changes to the RESTful API. - **Stop agent API is now asynchronous** The [Stop a conversational AI agent](/en/api-reference/api-ref/conversational-ai/leave) API now responds immediately after request parameters are validated. The request is processed asynchronously after the API returns. - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters added** - `properties.rtc` #### v2.2 Released on December 15, 2025. #### New features Included in this release: - **Geofencing** Use `geofence` configuration when you [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) to limit which Agora servers the Conversational AI Engine can access based on geographic regions. See [Restrict agent zones](best-practices/regional-restrictions) for details. - **Agent greeting mode** Adds a field `llm.greeting_configs.mode` to the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) request to set the agent's greeting broadcast mode. The following modes are supported: - `single_every` (Default): The agent broadcasts a greeting every time a user joins a channel where there are no other users. - `single_first`: The agent broadcasts a greeting only when the first user joins a channel. - **New TTS providers** - [Sarvam (Beta)](models/tts/sarvam) #### Improvements This release includes the following enhancements: - **TTS parameter update** Adds `base_url` field to the TTS parameters for [OpenAI](models/tts/openai) and [ElevenLabs](models/tts/elevenlabs). This field specifies the endpoint URL for the TTS service. #### API changes This release introduces the following changes to the RESTful API. - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters added** - `properties.geofence` - `llm.greeting_configs.mode` #### v2.1 Released on December 5, 2025. #### New features Included in this release: - **Template variables** This version adds the `llm.template_variables` field to the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API, used to insert variables into the agent's `system_messages`, `greeting_message`, `failure_message`, and `parameters.silence_config.content` text. By configuring these variables, the Conversational AI engine automatically replaces them with the corresponding values defined in `llm.template_variables`. Template variables, combined with prompt customization and SIP outbound calling functionality, enable you to dynamically inject content to automate processes such as automatic hang-up, voicemail recognition, automatic message leaving, and call transfer. - **Custom labels** This version adds a `labels` field to the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API, enabling agents to carry custom labels. These labels are bound to the agent and returned in the `payload` field of all message notification callbacks from the Conversational AI engine, allowing you to implement custom business logic, such as tagging activity IDs, customer groups, and business scenarios. In SIP outbound call scenarios, you can pass a custom label in the `properties.labels` field when calling the outbound call interface to mark the call. #### API changes This release introduces the following changes to the RESTful API. - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters added** - `properties.labels` - `llm.template_variables` #### v2.0 Released on November 15, 2025. #### New features Included in this release: - **Telephony (Beta)** This version adds an outbound calling feature that enables the conversational AI agent to initiate an outbound call to a specified number through a POST API. After the call is answered, the agent can engage in real-time dialogue with the callee. This feature supports a wide range of outbound AI call scenarios. A set of phone number management APIs is also added for handling numbers connected to Conversational AI Engine. Refer to the API changes section for details. > **Info: Telephony pricing** > > The telephony feature is currently in **Beta** and is provided free of charge. Pricing terms may change upon official release. - **Selective attention locking (Beta)** This version adds the selective attention lock feature. Register voiceprints to enable the agent to identify specific speakers and suppress background voices and environmental noise, ensuring clearer, more focused conversations. - **Graceful exit** This version adds a new `farewell_config` field to [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API to configure the graceful exit feature. When enabled, calling the [Stop a Conversational Agent](/en/api-reference/api-ref/conversational-ai/leave) API causes the agent to enter an `IDLE` state before leaving the channel. - **Keyword interruption mode** This release adds a new option to the `turn_detection.interrupt_mode` field in the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API. Set this field to `"keyword"` to enable keyword interruption mode. When this mode is enabled, the agent stops its current behavior after detecting any of the keywords specified in the `turn_detection.interrupt_keywords` field. - **Adaptive interruption mode** This release adds a new option to the `turn_detection.interrupt_mode` field in the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API. Set this field to `"adaptive"` to enable adaptive interruption mode. When this mode is enabled, the agent dynamically increases the voice continuity threshold while speaking to reduce accidental interruptions. - **New ASR, LLM, MLLM, and TTS providers** - ASR - [OpenAI (Beta)](models/asr/openai) - [Speechmatics](models/asr/speechmatics) - [Google (Beta)](models/asr/google) - Amazon Transcribe (Beta) - [AssemblyAI (Beta)](models/asr/assembly-ai) - LLM - [Groq](models/llm/groq) - [Amazon Bedrock](models/llm/amazon) - MLLM - [Google Gemini Live](models/mllm/gemini) - TTS - [Rime (Beta)](models/tts/rime) - [Fish Audio (Beta)](models/tts/fish-audio) - [Google (Beta)](models/tts/google) - [Amazon Polly (Beta)](models/tts/amazon) - **New webhook notification events** This release adds three new webhook notification event types to support metrics reporting and call-state monitoring: - `111`: [agent metrics](reference/event-types#111-agent-metrics) Notifies real-time performance metrics for each dialogue turn, including ASR, LLM, and TTS latency measurements. - `201`: [inbound call state](reference/event-types#201-inbound-call-state) Reports state changes for incoming calls, such as when a call starts, is answered, transferred, or hung up. - `202`: [outbound call state](reference/event-types#202-outbound-call-state) Reports state changes for outbound calls initiated by the agent, including call start, dialing, ringing, answer, and hang-up events. #### Improvements This release includes the following enhancements: - **Support for avatars with MLLMs** Added support for using avatars with MLLMs. #### API changes This release introduces the following changes to the RESTful API. - Changes to [**Start a conversational AI agent**](/en/api-reference/api-ref/conversational-ai/join) - **New parameters added** - `properties.parameters.farewell_config` - `properties.advanced_features.enable_sal` - `properties.sal` - `properties.sal.sal_mode` - `properties.sal.sample_urls` - `properties.turn_detection.interrupt_mode` (supports `adaptive` and `keyword` values) - `properties.turn_detection.interrupt_keywords` - `properties.turn_detection.interrupt_duration_ms` (migrated from `vad.interrupt_duration_ms`) - `properties.turn_detection.prefix_padding_ms` (migrated from `vad.prefix_padding_ms`) - `properties.turn_detection.silence_duration_ms` (migrated from `vad.silence_duration_ms`) - `properties.turn_detection.threshold` (migrated from `vad.threshold`) - **Deprecated** - The `vad` interface is deprecated. All configuration items have been moved to the `turn_detection` field. - **New APIs** - Telephony (Beta) - Initiate an outbound call - Retrieve call records - Hang-up a call - Retrieve call status - Phone number management (Beta) - Retrieve list of numbers - Import number - Retrieve number information - Update number configuration - Delete number #### Toolkit API This release renames all APIs and parameters containing the word `transcription` in the client-side subtitle API to use `transcript`, as shown below: #### Android - `onTranscriptionUpdated` renamed to `onTranscriptUpdated` - `TranscriptionRenderMode` renamed to `TranscriptRenderMode` - `TranscriptionType` renamed to `TranscriptType` - `TranscriptionStatus` renamed to `TranscriptStatus` - `Transcription` renamed to `Transcript` #### iOS - `onTranscriptionUpdated` renamed to `onTranscriptUpdated` - `TranscriptionRenderMode` renamed to `TranscriptRenderMode` - `TranscriptionType` renamed to `TranscriptType` - `TranscriptionStatus` renamed to `TranscriptStatus` - `Transcription` renamed to `Transcript` #### Web - `TRANSCRIPTION_UPDATED` renamed to `TRANSCRIPT_UPDATED` #### v1.7 Released on July 31, 2025. #### New features - **AI avatars** Create visual avatar representations for your conversational agents using third-party avatar providers. AI avatars provide a visual presence during voice interactions, making conversations feel more natural and engaging. Enable AI avatars by setting `avatar.enable` to `true` and configuring the `avatar.vendor` and `avatar.params` fields when calling [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) to create your agent. > **Info** > > AI avatars require video streaming and incur additional charges. See [video calling pricing](/en/realtime-media/rtc/reference/pricing) for details. - **Selective attention locking (Beta)** This version introduces the selective attention locking feature, which uses voiceprint recognition technology to identify and filter out the speaker while suppressing background noise. This enhances the efficiency of conversational AI, particularly improving speech recognition accuracy. To experience this feature, contact [technical support](mailto:support@agora.io). - **Send picture messages (Beta)** The toolkit now includes an API for [sending picture messages](build/send-multimodal-messages). You can send image URLs to the main model, which automatically references the image in future interactions to generate more relevant responses. A new callback is available to receive image message receipt details after successful transmission. > **Info** > > - The picture messaging feature is currently in Beta and free for a limited time. > - Image processing depends on the capabilities of the integrated LLM. Ensure the LLM you connect to the Conversational AI Engine supports image input. #### API changes This release introduces the following modifications to the RESTful API. - [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) - **New parameters added** - `avatar.enable` - `avatar.vendor` - `avatar.params` ##### Toolkit API - Android: - `chat` - `ImageMessage` - `onMessageReceiptUpdated` - `MessageReceipt` - iOS: - `chat` - `ChatMessage` - `ChatMessageType` - `ImageMessage` - `onMessageReceiptUpdated` - `MessageReceipt` - Web: - `chat` - `TMessageReceipt` - `EChatMessagePriority` - `EChatMessageType` - `IChatMessageBase` - `IChatMessageImage` #### v1.6 Released on July 15, 2025. #### New features - **Support for OpenAI Realtime API** Integrate Multimodal Large Language Models (MLLMs) with Conversational AI Engine to enable end-to-end real-time audio and text interactions. See [OpenAI Realtime API](models/mllm/openai) for integration details. - **Support for more TTS vendors** Conversational AI Engine now supports the following additional TTS vendors: - [Cartesia](models/tts/cartesia) - [OpenAI](models/tts/openai) - **Custom ASR provider support** To improve flexibility in configuring conversational agents, this release allows you to select a custom automatic speech recognition (ASR) provider. The [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API now includes the following new parameters: - `asr.vendor`: Specify the ASR provider - `asr.params`: Configure ASR parameters The following ASR providers are supported: - **ARES** (default) - **Microsoft Azure** - **Deepgram** **Billing update:** In earlier versions, the service fee included the cost of the Ares ASR provider. Starting in v1.6, the pricing is restructured as follows: - If you use **ARES ASR**, the total price remains unchanged: ***Total cost = Conversational AI Engine Audio Basic Task + ARES ASR Task*** - If you use **a different ASR provider**, you are charged **only** the new **Conversational AI Engine Audio Basic Task** fee. For further details, see [Pricing](reference/pricing). - **Multi-platform toolkit** Agora now offers a toolkit to help you quickly build conversational agent apps. The toolkit is available for [**iOS**](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios), [**Android**](/en/api-reference/api-ref/conversational-ai/client-toolkit/android), and [**Web**](/en/api-reference/api-ref/conversational-ai/client-toolkit/web), and includes APIs for common scenarios. Call these APIs to combine the capabilities of the Agora Voice SDK and Signaling SDK to achieve the following functions: - [**Display live transcript**](build/transcripts) Display real-time text output of user-agent conversations. The transcript component is now more robust, with better error handling, session management, and extensibility. - [**Interrupt the agent**](build/shape-the-conversation/interrupt-agent) Stop the agent from speaking or thinking mid-conversation. - [**Client-side events**](build/handle-runtime-events/event-notifications) Track changes in conversation state, performance metrics, and error events. - [**Optimize audio settings**](best-practices/audio-setup) Quickly apply best-practice audio configurations to improve agent responsiveness and clarity. #### API changes ##### REST API This release introduces several important modifications to the RESTful API. - [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) - **New parameters added** - `asr.vendor` - `asr.params` - `advanced_features.enable_mllm` - `properties.mllm` - `turn_detection.type` - `turn_detection.interrupt_duration_ms` - `turn_detection.prefix_padding_ms` - `turn_detection.silence_duration_ms` - `turn_detection.threshold` - `turn_detection.create_response` - `turn_detection.interrupt_response` - `turn_detection.eagerness` - `parameters.enable_metrics` - `parameters.data_channel` - `parameters.enable_error_message` ##### Toolkit APIs - [Android SDK](/en/api-reference/api-ref/conversational-ai/client-toolkit/android) - [iOS SDK](/en/api-reference/api-ref/conversational-ai/client-toolkit/ios) - [Web SDK](/en/api-reference/api-ref/conversational-ai/client-toolkit/web) #### v1.5 Released on June 9, 2025. #### New features - **Voice interruption mode** This release adds the `turn_detection.interrupt_mode` parameter to the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API, allowing you to control how the agent handles human voice interruptions. The following modes are supported: - **`interrupt`**: (Default) The human voice immediately interrupts the agent. The agent terminates the current interaction and processes the new human voice input. - **`append`**: The human voice does not interrupt the agent. The agent processes the newly received human voice request after the current interaction ends. - **`ignore`**: The agent ignores human voice requests received during speaking or thinking. These requests are discarded and not stored in the context. - **TTS filtering** This release adds the `tts.skip_patterns` parameter to the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API. This parameter controls whether the TTS module skips bracketed content when reading LLM response text. This prevents the agent from vocalizing structural prompt information like tone indicators, action descriptions, and system prompts, creating a more natural and immersive listening experience. #### API changes This release introduces several important modifications to the RESTful API. - [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) - **New parameters added** - `turn_detection.interrupt_mode` - `parameters.silence_config` - `tts.skip_patterns` #### v1.4 Released on May 29, 2025. #### New features - **Metadata support for LLM requests** This release adds the `llm.vendor` parameter to the [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) API. When set to `"custom"`, the agent includes additional metadata when calling the LLM, such as `turn_id` and `timestamp`. - **Support for Anthropic** Conversational AI Engine now supports `anthropic` as a request style for chat completion. Refer to the `llm.style` parameter in [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join). #### Improvements This release includes the following enhancements: - **Advanced LLM configuration**: The [Update agent configuration](/en/api-reference/api-ref/conversational-ai/update) API now supports: - `llm.system_messages` for updating system prompts - `llm.params` for modifying configuration parameters used when calling the large language model #### API changes This release introduces several important modifications to the RESTful API. - [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) - **New parameters added** - `llm.vendor` - **Removed parameters:** - `agent_rtm_uid` - [Update agent configuration](/en/api-reference/api-ref/conversational-ai/update) - **New parameters added** - `llm.system_messages` - `llm.params` #### v1.3 Released on April 16, 2025. #### New features - **Agent conversation history**: This version adds two methods to retrieve an agent's history. The history includes messages exchanged between the user and the agent and timestamps of agent creation and exit. - Call the RESTful API `history` endpoint to [Retrieve agent history](/en/api-reference/api-ref/conversational-ai/history). - Subscribe to the [agent history event](reference/event-types#103-agent-history) through the [Agora message notification service](build/handle-runtime-events/webhooks). When the agent stops, Agora automatically sends the agent's history to your business server through a Webhook callback. #### Improvements - **Customize the priority of broadcast information**: This version upgrades the [Broadcast a message using TTS](/en/api-reference/api-ref/conversational-ai/speak) interface and adds two new configuration parameters related to broadcast interruption logic: - `priority`: Sets the priority of the message broadcast. Supports setting the following priorities: - `INTERRUPT` High priority - `APPEND`: Medium priority - `IGNORE`: Low priority - `interruptable`: Configure whether to allow human voice to interrupt the agent's broadcast. #### API changes - Adds the [Retrieve agent history](/en/api-reference/api-ref/conversational-ai/history) method. - Adds `priority` and `interruptable` parameters to the [Broadcast a message using TTS](/en/api-reference/api-ref/conversational-ai/speak) method. #### v1.2 Released on April 10, 2025. #### New features - **Broadcast a message using TTS**: A new message broadcast interface enables a specified agent to deliver a custom message. When interacting with an agent, calling this interface interrupts the agent's speech and thinking process, allowing the TTS module to immediately broadcast the custom message. - **Interrupt the agent**: The interrupt agent endpoint lets you stop the specified agent's speech and thinking process. #### API changes This version adds the following APIs: - [Broadcast a message using TTS](/en/api-reference/api-ref/conversational-ai/speak) - [Interrupt the agent](/en/api-reference/api-ref/conversational-ai/interrupt) #### v1.1 Released on March 27, 2025. #### New features The [Start a conversational agent](/en/api-reference/api-ref/conversational-ai/join) API adds the `enable_rtm` and `agent_rtm_uid` parameters to enable Signaling integration with the conversational AI agent. When this feature is enabled, the agent can leverage the Signaling SDK to obtain a user's custom context information such as speaking status, selected text, signature, and score, and pass this data to the agent to generate more relevant content. For details, see [Transmit custom information](build/shape-the-conversation/custom-information). #### Improvements To help you quickly integrate a custom large language model (LLM), this version adds documentation for [Custom LLMs](build/custom-model-integration/custom-llm). Refer to the sample code in the documentation to integrate your custom model into the Conversational AI Engine and enable advanced capabilities such as Retrieval-Augmented Generation (RAG), multi-modal processing, and tool invocation. #### API changes The `POST` method to [Start a conversational AI agent](/en/api-reference/api-ref/conversational-ai/join) now includes the `enable_rtm` and `agent_rtm_uid` parameters. #### v1.0 (Public Beta) This version, released on March 4, 2025, adds pricing information for the Agora Conversational AI Engine. For more information, see [Pricing](reference/pricing). #### Integration guide To achieve the best conversation experience, use Agora Conversational AI Engine with the following Agora SDKs: - Agora RTC Native SDK, v4.5.1 or later. - Agora RTC Web SDK, version 4.23.2 or later. #### New features - **Live transcripts**: Supports real-time text output of conversations between users and the AI agent for transcript display in your app's UI. Agora provides an open-source transcript processing module. Integrate the module and call its API to implement live transcript. For details, see [Display live transcripts](build/transcripts). - **Message Notification Service**: Introduces a new Conversational AI Engine message notification service. Configure it in the Agora console and subscribe to agent creation, stop, and error events. When a subscribed event occurs, Agora sends the details to your specified callback address. See [Receive event notifications](build/handle-runtime-events/webhooks). - **Keywords**: Enhances recognition accuracy of Conversational AI Engine for proprietary words by adding keywords. This feature is currently in Beta stage. For details, [contact technical support](https://agoraio.zendesk.com/hc/en-us). #### v1.0 (Private Beta) Released on February 18, 2025. The first beta release of the Conversational AI Engine brings natural, smooth, low-latency, and highly reliable real-time voice conversations with AI agents to Agora channels. It enables you to efficiently build intelligent and immersive interactive experiences. See [Product overview](/en/ai) for details. #### Core features - **Real-time voice conversation** Supports natural and smooth real-time voice conversations with AI. It delivers a low-latency, ultra-responsive interactive experience as if the user is communicating with a real person. - **Intelligent noise suppression** Intelligently identifies and suppresses background noise, ensuring clear sound transmission even in noisy environments to provide users with a high-quality audio experience. - **Background human voice suppression** Suppresses background voices and noise while accurately preserving the primary speaker's voice. This ensures a clear and focused interactive experience in multi-speaker environments. - **Intelligent interruption handling** Allows users to interrupt AI at any time to ensure quick and natural responses. This feature enables smooth transitions and avoids mechanical interactions. - **Intelligent transmission** An AI-optimized transmission algorithm ensures stable voice data delivery even in weak network conditions where packet loss reaches 80%. This guarantees conversation continuity and reliability across diverse network environments. - **Flexible arrangement** Supports multiple Large Language Model (LLM) and Text-to-Speech (TTS) providers, enabling flexible orchestration to meet diverse business needs and deliver highly customizable AI dialogue solutions. - **Multi-platform support** Compatible with iOS, Android, Web, and various embedded hardware platforms, providing a seamless and consistent cross-platform experience. #### Integration guide - For the best conversational experience, Agora recommends using Conversational AI Engine with specific Agora Video/Voice SDK versions. For details, [contact technical support](mailto:support@agora.io). - The number of Peak Concurrent Users (PCU) allowed to call the server API under a single App ID is limited to 20. If you need to increase this limit, [contact technical support](mailto:support@agora.io).