Add `TemporalDurability`, `DBOSDurability` and `PrefectDurability` capabilities to replace the deprecated wrapper agents

Merged
DO
5mo ago
+11151-1256

Summary

Introduces durability capabilities — TemporalDurability, DBOSDurability, and PrefectDurability — that you attach to an agent via capabilities=[...] instead of wrapping the agent.

from dbos import DBOS

from pydantic_ai import Agent
from pydantic_ai.durable_exec.dbos import DBOSDurability

agent = Agent(
    'openai:gpt-5.2',
    name='geography',
    capabilities=[DBOSDurability()],
)

@DBOS.workflow()
async def answer(prompt: str) -> str:
    # Inside the workflow, model requests and MCP communication
    # run as durable DBOS steps; outside one, the agent behaves
    # like a regular agent.
    result = await agent.run(prompt)
    return result.output

The capability makes the agent durable-capable; your workflow/flow decides which runs are durable. Same shape for Temporal (run inside a @workflow.defn, with activities registered on the worker via PydanticAIPlugin or DurabilityPlugin) and Prefect (run inside a @flow) — migration diffs below.

The existing TemporalAgent / DBOSAgent / PrefectAgent wrapper classes are deprecated in this PR (they emit DeprecationWarning and are slated for removal in v3). They keep working unchanged at runtime — port at your leisure.

Try it out

If you're already on a wrapper agent, the port is roughly a one-liner per agent. The capability constructors mirror the wrapper-agent constructors, minus the agent-introspection arguments (model, name, toolsets) that the capability discovers automatically when it's bound to the agent.

Temporal — replace the TemporalAgent wrap with a capability and (optionally) swap the worker plugin:

-from pydantic_ai.durable_exec.temporal import TemporalAgent
-temporal_agent = TemporalAgent(agent, models={'fast': fast_model})
+from pydantic_ai.durable_exec.temporal import TemporalDurability
+agent = Agent(
+    'openai:gpt-5.2',
+    name='geography',
+    capabilities=[TemporalDurability(models={'fast': fast_model})],
+)

 @workflow.defn
 class GeographyWorkflow(PydanticAIWorkflow):
-    __pydantic_ai_agents__ = [temporal_agent]
+    __pydantic_ai_agents__ = [agent]  # PydanticAIPlugin discovers TemporalDurability

     @workflow.run
     async def run(self, prompt: str) -> str:
-        result = await temporal_agent.run(prompt)
+        result = await agent.run(prompt)
         return result.output

If you used TemporalAgent's provider_factory= to wire runtime provider config (API keys, base URLs) into model strings, use a deps-aware [ResolveModelId][pydantic_ai.capabilities.ResolveModelId] capability instead — it runs inside the activity with the run's real deps, so it's strictly more capable (see "Model resolution across the durable boundary" below).

PydanticAIPlugin accepts both TemporalAgent and bare AbstractAgent (carrying a TemporalDurability) in __pydantic_ai_agents__. If you'd rather register activities directly on the worker, use DurabilityPlugin(agent) in place of AgentPlugin(temporal_agent).

DBOS — unlike DBOSAgent, which auto-wrapped run / run_sync as a DBOS workflow, DBOSDurability deliberately does not wrap the run: call agent.run() inside your own @DBOS.workflow (an intentional behavior change — the capability makes runs durable-capable; your workflow decides which runs are durable):

-from pydantic_ai.durable_exec.dbos import DBOSAgent
-dbos_agent = DBOSAgent(agent, parallel_execution_mode='parallel_ordered_events')
-result = await dbos_agent.run('hi')
+from pydantic_ai.durable_exec.dbos import DBOSDurability
+agent = Agent(
+    'openai:gpt-5.2',
+    name='geography',
+    capabilities=[DBOSDurability(parallel_execution_mode='parallel_ordered_events')],
+)
+
+@DBOS.workflow()
+async def answer(prompt: str) -> str:
+    result = await agent.run(prompt)
+    return result.output

Prefect — same shape: PrefectDurability does not auto-wrap the run as a @flow; wrap it yourself:

