HKUDS/Vibe-Trading · error · ValueError

expected data:<mime>;base64,<payload>

Error message

expected data:<mime>;base64,<payload>

What it means

save_base64_data_url persists a data: URL payload to disk. It first validates the URL shape against _DATA_URL_RE, which expects the form data:<mime>;base64,<payload>. If the regex does not match — missing 'data:' scheme, missing ';base64' marker, or malformed structure — it raises this ValueError.

Source

Thrown at agent/src/utils/media_decode.py:47

def save_base64_data_url(data_url: str, output_dir: Path, *, max_bytes: int = 0) -> Path:
    """Decode a base64 data URL and save it to *output_dir*.

    Args:
        data_url: A ``data:<mime>;base64,...`` URL.
        output_dir: Directory where the decoded file should be written.
        max_bytes: Optional maximum decoded byte length. ``0`` disables the
            limit.

    Returns:
        The path of the decoded file.

    Raises:
        FileSizeExceeded: If decoded data exceeds ``max_bytes``.
        ValueError: If the URL is malformed or uses an unsupported MIME type.
    """
    match = _DATA_URL_RE.match(data_url)
    if not match:
        raise ValueError("expected data:<mime>;base64,<payload>")
    mime = match.group(1).strip().lower()
    ext = _EXT_BY_MIME.get(mime)
    if not ext:
        raise ValueError(f"unsupported data URL MIME type: {mime}")

    payload = match.group(3).strip()
    try:
        decoded = base64.b64decode(payload, validate=True)
    except (binascii.Error, ValueError) as exc:
        raise ValueError("invalid base64 payload") from exc

    if max_bytes and len(decoded) > max_bytes:
        raise FileSizeExceeded(f"decoded media exceeds {max_bytes} bytes")

    output_dir.mkdir(parents=True, exist_ok=True)
    path = output_dir / f"{uuid.uuid4().hex}{ext}"
    path.write_bytes(decoded)
    return path

View on GitHub (pinned to 80ffdda44c)

Solutions

  1. Ensure the input is a full data URL: data:<mime>;base64,<payload>
  2. If you hold raw base64, construct the data URL explicitly with the correct MIME type
  3. Strip surrounding whitespace before passing the value
  4. Log the first ~40 chars of the offending value to spot structural typos quickly

Example fix

# before
path = save_base64_data_url(raw_b64, out_dir)  # raw base64, no data: prefix

# after
path = save_base64_data_url(f"data:image/png;base64,{raw_b64}", out_dir)
Defensive patterns

Strategy: validation

Validate before calling

import re
_DATA_URL_RE = re.compile(r"^data:([\w./+-]+);base64,(.+)$", re.DOTALL)

def is_valid_data_url(value: str) -> bool:
    return bool(_DATA_URL_RE.match(value.strip()))

assert is_valid_data_url(data_url), "expected data:<mime>;base64,<payload>"

Type guard

def is_data_url(value: str) -> bool:
    return isinstance(value, str) and value.strip().lower().startswith("data:") and ";base64," in value

Try / catch

try:
    path = save_base64_data_url(data_url, out_dir)
except ValueError as e:
    if "expected data:" in str(e):
        return reject_attachment("malformed data URL")
    raise

Prevention

When it happens

Trigger: Calling save_base64_data_url with strings like 'data:image/png,' (no payload marker), 'image/png;base64,AAA...', 'data:image/png,AAAA' (missing ;base64), or arbitrary non-data-URL text passed in a media field.

Common situations: Frontends sending raw base64 without the data: prefix, URLs constructed by string concatenation with a typo, envelope media fields populated with http URLs instead of data URLs, or trailing/leading whitespace breaking the match.

Related errors


AI-assisted analysis of HKUDS/Vibe-Trading@80ffdda44c (2026-08-28). Data as JSON: /api/errors/73b1ee90d82aa6fc. Report an issue: GitHub.