如何为Alexa开发决策树技能?情绪交互逻辑实现求助
搞定Alexa技能情绪交互的逻辑实现方案
嘿,我来帮你解决这个Alexa技能的情绪交互问题!你的需求是让Alexa先询问用户情绪,再根据用户的反馈(比如SAD)展开针对性追问,核心问题其实是如何在对话过程中保存用户的情绪选择,这里给你明确的方案:
核心结论:用会话属性(Session Attributes)而非普通变量
普通变量是局部的,只能在当前处理函数里生效,用户回答后进入下一个对话环节时,变量值就丢失了。而会话属性是绑定在当前对话会话中的,能在整个交互流程里存储和读取数据,完美适配这种跨Intent的逻辑需求。
具体实现步骤(结合你的AWS代码片段)
1. 先初始化会话属性
在技能启动的LaunchRequest里,初始化一个用来存储用户情绪的会话属性:
const GREETING = [ 'What emotion are you feeling today?', 'Hello, what emotion are you feeling right now?' ]; const LaunchRequestHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'LaunchRequest'; }, handle(handlerInput) { // 初始化会话属性,用于存储用户后续输入的情绪 const sessionAttributes = handlerInput.attributesManager.getSessionAttributes(); sessionAttributes.userEmotion = ''; // 随机选择问候语 const speakOutput = GREETING[Math.floor(Math.random() * GREETING.length)]; return handlerInput.responseBuilder .speak(speakOutput) .reprompt(speakOutput) .getResponse(); } };
2. 处理用户的情绪回答
创建一个EmotionResponseIntent(需要在你的技能模型里定义这个Intent,并且添加emotion槽位,包含SAD、HAPPY等情绪值),在这个Handler里读取用户的情绪,存入会话属性,然后触发对应追问:
const EmotionResponseIntentHandler = { canHandle(handlerInput) { return Alexa.getRequestType(handlerInput.requestEnvelope) === 'IntentRequest' && Alexa.getIntentName(handlerInput.requestEnvelope) === 'EmotionResponseIntent'; }, handle(handlerInput) { const sessionAttributes = handlerInput.attributesManager.getSessionAttributes(); // 获取用户回答的情绪(从槽位中读取) const userEmotion = Alexa.getSlotValue(handlerInput.requestEnvelope, 'emotion').toUpperCase(); // 将情绪存入会话属性,供后续Intent使用 sessionAttributes.userEmotion = userEmotion; let speakOutput = ''; // 根据不同情绪触发对应追问 switch(userEmotion) { case 'SAD': speakOutput = 'Is this from something in the past or happening right now?'; break; case 'HAPPY': speakOutput = 'That\'s wonderful! What made you feel this way?'; break; // 可以继续扩展更多情绪的逻辑 default: speakOutput = `Got it, you're feeling ${userEmotion.toLowerCase()}. Want to tell me more about it?`; } return handlerInput.responseBuilder .speak(speakOutput) .reprompt(speakOutput) .getResponse(); } };
3. 后续追问的处理(可选)
如果需要针对用户的“过去/当下”回答继续交互,只需要在对应的Intent里读取会话属性中的userEmotion值,就能知道之前的情绪上下文,继续定制对话内容。
额外补充
如果需要跨会话保存用户的情绪数据(比如用户下次打开技能时,能记得上次的情绪),可以使用持久属性(Persistent Attributes),不过你的需求是当前对话内的逻辑,会话属性完全够用。
内容的提问来源于stack exchange,提问作者Rohan Venkatram
相关产品推荐
相关产品推荐

