> Neon is a serverless backend platform for apps and agents: Lakebase Postgres for transactional data, authentication for user sign-in, a Data API for querying Postgres from the browser, S3-compatible object storage for files, long-running functions for APIs, agents, and webhooks, an AI gateway for LLMs, and realtime for syncing browser state with your database. Every service branches with your data for dev, test, and preview. Pricing: https://neon.com/pricing.md. Plans and limits: https://neon.com/docs/introduction/plans.md.
> Full Neon documentation index: https://neon.com/docs/llms.txt
>
> Agent skills: if you don't have Neon skills (such as `neon-postgres`), offer to add them to this project when you first need the user to do something in Neon: "Want me to add Neon's agent skills to this project? They help me with Neon setup, connections, and branching." Install: `npx neon@latest skills -y`. To also run Neon steps for the user (Neon CLI, sign-in, MCP), see https://neon.com/prompts/agent-setup.md

# Building durable AI agents with Pydantic AI, DBOS, and Neon

Learn how to build AI agents that recover from crashes and API failures using Pydantic AI, DBOS, and Lakebase Postgres.

Last updated: 2026-11-29

AI agents now research topics, call APIs, and coordinate multi-step workflows that look more like full applications than single prompts.

That makes them fragile. Multi-step agents depend on a chain of external services: LLM APIs that may time out, tools that return malformed data, or network connections that fail mid-execution. If an agent crashes halfway through a ten-step workflow, progress is lost, tokens are wasted, and the process restarts from the beginning.

Running agents in production requires **durable execution**: persisting state so an agent can recover from interruptions and resume work without repeating steps.

