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 @@ -140,12 +140,19 @@ def describe_value(value: object) -> str:
return f'{cls.__module__}.{cls.__qualname__}'


def _json_default(obj: object) -> object:
"""Dump BaseModel instances nested in containers; anything else is a TypeError."""
if isinstance(obj, BaseModel):
return obj.model_dump(mode='json', by_alias=True, exclude_none=True)
raise TypeError(f'Object of type {type(obj).__name__} is not JSON serializable')


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_default)
except (TypeError, ValueError):
return str(value)

Expand Down
20 changes: 20 additions & 0 deletions packages/genkit/tests/genkit/core/instrumentation_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,11 @@

from __future__ import annotations

import json
from collections.abc import Awaitable, Callable, Mapping

import pytest
from pydantic import BaseModel, Field

from genkit._core._action import Action
from genkit._core._telemetry import _instrumentation as core_instrumentation
Expand Down Expand Up @@ -425,3 +427,21 @@ async def run_in_new_span(
next: Callable[[SpanContext], Awaitable[object]],
) -> object:
return await next(RecordedSpan('backend'))


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


def test_to_json_attr_serializes_models_nested_in_containers() -> None:
value = {'bookings': [_Reservation(partySize=2)], 'by_id': {'a': _Reservation(partySize=4, notes='x')}}

assert json.loads(core_instrumentation.to_json_attr(value)) == {
'bookings': [{'partySize': 2}],
'by_id': {'a': {'partySize': 4, 'notes': 'x'}},
}


def test_to_json_attr_falls_back_to_str_for_unserializable_objects() -> None:
assert core_instrumentation.to_json_attr({'a': object}) == str({'a': object})