Building an Automated Email Response System with Amazon Connect and Bedrock Knowledge Base
A single pane for your customer service agents to receive, prioritize, assign, respond and report on your end-user emails communications.
Anonymous User
Amazon Employee
Published Jun 3, 2025
In today's customer service landscape, efficiently handling email inquiries is crucial for maintaining customer satisfaction while optimizing agent productivity. By leveraging Amazon Connect's email channel capabilities alongside Amazon Bedrock's knowledge base and AI capabilities, organizations can create intelligent systems that automatically respond to customer emails when appropriate, while seamlessly routing more complex inquiries to human agents.
This article provides a comprehensive guide to building an automated email response system that:
- Receives incoming emails through Amazon Connect
- Analyzes the content using Amazon Bedrock
- Generates appropriate responses using a knowledge base when confidence is high
- Routes complex inquiries to human agents when necessary
By the end of this tutorial, you'll have a fully functional system that can significantly reduce response times and free up your agents to handle more complex customer interactions.
Before diving into the implementation details, let's understand the high-level architecture of our solution:
- Email Reception: Amazon Connect receives incoming emails through its email channel
- Content Extraction: A Lambda function extracts the email content and any attachments
- Intent Analysis: Amazon Bedrock analyzes the email to determine intent and extract key information
- Knowledge Base Query: The system queries an Amazon Bedrock knowledge base with the customer's question
- Response Generation: If the confidence score is high enough, an automated response is generated
- Routing Logic: Emails requiring human intervention are routed to appropriate agent queues
- Response Delivery: The system delivers either the automated response or routes to an agent
Before starting this implementation, ensure you have:
- An AWS account with appropriate permissions
- Amazon Connect instance set up
- Amazon Bedrock access enabled in your AWS account
- A knowledge base created in Amazon Bedrock with relevant content
- Basic understanding of AWS services, particularly Lambda, DynamoDB, and IAM
First, let's set up the email channel in your Amazon Connect instance:
- Navigate to Amazon Connect: Open the AWS Management Console and go to Amazon Connect
- Select your instance: Click on your Amazon Connect instance
- Access Channels: In the left navigation pane, select "Channels"
- Enable Email: Click on "Email" and then "Enable email communications"
- Configure Email Domain:
- You can use an Amazon SES verified domain or create a new one
- Follow the verification process if using a new domain
- Configure SPF and DKIM records for your domain
- Create Email Flow: Set up an email flow that will handle incoming emails
- Go to "Routing" > "Contact flows"
- Create a new flow or modify an existing one to handle email contacts
Now, let's create a contact flow that will process incoming emails:
- Create a New Flow: In Amazon Connect, go to "Routing" > "Contact flows" and create a new flow
- Add Initial Blocks:
- Start with a "Set contact attributes" block to store email metadata
- Add a "Check contact attributes" block to verify it's an email contact
- Add Lambda Integration
- Add an "Invoke AWS Lambda function" block
- Configure it to call our email processing Lambda (we'll create this in the next step)
- Set the function input parameters to include the contact attributes and a "callType" parameter with value "pass1"
- Add Conditional Routing:
- Add a "Check contact attributes" block after the Lambda function
- Create a branch based on the "InferenceScore" attribute returned by Lambda
- If score > 80%, route to automated response
- If score < 80%, route to agent queue
- Configure Automated Response:
- For high confidence responses, add a "Send message" block
- Use the "ResponseSubject" and "ResponseBody" attributes from Lambda for the email reply
- Add a "Disconnect / hang up" block after sending the message
- Configure Agent Routing:
- For low confidence responses, add a "Set working queue" block
- Add a "Transfer to queue" block to route the contact to agents
- Configure appropriate queue settings and priorities
- Save and Publish: Save your contact flow and publish it to make it active
Your contact flow should look something like this:
Now, let's implement the Lambda function that will process incoming emails and interact with Amazon Bedrock. We'll dive deep into the implementation details:
- Create a Lambda Function:
- Go to AWS Lambda in the console
- Click "Create function"
- Choose "Author from scratch"
- Name your function (e.g., "EmailProcessingFunction")
- Select Python 3.9 or later as the runtime
- Create or assign an appropriate execution role with permissions for:
- Amazon Connect
- Amazon S3
- Amazon Bedrock
- Amazon DynamoDB
- Amazon Comprehend
- CloudWatch Logs
- Configure Environment Variables:
- INSTANCE_NAME: Your Amazon Connect instance name
- CONNECT_BUCKET: S3 bucket for Connect email attachments
- DYNAMO_TABLE_NAME: DynamoDB table to store responses
- ENABLE_LOGGING: Set to "true" for detailed logging
- Create DynamoDB Table:
- Go to DynamoDB in the AWS console
- Create a new table with "contactid" as the partition key
- Enable point-in-time recovery for data protection
Let's break down the Lambda function code into key components:
This is one of the most critical parts of the function, as it handles the complex task of extracting email content from Amazon Connect events:
This function handles the complex task of extracting email content from Amazon Connect events. It:
- Tries to find the email reference in the event data
- Falls back to using the Connect API if needed
- Downloads the email content from the provided URL
- Processes the content to extract the clean text
These functions handle cleaning up the email content by removing HTML tags and normalizing whitespace.
This function uses Amazon Comprehend to detect the language of the email, which can be useful for multilingual support.
This function calls Amazon Bedrock to analyze the email content, using a carefully crafted prompt to extract intents, PII, and the user's question.
The most critical part of our solution is querying the Bedrock Knowledge Base to generate a response. Let's examine this in detail:
The call_Knowledgebase function is the core of our knowledge base integration:
This function:
- Takes a query and knowledge base ID as input
- Calls the Bedrock Agent Runtime API to retrieve relevant information from the knowledge base
- Formats the retrieved content for the model
- Generates a response using the Bedrock model with the retrieved context
- Returns the response along with metadata about the sources
This function formats the prompt for the Bedrock model, including the retrieved content from the knowledge base as context.
This function calls the Bedrock model with the prepared prompt and returns the generated response.
To maintain a record of responses and enable follow-up interactions, we store the results in DynamoDB:
This function saves the knowledge base response, query, and other metadata to DynamoDB for future reference.
To provide accurate responses, we need to set up and populate a knowledge base in Amazon Bedrock:
- Create Knowledge Base:
- Go to Amazon Bedrock in the AWS console
- Navigate to "Knowledge bases"
- Click "Create knowledge base"
- Provide a name and description
- Configure Data Source:
- Choose your data source type (S3, SharePoint, etc.)
- For S3, specify the bucket containing your knowledge documents
- Configure parsing options based on your document formats
- Configure Vector Store:
- Select the embedding model (e.g., Amazon Titan Embeddings)
- Configure chunking settings for optimal retrieval:
- Chunk size: 300-500 tokens for balanced context
- Overlap: 20-50 tokens to maintain context across chunks
- Configure Retrieval Settings:
- Set the maximum number of results to return (5 is a good starting point)
- Configure filtering options if needed
- Review and Create:
- Review your settings
- Create the knowledge base
- Update Lambda Configuration
- Copy your knowledge base ID
- Update the knowledgeBaseId parameter in your Lambda function
For optimal results, prepare your knowledge base content with these best practices:
- Document Structure:
- Use clear headings and subheadings
- Include a table of contents for longer documents
- Use consistent formatting
- Content Quality
- Ensure information is accurate and up-to-date
- Use clear, concise language
- Include common questions and their answers
- Metadata:
- Add relevant metadata to documents (tags, categories)
- Include document titles that reflect content
- Consider adding version information
- File Formats:
- Use PDF, HTML, or Markdown for structured content
- Ensure text is extractable (not images of text)
After setting up all components, it's time to test and optimize your system:
- Send Test Emails:
- Send test emails to your configured email address
- Monitor the contact flow execution in Amazon Connect
- Check the Lambda CloudWatch logs for detailed processing information
- Verify that the email content is correctly extracted and analyzed
- Review Automated Responses:
- Evaluate the quality of automated responses
- Check if the confidence scoring is appropriate
- Adjust the threshold in your contact flow if needed (80% is a starting point)
- Look for any formatting issues in the responses
- Monitor Agent Queue:
- Check if complex inquiries are correctly routed to agents
- Gather feedback from agents on the quality of routing
- Analyze which types of emails are being routed to agents vs. automated
- Optimize Knowledge Base:
- Add more content to your knowledge base for better coverage
- Refine existing content based on common questions
- Consider adding synonyms and alternative phrasings
- Review the confidence scores and adjust content accordingly
- Adjust Prompts:
- Fine-tune the prompts sent to Bedrock for better analysis
- Experiment with different instruction formats
- Adjust the system prompt for the knowledge base query
Once your basic system is working, consider these enhancements:
Extend your system to handle emails in multiple languages:
Implementation details:
- Use Amazon Comprehend to detect the language
- Use Amazon Translate to translate non-English content
- Process the translated content with your existing pipeline
- Translate the response back to the original language
- Update your contact flow to handle language-specific routing
Enhance your system to process email attachments:
For text-based attachments like PDFs, you can extract the content and include it in your analysis:
Add sentiment analysis to prioritize urgent or negative emails:
This allows you to:
- Prioritize negative emails for faster agent response
- Track sentiment trends over time
- Adjust automated responses based on sentiment
- Route highly negative emails to specialized agents
Create dynamic response templates that can be customized based on the query:
Templates can include:
- Appropriate greetings based on time of day
- Company-specific formatting and signatures
- Conditional sections based on the query type
- Links to relevant resources
To continuously improve your system, implement comprehensive monitoring:
- Create CloudWatch Dashboards:
- Track email volume by time of day/week
- Monitor automated response rate vs. agent handling
- Track confidence scores and their distribution
- Measure response times for automated vs. agent responses
- Set Up Alerts:
- Configure alerts for unusual patterns
- Get notified of sustained low confidence scores
- Monitor for increased error rates
- Set up alerts for high-volume periods
- Implement Feedback Loop:
- Add a mechanism for agents to flag incorrect automated responses
- Use this feedback to improve your knowledge base
- Periodically review and update your content
- Track common failure patterns
- Performance Metrics:
- Average handling time for automated responses
- Percentage of emails handled automatically
- Customer satisfaction with automated responses
- Knowledge base coverage (percentage of questions answered)
When implementing this solution, consider these security best practices:
- PII Handling:
- Implement proper redaction of PII in logs
- Ensure DynamoDB encryption at rest
- Set up appropriate IAM permissions
- Consider implementing tokenization for sensitive data
- Data Retention:
- Implement appropriate retention policies for emails and responses
- Set up lifecycle policies for S3 objects
- Configure TTL for DynamoDB items
- Ensure compliance with relevant regulations
- Access Controls:
- Implement least privilege access for all components
- Use IAM roles with specific permissions
- Set up CloudTrail logging for all API calls
- Regularly review access patterns
- Encryption:
- Ensure encryption in transit for all communications
- Implement encryption at rest for all data stores
- Use KMS for key management
- Regularly rotate encryption keys
By implementing this automated email response system with Amazon Connect and Amazon Bedrock, you've created a powerful solution that can significantly improve your customer service operations. The system intelligently handles routine inquiries automatically while ensuring complex questions receive the human touch they require.
This approach offers several key benefits:
- Reduced response times for common questions
- Consistent answers based on your knowledge base
- More efficient use of agent time
- Scalable handling of email volume
- Data-driven insights into customer inquiries
As you continue to refine your knowledge base and optimize your prompts, the system will become increasingly effective at handling a wider range of customer inquiries, further improving your operational efficiency and customer satisfaction.
- [Amazon Connect Documentation](https://docs.aws.amazon.com/connect/)
- [Amazon Bedrock Knowledge Base Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/knowledge-base.html)
- [Lambda Function Best Practices](https://docs.aws.amazon.com/lambda/latest/dg/best-practices.html)
- [Amazon Comprehend for Sentiment Analysis](https://docs.aws.amazon.com/comprehend/latest/dg/how-sentiment.html)
- [Amazon Bedrock Prompt Engineering Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/prompt-engineering.html)
- [Amazon Connect Email Channel Setup](https://docs.aws.amazon.com/connect/latest/adminguide/email.html)
Any opinions in this post are those of the individual author and may not reflect the opinions of AWS.