Skip to contentSkip to navigationSkip to topbar
On this page

TwiML™ Voice: <VirtualAgent> with Dialogflow CX


The <VirtualAgent> TwiML noun, used with Twilio's Google Dialogflow CX Connector Add-on, allows you to connect callers to a Google Dialogflow agent. <VirtualAgent> nests inside the <Connect> verb to direct a call to a Dialogflow agent.


Set up the integration between Twilio and Dialogflow CX

set-up-the-integration-between-twilio-and-dialogflow-cx page anchor

Before using <VirtualAgent>, complete the Dialogflow CX one-click integration.


<Connect> attributes

connect-attributes page anchor

<VirtualAgent> is a TwiML noun that is nested within the <Connect> verb.

After the <Connect><VirtualAgent> session ends, you might execute a new set of TwiML instructions for the call. To execute a new set of instructions, use the action and method attributes of the <Connect> noun.

Attribute NameAllowed ValuesDefault Values
actionRelative or absolute URLCurrent TwiML document URL
methodGET, POSTPOST

action

action page anchor

The action attribute takes an absolute or relative URL as a value. After a <Connect><VirtualAgent> session ends, Twilio sends an HTTP request to this action URL. It expects a response that contains a new set of TwiML instructions. Lacking an action attribute, Twilio requests TwiML instructions from the current TwiML document.

(information)

Example 1: action attribute with <Connect> and <VirtualAgent>

The following code sample uses the action attribute with <Connect> and <VirtualAgent>.

Specify an action URL with <Connect>Link to code sample: Specify an action URL with <Connect>
1
const VoiceResponse = require('twilio').twiml.VoiceResponse;
2
3
const response = new VoiceResponse();
4
const connect = response.connect({
5
action: 'https://myactionurl.com/twiml'
6
});
7
connect.virtualAgent({
8
connectorName: 'project',
9
statusCallback: 'https://mycallbackurl.com'
10
});
11
12
console.log(response.toString());

Output

1
<?xml version="1.0" encoding="UTF-8"?>
2
<Response>
3
<Connect action="https://myactionurl.com/twiml" >
4
<VirtualAgent connectorName="project" statusCallback="https://mycallbackurl.com"/>
5
</Connect>
6
</Response>

