Lex 2聊天机器人jokeintent意图完成却未返回指定笑话求助
问题解决:Lex V2聊天机器人未返回预期笑话,仅提示Intent fulfilled
问题描述
研究该错误数小时,多次修改后,聊天机器人始终返回“Intent jokeintent is fulfilled”,而非需要的笑话,推测问题出在Lambda函数返回的响应上。
已排查项
- 测试Lambda函数可返回正确笑话
- 使用Lex 2版本
- 已选择Lambda函数作为实现钩子
- 聊天机器人设置已关联该Lambda函数
代码问题分析
你的Lambda函数存在两个核心问题,导致Lex无法正确解析并展示笑话内容:
响应消息格式不符合Lex V2规范
Lex V2要求messages字段是数组类型,而非单个对象。你当前的写法是单个对象,Lex无法识别有效消息内容,因此返回默认的Intent fulfilled提示。槽值获取逻辑错误
在Lex V2的事件结构中,槽值嵌套在value.interpretedValue下,你直接比较event["sessionState"]["intent"]["slots"]["joketype"]与字符串,永远无法匹配成功,导致response["messages"]["content"]从未被赋值,最终没有有效消息返回。额外问题:sessionId硬编码
硬编码sessionId会导致会话上下文混乱,应该从传入的event中获取真实的sessionId。
修正后的Lambda代码
import json def dad_joke(): return "How do you find Will Smith in a snow storm? Find the fresh prints" def random_joke(): return "Why was Cinderella so bad at soccer? she kept running away from the ball" def animal_joke(): return "What do rabbits eat for breakfast? IHOP" def poop_joke(): return "What did one piece of toilet paper say to the other? I'm feeling really wiped" def lambda_handler(event, context): # 初始化符合Lex V2规范的响应结构 response = { "sessionState": { "dialogAction": { "type": "Close" }, "intent": { "name" : "jokesIntent", "state": "Fulfilled" } }, "sessionId": event["sessionId"], # 使用event中的真实sessionId "messages": [] # messages必须是数组 } # 获取槽值的正确方式 joketype_slot = event["sessionState"]["intent"]["slots"]["joketype"] if joketype_slot and "value" in joketype_slot: joketype = joketype_slot["value"]["interpretedValue"] # 根据槽值匹配对应的笑话函数 joke_map = { "random joke": random_joke, "animal joke": animal_joke, "dad joke": dad_joke, "poop joke": poop_joke } if joketype in joke_map: # 向messages数组中添加消息对象 response["messages"].append({ "contentType": "PlainText", "content": joke_map[joketype]() }) return response
修改说明
- 将
messages改为数组,并在匹配到槽值后向数组中添加符合格式的消息对象; - 修正槽值获取逻辑,正确提取
interpretedValue; - 用字典映射替代多层if-else,简化代码逻辑;
- 替换硬编码的sessionId为event中的真实值;
- 增加空值判断,避免槽值未填充时出现KeyError。
内容的提问来源于stack exchange,提问作者kelsey
相关产品推荐
相关产品推荐

