为什么 AWS Lambda 内部服务器错误 500 但在 Endpoint SageMaker 中成功 /invocations POST 200?

Why AWS Lambda Internel Server Error 500 but successfully /invocations POST 200 in Endpoint SageMaker?

import os
import io
import boto3
import json
import csv


# grab environment variables
ENDPOINT_NAME = os.environ['ENDPOINT_NAME']
# grab runtime client
runtime = boto3.client('runtime.sagemaker')

def lambda_handler(event, context):
    # Load data from POST request
    data = json.loads(json.dumps(event))
    
    # Grab the payload
    payload = data['body']
    
    # Invoke the model. In this case the data type is a JSON but can be other things such as a CSV
    response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
                                   ContentType='application/json',
                                   Body=payload)
    
    # Get the body of the response from the model
    result = response['Body'].read().decode()

    # Return it along with the status code of 200 meaning this was succesful 
    return {
        'statusCode': 200,
        'body': result
    }

来自 AWS Lambda 的响应

{
  "errorMessage": "'body'",
  "errorType": "KeyError",
  "stackTrace": [
    [
      "/var/task/lambda_function.py",
      18,
      "lambda_handler",
      "payload = data['body']"
    ]
  ]
}

response from Postman 500 Internal Server Error

but successfully invoke POST 200 in SageMaker Endpoint

问题出在您尝试使用数据['body'] 解析负载时。数据未以端点期望的格式传递。使用以下代码片段为端点正确 format/serialize 数据。此外,为了使所有这些更清楚,请确保检查您的有效负载类型,以确保您没有意外地再次序列化。

    data = json.loads(json.dumps(event))
    payload = json.dumps(data)
    response = runtime.invoke_endpoint(EndpointName=ENDPOINT_NAME,
                                       ContentType='application/json',
                                       Body=payload)
    result = json.loads(response['Body'].read().decode())

我在 AWS 工作,我的观点是我自己的