cd /news/ai-agents/build-durable-agents-with-pydantic-a… · home topics ai-agents article
[ARTICLE · art-64557] src=dev.to ↗ pub= topic=ai-agents verified=true sentiment=↑ positive

Build Durable Agents With Pydantic AI And Temporal

Pydantic AI has introduced a native integration with Temporal, a durable execution engine, enabling agentic applications to resume from failures rather than restarting. The TemporalAgent class wraps existing agents, converting tool calls and model requests into Temporal Activities that can be retried on failure. This integration allows workflows to be replayed from event history, ensuring progress is preserved across crashes.

read3 min views1 publishedJul 18, 2026

Agentic applications can fail mid-run: a network call drops, a server process crashes, an LLM request times out. Without durability built in, these failures mean lost progress and repeated (wasted) LLM calls when the process has to start over.

Pydantic AI provides a native integration with Temporal, a durable execution engine. Temporal records each step of a workflow's execution as an event history, so if a process crashes, it can resume from where it left off instead of starting over.

Pydantic AI exposes this through the TemporalAgent

class, which wraps an existing agent and converts its tool calls, MCP calls, and model requests into Temporal Activities.

from pydantic_ai import Agent
from pydantic_ai.durable_exec.temporal import TemporalAgent

planning_agent = Agent(
    model='anthropic:claude-fable-5',
)
temporal_agent = TemporalAgent(
    wrapped=planning_agent
)

You call .run(...)

on temporal_agent

the same way you would on the underlying agent. The difference is under the hood: each tool call, MCP call, or model request now runs as a Temporal Activity.

Activity — a function that performs a unit of work: an LLM call, an API request, a file write. If it fails, Temporal can retry it based on a configured retry policy.

from temporalio import activity

@activity.defn
async def create_sandbox(user_id: str) -> str:
    sandbox = await AsyncSandbox.create(template="node-expo-builder")
    return sandbox.sandbox_id

Workflow — orchestrates Activities, defining what runs and in what order. Workflow code must be deterministic (no direct network calls, no random values, no reading the system clock), since Temporal replays it to reconstruct state.

from temporalio import workflow
from datetime import timedelta

@workflow.defn
class ExampleWorkflow:
    @workflow.run
    async def run(self, prompt: str) -> str:
        sandbox_id = await workflow.execute_activity(
            create_sandbox,
            args=[self.user_id],
            start_to_close_timeout=timedelta(minutes=2),
        )
        return sandbox_id

Worker — polls a task queue for scheduled work and executes it. A Workflow or Activity must be registered with a Worker before it can run.

import asyncio
from temporalio.client import Client
from temporalio.worker import Worker

async def main():
    client = await Client.connect("localhost:7233")

    worker = Worker(
        client,
        task_queue="coding-agent",
        workflows=[ExampleWorkflow],
        activities=[create_sandbox],
    )
    await worker.run()

if __name__ == "__main__":
    asyncio.run(main())

The task queue name is the only link between the code that starts a Workflow and the Worker that executes it — they never call each other directly.

Workers run Activities and Workflows differently: Activities run their function body when scheduled, and may be retried on failure per their retry policy. Workflows are replayed against their event history each time they need to advance, which is what lets a Workflow resume correctly on a new Worker after a crash.

Once a Workflow is running, Signal and Query let you interact with it from outside.

Signal sends data into a running Workflow, asynchronously, with no return value:

@workflow.signal
async def approve_plan(self) -> None:
    self._plan_approved = True

@workflow.signal
async def reject_plan(self, feedback: str = "") -> None:
    self._plan_approved = False
    self._plan_feedback = feedback

Signals only work while a Workflow is still running — once it's completed, failed, or been terminated, it can no longer receive one.

Query reads a Workflow's current state, synchronously and without side effects:

@workflow.query
def state(self) -> WorkflowState:
    return WorkflowState(
        status=self._status,
        project_name=self._project_name,
        preview_url=self._preview_url,
    )

Queries can also run against a completed Workflow, within your namespace's retention period. This doesn't extend to terminated Workflows, which aren't safely queryable.

Because Temporal keeps a full event history, a Workflow can and resume without losing state — a pattern suited to human approval steps.

from temporalio import workflow

@workflow.defn
class ExampleWorkflow:
    @workflow.run
    async def run(self):
        while True:
            self._plan_approved = None
            await workflow.wait_condition(lambda: self._plan_approved is not None)

            if self._plan_approved:
                break

workflow.wait_condition

s execution until the given condition is true. Here, the Workflow waits until a Signal (like approve_plan

above) sets self._plan_approved

. If the process running this Workflow crashes while it's d, a new Worker can pick it up and it resumes waiting at the same point.

This example has no timeout, so it waits indefinitely. In production, you'd typically pass a timeout

to wait_condition

and handle the case where no decision ever comes.

This is part of an ongoing series on my channel, Mastering Pydantic AI.

── more in #ai-agents 4 stories · sorted by recency
── more on @pydantic ai 3 stories trending now
sponsored brought to you by zahid.host 4,200+ EU-deployed projects
reading about agents? ship yours in a single git push.

Run your AI side-project on zahid.host

EU-based hosting, git-push deploys, automatic HTTPS, no cold starts. Free tier with a custom domain — perfect for shipping the agent you just read about.

$git push zahid main
Live at https://your-agent.zahid.host
Get free account → Pricing
from €0/mo · no card required
LIVE [news/build-durable-agents…] indexed:0 read:3min 2026-07-18 ·