用aws搭建一个基于ai的自动邮件回复系统
这是一个基于aws的ai自动回复email的尝试。用户验证邮箱之后,aws ses得到授权可以代替用户接收&发送邮件。aws ses在接收邮件的时候触发lambda。lambda提取邮件的sender,topic和content。调取open ai的api生成回复。然后lambda调取ses发送邮件给sender。
产品需求
functional requirements
这个系统应该实现以下功能:
-
识别incoming email的意图,过滤掉广告和营销邮件
-
收到客户发来的问询邮件,这类如果有明确的指示直接回复
-
收到没有明确意图识别的邮件,转发给我的个人邮箱做判断。
performance requirements
-
系统可以在几秒钟内做出自动判断。
-
价格应该控制在1美元之内。
aws ses接收邮件的设置
-
Go to AWS SES in your Region. In my case, it is us-west-2.
-
Under Configuration -> Email Receiving, create a rule set.
-
When creating a rule set, add Recipient condition as your (business) email address. This email address will receive and automatically reply messages using openAI.
-
Next, in the Add actions section, add Publish to Amazon SNS topic. Create a SNS topic that listens to email receive events. Use Base64 encoding.
-
Go to AWS SNS. Select the SNS topic you just created. Create susbcription for your SNS topic. Select AWS Lambda for the protocol.
-
Go to AWS Lambda. Make sure your newly created Lambda listens to the newly created SNS topic. Also, make sure the SNS topic has permission to invoke Lambda.
lambda处理incoming邮件
Write a simple code snippet that extracts incoming email content.
def lambda_handler(event, context):
print("Received the following message.")
if 'Records' in event:
# this is a SNS message
for record in event['Records']:
sns_body = record['Sns']
message_body = json.loads(sns_body['Message'])
encoded_email_content = message_body['content']
decoded_email_content = decode_base64(encoded_email_content)
plain_text = read_text_plain(decoded_email_content)
print(plain_text)
email_subject = message_body['mail']['commonHeaders']['subject']
print(email_subject)
email_sender = message_body['mail']['source']
print(email_sender)
open ai的设计和整合
首先需要一个open ai的key,这个怎么获取不赘述了。
在aws lambda里加入open ai的layer,并且把lambda中获取的email content和subject feed到open ai里面做邮件意图识别,用open ai生成回复邮件。
我在这里省略了openai的prompt等信息。将来我会把github发在这里。
result = classify_and_reply_email(plain_text, email_subject)
if not result['reply_needed']:
print("Do not reply.")
return
lambda发送回复邮件
def send_email(sender, recipient, subject, body_text, body_html):
# Create a new SES client
ses_client = boto3.client('ses', region_name="us-west-2")
# Try to send the email
try:
# Send the email using SES
response = ses_client.send_email(
Source=sender,
Destination={
'ToAddresses': [
recipient,
],
},
Message={
'Subject': {
'Data': subject,
'Charset': 'UTF-8'
},
'Body': {
'Text': {
'Data': body_text,
'Charset': 'UTF-8'
},
'Html': {
'Data': body_html,
'Charset': 'UTF-8'
}
}
}
)
except ClientError as e:
print(f"Error: {e.response['Error']['Message']}")
return False
except NoCredentialsError:
print("AWS credentials not available.")
return False
print(f"Email sent! Message ID: {response['MessageId']}")
return True