{"record":{"id":"cb8232be20a29238","repo":"huggingface/smolagents","slug":"cannot-serialize-object-e","errorCode":null,"errorMessage":"Cannot serialize object: {e}","messagePattern":"Cannot serialize object: (.+?)","errorType":"validation","errorClass":"SerializationError","httpStatus":null,"severity":"error","filePath":"src/smolagents/serialization.py","lineNumber":292,"sourceCode":"                json_safe = SafeSerializer.to_json_safe(obj)\n                return SafeSerializer.SAFE_PREFIX + json.dumps(json_safe)\n            except SerializationError:\n                # Warn about insecure pickle usage\n                import warnings\n\n                warnings.warn(\n                    \"Falling back to insecure pickle serialization. \"\n                    \"This is a security risk and will be removed in a future version. \"\n                    \"Consider using only safe serializable types (primitives, lists, dicts, \"\n                    \"numpy arrays, PIL images, datetime objects, dataclasses).\",\n                    FutureWarning,\n                    stacklevel=2,\n                )\n                # Fallback to pickle (with prefix)\n                try:\n                    return \"pickle:\" + base64.b64encode(pickle.dumps(obj)).decode()\n                except (pickle.PicklingError, TypeError, AttributeError) as e:\n                    raise SerializationError(f\"Cannot serialize object: {e}\") from e\n\n    @staticmethod\n    def loads(data: str, allow_pickle: bool = False) -> Any:\n        \"\"\"\n        Deserialize string with format detection.\n\n        Args:\n            data: Serialized string (with \"safe:\" or \"pickle:\" prefix)\n            allow_pickle: If False (default), reject pickle data (strict safe mode).\n                         If True, accept both safe and pickle formats.\n\n        Returns:\n            Deserialized object\n\n        Raises:\n            SerializationError: If pickle data received but allow_pickle=False\n        \"\"\"\n        if data.startswith(SafeSerializer.SAFE_PREFIX):","sourceCodeStart":274,"sourceCodeEnd":310,"githubUrl":"https://github.com/huggingface/smolagents/blob/30bb1161095dbae2271e6bc3cc4c219cc3897a57/src/smolagents/serialization.py#L274-L310","documentation":"SafeSerializer.dumps tried to serialize an object that is not JSON-safe and also could not be pickled (pickle raised PicklingError, TypeError, or AttributeError). The serializer's fallback chain is: JSON-safe types, then base64-pickled bytes with a 'pickle:' prefix; when both fail it raises this SerializationError. It usually means the object holds unpicklable state such as open file handles, sockets, threads, locks, lambdas, or modules.","triggerScenarios":"Calling append_answer, model_dump_json, render_as_markdown, log_messages, send_variables, or _serialize_with_fallback with an object containing non-picklable members (open files, sockets, DB connections, threading locks, lambdas, module references) after json-safe conversion already failed.","commonSituations":"Saving agent logs/traces where a Tool instance or action output holds a live resource (open file, requests.Session, boto3 client); lambdas stored in tool outputs; objects with __slots__ missing __getstate__; objects referencing sys.modules internals.","solutions":["Find the unpicklable attribute (run pickle.dumps on suspected fields individually) and remove/replace it before serializing","Convert the object to plain dict/list/str primitives (e.g. define to_dict() or __json_safe__ conversion) before passing it","For resources like files/sessions, store a serializable descriptor (path, config) instead of the live object","As a last resort, sanitize the object (del/None out locks, sockets) before serialization"],"exampleFix":"# before\nresult = {\"model\": my_agent.model, \"session\": requests.Session()}\nSafeSerializer.dumps(result)  # Cannot serialize object\n\n# after\nresult = {\"model\": str(my_agent.model), \"session\": None}\nSafeSerializer.dumps(result)","handlingStrategy":"validation","validationCode":"import pickle\n\ndef is_serializable(obj) -> bool:\n    try:\n        pickle.dumps(obj)\n        return True\n    except Exception:\n        return False\n\n# before dumps(): assert is_serializable(payload) or sanitize it","typeGuard":"def is_json_safe(v) -> bool:\n    return v is None or isinstance(v, (str, int, float, bool, list, dict)) and (not isinstance(v, dict) or all(is_json_safe(x) for x in v.values())) and (not isinstance(v, list) or all(is_json_safe(x) for x in v))","tryCatchPattern":"from smolagents.serialization import SerializationError\ntry:\n    SafeSerializer.dumps(payload)\nexcept SerializationError:\n    payload = sanitize(payload)  # replace live resources with descriptors\n    SafeSerializer.dumps(payload)","preventionTips":["Never store open files, sessions, sockets, locks, or lambdas in objects you will serialize","Define to_dict()/__state__ helpers converting objects to primitives before logging/saving","Unit-test round-trip (dumps→loads) for every payload type you persist"],"tags":["serialization","pickle","smolagents"],"backgroundTag":"object-not-serializable","analyzedSha":"30bb1161095dbae2271e6bc3cc4c219cc3897a57","analyzedAt":"2026-08-28T18:52:54.169Z","schemaVersion":2},"datasetVersion":"2026-08-28T21:17:43.275Z"}