vibe.serialization

Safe JSON serialization utilities.

This module provides utilities for safely converting Python objects to JSON-serializable form, handling edge cases like: - Dataclasses and Pydantic models - Circular references (via max_depth) - Non-serializable objects (fallback to repr) - Message objects (via message_to_dict)

Usage

from vibe.serialization import safe_json_serialize

Convert any object to JSON-serializable form

data = safe_json_serialize(complex_object)

Then use json.dumps safely

json_str = json.dumps(data)

safe_json_serialize

safe_json_serialize(obj: object, max_depth: int = DEFAULT_SERIALIZATION_DEPTH) -> object

Convert any object to a JSON-serializable form.

Handles common Python types, dataclasses, Pydantic models, and Message objects. Falls back to repr() for truly non-serializable objects.

Parameters:
  • obj (object) –

    Any Python object to serialize

  • max_depth (int, default: DEFAULT_SERIALIZATION_DEPTH ) –

    Maximum recursion depth to prevent infinite loops (default: 10)

Returns:
  • object

    A JSON-serializable representation of the object:

  • object
    • Primitives: returned as-is
  • object
    • Lists/tuples/sets: converted to lists with elements serialized
  • object
    • Dicts: keys stringified, values serialized
  • object
    • Message objects: converted via message_to_dict
  • object
    • Pydantic models: converted via model_dump()
  • object
    • Objects with dict: converted via vars()
  • object
    • Other: converted via repr()

Examples:

>>> safe_json_serialize({"a": 1, "b": [2, 3]})
{'a': 1, 'b': [2, 3]}
>>> safe_json_serialize(UserMessage(content="hello"))
{'type': 'user', 'content': 'hello', 'is_auto_reply': False}
>>> safe_json_serialize(object())  # Falls back to repr
'<object object at 0x...>'

json_serialize_or_repr

json_serialize_or_repr(obj: object) -> str

Serialize object to JSON string, falling back to repr on failure.

This is a convenience function for cases where you need a string representation.

Parameters:
  • obj (object) –

    Any Python object

Returns:
  • str

    JSON string if serializable, repr() string otherwise