Skip to content

Commit 9b34d6b

Browse files
dmontaguDouweM
andauthored
Retain defaults in non-strict openai schemas (#1519)
Co-authored-by: Douwe Maan <douwe@pydantic.dev>
1 parent a08a20e commit 9b34d6b

File tree

2 files changed

+16
-5
lines changed

2 files changed

+16
-5
lines changed

pydantic_ai_slim/pydantic_ai/profiles/openai.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,10 +93,18 @@ def walk(self) -> JsonSchema:
9393
def transform(self, schema: JsonSchema) -> JsonSchema: # noqa C901
9494
# Remove unnecessary keys
9595
schema.pop('title', None)
96-
schema.pop('default', None)
9796
schema.pop('$schema', None)
9897
schema.pop('discriminator', None)
9998

99+
default = schema.get('default', _sentinel)
100+
if default is not _sentinel:
101+
# the "default" keyword is not allowed in strict mode, but including it makes some Ollama models behave
102+
# better, so we keep it around when not strict
103+
if self.strict is True:
104+
schema.pop('default', None)
105+
elif self.strict is None: # pragma: no branch
106+
self.is_strict_compatible = False
107+
100108
if schema_ref := schema.get('$ref'):
101109
if schema_ref == self.root_ref:
102110
schema['$ref'] = '#'

tests/models/test_openai.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1095,7 +1095,10 @@ def tool_with_tuples(x: tuple[int], y: tuple[str] = ('abc',)) -> str:
10951095
'$defs': {
10961096
'MyDefaultRecursiveDc': {
10971097
'properties': {
1098-
'field': {'anyOf': [{'$ref': '#/$defs/MyDefaultRecursiveDc'}, {'type': 'null'}]}
1098+
'field': {
1099+
'anyOf': [{'$ref': '#/$defs/MyDefaultRecursiveDc'}, {'type': 'null'}],
1100+
'default': None,
1101+
}
10991102
},
11001103
'type': 'object',
11011104
},
@@ -1213,7 +1216,7 @@ def tool_with_tuples(x: tuple[int], y: tuple[str] = ('abc',)) -> str:
12131216
{
12141217
'$defs': {
12151218
'MyDefaultDc': {
1216-
'properties': {'x': {'type': 'integer'}},
1219+
'properties': {'x': {'default': 1, 'type': 'integer'}},
12171220
'type': 'object',
12181221
}
12191222
},
@@ -1253,7 +1256,7 @@ def tool_with_tuples(x: tuple[int], y: tuple[str] = ('abc',)) -> str:
12531256
{
12541257
'$defs': {
12551258
'MyDefaultDc': {
1256-
'properties': {'x': {'type': 'integer'}},
1259+
'properties': {'x': {'default': 1, 'type': 'integer'}},
12571260
'type': 'object',
12581261
}
12591262
},
@@ -1293,7 +1296,7 @@ def tool_with_tuples(x: tuple[int], y: tuple[str] = ('abc',)) -> str:
12931296
{
12941297
'$defs': {
12951298
'MyDefaultDc': {
1296-
'properties': {'x': {'type': 'integer'}},
1299+
'properties': {'x': {'default': 1, 'type': 'integer'}},
12971300
'type': 'object',
12981301
}
12991302
},

0 commit comments

Comments
 (0)