From f285566db2b1236e4ae3eacdb919bc461cc9c511 Mon Sep 17 00:00:00 2001 From: kcncb <128760047+kcncb@users.noreply.github.com> Date: Wed, 18 Nov 2026 14:42:52 +0800 Subject: [PATCH] fix(core): serialize nested BaseModel instances in to_json_attr --- .../_core/_telemetry/_instrumentation.py | 8 ++- .../tests/genkit/core/to_json_attr_test.py | 51 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 packages/genkit/tests/genkit/core/to_json_attr_test.py diff --git a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py index 6c58c629..0bd73c45 100644 --- a/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py +++ b/packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py @@ -32,6 +32,7 @@ from typing import Any, Literal, Protocol, TypeVar, runtime_checkable from pydantic import BaseModel +from pydantic_core import to_jsonable_python from ._attrs import METADATA_PREFIX, Attr from ._log_exporter import reset_log_export @@ -140,12 +141,17 @@ def describe_value(value: object) -> str: return f'{cls.__module__}.{cls.__qualname__}' +def _json_default(obj: object) -> object: + """Encode leaves that json rejects: models, datetimes, UUIDs, bytes, dataclasses.""" + return to_jsonable_python(obj, by_alias=True, exclude_none=True, bytes_mode='base64', fallback=str) + + 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/to_json_attr_test.py b/packages/genkit/tests/genkit/core/to_json_attr_test.py new file mode 100644 index 00000000..9c7f34f0 --- /dev/null +++ b/packages/genkit/tests/genkit/core/to_json_attr_test.py @@ -0,0 +1,51 @@ +#!/usr/bin/env python3 +# +# Copyright 2026 Google LLC +# SPDX-License-Identifier: Apache-2.0 + +"""Nested models and other non-JSON leaves still serialize to valid JSON attributes.""" + +import json +from datetime import UTC, datetime + +from pydantic import BaseModel, ConfigDict, Field + +from genkit._core._telemetry._instrumentation import to_json_attr + + +class Reservation(BaseModel): + """Booking payload whose alias and optional field must survive encoding.""" + + model_config = ConfigDict(populate_by_name=True) + + party_size: int = Field(alias='partySize') + notes: str | None = None + + +def test_nested_model_in_dict_is_json() -> None: + """A dict holding models serializes through the alias and drops None.""" + encoded = to_json_attr({'bookings': [Reservation(partySize=2)]}) + assert json.loads(encoded) == {'bookings': [{'partySize': 2}]} + + +def test_list_of_models_is_json() -> None: + """A list of models is JSON, not a str() of the list.""" + encoded = to_json_attr([Reservation(partySize=3, notes='window')]) + assert json.loads(encoded) == [{'partySize': 3, 'notes': 'window'}] + + +def test_top_level_model_unchanged() -> None: + """A bare model keeps the existing compact model_dump_json output.""" + assert to_json_attr(Reservation(partySize=4)) == '{"partySize":4}' + + +def test_datetime_leaf_is_iso() -> None: + """Leaves the json module rejects, such as datetimes, encode as JSON scalars.""" + encoded = to_json_attr({'at': datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)}) + assert json.loads(encoded) == {'at': '2026-01-02T03:04:05Z'} + + +def test_unencodable_leaf_still_returns_string() -> None: + """Anything neither json nor pydantic can encode stays a readable string.""" + encoded = to_json_attr({'weird': object()}) + assert 'weird' in encoded