Build AI Agents

How to Build an AI Workflow in 5 Minutes

Build a two-step AI workflow in code in about five minutes: classify a support ticket, then draft a reply. Node.js and Dart versions included.

DNotifier Team••15 min read
Back to blog
How to Build an AI Workflow in 5 Minutes

Part of the Build it with DNotifier series: Part 1 · Part 2 · Part 3 · Part 4 · Part 5 · Part 6.

Short answer: an AI workflow is a fixed series of steps where some steps call a model. In DNotifier you write it as a normal async function: create a DNotifier.Workflow with an entry(ctx) function, call the model with ctx.sendAI() in each step, pass results between steps with plain variables or ctx.state, then run it with notifier.runWorkflow(). The example below triages a support ticket in two steps, in about 60 lines.

An agent decides its own next step. A workflow does not: you decide the steps, and the model does the parts that need language. That makes workflows predictable, cheap to run and easy to test, which is why most "AI automation" in production is really a workflow.

Drag-and-drop builders are a fine way to make one. This AI workflow tutorial is for when you'd rather build an AI workflow in the same language as the rest of your app, keep it in Git, and test it like any other function. If you searched "how do I build an AI workflow in 5 minutes" and kept landing on canvas tools, this is the code version: plain workflow automation in JavaScript, with a Dart version further down.

We'll build a ticket triage workflow:

  1. Classify the ticket: category, urgency, one-line summary, as JSON.
  2. Draft a first reply that uses that classification.
Build an AI workflow in five minutes: the five stepsStep 1, create an app. Step 2, add a model provider key. Step 3, install the SDK. Step 4, write an entry function with two ctx.sendAI steps. Step 5, call runWorkflow and open the run in the dashboard. FIVE MINUTES, FIVE STEPSCreate an app0:001Create an appapp.dnotifier.comAdd a model key1:002Add a model keyAI Studio → ProvidersInstall the SDK2:003Install the SDKnpm i …/dnotifierWrite entry()3:004Write entry()two ctx.sendAI() stepsRun + see the graph4:005Run + see the graphrunWorkflow()Timings assume Node 18+ is installed and you already have a model provider API key.
Click a step.
Build an AI workflow in five minutes: the five steps
A two-step AI workflow that triages support ticketsA ticket goes into step 1, which asks the model to classify it as JSON. Plain code parses the JSON and stores it in ctx.state. Step 2 asks the model to draft a reply using that category and urgency. The result has category, urgency, summary and draft. THE TICKET-TRIAGE WORKFLOWTicketTicketctx.input1 · Classify1 · Classifyctx.sendAI() → JSONCode reads itCode reads itJSON.parse()2 · Draft reply2 · Draft replyctx.sendAI(){ "category": "billing", "urgency": "high" }Shared statectx.state.ticket · visible to every later stepTwo model calls with plain code between them. Each labeled step is recorded in the run trace.Result: { category, urgency, summary, draft }
Click a step.
A two-step AI workflow that triages support tickets

Minutes 0 to 2: App, key, SDK

