# Build Durable Agents With Pydantic AI And Temporal

> Source: <https://dev.to/joxiahdev/build-durable-agents-with-pydantic-ai-and-temporal-3e67>
> Published: 2026-07-18 11:00:00+00:00

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.

``` python
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.

``` python
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.

``` python
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.

``` python
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:

``` php
@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:

``` php
@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 pause and resume without losing state — a pattern suited to human approval steps.

``` python
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`

pauses 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 paused, 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](https://youtube.com/@joxiahdev), **Mastering Pydantic AI**.
