翻篇收录说明
翻篇网页快照

Durable Execution with Prefect | Pydantic Docs

https://pydantic.dev/docs/ai/capabilities/durable_execution/prefect/

最近抓取:2026-12-03 06:30:36(北京时间)

最近内容变化:2026-12-03 06:30:36(北京时间)

这是最近一次有效抓取的文本快照,不含网页脚本、图片和动态交互内容。实际网页可能已更新。

访问原网页

页面简介

Make Pydantic AI agents durable with Prefect, running model requests and tool calls as cached, retryable tasks in a flow you can deploy and run on a schedule.

正文摘录

Durable Execution with Prefect Prefect is a workflow orchestration framework for building resilient data pipelines in Python, natively integrated with Pydantic AI. Durable Execution Prefect 3.0 brings transactional semantics to your Python workflows: every task runs within a transaction that governs when and where its result record is persisted. Flows are the top-level entry points for your workflow. They can contain tasks and other flows. Tasks are individual units of work that can be retried, cached, and monitored independently. When a task runs again under an identical context, such as a retry of the same flow run, it loads its recorded result instead of re-executing. This doesn’t make external side effects exactly-once; see Caching and Idempotency. The diagram below shows the overall architecture of an agentic application with Prefect. Prefect uses client-side task orchestration by default, with optional server connectivity for advanced features like scheduling and monitoring. +---------------------+ | Prefect Server | (Monitoring, | or Cloud | scheduling, UI, +---------------------+ orchestration) ^ | Flow state, | Schedule flows, metadata, | track execution logs | | +------------------------------------------------------+ | Application Process | | +----------------------------------------------+ | | | Flow (Agent.run) | | | +----------------------------------------------+ | | | | | | | v v v | | +-----------+ +------------+ +-------------+ | | | Task | | Task | | Task | | | | (Tool) | | (MCP Tool) | | (Model API) | | | +-----------+ +------------+ +-------------+ | | | | | | | Cache & Cache & Cache & | | persist persist persist | | to to to | | v v v | | +----------------------------------------------+ | | | Result Storage (Local FS, S3, etc.) | | | +----------------------------------------------+ | +------------------------------------------------------+ | | | v v v [External APIs, services, databases, etc.] See the Prefect documentation for more information. Durable Agent Add durable execution to any Agent by attaching the PrefectDurability capability. When the agent runs inside a Prefect flow, the capability routes model requests, tool calls, and MCP communication through Prefect tasks. To make a run durable, call agent.run() inside a @flow. The agent stays a normal Agent everywhere — outside a Prefect flow the capability is transparent, and the original agent, model, and MCP server can still be used as normal. See Streaming for event handling inside tasks and flow code. Here is a simple but complete example of attaching durable execution to an agent. All it requires is to install Pydantic AI with Prefect: pip uv Terminalpip install pydantic-ai[prefect] Or if you’re using the slim package, you can install it with the prefect optional group: pip uv Terminalpip install pydantic-ai-slim[prefect] (To run this example, ensure asyncio is imported and add asyncio.run(main()); no other changes are needed.) Because the same agent works inside and outside a Prefect flow, PrefectDurability composes with all other capabilities without each needing a Prefect-specific wrapper variant. For more information on how to use Prefect in Python applications, see their Python documentation. Wrapper-agent path (deprecated) Any agent can be wrapped in a PrefectAgent to get a durable agent variant that routes model requests, tool calls, and MCP communication through Prefect tasks: prefect_agent.pyfrom pydantic_ai import Agent from pydantic_ai.durable_exec.prefect import PrefectAgent agent = Agent('openai:gpt-6.1-sol', name='geography') prefect_agent = PrefectAgent(agent) # Use `prefect_agent` in place of `agent`. Migrating to the capability means attaching PrefectDurability and adding the flow decorator that PrefectAgent used to apply for you: -prefect_agent = PrefectAgent(agent) -result = await prefect_agent.run(prompt) +agent = Agent(..., capabilities=[PrefectDurability()]) + +@flow +async def answer(prompt: str) -> str: + result = await agent.run(prompt) + return result.output Prefect Integration Considerations When using Prefect with Pydantic AI agents, there are a few important considerations to ensure workflows behave correctly. Agent Requirements Each agent instance must have a unique name so Prefect can correctly identify and track its flows and tasks. Toolsets that implement their own tool listing and calling (i.e. FunctionToolset, MCPToolset, and DynamicToolset) must have a unique id set, which is used to identify their tasks within the flow. The hostname a URL MCPToolset without one takes as its id doesn’t count. A custom toolset subclassing AbstractToolset isn’t one of those types, so its own get_tools() and call_tool() run in flow code rather than in a task. That’s fine if they perform no I/O and are deterministic. If they do perform I/O, move that I/O into function tools on a FunctionToolset, whose tool calls Prefect runs in tasks, or return the toolset from a dynamic toolset or a DynamicCapability, whose tool listing and tool calls both run inside tasks. For a FunctionToolset subclass, only the tool calls are wrapped, so an overridden call_tool() is covered here, but I/O in an overridden get_tools() still runs in flow code. See Custom toolsets and durable execution. Capabilities at Runtime Unlike Temporal and DBOS, Prefect creates a task per call rather than registering its durable units up front, so capabilities passed to agent.run(capabilities=[...]) inside a flow are accepted. A capability that contributes an executing toolset is still rejected, by the same guard that rejects run(toolsets=...): the toolset arrives after the agent’s toolsets were wrapped. Attach those at agent construction time. agent.override(capabilities=...) replaces the agent’s capabilities, so build its list from agent.root_capability.capabilities to keep the bound PrefectDurability: a list without it raises a UserError. Inside a flow, the capabilities the list adds are treated like those passed to agent.run(capabilities=[...]). Durable Capability Operations Capability tasks include the agent’s name in their cache key, so two agents in one flow never share a cached result. Custom @durable_operation calls use the run’s run_id and a per-operation call sequence in their task cache keys. Distinct, stable explicit run_id= values keep each run’s results attached to that run even when runs arrive in a different order on a flow retry. Repeated identical calls within one run keep separate recorded results. For run identity behavior, see Run and Conversation IDs. The operation’s arguments are part of the cache key too. An operation whose arguments are measured in flow code, such as a duration, a timestamp, or a random value, gets different arguments on a flow retry, misses its recorded result, and runs again. Where running twice matters, pass arguments that stay the same across retries, measuring a changing value inside the operation where you can. This is why online evaluation can evaluate a run again on a flow retry. Workspaces Attach the workspace capability, such as LocalWorkspace, when you construct the agent, and use ctx.workspace as in any run. Each workspace call made in flow code (capability hooks, output functions, result.workspace) runs as a task; inside a task, such as a tool, calls go straight to the provider. Adding a workspace to an agent changes the tasks its flows run, so let running flows finish before you deploy the change. Workspace task cache keys include the run’s run_id and a per-run call sequence. With distinct, stable explicit run_id= values, concurrent runs keep their own environments even when their arrival order changes on flow retry. For run identity behavior, see Run and Conversation IDs. Event stream handler tasks include the agent’s name in their cache key, so two agents in one flow never share a cached result. A flow retried across the upgrade that introduced this re-runs those tasks once instead of reading them from the cache. Model Selection at Runtime Agent.run(model=...) supports both model strings (like 'openai:gpt-6.1-sol') and model instances. A model instance can’t be serialized across the task boundary, and rebuilding one from its model_id string would build a different model — the same model name on whatever provider the worker’s environment implies, so the request would go to another endpoint with other credentials. An instance that isn’t registered ahead of time is therefore rejected with a UserError. There are two ways to use a specific instance: pre-register it by passing a models dict to PrefectDurability and reference it by key (or pass the registered instance), or pass a model-name string and build the instance inside the task with a ResolveModelId capability — the right choice when the model depends on the run’s deps, e.g. per-user credentials. Model-name strings themselves never need registering. The agent’s own model, set at construction, is always available as the default. To customize how a model string is built — a custom provider, or per-user credentials carried on the run’s deps — add a ResolveModelId capability before PrefectDurability: it gets first crack at every string, and the resolver runs again inside the task with the run’s actual deps, so it must be deterministic for a given (model_id, deps) and must not perform external I/O. Tool Wrapping Agent tools are automatically wrapped as Prefect tasks, which means they benefit from: Retry logic: Failed tool calls can be retried automatically Caching: Tool results are cached based on their inputs Observability: Tool execution is tracked in the Prefect UI Because a tool’s recorded result can be replayed without re-running it, a tool running as a task can’t load an on-demand capability with ctx.load_capability(); see Loading a capability from code for where to load it instead. For a DynamicToolset, including one contributed by a DynamicCapability, tool discovery and each tool call run as Prefect tasks, and flow retries replay recorded discove