3

I want to handle error messages dynamically and not rely on what we declared in the Lex dashboard. However when I tried to type a wrong message it will immediately trigger the default error message. When I check the lambda logs using Serverless the lambda function was not executed.

See logs:

enter image description here

There was no new entry when I typed in "can you do this". I was expecting that the lambda function would execute since I added some console.log to check out the event data.

Is it even possible?

jhnferraris
  • 1,361
  • 1
  • 12
  • 34

2 Answers2

4

You can handle these dynamically but for that you need to 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, then to Lambda function and then 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.

sid8491
  • 6,622
  • 6
  • 38
  • 64
3

The Lambda function will only be called when an Intent has been matched.

The "Sorry, can you please repeat that?" (or whatever else you have specified in the Error Handling section of the Lex dashboard) is returned when the input text doesn't match an Intent, independent of your Lambda function.

You can have validation code in your Lambda - but again, this will only be called if an Intent is matched to begin with.

One approach is to have extra Intents to handle utterances your users may say that fall outside of the scope of the chatbot e.g. "Who are you", "what's your name", "Do bots dream of bot sheep", whatever. The list of sample utterances for these extra Intents can be updated as more users test / use your bot.

AndyOS
  • 3,607
  • 3
  • 23
  • 31