Sitemap
Rabi Yireh

Rabi Yireh

54 min readOct 26, 2026

--

More

1. How to Create Dialog Flows

  • Access Flow Designer: Navigate to your Amazon Connect console, go to Routing > Flows, and click Create flow.
  • Amazon AWS Documentation +1

Select Flow Type: Choose the appropriate flow type (e.g., Inbound, Customer queue, or Outbound).

  • Amazon AWS Documentation
  • Add Action Blocks: Drag and drop blocks from the left-hand menu onto the canvas and link them together:
  • Play Prompt: Plays static text-to-speech or audio files to the customer.
  • Get Customer Input: Captures customer responses via touch-tone keypad (DTMF) or speech.
  • Check Contact Attributes: Routes customers based on account type, language, or channel.
  • Amazon AWS Documentation +3
  • Publish the Flow: Link all error and success branches, then click Publish to make it live.
  • Amazon AWS Documentation

2. How to Find Out Intent (Conversational AI / Lex)

  • Integrate Amazon Lex: In your flow, drag a Get Customer Input block and select the Amazon Lex tab.
  • Amazon AWS Documentation
  • Configure Bot and Alias: Choose your pre-built Amazon Lex V2 bot and its specific alias.
  • Amazon AWS Documentation
  • Set Up Utterances and Prompts: Define the greeting or prompt message and ensure your Lex model’s language attributes match the Connect flow.
  • Amazon AWS Documentation
  • Capture Intent Output: As the customer speaks or types, Lex classifies the input into an Intent and extracts relevant Slots (parameters), storing them in contact attributes that the flow can branch on using condition blocks.
  • Amazon AWS Documentation +1

3. How to Call Database APIs to Extract Data

  • Use AWS Lambda: Amazon Connect cannot query a database directly; instead, it invokes an AWS Lambda function using the Invoke AWS Lambda function block.
  • Amazon Web Services (AWS) +2
  • Pass Contact Attributes: Configure the Lambda block to send contact data (such as phone number, customer ID, or recognized Lex intent/slots) as input events to the Lambda function.
  • Amazon Web Services (AWS)
  • Query the Database: Inside the Lambda function (written in Node.js, Python, etc.), use database drivers or ORMs to query external databases (e.g., Amazon Aurora, DynamoDB, or SQL databases).
  • YouTube·Rajiv Coomar
  • Return Data to Connect: Return a JSON payload from Lambda containing the retrieved data, which Amazon Connect automatically saves into Contact Attributes for use later in the flow.
  • Amazon AWS Documentation

4. How to Generate Replies

  • Dynamic Text-to-Speech (TTS): Use dynamic attributes (e.g., $.External.CustomerName or $.External.AccountBalance) populated from your Lambda database lookup inside a Play Prompt or Get Customer Input block.
  • Lex-Driven Responses: Allow the Amazon Lex bot to synthesize and return conversational slot-filling replies or fallback messages directly back through the voice or chat channel.
  • Multi-Channel Delivery: The same flow text or audio prompt renders across voice (via Amazon Polly TTS) or digital chat interfaces seamlessly.
  • Amazon AWS Documentation +6
  • Amazon Web Services (AWS)
  • Click to Call in Amazon Connect | AWS Contact Center
  • Amazon Connect as your contact center in the cloud. It allows you to set up contact centers and contact flows to handle customer i…

draw some diagram for architecture and flow of dat

Here is the architecture and text-based sequence flow diagram showing how Amazon Connect, Amazon Lex, AWS Lambda, and a database work together to route calls, detect intents, fetch data, and generate responses.

1. High-Level Architecture Diagram

text

[ Customer Call / Chat ]
│
▼
┌────────────────────────────────────────────────────────┐
│ AMAZON CONNECT │
│ │
│ ┌────────────────────────────────────────────────┐ │
│ │ FLOW CANVAS │ │
│ │ │ │
│ │ 1. Play Prompt ──► 2. Get Customer Input │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ [ Amazon Lex Block ] │ │
│ └─────────────────────────────┬──────────────────┘ │
└─────────────────────────────────┼──────────────────────┘
│
3. Stream Audio │ 4. Return Intent
& Utterance │ & Slots
▼
┌──────────────────────────┐
│ AMAZON LEX │
│ (Natural Language / NLU) │
└──────────────────────────┘
│
│ 5. Invoke (Input Attributes)
▼
┌──────────────────────────┐
│ AWS LAMBDA │
│ (Backend API Logic) │
└─────────────┬────────────┘
│
6. Database Query │ 7. Return JSON
(e.g., SQL/NoSQL) │ Data Payload
▼
┌──────────────────────────┐
│ EXTERNAL DATABASE │
│ (DynamoDB / RDS / etc) │
└──────────────────────────┘


2. Step-by-Step Data Flow Sequence

The table below traces the continuous life of a customer interaction from the moment the call hits Amazon Connect to the final spoken response.

StepComponentAction DescriptionData / Protocol1CustomerInbounds a real-time call or web chat to the contact center.SIP / RTP / WebSockets2Amazon ConnectTriggers the custom Inbound Flow, executes a “Play Prompt” greeting, and enters the “Get Customer Input” block.Audio Stream / Text3Amazon LexReceives the customer’s live voice/text stream from Connect, processes the natural language, and matches it to a configured intent.Voice/Text Utterance4Amazon LexSignals back to Amazon Connect that the intent (e.g., CheckBalance) has been successfully identified, passing along any filled slot values.Intent & Slot Attributes5Amazon ConnectExecutes the "Invoke AWS Lambda function" block, packaging contact details (like CustomerPhoneNumber or Lex slots) into a single event object.JSON Input Event6AWS LambdaRuns backend API logic to sanitize input parameters and queries the underlying database for matching records.DB Driver / SQL / SDK7DatabaseEvaluates the lookup query and passes the requested customer record or transactional history back to the execution environment.Key-Value / Row Dataset8AWS LambdaFormats the raw database results into a flat, key-value JSON dictionary response structured specifically for the contact center platform.JSON Return Object9Amazon ConnectMap-saves the Lambda JSON response directly into its runtime External Contact Attributes context memory.$.External.AttributeName10Amazon ConnectFeeds those live dynamic variables directly into an outbound "Play Prompt" block using high-quality Text-to-Speech synthesis.Amazon Polly Audio

End-to-End System Architecture

Comprehensive Architecture Breakdown

1. Ingestion & Communication Layer

  • User Interaction: Customers connect via PSTN/SIP voice trunking or secure WebSockets for web chat.
  • Amazon Connect Flow Canvas: Acts as the primary state machine. It handles call shielding, media stream orchestration, and global error catch blocks.

2. Conversational AI Layer (Intent Parsing)

  • Amazon Lex Integration: The Connect flow streams audio directly to Amazon Lex via built-in deep integration.
  • NLU & Slot Filling: Lex recognizes the intent (e.g., GetAccountStatus) and extracts entity slots (e.g., AccountNumber). If information is missing, Lex manages the audio loop back to the user to fill the required slots before passing control back to Connect.

3. Compute & Orchestration Layer (API Invocation)

  • AWS Lambda Webhook: Once Connect receives the validated intent and slots from Lex, it executes an synchronous Invoke AWS Lambda function block.
  • Context Payload: Connect automatically packages a structured JSON payload containing:
  • System Attributes: CustomerPhoneNumber, ChannelType, ContactId
  • Lex Attributes: Recognized slots and intent confidence scores.

4. Data Persistence & Analytics Layer

  • Database Extraction: The Lambda function utilizes the AWS SDK to query Amazon DynamoDB (or a relational database via RDS Proxy) using the slot value as a partition key.
  • State Return: Lambda returns a flat JSON key-value map. Amazon Connect ingests this map into the $.External namespace memory, making it accessible to any subsequent prompt blocks for dynamic text-to-speech rendering.
  • CloudWatch Telemetry: Every execution, timeout, or database connection exception is streamed to Amazon CloudWatch Logs. If Lambda fails or times out (default 8-second ceiling), the Connect canvas immediately routes the contact down the dedicated Error branch to ensure graceful degradation (e.g., routing to a live agent or playing a fallback static message).

Would you like to see the exact JSON schema structure that Amazon Connect sends to AWS Lambda, or should we draft a Python Lambda blueprint to parse these parameters and safely fetch records from DynamoDB?

text

┌────────────────────────┐
│ User (Voice/Chat) │
└───────────┬────────────┘
│
▼ (PSTN / WebSockets)
┌────────────────────────┐
│ Amazon Connect │◄───────────────────────┐
│ (Flow Canvas) │ │
└───────────┬────────────┘ │
│ │
├────────────────► [ Amazon Lex ] │ (Returns Intent
│ (Streams Audio) (Intent Parsing) │ & Slot Values)
│ │
│ │
▼ (Synchronous JSON Invocation) │
┌────────────────────────┐ │
│ AWS Lambda ├────────────────────────┘
│ (Backend Orchestrator)│
└─────┬──────────────┬───┘
│ │
│ (Queries PK) │ (Streams Telemetry / Timeouts)
▼ ▼
┌──────────────────┐ ┌──────────────────┐
│ Amazon DynamoDB │ │ Amazon CloudWatch│
│ (Data Store) │ │ (Logs & Metrics) │
┌──────────────────┐ ┌──────────────────┐

When you use the Invoke AWS Lambda function block after an Amazon Lex interaction, Amazon Connect structures the inbound event payload into the following format. Your Lambda function code parses this exact JSON to extract the customer's phone number, intent, and slots.

{
"Name": "ContactFlowEvent",
"Details": {
"ContactData": {
"Attributes": {},
"Channel": "VOICE",
"ContactId": "a1b2c3d4-e5f6-7a8b-9c0d-1e2f3a4b5c6d",
"CustomerEndpoint": {
"Address": "+14145550199",
"Type": "TELEPHONE"
},
"InitialContactId": "a1b2c3d4-e5f6-7a8b-9c0d-1e2f3a4b5c6d",
"InitiationMethod": "INBOUND",
"InstanceARN": "arn:aws:connect:us-east-1:123456789012:instance/f4e3d2c1-b0a9-8f7e-6d5c-4b3a2f1e0d9c",
"LanguageCode": "en-US",
"Queue": null,
"SystemEndpoint": {
"Address": "+18005550100",
"Type": "TELEPHONE"
}
},
"Parameters": {
"LexV2Bot": {
"Name": "AccountLookupBot",
"Id": "BOTID12345",
"Alias": "LiveProdBot",
"AliasId": "TSTALIASID",
"Locale": "en_US",
"Intent": {
"Name": "CheckBalance",
"ConfirmationState": "None",
"Slots": {
"AccountNumber": {
"Value": "987654321"
}
}
}
}
}
}
}
{
"CustomerName": "Ravi",
"AccountBalance": "1540.25",
"AccountStatus": "Active",
"IsVip": "true"
}

Use code with caution.

Inside Amazon Connect, you instantly reference these values using the syntax: $.External.CustomerName and $.External.AccountBalance.

import json
import os
import boto3
from botocore.exceptions import ClientError
# Initialize the DynamoDB resource outside the handler for connection reuse
dynamodb = boto3.resource('dynamodb')
# Target table name configuration via environment variables
TABLE_NAME = os.environ.get('DYNAMODB_TABLE_NAME', 'CustomerAccounts')
table = dynamodb.Table(TABLE_NAME)
def lambda_handler(event, context):
"""
Parses Amazon Connect contact flow events, extracts Lex V2 slots,
queries DynamoDB, and returns flat key-value pairs back to Connect.
"""
print("Received Inbound Connect Event: ", json.dumps(event))

