Skip to content

fix(python): serialize Pydantic models with mode='json' in tool results - #2225

Merged
SteveSandersonMS merged 2 commits into
github:mainfrom
rinceyuan:fix/python-tool-result-serialization
Aug 3, 2026
Merged

fix(python): serialize Pydantic models with mode='json' in tool results#2225
SteveSandersonMS merged 2 commits into
github:mainfrom
rinceyuan:fix/python-tool-result-serialization

Conversation

@rinceyuan

@rinceyuan rinceyuan commented Aug 3, 2026

Copy link
Copy Markdown
Contributor

Summary

Fix Python tool handlers returning Pydantic models containing datetime, date, UUID, Decimal, Enum, or set fields being silently reported as failures.

Root cause

BaseModel.model_dump() defaults to mode="python", which keeps native Python types. json.dumps then fails on those values, and the error is surfaced as a generic tool failure.

Fix

Use model_dump(mode="json") so Pydantic converts model fields to JSON-safe values before json.dumps runs.

Test

Added test_pydantic_model_with_non_primitive_fields_is_serialized, covering the exact JSON representations of UUID, datetime, date, Decimal, Enum, and set fields.

This addresses the Pydantic-model case in #2203. Plain dictionaries containing native non-JSON types remain outside this focused change.

model_dump() defaults to mode='python', which leaves datetime, UUID,
Decimal, Enum and set as native Python objects. json.dumps then fails
on these, and the error is swallowed as a generic tool failure.

Use model_dump(mode='json') so Pydantic converts all fields to
JSON-safe types before serialization.

Closes github#2203
@rinceyuan
rinceyuan requested a review from a team as a code owner August 3, 2026 02:30
@rinceyuan

Copy link
Copy Markdown
Contributor Author

@microsoft-github-policy-service agree company=Microsoft

@rinceyuan

Copy link
Copy Markdown
Contributor Author

@SteveSandersonMS One-line Python fix + test. Tool results with datetime/UUID/Decimal/Enum were silently failing because model_dump() defaults to mode='python'. Tests pass.

Assert the JSON representation of date and datetime fields, cover set serialization, and fix import ordering for Ruff.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

@SteveSandersonMS SteveSandersonMS left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks

@SteveSandersonMS
SteveSandersonMS added this pull request to the merge queue Aug 3, 2026
Merged via the queue into github:main with commit 26b88ce Aug 3, 2026
38 checks passed
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.

2 participants