-from pydantic_ai.durable_exec.prefect import PrefectAgent
-prefect_agent = PrefectAgent(agent, tool_task_config=TaskConfig(retries=3))
-result = await prefect_agent.run('hi')
+from pydantic_ai.durable_exec.prefect import PrefectDurability
+agent = Agent(
+    'openai:gpt-5.2',
+    name='geography',
+    capabilities=[PrefectDurability(tool_task_config=TaskConfig(retries=3))],
+)
+
+@flow
+async def answer(prompt: str) -> str:
+    result = await agent.run(prompt)
+    return result.output

Full standalone examples live in docs/durable_execution/{temporal,dbos,prefect}.md under "Durability as a Capability".

Migration is replay-compatible

Activity/step names and payloads are identical between the wrapper and capability paths (as long as the agent's name and toolset ids stay the same), so Temporal workflows started under TemporalAgent replay correctly after switching to TemporalDurability — no need to drain or version workflows first. This is called out in the docs.

Why a capability instead of a wrapper agent?

  • Composes with other capabilities — durability is just another link in the capability chain, so it stacks cleanly with Instrumentation, ProcessEventStream, SetToolMetadata, and any user-defined capability without each one needing a wrapper-agent variant.
  • No frozen-at-wrap-time snapshot — the capability binds to the agent at attach time but reuses the live agent for model and toolset access, so changes to the agent surface naturally rather than requiring a re-wrap.
  • Hook-based — durability is wired up via the same capability hooks (wrap_run, wrap_model_request, wrap_run_event_stream, get_wrapper_toolset, resolve_model_id, …) any capability would use; no parallel agent-runtime hierarchy. A first-class extension point so third-party integrations don't have to subclass WrapperAgent / WrapperModel / WrapperToolset is tracked as a post-v2 RFC (#5477).

Built on #6333's model-resolution surface

The generic hooks the durability capabilities lean on landed separately: #6333 introduced the canonical resolve_model_id(ctx, *, model_id) hook (with ModelResolutionContext), the ResolveModelId capability, and the for_agent() binding lifecycle (the constructor model stays a raw string through binding whenever a resolver is attached, so resolvers always get the original string). This PR consumes that surface and adds the remaining core pieces durable execution needs:

  • RunContext.root_capability — exposes the capability chain to hooks so they can walk it. Used by TemporalDurability to detect capabilities added per-run (whose activities were never registered with the worker) and reject them with a clear error.
  • Innermost capability tier — durability capabilities declare CapabilityOrdering(position='innermost'), and agent construction binds capabilities in two phases so the innermost tier binds after the other capabilities have contributed their toolsets (its activity registration sees the complete toolset picture) and resolves last in the resolve_model_id chain (user resolvers win).
  • ModelRequestContext.model_id (public) — the model-name string this request's model was selected/resolved from, which can differ from the resolved model's own model_id (e.g. for models= aliases or custom resolvers). Durability reads it to serialize the right string across the activity boundary; re-deriving it from the resolved model would rebuild the wrong model on the worker.
  • CompletedStreamedResponse — hoisted from the Temporal integration into pydantic_ai.models as a shared building block: replays an already-completed ModelResponse as a stream, which is how run_stream() / iter() / run_stream_events() work inside a workflow (events buffered in the activity, replayed workflow-side). The old constructor argument order is deprecated with a warning.

Model resolution across the durable boundary

Model strings can't cross the workflow/activity boundary as Model instances, so resolution is split:

  • At binding time, only models= aliases resolve eagerly. Any other string default stays raw and defers to the worker.
  • On the worker (inside the activity), the full deps-aware resolve_model_id chain runs — custom ResolveModelId capabilities first (this is the provider_factory replacement, with access to the run's real deserialized deps), infer_model only as a last-resort backstop. Workflows can therefore accept arbitrary agent.run(model='...') strings without pre-registering them.
  • Per-step [ModelSelector][pydantic_ai.capabilities.SelectModel]s work: when a selector is active, the serialized id is derived from the actually-selected model rather than the run-level default.
  • Model instances: under Temporal, an instance passed at runtime is sent to the worker as its model_id string and rebuilt there — faithful for standard providers, but instances whose behavior depends on a custom client/provider/settings should be pre-registered in models=. Under DBOS and Prefect, runtime/override models are rejected with a UserError (the durable steps/tasks close over the construction-time model), matching the deprecated wrappers.

Per-integration specifics

  • Temporal: New DurabilityPlugin for activity registration on the worker; __pydantic_ai_agents__ accepts both TemporalAgent (legacy) and bare agents carrying a TemporalDurability. Per-tool activity config moves out of the constructor and onto the tool itself — declare it inline as @toolset.tool(metadata={'temporal': ActivityConfig(...)}) (or 'temporal': False to skip the activity wrap entirely for an async tool), or apply it across a selection of tools with SetToolMetadata(tools=['my_tool'], temporal=ActivityConfig(...)):

    toolset = FunctionToolset(id='research')
    
    @toolset.tool(metadata={'temporal': ActivityConfig(start_to_close_timeout=timedelta(minutes=5))})
    async def fetch_paper(arxiv_id: str) -> str: ...
    

    See docs/durable_execution/temporal.md for the full example.

  • DBOS: DBOSDurability routes model requests and MCP I/O through DBOS steps when the run executes inside a @DBOS.workflow; unlike the deprecated DBOSAgent, it does not wrap the run itself (intentional behavior change — see "Try it out"). Default parallel_execution_mode='parallel_ordered_events' preserves DBOS's deterministic-replay guarantees; 'sequential' is also accepted, 'parallel' is excluded by type. New event_stream_handler_step_config= knob for the event-stream-handler steps.

  • Prefect: PrefectDurability routes model requests, tool calls, and MCP I/O through Prefect tasks when the run executes inside a @flow; like DBOS, it does not wrap the run itself. Per-tool task config via metadata={'prefect': TaskConfig(...)} (or 'prefect': False), mirroring the Temporal pattern.

New public surface

  • The three durability capabilities: [TemporalDurability][pydantic_ai.durable_exec.temporal.TemporalDurability], [DBOSDurability][pydantic_ai.durable_exec.dbos.DBOSDurability], [PrefectDurability][pydantic_ai.durable_exec.prefect.PrefectDurability], plus the Temporal-specific DurabilityPlugin worker plugin.
  • On the core: RunContext.root_capability, ModelRequestContext.model_id, and CompletedStreamedResponse (moved into pydantic_ai.models), as described above.

Everything else the integrations need to coordinate with the agent loop (call_model, open_model_stream, disable_threads, process_event_stream, StreamedActivityResult, the _safe_at_runtime ClassVar opt-in that lets Instrumentation be added at run time, …) is kept private — these are mechanics of the bundled integrations, not a stable third-party contract. That first-class contract for writing third-party durability integrations on top of public API only is #5477, a post-v2 RFC; until it lands, the Restate SDK's pydantic-ai integration is the canonical pattern for a third-party adapter.

Known limitations (capability-path specific)

The wrapper-agent limitations (no in-workflow streaming, async tool functions only inside Temporal workflows, image output disabled, DBOS 'parallel' mode excluded, …) all carry over and are documented in docs/durable_execution/{temporal,dbos,prefect}.md. New to the capability path:

  • No per-run capabilities inside a Temporal workflow: capabilities passed via agent.run(capabilities=[...]) from inside a workflow are rejected by TemporalDurability — activities must be registered with the worker before the workflow runs, and binding (which registers activities) only happens at agent construction. TemporalDurability snapshots the bound capability classes and raises UserError for any runtime capability class the snapshot didn't see, so this fails loudly rather than silently bypassing durability. Attach all capabilities at agent construction time.
  • Runtime-added toolsets of kinds that can't be made durable after construction (which kinds varies by engine) are likewise rejected with a clear error.
  • Runtime/override models under DBOS and Prefect are rejected, as described above.

Backwards compatibility

TemporalAgent / DBOSAgent / PrefectAgent keep working at runtime, but now emit DeprecationWarning with a per-argument migration mapping, and are slated for removal in v3. CompletedStreamedResponse's old constructor argument order is deprecated with a warning. No other public APIs change.

Test plan

  • 340 tests across the three durability suites (tests/test_temporal.py, tests/test_dbos.py, tests/test_prefect.py)
  • 100% line/branch coverage held across all three durability submodules
  • tests/test_capabilities.py covers the resolution surface end to end (chain composition and ordering, worker-side re-resolution, models= aliases, per-step selectors, raw-string deferral)
  • Regression tests for runtime-model rejection (DBOS/Prefect), runtime-capability rejection (Temporal), and from_agent duplicate detection
  • No regressions in the rest of the suite; CI fully green
  • Auto-review pass