How to create a fallback intent in Amazon Lex or call a Lamda when error is triggered?

1.3k views Asked by At

I have a small bot on amazon lex, I am unable to figure out a way to define a default intent or a fallback intent.

1

There are 1 answers

0
sid8491 On

As of now, Amazon Lex does not support any fallback intent or default intent. However I have found a workaround. Here's what I did.

Setup an API Gateway and Lambda function in between your chat-client and the Lex.

enter image description here

Your chat-client will send request to API Gateway, API Gateway will forward this to Lambda function and Lambda function will forward the request to Lex (Lex will have one more lambda function). While returning the response from Lex, you can check in the Lambda function if it's an error message and trigger some action.

In the Lambda function we can use something like this:

import logging
import boto3

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

client_run = boto3.client('lex-runtime')
client_model = boto3.client('lex-models')

def lambda_handler(event, context):
    response = client_run.post_text(
        botName='name_of_your_bot',
        botAlias='alias_of_your_bot',
        userId='some_id',
        sessionAttributes={
            'key1': 'value1'
        },
        inputText=event['user_query']
    )
    bot_details = client_model.get_bot(
    name='name_of_your_bot',
    versionOrAlias='$LATEST'
    )
    for content in bot_details['clarificationPrompt']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    for content in bot_details['abortStatement']['messages']:
        if response["message"] == content['content']:
            return error_handling_method(event)
    return response["message"]

Hope it helps.