db3.aiVisit main site

11 October 2026

How to Build AI Workflows: A Reliable Developer Guide

Building an AI workflow is not the same as sending a prompt. A production workflow needs a clear outcome, a durable record of work, narrow tool permissions, safe model boundaries, and a recovery path when an external dependency fails.

The practical approach is to begin with one deterministic path: accept a validated request, persist a workflow run, call a model only for the decision it is suited to make, execute tools through application-owned contracts, and move slow or retryable work to a queue. Record each transition so we can diagnose, resume, or replay the run without guessing what happened.

For a TypeScript product, db3.ai brings application services, queues, storage, and durable flows into the same runtime. Keep in mind that its current AI client is a bounded server-side text client. Tool and agent abstractions are application-owned today, so we should build explicit boundaries rather than assume an agent API exists.

Table of contents

Before you start

Choose one workflow that has a measurable completed outcome. In this guide, we will use a support-ticket triage workflow:

  • A user submits a ticket.
  • The application validates ownership and stores the ticket.
  • A model classifies urgency and proposes a routing decision.
  • A guarded tool reads allowed account context.
  • A queue handles any slow enrichment or notification.
  • The application records the run, step results, and failures.

Prepare these inputs before writing code:

  • A server-side model credential, stored outside browser code and source control.
  • A database table or model for workflow runs and steps.
  • A stable tenant, user, or workspace identity from trusted authentication.
  • Tool contracts with explicit input, output, and permission checks.
  • A worker process for queued steps.
  • Test doubles for the model and every external tool.

Start from the db3.ai starter app if you want an application with server code, authentication, persistence, and an optional bounded AI feature already in place. Keep routes, prompts, business rules, and orchestration in your app, as described in the project structure guide.

1. Define one outcome and one workflow contract

Write the completed outcome in a sentence before you choose a model or tool. For our example: route a valid support ticket to the correct team, or leave it pending with a reason.

Next, define a workflow contract that separates immutable request facts from generated data. Persist stable identifiers, version information, and a correlation ID. Do not persist a request object, an open database connection, an API key, or an unbounded prompt.

// Illustrative application types
interface WorkflowRun {
  id: string;
  tenantId: string;
  ticketId: string;
  definitionVersion: string;
  status: 'queued' | 'running' | 'completed' | 'failed' | 'needs_review';
  idempotencyKey: string;
  correlationId: string;
}

interface TriageDecision {
  urgency: 'low' | 'normal' | 'high';
  targetQueue: 'billing' | 'technical' | 'account';
  needsAccountLookup: boolean;
  rationale: string;
}

Expected result: a second submission with the same idempotency key resolves to the existing run or a deliberate replacement policy. It does not silently create duplicate downstream work.

Troubleshooting: if the workflow cannot be described without a vague "do whatever is needed" step, narrow the first release. Start with a classification or enrichment task, then add branching only after the linear path is observable.

Diagram of an AI workflow with state, model, tool execution, queue processing, and retry audit trail

2. Put the model behind a narrow decision boundary

Models are useful for interpretation, extraction, ranking, and language generation. They should not be the source of truth for tenant access, money movement, or irreversible side effects.

Give the model the smallest possible input and ask for a bounded result. Validate the returned value before it controls the workflow. If the provider response is malformed, incomplete, or outside your schema, mark the step as failed or send it to review instead of falling back to a guess.

async function decideTriage(input: {
  subject: string;
  body: string;
  allowedQueues: string[];
}): Promise<TriageDecision> {
  const text = await model.generate({
    instructions: 'Classify one support ticket. Return JSON only.',
    input: JSON.stringify(input),
    maxOutputTokens: 300,
  });

  return validateTriageDecision(JSON.parse(text));
}

Expected result: every model step has a timeout, output limit, validated schema, provider response identifier, and an application-level failure classification.

Troubleshooting: do not retry a request just because the caller lost its connection. First determine whether the provider outcome is known. For costly or ambiguous operations, use a durable run record and an idempotency key before trying again.

The db3.ai AI guide shows the current bounded text pattern: explicit server-side credentials, separate instructions and source input, output limits, timeouts, and safe error handling. It also makes an important limitation clear: streaming, structured outputs, tools, agents, durable request tracking, and failover should not be treated as already-provided framework features.

3. Expose tools as application-owned capabilities

A tool is not a function the model can call without limits. It is a capability your application grants for a specific run, tenant, and action. Give every tool a small input schema, a precise authorization check, a timeout, and an audit event.

For example, an account lookup tool should receive a ticket ID and trusted tenant ID from the workflow context. It should not accept a customer ID selected by the model and return every field in the account record.

interface ToolContext {
  tenantId: string;
  ticketId: string;
  actorId: string;
  correlationId: string;
}

async function readAllowedAccountContext(ctx: ToolContext) {
  const ticket = await Ticket.where({ id: ctx.ticketId, tenantId: ctx.tenantId }).firstOrFail();
  const account = await Account.where({ id: ticket.accountId, tenantId: ctx.tenantId }).firstOrFail();

  return {
    plan: account.plan,
    paymentState: account.paymentState,
  };
}

Expected result: the tool returns only the fields the routing step needs, and every access can be tied to the workflow run.

Troubleshooting: if a tool requires broad database access or a raw request object, split it. A narrow read tool, a narrow update tool, and a reviewed escalation step are safer than one catch-all capability.

For low-code integrations or large connector catalogs, products such as n8n and Make can be useful alongside an application. When the workflow must share your application identity, models, data, and authorization boundaries, keep the critical business logic in typed application code.

4. Persist state before slow or retryable work

The HTTP request should create or update durable state quickly. Long-running model calls, file processing, notifications, and provider retries belong beyond the request boundary.

Persist the workflow run, the current step, and the idempotency key before dispatching background work. If your database and queue cannot be committed atomically, use an outbox or a deliberate post-commit dispatch process so a crashed request does not leave work in an unknown state.

The db3.ai Queue guide is built for work that must outlive the request, including AI requests, email delivery, file processing, imports, and reports. Its job guidance is directly applicable here: persist JSON-safe application identity, validate it when a job is restored, and avoid treating repeated execution as exactly-once delivery.

async function startTriage(ticketId: string, tenantId: string) {
  const run = await createOrFindRun({ ticketId, tenantId });

  if (run.status === 'queued') {
    await queue.dispatch(new TriageTicketJob({ runId: run.id }));
  }

  return run;
}

Expected result: a client receives a run ID quickly, while a worker processes the durable job from a named queue.

Troubleshooting: if a worker cannot resolve an old job type after a deployment, keep a compatible handler available until existing jobs drain or migrate the stored payload deliberately.

5. Turn the workflow into small, replayable steps

Treat each step as a contract with named input, output, and failure behavior. A useful first sequence is:

  1. Load the authorized ticket and workflow run.
  2. Sanitize and bound model input.
  3. Ask the model for a triage decision.
  4. Validate the decision against your application schema.
  5. Run the allowed account-context tool only when needed.
  6. Persist the routing result or create a review task.
  7. Queue a notification after the authoritative result is stored.

Use a flow engine when the step history, inputs, outputs, and replay decisions matter. db3.ai Flows creates durable run and step state, dispatches flow steps through Queue, and records progress events. Its current graph model is intentionally constrained to a connected sequential path, which makes it a good match for a clear first workflow. Add explicit application logic or a different orchestration tool if your design needs complex branching, merging, or cycles.

Expected result: we can inspect which step ran, which output it produced, and why a run stopped.

Troubleshooting: version block types and workflow definitions. Replaying an old run can repeat side effects, and an old graph may still invoke newly deployed block code. Use idempotency keys for external updates, emails, payments, and provider calls.

6. Make observability part of the workflow contract

Observability is not a final dashboard task. Add it when you define the first step. Every run and event should carry a correlation ID, tenant scope, workflow definition version, step name, attempt number, and safe outcome code.

