Voiced by Amazon Polly |
Overview
In today’s fast-paced digital landscape, real-time customer engagement is essential. This document provides a detailed guide on integrating an AI-powered Amazon Bedrock agent with WhatsApp using Meta’s WhatsApp Business API Cloud and AWS Lambda. By utilizing a serverless architecture, this solution simplifies infrastructure management while leveraging generative AI to create an intelligent chatbot capable of understanding and responding dynamically.
Pioneers in Cloud Consulting & Migration Services
- Reduced infrastructural costs
- Accelerated application deployment
Architecture Overview
Our solution employs a modern, serverless architecture:
- Meta WhatsApp Business API Cloud: Sends and receives WhatsApp messages.
- AWS Lambda: Processes incoming webhook events.
- Amazon Bedrock Agent: Generates smart, AI-driven responses.
- Amazon DynamoDB: Manages session data and conversation context.
This integration allows your chatbot to handle messages, maintain session integrity, and respond intelligently without traditional server management.
Prerequisites
Before starting, ensure you have:
- A Meta developer account with an app created in the Meta Developer Console.
- Access to the WhatsApp Business API Cloud.
- An AWS account with permissions to create and deploy AWS Lambda functions.
- Basic familiarity with Python (or Node.js) and RESTful API concepts.
Setting Up the Meta Developer Console
- Create an application: Create a new app in the Meta Developer Console.
- Attach the WhatsApp Product: In your app, navigate to the WhatsApp section and click “Getting Started” to attach the WhatsApp product.
- Test the Setup: Use the provided test number from Meta to send a default template message and ensure your configuration is correct.
- Add the Function: Proceed to add the necessary functions for your integration.
Building the Webhook with AWS Lambda
Our webhook (an AWS Lambda function) bridges WhatsApp and the Amazon Bedrock agent. Let’s review the key code components.
- Extracting Session Details
This function retrieves the user’s phone number and current timestamp, which are crucial for session management.
1 2 3 4 5 6 |
def get_session_details(event): phone_number = event["entry"][0]["changes"][0]["value"]["contacts"][0]["wa_id"] ist = pytz.timezone("Asia/Kolkata") ist_time = datetime.now(ist) ist_timestamp = int(ist_time.timestamp()) return [phone_number, ist_timestamp] |
- Managing Conversation Sessions
This function checks for an active session in Amazon DynamoDB (within a 5-minute window) and creates a new session if necessary.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
def is_session_active(phone_number, current_timestamp): dynamodb = boto3.resource('dynamodb') table = dynamodb.Table("Your_DynamoDB_Table_Name") ist = pytz.timezone("Asia/Kolkata") ist_time = datetime.fromtimestamp(current_timestamp, ist) five_minutes_ago = ist_time - timedelta(minutes=5) five_minutes_later = ist_time + timedelta(minutes=5) response = table.scan( FilterExpression="#pn = :phone_number AND #ts BETWEEN :start_time AND :end_time", ExpressionAttributeNames={"#pn": "phone_number", "#ts": "timestamp"}, ExpressionAttributeValues={ ":phone_number": phone_number, ":start_time": int(five_minutes_ago.timestamp()), ":end_time": int(five_minutes_later.timestamp()) } ) if response['Items']: existing_session = response['Items'][0] return existing_session["sessionId"], True new_session_id = f"{phone_number}{current_timestamp}" table.put_item( Item={ "sessionId": new_session_id, "phone_number": phone_number, "timestamp": current_timestamp, } ) return new_session_id, False |
- Handling Incoming Messages and Invoking the Amazon Bedrock Agent
The AWS Lambda handler processes incoming webhook events. It verifies the webhook, extracts message details, checks for duplicate messages, logs the conversation, and invokes the Amazon Bedrock agent for a response.
Segment 1: Webhook Verification
1 2 |
def lambda_handler(event, context): print(event) |
# Verify webhook using query parameters.
1 2 3 4 5 6 7 8 9 10 11 12 |
if "queryStringParameters" in event: query_params = event["queryStringParameters"] verify_token = os.getenv("VERIFY_TOKEN") mode = query_params.get("hub.mode") token = query_params.get("hub.verify_token") challenge = query_params.get("hub.challenge") if mode and token and mode == "subscribe" and token == verify_token: print("WEBHOOK_VERIFIED") return {"statusCode": 200, "body": challenge} else: return {"statusCode": 403} |
#### Segment 2: Parsing the Request Body
1 2 3 4 5 6 7 |
token = os.getenv("WHATSAPP_TOKEN") try: body = json.loads(event.get("body", "{}")) if "object" in body: entry = body.get("entry", [{}])[0] changes = entry.get("changes", [{}])[0] value = changes.get("value", {}) |
#### Segment 3: Extracting Message Details
1 2 3 4 5 |
if "messages" in value: message = value["messages"][0] phone_number_id = value.get("metadata", {}).get("phone_number_id", "") from_number = message.get("from", "") msg_body = message.get("text", {}).get("body", "").strip() |
#### Segment 4: Session Management and Duplicate Check
1 2 3 4 5 6 |
details = get_session_details(body) phone_number, current_time = details[0], details[1] session_id, is_active = is_session_active(phone_number, current_time) if is_last_client_message_duplicate(session_id, msg_body): return {"statusCode": 200, "body": "Acknowledged duplicate message"} |
#### Segment 5: Logging and Invoking the Amazon Bedrock Agent
1 2 3 |
PutRecord(session_id, "\nClient:" + msg_body + "\n", "") agent_response = invokeagent(session_id, msg_body)['reply'] PutRecord(session_id, "", "Agent:" + agent_response) |
#### Segment 6: Sending the Response
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
response = requests.post( f"https://graph.facebook.com/v12.0/{phone_number_id}/messages", headers={"Content-Type": "application/json"}, json={ "messaging_product": "whatsapp", "to": from_number, "text": {"body": agent_response} }, params={"access_token": token} ) if response.status_code != 200: print("WhatsApp API Error:", response.status_code, response.text) return {"statusCode": 200, "body": "Message processed successfully"} else: print("Unsupported event structure:", json.dumps(value)) return {"statusCode": 200, "body": "Acknowledged unknown event"} except Exception as e: print("Unhandled Exception:", e) return {"statusCode": 500, "body": f"Internal server error: {str(e)}"} return {"statusCode": 400, "body": "Unexpected payload structure"} |
Deploying Your AWS Lambda Function
- Package Your Code: Clone your repository, install dependencies, and compress your project files into a .zip file.
- Create AWS Lambda Function: In the AWS Lambda console, choose “Create function” and select “Author from scratch.” Configure your function with:
- Runtime: Python 3.x (or your chosen runtime)
- Timeout: At least 30 seconds
- Environment Variables:
- VERIFY_TOKEN: e.g., “VERIFY”
- WHATSAPP_TOKEN: Your Meta WhatsApp token
- Upload Your Code: In the AWS Lambda console, upload your .zip file.
- Set Up the Function URL: Enable the function URL (authentication set to “None”) and configure your Meta Developer Console’s webhook settings to point to your AWS Lambda URL with the /webhook endpoint.
Testing the Integration
- Send a Test Message: Use the Meta Developer Console or send a message directly from WhatsApp.
- Verify Processing: Ensure the AWS Lambda function processes the message, invokes the Bedrock agent, and returns the correct response.
- Monitor Logs: Use Amazon CloudWatch to troubleshoot session management or API call issues.
Conclusion
Whether automating customer service or creating interactive applications, this integration offers a flexible platform to get you started.
Drop a query if you have any questions regarding Amazon Bedrock and we will get back to you quickly.
Empowering organizations to become ‘data driven’ enterprises with our Cloud experts.
- Reduced infrastructure costs
- Timely data-driven decisions
About CloudThat
CloudThat is an award-winning company and the first in India to offer cloud training and consulting services worldwide. As a Microsoft Solutions Partner, AWS Advanced Tier Training Partner, and Google Cloud Platform Partner, CloudThat has empowered over 850,000 professionals through 600+ cloud certifications winning global recognition for its training excellence including 20 MCT Trainers in Microsoft’s Global Top 100 and an impressive 12 awards in the last 8 years. CloudThat specializes in Cloud Migration, Data Platforms, DevOps, IoT, and cutting-edge technologies like Gen AI & AI/ML. It has delivered over 500 consulting projects for 250+ organizations in 30+ countries as it continues to empower professionals and enterprises to thrive in the digital-first world.
FAQs
1. Can I integrate with multiple WhatsApp numbers?
ANS: – Yes, but you must configure the Meta Developer Console for each number and modify your AWS Lambda function to handle different numbers.
2. How do I handle media messages like images and audio?
ANS: – Extend your webhook logic to process media URLs received from WhatsApp and store them in Amazon S3 or another storage service.
WRITTEN BY Shantanu Singh
Shantanu Singh works as a Research Associate at CloudThat. His expertise lies in Data Analytics. Shantanu's passion for technology has driven him to pursue data science as his career path. Shantanu enjoys reading about new technologies to develop his interpersonal skills and knowledge. He is very keen to learn new technology. His dedication to work and love for technology make him a valuable asset.
Comments