Skip to content

[Example Request] #4839

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
matthew77777 opened this issue Apr 7, 2025 · 0 comments
Open

[Example Request] #4839

matthew77777 opened this issue Apr 7, 2025 · 0 comments

Comments

@matthew77777
Copy link

matthew77777 commented Apr 7, 2025

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant