Alexa 提出问题并从外部 API 获得响应



我已经设置了一个简单的意图

{
  "interactionModel": {
    "languageModel": {
      "invocationName": "viva bank",
      "intents": [
        ...builtin intents...{
          "name": "ask",
          "slots": [{
            "name": "question",
            "type": "AMAZON.SearchQuery"
          }],
          "samples": [
            "when {question}",
            "how to {question}",
            "what {question}"
          ]
        }
      ],
      "types": []
    }
  }
}

但是当我问一个问题时,它会给我一个通用的错误响应,如下所示:

我:亚历克萨问万岁银行什么时候收取滞纳金

Alexa:对不起,我不知道。

这是我的lambda代码,但我认为它并没有走那么远。

'use strict';
const Alexa = require('ask-sdk-core');
var https = require('https');
var querystring = require('querystring');
const APP_ID = 'amzn1.ask.skill.1234';
const AskIntentHandler = {
  canHandle(handlerInput) {
    return !!handlerInput.requestEnvelope.request.intent.slots['question'].value;
  },
  handle(handlerInput) {
    var question = handlerInput.requestEnvelope.request.intent.slots['question'].value;
    console.log('mydata:', question);
    var responseString = '';
    const subscription_key = 'XXXX';
    var data = {
      simplequery: question,
      channel: 'Alexa'
    };
    var get_options = {
      headers: {
        'Subscription-Key': subscription_key
      }
    };
    https.get('https://fakeapi.com/' + querystring.stringify(data), get_options, (res) => {
      console.log('statusCode:', res.statusCode);
      console.log('headers:', res.headers);
      res.on('data', (d) => {
        responseString += d;
      });
      res.on('end', function(res) {
        var json_hash = JSON.parse(responseString);
        // grab the first answer returned as text and have Alexa read it
        const speechOutput = json_hash['results'][0]['content']['text'];
        console.log('==> Answering: ', speechOutput);
        // speak the output
        return handlerInput.responseBuilder.speak(speechOutput).getResponse();
      });
    }).on('error', (e) => {
      console.error(e);
      return handlerInput.responseBuilder.speak("I'm sorry I ran into an error").getResponse();
    });
  }
};
exports.handler = (event, context) => {
  const alexa = Alexa.handler(event, context);
  alexa.APP_ID = APP_ID;
  alexa.registerHandlers(AskIntentHandler);
  alexa.execute();
};

真的只是想创建一个非常简单的传递,向Alexa提出一个问题,然后我将其传送到外部API并让Alexa读取响应。

如果问题槽对于意图是必需的,并且您需要包含意向名称,则可以根据需要使问题槽值。您可以使用 async/await 来处理 API。

const Alexa = require('ask-sdk-core');
const https = require('https');
const querystring = require('querystring');
const { getSlotValue } = Alexa;
const APP_ID = 'amzn1.ask.skill.1234';
const AskIntentHandler = {
  canHandle(handlerInput) {
    return (
      handlerInput.requestEnvelope.request.type === "IntentRequest" &&
      handlerInput.requestEnvelope.request.intent.name === "AskIntent"
    );
  },
  async handle(handlerInput) {
    const question = getSlotValue(handlerInput.requestEnvelope, "question");
    console.log("question ", question);
    const data = await getAnswer(question);
    const speechText = data;
    return handlerInput.responseBuilder
      .speak(speechText)
      .reprompt(speechText)
      .getResponse();
  }
};
const getAnswer = question => {
  const subscription_key = "XXXX";
  let data = {
    simplequery: question,
    channel: "Alexa"
  };
  let get_options = {
    headers: {
      "Subscription-Key": subscription_key
    }
  };
  return new Promise((resolve, reject) => {
    https
      .get(
        "https://fakeapi.com/" + querystring.stringify(data),
        get_options,
        res => {
          console.log("statusCode:", res.statusCode);
          console.log("headers:", res.headers);
          res.on("data", d => {
            responseString += d;
          });
          res.on("end", function(res) {
            var json_hash = JSON.parse(responseString);
            // grab the first answer returned as text and have Alexa read it
            const speechOutput = json_hash["results"][0]["content"]["text"];
            console.log("==> Answering: ", speechOutput);
            resolve(speechOutput);
          });
        }
      )
      .on("error", e => {
        console.error(e);
        resolve("I'm sorry I ran into an error");
      });
  });
};

在 AskIntentHandler 中,除了检查问题槽之外,您还应该将"canHandle"设置为意图的名称。

const AskIntentHandler = {
  canHandle (handlerInput) {
  return handlerInput.requestEnvelope.request.type === 'IntentRequest' &&
      handlerInput.requestEnvelope.request.intent.name === 'AskIntent' &&
      !!handlerInput.requestEnvelope.request.intent.slots['question'].value
  },
  handle (handlerInput) {
     // API Request Here
  }
}

此外,如果始终需要"问题"来运行意图,您可以设置一个对话框,以便Alexa在用户无法识别问题时询问"问题"。

https://developer.amazon.com/docs/custom-skills/delegate-dialog-to-alexa.html

最新更新