页面简介
Make Pydantic AI agents durable with DBOS, checkpointing model requests and MCP calls to Postgres or SQLite so a workflow resumes from its last completed step.
正文摘录
Durable Execution with DBOS DBOS is a lightweight durable execution library natively integrated with Pydantic AI. Build Reliable and Observable AI Agents with Pydantic AI and DBOS on the Pydantic blog walks through an example. Durable Execution DBOS workflows make your program durable by checkpointing its state in a database. If your program ever fails, when it restarts all your workflows will automatically resume from the last completed step. Workflows must be deterministic and generally cannot include I/O. Steps may perform I/O (network, disk, API calls). If a step fails, it restarts from the beginning. Every workflow input and step output is durably stored in the system database. When workflow execution fails, whether from crashes, network issues, or server restarts, DBOS leverages these checkpoints to recover workflows from their last completed step. DBOS queues provide durable, database-backed alternatives to systems like Celery or BullMQ, supporting features such as concurrency limits, rate limits, timeouts, and prioritization. See the DBOS docs for details. The diagram below shows the overall architecture of an agentic application in DBOS. DBOS runs fully in-process as a library. Functions remain normal Python functions but are checkpointed into a database (Postgres or SQLite). Clients (HTTP, RPC, Kafka, etc.) | v +------------------------------------------------------+ | Application Servers | | | | +----------------------------------------------+ | | | Pydantic AI + DBOS Libraries | | | | | | | | [ Workflows (Agent Run Loop) ] | | | | [ Steps (Tool, MCP, Model) ] | | | | [ Queues ] [ Cron Jobs ] [ Messaging ] | | | +----------------------------------------------+ | | | +------------------------------------------------------+ | v +------------------------------------------------------+ | Database | | (Stores workflow and step state, schedules tasks) | +------------------------------------------------------+ See the DBOS documentation for more information. Durable Agent Add durable execution to any Agent by attaching the DBOSDurability capability. When the agent runs inside a DBOS workflow, the capability routes model requests and MCP communication through DBOS steps. To make a run durable, call agent.run() inside a @DBOS.workflow. The agent stays a normal Agent everywhere — outside a DBOS workflow the capability is transparent, and the original agent, model, and MCP server can still be used as normal. Custom tool functions and event stream handlers registered on the agent directly or through another capability are not automatically wrapped by DBOS. An event_stream_handler= passed to DBOSDurability runs inside a DBOS step and receives live-streamed events. If they involve non-deterministic behavior or perform I/O, you should explicitly decorate them with @DBOS.step. Here is a simple but complete example of attaching durable execution to an agent. All it requires is to install Pydantic AI with the DBOS open-source library: pip uv Terminalpip install pydantic-ai[dbos] Or if you’re using the slim package, you can install it with the dbos optional group: pip uv Terminalpip install pydantic-ai-slim[dbos] After that, run the following example code: dbos_durability.py from dbos import DBOS, DBOSConfig from pydantic_ai import Agent from pydantic_ai.durable_exec.dbos import DBOSDurability dbos_config: DBOSConfig = { 'name': 'pydantic_dbos_agent', 'system_database_url': 'sqlite:///dbostest.sqlite', # (1) } DBOS(config=dbos_config) agent = Agent( 'openai:gpt-6.1-sol', instructions="You're an expert in geography.", name='geography', # (2) capabilities=[DBOSDurability()], # (3) ) @DBOS.workflow() # (4) async def answer(question: str) -> str: result = await agent.run(question) return result.output async def main(): DBOS.launch() answer_text = await answer('What is the capital of Mexico?') print(answer_text) #> Mexico City (Ciudad de México, CDMX) This example uses SQLite. Postgres is recommended for production. The agent's name is used to uniquely identify its workflows. Attach durability via capabilities=[...]. The capability routes model requests and MCP communication through DBOS steps when the agent runs inside a workflow. Because DBOS workflows must be registered before DBOS.launch(), the agent must also be constructed before calling DBOS.launch(). Wrap agent.run() in your own @DBOS.workflow to make the run durable. (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 DBOS workflow, DBOSDurability composes with all other capabilities without each needing a DBOS-specific wrapper variant. For more information on how to use DBOS in Python applications, see their Python SDK guide. Wrapper-agent path (deprecated) Any agent can be wrapped in a DBOSAgent to get a durable agent variant that routes model requests and MCP communication through DBOS steps: dbos_agent.pyfrom pydantic_ai import Agent from pydantic_ai.durable_exec.dbos import DBOSAgent agent = Agent('openai:gpt-6.1-sol', name='geography') dbos_agent = DBOSAgent(agent) # Use `dbos_agent` in place of `agent`. Migrating to the capability means attaching DBOSDurability and adding the workflow decorator that DBOSAgent used to apply for you: -dbos_agent = DBOSAgent(agent) -result = await dbos_agent.run(prompt) +agent = Agent(..., capabilities=[DBOSDurability()]) + +@DBOS.workflow() +async def answer(prompt: str) -> str: + result = await agent.run(prompt) + return result.output DBOS Integration Considerations When using DBOS with Pydantic AI agents, there are a few important considerations to ensure workflows and toolsets behave correctly. Agent and Toolset Requirements Each agent instance must have a unique name so DBOS can correctly resume workflows after a failure or restart. Each MCPToolset must have a unique id, as DBOS derives its step names and per-run tool-defs cache key from it. This field is normally optional, but is required when using DBOS, and the hostname a URL toolset without one takes as its id doesn’t count. It should not be changed once the durable agent has been deployed to production, as this would break active workflows. MCP tools perform I/O and always run in their DBOS step. Setting a tool’s metadata={'dbos': False} is rejected instead of running the MCP call inline in workflow code. An MCP server is connected once per workflow rather than once per step: the first step that needs it connects it — inside a step, so DBOS retries a failed connection like any other step failure — and the workflow holds the session until the run ends. Tool discovery still runs its get_tools step, and whether it runs is decided by the run’s own recorded history rather than by what a warm process happens to hold, so the step sequence stays the same on recovery; the server’s own cache_tools then answers those steps from the session the run is already holding, without another round trip. Concurrent runs in one process share a server’s session, as they do outside a workflow, and it is closed once the last of them ends. DynamicToolsets, including those contributed by a DynamicCapability, are wrapped too and require a stable id. Tool discovery, argument validation, and calls run as {name}__dynamic_toolset__{id}.get_tools, {name}__dynamic_toolset__{id}.validate_args, and {name}__dynamic_toolset__{id}.call_tool steps. A tool’s args_validator runs in the validate_args step, which re-resolves the toolset like call_tool; a tool without one schedules no validation step. Validation runs before approval and deferral, so rejected arguments never reach an approver. All of the dynamic toolset’s I/O — including MCP communication — happens inside those steps, so it is checkpointed. When the factory is built with per_run_step=False, the run resolves the toolset once and each step reuses it, entering it the first time a step needs it and leaving it entered for the rest of the run. Building a toolset is not the same as connecting it — an MCPToolset opens nothing until it is entered — so connecting happens inside a step, where it is retried like any other step failure. The factory itself, and the for_run of the toolset it returns (for an MCPToolset, its auth or headers function), run in workflow code and re-run whenever that replays, so like the capability factory below they must be deterministic given the run’s deps: build the toolset in the factory and leave its I/O to the steps. This is the lifecycle a non-durable run gives the toolset, so a toolset’s own caching — such as cache_tools on an MCPToolset the factory returns — works as it does outside a workflow, instead of being discarded between steps. A per_run_step=True factory is re-resolved inside each step, as it asks to be. For a DynamicCapability, DBOS reuses the capability resolved for the run inside those steps. The capability factory itself runs in workflow code and re-runs when a workflow recovers, so like all workflow code it must be deterministic given the run’s deps: construct the toolset in the factory and leave its I/O to the steps. A toolset contributed by a capability — a Capability with tools=, or a locally-running MCP server — derives its id from the capability’s own id, so set Capability(id='...', tools=[...]) or MCP(id='...', url='...'). An MCP resolves its id in precedence order: an explicit id=, then a native=MCPServerTool(...) id, then the server URL’s hostname. Two MCP capabilities on one host are rejected, so give each an explicit id. A bare non-URL local client (e.g. MCP(local=Path(...))) with none of these stays id-less and must be given an explicit id to be used here. Function tools and event stream handlers registered on the agent directly or through another capability are not automatically wrapped by DBOS. An event_stream_handler= passed to DBOSDurability runs inside a DBOS step and receives live-streamed events. For directly registered tools and handlers, you can decide how to integrate them: Decorate