try:
# 1. Safely extract Lex V2 Intent details from the input schema
details = event.get('Details', {})
parameters = details.get('Parameters', {})
lex_v2_bot = parameters.get('LexV2Bot', {})
intent_info = lex_v2_bot.get('Intent', {})
slots = intent_info.get('Slots', {})

# Extract the specific AccountNumber slot value
account_number_slot = slots.get('AccountNumber', {})
account_number = account_number_slot.get('Value') if account_number_slot else None

# Edge Case Fallback: If Lex slots are empty, try fallback parameters or phone number
if not account_number:
print("Warning: AccountNumber slot missing from Lex context. Checking customer endpoint...")
customer_endpoint = details.get('ContactData', {}).get('CustomerEndpoint', {})
# Strip prefixes if necessary; using phone number as secondary lookup mechanism
account_number = customer_endpoint.get('Address')

if not account_number:
print("Error: No viable lookup key (slot or phone number) found in payload.")
return {"Result": "MissingLookupKey"}
# 2. Execute a highly targeted Key query against DynamoDB
print(f"Executing DynamoDB item lookup on Primary Key: {account_number}")
response = table.get_item(
Key={
'AccountNumber': str(account_number)
}
)

# 3. Handle data availability edge cases (Zero records vs Multi-matches)
item = response.get('Item')
if not item:
print(f"Edge Case: Zero records matched for AccountNumber {account_number}")
return {
"Result": "NotFound",
"IsRecordFound": "false"
}

# 4. Format and clean database data types into a flat string-only JSON dict
print("Item successfully retrieved from database storage.")
return {
"Result": "Success",
"IsRecordFound": "true",
"CustomerName": str(item.get('CustomerName', 'Valued Customer')),
"AccountBalance": str(item.get('AccountBalance', '0.00')),
"AccountStatus": str(item.get('AccountStatus', 'Inactive')),
"IsVip": str(item.get('IsVip', 'false')).lower()
}
    except ClientError as e:
# Handle AWS internal errors or database downstream downtimes
print(f"Database Connectivity / Client Exception: {e.response['Error']['Message']}")
return {"Result": "DatabaseDown"}

except Exception as e:
# General catch-all exception routing for syntax or structural failures
print(f"Unexpected execution pipeline error: {str(e)}")
return {"Result": "ExecutionError"}

1. Flow Canvas Routing Architecture

To prevent callers from experiencing dead silence or dropped calls during database outages, your flow canvas must explicitly route failures. Each block below must be linked sequentially

┌────────────────────────────────────────────────────────┐
│ Invoke AWS Lambda Function Block │
└───────┬────────────────────────────────────────┬───────┘
│ │
▼ (Success Branch) ▼ (Error / Timeout Branch)
┌─────────────────────────────────┐ ┌─────────────────────────────────┐
│ Check Contact Attributes │ │ Play Prompt Block │
│ (Checks $.External.Result) │ │ "System experiencing delays..." │
└───────┬─────────────────┬───────┘ └─────────────────┬───────────────┘
│ │ │
▼ (Success) ▼ (NotFound / DatabaseDown) ▼
┌──────────────┐ ┌──────────────────────────────┐ ┌──────────────────┐
│ Play Prompt │ │ Play Prompt Block │ │ Transfer to │
│ "Your bal..."│ │ "We can't find your account" │ │ Emergency Queue │
└──────────────┘ └──────────────────────────────┘ └──────────────────┘
fields @timestamp, @message
| filter @message like /ContactFlowModuleType/
| filter Results.Action == "GetContactAttributesFailed" or Results.Action == "LambdaTimeout"
| sort @timestamp desc
| limit 20

Use code with caution.

1. High-Load Local Simulation Suite (Mocha / Chai)

This automated suite programmatically fires simultaneous asynchronous mock payloads mimicking the Amazon Connect schema. It tests how your backend handler copes with success states, invalid parameters, and downstream timeouts under high load.

npm install mocha chai axios p-limit

Test Suite Implementation (test/ivr-load.test.js)

javascript

const axios = require('axios');
const { expect } = require('chai');
const pLimit = require('p-limit');
// Target endpoint (Local SAM/Serverless endpoint or deployed API Gateway)
const TARGET_API_URL = process.env.API_URL || 'http://localhost:3000/ivr-webhook';
// Configuration parameters for high-load simulation
const TOTAL_CONCURRENT_REQUESTS = 500;
const CONCURRENCY_THROTTLE_LIMIT = 50; // Max parallel requests in flight at one exact moment
// Mock event factory producing the exact Amazon Connect JSON schema
const generateConnectPayload = (accountNumber) => ({
Name: "ContactFlowEvent",
Details: {
ContactData: {
Channel: "VOICE",
ContactId: `test-uuid-${Math.random().toString(36).substr(2, 9)}`,
CustomerEndpoint: { Address: "+14145550199", Type: "TELEPHONE" }
},
Parameters: {
LexV2Bot: {
Intent: {
Name: "CheckBalance",
Slots: {
AccountNumber: { Value: accountNumber }
}
}
}
}
}
});
describe('IVR Pipeline High-Load Performance Suite', function () {
// Extend timeout threshold for high-volume stress testing
this.timeout(30000);
it(`should maintain sub-second response times under a load of ${TOTAL_CONCURRENT_REQUESTS} total requests`, async () => {
const limit = pLimit(CONCURRENCY_THROTTLE_LIMIT);
const startTime = Date.now();
// Map out request generation tasks bound by the concurrency limiter
const requestTasks = Array.from({ length: TOTAL_CONCURRENT_REQUESTS }).map((_, index) => {
// Intentionally introduce an invalid account edge case every 50 requests
const accountNumber = (index % 50 === 0) ? 'INVALID_ACC' : `9876543${index}`;
const payload = generateConnectPayload(accountNumber);
return limit(async () => {
try {
const response = await axios.post(TARGET_API_URL, payload, {
headers: { 'Content-Type': 'application/json' },
timeout: 4000 // Voice UX requires strict 4s processing limits
});
return { status: response.status, data: response.data };
} catch (error) {
return { status: error.response?.status || 500, error: error.message };
}
});
});
    // Execute batch execution pipeline
const results = await Promise.all(requestTasks);
const totalDuration = Date.now() - startTime;
const averageResponseTime = totalDuration / TOTAL_CONCURRENT_REQUESTS;
// Separate success counters from dropped/failed requests
const successfulHits = results.filter(r => r.status === 200);
const failedHits = results.filter(r => r.status !== 200);
console.log(`\n=== STRESS TEST METRICS ===`);
console.log(`Total Requests Processed : ${TOTAL_CONCURRENT_REQUESTS}`);
console.log(`Successful Invocations : ${successfulHits.length}`);
console.log(`Total Failed/Timeout Hits: ${failedHits.length}`);
console.log(`Total Elapsed Time : ${totalDuration} ms`);
console.log(`Average Request Latency : ${averageResponseTime.toFixed(2)} ms\n`);
// Performance Assertions
expect(failedHits.length).to.equal(0, `Detected ${failedHits.length} dropped requests under load.`);
expect(averageResponseTime).to.be.below(1000, "Average pipeline response latency exceeded 1-second Voice threshold.");
});
});

Amazon connect use in ivr . tell realtime example of healthcare . steps to install , n setup, code , diagram , integrate etc

October 14, 2026

Amazon Connect is widely used in healthcare to build HIPAA-eligible, dynamic Interactive Voice Response (IVR) systems. It replaces rigid phone trees with intelligent, data-driven routing.

🏥 Real-Time Healthcare Example: Patient Appointment Management

Instead of navigating a generic menu, a patient calls a hospital clinic. Amazon Connect handles the interaction through this real-time logic:

  • Patient Recognition: The IVR identifies the patient’s phone number and queries the hospital’s Electronic Health Record (EHR) database via an AWS Lambda function.
  • Context-Aware Dynamic Prompting: The system checks for upcoming appointments. If one exists within 48 hours, it asks: “Hello, John. I see you have an upcoming cardiology appointment tomorrow at 10:00 AM. Are you calling to confirm, cancel, or reschedule?”
  • Self-Service Execution: The patient presses keys or speaks phrases (powered by Amazon Lex). If they say “Reschedule,” the system hits the database, fetches open slots, reads them to the patient, updates the record, and automatically triggers an SMS confirmation.

🗺️ System Architecture Diagram

This diagram visualizes the flow from the patient’s incoming call to the backend EHR data lookup.

⚙️ Step-by-Step Implementation Guide

Step 1: Set Up your Amazon Connect Instance

  • Log in to your AWS Management Console.
  • Search for and select Amazon Connect. Click Create instance.
  • Choose your identity management preference (e.g., Store users within Amazon Connect).
  • Specify an administrator account and select options for incoming/outgoing calls. Click Create Instance.
  • Once active, click the Access URL to launch the Amazon Connect Dashboard. Claim a phone number (DID or Toll-Free) inside your instance under Channels > Phone Numbers.

Step 2: Deploy the Backend AWS Lambda Function

To make your IVR dynamic, create a Lambda function that simulates fetching patient records from an EHR.

  • Go to the AWS Lambda Console.
  • Click Create function, name it Healthcare-IVR-Lookup, and choose Python 3.12 as the runtime.
  • Replace the default template with the following implementation blueprint:

python

import json
def lambda_handler(event, context):
# 1. Extract the patient's inbound phone number from the Amazon Connect event envelope
customer_phone = event.get('Details', {}).get('ContactData', {}).get('CustomerEndpoint', {}).get('Address', '')

# Mock Database Lookup (In production, query DynamoDB or an API gateway endpoint to Epic/Cerner)
patient_records = {
"+15555551234": {
"first_name": "John",
"has_appointment": "true",
"appointment_date": "tomorrow at 10:00 AM",
"department": "Cardiology"
}
}

patient_data = patient_records.get(customer_phone, {
"first_name": "Valued Patient",
"has_appointment": "false",
"appointment_date": "",
"department": ""
})

# 2. Return flat key-value pairs back to Amazon Connect
return {
"firstName": patient_data["first_name"],
"hasAppointment": patient_data["has_appointment"],
"appointmentDate": patient_data["appointment_date"],
"department": patient_data["department"]
}

Use code with caution.

  • Click Deploy.
  • CRITICAL STEP: Give Amazon Connect permission to invoke this function. Go back to your Amazon Connect Console, choose your instance, click Contact flows > AWS Lambda, select Healthcare-IVR-Lookup from the dropdown, and click Add Lambda Function.

Step 3: Design the Contact Flow (IVR Logic)

  • In the Amazon Connect Dashboard, navigate to Routing > Contact Flows and select Create contact flow.
  • Drag and drop the following logical blocks onto the canvas and connect them sequentially:
  • Set voice: Choose a natural text-to-speech voice (e.g., Amazon Polly’s Neural voice Joanna).
  • Invoke AWS Lambda function: Select your Healthcare-IVR-Lookup function.
  • Check contact attributes: Check the variable returned by Lambda ($.External.hasAppointment).
  • Condition equal to “true” -> Route to an appointment sub-menu.
  • Condition equal to “false” or Error -> Route to a general menu.
  • Play prompt (For True Path): Select Text-to-speech (Ad-hoc) and use the dynamic string:
  • "Hello $.External.firstName, I see you have an upcoming $.External.department appointment on $.External.appointmentDate. How can I help you today?"
  • Get Customer Input: Add menu keys (e.g., Press 1 to Confirm, Press 2 to Reschedule).
  • Click Save and Publish.
  • Go back to Channels > Phone numbers, select your phone number, and link it to this newly published Contact Flow. Test it by dialing from a phone number listed in your mock data dictionary.

