Skip to content

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.

Source

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

The idea

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.

How this relates to Subagents

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:

ControlDynamicWorkflowSubAgents
Retries of the parent’s toolmax_retries, like other script tools such as CodeModetool_retries
Number of sub-agent runsmax_agent_calls, across the catalogSubAgent.max_calls, per delegate
Usage limits of one sub-agent runsub_agent_usage_limits, for every runSubAgent.usage_limits, per delegate
Shared usage accountingforward_usageforward_usage
Sub-agent modelinherit_model, for every runthe models menu and SubAgent.models

Installation

The script runs inside the Monty sandbox, so install the extra:

Terminal
pip install "pydantic-ai-harness[dynamic-workflow]"

Your first 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.

What the model does with 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.

Sub-agents can return structured data

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.

How results come back

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 printthat 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.

Choosing sub-agent models

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.

Keeping it safe: budgets

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.

max_agent_calls: an exact count

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 and forward_usage: bounding cost

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_usageCounterWhat the limit means
True (default)the parent’s usage is shared across the treea 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.
Falseeach sub-agent run counts on its ownper-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.

resource_limits: guarding the script itself

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.

Workflows do not nest

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.

Renaming a sub-agent: WorkflowAgent

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.

Adding sub-agents mid-run: reveal()

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.

Loading it only when needed: defer_loading

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.

What runs in the sandbox

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, and random. Import what you use. There is no filesystem or environment access.
  • No clock or randomness: datetime.datetime.now(), datetime.date.today(), time.time(), and unseeded random fail. time.sleep and asyncio.sleep really wait; with max_duration_seconds set, a script may sleep for at most that long in total.
  • asyncio.gather(...) takes positional awaitables but no keyword arguments, including return_exceptions=True. It runs sub-agents and asyncio.sleep calls concurrently, except in a DBOS workflow where a sub-agent carries DBOSDurability, 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.

Remote workers

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.

Running inside a Temporal workflow

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.

Running under other durable engines

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.

Scheduling sub-agent calls

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.

Observability

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.

Further reading

API reference

DynamicWorkflow

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.

Attributes

agents

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]]

tool_name

Name of the orchestration tool exposed to the model.

Type: str Default: 'run_workflow'

max_agent_calls

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

max_retries

Maximum retries for the orchestration tool (syntax/runtime errors count as retries).

Type: int Default: 3

forward_usage

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

inherit_model

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

sub_agent_usage_limits

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

resource_limits

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

call_scheduler

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

monty_sandbox

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)

Methods

reveal
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.

Returns

None

get_toolset
def get_toolset() -> DynamicWorkflowToolset[AgentDepsT]

Provide the orchestration toolset to the agent.

Returns

DynamicWorkflowToolset[AgentDepsT]

WorkflowAgent

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).

Attributes

agent

The sub-agent to run when the script calls this function.

Type: AbstractAgent[AgentDepsT, object]

name

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

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

resolved_name

The sandbox function name: the explicit name, else the agent’s name.

Type: str | None

resolved_description

The catalog description: the explicit description, else the agent’s own description.

An explicit empty string hides the agent’s own description.

Type: str | None

WorkflowCall

One sub-agent call a workflow script made, handed to a WorkflowCallScheduler.

Attributes

agent_name

The sandbox function name the script called.

Type: str

start

Runs the sub-agent and returns its output.

Type: Callable[[], Awaitable[object]]

WorkflowCallScheduler

Bases: Protocol

Decides when the sub-agent calls of one workflow script start.

DynamicWorkflow(call_scheduler=...) creates one for each run_workflow call.

Methods

run

@async

def run(call: WorkflowCall) -> object

Run one sub-agent call by awaiting call.start(), and return its output.

Returns

object

flush

@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.

Returns

None

WorkflowResourceLimits

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.

Attributes

max_duration_seconds

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

max_duration_secs

Deprecated: renamed to max_duration_seconds.

Type: float

max_memory

Maximum sandbox memory, in bytes.

Type: int

DynamicWorkflowToolset

Bases: AbstractToolset[AgentDepsT]

Single-tool toolset that runs sub-agent orchestration scripts in a Monty sandbox.

Attributes

agents

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]]

tool_name

Name of the tool exposed to the model.

Type: str Default: 'run_workflow'

max_agent_calls

Maximum total sub-agent runs per agent run (an exact, host-enforced ceiling).

Type: int Default: 50

max_retries

Maximum retries for the run_workflow tool (syntax/runtime errors count as retries).

Type: int Default: 3

forward_usage

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

inherit_model

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

sub_agent_usage_limits

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

resource_limits

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

call_scheduler

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

monty_sandbox

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)

toolset_id

Stable toolset id; defaults to the tool name.

Type: str | None Default: None

owning_capability

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

Methods

for_run

@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.

Returns

Self