Dynamic Workflow
Coordinate sub-agents in parallel, chain their results, or retry them in one tool call. Use DynamicWorkflow when this coordination can run as Python rather than needing the orchestrator’s judgment after each step. On success, intermediate results stay out of the orchestrator’s context unless the script returns or prints them.
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 LR
accTitle: Dynamic Workflow: coordinate sub-agents with one script
accDescr: The orchestrator model calls run_workflow with one Python script, and DynamicWorkflow runs it in the Monty sandbox. The script starts two reviewer sub-agent runs in parallel, one for auth.py and one for parser.py, and their two reports stay in the sandbox. It passes both reports to a summarizer run and returns only the summary to the orchestrator model.
model(["orchestrator model"])
cap["DynamicWorkflow()<br/>Monty sandbox<br/>reports stay here"]:::capability
reviewers["reviewer x 2<br/>auth.py, parser.py<br/>in parallel"]:::external
summarizer["summarizer"]:::external
model -->|"run_workflow,<br/>one script"| cap
cap -->|"two tasks"| reviewers
reviewers -->|"two reports"| cap
cap -->|"both reports"| summarizer
summarizer -->|"summary"| cap
cap -->|"summary only"| model
classDef capability stroke:#E520E9,stroke-width:2px
classDef external stroke:#0E9C86,stroke-width:2px
classDef blocked stroke:#E5533D,stroke-width:2px,stroke-dasharray:4 3
DynamicWorkflow gives the orchestrator one tool, run_workflow. The model writes a Python script that runs in the Monty sandbox, with each named sub-agent available as an async function. Like Code Mode, it replaces repeated tool calls with code; unlike Code Mode, it calls whole agents rather than individual tools.
Use SubAgents for occasional delegations or when the parent needs to judge each result before continuing. Use DynamicWorkflow for scripted fan-out, chaining, voting, or retries. You can switch between them without changing the underlying agents. Start with SubAgents if you are unsure.
The controls they share cover the same ground at different levels. DynamicWorkflow budgets the whole catalog because one script fans out over it; SubAgents budgets each delegate because the parent picks one per call:
| Control | DynamicWorkflow | SubAgents |
|---|---|---|
| Retries of the parent’s tool | max_retries, like other script tools such as CodeMode | tool_retries |
| Number of sub-agent runs | max_agent_calls, across the catalog | SubAgent.max_calls, per delegate |
| Usage limits of one sub-agent run | sub_agent_usage_limits, for every run | SubAgent.usage_limits, per delegate |
| Shared usage accounting | forward_usage | forward_usage |
| Sub-agent model | inherit_model, for every run | the models menu and SubAgent.models |
The script runs inside the Monty sandbox, so install the extra:
pip install "pydantic-ai-harness[dynamic-workflow]"
uv add "pydantic-ai-harness[dynamic-workflow]"
Two sub-agents, one orchestrator:
from pydantic_ai import Agent
from pydantic_ai_harness import DynamicWorkflow
reviewer = Agent('openai:gpt-6.1-sol', name='reviewer', description='Reviews code for bugs.')
summarizer = Agent('openai:gpt-6.1-sol', name='summarizer', description='Summarizes findings.')
orchestrator = Agent(
'openai:gpt-6.1-sol',
capabilities=[DynamicWorkflow(agents=[reviewer, summarizer])],
)
Each agent’s name becomes its sandbox function name and must be a valid Python identifier. Its description tells the model when to call it.
The model can review two files concurrently, then summarize both reports:
import asyncio
reports = await asyncio.gather(
reviewer(task='Review auth.py for bugs:\n<file contents>'),
reviewer(task='Review parser.py for bugs:\n<file contents>'),
)
await summarizer(task='Summarize these review findings:\n' + '\n\n'.join(reports))
Call sub-agents with await and a keyword-only task. asyncio.gather runs calls concurrently (except in a DBOS workflow where a sub-agent carries DBOSDurability); the last expression supplies the tool result.
Each call is an isolated Agent.run with its own model loop, history, tools, and output. Include all required context in task: calls do not remember earlier runs. Each run costs tokens; use the budgets below to limit usage.
A sub-agent returns whatever its output_type produces. The default is a string, but give a sub-agent a Pydantic model and the script receives a dict:
from pydantic import BaseModel
class Score(BaseModel):
value: int
reason: str
critic = Agent('openai:gpt-6.1-sol', name='critic', description='Scores an answer 0-10.', output_type=Score)
Inside the script the model reads the fields by subscript, the way it would read a JSON object:
result = await critic(task='Score this answer: ...')
result['value'] # not result.value
The catalog the model sees renders each output type as a TypedDict, so it knows the fields and reads them by subscript on its own.
Sub-agent runs cannot pause for tool approval or a pending model response. The catalog omits DeferredToolRequests and PendingModelResponse; a sub-agent run that ends with either raises RuntimeError in the script. Pending requests are cancelled best effort; a batch is cancelled only when no other request in it is waiting.
The value of the script’s last expression becomes the tool result, so the script does not need to print() it.
| The script… | The model receives |
|---|---|
| ends in a value, no print | that value directly (or {} if it is None) |
| prints and ends in a value | {"output": "<printed text>", "result": <value>} |
prints and ends in None | {"output": "<printed text>"} |
print() is for debug logging; it stringifies, so let the last expression carry the real result.
By default each sub-agent uses the model it was constructed with. Set inherit_model=True when the host passes a per-run model override to the parent agent (for example from a /model command) and every sub-agent dispatch should follow that resolved parent model. Leave it False when a sub-agent is deliberately pinned to a different model.
A sub-agent is non-deterministic, costs tokens, and can fan out into more sub-agents. DynamicWorkflow gives you a hard count ceiling, token budgets, and a guard against runaway sandbox scripts.
DynamicWorkflow(agents=[...], max_agent_calls=50) # 50 is the default
A hard, host-enforced ceiling on the number of sub-agent runs in one parent run. It is one budget shared across every run_workflow call in that run, and it holds exactly even when the script fans out with asyncio.gather. When the budget runs out, the workflow stops calling sub-agents and returns a terminal result with bounded previews of up to the 20 most recent completed results. This is the only knob that bounds the number of runs exactly.
sub_agent_usage_limits is a UsageLimits applied to each sub-agent run. forward_usage controls whether the whole tree shares one usage counter:
forward_usage | Counter | What the limit means |
|---|---|---|
True (default) | the parent’s usage is shared across the tree | a tree-wide cap. Under concurrent fan-out it is best-effort: several sub-agents can pass the check before any of them adds to the count. |
False | each sub-agent run counts on its own | per-run limits. A per-run total_tokens_limit of T with max_agent_calls of N bounds the tree to roughly N * T tokens. |
Without sub_agent_usage_limits, sub-agents sharing the counter (forward_usage=True) run under the usage_limits you pass to the parent run(), so the parent’s budget bounds the whole tree. With forward_usage=False they fall back to Pydantic AI’s default request_limit of 50 per run. For an exact ceiling on the number of runs, use max_agent_calls.
These limits guard the orchestration script’s own memory, not the sub-agents it calls. The default backstop is 256 MB with no time limit. Printed output is collected separately with Monty’s 10 MiB default cap.
DynamicWorkflow(agents=[...], resource_limits={'max_duration_seconds': 30})
max_duration_seconds counts sandbox execution time, excluding waits for sub-agents. There is no default duration cap. A CPU-bound loop that never awaits is not stopped by sub-agent budgets and blocks the workflow thread under Temporal. Set max_duration_seconds to stop such loops. A partial limits dict overrides only the named caps. Pass 'unlimited' to remove sandbox resource limits; the separate 10 MiB print cap remains. max_duration_secs is the deprecated name of max_duration_seconds and still works, with a warning.
A sub-agent cannot start its own workflow: a sub-agent that has the DynamicWorkflow capability is not offered run_workflow while it runs inside a workflow. The practical rule: do not give the sub-agents in your catalog the DynamicWorkflow capability. They are the leaves of the orchestration, not orchestrators.
By default a sub-agent shows up under its own name and description. To give it a different name or description for one workflow without editing the agent itself, wrap it in a WorkflowAgent:
from pydantic_ai_harness.dynamic_workflow import WorkflowAgent
DynamicWorkflow(
agents=[
WorkflowAgent(
reviewer,
name='check',
description='Checks one code change and returns actionable review findings.',
),
],
)
Now the model calls check(task=...). Passing a bare agent is shorthand for wrapping it in a WorkflowAgent with no overrides.
The catalog is fixed when a run starts, which keeps it in the prompt-cache prefix across turns. To make a new sub-agent available during a run (say once a fixer agent has been provisioned), keep a reference to the DynamicWorkflow instance and call reveal():
workflow = DynamicWorkflow(agents=[reviewer])
orchestrator = Agent('openai:gpt-6.1-sol', capabilities=[workflow])
# later, from the host or from another tool:
workflow.reveal(fixer)
The new agent becomes callable on the next step, announced by an AgentRevealPart (a capability part whose agent_name field names the sub-agent) containing its signature. The tool description stays fixed to preserve the prompt-cache prefix. If compaction or a history processor removes the announcement, it is sent again.
reveal() is append-only. Missing names, invalid identifiers, reserved keywords, and collisions raise UserError immediately.
DynamicWorkflow carries a fair amount of instruction text, and most turns do not need it. Keep it collapsed to a one-line entry until the model actually loads it:
DynamicWorkflow(
agents=[reviewer, summarizer],
id='workflow',
defer_loading=True,
)
defer_loading=True needs a stable id. See on-demand capabilities for the full picture.
The script runs in Monty, a subset of Python. Knowing the edges matters:
- No third-party libraries.
- Importable standard-library modules include
sys,typing,asyncio,math,json,re,unicodedata,datetime,time, andrandom. Import what you use. There is no filesystem or environment access. - No clock or randomness:
datetime.datetime.now(),datetime.date.today(),time.time(), and unseededrandomfail.time.sleepandasyncio.sleepreally wait; withmax_duration_secondsset, a script may sleep for at most that long in total. asyncio.gather(...)takes positional awaitables but no keyword arguments, includingreturn_exceptions=True. It runs sub-agents andasyncio.sleepcalls concurrently, except in a DBOS workflow where a sub-agent carriesDBOSDurability, where sub-agent calls and sleeps run one at a time. Other task creation and wait APIs are unavailable.
Before a script runs it is statically type-checked against the sub-agent signatures. An ordinary, statically provable mistake such as a misspelled function, a positional task, or a wrong-typed argument costs one retry but no sub-agent budget or sandbox execution. Values typed as Any can reach runtime validation; they are still rejected before a sub-agent runs.
Set monty_sandbox to a Monty server’s root URL to run the orchestration script on a remote worker instead of a local subprocess:
from pydantic_ai import Agent
from pydantic_ai_harness import DynamicWorkflow
reviewer = Agent('openai:gpt-6.1-sol', name='reviewer', description='Reviews code for bugs.')
workflow = DynamicWorkflow(agents=[reviewer], monty_sandbox='https://sandbox.example.com')
It takes the same values as Code Mode’s monty_sandbox. A URL with a path, query, or fragment, or a pool passed instead of a function, raises a UserError when DynamicWorkflow is built. A URL connects without a key. To send credentials or set other pool options, pass a sync or async function returning a pydantic_monty.AsyncMontyRemote, such as logfire.agent_sandboxes for Logfire Agent Sandboxes:
import logfire
from pydantic_ai import Agent
from pydantic_ai_harness import DynamicWorkflow
logfire.configure()
reviewer = Agent('openai:gpt-6.1-sol', name='reviewer', description='Reviews code for bugs.')
workflow = DynamicWorkflow(agents=[reviewer], monty_sandbox=logfire.agent_sandboxes)
The function is called for each run_workflow call, and each script gets a new session. A URL’s pool has a per-turn transport deadline of max_duration_seconds plus 10 seconds, or none when no duration is set; a function’s pool uses its own request_timeout (10 seconds by default). Time spent waiting for sub-agents counts toward neither.
Only the script moves to the worker. Sub-agents and print output stay in your process. Use https:// unless the network is trusted: the connection carries the script, its sub-agent arguments, and their results.
Pool creation, connection, and session checkout errors propagate to the code calling the agent, since the model can’t fix sandbox configuration. A worker crash or lost connection ends the script and becomes a model retry that lists the completed sub-agent results; the original exception stays the retry’s cause. Any other host error, such as a call_scheduler whose flush raises, also propagates to your code, so its text never reaches the model. A time limit, including a pool’s request_timeout and a remote turn_timeout, asks the model to make the script do less work.
Under Temporal the script runs in workflow code, so the worker must be reachable whenever the workflow replays.
Attach TemporalDurability to the orchestrating agent alongside DynamicWorkflow, and to each sub-agent whose model requests should run as activities, then register every agent with its own AgentPlugin. The script runs in workflow code, like Code Mode’s run_code, and is re-executed during replay against the recorded sub-agent results. Unlike Code Mode, a max_duration_seconds you set still applies inside the workflow, so a script that runs close to it can stop at a different point on replay and cause a NondeterminismError.
When any sub-agent in the catalog carries DBOSDurability, the script’s sub-agent calls, and any
asyncio.sleep it gathers, run one at a time inside a DBOS workflow, so recovery replays each
call’s steps in order. An asyncio.gather over sub-agents then takes the sum of their run times
rather than the longest. A sub-agent that carries DBOSDurability checkpoints its model requests,
MCP tool calls, and tools decorated with @DBOS.step, DBOS checks the roles those @DBOS.step
tools require, and recovery runs on from its last checkpoint. Its other function tools run again on
recovery, so put side effects in @DBOS.step tools. A sub-agent without DBOSDurability keeps no
checkpoints, so recovery runs its model requests again.
When sub-agents carry AWSLambdaDurability, the calls a script makes before it next waits run as
branches of one Lambda parallel operation, so they still run concurrently and each keeps its own
checkpoints. Recovery returns each finished branch’s recorded output and resumes an unfinished one
from its checkpoints.
Under other engines, sub-agents run concurrently.
call_scheduler decides when the script’s sub-agent calls start. It is called with the run
context once per run_workflow call, and returns a WorkflowCallScheduler. Each call reaches its
run as a WorkflowCall carrying the sub-agent’s agent_name, and starts when run awaits
call.start(). Its flush is awaited each time the script waits on its calls, once every call
made before the wait has reached run. A durable engine integration can use this to register
every call of a batch, in the order the script made them, before any of them starts:
import asyncio
from pydantic_ai import Agent, RunContext
from pydantic_ai_harness.dynamic_workflow import DynamicWorkflow, WorkflowCall
class StartTogether:
def __init__(self) -> None:
self._held: list[asyncio.Future[None]] = []
async def run(self, call: WorkflowCall) -> object:
held = asyncio.get_running_loop().create_future()
self._held.append(held) # register `call.agent_name` with the engine here
await held
return await call.start()
async def flush(self) -> None:
for held in self._held:
held.set_result(None)
self._held.clear()
def start_together(ctx: RunContext[None]) -> StartTogether:
return StartTogether()
reviewer = Agent('openai:gpt-6.1-sol', name='reviewer', description='Reviews code for bugs.')
workflow = DynamicWorkflow(agents=[reviewer], call_scheduler=start_together)
A call only completes after run awaits its call.start(), so a scheduler that holds calls back
has to release them in flush. Under AWSLambdaDurability, the calls that have started when
flush returns run as one parallel operation, so a released call has to await call.start()
without suspending first: one that waits on something else first, such as a concurrency limit,
misses the operation and the script waits on it indefinitely. An exception that run raises
itself reaches the script as a RuntimeError naming only its type. Under DBOSDurability the
calls already start one at a time in dispatch order, and the call_scheduler factory is not called.
The Logfire trace is the best way to see what a workflow did. Each sub-agent run appears nested under the run_workflow span, and the span carries the exact code argument the model wrote, so you can read the script it actually ran. To watch sub-agent runs inside the one tool call, set event_stream_handler on each sub-agent Agent.
- Code Mode: the same sandbox, calling the agent’s own tools instead of sub-agents.
- Subagents: one-delegation-per-tool-call sub-agents, without the scripted choreography.
- Dynamic Workflows: feature that enabled the Bun rewrite (Pydantic): how
DynamicWorkflowbrings the pattern to any Pydantic AI agent. - Rewriting Bun in Rust (Bun): the same pattern at scale, via Claude Code’s dynamic workflows.
- Capabilities and on-demand capabilities.
Bases: AbstractCapability[AgentDepsT]
Capability that lets the model orchestrate named sub-agents from a Python script.
Instead of one sub-agent per tool call, the model writes a single Python script (run in a
Monty sandbox) that calls each sub-agent as an async function and composes the results: fan
out with asyncio.gather, chain one agent’s output into the next, vote, or loop until done.
from pydantic_ai import Agent
from pydantic_ai_harness.dynamic_workflow import DynamicWorkflow
reviewer = Agent('openai:gpt-5', name='reviewer', description='Review code for bugs.')
summarizer = Agent('openai:gpt-5', name='summarizer', description='Summarize findings.')
orchestrator = Agent(
'openai:gpt-5',
capabilities=[DynamicWorkflow(agents=[reviewer, summarizer])],
)
Each sub-agent runs isolated (its own message history) with the parent’s deps forwarded;
by default the parent’s usage accumulator is shared so the whole tree’s spend is tallied in
one place. Use max_agent_calls for a hard, host-enforced ceiling on sub-agent runs. Workflows
do not nest. Set defer_loading=True (with a stable id) to keep the tool out of the prompt
until the model loads the capability.
Sub-agents the orchestration script can call as async functions.
Read at construction only; later mutation of the passed sequence is ignored. A raw agent is
shorthand for WorkflowAgent(agent), using the agent’s own name and description; use a
WorkflowAgent entry for a per-use-site override. Use reveal() to add a sub-agent after
construction.
Type: Sequence[AbstractAgent[AgentDepsT, object] | WorkflowAgent[AgentDepsT]]
Name of the orchestration tool exposed to the model.
Type: str Default: 'run_workflow'
Maximum total sub-agent runs per agent run: an exact, host-enforced ceiling that holds even
under concurrent fan-out (unlike a parent usage_limits).
Type: int Default: 50
Maximum retries for the orchestration tool (syntax/runtime errors count as retries).
Type: int Default: 3
Share the parent run’s usage accumulator with sub-agents, tallying the whole tree’s
token and request spend in one place.
Unless sub_agent_usage_limits is set, sub-agents also run under the parent run’s
usage_limits, checked against the shared counter, so they bound the whole tree (best-effort
under concurrent fan-out). Use max_agent_calls for an exact ceiling on the number of runs.
Type: bool Default: True
Run every sub-agent with the parent run’s resolved model instead of its constructed model.
Use this when the host switches models per run (for example a /model command passing a
run-level model override); without it, catalog sub-agents keep the model they were constructed
with. Keep False to pin sub-agents to their own configured models.
Type: bool Default: False
UsageLimits applied to every sub-agent run, replacing the parent run’s limits or Pydantic AI’s default.
With forward_usage=False, a per-run total_tokens_limit of T plus max_agent_calls of
N bounds the tree to roughly N * T tokens (each run can overshoot by its final response,
since core checks token limits after a response arrives). With forward_usage=True the limit
is checked against the shared counter — a tree-wide cap, best-effort under concurrent fan-out.
None runs sub-agents under the parent run’s usage_limits with forward_usage=True, and
under Pydantic AI’s default (request_limit=50, no token limit) with forward_usage=False.
Type: UsageLimits | None Default: None
Sandbox limits guarding the orchestration script’s own memory.
None applies a 256 MB backstop with no execution-time cap; 'unlimited' removes all limits;
a WorkflowResourceLimits mapping is merged onto the backstop, overriding only the caps it
names. There is no default max_duration_seconds: Monty’s timer bounds in-sandbox execution time
and time awaiting sub-agents does not count against it, so set one only to guard a pure-CPU
while True loop.
Type: WorkflowResourceLimits | Literal[‘unlimited’] | None Default: None
Creates a WorkflowCallScheduler for each run_workflow call, to decide when its sub-agent calls start.
None starts each call as soon as the script makes it. A durable engine integration can use a
scheduler to hold the calls back until the script waits on them, then register them in the
order the script made them before starting them together. When a sub-agent runs under
DBOSDurability, the calls already run one at a time in that order, and the factory is not called.
Type: Callable[[RunContext[AgentDepsT]], WorkflowCallScheduler] | None Default: None
Where the orchestration script runs: an http://, https://, ws://, or wss:// URL of the server root, with no path, query, or fragment, which connects without a key, or a sync or async function that returns a pydantic_monty.AsyncMontyRemote, such as logfire.agent_sandboxes, called for each run_workflow call. Unset, scripts run locally.
Sub-agents and print output stay in your process. A URL’s pool gets a per-turn transport deadline of
max_duration_seconds plus 10 seconds, or none without one; a pool from a function uses its own
request_timeout. Time spent awaiting sub-agents counts toward neither.
Type: str | Callable[[], AsyncMontyRemote | Awaitable[AsyncMontyRemote]] | None Default: field(default=None, repr=False)
def reveal(agent: AbstractAgent[AgentDepsT, object] | WorkflowAgent[AgentDepsT]) -> None
Reveal a sub-agent on the next model step.
The sub-agent is announced to the model on the next step and becomes callable then; the
run_workflow description stays frozen at the agents present when the run started. Reveal
is append-only: a revealed sub-agent cannot be removed for the rest of the run. Its resolved
name must be a valid, unique sandbox function name, or this raises UserError at the call
site. If one DynamicWorkflow instance is shared across concurrent runs, reveal() reaches
all in-flight runs and joins the baseline catalog for runs that start afterwards.
def get_toolset() -> DynamicWorkflowToolset[AgentDepsT]
Provide the orchestration toolset to the agent.
DynamicWorkflowToolset[AgentDepsT]
Bases: Generic[AgentDepsT]
One sub-agent exposed to the orchestration script as an async function.
WorkflowAgent is the per-use-site override for when the agent’s own name
or description is not what this workflow should show, such as renaming the
sandbox function or re-describing the agent for this catalog. Passing a bare
agent to DynamicWorkflow(agents=[...]) is equivalent to WorkflowAgent(agent).
The sub-agent to run when the script calls this function.
Type: AbstractAgent[AgentDepsT, object]
Sandbox function name; must be a valid Python identifier and unique across the
workflow. Falls back to the agent’s name.
Type: str | None Default: None
Description shown to the model in the sub-agent catalog, rendered as the sandbox
function’s docstring. An explicit value, including '', overrides the agent’s own
description. When neither is set, the model sees only the bare signature.
Type: str | None Default: None
The sandbox function name: the explicit name, else the agent’s name.
The catalog description: the explicit description, else the agent’s own description.
An explicit empty string hides the agent’s own description.
One sub-agent call a workflow script made, handed to a WorkflowCallScheduler.
The sandbox function name the script called.
Type: str
Runs the sub-agent and returns its output.
Type: Callable[[], Awaitable[object]]
Bases: Protocol
Decides when the sub-agent calls of one workflow script start.
DynamicWorkflow(call_scheduler=...) creates one for each run_workflow call.
@async
def run(call: WorkflowCall) -> object
Run one sub-agent call by awaiting call.start(), and return its output.
@async
def flush() -> None
Called each time the script waits on its calls, once every call it made before the wait has reached run.
A call the script is waiting on only completes once run awaits its call.start(), so a
scheduler that holds calls back must release them here. A durable engine that batches the
calls, like AWSLambdaDurability, takes its batch right after this returns, so under one a
released call has to await call.start() without suspending first, or it misses the batch
and the script waits on it indefinitely.
Bases: TypedDict
Caps on the orchestration script’s own sandbox resources (not sub-agent latency).
A harness-owned view of the sandbox limits the capability supports, so the public API does not depend on the underlying sandbox’s own types. Every field is optional; an omitted field keeps its backstop value.
Ceiling on the time the script spends executing sandbox code. Monty checks it per bytecode
step, so time spent awaiting sub-agents does not count against it — neither a single await
nor a concurrent asyncio.gather batch, because during that wait the script is suspended on
the host, not running sandbox code. There is no default cap. Set one to bound a pure-CPU
while True loop, which would otherwise burn a core in the sandbox worker (and block the
workflow thread under Temporal) — the one runaway the sub-agent budgets do not catch.
Sleeping is not execution time either, so when set, the script may also sleep for up to this
long in total.
Type: float
Deprecated: renamed to max_duration_seconds.
Type: float
Maximum sandbox memory, in bytes.
Type: int
Bases: AbstractToolset[AgentDepsT]
Single-tool toolset that runs sub-agent orchestration scripts in a Monty sandbox.
Sub-agents callable from the orchestration script, each as an async function.
DynamicWorkflow.reveal() is the only supported way to add a sub-agent mid-run.
The toolset observes appends to this list as the reveal channel. Any entry that
arrives invalid is a contract violation that raises.
Type: list[WorkflowAgent[AgentDepsT]]
Name of the tool exposed to the model.
Type: str Default: 'run_workflow'
Maximum total sub-agent runs per agent run (an exact, host-enforced ceiling).
Type: int Default: 50
Maximum retries for the run_workflow tool (syntax/runtime errors count as retries).
Type: int Default: 3
Share the parent run’s usage accumulator with sub-agents. See
DynamicWorkflow.forward_usage for what is and is not forwarded.
Type: bool Default: True
Run every sub-agent with the parent run’s resolved model instead of its constructed model.
See DynamicWorkflow.inherit_model for when to use this.
Type: bool Default: False
UsageLimits applied to every sub-agent run, replacing the parent run’s limits or Pydantic AI’s default.
See DynamicWorkflow.sub_agent_usage_limits for the budgeting semantics.
Type: UsageLimits | None Default: None
Sandbox limits guarding the orchestration script’s own memory (not sub-agents).
See DynamicWorkflow.resource_limits for the None/'unlimited'/partial-dict semantics.
Type: WorkflowResourceLimits | Literal[‘unlimited’] | None Default: None
Creates the scheduler that decides when each script’s sub-agent calls start.
See DynamicWorkflow.call_scheduler.
Type: Callable[[RunContext[AgentDepsT]], WorkflowCallScheduler] | None Default: None
Where the orchestration script runs: a Monty server URL or a function that returns the remote pool.
See DynamicWorkflow.monty_sandbox.
Type: MontySandbox | None Default: field(default=None, repr=False)
Stable toolset id; defaults to the tool name.
Type: str | None Default: None
The DynamicWorkflow capability this toolset belongs to, when capability-provided.
Used to resolve whether the capability is visible to the model on the current step (deferred
and unloaded means hidden), by identity against the run’s capability registry — ids cannot be
used for this, because an id-less capability is registered under a run-generated key and a
wrapper capability is registered in place of what it wraps. None (a toolset used directly,
outside any capability) is always visible.
Type: AbstractCapability[AgentDepsT] | None Default: None
@async
def for_run(ctx: RunContext[AgentDepsT]) -> Self
Fresh instance per run so the sub-agent-call budget is per-run.
Clone shallowly, keeping agents shared so reveals stay visible to this run,
reset the per-run call budget, and rebuild the per-run index. Entries are
validated eagerly by DynamicWorkflow.__post_init__ and DynamicWorkflow.reveal(),
so a strict rebuild here cannot fail unless this list was mutated outside those
APIs. That is unsupported and fails fast.