0

我必须将 Amazon lex 与 Amazon lambda 集成。我遇到了一个问题。我是新手,所以请帮助我。我想申请使用 Lex 的产品。“我在哪里可以找到肉”和肉将被存储到插槽'SearchProduct' 然后它将在数据库中搜索并通过 lex 回复。就像“我在 4 号过道里找到了肉”

在这里,我可以通过扫描 dynamodb 获得 Aisle no 4 的值,但我无法发送响应。

 'use strict';

const AWS = require('aws-sdk');
const docClient = new AWS.DynamoDB.DocumentClient({ region: "us-east-1" });
var reply = ' ';


// --------------- Helpers to build responses which match the structure of the necessary dialog actions -----------------------

function elicitSlot(sessionAttributes, intentName, slots, slotToElicit, message, responseCard) {
    return {
        sessionAttributes,
        dialogAction: {
            type: 'ElicitSlot',
            intentName,
            slots,
            slotToElicit,
            message,
            responseCard,
        },
    };
}

function close(sessionAttributes, fulfillmentState, message, responseCard) {
    return {
        sessionAttributes,
        dialogAction: {
            type: 'Close',
            fulfillmentState,
            message,
            responseCard,
        },
    };
}

function delegate(sessionAttributes, slots) {
    return {
        sessionAttributes,
        dialogAction: {
            type: 'Delegate',
            slots,
        },
    };
}



// ---------------- Helper Functions --------------------------------------------------

// build a message for Lex responses
function buildMessage(messageContent) {
    return {
        contentType: 'PlainText',
        content: messageContent,
    };
}



// --------------- Functions that control the skill's behavior -----------------------

/**
 * Performs dialog management and fulfillment for ordering a beverage.
 * (we only support ordering a mocha for now)
 */
function ItemSearch(intentRequest, callback) {

    const outputSessionAttributes = intentRequest.sessionAttributes;
    const source = intentRequest.invocationSource;

    if (source === 'FulfillmentCodeHook') {
        const slots = intentRequest.currentIntent.slots;
        const requestProductName = (slots.SearchProduct ? slots.SearchProduct : null);

        var scanningParameters = {
            TableName: "my table name",
            ProjectionExpression: "#pro, Aisle",
            FilterExpression: "contains (#pro, :productname)",
            ExpressionAttributeNames: {
                "#pro": "ProductName",
            },
            ExpressionAttributeValues: {
                ":productname": requestProductName
            }
        };

        docClient.scan(scanningParameters, function(err, data) {
            if (err) {

                callback(close(outputSessionAttributes, 'Fulfilled', { contentType: 'PlainText', content: 'not found' }));
            }
            else {
                console.log(data);
                if (data.Count == 0) {
                    reply = 'not found';
                    callback(close(outputSessionAttributes, 'Fulfilled', { contentType: 'PlainText', content: 'not found' }));
                }
                else {
                    reply = requestProductName + ' can be found in Aisle No: ' + data.Items[0].Aisle;
                    callback(close(outputSessionAttributes, 'Fulfilled', { contentType: 'PlainText', content: requestProductName + ' can be found in Aisle No: ' + data.Items[0].Aisle }));

                }
            }
        });
    }

    callback(close(outputSessionAttributes, 'Fulfilled', {
        contentType: 'PlainText',
        content: `Thanks for using CoffeeBot! `  // i want the reply from the search here but i always end up with null
    }));
}

// --------------- Intents -----------------------

/**
 * Called when the user specifies an intent for this skill.
 */
function dispatch(intentRequest, callback) {

    console.log(`dispatch userId=${intentRequest.userId}, intent=${intentRequest.currentIntent.name}`);

    const name = intentRequest.currentIntent.name;

    // dispatch to the intent handlers
    if (name.startsWith('Product')) {
        return ItemSearch(intentRequest, callback);
    }
    throw new Error(`Intent with name ${name} not supported`);
}

// --------------- Main handler -----------------------

// Route the incoming request based on intent.
// The JSON body of the request is provided in the event slot.
exports.handler = (event, context, callback) => {

    console.log(JSON.stringify(event));

    try {
        console.log(`event.bot.name=${event.bot.name}`);

        // fail if this function is for a different bot
        if (!event.bot.name.startsWith('Aowi')) {
            callback('Invalid Bot Name');
        }
        dispatch(event, (response) => callback(null, response));
    }
    catch (err) {
        callback(err);
    }
};

我正在从搜索中获得回复,但我无法将回复发送给 Lex。内容部分始终为空。

Response:
{
  "sessionAttributes": {},
  "dialogAction": {
    "type": "Close",
    "fulfillmentState": "Fulfilled",
    "message": {
      "contentType": "PlainText",
      "content": " "
    }
  }
}

Lex 将发送名为 'SearchProduct' == 'meat' 的槽。

在此处输入图像描述

我不确定我在哪一部分做错了。如果有人可以帮助我改进代码,请不胜感激。谢谢

4

2 回答 2

0

此错误是因为 Amazon Lex 需要某种 JSON 格式的响应。从看起来您已经在 Node.js 中编写代码的情况来看。我不是节点专家,但我可以为您提供一个工作示例,说明如何将响应发送回 lex。

代码流程是这样的:

调用意图 -> 调用 Lambda 函数 ->(您的 Lamba 代码运行并处理 lex 给出的数据)-> 您生成响应以发送回 Lex -> Lex 读取响应 json 并根据您返回的内容对其进行解释。

def close(fulfillment_state, message):
response = {
    'dialogAction': {
        'type': 'Close',
        'fulfillmentState': fulfillment_state,
        'message': message
    }
}
return response
response_to_lex =  close('Fulfilled',{'contentType': 'PlainText','content': 'Message i want to send to lex'})

close 函数为 lex 创建一个“Close”类型的 fullfilment 事件,并生成一个适当的响应消息。注意:type、fulfullmentState 和 message是强制参数,需要回传给 lex。

此链接有助于深入理解它:Lex Docs

还在这里查看 LEX 和 Node Lambda 的文档,我可以看到调用调度函数的方法是不同的。但我在这里可能完全不正确。

于 2018-06-18T11:42:38.093 回答
0

您必须以特定格式发送响应。下面是 Node.js 的示例

 const response = {
          dialogAction: {
                        type: "Close",
                        fulfillmentState: "Fulfilled",
                        message: {
                            contentType: "PlainText",
                            content: "i have found Meat in Aisle no 4"
                        }
                    }
                };
                callback(null, response);

如果对你有帮助,你能接受答案吗?

于 2019-04-16T11:52:14.763 回答