TwiML™ Voice: <ConversationRelay>
Legal notice
ConversationRelay, including the <ConversationRelay>
TwiML noun and API, uses artificial intelligence or machine learning technologies. By enabling or using any features or functionalities within Programmable Voice that Twilio identifies as using artificial intelligence or machine learning technology, you acknowledge and agree to certain terms. Your use of these features or functionalities is subject to the terms of the Predictive and Generative AI or ML Features Addendum.
ConversationRelay isn't compliant with the Payment Card Industry (PCI) and doesn't support Voice workflows that are subject to PCI.
Info
Before using ConversationRelay, you need to complete the onboarding steps and agree to the Predictive and Generative AI/ML Features Addendum. See the ConversationRelay Onboarding Guide for more details.
The <ConversationRelay>
TwiML noun under the <Connect>
verb routes a call to Twilio's ConversationRelay service, providing advanced AI-powered voice interactions. ConversationRelay handles the complexities of live, synchronous voice calls, such as Speech-to-Text (STT) and Text-to-Speech (TTS) conversions, session management, and low-latency communication with your application. This approach allows your system to focus on processing conversational AI logic and sending back responses effectively.
In a typical setup, <ConversationRelay>
connects to your AI application through a WebSocket, allowing real-time and event-based interaction. Your application receives transcribed caller speech in structured messages and sends responses as text, which ConversationRelay converts to speech and plays back to the caller. This setup is commonly used for customer service, virtual assistants, and other scenarios that require real-time, AI-based voice interactions.
Before you can use <ConversationRelay>
, make sure you've completed the onboarding steps and configured your Twilio account accordingly.
To ensure the secure operation of <ConversationRelay>
, your WebSocket server must validate incoming requests using the Twilio signature. For detailed guidance on setting up signature validation, see Configure your WebSocket server.
1const VoiceResponse = require('twilio').twiml.VoiceResponse;23const response = new VoiceResponse();4const connect = response.connect({5action: 'https://myhttpserver.com/connect_action'6});7connect.conversationRelay({8url: 'wss://mywebsocketserver.com/websocket',9welcomeGreeting: 'Hi! Ask me anything!'10});1112console.log(response.toString());
Output
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Connect action="https://myhttpserver.com/connect_action">4<ConversationRelay url="wss://mywebsocketserver.com/websocket" welcomeGreeting="Hi! Ask me anything!" />5</Connect>6</Response>
action
(optional): The URL that Twilio will request when the<Connect>
verb ends.url
(required): The URL of your WebSocket server (must use thewss://
protocol).welcomeGreeting
(optional): The message automatically played to the caller after we answer the call and establish the WebSocket connection.
When the TwiML execution is complete, Twilio will make a callback to the action
URL with call information and the return parameters from ConversationRelay
.
ConversationRelay integrates with Conversational Intelligence for native virtual agent observability and performance monitoring. To enable this feature, you need to set the intelligenceService
attribute in the <ConversationRelay>
noun as documented below.
For more details on getting started with the ConversationRelay and Conversational Intelligence integration, please see this guide.
The <ConversationRelay>
noun supports the following attributes:
Attribute name | Description | Default value | Required |
---|---|---|---|
url | The URL to your WebSocket server (must use wss:// ). | Required | |
welcomeGreeting | The message automatically played to the caller after we answer the call and establish the WebSocket connection. | Optional | |
welcomeGreetingInterruptible | Specifies if the caller can interrupt the welcomeGreeting with speech. Values can be "none" , "dtmf" , "speech" , or "any" . For backward compatibility, Boolean values are also accepted: true = "any" and false = "none" . | "any" | Optional |
language | The language code (for example, "en-US" ) that applies to both Speech-to-Text (STT) and Text-to-Speech (TTS). Setting this attribute is equivalent to setting both ttsLanguage and transcriptionLanguage . | "en-US" | Optional |
ttsLanguage | The default language code to use for TTS when the text token message doesn't specify a language. If you set both attributes, this one overrides the language attribute. You can modify this via the ttsLanguage field in the language message you send through the Service Provider Interface (SPI). | Optional | |
ttsProvider | The provider for TTS. Available choices are "Google" , "Amazon" , and "ElevenLabs" . | "ElevenLabs" | Optional |
voice | The voice used for TTS. Options vary based on the ttsProvider . For details, refer to the Twilio TTS Voices. We list additional voices available for ConversationRelay below. | "UgBBYS2sOqTuMpoF3BR0" (ElevenLabs), "en-US-Journey-O" (Google), "Joanna-Neural" (Amazon) | Optional |
transcriptionLanguage | The language code to use for STT when the session starts. If you set both attributes, this one overrides the language attribute for the transcription language. You can modify this via the transcriptionLanguage field in the language message you send through the SPI. | Optional | |
transcriptionProvider | The provider for STT (Speech Recognition). Available choices are "Google" and "Deepgram" . | "Google" | Optional |
speechModel | The speech model used for STT. Choices vary based on the transcriptionProvider . Refer to the provider's documentation for an accurate list. | "telephony" (Google), "nova-2-general" (Deepgram) | Optional |
interruptible | Specifies if caller speech can interrupt TTS playback. Values can be "none" , "dtmf" , "speech" , or "any" . For backward compatibility, Boolean values are also accepted: true = "any" and false = "none" . | "any" | Optional |
dtmfDetection | Specifies whether the system sends Dual-tone multi-frequency (DTMF) keypresses over the WebSocket. Set to true to turn on DTMF events. | Optional | |
reportInputDuringAgentSpeech | Specifies whether your application receives prompts and DTMF events while the agent is speaking. Values can be "none" , "dtmf" , "speech" , or "any" . Note: The default value for this attribute has changed. The default was "any" before May, 2025 and it's now "none" . | "none" | Optional |
preemptible | Specifies if the TTS of the current talk cycle can allow text tokens from the subsequent talk cycle to interrupt. | false | Optional |
hints | A comma-separated list of words or phrases that helps Speech-to-Text recognition for uncommon words, product names, or domain-specific terminology. Works similarly to the hints attribute in <Gather> . | Optional | |
debug | A space-separated list of options that you can use to subscribe to debugging messages. Options are debugging , speaker-events , and tokens-played . The debugging option provides general debugging information. speaker-events will notify your application about agentSpeaking and clientSpeaking events. tokens-played will provide messages about what's just been played over TTS. | Optional | |
elevenlabsTextNormalization | Specifies whether or not to apply text normalization while using the ElevenLabs TTS provider. Options are "on" , "auto" , or "off" . "auto" has the same effect as "off" for ConversationRelay voice calls. | "off" | Optional |
intelligenceService | A Conversational Intelligence Service SID or unique name for persisting conversation transcripts and running Language Operators for virtual agent observability. Please see this guide for more details. | Optional |
We offer TTS provider support for ElevenLabs, which provides additional natural-sounding voice synthesis. Use the interface below to search and filter through a wide selection of voices by language, accent, age, and more. Each voice entry includes a voiceID
that you can copy and paste into your <ConversationRelay>
configuration.
How to Use ElevenLabs Voices
- Search or Filter: Use the tool below to locate a voice that matches your requirements (for example, language, accent, category, age, gender, tag).
- Copy the
voiceID
: From the search results, copy the unique identifier (for example,NYC9WEgkq1u4jiqBseQ9
). - Configure
<ConversationRelay>
: In your TwiML, setttsProvider="ElevenLabs"
and use the copiedvoiceID
in thevoice
attribute.
Example:
1<Connect>2<ConversationRelay url="wss://example.com/websocket" ttsProvider="ElevenLabs" voice="NYC9WEgkq1u4jiqBseQ9" ... />3</Connect>
If you don't explicitly specify the voice attribute in your <ConversationRelay>
configuration, ConversationRelay automatically applies a default voice based on the language setting (as defined by the language or ttsLanguage attribute) and the selected TTS provider (default is ElevenLabs). Below is the complete list of default voice settings:
Language | Voice ID | TTS provider | Speech model | Transcription provider |
---|---|---|---|---|
bg-BG | AB9XsbSA4eLG12t2myjN | ElevenLabs | long | |
cs-CZ | uYFJyGaibp4N2VwYQshk | ElevenLabs | long | |
da-DK | ygiXC2Oa1BiHksD3WkJZ | ElevenLabs | long | |
de-DE | FTNCalFNG5bRnkkaP5Ug | ElevenLabs | telephony | |
en-AU | 9Ft9sm9dzvprPILZmLJl | ElevenLabs | telephony | |
en-GB | Fahco4VZzobUeiPqni1S | ElevenLabs | telephony | |
en-IN | mCQMfsqGDT6IDkEKR20a | ElevenLabs | long | |
en-US | UgBBYS2sOqTuMpoF3BR0 | ElevenLabs | telephony | |
es-ES | 6xftrpatV0jGmFHxDjUv | ElevenLabs | telephony | |
es-US | CaJslL1xziwefCeTNzHv | ElevenLabs | telephony | |
fi-FI | 6xPz2opT0y5qtoRh1U1Y | ElevenLabs | long | |
fr-CA | IPgYtHTNLjC7Bq7IPHrm | ElevenLabs | telephony | |
fr-FR | a5n9pJUnAhX4fn7lx3uo | ElevenLabs | telephony | |
hi-IN | IvLWq57RKibBrqZGpQrC | ElevenLabs | long | |
hu-HU | TumdjBNWanlT3ysvclWh | ElevenLabs | long | |
id-ID | 1k39YpzqXZn52BgyLyGO | ElevenLabs | long | |
it-IT | uScy1bXtKz8vPzfdFsFw | ElevenLabs | telephony | |
ja-JP | 3JDquces8E8bkmvbh6Bc | ElevenLabs | telephony | |
kn-IN | kn-IN-Standard-A | long | ||
ko-KR | uyVNoMrnUku1dZyVEXwD | ElevenLabs | telephony | |
ml-IN | ml-IN-Standard-A | long | ||
mr-IN | mr-IN-Standard-A | long | ||
nl-BE | s7Z6uboUuE4Nd8Q2nye6 | ElevenLabs | telephony | |
nl-NL | UNBIyLbtFB9k7FKW8wJv | ElevenLabs | telephony | |
pl-PL | W0sqKm1Sfw1EzlCH14FQ | ElevenLabs | long | |
pt-BR | CstacWqMhJQlnfLPxRG4 | ElevenLabs | telephony | |
pt-PT | TsZfI8Nbn2Xd7ArC76n9 | ElevenLabs | telephony | |
ro-RO | OlBp4oyr3FBAGEAtJOnU | ElevenLabs | long | |
ru-RU | AB9XsbSA4eLG12t2myjN | ElevenLabs | long | |
sv-SE | 4xkUqaR9MYOJHoaC1Nak | ElevenLabs | long | |
ta-IN | ZhJ5LanYnCmLKQUXvsV7 | ElevenLabs | long | |
te-IN | te-IN-Standard-A | long | ||
th-TH | th-TH-Standard-A | long | ||
tr-TR | IuRRIAcbQK5AQk1XevPj | ElevenLabs | long | |
uk-UA | nCqaTnIbLdME87OuQaZY | ElevenLabs | long | |
vi-VN | foH7s9fX31wFFH2yqrFa | ElevenLabs | long |
Our internal configuration defines these default settings and updates them periodically. Refer to the Twilio Twilio TTS Voices documentation for a complete and current list of supported languages, default voices, and detailed settings.
By understanding these defaults, you can decide when it's necessary to explicitly set the voice parameter to achieve the desired auditory experience for your application.
For additional voices from Google or Amazon (including generative options), refer to our Twilio TTS Voices documentation. Each provider offers a variety of languages and styles, enabling you to tailor your application's voice experience to your specific needs.
Include nested elements within <ConversationRelay>
for more granular configuration. For more information on configuring ConversationRelay, refer to the ConversationRelay Onboarding Guide.
The <Language>
element maps a language code to specific TTS and STT settings. Use this element to configure multiple languages for your session.
Example
1const VoiceResponse = require('twilio').twiml.VoiceResponse;23const response = new VoiceResponse();4const connect = response.connect();5const conversationrelay = connect.conversationRelay({6url: 'wss://mywebsocketserver.com/websocket'7});8conversationrelay.language({9code: 'sv-SE',10ttsProvider: 'amazon',11voice: 'Elin-Neural',12transcriptionProvider: 'google',13speechModel: 'long'14});15conversationrelay.language({16code: 'en-US',17ttsProvider: 'google',18voice: 'en-US-Journey-O'19});2021console.log(response.toString());
Output
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Connect>4<ConversationRelay url="wss://mywebsocketserver.com/websocket">5<Language code="sv-SE" ttsProvider="amazon" voice="Elin-Neural" transcriptionProvider="google" speechModel="long"/>6<Language code="en-US" ttsProvider="google" voice="en-US-Journey-O" />7</ConversationRelay>8</Connect>9</Response>
Attributes
Attribute name | Description of attributes | Default value | Required |
---|---|---|---|
code | The language code (for example, "en-US" ) that applies to both STT and TTS. | Required | |
ttsProvider | The provider for TTS. Choices are "Google" , "Amazon" , and "ElevenLabs" . | Inherited from <ConversationRelay> | Optional |
voice | The voice used for TTS. Choices vary based on the ttsProvider . | Inherited from <ConversationRelay> | Optional |
transcriptionProvider | The provider for STT. Choices are "Google" and "Deepgram" . | Inherited from <ConversationRelay> | Optional |
speechModel | The speech model used for STT. Choices vary based on the transcriptionProvider . | Inherited from <ConversationRelay> | Optional |
language | The language code for the session (for example, "en-US" ). | "en-US" | Optional |
customParameter | Custom parameters to be sent in the setup message. | Optional |
Notes
- If you specify the same language code in both
<ConversationRelay>
and<Language>
, the settings in<Language>
take precedence. ConversationRelay
provides default settings for commonly used languages.
The <Parameter>
element allows you to send custom parameters from the TwiML directly into the initial "setup" message sent over the WebSocket. These parameters appear under the customParameters
field in the JSON message.
Example
1const VoiceResponse = require('twilio').twiml.VoiceResponse;23const response = new VoiceResponse();4const connect = response.connect();5const conversationrelay = connect.conversationRelay({6url: 'wss://mywebsocketserver.com/websocket'7});8conversationrelay.parameter({9name: 'foo',10value: 'bar'11});12conversationrelay.parameter({13name: 'hint',14value: 'Annoyed customer'15});1617console.log(response.toString());
Output
1<?xml version="1.0" encoding="UTF-8"?>2<Response>3<Connect>4<ConversationRelay url="wss://mywebsocketserver.com/websocket">5<Parameter name="foo" value="bar"/>6<Parameter name="hint" value="Annoyed customer"/>7</ConversationRelay>8</Connect>9</Response>
Resulting Setup Message
1{2"type": "setup",3"sessionId": "VX00000000000000000000000000000000",4"callSid": "CA00000000000000000000000000000000",5"...": "...",6"customParameters": {7"foo": "bar",8"hint": "Annoyed customer"9}10}
Language settings refer to configurations for both Text-to-Speech and Speech-to-Text:
- Text-to-Speech (TTS) settings:
ttsLanguage
ttsProvider
voice
- Speech-to-Text (STT) settings:
transcriptionLanguage
transcriptionProvider
speechModel
Configure language settings in two places:
- Attributes of
<ConversationRelay>
: These serve as the default settings used when the session starts. - Within
<Language>
Elements: Each<Language>
element configures settings for a specific language code. You can include multiple<Language>
elements to support multiple languages.
- In
<ConversationRelay>
, thettsLanguage
attribute overrides thelanguage
attribute for the default TTS language. - In
<ConversationRelay>
, thetranscriptionLanguage
attribute overrides thelanguage
attribute for the STT language. - If a
<Language>
element specifies the samecode
attribute as in<ConversationRelay>
, the<Language>
element's settings take precedence. - The system uses default values when you don't provide specific settings.
Default Values
language
: Defaults toen-US
if not specified.ttsProvider
: Defaults toElevenLabs
if not specified.transcriptionProvider
: Defaults toGoogle
if not specified.- If you set the
ttsProvider
attribute without thevoice
attribute, the system uses a default voice for that provider. - If you set the
transcriptionProvider
attribute without thespeechModel
attribute, the system uses a default model for that provider. - If you set the
voice
attribute without thettsProvider
attribute, the system infers the provider from the default or specifiedttsProvider
. - If you set the
speechModel
attribute without thetranscriptionProvider
attribute, the system infers the provider from the default or specifiedtranscriptionProvider
.
For Speech-to-Text (STT) settings:
- At session start, the service uses the
transcriptionLanguage
attribute to initiate the STT session. - If the combination of the
transcriptionProvider
andspeechModel
attributes is invalid, the call disconnects, and the system reports an error in the action callback and error notifications. - You can change the
transcriptionLanguage
attribute during the session via thelanguage
message you send through the Service Provider Interface (SPI).
For Text-to-Speech (TTS) settings:
- When the
lang
property is present in thetext
token message from the SPI, the service uses it to select the TTS voice. - If the combination of the
ttsProvider
andvoice
attributes is invalid, the system sends an error message over the SPI. - If you don't specify the
lang
property in thetext
token, the service uses the current TTS language settings.
ConversationRelay
interacts with your application server via a WebSocket connection specified by the url
attribute. Messages exchanged follow this Service Provider Interface (SPI) specification.
ConversationRelay validates all incoming SPI messages to ensure they conform to the expected format. If validation fails, Twilio returns error 64107 with details about the validation failure. The following validation rules apply:
- The
token
field can't benull
or missing. - If
lang
is provided, it must be one of the supported languages.
- The
source
field must contain a valid URL.
- The
digits
field can't benull
or empty. - The
digits
field must only contain the characters 0-9, w, #, and *.
- Either
ttsLanguage
ortranscriptionLanguage
must be present. - If provided,
ttsLanguage
must be one of the supported languages. - If provided,
transcriptionLanguage
must be one of the supported languages.
Info
ConversationRelay validates messages but continues the session even when it returns an error 64107 for non-conforming requests. These validation messages are informative only.
ConversationRelay sends this message immediately after establishing the WebSocket connection.
1{2"type": "setup",3"sessionId": "VX00000000000000000000000000000000",4"callSid": "CA00000000000000000000000000000000",5"from": "+14151234567",6"to": "+18881234567",7"direction": "inbound",8"...": "...",9"customParameters" : {10"foo": "bar"11}12}
ConversationRelay sends this message when the caller says something.
1{2"type": "prompt",3"voicePrompt": "Hi! Can you tell me about life?",4"lang": "en-US",5"last": true6}
ConversationRelay sends this message when you turn on DTMF detection and the caller presses a key.
1{2"type": "dtmf",3"digit": "1"4}
ConversationRelay sends this message when the caller interrupts TTS playback by speaking.
1{2"type": "interrupt",3"utteranceUntilInterrupt": "Life is a complex set of",4"durationUntilInterruptMs": "460"5}
ConversationRelay sends this message when an error occurs during the session.
1{2"type": "error",3"description": "Invalid message received: { \"foo\" : \"bar\" }"4}
Send text tokens, and ConversationRelay converts them into speech.
1{2"type": "text",3"token": "Hello world!",4"last": false5}
token
attribute (Required): Converts the provided text to speech.last
attribute (Optional, default isfalse
): Indicates whether this is the last token in the current message.
Best practices
- Use streaming text tokens for smoother TTS playback.
- Set
"last": true
when you have sent the final token of a message.
Request to play media to the caller.
1{2"type": "play",3"source": "https://api.twilio.com/cowbell.mp3",4"loop": 1,5"preemptible": false6}
source
attribute (Required): The URL of the media to play.loop
attribute (Optional, default is1
): Number of times to play the media. A value of0
plays it 1,000 times (maximum).preemptible
attribute (Optional, default isfalse
): If set totrue
, subsequenttext
orplay
messages will stop this media playback.
Request to send DTMF digits to the caller. ConversationRelay sends digits as per Twilio's <Play>
digits
attribute.
1{2"type": "sendDigits",3"digits": "9www4085551212"4}
Change the transcription and TTS language during the session.
1{2"type": "language",3"ttsLanguage": "sv-SE",4"transcriptionLanguage": "en-US"5}
Info
This affects future TTS and STT sessions.
End the session and return control of the call to Twilio through ConversationRelay
.
1{2"type": "end",3"handoffData": "{\"reasonCode\":\"live-agent-handoff\", \"reason\": \"The caller wants to talk to a real person\"}"4}
handoffData
attribute (Optional): A string containing data to pass back in the action callback.
When an action
URL is specified in the <Connect>
verb, ConversationRelay
will make a request to that URL when the <Connect>
verb ends. The request includes call information and session details.
Example Payloads
1{2"AccountSid": "AC00000000000000000000000000000000",3"CallSid": "CA00000000000000000000000000000000",4"CallStatus": "in-progress",5"From": "client:caller",6"To": "test:conversationrelay",7"Direction": "inbound",8"ApplicationSid": "AP00000000000000000000000000000000",9"SessionId": "VX00000000000000000000000000000000",10"SessionStatus": "ended",11"SessionDuration": "25",12"HandoffData": "{\"reason\": \"The caller requested to talk to a real person\"}"13}
1{2"AccountSid": "AC00000000000000000000000000000000",3"CallSid": "CA00000000000000000000000000000000",4"CallStatus": "in-progress",5"From": "client:caller",6"To": "test:conversationrelay",7"Direction": "inbound",8"ApplicationSid": "AP00000000000000000000000000000000",9"SessionId": "VX00000000000000000000000000000000",10"SessionStatus": "failed",11"SessionDuration": "10",12"ErrorCode": "39001",13"ErrorMessage": "Network connection to WebSocket server failed."14}
1{2"AccountSid": "AC00000000000000000000000000000000",3"CallSid": "CA00000000000000000000000000000000",4"CallStatus": "completed",5"From": "client:caller",6"To": "test:conversationrelay",7"Direction": "inbound",8"ApplicationSid": "AP00000000000000000000000000000000",9"SessionId": "VX00000000000000000000000000000000",10"SessionStatus": "completed",11"SessionDuration": "35"12}
- Streaming Text Tokens: For smoother TTS playback, stream text tokens incrementally and set
"last": true
when the message is complete. - Error Handling: Monitor for
error
messages sent over the SPI to handle any issues promptly. - Language Switching: Use the
language
message to switch languages dynamically during a session. - Session Management: Use the
end
message to gracefully end sessions when your application logic determines it's appropriate. - Don't "wait" to send text tokens back from the Large Language Model (LLM); send them as you receive them.
- To achieve the lowest latency, use the partial completions (streaming) through the LLM APIs. That way, the system sends each word in separate text tokens. The last one of that has
last=true
. This enables ConversationRelay to identify the first sayable string. - Don't trim LLM tokens; the tokens need to have spaces between them.
- Setting the
last
flag properly- When sending text tokens that include punctuation, ensure the final token in the message includes
"last": true
. - Without a final token marked with
"last": true
, ConversationRelay assumes additional tokens are forthcoming and may stop reading at the first punctuation mark (for example, period, comma, or question mark).
- When sending text tokens that include punctuation, ensure the final token in the message includes
- Using partial completions for streaming
-
In streaming mode, send each text token incrementally with
"last": false
. -
When the LLM indicates that the response is complete (for example, when
response.finish_reason()
equals"stop"
), mark that final token with"last": true
.Example:
1{ "type": "text", "token": "Hello", "last": false }2{ "type": "text", "token": " world", "last": false }3{ "type": "text", "token": "!", "last": true }
-
- Handling complete responses (non-streaming)
-
In non-streaming mode, when the entire response is generated as a single complete sentence, mark the token with
"last": true
.Example:
{ "type": "text", "token": "Hello world!", "last": true }
-
- Punctuation handling in longer messages
- For messages with complex punctuation, consider breaking the response into smaller chunks.
- Each chunk should have the appropriate punctuation, with only the final token of the overall message marked with
"last": true
.
By following these guidelines, you can ensure that ConversationRelay processes and speaks your full message smoothly without unexpected pauses or truncation.
When setting up system prompts for Large Language Models (LLMs) in ConversationRelay
, consider these best practices to ensure optimal performance with Text-to-Speech (TTS) in ConversationRelay:
- Explicit Number Formatting: Encourage the LLM to spell out numbers (for example, "two" instead of "2") to avoid misinterpretation by TTS.
- Avoid Special Characters: Avoid bullet points, asterisks, or special symbols, as these can cause pauses or mispronunciations in voice output.
- Focus on Conversational Tone: Design prompts to produce conversational, naturally flowing responses, which translate more effectively to TTS.
These prompt adjustments help improve the LLM-generated tokens' compatibility with voice output in ConversationRelay, enhancing clarity and consistency for users.
All WebSocket messages from ConversationRelay to your API follow the strict formats defined in these docs. Your application must also adhere to these specifications when sending messages back to ConversationRelay.
- Use One-Way Communication: Managed API services like AWS API Gateway often support two-way communication, but this approach doesn't work with ConversationRelay. Two-way communication may cause your application to send back non-conforming messages, causing us to terminate the session.
- Explicit Message Handling: Use one-way communication only, ensuring precise control over what and when you send messages to ConversationRelay.
Following these practices helps maintain session stability and ensures compatibility with ConversationRelay's message handling.
When working with Text-to-Speech (TTS) in ConversationRelay, proper text normalization is important for delivering clear and natural spoken responses. This is especially important when using ElevenLabs voices, which may have difficulty with certain formats. Consider the following guidelines:
- Numbers and Units: Write numbers as words for improved pronunciation. For example, write "twenty dollars and fifty cents" instead of "$20.50".
- Dates: Spell out dates completely (for example, "March twenty-eighth, two thousand twenty-five" instead of "03/28/2025").
- Email Addresses: Replace or spell out special characters. For instance, write "user at example dot com" rather than "user@example.com" since the "@" sign may be mispronounced.
- Names: Use consistent formatting for names throughout the call to avoid variations (for example, always use "Anna" rather than alternating between "A-nna" and "Ah-nna").
- Abbreviations: Spell out abbreviations that should be pronounced fully (for example, "Doctor" instead of "Dr.").
- Special Characters: Replace special characters with their spoken equivalents (for example, "percent" instead of "%").
- Punctuation: Use appropriate punctuation to create natural pauses and intonation.
- Acronyms and Initialisms: Insert spaces between letters if they must be spelled out (for example, "H T T P" for letter-by-letter pronunciation).
If you use the ElevenLabs TTS provider then you can also use the elevenlabsTextNormalization
TwiML attribute to help with text normalization. Setting this attribute to on
will tell ElevenLabs to take an extra step to normalize text for you. Set the attribute to off
for more control over the text normalization process and lower latency.
For detailed text normalization guidelines, refer to ElevenLabs' text normalization best practices.
Text-to-Speech (TTS) voice quality varies significantly by provider and voice type. While generative voices often offer higher fidelity and more natural-sounding responses, they can introduce additional latency and process TTS at a slower rate.
- Quality versus Latency: Generative voices may produce more realistic responses but could add latency, affecting real-time applications.
- Test Before Production: We recommend testing various providers and voices to determine the best balance of quality and responsiveness for your specific use case.
Selecting the right TTS voice involves balancing quality and performance, so thorough testing is essential before production deployment.
Speech-to-Text (STT) quality and latency can vary depending on the provider and the environment. Google and Deepgram each offer unique strengths for different scenarios, such as clean versus noisy audio environments.
- Environment Sensitivity: Some models may perform better in noisy environments, while others excel with clean audio. Test in environments that reflect your actual use case.
- Customize for Optimal Recognition: We encourage testing various combinations of STT providers and speech models to find the best quality and responsiveness for your application.
Optimizing STT performance requires careful selection based on environment and model capabilities, so thorough testing is essential for achieving the best results.
In the event of a WebSocket connection error in ConversationRelay
, implement reconnection logic by initiating a new <Connect><ConversationRelay>
request:
- Re-establish the Connection in
ConversationRelay
: If you lose the WebSocket connection, handle the disconnect in your<Connect>
element'saction
URL callback by returning new TwiML containing<Connect><ConversationRelay>
to restore the session. - Validate Call Consistency in
ConversationRelay
: Ensure the callSid remains the same to confirm continuity of the original call session.
This approach helps maintain session stability and consistency following any connection disruptions.
When you switch languages during a session via an SPI message, ConversationRelay uses the pre-set voice associated with the new language that you configured in the initial TwiML setup. If you didn't configure a specific voice for that language, ConversationRelay will use its default voice for the selected language.
- Initial Language Configuration: To maintain a consistent voice experience across languages, define the desired voice for each supported language explicitly in the TwiML configuration. This setup ensures that when you change the language via an SPI message during the session, the specified voice is used. This prevents the system from defaulting to its own voice.
- Voice on Language Change: If you issue a language change and haven't set a specific voice for that language in TwiML, the system will use its default voice for that language. For example, switching from English (en-GB) with a male voice to Spanish (es-ES) may result in a female voice if the default Spanish voice is female.
- No Voice Updates Mid-Session: Once the session starts, you can't modify voice and language configurations set in TwiML through SPI messages.
This setup ensures consistent voice behavior for each language by configuring it in TwiML before the call begins.
ConversationRelay supports both streaming and non-streaming modes for sending LLM responses. Each mode has unique trade-offs in latency and response fluidity:
- Non-Streaming Mode: In non-streaming mode, you send the full LLM response to ConversationRelay at once. This approach, while slightly more latent for initial responses, can provide a smoother and more consistent TTS experience, with less variability in pacing and fluidity of the speech output.
- Latency Trade-Off: Initial response time (time to first token) is longer in non-streaming mode, which may affect perceived responsiveness for the first reply.
- When to Use: Non-streaming mode can be effective if the session prioritizes TTS consistency over immediate response speed.
- Streaming Mode: Streaming mode sends text tokens incrementally as they're generated by the LLM, allowing ConversationRelay to start speaking sooner. This provides quicker initial responses but may introduce slight variability in TTS pacing and fluidity.
- Responsiveness: Streaming mode minimizes latency in initial responses, making it ideal for real-time interactions where responsiveness is critical.
- Goal of Streaming Mode: While streaming mode may not be perfect in all cases, we recommend it for most applications, and improvements are ongoing to enhance fluidity in TTS output.
- Recommendation for Streaming Mode: Both modes are viable, and you can experiment with streaming or non-streaming to find the best balance of response time and TTS quality for your use case. For non-streaming, send text in bulk once the LLM response is complete. For streaming, send text tokens in smaller chunks as they become available.
For errors, such as messages that ConversationRelay doesn't understand, we will respond with an error message.
If your WebSocket sends unidentified messages to ConversationRelay and the last 10 messages remain unidentified, we will terminate the connection. The status code will be 1007 with the reason "Too many consecutive malformed messages." In that case, we will report an error 64105 "WebSocket Ended."
If the WebSocket disconnects unexpectedly in ConversationRelay, we don't reconnect, and the call disconnects with a failed
status.
ConversationRelay
, including the <ConversationRelay>
TwiML nouns and APIs, use artificial intelligence or machine learning technologies.
Our AI Nutrition Facts for ConversationRelay
provide an overview of the AI feature you're using, so you can better understand how the AI is working with your data. The below AI Nutrition Label details the ConversationRelay AI qualities. For more information and the glossary regarding the AI Nutrition Facts Label, refer to our AI Nutrition Facts page.
AI Nutrition Facts
ConversationRelay (STT and TTS) - Programmable Voice - Deepgram
- Description
- Generate speech to text in real-time through a WebSocket API in Programmable Voice.
- Privacy Ladder Level
- N/A
- Feature is Optional
- Yes
- Model Type
- Automatic Speech Recognition
- Base Model
- Deepgram Nova2
- Base Model Trained with Customer Data
- No
- Customer Data is Shared with Model Vendor
- No
- Training Data Anonymized
- N/A
- Data Deletion
- N/A
- Human in the Loop
- Yes
- Data Retention
- N/A
- Logging & Auditing
- Yes
- Guardrails
- Yes
- Input/Output Consistency
- Yes
- Other Resources
- Learn more about this label at nutrition-facts.ai
Trust Ingredients
ConversationRelay uses the Default Base Model provided by the Model Vendor. The Base Model is not trained using Customer Data.
ConversationRelay uses the Default Base Model provided by the Model Vendor. The Base Model is not trained using Customer Data.
Base Model is not trained using any Customer Data.
Customer Data is not stored or retained in the Base Model.
Customer can view and listen to the input and output in the customer's own terminal.
Compliance
Customer can view and listen to the input and output in the customer's own terminal.
Customer can view and listen to the input and output in the customer's own terminal.
Customer is responsible for human review.
Learn more about this label at nutrition-facts.ai
AI Nutrition Facts
ConversationRelay (STT and TTS) - Programmable Voice - Google AI
- Description
- Generate speech to text in real-time and convert text into natural-sounding speech through a WebSocket API in Programmable Voice.
- Privacy Ladder Level
- N/A
- Feature is Optional
- Yes
- Model Type
- Generative and Predictive - Automatic Speech Recognition and Text-to-Speech
- Base Model
- Google Speech-to-Text; Google Text-to-Speech
- Base Model Trained with Customer Data
- No
- Customer Data is Shared with Model Vendor
- No
- Training Data Anonymized
- N/A
- Data Deletion
- N/A
- Human in the Loop
- Yes
- Data Retention
- N/A
- Logging & Auditing
- Yes
- Guardrails
- Yes
- Input/Output Consistency
- Yes
- Other Resources
- Learn more about this label at nutrition-facts.ai
Trust Ingredients
ConversationRelay uses the Default Base Model provided by the Model Vendor. The Base Model is not trained using Customer Data.
ConversationRelay uses the Default Base Model provided by the Model Vendor. The Base Model is not trained using Customer Data.
Base Model is not trained using any Customer Data.
Customer Data is not stored or retained in the Base Model.
Customer can view and listen to the input and output in the customer's own terminal.
Compliance
Customer can view and listen to the input and output in the customer's own terminal.
Customer can view and listen to the input and output in the customer's own terminal.
Customer is responsible for human review.
Learn more about this label at nutrition-facts.ai
AI Nutrition Facts
ConversationRelay (STT and TTS) - Programmable Voice - Amazon AI
- Description
- Convert text into natural sounding speech through a websocket API in Programmable Voice.
- Privacy Ladder Level
- N/A
- Feature is Optional
- Yes
- Model Type
- Generative and Predictive
- Base Model
- Amazon Polly Text-to-Speech
- Base Model Trained with Customer Data
- No
- Customer Data is Shared with Model Vendor
- No
- Training Data Anonymized
- N/A
- Data Deletion
- N/A
- Human in the Loop
- Yes
- Data Retention
- N/A
- Logging & Auditing
- Yes
- Guardrails
- Yes
- Input/Output Consistency
- Yes
- Other Resources
- Learn more about this label at nutrition-facts.ai
Trust Ingredients
ConversationRelay uses the Default Base Model provided by the Model Vendor. The Base Model is not trained using Customer Data.
ConversationRelay uses the Default Base Model provided by the Model Vendor. The Base Model is not trained using Customer Data.
Base Model is not trained using any Customer Data.
Customer Data is not stored or retained in the Base Model.
Customer can view and listen to the input and output in the customer's own terminal.
Compliance
Customer can view and listen to the input and output in the customer's own terminal.
Customer can view and listen to the input and output in the customer's own terminal.
Customer is responsible for human review.
Learn more about this label at nutrition-facts.ai
AI Nutrition Facts
ConversationRelay (STT and TTS) - Programmable Voice - ElevenLabs
- Description
- Convert text into a human-sounding voice using speech synthesis technology from ElevenLabs.
- Privacy Ladder Level
- N/A
- Feature is Optional
- Yes
- Model Type
- Predictive
- Base Model
- ElevenLabs Text-To-Speech: Flash 2 and Flash 2.5
- Base Model Trained with Customer Data
- No
- Customer Data is Shared with Model Vendor
- No
- Training Data Anonymized
- N/A
- Data Deletion
- N/A
- Human in the Loop
- Yes
- Data Retention
- Customer can review TwiML logs, including <Say> Logs, to debug and troubleshoot for up to 30 days.
- Logging & Auditing
- Yes
- Guardrails
- Yes
- Input/Output Consistency
- Yes
- Other Resources
- Learn more about this label at nutrition-facts.ai
Trust Ingredients
The Base Model is not trained using any Customer Data.
Programmable Voice uses the default Base Model provided by the Model Vendor. The Base Model is not trained using customer data.
Base Model is not trained using any Customer Data.
The Base Model is not trained using any Customer Data.
Customers can view text input and listen to the audio output.
Compliance
Customers can view text input and listen to the audio output.
Customers can view text input and listen to the audio output.
Customer is responsible for human review.
Learn more about this label at nutrition-facts.ai