All articles on Amazon Lex
Amazon Lex can't communicate directly with Cognigy.AI, therefore it needs a Lambda function to forward the payload to Cognigy.AI and then return the response in a special format to Amazon Lex.
When using the Cognigy.AI NLU we only use Amazon Lex for transcription, and forward the transcript to Cognigy.AI where it is processed normally.
Setup
- Log on to the AWS console as a privileged user.
- Open AWS Lambda and create a new Lambda function with a Node.js 16.x runtime.
- Copy the following code into your index.js file
const COGNIGY_ENDPOINT_HOSTNAME = "endpoint-trial.cognigy.ai"; const COGNIGY_ENDPOINT_PATH = "/your-url-token"; // Change these attributes to the session attributes that contain your userId and sessionId const USERID_ATTRIBUTE = "CustomerNumber"; const SESSIONID_ATTRIBUTE = "ContactId"; const AWS = require("aws-sdk"); exports.handler = async (event, context, callback) => { try { const postObject = { userId: event["sessionState"]["sessionAttributes"][USERID_ATTRIBUTE] || AWS.util.uuid.v4(), sessionId: event["sessionState"]["sessionAttributes"][SESSIONID_ATTRIBUTE] || AWS.util.uuid.v4(), text: event["transcriptions"][0]["transcription"], data: {}, }; const defaultSessionAtrributes = { action: "NONE", action_data: "", }; const resultMap = await sendMessageToCognigy(postObject); if (resultMap["data"] && resultMap["data"]["connect_action"]) { defaultSessionAtrributes["action"] = resultMap["data"]["connect_action"]; } if (resultMap["data"] && resultMap["data"]["connect_action_data"]) { defaultSessionAtrributes["action_data"] = JSON.stringify(resultMap["data"]["connect_action_data"]); } const response = { sessionState: { sessionAttributes: { action: defaultSessionAtrributes.action, action_data: defaultSessionAtrributes.action_data, }, dialogAction: { type: "Close", fulfillmentState: "Fulfilled", message: resultMap["text"], }, intent: { confirmationState: "Confirmed", name: event["sessionState"]["intent"]["name"], slots: {}, state: "Fulfilled", }, }, messages: [{ contentType: "PlainText", content: resultMap["text"], }, ], }; callback(null, response); } catch (e) { return e; } }; const https = require("https"); async function sendMessageToCognigy(postObject) { return new Promise((resolve, reject) => { const postData = JSON.stringify(postObject); const options = { hostname: COGNIGY_ENDPOINT_HOSTNAME, path: COGNIGY_ENDPOINT_PATH, method: "POST", headers: { "Content-Type": "application/json", }, }; const request = https.request(options, handleResponse); request.on("error", error => { reject(error); }); request.write(postData); request.end(); function handleResponse(response) { let data = ""; response.on("data", d => { data += d.toString(); }); response.on("end", () => { resolve(JSON.parse(data)); }); } }); }
- Replace the two variables in the top rows with your Endpoint hostname and the URL token of your Endpoint.
- Save the Lambda function.
Comments
0 comments