Skip to content

Commit 51d1acb

Browse files
severinhDouweM
andauthored
Support strict mode in NativeOutput (#2084)
Co-authored-by: Douwe Maan <douwe@pydantic.dev>
1 parent 90fc3fd commit 51d1acb

File tree

3 files changed

+17
-0
lines changed

3 files changed

+17
-0
lines changed

pydantic_ai_slim/pydantic_ai/_output.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ def build(
182182
_flatten_output_spec(output_spec.outputs),
183183
name=output_spec.name,
184184
description=output_spec.description,
185+
strict=output_spec.strict,
185186
)
186187
)
187188
elif isinstance(output_spec, PromptedOutput):

pydantic_ai_slim/pydantic_ai/output.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,17 +154,21 @@ class NativeOutput(Generic[OutputDataT]):
154154
"""The name of the structured output that will be passed to the model. If not specified and only one output is provided, the name of the output type or function will be used."""
155155
description: str | None
156156
"""The description of the structured output that will be passed to the model. If not specified and only one output is provided, the docstring of the output type or function will be used."""
157+
strict: bool | None
158+
"""Whether to use strict mode for the output, if the model supports it."""
157159

158160
def __init__(
159161
self,
160162
outputs: OutputTypeOrFunction[OutputDataT] | Sequence[OutputTypeOrFunction[OutputDataT]],
161163
*,
162164
name: str | None = None,
163165
description: str | None = None,
166+
strict: bool | None = None,
164167
):
165168
self.outputs = outputs
166169
self.name = name
167170
self.description = description
171+
self.strict = strict
168172

169173

170174
@dataclass(init=False)

tests/test_agent.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
from pydantic_ai import Agent, ModelRetry, RunContext, UnexpectedModelBehavior, UserError, capture_run_messages
1616
from pydantic_ai._output import (
1717
NativeOutput,
18+
NativeOutputSchema,
1819
OutputSpec,
1920
PromptedOutput,
2021
TextOutput,
@@ -1513,6 +1514,17 @@ class CityLocation(BaseModel):
15131514
)
15141515

15151516

1517+
def test_native_output_strict_mode():
1518+
class CityLocation(BaseModel):
1519+
city: str
1520+
country: str
1521+
1522+
agent = Agent(output_type=NativeOutput(CityLocation, strict=True))
1523+
output_schema = agent._output_schema # pyright: ignore[reportPrivateUsage]
1524+
assert isinstance(output_schema, NativeOutputSchema)
1525+
assert output_schema.object_def.strict
1526+
1527+
15161528
def test_prompted_output_function_with_retry():
15171529
class Weather(BaseModel):
15181530
temperature: float

0 commit comments

Comments
 (0)