使用Python开发Alexa技能:解决AMAZON.RepeatIntent执行后无法回到原启发式对话(Elicit Dialog)的问题
解决Alexa RepeatIntent重复后无法回到原意图流程的问题
我来帮你分析下问题出在哪,以及怎么解决:
为什么会出现AttributeError: 'Response' object has no attribute 'add_directive'?
你之前的代码里,cached_response是通过反序列化得到的已完成的Response实例,它是Alexa最终要返回的响应结构,而add_directive是ResponseBuilder类的方法——只有用ResponseBuilder构建响应的过程中,才能添加指令。直接操作已经生成的Response对象自然会报错。
另外,直接返回缓存的Response,相当于完全复用了之前的响应,但没有保留原意图的对话上下文,所以用户后续回复时,Alexa不知道要回到哪个意图处理,导致技能停止。
正确的解决方案思路
不要缓存整个Response对象,而是缓存需要重复的语音内容和原意图名称,然后在RepeatIntent处理时,用当前的ResponseBuilder重新构建响应,同时添加DelegateDirective来引导Alexa继续原意图的对话流程。
步骤1:在原意图中缓存必要信息
比如在你的QuestionIntentHandler的handle方法里,把要重复的语音和原意图名称存入会话属性:
def handle(self, handler_input): # ... 你的原有逻辑,生成speak_output ... attr = handler_input.attributes_manager.session_attributes # 缓存要重复的语音内容 attr["recent_speak_output"] = speak_output # 缓存原意图的名称,用于后续回到该流程 attr["last_intent"] = "QuestionIntent" return handler_input.response_builder.speak(speak_output).response
步骤2:修改RepeatIntentHandler的处理逻辑
重新构建响应,同时添加DelegateDirective指向原意图:
from ask_sdk_model import Intent from ask_sdk_model.dialog import DelegateDirective class RepeatIntentHandler(AbstractRequestHandler): """Handler for repeating the response to the user.""" def can_handle(self, handler_input): return is_intent_name("AMAZON.RepeatIntent")(handler_input) def handle(self, handler_input): attr = handler_input.attributes_manager.session_attributes response_builder = handler_input.response_builder # 从会话属性中获取缓存的内容,给默认值避免空值报错 recent_speak = attr.get("recent_speak_output", "抱歉,我没有可以重复的内容。") last_intent = attr.get("last_intent") # 如果有原意图,构建带DelegateDirective的响应 if last_intent: return response_builder.speak(recent_speak) \ .add_directive(DelegateDirective(updated_intent=Intent(name=last_intent))) \ .response # 没有原意图时,只返回重复的语音 else: return response_builder.speak(recent_speak).response
为什么这样可行?
- 用ResponseBuilder重新构建响应,确保可以正常添加
DelegateDirective指令; DelegateDirective会告诉Alexa,接下来需要继续处理指定的原意图(比如QuestionIntent),这样用户在听到重复的问题后回复,技能就能回到原意图的流程继续处理,而不是直接停止;- 缓存语音内容和意图名称比缓存整个Response更灵活,也更容易维护。
内容的提问来源于stack exchange,提问作者Dilip Kukadiya
相关产品推荐
相关产品推荐

