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

Function safe_serialize

agentops/helpers/serialization.py:109–137  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

107
108
109def 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)

Callers 15

on_llm_startMethod · 0.90
on_llm_endMethod · 0.90
on_chain_startMethod · 0.90
on_chain_endMethod · 0.90
on_tool_endMethod · 0.90
on_agent_actionMethod · 0.90
on_agent_finishMethod · 0.90
on_chat_model_startMethod · 0.90
wrapperMethod · 0.90

Calls 1

model_to_dictFunction · 0.70

Used in the wild real call sites across dependent graphs

searching dependent graphs…