For Dialogflow CX, this HTTP request's body contains additional information about the result of the <Connect><VirtualAgent> session, along with Twilio's standard request parameters. A <Connect><VirtualAgent> session ends (and thereby triggers Twilio's HTTP request to the action URL) in the following ways:

  • The Dialogflow CX agent session ends successfully and the caller did not hang up.
  • The conversation with the Dialogflow CX agent requires a live agent handoff.
  • The caller hangs up.
  • The conversation with the virtual agent pauses.
  • An error occurred during the VirtualAgent session.

Twilio's request to the action URL

twilios-request-to-the-action-url page anchor

The Twilio request body to the action URL contains parameters about the <Connect><VirtualAgent> session, along with Twilio's standard request parameters. To configure the call behavior after a <Connect><VirtualAgent> session or to log data for analytics purposes, write your app or service to consume this data from the request.

ParameterDescription
VirtualAgentProviderService that provided the VirtualAgent. Set this to DialogflowCX.
VirtualAgentStatusReason the VirtualAgent ended the session.
VirtualAgentProviderDataJSON object that contains the provider-specific action callback event data.
VirtualAgentErrorCodeIf VirtualAgentStatus returned failed, Twilio returns this error code.
VirtualAgentErrorIf VirtualAgentStatus returned failed, the response returns this message that describes the error that caused the VirtualAgent session to fail.
VirtualAgentProviderErrorIf VirtualAgentErrorCode returned 32601, the response returns this Dialogflow-provided error message.

This property describes why the VirtualAgent session ended. Possible values include:

  • completed: VirtualAgent terminated the session in one of the following ways:
    • The Dialogflow CX agent indicated end of conversation (by matching the end of conversation intent)
    • The caller hung up
  • live-agent-handoff: VirtualAgent returned a live agent handoff response
  • failed: An error occurred during VirtualAgent processing
  • paused: VirtualAgent session was paused with the intention of the session being resumed later

VirtualAgentProviderData for the action URL

virtualagentproviderdata-for-the-action-url page anchor

This parameter contains Dialogflow-specific data from the agent interaction expressed in a serialized JSON object with key-value pairs.

KeyValueTypeNecessity
ConversationIdUnique identifier that Google provides for this conversation.stringRequired
EndUserIdUnique identifier that Google provides for the caller.stringRequired
AgentHandoffParametersParameters included from the virtual agent if the agent returned a live agent handoff response.stringOptional
PauseParametersCustom parameters that the virtual agent includes if the virtual agent returns a custom payload response with {"TWILIO_ACTION": "PAUSE"}.stringOptional
FeatureUsageDuration of Dialogflow CX Voice capabilities used in a JSON object of key-value pairs. Includes both standard and Generative AI capabilities for Voice. The keys are standard-voice-minutes, generative-ai-voice-seconds, custom-voice-model-minutes.objectOptional
IntentConfidenceVirtual agent's confidence in detecting caller intent expressed as a numerical range from 0.0 (absolute uncertainty) to 1.0 (absolute certainty).numberOptional
IntentIdUnique identifier of the caller's intent ID that Google provides.stringOptional
IntentDisplayNameHuman readable name you give to this intent.stringOptional
SentimentAnalysisScoreCaller sentiment expressed as a numerical range between -1.0 (negative) and 1.0 (positive).numberOptional
SentimentAnalysisMagnitudeNon-negative number from 0 to +inf range that represents the absolute magnitude of sentiment, independent of score (positive or negative).numberOptional

Respond to Twilio's request to the action URL

respond-to-twilios-request-to-the-action-url page anchor

To continue a call after a <Connect><VirtualAgent> session ends, your application should provide new TwiML instructions based on that session.

This optional <Connect> attribute indicates the HTTP request method to be used when Twilio sends a request to the action URL. If you don't specify a method attribute in <Connect>, POST is used by default.

The allowed values are POST and GET.


<VirtualAgent> attributes

virtualagent-attributes page anchor

The following table lists all <VirtualAgent> attributes with their allowed values. The Dialogflow CX integration allows additional customization of the call flow using <Parameter> and <Configuration> TwiML nouns.

NameAllowed ValuesNecessityDefault Value
connectorNameStringRequiredempty
statusCallbackAbsolute URLOptionalempty
statusCallbackMethodGET, POSTOptionalPOST

The Dialogflow CX connector instance configures this attribute in the Unique Name field. You can review your Dialogflow CX connector instances in the Twilio Console(link takes you to an external page).

The statusCallback attribute points to an absolute URL where Twilio sends HTTP requests. During the Dialogflow agent interaction, Twilio sends HTTP requests to this URL each time an intent matches in the Dialogflow agent's conversation.

The Twilio request bodies to your statusCallback URL contains information about intents, transcripts (caller text vs. virtual agent text), sentiment analysis (if enabled), and custom parameters that your app sent to Dialogflow to build custom logic.

The Twilio request body to your statusCallback URL contains all of the following parameters:

ParameterDescriptionExampleTypeNecessity
AccountSidUnique identifier for the Twilio Account that starts with AC followed by 32 hexadecimal digits.AC4d951d9e1c0287ccbc1e2fef65ce1eedstringRequired
CallSidUnique identifier for the Twilio Call that starts with CA followed by 32 hexadecimal digits.CA6dce364f7c2c23a01b43cede10efc3c3stringRequired
TimestampTime of the event formatted as a UTC ISO 8601 Timestamp.2025-02-19T18:44:48+00:00stringRequired
StatusCallbackEventEvent type that triggered the status callback request.intentstringRequired
VirtualAgentProviderSource of the VirtualAgent.DialogflowCXstringRequired
VirtualAgentProviderDataJSON object containing data from Dialogflow CX.JSON objectRequired

VirtualAgentProviderData for the statusCallback URL

virtualagentproviderdata-for-the-statuscallback-url page anchor

This parameter in the status callback contains the Dialogflow CX-specific intent event data formatted as a serialized JSON object. The JSON object can contain the following key-value pairs.

KeyValueTypeNecessity
ReplyTextContent of VirtualAgent response to the caller.stringRequired
ConversationIdUnique identifier that Google provides for this conversation.stringRequired
EndUserIdUnique identifier that Google provides for the caller.stringRequired
LanguageCodeLanguage triggered during intent detection.stringOptional
ParametersSerialized JSON object with key-value pairs that contains the collected session parameters.objectOptional
ConfidenceVirtual agent's confidence in detecting caller intent expressed as a numerical range from 0.0 (absolute uncertainty) to 1.0 (absolute certainty).numberOptional
ResolvedInputFinal text input matched against. This value might differ from the original input due to spelling correction or other processing.stringOptional
IntentIdUnique identifier of the caller's intent ID that Google provides.stringOptional
IntentDisplayNameHuman readable name you give to this intent.stringOptional
SentimentAnalysisScoreCaller sentiment expressed as a numerical range between -1.0 (negative) and 1.0 (positive).numberOptional
SentimentAnalysisMagnitudeNon-negative number from 0 to +inf range that represents the absolute magnitude of sentiment, independent of score (positive or negative).numberOptional

The HTTP method your agent should use when requesting the statusCallback URL. This attribute accepts GET or POST. The value defaults to POST.


To pass custom parameters to your Dialogflow CX agent, nest the <Parameter> TwiML noun within <VirtualAgent>. The <Parameter> noun allows you to send custom session parameters(link takes you to an external page) to your Dialogflow CX virtual agent. Your agent can reference them as $session.params.parameter-name.

<Parameter> has two attributes: name and value. Use both every time you use <Parameter>.

(information)

Example 2: Add a personalized greeting

To provide the caller with a personalized agent greeting, supply a nested <Parameter> element with the customer name to the Dialogflow CX agent.

This key-value pair passes in as a session parameter(link takes you to an external page). Reference this as $session.params.cutomer_name at runtime in your Dialogflow CX agent.

Add custom parameters to a Dialogflow CX interactionLink to code sample: Add custom parameters to a Dialogflow CX interaction
1
const VoiceResponse = require('twilio').twiml.VoiceResponse;
2
3
const response = new VoiceResponse();
4
const connect = response.connect();
5
const virtualagent = connect.virtualAgent({connectorName: 'uniqueName'});
6
virtualagent.parameter({name: 'customer_name', value: 'Burton Guster'});
7
8
console.log(response.toString());

Output

1
<Response>
2
<Connect>
3
<VirtualAgent connectorName="uniqueName">
4
<Parameter name="customer_name" value="Burton Guster"/>
5
</VirtualAgent>
6
</Connect>
7
</Response>

Pause and resume a conversation session

pause-and-resume-a-conversation-session page anchor

You can pause and resume a Dialogflow CX agent conversation session at any time. This allows you to pass a call back and forth between Dialogflow and Twilio while keeping the session context intact. As a result, the caller doesn't need to repeat themselves or start from the beginning when Twilio passes the call back to Dialogflow.

Sessions stay active for a 30 minute time-to-live (TTL) period between pausing and resuming.

To pause a session, your Dialogflow CX agent must return a custom payload(link takes you to an external page) serialized JSON object that contains the key TWILIO_ACTION with the value PAUSE. This signals to Twilio that the session should be paused. Twilio then sends a request to the action URL you've specified. You can add additional parameters in the custom payload from your Dialogflow agent. Twilio includes the parameters in the request to the action URL.

When a session pauses, the Twilio request to your action URL performs two actions:

  1. Sets VirtualAgentStatus to paused.
  2. Returns VirtualAgentProviderData with a PauseParameters property. This property contains any custom parameters from the custom payload.
(information)

Example 3: Pause a session

If your Dialogflow CX agent returns the following custom payload response to Twilio:

1
{
2
"TWILIO_ACTION": "PAUSE",
3
"memberId": "$session.params.member_id",
4
"paymentAmount": "$122.34"
5
}

Twilio's request to your action URL contains the following values in the PauseParameters field:

1
{
2
"memberId": "abc123",
3
"paymentAmount": "$122.34"
4
}

To resume a session, send a request to Twilio with the TwiML <Connect><VirtualAgent> containing a nested <Config> noun. The <Config> noun can include the following parameters as name and value pairs.

name Attributevalue AttributeNecessity
resumeEndUserIdValue of the EndUserId property in the VirtualAgentProviderData parameterRequired
resumeEventNameName of the custom event handler(link takes you to an external page) that the VirtualAgent triggers when the session resumes.Optional

You can only resume a session of the same Call SID which initiated the conversation.

To learn more about <Config>, consult the dynamic connector configuration section.

(information)

Example 4: Resume a session with configuration settings

To resume a session with both the resumeEndUserId and resumeEventName configuration settings, write the following TwiML document.

1
<?xml version="1.0" encoding="UTF-8"?>
2
<Response>
3
<Connect>
4
<VirtualAgent connectorName="uniqueName">
5
<Config name="resumeEndUserId" value="projects/ccai-test-customer/locations/us-east1/conversations/119qL_EbVa6QqascUqOqi0taw/participants/40aMiI3SQZaEbby-EIyhrw"/>
6
<Config name="resumeEventName" value="customEventName"/>
7
</VirtualAgent>
8
</Connect>
9
</Response>

Dynamic connector configuration

dynamic-connector-configuration page anchor

With the TwiML <Config> noun, you can change the behavior of your virtual agent. This includes changing your underlying Dialogflow CX Connector's configuration or passing additional parameters. The <Config> noun nests inside of <VirtualAgent>. <Config> has two attributes: name and value, both of which must be used every time you use <Config>.

For each configuration option you want to override, include a new <Config> noun. The name attribute corresponds to one of your Dialogflow CX Connector's configuration options, such as language, sentimentAnalysis, voiceName, and welcomeIntent.

You can set additional attributes not present in your Dialogflow CX Connector configuration using this TwiML noun. These include voiceModel, speechModel, and speechModelVariant.

The TwiML <Config> noun accepts the following attributes:

AttributeDescriptionDefault
languageLanguage in which the caller interacts with the Dialogflow CX Virtual Agent, like es-es. When choosing a language, you must apply "STT" and "TTS" filters in the Dialogflow CX languages(link takes you to an external page)The Dialogflow CX connector configuration setting
sentimentAnalysisBoolean indicating whether to analyze sentiment or not. If you want Dialogflow to perform sentiment analysis on the intents, select language that supports Sentiment filter and STT/TTS in the Dialogflow CX languages(link takes you to an external page)The Dialogflow CX connector configuration setting
voiceNameTTS voice(link takes you to an external page) that the Dialogflow CX Virtual Agent uses, like en-US-Standard-CThe Dialogflow CX connector configuration setting
welcomeIntentName of the event you want to trigger when connecting to your virtual agent. To trigger the Default Welcome Intent, set this to the built-in system event(link takes you to an external page) WELCOME. To set where the flow should start, configure custom events(link takes you to an external page) on your Dialogflow CX agent.None
voiceModelTTS custom voice model(link takes you to an external page) that your virtual agent uses. If specified in addition to voiceName, this attribute takes precedence. This feature allows you to train a custom voice model using your own studio-quality audio recordings to create a unique voice. To use a custom voice model, grant Twilio's service account (virtualagent-ccai-prod@dialogflow-prod-env.iam.gserviceaccount.com) the automl.models.predict IAM permission on the resource model.None
speechModelSTT model(link takes you to an external page) that your virtual agent uses to process human speech.default
speechModelVariantSpeech model variant that your virtual agent uses in speech-to-text. If you specify an enhanced model variant but it doesn't exist, this throws an error. To learn more, consult the Enhanced Models(link takes you to an external page) guide.USE_BEST_AVAILABLE
resumeEndUserIdID of the caller to resume a paused session with.None
resumeEventNameCustom event that the Dialogflow CX agent triggers when resuming a paused session.None
(information)

Example 5: Customize the TTS voice and language

If you want to customize the TTS voice and language for the virtual agent interaction, you can supply the respective configuration settings inside the <Config/> attributes as follows:

Override Dialogflow CX Connector ConfigurationLink to code sample: Override Dialogflow CX Connector Configuration
1
const VoiceResponse = require('twilio').twiml.VoiceResponse;
2
3
const response = new VoiceResponse();
4
const connect = response.connect();
5
const virtualagent = connect.virtualAgent({connectorName: 'uniqueName'});
6
virtualagent.config({name: 'language', value: 'en-us'});
7
virtualagent.config({name: 'voiceName', value: 'en-US-Wavenet-C'});
8
9
console.log(response.toString());

Output

1
<Response>
2
<Connect>
3
<VirtualAgent connectorName="uniqueName">
4
<Config name="language" value="en-us"/>
5
<Config name="voiceName" value="en-US-Wavenet-C"/>
6
</VirtualAgent>
7
</Connect>
8
</Response>

You can also use Twilio Studio.

  1. Click on the Virtual Agent widget.
    The configuration panel appears from the right edge of the screen.
  2. Click the Config tab.
  3. Go to the Configurations section.
  4. Type your API key into the Key field.
  5. Type your language choice in the matching Value field.
  6. Click Save.
  7. Click Publish in the Canva menu to publish your flow.