Record metadata that helps us operate the system without storing secrets or raw customer content:

  • Workflow run ID and parent run ID.
  • Step start and finish timestamps.
  • Queue job ID, queue name, and attempt number.
  • Model name, provider response ID, and token usage when available.
  • Tool name, authorization result, and duration.
  • Sanitized error class, retry decision, and operator action.

Avoid logging API keys, session cookies, full prompts, sensitive tool output, or unredacted provider errors. db3.ai Flows exposes run details, ordered steps, lifecycle events, and durable progress logs, but your application still needs to scope history access and redact sensitive values before recording them.

Developer reviewing tests and operational signals for an AI workflow

Expected result: an operator can answer three questions for any run: what happened, what can safely be retried, and who is allowed to inspect it.

Troubleshooting: if the only diagnostic record is a stack trace, add structured events at each state transition. If logs contain whole prompts or tool results, reduce them to safe identifiers, sizes, and outcome codes.

7. Test failure paths before adding autonomy

A happy-path demo is not a reliable workflow. Test the transitions that occur when a provider times out, a tool denies access, a worker restarts, or a duplicate event arrives.

Use controlled fakes for model and tool behavior. Then run integration tests against your real workflow state and queue configuration. At minimum, cover:

  • Invalid input is rejected before any provider call.
  • A model timeout creates a safe, inspectable failure.
  • Invalid model output cannot trigger a tool.
  • A tool authorization failure does not leak cross-tenant data.
  • A queued job survives a producer restart.
  • A retry does not duplicate a notification or update.
  • A failed run can be repaired and replayed with an explicit definition choice.

Expected result: each test asserts durable state, not only a returned HTTP status. A failed attempt should have a visible classification and a defined next action.

Troubleshooting: distinguish retryable dependency failures from permanent validation and authorization failures. Retrying a bad request or denied operation increases noise and can create unnecessary provider cost.

A compact implementation blueprint

Use this sequence as the first implementation plan:

  1. Create WorkflowRun and WorkflowStep models with tenant ownership and correlation IDs.
  2. Build one API endpoint that validates input and creates a run idempotently.
  3. Write one queued job that loads the run from durable identity.
  4. Implement one model decision with bounded input, bounded output, timeout, and schema validation.
  5. Add one read-only, tenant-scoped tool.
  6. Persist every step outcome before moving to the next one.
  7. Add safe events, metrics, and a run-detail screen for operators.
  8. Write failure and replay tests before enabling any automatic external action.

This approach also makes architectural choices clearer. Use a plain queue when one job has one retry boundary. Use a durable flow when several steps and replay history matter. Use a scheduler only when recurring work must become due. Use a general-purpose orchestration product when you need its specific branching, cross-service, or ecosystem capabilities.

FAQ

What is the smallest useful AI workflow?

A validated request, one bounded model decision, one persisted result, and one safe failure path. Do not begin with an autonomous agent that has broad database or network access.

Should a model decide which tools it can use?

A model can propose an action, but your application should select from an allowlist and enforce the authorization policy. The model output is input to your control plane, not permission to bypass it.

When should we use a queue instead of handling work in the request?

Use a queue when the operation may outlive the request, needs retries, depends on a worker, or should be isolated from request latency. Keep the request responsible for validation and durable state creation.

Can we replay failed workflows safely?

Only when each side effect is idempotent or protected by a provider-supported idempotency mechanism. A replay creates another attempt, not proof that the original attempt produced no external effect.

Does db3.ai provide agent tool calling today?

No. The current db3.ai AI documentation describes a stateless text client, while tools and agents remain planned framework work. We can still build guarded tool use as application-owned flow blocks and queue jobs now.

Build the first reliable path

Start with a small workflow whose result we can verify: one outcome, one model decision, one guarded tool, one durable queue boundary, and one complete failure path. From there, add steps only when you can state their input, permission model, retry behavior, and operator view.

To implement the foundation in db3.ai, begin with the starter app, add the bounded AI text feature, then introduce Queue and Flows when your workflow needs durable execution and inspectable history.