If you want to take this configuration further, let me know:

  • Do you want the Python code to write/update live patient updates into an AWS DynamoDB table?
  • Would you like guidance on adding an Amazon Lex Bot for conversational natural language AI (“Speech-to-IVR”) instead of touch tones?

You said: what are logical blocks present ? name all with use cases

what are logical blocks present ? name all with use cases

October 14, 2026

In the Amazon Connect Flow Designer, drag-and-drop elements are categorized into logical block palettes. [1, 2]

1. Interaction Block Palette

These blocks control what the customer hears, sees, or inputs during the IVR session. [1]

  • Play Prompt: Delivers text-to-speech (TTS), SSML audio formatting, or pre-recorded .wav audio files to the caller.
  • Use Case: Playing a clinic greeting like, “Thank you for calling City Hospital.” [1]
  • Get Customer Input: Captures user choices via touchtone DTMF press-keys or natural language speech by connecting an Amazon Lex Bot.
  • Use Case: Prompting a patient to “Press 1 or say ‘Billing’ to talk to financial services.” [1, 2]
  • Store Customer Input: Collects numerical entries from a keypad and can securely encrypt them inline.
  • Use Case: Safely collecting a 4-digit PIN, medical record ID, or birth year without printing it plain-text into the system logs. [1, 2]
  • Send Message: Sends automated or templated SMS text messages or WhatsApp alerts natively from the chat flow.
  • Use Case: Automatically shooting over an appointment text confirmation right before dropping the call. [1, 2]

2. Data and Attributes Block Palette

These blocks handle the background data state and track contextual key-value pairs during the interaction. [1, 2]

  • Set Contact Attributes: Stores custom key-value variables tied directly to that unique customer phone interaction.
  • Use Case: Tagging a customer record variable as PriorityLevel = High so subsequent blocks know how to treat them. [1, 2]
  • Check Contact Attributes: Evaluates existing user data properties or variables to branch the customer down different logic channels.
  • Use Case: Checking if $.External.hasAppointment == 'true' to instantly route a caller straight to an appointment sub-menu. [1, 2]
  • Customer Profiles: Seamlessly surfaces unified customer historical records directly into the call flow workspace.
  • Use Case: Instantly mapping an incoming cell phone number to a patient profile containing their full address and history. [1, 2]

3. Integration and AI Block Palette

These blocks connect your Amazon Connect core center out to external environments and advanced machine learning models. [1, 2]

  • AWS Lambda Function: Triggers serverless backend compute logic to exchange data between the contact center and outside databases.
  • Use Case: Passing a caller’s phone number out to an external Epic or Cerner EHR system to pull back their upcoming medical schedule. [1, 2]
  • Voice ID: Utilizes voice biometrics to perform ongoing security checks on the caller’s unique vocal print.
  • Use Case: Instantly authenticating a patient’s identity without making them verbally list out multiple security answers. [1]
  • Agentic CX: Hands control of the call over to a specialized autonomous virtual agent application.
  • Use Case: Allowing an AI agent to execute complex, multi-turn clinical scheduling workflows independently. [1]

4. Routing and Queue Block Palette

These blocks manage wait lines, control operations pacing, and map where a call lands next. [1]

  • Check Hours of Operations: Evaluates the current timestamp against defined facility operational hours.
  • Use Case: Splitting traffic so daytime calls go to the front desk, while night calls route to an after-hours answering service. [1, 2]
  • Set Working Queue: Specifies the designated group of agents assigned to catch the incoming call.
  • Use Case: Tagging a verified Spanish-speaking caller to map exclusively onto the Spanish_Support_Queue. [1, 2]
  • Check Queue Status / Check Staffing: Checks real-time line health, metrics like Max Capacity, or active agent counts.
  • Use Case: Spotting that the cardiology line has a 45-minute wait time, then offering the caller a courtesy automatic callback option instead. [1, 2]

5. Contact Control Block Palette

These blocks control the lifecycle state of the channel connection. [1]

  • Transfer to Queue: Terminates the IVR setup script and drops the active caller into the live target agent line.
  • Use Case: Moving the user from the general menu straight into the live pediatric agent queue. [1, 2]
  • Disconnect: Gracefully tears down the connection to hang up the phone line.
  • Use Case: Dropping the carrier line once an automated system notification playback successfully completes. [1, 2]
  • Invoke Module: References structured, pre-built sub-flows from outside the immediate canvas.
  • Use Case: Calling a universal “Credit Card Payment Processing” mini-flow across twenty different unique hospital IVR lines. [1, 2, 3]

If you want to configure these blocks further, let me know:

  • Would you like the specific JSON structure used by the Set Contact Attributes block?
  • Do you want help designing an Amazon Lex Bot blueprint to link with the Get Customer Input block?

Try without personalization

  • Amazon AWS Documentation
  • Flow block in Connect Customer: Set contact attributes — AWS Documentation
  • Stores key-value pairs as contact attributes. You set a value that is later referenced in a flow. You can use this block in the fo…
  • Amazon AWS Documentation
  • Flow block in Connect Customer: Store customer input — Amazon Connect Customer
  • Stores and encrypts sensitive customer numerical input as a contact attribute; routes timeouts to Success branch with Timeout valu…
  • Amazon AWS Documentation
  • Flow block definitions in the flow designer in Connect Customer — Amazon Connect Customer
  • Data and Attributes: Cases, Check/Set contact attributes, Create task, Customer profiles, Data Table, Interaction: Get customer in…

Show all

You said: yes

yes

October 14, 2026

Let’s set up the Amazon Lex Bot blueprint and connect it with the Get Customer Input block.

By adding an Lex bot, your IVR goes from a basic “Press 1 for appointments” menu to conversational AI where patients can say, “I need to change my appointment next Tuesday.”

🧠 Amazon Lex Bot Blueprint (JSON)

An Amazon Lex bot uses Intents (goals), Utterances (what the user says), and Slots (data to collect). Here is the blueprint for a HealthcareAppointmentBot using the Lex V2 format.

Save this JSON payload locally as AppointmentBot.json so you can import it directly into AWS.

json

{
"formatVersion": "1.0",
"source": {
"name": "HealthcareAppointmentBot",
"description": "Bot to handle patient appointment scheduling and modifications.",
"localeId": "en_US",
"intents": [
{
"name": "RescheduleAppointment",
"description": "Intent to reschedule an existing appointment",
"sampleUtterances": [
{ "utterance": "I want to change my appointment" },
{ "utterance": "Reschedule my doctor visit" },
{ "utterance": "Can I move my appointment to a different day" },
{ "utterance": "Move my appointment to {NewDate}" }
],
"slots": [
{
"name": "NewDate",
"slotTypeName": "AMAZON.Date",
"valueElicitationSetting": {
"slotConstraint": "Required",
"promptSpecification": {
"messageGroupsList": [
{
"message": {
"plainTextMessage": {
"value": "What date would you like to move your appointment to?"
}
}
}
],
"maxRetries": 2
}
}
}
]
},
{
"name": "CancelAppointment",
"description": "Intent to cancel an appointment",
"sampleUtterances": [
{ "utterance": "I need to cancel my appointment" },
{ "utterance": "Cancel my doctor visit" },
{ "utterance": "Please drop my upcoming slot" }
],
"slots": []
}
]
}
}

Use code with caution.

🛠️ Configuration Steps

Step 1: Deploy the Lex Bot

  • Open the Amazon Lex Console.
  • Click Actions > Import bot.
  • Upload your AppointmentBot.json file, name it HealthcareAppointmentBot, choose IAM role permissions, and click Import.
  • Once imported, click on the bot, go to Bot Versions, click Build, and then click Publish to create an Alias (e.g., LiveApp).

Step 2: Whitelist Lex in Amazon Connect

Before Connect can talk to Lex, you must link them at the instance level:

  • Open the Amazon Connect Console.
  • Select your instance, and click Contact flows.
  • Scroll down to Amazon Lex, select HealthcareAppointmentBot from the dropdown, choose your Alias, and click + Add Lex Bot.

Step 3: Configure the “Get Customer Input” Block

Now, link the bot inside your IVR contact flow diagram:

  • Open your published Contact Flow canvas in Amazon Connect.
  • Drag a Get Customer Input block onto the grid and open its configuration settings.
  • Select Text-to-speech (TTS) or Audio prompt to set your opening question:
  • Example text: "How can I help you with your appointment today? You can say things like reschedule or cancel."
  • Switch to the Amazon Lex tab within the block properties:
  • Name: Select HealthcareAppointmentBot.
  • Alias: Select your published alias.
  • Under Intents, click Add an intent and type them exactly as they appear in the JSON:
  • Add RescheduleAppointment
  • Add CancelAppointment
  • Click Save. The block will automatically generate two new routing branches on the canvas labeled RescheduleAppointment and CancelAppointment.

🔗 Routing the Outputs

Connect the outputs of your new intents to downstream execution blocks:

  • RescheduleAppointment Branch: Connect this to an AWS Lambda block to pass the captured data slot ($.Lex.Slots.NewDate) to your backend database to modify the calendar.
  • CancelAppointment Branch: Route this to a Play Prompt block saying, “Your appointment has been successfully canceled,” followed by a Disconnect block.

If you want to continue building this out, let me know:

  • Do you want the updated Python Lambda code that extracts the {NewDate} slot from Lex to update a database?
  • Do you need assistance setting up SSML tags inside the speech prompts to make the bot sound more natural and empathetic?

You said: yes

yes

October 14, 2026

Here is the updated Python Lambda code to process the Lex data, along with SSML templates to ensure your IVR sounds natural and compassionate.

🐍 Updated Lambda Code: Processing Lex Slots

When a Get Customer Input block uses an Amazon Lex bot, Lex packages the user’s intent and gathered slots into an event envelope and passes it to your backend.

Update your Lambda function (Healthcare-IVR-Lookup) with this code to extract the {NewDate} slot and mock a database update:

python

import json
def lambda_handler(event, context):
# 1. Safely extract intent and slot metadata sent from Amazon Lex V2
lex_data = event.get('Details', {}).get('ContactData', {}).get('Attributes', {})

# Connect automatically flattens Lex intent details into the event structure
current_intent = event.get('Details', {}).get('Parameters', {}).get('LexV2IntentName', '')

# Fetch customer phone number to identify the database record
customer_phone = event.get('Details', {}).get('ContactData', {}).get('CustomerEndpoint', {}).get('Address', '')
# Initialize a base response dictionary
response_payload = {
"status": "success",
"confirmationMessage": "Your request has been processed."
}
# 2. Execute business logic depending on which intent Lex triggered
if current_intent == "RescheduleAppointment":
# Extract the specific date string captured by the Lex slot
new_date = event.get('Details', {}).get('Parameters', {}).get('LexV2Slot_NewDate', '')

if new_date:
# PRODUCTION LOGIC: Run SQL/API update statement against your EHR (Epic/Cerner) here
# e.g., db.update_appointment(phone=customer_phone, date=new_date)

