Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 6 additions & 3 deletions src/google/adk/telemetry/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -116,11 +116,14 @@ def _safe_json_serialize(obj) -> str:
The JSON-serialized object string or <non-serializable> if the object cannot be serialized.
"""

def _default(o: Any) -> Any:
if isinstance(o, BaseModel):
return o.model_dump(mode='json')
return '<not serializable>'

try:
# Try direct JSON serialization first
return json.dumps(
obj, ensure_ascii=False, default=lambda o: '<not serializable>'
)
return json.dumps(obj, ensure_ascii=False, default=_default)
Comment on lines +119 to +126
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

This correctly handles Pydantic model serialization. To improve reusability and fix a similar issue in another file, I suggest extracting the _default logic into a module-level function, for example _pydantic_json_default.

# At module level in tracing.py
def _pydantic_json_default(o: Any) -> Any:
  if isinstance(o, BaseModel):
    return o.model_dump(mode='json')
  return '<not serializable>'

A nearly identical function, _safe_json_serialize_no_whitespaces in src/google/adk/telemetry/_experimental_semconv.py, still uses the old lambda and will also need this fix. Making the helper function module-level will allow you to import and reuse it there, avoiding code duplication.

Suggested change
def _default(o: Any) -> Any:
if isinstance(o, BaseModel):
return o.model_dump(mode='json')
return '<not serializable>'
try:
# Try direct JSON serialization first
return json.dumps(
obj, ensure_ascii=False, default=lambda o: '<not serializable>'
)
return json.dumps(obj, ensure_ascii=False, default=_default)
try:
# Try direct JSON serialization first
return json.dumps(obj, ensure_ascii=False, default=_pydantic_json_default)

except (TypeError, OverflowError):
return '<not serializable>'

Expand Down