Skip to content

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

Closed
pcbeingused33 wants to merge 1 commit into
genkit-ai:mainfrom
pcbeingused33:fix/to-json-attr-nested-models
Closed

pcbeingused33 wants to merge 1 commit into
genkit-ai:mainfrom
pcbeingused33:fix/to-json-attr-nested-models

Conversation

@pcbeingused33

Copy link
Copy Markdown
Contributor

Fixes #80

Cause. to_json_attr only handled a BaseModel at the top level. When an action or flow takes or returns a container holding models (e.g. list[Reservation], dict[str, Reservation]), json.dumps raised TypeError and the function fell back to str(value), so the input/output span attributes held a Python repr instead of valid 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. Anything else still raises TypeError, so the existing str() fallback is unchanged.

Test. Added tests in instrumentation_test.py: nested models in a list and a dict round-trip through json.loads (with aliases and None fields dropped), and an unserializable object still falls back to str(). The first fails on main and passes with the fix.

This PR was prepared with AI assistance (Claude Code); the change and its tests were reviewed before submission.

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 genkit-ai#80
@genkit-bot

Copy link
Copy Markdown

Thanks for your interest in Genkit. We're closing this pull request because we can't accept it in its current form. If you'd like to contribute, please start a discussion with the maintainers on an issue first; see CONTRIBUTING.md.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix(core): serialize nested BaseModel instances in to_json_attr

3 participants