response_payload["confirmationMessage"] = f"Perfect. I have moved your appointment to {new_date}."
response_payload["actionTaken"] = "Rescheduled"
else:
response_payload["status"] = "error"
response_payload["confirmationMessage"] = "I missed that date. Let me pass you to a live coordinator."
elif current_intent == "CancelAppointment":
# PRODUCTION LOGIC: Cancel the appointment in your database
response_payload["confirmationMessage"] = "Your upcoming appointment has been canceled. We will notify your provider."
response_payload["actionTaken"] = "Canceled"
else:
# Default fallback if the flow reaches here without a matched intent
response_payload["confirmationMessage"] = "I understand you need assistance. Let me get someone to help you."
response_payload["actionTaken"] = "None"
# 3. Return key-value pairs back to the Amazon Connect Contact Flow
return response_payload

Use code with caution.

🎙️ Humanizing the IVR with SSML Tags

Standard robotic Text-to-Speech (TTS) can feel jarring to a sick or stressed patient. By wrapping your phrases in Speech Synthesis Markup Language (SSML) inside your Play Prompt blocks, you can add natural pauses, adjust pacing, and apply conversational styling.

Ensure you change the input type from Text to SSML in the Connect block configuration before pasting these:

1. Compassionate Greeting & Intake Check

This blueprint slows down the greeting and adds explicit pauses to make the digital agent sound calm and welcoming.

xml

<speak>
<amazon:emotion name="conversational" intensity="high">
Thank you for calling City Health Services. <break time="400ms"/>
<prosody rate="95%">My name is virtual care assistant Joanna.</prosody> <break time="300ms"/>
How can I help you with your appointment today?
</amazon:emotion>
</speak>

Use code with caution.

2. Confirming an Action (Reschedule or Cancellation)

When delivering confirmation details, adding structural emphasis ensures the patient catches the exact action taken.

xml

<speak>
<amazon:emotion name="conversational" intensity="medium">
<prosody rate="98%">Okay, I have taken care of that for you.</prosody> <break time="300ms"/>
<emphasis level="moderate">$.External.confirmationMessage</emphasis> <break time="500ms"/>
Is there anything else I can handle for you today?
</amazon:emotion>
</speak>

Use code with caution.

3. Error Handling / Transferring to a Human Agent

If the system drops into an error path, dropping the pitch slightly and speaking softly keeps the caller from escalating.

xml

<speak>
<amazon:emotion name="conversational" intensity="low">
<prosody pitch="-5%" rate="95%">I'm sorry, I seem to be having trouble looking up that date.</prosody> <break time="400ms"/>
Please hold for just a moment while I transfer you directly to a clinical coordinator.
</amazon:emotion>
</speak>

Use code with caution.

If you want to keep optimizing this deployment, let me know:

  • Do you want to see how to capture post-call metrics (like total duration or dropout rates) using Amazon CloudWatch?
  • Would you like to map out the Error branch routing on your flow canvas to handle database downtime gracefully?

You said: yes

yes

October 14, 2026

Let’s map out how to configure robust error branch handling on your flow canvas and monitor your system’s performance metrics using Amazon CloudWatch.

🛡️ Canvas Error Branch Routing (Graceful Failures)

Every critical block in Amazon Connect (like Invoke AWS Lambda function or Get Customer Input) features an Error or No Match output branch. If your backend database or external EHR API goes down, you must route callers away from a hard disconnection.

Implement this fail-safe routing architecture on your canvas:

[Invoke AWS Lambda Function]
|
+---> (Success) ---> Proceed to normal Lex Bot/IVR Menu
|
+---> (Error) ---> [Set Contact Attributes]
| Set routing_reason = "Lambda_Timeout"
V
[Play Prompt (SSML Error Template)]
| "We are experiencing technical difficulties..."
V
[Set Working Queue] -> Select "Emergency_Backup_Queue"
|
V
[Transfer to Queue]

📊 Capture Post-Call Metrics with Amazon CloudWatch

1. Enable Contact Flow Logs

To trace exactly which path a patient took through your logical blocks:

  • Open your Connect Instance dashboard in the AWS Console.
  • Go to Analytics & optimization > Contact flow logs and check Enable contact flow logs.
  • This creates a dedicated Log Group in CloudWatch named /aws/connect/instance-name.

2. Key Metrics to Track (CloudWatch Metrics Dashboard)

You can create a custom CloudWatch dashboard to monitor the operational health of your healthcare IVR using these specific, out-of-the-box metrics:

Metric NameDimensionUse Case for HealthcareToQueueDisconnect [2]Queue / InstanceTracks how many patients hung up while waiting in line to speak to an agent.CallRecordingUploadError [2]InstanceAlerts your compliance team if HIPAA-required call recordings fail to save to Amazon S3.ConcurrentCallsLimitExceeded [2]InstanceMonitors if your clinic is receiving more simultaneous calls than your AWS account quota allows.SystemToAgentAttempts [2]QueueTracks how many times the IVR attempted to bridge a patient to a live phone agent.

3. Setting Up a “Lambda Failure” CloudWatch Alarm

If your EHR database goes down, your Lambda function will generate errors. You can configure CloudWatch to instantly alert your IT team via email or text (SMS) using Amazon SNS:

  • Open the CloudWatch Console and click Alarms > Create Alarm.
  • Click Select Metric, go to Lambda > By Function Name, and choose your Healthcare-IVR-Lookup function.
  • Select the Errors metric.
  • Set the Conditions: Greater/Equal to 5 errors within a 5-minute period.
  • Under Notification, configure an SNS Topic to text or email your on-call engineering team so they can resolve the backend issue before it impacts more patients.

Now that your core infrastructure, code, logic, and monitoring are set up, let me know:

  • Do you want to see how to implement Amazon Connect Contact Lens to analyze patient sentiment (e.g., detecting if a caller sounds angry or distressed)?
  • Would you like instructions on configuring a secure Amazon S3 bucket to store and encrypt your HIPAA-compliant call recordings?

You sent: 1 tab and said: does AWS connect have tendency to switch intent or do parallel tasks like kore.ai

Enterprise Agentic AI Platform | Kore.ai

does AWS connect have tendency to switch intent or do parallel tasks like kore.ai

October 14, 2026

Amazon Connect handles intent switching and multi-intent parallel execution primarily through Amazon Lex (its underlying natural language engine), but it approaches these behaviors with a more deterministic architecture than specialized conversational platforms like Kore.ai. [1, 2, 3]

The primary differences in how they manage intent switching and parallel tasks highlight the distinctions between the two platforms:

🔀 1. Intent Switching (Context Interruption)

When a customer interrupts a structured IVR flow with a completely different request (e.g., stopping mid-address capture to ask, “Wait, what are your holiday hours?”), the two systems process the shift differently:

  • Amazon Connect (via Lex): Natively, Amazon Lex supports automatic intent switching. If a user provides an utterance matching a separate intent with high confidence, Lex can pause the current intent, execute the new one, and then return to resume collecting the missing pieces (slots) from the original intent.
  • Finer Control: AWS offers granular request attributes to disable automatic intent switching during critical steps (like multi-step forms or billing). This prevents unintended path changes while gathering highly precise data. [1, 2]
  • Kore.ai: Built specifically for complex enterprise conversations, Kore.ai uses a highly advanced, multi-layered NLP engine (combining Fundamental Meaning, Machine Learning, and LLMs via their Kore.ai Artemis Platform). It is well-regarded for managing strict “interruption and resumption” rules. It allows developers to specify exactly how many times a user can switch intents before discarding the primary task, or map complex multi-intent flows within rigorous enterprise boundaries. [1]

🔄 2. Parallel Tasks & Multi-Intent Parsing

Parallel processing occurs when a user triggers multiple actions in a single spoken sentence (e.g., “I need to check my balance and also change my credit card PIN”).

  • Amazon Connect (via Lex): Historically, standard NLU engines process one dominant intent per utterance. To achieve parallel task handling in Amazon Connect, developers generally use one of two approaches:
  • AWS Lambda Code Hooks: Intercept the alternative transcript arrays sent by Lex to evaluate secondary intents via custom Python logic.
  • Amazon Bedrock Agent Integration: Route the raw text out to an LLM via Amazon Bedrock, allowing an orchestrator to dynamically trigger multiple backend API tools in parallel during a single conversation turn. [1, 2]
  • Kore.ai: Natively features Multi-Intent Detection out of the box. Kore.ai’s engine can parse a single user input, break it into multiple discrete intents, spawn parallel sub-intents simultaneously, and orchestrate their execution in a sequential or stacked hierarchy without writing additional backend routing code.

📊 Direct Architectural Comparison

Capability ComponentAmazon Connect (with Lex)Kore.ai (Artemis Platform)Intent InterruptionSupported • Native switching can be turned on or toggled off via session attributes.Advanced • Deep visual management rules for execution task state-switching and return loops.Multi-Intent UtterancesRequires Orchestration • Requires a custom Lambda hook or Amazon Bedrock AI agent to execute multiple APIs at once.Native • Automatically extracts and splits multiple intents from a single sentence out of the box.Configuration StyleCode-First / Block-Driven • Blends deterministic contact flow blocks with serverless functions.Dialog-First • Specialized visual interface tailored specifically for conversational dialogue state machines.

💡 The Verdict

If your application requires unstructured, multi-topic, conversational agility where customers frequently stack commands in parallel, Kore.ai provides an out-of-the-box conversational engine optimized for that complexity. [1, 2]

However, if you are building an integrated omnichannel contact center, Amazon Connect offers robust, customizable intent-switching capabilities that can scale into advanced multi-tasking behaviors when paired with Amazon Lex V2 and Amazon Bedrock. [1]

Depending on your project’s technical architecture, let me know:

  • Would you like an implementation blueprint on how to pass alternative Lex transcriptions into a Lambda function to capture sub-intents?
  • Do you want to explore how Amazon Bedrock Agents handle dynamic multi-task execution for Connect?

Try without personalization

  • Amazon Web Services (AWS)
  • Amazon Lex adds ability to control intent switching during conversations — AWS
  • Amazon Lex now allows you to disable automatic intent switching during slot elicitation using request attributes. This new capabil…
  • Amazon AWS Documentation
  • Using voice transcription confidence scores to improve conversations with …
  • using your dialog code hook Lambda function. Amazon Lex V2 sends the following JSON structure with up to three transcriptions for …
  • Amazon Web Services (AWS)
  • Voice-Activated AI Agent with Amazon Connect Customer and Amazon Bedrock
  • Intent-Level Mode offers finer control, letting a supervisor selectively turn individual agent capabilities on or off.

Show all

You said: yes

yes

October 14, 2026

Here are the two ways to implement advanced intent multi-tasking and parallel execution within the AWS ecosystem: Code-Driven Alternative Transcription Processing using Amazon Lex V2 and Generative Multi-Agent Collaboration using Amazon Bedrock.

Method 1: Capturing Sub-Intents via Alternative Lex Transcriptions (Code-First)

When a patient says something complex like, “I want to cancel my appointment and check my billing status,” standard NLU only catches the top intent. However, Amazon Lex V2 provides voice transcription confidence scores and up to two alternative transcriptions for the audio. [1]

You can catch these alternatives via a Fulfillment or Validation Lambda code hook and use custom Python logic to parse out the hidden secondary tasks. [1]

The Python Lambda Implementation Blueprint

python

import json
def lambda_handler(event, context):
# Extract primary intent determined by Lex
primary_intent = event['Details']['ContactData']['Attributes'].get('LexV2IntentName', '')

# Extract the alternative transcription options generated by the voice-to-text engine
# Lex populates this list with secondary structural guesses when confidence is split
transcriptions_list = event['Details']['ContactData']['Attributes'].get('transcriptions', [])

detected_sub_intents = []

