Durable Pydantic AI agents with Azure Durable Task Pydantic AI Harness now ships AzureDurableTaskDurability, a capability that runs model requests, function tool calls, MCP calls and durable capability operations as Durable Task activities so a killed worker can replay recorded results and resume an agent run instead of re-paying for model calls or repeating side effects like refunds. The capability builds on Microsoft's Durable Task engine, which powers Azure Durable Functions, and Microsoft's Azure team announced the integration in a post titled "Introducing Azure Durable Task for Pydantic AI agents." Outside an orchestration the agent runs exactly as before, and the azure-durable-task extra installs the Durable Task Python SDK, the Azure-managed worker and client, and azure-identity. A support agent gets a ticket: order A-1001 arrived damaged. It asks the model what to do, looks up the order, asks the model again, and issues a refund. Then the worker running it is killed by a deploy, a scale-in event, or an out-of-memory error, and the process takes everything it knew about the run with it. Restart the run from the top and you pay for the model requests twice, call the order API twice, and maybe refund the customer twice. Don't restart it and the ticket sits half-handled until someone notices. Durable Task https://github.com/microsoft/durabletask-python is Microsoft's answer to that problem, and it is the engine behind Azure Durable Functions. You write an orchestrator as ordinary Python code. The work it delegates runs as activities, and Azure Durable Task Scheduler https://learn.microsoft.com/en-us/azure/durable-task/scheduler/durable-task-scheduler records the result of every completed activity. When a worker dies, another worker picks up the orchestration, replays the recorded results, and carries on from the step that was in flight. Pydantic AI Harness https://pydantic.dev/docs/ai/harness/ now ships AzureDurableTaskDurability https://pydantic.dev/docs/ai/harness/azure-durable-task/ , a capability that brings the agent loop into that model. By default, model requests, function tool calls, MCP calls, and durable capability operations each run as a Durable Task activity. Outside an orchestration the agent runs exactly as it did before. The Azure team announced it on their side too, in Introducing Azure Durable Task for Pydantic AI agents https://techcommunity.microsoft.com/blog/appsonazureblog/introducing-azure-durable-task-for-pydantic-ai-agents/4571024?utm source=pydantic&utm medium=partnership&utm campaign=azure-durable-task-pydantic-ai . uv add logfire "pydantic-ai-harness azure-durable-task " "pydantic-ai-slim anthropic " The azure-durable-task extra installs the Durable Task Python SDK, the Azure-managed worker and client, and azure-identity . The examples use Anthropic, but any provider Pydantic AI supports works. Pydantic Logfire https://pydantic.dev/logfire instruments the agent, so each run shows up as a trace with every model request, tool call, and activity. Set your model provider key and a Logfire write token https://pydantic.dev/docs/logfire/manage/create-write-tokens/ before running the examples: export ANTHROPIC API KEY='your-anthropic-api-key' export LOGFIRE TOKEN='your-logfire-write-token' For local development, start the Durable Task Scheduler emulator https://learn.microsoft.com/en-us/azure/durable-task/sdks/quickstart-portable-durable-task-sdks in Docker: docker run --rm --name dts-emulator \ -p 127.0.0.1:8080:8080 -p 127.0.0.1:8082:8082 \ mcr.microsoft.com/dts/dts-emulator:v0.0.9 The emulator serves the SDK on port 8080 with a task hub called default , and its dashboard on http://localhost:8082 http://localhost:8082 . No Azure subscription needed yet. Attach the capability to the agent, give the agent a name , and write the orchestrator. The name prefixes every activity the agent registers, so it is recorded in orchestration history. Save this as support agent.py : python from collections.abc import Generator import logfire from durabletask import task from pydantic ai import Agent, RunContext from pydantic ai harness.azure durable task import AzureDurableTaskDurability, run durable logfire.configure service name='support-agent' logfire.instrument pydantic ai agent = Agent 'anthropic:claude-sonnet-5-5', name='support', instructions='Look up the order, then refund it if it arrived damaged.', capabilities= AzureDurableTaskDurability , @agent.tool plain def lookup order order id: str - dict str, str : return {'order id': order id, 'status': 'delivered', 'note': 'box arrived crushed', 'total': '42.00'} @agent.tool def issue refund ctx: RunContext None , order id: str, amount: str - str: idempotency key = f'{ctx.run id}:{ctx.tool call id}' logfire.info 'refund {order id} {amount}', order id=order id, amount=amount, idempotency key=idempotency key Stub: call your payments API here with idempotency key, so a repeated call is a no-op. return f'Refunded {amount} on {order id}' def support ctx: task.OrchestrationContext, prompt: str - Generator task.Task object , object, str : result = yield from run durable ctx, lambda: agent.run prompt return result.output The tools are ordinary Pydantic AI tools. issue refund is a stub that logs the refund to Logfire https://pydantic.dev/logfire instead of moving money, so the example runs without a payments account. Nothing about either tool changes to make it durable, apart from the idempotency key, which the section on replay explains. run durable is the bridge between the Durable Task generator style and an async agent run, and you call it wherever the agent belongs in your workflow. The orchestrator returns JSON-compatible output. If the agent has a Pydantic model as output type , return result.output.model dump mode='json' . Finally, start a worker and schedule an orchestration from main.py : python import logfire from durabletask.client import TaskHubGrpcClient from durabletask.worker import TaskHubGrpcWorker from support agent import AzureDurableTaskDurability, agent, support emulator = dict host address='localhost:8080', metadata= 'taskhub', 'default' , secure channel=False worker = TaskHubGrpcWorker emulator worker.add orchestrator support durability = AzureDurableTaskDurability.from agent agent assert durability is not None with durability.register worker , worker, TaskHubGrpcClient emulator as client: worker.start with logfire.span 'support ticket A-1001' : instance id = client.schedule new orchestration support, input='Order A-1001 arrived damaged. Please sort it out.' state = client.wait for orchestration completion instance id, timeout=60 assert state is not None state.raise if failed print state.get output Agent binds its own copy of each capability, so from agent fetches the bound one. Enter register worker before the worker starts and leave it after the worker stops. It registers the agent's activities and runs them. Orchestrators and clients are plain Durable Task SDK code, and a client can live in a different process that never imports the agent. The logfire.span wraps client code, which never replays, so it appears once per ticket in Logfire. I ran the agent above against the emulator and killed the worker with os. exit 1 inside issue refund , after the refund ran and before its result reached the scheduler. Then I started a second worker. For the test, each tool also appended a line to a file every time its body executed: lookup order A-1001 pid=10761 issue refund A-1001 key=d3885ebc...:support:d6b9f9de...:toolu 01M455EcNkh3yCYePF2ieJAt pid=10761 issue refund A-1001 key=d3885ebc...:support:d6b9f9de...:toolu 01M455EcNkh3yCYePF2ieJAt pid=10821 The first worker made two model requests, ran lookup order , and died inside issue refund . The second worker didn't repeat any of the first three activities. It replayed them from history, ran issue refund again because its result was never recorded, made the final model request, and completed the orchestration about a second later: COMPLETED I've refunded order A-1001 in full, $42.00. The order was marked delivered, and its note said the box arrived crushed, which matches the damage you reported. The refund tool ran twice. That is the honest shape of durable execution, and it brings us to the rules. Each time an activity completes, the SDK runs your orchestrator again from the start and serves every completed result from history. That is how a replacement worker resumes the orchestration, and it means a few things about how you write the agent: - Activities run at least once. A worker can die after a tool's side effect and before its result is recorded, as it did above. Make tools idempotent. ctx.run id and ctx.tool call id survive the restart unchanged, which makes them a good idempotency key: the two issue refund lines carry the same one. - Orchestrator-side code runs on every replay. Hooks, instruction functions, output validators, and inline tools must be deterministic and must not do network, file, or thread I/O. Put I/O in a tool or a capability's @durable operation method. - Names are persisted. Activity names come from the agent's name , toolset IDs, and tool names. Don't rename any of them while orchestrations that use them are still running. - Replay cost grows with run length. Each replay re-runs the agent up to its latest step, so orchestrator CPU grows with the square of the number of steps. Keep very long conversations in separate orchestrations. - Spans repeat. Pydantic AI spans created in orchestrator code are emitted again on every replay, so one run shows its agent run and model request spans several times in Logfire. - Errors change type. An exception raised in a model request or tool reaches the orchestrator as durabletask.task.TaskFailedError . UserError keeps its type. Dependencies follow the same logic. They cross into activities as data, so they must be JSON-serializable dataclasses, Pydantic models, and JSON values , and activities rebuild them from the agent's deps type . Create database clients and HTTP sessions inside the tool that uses them, not in deps . A refund above a threshold, a production deploy, a payment: some tool calls need a person to say yes. With Durable Task the approval belongs to the orchestrator, and the orchestration waits for an external event. No activity runs while it waits, so a review can take five minutes or three days. Mark the tool with requires approval=True and add DeferredToolRequests to the output type: python from collections.abc import Generator from durabletask.task import OrchestrationContext, Task from pydantic import TypeAdapter import logfire from pydantic ai import Agent, DeferredToolRequests, DeferredToolResults, UserError from pydantic ai harness.azure durable task import AzureDurableTaskDurability, run durable logfire.configure service name='payment-review' logfire.instrument pydantic ai agent = Agent 'anthropic:claude-sonnet-5-5', name='review', output type= str, DeferredToolRequests , capabilities= AzureDurableTaskDurability , @agent.tool plain requires approval=True def approve payment amount: int - str: return f'Paid {amount}' def review ctx: OrchestrationContext, prompt: str - Generator Task object , object, str : result = yield from run durable ctx, lambda: agent.run prompt while isinstance result.output, DeferredToolRequests : requests = result.output event name = f'review:{ctx.new uuid }' ctx.set custom status { 'event': event name, 'requests': TypeAdapter DeferredToolRequests .dump python requests, mode='json' , } payload = yield ctx.wait for external event event name approvals = TypeAdapter dict str, bool .validate python payload, strict=True if set approvals = {call.tool call id for call in requests.approvals}: raise UserError 'Decisions must match the reviewed tool-call IDs exactly.' result = yield from run durable ctx, lambda: agent.run message history=result.all messages , deferred tool results=DeferredToolResults approvals=dict approvals , usage=result.usage, conversation id=result.conversation id, , ctx.set custom status None return result.output The orchestrator publishes the pending tool calls and a fresh event name in its custom status. Your review UI reads that status with client.get orchestration state instance id , shows the requests to a person, and sends their decision back with client.raise orchestration event instance id, event name, data={tool call id: True} . The agent resumes with the full message history and the usage it had already accumulated. Two details are easy to get wrong. A new event name per pause means a late decision can't answer a later review. And Durable Task matches event names case-insensitively, so tool-call IDs belong in the payload, never in the event name. The Azure Durable Task docs https://pydantic.dev/docs/ai/harness/azure-durable-task/ approvals-and-deferred-calls include a submit review helper that checks the review is still pending before raising the event. Pass native RetryPolicy values to set activity retries separately for model requests and tool calls: python from datetime import timedelta import logfire from durabletask.task import RetryPolicy from pydantic ai harness.azure durable task import AzureDurableTaskDurability logfire.configure service name='support-agent' logfire.instrument pydantic ai durability = AzureDurableTaskDurability model options=RetryPolicy first retry interval=timedelta seconds=1 , max number of attempts=3 , tool options=RetryPolicy first retry interval=timedelta seconds=1 , max number of attempts=2 , ModelRetry and deferred calls are agent control flow, not activity failures, so they never consume a retry. UserError and serialization failures aren't retried at all. For finer control, resolve tool options returns a policy per tool, or False to run a pure function tool inline in the orchestrator instead of as an activity. Inline tools replay on every step, so they must be deterministic and free of I/O. MCP and dynamic tools always run as activities. Moving from the emulator to a real scheduler changes the worker and the client. The orchestrator and register worker stay the same: python import logfire from azure.identity import DefaultAzureCredential from durabletask.azuremanaged.client import DurableTaskSchedulerClient from durabletask.azuremanaged.worker import DurableTaskSchedulerWorker logfire.configure service name='support-worker', environment='production' logfire.instrument pydantic ai credential = DefaultAzureCredential endpoint = '