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

如何在Alexa技能的Lambda函数中获取Slot值并完成API鉴权

代码问题修复说明

核心错误点

  • 取值逻辑错误:你通过cpf = slots['cpf']获取到的是Alexa的Slot对象,而非用户输入的CPF字符串,后续直接用整个对象和存储字符串的cpfs_cnpjs列表匹配,永远会返回不匹配的结果。
  • 去重逻辑位置错误:你把cpfs_cnpjs = list(dict.fromkeys(cpfs_cnpjs))写在了遍历response['Data']的循环内部,每处理一条msg就会覆盖一次列表,最终列表只会保留最后一条msg对应的CPF/CNPJ数据,之前遍历得到的有效数据都会丢失。
  • 潜在的格式不匹配问题:用户输入的CPF格式(比如纯数字)可能和外部API返回的CPF格式(比如带.、-分隔符)不一致,会导致匹配失败。

修正后的完整代码

import requests
# 请确保你已经导入了所有需要的依赖:AbstractRequestHandler、HandlerInput、Response、is_intent_name等

class VerificarCpfIntent(AbstractRequestHandler):
    """Handler for Verificar CPF Intent."""
    def can_handle(self, handler_input):
        # type: (HandlerInput) -> bool
        return is_intent_name("VerificarCpfIntent")(handler_input)

    def handle(self, handler_input):
        # type: (HandlerInput) -> Response
        slots = handler_input.request_envelope.request.intent.slots
        cpf_slot = slots['cpf']
        cpf_input = cpf_slot.value.strip() # 直接提取用户输入的CPF字符串,去掉首尾空格
        speech_text = "Ok"
        
        if cpf_input:
            try:
                # 这里如果你的API需要传入用户CPF查询,请自行修改请求参数,当前逻辑是拉取全量CPF校验
                response = requests.get("你的外部API地址", timeout=5).json()
                cpfs_cnpjs = []
                for msg in response['Data']:
                    for cpf_cnpj in msg['ConsumidorObj'].get('CpfsCnpjs', []):
                        # 可以在这里做格式统一,比如去掉所有非数字字符再存入列表
                        cleaned_cpf = ''.join(filter(str.isdigit, str(cpf_cnpj[1])))
                        cpfs_cnpjs.append(cleaned_cpf)
                # 把去重逻辑移到循环外,所有数据收集完成后再去重
                cpfs_cnpjs = list(dict.fromkeys(cpfs_cnpjs))
                # 也对用户输入的CPF做格式统一,避免格式差异导致匹配失败
                cleaned_input = ''.join(filter(str.isdigit, cpf_input))
                
                if cleaned_input in cpfs_cnpjs:
                    speech_text = "Olá fulano"
                else:
                    speech_text = "Humm, não encontrei seu usuário, se você não possuir login no aplicativo ou plataforma, crie um usuário em um desses canais"
            except Exception as e:
                # 异常捕获,避免API请求失败导致技能崩溃
                speech_text = "Desculpe, no momento não consigo verificar seus dados, tente novamente mais tarde"

        return (
            handler_input.response_builder
                .speak(speech_text).set_should_end_session(True)
                .response
        )

额外优化建议

  • 如果你的外部API支持单条CPF查询,建议直接把用户输入的CPF作为参数传给API,不要拉取全量CPF列表比对,既能提高请求速度,也能避免数据泄露风险。
  • 可以增加CPF格式合法性校验逻辑,用户输入不符合CPF规则时直接提示重新输入,不用调用API。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 22:54:04