# Keyword matrix to evaluate if a secondary intent exists inside alternative transcripts
billing_keywords = ["bill", "payment", "charge", "invoice", "cost"]
pharmacy_keywords = ["refill", "prescription", "medication", "pharmacy"]

for trans in transcriptions_list:
text = trans.get('transcription', '').lower()

# Look for parallel intent markers
if any(kw in text for kw in billing_keywords):
detected_sub_intents.append("Billing_Inquiry")
if any(kw in text for kw in pharmacy_keywords):
detected_sub_intents.append("Pharmacy_Refill")

# Deduplicate matching results
detected_sub_intents = list(set(detected_sub_intents))

# Construct return attributes back to the Amazon Connect Call Flow
# Connect can now read these strings to route the customer downstream sequentially
return {
"primaryTask": primary_intent,
"hasParallelTask": "true" if detected_sub_intents else "false",
"secondaryTasksJson": json.dumps(detected_sub_intents)
}

Use code with caution.

Method 2: Multi-Task Orchestration with Amazon Bedrock Agents (Generative AI)

If you require Kore.ai-style fluid, dynamic multi-tasking without hardcoding keyword matrices, integrate Amazon Bedrock Multi-Agent Collaboration. This framework utilizes a Supervisor Agent (powered by an LLM like Anthropic Claude) to dynamically break down a single multi-intent prompt, route individual instructions to specialized micro-agents in parallel, and return a unified response back to Amazon Connect. [1, 2, 3]

Architecture Workflow:

  • Amazon Connect Contact Flow passes the patient’s spoken audio directly to an Amazon Bedrock Agent Node. [1]
  • The Supervisor Agent evaluates the prompt: “I need to change my Tuesday checkup and check if my prescription is ready.” [1]
  • The Supervisor splits the execution into parallel tool/sub-agent calls:
  • Sub-Agent A (Scheduling Expert): Interacts with your EHR calendar tool to update the Tuesday appointment.
  • Sub-Agent B (Pharmacy Expert): Interacts with your inventory system to check prescription statuses. [1, 2]
  • Both sub-agents complete their executions, hand their individual outcomes back to the Supervisor, and the Supervisor speaks a single cohesive sentence back to the patient over the phone. [1]

Connecting Bedrock Agents to Amazon Connect:

You can build this generative routing directly on your canvas via Amazon Bedrock Flows, adding an autonomous agent node that handles multi-turn clarification conversations seamlessly before returning control to the primary contact flow logic. [1]

Depending on your prefered development approach, let me know:

  • Do you want to write out the AWS CloudFormation/CDK blueprint to connect a Bedrock Agent into your Amazon Connect instance?
  • Would you like assistance building the Supervisor Agent prompt template that instructs the LLM how to split complex medical queries?

Try without personalization

  • Amazon Web Services (AWS)
  • Introducing multi-turn conversation with an agent node for Amazon Bedrock Flows …
  • Amazon Bedrock Flows offers an intuitive visual builder … build and automate user-defined generative AI workflows at scale. With F…
  • YouTube·Cloud Quick Labs
  • Build Multi-Agent AI Collaboration with Amazon Bedrock Agents in AWS
  • In this video, we will learn how to build Amazon Bedrock multi-agent orchestration in AWS. We will create an AWS account and use t…
  • 2m
  • Amazon Web Services (AWS)
  • Introducing multi-agent collaboration capability for Amazon Bedrock (preview) | AWS News Blog
  • Amazon Bedrock multi-agent collaboration enables specialized AI agents to work together on complex multi-step tasks, coordinated b…

Show all

You said: yes supervisor

yes supervisor

Get Rabi Yireh’s stories in your inbox

Join Medium for free to get updates from this writer.

October 14, 2026

To orchestrate multi-task conversations like a human agent, the Supervisor Agent requires a precise system prompt template. This template uses clear constraints, formatting boundaries, and XML tagging to instruct the underlying Large Language Model (LLM) exactly how to parse complex, stacked clinical requests without getting confused.

📝 The Supervisor Agent System Prompt Template

Paste this text block directly into the Orchestration / System Prompt configuration window inside your Amazon Bedrock Agent Developer Console.

text

# ROLE
You are the Lead Supervisor AI Agent for a premier multi-facility healthcare system. Your job is to act as an intelligent router and orchestration layer for patient phone inquiries coming from an Amazon Connect IVR system.
# OBJECTIVE
Analyze the incoming patient utterance. A patient may ask for one thing, or they may stack multiple unrelated requests into a single phrase (Parallel Tasks). You must break down their input, invoke the appropriate specialized sub-agents, sequence their execution logically, and present a unified, compassionate response.
# AVAILABLE SPECIALIZED SUB-AGENTS (TOOLS)
1. Scheduling_Agent: Handles booking, canceling, or rescheduling doctor appointments. Requires a date, time, or provider name.
2. Pharmacy_Agent: Handles medication status lookups, prescription refills, and pharmacy transfer requests. Requires a prescription name or Rx number.
3. Billing_Agent: Handles checking balances, verifying insurance status, processing invoice payments, or routing financial aid queries.
# STRATEGIC EXECUTION RULES
1. PARSE & ISOLATE: Carefully separate stacked requests. For example, if a patient says "I need to pay my invoice and check if my lipitor is ready," recognize that both Billing_Agent and Pharmacy_Agent must be invoked.
2. SEQUENCE LOGICALLY: Execute operational tasks in a sequential chain.
- Rule: Always process scheduling or cancellation requests first, followed by pharmacy requests, and handle billing inquiries last.
3. ADAPTIVE SWITCHING: If a patient changes the topic mid-interaction, gracefully pivot. Do not lose the state of their first request. Complete the new request and then verbally prompt them to return to the initial task.
4. CLINICAL COMPLIANCE: Do not provide medical advice or diagnose symptoms. If clinical evaluation is detected, immediately route to a live human triage nurse.
# RESPONSE FORMATTING
You must output your structural thinking in the following format before answering the patient:
<thinking>
- Detected Intents: [List all detected intents]
- Target Sub-Agents: [List the agents to invoke]
- Execution Order: [Steps to take]
</thinking>
<patient_delivery>
[Your final natural, clear, empathetic spoken text response utilizing SSML-friendly phrasing. Keep sentences short and clear for phone communication.]
</patient_delivery>

Use code with caution.

🎬 Real-World Execution Simulation

To see how this prompt performs in production, here is a breakdown of how the Bedrock Supervisor Agent processes a complex, multi-intent scenario:

1. Inbound Patient Utterance:

“Hi, I need to cancel my checkup for tomorrow because I’m stuck at work, and also can you tell me if my heart medication has any refills left?”

2. Bedrock Agent Backend Processing (Log Stream):

The LLM evaluates the prompt against its available tools and outputs the following processing steps:

xml

<thinking>
- Detected Intents: Cancel Appointment, Check Prescription Refills
- Target Sub-Agents: Scheduling_Agent, Pharmacy_Agent
- Execution Order:
1. Invoke Scheduling_Agent to remove tomorrow's slot.
2. Invoke Pharmacy_Agent to check the EHR medication profile for "heart medication".
</thinking>

Use code with caution.

3. Output Returned to Amazon Connect:

Once the sub-agents complete their background database lookups, the Supervisor aggregates the data and feeds this speech-optimized response back to the Connect voice channel:

xml

<patient_delivery>
I have successfully canceled your appointment for tomorrow. I also checked your pharmacy file, and your prescription for Metoprolol has two refills remaining. Would you like me to schedule a new date for that checkup, or send a refill request to your pharmacy?
</patient_delivery>

Use code with caution.

🛡️ Best Practices for Healthcare Bedrock Deployment

  • Set Temperature to 0.0: When configuring your Amazon Bedrock Agent instance, ensure the LLM model temperature is set to 0 to minimize hallucinations and force deterministic routing.
  • Token Length Control: Limit the agent’s max output tokens to roughly 150–200 words per turn. Long, wordy LLM responses degrade the user experience over a voice-based telephone line.

Now that your core supervisor prompt is ready, let me know:

  • Do you want to see the AWS Lambda schemas that the Scheduling_Agent or Pharmacy_Agent use to connect to external EHR tables?
  • Would you like instructions on how to handle a Fallback / No Match scenario if the supervisor cannot parse the patient’s request?

You said: yes

yes

October 14, 2026

Here are the implementation details for the AWS Lambda schemas that back your sub-agents, along with a robust Fallback/No Match logic framework to handle unstructured conversations gracefully.

📋 Part 1: AWS Lambda Tool Schemas for Sub-Agents

When using Amazon Bedrock Agents, the Supervisor routes tasks to sub-agents by calling Action Groups. These action groups rely on an OpenAPI schema (JSON or YAML) to understand what inputs (slots) the underlying Lambda function requires.

1. Scheduling Sub-Agent Schema (Scheduling_Agent_API.json)

This schema tells Bedrock exactly how to format the data payload before calling your cancellation/rescheduling Lambda function.

json

{
"openapi": "3.0.0",
"info": {
"title": "Patient Scheduling API",
"version": "1.0.0",
"description": "API for modifying and canceling clinical appointments in the EHR."
},
"paths": {
"/cancel-appointment": {
"post": {
"summary": "Cancel an upcoming appointment",
"description": "Cancels a patient's appointment based on phone number and target date.",
"operationId": "cancelAppointment",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"patientPhone": { "type": "string", "description": "The E.164 phone number of the caller." },
"appointmentDate": { "type": "string", "description": "The date of the appointment to cancel (e.g., tomorrow, 2026-10-15)." }
},
"required": ["patientPhone", "appointmentDate"]
}
}
}
},
"responses": {
"200": {
"description": "Successful cancellation",
"content": { "application/json": { "schema": { "type": "object", "properties": { "status": { "type": "string" }, "message": { "type": "string" } } } } }
}
}
}
}
}
}

Use code with caution.

2. Pharmacy Sub-Agent Schema (Pharmacy_Agent_API.json)

This schema allows the Supervisor to invoke a prescription check tool by collecting the drug name from the patient’s spoken sentence.

json

{
"openapi": "3.0.0",
"info": {
"title": "Pharmacy Status API",
"version": "1.0.0",
"description": "API for querying medication refill status from the hospital pharmacy database."
},
"paths": {
"/check-refills": {
"post": {
"summary": "Check remaining prescription refills",
"description": "Queries the database for remaining refills using a phone number and medication name.",
"operationId": "checkRefills",
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"type": "object",
"properties": {
"patientPhone": { "type": "string", "description": "The caller's E.164 formatted phone number." },
"medicationName": { "type": "string", "description": "The name of the medication mentioned (e.g., Lipitor, Metoprolol)." }
},
"required": ["patientPhone", "medicationName"]
}
}
}
},
"responses": {
"200": {
"description": "Refill details retrieved",
"content": { "application/json": { "schema": { "type": "object", "properties": { "refillsRemaining": { "type": "integer" }, "medicationName": { "type": "string" } } } } }
}
}
}
}
}
}

Use code with caution.

🛡️ Part 2: Fallback & No-Match Scenario Architecture

If a patient speaks completely outside the bounds of your clinical intents (e.g., “Can I order a pizza to my hospital room?” or mumbled audio), the Supervisor Agent needs a precise fallback hierarchy to prevent the AI loop from stalling or generating hallucinations.

