You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Amazon Alexa Skills开发指南:如何在技能中添加循环功能?

实现掷骰子Alexa Skill循环逻辑的方案

Alexa Skill 没有传统程序里常驻的显式主循环,所有交互都基于意图触发+会话状态控制实现,你需要的循环效果可以通过保持会话开启、每次处理完请求后重复抛出相同询问实现,不需要写while/for类的循环语句。

1. 先配置意图模型(在Alexa开发者控制台Build页面操作)

  • 启用内置意图:AMAZON.YesIntent、AMAZON.NoIntent、AMAZON.StopIntent、AMAZON.CancelIntent
  • 无需额外创建自定义意图,上述内置意图已经覆盖你需要的所有用户回复场景

2. 编写业务处理逻辑(以最常用的Node.js ASK SDK为例,Python SDK逻辑完全一致)

启动意图处理(用户唤醒技能时触发)

const LaunchRequestHandler = {
  canHandle(handlerInput) {
    return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest';
  },
  handle(handlerInput) {
    const speakText = "我可以掷骰子吗?";
    // 核心配置:设置会话不关闭,等待用户回复
    return handlerInput.responseBuilder
      .speak(speakText)
      .reprompt(speakText)
      .withShouldEndSession(false)
      .getResponse();
  }
};

肯定回复意图处理(用户回答「是」时触发)

const YesIntentHandler = {
  canHandle(handlerInput) {
    return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
      && Alexa.getIntentName(handlerInput.requestEnvelope) === 'AMAZON.YesIntent';
  },
  handle(handlerInput) {
    // 掷骰子逻辑:生成1-6的随机整数
    const diceResult = Math.floor(Math.random() * 6) + 1;
    const speakText = `掷出的点数是${diceResult},我可以再掷一次骰子吗?`;
    // 再次保持会话开启,等待用户后续回复
    return handlerInput.responseBuilder
      .speak(speakText)
      .reprompt(speakText)
      .withShouldEndSession(false)
      .getResponse();
  }
};

退出意图处理(用户回答「否」「退出」时触发)

const ExitIntentHandler = {
  canHandle(handlerInput) {
    return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest'
      && ['AMAZON.NoIntent', 'AMAZON.StopIntent', 'AMAZON.CancelIntent'].includes(
        Alexa.getIntentName(handlerInput.requestEnvelope)
      );
  },
  handle(handlerInput) {
    const speakText = "好的,再见";
    // 关闭会话,结束循环
    return handlerInput.responseBuilder
      .speak(speakText)
      .withShouldEndSession(true)
      .getResponse();
  }
};

3. 注册处理逻辑

把上述三个Handler按ASK SDK的要求注册到你的Skill实例中即可生效。

核心逻辑说明:你需要的循环完全由会话状态控制,只要设置withShouldEndSession(false),会话就会保持开启等待用户回复,用户回复后会自动触发对应意图的处理逻辑,相当于自动完成循环;需要结束时设置withShouldEndSession(true)关闭会话即可。

内容的提问来源于stack exchange,提问作者clamum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 20:45:05