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

如何将Lambda获取的第三方天气API结果回传给Lex插槽?

别担心,这事儿其实挺简单的,我给你拆解成几步来操作,用Lex控制台和Lambda在线编辑器完全能搞定~

步骤1:在Lambda里解析天气API的响应

首先,你得先把第三方API返回的响应里的温度数据提取出来。假设你的API返回的是JSON格式(大部分天气API都是这样),比如返回结构大概是:

{
  "data": {
    "temp": 28,
    "unit": "Celsius",
    "city": "Hyderabad",
    "country": "India"
  }
}

那在Lambda代码里,你可以这么提取温度(以Python为例,用Node.js的话思路完全一致):

import requests

def lambda_handler(event, context):
    # 先从Lex的请求里拿到用户输入的Country和City插槽值
    current_intent = event['currentIntent']
    country = current_intent['slots']['Country']
    city = current_intent['slots']['City']
    
    # 调用你的天气API(替换成你实际的API地址和参数)
    weather_api_url = f"https://your-weather-api-endpoint?country={country}&city={city}"
    api_response = requests.get(weather_api_url)
    weather_data = api_response.json()
    
    # 提取温度详情,这里根据你API的实际返回结构调整
    temperature = weather_data['data']['temp']
    temp_unit = weather_data['data']['unit']
    temp_details = f"{temperature}°{temp_unit}"
步骤2:把温度数据回传给Lex插槽

接下来就是把提取到的温度填充到你Lex里对应的插槽(比如你创建了一个叫Temperature的插槽),同时给用户返回自然的回复。Lambda需要返回符合Lex要求的响应格式:

# 准备返回给Lex的响应
    return {
        "sessionAttributes": {},  # 如果需要保存会话数据可以在这里添加
        "dialogAction": {
            "type": "Close",  # 如果所有信息都收集完了,用Close结束对话;如果还要收集其他插槽,用Delegate
            "fulfillmentState": "Fulfilled",
            "message": {
                "contentType": "PlainText",
                "content": f"我查到啦!印度Hyderabad当前的温度是{temp_details}~"
            },
            "slots": {
                # 把原来的插槽值带上,再加上填充好的Temperature插槽
                "Country": country,
                "City": city,
                "Temperature": temperature  # 这里把温度值传给Lex的Temperature插槽
            }
        }
    }
额外注意事项
  • 确保Lex的Intent里确实创建了用来接收温度的插槽(比如Temperature),并且插槽的数据类型和你返回的温度类型匹配(比如是数值型就返回数字,字符串型就返回文本)。
  • 别忘了处理API调用失败的情况,比如加个try-except块,如果API请求出错,就给用户返回友好的提示:
    try:
        api_response = requests.get(weather_api_url)
        api_response.raise_for_status()  # 触发HTTP错误
        weather_data = api_response.json()
    except Exception as e:
        return {
            "sessionAttributes": {},
            "dialogAction": {
                "type": "Close",
                "fulfillmentState": "Failed",
                "message": {
                    "contentType": "PlainText",
                    "content": "抱歉,我暂时查不到这个城市的天气信息,请稍后再试~"
                }
            }
        }
    
  • 在Lex控制台的Intent设置里,要把Fulfillment部分设置为调用你的Lambda函数,这样Lex才会在收集完Country和City插槽后触发Lambda。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:10:08