huggingface/smolagents · error · SerializationError

Cannot safely serialize object of type {type(obj).__name__}

Error message

Cannot safely serialize object of type {type(obj).__name__}

What it means

SerializationError raised in safe (no-pickle) mode when _to_json_safe encounters an object it cannot represent as JSON: not a dataclass, and not any of the whitelisted primitive/container types. Safe mode fails closed rather than silently dropping data.

Source

Thrown at src/smolagents/remote_executors.py:256

                        return {"__type__": "ndarray", "data": obj.tolist(), "dtype": str(obj.dtype)}
                    elif isinstance(obj, (np.integer, np.floating)):
                        return obj.item()
                except ImportError:
                    pass

                # Try dataclass
                import dataclasses

                if dataclasses.is_dataclass(obj) and not isinstance(obj, type):
                    return {
                        "__type__": "dataclass",
                        "class_name": type(obj).__name__,
                        "module": type(obj).__module__,
                        "data": {f.name: _to_json_safe(getattr(obj, f.name)) for f in dataclasses.fields(obj)},
                    }

                # Cannot safely serialize - raise error for safe mode
                raise SerializationError(f"Cannot safely serialize object of type {type(obj).__name__}")

            def _serialize_with_fallback(obj):
                """Serialize with safe method, fallback to pickle if allowed."""
                import pickle

                if not ALLOW_PICKLE:
                    # Safe ONLY mode - NO pickle fallback, raise error if can't serialize
                    json_safe = _to_json_safe(obj)  # Will raise SerializationError if fails
                    return "safe:" + json.dumps(json_safe)
                else:
                    # Try safe first, fallback to pickle if allowed
                    try:
                        json_safe = _to_json_safe(obj)
                        return "safe:" + json.dumps(json_safe)
                    except SerializationError:
                        # Fallback to pickle
                        try:
                            return "pickle:" + base64.b64encode(pickle.dumps(obj)).decode()

View on GitHub (pinned to 30bb116109)

Solutions

  1. Return JSON-friendly types (dict, list, str, int, float, bool, None, enums, dataclasses) from executed code / final answers
  2. Add a dataclass or as_dict() conversion for the object before returning it
  3. Set allow_pickle=True on the executor if you trust the sandbox (e.g. DockerExecutor(..., allow_pickle=True))

Example fix

# before
class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y
final_answer = Point(1, 2)

# after
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int
final_answer = Point(1, 2)
Defensive patterns

Strategy: validation

Validate before calling

import dataclasses, enum
SAFE_TYPES = (str, int, float, bool, type(None), list, dict, tuple, enum.Enum)

def is_json_safe(obj) -> bool:
    if isinstance(obj, SAFE_TYPES):
        return True
    return dataclasses.is_dataclass(obj) and not isinstance(obj, type)

Type guard

def is_json_safe(obj) -> bool:
    import dataclasses, enum
    if isinstance(obj, (str, int, float, bool, type(None), enum.Enum)):
        return True
    if isinstance(obj, (list, tuple, set)):
        return all(is_json_safe(x) for x in obj)
    if isinstance(obj, dict):
        return all(isinstance(k, str) and is_json_safe(v) for k, v in obj.items())
    return dataclasses.is_dataclass(type(obj))

Try / catch

from smolagents.remote_executors import SerializationError

try:
    output = executor.run_code_raise_errors(code)
except SerializationError as e:
    output = executor.run_code_raise_errors("final_answer(str(result))")

Prevention

When it happens

Trigger: Returning an object as a final answer from remote-executed code (or passing one in additional_imports state) that is an arbitrary class instance, lambda, file handle, numpy array, etc., while allow_pickle=False.

Common situations: Final answer is a custom class, pandas/numpy object, or ORM model; migrating from pickle-based serialization to the default safe serializer; Docker/E2B executors returning rich objects.

Related errors


AI-assisted analysis of huggingface/smolagents@30bb116109 (2026-08-28). Data as JSON: /api/errors/a2731be3807ef02d. Report an issue: GitHub.