# Voice Agents SDK reference — Main > Only Main documentation is included in this export. # Go (/en/api-reference/api-ref/server-sdk/go) > Documentation: Voice Agents SDK reference. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-sdk-v1.txt). Full API reference for the Agora Conversational AI Go SDK. ## client.NewClient The entry point for the SDK. Creates a new API client with the given request options. All sub-clients share the same configuration. ```go import ( "github.com/AgoraIO/agora-agents-go/v2/client" "github.com/AgoraIO/agora-agents-go/v2/option" ) ``` ### Constructor ```go func NewClient(opts ...option.RequestOption) *Client ``` Creates a new API client. All sub-clients share the same configuration. For AgentKit integrations, use [`agentkit.NewAgoraClient`](#agentkitnewagoraclient) instead. ### Request options Request options configure transport, retries, and advanced authentication behavior. For session integrations, prefer [`agentkit.NewAgoraClient`](#agentkitnewagoraclient) with `AppID` and `AppCertificate`. AgentKit generates Conversational AI REST authentication and RTC join tokens when session methods run. #### `option.WithArea` ```go func WithArea(area core.Area) *core.AreaRequestOption ``` Enables regional routing with automatic DNS-based domain selection. ```go c := client.NewClient( option.WithArea(option.AreaUS), ) ``` #### `option.WithBaseURL` ```go func WithBaseURL(baseURL string) *core.BaseURLOption ``` Overrides the default API endpoint. Useful for testing. ```go import Agora "github.com/AgoraIO/agora-agents-go/v2" c := client.NewClient( option.WithBaseURL(Agora.Environments.Default), ) ``` #### `option.WithHTTPClient` ```go func WithHTTPClient(httpClient core.HTTPClient) *core.HTTPClientOption ``` Provides a custom `*http.Client`. Recommended for production to set timeouts. ```go c := client.NewClient( option.WithHTTPClient(&http.Client{ Timeout: 10 * time.Second, }), ) ``` #### `option.WithMaxAttempts` ```go func WithMaxAttempts(attempts uint) *core.MaxAttemptsOption ``` Sets the maximum number of retry attempts. Default: `2`. Retries use exponential backoff for status codes 408, 429, and 5xx. ```go c := client.NewClient( option.WithMaxAttempts(3), ) ``` #### `option.WithHTTPHeader` ```go func WithHTTPHeader(httpHeader http.Header) *core.HTTPHeaderOption ``` Adds custom HTTP headers to every request. #### `option.WithBodyProperties` ```go func WithBodyProperties(bodyProperties map[string]interface{}) *core.BodyPropertiesOption ``` Adds extra properties to the JSON request body. #### `option.WithQueryParameters` ```go func WithQueryParameters(queryParameters url.Values) *core.QueryParametersOption ``` Adds query parameters to the request URL. #### `option.WithPool` ```go func WithPool(pool *core.Pool) *core.AreaRequestOption ``` Uses a pre-configured `Pool` for regional routing. ### Sub-clients `client.NewClient` exposes Fern-generated sub-clients for direct REST API access. You typically do not need these when using the [agentkit layer](#agentkitnewagent). | Field | Type | Description | | ------------------- | ------------------------- | ---------------------------------------------------------------------------------------- | | `c.Agents` | `*agents.Client` | Agent lifecycle (start, list, stop, speak, interrupt, update, get, getHistory, getTurns) | | `c.AgentManagement` | `*agentmanagement.Client` | Management actions: `agent-think` | | `c.Telephony` | `*telephony.Client` | Telephony operations (call, hangup) | | `c.PhoneNumbers` | `*phonenumbers.Client` | Phone number management | All sub-client methods take `context.Context` as their first argument. See the [generated reference](https://github.com/AgoraIO/agora-agents-go/blob/HEAD/./reference.md) for full method signatures. ### Environments The root `Agora` package exposes the default API endpoint: ```go import Agora "github.com/AgoraIO/agora-agents-go/v2" Agora.Environments.Default // "https://api.agora.io/api/conversational-ai-agent" ``` ### Pointer helpers The root `Agora` package provides helper functions for creating pointers to literal values. These are required for optional fields in Fern-generated request structs, which use pointer types to distinguish between "not set" and "set to zero value". ```go import Agora "github.com/AgoraIO/agora-agents-go/v2" ``` | Function | Signature | Example | | ----------------------- | ---------------------------- | ------------------------------- | | `Agora.Bool` | `func(bool) *bool` | `Enable: Agora.Bool(true)` | | `Agora.Int` | `func(int) *int` | `IdleTimeout: Agora.Int(120)` | | `Agora.String` | `func(string) *string` | `APIKey: Agora.String("")` | | `Agora.Float64` | `func(float64) *float64` | `Threshold: Agora.Float64(0.5)` | | `Agora.Float32` | `func(float32) *float32` | — | | `Agora.Int8/16/32/64` | `func(intN) *intN` | — | | `Agora.Uint/8/16/32/64` | `func(uintN) *uintN` | — | | `Agora.UUID` | `func(uuid.UUID) *uuid.UUID` | — | | `Agora.Time` | `func(time.Time) *time.Time` | — | ## agentkit.NewAgoraClient The AgentKit client. [`NewAgent`](#agentkitnewagent) requires it, and sessions created from the agent inherit the client's App ID, App Certificate, and REST authentication mode. ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/option" ) ``` ### Constructor ```go func NewAgoraClient(opts AgoraClientOptions) *AgoraClient ``` Creates an AgentKit client with the given options. ```go c := agentkit.NewAgoraClient(agentkit.AgoraClientOptions{ Area: option.AreaUS, AppID: "your-app-id", AppCertificate: "your-app-certificate", }) ``` #### AgoraClientOptions | Field | Type | Required | Description | | ---------------- | ----------------- | ----------- | --------------------------------------------------------------------------------------- | | `Area` | `option.Area` | Yes | Geographic region for regional routing, for example `option.AreaUS`. Panics if not set | | `AppID` | `string` | Yes | Agora App ID, used as the REST API path parameter and for token generation | | `AppCertificate` | `string` | Conditional | Used to sign tokens. Required for App credentials mode. Keep this value secret | | `CustomerID` | `string` | No | Customer ID for Basic authentication. Use with `CustomerSecret` | | `CustomerSecret` | `string` | No | Customer secret for Basic authentication | | `Token` | `string` | No | Token for token authentication. Can't be combined with `CustomerID` or `CustomerSecret` | | `HTTPClient` | `core.HTTPClient` | No | Custom HTTP transport | The authentication mode is `AuthModeAppCredentials` by default, `AuthModeBasic` when `CustomerID` is set, or `AuthModeToken` when `Token` is set. ### Methods and fields Methods and fields available on any `*AgoraClient` instance. | Member | Type | Description | | -------------------------------------------------------- | ------------------------- | -------------------------------------------------------- | | `StopAgent(ctx, agentID)` | `error` | Stops an agent by ID. Treats a `404` response as success | | `AppID()` | `string` | The configured App ID | | `AppCertificate()` | `string` | The configured App Certificate | | `IsAppCredentialsMode()` | `bool` | Whether the client uses App credentials mode | | `HTTPClient()` | `core.HTTPClient` | The configured HTTP transport | | `AgentsClient()` | `*agents.Client` | The agents sub-client | | `AgentManagementClient()` | `*agentmanagement.Client` | The agent management sub-client | | `Agents`, `AgentManagement`, `Telephony`, `PhoneNumbers` | Sub-clients | Direct REST API access. See [Sub-clients](#sub-clients) | ## agentkit.NewAgent `Agent` is an immutable configuration object. Each vendor chaining method returns a new `*Agent` — the original is never modified. Define one agent at startup and create sessions from it for each user conversation. ```go import ( "github.com/AgoraIO/agora-agents-go/v2/agentkit" "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ) ``` ### Constructor ```go func NewAgent(client *AgoraClient, opts ...AgentOption) *Agent ``` Pass an [`AgoraClient`](#agentkitnewagoraclient) and `AgentOption` functions to configure the agent's instructions, greeting, and other properties. Panics with `NewAgent requires AgoraClient` if `client` is `nil`. To name an agent instance, set `Name` in [`CreateSessionOptions`](#createsessionoptions). ```go agent := agentkit.NewAgent(c, agentkit.WithInstructions("You are a helpful voice assistant."), // LLM system prompt agentkit.WithGreeting("Hello! How can I help you today?"), // first words spoken on session start agentkit.WithMaxHistory(10), ) ``` ### AgentOption functions `AgentOption` functions are passed to `NewAgent`. `AgentOption` is `func(*core.BaseAgent)`. | Function | Parameter type | Description | | -------------------------------------- | ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `WithPipelineID(pipelineID)` | `string` | Published pipeline ID | | `WithInstructions(instructions)` | `string` | LLM system prompt | | `WithGreeting(greeting)` | `string` | First message the agent speaks | | `WithFailureMessage(msg)` | `string` | Message spoken when the LLM fails | | `WithMaxHistory(n)` | `int` | Maximum conversation turns to retain | | `WithTurnDetectionConfig(td)` | `*TurnDetectionConfig` | Cascading-flow turn detection configuration. Use `Config.StartOfSpeech` and `Config.EndOfSpeech` for SOS/EOS detection. Use interruption config for interruption behavior and MLLM vendor `TurnDetection` for MLLM turn detection | | `WithInterruptionConfig(interruption)` | `*InterruptionConfig` | Unified interruption control using the top-level `interruption` object | | `WithGreetingConfigs(configs)` | `*LlmGreetingConfigs` | Sets `llm.greeting_configs`, including v2.7 `interruptable` | | `WithSalConfig(sal)` | `*SalConfig` | Speech analytics configuration | | `WithAdvancedFeatures(af)` | `*AdvancedFeatures` | Advanced feature flags, for example `EnableMllm`, `EnableAivad` | | `WithTools(enabled)` | `bool` | Enable or disable MCP tool and custom tool invocation | | `WithParameters(params)` | `*SessionParams` | Additional session parameters | | `WithAudioScenario(audioScenario)` | `ParametersAudioScenario` | Sets `parameters.audio_scenario` (`default`, `chorus`, or `aiserver`) | | `WithGeofence(gf)` | `*GeofenceConfig` | Regional access restriction | | `WithLabels(labels)` | `map[string]string` | Custom key-value labels returned in notification callbacks | | `WithRtc(rtc)` | `*RtcConfig` | RTC media encryption | | `WithFillerWords(fw)` | `*FillerWordsConfig` | Filler words played while waiting for the LLM response | | `WithGreetingAudioURL(url)` | `string` | Sets `llm.greeting_audio_url` | | `WithSessionOptOut(optOut)` | `bool` | Sets `parameters.opt_out` | ### Vendor chaining methods Vendor methods are called on the `*Agent` returned by `NewAgent`. Each method returns a **new** `*Agent` — the original is never modified. #### `WithLlm(vendor)` Sets the LLM vendor. Pass an instance of [`NewOpenAI`](#newopenai), [`NewAzureOpenAI`](#newazureopenai), [`NewAnthropic`](#newanthropic), [`NewGemini`](#newgemini), or any other [LLM vendor](#other-llm-vendors). ```go func (a *Agent) WithLlm(vendor vendors.LLM) *Agent ``` #### `WithTts(vendor)` Sets the TTS vendor. Captures the vendor's sample rate for [avatar](#avatar-vendors) validation. **Panics** if an avatar is already configured and its required sample rate differs from the TTS sample rate. ```go func (a *Agent) WithTts(vendor vendors.TTS) *Agent ``` #### `WithStt(vendor)` Sets the STT vendor. Pass an instance of any [STT vendor constructor](#stt-vendors). ```go func (a *Agent) WithStt(vendor vendors.STT) *Agent ``` #### `WithMllm(vendor)` Sets the MLLM vendor for multimodal mode. Pass [`NewOpenAIRealtime`](#newopenairealtime), [`NewAzureOpenAIRealtime`](#newazureopenairealtime), [`NewGeminiLive`](#newgeminilive), [`NewVertexAI`](#newvertexai), [`NewXaiGrok`](#newxaigrok), or [`NewOpenAIGPTLive`](#newopenaigptlive). Automatically sets `mllm.enable = true`. ```go func (a *Agent) WithMllm(vendor vendors.MLLM) *Agent ``` #### `WithAvatar(vendor)` Sets the avatar vendor. For LiveAvatar and HeyGen avatars, **panics** if TTS is already configured with a sample rate that doesn't match the avatar's required rate. For other avatars, a mismatch causes `WithTts()` to panic or `Start()` to return an error. ```go func (a *Agent) WithAvatar(vendor vendors.Avatar) *Agent ``` #### `WithTurnDetection(config)` Configures cascading-flow turn detection. Use `Config.StartOfSpeech` and `Config.EndOfSpeech` for SOS/EOS detection. Use interruption config for interruption behavior and MLLM vendor `TurnDetection` for MLLM turn detection. ```go func (a *Agent) WithTurnDetection(td *TurnDetectionConfig) *Agent ``` ### Other builder methods The following methods follow the same pattern — each returns a new `*Agent` with the updated configuration. | Method | Parameter type | Description | | ---------------------------------- | ------------------------- | ----------------------------------------------------- | | `WithInstructions(instructions)` | `string` | Override the LLM system prompt | | `WithGreeting(greeting)` | `string` | Override the greeting message | | `WithInterruption(interruption)` | `*InterruptionConfig` | Set interruption configuration | | `WithGreetingConfigs(configs)` | `*LlmGreetingConfigs` | Set greeting playback configuration | | `WithGreetingAudioURL(url)` | `string` | Set `llm.greeting_audio_url` | | `WithSessionOptOut(optOut)` | `bool` | Set `parameters.opt_out` | | `WithAudioScenario(audioScenario)` | `ParametersAudioScenario` | Set `parameters.audio_scenario` | | `WithSal(sal)` | `*SalConfig` | Set SAL configuration | | `WithAdvancedFeatures(af)` | `*AdvancedFeatures` | Set advanced features | | `WithTools(enabled)` | `bool` | Enable or disable MCP tool and custom tool invocation | | `WithParameters(params)` | `*SessionParams` | Set session parameters | | `WithFailureMessage(msg)` | `string` | Set the failure message | | `WithMaxHistory(n)` | `int` | Set the maximum conversation history length | | `WithGeofence(gf)` | `*GeofenceConfig` | Set geofence configuration | | `WithLabels(labels)` | `map[string]string` | Set custom labels | | `WithRtc(rtc)` | `*RtcConfig` | Set RTC configuration | | `WithFillerWords(fw)` | `*FillerWordsConfig` | Set filler words configuration | ### `ToProperties()` Converts the agent configuration to a `*Agora.StartAgentsRequestProperties` for direct use with the low-level client. Called internally by `AgentSession.Start()`. Use this directly when building custom request bodies. ```go func (a *Agent) ToProperties(opts ToPropertiesOptions) (*Agora.StartAgentsRequestProperties, error) ``` **Returns an error if:** - Neither `Token` nor `AppID` + `AppCertificate` is provided - `AgentUID` isn't numeric when a token must be generated - `RemoteUIDs` is empty - `ExpiresIn` is invalid - MLLM is combined with an enabled avatar - In cascading mode: LLM or TTS isn't configured - Config marshaling fails #### ToPropertiesOptions ```go type ToPropertiesOptions struct { Channel string AgentUID string RemoteUIDs []string Token string AppID string AppCertificate string ExpiresIn int IdleTimeout *int EnableStringUID *bool SkipVendorValidation bool SkipVendorValidationCategories []string AllowMissingVendorCategories []string Warn func(string) } ``` | Field | Type | Required | Description | | -------------------------------- | -------------- | ----------- | ------------------------------------------------------------------------------------ | | `Channel` | `string` | Yes | Agora channel name | | `AgentUID` | `string` | Yes | Agent's UID in the channel | | `RemoteUIDs` | `[]string` | Yes | Remote participant UIDs | | `Token` | `string` | Conditional | Pre-generated RTC+RTM token. Skips generation if set | | `AppID` | `string` | Conditional | Agora App ID. Required if `Token` is not set | | `AppCertificate` | `string` | Conditional | Agora App Certificate. Required if `Token` is not set | | `ExpiresIn` | `int` | No | Token lifetime in seconds. Default: `86400`. Valid range: 1–86400 | | `IdleTimeout` | `*int` | No | Session idle timeout in seconds | | `EnableStringUID` | `*bool` | No | Enable string UID mode | | `SkipVendorValidation` | `bool` | No | Advanced option for pipeline-backed starts without explicit LLM/TTS | | `SkipVendorValidationCategories` | `[]string` | No | Skip request-shape validation for the listed vendor categories (`asr`, `llm`, `tts`) | | `AllowMissingVendorCategories` | `[]string` | No | Allow the listed vendor categories to be omitted from properties | | `Warn` | `func(string)` | No | Warning sink for recoverable config issues | ### Getters Read-only methods available on any `*Agent` instance. | Method | Return type | Description | | ---------------------------- | ------------------------ | ----------------------------------- | | `PipelineID()` | `string` | Published pipeline ID | | `Instructions()` | `string` | LLM system prompt | | `Greeting()` | `string` | Greeting message | | `FailureMessage()` | `string` | Message spoken when LLM fails | | `MaxHistory()` | `*int` | Maximum conversation history length | | `LlmConfig()` | `map[string]interface{}` | LLM configuration | | `TtsConfig()` | `map[string]interface{}` | TTS configuration | | `SttConfig()` | `map[string]interface{}` | STT configuration | | `MllmConfig()` | `map[string]interface{}` | MLLM configuration | | `TtsSampleRate()` | `*vendors.SampleRate` | TTS sample rate | | `AvatarRequiredSampleRate()` | `*vendors.SampleRate` | Avatar required sample rate | | `Avatar()` | `map[string]interface{}` | Avatar configuration | | `TurnDetection()` | `*TurnDetectionConfig` | Turn detection configuration | | `Interruption()` | `*InterruptionConfig` | Interruption configuration | | `GreetingConfigs()` | `*LlmGreetingConfigs` | Greeting playback configuration | | `Sal()` | `*SalConfig` | SAL configuration | | `AdvancedFeatures()` | `*AdvancedFeatures` | Advanced features | | `Parameters()` | `*SessionParams` | Session parameters | | `Geofence()` | `*GeofenceConfig` | Geofence configuration | | `Labels()` | `map[string]string` | Custom labels | | `Rtc()` | `*RtcConfig` | RTC configuration | | `FillerWords()` | `*FillerWordsConfig` | Filler words configuration | ### `agent.CreateSession` Creates an [`AgentSession`](#agentkitnewagentsession) from the agent configuration. This is the recommended way to create a session. The session's REST client, App ID, App Certificate, and REST authentication mode come from the agent's [`AgoraClient`](#agentkitnewagoraclient). Call `Start()` on the returned session to join the agent to the channel. ```go func (a *Agent) CreateSession(opts CreateSessionOptions) *AgentSession ``` ```go session := agent.CreateSession(agentkit.CreateSessionOptions{ Name: "support-assistant", Channel: "support-room-123", AgentUID: "1", RemoteUIDs: []string{"100"}, }) ``` #### CreateSessionOptions | Field | Type | Required | Description | | ----------------- | -------------- | ----------- | ------------------------------------------------------------------------------------------------ | | `Name` | `string` | No | Agent instance identifier, sent as the top-level `/join` field `name`. Auto-generated when empty | | `Channel` | `string` | Yes | Agora channel name | | `Token` | `string` | Conditional | Pre-generated RTC+RTM token. Skips auto-generation if set | | `AgentUID` | `string` | Yes | Agent's UID in the channel | | `RemoteUIDs` | `[]string` | Yes | Remote participant UIDs | | `IdleTimeout` | `*int` | No | Idle timeout in seconds | | `EnableStringUID` | `*bool` | No | Enable string UID mode | | `ExpiresIn` | `int` | No | Auto-generated token lifetime in seconds | | `Preset` | `[]string` | No | Advanced preset value for project-specific routing. Don't set for standard AgentKit usage | | `PipelineID` | `string` | No | Published pipeline ID to send on session start | | `Debug` | `bool` | No | Enable debug logging of the start request | | `Warn` | `func(string)` | No | Custom warning sink; defaults to logger | ## agentkit.NewAgentSession `AgentSession` manages the full lifecycle of a running agent. In most cases, use [`agent.CreateSession`](#agentcreatesession). Use `NewAgentSession` only when you need to supply the session's clients and agent yourself, then call `Start()` to join the agent to the channel. ```go import "github.com/AgoraIO/agora-agents-go/v2/agentkit" ``` ### Constructor ```go func NewAgentSession(opts AgentSessionOptions) *AgentSession ``` If `Name` is empty, defaults to `agent-`. The session starts in `AgentSessionLifecycleIdle`. #### AgentSessionOptions ```go type AgentSessionOptions struct { Client *agents.Client HTTPClient core.HTTPClient AgentManagementClient *agentmanagement.Client Agent agentcore.AgentRuntime AppID string AppCertificate string Name string Channel string Token string AgentUID string RemoteUIDs []string IdleTimeout *int EnableStringUID *bool ExpiresIn int UseAppCredentialsForREST bool Preset []string PipelineID string Debug bool Warn func(string) } ``` | Field | Type | Required | Description | | -------------------------- | ------------------------- | ----------- | ---------------------------------------------------------------------------------------- | | `Client` | `*agents.Client` | Yes | Fern-generated agents sub-client (from `c.Agents`) | | `HTTPClient` | `core.HTTPClient` | No | Custom HTTP transport | | `AgentManagementClient` | `*agentmanagement.Client` | Conditional | Agent management sub-client (from `c.AgentManagement`). Required for `Think()` | | `Agent` | `agentcore.AgentRuntime` | Yes | Agent configuration. A `*Agent` built with `NewAgent` satisfies this interface | | `AppID` | `string` | Yes | Agora App ID | | `AppCertificate` | `string` | Conditional | Required if `Token` is not set or `UseAppCredentialsForREST` is `true` | | `Name` | `string` | No | Agent instance identifier. Default: `agent-` | | `Channel` | `string` | Yes | Agora channel name | | `Token` | `string` | Conditional | Pre-generated RTC+RTM token. Skips auto-generation if set | | `AgentUID` | `string` | Yes | Agent's UID in the channel | | `RemoteUIDs` | `[]string` | Yes | Remote participant UIDs | | `IdleTimeout` | `*int` | No | Idle timeout in seconds | | `EnableStringUID` | `*bool` | No | Enable string UID mode | | `ExpiresIn` | `int` | No | Auto-generated token lifetime in seconds | | `UseAppCredentialsForREST` | `bool` | No | Generate ConvoAI REST auth headers per request | | `Preset` | `[]string` | No | Advanced preset value for project-specific routing. Do not set for normal builder usage. | | `PipelineID` | `string` | No | Published pipeline ID to send on session start | | `Debug` | `bool` | No | Enable debug logging of the start request | | `Warn` | `func(string)` | No | Custom warning sink; defaults to logger | `PipelineID` is sent as the top-level `/join` field `pipeline_id`, not inside `properties`. If not set, `AgentSession.Start()` uses the agent-level value from `WithPipelineID`. ### State machine A session progresses through the following states: ```text Start() API success ┌──────┐ ┌──────────┐ ┌─────────┐ │ idle │─────>│ starting │─────>│ running │ └──┬───┘ └────┬─────┘ └────┬────┘ │ │ │ │ │ error │ Stop() │ ▼ ▼ │ ┌─────────┐ ┌──────────┐ │ │ error │ │ stopping │ │ └────┬────┘ └────┬─────┘ │ │ │ │ │ │ success │ ▼ ▼ │ ┌──────────┐ ┌─────────┐ └─────────>│ (restart)│ │ stopped │ └──────────┘ └─────────┘ ``` | Transition | Trigger | | -------------------- | ---------------------------------------------------- | | `idle → starting` | `Start()` called | | `starting → running` | API responds with agent ID | | `starting → error` | API request fails | | `running → stopping` | `Stop()` called | | `stopping → stopped` | API confirms agent stopped | | `stopping → error` | Stop request fails and agent was not already stopped | `Start()` can also be called from `stopped` or `error` state to restart the session. If you call `Start()` from an invalid state, or if it fails avatar validation, it returns an error without changing the status or emitting the `error` event. If `Say()`, `Interrupt()`, `Update()`, or `Think()` fails, it returns an error but doesn't change the session status. ### Methods All methods take `context.Context` as the first argument. Register event handlers **before** calling `Start()` to avoid missing the `started` event. #### `Start(ctx)` Starts the agent session. Validates avatar/TTS configuration, generates a token if not provided, and calls the Agora API. Returns the agent ID. ```go func (s *AgentSession) Start(ctx context.Context) (string, error) ``` - Valid from: `idle`, `stopped`, `error` - Transitions to: `starting` → `running` on success, `error` on failure - Emits: `"started"` on success, `"error"` on failure - Validates avatar config and avatar/TTS sample rate match before making the API call ```go agentID, err := session.Start(ctx) if err != nil { log.Fatalf("Failed to start session: %v", err) } ``` #### `Stop(ctx)` Stops the running agent and removes it from the channel. ```go func (s *AgentSession) Stop(ctx context.Context) error ``` - Valid from: `running` - Transitions to: `stopping` → `stopped` on success, `error` on failure - Emits: `"stopped"` on success, `"error"` on failure ```go err := session.Stop(ctx) if err != nil { log.Fatalf("Failed to stop session: %v", err) } ``` #### `Say(ctx, text, priority, interruptable)` Instructs the agent to speak the given text. ```go func (s *AgentSession) Say(ctx context.Context, text string, priority *Agora.SpeakAgentsRequestPriority, interruptable *bool) error ``` - Valid from: `running` - Pass `nil` for `priority` or `interruptable` to use defaults | Parameter | Type | Description | | --------------- | ----------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `text` | `string` | The text for the agent to speak | | `priority` | `*Agora.SpeakAgentsRequestPriority` | Optional priority level. Pass `nil` for default. Use `agentkit.SpeakPriorityInterrupt.Ptr()`, `agentkit.SpeakPriorityAppend.Ptr()`, or `agentkit.SpeakPriorityIgnore.Ptr()` convenience constants instead of the raw generated enum | | `interruptable` | `*bool` | Whether this message can be interrupted. Pass `nil` for default | ```go err := session.Say(ctx, "One moment while I look that up.", nil, nil) ``` #### `Interrupt(ctx)` Interrupts the agent's current speech. ```go func (s *AgentSession) Interrupt(ctx context.Context) error ``` - Valid from: `running` #### `Update(ctx, properties)` Updates the agent's properties mid-session without restarting. Accepts a typed properties struct in REST API format. ```go func (s *AgentSession) Update(ctx context.Context, properties *Agora.UpdateAgentsRequestProperties) error ``` - Valid from: `running` #### `GetHistory(ctx)` Retrieves the conversation history. Requires a valid agent ID — `Start()` must have been called successfully. ```go func (s *AgentSession) GetHistory(ctx context.Context) (*Agora.GetHistoryAgentsResponse, error) ``` #### `GetTurns(ctx)` / `GetAllTurns(ctx)` Retrieves turn-by-turn analytics for the session. Requires a valid agent ID — `Start()` must have been called successfully. ```go func (s *AgentSession) GetTurns(ctx context.Context, opts ...GetTurnsOptions) (*Agora.GetTurnsAgentsResponse, error) func (s *AgentSession) GetAllTurns(ctx context.Context, opts ...GetAllTurnsOptions) (*Agora.GetTurnsAgentsResponse, error) type GetTurnsOptions struct { PageIndex *int PageSize *int } type GetAllTurnsOptions struct { PageSize *int } ``` `PageIndex` starts at 1. Use `GetAllTurns` to iterate through every page with a default page size of 50 and return the final response with aggregated `Turns`. - **Requires:** Valid agent ID When you consume server notifications, event `112` means all turns for the session have finished and are ready to query. #### `GetInfo(ctx)` Gets the current agent status from the API. Requires a valid agent ID. ```go func (s *AgentSession) GetInfo(ctx context.Context) (*Agora.GetAgentsResponse, error) ``` #### `Think(ctx)` Injects a thought or instruction into a running agent. In v2.7, omitting `on_listening_action` uses the server default `interrupt`. Set `agentkit.ThinkOnListeningActionInject.Ptr()` if you need legacy inject behavior. AgentKit also exposes `ThinkOnListeningActionInterrupt`, `ThinkOnListeningActionIgnore`, `ThinkOnThinkingActionInterrupt`, `ThinkOnThinkingActionIgnore`, `ThinkOnSpeakingActionInterrupt`, and `ThinkOnSpeakingActionIgnore` convenience constants. All three state actions also accept `append`. Pass `Agora.AgentThinkAgentManagementRequestOnListeningActionAppend.Ptr()`, `Agora.AgentThinkAgentManagementRequestOnThinkingActionAppend.Ptr()`, or `Agora.AgentThinkAgentManagementRequestOnSpeakingActionAppend.Ptr()`. With `append`, the instruction doesn't interrupt the current interaction. The agent waits for the current user turn, LLM inference, or TTS playback to finish, then appends the instruction to the context as a separate user message and starts a new turn. ```go func (s *AgentSession) Think(ctx context.Context, text string, onListeningAction *Agora.AgentThinkAgentManagementRequestOnListeningAction, onThinkingAction *Agora.AgentThinkAgentManagementRequestOnThinkingAction, onSpeakingAction *Agora.AgentThinkAgentManagementRequestOnSpeakingAction, interruptable *bool, metadata map[string]string) (*Agora.AgentThinkAgentManagementResponse, error) func (s *AgentSession) ThinkWithOptions(ctx context.Context, text string, opts *ThinkOptions) (*Agora.AgentThinkAgentManagementResponse, error) ``` - **Valid from:** `running` #### `On(event, handler)` Registers an event handler. Multiple handlers can be registered for the same event. Handlers run synchronously; panics in handlers are recovered and reported through the session warning sink. ```go func (s *AgentSession) On(event string, handler EventHandler) ``` ```go session.On("started", func(data interface{}) { info := data.(map[string]string) fmt.Println("Agent is live:", info["agent_id"]) }) session.On("stopped", func(data interface{}) { fmt.Println("Agent has left") }) session.On("error", func(data interface{}) { log.Println("Session error:", data) }) ``` #### `Off(event, handler)` Unregisters a previously registered event handler. ```go func (s *AgentSession) Off(event string, handler EventHandler) ``` ### Events | Event | Data type | Description | | ----------- | -------------------------------------- | ------------------------------------- | | `"started"` | `map[string]string{"agent_id": "..."}` | Agent successfully joined the channel | | `"stopped"` | `map[string]string{"agent_id": "..."}` | Agent left the channel | | `"error"` | `error` | An unrecoverable error occurred | ### Getters Read-only methods available on any `*AgentSession` instance. | Method | Return type | Description | | ---------------------- | ------------------------- | ------------------------------------------------------------------------- | | `ID()` | `string` | Agent ID. Empty string before `Start()` succeeds | | `Status()` | `AgentSessionLifecycle` | Current session state | | `Agent()` | `AgentRuntime` | The agent configuration | | `AppID()` | `string` | The Agora App ID | | `Raw()` | `*agents.Client` | Direct access to the Fern-generated agents client for advanced operations | | `RawAgentManagement()` | `*agentmanagement.Client` | Direct access to the Fern-generated agent management client | #### Using `session.Raw()` Use `session.Raw()` to call REST API endpoints not yet exposed by the agentkit layer. ```go response, err := session.Raw().List(ctx, &Agora.ListAgentsRequest{ Appid: session.AppID(), }) ``` ### Thread safety All state access is protected by `sync.RWMutex`. The session is safe for concurrent use across go routines. ## Vendors All vendor constructors are in the `agentkit/vendors` package. **Constructors panic if required fields are empty** — this is Go-idiomatic behavior for programmer configuration errors. ```go import "github.com/AgoraIO/agora-agents-go/v2/agentkit/vendors" ``` ### Interfaces ```go type LLM interface { ToConfig() map[string]interface{} } type TTS interface { ToConfig() map[string]interface{} GetSampleRate() *SampleRate } type STT interface { ToConfig() map[string]interface{} } type MLLM interface { ToConfig() map[string]interface{} } type Avatar interface { ToConfig() map[string]interface{} RequiredSampleRate() SampleRate } ``` ### LLM vendors Use with [`WithLlm()`](#withllmvendor). #### `NewOpenAI` ```go func NewOpenAI(opts OpenAIOptions) *OpenAI ``` Panics if `Model` is empty. Panics if `APIKey` is empty unless `Model` is one of the supported Agora-managed OpenAI models (`gpt-4o-mini`, `gpt-4.1-mini`, `gpt-5-nano`, `gpt-5-mini`) and `BaseURL` / `Vendor` are not set. | Field | Type | Required | Default | Description | | ------------------- | -------------------------- | --------- | ---------- | ----------------------------------------------------------------------------------------------------- | | `APIKey` | `string` | BYOK only | — | OpenAI API key. Optional for supported Agora-managed OpenAI models. | | `Model` | `string` | Yes | — | Model identifier | | `BaseURL` | `string` | BYOK only | — | API endpoint. Required when `APIKey` is set. | | `Temperature` | `*float64` | No | — | Sampling temperature | | `TopP` | `*float64` | No | — | Nucleus sampling | | `MaxTokens` | `*int` | No | — | Maximum tokens in response | | `SystemMessages` | `[]map[string]interface{}` | No | — | System messages | | `GreetingMessage` | `string` | No | — | Agent greeting message | | `FailureMessage` | `string` | No | — | Message spoken when LLM fails | | `InputModalities` | `[]string` | No | `["text"]` | Input modalities | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Params` | `map[string]interface{}` | No | — | Additional model parameters | | `Headers` | `map[string]string` | No | — | Custom HTTP headers forwarded to the LLM provider | | `GreetingConfigs` | `map[string]interface{}` | No | — | Greeting playback configuration | | `TemplateVariables` | `map[string]string` | No | — | Template variables for messages. Custom tools can reference them with `{{template_variables.}}` | | `MaxHistory` | `*int` | No | — | Maximum number of conversation history messages to cache | | `Vendor` | `string` | No | — | Vendor override | | `McpServers` | `[]map[string]interface{}` | No | — | MCP server connections | | `Tools` | `[]*Agora.LlmTool` | No | — | Synchronous custom tool definitions the LLM can call. Requires `WithTools(true)` | #### `NewAzureOpenAI` ```go func NewAzureOpenAI(opts AzureOpenAIOptions) *AzureOpenAI ``` Panics if `APIKey`, `Model`, `Endpoint`, or `DeploymentName` is empty. | Field | Type | Required | Default | Description | | ------------------- | -------------------------- | -------- | ---------------------- | -------------------------------------------------------------------------------------------------------------- | | `APIKey` | `string` | Yes | — | Azure OpenAI API key | | `Endpoint` | `string` | Yes | — | Azure endpoint URL | | `DeploymentName` | `string` | Yes | — | Azure deployment name | | `Model` | `string` | Yes | — | Deployment's base model name (e.g., `"gpt-4o"`). Emitted as `params.model` for parity with the TypeScript SDK. | | `APIVersion` | `string` | No | `"2024-08-01-preview"` | API version | | `Temperature` | `*float64` | No | — | Sampling temperature | | `TopP` | `*float64` | No | — | Nucleus sampling | | `MaxTokens` | `*int` | No | — | Maximum tokens | | `SystemMessages` | `[]map[string]interface{}` | No | — | System messages | | `GreetingMessage` | `string` | No | — | Agent greeting message | | `FailureMessage` | `string` | No | — | Message spoken when LLM fails | | `InputModalities` | `[]string` | No | `["text"]` | Input modalities | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Params` | `map[string]interface{}` | No | — | Additional model parameters | | `Headers` | `map[string]string` | No | — | Custom HTTP headers forwarded to the LLM provider | | `GreetingConfigs` | `map[string]interface{}` | No | — | Greeting playback configuration | | `TemplateVariables` | `map[string]string` | No | — | Template variables for messages. Custom tools can reference them with `{{template_variables.}}` | | `MaxHistory` | `*int` | No | — | Maximum number of conversation history messages to cache | | `Vendor` | `string` | No | — | Vendor override | | `McpServers` | `[]map[string]interface{}` | No | — | MCP server connections | | `Tools` | `[]*Agora.LlmTool` | No | — | Synchronous custom tool definitions the LLM can call. Requires `WithTools(true)` | #### `NewAnthropic` ```go func NewAnthropic(opts AnthropicOptions) *Anthropic ``` Panics if `APIKey`, `Model`, `URL`, `Headers`, or `MaxTokens` is empty. | Field | Type | Required | Default | Description | | ------------------- | -------------------------- | -------- | ---------- | ----------------------------------------------------------------------------------------------------- | | `APIKey` | `string` | Yes | — | Anthropic API key | | `Model` | `string` | Yes | — | Model identifier | | `URL` | `string` | Yes | — | Anthropic messages endpoint URL | | `Headers` | `map[string]string` | Yes | — | Request headers, including Anthropic API version | | `MaxTokens` | `*int` | Yes | — | Max tokens | | `Temperature` | `*float64` | No | — | Sampling temperature | | `TopP` | `*float64` | No | — | Nucleus sampling | | `SystemMessages` | `[]map[string]interface{}` | No | — | System messages | | `GreetingMessage` | `string` | No | — | Agent greeting message | | `FailureMessage` | `string` | No | — | Message spoken when LLM fails | | `InputModalities` | `[]string` | No | `["text"]` | Input modalities | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Params` | `map[string]interface{}` | No | — | Additional model parameters | | `GreetingConfigs` | `map[string]interface{}` | No | — | Greeting playback configuration | | `TemplateVariables` | `map[string]string` | No | — | Template variables for messages. Custom tools can reference them with `{{template_variables.}}` | | `MaxHistory` | `*int` | No | — | Maximum number of conversation history messages to cache | | `Vendor` | `string` | No | — | Vendor override | | `McpServers` | `[]map[string]interface{}` | No | — | MCP server connections | | `Tools` | `[]*Agora.LlmTool` | No | — | Synchronous custom tool definitions the LLM can call. Requires `WithTools(true)` | #### `NewGemini` ```go func NewGemini(opts GeminiOptions) *Gemini ``` Panics if `APIKey` or `Model` is empty. | Field | Type | Required | Default | Description | | ------------------- | -------------------------- | -------- | ---------- | ----------------------------------------------------------------------------------------------------- | | `APIKey` | `string` | Yes | — | Google AI API key | | `Model` | `string` | Yes | — | Model identifier | | `URL` | `string` | No | — | Custom API endpoint URL | | `Temperature` | `*float64` | No | — | Sampling temperature | | `TopP` | `*float64` | No | — | Nucleus sampling | | `TopK` | `*int` | No | — | Top-K sampling | | `MaxOutputTokens` | `*int` | No | — | Maximum output tokens | | `SystemMessages` | `[]map[string]interface{}` | No | — | System messages | | `GreetingMessage` | `string` | No | — | Agent greeting message | | `FailureMessage` | `string` | No | — | Message spoken when LLM fails | | `InputModalities` | `[]string` | No | `["text"]` | Input modalities | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Params` | `map[string]interface{}` | No | — | Additional model parameters | | `Headers` | `map[string]string` | No | — | Custom HTTP headers forwarded to the LLM provider | | `GreetingConfigs` | `map[string]interface{}` | No | — | Greeting playback configuration | | `TemplateVariables` | `map[string]string` | No | — | Template variables for messages. Custom tools can reference them with `{{template_variables.}}` | | `MaxHistory` | `*int` | No | — | Maximum number of conversation history messages to cache | | `Vendor` | `string` | No | — | Vendor override | | `McpServers` | `[]map[string]interface{}` | No | — | MCP server connections | | `Tools` | `[]*Agora.LlmTool` | No | — | Synchronous custom tool definitions the LLM can call. Requires `WithTools(true)` | ### Other LLM vendors The SDK also includes named helpers for the remaining Agora-supported LLM providers. These helpers choose the correct request format internally. | Constructor | Options Struct | Required Fields | | ------------------ | ---------------------- | ------------------------------------------- | | `NewGroq` | `GroqOptions` | `APIKey`, `Model`, `BaseURL` | | `NewVertexAILLM` | `VertexAILLMOptions` | `APIKey`, `Model`, `ProjectID`, `Location` | | `NewAmazonBedrock` | `AmazonBedrockOptions` | `AccessKey`, `SecretKey`, `Region`, `Model` | | `NewDify` | `DifyOptions` | `APIKey`, `URL`, `Model` | | `NewCustomLLM` | `CustomLLMOptions` | `APIKey`, `BaseURL`, `Model` | | `NewXaiLLM` | `XaiLLMOptions` | `APIKey`, `Model`, `BaseURL` | The `Tools` field in LLM vendor options declares custom tools the LLM can choose to call. Each tool includes a model-visible function definition and the server configuration for a synchronous `GET` or `POST` request. `WithTools(true)` applies to both `Tools` and `McpServers`. For more information, see [Call custom tools](/en/ai/build/tools/custom-tools). ### TTS vendors Use with [`WithTts()`](#withttsvendor). The `SampleRate` field determines avatar compatibility — see [`WithAvatar()`](#withavatarvendor). Use [`SampleRate` constants](#samplerate) for the `SampleRate` field. #### `NewElevenLabsTTS` ```go func NewElevenLabsTTS(opts ElevenLabsTTSOptions) *ElevenLabsTTS ``` Panics if `Key`, `ModelID`, `VoiceID`, or `BaseURL` is empty. | Field | Type | Required | Description | | -------------------------- | ------------- | -------- | --------------------------------------------------- | | `Key` | `string` | Yes | ElevenLabs API key | | `ModelID` | `string` | Yes | Model identifier, for example `"eleven_flash_v2_5"` | | `VoiceID` | `string` | Yes | Voice identifier | | `BaseURL` | `string` | Yes | WebSocket base URL | | `SampleRate` | `*SampleRate` | No | Output sample rate | | `OptimizeStreamingLatency` | `*int` | No | Latency optimization level (0–4) | | `Stability` | `*float64` | No | Voice stability (0.0–1.0) | | `SimilarityBoost` | `*float64` | No | Voice similarity boost (0.0–1.0) | | `Style` | `*float64` | No | Voice style exaggeration (0.0–1.0) | | `UseSpeakerBoost` | `*bool` | No | Enable speaker boost | | `SkipPatterns` | `[]int` | No | Patterns to skip in TTS output | #### `NewMicrosoftTTS` ```go func NewMicrosoftTTS(opts MicrosoftTTSOptions) *MicrosoftTTS ``` Panics if `Key`, `Region`, or `VoiceName` is empty. | Field | Type | Required | Description | | -------------- | ------------- | -------- | --------------------------------------------- | | `Key` | `string` | Yes | Azure Speech Services key | | `Region` | `string` | Yes | Azure region, for example `"eastus"` | | `VoiceName` | `string` | Yes | Voice name, for example `"en-US-JennyNeural"` | | `SampleRate` | `*SampleRate` | No | Output sample rate | | `Speed` | `*float64` | No | Speaking rate multiplier | | `Volume` | `*float64` | No | Audio volume | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewOpenAITTS` Fixed sample rate: `SampleRate24kHz`. ```go func NewOpenAITTS(opts OpenAITTSOptions) *OpenAITTS ``` Panics if `Voice` is empty. `APIKey`, `Model`, and `BaseURL` are required together for BYOK. `APIKey` is optional for the Agora-managed `tts-1` path. Always returns `SampleRate24kHz` from `GetSampleRate()`. | Field | Type | Required | Description | | -------------- | ---------- | --------- | ------------------------------------------------------------------------------ | | `APIKey` | `string` | BYOK only | OpenAI API key. Optional for the Agora-managed `tts-1` path. | | `Voice` | `string` | Yes | Voice name: `"alloy"`, `"echo"`, `"fable"`, `"onyx"`, `"nova"`, or `"shimmer"` | | `Model` | `string` | BYOK only | Model identifier | | `BaseURL` | `string` | BYOK only | OpenAI TTS endpoint URL | | `Instructions` | `string` | No | Custom instructions for voice style, accent, pace, and tone | | `Speed` | `*float64` | No | Speech speed multiplier | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewCartesiaTTS` ```go func NewCartesiaTTS(opts CartesiaTTSOptions) *CartesiaTTS ``` Panics if `APIKey`, `VoiceID`, or `ModelID` is empty. | Field | Type | Required | Description | | -------------- | ------------- | -------- | ----------------------------------------------------------- | | `APIKey` | `string` | Yes | Cartesia API key | | `VoiceID` | `string` | Yes | Voice identifier (serialized as `{"mode":"id","id":"..."}`) | | `ModelID` | `string` | Yes | Model identifier | | `BaseURL` | `string` | No | WebSocket URL for the Cartesia streaming API | | `Language` | `string` | No | Target language for speech synthesis | | `SampleRate` | `*SampleRate` | No | Output sample rate | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewGoogleTTS` ```go func NewGoogleTTS(opts GoogleTTSOptions) *GoogleTTS ``` Panics if `Key` or `VoiceName` is empty. | Field | Type | Required | Description | | -------------- | ------------- | -------- | -------------------- | | `Key` | `string` | Yes | Google Cloud API key | | `VoiceName` | `string` | Yes | Voice name | | `LanguageCode` | `string` | No | Language code | | `SampleRate` | `*SampleRate` | No | Output sample rate | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewAmazonTTS` ```go func NewAmazonTTS(opts AmazonTTSOptions) *AmazonTTS ``` Panics if `AccessKey`, `SecretKey`, `Region`, `VoiceID`, or `Engine` is empty. | Field | Type | Required | Description | | -------------- | -------- | -------- | --------------------- | | `AccessKey` | `string` | Yes | AWS access key | | `SecretKey` | `string` | Yes | AWS secret key | | `Region` | `string` | Yes | AWS region | | `VoiceID` | `string` | Yes | Amazon Polly voice ID | | `Engine` | `string` | Yes | Polly engine type | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewDeepgramTTS` ```go func NewDeepgramTTS(opts DeepgramTTSOptions) *DeepgramTTS ``` Panics if `APIKey` or `Model` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ----------------------------------------------------------------------------- | | `APIKey` | `string` | Yes | Deepgram API key | | `Model` | `string` | Yes | Deepgram TTS model, for example `"aura-2-thalia-en"` | | `BaseURL` | `string` | No | WebSocket endpoint. Defaults server-side to `wss://api.deepgram.com/v1/speak` | | `SampleRate` | `*SampleRate` | No | Output sample rate | | `AdditionalParams` | `map[string]interface{}` | No | Additional Deepgram TTS parameters, flattened into `params` | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewHumeAITTS` ```go func NewHumeAITTS(opts HumeAITTSOptions) *HumeAITTS ``` Panics if `Key`, `VoiceID`, or `Provider` is empty. | Field | Type | Required | Description | | ----------------- | ---------- | -------- | -------------------------------------------------------- | | `Key` | `string` | Yes | Hume AI API key | | `VoiceID` | `string` | Yes | Hume AI voice ID | | `Provider` | `string` | Yes | Voice provider type, such as `CUSTOM_VOICE` or `HUME_AI` | | `ConfigID` | `string` | No | Configuration ID | | `BaseURL` | `string` | No | Base URL | | `Speed` | `*float64` | No | Playback speed | | `TrailingSilence` | `*float64` | No | Trailing silence in seconds | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewRimeTTS` ```go func NewRimeTTS(opts RimeTTSOptions) *RimeTTS ``` In BYOK mode (default), panics if `Key`, `Speaker`, or `ModelID` is empty. In managed mode, panics if `BaseURL` or `ModelID` is empty. | Field | Type | Required | Description | | ---------------- | ---------------- | ------------ | ----------------------------------------- | | `CredentialMode` | `CredentialMode` | No | `"managed"` or `"byok"`. Defaults to BYOK | | `Key` | `string` | BYOK only | Rime API key | | `Speaker` | `string` | BYOK only | Speaker identifier | | `ModelID` | `string` | Yes | Model identifier | | `BaseURL` | `string` | Managed only | WebSocket URL | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewFishAudioTTS` ```go func NewFishAudioTTS(opts FishAudioTTSOptions) *FishAudioTTS ``` Panics if `Key`, `ReferenceID`, or `Backend` is empty. | Field | Type | Required | Description | | -------------- | -------- | -------- | --------------------- | | `Key` | `string` | Yes | Fish Audio API key | | `ReferenceID` | `string` | Yes | Reference audio ID | | `Backend` | `string` | Yes | Backend model version | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewMiniMaxTTS` ```go func NewMiniMaxTTS(opts MiniMaxTTSOptions) *MiniMaxTTS ``` Panics if `Model` is empty. `Key` is optional for supported preset-backed MiniMax models (`speech-2.6-turbo`, `speech_2_6_turbo`, `speech-2.8-turbo`, `speech_2_8_turbo`). In BYOK mode (`Key` set), `GroupID` and `URL` are also required. In preset-backed mode, don't set `GroupID`, `VoiceID`, or `URL`. | Field | Type | Required | Description | | ------------------ | ------------------------ | --------- | -------------------------------------------------------------------- | | `Key` | `string` | No | MiniMax API key. Optional for supported preset-backed MiniMax models | | `GroupID` | `string` | BYOK only | MiniMax group ID | | `Model` | `string` | Yes | Model name, for example `"speech-02-turbo"` | | `VoiceID` | `string` | No | Voice style identifier. BYOK only | | `URL` | `string` | BYOK only | WebSocket endpoint | | `AdditionalParams` | `map[string]interface{}` | No | Additional MiniMax parameters, flattened into `params` | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewMurfTTS` ```go func NewMurfTTS(opts MurfTTSOptions) *MurfTTS ``` Panics if `Key` is empty. | Field | Type | Required | Description | | -------------- | ---------- | -------- | ----------------------------------------------- | | `Key` | `string` | Yes | Murf API key | | `VoiceID` | `string` | No | Voice ID, for example `"Ariana"` or `"Natalie"` | | `BaseURL` | `string` | No | WebSocket endpoint | | `Locale` | `string` | No | Voice locale | | `Rate` | `*float64` | No | Speech rate | | `Pitch` | `*float64` | No | Pitch adjustment | | `Model` | `string` | No | TTS model | | `SampleRate` | `*int` | No | Audio sample rate | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewSarvamTTS` ```go func NewSarvamTTS(opts SarvamTTSOptions) *SarvamTTS ``` Panics if `Key`, `Speaker`, or `TargetLanguageCode` is empty. | Field | Type | Required | Description | | -------------------- | ---------- | -------- | -------------------- | | `Key` | `string` | Yes | Sarvam API key | | `Speaker` | `string` | Yes | Speaker name | | `TargetLanguageCode` | `string` | Yes | Target language code | | `Pitch` | `*float64` | No | Pitch adjustment | | `Pace` | `*float64` | No | Speed of speech | | `Loudness` | `*float64` | No | Volume level | | `SampleRate` | `*int` | No | Audio sample rate | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewTypecastTTS` ```go func NewTypecastTTS(opts TypecastTTSOptions) *TypecastTTS ``` Panics if `APIKey`, `VoiceID`, or `Model` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------------------------------- | | `APIKey` | `string` | Yes | Typecast API key | | `VoiceID` | `string` | Yes | Typecast voice identifier | | `Model` | `string` | Yes | Typecast TTS model name, for example `"ssfm-v30"` | | `AdditionalParams` | `map[string]interface{}` | No | Additional Typecast parameters | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewGradiumTTS` ```go func NewGradiumTTS(opts GradiumTTSOptions) *GradiumTTS ``` Panics if `APIKey` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ---------------------------------------------------------- | | `APIKey` | `string` | Yes | Gradium API key | | `URL` | `string` | No | WebSocket endpoint for streaming TTS output | | `ModelName` | `string` | No | Gradium TTS model name | | `VoiceID` | `string` | No | Gradium voice identifier | | `SampleRate` | `*SampleRate` | No | Output sample rate | | `AdditionalParams` | `map[string]interface{}` | No | Additional Gradium TTS parameters, flattened into `params` | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewMistralTTS` ```go func NewMistralTTS(opts MistralTTSOptions) *MistralTTS ``` Panics if `APIKey` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ---------------------------------------------------------- | | `APIKey` | `string` | Yes | Mistral API key | | `Model` | `string` | No | Mistral TTS model name | | `Voice` | `string` | No | Mistral voice identifier | | `AdditionalParams` | `map[string]interface{}` | No | Additional Mistral TTS parameters, flattened into `params` | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewGenericTTS` ```go func NewGenericTTS(opts GenericTTSOptions) *GenericTTS ``` Custom OpenAI-compatible HTTP TTS. `URL` is required and must be an absolute HTTP or HTTPS address that includes a host — this panics if `URL` is missing, badly formatted, or uses a non-HTTP(S) scheme such as `ws`, `wss`, or `ftp`. A valid URL is serialized as `tts.vendor = "generic_http"`. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `URL` | `string` | Yes | The HTTP(S) endpoint of your custom TTS service | | `Headers` | `map[string]string` | No | Custom HTTP headers to forward to the TTS service. Omitted from the request if not set | | `APIKey` | `string` | No | The API key used to authenticate with the TTS service | | `Model` | `string` | No | The TTS model name | | `Voice` | `string` | No | The voice name | | `Speed` | `*float64` | No | The speech rate | | `SampleRate` | `*SampleRate` | No | The sample rate, in Hz, of the output audio. If your TTS service doesn't support multiple sample rates, make sure the returned audio's sample rate matches this value | | `ResponseFormat` | `string` | No | The output audio format. Conversational AI Engine currently supports `pcm` | | `Instruction` | `string` | No | Instructions for voice style, emotion, or other playback directives | | `AdditionalParams` | `map[string]interface{}` | No | Additional parameters passed through to the TTS service. Explicit fields with the same name take precedence | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewXaiTTS` ```go func NewXaiTTS(opts XaiTTSOptions) *XaiTTS ``` Panics if `APIKey` or `Language` is empty. | Field | Type | Required | Description | | -------------- | ------------- | -------- | ----------------------------------------- | | `APIKey` | `string` | Yes | xAI API key | | `Language` | `string` | Yes | BCP-47 language code for speech synthesis | | `VoiceID` | `string` | No | xAI voice identifier | | `SampleRate` | `*SampleRate` | No | Audio sample rate | | `SkipPatterns` | `[]int` | No | Patterns to skip | #### `NewSmallestAITTS` ```go func NewSmallestAITTS(opts SmallestAITTSOptions) *SmallestAITTS ``` Panics if `APIKey` is empty. | Field | Type | Required | Description | | ----------------------------- | ------------------------ | -------- | -------------------------------------------------- | | `APIKey` | `string` | Yes | Smallest AI API key | | `URL` | `string` | No | Streaming TTS endpoint | | `Model` | `string` | No | TTS model name, for example `"lightning_v3.1_pro"` | | `VoiceID` | `string` | No | Voice identifier, for example `"hazel"` | | `SampleRate` | `*int` | No | Output audio sample rate in Hz | | `Speed` | `*float64` | No | Speech rate multiplier | | `Language` | `string` | No | Language code for speech synthesis | | `NumberPronunciationLanguage` | `string` | No | Language code used when reading numbers aloud | | `MathNotation` | `*bool` | No | Read mathematical notation as spoken mathematics | | `PronunciationDicts` | `[]string` | No | Pronunciation dictionaries to apply | | `SessionID` | `string` | No | Caller-supplied session identifier | | `RequestID` | `string` | No | Caller-supplied request identifier | | `SkipPatterns` | `[]int` | No | Patterns to skip | | `AdditionalParams` | `map[string]interface{}` | No | Additional Smallest AI parameters | Voice identifiers are model-specific, so `VoiceID` must belong to the model set in `Model`. For details, see [Smallest AI](/en/ai/models/tts/smallest-ai). ### STT vendors Use with [`WithStt()`](#withsttvendor). #### `NewDeepgramSTT` ```go func NewDeepgramSTT(opts DeepgramSTTOptions) *DeepgramSTT ``` Panics if `APIKey` is empty unless `Model` is one of the supported Agora-managed Deepgram models (`nova-2`, `nova-3`). | Field | Type | Required | Description | | ------------------ | ------------------------ | --------- | ------------------------------------------------------------------------ | | `APIKey` | `string` | BYOK only | Deepgram API key. Optional only for Agora-managed `nova-2` and `nova-3`. | | `Model` | `string` | No | Model, for example `"nova-2"` | | `Language` | `string` | No | Language code, for example `"en-US"` | | `Keyterm` | `string` | No | Key term to boost recognition (serialized as `keyterm`) | | `SmartFormat` | `*bool` | No | Enable smart formatting | | `Punctuation` | `*bool` | No | Enable punctuation | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor parameters | #### `NewSpeechmaticsSTT` ```go func NewSpeechmaticsSTT(opts SpeechmaticsSTTOptions) *SpeechmaticsSTT ``` Panics if `Key` or `Language` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ---------------------------------------------------- | | `Key` | `string` | Yes | Speechmatics API key. `APIKey` is a deprecated alias | | `Language` | `string` | Yes | Language code | | `URI` | `string` | No | Speechmatics streaming WebSocket URL | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | | `Model` | `string` | No | Model identifier | #### `NewMicrosoftSTT` ```go func NewMicrosoftSTT(opts MicrosoftSTTOptions) *MicrosoftSTT ``` Panics if `Key`, `Region`, or `Language` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------- | | `Key` | `string` | Yes | Azure Speech Services key | | `Region` | `string` | Yes | Azure region | | `Language` | `string` | Yes | Language code | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewOpenAISTT` ```go func NewOpenAISTT(opts OpenAISTTOptions) *OpenAISTT ``` Panics if `APIKey` is empty. `WithStt()` also panics if the transcription `prompt` or `language` isn't set through the `Prompt` and `Language` fields or within `InputAudioTranscription`. `model` defaults to `gpt-4o-mini-transcribe`. | Field | Type | Required | Description | | ------------------------- | ------------------------ | -------- | ---------------------------------------------------------- | | `APIKey` | `string` | Yes | OpenAI API key | | `Model` | `string` | No | Transcription model. Defaults to `gpt-4o-mini-transcribe`. | | `Language` | `string` | No | Language code | | `Prompt` | `string` | No | Prompt for OpenAI transcription | | `InputAudioTranscription` | `map[string]interface{}` | No | OpenAI transcription settings | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewGoogleSTT` ```go func NewGoogleSTT(opts GoogleSTTOptions) *GoogleSTT ``` Panics if `ProjectID`, `Location`, `ADCCredentialsString`, or `Language` is empty. | Field | Type | Required | Description | | ---------------------- | ------------------------ | -------- | ---------------------------------------------- | | `ProjectID` | `string` | Yes | Google Cloud project ID | | `Location` | `string` | Yes | Google Cloud region | | `ADCCredentialsString` | `string` | Yes | Google service account credentials JSON string | | `Language` | `string` | Yes | Google recognition language | | `Model` | `string` | No | Model identifier | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewAmazonSTT` ```go func NewAmazonSTT(opts AmazonSTTOptions) *AmazonSTT ``` Panics if `AccessKey`, `SecretKey`, `Region`, or `Language` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------ | | `AccessKey` | `string` | Yes | AWS access key | | `SecretKey` | `string` | Yes | AWS secret key | | `Region` | `string` | Yes | AWS region | | `Language` | `string` | Yes | Language code | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewAssemblyAISTT` ```go func NewAssemblyAISTT(opts AssemblyAISTTOptions) *AssemblyAISTT ``` Panics if `APIKey` or `Language` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ---------------------------------------------------------- | | `APIKey` | `string` | Yes | AssemblyAI API key | | `Language` | `string` | Yes | AssemblyAI language code | | `WsURL` | `string` | No | AssemblyAI streaming WebSocket URL, serialized as `ws_url` | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewGeminiSTT` ```go func NewGeminiSTT(opts GeminiSTTOptions) *GeminiSTT ``` Panics if `APIKey` is empty, if `Mode` is set to a value other than `SMART` or `VERBATIM`, if `CustomVocabulary` is combined with `WordTimestamp`, or if `SMART` mode is combined with `WordTimestamp` or `Diarization`. | Field | Type | Required | Description | | ------------------ | ------------------------- | -------- | ------------------------------------------------------------------------------ | | `APIKey` | `string` | Yes | Google AI API key | | `Model` | `string` | No | Transcription model | | `Language` | `string` | No | Recognition language | | `LanguageHints` | `[]string` | No | Candidate transcription languages. `LanguageCodes` is a deprecated alias | | `CustomVocabulary` | `[]string` | No | Words and phrases to bias recognition toward | | `SampleRate` | `int` | No | Audio sample rate in Hz. Defaults to `16000` | | `WordTimestamp` | `*bool` | No | Enable word-level timestamps | | `Mode` | `GeminiTranscriptionMode` | No | Transcript formatting mode: `SMART` or `VERBATIM`. Service default: `VERBATIM` | | `Diarization` | `*bool` | No | Enable speaker labels | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewXaiSTT` ```go func NewXaiSTT(opts XaiSTTOptions) *XaiSTT ``` Panics if `APIKey` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------ | | `APIKey` | `string` | Yes | xAI API key | | `BaseURL` | `string` | No | API endpoint URL | | `Language` | `string` | No | Language code | | `SampleRate` | `*SampleRate` | No | Audio sample rate | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewAresSTT` ```go func NewAresSTT(options ...AresSTTOptions) *AresSTT ``` Agora-managed global ASR provider. `options` is variadic so callers can select Ares without configuring keyword hints; panics if more than one options value is passed. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ---------------------------------- | | `Keywords` | `[]string` | No | Keywords that improve ASR accuracy | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewSarvamSTT` ```go func NewSarvamSTT(opts SarvamSTTOptions) *SarvamSTT ``` Panics if `APIKey` or `Language` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------ | | `APIKey` | `string` | Yes | Sarvam API key | | `Language` | `string` | Yes | Language code | | `Model` | `string` | No | Model identifier | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewSmallestAISTT` ```go func NewSmallestAISTT(opts SmallestAISTTOptions) *SmallestAISTT ``` Panics if `APIKey` is empty. | Field | Type | Required | Description | | -------------------- | ------------------------ | -------- | ---------------------------------------------------------- | | `APIKey` | `string` | Yes | Smallest AI API key | | `URL` | `string` | No | Streaming ASR WebSocket endpoint | | `Language` | `string` | No | Language code for speech recognition | | `SampleRate` | `*int` | No | Input audio sample rate in Hz | | `Encoding` | `string` | No | Input audio encoding, for example `"linear16"` | | `WordTimestamps` | `bool` | No | Include word-level timestamps | | `SentenceTimestamps` | `bool` | No | Include sentence-level timestamps | | `Diarize` | `bool` | No | Enable speaker diarization | | `VADEvents` | `bool` | No | Emit voice activity detection events | | `Endpointing` | `bool` | No | Enable automatic end-of-utterance detection | | `EOUTimeoutMs` | `*int` | No | End-of-utterance timeout in milliseconds | | `Format` | `bool` | No | Enable Smallest AI's transcript formatting | | `FinalizeOnWords` | `bool` | No | Finalize results based on word count | | `MaxWords` | `string` | No | Maximum words per result, as a string | | `Punctuate` | `bool` | No | Add punctuation to results | | `Capitalize` | `bool` | No | Apply capitalization to results | | `ITNNormalize` | `bool` | No | Apply inverse text normalization | | `FullTranscript` | `bool` | No | Return the full accumulated transcript | | `Keywords` | `string` | No | Keyword boosts, comma-separated in `keyword:weight` format | | `RedactPII` | `bool` | No | Redact personally identifiable information | | `RedactPCI` | `bool` | No | Redact payment card information | | `AdditionalParams` | `map[string]interface{}` | No | Additional Smallest AI parameters | Boolean options are serialized as the strings `"true"` or `"false"` for the Smallest AI wire protocol. Unlike the other SDKs, these fields are plain `bool` rather than pointers, so every one of them is sent on each request. For details, see [Smallest AI](/en/ai/models/asr/smallest-ai). ### MLLM vendors Use with [`WithMllm()`](#withmllmvendor) for multimodal end-to-end audio processing without separate STT, LLM, or TTS steps. `WithMllm()` automatically sets `mllm.enable = true`; you do not need to set the deprecated `AdvancedFeatures.EnableMllm` flag. #### `NewOpenAIRealtime` ```go func NewOpenAIRealtime(opts OpenAIRealtimeOptions) *OpenAIRealtime ``` Panics if `APIKey` is empty. | Field | Type | Required | Default | Description | | ------------------------- | -------------------------- | -------- | --------------------------- | --------------------------------------------------------------------- | | `APIKey` | `string` | Yes | — | OpenAI API key | | `Model` | `string` | No | `"gpt-4o-realtime-preview"` | Model identifier | | `Voice` | `string` | No | — | Voice name | | `Instructions` | `string` | No | — | System instructions | | `InputAudioTranscription` | `map[string]interface{}` | No | — | Input audio transcription settings | | `URL` | `string` | No | — | Custom WebSocket URL | | `GreetingMessage` | `string` | No | — | Agent greeting message | | `FailureMessage` | `string` | No | — | Message played when the model call fails | | `InputModalities` | `[]string` | No | — | Input modalities | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Messages` | `[]map[string]interface{}` | No | — | Conversation messages for short-term memory | | `Params` | `map[string]interface{}` | No | — | Additional parameters | | `TurnDetection` | `*Agora.MllmTurnDetection` | No | — | MLLM turn detection configuration; overrides top-level turn detection | #### `NewAzureOpenAIRealtime` ```go func NewAzureOpenAIRealtime(opts AzureOpenAIRealtimeOptions) *AzureOpenAIRealtime ``` Panics if `APIKey`, `URL`, or `TurnDetection` is empty. | Field | Type | Required | Default | Description | | ------------------ | -------------------------- | -------- | ------- | --------------------------------------------------------------------- | | `APIKey` | `string` | Yes | — | Azure OpenAI API key | | `URL` | `string` | Yes | — | Azure OpenAI Realtime WebSocket URL | | `TurnDetection` | `*Agora.MllmTurnDetection` | Yes | — | MLLM turn detection configuration; overrides top-level turn detection | | `Model` | `string` | No | — | Azure OpenAI Realtime model or deployment name | | `Voice` | `string` | No | — | Voice identifier | | `Instructions` | `string` | No | — | System instructions | | `MaxHistory` | `*int` | No | — | Number of conversation history messages to cache | | `GreetingMessage` | `string` | No | — | Agent greeting message | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Messages` | `[]map[string]interface{}` | No | — | Conversation messages for short-term memory | #### `NewGeminiLive` ```go func NewGeminiLive(opts GeminiLiveOptions) *GeminiLive ``` Panics if `APIKey` or `Model` is empty. | Field | Type | Required | Default | Description | | ------------------ | -------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------- | | `APIKey` | `string` | Yes | — | Google AI API key | | `Model` | `string` | Yes | — | Gemini Live model identifier | | `ThinkingLevel` | `string` | No | — | Reasoning budget (`"low"`, `"medium"`, or `"high"`), supported only by `"models/gemini-3.8-live-extended-thinking"` | | `URL` | `string` | No | — | Custom WebSocket URL | | `Instructions` | `string` | No | — | System instruction | | `Voice` | `string` | No | — | Voice name | | `AffectiveDialog` | `*bool` | No | — | Enable affective (emotion-aware) dialog | | `ProactiveAudio` | `*bool` | No | — | Enable proactive audio | | `TranscribeAgent` | `*bool` | No | — | Enable transcription of agent audio | | `TranscribeUser` | `*bool` | No | — | Enable transcription of user audio | | `HttpOptions` | `map[string]interface{}` | No | — | Custom HTTP client options | | `GreetingMessage` | `string` | No | — | Agent greeting message | | `FailureMessage` | `string` | No | — | Message played when the model call fails | | `InputModalities` | `[]string` | No | — | Input modalities | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Messages` | `[]map[string]interface{}` | No | — | Conversation messages for short-term memory | | `AdditionalParams` | `map[string]interface{}` | No | — | Additional parameters | | `TurnDetection` | `*Agora.MllmTurnDetection` | No | — | MLLM turn detection configuration; overrides top-level turn detection | #### `NewVertexAI` ```go func NewVertexAI(opts VertexAIOptions) *VertexAI ``` Panics if `ProjectID` or `ADCredentialsString` is empty. | Field | Type | Required | Default | Description | | --------------------- | -------------------------- | -------- | ------------------------ | --------------------------------------------------------------------- | | `ProjectID` | `string` | Yes | — | Google Cloud project ID | | `ADCredentialsString` | `string` | Yes | — | Application Default Credentials JSON string | | `Location` | `string` | No | `"us-central1"` | Google Cloud region | | `Model` | `string` | No | `"gemini-2.0-flash-exp"` | Model identifier | | `URL` | `string` | No | — | Custom WebSocket URL | | `Voice` | `string` | No | — | Voice name | | `Instructions` | `string` | No | — | System instruction | | `AffectiveDialog` | `*bool` | No | — | Enable affective (emotion-aware) dialog | | `ProactiveAudio` | `*bool` | No | — | Enable proactive audio | | `TranscribeAgent` | `*bool` | No | — | Enable transcription of agent audio | | `TranscribeUser` | `*bool` | No | — | Enable transcription of user audio | | `HttpOptions` | `map[string]interface{}` | No | — | Custom HTTP client options | | `GreetingMessage` | `string` | No | — | Agent greeting message | | `FailureMessage` | `string` | No | — | Message played when the model call fails | | `InputModalities` | `[]string` | No | — | Input modalities | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Messages` | `[]map[string]interface{}` | No | — | Conversation messages for short-term memory | | `AdditionalParams` | `map[string]interface{}` | No | — | Additional parameters | | `TurnDetection` | `*Agora.MllmTurnDetection` | No | — | MLLM turn detection configuration; overrides top-level turn detection | #### `NewXaiGrok` ```go func NewXaiGrok(opts XaiGrokOptions) *XaiGrok ``` xAI Grok MLLM vendor (`mllm.vendor`: `"xai"`). Panics if `APIKey` is empty. Defaults `URL` to `wss://api.x.ai/v1/realtime`. > **Caution** > > `NewXAIGrok` / `XAIGrokOptions` are deprecated aliases. ##### XaiGrokOptions Same fields as `XAIGrokOptions` below. #### `NewXAIGrok` (deprecated) ```go func NewXAIGrok(opts XAIGrokOptions) *XAIGrok ``` **Deprecated. Use `NewXaiGrok` instead.** ##### XAIGrokOptions | Field | Type | Required | Default | Description | | ------------------ | -------------------------- | -------- | ------------------------------ | ------------------------------------------- | | `APIKey` | `string` | Yes | — | xAI API key | | `URL` | `string` | No | `"wss://api.x.ai/v1/realtime"` | xAI Realtime WebSocket URL | | `Voice` | `string` | No | — | Voice identifier | | `Language` | `string` | No | — | Language code | | `SampleRate` | `*int` | No | — | Audio sample rate in Hz | | `GreetingMessage` | `string` | No | — | Agent greeting message | | `FailureMessage` | `string` | No | — | Message played when the model call fails | | `InputModalities` | `[]string` | No | — | Input modalities | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Messages` | `[]map[string]interface{}` | No | — | Conversation messages for short-term memory | | `Params` | `map[string]interface{}` | No | — | Additional xAI parameters | | `TurnDetection` | `*Agora.MllmTurnDetection` | No | — | `agora_vad` / `server_vad` turn detection | #### `NewOpenAIGPTLive` ```go func NewOpenAIGPTLive(opts OpenAIGPTLiveOptions) *OpenAIGPTLive ``` [OpenAI GPT-Live](/en/ai/models/mllm/openai-gpt-live) MLLM vendor (`mllm.vendor`: `"openai_gpt_live"`). Panics if `APIKey` is empty. `WithMllm()` also panics if `URL` isn't a full `ws://` or `wss://` endpoint, `Headers` isn't a JSON object string, `Delegation` isn't `client` or `responses`, or `SessionParams` overrides a protected field. > **Caution: Early access** > > OpenAI GPT-Live is available in early access and isn't intended for production traffic. The SDK automatically routes sessions that use this vendor to the preview endpoint. GPT-Live doesn't support turn detection or input audio transcription. ```go mllm := 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", }) ``` ##### OpenAIGPTLiveOptions | Field | Type | Required | Default | Description | | --------------------- | -------------------------- | -------- | ----------------------------------------- | ----------------------------------------------------------------------------------------------------------------- | | `APIKey` | `string` | Yes | — | OpenAI API key | | `Model` | `string` | No | `"gpt-live-1"` | Model name | | `Voice` | `string` | No | — | Output voice. Provider default: `marin` | | `Prompt` | `string` | No | — | Session instructions that define the assistant's behavior | | `GreetingMessage` | `string` | No | — | Greeting the agent speaks when a user joins. Serialized as `greeting_message` | | `FailureMessage` | `string` | No | — | Message played when the model call fails | | `URL` | `string` | No | `"wss://api.openai.com/v1/live/sessions"` | Full `ws://` or `wss://` endpoint | | `BaseURL` | `string` | No | `"wss://api.openai.com"` | Host used when `URL` isn't set | | `Path` | `string` | No | `"/v1/live/sessions"` | WebSocket path used when `URL` isn't set | | `InputModalities` | `[]string` | No | — | Input modalities | | `OutputModalities` | `[]string` | No | — | Output modalities | | `Messages` | `[]map[string]interface{}` | No | — | Conversation history passed to the model as context | | `McpServers` | `[]map[string]interface{}` | No | — | MCP servers whose tools GPT-Live can call. Requires `WithTools(true)` | | `ToolEnabled` | `*bool` | No | — | Advertise the agent's tools to GPT-Live. Provider default: `false` | | `Delegation` | `string` | No | — | Tool delegation mode: `client` or `responses`. Provider default: `responses`. Can't be changed during the session | | `ResponsesModel` | `string` | No | — | Model used for delegated tool calls | | `InterruptOnUserTurn` | `*bool` | No | — | Interrupt playback when the user speaks. Provider default: `false` | | `OutputIdleEndMs` | `*int` | No | — | Agent silence boundary in milliseconds. Provider default: `600`. `0` disables inference | | `InputIdleEndMs` | `*int` | No | — | User silence boundary in milliseconds. Provider default: `1500` | | `OutputSilencePeak` | `*int` | No | — | Speech amplitude threshold on the 16-bit scale. Provider default: `50` | | `OutputSampleRate` | `*int` | No | — | Output PCM sample rate in Hz. Provider default: `24000` | | `OutputBufferMs` | `*int` | No | — | Initial audio cushion in milliseconds. Provider default: `0`. A negative value disables pacing | | `InputBatchMs` | `*int` | No | — | Microphone audio batching interval in milliseconds | | `AlphaSelector` | `string` | No | — | OpenAI-Alpha selector for preview contracts. Omitted when not set | | `Headers` | `string` | No | — | Extra provider request headers, as a JSON object string | | `SessionParams` | `map[string]interface{}` | No | — | Additional session fields. Can't override `model`, `delegation`, `audio`, `instructions`, or `input` | | `Params` | `map[string]interface{}` | No | — | Additional provider parameters. Explicit options take precedence | | `Instructions` | `string` | No | — | Deprecated. Use `Prompt` instead | `InputAudioTranscription` and `TurnDetection` are deprecated. GPT-Live doesn't support them: setting `InputAudioTranscription` panics, and the SDK ignores `TurnDetection` and logs a warning. ### Avatar vendors Use with [`WithAvatar()`](#withavatarvendor). Some avatar vendors require a specific TTS sample rate. To learn when a mismatch panics or returns an error, see [`WithAvatar()`](#withavatarvendor). #### `NewLiveAvatarAvatar` Requires TTS at **24,000 Hz** (`SampleRate24kHz`). ```go func NewLiveAvatarAvatar(opts LiveAvatarAvatarOptions) *LiveAvatarAvatar ``` Panics if `APIKey` or `AgoraUID` is empty, or if `Quality` is not `"low"`, `"medium"`, or `"high"`. | Field | Type | Required | Description | | --------------------- | ------------------------ | -------- | ----------------------------------------------- | | `APIKey` | `string` | Yes | LiveAvatar API key | | `Quality` | `string` | Yes | Video quality: `"low"`, `"medium"`, or `"high"` | | `AgoraUID` | `string` | Yes | UID for the avatar's video stream | | `AgoraToken` | `string` | No | RTC token for avatar authentication | | `AvatarID` | `string` | No | LiveAvatar avatar ID | | `Enable` | `*bool` | No | Enable or disable the avatar. Default: `true` | | `DisableIdleTimeout` | `*bool` | No | Disable the idle timeout | | `ActivityIdleTimeout` | `*int` | No | Idle timeout in seconds | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewAkoolAvatar` Requires TTS at **16,000 Hz** (`SampleRate16kHz`). ```go func NewAkoolAvatar(opts AkoolAvatarOptions) *AkoolAvatar ``` Panics if `APIKey` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ---------------------------- | | `APIKey` | `string` | Yes | Akool API key | | `AvatarID` | `string` | No | Avatar ID | | `Enable` | `*bool` | No | Enable or disable the avatar | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor parameters | #### `NewAnamAvatar` Anam avatars do not enforce a fixed TTS sample rate. ```go func NewAnamAvatar(opts AnamAvatarOptions) *AnamAvatar ``` Panics if `APIKey` is empty. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | -------------------------------------------------- | | `APIKey` | `string` | Yes | Anam API key | | `AvatarID` | `string` | No | Anam avatar identifier (serialized as `avatar_id`) | | `Enable` | `*bool` | No | Enable or disable the avatar | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewGenericAvatar` ```go func NewGenericAvatar(opts GenericAvatarOptions) *GenericAvatar ``` Panics if `APIKey`, `APIBaseURL`, `AvatarID`, or `AgoraUID` is empty. `AgoraAppID`, `AgoraChannel`, and `AgoraToken` are optional; AgentKit fills them from the session on `Start()` when omitted. Generic avatars do not enforce a fixed TTS sample rate. Use the sample rate required by your avatar provider. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------------------------------------------------------------------ | | `APIKey` | `string` | Yes | Generic avatar vendor API key | | `APIBaseURL` | `string` | Yes | Generic avatar API endpoint | | `AvatarID` | `string` | Yes | Avatar identifier | | `AgoraUID` | `string` | Yes | UID for avatar video stream; use a different UID from `AgentUID` | | `AgoraToken` | `string` | No | Avatar token; auto-generated with the same token format as agent tokens when omitted | | `AgoraAppID` | `string` | No | Overrides session App ID | | `AgoraChannel` | `string` | No | Overrides session channel | | `Enable` | `*bool` | No | Enable or disable the avatar | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewTavus` ```go func NewTavus(opts TavusOptions) *Tavus ``` Panics if `APIKey`, `APIBaseURL`, `AvatarID`, or `AgoraUID` is empty. `AgoraAppID`, `AgoraChannel`, and `AgoraToken` are optional; AgentKit fills them from the session on `Start()` when omitted. Serializes `vendor: "generic"`. For the endpoint and a full example, see [Tavus](/en/ai/models/avatar/tavus). Tavus avatars do not enforce a fixed TTS sample rate. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------------------------------------------------------------------ | | `APIKey` | `string` | Yes | Tavus API key | | `APIBaseURL` | `string` | Yes | Tavus API endpoint | | `AvatarID` | `string` | Yes | Tavus avatar identifier | | `AgoraUID` | `string` | Yes | UID for avatar video stream; use a different UID from `AgentUID` | | `AgoraToken` | `string` | No | Avatar token; auto-generated with the same token format as agent tokens when omitted | | `AgoraAppID` | `string` | No | Overrides session App ID | | `AgoraChannel` | `string` | No | Overrides session channel | | `Enable` | `*bool` | No | Enable or disable the avatar | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewProtoface` ```go func NewProtoface(opts ProtofaceOptions) *Protoface ``` Panics if `APIKey`, `APIBaseURL`, `AvatarID`, or `AgoraUID` is empty. `AgoraAppID`, `AgoraChannel`, and `AgoraToken` are optional; AgentKit fills them from the session on `Start()` when omitted. Serializes `vendor: "generic"`. For the endpoint and a full example, see [Protoface](/en/ai/models/avatar/protoface). Protoface avatars do not enforce a fixed TTS sample rate. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------------------------------------------------------------------ | | `APIKey` | `string` | Yes | Protoface API key | | `APIBaseURL` | `string` | Yes | Protoface API endpoint | | `AvatarID` | `string` | Yes | Protoface avatar identifier | | `AgoraUID` | `string` | Yes | UID for avatar video stream; use a different UID from `AgentUID` | | `AgoraToken` | `string` | No | Avatar token; auto-generated with the same token format as agent tokens when omitted | | `AgoraAppID` | `string` | No | Overrides session App ID | | `AgoraChannel` | `string` | No | Overrides session channel | | `Enable` | `*bool` | No | Enable or disable the avatar | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewLemonSlice` ```go func NewLemonSlice(opts LemonSliceOptions) *LemonSlice ``` Panics if `APIKey`, `APIBaseURL`, `AvatarID`, or `AgoraUID` is empty. `AgoraAppID`, `AgoraChannel`, and `AgoraToken` are optional; AgentKit fills them from the session on `Start()` when omitted. Serializes `vendor: "generic"`. For the endpoint and a full example, see [LemonSlice](/en/ai/models/avatar/lemonslice). LemonSlice avatars do not enforce a fixed TTS sample rate. | Field | Type | Required | Description | | ------------------ | ------------------------ | -------- | ------------------------------------------------------------------------------------ | | `APIKey` | `string` | Yes | LemonSlice API key | | `APIBaseURL` | `string` | Yes | LemonSlice API endpoint | | `AvatarID` | `string` | Yes | Always `lemonslice` | | `AgoraUID` | `string` | Yes | UID for avatar video stream; use a different UID from `AgentUID` | | `AgoraToken` | `string` | No | Avatar token; auto-generated with the same token format as agent tokens when omitted | | `AgoraAppID` | `string` | No | Overrides session App ID | | `AgoraChannel` | `string` | No | Overrides session channel | | `Enable` | `*bool` | No | Enable or disable the avatar | | `AdditionalParams` | `map[string]interface{}` | No | Additional vendor params | #### `NewHeyGenAvatar` (deprecated) Requires TTS at **24,000 Hz** (`SampleRate24kHz`). ```go func NewHeyGenAvatar(opts HeyGenAvatarOptions) *HeyGenAvatar ``` > **Caution** > > `NewHeyGenAvatar` and `HeyGenAvatarOptions` are deprecated. Use [`NewLiveAvatarAvatar`](#newliveavataravatar) instead. `HeyGenAvatarOptions` is an alias of `LiveAvatarAvatarOptions` and the fields are identical; the emitted `vendor` remains `"heygen"`. Panics if `APIKey` or `AgoraUID` is empty, or if `Quality` is not `"low"`, `"medium"`, or `"high"`. ## Token utilities Helper functions for generating and managing tokens. ```go import "github.com/AgoraIO/agora-agents-go/v2/agentkit" ``` ```go func GenerateRtcToken(opts GenerateTokenOptions) (string, error) func GenerateRtcTokenWithAccount(opts GenerateRtcTokenWithAccountOptions) (string, error) func GenerateConvoAIToken(opts GenerateConvoAITokenOptions) (string, error) ``` ### `GenerateConvoAIToken()` Generates a combined RTC+RTM Conversational AI token. This is the same token the SDK generates automatically when the session has an App ID and App Certificate. ```go func GenerateConvoAIToken(opts GenerateConvoAITokenOptions) (string, error) ``` | Field | Type | Required | Description | | ----------------- | -------- | -------- | ------------------------------------------------------------------ | | `AppID` | `string` | Yes | Agora App ID | | `AppCertificate` | `string` | Yes | Agora App Certificate | | `ChannelName` | `string` | Yes | The channel the token grants access to | | `UID` | `int` | Yes | Numeric UID this token is issued for | | `TokenExpire` | `int` | No | Token lifetime in seconds. Default: `86400`. Valid range: 1–86400 | | `PrivilegeExpire` | `int` | No | Privilege lifetime in seconds. `0` means the same as `TokenExpire` | ```go token, err := agentkit.GenerateConvoAIToken(agentkit.GenerateConvoAITokenOptions{ AppID: os.Getenv("AGORA_APP_ID"), AppCertificate: os.Getenv("AGORA_APP_CERT"), ChannelName: "support-room-123", UID: 1, TokenExpire: 12 * 3600, }) ``` ### `GenerateRtcTokenWithAccount()` Generates an RTC token for a string account (user ID). Use `GenerateConvoAIToken()` instead for most Conversational AI use cases. ```go func GenerateRtcTokenWithAccount(opts GenerateRtcTokenWithAccountOptions) (string, error) ``` | Field | Type | Required | Description | | ---------------- | -------- | -------- | ------------------------------------------------------------------------------- | | `AppID` | `string` | Yes | Agora App ID | | `AppCertificate` | `string` | Yes | Agora App Certificate | | `Channel` | `string` | Yes | Channel name | | `Account` | `string` | Yes | String user account | | `Role` | `int` | No | RTC role: `RolePublisher` (1) or `RoleSubscriber` (2). Default: `RolePublisher` | | `ExpirySeconds` | `int` | No | Token lifetime in seconds. Default: `DefaultExpirySeconds` (86400) | ### `GenerateRtcToken()` Generates an RTC-only token. Use `GenerateConvoAIToken()` instead for most Conversational AI use cases. ```go func GenerateRtcToken(opts GenerateTokenOptions) (string, error) ``` | Field | Type | Required | Description | | ---------------- | -------- | -------- | ------------------------------------------------------------------------------- | | `AppID` | `string` | Yes | Agora App ID | | `AppCertificate` | `string` | Yes | Agora App Certificate | | `Channel` | `string` | Yes | Channel name | | `UID` | `uint32` | Yes | User ID. Use `0` for any user | | `Role` | `int` | No | RTC role: `RolePublisher` (1) or `RoleSubscriber` (2). Default: `RolePublisher` | | `ExpirySeconds` | `int` | No | Token lifetime in seconds. Default: `DefaultExpirySeconds` (86400) | ### `ExpiresInHours()` / `ExpiresInMinutes()` Helper functions for specifying token lifetimes. Use with `CreateSessionOptions.ExpiresIn`, `AgentSessionOptions.ExpiresIn`, or token generation functions. Returns an error if the value is ≤ 0; warns and caps at 86400 if the result exceeds 24 hours. ```go func ExpiresInHours(hours float64) (int, error) func ExpiresInMinutes(minutes float64) (int, error) ``` ```go expiresIn, err := agentkit.ExpiresInHours(12) if err != nil { log.Fatalf("Invalid expiry: %v", err) } session := agent.CreateSession(agentkit.CreateSessionOptions{ // ... ExpiresIn: expiresIn, }) ``` ## Types and constants Shared types, constants, and enums used across the SDK. ### `AgentSessionLifecycle` Typed string constants representing the session lifecycle states. Read with `session.Status()`. ```go type AgentSessionLifecycle string const ( AgentSessionLifecycleIdle AgentSessionLifecycle = "idle" AgentSessionLifecycleStarting AgentSessionLifecycle = "starting" AgentSessionLifecycleRunning AgentSessionLifecycle = "running" AgentSessionLifecycleStopping AgentSessionLifecycle = "stopping" AgentSessionLifecycleStopped AgentSessionLifecycle = "stopped" AgentSessionLifecycleError AgentSessionLifecycle = "error" ) ``` `StatusIdle`, `StatusStarting`, `StatusRunning`, `StatusStopping`, `StatusStopped`, and `StatusError` are deprecated aliases of these constants. `agentkit.SessionStatus` is a different type: the agent status returned by the REST API endpoint that lists agents. ### `SampleRate` Typed integer constants for audio sample rates, defined in the `vendors` package (`vendors.SampleRate`). Use with TTS vendor `SampleRate` fields and avatar sample rate validation. ```go type SampleRate int const ( SampleRate8kHz SampleRate = 8000 SampleRate16kHz SampleRate = 16000 SampleRate22kHz SampleRate = 22050 SampleRate24kHz SampleRate = 24000 SampleRate44kHz SampleRate = 44100 SampleRate48kHz SampleRate = 48000 ) ``` Convenience constants for avatar sample rate requirements: ```go const ( LiveAvatarRequiredSampleRate = SampleRate24kHz AkoolRequiredSampleRate = SampleRate16kHz // 16000 Hz ) ``` ### `EventHandler` The function signature for session event handlers. Pass implementations to [`session.On()`](#onevent-handler). ```go type EventHandler func(data interface{}) ``` | Event | `data` type | Cast example | | ----------- | ------------------- | -------------------------------------- | | `"started"` | `map[string]string` | `data.(map[string]string)["agent_id"]` | | `"stopped"` | `map[string]string` | `data.(map[string]string)["agent_id"]` | | `"error"` | `error` | `data.(error)` | ### Area constants Used with `option.WithArea()` to select the regional API endpoint. ```go option.AreaUS // United States (west + east) option.AreaEU // Europe (west + central) option.AreaAP // Asia-Pacific (southeast + northeast) option.AreaCN // Chinese Mainland (east + north) option.AreaUnknown // Zero value; not a valid region ``` Passing `option.AreaUnknown` to `WithArea`, or not setting `Area` in `NewAgoraClient`, causes a panic. ### Type aliases The `agentkit` package defines type aliases for common Fern-generated types. Use these in place of the full `Agora.*` names when building configuration objects. `TurnDetectionConfig` isn't an alias. It's an AgentKit struct that mirrors `Agora.StartAgentsRequestPropertiesTurnDetection` and adds a `Language` field. | Alias | Underlying type | | ----------------------------------- | --------------------------------------------------------------------- | | `SalConfig` | `Agora.StartAgentsRequestPropertiesSal` | | `AdvancedFeatures` | `Agora.StartAgentsRequestPropertiesAdvancedFeatures` | | `SessionParams` | `Agora.StartAgentsRequestPropertiesParameters` | | `GeofenceConfig` | `Agora.StartAgentsRequestPropertiesGeofence` | | `RtcConfig` | `Agora.StartAgentsRequestPropertiesRtc` | | `FillerWordsConfig` | `Agora.StartAgentsRequestPropertiesFillerWords` | | `FillerWordsContentMode` | `Agora.StartAgentsRequestPropertiesFillerWordsContentMode` | | `FillerWordsContentGeneratedConfig` | `Agora.StartAgentsRequestPropertiesFillerWordsContentGeneratedConfig` | | `LlmTool` | `Agora.LlmTool` | | `LlmToolFunction` | `Agora.LlmToolFunction` | | `LlmToolFunctionParameters` | `Agora.LlmToolFunctionParameters` | | `LlmToolExecution` | `Agora.LlmToolExecution` | | `LlmToolServer` | `Agora.LlmToolServer` | | `LlmConfig` | `Agora.Llm` | | `MllmConfig` | `Agora.Mllm` | | `AsrConfig` | `Agora.Asr` | | `TtsConfig` | `Agora.Tts` | | `AvatarConfig` | `Agora.StartAgentsRequestPropertiesAvatar` | | `SttConfig` | `AsrConfig` | | `LlmStyle` | `Agora.LlmStyle` | | `SessionInfo` | `Agora.GetAgentsResponse` | | `ThinkResponse` | `Agora.AgentThinkAgentManagementResponse` | Additional SOS/EOS turn detection aliases: `TurnDetectionNestedConfig`, `StartOfSpeechConfig`, `EndOfSpeechConfig`, and related sub-types. Session/conversation aliases: `SessionListResponse`, `ConversationHistory`, `ConversationTurns`, etc. Think type aliases: `ThinkOnListeningAction`, `ThinkOnThinkingAction`, `ThinkOnSpeakingAction`. `FillerWordsConfig` supports static and generated filler words. Generated mode requires static fallback phrases, while `GeneratedConfig` and `Prompt` are optional. Agora hosts the generation service, so you can't configure its model endpoint, API key, or model parameters. For the field structure, see [Configure generated filler words](/en/ai/build/shape-the-conversation/filler-words#configure-generated-filler-words). `FillerWordsContentGeneratedConfig` sets the conversation context for generated filler words. Use `ContextMessageLimit` (`*int`, `1` to `6`, defaults to `1`) to set how many of the most recent conversation messages to use, counting the current turn's message, and `HistoryCharacterLimit` (`*int`, `0` to `10000`, defaults to `1000`) to cap the combined characters of the earlier messages. For details, see [Talking while waiting](/en/ai/build/shape-the-conversation/filler-words#widen-the-conversation-window). ### `core.APIError` The Fern-generated error type returned when the API responds with a 4xx or 5xx status code. Use `errors.As` to inspect the error. `apiError.Error()` returns `": "`, and `apiError.Unwrap()` returns the wrapped error containing the response body. ```go import "github.com/AgoraIO/agora-agents-go/v2/core" _, err := session.Start(ctx) if err != nil { var apiError *core.APIError if errors.As(err, &apiError) { log.Printf("Status: %d", apiError.StatusCode) log.Printf("Body: %v", apiError.Unwrap()) } return err } ``` | Field | Type | Description | | ------------ | ------------- | ------------------------------------ | | `StatusCode` | `int` | HTTP status code returned by the API | | `Header` | `http.Header` | Response headers from the API | # Python (/en/api-reference/api-ref/server-sdk/python) > Documentation: Voice Agents SDK reference. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-sdk-v1.txt). Full API reference for the Agora Conversational AI Python SDK. Install the SDK from PyPI. The import package is `agora_agent`. ```bash pip install agora-agents ``` ## Agora / AsyncAgora Client `Agora` (sync) and `AsyncAgora` (async) extend the Fern-generated base client with regional domain pool support and three authentication modes. Use `Agora` for synchronous applications and `AsyncAgora` for asyncio-based applications. ```python from agora_agent import Agora, Area client = Agora( area=Area.US, app_id='your-app-id', app_certificate='your-app-certificate', ) ``` See [Sync vs. Async](#sync-vs-async) to choose the right client for your application. ### Constructor ```python Agora( *, area: Area, app_id: str, app_certificate: str, customer_id: Optional[str] = None, customer_secret: Optional[str] = None, auth_token: Optional[str] = None, headers: Optional[Dict[str, str]] = None, timeout: Optional[float] = None, follow_redirects: Optional[bool] = True, httpx_client: Optional[httpx.Client] = None, debug: bool = False, ) ``` `app_id` and `app_certificate` are always required. Add `customer_id` and `customer_secret` for Basic Auth, or `auth_token` for token mode. | Parameter | Type | Required | Default | Description | | ------------------ | ---------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------- | | `area` | [`Area`](#area) | Yes | — | Region for API routing | | `app_id` | `str` | Yes | — | Agora App ID | | `app_certificate` | `str` | Yes | — | Agora App Certificate. Keep this secret and never expose it client-side | | `customer_id` | `str` | No | `None` | Customer ID (Basic Auth mode). Requires `customer_secret` | | `customer_secret` | `str` | No | `None` | Customer Secret (Basic Auth mode) | | `auth_token` | `str` | No | `None` | Raw token string. The SDK sends `Authorization: agora token=`. Can't be combined with `customer_id` and `customer_secret` | | `headers` | `Dict[str, str]` | No | `None` | Additional headers sent with every request | | `timeout` | `float` | No | `None` | Request timeout in seconds. Effectively 60 seconds when not set | | `follow_redirects` | `bool` | No | `True` | Whether to follow HTTP redirects | | `httpx_client` | `httpx.Client` | No | `None` | Custom httpx client instance | | `debug` | `bool` | No | `False` | Log HTTP requests and responses, with secrets redacted. Ignored when `httpx_client` is set | Authentication mode is resolved from the parameters you provide: | Parameters provided | Resolved mode | | --------------------------------- | ------------------- | | `customer_id` + `customer_secret` | `"basic"` | | `auth_token` | `"token"` | | Neither | `"app-credentials"` | Passing `customer_id` without `customer_secret`, or combining `auth_token` with `customer_id`, raises `ValueError`. `AsyncAgora` has the same constructor signature, except `httpx_client` accepts `httpx.AsyncClient` instead of `httpx.Client`. ```python from agora_agent import AsyncAgora, Area client = AsyncAgora( area=Area.US, app_id='your-app-id', app_certificate='your-app-certificate', ) ``` See [Authentication](/en/api-reference/api-ref/conversational-ai/authentication) for details on each mode. ### Properties #### `pool` Access the underlying `Pool` object for advanced domain management. ```python pool = client.pool pool.get_area() # Area.US ``` - **Returns:** `Pool` #### `area` and `area_scope` `area` returns the configured [`Area`](#area). `area_scope` returns `"global"` or `"cn"`. ### Methods The following methods are available in addition to the Fern-generated sub-client methods. #### `next_region()` Cycles to the next region prefix in the domain pool. Call this after a request failure to try a different regional endpoint. Synchronous on both `Agora` and `AsyncAgora`. ```python client.next_region() ``` #### `select_best_domain()` Triggers DNS-based domain selection to find the fastest-responding domain suffix. Results are cached for 30 seconds. ```python # Sync (Agora) client.select_best_domain() # Async (AsyncAgora) — requires await await client.select_best_domain() ``` #### `stop_agent(agent_id)` Stops an agent by ID without an `AgentSession` reference, for example, from an end-call handler. The method treats a `404` response as success. Synchronous on `Agora`, `async` on `AsyncAgora`. ```python # Sync (Agora) client.stop_agent(agent_id) # Async (AsyncAgora) await client.stop_agent(agent_id) ``` #### `get_current_url()` Returns the full API URL currently in use as a `str`. Synchronous on both `Agora` and `AsyncAgora`. ```python url = client.get_current_url() # Example: 'https://api-us-west-1.agora.io/api/conversational-ai-agent' ``` ### Sub-clients Both `Agora` and `AsyncAgora` expose Fern-generated sub-clients for direct REST API access. You typically do not need these when using the [agentkit layer](#agent). | Property | Sync type | Async type | Description | | ------------------------- | ----------------------- | ---------------------------- | -------------------------------------------------- | | `client.agents` | `AgentsClient` | `AsyncAgentsClient` | Start, stop, list, update agents | | `client.agent_management` | `AgentManagementClient` | `AsyncAgentManagementClient` | Inject instructions into a running agent (`think`) | | `client.telephony` | `TelephonyClient` | `AsyncTelephonyClient` | Telephony operations | | `client.phone_numbers` | `PhoneNumbersClient` | `AsyncPhoneNumbersClient` | Phone number management | Sub-clients are lazily initialized on first access. For most use cases, prefer the [`AgentSession`](#agentsession-asyncagentsession) API over calling `client.agents` directly. For full method signatures and request parameters, see the [REST API reference](/en/api-reference/api-ref/conversational-ai/join). ## Agent `Agent` is an immutable configuration object. Each builder method returns a new `Agent` instance — the original is never modified. Define one `Agent` at startup and call `create_session()` on it for each user conversation. ```python from agora_agent import Agent ``` ### Constructor ```python Agent( client: Agora | AsyncAgora, instructions: Optional[str] = None, turn_detection: Optional[TurnDetectionConfig | dict] = None, interruption: Optional[InterruptionConfig] = None, sal: Optional[SalConfig] = None, advanced_features: Optional[Dict[str, Any]] = None, parameters: Optional[SessionParams | dict] = None, greeting: Optional[str] = None, failure_message: Optional[str] = None, max_history: Optional[int] = None, geofence: Optional[GeofenceConfig] = None, labels: Optional[Dict[str, str]] = None, rtc: Optional[RtcConfig] = None, filler_words: Optional[FillerWordsConfig] = None, greeting_configs: Optional[Dict[str, Any]] = None, pipeline_id: Optional[str] = None, ) ``` `client` is required. Omitting it raises `TypeError`. All other parameters are optional. Use the [builder methods](#builder-methods-1) to set vendor configuration after construction. | Parameter | Type | Default | Description | | ------------------- | ------------------------------- | ------- | -------------------------------------------------------------------- | | `client` | `Agora` or `AsyncAgora` | — | Authenticated client used by sessions | | `pipeline_id` | `Optional[str]` | `None` | Published AI Studio pipeline ID used as the base configuration | | `instructions` | `Optional[str]` | `None` | Deprecated. Set `system_messages` on the LLM vendor instead | | `turn_detection` | `Optional[TurnDetectionConfig]` | `None` | Voice activity detection settings | | `interruption` | `Optional[InterruptionConfig]` | `None` | Unified interruption control configuration | | `sal` | `Optional[SalConfig]` | `None` | Selective Attention Locking configuration | | `advanced_features` | `Optional[Dict[str, Any]]` | `None` | Advanced features, for example `{'enable_rtm': True}` | | `parameters` | `Optional[SessionParams]` | `None` | Additional session parameters | | `greeting` | `Optional[str]` | `None` | Deprecated. Set `greeting_message` on the LLM or MLLM vendor instead | | `failure_message` | `Optional[str]` | `None` | Deprecated. Set `failure_message` on the LLM or MLLM vendor instead | | `max_history` | `Optional[int]` | `None` | Deprecated. Set `max_history` on the LLM vendor instead | | `greeting_configs` | `Optional[Dict[str, Any]]` | `None` | Deprecated. Set `greeting_configs` on the LLM vendor instead | | `geofence` | `Optional[GeofenceConfig]` | `None` | Regional access restriction | | `labels` | `Optional[Dict[str, str]]` | `None` | Custom key-value labels returned in notification callbacks | | `rtc` | `Optional[RtcConfig]` | `None` | RTC media encryption | | `filler_words` | `Optional[FillerWordsConfig]` | `None` | Filler words played while waiting for the LLM response | ### Builder methods All builder methods return a **new** `Agent` instance. The original is never modified. #### `with_llm(vendor)` Sets the LLM vendor for the cascading flow. Pass an instance of [`OpenAI`](#openai-1), [`AzureOpenAI`](#azureopenai-1), [`Anthropic`](#anthropic-1), or [`Gemini`](#gemini-1). ```python with_llm(vendor: BaseLLM) -> Agent ``` #### `with_tts(vendor)` Sets the TTS vendor. Records the vendor's `sample_rate` for [avatar](#avatar-vendors-1) validation. Raises `ValueError` if an avatar is already set and its required sample rate differs. ```python with_tts(vendor: BaseTTS) -> Agent ``` #### `with_stt(vendor)` Sets the STT vendor. Pass an instance of any [STT vendor class](#stt-vendors-1). ```python with_stt(vendor: BaseSTT) -> Agent ``` #### `with_mllm(vendor)` Sets the MLLM vendor for multimodal flow. Pass an instance of any MLLM vendor class, including [`OpenAIGPTLive`](#openaigptlive). Calling `with_mllm()` automatically sets `mllm.enable = True`. MLLM sessions do not require TTS, STT, or LLM vendors. ```python with_mllm(vendor: BaseMLLM) -> Agent ``` #### `with_avatar(vendor)` Sets the avatar vendor. Raises `ValueError` if the TTS sample rate does not match the avatar's required rate. ```python with_avatar(vendor: BaseAvatar) -> Agent ``` **Raises:** `ValueError` — if TTS sample rate does not match the avatar's `required_sample_rate`. #### `with_turn_detection(config)` Configures cascading-flow SOS/EOS voice activity detection. Use `config.start_of_speech` and `config.end_of_speech` for SOS/EOS detection. Use `with_interruption()` for interruption behavior and MLLM vendor `turn_detection` for MLLM turn detection. ```python with_turn_detection(config: TurnDetectionConfig) -> Agent ``` #### `with_interruption(config)` Configures unified interruption behavior using the top-level `interruption` object. Use this for `start_of_speech` and `keywords` interruption modes. ```python with_interruption(config: InterruptionConfig) -> Agent ``` #### `with_instructions(instructions)` Overrides the LLM system prompt on a new `Agent` instance. Deprecated. Set `system_messages` on the LLM vendor instead. ```python with_instructions(instructions: str) -> Agent ``` #### `with_greeting(greeting)` Overrides the greeting message on a new `Agent` instance. Deprecated. Set `greeting_message` on the LLM or MLLM vendor instead. ```python with_greeting(greeting: str) -> Agent ``` #### Other builder methods The following methods follow the same pattern — each returns a new `Agent` instance with the updated configuration. | Method | Parameter type | Description | | ------------------------------------- | ------------------------- | ------------------------------------------------------------------- | | `with_sal(config)` | `SalConfig` | Set Selective Attention Locking configuration | | `with_advanced_features(features)` | `Dict[str, Any]` | Set advanced features | | `with_tools(enabled=True)` | `bool` | Enable or disable MCP tool and custom tool invocation | | `with_parameters(parameters)` | `SessionParams` or `dict` | Set session parameters | | `with_audio_scenario(audio_scenario)` | `str` | Set the RTC audio scenario (`parameters.audio_scenario`) | | `with_failure_message(message)` | `str` | Deprecated. Set `failure_message` on the LLM or MLLM vendor instead | | `with_max_history(max_history)` | `int` | Deprecated. Set `max_history` on the LLM vendor instead | | `with_greeting_configs(configs)` | `Dict[str, Any]` | Deprecated. Set `greeting_configs` on the LLM vendor instead | | `with_geofence(geofence)` | `GeofenceConfig` | Set geofence configuration | | `with_labels(labels)` | `Dict[str, str]` | Set custom labels | | `with_rtc(rtc)` | `RtcConfig` | Set RTC configuration | | `with_filler_words(filler_words)` | `FillerWordsConfig` | Set filler words configuration | ### `create_session()` Creates a sync [`AgentSession`](#agentsession-asyncagentsession) using the client bound to this `Agent`. Doesn't start the agent. Call [`session.start()`](#start-1) to join the channel. ```python create_session( channel: str, agent_uid: str, remote_uids: List[str], name: Optional[str] = None, token: Optional[str] = None, idle_timeout: Optional[int] = None, enable_string_uid: Optional[bool] = None, preset: Optional[str | Sequence[str]] = None, pipeline_id: Optional[str] = None, expires_in: Optional[int] = None, debug: Optional[bool] = None, warn: Optional[Callable[[str], None]] = None, ) -> AgentSession ``` `create_session()` fields: | Parameter | Type | Required | Description | | ------------------- | --------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `channel` | `str` | Yes | Channel name to join | | `agent_uid` | `str` | Yes | The agent's RTC UID. Must be a numeric string when the token is auto-generated | | `remote_uids` | `List[str]` | Yes | Remote user UIDs the agent listens and responds to | | `name` | `Optional[str]` | No | Agent instance name. `Agent` has no name option, so set it here. Defaults to `agent-{timestamp}` | | `token` | `Optional[str]` | No | Pre-built RTC+RTM token. Omit to auto-generate from app credentials | | `expires_in` | `Optional[int]` | No | Token lifetime in seconds. Only applies when the token is auto-generated. Valid range: 1–86400. Use [`expires_in_hours()`](#expires_in_hours-expires_in_minutes) for clarity | | `idle_timeout` | `Optional[int]` | No | Seconds before the agent auto-exits when no audio is detected | | `enable_string_uid` | `Optional[bool]` | No | Use string UIDs instead of numeric UIDs | | `preset` | `Optional[str \| Sequence[str]]` | No | Advanced project-specific presets. Most applications should not set this | | `pipeline_id` | `Optional[str]` | No | Published AI Studio pipeline ID. Overrides the agent-level value | | `debug` | `Optional[bool]` | No | Print the redacted start request | | `warn` | `Optional[Callable[[str], None]]` | No | Callback that receives SDK warning messages | ### `create_async_session()` Takes the same parameters as [`create_session()`](#create_session) and returns an [`AsyncAgentSession`](#agentsession-asyncagentsession). Use it with an `Agent` bound to an `AsyncAgora` client. ```python create_async_session(...) -> AsyncAgentSession ``` ### `to_properties()` Converts the agent configuration into a `StartAgentsRequestProperties` object for the Agora API. Called internally by `AgentSession.start()`. ```python to_properties( channel: str, agent_uid: str, remote_uids: List[str], idle_timeout: Optional[int] = None, enable_string_uid: Optional[bool] = None, token: Optional[str] = None, app_id: Optional[str] = None, app_certificate: Optional[str] = None, expires_in: Optional[int] = None, skip_vendor_validation: bool = False, skip_vendor_validation_categories: Optional[AbstractSet[str]] = None, allow_missing_vendor_categories: Optional[AbstractSet[str]] = None, ) -> StartAgentsRequestProperties ``` `skip_vendor_validation` is deprecated. Use `skip_vendor_validation_categories` and `allow_missing_vendor_categories` instead. **Raises:** `ValueError` if neither `token` nor `app_id`+`app_certificate` is provided, if required vendors (LLM, TTS) are missing in cascading mode, if an enabled avatar is combined with MLLM, or if `agent_uid` isn't numeric when the SDK generates a token. ### Properties Read-only properties available on any `Agent` instance. | Property | Type | Description | | ------------------- | ------------------------------- | ------------------------------------------ | | `pipeline_id` | `Optional[str]` | AI Studio pipeline ID | | `tts_sample_rate` | `Optional[int]` | TTS sample rate | | `greeting_configs` | `Optional[Dict[str, Any]]` | Greeting playback configuration | | `instructions` | `Optional[str]` | LLM system prompt | | `greeting` | `Optional[str]` | Greeting message | | `failure_message` | `Optional[str]` | Message spoken when LLM fails | | `max_history` | `Optional[int]` | Maximum conversation history length | | `llm` | `Optional[Dict[str, Any]]` | LLM config dict (from `to_config()`) | | `tts` | `Optional[Dict[str, Any]]` | TTS config dict | | `stt` | `Optional[Dict[str, Any]]` | STT config dict | | `mllm` | `Optional[Dict[str, Any]]` | MLLM config dict | | `avatar` | `Optional[Dict[str, Any]]` | Avatar config dict | | `turn_detection` | `Optional[TurnDetectionConfig]` | Turn detection configuration | | `interruption` | `Optional[InterruptionConfig]` | Unified interruption control configuration | | `sal` | `Optional[SalConfig]` | SAL configuration | | `advanced_features` | `Optional[Dict[str, Any]]` | Advanced features | | `parameters` | `Optional[SessionParams]` | Session parameters | | `geofence` | `Optional[GeofenceConfig]` | Geofence configuration | | `labels` | `Optional[Dict[str, str]]` | Custom labels | | `rtc` | `Optional[RtcConfig]` | RTC configuration | | `filler_words` | `Optional[FillerWordsConfig]` | Filler words configuration | | `config` | `Dict[str, Any]` | Full configuration snapshot | ### Type aliases Public aliases over Fern-generated types: `LlmConfig`, `SttConfig`, `AsrConfig` (= `SttConfig`), `MllmConfig`, `AvatarConfig`, session/conversation types, and think types (`ThinkOnListeningAction`, etc.). Think value constants: `ThinkOnListeningActionInject`, `ThinkOnListeningActionInterrupt`, `ThinkOnListeningActionIgnore`, `ThinkOnThinkingActionInterrupt`, `ThinkOnThinkingActionIgnore`, `ThinkOnSpeakingActionInterrupt`, `ThinkOnSpeakingActionIgnore`. The think action parameters also accept the string `append`, which has no convenience constant. `FillerWordsConfig` supports static and generated filler words. In generated mode, `generated_config`, `prompt`, and the static fallback phrases are optional. If you omit `generated_config`, the service uses its default generation settings. Agora hosts the generation service, so you can't configure its model endpoint, API key, or model parameters. The only supported fallback strategy is `static`. For the field structure, see [Configure generated filler words](/en/ai/build/shape-the-conversation/filler-words#configure-generated-filler-words). Public aliases also include `FillerWordsContentGeneratedConfig` and the custom tool types `LlmToolConfig`, `LlmToolFunctionConfig`, `LlmToolFunctionParametersConfig`, `LlmToolExecutionConfig`, and `LlmToolServerConfig`. `FillerWordsContentGeneratedConfig` sets the conversation context for generated filler words. Use `context_message_limit` (`1` to `6`, defaults to `1`) to set how many of the most recent conversation messages to use, counting the current turn's message, and `history_character_limit` (`0` to `10000`, defaults to `1000`) to cap the combined characters of the earlier messages. For details, see [Talking while waiting](/en/ai/build/shape-the-conversation/filler-words#widen-the-conversation-window). ## AgentSession / AsyncAgentSession `AgentSession` (sync) and `AsyncAgentSession` (async) manage the full lifecycle of a running agent. Obtain a session with [`agent.create_session()`](#create_session) (sync) or [`agent.create_async_session()`](#create_async_session) (async). Direct construction is available for advanced use cases. ```python from agora_agent.agentkit import AgentSession, AsyncAgentSession ``` ### Constructor Sessions are normally created via `Agent.create_session()`. Direct construction is available for advanced use: ```python AgentSession( client: Any, agent: Agent, app_id: str, name: str, channel: str, agent_uid: str, remote_uids: List[str], app_certificate: Optional[str] = None, token: Optional[str] = None, idle_timeout: Optional[int] = None, enable_string_uid: Optional[bool] = None, preset: Optional[str | Sequence[str]] = None, pipeline_id: Optional[str] = None, expires_in: Optional[int] = None, debug: Optional[bool] = None, warn: Optional[Callable[[str], None]] = None, ) ``` `AsyncAgentSession` has the same constructor signature. | Parameter | Type | Required | Description | | ------------------- | --------------------------------- | -------- | ------------------------------------------- | | `client` | `Agora` or `AsyncAgora` | Yes | Authenticated client | | `agent` | `Agent` | Yes | Agent configuration | | `app_id` | `str` | Yes | Agora App ID | | `name` | `str` | Yes | Session name | | `channel` | `str` | Yes | Channel name | | `agent_uid` | `str` | Yes | UID for the agent | | `remote_uids` | `List[str]` | Yes | UIDs of remote participants | | `app_certificate` | `Optional[str]` | No | App Certificate (for auto token generation) | | `token` | `Optional[str]` | No | Pre-built RTC+RTM token | | `idle_timeout` | `Optional[int]` | No | Idle timeout in seconds | | `enable_string_uid` | `Optional[bool]` | No | Enable string UIDs | | `preset` | `Optional[str \| Sequence[str]]` | No | Advanced project-specific presets | | `pipeline_id` | `Optional[str]` | No | Published AI Studio pipeline ID | | `expires_in` | `Optional[int]` | No | Auto-generated token lifetime in seconds | | `debug` | `Optional[bool]` | No | Print the redacted start request | | `warn` | `Optional[Callable[[str], None]]` | No | Callback that receives SDK warning messages | ### Methods The following methods are available on both `AgentSession` and `AsyncAgentSession`. Methods that make API calls require `await` on `AsyncAgentSession`. #### `start()` Starts the agent session. Generates an RTC token if not provided, validates avatar/TTS config for cascading sessions, and calls the Agora API. MLLM sessions do not require TTS; an enabled avatar is rejected when MLLM is configured (a disabled avatar is allowed). | | Sync (`AgentSession`) | Async (`AsyncAgentSession`) | | ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- | | **Signature** | `start() -> str` | `async start() -> str` | | **Returns** | Agent ID | Agent ID | | **Raises** | `RuntimeError` if not in `idle`, `stopped`, or `error` state | Same | | **Raises** | `ValueError` if the avatar and TTS sample rates don't match, an enabled avatar is used with MLLM, or `agent_uid` isn't a numeric string when auto-generating a token | Same | | **Raises** | `ApiError` on API failure | Same | ```python # Sync agent_id = session.start() # Async agent_id = await session.start() ``` #### `stop()` Stops the agent session and removes the agent from the channel. If the agent has already stopped (404 from API), transitions to `stopped` without raising. | | Sync | Async | | ------------- | ---------------------------------------- | ---------------------- | | **Signature** | `stop() -> None` | `async stop() -> None` | | **Raises** | `RuntimeError` if not in `running` state | Same | ```python # Sync session.stop() # Async await session.stop() ``` #### `say(text, priority=None, interruptable=None)` Instructs the agent to speak the given text. | | Sync | Async | | ------------- | --------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | | **Signature** | `say(text: str, priority: Optional[str] = None, interruptable: Optional[bool] = None, *, options: Optional[SayOptions] = None) -> None` | Same with `async` | | **Raises** | `RuntimeError` if not in `running` state | Same | | Parameter | Type | Required | Description | | --------------- | ------ | -------- | -------------------------------------- | | `text` | `str` | Yes | Text to speak | | `priority` | `str` | No | `INTERRUPT`, `APPEND`, or `IGNORE` | | `interruptable` | `bool` | No | Whether the message can be interrupted | ```python # Sync session.say('One moment while I look that up.', priority='INTERRUPT', interruptable=False) # Async await session.say('One moment while I look that up.', priority='INTERRUPT', interruptable=False) ``` #### `interrupt()` Interrupts the agent while speaking or thinking. | | Sync | Async | | ------------- | ---------------------------------------- | --------------------------- | | **Signature** | `interrupt() -> None` | `async interrupt() -> None` | | **Raises** | `RuntimeError` if not in `running` state | Same | ```python # Sync session.interrupt() # Async await session.interrupt() ``` #### `update(properties)` Updates the agent configuration mid-session without restarting. Accepts a partial properties object in REST API format. | | Sync | Async | | ------------- | ---------------------------------------- | --------------------------------------- | | **Signature** | `update(properties: Any) -> None` | `async update(properties: Any) -> None` | | **Raises** | `RuntimeError` if not in `running` state | Same | ```python from agora_agent.agentkit import AgentConfigUpdate # Sync session.update(properties) # Async await session.update(properties) ``` #### `think(text, ...)` Injects a custom text instruction into the running agent. | | Sync | Async | | ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | | **Signature** | `think(text: str, *, on_listening_action=None, on_thinking_action=None, on_speaking_action=None, interruptable: Optional[bool] = None, metadata: Optional[Dict[str, str]] = None, options: Optional[ThinkOptions] = None) -> ThinkResponse` | Same with `async` | | **Raises** | `RuntimeError` if not in `running` state | Same | | Parameter | Type | Required | Description | | --------------------- | ---------------- | -------- | -------------------------------------------------------------------------------- | | `text` | `str` | Yes | The instruction text | | `on_listening_action` | `str` | No | Action when the agent is listening: `inject`, `interrupt`, `ignore`, or `append` | | `on_thinking_action` | `str` | No | Action when the agent is thinking: `interrupt`, `ignore`, or `append` | | `on_speaking_action` | `str` | No | Action when the agent is speaking: `interrupt`, `ignore`, or `append` | | `interruptable` | `bool` | No | Whether the user can interrupt the resulting response | | `metadata` | `Dict[str, str]` | No | Custom key-value metadata | In API v2.7, omitting `on_listening_action` uses the server default `interrupt`. Pass `on_listening_action='inject'` explicitly to preserve the pre-v2.7 behavior. `on_listening_action`, `on_thinking_action`, and `on_speaking_action` all accept `append`. With `append`, the instruction doesn't interrupt the current interaction. The agent waits for the current user turn, LLM inference, or TTS playback to finish, then appends the instruction to the context as a separate user message and starts a new turn. ```python session.think( 'Summarize the last answer', on_listening_action='append', on_thinking_action='append', on_speaking_action='append', ) ``` #### `get_history()` Fetches the conversation history for this session. Requires a valid agent ID — `start()` must have been called successfully. | | Sync | Async | | ------------- | ----------------------------- | ---------------------------- | | **Signature** | `get_history() -> Any` | `async get_history() -> Any` | | **Raises** | `RuntimeError` if no agent ID | Same | ```python # Sync history = session.get_history() # Async history = await session.get_history() ``` #### `get_turns(*, page_index=None, page_size=None)` Retrieves paginated turn analytics for a completed or running session. Parameters are keyword-only. Raises `RuntimeError` if there's no agent ID. Requires `await` on `AsyncAgentSession`. In v2.7, the API defaults to page 1 and up to 50 turns per page. Responses include `agent_id`, `name`, `channel`, `total_turn_count`, `pagination`, and `turns`. ```python page = session.get_turns(page_index=1, page_size=50) ``` #### `get_all_turns(*, page_size=None)` Fetches all turn pages and returns a single `GetTurnsAgentsResponse` with the combined `turns` list. ```python all_turns = session.get_all_turns(page_size=50) ``` #### `get_info()` Fetches current agent metadata from the API. Requires a valid agent ID. | | Sync | Async | | ------------- | ----------------------------- | ------------------------- | | **Signature** | `get_info() -> Any` | `async get_info() -> Any` | | **Raises** | `RuntimeError` if no agent ID | Same | ```python # Sync info = session.get_info() # Async info = await session.get_info() ``` #### `on(event, handler)` Registers an event handler. Synchronous on both `AgentSession` and `AsyncAgentSession`. Register handlers **before** calling `start()` to avoid missing the `started` event. ```python session.on('started', lambda data: print(f'Started: {data}')) ``` | Parameter | Type | Description | | --------- | --------------------- | -------------------------------------------- | | `event` | `str` | Event type: `started`, `stopped`, or `error` | | `handler` | `Callable[..., None]` | Callback function | #### `off(event, handler)` Removes a previously registered event handler. Synchronous on both `AgentSession` and `AsyncAgentSession`. ```python session.off('started', my_handler) ``` ### Properties The following read-only properties are available on both `AgentSession` and `AsyncAgentSession` instances. | Property | Type | Description | | ---------------------- | ------------------------------------------------------- | ------------------------------------------------------------------------------------------------ | | `id` | `Optional[str]` | Agent ID, populated after `start()` resolves | | `status` | `str` | Current session state: `'idle'`, `'starting'`, `'running'`, `'stopping'`, `'stopped'`, `'error'` | | `agent` | `Agent` | The agent configuration this session was created from | | `app_id` | `str` | The Agora App ID for this session | | `raw` | `AgentsClient` or `AsyncAgentsClient` | Direct access to the Fern-generated agents client for advanced operations | | `raw_agent_management` | `AgentManagementClient` or `AsyncAgentManagementClient` | Direct access to the Fern-generated agent management client | ### State transitions | Current state | Allowed actions | | ------------- | ------------------------------------------------------- | | `idle` | `start()` | | `starting` | (waiting for API) | | `running` | `stop()`, `say()`, `interrupt()`, `update()`, `think()` | | `stopping` | (waiting for API) | | `stopped` | `start()` (restart) | | `error` | `start()` (retry) | `get_history()`, `get_info()`, `get_turns()`, and `get_all_turns()` work in any state after `start()` has returned an agent ID. ## Vendors Vendor classes are exported from both `agora_agent` and `agora_agent.agentkit.vendors`. ```python from agora_agent import OpenAI, ElevenLabsTTS, DeepgramTTS, DeepgramSTT, OpenAIRealtime, XaiGrok, GenericAvatar ``` ### LLM vendors Use with [`with_llm()`](#with_llmvendor). > **Info** > > `greeting_configs` accepts either a dict or `LlmGreetingConfigs`. In v2.7, `greeting_configs.interruptable=False` makes the greeting uninterruptible; `True` follows the global `interruption` settings. #### OpenAI ```python from agora_agent import OpenAI llm = OpenAI( api_key='your-key', base_url='https://api.openai.com/v1/chat/completions', model='gpt-4o-mini', temperature=0.7, ) ``` | Parameter | Type | Required | Default | Description | | -------------------- | ---------------------- | ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_key` | `str` | No | `None` | OpenAI API key. Omit to use Agora-managed credentials for `gpt-4o-mini`, `gpt-4.1-mini`, `gpt-5-nano`, or `gpt-5-mini` | | `model` | `str` | Yes | — | Model name | | `base_url` | `str` | Conditional | `None` | API endpoint URL. Required when `api_key` is set; not allowed without it | | `temperature` | `float` | No | `None` | Sampling temperature (0.0–2.0) | | `top_p` | `float` | No | `None` | Nucleus sampling (0.0–1.0) | | `max_tokens` | `int` | No | `None` | Maximum tokens to generate | | `system_messages` | `List[Dict]` | No | `None` | Additional system messages | | `greeting_message` | `str` | No | `None` | Agent greeting message | | `failure_message` | `str` | No | `None` | Message spoken when the LLM call fails | | `max_history` | `int` | No | `None` | Maximum number of conversation history messages to cache | | `input_modalities` | `List[str]` | No | `None` | Input modalities | | `output_modalities` | `List[str]` | No | `None` | Output modalities | | `greeting_configs` | `Dict[str, Any]` | No | `None` | Greeting configuration | | `template_variables` | `Dict[str, str]` | No | `None` | Template variables for system prompt interpolation. Serialized to `llm.template_variables`, where custom tools can reference them with `{{template_variables.}}` | | `headers` | `Dict[str, str]` | No | `None` | Custom HTTP headers forwarded to the LLM provider | | `params` | `Dict[str, Any]` | No | `None` | Additional model parameters | | `vendor` | `str` | No | `None` | Vendor override | | `mcp_servers` | `List[Dict]` | No | `None` | MCP server connections | | `tools` | `List[Dict[str, Any]]` | No | `None` | Synchronous custom tool definitions the LLM can call. Accepts dictionaries or `LlmToolConfig` objects. Requires `with_tools(True)` | #### AzureOpenAI ```python from agora_agent import AzureOpenAI llm = AzureOpenAI( api_key='your-azure-key', model='gpt-4o-mini', endpoint='https://your-resource.openai.azure.com', deployment_name='gpt-4o-mini', ) ``` | Parameter | Type | Required | Default | Description | | -------------------- | ---------------------- | -------- | ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Azure OpenAI API key | | `model` | `str` | Yes | — | Azure deployment model name | | `endpoint` | `str` | Yes | — | Azure endpoint URL | | `deployment_name` | `str` | Yes | — | Azure deployment name | | `api_version` | `str` | No | `'2024-08-01-preview'` | Azure API version | | `temperature` | `float` | No | `None` | Sampling temperature (0.0–2.0) | | `top_p` | `float` | No | `None` | Nucleus sampling (0.0–1.0) | | `max_tokens` | `int` | No | `None` | Maximum tokens to generate | | `system_messages` | `List[Dict]` | No | `None` | Additional system messages | | `greeting_message` | `str` | No | `None` | Agent greeting message | | `failure_message` | `str` | No | `None` | Message spoken when the LLM call fails | | `max_history` | `int` | No | `None` | Maximum number of conversation history messages to cache | | `input_modalities` | `List[str]` | No | `None` | Input modalities | | `output_modalities` | `List[str]` | No | `None` | Output modalities | | `params` | `Dict[str, Any]` | No | `None` | Additional model parameters | | `headers` | `Dict[str, str]` | No | `None` | Custom HTTP headers forwarded to the LLM provider | | `greeting_configs` | `Dict[str, Any]` | No | `None` | Greeting configuration | | `template_variables` | `Dict[str, str]` | No | `None` | Template variables for system prompt interpolation. Serialized to `llm.template_variables`, where custom tools can reference them with `{{template_variables.}}` | | `vendor` | `str` | No | `None` | Vendor override | | `mcp_servers` | `List[Dict]` | No | `None` | MCP server connections | | `tools` | `List[Dict[str, Any]]` | No | `None` | Synchronous custom tool definitions the LLM can call. Accepts dictionaries or `LlmToolConfig` objects. Requires `with_tools(True)` | #### Anthropic ```python from agora_agent import Anthropic 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'}, ) ``` | Parameter | Type | Required | Default | Description | | -------------------- | ---------------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Anthropic API key | | `model` | `str` | Yes | — | Model name | | `url` | `str` | Yes | — | Anthropic messages endpoint URL | | `max_tokens` | `int` | Yes | — | Maximum tokens to generate | | `headers` | `Dict[str, str]` | Yes | — | Request headers, including `anthropic-version` | | `temperature` | `float` | No | `None` | Sampling temperature (0.0–1.0) | | `top_p` | `float` | No | `None` | Nucleus sampling (0.0–1.0) | | `system_messages` | `List[Dict]` | No | `None` | Additional system messages | | `greeting_message` | `str` | No | `None` | Agent greeting message | | `failure_message` | `str` | No | `None` | Message spoken when the LLM call fails | | `max_history` | `int` | No | `None` | Maximum number of conversation history messages to cache | | `input_modalities` | `List[str]` | No | `None` | Input modalities | | `output_modalities` | `List[str]` | No | `None` | Output modalities | | `params` | `Dict[str, Any]` | No | `None` | Additional model parameters | | `greeting_configs` | `Dict[str, Any]` | No | `None` | Greeting configuration | | `template_variables` | `Dict[str, str]` | No | `None` | Template variables for system prompt interpolation. Serialized to `llm.template_variables`, where custom tools can reference them with `{{template_variables.}}` | | `vendor` | `str` | No | `None` | Vendor override | | `mcp_servers` | `List[Dict]` | No | `None` | MCP server connections | | `tools` | `List[Dict[str, Any]]` | No | `None` | Synchronous custom tool definitions the LLM can call. Accepts dictionaries or `LlmToolConfig` objects. Requires `with_tools(True)` | #### Gemini ```python from agora_agent import Gemini llm = Gemini(api_key='your-google-key', model='gemini-2.0-flash-exp') ``` | Parameter | Type | Required | Default | Description | | -------------------- | ---------------------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Google AI API key | | `model` | `str` | Yes | — | Model name | | `url` | `str` | No | `None` | Custom API endpoint URL | | `temperature` | `float` | No | `None` | Sampling temperature (0.0–2.0) | | `top_p` | `float` | No | `None` | Nucleus sampling (0.0–1.0) | | `top_k` | `int` | No | `None` | Top-k sampling | | `max_output_tokens` | `int` | No | `None` | Maximum output tokens | | `system_messages` | `List[Dict]` | No | `None` | Additional system messages | | `greeting_message` | `str` | No | `None` | Agent greeting message | | `failure_message` | `str` | No | `None` | Message spoken when the LLM call fails | | `max_history` | `int` | No | `None` | Maximum number of conversation history messages to cache | | `input_modalities` | `List[str]` | No | `None` | Input modalities | | `output_modalities` | `List[str]` | No | `None` | Output modalities | | `params` | `Dict[str, Any]` | No | `None` | Additional model parameters | | `headers` | `Dict[str, str]` | No | `None` | Custom HTTP headers forwarded to the LLM provider | | `greeting_configs` | `Dict[str, Any]` | No | `None` | Greeting configuration | | `template_variables` | `Dict[str, str]` | No | `None` | Template variables for system prompt interpolation. Serialized to `llm.template_variables`, where custom tools can reference them with `{{template_variables.}}` | | `vendor` | `str` | No | `None` | Vendor override | | `mcp_servers` | `List[Dict]` | No | `None` | MCP server connections | | `tools` | `List[Dict[str, Any]]` | No | `None` | Synchronous custom tool definitions the LLM can call. Accepts dictionaries or `LlmToolConfig` objects. Requires `with_tools(True)` | #### Other LLM vendors The SDK also includes named helpers for the remaining Agora-supported LLM providers. These helpers choose the correct request format internally. | Class | Provider | Key parameters | | --------------- | --------------------- | ------------------------------------------------------ | | `Groq` | Groq | `api_key`, `model`, `base_url` | | `VertexAILLM` | Google Vertex AI | `api_key`, `model`, `project_id`, `location`, `url?` | | `AmazonBedrock` | Amazon Bedrock | `access_key`, `secret_key`, `region`, `model`, `url?` | | `Dify` | Dify | `api_key`, `url`, `model`, `user?`, `conversation_id?` | | `CustomLLM` | OpenAI-compatible LLM | `api_key`, `base_url`, `model` | These helpers also accept common LLM fields, such as `system_messages`, `greeting_message`, `failure_message`, `max_history`, `params`, and `headers`. `Groq` and `CustomLLM` use the OpenAI request style, and `VertexAILLM` uses the Gemini request style. The LLM vendor `template_variables` parameter declares fixed string values known when you create the agent. Custom tools can reference these values in `server.url`, `server.headers`, or `server.body` with `{{template_variables.}}`. The model and engine supply `{{args.}}` and `{{tool_call_id}}` at runtime, so you don't need to declare them in `template_variables`. The LLM vendor `tools` parameter declares synchronous custom tools. Each tool includes a function definition and the server request configuration. The SDK enables tool calling for `tools` and `mcp_servers` only after you call `with_tools()` or `with_tools(True)`. For more information, see [Call custom tools](/en/ai/build/tools/custom-tools). ### TTS vendors Use with [`with_tts()`](#with_ttsvendor). The `sample_rate` option determines avatar compatibility — see [`with_avatar()`](#with_avatarvendor). #### ElevenLabsTTS ```python from agora_agent.agentkit.vendors import ElevenLabsTTS ``` | Parameter | Type | Required | Default | Description | | ---------------------------- | ----------- | -------- | ------- | ------------------------------------------------ | | `key` | `str` | Yes | — | ElevenLabs API key | | `model_id` | `str` | Yes | — | Model ID, for example `'eleven_flash_v2_5'` | | `voice_id` | `str` | Yes | — | Voice ID | | `base_url` | `str` | Yes | — | WebSocket base URL | | `sample_rate` | `int` | No | `None` | Sample rate in Hz: 16000, 22050, 24000, or 44100 | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | | `optimize_streaming_latency` | `int` | No | `None` | Latency optimization level (0–4) | | `stability` | `float` | No | `None` | Voice stability (0.0–1.0) | | `similarity_boost` | `float` | No | `None` | Similarity boost (0.0–1.0) | | `style` | `float` | No | `None` | Style exaggeration (0.0–1.0) | | `use_speaker_boost` | `bool` | No | `None` | Enable speaker boost | #### MicrosoftTTS ```python from agora_agent.agentkit.vendors import MicrosoftTTS ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ----------------------------------------------- | | `key` | `str` | Yes | — | Azure subscription key | | `region` | `str` | Yes | — | Azure region, for example `'eastus'` | | `voice_name` | `str` | Yes | — | Voice name, for example `'en-US-JennyNeural'` | | `sample_rate` | `int` | No | `None` | Sample rate in Hz: 8000, 16000, 24000, or 48000 | | `speed` | `float` | No | `None` | Speaking rate multiplier | | `volume` | `float` | No | `None` | Audio volume | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional Microsoft TTS parameters | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### OpenAITTS Fixed sample rate: 24000 Hz. ```python from agora_agent.agentkit.vendors import OpenAITTS ``` | Parameter | Type | Required | Default | Description | | --------------- | ----------- | -------- | ------- | ------------------------------------------------------------------------------------------- | | `api_key` | `str` | No | `None` | OpenAI API key. Omit to use Agora-managed credentials for [supported models](/en/ai/models) | | `voice` | `str` | Yes | — | Voice name: `'alloy'`, `'echo'`, `'fable'`, `'onyx'`, `'nova'`, or `'shimmer'` | | `model` | `str` | No | `None` | Model name. Required (with `api_key` and `base_url`) for BYOK | | `base_url` | `str` | No | `None` | Endpoint URL. Required (with `api_key` and `model`) for BYOK | | `instructions` | `str` | No | `None` | Custom voice instructions | | `speed` | `float` | No | `None` | Speech speed multiplier | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### CartesiaTTS ```python from agora_agent.agentkit.vendors import CartesiaTTS ``` | Parameter | Type | Required | Default | Description | | --------------- | ----------- | -------- | ------- | ------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Cartesia API key | | `voice_id` | `str` | Yes | — | Voice ID (serialized to the `voice` `{mode, id}` object) | | `model_id` | `str` | Yes | — | Model ID | | `base_url` | `str` | No | `None` | WebSocket URL | | `language` | `str` | No | `None` | Target language | | `sample_rate` | `int` | No | `None` | Sample rate in Hz: 8000, 16000, 22050, 24000, 44100, or 48000 | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### GoogleTTS ```python from agora_agent.agentkit.vendors import GoogleTTS ``` | Parameter | Type | Required | Default | Description | | ------------------- | ----------- | -------- | ------- | ---------------------------------------------------------------------------------- | | `key` | `str` | Yes | — | Google Cloud service account credentials JSON string (serialized to `credentials`) | | `voice_name` | `str` | Yes | — | Voice name | | `language_code` | `str` | No | `None` | Language code, for example `'en-US'` | | `sample_rate_hertz` | `int` | No | `None` | Sample rate in Hz | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### AmazonTTS ```python from agora_agent.agentkit.vendors import AmazonTTS ``` | Parameter | Type | Required | Default | Description | | --------------- | ----------- | -------- | ------- | ---------------------------------------------------------------- | | `access_key` | `str` | Yes | — | AWS access key | | `secret_key` | `str` | Yes | — | AWS secret key | | `region` | `str` | Yes | — | AWS region, for example `'us-east-1'` | | `voice_id` | `str` | Yes | — | Amazon Polly voice ID | | `engine` | `str` | Yes | — | Polly engine: `standard`, `neural`, `long-form`, or `generative` | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### HumeAITTS ```python from agora_agent.agentkit.vendors import HumeAITTS ``` | Parameter | Type | Required | Default | Description | | ------------------ | ----------- | -------- | ------- | ------------------------------------------------ | | `key` | `str` | Yes | — | Hume AI API key | | `voice_id` | `str` | Yes | — | Hume AI voice ID | | `provider` | `str` | Yes | — | Voice provider type: `HUME_AI` or `CUSTOM_VOICE` | | `config_id` | `str` | No | `None` | Configuration ID | | `base_url` | `str` | No | `None` | Base URL | | `speed` | `float` | No | `None` | Playback speed | | `trailing_silence` | `float` | No | `None` | Trailing silence in seconds | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### RimeTTS ```python from agora_agent.agentkit.vendors import RimeTTS ``` | Parameter | Type | Required | Default | Description | | ----------------- | ----------- | -------- | ------- | ----------------------------------- | | `credential_mode` | `str` | No | `None` | `managed` or `byok` | | `key` | `str` | No | `None` | Rime API key | | `speaker` | `str` | No | `None` | Speaker ID | | `model_id` | `str` | No | `None` | Model ID | | `base_url` | `str` | No | `None` | WebSocket URL | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | In `byok` mode (default), `key`, `speaker`, and `model_id` are required. In `managed` mode, `base_url` and `model_id` are required. #### FishAudioTTS ```python from agora_agent.agentkit.vendors import FishAudioTTS ``` | Parameter | Type | Required | Default | Description | | --------------- | ----------- | -------- | ------- | ------------------------------------------------- | | `key` | `str` | Yes | — | Fish Audio API key | | `reference_id` | `str` | Yes | — | Reference ID | | `backend` | `str` | Yes | — | Backend model version, for example `'speech-1.5'` | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### MiniMaxTTS ```python from agora_agent.agentkit.vendors import MiniMaxTTS ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ----------------------------------------------------------------- | | `model` | `str` | Yes | — | Model name, for example `'speech-02-turbo'` | | `key` | `str` | No | `None` | MiniMax API key. Required for BYOK; omit for preset-backed models | | `group_id` | `str` | No | `None` | MiniMax group ID. Required for BYOK | | `voice_id` | `str` | No | `None` | Voice style identifier (provide `voice_id` or `timber_weights`) | | `url` | `str` | No | `None` | WebSocket endpoint (BYOK) | | `speed` | `float` | No | `None` | Speaking speed | | `vol` | `float` | No | `None` | Volume gain | | `pitch` | `float` | No | `None` | Pitch adjustment | | `emotion` | `str` | No | `None` | Emotion style | | `sample_rate` | `int` | No | `None` | Output sample rate in Hz | | `language_boost` | `str` | No | `None` | Language boost strategy | | `timber_weights` | `List[Dict]` | No | `None` | Alternative timbre mix config | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional MiniMax TTS parameters | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### DeepgramTTS ```python from agora_agent.agentkit.vendors import DeepgramTTS ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ----------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Deepgram API key | | `model` | `str` | Yes | — | Model name, for example `'aura-2-thalia-en'` | | `base_url` | `str` | No | `None` | WebSocket endpoint. Defaults server-side to `wss://api.deepgram.com/v1/speak` | | `sample_rate` | `int` | No | `None` | Sample rate in Hz | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional Deepgram TTS parameters | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### MurfTTS ```python from agora_agent.agentkit.vendors import MurfTTS ``` | Parameter | Type | Required | Default | Description | | --------------- | ----------- | -------- | ------- | ----------------------------------------------- | | `key` | `str` | Yes | — | Murf API key | | `voice_id` | `str` | No | `None` | Voice ID, for example `'Ariana'` or `'Natalie'` | | `base_url` | `str` | No | `None` | WebSocket endpoint | | `locale` | `str` | No | `None` | Voice locale | | `rate` | `float` | No | `None` | Speech rate | | `pitch` | `float` | No | `None` | Pitch adjustment | | `model` | `str` | No | `None` | TTS model | | `sample_rate` | `int` | No | `None` | Audio sample rate | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### SarvamTTS ```python from agora_agent.agentkit.vendors import SarvamTTS ``` | Parameter | Type | Required | Default | Description | | ---------------------- | ----------- | -------- | ------- | ----------------------------------- | | `key` | `str` | Yes | — | Sarvam API key | | `speaker` | `str` | Yes | — | Speaker name | | `target_language_code` | `str` | Yes | — | Target language code | | `pitch` | `float` | No | `None` | Pitch adjustment | | `pace` | `float` | No | `None` | Speed of speech | | `loudness` | `float` | No | `None` | Volume level | | `sample_rate` | `int` | No | `None` | Audio sample rate in Hz | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### TypecastTTS ```python from agora_agent.agentkit.vendors import TypecastTTS ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------------------- | | `api_key` | `str` | Yes | — | Typecast API key | | `voice_id` | `str` | Yes | — | Typecast voice identifier | | `model` | `str` | Yes | — | Typecast TTS model name, for example `'ssfm-v30'` | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional Typecast parameters | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### GradiumTTS ```python from agora_agent.agentkit.vendors import GradiumTTS ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------------- | | `api_key` | `str` | Yes | — | Gradium API key | | `url` | `str` | No | `None` | WebSocket endpoint for streaming TTS output | | `model_name` | `str` | No | `None` | Gradium TTS model name | | `voice_id` | `str` | No | `None` | Gradium voice identifier | | `sample_rate` | `int` | No | `None` | Audio sample rate in Hz | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional Gradium TTS parameters | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### MistralTTS ```python from agora_agent.agentkit.vendors import MistralTTS ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ----------------------------------- | | `api_key` | `str` | Yes | — | Mistral API key | | `model` | `str` | No | `None` | Mistral TTS model name | | `voice` | `str` | No | `None` | Mistral voice identifier | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional Mistral TTS parameters | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### GenericTTS Custom OpenAI-compatible HTTP TTS. `url` is required and must be an HTTP or HTTPS endpoint that includes a host. An invalid URL format, or a non-HTTP(S) scheme such as `ws` or `wss`, raises a `ValueError`. A valid URL is serialized as `tts.vendor = "generic_http"`. ```python from agora_agent import GenericTTS ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | `str` | Yes | — | The HTTP(S) endpoint of your custom TTS service | | `headers` | `Dict[str, str]` | No | `None` | Custom HTTP headers to forward to the TTS service. Omitted from the request if not set | | `api_key` | `str` | No | `None` | The API key used to authenticate with the TTS service | | `model` | `str` | No | `None` | The TTS model name | | `voice` | `str` | No | `None` | The voice name | | `speed` | `float` | No | `None` | The speech rate | | `sample_rate` | `int` | No | `None` | The sample rate, in Hz, of the output audio. If your TTS service doesn't support multiple sample rates, make sure the returned audio's sample rate matches this value | | `response_format` | `str` | No | `None` | The output audio format. Conversational AI Engine currently supports `pcm` | | `instruction` | `str` | No | `None` | Instructions for voice style, emotion, or other playback directives | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters passed through to the TTS service. Explicit fields with the same name take precedence | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### XaiTTS ```python from agora_agent.agentkit.vendors import XaiTTS ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ----------------------------------------- | | `api_key` | `str` | Yes | — | xAI API key | | `language` | `str` | Yes | — | BCP-47 language code for speech synthesis | | `voice_id` | `str` | No | `None` | xAI voice identifier | | `sample_rate` | `int` | No | `None` | Audio sample rate in Hz | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional xAI TTS parameters | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | #### SmallestAITTS ```python from agora_agent.agentkit.vendors import SmallestAITTS ``` | Parameter | Type | Required | Default | Description | | ------------------------------- | ---------------- | -------- | ------- | -------------------------------------------------- | | `api_key` | `str` | Yes | — | Smallest AI API key | | `url` | `str` | No | `None` | Streaming TTS endpoint | | `model` | `str` | No | `None` | TTS model name, for example `'lightning_v3.1_pro'` | | `voice_id` | `str` | No | `None` | Voice identifier, for example `'hazel'` | | `sample_rate` | `int` | No | `None` | Output audio sample rate in Hz | | `speed` | `float` | No | `None` | Speech rate multiplier | | `language` | `str` | No | `None` | Language code for speech synthesis | | `number_pronunciation_language` | `str` | No | `None` | Language code used when reading numbers aloud | | `math_notation` | `bool` | No | `None` | Read mathematical notation as spoken mathematics | | `pronunciation_dicts` | `List[str]` | No | `None` | Pronunciation dictionaries to apply | | `session_id` | `str` | No | `None` | Caller-supplied session identifier | | `request_id` | `str` | No | `None` | Caller-supplied request identifier | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional Smallest AI parameters | | `skip_patterns` | `List[int]` | No | `None` | Skip patterns for bracketed content | Voice identifiers are model-specific, so `voice_id` must belong to the model set in `model`. For details, see [Smallest AI](/en/ai/models/tts/smallest-ai). ### STT vendors Use with [`with_stt()`](#with_sttvendor). #### DeepgramSTT `api_key` is required unless `model` is an Agora-managed model (`nova-2` or `nova-3`). ```python from agora_agent.agentkit.vendors import DeepgramSTT ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | --------------------------------------------------------------------------------------------- | | `api_key` | `str` | No | `None` | Deepgram API key. Omit to use Agora-managed credentials for [supported models](/en/ai/models) | | `model` | `str` | No | `None` | Model name, for example `'nova-2'` | | `language` | `str` | No | `None` | Language code, for example `'en-US'` | | `keyterm` | `str` | No | `None` | Boost specialized terms and brands | | `smart_format` | `bool` | No | `None` | Enable smart formatting | | `punctuation` | `bool` | No | `None` | Enable punctuation | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional vendor parameters | #### SpeechmaticsSTT ```python from agora_agent.agentkit.vendors import SpeechmaticsSTT ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ----------------------------------------------------- | | `key` | `str` | Yes | — | Speechmatics API key. `api_key` is a deprecated alias | | `language` | `str` | Yes | — | Language code, for example `'en'` | | `model` | `str` | No | `None` | Model name | | `uri` | `str` | No | `None` | Speechmatics streaming WebSocket URL | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | #### MicrosoftSTT ```python from agora_agent.agentkit.vendors import MicrosoftSTT ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------ | | `key` | `str` | Yes | — | Azure subscription key | | `region` | `str` | Yes | — | Azure region, for example `'eastus'` | | `language` | `str` | Yes | — | Language code, for example `'en-US'` | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | #### OpenAISTT ```python from agora_agent.agentkit.vendors import OpenAISTT ``` | Parameter | Type | Required | Default | Description | | --------------------------- | ---------------- | -------- | ------- | ------------------------------------------------------------- | | `api_key` | `str` | Yes | — | OpenAI API key | | `model` | `str` | No | `None` | Transcription model. Default: `'gpt-4o-mini-transcribe'` | | `language` | `str` | No | `None` | Language code | | `prompt` | `str` | No | `None` | Prompt that guides transcription | | `input_audio_transcription` | `Dict[str, Any]` | No | `None` | OpenAI transcription settings (`model`, `prompt`, `language`) | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | The serialized configuration requires a transcription `prompt` and `language` — provide them through the `prompt` and `language` parameters or within `input_audio_transcription`. `model` defaults to `gpt-4o-mini-transcribe`. #### GoogleSTT ```python from agora_agent.agentkit.vendors import GoogleSTT ``` | Parameter | Type | Required | Default | Description | | ------------------------ | ---------------- | -------- | ------- | ---------------------------------------------- | | `project_id` | `str` | Yes | — | Google Cloud project ID | | `location` | `str` | Yes | — | Google Cloud region | | `adc_credentials_string` | `str` | Yes | — | Google service account credentials JSON string | | `language` | `str` | Yes | — | Language code, for example `'en-US'` | | `model` | `str` | No | `None` | Recognition model | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | #### AmazonSTT ```python from agora_agent.agentkit.vendors import AmazonSTT ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------- | | `access_key` | `str` | Yes | — | AWS access key ID | | `secret_key` | `str` | Yes | — | AWS secret access key | | `region` | `str` | Yes | — | AWS region, for example `'us-east-1'` | | `language` | `str` | Yes | — | Language code | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | #### AssemblyAISTT ```python from agora_agent.agentkit.vendors import AssemblyAISTT ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ---------------------------------- | | `api_key` | `str` | Yes | — | AssemblyAI API key | | `language` | `str` | Yes | — | Language code | | `ws_url` | `str` | No | `None` | AssemblyAI streaming WebSocket URL | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | #### AresSTT ```python from agora_agent.agentkit.vendors import AresSTT ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | -------------------------------------------------- | | `keywords` | `List[str]` | No | `None` | Keywords that improve ASR accuracy | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters. Must not contain `keywords` | #### GeminiSTT ```python from agora_agent.agentkit.vendors import GeminiSTT ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Google API key | | `model` | `str` | No | `None` | Transcription model. Defaults to `gemini-3.5-transcribe-live` | | `language` | `str` | No | `None` | Recognition language | | `language_hints` | `List[str]` | No | `None` | Candidate transcription languages. `language_codes` is a deprecated alias | | `custom_vocabulary` | `List[str]` | No | `None` | Words and phrases to bias recognition toward | | `word_timestamp` | `bool` | No | `None` | Enable word-level timestamps | | `mode` | `str` | No | `None` | Transcript formatting mode: `SMART` or `VERBATIM` | | `diarization` | `bool` | No | `None` | Enable speaker labels | | `sample_rate` | `int` | No | `None` | Audio sample rate in Hz. Defaults to `16000` | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | #### XaiSTT ```python from agora_agent.agentkit.vendors import XaiSTT ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ----------------------- | | `api_key` | `str` | Yes | — | xAI API key | | `base_url` | `str` | No | `None` | API endpoint URL | | `language` | `str` | No | `None` | Language code | | `sample_rate` | `int` | No | `None` | Audio sample rate in Hz | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | #### SarvamSTT ```python from agora_agent.agentkit.vendors import SarvamSTT ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------------- | | `api_key` | `str` | Yes | — | Sarvam API key | | `language` | `str` | Yes | — | Language code, for example `'en'` or `'hi'` | | `model` | `str` | No | `None` | Model name | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | #### SmallestAISTT ```python from agora_agent.agentkit.vendors import SmallestAISTT ``` | Parameter | Type | Required | Default | Description | | --------------------- | ---------------- | -------- | ------- | ---------------------------------------------------------- | | `api_key` | `str` | Yes | — | Smallest AI API key | | `language` | `str` | No | `None` | Language code for speech recognition | | `url` | `str` | No | `None` | Streaming ASR WebSocket endpoint | | `sample_rate` | `int` | No | `None` | Input audio sample rate in Hz | | `encoding` | `str` | No | `None` | Input audio encoding, for example `'linear16'` | | `word_timestamps` | `bool` | No | `None` | Include word-level timestamps | | `sentence_timestamps` | `bool` | No | `None` | Include sentence-level timestamps | | `diarize` | `bool` | No | `None` | Enable speaker diarization | | `vad_events` | `bool` | No | `None` | Emit voice activity detection events | | `endpointing` | `bool` | No | `None` | Enable automatic end-of-utterance detection | | `eou_timeout_ms` | `int` | No | `None` | End-of-utterance timeout in milliseconds | | `format` | `bool` | No | `None` | Enable Smallest AI's transcript formatting | | `finalize_on_words` | `bool` | No | `None` | Finalize results based on word count | | `max_words` | `str` | No | `None` | Maximum words per result, as a string | | `punctuate` | `bool` | No | `None` | Add punctuation to results | | `capitalize` | `bool` | No | `None` | Apply capitalization to results | | `itn_normalize` | `bool` | No | `None` | Apply inverse text normalization | | `full_transcript` | `bool` | No | `None` | Return the full accumulated transcript | | `keywords` | `str` | No | `None` | Keyword boosts, comma-separated in `keyword:weight` format | | `redact_pii` | `bool` | No | `None` | Redact personally identifiable information | | `redact_pci` | `bool` | No | `None` | Redact payment card information | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional Smallest AI parameters | Boolean options are serialized as the strings `"true"` or `"false"` for the Smallest AI wire protocol. For details, see [Smallest AI](/en/ai/models/asr/smallest-ai). ### MLLM vendors Use with [`with_mllm()`](#with_mllmvendor) for multimodal end-to-end audio processing without separate STT or TTS steps. Calling `with_mllm()` automatically enables the MLLM module (sets `mllm.enable=true`); the older `advanced_features.enable_mllm` flag is deprecated. #### OpenAIRealtime ```python from agora_agent.agentkit.vendors import OpenAIRealtime ``` | Parameter | Type | Required | Default | Description | | --------------------------- | ------------------------- | -------- | ------------------------------------ | ----------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | OpenAI API key | | `model` | `str` | No | `None` | Model name, for example `'gpt-4o-realtime-preview'` | | `voice` | `str` | No | `None` | Voice identifier | | `instructions` | `str` | No | `None` | System instructions | | `input_audio_transcription` | `Dict[str, Any]` | No | `None` | Audio transcription settings | | `url` | `str` | No | `'wss://api.openai.com/v1/realtime'` | Custom WebSocket URL | | `greeting_message` | `str` | No | `None` | Agent greeting message | | `failure_message` | `str` | No | `None` | Message played when the model call fails | | `input_modalities` | `List[str]` | No | `None` | Input modalities, for example `['audio']` | | `output_modalities` | `List[str]` | No | `None` | Output modalities, for example `['text', 'audio']` | | `messages` | `List[Dict]` | No | `None` | Conversation messages for short-term memory | | `params` | `Dict[str, Any]` | No | `None` | Additional parameters | | `turn_detection` | `MllmTurnDetectionConfig` | No | `None` | MLLM turn detection configuration; overrides top-level `turn_detection` | #### AzureOpenAIRealtime ```python from agora_agent.agentkit.vendors import AzureOpenAIRealtime ``` | Parameter | Type | Required | Default | Description | | --------------------------- | ------------------------- | -------- | ------- | ----------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Azure OpenAI API key | | `url` | `str` | Yes | — | Azure OpenAI Realtime WebSocket URL | | `turn_detection` | `MllmTurnDetectionConfig` | Yes | — | MLLM turn detection configuration; overrides top-level `turn_detection` | | `model` | `str` | No | `None` | Azure OpenAI Realtime model or deployment name | | `voice` | `str` | No | `None` | Voice identifier | | `instructions` | `str` | No | `None` | System instructions | | `input_audio_transcription` | `Dict[str, Any]` | No | `None` | Audio transcription settings | | `max_history` | `int` | No | `None` | Number of conversation history messages to cache | | `greeting_message` | `str` | No | `None` | Agent greeting message | | `failure_message` | `str` | No | `None` | Message played when the model call fails | | `output_modalities` | `List[str]` | No | `None` | Output modalities, for example `['text', 'audio']` | | `messages` | `List[Dict]` | No | `None` | Conversation messages for short-term memory | | `params` | `Dict[str, Any]` | No | `None` | Additional Azure OpenAI parameters | #### GeminiLive ```python from agora_agent.agentkit.vendors import GeminiLive ``` | Parameter | Type | Required | Default | Description | | ------------------- | ------------------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Google Gemini API key | | `model` | `str` | Yes | — | Gemini Live model name | | `thinking_level` | `str` | No | `None` | Reasoning budget (`'low'`, `'medium'`, or `'high'`), supported only by `'models/gemini-3.8-live-extended-thinking'` | | `url` | `str` | No | `None` | Custom WebSocket URL | | `instructions` | `str` | No | `None` | System instructions | | `voice` | `str` | No | `None` | Voice name | | `affective_dialog` | `bool` | No | `None` | Enable affective dialog | | `proactive_audio` | `bool` | No | `None` | Enable proactive audio | | `transcribe_agent` | `bool` | No | `None` | Transcribe agent speech | | `transcribe_user` | `bool` | No | `None` | Transcribe user speech | | `http_options` | `Dict[str, Any]` | No | `None` | HTTP options | | `greeting_message` | `str` | No | `None` | Agent greeting message | | `failure_message` | `str` | No | `None` | Message played when the model call fails | | `input_modalities` | `List[str]` | No | `None` | Input modalities | | `output_modalities` | `List[str]` | No | `None` | Output modalities | | `messages` | `List[Dict]` | No | `None` | Conversation messages for short-term memory | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | | `turn_detection` | `MllmTurnDetectionConfig` | No | `None` | MLLM turn detection configuration; overrides top-level `turn_detection` | #### VertexAI ```python from agora_agent.agentkit.vendors import VertexAI ``` | Parameter | Type | Required | Default | Description | | ------------------------ | ------------------------- | -------- | ------- | ----------------------------------------------------------------------- | | `model` | `str` | Yes | — | Model name, for example `'gemini-2.0-flash-exp'` | | `project_id` | `str` | Yes | — | Google Cloud project ID | | `location` | `str` | Yes | — | Google Cloud location, for example `'us-central1'` | | `adc_credentials_string` | `str` | Yes | — | Application Default Credentials JSON string | | `url` | `str` | No | `None` | Custom WebSocket URL | | `instructions` | `str` | No | `None` | System instructions for the model | | `voice` | `str` | No | `None` | Voice name, for example `'Aoede'` or `'Charon'` | | `affective_dialog` | `bool` | No | `None` | Enable affective dialog | | `proactive_audio` | `bool` | No | `None` | Enable proactive audio | | `transcribe_agent` | `bool` | No | `None` | Transcribe agent speech | | `transcribe_user` | `bool` | No | `None` | Transcribe user speech | | `http_options` | `Dict[str, Any]` | No | `None` | HTTP options | | `greeting_message` | `str` | No | `None` | Agent greeting message | | `failure_message` | `str` | No | `None` | Message played when the model call fails | | `input_modalities` | `List[str]` | No | `None` | Input modalities | | `output_modalities` | `List[str]` | No | `None` | Output modalities | | `messages` | `List[Dict]` | No | `None` | Conversation messages for short-term memory | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional parameters | | `turn_detection` | `MllmTurnDetectionConfig` | No | `None` | MLLM turn detection configuration; overrides top-level `turn_detection` | #### XaiGrok [xAI Grok](/en/ai/models/mllm/xai) MLLM vendor (`mllm.vendor`: `"xai"`). | Parameter | Type | Required | Default | Description | | ------------------- | ------------------------- | -------- | ---------------------------- | --------------------------------------------- | | `api_key` | `str` | Yes | — | xAI API key | | `url` | `str` | No | `wss://api.x.ai/v1/realtime` | xAI Realtime WebSocket URL | | `voice` | `str` | No | `None` | Voice identifier, for example `eve` or `rex` | | `language` | `str` | No | `None` | Language code, for example `en` | | `sample_rate` | `int` | No | `None` | Audio sample rate in Hz | | `greeting_message` | `str` | No | `None` | Greeting message | | `failure_message` | `str` | No | `None` | Message played when the model call fails | | `input_modalities` | `List[str]` | No | `None` | Input modalities | | `output_modalities` | `List[str]` | No | `None` | Output modalities | | `messages` | `List[Dict]` | No | `None` | Conversation messages | | `params` | `Dict[str, Any]` | No | `None` | Additional xAI parameters | | `turn_detection` | `MllmTurnDetectionConfig` | No | `None` | Supports `agora_vad` and `server_vad` for xAI | #### OpenAIGPTLive [OpenAI GPT-Live](/en/ai/models/mllm/openai-gpt-live) MLLM vendor (`mllm.vendor`: `"openai_gpt_live"`). `with_mllm()` raises `ValueError` if `url` isn't a full `ws://` or `wss://` endpoint, `headers` isn't a JSON object string, `delegation` isn't `client` or `responses`, or `session_params` overrides a protected field. > **Caution: Early access** > > OpenAI GPT-Live is available in early access and isn't intended for production traffic. The SDK automatically routes sessions that use this vendor to the preview endpoint. GPT-Live doesn't support turn detection or input audio transcription. ```python from agora_agent import OpenAIGPTLive 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', ) ``` | Parameter | Type | Required | Default | Description | | ------------------------ | ---------------------- | -------- | ------- | ----------------------------------------------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | OpenAI API key | | `model` | `str` | No | `None` | Model name. Defaults to `gpt-live-1` | | `voice` | `str` | No | `None` | Output voice. Provider default: `marin` | | `prompt` | `str` | No | `None` | Session instructions that define the assistant's behavior | | `greeting` | `str` | No | `None` | Greeting the agent speaks when a user joins. Serialized as `greeting_message` | | `failure_message` | `str` | No | `None` | Message played when the model call fails | | `url` | `str` | No | `None` | Full `ws://` or `wss://` endpoint. Defaults to `wss://api.openai.com/v1/live/sessions` | | `base_url` | `str` | No | `None` | Host used when `url` is omitted. Defaults to `wss://api.openai.com` | | `path` | `str` | No | `None` | WebSocket path used when `url` is omitted. Defaults to `/v1/live/sessions` | | `input_modalities` | `List[str]` | No | `None` | Input modalities | | `output_modalities` | `List[str]` | No | `None` | Output modalities | | `messages` | `List[Dict[str, Any]]` | No | `None` | Conversation history passed to the model as context | | `mcp_servers` | `List[Dict[str, Any]]` | No | `None` | MCP servers whose tools GPT-Live can call. Requires `with_tools(True)` | | `tool_enabled` | `bool` | No | `None` | Advertise the agent's tools to GPT-Live. Provider default: `false` | | `delegation` | `str` | No | `None` | Tool delegation mode: `client` or `responses`. Provider default: `responses`. Can't be changed during the session | | `responses_model` | `str` | No | `None` | Model used for delegated tool calls | | `interrupt_on_user_turn` | `bool` | No | `None` | Interrupt playback when the user speaks. Provider default: `false` | | `output_idle_end_ms` | `int` | No | `None` | Agent silence boundary in milliseconds. Provider default: `600`. `0` disables inference | | `input_idle_end_ms` | `int` | No | `None` | User silence boundary in milliseconds. Provider default: `1500` | | `output_silence_peak` | `int` | No | `None` | Speech amplitude threshold on the 16-bit scale. Provider default: `50` | | `output_sample_rate` | `int` | No | `None` | Output PCM sample rate in Hz. Provider default: `24000` | | `output_buffer_ms` | `int` | No | `None` | Initial audio cushion in milliseconds. Provider default: `0`. A negative value disables pacing | | `input_batch_ms` | `int` | No | `None` | Microphone audio batching interval in milliseconds | | `alpha_selector` | `str` | No | `None` | OpenAI-Alpha selector for preview contracts. Omitted when not set | | `headers` | `str` | No | `None` | Extra provider request headers, as a JSON object string | | `session_params` | `Dict[str, Any]` | No | `None` | Additional session fields. Can't override `model`, `delegation`, `audio`, `instructions`, or `input` | | `params` | `Dict[str, Any]` | No | `None` | Additional provider parameters. Explicit options take precedence | | `instructions` | `str` | No | `None` | Deprecated. Use `prompt` instead | `input_audio_transcription` and `turn_detection` are deprecated and accepted only for compatibility. GPT-Live doesn't support them: setting `input_audio_transcription` raises `ValueError`, and the SDK ignores `turn_detection` and logs a warning. ### Avatar vendors Use with [`with_avatar()`](#with_avatarvendor). Some avatar vendors require a specific TTS sample rate, enforced at runtime. #### HeyGenAvatar **Deprecated — renamed to [`LiveAvatarAvatar`](#liveavataravatar).** `HeyGenAvatar` still works (serializes `vendor: "heygen"`) but emits a deprecation warning. Use `LiveAvatarAvatar` for new code. Requires TTS at **24,000 Hz**. ```python from agora_agent.agentkit.vendors import HeyGenAvatar ``` | Parameter | Type | Required | Default | Description | | ----------------------- | ------ | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------ | | `api_key` | `str` | Yes | — | HeyGen API key | | `quality` | `str` | Yes | — | Video quality: `'low'`, `'medium'`, or `'high'` | | `agora_uid` | `str` | Yes | — | Agora UID for the avatar video stream | | `agora_token` | `str` | No | `None` | Avatar token. When omitted, `AgentSession.start()` generates one for `agora_uid` using the same token path as the agent. | | `avatar_id` | `str` | No | `None` | HeyGen avatar ID | | `enable` | `bool` | No | `True` | Enable or disable the avatar | | `disable_idle_timeout` | `bool` | No | `None` | Disable the idle timeout | | `activity_idle_timeout` | `int` | No | `None` | Idle timeout in seconds. Default: 120 | #### AkoolAvatar Requires TTS at **16,000 Hz**. ```python from agora_agent.agentkit.vendors import AkoolAvatar ``` | Parameter | Type | Required | Default | Description | | ----------- | ------ | -------- | ------- | ---------------------------- | | `api_key` | `str` | Yes | — | Akool API key | | `avatar_id` | `str` | No | `None` | Avatar ID | | `enable` | `bool` | No | `True` | Enable or disable the avatar | #### LiveAvatarAvatar Required TTS sample rate: **24000 Hz** Same options as [`HeyGenAvatar`](#heygenavatar), but serializes `vendor: "liveavatar"`. `agora_token` is optional and generated by `AgentSession.start()` when omitted. #### AnamAvatar ```python from agora_agent.agentkit.vendors import AnamAvatar ``` | Parameter | Type | Required | Default | Description | | ----------- | ------ | -------- | ------- | ---------------------------- | | `api_key` | `str` | Yes | — | Anam API key | | `avatar_id` | `str` | Yes | — | Anam avatar ID | | `enable` | `bool` | No | `True` | Enable or disable the avatar | #### GenericAvatar ```python from agora_agent.agentkit.vendors import GenericAvatar ``` | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Generic avatar provider API key | | `agora_uid` | `str` | Yes | — | Avatar RTC UID. Must differ from the agent UID. | | `api_base_url` | `str` | Yes | — | Avatar provider API base URL | | `avatar_id` | `str` | Yes | — | Avatar ID | | `agora_token` | `str` | No | `None` | Optional avatar token. Generated by `AgentSession.start()` when omitted. | | `agora_appid` | `str` | No | `None` | Optional; filled from the session App ID when omitted. | | `agora_channel` | `str` | No | `None` | Optional; filled from the session channel when omitted. | | `enable` | `bool` | No | `True` | Enable or disable the avatar | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional vendor parameters. Explicit parameters take precedence over matching keys. | Avatar tokens are separate from the agent join token but generated with the same `generate_convo_ai_token` path, using the avatar's `agora_uid` as `uid`. #### Tavus ```python from agora_agent.agentkit.vendors import Tavus ``` Serializes `vendor: "generic"`. For the endpoint and a full example, see [Tavus](/en/ai/models/avatar/tavus). | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Tavus API key | | `agora_uid` | `str` | Yes | — | Avatar RTC UID. Must differ from the agent UID. | | `api_base_url` | `str` | Yes | — | Tavus API base URL | | `avatar_id` | `str` | Yes | — | Tavus avatar ID | | `agora_token` | `str` | No | `None` | Optional avatar token. Generated by `AgentSession.start()` when omitted. | | `agora_appid` | `str` | No | `None` | Optional; filled from the session App ID when omitted. | | `agora_channel` | `str` | No | `None` | Optional; filled from the session channel when omitted. | | `enable` | `bool` | No | `True` | Enable or disable the avatar | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional vendor parameters. Explicit parameters take precedence over matching keys. | #### Protoface ```python from agora_agent.agentkit.vendors import Protoface ``` Serializes `vendor: "generic"`. For the endpoint and a full example, see [Protoface](/en/ai/models/avatar/protoface). | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | Protoface API key | | `agora_uid` | `str` | Yes | — | Avatar RTC UID. Must differ from the agent UID. | | `api_base_url` | `str` | Yes | — | Protoface API base URL | | `avatar_id` | `str` | Yes | — | Protoface avatar ID | | `agora_token` | `str` | No | `None` | Optional avatar token. Generated by `AgentSession.start()` when omitted. | | `agora_appid` | `str` | No | `None` | Optional; filled from the session App ID when omitted. | | `agora_channel` | `str` | No | `None` | Optional; filled from the session channel when omitted. | | `enable` | `bool` | No | `True` | Enable or disable the avatar | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional vendor parameters. Explicit parameters take precedence over matching keys. | #### LemonSlice ```python from agora_agent.agentkit.vendors import LemonSlice ``` Serializes `vendor: "generic"`. For the endpoint and a full example, see [LemonSlice](/en/ai/models/avatar/lemonslice). | Parameter | Type | Required | Default | Description | | ------------------- | ---------------- | -------- | ------- | ------------------------------------------------------------------------------------- | | `api_key` | `str` | Yes | — | LemonSlice API key | | `agora_uid` | `str` | Yes | — | Avatar RTC UID. Must differ from the agent UID. | | `api_base_url` | `str` | Yes | — | LemonSlice API base URL | | `avatar_id` | `str` | Yes | — | Always `lemonslice` | | `agora_token` | `str` | No | `None` | Optional avatar token. Generated by `AgentSession.start()` when omitted. | | `agora_appid` | `str` | No | `None` | Optional; filled from the session App ID when omitted. | | `agora_channel` | `str` | No | `None` | Optional; filled from the session channel when omitted. | | `enable` | `bool` | No | `True` | Enable or disable the avatar | | `additional_params` | `Dict[str, Any]` | No | `None` | Additional vendor parameters. Explicit parameters take precedence over matching keys. | ## Token utilities Helper functions for generating and managing tokens. Use these when you need control over token lifetime or when generating tokens outside of a session. ```python from agora_agent.agentkit.token import generate_convo_ai_token, generate_rtc_token from agora_agent.agentkit import expires_in_hours, expires_in_minutes ``` ### `generate_convo_ai_token()` Generates a Conversational AI token combining RTC and RTM privileges. This is the same token the SDK generates automatically in app-credentials mode. Use this when passing a pre-built token to [`create_session()`](#create_session). ```python generate_convo_ai_token( app_id: str, app_certificate: str, channel_name: str, uid: int, token_expire: int = 86400, privilege_expire: int = 0, ) -> str ``` | Parameter | Type | Required | Default | Description | | ------------------ | ----- | -------- | ------- | ----------------------------------------------------------------- | | `app_id` | `str` | Yes | — | Agora App ID | | `app_certificate` | `str` | Yes | — | Agora App Certificate | | `channel_name` | `str` | Yes | — | The channel the token grants access to | | `uid` | `int` | Yes | — | Numeric RTC UID the token is issued for | | `token_expire` | `int` | No | `86400` | Token lifetime in seconds. Valid range: 1–86400 | | `privilege_expire` | `int` | No | `0` | Seconds until privileges expire. `0` means same as `token_expire` | **Returns:** `str` — the generated token. **Raises:** `ValueError` if `app_id` or `app_certificate` isn't exactly 32 characters. `TypeError` if `uid` isn't an `int`. ```python from agora_agent.agentkit.token import generate_convo_ai_token from agora_agent.agentkit import expires_in_hours token = generate_convo_ai_token( app_id='your-app-id', app_certificate='your-app-certificate', channel_name='support-room-123', uid=1, token_expire=expires_in_hours(12), ) ``` ### `generate_rtc_token()` Generates an RTC-only token for channel join. Use `generate_convo_ai_token()` instead for most Conversational AI use cases. ```python generate_rtc_token( app_id: str, app_certificate: str, channel: str, uid: int, role: int = 1, expiry_seconds: int = 86400, ) -> str ``` | Parameter | Type | Required | Default | Description | | ----------------- | ----- | -------- | ------- | ----------------------------------------------- | | `app_id` | `str` | Yes | — | Agora App ID | | `app_certificate` | `str` | Yes | — | Agora App Certificate | | `channel` | `str` | Yes | — | Channel name | | `uid` | `int` | Yes | — | User ID. Use `0` for any user | | `role` | `int` | No | `1` | RTC role: `1` for publisher, `2` for subscriber | | `expiry_seconds` | `int` | No | `86400` | Token lifetime in seconds. Valid range: 1–86400 | **Returns:** `str` — the generated token. **Raises:** `ValueError` if `app_id` or `app_certificate` isn't exactly 32 characters. ### `expires_in_hours()` / `expires_in_minutes()` Helper functions for specifying token lifetimes. Use with [`create_session()`](#create_session) or token generation functions. Values are validated and capped at the Agora maximum of 86400 seconds (24 hours). ```python expires_in_hours(hours: float) -> int expires_in_minutes(minutes: float) -> int ``` | Function | Returns | Behavior | | ----------------------- | --------------- | ------------------------------------------------------------------------------ | | `expires_in_hours(n)` | `int` — seconds | Raises `ValueError` if `n` ≤ 0. Warns and caps at 86400 if result exceeds 24 h | | `expires_in_minutes(n)` | `int` — seconds | Raises `ValueError` if `n` ≤ 0. Warns and caps at 86400 if result exceeds 24 h | ```python from agora_agent.agentkit import expires_in_hours, expires_in_minutes session = agent.create_session( channel='support-room-123', agent_uid='1', remote_uids=['100'], expires_in=expires_in_hours(12), ) ``` ## Types and enums Shared types and enums used across `Agora`, `AsyncAgora`, `Agent`, `AgentSession`, and vendor classes. ### `Area` Region used for API routing. Pass to `Agora` or `AsyncAgora` via the `area` parameter. ```python from agora_agent import Area ``` | Value | Region | | --------- | -------------- | | `Area.US` | United States | | `Area.EU` | Europe | | `Area.AP` | Asia-Pacific | | `Area.CN` | China mainland | ### Session events Event names for `session.on()` and `session.off()` are plain strings: `'started'`, `'stopped'`, and `'error'`. | Value | Payload | Description | | ----------- | --------------------------- | ------------------------------------- | | `'started'` | `dict` with `agent_id: str` | Agent successfully joined the channel | | `'stopped'` | `dict` with `agent_id: str` | Agent left the channel | | `'error'` | `Exception` | An unrecoverable error occurred | ### `SpeakPriority` Controls how the agent handles a [`say()`](#saytext-prioritynone-interruptablenone) call relative to its current activity. Pass as a string to `session.say()`. | Value | Description | | ------------- | --------------------------------------------------------------- | | `'INTERRUPT'` | Agent immediately stops current speech and delivers the message | | `'APPEND'` | Message is queued and delivered after current speech ends | | `'IGNORE'` | Message is discarded if the agent is currently speaking | ### `ApiError` Raised when the API returns a 4xx or 5xx response. Catch this to inspect the status code and response body. ```python from agora_agent.core.api_error import ApiError try: agent_id = session.start() except ApiError as e: print(e.status_code) print(e.body) ``` | Property | Type | Description | | ------------- | -------------------------- | ------------------------------------ | | `status_code` | `Optional[int]` | HTTP status code returned by the API | | `headers` | `Optional[Dict[str, str]]` | Response headers | | `body` | `Any` | Raw response body from the API | ## Sync vs. Async The Python SDK provides two parallel client and session hierarchies — synchronous and asynchronous. Choose based on your application's runtime model. | | Sync | Async | | ------------ | -------------- | ------------------- | | Client | `Agora` | `AsyncAgora` | | Session | `AgentSession` | `AsyncAgentSession` | | HTTP backend | `httpx.Client` | `httpx.AsyncClient` | **Use `Agora` (sync) when:** - You are writing scripts, CLI tools, or batch jobs - Your web framework is synchronous, for example Flask or Django without async views - You want the simplest possible code **Use `AsyncAgora` (async) when:** - Your application uses `asyncio`, for example FastAPI, Starlette, or aiohttp - You need to manage multiple concurrent agent sessions efficiently - You want non-blocking I/O The `Agent` builder class is the same for both. It doesn't make HTTP calls, so it has no async variant. Construct `Agent(client=AsyncAgora(...))` and call `agent.create_async_session()` to receive an `AsyncAgentSession`. # TypeScript (/en/api-reference/api-ref/server-sdk/typescript) > Documentation: Voice Agents SDK reference. > Documentation version: Main. > This document describes only this version. [Version index](/llms/doc-versions-convoai-sdk-v1.txt). Full API reference for the Agora Conversational AI TypeScript SDK. ## AgoraClient `AgoraClient` extends the Fern-generated base client with domain pool support for regional URL cycling and three authentication modes. Pass `appId` and `appCertificate` only for the recommended app-credentials mode. The SDK mints fresh REST tokens per request and generates RTC join tokens at session start. ```typescript import { AgoraClient, Area } from 'agora-agents'; ``` ### Constructor ```typescript const client = new AgoraClient(options: AgoraClient.Options); ``` The authentication mode is resolved automatically from the options you provide. | Option | Type | Required | Description | | ------------------ | --------------- | -------- | ----------------------------------------------------------------------- | | `area` | [`Area`](#area) | Yes | Region for API routing (`Area.US`, `Area.EU`, `Area.AP`, `Area.CN`) | | `appId` | `string` | Yes | Agora App ID | | `appCertificate` | `string` | Yes | Agora App Certificate. Keep this secret and never expose it client-side | | `customerId` | `string` | No | Customer ID for Basic Auth | | `customerSecret` | `string` | No | Customer Secret for Basic Auth | | `authToken` | `string` | No | Raw Agora token. The SDK sends `Authorization: agora token=` | | `timeoutInSeconds` | `number` | No | Default request timeout in seconds | | `maxRetries` | `number` | No | Maximum retry attempts | | `fetch` | `typeof fetch` | No | Custom fetch implementation for unsupported runtimes | Authentication mode is resolved from the options you provide: | Options provided | Resolved [`authMode`](#agoraauthmode) | | ------------------------------- | ------------------------------------- | | `customerId` + `customerSecret` | `"basic"` | | `authToken` | `"token"` | | Neither | `"app-credentials"` | Passing `customerId` without `customerSecret` throws an error. See [Authentication](/en/api-reference/api-ref/conversational-ai/authentication) for details on each mode. ### Properties The following read-only properties are available on any `AgoraClient` instance. | Property | Type | Description | | ---------------- | --------------------------------- | ------------------------------------------------------------- | | `appId` | `string` | The Agora App ID | | `appCertificate` | `string` | The Agora App Certificate | | `authMode` | [`AgoraAuthMode`](#agoraauthmode) | The resolved authentication mode | | `area` | [`Area`](#area) | The configured region | | `pool` | `Pool` | The underlying domain pool instance used for regional routing | ### Methods The following methods are available in addition to the Fern-generated sub-client methods. #### `nextRegion()` Cycles to the next region prefix in the domain pool. Call this after a request failure to try a different regional endpoint. ```typescript client.nextRegion(); ``` #### `selectBestDomain(signal?)` Runs a DNS check to select the best domain suffix. Calls made within 30 seconds of the last successful selection are no-ops. ```typescript await client.selectBestDomain(); ``` | Parameter | Type | Description | | --------- | ------------- | --------------------------------------------- | | `signal` | `AbortSignal` | Optional abort signal to cancel the DNS check | #### `stopAgent(agentId)` Stops an agent by ID without an `AgentSession` reference, for example, from an end-call handler. The method treats a `404` response as success. ```typescript stopAgent(agentId: string): Promise ``` #### `getCurrentURL()` Returns the full API URL currently in use as a `string`. ```typescript const url = client.getCurrentURL(); // Example: 'https://api-us-west-1.agora.io/api/conversational-ai-agent' ``` ### Sub-clients `AgoraClient` exposes Fern-generated sub-clients for direct REST API access. You typically do not need these when using the [agentkit layer](#agent). | Property | Description | | ------------------------ | --------------------------------------------------------------- | | `client.agents` | Start, stop, update, speak, interrupt, get history, list agents | | `client.agentManagement` | Inject instructions into a running agent (`think`) | | `client.telephony` | Telephony operations | | `client.phoneNumbers` | Phone number management | For full method signatures and request parameters, see the [REST API reference](/en/api-reference/api-ref/conversational-ai/join). ## Agent `Agent` is an immutable configuration object. Each builder method returns a new `Agent` instance — the original is never modified. Define one `Agent` at startup and call `createSession()` on it for each user conversation. ```typescript import { Agent } from 'agora-agents'; ``` ### Constructor ```typescript new Agent(options: AgentOptions) ``` `client` is required. All other options are optional. Use the [builder methods](#builder-methods) to set vendor configuration after construction. | Option | Type | Default | Description | | ------------------ | --------------------- | ----------- | -------------------------------------------------------------------------------------------------------- | | `client` | `AgoraClient` | — | Required. Agora client used by `createSession()` | | `pipelineId` | `string` | `undefined` | Published AI Studio pipeline ID used as the base configuration. `SessionOptions.pipelineId` overrides it | | `instructions` | `string` | `undefined` | Deprecated. Set `systemMessages` on the LLM vendor instead | | `greeting` | `string` | `undefined` | Deprecated. Set `greetingMessage` on the LLM or MLLM vendor instead | | `failureMessage` | `string` | `undefined` | Deprecated. Set `failureMessage` on the LLM or MLLM vendor instead | | `maxHistory` | `number` | `undefined` | Deprecated. Set `maxHistory` on the LLM vendor instead | | `greetingConfigs` | `LlmGreetingConfigs` | `undefined` | Deprecated. Set `greetingConfigs` on the LLM vendor instead | | `turnDetection` | `TurnDetectionConfig` | `undefined` | Voice activity detection settings | | `interruption` | `InterruptionConfig` | `undefined` | Unified interruption control settings | | `sal` | `SalConfig` | `undefined` | Selective Attention Locking configuration | | `avatar` | `AvatarConfig` | `undefined` | Avatar configuration | | `advancedFeatures` | `AdvancedFeatures` | `undefined` | Enable MLLM mode, AI-VAD, and other advanced features | | `parameters` | `SessionParamsInput` | `undefined` | Session parameters including silence and farewell config | | `geofence` | `GeofenceConfig` | `undefined` | Regional access restriction | | `labels` | `Labels` | `undefined` | Custom key-value labels returned in notification callbacks | | `rtc` | `RtcConfig` | `undefined` | RTC media encryption | | `fillerWords` | `FillerWordsConfig` | `undefined` | Filler words played while waiting for the LLM response | ### Builder methods All builder methods return a **new** `Agent` instance. The original is never modified. #### `withLlm(vendor)` Sets the LLM vendor. Pass an instance of [`OpenAI`](#openai), [`AzureOpenAI`](#azureopenai), [`Anthropic`](#anthropic), [`Gemini`](#gemini), or any [other LLM vendor](#other-llm-vendors). ```typescript withLlm(vendor: LlmVendor): Agent ``` #### `withTts(vendor)` Sets the TTS vendor. The sample rate type is captured and tracked for [avatar](#avatar-vendors) compatibility. ```typescript withTts(vendor: TtsVendor): Agent ``` #### `withStt(vendor)` Sets the STT vendor. Pass an instance of any [STT vendor class](#stt-vendors). ```typescript withStt(vendor: SttVendor): Agent ``` #### `withMllm(vendor)` Sets the MLLM vendor for multimodal mode. Pass [`OpenAIRealtime`](#openairealtime), [`AzureOpenAIRealtime`](#azureopenairealtime), [`GeminiLive`](#geminilive), [`VertexAI`](#vertexai), [`XaiGrok`](#xaigrok), or [`OpenAIGPTLive`](#openaigptlive). Calling `withMllm()` automatically sets `mllm.enable = true`. MLLM mode does not require `withTts()` / `withLlm()` / `withStt()`. > **Info** > > Avatars are only supported with the cascading ASR + LLM + TTS pipeline. If you combine `withMllm()` with `withAvatar()`, the SDK throws an error when `toProperties()` or `session.start()` is called. ```typescript withMllm(vendor: GlobalMllmVendor | CNMllmVendor): Agent ``` #### `withAvatar(vendor)` Sets the avatar vendor. The `this` constraint enforces at compile time that the agent's TTS sample rate matches the avatar's required rate. > **Info** > > Requires the cascading ASR + LLM + TTS pipeline. If you combine `withAvatar()` with `withMllm()`, the SDK throws an error when `toProperties()` or `session.start()` is called. ```typescript withAvatar( this: Agent, vendor: AvatarVendor ): Agent ``` #### `withTurnDetection(config)` Configures cascading-flow turn detection. Pass `{ config: { start_of_speech, end_of_speech } }` for SOS/EOS detection. Use `withInterruption()` for interruption behavior and MLLM vendor `turnDetection` for MLLM turn detection. ```typescript withTurnDetection(config: TurnDetectionConfig): Agent ``` #### `withInterruption(config)` Configures unified interruption behavior using the top-level `interruption` object. Use this for `start_of_speech` and `keywords` interruption modes. ```typescript withInterruption(config: InterruptionConfig): Agent ``` #### `withInstructions(text)` Overrides the LLM system prompt on a new `Agent` instance. Deprecated. Set `systemMessages` on the LLM vendor instead. ```typescript withInstructions(instructions: string): Agent ``` #### `withGreeting(text)` Overrides the greeting message on a new `Agent` instance. Deprecated. Set `greetingMessage` on the LLM or MLLM vendor instead. ```typescript withGreeting(greeting: string): Agent ``` #### Other builder methods The following methods follow the same pattern — each returns a new `Agent` instance with the updated configuration. | Method | Parameter type | Description | | ---------------------------------- | ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `withSal(config)` | `SalConfig` | Set Selective Attention Locking configuration | | `withAdvancedFeatures(features)` | `AdvancedFeatures` | Set advanced features | | `withTools(enabled = true)` | `boolean` | Enable or disable MCP tool and custom tool invocation | | `withParameters(parameters)` | `SessionParamsInput` | Set session parameters | | `withAudioScenario(audioScenario)` | `ParametersAudioScenario` | Set `parameters.audio_scenario`. Use the exported `AudioScenario` constants for discoverability, for example `agent.withAudioScenario(AudioScenario.Aiserver)` | | `withFailureMessage(message)` | `string` | Deprecated. Set `failureMessage` on the LLM or MLLM vendor instead | | `withMaxHistory(n)` | `number` | Deprecated. Set `maxHistory` on the LLM vendor instead. For Azure OpenAI Realtime MLLM, set `maxHistory` on the MLLM vendor | | `withGreetingConfigs(configs)` | `LlmGreetingConfigs` | Deprecated. Set `greetingConfigs` on the LLM vendor instead | | `withGeofence(geofence)` | `GeofenceConfig` | Set geofence configuration | | `withLabels(labels)` | `Labels` | Set custom labels | | `withRtc(rtc)` | `RtcConfig` | Set RTC configuration | | `withFillerWords(fillerWords)` | `FillerWordsConfig` | Set filler words configuration | ### `createSession(options)` Creates an [`AgentSession`](#agentsession) for a channel using the agent's client. Doesn't start the agent. Call [`session.start()`](#start) to join the channel. ```typescript createSession(options: SessionOptions): AgentSession ``` `SessionOptions` fields: | Option | Type | Required | Description | | ----------------- | --------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | | `channel` | `string` | Yes | Channel name to join | | `agentUid` | `string` | Yes | The agent's RTC UID. Must be a numeric string when `token` is omitted | | `remoteUids` | `string[]` | Yes | Remote user UIDs the agent listens and responds to | | `name` | `string` | No | Agent instance name sent to the Agora API. Defaults to `agent-{timestamp}` | | `token` | `string` | No | Pre-built RTC+RTM token. Omit to auto-generate from app credentials | | `expiresIn` | `number` | No | Token lifetime in seconds. Only applies when the token is auto-generated. Valid range: 1–86400. Use [`ExpiresIn`](#expiresin) helpers for clarity | | `idleTimeout` | `number` | No | Seconds before the agent auto-exits when no audio is detected. `0` disables the timeout | | `enableStringUid` | `boolean` | No | Use string UIDs instead of numeric UIDs | | `preset` | `PresetInput` | No | Advanced project-specific presets. Use only when Agora provides a specific preset ID for your project. Most applications should not set this field | | `pipelineId` | `string` | No | Published AI Studio pipeline ID to use as the base configuration | | `debug` | `boolean` | No | Log API requests to the console | | `warn` | `(message: string) => void` | No | Custom warning logger; pass a no-op to silence warnings | `preset` is session-scoped because the underlying Agora start/join API applies presets per session, not per reusable `Agent` definition. When you omit credentials for supported reseller-backed vendor models, AgentKit infers the matching session preset automatically: - Deepgram STT: `nova-2`, `nova-3` - OpenAI LLM: `gpt-4o-mini`, `gpt-4.1-mini`, `gpt-5-nano`, `gpt-5-mini` - OpenAI TTS: `tts-1` - MiniMax TTS: `speech-2.6-turbo`, `speech-2.8-turbo` If you provide your own vendor API key for those same models, AgentKit keeps the request in BYOK mode and does not infer a preset. ### Properties Read-only properties available on any `Agent` instance. | Property | Type | Description | | ------------------ | ---------------------------------- | ------------------------------------- | | `pipelineId` | `string \| undefined` | AI Studio pipeline ID | | `greetingConfigs` | `LlmGreetingConfigs \| undefined` | Greeting playback configuration | | `instructions` | `string \| undefined` | LLM system prompt | | `greeting` | `string \| undefined` | Greeting message | | `failureMessage` | `string \| undefined` | Message spoken when LLM fails | | `maxHistory` | `number \| undefined` | Maximum conversation history length | | `llm` | `LlmConfig \| undefined` | LLM configuration | | `tts` | `TtsConfig \| undefined` | TTS configuration | | `stt` | `SttConfig \| undefined` | STT configuration | | `mllm` | `MllmConfig \| undefined` | MLLM configuration | | `avatar` | `AvatarConfig \| undefined` | Avatar configuration | | `turnDetection` | `TurnDetectionConfig \| undefined` | Turn detection configuration | | `interruption` | `InterruptionConfig \| undefined` | Interruption configuration | | `sal` | `SalConfig \| undefined` | SAL configuration | | `advancedFeatures` | `AdvancedFeatures \| undefined` | Advanced features | | `parameters` | `SessionParams \| undefined` | Session parameters | | `geofence` | `GeofenceConfig \| undefined` | Geofence configuration | | `labels` | `Labels \| undefined` | Custom labels | | `rtc` | `RtcConfig \| undefined` | RTC configuration | | `fillerWords` | `FillerWordsConfig \| undefined` | Filler words configuration | | `config` | `AgentOptions` | Full read-only configuration snapshot | ### `toProperties(opts)` Low-level method to convert the agent configuration to the Fern request format. Used internally by `AgentSession.start()`. You typically do not need to call this directly unless building custom request bodies. ```typescript toProperties(opts): StartAgentsRequest.Properties ``` In cascading mode, throws if TTS or LLM isn't set. If you don't call `withStt()`, ASR defaults to ARES (`fengming` for `Area.CN`). `turnDetection.language` defaults to `en-US` and is also sent as `asr.language`. ### Type aliases Public aliases over Fern-generated types include `LlmConfig`, `SttConfig`, `AsrConfig` (= `SttConfig`), `MllmConfig`, `AvatarConfig`, session/conversation types, and think types (`ThinkOnListeningAction`, etc.). Think value constants: `ThinkOnListeningActionInject`, `ThinkOnListeningActionInterrupt`, `ThinkOnListeningActionIgnore`, `ThinkOnThinkingActionInterrupt`, `ThinkOnThinkingActionIgnore`, `ThinkOnSpeakingActionInterrupt`, `ThinkOnSpeakingActionIgnore`. The think action options also accept the string `append`, which has no convenience constant. With `append`, the instruction doesn't interrupt the current interaction. The agent waits for the current user turn, LLM inference, or TTS playback to finish, then appends the instruction to the context as a separate user message and starts a new turn. `FillerWordsConfig` supports static and generated filler words. Generated mode requires static fallback phrases, while `generated_config` and `prompt` are optional. Agora hosts the generation service, so you can't configure its model endpoint, API key, or model parameters. For the field structure, see [Configure generated filler words](/en/ai/build/shape-the-conversation/filler-words#configure-generated-filler-words). `FillerWordsContentGeneratedConfig` sets the conversation context for generated filler words. Use `context_message_limit` (`1` to `6`, defaults to `1`) to set how many of the most recent conversation messages to use, counting the current turn's message, and `history_character_limit` (`0` to `10000`, defaults to `1000`) to cap the combined characters of the earlier messages. For details, see [Talking while waiting](/en/ai/build/shape-the-conversation/filler-words#widen-the-conversation-window). Public aliases also include `FillerWordsContentGeneratedConfig` and the custom tool types `LlmTool`, `LlmToolFunction`, `LlmToolServer`, and `LlmToolExecution`. `llm.tools` is independent of MCP server configuration, but both require `withTools(true)` to enable tool calling. ## AgentSession `AgentSession` manages the full lifecycle of a running agent. Create sessions using [`agent.createSession()`](#createsessionoptions); do not call the constructor directly. ```typescript import { AgentSession } from 'agora-agents'; ``` ### State machine A session progresses through the following states: ```text idle ──► starting ──► running ──► stopping ──► stopped │ │ ▼ ▼ error error ``` | Transition | Trigger | | -------------------- | --------------------------------------- | | `idle → starting` | `start()` called | | `starting → running` | API responds with agent ID | | `starting → error` | API request fails | | `running → stopping` | `stop()` called | | `stopping → stopped` | API confirms agent stopped | | `stopping → error` | Stop request fails with a non-404 error | `start()` can also be called from `stopped` or `error` state to restart the session. `say()`, `interrupt()`, `update()`, and `think()` reject on failure but don't change the session state. ### Methods The following methods are available on an `AgentSession` instance. #### `start()` Starts the agent session. Generates tokens if not provided, sends the start request, and returns the agent ID. Resolves explicit `preset` values and also infers reseller presets from supported vendor configs when credentials are omitted. ```typescript start(): Promise ``` - Transitions: `idle` / `stopped` / `error` → `starting` → `running` - Throws if called in `starting`, `running`, or `stopping` state - Throws if avatar config is invalid (wrong TTS sample rate) - Throws if no `token` is provided and the client has no `appCertificate` - Throws if `agentUid` (or avatar `agoraUid`) isn't numeric when tokens are auto-generated - Throws if `appId` or `appCertificate` isn't exactly 32 characters when tokens are auto-generated - Throws if MLLM is enabled together with an enabled avatar — avatars are only supported with the cascading ASR + LLM + TTS pipeline - Applies explicit `preset` values when provided and sends Agora-managed configuration when supported vendor credentials are omitted - Fills generic avatar `agora_appid` and `agora_channel` from the session when omitted - Generates avatar `agora_token` for `HeyGenAvatar`, `LiveAvatarAvatar`, `GenericAvatar`, `Tavus`, `Protoface`, and `LemonSlice` when `agoraToken` is omitted and the client has an `appCertificate`. Other vendors (`AkoolAvatar`, `AnamAvatar`) never receive an auto-generated token. #### `stop()` Stops the agent session and removes the agent from the channel. If the agent has already stopped — for example due to idle timeout — resolves silently rather than throwing a 404 error. ```typescript stop(): Promise ``` - Transitions: `running` → `stopping` → `stopped` - Throws if called outside `running` state #### `say(text, options?)` Instructs the agent to speak the given text. ```typescript say(text: string, options?: SayOptions): Promise ``` | Parameter | Type | Required | Description | | ----------------------- | --------------------------------- | -------- | --------------------------------------------------- | | `text` | `string` | Yes | The text for the agent to speak | | `options.priority` | [`SpeakPriority`](#speakpriority) | No | Message priority | | `options.interruptable` | `boolean` | No | Whether this message can be interrupted by the user | - Only valid in `running` state #### `interrupt()` Interrupts the agent's current speech. ```typescript interrupt(): Promise ``` - Only valid in `running` state #### `think(text, options?)` Injects a custom text instruction into the running agent. ```typescript think(text: string, options?: ThinkOptions): Promise ``` | Parameter | Type | Required | Description | | ----------------------------- | ------------------------ | -------- | -------------------------------------------------------------------------------- | | `text` | `string` | Yes | The instruction text | | `options.on_listening_action` | `ThinkOnListeningAction` | No | Action when the agent is listening: `inject`, `interrupt`, `ignore`, or `append` | | `options.on_thinking_action` | `ThinkOnThinkingAction` | No | Action when the agent is thinking: `interrupt`, `ignore`, or `append` | | `options.on_speaking_action` | `ThinkOnSpeakingAction` | No | Action when the agent is speaking: `interrupt`, `ignore`, or `append` | | `options.interruptable` | `boolean` | No | Whether the user can interrupt the resulting response | | `options.metadata` | `Record` | No | Custom key-value metadata | - Only valid in `running` state #### `update(config)` Updates the agent configuration mid-session without restarting. Accepts a partial configuration object in REST API format. ```typescript update(config: AgentConfigUpdate): Promise ``` - Only valid in `running` state #### `getHistory()` Fetches the conversation history for this session. Requires a valid agent ID — `start()` must have been called successfully. ```typescript getHistory(): Promise ``` #### `getTurns(options?)` Fetches turn-by-turn analytics for this session, including start/end events and latency metrics. Requires a valid agent ID and `start()` must have been called successfully. ```typescript getTurns(options?: GetTurnsOptions): Promise ``` - `options.page_index`: page number, starting from `1` - `options.page_size`: number of turns per page #### `getAllTurns(options?)` Fetches all turn analytics pages and merges the `turns` array. Requires a valid agent ID and `start()` must have been called successfully. ```typescript getAllTurns(options?: Omit): Promise ``` - Requires a valid `agentId` - For very long sessions, prefer processing pages with `getTurns()` to avoid holding all turns in memory #### `getInfo()` Fetches current agent metadata from the API. Requires a valid agent ID. ```typescript getInfo(): Promise ``` #### `on(event, handler)` Subscribes to a session event. Register handlers **before** calling `start()` to avoid missing the `started` event. ```typescript on(event: AgentSessionEvent, handler: AgentSessionEventHandler): void ``` #### `off(event, handler)` Unsubscribes a previously registered event handler. ```typescript off(event: AgentSessionEvent, handler: AgentSessionEventHandler): void ``` ### Events The session emits the following events. See [`AgentSessionEvent`](#agentsessionevent) and [`AgentSessionEventHandler`](#agentsessioneventhandler) for type details. | Event | Payload type | Description | | ----------- | --------------------- | --------------------------------------------- | | `"started"` | `{ agentId: string }` | Agent successfully joined the channel | | `"stopped"` | `{ agentId: string }` | Agent left the channel | | `"error"` | `unknown` | The error thrown during `start()` or `stop()` | ### Properties The following read-only properties are available on any `AgentSession` instance. | Property | Type | Description | | -------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------- | | `status` | `"idle" \| "starting" \| "running" \| "stopping" \| "stopped" \| "error"` | Current session state. One of `"idle"`, `"starting"`, `"running"`, `"stopping"`, `"stopped"`, `"error"` | | `id` | `string \| null` | Agent ID, populated after `start()` resolves | | `agent` | `Agent` | The agent configuration this session was created from | | `appId` | `string` | The Agora App ID for this session | | `raw` | `AgentsClient` | Direct access to the Fern-generated `AgentsClient` for advanced operations | | `rawAgentManagement` | `AgentManagementClient` | Direct access to the Fern-generated agent management client | #### Using `session.raw` Access the generated REST client to call endpoints not yet wrapped: ```typescript await session.raw.getTurns({ appid: session.appId, agentId: session.id!, }); ``` You must pass `appid` and `agentId` manually when using raw methods. ### Presets and BYOK Prefer configuring vendors on the `Agent` builder. When you omit credentials for supported Agora-managed models, AgentKit sends the matching Agora-managed configuration at session start. `preset` is an advanced session option for project-specific settings, not for selecting Agora-managed models. Most applications should use the builder instead. - Omit vendor credentials on the builder for supported Agora-managed models. - Provide vendor API keys when you want BYOK. - Pass `preset` on `agent.createSession(...)` only when you need to access specific project-specific settings. Supported Agora-managed models: - Deepgram STT: `nova-2`, `nova-3` - OpenAI LLM: `gpt-4o-mini`, `gpt-4.1-mini`, `gpt-5-nano`, `gpt-5-mini` - OpenAI TTS: `tts-1` - MiniMax TTS: `speech-2.6-turbo`, `speech-2.8-turbo` ## Vendors All vendor classes are imported from `agora-agents`. Pass vendor instances to the [Agent builder methods](#builder-methods). ### LLM vendors Use with [`withLlm()`](#withllmvendor). #### OpenAI ```typescript new OpenAI(options: OpenAIOptions) ``` | Option | Type | Required | Description | | ------------------- | --------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------ | | `apiKey` | `string` | Usually | OpenAI API key. Optional for Agora-managed preset models | | `model` | `string` | Yes | Model name, for example `'gpt-4o-mini'` | | `url` | `string` | Conditional | API endpoint URL. Required when `apiKey` is set (BYOK); default `https://api.openai.com/v1/chat/completions` | | `maxHistory` | `number` | No | Maximum conversation history to cache | | `temperature` | `number` | No | Sampling temperature (0.0–2.0) | | `topP` | `number` | No | Nucleus sampling (0.0–1.0) | | `maxTokens` | `number` | No | Maximum tokens to generate | | `systemMessages` | `Record[]` | No | Additional system messages | | `greetingMessage` | `string` | No | Agent greeting message | | `failureMessage` | `string` | No | Message spoken when the LLM call fails | | `inputModalities` | `string[]` | No | Input modalities. Default: `["text"]` | | `outputModalities` | `string[]` | No | Output modalities | | `params` | `Record` | No | Additional LLM parameters passed to the model | | `headers` | `Record` | No | Custom HTTP headers forwarded to the LLM provider | | `vendor` | `string` | No | Vendor override | | `mcpServers` | `Record[]` | No | MCP server connections | | `tools` | `LlmTool[]` | No | Synchronous custom tool definitions the LLM can call. Requires `withTools(true)` | | `greetingConfigs` | `LlmGreetingConfigs` | No | Greeting playback configuration | | `templateVariables` | `Record` | No | Template variables for messages. Custom tools can reference them with `{{template_variables.}}` | `apiKey` is optional for the following reseller preset models: `gpt-4o-mini`, `gpt-4.1-mini`, `gpt-5-nano`, `gpt-5-mini`. If `apiKey` is omitted for one of those models, AgentKit infers the matching session preset. This no-key branch is only available with the default OpenAI endpoint and without a custom vendor hint. If `apiKey` is provided, AgentKit uses standard BYOK behavior instead. #### AzureOpenAI ```typescript new AzureOpenAI(options: AzureOpenAIOptions) ``` | Option | Type | Required | Description | | ------------------- | --------------------------- | ----------- | ----------------------------------------------------------------------------------------------------- | | `apiKey` | `string` | Yes | Azure OpenAI API key | | `model` | `string` | Yes | Model or deployment name | | `resourceName` | `string` | Conditional | Azure resource name. Required unless `endpoint` is set | | `endpoint` | `string` | Conditional | Full Azure base URL. Takes precedence over `resourceName`; required unless `resourceName` is set | | `deploymentName` | `string` | Yes | Deployment name in Azure | | `apiVersion` | `string` | No | Azure API version. Default: `'2024-08-01-preview'` | | `maxHistory` | `number` | No | Maximum conversation history to cache | | `temperature` | `number` | No | Sampling temperature (0.0–2.0) | | `topP` | `number` | No | Nucleus sampling (0.0–1.0) | | `maxTokens` | `number` | No | Maximum tokens to generate | | `systemMessages` | `Record[]` | No | Additional system messages | | `greetingMessage` | `string` | No | Agent greeting message | | `failureMessage` | `string` | No | Message spoken when the LLM call fails | | `inputModalities` | `string[]` | No | Input modalities. Default: `["text"]` | | `outputModalities` | `string[]` | No | Output modalities | | `params` | `Record` | No | Additional LLM parameters | | `headers` | `Record` | No | Custom HTTP headers forwarded to the LLM provider | | `vendor` | `string` | No | Vendor override. Defaults to `azure` | | `mcpServers` | `Record[]` | No | MCP server connections | | `tools` | `LlmTool[]` | No | Synchronous custom tool definitions the LLM can call. Requires `withTools(true)` | | `greetingConfigs` | `LlmGreetingConfigs` | No | Greeting playback configuration | | `templateVariables` | `Record` | No | Template variables for messages. Custom tools can reference them with `{{template_variables.}}` | #### Anthropic ```typescript new Anthropic(options: AnthropicOptions) ``` | Option | Type | Required | Description | | ------------------- | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------- | | `apiKey` | `string` | Yes | Anthropic API key | | `model` | `string` | Yes | Model name | | `url` | `string` | Yes | Anthropic messages endpoint URL | | `maxTokens` | `number` | Yes | Maximum tokens to generate | | `headers` | `Record` | Yes | Request headers, including `anthropic-version` | | `maxHistory` | `number` | No | Maximum conversation history to cache | | `temperature` | `number` | No | Sampling temperature (0.0–1.0) | | `topP` | `number` | No | Nucleus sampling (0.0–1.0) | | `systemMessages` | `Record[]` | No | Additional system messages | | `greetingMessage` | `string` | No | Agent greeting message | | `failureMessage` | `string` | No | Message spoken when the LLM call fails | | `inputModalities` | `string[]` | No | Input modalities. Default: `["text"]` | | `outputModalities` | `string[]` | No | Output modalities | | `params` | `Record` | No | Additional LLM parameters | | `vendor` | `string` | No | Vendor override | | `mcpServers` | `Record[]` | No | MCP server connections | | `tools` | `LlmTool[]` | No | Synchronous custom tool definitions the LLM can call. Requires `withTools(true)` | | `greetingConfigs` | `LlmGreetingConfigs` | No | Greeting playback configuration | | `templateVariables` | `Record` | No | Template variables for messages. Custom tools can reference them with `{{template_variables.}}` | #### Gemini ```typescript new Gemini(options: GeminiOptions) ``` | Option | Type | Required | Description | | ------------------- | --------------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `apiKey` | `string` | Yes | Google API key | | `model` | `string` | Yes | Model name, for example `'gemini-pro'` | | `url` | `string` | No | API endpoint URL. Default: `https://generativelanguage.googleapis.com/v1beta/models/{model}:streamGenerateContent?alt=sse&key={apiKey}`, with the API key in the URL | | `maxHistory` | `number` | No | Maximum conversation history to cache | | `temperature` | `number` | No | Sampling temperature (0.0–2.0) | | `topP` | `number` | No | Nucleus sampling (0.0–1.0) | | `topK` | `number` | No | Top-k sampling | | `maxOutputTokens` | `number` | No | Maximum output tokens to generate | | `systemMessages` | `Record[]` | No | Additional system messages | | `greetingMessage` | `string` | No | Agent greeting message | | `failureMessage` | `string` | No | Message spoken when the LLM call fails | | `inputModalities` | `string[]` | No | Input modalities. Default: `["text"]` | | `outputModalities` | `string[]` | No | Output modalities | | `params` | `Record` | No | Additional LLM parameters | | `headers` | `Record` | No | Custom HTTP headers forwarded to the LLM provider | | `vendor` | `string` | No | Vendor override | | `mcpServers` | `Record[]` | No | MCP server connections | | `tools` | `LlmTool[]` | No | Synchronous custom tool definitions the LLM can call. Requires `withTools(true)` | | `greetingConfigs` | `LlmGreetingConfigs` | No | Greeting playback configuration | | `templateVariables` | `Record` | No | Template variables for messages. Custom tools can reference them with `{{template_variables.}}` | ### Other LLM vendors | Class | Provider | Key options | | --------------- | --------------------- | ---------------------------------------------------- | | `Groq` | Groq | `apiKey`, `model`, `url` | | `VertexAILLM` | Google Vertex AI | `apiKey`, `model`, `projectId`, `location`, `url?` | | `AmazonBedrock` | Amazon Bedrock | `accessKey`, `secretKey`, `region`, `model` | | `Dify` | Dify | `apiKey`, `url`, `model`, `user?`, `conversationId?` | | `CustomLLM` | OpenAI-compatible LLM | `apiKey`, `model`, `url` | `Groq` and `CustomLLM` share `OpenAI`'s option shape; `VertexAILLM` mirrors `Gemini`. All accept common LLM fields, such as `systemMessages`, `greetingMessage`, `failureMessage`, `maxHistory`, `params`, `headers`, and `tools`. `tools` declares custom tools the LLM can choose to call. Each tool includes a model-visible function definition and the server configuration for a synchronous `GET` or `POST` request. `withTools(true)` applies to both `tools` and MCP server configuration. For more information, see [Call custom tools](/en/ai/build/tools/custom-tools). ### TTS vendors Use with [`withTts()`](#withttsvendor). The `sampleRate` option determines avatar compatibility — see [`withAvatar()`](#withavatarvendor). #### ElevenLabsTTS ```typescript new ElevenLabsTTS(options: ElevenLabsTTSOptions) ``` | Option | Type | Required | Description | | -------------------------- | ---------------------------------- | -------- | ------------------------------------------- | | `key` | `string` | Yes | ElevenLabs API key | | `modelId` | `string` | Yes | Model ID, for example `'eleven_flash_v2_5'` | | `voiceId` | `string` | Yes | Voice ID | | `baseUrl` | `string` | Yes | WebSocket base URL | | `sampleRate` | `16000 \| 22050 \| 24000 \| 44100` | No | Audio sample rate in Hz | | `optimizeStreamingLatency` | `number` | No | Latency optimization level (0–4) | | `stability` | `number` | No | Voice stability (0.0–1.0) | | `similarityBoost` | `number` | No | Voice similarity boost (0.0–1.0) | | `style` | `number` | No | Voice style exaggeration (0.0–1.0) | | `useSpeakerBoost` | `boolean` | No | Enable speaker boost | | `skipPatterns` | `number[]` | No | Skip patterns for bracketed content | #### MicrosoftTTS ```typescript new MicrosoftTTS(options: MicrosoftTTSOptions) ``` | Option | Type | Required | Description | | -------------- | ------------------------- | -------- | --------------------------------------------- | | `key` | `string` | Yes | Azure Speech API key | | `region` | `string` | Yes | Azure region, for example `'eastus'` | | `voiceName` | `string` | Yes | Voice name, for example `'en-US-JennyNeural'` | | `sampleRate` | `16000 \| 24000 \| 48000` | No | Audio sample rate in Hz | | `speed` | `number` | No | Speaking rate multiplier | | `volume` | `number` | No | Audio volume | | `skipPatterns` | `number[]` | No | Skip patterns for bracketed content | #### OpenAITTS Fixed at 24,000 Hz — no configurable sample rate. ```typescript new OpenAITTS(options: OpenAITTSOptions) ``` | Option | Type | Required | Description | | -------------- | ---------- | -------- | ------------------------------------------------------------------------------ | | `apiKey` | `string` | Usually | OpenAI API key | | `voice` | `string` | Yes | Voice name: `'alloy'`, `'echo'`, `'fable'`, `'onyx'`, `'nova'`, or `'shimmer'` | | `model` | `string` | No | Model name. Required (with `apiKey` and `baseUrl`) for BYOK | | `baseUrl` | `string` | No | Endpoint URL. Required (with `apiKey` and `model`) for BYOK | | `instructions` | `string` | No | Custom voice instructions | | `speed` | `number` | No | Speech speed multiplier | | `skipPatterns` | `number[]` | No | Skip patterns for bracketed content | `apiKey` is optional only for the reseller-backed `tts-1` preset path. If omitted with `model: 'tts-1'` or no explicit model, AgentKit infers `openai_tts_1`. If provided, the request stays in BYOK mode. #### CartesiaTTS ```typescript new CartesiaTTS(options: CartesiaTTSOptions) ``` | Option | Type | Required | Description | | -------------- | --------------------------------------------------- | -------- | ------------------------------------------------------ | | `apiKey` | `string` | Yes | Cartesia API key | | `voiceId` | `string` | Yes | Voice ID (serialized as `{"mode": "id", "id": "..."}`) | | `modelId` | `string` | Yes | Model ID | | `baseUrl` | `string` | No | WebSocket URL | | `language` | `string` | No | Target language | | `sampleRate` | `8000 \| 16000 \| 22050 \| 24000 \| 44100 \| 48000` | No | Audio sample rate in Hz | | `skipPatterns` | `number[]` | No | Skip patterns for bracketed content | #### Other TTS vendors | Class | Key parameters | | --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------- | | `GoogleTTS` | `key`, `voiceName`, `languageCode?`, `sampleRate?` | | `AmazonTTS` | `accessKey`, `secretKey`, `region`, `voiceId`, `engine` | | `DeepgramTTS` | `apiKey`, `model`, `baseUrl?`, `sampleRate?`, `additionalParams?` | | `HumeAITTS` | `key`, `voiceId`, `provider`, `configId?`, `baseUrl?`, `speed?`, `trailingSilence?` | | `RimeTTS` | `key`, `speaker`, `modelId`, `baseUrl?`, `credentialMode?`. In managed mode (`CredentialMode.Managed`), only `modelId` and `baseUrl` are required | | `FishAudioTTS` | `key`, `referenceId`, `backend` | | `MiniMaxTTS` | `key?`, `groupId?`, `model`, `voiceId?`, `url?` | | `MurfTTS` | `key`, `voiceId?`, `baseUrl?`, `locale?`, `rate?`, `pitch?`, `model?`, `sampleRate?` | | `SarvamTTS` | `key`, `speaker`, `targetLanguageCode`, `pitch?`, `pace?`, `loudness?`, `sampleRate?` | | `GradiumTTS` | `apiKey`, `url?`, `modelName?`, `voiceId?`, `sampleRate?`, `additionalParams?` | | `MistralTTS` | `apiKey`, `model?`, `voice?`, `additionalParams?` | | `TypecastTTS` | `apiKey`, `voiceId`, `model`, `additionalParams?` | | `XAiTTS` | `apiKey`, `language`, `voiceId?`, `sampleRate?`, `additionalParams?` | | `SmallestAITTS` | `apiKey`, `url?`, `model?`, `voiceId?`, `sampleRate?`, `speed?`, `language?`, `additionalParams?` | `SmallestAITTS` also accepts `numberPronunciationLanguage?`, `mathNotation?`, `pronunciationDicts?`, `sessionId?`, and `requestId?`. Voice identifiers are model-specific, so `voiceId` must belong to the model set in `model`. For details, see [Smallest AI](/en/ai/models/tts/smallest-ai). For `MiniMaxTTS`, `key` is optional only for reseller-backed models: `speech-2.6-turbo`, `speech-2.8-turbo`. If `key` is omitted for one of those models, AgentKit infers the matching session preset. In that preset-backed path, `groupId`, `voiceId`, and `url` are optional overrides rather than required fields. If `key` is provided, AgentKit uses BYOK, and `groupId`, `voiceId`, and `url` are required. #### GenericTTS Custom OpenAI-compatible HTTP TTS. `url` is required and must be an absolute HTTP or HTTPS address — the constructor throws if `url` is missing, badly formatted, or uses a non-HTTP(S) scheme such as `ws:` or `wss:`. A valid URL is serialized as `tts.vendor = "generic_http"`. ```typescript new GenericTTS(options: GenericTTSOptions) ``` | Option | Type | Required | Description | | ------------------ | ------------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `url` | `string` | Yes | The HTTP(S) endpoint of your custom TTS service | | `headers` | `Record` | No | Custom HTTP headers to forward to the TTS service. Omitted from the request if not set | | `apiKey` | `string` | No | The API key used to authenticate with the TTS service | | `model` | `string` | No | The TTS model name | | `voice` | `string` | No | The voice name | | `speed` | `number` | No | The speech rate | | `sampleRate` | `number` | No | The sample rate, in Hz, of the output audio. If your TTS service doesn't support multiple sample rates, make sure the returned audio's sample rate matches this value | | `responseFormat` | `"pcm"` | No | The output audio format. Conversational AI Engine currently supports `pcm` | | `instruction` | `string` | No | Instructions for voice style, emotion, or other playback directives | | `additionalParams` | `Record` | No | Additional parameters passed through to the TTS service. Explicit fields with the same name take precedence | | `skipPatterns` | `number[]` | No | Skip patterns for bracketed content | ### STT vendors Use with [`withStt()`](#withsttvendor). #### DeepgramSTT ```typescript new DeepgramSTT(options?: DeepgramSTTOptions) ``` Provide `apiKey`, or omit it and set `model` to `nova-2` or `nova-3` to use Agora-managed credentials. The constructor throws otherwise. | Option | Type | Required | Description | | ------------------ | ------------------------- | ----------- | ------------------------------------------------------------------------------------- | | `apiKey` | `string` | No | Deepgram API key. Optional for `nova-2` and `nova-3` reseller preset usage | | `model` | `string` | Conditional | Model name, for example `'nova-2'` or `'enhanced'`. Required when `apiKey` is omitted | | `language` | `string` | No | Language code, for example `'en-US'` | | `keyterm` | `string` | No | Boost specialized terms and brands | | `smartFormat` | `boolean` | No | Enable smart formatting | | `punctuation` | `boolean` | No | Enable punctuation | | `additionalParams` | `Record` | No | Additional vendor parameters | For `nova-2` and `nova-3`, omit `apiKey` to use Agora-managed credentials. For all other Deepgram models, `apiKey` is required. #### Other STT vendors | Class | Key parameters | | ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `SpeechmaticsSTT` | `key`, `language`, `model?`, `uri?`. `apiKey` is a deprecated alias of `key` | | `MicrosoftSTT` | `key`, `region`, `language` | | `OpenAISTT` | `apiKey`, `model?`, `language?`, `prompt?`, `inputAudioTranscription?` | | `GoogleSTT` | `projectId`, `location`, `adcCredentialsString`, `language`, `model?` | | `AmazonSTT` | `accessKey`, `secretKey`, `region`, `language` | | `AssemblyAISTT` | `apiKey`, `language`, `ws_url?` | | `AresSTT` | `keywords?`, `additionalParams?` | | `GeminiSTT` | `apiKey`, `model?`, `language?`, `languageHints?`, `customVocabulary?`, `sampleRate?` (default `16000`), `wordTimestamp?`, `mode?` (`SMART` or `VERBATIM`), `diarization?`, `additionalParams?` | | `XAiSTT` | `apiKey`, `language?`, `baseUrl?`, `sampleRate?`, `additionalParams?` | | `SarvamSTT` | `apiKey`, `language`, `model?` | | `SmallestAISTT` | `apiKey`, `language?`, `url?`, `sampleRate?`, `encoding?`, `keywords?`, `additionalParams?` | `SmallestAISTT` also accepts the boolean options `wordTimestamps?`, `sentenceTimestamps?`, `diarize?`, `vadEvents?`, `endpointing?`, `format?`, `finalizeOnWords?`, `punctuate?`, `capitalize?`, `itnNormalize?`, `fullTranscript?`, `redactPii?`, and `redactPci?`, plus `eouTimeoutMs?` and `maxWords?`. Boolean options are serialized as the strings `"true"` or `"false"` for the Smallest AI wire protocol. For details, see [Smallest AI](/en/ai/models/asr/smallest-ai). For `OpenAISTT`, the serialized configuration requires a transcription `prompt` and `language` — provide them through the `prompt` and `language` options or within `inputAudioTranscription`. `model` defaults to `gpt-4o-mini-transcribe`. ### MLLM vendors Use with [`withMllm()`](#withmllmvendor) for multimodal end-to-end audio processing without separate STT or TTS steps. Calling `withMllm()` automatically enables the MLLM module (sets `mllm.enable = true`); the older `advancedFeatures.enable_mllm` flag is deprecated. #### OpenAIRealtime ```typescript new OpenAIRealtime(options: OpenAIRealtimeOptions) ``` | Option | Type | Required | Description | | ------------------------- | --------------------------- | -------- | ---------------------------------------------------------------------- | | `apiKey` | `string` | Yes | OpenAI API key | | `model` | `string` | No | Model name, for example `'gpt-4o-realtime-preview'` | | `voice` | `string` | No | Voice identifier | | `instructions` | `string` | No | System instructions | | `inputAudioTranscription` | `Record` | No | Audio transcription settings | | `url` | `string` | No | WebSocket URL | | `greetingMessage` | `string` | No | Agent greeting message | | `failureMessage` | `string` | No | Message played when the model call fails | | `inputModalities` | `string[]` | No | Input modalities, for example `['audio']` | | `outputModalities` | `string[]` | No | Output modalities, for example `['text', 'audio']` | | `messages` | `Record[]` | No | Conversation messages for short-term memory | | `params` | `Record` | No | Additional MLLM parameters | | `turnDetection` | `MllmTurnDetectionConfig` | No | MLLM turn detection configuration; overrides top-level `turnDetection` | #### AzureOpenAIRealtime ```typescript new AzureOpenAIRealtime(options: AzureOpenAIRealtimeOptions) ``` | Option | Type | Required | Description | | ------------------ | --------------------------- | -------- | ---------------------------------------------------------------------- | | `apiKey` | `string` | Yes | Azure OpenAI API key | | `url` | `string` | Yes | Azure OpenAI Realtime WebSocket URL | | `turnDetection` | `MllmTurnDetectionConfig` | Yes | MLLM turn detection configuration; overrides top-level `turnDetection` | | `model` | `string` | No | Azure OpenAI Realtime model or deployment name | | `voice` | `string` | No | Voice identifier | | `instructions` | `string` | No | System instructions | | `maxHistory` | `number` | No | Number of conversation history messages to cache | | `greetingMessage` | `string` | No | Agent greeting message | | `outputModalities` | `string[]` | No | Output modalities, for example `['text', 'audio']` | | `messages` | `Record[]` | No | Conversation messages for short-term memory | | `params` | `AzureOpenAIRealtimeParams` | No | Additional Azure OpenAI parameters | #### GeminiLive ```typescript new GeminiLive(options: GeminiLiveOptions) ``` | Option | Type | Required | Description | | ------------------ | --------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------- | | `apiKey` | `string` | Yes | Google API key | | `model` | `string` | Yes | Model name, for example `'models/gemini-3.8-live-extended-thinking'` | | `thinkingLevel` | `GeminiThinkingLevel` | No | Reasoning budget (`'low'`, `'medium'`, or `'high'`), supported only by `'models/gemini-3.8-live-extended-thinking'` | | `url` | `string` | No | WebSocket URL | | `instructions` | `string` | No | System instructions for the model | | `voice` | `string` | No | Voice name, for example `'Aoede'` or `'Charon'` | | `affectiveDialog` | `boolean` | No | Enable affective dialog | | `proactiveAudio` | `boolean` | No | Enable proactive audio | | `transcribeAgent` | `boolean` | No | Transcribe agent speech | | `transcribeUser` | `boolean` | No | Transcribe user speech | | `httpOptions` | `Record` | No | HTTP options | | `greetingMessage` | `string` | No | Agent greeting message | | `failureMessage` | `string` | No | Message played when the model call fails | | `inputModalities` | `string[]` | No | Input modalities | | `outputModalities` | `string[]` | No | Output modalities | | `messages` | `Record[]` | No | Conversation messages for short-term memory | | `additionalParams` | `Record` | No | Additional parameters | | `turnDetection` | `MllmTurnDetectionConfig` | No | MLLM turn detection configuration; overrides top-level `turnDetection` | #### VertexAI ```typescript new VertexAI(options: VertexAIOptions) ``` | Option | Type | Required | Description | | ---------------------- | --------------------------- | -------- | ------------------------------------------------------------------------------ | | `model` | `string` | Yes | Model name, for example `'gemini-live-2.5-flash-preview-native-audio-09-2025'` | | `projectId` | `string` | Yes | Google Cloud project ID | | `location` | `string` | Yes | Google Cloud location or region | | `adcCredentialsString` | `string` | Yes | Application Default Credentials JSON string | | `url` | `string` | No | WebSocket URL | | `instructions` | `string` | No | System instructions for the model | | `voice` | `string` | No | Voice name, for example `'Aoede'` or `'Charon'` | | `affectiveDialog` | `boolean` | No | Enable affective dialog | | `proactiveAudio` | `boolean` | No | Enable proactive audio | | `transcribeAgent` | `boolean` | No | Transcribe agent speech | | `transcribeUser` | `boolean` | No | Transcribe user speech | | `httpOptions` | `Record` | No | HTTP options | | `greetingMessage` | `string` | No | Agent greeting message | | `failureMessage` | `string` | No | Message played when the model call fails | | `inputModalities` | `string[]` | No | Input modalities | | `outputModalities` | `string[]` | No | Output modalities | | `messages` | `Record[]` | No | Conversation messages for short-term memory | | `additionalParams` | `Record` | No | Additional parameters | | `turnDetection` | `MllmTurnDetectionConfig` | No | MLLM turn detection configuration; overrides top-level `turnDetection` | #### XaiGrok ```typescript new XaiGrok(options: XaiGrokOptions) ``` | Option | Type | Required | Description | | ------------------ | --------------------------- | -------- | ---------------------------------------------------------------------- | | `apiKey` | `string` | Yes | xAI API key | | `url` | `string` | No | WebSocket URL (defaults to xAI Realtime API) | | `voice` | `string` | No | Voice identifier, for example `'eve'` | | `language` | `string` | No | Language code | | `sampleRate` | `number` | No | Audio sample rate in Hz | | `greetingMessage` | `string` | No | Agent greeting message | | `failureMessage` | `string` | No | Message played when the model call fails | | `inputModalities` | `string[]` | No | Input modalities | | `outputModalities` | `string[]` | No | Output modalities | | `messages` | `Record[]` | No | Conversation messages for short-term memory | | `params` | `Record` | No | Additional xAI parameters | | `turnDetection` | `MllmTurnDetectionConfig` | No | MLLM turn detection configuration; overrides top-level `turnDetection` | #### OpenAIGPTLive [OpenAI GPT-Live](/en/ai/models/mllm/openai-gpt-live) MLLM vendor (`mllm.vendor`: `"openai_gpt_live"`). The constructor throws if `apiKey` is empty. `withMllm()` throws if `url` isn't a full `ws://` or `wss://` endpoint, `headers` isn't a JSON object string, `delegation` isn't `client` or `responses`, or `sessionParams` overrides a protected field. > **Caution: Early access** > > OpenAI GPT-Live is available in early access and isn't intended for production traffic. The SDK automatically routes sessions that use this vendor to the preview endpoint. GPT-Live doesn't support turn detection or input audio transcription. ```typescript new OpenAIGPTLive(options: OpenAIGPTLiveOptions) ``` | Option | Type | Required | Description | | --------------------- | --------------------------- | -------- | ----------------------------------------------------------------------------------------------------------------- | | `apiKey` | `string` | Yes | OpenAI API key | | `model` | `string` | No | Model name. Defaults to `gpt-live-1` | | `voice` | `string` | No | Output voice. Provider default: `marin` | | `prompt` | `string` | No | Session instructions that define the assistant's behavior | | `greeting` | `string` | No | Greeting the agent speaks when a user joins. Serialized as `greeting_message` | | `failureMessage` | `string` | No | Message played when the model call fails | | `url` | `string` | No | Full `ws://` or `wss://` endpoint. Defaults to `wss://api.openai.com/v1/live/sessions` | | `baseUrl` | `string` | No | Host used when `url` is omitted. Defaults to `wss://api.openai.com` | | `path` | `string` | No | WebSocket path used when `url` is omitted. Defaults to `/v1/live/sessions` | | `inputModalities` | `string[]` | No | Input modalities | | `outputModalities` | `string[]` | No | Output modalities | | `messages` | `Record[]` | No | Conversation history passed to the model as context | | `mcpServers` | `McpServersItem[]` | No | MCP servers whose tools GPT-Live can call. Requires `withTools(true)` | | `toolEnabled` | `boolean` | No | Advertise the agent's tools to GPT-Live. Provider default: `false` | | `delegation` | `'client' \| 'responses'` | No | Tool delegation mode: `client` or `responses`. Provider default: `responses`. Can't be changed during the session | | `responsesModel` | `string` | No | Model used for delegated tool calls | | `interruptOnUserTurn` | `boolean` | No | Interrupt playback when the user speaks. Provider default: `false` | | `outputIdleEndMs` | `number` | No | Agent silence boundary in milliseconds. Provider default: `600`. `0` disables inference | | `inputIdleEndMs` | `number` | No | User silence boundary in milliseconds. Provider default: `1500` | | `outputSilencePeak` | `number` | No | Speech amplitude threshold on the 16-bit scale. Provider default: `50` | | `outputSampleRate` | `number` | No | Output PCM sample rate in Hz. Provider default: `24000` | | `outputBufferMs` | `number` | No | Initial audio cushion in milliseconds. Provider default: `0`. A negative value disables pacing | | `inputBatchMs` | `number` | No | Microphone audio batching interval in milliseconds | | `alphaSelector` | `string` | No | OpenAI-Alpha selector for preview contracts. Omitted when not set | | `headers` | `string` | No | Extra provider request headers, as a JSON object string | | `sessionParams` | `Record` | No | Additional session fields. Can't override `model`, `delegation`, `audio`, `instructions`, or `input` | | `params` | `Record` | No | Additional provider parameters. Explicit options take precedence | | `instructions` | `string` | No | Deprecated. Use `prompt` instead | `inputAudioTranscription` and `turnDetection` are deprecated and accepted only for compatibility. GPT-Live doesn't support them: setting `inputAudioTranscription` throws, and the SDK ignores `turnDetection` and logs a warning. ### Avatar vendors Use with [`withAvatar()`](#withavatarvendor). Some avatar vendors require a specific TTS sample rate, enforced at compile time and runtime. #### HeyGenAvatar Deprecated. Use [`LiveAvatarAvatar`](#liveavataravatar) for new integrations. `HeyGenAvatar` still works and serializes `vendor: "heygen"`. Requires TTS at **24,000 Hz**. ```typescript new HeyGenAvatar(options: HeyGenAvatarOptions) ``` | Option | Type | Required | Description | | --------------------- | ----------------------------- | -------- | --------------------------------------------- | | `apiKey` | `string` | Yes | HeyGen API key | | `quality` | `'low' \| 'medium' \| 'high'` | Yes | Video quality: 360p, 480p, or 720p | | `agoraUid` | `string` | Yes | RTC UID for the avatar stream | | `agoraToken` | `string` | No | RTC token for avatar authentication | | `avatarId` | `string` | No | HeyGen avatar ID | | `disableIdleTimeout` | `boolean` | No | Disable idle timeout. Default: `false` | | `activityIdleTimeout` | `number` | No | Idle timeout in seconds. Default: `120` | | `enable` | `boolean` | No | Enable or disable the avatar. Default: `true` | #### AkoolAvatar Requires TTS at **16,000 Hz**. ```typescript new AkoolAvatar(options: AkoolAvatarOptions) ``` | Option | Type | Required | Description | | ---------- | --------- | -------- | --------------------------------------------- | | `apiKey` | `string` | Yes | Akool API key | | `avatarId` | `string` | No | Akool avatar ID | | `enable` | `boolean` | No | Enable or disable the avatar. Default: `true` | #### LiveAvatarAvatar Requires TTS at **24,000 Hz**. ```typescript new LiveAvatarAvatar(options: LiveAvatarAvatarOptions) ``` | Option | Type | Required | Description | | --------------------- | ----------------------------- | -------- | --------------------------------------------- | | `apiKey` | `string` | Yes | LiveAvatar API key | | `quality` | `'low' \| 'medium' \| 'high'` | Yes | Video quality | | `agoraUid` | `string` | Yes | RTC UID for the avatar stream | | `agoraToken` | `string` | No | Avatar token override | | `avatarId` | `string` | No | Avatar ID | | `disableIdleTimeout` | `boolean` | No | Disable idle timeout | | `activityIdleTimeout` | `number` | No | Idle timeout in seconds | | `enable` | `boolean` | No | Enable or disable the avatar. Default: `true` | #### AnamAvatar ```typescript new AnamAvatar(options: AnamAvatarOptions) ``` | Option | Type | Required | Description | | ---------- | --------- | -------- | --------------------------------------------- | | `apiKey` | `string` | Yes | Anam API key | | `avatarId` | `string` | No | Anam avatar ID | | `enable` | `boolean` | No | Enable or disable the avatar. Default: `true` | #### GenericAvatar Generic avatars can omit `agoraAppId`, `agoraChannel`, and `agoraToken`. AgentKit fills them from the session at `start()`. ```typescript new GenericAvatar(options: GenericAvatarOptions) ``` | Option | Type | Required | Description | | ------------------ | ------------------------- | -------- | ---------------------------------------------------------------------------------- | | `apiKey` | `string` | Yes | Custom avatar provider API key | | `apiBaseUrl` | `string` | Yes | Avatar provider API base URL | | `avatarId` | `string` | Yes | Avatar ID | | `agoraUid` | `string` | Yes | RTC UID for the avatar stream | | `agoraAppId` | `string` | No | Agora App ID override | | `agoraChannel` | `string` | No | Agora channel override | | `agoraToken` | `string` | No | Avatar token override | | `enable` | `boolean` | No | Enable or disable the avatar. Default: `true` | | `additionalParams` | `Record` | No | Additional vendor parameters. Explicit options take precedence over matching keys. | #### Tavus Tavus avatars can omit `agoraAppId`, `agoraChannel`, and `agoraToken`. AgentKit fills them from the session at `start()`. Serializes `vendor: "generic"`. For the endpoint and a full example, see [Tavus](/en/ai/models/avatar/tavus). ```typescript new Tavus(options: TavusOptions) ``` | Option | Type | Required | Description | | ------------------ | ------------------------- | -------- | ---------------------------------------------------------------------------------- | | `apiKey` | `string` | Yes | Tavus API key | | `apiBaseUrl` | `string` | Yes | Tavus API base URL | | `avatarId` | `string` | Yes | Tavus avatar ID | | `agoraUid` | `string` | Yes | RTC UID for the avatar stream | | `agoraAppId` | `string` | No | Agora App ID override | | `agoraChannel` | `string` | No | Agora channel override | | `agoraToken` | `string` | No | Avatar token override | | `enable` | `boolean` | No | Enable or disable the avatar. Default: `true` | | `additionalParams` | `Record` | No | Additional vendor parameters. Explicit options take precedence over matching keys. | #### Protoface Protoface avatars can omit `agoraAppId`, `agoraChannel`, and `agoraToken`. AgentKit fills them from the session at `start()`. Serializes `vendor: "generic"`. For the endpoint and a full example, see [Protoface](/en/ai/models/avatar/protoface). ```typescript new Protoface(options: ProtofaceOptions) ``` | Option | Type | Required | Description | | ------------------ | ------------------------- | -------- | ---------------------------------------------------------------------------------- | | `apiKey` | `string` | Yes | Protoface API key | | `apiBaseUrl` | `string` | Yes | Protoface API base URL | | `avatarId` | `string` | Yes | Protoface avatar ID | | `agoraUid` | `string` | Yes | RTC UID for the avatar stream | | `agoraAppId` | `string` | No | Agora App ID override | | `agoraChannel` | `string` | No | Agora channel override | | `agoraToken` | `string` | No | Avatar token override | | `enable` | `boolean` | No | Enable or disable the avatar. Default: `true` | | `additionalParams` | `Record` | No | Additional vendor parameters. Explicit options take precedence over matching keys. | #### LemonSlice LemonSlice avatars can omit `agoraAppId`, `agoraChannel`, and `agoraToken`. AgentKit fills them from the session at `start()`. Serializes `vendor: "generic"`. For the endpoint and a full example, see [LemonSlice](/en/ai/models/avatar/lemonslice). ```typescript new LemonSlice(options: LemonSliceOptions) ``` | Option | Type | Required | Description | | ------------------ | ------------------------- | -------- | ---------------------------------------------------------------------------------- | | `apiKey` | `string` | Yes | LemonSlice API key | | `apiBaseUrl` | `string` | Yes | LemonSlice API base URL | | `avatarId` | `string` | Yes | Always `lemonslice` | | `agoraUid` | `string` | Yes | RTC UID for the avatar stream | | `agoraAppId` | `string` | No | Agora App ID override | | `agoraChannel` | `string` | No | Agora channel override | | `agoraToken` | `string` | No | Avatar token override | | `enable` | `boolean` | No | Enable or disable the avatar. Default: `true` | | `additionalParams` | `Record` | No | Additional vendor parameters. Explicit options take precedence over matching keys. | ## Token utilities Helper functions and classes for generating and managing tokens. Use these when you need control over token lifetime, or when generating tokens outside of a session. ```typescript import { generateConvoAIToken, ExpiresIn } from 'agora-agents'; ``` ### `generateConvoAIToken(options)` Generates a Conversational AI token combining RTC and RTM privileges. This is the same token the SDK generates automatically in app-credentials mode. Use this when you need a token outside of a session, or when passing a pre-built token to [`SessionOptions.token`](#createsessionoptions). ```typescript generateConvoAIToken(options: GenerateConvoAITokenOptions): string ``` | Option | Type | Required | Description | | ----------------- | -------- | -------- | ------------------------------------------------------------- | | `appId` | `string` | Yes | Agora App ID | | `appCertificate` | `string` | Yes | Agora App Certificate | | `channelName` | `string` | Yes | The channel the token grants access to | | `uid` | `number` | Yes | Numeric RTC UID the token is issued for | | `tokenExpire` | `number` | No | Token lifetime in seconds. Default: `86400` | | `privilegeExpire` | `number` | No | Privilege lifetime in seconds. Default: same as `tokenExpire` | **Returns:** `string` — the generated token. **Throws:** if `appId` or `appCertificate` isn't exactly 32 characters. ```typescript const token = generateConvoAIToken({ appId: 'your-app-id', appCertificate: 'your-app-certificate', channelName: 'support-room-123', uid: 1, tokenExpire: ExpiresIn.hours(12), }); ``` ### `ExpiresIn` Helper for specifying token lifetimes. Use with [`SessionOptions.expiresIn`](#createsessionoptions) or [`generateConvoAIToken`](#generateconvoaitokenoptions). Values are validated and capped at the Agora maximum of 86400 seconds (24 hours). | Value or method | Returns | Description | | ---------------------- | -------- | ---------------------------------------------------------------------- | | `ExpiresIn.DAY` | `86400` | 24 hours — the Agora maximum and default | | `ExpiresIn.MAX` | `86400` | The Agora maximum | | `ExpiresIn.HOUR` | `3600` | One hour | | `ExpiresIn.seconds(n)` | `number` | `n` seconds, validated and capped at 24 h | | `ExpiresIn.hours(n)` | `number` | `n` hours in seconds. Throws if `n` ≤ 0, caps at 24 h with a warning | | `ExpiresIn.minutes(n)` | `number` | `n` minutes in seconds. Throws if `n` ≤ 0, caps at 24 h with a warning | ## Types and enums Shared types and enums used across `AgoraClient`, `Agent`, `AgentSession`, and vendor classes. ### `Area` Region used for API routing. Pass to `AgoraClient` via the `area` option. ```typescript import { Area } from 'agora-agents'; ``` | Value | Region | | --------- | -------------- | | `Area.US` | United States | | `Area.EU` | Europe | | `Area.AP` | Asia-Pacific | | `Area.CN` | China mainland | ### `AgoraAuthMode` The resolved authentication mode on an `AgoraClient` instance. Read via `client.authMode`. ```typescript type AgoraAuthMode = "app-credentials" | "token" | "basic"; ``` | Value | Description | | ------------------- | -------------------------------------------------------------- | | `"app-credentials"` | App ID and App Certificate provided. SDK auto-generates tokens | | `"token"` | Pre-built `authToken` provided | | `"basic"` | `customerId` and `customerSecret` provided | ### `AgentSessionEvent` Union type of all valid event names for `session.on()` and `session.off()`. ```typescript type AgentSessionEvent = "started" | "stopped" | "error"; ``` ### `AgentSessionEventHandler` Generic handler type for session event callbacks. ```typescript type AgentSessionEventHandler = (data: T) => void; ``` | Event | `T` | | ----------- | ---------------------------- | | `"started"` | `{ agentId: string }` | | `"stopped"` | `{ agentId: string }` | | `"error"` | `unknown` (the thrown error) | ### `SpeakPriority` Controls how the agent handles a [`say()`](#saytext-options) call relative to its current activity. ```typescript type SpeakPriority = "INTERRUPT" | "APPEND" | "IGNORE"; ``` | Value | Description | | ------------- | --------------------------------------------------------------- | | `"INTERRUPT"` | Agent immediately stops current speech and delivers the message | | `"APPEND"` | Message is queued and delivered after current speech ends | | `"IGNORE"` | Message is discarded if the agent is currently speaking | The `SpeakPriorityInterrupt`, `SpeakPriorityAppend`, and `SpeakPriorityIgnore` constants are also exported. ### `AgoraError` Thrown when the API returns a 4xx or 5xx response. Catch this to inspect the status code and response body. ```typescript import { AgoraError } from 'agora-agents'; try { const agentId = await session.start(); } catch (err) { if (err instanceof AgoraError) { console.error('Status:', err.statusCode); console.error('Message:', err.message); console.error('Body:', err.body); } } ``` | Property | Type | Description | | ------------- | -------------------------- | ------------------------------------------------- | | `statusCode` | `number \| undefined` | HTTP status code returned by the API | | `message` | `string` | Error message, including the status code and body | | `body` | `unknown` | Raw response body from the API, if any | | `rawResponse` | `RawResponse \| undefined` | The raw HTTP response |