AWS Lex调用Lambda获取天气异常:仅显示Intent完成无天气数据
AWS Lex Bot调用Lambda获取天气数据异常问题
我创建了一个AWS Lex Bot,通过Lambda调用天气API获取城市温度。Lambda单独测试可正常返回对应城市的温度,已成功配置Lex调用Lambda,但触发findingweather意图时,仅显示“intent findingweather is fulfilled”,未返回天气数据。
相关Lambda代码
import json import boto3 from pprint import pprint import urllib3 def weatherfunc(city_name): api_key = '9100010fc2b045080a7exxf42051e547bdxx' base_url = 'http://api.openweathermap.org/data/2.5/weather?' finalurl = base_url + 'appid=' + api_key + '&q=' + city_name httprequest = urllib3.PoolManager() response = httprequest.request('GET',finalurl) #pprint(response.data) weather_status = json.loads(response.data.decode('utf-8')) return weather_status["main"]["temp"] def lambda_handler(event, context): city = event['City'] a = weatherfunc(city)
Lex配置截图

问题原因及修复方案
问题核心是Lambda的lambda_handler未返回AWS Lex要求的标准响应格式,Lex无法识别并展示天气数据;同时参数获取路径不符合Lex的传参规则。
修复后的完整代码
import json import urllib3 def weatherfunc(city_name): api_key = '9100010fc2b045080a7exxf42051e547bdxx' base_url = 'http://api.openweathermap.org/data/2.5/weather?' finalurl = base_url + 'appid=' + api_key + '&q=' + city_name httprequest = urllib3.PoolManager() response = httprequest.request('GET',finalurl) weather_status = json.loads(response.data.decode('utf-8')) # 将开尔文温度转换为摄氏度并保留两位小数 temp_celsius = round(weather_status["main"]["temp"] - 273.15, 2) return temp_celsius def lambda_handler(event, context): # Lex传递的参数路径为CurrentIntent.Slots.City city = event['CurrentIntent']['Slots']['City'] temp = weatherfunc(city) # 返回Lex标准响应结构 return { "dialogAction": { "type": "Close", "fulfillmentState": "Fulfilled", "message": { "contentType": "PlainText", "content": f"{city}当前温度为{temp}摄氏度" } } }
关键修改说明
- 参数路径修正:Lex调用Lambda时,用户输入的城市参数存储在
event['CurrentIntent']['Slots']['City'],而非直接event['City'],这是单独测试与Lex调用的参数差异点。 - 标准响应结构:必须返回包含
dialogAction的JSON对象,指定Close类型(结束对话)、Fulfilled状态(意图完成),并在message中定义展示给用户的文本内容。 - 温度单位转换:OpenWeatherMap默认返回开尔文温度,添加转换为摄氏度的逻辑,让结果更符合用户认知。
内容的提问来源于stack exchange,提问作者Jason
相关产品推荐
相关产品推荐