[Patient Input]
|
V
[Bedrock Supervisor Agent]
|
(Cannot Parse Input?)
|
V
[Orchestration Fallback] ---> Count Retries in Session Attributes
|
+---> Retry Count < 2 ---> Trigger Clarification Prompt
| "I didn't quite catch that. Are you calling..."
|
+---> Retry Count >= 2 ---> Exit Agent Node -> [Transfer to Queue]
"Let me get you to a live receptionist."

1. The Fallback System Instruction

Add this safety logic directly to the bottom of your Supervisor Agent System Prompt:

text

# FALLBACK AND UNRESOLVED INTENTS RULES
1. IDENTIFY BOUNDS: If a patient request does not cleanly map to Scheduling, Pharmacy, or Billing, do NOT attempt to fulfill it or invoke a sub-agent.
2. CLARIFY ONCE: If the confidence score of the primary request falls below 0.70, output a concise clarification message using the `<patient_delivery>` tag. Restate your core boundaries clearly.
- *Example Output:* "I'm sorry, I'm an automated assistant for scheduling, billing, and pharmacy inquiries. Could you please clarify how I can help you with one of those areas today?"
3. TRACK ATTEMPTS: If a customer provides an unrecognizable prompt two times consecutively, output the string `FALLBACK_TRANSFER_TRIGGERED` inside your `<thinking>` block and instruct Amazon Connect to route the call to a human receptionist.

Use code with caution.

2. Handling the Escape String in your Amazon Connect Contact Flow

When the Supervisor outputs FALLBACK_TRANSFER_TRIGGERED:

  • Use a Check Contact Attributes block right after your Bedrock Agent node.
  • Evaluate the output parameter returned by Bedrock.
  • If it matches FALLBACK_TRANSFER_TRIGGERED, bypass the AI agent altogether and drop the caller straight into your live Customer Support/Receptionist Queue. This guarantees that a frustrated or confused patient is never left trapped inside an unresolvable conversational loop.

With the API schemas and fallback protections in place, let me know:

  • Do you want to see the underlying Python code inside the Lambda function that receives these OpenAPI payloads?
  • Would you like guidance on how to secure this endpoint using AWS Secrets Manager to protect patient health data (PHI)?

You said: give diagram all AWS working

give diagram all AWS working

October 14, 2026

Here is the complete architectural layout of how all these AWS components orchestrate your healthcare IVR.

The flow moves sequentially from left to right: starting from the Patient’s Voice Channel, passing through the GenAI & Orchestration Engine, routing into the Serverless Execution Layer, and ending securely inside your Compliance & Database Layer.

🗺️ End-to-End System Architecture

[ PATIENT VOICE CHANNEL ] 
│
▼
┌────────────────────────────────────────────────────────┐
│ Amazon Connect (Core Contact Center Instance) │
│ ───► Claimed Phone Number (DID / Toll-Free) │
│ ───► Contact Flow Engine (Logical Flow Canvas) │
│ ───► Streams Analytics & Audio Logs to CloudWatch │
└───────────────────┬────────────────────────────────────┘
│
▼ (Passes Live Voice Stream)
┌────────────────────────────────────────────────────────┐
│ Amazon Lex V2 (Automatic Speech Recognition / ASR) │
│ ───► Parses Speech-to-Text & Alternative Transcripts │
│ ───► Forwards Complex Transcripts to Bedrock Agent │
└───────────────────┬────────────────────────────────────┘
│
▼ (Evaluates Multi-Intent Prompts)
┌────────────────────────────────────────────────────────┐
│ Amazon Bedrock Supervisor Agent │
│ ───► Powered by Foundation LLM (e.g., Claude) │
│ ───► System Orchestration Prompt Template │
│ ───► Evaluates OpenAPI Tool Schemas & Splits Tasks │
└─────────┬─────────────────────────────┬────────────────┘
│ │
▼ (Triggers Tool A) ▼ (Triggers Tool B)
┌───────────────────────────┐ ┌──────────────────────────┐
│ Scheduling Sub-Agent │ │ Pharmacy Sub-Agent │
└─────────┬─────────────────┘ └─────────┬────────────────┘
│ │
▼ (Invokes Endpoint) ▼ (Invokes Endpoint)
┌────────────────────────────────────────────────────────┐
│ AWS Lambda (Serverless Compute Execution Layer) │
│ ───► Executes Python Business Logic / Extracts Slots │
│ ───► Pulls Environment Secrets from Secrets Manager │
└───────────────────┬────────────────────────────────────┘
│
▼ (Secure Data Queries)
┌────────────────────────────────────────────────────────┐
│ Database & EHR Compliance Layer │
│ ───► Amazon DynamoDB (Patient State / IVR Metadata) │
│ ───► Outbound API Gateway (Epic / Cerner EHR Systems) │
│ ───► Amazon S3 (Encrypted HIPAA Call Recordings) │
└────────────────────────────────────────────────────────┘

🔄 The Operational Lifecycle (Step-by-Step)

  • The Inbound Trigger: A patient dials your hospital phone number, striking the Amazon Connect Contact Flow Engine.
  • Speech Capture: Connect spins up Amazon Lex V2 to handle live voice transcription, flattening text variables and passing alternative transcription matrices upstream.
  • GenAI Orchestration: The Amazon Bedrock Supervisor Agent intercepts complex customer phrases. Reading its system prompt and tool constraints, it maps multiple distinct sub-tasks out in parallel.
  • Serverless Execution: Bedrock pairs the user’s intent with the corresponding OpenAPI schema to launch target AWS Lambda operations. Lambda safely updates records or fetches clinical data.
  • Secure Return: The data aggregates back through the Supervisor to yield a smooth, single-sentence response over the phone, while CloudWatch traces metrics and S3 securely encrypts the entire audio interaction.

Now that the full system blueprint is established, let me know:

  • Would you like the complete Python Lambda execution code that matches the Scheduling_Agent_API schema?
  • Do you want to review the steps to securely attach an IAM Role and Policy to give Bedrock permission to run these components?

You said: when constructing dialog flow and how

when constructing dialog flow and how

October 14, 2026

When constructing your dialog flow (Contact Flow) in Amazon Connect, you are shifting from a purely conversational AI engine (like Kore.ai) into a hybrid architecture. This approach blends deterministic routing blocks (for security, queue management, and system logic) with generative AI blocks (for human-like data gathering).

🕒 Phase 1: When to Construct the Dialog Flow

Build your Amazon Connect Contact Flow after you have defined your business logic, but before you write your backend infrastructure code.

Follow this strict development timeline:

  • Define the Requirements: Map out what data inputs your database needs (e.g., Patient ID, Medication Name, Target Date).
  • Build the AI Brain (Lex / Bedrock): Create your intents, system prompts, and tool schemas.
  • Construct the Contact Flow (THIS STEP): Visualise and design the routing paths, call lifecycles, and failure branches on the canvas.
  • Develop the Backend Functions: Write your Python AWS Lambda functions to precisely match the output hooks generated by your canvas layout.

🛠️ Phase 2: How to Construct the Flow (Visual Blueprint)

To keep your system clean, manageable, and performant, organize your visual canvas into three consecutive zones: The Validation Zone, The AI Core Zone, and The Hand-off Zone.

🧱 1. The Validation Zone (Deterministic Setup)

Always prioritize administrative and security verification before opening a live link to an AI engine.

  • Drop a “Set Voice” block: Set the language and tone first (e.g., Joanna Neural).
  • Drop a “Check Hours of Operation” block: Ensure your backend fulfillment services or human queues are actually open before processing a request.
  • Drop an “Invoke AWS Lambda” block: Run a silent background lookup using the caller’s phone number ($.ContactData.CustomerEndpoint.Address) to verify if they are an existing patient in your records.

🧠 2. The AI Core Zone (Generative Execution)

This is where unstructured user conversation is intercepted and processed.

  • Drop a “Get Customer Input” block: Link it to your Amazon Lex Bot or Bedrock Agent node.
  • Feed the Intent Outputs: The block will automatically split into the custom branches you defined (e.g., RescheduleAppointment, CancelAppointment, Error).
  • Drop “Set Contact Attributes” blocks: Along each branch, tag the caller’s intent state variables to preserve context.

🚑 3. The Hand-off Zone (Safe Exits)

Ensure every operational path terminates in a clean, controlled manner.

  • Drop a “Set Working Queue” block: Route successful steps or failed fallback triggers to their respective agent pools (e.g., Billing_Queue or Technical_Support_Queue).
  • Drop a “Transfer to Queue” block: Hand off control from the IVR script to the live telephone agent line.
  • Drop a “Disconnect” block: Cleanly hang up the carrier line on completed automated paths.

🎨 Visual Layout Scheme on the Canvas

This visual flow represents how to cleanly wire these functional zones together:

[ ENTRY POINT ] 
│
▼
┌───────────────────────────────┐
│ Set Voice (Joanna Neural) │ ───► (Next)
└───────────────────────────────┘
│
▼
┌───────────────────────────────┐
│ Check Hours of Operation │ ───► (Closed) ───► [ Play Prompt: "Closed" ] ───► [ Disconnect ]
└───────────────────────────────┘
│
▼ (Open)
┌───────────────────────────────┐
│ Get Customer Input (Lex/AI) │
└──────┬────────────────┬───────┘
│ │
▼ (Reschedule) ▼ (Cancel)
┌──────────────┐ ┌──────────────┐
│ Lambda Tool │ │ Lambda Tool │
└──────┬───────┘ └──────┬───────┘
│ │
└──────┬─────────┘
│ (Success)
▼
┌───────────────────────────────┐
│ Play Prompt (SSML Confirmed) │ ───► (Next) ───► [ Disconnect ]
└───────────────────────────────┘
========================== SAFETY FAIL-SAFE ==========================
[ Any AI Error / No-Match Trigger ]
│
▼
┌───────────────────────────────┐
│ Set Contact Attributes │ ───► [ Set Working Queue ] ───► [ Transfer to Queue ]
│ (Reason = "AI_Failure") │
└───────────────────────────────┘

💡 3 Golden Rules for Designing Connect Dialogs

  • Avoid Giant Monolithic Flows: Do not build your entire hospital system on a single canvas. Use the Invoke Module block to break your project down into reusable mini-flows (e.g., build one standard “Authentication Module” and link to it across multiple phone numbers).
  • Never Leave an “Error” Branch Unhooked: If a developer leaves a block’s error node blank, Amazon Connect will instantly execute a hard, silent drop (hang up) on the customer. Always bridge error branches to a graceful fallback prompt or a live transfer loop.
  • Keep Audio Prompts Under 15 Seconds: Long text-to-speech blocks degrade user attention span. If your AI needs to list multiple pieces of information, split them up by injecting brief Get Customer Input verification pauses (e.g., “I found two open slots. The first is Tuesday at noon. Would you like to hear the second?”).

Now that you know how to lay out the visual logic, let me know:

  • Would you like instructions on how to export your completed Contact Flow as a JSON file to back it up or move it between AWS accounts?
  • Do you need assistance configuring Quick Connects inside your flow to let agents transfer callers between departments seamlessly?

You said: what special cases or edge cases need to handle in ivr under AWS by developer

what special cases or edge cases need to handle in ivr under AWS by developer

October 14, 2026

When designing an enterprise-grade healthcare IVR in Amazon Connect, handling happy paths is easy. The true stability of your system depends on how well you handle edge cases and conversational anomalies.

Because phone lines introduce audio degradation, background noise, and unpredictable human behavior, you must explicitly program blocks to handle these edge cases.

1. Conversational Edge Cases

