MCPcopy Create free account
hub / github.com/AgentOps-AI/agentops / model_to_dict

Function model_to_dict

agentops/helpers/serialization.py:75–106  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

73
74
75def 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
109def safe_serialize(obj: Any) -> Any:

Callers 9

wrapperMethod · 0.90
test_pydantic_modelsMethod · 0.90
test_parse_methodMethod · 0.90
test_dict_fallbackMethod · 0.90
safe_serializeFunction · 0.70

Calls 2

model_dumpMethod · 0.45
dictMethod · 0.45

Used in the wild real call sites across dependent graphs

searching dependent graphs…