Skip to content

[Example Request] #4839

Description

@matthew77777

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)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions