From db98f3fb795d167bf1b916be537c74a38e2c6604 Mon Sep 17 00:00:00 2001 From: Alex Date: Wed, 2 Dec 2026 02:42:54 -0400 Subject: [PATCH] fix(core): serialize nested BaseModel instances in to_json_attr to_json_attr only dumped a top-level BaseModel; a list or dict holding models made json.dumps raise TypeError and fell back to str(), producing invalid JSON in the input/output span attributes. Pass a default handler that dumps nested models with model_dump(mode='json', by_alias=True, exclude_none=True), matching _encode_json_value in genkit-otel. Fixes #80 --- .../_core/_telemetry/_instrumentation.py | 9 ++++++++- .../tests/genkit/core/instrumentation_test.py | 20 +++++++++++++++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py index 6c58c629..f14c5caf 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py @@ -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) diff --git a/packages/genkit/tests/genkit/core/instrumentation_test.py b/packages/genkit/tests/genkit/core/instrumentation_test.py index edfbbe3e..a62953a1 100644 --- a/packages/genkit/tests/genkit/core/instrumentation_test.py +++ b/packages/genkit/tests/genkit/core/instrumentation_test.py @@ -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 @@ -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})