Convert a model object to a dictionary safely. Handles various model types including: - Pydantic models (model_dump/dict methods) - Dictionary-like objects - API response objects with parse method - Objects with __dict__ attribute Args: obj: The model object to conv
(obj: Any)
| 73 | |
| 74 | |
| 75 | def model_to_dict(obj: Any) -> dict: |
| 76 | """Convert a model object to a dictionary safely. |
| 77 | |
| 78 | Handles various model types including: |
| 79 | - Pydantic models (model_dump/dict methods) |
| 80 | - Dictionary-like objects |
| 81 | - API response objects with parse method |
| 82 | - Objects with __dict__ attribute |
| 83 | |
| 84 | Args: |
| 85 | obj: The model object to convert to dictionary |
| 86 | |
| 87 | Returns: |
| 88 | Dictionary representation of the object, or empty dict if conversion fails |
| 89 | """ |
| 90 | if obj is None: |
| 91 | return {} |
| 92 | if isinstance(obj, dict): |
| 93 | return obj |
| 94 | if hasattr(obj, "model_dump"): # Pydantic v2 |
| 95 | return obj.model_dump() |
| 96 | elif hasattr(obj, "dict"): # Pydantic v1 |
| 97 | return obj.dict() |
| 98 | # TODO this is causing recursion on nested objects. |
| 99 | # elif hasattr(obj, "parse"): # Raw API response |
| 100 | # return model_to_dict(obj.parse()) |
| 101 | else: |
| 102 | # Try to use __dict__ as fallback |
| 103 | try: |
| 104 | return obj.__dict__ |
| 105 | except: |
| 106 | return {} |
| 107 | |
| 108 | |
| 109 | def safe_serialize(obj: Any) -> Any: |
searching dependent graphs…