简体   繁体   English

如何让 ConfirmIntent 在 Amazon Lex 和 Lambda 上工作

[英]How to get ConfirmIntent to work on Amazon Lex and Lambda

I am trying to develop an IT chat bot to help people answer issues that they could fix on their own if they only had the correct information or steps.我正在尝试开发一个 IT 聊天机器人来帮助人们回答他们可以自己解决的问题,如果他们只有正确的信息或步骤。 I am using Amazon Lex as the bots infrastructure.我使用 Amazon Lex 作为机器人基础设施。 I have written the intents in the Lex console, and lambda functions for each intent to validate and fulfill the intent.我已经在 Lex 控制台中编写了意图,并为每个意图编写了 lambda 函数来验证和实现意图。 The issue I am running into is using confirmIntent in lambda. With confirmintent I want the user to be prompted with "Did this resolve your issue?"我遇到的问题是在 lambda 中使用 confirmIntent。使用 confirmintent 我希望提示用户“这是否解决了您的问题?” after the bot prints the steps and then based on if the user says Yes or No the bot responds.在机器人打印步骤后,然后根据用户说“是”或“否”机器人做出响应。 The issue I am running into is when I set it up like AWS documentation says to I get this error:我遇到的问题是当我像 AWS 文档所说的那样设置它时出现此错误:

[ERROR] Runtime.MarshalError: Unable to marshal response: Object of type function is not JSON serializable Traceback (most recent call last):

I am not sure what the error means and was needing some help to figure it out to fix my lambda functions so that the function works correctly.我不确定错误是什么意思,需要一些帮助来解决它以修复我的 lambda 函数,以便 function 正常工作。 below is the basic format of my code with just one intent for example下面是我的代码的基本格式,例如只有一个意图

def get_slots(intent_request):
    return intent_request['currentIntent']['slots']

def rreplace(s, old, new, occurrence):
    li = s.rsplit(old, occurrence)
    return new.join(li)

def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):
    return {
        'sessionAttributes': session_attributes,
        'dialogAction': {
            'type': 'ElicitSlot',
            'intentName': intent_name,
            'slots': slots,
            'slotToElicit': slot_to_elicit,
            'message': message
        }
    }

def close(session_attributes, fulfillment_state, message):
    response = {
        'sessionAttributes': session_attributes,
        'dialogAction': {
            'type': 'Close',
            'fulfillmentState': fulfillment_state,
            'message': message
        }
    }

    return response

def delegate(session_attributes, slots):
    print("This is sessionAttributes value in delegate", session_attributes)
    return {
        'sessionAttributes': session_attributes,
        'dialogAction': {
            'type': 'Delegate',
            'slots': slots
        }
    }

def parse_int(n):
    try:
        return int(n)
    except ValueError:
        return float('nan')

def build_validation_result(is_valid, violated_slot, message_content):
    print("Inside build validation function")
    if message_content is None:
        print("inside if statment in validation function above first return")
        return {
            "isValid": is_valid,
            "violatedSlot": violated_slot,
        }
        print("inside if statment in validation function above second return")

    return {
        'isValid': is_valid,
        'violatedSlot': violated_slot,
        'message': {'contentType': 'PlainText', 'content': message_content}
    }

def confirm_intent(session_attributes, intent_name, slots, message):
    print('Made it inside confirm_intent')
    return {
        'sessionAttributes': session_attributes,
        'dialogAction': {
            'type': 'ConfirmIntent',
            'intentName': intent_name,
            'slots': slots,
            'message': {
                'contentType': 'PlainText',
                'content': "test"
            }
        }
    }

def password(intent_request):
    source = intent_request['invocationSource']
    output_session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {}
    slots = intent_request['currentIntent']['slots']
    # whatever you want to do
    if source == 'DialogCodeHook':
        slot = get_slots(intent_request)
        passwordType = validate_intro_request(slots)
        if not passwordType['isValid']:
            slot[passwordType['violatedSlot']] = None
            
            return elicit_slot(intent_request['sessionAttributes'],
                               intent_request['currentIntent']['name'],
                               slot,
                               passwordType['violatedSlot'],
                               passwordType['message'])
        return delegate(output_session_attributes, slots)

    if source == 'FulfillmentCodeHook':
        # action fulfillment code
        msg = "did that resolve the issue"
        return confirm_intent(output_session_attributes, 'PasswordReset', slots, msg)
        
def validate_password_request(password):
    issues = ['need to reset my password']
    if password is not None and password.lower() not in issues:
        return build_validation_result(False,'password','We do not understand your {}, please try to reword your issue for password information'.format(passwords))

def dispatch(intent_request):
    logger.debug('dispatch userId={}, intentName={}'.format(intent_request['userId'], intent_request['currentIntent']['name']))
    

    intent_name = intent_request['currentIntent']['name']

    # Dispatch to your bot's intent handlers
    if intent_name == 'PasswordReset':
        return i_password(intent_request)
    raise Exception('Intent with name ' + intent_name + ' not supported')

def lambda_handler(event, context):
    """
    Route the incoming request based on intent.
    The JSON body of the request is provided in the event slot.
    """
    # By default, treat the user request as coming from the Pacific timezone.
    os.environ['TZ'] = 'America/Los_Angeles'
    time.tzset()
    logger.info('Received event: {}'.format(event))

    return dispatch(event)```

In your code, the below line is incorrect as the message is an object of content type and content.在您的代码中,以下行不正确,因为消息是 object 的内容类型和内容。 You're passing only string it should map to contents.您只将字符串 map 传递给内容。

This may cause the Jain parser error at lex,这可能会导致 lex 处的 Jain 解析器错误,

msg = "did that resolve the issue"
        return confirm_intent(output_session_attributes, 'PasswordReset', slots, msg)

msg variable should map to content property of message in confirm intent function. msg变量应为 map 以确认意图 function 中消息的内容属性。

Hope this resolves your issues.希望这可以解决您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM