Skip to content
Closed
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
Expand Up @@ -139,12 +139,18 @@ def describe_value(value: object) -> str:
return f'{cls.__module__}.{cls.__qualname__}'


def _json_attr_default(obj: object) -> object:
if isinstance(obj, BaseModel):
return obj.model_dump(mode='json', by_alias=True, exclude_none=True)
return str(obj)


def to_json_attr(value: object) -> str:
"""Serialize an arbitrary object for an input/output span attribute."""
if isinstance(value, BaseModel):
return value.model_dump_json(by_alias=True, exclude_none=True)
try:
return json.dumps(value)
return json.dumps(value, default=_json_attr_default)
except (TypeError, ValueError):
return str(value)

Expand Down
29 changes: 29 additions & 0 deletions packages/genkit/tests/genkit/core/instrumentation_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -391,3 +391,32 @@ async def run_in_new_span(
next: Callable[[SpanContext], Awaitable[object]],
) -> object:
return await next(RecordedSpan('backend'))


def test_to_json_attr_serializes_nested_pydantic_models() -> None:
"""Containers holding BaseModel instances serialize as valid JSON with aliases and without nulls."""
import json

from pydantic import BaseModel, ConfigDict, Field

from genkit._core._telemetry._instrumentation import to_json_attr

class Reservation(BaseModel):
model_config = ConfigDict(populate_by_name=True)

party_size: int = Field(alias='partySize')
notes: str | None = None

encoded = to_json_attr({
'bookings': [
Reservation.model_validate({'partySize': 2}),
Reservation.model_validate({'partySize': 4, 'notes': 'patio'}),
]
})

assert json.loads(encoded) == {
'bookings': [
{'partySize': 2},
{'partySize': 4, 'notes': 'patio'},
]
}
Loading