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

如何基于Python SDK在Alexa多意图技能中保持会话持续开启

解决Alexa Python SDK技能保持会话开启的问题

嘿,这个问题我熟!你要让Alexa在不同意图间保持会话(蓝灯常亮)不用重新唤醒,核心就是控制会话的结束状态,用Python SDK其实很容易实现,我给你拆解一下:

核心原理

Alexa默认在返回响应后会自动结束会话(should_end_session=True),所以你需要在需要继续交互的响应里显式告诉Alexa不要结束会话。有两种常用方式:


方法1:使用ask()方法(推荐)

ask()方法是Alexa ResponseBuilder提供的快捷方式,它会同时完成三个动作:

  1. 说出你指定的主文本
  2. 设置重新提示文本(用户没回应时会触发)
  3. 自动将should_end_session设为False,保持会话开启

比如修改你的NameCaptureIntentHandler,处理完名字后返回带ask()的响应:

from ask_sdk_core.dispatch_components import AbstractRequestHandler
from ask_sdk_core.utils import is_intent_name
from ask_sdk_core.handler_input import HandlerInput
from ask_sdk_model import Response

class NameCaptureIntentHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        return is_intent_name("NameCaptureIntent")(handler_input)
    
    def handle(self, handler_input):
        # 提取用户输入的名字槽位
        name_slot = handler_input.request_envelope.request.intent.slots.get("NameSlot")
        name = name_slot.value if name_slot else "朋友"
        
        # 构建带会话保持的响应
        speech_content = f"很高兴认识你{name},你来自哪里?"
        reprompt_content = "可以告诉我你来自哪个地区吗?"
        
        return (
            handler_input.response_builder
                .speak(speech_content)  # 主回复内容
                .ask(reprompt_content)   # 设置重新提示并保持会话
                .response
        )

这样Alexa说完后会保持蓝灯亮起,直接监听你的下一句回答,不用再喊“Alexa”唤醒。


方法2:手动设置should_end_session=False

如果你不需要重新提示文本,也可以直接用with_should_end_session(False)来强制保持会话:

return (
    handler_input.response_builder
        .speak("很高兴认识你Jeff,你来自哪里?")
        .with_should_end_session(False)
        .response
)

不过更推荐用ask(),因为它能处理用户沉默的情况,会自动重复提示,提升交互体验。


结束会话的处理

当你完成所有交互(比如用户回答完地区后),只需要不调用ask(),或者显式设置should_end_session=True,Alexa就会结束会话,蓝灯熄灭:

class CaptureCustomerLivingIntentHandler(AbstractRequestHandler):
    def can_handle(self, handler_input):
        return is_intent_name("CaptureCustomerLivingIntent")(handler_input)
    
    def handle(self, handler_input):
        location_slot = handler_input.request_envelope.request.intent.slots.get("LocationSlot")
        location = location_slot.value if location_slot else "某个很棒的地方"
        
        speech_text = f"哇,{location}听起来超棒!今天的问答测验就到这里啦~"
        
        return (
            handler_input.response_builder
                .speak(speech_text)
                # 这里不调用ask,默认should_end_session=True,会话自动结束
                .response
        )

注意事项

  • 确保每个需要后续交互的意图响应都加上会话保持的设置,不要遗漏任何一步
  • 槽位名称要和你在Alexa开发者控制台配置的一致,避免提取不到用户输入

这样修改后,你的交互流程就能实现不用重复唤醒Alexa的效果啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 13:32:31