If you did the 5-minute agent, skip this.

  1. Create an app at app.dnotifier.com and copy the app ID and secret. AI features need the Starter plan or above.
  2. Add your OpenAI key (or another provider's) in AI Studio → Providers.
  3. Install:
mkdir triage && cd triage
npm init -y && npm pkg set type=module
npm install @dnotifier-realtime/dnotifier

Minute 3: Write the workflow

Create triage.mjs:

// triage.mjs: a two-step AI workflow that triages a support ticket.
// Run: DNOTIFIER_APP_ID=... DNOTIFIER_SECRET=... node triage.mjs
import { DNotifier } from "@dnotifier-realtime/dnotifier";

const notifier = new DNotifier({
  appId: process.env.DNOTIFIER_APP_ID,
  secret: process.env.DNOTIFIER_SECRET,
  transport: "http",
  userId: "triage-script",
});
await notifier.connect();

const textOf = (res) => res?.data?.content ?? res?.content ?? "";

const triage = new DNotifier.Workflow({
  name: "ticket-triage",
  description: "Classify a support ticket, then draft a first reply",
  observability: true, // every step shows up in the dashboard under Workflows
  async entry(ctx) {
    // Step 1: classify. Ask for JSON so code, not prose, decides what happens next.
    const classified = await ctx.sendAI({
      message: {
        useKnowledgeBase: false,
        messages: [
          {
            role: "system",
            content:
              'Classify this support ticket. Reply with JSON only: ' +
              '{"category":"billing|bug|how-to|other","urgency":"low|normal|high","summary":"one sentence"}',
          },
          { role: "user", content: ctx.input },
        ],
      },
      saveHistory: false,
      label: "Classify ticket",
    });

    let ticket;
    try {
      ticket = JSON.parse(textOf(classified));
    } catch {
      ticket = { category: "other", urgency: "normal", summary: ctx.input.slice(0, 120) };
    }
    ctx.state.ticket = ticket;

    // Step 2: draft a reply that uses what step 1 found.
    const draft = await ctx.sendAI({
      message: {
        useKnowledgeBase: false,
        messages: [
          {
            role: "system",
            content:
              `You write first replies for a support team. The ticket is a ${ticket.category} issue ` +
              `with ${ticket.urgency} urgency. Be warm, specific and under 90 words. ` +
              `Don't promise refunds or dates.`,
          },
          { role: "user", content: ctx.input },
        ],
      },
      saveHistory: false,
      label: "Draft reply",
    });

    return { ...ticket, draft: textOf(draft) };
  },
});

const ticketText =
  process.argv[2] ??
  "Hi, I was charged twice for my Pro plan this month and I need the second charge reversed before Friday.";

const run = await notifier.runWorkflow({ workflow: triage, input: ticketText });

console.log(run.result);
console.log("executionId:", run.executionId);

A few things worth noticing:

  • The workflow is just a function. entry(ctx) runs top to bottom. If you can write an async function, you can write a workflow.
  • Step 1 asks for JSON. Making the model return structured data means code decides what happens next. If the JSON is broken, the catch gives a safe default instead of failing the whole run.
  • ctx.state holds shared data. Later steps (and the run trace) can see what earlier steps found.
  • label names each step. With observability: true, those names show up in the run trace in your dashboard.

Minute 4: Run it

DNOTIFIER_APP_ID=your-app-id DNOTIFIER_SECRET=your-secret node triage.mjs

You get back an object with category, urgency, summary and draft. For the sample ticket (a double charge with a Friday deadline) you should see billing and high, and a reply that acknowledges the deadline without promising a refund, because we told it not to.

Then open Workflows in the dashboard and find the run by its executionId. You should see "Classify ticket" and "Draft reply" recorded as steps, with their inputs and outputs. That is the part that saves you hours later.

The same workflow in Dart

// bin/triage.dart: the same two-step triage workflow in Dart.
// Run: dart run bin/triage.dart --define=DNOTIFIER_APP_ID=... --define=DNOTIFIER_SECRET=...
import 'dart:convert';

import 'package:dnotifier/dnotifier.dart';

const appId = String.fromEnvironment('DNOTIFIER_APP_ID');
const secret = String.fromEnvironment('DNOTIFIER_SECRET');

String textOf(dynamic res) =>
    (res is Map && res['data'] is Map) ? '${res['data']['content'] ?? ''}' : '$res';

Future<void> main(List<String> args) async {
  final notifier = DNotifier(
    appId: appId,
    secret: secret,
    transport: 'http',
    userId: 'triage-script',
    onConnected: () {},
  );
  await notifier.connect();

  final triage = DNotifier.Workflow(
    name: 'ticket-triage',
    observability: true,
    entry: (ctx) async {
      final ticketText = ctx.input as String;

      final classified = await ctx.sendAI(
        message: {
          'useKnowledgeBase': false,
          'messages': [
            {
              'role': 'system',
              'content': 'Classify this support ticket. Reply with JSON only: '
                  '{"category":"billing|bug|how-to|other","urgency":"low|normal|high","summary":"one sentence"}',
            },
            {'role': 'user', 'content': ticketText},
          ],
        },
        saveHistory: false,
        label: 'Classify ticket',
      );

      Map<String, dynamic> ticket;
      try {
        ticket = jsonDecode(textOf(classified)) as Map<String, dynamic>;
      } catch (_) {
        ticket = {'category': 'other', 'urgency': 'normal', 'summary': ticketText};
      }
      ctx.state['ticket'] = ticket;

      final draft = await ctx.sendAI(
        message: {
          'useKnowledgeBase': false,
          'messages': [
            {
              'role': 'system',
              'content': 'You write first replies for a support team. This is a '
                  '${ticket['category']} issue with ${ticket['urgency']} urgency. '
                  'Be warm, specific and under 90 words. Don\'t promise refunds or dates.',
            },
            {'role': 'user', 'content': ticketText},
          ],
        },
        saveHistory: false,
        label: 'Draft reply',
      );

      return {...ticket, 'draft': textOf(draft)};
    },
  );

  final run = await notifier.runWorkflow(
    workflow: triage,
    input: args.isNotEmpty
        ? args.first
        : 'I was charged twice for my Pro plan this month. Please reverse it before Friday.',
  );

  print(run.result);
  print('executionId: ${run.executionId}');
}
dart run bin/triage.dart --define=DNOTIFIER_APP_ID=... --define=DNOTIFIER_SECRET=...

Run it in the cloud

A workflow like this usually runs behind an API route (your help desk posts the ticket and gets the triage back) or from a queue consumer. Over HTTP it holds no open connection, so it fits the same container setup as the agent API in part 1:

Deploy to AWS

Deploy a DNotifier agent API on AWSAWS reference architecture. Web and mobile clients reach a Node API container through Load balancer. The container runs on Amazon ECS on Fargate, reads the DNotifier app ID and secret from Secrets Manager, uses RDS and sends logs to CloudWatch. It calls DNotifier over HTTPS; DNotifier calls Amazon Bedrock with your own credentials, or another provider. YOUR AWS ACCOUNTReact webReact webbrowserFlutter appFlutter appiOS · AndroidCloudFront + S3CloudFront + S3React buildLoad balancerLoad balancerALB · /api/*Node API containerAmazon ECS on FargateNode API container/api/agent · DNotifier SDKSecrets ManagerSecrets Managerapp ID + secretRDSRDSor DynamoDBCloudWatchCloudWatchlogs + alarmsAmazon BedrockAmazon Bedrockprovider: aws_bedrockDNotifier (hosted)DNotifieragents · workflowsknowledge · tracesOther providersOther providersOpenAI, Anthropic…Only the container holds the DNotifier secret, read from the secret store at start.
PieceAWS serviceWhy
React buildS3 bucket behind CloudFrontStatic files on a CDN. Add a second CloudFront behavior for /api/* pointing at the load balancer, so the browser calls the same domain.
Node containerAmazon ECS on Fargate, behind an Application Load BalancerLong-lived containers handle server-sent events and WebSockets without timeouts. (App Runner moved to maintenance mode in 2026; AWS points new apps to ECS Express Mode.)
App ID + secretAWS Secrets ManagerInjected into the task as environment variables through the task definition's secrets block. Never baked into the image.
Your dataAmazon RDS or DynamoDBOnly your tool code talks to it, from inside the VPC.
LogsCloudWatch LogsLog the DNotifier executionId next to each request, so you can jump from a CloudWatch line to the run trace.
Models (optional)Amazon Bedrock via the aws_bedrock providerAdd Bedrock in AI Studio → Providers if you want inference billed to your AWS account. Any other provider works too.
# 1. Store the credentials (once)
aws secretsmanager create-secret --name dnotifier/prod \
  --secret-string '{"DNOTIFIER_APP_ID":"<app-id>","DNOTIFIER_SECRET":"<secret>"}'

# 2. Build and push the image
aws ecr create-repository --repository-name order-help-api
aws ecr get-login-password | docker login --username AWS --password-stdin <account>.dkr.ecr.<region>.amazonaws.com
docker build -t <account>.dkr.ecr.<region>.amazonaws.com/order-help-api:1 .
docker push <account>.dkr.ecr.<region>.amazonaws.com/order-help-api:1

# 3. In the ECS task definition, pull the values from Secrets Manager:
#   "secrets": [
#     { "name": "DNOTIFIER_APP_ID", "valueFrom": "<secret-arn>:DNOTIFIER_APP_ID::" },
#     { "name": "DNOTIFIER_SECRET", "valueFrom": "<secret-arn>:DNOTIFIER_SECRET::" }
#   ],
#   "portMappings": [{ "containerPort": 3001 }]

Watch out: Set the load balancer's idle timeout above your longest agent run if you use the streaming endpoint.

Deploy to Azure

Deploy a DNotifier agent API on AzureAzure reference architecture. Web and mobile clients reach a Node API container through Container Apps ingress. The container runs on Azure Container Apps, reads the DNotifier app ID and secret from Key Vault, uses PostgreSQL and sends logs to Azure Monitor. It calls DNotifier over HTTPS; DNotifier calls Azure OpenAI with your own credentials, or another provider. YOUR AZURE SUBSCRIPTIONReact webReact webbrowserFlutter appFlutter appiOS · AndroidStatic Web AppsStatic Web AppsReact buildContainer Apps ingressContainer Apps ingressHTTPSNode API containerAzure Container AppsNode API container/api/agent · DNotifier SDKKey VaultKey Vaultapp ID + secretPostgreSQLPostgreSQLor Cosmos DBAzure MonitorAzure MonitorApp InsightsAzure OpenAIAzure OpenAIprovider: azure_aiDNotifier (hosted)DNotifieragents · workflowsknowledge · tracesOther providersOther providersOpenAI, Anthropic…Only the container holds the DNotifier secret, read from the secret store at start.
PieceAzure serviceWhy
React buildAzure Static Web AppsLink the Container App as the site's backend (Standard plan) so /api calls stay on the same domain, or call the API's own URL with CORS.
Node containerAzure Container AppsManaged containers with HTTPS ingress, scale rules and long-lived connections.
App ID + secretContainer Apps secrets, backed by Key VaultStore the secret in Key Vault and reference it from the app with a managed identity; expose it as an env var with secretref:.
Your dataAzure Database for PostgreSQL or Cosmos DBReachable only from your app's environment.
LogsAzure Monitor / Application InsightsLog the DNotifier executionId with each request.
Models (optional)Azure OpenAI via the azure_ai providerKeeps model usage on your Azure bill and in your chosen region. Any other provider works too.
# 1. Build from source and deploy (creates the environment if needed)
az containerapp up --name order-help-api --resource-group dnotifier-rg \
  --location westeurope --source . --ingress external --target-port 3001

# 2. Add the secret and point env vars at it
az containerapp secret set -n order-help-api -g dnotifier-rg \
  --secrets dnotifier-secret=<secret>
az containerapp update -n order-help-api -g dnotifier-rg \
  --set-env-vars DNOTIFIER_APP_ID=<app-id> DNOTIFIER_SECRET=secretref:dnotifier-secret NODE_ENV=production

Watch out: If you use Static Web Apps linked backends, the API is only reachable through the site; that's usually what you want.

Deploy to Google Cloud

Deploy a DNotifier agent API on Google CloudGoogle Cloud reference architecture. Web and mobile clients reach a Node API container through Cloud Run HTTPS. The container runs on Cloud Run service, reads the DNotifier app ID and secret from Secret Manager, uses Cloud SQL and sends logs to Cloud Logging. It calls DNotifier over HTTPS; DNotifier calls Gemini API with your own credentials, or another provider. YOUR GOOGLE CLOUD PROJECTReact webReact webbrowserFlutter appFlutter appiOS · AndroidFirebase HostingFirebase HostingReact buildCloud Run HTTPSCloud Run HTTPS/api rewriteNode API containerCloud Run serviceNode API container/api/agent · DNotifier SDKSecret ManagerSecret Managerapp ID + secretCloud SQLCloud SQLor FirestoreCloud LoggingCloud Logginglogs + alertsGemini APIGemini APIprovider: google_geminiDNotifier (hosted)DNotifieragents · workflowsknowledge · tracesOther providersOther providersOpenAI, Anthropic…Only the container holds the DNotifier secret, read from the secret store at start.
PieceGoogle Cloud serviceWhy
React buildFirebase HostingRewrite /api/** to the Cloud Run service so the browser calls the same domain. Hosting-to-Cloud Run requests time out after 60 seconds, so keep agent runs short or call Cloud Run's URL directly for long streams.
Node containerCloud RunDeploy straight from source. Cloud Run sets PORT, which the example server already reads.
App ID + secretSecret ManagerMounted as env vars with --set-secrets. Never in the image or in the repo.
Your dataCloud SQL or FirestoreOnly your tool code reads it.
LogsCloud LoggingLog the DNotifier executionId with each request.
Models (optional)Gemini via the google_gemini providerAdd your Gemini key in AI Studio → Providers. Any other provider works too.
# 1. Store the secret (once)
printf '%s' '<secret>' | gcloud secrets create dnotifier-secret --data-file=-

# 2. Build from source and deploy
gcloud run deploy order-help-api --source . --region europe-west1 \
  --set-env-vars DNOTIFIER_APP_ID=<app-id>,NODE_ENV=production \
  --set-secrets DNOTIFIER_SECRET=dnotifier-secret:latest \
  --allow-unauthenticated   # your own auth still runs inside the app

Watch out: Cloud Run scales to zero by default. The first request after a quiet period pays a cold start; set --min-instances 1 if that matters.

# Dockerfile (same on every cloud)
FROM node:22-slim
WORKDIR /app
COPY package*.json ./
RUN npm install --omit=dev
COPY . .
ENV NODE_ENV=production
EXPOSE 3001
CMD ["node", "index.js"]

Where to take it next

Two steps in a row is the simplest pattern. Real processes need a few more:

  • Parallel steps, when two lookups don't depend on each other.
  • Routing, when the classification decides which branch runs.
  • Human approval, when a person should check the draft before it's sent.
  • Agents as steps, when one step needs to call tools on its own.

All four are in How to Build an AI Workflow in Code, where we build an inbound lead workflow that researches, scores, routes and waits for a sign-off. To call this workflow from your app, put it behind an API route the same way we did with the agent in part 1.

Workflows you write in code, traced step by step. Create your app · Workflows · Build a workflow (docs)

Next in the series: Part 5: How to Build an AI Workflow in Code

Previous: Part 3: AI Agent Architecture

Get the code. Every example in this series, as runnable projects: dnotifier-agent-workflow-examples.zip. Run each one with your own app ID, secret and model key.

FAQ

What is an AI workflow?

A set of steps that always run in a defined order, where one or more steps use an AI model, for example classify, then draft, then route. Unlike an agent, the workflow's path is set by your code.

Do I need a drag-and-drop tool to build an AI workflow?

No. Visual tools are good for quick automations. Writing the workflow in code gives you version control, tests, code review and the full power of your language. With DNotifier, a workflow is an async function.

How do I pass data between workflow steps?

Use ordinary variables inside entry(ctx), or ctx.state when you want the value shared with agents and visible in the run trace.

What's the difference between an AI workflow and an AI agent?

In a workflow, your code decides the steps. In an agent, the model decides which tools to call and when. Many real systems combine them: a workflow whose steps are agents. See How to Build a Multi-Agent Workflow.

Can I use different models for different steps?

Yes. ctx.sendAI() accepts provider and model, so a cheap model can classify and a stronger one can write.

Tags

#workflows#how-to#nodejs#dart#automation#quickstart

Keep reading

Related articles

View all →