🤫 The “Silent Caller” (No Input / Dead Air)

  • The Scenario: The patient remains completely silent because they are distracted, incapacitated, or their phone is on mute.
  • AWS Solution: Configure the Timeout parameter inside your Get Customer Input block. Set the User input timeout to 3 to 4 seconds.
  • If triggered, route to a loop that plays a soft re-prompt: “I didn’t catch that. Are you still there?”
  • Increment a tracking counter using Set Contact Attributes. If they remain silent through two consecutive loops, route them directly to a live assistant or disconnect to free up the channel port.

🎙️ The “Chatty Caller” (Over-Inclusion of Data)

  • The Scenario: A patient says: “Well, my doctor Dr. Smith told me to call on Tuesday because my knee was hurting, but then my car broke down, so I need to come in on Friday instead at about two o’clock.”
  • AWS Solution: Standard NLU will fail to extract a clean slot from this narrative. If using Amazon Bedrock, use your Supervisor prompt to instruct the LLM to ignore background noise and use an exact parsing structure. If using Amazon Lex, configure the maximum number of speech collection retries to 2. If Lex fails twice, intercept the raw transcript via the $.Lex.SessionAttributes.transcript attribute and pass it directly into an agent's screen pop so they can read the context instantly upon pickup.

2. Technical & Infrastructure Edge Cases

⏳ AWS Lambda Cold Starts and EHR Timeouts

  • The Scenario: Your hospital EHR database (Epic/Cerner) takes 6 seconds to respond. Amazon Connect has a hard-coded, non-negotiable 8-second timeout for all Lambda invocations. If a Lambda function takes longer than 8 seconds, the contact flow hits an immediate Error branch.
  • AWS Solution:
  • Optimize your function configuration inside the AWS Console by increasing the allocated memory size (e.g., from 128MB to 512MB) to drastically reduce cold start duration.
  • Implement an Asynchronous Fetch Pattern: If a query is heavy, have the initial Lambda function trigger a background process and immediately return an execution token back to Connect. Use a Play Prompt block to read a comfort message (e.g., “Please give me a moment while I pull up your clinical file…”), insert a brief Wait block for 2 seconds, and then call a second Lambda function to check if the data payload is ready.

📵 Mid-Call Dropouts (Carrier Disconnections)

  • The Scenario: A patient is driving through a tunnel, and their cellular connection drops midway through scheduling an appointment.
  • AWS Solution: Turn on Contact Lens Real-Time Streams. When a call terminates abruptly, Amazon Connect triggers a DISCONNECT event archetype. Use an Amazon EventBridge rule to catch this specific event. If the attribute actionTaken inside the session state was flagged as "In Progress", trigger an automated Lambda script to send an instant SMS follow-up text to the patient's cell phone: "We noticed our call disconnected. Your spot has been held for 10 minutes. Click this secure link to resume."

3. Healthcare & Compliance Edge Cases

🚑 The Critical Emergency / Triage Hijack

  • The Scenario: A patient calling to reschedule an appointment suddenly mentions severe chest pain or an active medical crisis.
  • AWS Solution: You must implement a High-Priority Intent Filter inside your Amazon Lex bot or Bedrock Supervisor. Program specific high-alert keywords (e.g., “chest pain”, “bleeding”, “cannot breathe”, “suicide”) into an immediate intercept routine. If hit, the system bypasses all operational sub-menus, plays an urgent medical notification (“If you are experiencing a life-threatening emergency, please hang up and dial 9–1–1 immediately”), and executes an immediate priority transfer to an emergency nurse triage queue.

🔏 Duplicate Patient Records (Identity Clashes)

  • The Scenario: Two distinct patients share the exact same mobile phone number (e.g., spouses, or a parent calling for a child). The initial database lookup returns multiple matching profiles.
  • AWS Solution: Never guess which patient is on the line. When a database query returns an array length greater than 1, route the flow to a specialized Step-Up Authentication Module. Use a Get Customer Input block to prompt the caller for secondary validating variables: “I see multiple accounts listed under this phone number. Please enter or speak the 4-digit birth year for the person who needs care today.” Use that secondary variable to isolate the correct index profile before moving into the AI Core.

📋 Checklist for Developer Deployment Validation

Before publishing your IVR production system, ensure you have verified these five conditions:

  • Every single Error and No Match output node on the canvas is securely mapped to a fallback or queue.
  • The Lambda timeout property within the function console is configured to be less than 8 seconds to prevent unpredictable state drops.
  • DTMF (Keypad entry) is enabled as an active backup option inside the Lex bot configuration in case the caller’s voice environment is too noisy.
  • Sensitive Patient Health Information (PHI) elements are explicitly labeled as Sensitive Data inside Connect to obfuscate them from standard plain-text logging systems.
  • Amazon Poly Neural voice selections are locked across all modules to maintain a consistent persona throughout the call lifecycle.

If you want to prepare your system for deployment, let me know:

  • Do you want to see how to structure the EventBridge JSON payload to catch mid-call dropouts?
  • Would you like guidance on masking variables within CloudWatch Logs to maintain strict HIPAA compliance?

tell more about contact lens and customer profiles in awes connect

In Amazon Connect, Contact Lens and Customer Profiles act as the core data and intelligence layer. They transform your IVR from a standard phone routing script into a context-aware customer service ecosystem.

🔍 1. Amazon Connect Contact Lens (AI-Powered Analytics)

Contact Lens brings machine learning directly into your contact center, providing real-time speech analytics, sentiment tracking, and compliance redaction.

Key Features & Capabilities:

  • Real-Time Sentiment Analysis: Analyzes the caller’s tone, words, and pacing as they speak. It scores sentiment on a scale from -5 (Highly Distressed/Angry) to +5 (Highly Satisfied).
  • Supervisor Alerts: You can configure rules to instantly alert a floor supervisor if a patient’s sentiment score drops into a negative threshold or if a customer shouts a specific keyword (e.g., “lawsuit” or “malpractice”).
  • Automated Categorization: Automatically tags calls based on conversational cues. For example, if a patient says “billing issue” or “overcharged,” Contact Lens automatically labels the call category as Billing_Dispute without requiring manual agent input.
  • HIPAA-Compliant PII Redaction: Automatically detects and redacts sensitive data — such as Social Security Numbers, credit card details, and dates of birth — from both text transcripts and audio recordings before they are saved to your storage bucket.

🛠️ Contact Flow Integration Use Case:

You can read Contact Lens variables mid-call on your canvas using a Check Contact Attributes block. If a patient is interacting with your AI agent and Contact Lens detects a sentiment score of -4, you can design your flow to gracefully stop the automation and route the caller to an escalation agent with high priority.

👤 2. Amazon Connect Customer Profiles (Unified Data View)

Customer Profiles aggregates fragmented data from multiple external databases into a single, unified record. It maps phone numbers directly to patient identity records in real time.

Key Features & Capabilities:

  • Out-of-the-Box Integrations: It features native, pre-built connectors to pull customer data from major enterprise platforms like Salesforce, Zendesk, ServiceNow, and Amazon S3.
  • Identity Resolution: If a patient calls from a mobile number, emails from a personal account, and submits a help ticket via a web portal, Customer Profiles uses machine learning to match and merge those touchpoints into a single master profile.
  • Agent Workspace Interface: When an agent answers a call, the Customer Profiles interface opens automatically on their screen. The agent instantly sees the patient’s full name, contact information, open tickets, and recent touchpoints without needing to switch tabs or search manually.

🛠️ Contact Flow Integration Use Case:

Instead of forcing a caller to type out an account number, use the Customer Profiles block right at the beginning of your canvas. The block matches the incoming phone number, retrieves the patient’s record, and outputs variables like $.CustomerProfiles.FirstName. You can then pass this attribute directly into your greeting: "Hello John, thank you for calling..."

🔄 How They Work Together: A Real-Time Scenario

Combining these two features allows you to deliver highly personalized, proactive customer service:

[ Inbound Call ] ────► Matches Caller ID via CUSTOMER PROFILES ────► Identifies patient as "John Doe"
│
▼
[ Live Conversation ] ──► CONTACT LENS tracks real-time sentiment ──► Detects high distress (Score: -4)
│
▼
[ Intelligent Transfer ] ──► Connect routes call to High-Priority Queue with full context pop on screen
  • The Match: A customer calls your support line. Customer Profiles identifies them as a high-tier enterprise client based on their phone number and pulls up their open support history.
  • The Assessment: The customer is frustrated about a delayed delivery and expresses intense dissatisfaction. Contact Lens tracks the conversation in real time, flags the negative sentiment, and detects the keyword “cancel subscription”.
  • The Resolution: The system triggers an automated workflow, immediately transferring the caller to a senior customer retention agent. The agent’s screen displays the unified profile data alongside the live transcript of the call, allowing them to resolve the issue seamlessly.

Depending on your project’s technical goals, let me know:

  • Do you want to see how to structure a Contact Lens Rule inside AWS to trigger an escalation?
  • Would you like guidance on connecting an external data source (like Salesforce or an S3 bucket) into Customer Profiles?

Try without personalization

yes

Part 1: Configuring a Contact Lens Real-Time Escalation Rule

When Contact Lens executes real-time analysis, it does not directly move calls on the canvas. Instead, it flags the call with a category type and publishes a matching event schema out to Amazon EventBridge. [1, 2]

To configure a supervisor alert when a patient expresses severe dissatisfaction, execute this three-step orchestration pattern:

[ Real-Time Audio Stream ] ──► (Contact Lens Rules Matcher)
│
▼ (Category: Customer-sentiment-is-low)
[ Amazon EventBridge ]
│
▼ (Triggers Custom Pattern Rule)
[ Amazon SNS Topic ] ──► (Dispatches SMS / Email Alert to Supervisor)

Step 1: Create the Real-Time Rule in the Connect Admin Console

  • Log into your Amazon Connect Admin Console and click on Rules. [1]
  • Click Create a rule, and select Conversational analytics. [1]
  • Set the trigger condition:
  • Analysis type: Select Real-time analytics.
  • Condition: Select Sentiment — Time period. Set it to trigger if Customer sentiment is Negative for the past 5 seconds. [1, 2]
  • Set the Action:
  • Select Assign category and name it Customer-sentiment-is-low.
  • Check the box to Generate an Amazon EventBridge event. Click Save and Publish. [1, 2, 3, 4]

Step 2: Configure the Amazon EventBridge Event Pattern

To catch this live evaluation drop, log into your AWS Management Console, navigate to Amazon EventBridge, click Create rule, and paste this exact Custom Event Pattern payload: [1]

json

{
"source": ["aws.connect"],
"detail-type": [ "Contact Lens Realtime Rules Matched" ],
"detail": {
"ruleName": ["Customer-sentiment-is-low"]
}
}

Use code with caution.

Step 3: Map the Target Action Endpoint

Scroll down to the Select targets section of the EventBridge rule interface. Target an Amazon SNS Topic named Amazon_Connect_Supervisor_Alert. This topic instantly broadcasts an email or SMS notification out to your on-call supervisor's cellular device, attaching the live chat transcript link so they can intervene. [1, 2, 3]

Part 2: Connecting an External Amazon S3 Bucket to Customer Profiles

If you have a legacy database or an external customer registry exporting nightly data updates, you can use the pre-built Amazon S3 Connector to stream data directly into Amazon Connect Customer Profiles. [1, 2]

Step 1: Format the Ingestion CSV File

Your S3 extraction files must avoid complex nested formatting. Structure your file using standard column indicators matching basic attributes: [1]

csv

