Implementation:BerriAI Litellm Safe JSON Dumps
| Attribute | Value |
|---|---|
| Sources | litellm/litellm_core_utils/safe_json_dumps.py |
| Domains | Serialization, Logging, Safety |
| Last Updated | 2026-02-15 16:00 GMT |
Overview
Provides a safe JSON serialization function that handles circular references, Pydantic models, and non-serializable objects without raising exceptions.
Description
The safe_dumps function recursively serializes any Python data structure to a JSON string, gracefully handling edge cases that would cause standard json.dumps to fail:
- Circular references -- Tracks object IDs in a
seenset and returns"CircularReference Detected"instead of entering infinite recursion. - Maximum depth -- Enforces a configurable recursion depth limit (default:
DEFAULT_MAX_RECURSE_DEPTH) and returns"MaxDepthExceeded"when exceeded. - Pydantic models -- Automatically calls
model_dump()onBaseModelinstances before serializing. - Sets and tuples -- Converts sets to sorted lists and tuples to tuples for JSON compatibility.
- Non-serializable objects -- Falls back to
str(obj), and if that also fails, returns"Unserializable Object".
This function is used extensively in logging and debugging paths where data structures may contain complex, nested, or self-referential objects.
Usage
Import safe_dumps whenever you need to serialize data for logging, error reporting, or debugging and cannot guarantee the data is cleanly serializable. It is a drop-in replacement for json.dumps that never raises.
Code Reference
Source Location
litellm/litellm_core_utils/safe_json_dumps.py (59 lines)
Signature
def safe_dumps(data: Any, max_depth: int = DEFAULT_MAX_RECURSE_DEPTH) -> str
Import
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
I/O Contract
safe_dumps
| Direction | Name | Type | Description |
|---|---|---|---|
| Input | data | Any |
Any Python data structure to serialize |
| Input | max_depth | int |
Maximum recursion depth (default: DEFAULT_MAX_RECURSE_DEPTH)
|
| Output | return | str |
JSON string representation; never raises an exception |
Usage Examples
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
# Normal serialization
data = {"model": "gpt-4", "messages": [{"role": "user", "content": "Hello"}]}
json_str = safe_dumps(data)
# '{"model": "gpt-4", "messages": [{"role": "user", "content": "Hello"}]}'
# Handles circular references
circular = {}
circular["self"] = circular
json_str = safe_dumps(circular)
# '{"self": "CircularReference Detected"}'
# Handles Pydantic models
from pydantic import BaseModel
class MyModel(BaseModel):
name: str
value: int
obj = MyModel(name="test", value=42)
json_str = safe_dumps({"result": obj})
# '{"result": {"name": "test", "value": 42}}'
# Handles non-serializable objects
import threading
data = {"lock": threading.Lock(), "count": 5}
json_str = safe_dumps(data)
# '{"lock": "<unlocked _thread.lock object at 0x...>", "count": 5}'
Related Pages
- BerriAI_Litellm_Sensitive_Data_Masker -- masks sensitive values before serialization
- BerriAI_Litellm_Dot_Notation_Indexing -- path-based access to nested structures that may be serialized with safe_dumps