Skip to content

fix(core): serialize nested BaseModel instances in to_json_attr #80

Open

Description

@huangjeff5

Problem

to_json_attr in packages/genkit/src/genkit/_core/_telemetry/_instrumentation.py only checks isinstance(value, BaseModel) at the top level:

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

When an action or flow takes or returns a container holding BaseModel instances (e.g. list[Reservation] or dict[str, Reservation]), json.dumps(value) raises TypeError and to_json_attr falls back to str(value):

to_json_attr({'bookings': [Reservation(party_size=2)]})
# => "{'bookings': [Reservation(party_size=2, notes=None)]}"  (invalid JSON)

Fix

Pass a default handler to json.dumps that dumps BaseModel instances via model_dump(mode='json', by_alias=True, exclude_none=True) (matching _encode_json_value in genkit-otel from #39) before falling back to str.

Context: #39 (comment)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions