Tool.model_dump() serializes the $defs parameter alias as 'defs' (nested-in-request dumps do not)
Found while reading Tool.Function.Parameters (defs is declared as Field(None, alias='') with populate_by_name=True).
Tool.model_dump() called directly emits the field name defs, not the JSON Schema key — but the same tool nested inside a `ChatRequest` and dumped through `chat()` emits correctly. Repro on main (35d9667, pydantic 2.14.2):
from ollama._types import Tool, ChatRequest
tool = {
'type': 'function',
'function': {
'name': 'find_items',
'parameters': {
'type': 'object',
'properties': {'item': {'$ref': '#/$defs/Item'}},
'required': ['item'],
'$defs': {'Item': {'type': 'object', 'properties': {'name': {'type': 'string'}}}},
},
},
}
t = Tool.model_validate(tool)
print(sorted(t.model_dump(exclude_none=True)['function']['parameters'].keys()))
# ['defs', 'properties', 'required', 'type'] <- leaked field name
cr = ChatRequest(model='x', messages=[{'role': 'user', 'content': 'y'}], tools=[tool])
print(sorted(cr.model_dump(exclude_none=True)['tools'][0]['function']['parameters'].keys()))
# ['$defs', 'properties', 'required', 'type'] <- correct through the request path
Anyone who serializes tools themselves (to build their own requests, cache them, or pass them to another client) gets a schema whose $ref targets (#/$defs/Item) point at a key that no longer exists.
The asymmetry seems to come from how pydantic-core serializes the nested model inside ChatRequest versus a top-level dump; I did not dig further than confirming the two paths differ.
Two fix shapes, for maintainers to weigh:
- Pin
pydantic>=2.11and setserialize_by_alias=TrueonParameters(smallest code, but raises the floor). - Keep the 2.9 floor and wrap-serialize
Parameters(amodel_serializer(mode='wrap')that renamesdefs→$\defs) or passby_alias=Trueat the requestmodel_dumpcall sites in_client.py(26 sites, and onlydefsis aliased among request models, so it is safe).
Happy to send a PR for whichever direction is preferred.
Hi! I have a small fix for this: a wrap serializer on Tool.Function.Parameters that renames defs to $defs, so direct Tool.model_dump() / model_dump_json() match the request path. It keeps the pydantic>=2.9 floor, and I added a regression test. Happy to open the PR if that direction works for you.
Nice — that's the constraint I ran into when offering the PR: the clean serialize_by_alias route needs pydantic>=2.11 while the repo floor is 2.9, and a wrap serializer on Tool.Function.Parameters sidesteps that while matching the request path exactly as you describe. Both options are laid out in the issue body; yours resolves the version-floor tradeoff, so if the maintainers are happy with the direction I'm glad to see it go ahead. (For whoever picks it up: the nested-in-request path already serializes `` correctly, so the regression test should pin both paths — direct dump leaks, nested dump doesn't.)