# Build agents and workflows

Application patterns for context, persistent state, durable results and safe retries.

Source: https://particledb.ai/guides/agents-and-workflows/

Use ParticleDB for an agent's records, retrieved context and execution state. The examples here describe application-managed workflows. They do not require a built-in agent scheduler.

## Prepare context

Retrieve relevant records with [search and memory](/guides/search-and-memory/). Scope data access to the authenticated user or account, and pass only the context required by the next step.

## Store execution state

```sql
CREATE TABLE agent_runs (
  id BIGINT PRIMARY KEY,
  status TEXT NOT NULL,
  attempts BIGINT NOT NULL,
  result TEXT
);
INSERT INTO agent_runs VALUES (1, 'pending', 0, NULL);
```

## Record a completed step

After your worker finishes the work, record its result in a transaction:

```sql
BEGIN;
UPDATE agent_runs
SET status = 'completed', attempts = attempts + 1, result = 'reviewed'
WHERE id = 1;
COMMIT;
```

```sql
SELECT status, attempts, result FROM agent_runs WHERE id = 1;
```

The result is `completed`, one attempt and `reviewed`.

## Handle retries

Give each logical action a stable identifier. Retry database transactions after a retryable conflict. For external actions, use the external system's idempotency support or record enough information to reconcile the result before trying again.

Database recovery does not guarantee exactly-once delivery of a payment, message or model request. Workers must handle the gap between an external response and a database commit.

## Put reusable logic in Particles

Use [Particles](/particles/overview/) for supported scoring, transformation and computation. The [availability page](/particles/limits/) explains which execution models are supported.

## Related

[Documentation home](/docs/) · [Troubleshooting](/guides/troubleshooting/)
