Safely serialize an object to JSON-compatible format This function handles complex objects by: 1. Returning strings untouched (even if they contain JSON) 2. Converting models to dictionaries 3. Using custom JSON encoder to handle special types 4. Falling back to string represent
(obj: Any)
| 107 | |
| 108 | |
| 109 | def safe_serialize(obj: Any) -> Any: |
| 110 | """Safely serialize an object to JSON-compatible format |
| 111 | |
| 112 | This function handles complex objects by: |
| 113 | 1. Returning strings untouched (even if they contain JSON) |
| 114 | 2. Converting models to dictionaries |
| 115 | 3. Using custom JSON encoder to handle special types |
| 116 | 4. Falling back to string representation only when necessary |
| 117 | |
| 118 | Args: |
| 119 | obj: The object to serialize |
| 120 | |
| 121 | Returns: |
| 122 | If obj is a string, returns the original string untouched. |
| 123 | Otherwise, returns a JSON string representation of the object. |
| 124 | """ |
| 125 | # Return strings untouched |
| 126 | if isinstance(obj, str): |
| 127 | return obj |
| 128 | |
| 129 | # Convert any model objects to dictionaries |
| 130 | if hasattr(obj, "model_dump") or hasattr(obj, "dict") or hasattr(obj, "parse"): |
| 131 | obj = model_to_dict(obj) |
| 132 | |
| 133 | try: |
| 134 | return json.dumps(obj, cls=AgentOpsJSONEncoder) |
| 135 | except (TypeError, ValueError) as e: |
| 136 | logger.warning(f"Failed to serialize object: {e}") |
| 137 | return str(obj) |
searching dependent graphs…