Dynamic Output
Dynamic output lets an agent author, persist, and immediately activate its own Pydantic output model during a run.
DynamicOutput is for open-ended tasks where the output schema is discovered while the agent works and should survive across runs as a plain Python module. For fixed schemas known before the run starts, see Output.
While Pydantic AI Harness is on 0.x releases, the API may change between minor releases; when it does, deprecation warnings and release-note migration guidance tell you (or your agent) exactly how to upgrade. See the version policy.
flowchart TB
accTitle: Dynamic Output: the agent authors and activates its own Pydantic output model
accDescr: In a run, the model calls author_output_schema(name, json_schema) on DynamicOutput(directory=...). The capability lints the JSON Schema, compiles it into a Pydantic v2 module saved as a versioned Python file with manifest.json, and returns the Python source. On the next step of the same run, prepare_output_tools rewrites the placeholder output tool to match the active model and validates the final output into an instance of that model. Downstream agents can also load the active model via active_output_type(workspace).
subgraph run["Agent run"]
model(["model"])
cap["DynamicOutput(directory=...)<br/>author_output_schema(name, json_schema)"]:::capability
out["rewritten output tool<br/>validates into authored BaseModel"]:::capability
end
files["<directory>/<name>.v<n>.py<br/>manifest.json"]
downstream["downstream agent<br/>await dynamic_output.active_output_type(workspace)"]
model <-->|"author schema, get Python source"| cap
cap -->|"lint, compile, save version"| files
files -->|"active schema"| out
model -->|"final_result(...)"| out
files -->|"active BaseModel class"| downstream
classDef capability stroke:#E520E9,stroke-width:2px
Install the dynamic-output extra (datamodel-code-generator and jsonschema):
pip install "pydantic-ai-harness[dynamic-output]"
uv add "pydantic-ai-harness[dynamic-output]"
Loading already-generated models through await dynamic_output.active_output_type(workspace) needs no extra dependencies beyond Pydantic.
Structured-output agents normally fix output_type before the run starts. When the shape of the answer depends on unfamiliar inputs (a rubric, an unseen dataset, or an evolving research deliverable), falling back to an untyped StructuredDict drops validation and leaves nothing reusable for later runs.
DynamicOutput exposes three tools:
author_output_schema(name, json_schema): lint the draft JSON Schema (valid JSON Schema, root'type': 'object', no external$ref/$dynamicRefor extension keywords, plus non-blocking warnings for missingtitle/description/required), compile it into a Pydantic v2BaseModel, check and import the module, persist it as<name>.v<version>.py, mark it as the single'active'model inmanifest.json(marking any previously active entry'inactive'), and return the generated Python source. Lint, codegen, AST, and name errors surface asModelRetry.list_output_schemas(): list every authored version with its status (activeorinactive), class name, module filename, and any load error.deactivate_output_schema(name): deactivate this run’s active schema if its name matchesname(leaving any newer schema authored by another concurrent run active on disk).
To end the same run with the newly authored model, attach dynamic_output.placeholder_output_type() (a ToolOutput[BaseModel] slot bound to that instance) to the agent’s output_type:
from pathlib import Path
from pydantic_ai import Agent
from pydantic_ai.capabilities import LocalWorkspace
from pydantic_ai_harness import DynamicOutput
dynamic_output = DynamicOutput(directory=Path('.output_models'))
agent = Agent(
'anthropic:claude-sonnet-5-5',
capabilities=[LocalWorkspace('.'), dynamic_output],
output_type=[str, dynamic_output.placeholder_output_type()],
)
directory is a path on the machine running the agent, relative to the process’s current directory, not a workspace path, and it must have 'operator' authority in the run’s workspace (see Trust boundary).
DynamicOutput contributes static, cache-stable system-prompt guidance explaining these tools. Leave guidance=None for the default text, pass a custom string, or set guidance='' to omit it.
dynamic_output.placeholder_output_type()returns aToolOutput[BaseModel]slot bound to thatDynamicOutputinstance, so its static type matches the authoredBaseModelinstance returned at runtime and tool output mode is guaranteed even on providers that default to native structured output. Passname=...to customize the tool name when pairing with other structured output types.DynamicOutputonly touches placeholder output tools created byplaceholder_output_type(); any other output types on the agent (fixed models, text, deferred tools) are left unchanged.- While no authored model is active, the placeholder tool is hidden so it cannot be submitted prematurely.
- Once a model is active, the model sees the authored model’s
snake_caseJSON Schema. Validation errors turn into normal core output retries, and other capabilities’ output hooks continue to run. - Active-schema state is isolated per run: each run reads
manifest.jsononce at its start, and subsequentauthor_output_schemaordeactivate_output_schemacalls update only that run’s in-flight output slot while persisting changes for future runs. DynamicOutputlayers on tool output mode viaplaceholder_output_type(). It does not rewriteNativeOutputorPromptedOutput, which have no output tools.
Every authored version is saved as <directory>/<name>.v<version>.py and indexed by a sibling manifest.json written atomically (temp file plus os.replace). The store holds at most one active output schema at a time: authoring any schema (a new version of the same name or a different name) marks any previously active entry 'inactive'. Re-authoring under the same name (case-insensitively normalized to snake_case, so 'Grading' and 'grading' evolve the same series) creates v2, v3, and so on without overwriting earlier versions.
Because each version is a plain Python module, you can read, diff, and hand-edit it on disk. The in-process module cache is keyed on (resolved_path, mtime_ns, size), so edits are picked up on the next load. If an edited active module fails to import or validate, last_error is recorded in manifest.json and OutputModelError is raised; fixing the file clears last_error.
An unreadable manifest.json is treated as empty on reads, while writes (author, deactivate) raise UserError instead of replacing it. Concurrent updates in one process share a per-directory lock; separate processes are not coordinated.
To reuse the active model in another agent without attaching DynamicOutput:
from pathlib import Path
from pydantic_ai import Agent
from pydantic_ai.workspaces import LocalWorkspaceBackend
from pydantic_ai_harness import DynamicOutput
async def run_downstream() -> None:
workspace = LocalWorkspaceBackend('.')
dynamic_output = DynamicOutput(directory=Path('.output_models'))
output_model = await dynamic_output.active_output_type(workspace)
if output_model is not None:
downstream = Agent('anthropic:claude-sonnet-5-5', output_type=output_model)
await downstream.run('Grade this submission.')
Under durable execution, each authoring, listing, deactivation, active-schema lookup, and module-source read for output validation runs as a durable operation named under the capability’s id (default 'dynamic_output'), so recovery and workflow replay reuse recorded results and reconstruct the authored model from recorded source without touching disk.
DynamicOutput imports generated and hand-edited .py modules from directory into the agent’s own process on this machine. A run therefore refuses to start unless its workspace is a writable LocalWorkspace that grants directory (and its resolved symlink target) 'operator' authority, and each selected .py module file (and its symlink target) is also checked for 'operator' authority before import:
- A sandbox workspace, a read-only workspace, or no workspace is refused.
- A workspace with
authority='user'orauthority='none'is refused unlesspath_authoritygivesdirectory(and the module file)'operator'. - A directory outside the workspace’s working directory has
'none'authority and must be named explicitly inpath_authority.
With defer_loading=True, the same checks run before each authoring tool call, in prepare_output_tools, and in wrap_output_validate.
await dynamic_output.active_output_type(workspace) enforces the same directory and module-file workspace checks before importing anything; OutputModelStore does not expose an unchecked model-loading method.
Code generation embeds model-controlled JSON Schema strings into Python source that is then executed in-process. To narrow that surface:
- External
$refand$dynamicRefpointers (anything not starting with'#') and extension keywords (x-*,customTypePath,customBasePath) are rejected at the lint gate beforedatamodel-code-generatorruns. datamodel-code-generatorruns withuntrusted_input=True,allow_remote_refs=False, andformatters=[Formatter.BUILTIN].- Generated Python source is verified against a declarative AST allowlist before execution.
These checks defend against schema-driven codegen escapes, but in-process Python execution is not a sandbox.
If the agent also has FileSystem or Shell tools that can write to directory, it can edit generated .py files directly and execute arbitrary Python on the next load. Workspace path_authority does not restrict file or shell tools; keep directory unreachable from those tools (for example, outside a FileSystem root or matched by its deny patterns, and without an unrestricted Shell tool). A ToolGuardrail on author_output_schema gates only schema-authoring calls, not direct file or shell edits.
DynamicOutput holds a live disk-backed store and opts out of agent spec serialization (get_serialization_name() returns None).
DynamicOutput emits no spans of its own. Core’s tool spans record author_output_schema, list_output_schemas, and deactivate_output_schema calls (including linting, codegen, and module validation inside author_output_schema), and core’s output-tool execution span records submissions against the rewritten output tool.
Bases: AbstractCapability[AgentDepsT]
Let an agent author, persist, and immediately activate its own Pydantic output model.
Exposes author_output_schema(name, json_schema), list_output_schemas, and
deactivate_output_schema. Authoring lints the JSON Schema, compiles it into a plain
Pydantic v2 module (<name>.v<version>.py) indexed by manifest.json, verifies the
generated AST before execution, returns the generated Python source, and activates the
model immediately for this run (each run stays isolated from concurrent runs, while
changes persist for future runs).
To end the same run with the newly authored model, attach dynamic_output.placeholder_output_type()
(a ToolOutput[BaseModel] slot bound to this instance) to the agent’s output_type:
from pathlib import Path
from pydantic_ai import Agent
from pydantic_ai.capabilities import LocalWorkspace
from pydantic_ai_harness import DynamicOutput
dynamic_output = DynamicOutput(directory=Path('.output_models'))
agent = Agent(
'anthropic:claude-sonnet-5-5',
capabilities=[LocalWorkspace('.'), dynamic_output],
output_type=[str, dynamic_output.placeholder_output_type()],
)
Only this instance’s placeholder slot is touched; any other output types on the agent are left unchanged. While no authored model is active for the run, the placeholder slot is hidden so it cannot be submitted prematurely. Once active, the placeholder slot exposes the authored model’s schema, validation errors surface as normal output retries, and other capabilities’ output hooks remain intact.
Because generated and hand-edited .py modules in directory are imported into the agent’s
own process, runs, authoring tools, output validation, and
await dynamic_output.active_output_type(workspace) require a writable LocalWorkspace
granting 'operator' authority to directory and to each selected module file (and its
resolved symlink target).
Directory holding <name>.v<version>.py modules and manifest.json.
A path on the machine running the agent, relative to the process’s current directory,
not a workspace path. Must have 'operator' authority in the run’s workspace.
Type: Path
Static system-prompt guidance on authoring output schemas. Cache-stable.
Leave None for the default text, or set '' to omit guidance entirely.
Type: str | None Default: None
Stable identity for durable execution and duplicate-capability checks.
Type: str | None Default: 'dynamic_output'
The disk-backed store for authoring, listing, deactivating, and inspecting manifest records.
Type: OutputModelStore
def placeholder_output_type(*, name: str | None = None) -> ToolOutput[BaseModel]
Return a ToolOutput[BaseModel] slot bound to this DynamicOutput instance.
Include it in Agent(..., output_type=[str, dynamic_output.placeholder_output_type()]) (or as the
sole output_type). Its static type is BaseModel, matching the authored BaseModel instance
returned at runtime, and ToolOutput guarantees tool output mode even on providers that default
to native structured output.
ToolOutput[BaseModel]
@classmethod
def combine(
cls,
capabilities: Sequence[AbstractCapability[AgentDepsT]],
) -> AbstractCapability[AgentDepsT]
Two under one id are one configuration stated twice; two that disagree raise rather than merge.
AbstractCapability[AgentDepsT]
@async
def for_run(ctx: RunContext[AgentDepsT]) -> DynamicOutput[AgentDepsT]
Return a per-run clone so active-schema changes in one run cannot affect concurrent runs.
DynamicOutput[AgentDepsT]
@async
def active_output_type(workspace: WorkspaceBackend) -> type[BaseModel] | None
Return the active authored type[BaseModel] after verifying workspace grants operator authority.
@async
def before_run(ctx: RunContext[AgentDepsT]) -> None
Check optional dependencies, workspace trust boundary, and capture the starting active model.
@async
def before_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs,
) -> ValidatedToolArgs
Re-check dependencies and workspace boundary when loaded lazily via defer_loading=True.
ValidatedToolArgs
@async
def after_tool_execute(
ctx: RunContext[AgentDepsT],
*,
call: ToolCallPart,
tool_def: ToolDefinition,
args: ValidatedToolArgs,
result: Any,
) -> Any
Update this run’s pinned active model from authoring tools and execute run-scoped deactivation.
def get_instructions() -> AgentInstructions[AgentDepsT] | None
Static, cache-stable guidance on the output-schema authoring tools.
AgentInstructions[AgentDepsT] | None
def get_toolset() -> AgentToolset[AgentDepsT] | None
Toolset providing the schema-authoring tools over this capability’s store.
AgentToolset[AgentDepsT] | None
@async
def prepare_output_tools(
ctx: RunContext[AgentDepsT],
tool_defs: list[ToolDefinition],
) -> list[ToolDefinition]
Hide placeholder output tools until active; rewrite only placeholder tools, leaving all others intact.
@async
def wrap_output_validate(
ctx: RunContext[AgentDepsT],
*,
output_context: OutputContext,
output: RawOutput,
handler: WrapOutputValidateHandler,
) -> Any
Bind the active authored BaseModel around core’s placeholder validation so all hooks stay intact.
@classmethod
def get_serialization_name(cls) -> str | None
Not spec-serializable: the capability holds a live, disk-backed store.
Read/write versioned store of <name>.v<version>.py output models under directory.
def author(name: str, json_schema: Mapping[str, object]) -> AuthoredOutputModel
Lint, compile, validate, persist, and activate a new version of name.
The store keeps at most one active output model at a time: authoring any schema
(whether a new version of the same name or a different name) marks any previously
active entry 'inactive'. Raises ValueError for an invalid name, OutputModelError
for blocking lint, code-generation, or load errors, and UserError if manifest.json
cannot be read. Failed drafts do not write a file, bump the version, or deactivate the
current model.
AuthoredOutputModel
def deactivate(name: str | None = None, *, module_file: str | None = None) -> bool
Mark the active output schema (or the named / specific-file active schema) as 'inactive'.
Returns whether an active schema was deactivated.
def list_all() -> list[OutputModelRecord]
Return every manifest entry in insertion order.
list[OutputModelRecord]
def active_record() -> OutputModelRecord | None
Return the currently active manifest entry, or None when none is active.
OutputModelRecord | None