amazon-sagemaker-examples icon indicating copy to clipboard operation
amazon-sagemaker-examples copied to clipboard

[Example Request]

Open matthew77777 opened this issue 8 months ago • 0 comments

I was wondering how to deal with the error below.

It occured when the inference bigins because autopilot created random models.

Received client error (406) from model with message "Accept type 'application/json' is not supported."

To deal with the problem, i fixed the code something like below but is it a right approach?

import boto3
from botocore.exceptions import ClientError

runtime = boto3.client("sagemaker-runtime")

def invoke_with_fallback(endpoint_name, payload):
    try:
        response = runtime.invoke_endpoint(
            EndpointName=endpoint_name,
            ContentType="application/json",
            Accept="application/json",
            Body=payload
        )
        return response["Body"].read().decode("utf-8")

    except ClientError as e:
        error_code = e.response["Error"]["Code"]
        error_msg = e.response["Error"]["Message"]
        
        if error_code == "ModelError" and "application/json" in error_msg:
            print("[WARN] JSON に非対応のため CSV で再試行します")

            response = runtime.invoke_endpoint(
                EndpointName=endpoint_name,
                ContentType="text/csv",
                Accept="text/csv",
                Body=convert_json_to_csv(payload)
            )
            return response["Body"].read().decode("utf-8")
        else:
            raise e

def convert_json_to_csv(payload):
    import json
    data = json.loads(payload)
    if isinstance(data, dict):
        return ",".join(str(v) for v in data.values())
    elif isinstance(data, list):
        return "\n".join(",".join(str(v) for v in row.values()) for row in data)
    else:
        raise ValueError("JSON payload format not supported.")

json_payload = '{"year":2023,"month_sin":0.5,"month_cos":0.86, ... }'
result = invoke_with_fallback("your-endpoint-name", json_payload)
print(result)

matthew77777 avatar Apr 07 '25 22:04 matthew77777