Structured output
Coming soonPass a Pydantic model as response_format= and the reply comes back parsed, on RunResult.output
rather than only as text.
from pydantic import BaseModel
class City(BaseModel):
name: str
country: str
result = await agent.run("Where is the Eiffel Tower?", response_format=City)
print(result.output) # -> City(name="Paris", country="France")output is populated only when you passed response_format=, and is None otherwise.
result.text still carries the raw reply either way.
Where it applies
| Call | Scope | Parsed for you |
|---|---|---|
agent.run(..., response_format=M) | that one run | yes, on RunResult.output |
create_session(response_format=M), in-process | every turn of the session | no |
create_session(response_format=M), deployment-backed | rejected | n/a |
On a session the schema goes into the session's agent configuration, so it constrains every turn,
but a session streams events rather than returning a RunResult and does not parse the reply for
you. A deployment-backed session refuses the argument outright with
UnsupportedSessionProcedureError, because it uses the completion config pinned in its deployed
agent. See Sessions.
An agent turn does not always end with a response that matches the schema. Then agent.run()
raises RuntimeError. To make the agent correct its response, use
StructuredOutputHook.
See also
- The Agent -
run()andRunResult. - Enforce structured output with a hook - use
pattern.hook.StructuredOutputHookto validate final JSON and retry invalid responses. - Sessions - why a deployment-backed session refuses this argument.