BerriAI/litellm · error · ServiceUnavailableError

SagemakerException

Error message

SagemakerException - {original_exception.message}

What it means

LiteLLM normalizes an HTTP 500 from a SageMaker inference endpoint into its generic ServiceUnavailableError. The 500 means the model container behind the endpoint hit an unhandled exception (crash, OOM, broken handler), not that LiteLLM failed. The message embeds the raw endpoint exception text (original_exception.message). Note the attached httpx.Response is synthetic (a placeholder POST to api.openai.com/v1/), so do not rely on its URL or headers when debugging.

Solutions

  1. Check the endpoint's CloudWatch logs (group /aws/sagemaker/Endpoints/<endpoint-name>) for the container stack trace at the failure timestamp
  2. Reproduce with a minimal direct boto3 invoke_endpoint call to confirm the failure is in the container, not in litellm
  3. If the handler crashes on OpenAI-format payloads, supply the input format / custom prompt template your container expects
  4. If OOM: move the endpoint to a larger instance type or reduce max_new_tokens
  5. Set num_retries on the call (litellm.completion(..., num_retries=3)) since 500s during model loading are often transient

Example fix

# before
response = litellm.completion(
    model='sagemaker/my-endpoint',
    messages=messages,
)

# after
response = litellm.completion(
    model='sagemaker/my-endpoint',
    messages=messages,
    num_retries=3,  # transient container 500s get retried
)
# still failing: inspect CloudWatch logs for the container stack trace
Defensive patterns

Strategy: retry

Validate before calling

import boto3

def sagemaker_endpoint_healthy(endpoint_name: str, region: str) -> bool:
    sm = boto3.client('sagemaker', region_name=region)
    return sm.describe_endpoint(EndpointName=endpoint_name)['EndpointStatus'] == 'InService'

Type guard

import litellm

def is_sagemaker_500(exc: BaseException) -> bool:
    return isinstance(exc, litellm.exceptions.ServiceUnavailableError) and 'SagemakerException' in str(exc)

Try / catch

import litellm
from litellm.exceptions import ServiceUnavailableError

try:
    resp = litellm.completion(model='sagemaker/my-endpoint', messages=messages)
except ServiceUnavailableError as e:
    if 'SagemakerException' not in str(e):
        raise
    # container 500s during model load are transient: back off and retry
    time.sleep(2 ** attempt)
    resp = litellm.completion(model='sagemaker/my-endpoint', messages=messages, num_retries=3)

Prevention

When it happens

Trigger: Any litellm.completion(..., model='sagemaker/<endpoint>') call where the SageMaker InvokeEndpoint API responds with HTTP 500: the container's inference handler raised a Python exception, the container was OOM-killed mid-request, or the model server (DJL/TGI/HuggingFace) returned an internal error status.

Common situations: A custom inference handler with a bug (expects 'inputs' key but receives OpenAI-style payload); container memory limits smaller than the model needs; endpoint just deployed and the model still loading; a bad container image whose /invocations route crashes.

Related errors


AI-assisted analysis of BerriAI/litellm@77b7c6c40c (2026-08-18). Data as JSON: /api/errors/7f36ae512f99b100. Report an issue: GitHub.

Appendix: source

Thrown at litellm/litellm_core_utils/exception_mapping_utils.py:1003

        raise BadRequestError(
            message="SagemakerException - the value of 'n' must be > 0 and <= 2 for sagemaker endpoints",
            model=model,
            llm_provider="sagemaker",
            response=getattr(original_exception, "response", None),
        )
    elif (
        "`inputs` tokens + `max_new_tokens` must be <=" in error_str
        or "instance type with more CPU capacity or memory" in error_str
    ):
        raise ContextWindowExceededError(
            message=f"SagemakerException - {error_str}",
            model=model,
            llm_provider="sagemaker",
            response=getattr(original_exception, "response", None),
        )
    elif hasattr(original_exception, "status_code"):
        if original_exception.status_code == 500:
            raise ServiceUnavailableError(
                message=f"SagemakerException - {original_exception.message}",
                llm_provider=custom_llm_provider,
                model=model,
                response=httpx.Response(
                    status_code=500,
                    request=httpx.Request(method="POST", url="https://api.openai.com/v1/"),
                ),
            )
        elif original_exception.status_code == 401:
            raise AuthenticationError(
                message=f"SagemakerException - {original_exception.message}",
                llm_provider=custom_llm_provider,
                model=model,
                response=getattr(original_exception, "response", None),
            )
        elif original_exception.status_code == 400:
            raise BadRequestError(
                message=f"SagemakerException - {original_exception.message}",

View on GitHub (pinned to 77b7c6c40c)