AWS Builder Center
Anatomy of an agentic Amazon Connect contact flow

Anatomy of an agentic Amazon Connect contact flow

Following a single inbound call through an agentic Amazon Connect contact flow to see which service does what at each step, and how a reusable CDK construct wires it all together in one deploy.

Building the modern voice AI experience with a single CDK construct

A modern voice AI experience on Amazon Connect brings together a rich set of AWS services, each contributing something the others can't. Connect for the telephony. Lex for the speech-to-intent boundary. Q in Connect and the underlying Wisdom domain for the AI assistant. Bedrock AgentCore Gateway for tool calling. AppIntegrations for data connectors. Customer Profiles for identity. Data Tables for per-caller configuration. Composed together, they yield a contact center where an AI agent reasons over a knowledge base, invokes tools that touch your business systems, escalates to a human queue when appropriate, and speaks to every caller in their own language.
We've been building this shape often enough on customer prototypes that we packaged the wiring into a reusable CDK construct —  ConnectPattern  — and open-sourced it under   aws-samples/sample-agentic-connect-experience  . One props object in, one  cdk deploy , and you get a working agentic contact center with dynamic multi-language voice, knowledge-base retrieval, and Lambda-backed tool calling exposed as MCP tools to the AI agent. What would otherwise be several days of setup comes out of the box, freeing your time for the parts that actually differentiate the experience — the prompt, the knowledge base, and the tools your business needs.
This post is a walkthrough. Rather than describing the construct's API, we're going to follow a single inbound call from the moment it lands on the claimed phone number through to the moment the AI agent hands control back — and at each step, look at which service is doing the work, where it's referenced in the contact flow JSON, and how the pattern provisions and wires it. If you're planning to build something like this yourself (whether or not you use the construct), this is the map.

The picture, briefly

The pattern provisions a set of resources once at deploy time, then references them inside a templated contact flow. When a call comes in, the flow reads the caller's country code, looks up the corresponding language configuration in a Data Table, sets a voice appropriate for that language, plays a welcome prompt in the caller's language, and hands off to a Lex bot whose only real job is to bridge speech to a Q in Connect orchestration AI agent. The agent has access to a knowledge base and to Lambda-backed MCP tools; it can complete the interaction or escalate to a human queue.
Caller
│
▼
Phone Number ──▶ FuncExtractCountryCode ──▶ Get Data Table row ──▶ Set Voice
│
┌────────────────────────┘
▼
Play welcome prompt
│
▼
FuncUpdateSessionData
│
▼
Get customer input (Lex QInConnectIntent)
│
▼
Q in Connect Assistant + AI Agent ─┬─▶ Retrieve (Wisdom KB)
│ │
│ └─▶ MCP tool (AgentCore Gateway)
│
┌────────┼────────┐
▼ ▼
COMPLETE ESCALATE
│ │
▼ ▼
Disconnect Queue
Each of those boxes maps to a specific block in the exported contact flow JSON, and each block references a resource ARN or ID that the CDK construct provisions and substitutes at deploy time. Let's walk through them.

Step 1: identifying the caller's language

The moment the call lands, the flow invokes a Lambda that reads the caller's number and returns a country calling code. The pattern ships this Lambda —  FuncExtractCountryCode  — and it uses the  phonenumbers  library to parse and validate the E.164 address. If the number is malformed, spoofed, or maps to a country we don't have language configuration for, the function returns a configurable fallback ( country_code_detection_fallback  on the props). The flow always has a valid code to key on.
In the contact flow JSON, this looks like an Invoke Lambda block referencing the function ARN, followed by a Get Data Table row block keyed by the returned code:
{
"Type": "InvokeLambdaFunction",
"Parameters": {
"LambdaFunctionARN": "${COUNTRY_CODE_EXTRACTOR_FUNC_ARN}",
"InvocationTimeLimitSeconds": "3"
},
"Transitions": {
"NextAction": "Get language row",
...
}
},
{
"Type": "SearchDataTableRow",
"Parameters": {
"DataTableId": "${DATA_TABLE_ID}",
"Filter": [
{ "Field": "country_code", "Operator": "eq", "Value": "$.External.country_code" }
]
}
}
The Data Table itself is where all the language-specific configuration lives — one row per country code, each row carrying a language code, TTS voice IDs, a welcome prompt, and an error message. Adding a new language means adding a row. No changes to the flow, no code deploys.
The pattern provisions the Data Table from a plain JSON definition — the sample stack ships two rows:
Attribute
 +34  (Spain)
 +1  (US / Canada)
 language_code 
 es-ES 
 en-US 
 language_name 
Spanish
English
 deepgram_voice 
 nestor 
 arcas 
 deepgram_model 
 deepgram:aura-2 
 deepgram:aura-2 
 elevenlabs_voice 
 gc61tTk93h3LBXPxew2V 
 s3TPKV1kjDlVtZbl4Ksh 
 elevenlabs_model 
 eleven_flash_v2_5 
 eleven_flash_v2_5 
 amazon_voice 
 MARCOS 
 BLAKE 
 amazon_model 
 connect:agentic 
 connect:agentic 
 welcome_prompt 
Bienvenido, ¿en qué podemos ayudarle?
Welcome, how can we help you?
 error_message 
Estamos experimentando un problema técnico. Le devolveremos la llamada en breve.
We're currently experiencing a technical issue. We'll call you back shortly.
The  ${DATA_TABLE_ID}  placeholder in the JSON is substituted at deploy time from the  CfnDataTable.attr_data_table_id  attribute the construct exposes. The  country_code_extractor_func_arn  is likewise substituted from the Lambda function ARN.

Step 2: setting the voice

Once we have the caller's language row loaded into  $.External.<field>  variables, the flow sets the voice engine and voice ID that will be used for everything the system says from this point onwards. This is the single place where the voice provider choice — Connect Agentic, Deepgram or ElevenLabs — becomes concrete.
The  Set voice  block reads the row's voice ID and engine, and this is where the pattern's  voice_provider  prop translates into contact flow content. Here's what the block looks like for Amazon Connect Agentic voices:
{
"Type": "SetContactData",
"Parameters": {
"TextToSpeechEngine": "$.DataTables.LangConfig.amazon_model",
"TextToSpeechVoice": "$.DataTables.LangConfig.amazon_voice"
}
}
Here's for Deepgram:
{
"Type": "SetContactData",
"Parameters": {
"TextToSpeechEngine": "$.DataTables.LangConfig.deepgram_model",
"TextToSpeechVoice": "$.DataTables.LangConfig.deepgram_voice",
"TextToSpeechCredentialsProvider": "aws-secretsmanager",
"TextToSpeechCredentialsARN": "${DEEPGRAM_SECRET_ARN}"
}
}
And for ElevenLabs:
{
"Type": "SetContactData",
"Parameters": {
"TextToSpeechEngine": "$.DataTables.LangConfig.elevenlabs_model",
"TextToSpeechVoice": "$.DataTables.LangConfig.elevenlabs_voice",
"TextToSpeechCredentialsProvider": "aws-secretsmanager",
"TextToSpeechCredentialsARN": "${ELEVENLABS_SECRET_ARN}"
}
}
The construct picks the correct variant at synth time based on  voice_provider='amazon' ,  voice_provider='deepgram' or  voice_provider='elevenlabs'  and inlines it into the contact flow's  ${TTS_PARAMETERS}  placeholder. If Deepgram or ElevenLabs are selected, the construct also provisions the Secrets Manager secret and its KMS key, and grants Lex and Connect the ability to decrypt it. All you provide is the API key value after the first deploy.
Two things worth noting about this block. First, the language code is set on the contact from the Data Table row — this affects everything downstream that respects the language attribute, including Lex's transcription language selection. Second, the voice provider decision travels with the call: from this block onwards, every prompt spoken to the caller uses the chosen engine and voice. If the caller is Spanish and the row says  nestor  on Deepgram, that's what they hear from now on.

Step 3: greeting the caller in their language

With the voice set, the flow plays the welcome prompt using the text that came out of the Data Table row:
{
"Type": "MessageParticipant",
"Parameters": {
"Text": "$.DataTables.LangConfig.welcome_prompt"
}
}
No branch, no if-else on language. The row's  welcome_prompt  column already contains the correct string ("Bienvenido, ¿en qué podemos ayudarle?" or "Welcome, how can we help you?"). The pattern that makes multi-language routing manageable is this: every user-facing string lives in the Data Table, not in the flow. Adding a language is a row addition, not a flow edit.

Step 4: preparing session data for the AI agent

Before we hand off to the Lex bot and the AI agent, the flow invokes a second Lambda that the pattern ships —  FuncUpdateSessionData  — whose job is to populate the  $.Custom.*  session variables that Q in Connect orchestration prompts reference. The orchestration prompt for the sample stack, for instance, expects  {{$.Custom.language_name}}  to resolve to "Spanish" or "English" so it can localize its output.
{
"Type": "InvokeLambdaFunction",
"Parameters": {
"LambdaFunctionARN": "${SESSION_UPDATE_FUNC_ARN}",
"Parameters": {
"language_name": "$.DataTables.LangConfig.language_name",
"customer_address": "$.CustomerEndpoint.Address"
}
}
}
The reason this indirection exists — instead of the AI agent reading directly from  $.External  or  $.Attributes  — is that Q in Connect orchestration prompts have their own variable namespace ( $.Custom.* ) which is populated by an  UpdateSessionData  API call, not by contact flow attributes directly. The Lambda is the bridge. It receives the values that need to reach the agent, calls  UpdateSessionData , and returns. From that point on, the agent's prompt can interpolate them.

Step 5: handing off to Lex — where QInConnectIntent lives

This is where speech-to-intent happens, and it's also where the Lex bot's role starts to look strange if you've built classical Lex flows before. In a traditional Lex integration, the bot has intents like  BookFlight  or  CheckOrderStatus  with utterance samples and slots. In an agentic Connect setup, the bot has exactly two intents:  FallbackIntent  and  QInConnectIntent .
 QInConnectIntent  is a built-in intent ( AMAZON.QInConnectIntent ) whose entire purpose is to bridge Lex to Q in Connect. When the customer says anything, Lex transcribes it and hands the utterance off to the associated Q in Connect assistant, which routes it to the appropriate AI agent for orchestration. The Lex bot in this setup does no NLU of its own beyond a fallback — it exists because Amazon Connect's  GetCustomerInput  block currently speaks to Lex, and Lex is the vehicle that speaks to Q in Connect.
The bot definition on the CDK side looks like this:
lex.CfnBot.IntentProperty(
name="QInConnect",
parent_intent_signature="AMAZON.QInConnectIntent",
q_in_connect_intent_configuration=lex.CfnBot.QInConnectIntentConfigurationProperty(
q_in_connect_assistant_configuration=lex.CfnBot.QInConnectAssistantConfigurationProperty(
assistant_arn=self.assistant.attr_assistant_arn
)
),
)
The  assistant_arn  field is what wires the Lex bot to a specific Q in Connect assistant. Every utterance the caller speaks now goes through this bridge.
In the contact flow, the block that engages Lex is  GetCustomerInput :
{
"Type": "GetParticipantInput",
"Parameters": {
"Text": "$.DataTables.LangConfig.welcome_prompt",
"Media": {
"Type": "Lex",
"LexV2Bot": { "AliasArn": "${LEX_BOT_ALIAS_ARN}" }
},
"InputTimeLimitSeconds": "15"
}
}
The  ${LEX_BOT_ALIAS_ARN}  placeholder gets substituted from  bot_alias.attr_arn  at deploy time. The pattern also handles a subtlety here that surprises people building this stack for the first time: the Lex bot alias must have its locales explicitly enabled via  bot_alias_locale_settings , and the version snapshot must reflect a fully-built DRAFT before the alias points to it. The pattern manages this with a build waiter that only marks the version as ready when  DescribeBotLocale  returns  Built  (not  ReadyExpressTesting , which is a partial state that reads like "built" but isn't).
Once the caller speaks,  QInConnectIntent  matches, the utterance is passed to the Q in Connect assistant, and control moves up the stack.

Step 6: the Q in Connect assistant and the AI agent

This is where the real work happens, and it's the largest concept-cluster in the whole flow. Three resources cooperate here: the Wisdom assistant (also called a Q in Connect assistant or "assistant domain"), the Wisdom AI agent (an orchestration agent bound to the assistant), and any number of tools the agent can invoke — the built-in retrieve tool for knowledge base access, and any MCP tools registered from Bedrock AgentCore Gateways.
The assistant is the container. It holds a reference to the Connect instance, the knowledge bases associated with it, and the AI agents that run within it. In CDK it's a  CfnAssistant  provisioned once, and then bound to the Connect instance via a  CfnIntegrationAssociation  of type  AMAZON_Q_CONNECT_ASSISTANT . This is what makes the assistant addressable from a contact flow at all.
The AI agent is where orchestration behavior is defined. The pattern creates orchestration-type agents ( type='ORCHESTRATION' ), each with its own prompt and its own tool configurations:
wisdom.CfnAIAgent(
self, f"{name}Agent",
assistant_id=self.assistant.attr_assistant_id,
type="ORCHESTRATION",
configuration=wisdom.CfnAIAgent.AIAgentConfigurationProperty(
orchestration_ai_agent_configuration=wisdom.CfnAIAgent.OrchestrationAIAgentConfigurationProperty(
connect_instance_arn=self.instance.attr_arn,
orchestration_ai_prompt_id=f"{prompt.attr_ai_prompt_id}:$LATEST",
tool_configurations=[complete_tool, escalate_tool, retrieve_tool, ...mcp_tools],
)
)
)
The tool configurations are what give the agent its capabilities. Three flavors show up:
 RETURN_TO_CONTROL  tools hand control back to the contact flow when the agent decides the interaction should end ( COMPLETE ) or escalate ( ESCALATE ). These are declared purely in the agent config — the "implementation" is the contact flow branch that runs after control returns.
The retrieve tool binds the agent to a Wisdom knowledge base. It's a  MODEL_CONTEXT_PROTOCOL  tool with the built-in ID  aws_service__qconnect_Retrieve , and its KB binding travels through  OverrideInputValues :
wisdom.CfnAIAgent.ToolConfigurationProperty(
tool_name="Retrieve",
tool_id="aws_service__qconnect_Retrieve",
tool_type="MODEL_CONTEXT_PROTOCOL",
override_input_values=[
wisdom.CfnAIAgent.ToolOverrideInputValueProperty(
json_path="$.retrievalConfiguration.knowledgeSource.assistantAssociationIds",
value=wisdom.CfnAIAgent.ToolOverrideInputValueConfigurationProperty(
constant=wisdom.CfnAIAgent.ToolOverrideConstantInputValueProperty(
type="JSON_STRING",
value=Fn.sub('["${AssocId}"]', {"AssocId": kb_association.attr_assistant_association_id}),
)
),
)
],
)
The identifier in  assistantAssociationIds  isn't the knowledge base ID — it's the  CfnAssistantAssociation  ID that links the KB to the assistant. This is the trickiest piece of the wiring: the retrieve tool references an association, not a knowledge base directly.
MCP tools point to Lambda functions exposed through Bedrock AgentCore Gateways. Each tool the pattern registers gets its own gateway with a JWT authorizer bound to the Connect instance, its own gateway target with the caller-provided schema, and a  MODEL_CONTEXT_PROTOCOL  tool entry on the agent that names the gateway namespace. When the model decides to invoke the tool, the call flows Assistant → Agent → AgentCore Gateway → Lambda → back through the same path with the response.
From the contact flow's perspective, all of this complexity collapses into a single  SendMessageToFlow  block that hands the customer utterance to the assistant:
{
"Type": "SendMessageToFlow",
"Parameters": {
"AssistantId": "${WISDOM_ASSISTANT_ARN}",
"AIAgentVersion": "${AI_AGENT_VERSION_ARN}"
}
}
 ${WISDOM_ASSISTANT_ARN}  comes from  assistant.attr_assistant_arn .  ${AI_AGENT_VERSION_ARN}  comes from a  CfnAIAgentVersion  resource that the construct creates to publish a stable version of the agent — using the DRAFT reference would work but would let flows read whatever's in the designer, which isn't what you want in a deployed setup.
The agent runs its orchestration loop: reads the utterance, decides whether to call retrieve, calls MCP tools, generates a reply, streams it back as speech. The loop continues until the agent invokes  COMPLETE  or  ESCALATE .

Step 7: escalation to a Connect queue

When the AI agent invokes the  ESCALATE  return-to-control tool, the contact flow branches to a  TransferToQueue  block:
{
"Type": "TransferParticipantToQueue",
"Parameters": {},
"Transitions": {
"NextAction": "queue-failed",
"Errors": [
{ "NextAction": "queue-failed", "ErrorType": "QueueAtCapacity" },
{ "NextAction": "queue-failed", "ErrorType": "NoMatchingError" }
]
}
}
But before it can transfer, the queue needs to be set. That happens earlier in the flow via a  SetQueue  block referencing  ${ESCALATION_QUEUE_ARN} :
{
"Type": "UpdateContactTargetQueue",
"Parameters": { "QueueId": "${ESCALATION_QUEUE_ARN}" }
}
The pattern provisions this queue along with its hours of operation. The  escalation_queue  prop takes a time zone and a weekly schedule:
ConnectPatternProps.EscalationQueue(
time_zone="Europe/Madrid",
hours_of_operation=[
("MONDAY", "09:00", "18:00"),
("TUESDAY", "09:00", "18:00"),
...
],
)
Which turns into a  CfnHoursOfOperation  and a  CfnQueue  inside the pattern. The queue is empty of human agents at deploy time — assigning agents to it is a manual step in the Connect admin panel, which is the correct boundary: infrastructure provisions the queue, staffing is a business decision.

Step 8: closing the loop

When the AI agent invokes  COMPLETE , the flow branches to a disconnect. There's very little to say about this block — it's a  DisconnectParticipant  — but it's worth noting that the agent gets to decide when the interaction is done, not the flow. The flow trusts the agent's judgement about whether the customer's issue has been addressed.

How the construct wires all of this together

The walkthrough above shows a lot of moving parts. The point of the pattern is that you don't wire them by hand.
A minimal usage of the construct looks like this:
ConnectPattern(
self, "ConnectPattern",
ConnectPatternProps(
voice_provider="deepgram",
country_code_detection_fallback="+1",
instance=ConnectPatternProps.Instance(alias="my-support-line"),
lex_bot=ConnectPatternProps.LexBot(name="MyBot", locales=["en_US", "es_ES"]),
phone_number=ConnectPatternProps.PhoneNumber(country_code="US"),
data_tables=[my_language_data_table],
agents=[
ConnectPatternProps.Agent(
name="Support",
retrieve_tool_target=my_kb_bucket,
prompt=ConnectPatternProps.Prompt(
name="SupportPrompt",
model_id="us.anthropic.claude-haiku-4-5-20251001-v1:0",
text=Path("assets/support_prompt.yaml").read_text(),
),
),
],
),
)
Every service the walkthrough named is provisioned from that single props object. The Connect instance, the phone number, the Data Table (with rows), the Lex bot (with locales, intents, version, and alias with locales enabled), the Q in Connect assistant, the assistant-to-instance integration association, the AI agent with its prompt and version, the knowledge base built from the S3 corpus, the assistant-KB association, the retrieve tool bound to that association, the escalation queue with hours of operation, the two operational Lambdas, and the Secrets Manager secrets with their KMS keys and resource grants required by Lex and Connect.
The contact flow itself is a templated JSON asset. All the placeholder ARNs and IDs ( ${WISDOM_ASSISTANT_ARN} ,  ${LEX_BOT_ALIAS_ARN} ,  ${DATA_TABLE_ID} ,  ${TTS_PARAMETERS} , and so on) are substituted at synth time from the resources the pattern created.

The demo scenario

The sample stack ships with a full working demo modeled on an EV charger contact center. Two experiences share the same construct:
An inbound customer support line where a Claude Haiku 4.5 orchestration agent answers questions grounded in a 24-article knowledge base covering account management, connectivity troubleshooting, error codes, and warranty questions. The agent uses the retrieve tool to search the KB before every response, escalates to a human queue on request or when it can't answer, and completes the interaction when the customer is done.
An outbound proactive-maintenance flow where a  StartOutboundVoiceContact  Lambda dials the customer, and a separate AI agent (same architecture, different prompt and tools) collects availability windows and books a technician visit through an MCP tool backed by DynamoDB.
Both flows run in English and Spanish, switching automatically based on the caller's country code — Spanish for  +34 , English for  +1 . Adding a third language means adding a Data Table row.

Try it yourself

The repository is at   aws-samples/sample-agentic-connect-experience  . The README walks through prerequisites (Bedrock model access, service-linked roles, and so on) and the deploy sequence. After deploy, populate the Deepgram or ElevenLabs secret if you selected either provider — the JSON format is  {"apiToken": "your-key-here"}  — dial the claimed number, and you should hear the AI agent respond in the language matching the country code of your phone.

What's next

The best way to understand what the pattern does is to deploy it and start pulling on the props. Swap in your own knowledge base corpus, register a Lambda-backed MCP tool for a business system you actually use, add a Data Table row for a new language, or replace the orchestration prompt entirely and watch how the agent's behavior changes without touching the rest of the construct. Clone   aws-samples/sample-agentic-connect-experience  , experiment, and let us know what you build.
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article