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

AWS Lex V2中如何在JavaScript Lambda获取用户输入槽位名称

获取AWS Lex V2中用户输入对应的槽位名称(JavaScript Lambda)

在AWS Lex V2触发Lambda的事件结构里,用户输入对应的槽位信息可从sessionState或interpretations字段中提取,以下是具体实现方案:

核心逻辑

Lex V2会将识别到的槽位数据存入event.sessionState.intent.slots,每个槽位包含用户输入的原始值(value.originalValue)。通过对比该值与inputTranscript,即可定位对应的槽位名称。

代码实现

方式1:从sessionState匹配槽位

// 获取格式化后的用户输入
const userInput = event.inputTranscript.trim();
// 获取当前意图下的所有槽位
const slots = event.sessionState.intent.slots;
let matchedSlotName = null;

// 遍历所有槽位寻找匹配项
for (const slotName in slots) {
  const slot = slots[slotName];
  // 校验槽位原始输入值是否与用户输入一致
  if (slot?.value?.originalValue && slot.value.originalValue.trim() === userInput) {
    matchedSlotName = slotName;
    break;
  }
}

// 后续业务逻辑处理
if (matchedSlotName) {
  console.log(`匹配到的槽位名称:${matchedSlotName}`);
} else {
  console.log("未找到与当前输入匹配的槽位");
}

方式2:从interpretations提取解析结果

如果需要参考Lex的顶级解析结果(比如多意图识别场景),可从event.interpretations中获取:

const userInput = event.inputTranscript.trim();
let matchedSlotName = null;

// 获取Lex排名第一的解析结果
const topInterpretation = event.interpretations[0];
if (topInterpretation?.intent?.slots) {
  for (const slotName in topInterpretation.intent.slots) {
    const slot = topInterpretation.intent.slots[slotName];
    if (slot?.value?.originalValue && slot.value.originalValue.trim() === userInput) {
      matchedSlotName = slotName;
      break;
    }
  }
}

注意事项

  • 建议用trim()处理输入,避免首尾空格导致匹配失败
  • 若存在槽位值重叠情况(同一输入可匹配多个槽位),需根据业务逻辑调整匹配优先级
  • 确保Lambda执行角色已配置访问Lex V2的基础权限

内容的提问来源于stack exchange,提问作者ICL Sales EXIMON

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 20:12:13