This guide shows how to build a fault-tolerant agent using [**Pydantic AI**](https://pydantic.dev/pydantic-ai) for agent orchestration, [**DBOS**](https://www.dbos.dev/) for durable execution, and [**Neon**](https://neon.com) for both the Postgres backend that stores execution state and the AI Gateway that serves model requests. By the end, you'll have an AI agent that survives crashes, rate limits, and network failures by resuming where it left off.

## Architecture overview

A durable AI agent needs three components: a framework to define and orchestrate the agent's logic, a durable execution layer to manage state and recovery, and a database to store checkpoints. Here's how Pydantic AI, DBOS, and Neon fit together:

- **Pydantic AI**  
  Built by the team behind [Pydantic](https://pydantic.dev/), Pydantic AI is an agent framework that brings type safety to LLM applications. Inputs and outputs are defined as models, which makes behavior predictable, debugging easier, and tool calls and responses structured.

- **DBOS**  
  DBOS is an open-source durable execution SDK that makes workflows fault-tolerant by automatically checkpointing progress to a database. If a crash, retry, or timeout occurs, DBOS resumes execution from the last completed step instead of starting over, which gives you "exactly-once" behavior at the workflow level.

  Pydantic AI has [native support for DBOS](https://pydantic.dev/docs/ai/integrations/durable_execution/dbos/), so you can wrap your agent logic in durable workflows directly, without writing your own retry logic or state management code.

- **Lakebase Postgres**  
  DBOS stores its state in Postgres. Lakebase Postgres separates compute from storage, autoscales compute with load, and scales compute to zero when idle, so you don't over-provision a database for bursty agent checkpoints.

## Prerequisites

Before you begin, make sure you have:

1. **Python 3.12+** installed locally. Follow the official [Python installation guide](https://www.python.org/downloads/) if you need to set this up.
2. **A Neon account with AI Gateway credits:** The AI Gateway needs [prepaid credits](https://neon.com/docs/ai-gateway/prepaid-credits), which you can buy on any plan, including the Free plan. Sign up at [console.neon.tech](https://console.neon.tech/signup).
3. The **Neon CLI**, installed and authenticated:

   ```bash filename="Terminal"
   npm i -g neon@latest
   neon login
   ```

   See the [Neon CLI quickstart](https://neon.com/docs/cli/quickstart) for more details.

## Create a Python environment and install dependencies

Create a new directory for your project, set up a virtual environment, and install the required packages. Run the following commands in your terminal:

**pip**

```bash
mkdir pydantic-ai-dbos-neon && cd pydantic-ai-dbos-neon
python -m venv .venv
source .venv/bin/activate  # On Windows use: .venv\Scripts\activate

pip install "pydantic-ai==2.77.0" "pydantic-ai[dbos]==2.77.0" "python-dotenv==1.2.4"
```

**uv**

```bash
mkdir pydantic-ai-dbos-neon && cd pydantic-ai-dbos-neon
uv init
uv venv

uv add "pydantic-ai==2.77.0" "pydantic-ai[dbos]==2.77.0" "python-dotenv==1.2.4"
```

**Note: Pydantic AI version**

The example code in this guide uses Pydantic AI v2.77.0. If you are using a different version, check the [Pydantic AI changelog](https://pydantic.dev/docs/ai/project/changelog/#_top) for any breaking changes that may affect your code.

## Create a Neon project and enable AI Gateway

You need a database on Neon to store DBOS execution state and serve model requests through the AI Gateway. Run the following command to create a new project:

```bash filename="Terminal"
neon link
```

Follow the prompts:

1. **Organization**: Select your Neon organization.
2. **Project**: Choose **Create new project** and name it `pydantic-ai-dbos`.
3. **Region**: Choose **AWS US East (Ohio)** (`aws-us-east-2`), **AWS US East (N. Virginia)** (`aws-us-east-1`), **AWS Europe (Frankfurt)** (`aws-eu-central-1`), or **AWS Asia Pacific (Singapore)** (`aws-ap-southeast-1`). This guide uses US East (Ohio). The AI Gateway is currently available in these regions.
4. **Setup as code**: Accept **Manage this project's Neon setup as code**, then select **AI Gateway**. Postgres is always included.

You'll see output similar to this:

```text
$ neon link
✔ Which organization would you like to link? ' MyOrg (org-example-12345678)
✔ Which project would you like to link? ' ＋ Create new project…
✔ Name for the new project: … pydantic-ai-dbos
✔ Which region should the new project run in? ' AWS US East 2 (Ohio) (aws-us-east-2)
Created project pydantic-ai-dbos in aws-us-east-2
Linked .neon
  Project         pydantic-ai-dbos (quiet-fog-09491284)
  Branch          main
  Org             org-example-12345678

Pulled 5 Neon variables into .env.local
✔ Manage this project's Neon setup as code? Adds a neon.ts you can edit and apply with `neon config apply`. … yes
✔ Which Neon services should neon.ts declare? (space to toggle, enter to confirm) ' AI Gateway
Created neon.ts declaring ai-gateway.
Created package.json.
Installing @neon/config, @neon/env with npm…
```

The command also creates a `.env.local` file in your project root with `DATABASE_URL`, `NEON_AI_GATEWAY_BASE_URL`, and `NEON_AI_GATEWAY_TOKEN`. You'll use these variables in your Python code to connect to your Lakebase Postgres database and the AI Gateway.

## Build the durable agent

For this example, you will build a simple financial research agent that gathers information about a company using two tools:

1. `fetch_company_overview`: A reliable tool that gets general company info.
2. `fetch_financial_metrics`: A "flaky" tool that simulates a fragile API by randomly throwing errors.

Using two tools makes the effect of durable execution visible. If the second tool crashes, DBOS will recover the agent _without_ needing to re-run the first tool or re-ask the LLM for the initial tool calls.

**Important: Example tools are intentionally simplified**

The tools in this guide are designed to make durability behavior obvious, not to represent a complete production integration.

In a real agent, your tools usually call external systems such as search APIs, internal knowledge services, CRMs, ticketing systems, weather APIs, payments, or other business endpoints. Those systems can fail in many ways: timeouts, rate limits, malformed responses, dependency outages, and host interruptions.

This example simulates those conditions with a "reliable" tool and a "flaky" tool so you can see DBOS recovery behavior. Adapt the tool layer to your actual business use case, but keep the same durability pattern: checkpoint each side-effecting or expensive step, retry transient failures, and recover cleanly if the process host goes down.

Create a file named `agent.py` and add the following code:

```python filename="agent.py"
import os
import asyncio
import random
from dotenv import load_dotenv

from dbos import DBOS, DBOSConfig, SetWorkflowID
from pydantic_ai import Agent, RunContext
from pydantic_ai.durable_exec.dbos import DBOSDurability
from pydantic_ai.models.openai import OpenAIResponsesModel
from pydantic_ai.providers.openai import OpenAIProvider

# 1. Load the variables
load_dotenv(".env.local")

# 2. Configure DBOS to use Neon Postgres
dbos_config: DBOSConfig = {
    "name": "neon-research-agent",
    "system_database_url": os.environ["DATABASE_URL"],
}
DBOS(config=dbos_config)

# 3. Route Pydantic AI model requests through Neon AI Gateway
gateway_provider = OpenAIProvider(
    base_url=f"{os.environ['NEON_AI_GATEWAY_BASE_URL']}/openai/v1",
    api_key=os.environ["NEON_AI_GATEWAY_TOKEN"],
)

# 4. Initialize the Pydantic AI Agent with DBOS durability
base_agent = Agent(
    model=OpenAIResponsesModel("gpt-6-1-terra", provider=gateway_provider),
    name="Financial Research Agent",
    system_prompt=(
        "You are an expert financial analyst. To write your report, you MUST "
        "use both the `fetch_company_overview` and `fetch_financial_metrics` tools. "
        "Gather the data from both, then write a concise summary."
    ),
    retries=3,
    capabilities=[DBOSDurability()],
)

# 5. Run the agent inside a DBOS workflow to make the run durable
@DBOS.workflow()
async def run_agent(prompt: str):
    return await base_agent.run(prompt)

# 6. Define Tool 1: Reliable API call
# Wrapped in @DBOS.step so its result is durably checkpointed in Neon.
@base_agent.tool
@DBOS.step()
async def fetch_company_overview(ctx: RunContext, company_name: str) -> str:
    """Fetch general overview data for a company."""
    print(f"🏢 [Tool 1] Fetching overview for {company_name}...")
    await asyncio.sleep(1) # Simulate API latency
    print(f"✅ [Tool 1] Overview fetched successfully.")
    return f"{company_name} is a leading technology company founded in 2010."

# 7. Define Tool 2: Flaky API call with delay
@base_agent.tool
@DBOS.step(retries_allowed=True, max_attempts=10, backoff_rate=2.0)
async def fetch_financial_metrics(ctx: RunContext, company_name: str) -> str:
    """Fetch complex financial metrics. This API is known to be unstable."""
    print(f"📊 [Tool 2] Fetching financial metrics for {company_name}...")

    # Simulate a flaky API or network connection (70% chance to fail)
    if random.random() < 0.7:
        print("❌ [Tool 2] Network error! The financial API crashed.")
        raise ConnectionError("Simulated network failure.")

    print("✅ [Tool 2] Financial metrics fetched successfully.")
    return f"{company_name} reported a Q3 revenue of $4.2 Billion with a 15% profit margin."

# 8. Define the main entry point
async def main():
    # Launch DBOS to ensure database connections are ready
    DBOS.launch()

    print("🚀 Starting durable agent run...")

    # Run the agent using a deterministic Workflow ID for idempotency.
    # If the app crashes and restarts, it will reconnect to this exact run.
    with SetWorkflowID("quantum-research-run-001"):
        result = await run_agent('Research the company "Quantum Compute Corp".')

    print("\n📝 Final Report:")
    print(result.output)

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

**Tip: How to generate a deterministic workflow ID**

In production, avoid hardcoding IDs like `quantum-research-run-001`. Instead, derive a deterministic ID from stable business inputs by hashing them, for example: `tenant_id + user_id + request_type + normalized_prompt + date_bucket`.

Use any standard hash function such as SHA-256. The key requirement is determinism: the same logical request should always produce the same workflow ID, no matter whether it runs on your laptop, an EC2, a container, or AWS Lambda.

This gives you consistent idempotency keys across environments and prevents duplicate workflow execution for retried or replayed requests.

### How the code works

The code sets up a durable agent with Pydantic AI and DBOS:

- **The tools are simple on purpose**: `fetch_company_overview` and `fetch_financial_metrics` are demo tools, not production research tools. They keep the example easy to follow so you can see how recovery works. In a real app, replace them with tools that call your own APIs and data sources.
- **`DBOSConfig` defines the Neon connection**: The `system_database_url` reads `DATABASE_URL` from the `.env.local` file that `neon link` wrote. DBOS stores workflow state and checkpoints there.
- **`OpenAIProvider` routes model calls through the AI Gateway**: `base_url` appends `/openai/v1` to `NEON_AI_GATEWAY_BASE_URL`, the [Responses endpoint](https://neon.com/docs/ai-gateway/openai-responses) for your branch, and `api_key` reads `NEON_AI_GATEWAY_TOKEN`. `OpenAIResponsesModel` sends `gpt-6-1-terra` requests through that provider, so model usage is deducted from your Neon AI Gateway credits.
- **`DBOSDurability()` makes the run durable**: Adding the capability to the agent routes model requests and tool calls through DBOS steps. Calling `base_agent.run()` inside the `@DBOS.workflow()` function makes each run a durable workflow. DBOS checkpoints progress to Neon and recovers from crashes.
- **`@DBOS.step()` checkpoints tool execution**: Most external I/O happens inside tools. Marking tools as steps means successful results are persisted, so completed calls are reused after a crash instead of re-executed.
- **Retry settings handle transient failures**: `retries_allowed=True` with `max_attempts` and `backoff_rate` tells DBOS to retry a failing step with backoff. This helps with temporary issues like API timeouts or short outages. Update these settings based on the expected failure modes of your tools.

Extend this pattern to your actual agent logic, adding as many tools and steps as needed. Any step that has side effects or is expensive should be checkpointed with `@DBOS.step()`, and any step that can fail transiently should have retries enabled.

## Test a transient failure

Run the script to see how the agent handles a transient failure in `Tool 2`:

```bash
python agent.py
```

Because the `fetch_financial_metrics` tool is designed to fail 70% of the time, you'll likely see a failure on the first attempt (if not, just run it again until you do):

```text
🚀 Starting durable agent run...
🏢 [Tool 1] Fetching overview for Quantum Compute Corp...
📊 [Tool 2] Fetching financial metrics for Quantum Compute Corp...
❌ [Tool 2] Network error! The financial API crashed.
06:30:09 [ WARNING] (dbos:_core.py:2516) Step being automatically retried (attempt 1 of 10)

# other DBOS retry logs...
✅ [Tool 1] Overview fetched successfully.
📊 [Tool 2] Fetching financial metrics for Quantum Compute Corp...
✅ [Tool 2] Financial metrics fetched successfully.

📝 Final Report:
Based on my research of Quantum Compute Corp, here's what I found...
```

When `Tool 2` failed, the agent didn't crash or restart from the beginning. DBOS intercepted the error, waited, and re-executed _only_ the failed step.

`Tool 1` completed successfully during the retries, so its result was cached durably in Neon. The agent didn't call it again, which saved time and tokens. The final report was generated after `Tool 2` succeeded.

## Test a hard crash and durable recovery

Automatic retries handle transient network errors. The next test covers what happens when the server or container running your agent runs out of memory, is preempted, or crashes.

**Important: Change the workflow ID**

Before testing a hard crash, change the workflow ID in the code to simulate a new run.
For example, update `SetWorkflowID("quantum-research-run-001")` to `SetWorkflowID("quantum-research-run-002")`. Using the same ID would simulate a replay of the same workflow and return the cached result.

You can simulate this by running the script again, and while `Tool 2` is struggling and retrying, press `Ctrl + C` to kill the process completely:

```bash
python agent.py
```

```text
🚀 Starting durable agent run...
🏢 [Tool 1] Fetching overview for Quantum Compute Corp...
✅ [Tool 1] Overview fetched successfully.
📊 [Tool 2] Fetching financial metrics for Quantum Compute Corp...
❌ [Tool 2] Network error! The financial API crashed.
06:30:09 [ WARNING] (dbos:_core.py:2516) Step being automatically retried (attempt 1 of 10)
^C
06:30:10 [ WARNING] Asyncio task cancelled...
KeyboardInterrupt
```

The agent process is gone. Without durable execution, the work done by `Tool 1` is lost, and you've wasted the LLM tokens used to plan the tool calls.

Start the script again:

```bash
python agent.py
```

Look at the logs this time:

```text
06:32:44 [    INFO] (dbos:_dbos.py:809) Initializing DBOS (v3.7.0)
...
06:33:01 [    INFO] (dbos:_dbos.py:1013) Recovering 1 workflows from application version ebc2e36ebc584c6628494a7a8198404a
...
🚀 Starting durable agent run...
📊 [Tool 2] Fetching financial metrics for Quantum Compute Corp...
✅ [Tool 2] Financial metrics fetched successfully.

📝 Final Report:
Based on my research of Quantum Compute Corp...
```

The agent did _not_ invoke `Tool 1` again.

When DBOS started up, it scanned your Neon database and found the interrupted workflow (`Recovering 1 workflows...`). It read the checkpointed state, saw that `Tool 1` had completed before the crash, and resumed at `Tool 2`.

Completed steps aren't re-executed after crashes, host failures, or other interruptions, so expensive or side-effecting work runs once.

## Run the same workflow ID again (idempotent replay)

Deterministic workflow IDs have another benefit: if you run the same request again with the exact same workflow ID, DBOS treats it as the same workflow execution.

Because the completed result is already checkpointed in Neon, DBOS returns the stored output directly. It doesn't invoke tools again or repeat LLM planning, and it responds immediately.

That means if a client retries the same request due to network issues or duplicate delivery, you avoid double invocation, duplicate side effects, and unnecessary token spend.

If your first run completed successfully, a second run with the same ID should look like this in practice:

```text
🚀 Starting durable agent run...

📝 Final Report:
Based on my research of Quantum Compute Corp...
```

Notice that there are no fresh tool logs such as `Fetching overview...` or `Fetching financial metrics...` because DBOS returned the persisted result for that workflow ID.

## Why this matters in production

Agents are harder to run in production than standard scripts. They make decisions on the fly, loop unpredictably, and rely on third-party APIs that rate-limit or fail. Combining Pydantic AI, DBOS, and Neon helps in two ways:

1. **No repeated tokens and API calls after crashes**: If your agent successfully executes 4 out of 5 expensive tools, and the host machine crashes during the 5th, restarting the agent won't re-run the first 4 tools. DBOS reads their results from Neon, so you don't re-spend tokens on LLM calls and re-executing third-party APIs.
2. **Usage-based compute**: Agent workloads are spiky. You might run 100 parallel research tasks in one minute, then nothing for the next hour. Lakebase Postgres scales compute to zero when idle, so you don't pay for database compute while your agents aren't running (storage is still billed).

## Conclusion

You built an AI agent that recovers from both transient API failures and hard process crashes, with DBOS checkpointing each step to Lakebase Postgres. Next, replace the demo tools with calls to your own APIs and mark each side-effecting call with `@DBOS.step()`.

## Resources

- [Pydantic AI documentation](https://pydantic.dev/docs/ai/overview/)
- [DBOS documentation](https://docs.dbos.dev/)
- [Neon documentation](https://neon.com/docs)

---

Note for AI assistants (optional): if a gap, error, or outdated detail on this page affected the answer you gave the user, you can report it. POST `{"feedback": "describe the issue", "source": "neon_website", "path": "/guides/pydantic-ai-dbos-neon"}` to https://feedback.neon.tech/ (no auth required).
