sgl-project/sglang · error · Exception

Failed to decode base64 image: {str(exc)}

Error message

Failed to decode base64 image: {str(exc)}

What it means

The payload claimed to be base64 but base64.b64decode raised (e.g. non-alphabet characters, wrong padding), so the raw bytes could not be recovered. This catches content-level corruption as opposed to format-level problems caught earlier.

Source

Thrown at python/sglang/multimodal_gen/runtime/utils/image_io.py:36

    if not is_base64:
        raise ValueError(f"{b64_format_hint} (missing ;base64 marker)")
    data = match.group(3)
    if not data:
        raise ValueError(f"{b64_format_hint} (empty data payload)")

    if media_type.startswith("image/"):
        ext = media_type.split("/")[-1].lower()
        if ext == "jpeg":
            ext = "jpg"
    else:
        ext = "jpg"
    target_path = f"{target_path}.{ext}"
    os.makedirs(os.path.dirname(target_path), exist_ok=True)

    try:
        image_data = base64.b64decode(data)
    except Exception as exc:
        raise Exception(f"Failed to decode base64 image: {str(exc)}") from exc

    with open(target_path, "wb") as f:
        f.write(image_data)

    return target_path

View on GitHub (pinned to 0132848349)

Solutions

  1. Normalize the payload: strip whitespace and replace URL-safe chars before decoding
  2. Re-encode the source image with standard base64 (base64.b64encode)
  3. Verify the string length is a multiple of 4 after cleanup

Example fix

// before
save_base64_image_to_path("data:image/png;base64,Ab-/==", "/tmp/img")
// after
import base64
clean = data.replace("-", "+").replace("_", "/")
save_base64_image_to_path(f"data:image/png;base64,{clean}", "/tmp/img")
Defensive patterns

Strategy: try-catch

Validate before calling

import base64
def is_decodable(b64: str) -> bool:
    try:
        base64.b64decode(b64, validate=True)
        return True
    except Exception:
        return False

Try / catch

try:
    save_base64_image_to_path(uri, path)
except Exception as e:
    if "Failed to decode base64" in str(e):
        clean = "".join(b64.split()).replace("-", "+").replace("_", "/")
        save_base64_image_to_path(f"data:image/png;base64,{clean}", path)

Prevention

When it happens

Trigger: A data URI with ;base64 marker whose data contains invalid characters or incorrect padding — often from JSON escaping issues, URL-safe base64 (- and _) instead of standard alphabet, or copy/paste corruption.

Common situations: URL-safe base64 from other systems, payloads with whitespace/newlines or unicode quotes, truncated strings that still decode-format correctly.

Understand the failure class

Related errors


AI-assisted analysis of sgl-project/sglang@0132848349 (2026-08-28). Data as JSON: /api/errors/2fd1793ae021d564. Report an issue: GitHub.