Attributes.AccountNumber,Attributes.FirstName,Attributes.LastName,Attributes.MobilePhone,Attributes.EmailAddress
ACC10029,Martha,Rivera,+15555551234,martha.rivera@example.com

Use code with caution.

Step 2: Establish the Object Type Mapping via the CLI

An Object Type Mapping tells Customer Profiles how to interpret raw columns from your CSV data schema and map them onto individual master records. Create a file named S3Mapping.json and deploy it using the AWS CLI: [1, 2, 3]

json

{
"DomainName": "Healthcare-Patients-Domain",
"ObjectTypeName": "S3PatientRecord",
"Description": "Nightly patient ingestion profile schema from hospital storage bucket.",
"AllowProfileCreation": true,
"SourceLastUpdatedTimestampFormat": "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'",
"Fields": {
"AccountNumber": { "Source": "_source.Attributes.AccountNumber", "Target": "_profile.AccountNumber" },
"FirstName": { "Source": "_source.Attributes.FirstName", "Target": "_profile.FirstName" },
"LastName": { "Source": "_source.Attributes.LastName", "Target": "_profile.LastName" },
"MobilePhone": { "Source": "_source.Attributes.MobilePhone", "Target": "_profile.PhoneNumber" },
"EmailAddress": { "Source": "_source.Attributes.EmailAddress", "Target": "_profile.Address.EmailAddress" }
},
"Keys": {
"_phone": [
{ "FieldNames": ["MobilePhone"] }
],
"_account": [
{ "FieldNames": ["AccountNumber"] }
]
}
}

Use code with caution.

  • CRITICAL INGESTION TIP: Ensure "AllowProfileCreation" is explicitly set to true. If set to false, the mapping will reject raw uploads that do not already match a pre-existing record, causing your data pipeline to fail silently. [1]

Run the following command in your terminal to initialize the mapping configuration: [1, 2]

bash

aws connectcustomerprofiles put-profile-object-type --cli-input-json file://S3Mapping.json --region us-east-1

Use code with caution.

Step 3: Link the Integration in the Connect Admin Dashboard

  • Open the Amazon Connect Console and select your instance.
  • Click Customer Profiles in the navigation panel.
  • Under Integrations, click Add Integration.
  • Select Amazon S3 from the application picker. Select the target bucket hosting your mock data CSV files.
  • Under Select Object Type, select the mapping configuration you just deployed (S3PatientRecord). Click Complete Integration. [1]

Customer Profiles will now scan this bucket directory every 15 minutes, automatically indexing records and preparing data variables for your IVR environment. [1, 2]

If you are preparing for a live integration review, let me know:

  • Would you like to review the step-by-step instructions to create an IAM Role and Policy that permits Amazon AppFlow to pull this S3 file securely?
  • Do you want to see how to structure the Customer Profiles block on your canvas to look up this specific S3PatientRecord schema mid-call?

Try without personalization

  • Amazon Web Services (AWS)
  • How to programmatically access Amazon Connect Rules using APIs | AWS Contact Center
  • Automate contact categorization, EventBridge events, email notifications, and task generation based on triggers like keywords, sen…
  • Amazon Web Services (AWS)
  • Building a real time customer sentiment email notification system using Contact Lens for Amazon Connect, Amazon EventBridge and Amazon Simple Notification System | AWS Contact Center
  • From the AWS Console navigate to “Amazon EventBridge” and select “Create rule” Scroll down to “Select targets” and select “SNS top…
  • Amazon AWS Documentation
  • Create conversational analytics rules using the Connect Customer admin website — Amazon Connect Customer
  • Create a rule, Conversational analytics, Add action, Save. Actions: Create Task, Send email or in-app notification, Generate Event…
  • Amazon Web Services (AWS)
  • Automate follow
  • 1. Navigate to the Amazon Connect admin console 2. Open Rules 3. Click Create a rule, Contact lens 4. Select A Contact Lens post-c…
  • Amazon Web Services (AWS)
  • How to use Amazon Connect Contact Lens to improve agent …
  • Conversational analytics enhances call recordings. Rules can also be used to trigger alerts for intervention in real-time.
  • Amazon Web Services (AWS)
  • Unify and organize customer information with Amazon …
  • Open the Amazon Connect console Select your Amazon Connect instance In the navigation pane, choose Customer Profiles For Integrati…
  • Amazon Web Services (AWS)
  • Amazon Connect Customer Profiles Connectors for Segment …
  • With just a few clicks, you can ingest data from third party applications to create unified customer profiles leveraging the pre-b…
  • Amazon AWS Documentation
  • Create and ingest customer data into Customer Profiles — Amazon Connect Customer
  • Define custom data via S3 and object type mappings. Upload separate S3 data files containing ProfileType, Create distinct object-t…
  • Amazon AWS Documentation
  • Create an object type mapping in Connect Customer …
  • An object type mapping tells Customer Profiles how to ingest a specific type of data from a source application — such as Salesforce,
  • Improve routing and self
  • Connect Customer Profile data object mapping to define how data from your data source (Amazon S3) should be mapped to your custome…
  • AWS re:Post
  • Unable to create Amazon connect customer profile through …
  • Set AllowProfileCreation to TRUE so it creates a profile when there’s no existing match. * You need at least one key defined.
  • Example: Programmatically integrate Amazon S3 with Connect Customer Customer Profiles — Amazon Connect Customer
  • Step 1 Create JSON file … including 15-minute scheduled TriggerConfig, Call PutIntegration API using aws customer-profiles put-int…

Show less

amazon Connect Streams API when used

The Amazon Connect Streams API is used when you need to integrate the Amazon Connect softphone interface (the Contact Control Panel, or CCP) directly into your own web applications.

Instead of forcing your customer support agents or clinical coordinators to use the standalone Amazon Connect browser tab, you embed the dialer directly into your primary web application — such as a custom CRM, an Electronic Health Record (EHR) interface (like Epic or Cerner), or a unified developer console.

🕒 When Exactly Do You Use It?

The Streams API acts as an event bridge between your custom application code and the core Amazon Connect WebRTC media streams.

┌────────────────────────────────────────────────────────┐
│ Your Custom Web Application Workspace (HTML / JS) │
│ │
│ ┌───────────────────────┐ ┌───────────────────────┐ │
│ │ Embedded CCP Core │ │ Custom EHR / CRM │ │
│ │ (<iframe>) │ │ Data Forms │ │
│ └───────────┬───────────┘ └───────────▲───────────┘ │
└──────────────│──────────────────────────│──────────────┘
▼ │
[ Streams API ] ───────────────────┘
Executes `connect.contact()` Hooks (Event Listeners)
│
▼ (Secure WebRTC Signaling)
┌────────────────────────────────────────────────────────┐
│ Amazon Connect Cloud Core │
└────────────────────────────────────────────────────────┘

Basic Code Initialization Example

The Streams API is a browser-side JavaScript library. Below is a minimal implementation blueprint demonstrating how to initialize the connection and set up an event listener that catches incoming calls:

html

<!DOCTYPE html>
<html>
<head>
<!-- Include the official Amazon Connect Streams API script from your hosting repository -->
<script src="amazon-connect-streams.js"></script>
</head>
<body>
<!-- Container where the actual Amazon Connect dialer will be injected -->
<div id="container-div" style="width: 320px; height: 480px;"></div>
<script type="text/javascript">
const ccpUrl = "https://connect.aws";
// 1. Initialize the embedded container interface
connect.core.initCCP(document.getElementById("container-div"), {
ccpUrl: ccpUrl,
loginPopup: true,
loginPopupAutoClose: true,
region: "us-east-1",
softphone: {
allowFramedSoftphone: true,
disableRingtone: false
}
});
// 2. Register event handlers to listen for incoming contact events
connect.contact(function(contact) {

// Listen for when the phone line actively rings for the agent
contact.onIncoming(function(incomingContact) {
console.log("Incoming call detected from customer line.");

# Fetch custom attributes passed from the Connect Contact Flow
let attributes = incomingContact.getAttributes();
let patientId = attributes.PatientID.value;

// EXECUTIVE ACTION: Execute your custom application screen-pop script
triggerApplicationScreenPop(patientId);
});
            // Listen for when the agent answers the connection
contact.onAccepted(function(acceptedContact) {
console.log("Agent answered the call. Connection established.");
});
});
function triggerApplicationScreenPop(id) {
// Logic to change the browser view or command your app to fetch patient data
console.log(`Commanding parent EHR window to load profile for Patient ID: ${id}`);
// window.location.href = `https://my-ehr-system.local{id}`;
}
</script>
</body>
</html>

SSML tags supported by Amazon Polly in Amazon Connect

Amazon Connect uses SSML (Speech Synthesis Markup Language) to control how Amazon Polly speaks IVR prompts — for example, pauses, pronunciation, speaking speed, and numbers.

AWS documents the following tags as supported by Amazon Connect.

Amazon Connect Customer

+1

1. Supported tags and their uses

SSML tag

Purpose

Example use in IVR

<speak>

Wraps the complete SSML prompt

Required outer tag

<break>

Adds a pause (up to 10 seconds)

Pause before a menu

<lang>

Specifies a language for part of the text

Speak a name using another language

<mark>

Adds a custom marker

Mark a position in speech metadata

<p>Adds paragraph-level pauses

Separate introduction from instructions

<phoneme>Specifies phonetic pronunciation

Pronounce a difficult name

<prosody> Adjusts speaking rate, volume, or pitch

Slow down important instructions

<s>

Separates sentences with pauses

Make menu instructions clearer

<say-as>

Controls how text is interpreted

Read digits individually or interpret dates

<sub>

Substitutes an alias for displayed text

Read an abbreviation as full words

<w>Specifies word pronunciation or meaning

Distinguish a word’s noun or verb pronunciation

<amazon:effect name="whispered"> Produces a whispering effect

A special whispered prompt

2. Examples you can use in Amazon Connect

Example A — Add a pause

<speak>
Thank you for calling customer service.
<break time="1s"/>
Please enter your claim number.
</speak>

Result: Polly pauses for one second between the greeting and the instruction.

Example B — Read digits individually

<speak>
Your verification code is
<say-as interpret-as="digits">583921</say-as>.
</speak>

Result: Polly reads the verification code digit by digit.

Example C — Pronounce an abbreviation

<speak>
Welcome to
<sub alias="Customer Service">CS</sub>.
</speak>

Result: Polly speaks “Customer Service” instead of “CS”.

Example D — Slow down the speech

<speak>
<prosody rate="slow">
Please listen carefully to the following options.
</prosody>
Press 1 for claims.
Press 2 for billing.
Press 3 to speak to an agent.
</speak>

Result: The introductory sentence is spoken slowly, while the menu is spoken at the normal rate.

Example E — Pronounce a difficult name

<speak>
Your assigned representative is
<phoneme alphabet="ipa" ph="ˈdʒɑːn">John</phoneme>.
</speak>

Result: Polly uses the specified phonetic pronunciation for “John”. The phonetic spelling should be selected for the intended name and accent.

3. How to enable SSML in Amazon Connect

Step 1: Open your contact flow

Go to Amazon Connect → Routing → Flows, and open the appropriate inbound contact flow.

Step 2: Add or edit a Play prompt block

Select the text-to-speech prompt option rather than using a prerecorded audio file.

Step 3: Choose SSML

Set Interpret as to SSML, then enter the text using the supported tags.

Step 4: Test the prompt

Test the live voice flow and verify pronunciation, pauses, and the selected voice. Unsupported tags in Connect are automatically ignored, so don’t assume that every tag supported by standalone Polly will work in Connect.

--

--