<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/">
    <channel>
        <title>Zarif Automates — Automation Workflows</title>
        <link>https://www.zarifautomates.com/blog/pillar/automation-workflows</link>
        <description>Automations that keep running once real work flows through them: n8n, webhooks, APIs, process templates, and when to use a fixed workflow instead of an agent.</description>
        <lastBuildDate>Fri, 09 Oct 2026 16:43:05 GMT</lastBuildDate>
        <docs>https://validator.w3.org/feed/docs/rss2.html</docs>
        <generator>https://github.com/jpmonette/feed</generator>
        <language>en</language>
        <image>
            <title>Zarif Automates — Automation Workflows</title>
            <url>https://www.zarifautomates.com/images/zarif-portrait.jpg</url>
            <link>https://www.zarifautomates.com/blog/pillar/automation-workflows</link>
        </image>
        <copyright>All rights reserved 2026, Zarif Choudhury</copyright>
        <item>
            <title><![CDATA[Build an Invoice Pipeline in n8n With a Review Branch]]></title>
            <link>https://www.zarifautomates.com/blog/invoice-pipeline-in-n8n</link>
            <guid isPermaLink="false">https://www.zarifautomates.com/blog/invoice-pipeline-in-n8n</guid>
            <pubDate>Sat, 26 Sep 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Import a tested n8n workflow that validates extracted invoice fields and routes exceptions to review, then swap in Gmail, Datalab and Sheets.]]></description>
            <content:encoded><![CDATA[This lesson gives you an n8n workflow you can import and run in a few minutes. It takes invoice data that an AI has already read off a PDF, checks it, and splits it in two: invoices that are safe to save, and invoices a person needs to look at first.

You need an n8n editor, or Node 24 if you'd rather run it from the command line. The lab half needs no accounts or API keys.

Here's the problem it solves. Getting an AI to read an invoice is the easy part. The hard part is deciding which readings can go straight into your spreadsheet and which ones can't. A total that doesn't add up, a missing invoice number, or the same invoice sent twice should stop and wait for a human.

In the lab, eight made-up results go through a check step and a sorting step. Two land as accepted invoice rows. Six land in a review queue, each with the reason it was stopped. The second half shows how to swap the made-up parts for a Gmail inbox, the Datalab extraction API and Google Sheets.

The workflow was imported and run with n8n 2.40.7 on Node 24.21.0 on September 26, 2026, using the real n8n engine and JavaScript Code nodes. The extraction results are synthetic, shaped like the responses in Datalab's docs. So the run tests the sorting, not how well any AI reads invoices. The live nodes in the second half are set up from n8n's and Datalab's docs and were not run.

This is part 6 of the Document AI series. Parts 1 to 5 cover what these APIs do and how the vendors compare. This one puts one of them to work. If you haven't picked an extractor yet, start with [Extend vs Datalab vs other parsers](/blog/extend-vs-datalab-vs-other-document-parsers).

## 1. The shape of the pipeline

```text
Live version (you build this in section 5)
  Gmail Trigger → Submit to Datalab → Wait → Check extraction status
    → Attach source → Validate invoice fields → Needs review?
        ├─ true  → Google Sheets: Review tab
        └─ false → Google Sheets: Invoices tab

Lab version (you import this now)
  Run the lab → Simulated Datalab results → Validate invoice fields → Needs review?
                                                                      ├─ true  → Review queue rows
                                                                      └─ false → Accepted invoice rows
```

The two versions share the middle. **Validate invoice fields** and **Needs review?** are identical in both, so the rules you test on fake invoices are the same rules that run on real ones.

Only the ends change. At the start, a Manual Trigger and a Code node full of test cases become an email trigger and two calls to Datalab. At the finish, the two Code nodes become Google Sheets writes.

## 2. Import and run the lab workflow

Copy the JSON at the end of this section into a file named `invoice-pipeline.json`. In the n8n editor, create a new workflow, open its menu, choose **Import from File** and pick the file. The [import guide](https://docs.n8n.io/build/manage-workflows/export-and-import) covers the options. The workflow has `active: false`, a Manual Trigger, no credentials and no HTTP Request node, so nothing leaves your machine.

Select **Execute Workflow**. The **Needs review?** node should show 6 items on its true output and 2 on its false output.

To run it from the command line instead, use an empty directory. n8n 2.40.7 requires Node 24 or later, and it refused to start on Node 22 in this run.

```bash
node --version   # must print v24 or later
npm init -y
npm install n8n@2.40.7
export N8N_USER_FOLDER="$PWD/n8n-test-state"
export N8N_DIAGNOSTICS_ENABLED=false
export N8N_VERSION_NOTIFICATIONS_ENABLED=false
export N8N_TEMPLATES_ENABLED=false
export N8N_PERSONALIZATION_ENABLED=false
export N8N_RUNNERS_BROKER_LISTEN_ADDRESS=127.0.0.1
export N8N_RUNNERS_BROKER_PORT=15691
npx n8n import:workflow --input=invoice-pipeline.json
npx n8n execute --id=ZarifInvoiceLab01 --rawOutput
```

The separate `N8N_USER_FOLDER` keeps this test away from any n8n setup you already use. Importing a workflow with an ID that already exists can overwrite it. The [CLI docs](https://docs.n8n.io/deploy/host-n8n/configure-n8n/use-the-command-line) describe `import:workflow` and `execute`.

Two things came up in the run. If you installed n8n under an older Node and then switched, run `npm rebuild isolated-vm`, or n8n can't evaluate expressions. And a warning that the Python task runner is missing is harmless here, because every Code node is JavaScript.

The full export:

```json
{
  "id": "ZarifInvoiceLab01",
  "name": "Invoice pipeline, local fixtures",
  "active": false,
  "nodes": [
    {
      "id": "1",
      "name": "Run the lab",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "parameters": {}
    },
    {
      "id": "2",
      "name": "Simulated Datalab results",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "// SIMULATED: each item mimics a completed Datalab /api/v1/extract poll\n// response in fast mode (fields, _citations, _score). No API is called.\nconst ok = (fields, scores) => {\n  const out = {};\n  for (const [key, value] of Object.entries(fields)) {\n    out[key] = value;\n    out[`${key}_citations`] = [`block_${key}`];\n    if (scores) out[`${key}_score`] = { score: scores[key] ?? 5, reasoning: 'fixture' };\n  }\n  return out;\n};\nconst lines = [\n  { description: 'Paper, A4, 10 boxes', quantity: 10, unit_price: 40, amount: 400 },\n  { description: 'Toner cartridge', quantity: 4, unit_price: 150, amount: 600 },\n];\nconst base = { invoice_number: 'INV-1001', vendor_name: 'Acme Supply Co.', invoice_date: '2026-09-14', currency: 'USD', subtotal: 1000, tax: 80, total_amount: 1080, line_items: lines };\nconst cases = [\n  ['clean', base, {}],\n  ['total_mismatch', { ...base, invoice_number: 'INV-1002', total_amount: 1008 }, {}],\n  ['missing_number', { ...base, invoice_number: null }, {}],\n  ['low_confidence', { ...base, invoice_number: 'INV-1004' }, { total_amount: 2 }],\n  ['duplicate', base, {}],\n  ['failed', null, null],\n  ['no_scores', { ...base, invoice_number: 'INV-1007' }, null],\n  ['clean_eur', { ...base, invoice_number: 'G-7731', vendor_name: 'Globex GmbH', currency: 'EUR' }, {}],\n];\nreturn cases.map(([name, fields, scores], i) => {\n  const source = { message_id: `msg-${i + 1}`, filename: `${name}.pdf` };\n  if (!fields) {\n    return { json: { source, poll: { status: 'failed', success: false, error: 'fixture: document could not be processed' } } };\n  }\n  const extraction = ok(fields, scores);\n  const values = Object.entries(extraction).filter(([k]) => k.endsWith('_score')).map(([, v]) => v.score);\n  return {\n    json: {\n      source,\n      poll: {\n        status: 'complete',\n        success: true,\n        page_count: 1,\n        extraction_schema_json: JSON.stringify(extraction),\n        extraction_score_average: values.length ? values.reduce((a, b) => a + b, 0) / values.length : null,\n      },\n    },\n  };\n});\n"
      }
    },
    {
      "id": "3",
      "name": "Validate invoice fields",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        440,
        0
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const REQUIRED = ['invoice_number', 'vendor_name', 'invoice_date', 'currency', 'total_amount'];\nconst CURRENCIES = ['USD', 'EUR'];\nconst MIN_SCORE = 4;\nconst cents = (n) => Math.round(Number(n) * 100);\nconst seen = new Set();\n\nreturn $input.all().map((item, index) => {\n  const { source, poll } = item.json;\n  const reasons = [];\n  let fields = {};\n\n  if (poll.status !== 'complete' || poll.success === false) {\n    reasons.push(`extraction_failed: ${poll.error ?? poll.status}`);\n  } else {\n    try {\n      fields = typeof poll.extraction_schema_json === 'string'\n        ? JSON.parse(poll.extraction_schema_json)\n        : poll.extraction_schema_json;\n    } catch (error) {\n      reasons.push('unparseable_extraction');\n    }\n  }\n\n  if (reasons.length === 0) {\n    for (const key of REQUIRED) {\n      if (fields[key] === null || fields[key] === undefined || fields[key] === '') reasons.push(`missing:${key}`);\n    }\n    const date = fields.invoice_date;\n    if (date && (!/^\\d{4}-\\d{2}-\\d{2}$/.test(date) || Number.isNaN(Date.parse(date)))) reasons.push('invalid_date');\n    if (fields.currency && !CURRENCIES.includes(fields.currency)) reasons.push('unexpected_currency');\n\n    const lineSum = (fields.line_items ?? []).reduce((sum, line) => sum + cents(line.amount), 0);\n    if (fields.line_items?.length && lineSum !== cents(fields.subtotal)) reasons.push('line_items_do_not_sum_to_subtotal');\n    if (cents(fields.subtotal) + cents(fields.tax ?? 0) !== cents(fields.total_amount)) reasons.push('subtotal_plus_tax_not_total');\n\n    if (poll.extraction_score_average === null || poll.extraction_score_average === undefined) {\n      reasons.push('scores_unavailable');\n    } else {\n      for (const key of REQUIRED) {\n        const score = fields[`${key}_score`]?.score;\n        if (typeof score === 'number' && score < MIN_SCORE) reasons.push(`low_confidence:${key}`);\n      }\n    }\n\n    const key = `${String(fields.vendor_name).toLowerCase()}|${fields.invoice_number}`;\n    if (fields.invoice_number && seen.has(key)) reasons.push('duplicate_in_batch');\n    seen.add(key);\n  }\n\n  const invoice = Object.fromEntries(\n    [...REQUIRED, 'subtotal', 'tax'].map((key) => [key, fields[key] ?? null]),\n  );\n  return {\n    json: { ...source, ...invoice, reasons, needs_review: reasons.length > 0 },\n    pairedItem: { item: index },\n  };\n});\n"
      }
    },
    {
      "id": "4",
      "name": "Needs review?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        660,
        0
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "needs-review",
              "leftValue": "={{ $json.needs_review }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "5",
      "name": "Review queue rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        -100
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $input.all().map((item, index) => ({\n  json: {\n    message_id: item.json.message_id,\n    source_file: item.json.filename,\n    reasons: item.json.reasons.join('; '),\n    extracted: JSON.stringify({\n      invoice_number: item.json.invoice_number,\n      vendor_name: item.json.vendor_name,\n      total_amount: item.json.total_amount,\n      currency: item.json.currency,\n    }),\n    status: 'awaiting_review',\n    decision: '',\n    reviewer: '',\n  },\n  pairedItem: { item: index },\n}));\n"
      }
    },
    {
      "id": "6",
      "name": "Accepted invoice rows",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        100
      ],
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "return $input.all().map((item, index) => ({\n  json: {\n    invoice_number: item.json.invoice_number,\n    vendor_name: item.json.vendor_name,\n    invoice_date: item.json.invoice_date,\n    currency: item.json.currency,\n    total_amount: item.json.total_amount,\n    source_file: item.json.filename,\n    message_id: item.json.message_id,\n    status: 'accepted',\n  },\n  pairedItem: { item: index },\n}));\n"
      }
    }
  ],
  "connections": {
    "Run the lab": {
      "main": [
        [
          {
            "node": "Simulated Datalab results",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simulated Datalab results": {
      "main": [
        [
          {
            "node": "Validate invoice fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate invoice fields": {
      "main": [
        [
          {
            "node": "Needs review?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Needs review?": {
      "main": [
        [
          {
            "node": "Review queue rows",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Accepted invoice rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "pinData": {},
  "tags": []
}
```

## 3. What each node does

| Node | Type | What to inspect |
| --- | --- | --- |
| Run the lab | Manual Trigger | Starts one execution when you click |
| Simulated Datalab results | Code | Eight fixtures shaped like a completed Datalab extract poll in fast mode. **Simulated.** |
| Validate invoice fields | Code | Required fields, date format, currency list, arithmetic, confidence scores, duplicates in the batch |
| Needs review? | If | Strict boolean check on `needs_review` |
| Review queue rows | Code | One row per exception, with reasons joined and the extracted values kept |
| Accepted invoice rows | Code | One clean row per invoice for the ledger sheet |

The test cases copy the response format in [Datalab's structured extraction docs](https://documentation.datalab.to/docs/recipes/structured-extraction/api-overview). With Datalab, you send a file, then keep checking back until the job is done. Each check is called a poll. A finished poll carries `status`, `success`, `page_count` and `extraction_schema_json`, which is a JSON string holding your fields plus a `_citations` list for each one.

In fast mode, [Datalab's confidence scoring](https://documentation.datalab.to/docs/recipes/structured-extraction/confidence-scoring) also grades each field. It adds a `_score` object per field, from 1 for no clear evidence to 5 for high confidence, plus an `extraction_score_average`. The docs, read on 2026-09-26, say scoring is in beta, runs only in fast mode, and can fail on its own. So a missing average means "unavailable", not "zero".

That's why the validator treats a missing score as its own review reason. Counting it as a pass would let a result through with no confidence signal at all. Counting it as a fail would blur "the model was unsure" with "the score never arrived".

Here is the check logic from the Code node, formatted for reading. It runs once over all items together, which is how it can spot the same invoice twice in one batch.

```javascript
const REQUIRED = ['invoice_number', 'vendor_name', 'invoice_date', 'currency', 'total_amount'];
const CURRENCIES = ['USD', 'EUR'];
const MIN_SCORE = 4;
const cents = (n) => Math.round(Number(n) * 100);
const seen = new Set();

return $input.all().map((item, index) => {
  const { source, poll } = item.json;
  const reasons = [];
  let fields = {};

  if (poll.status !== 'complete' || poll.success === false) {
    reasons.push(`extraction_failed: ${poll.error ?? poll.status}`);
  } else {
    try {
      fields = typeof poll.extraction_schema_json === 'string'
        ? JSON.parse(poll.extraction_schema_json)
        : poll.extraction_schema_json;
    } catch (error) {
      reasons.push('unparseable_extraction');
    }
  }

  if (reasons.length === 0) {
    for (const key of REQUIRED) {
      if (fields[key] === null || fields[key] === undefined || fields[key] === '') reasons.push(`missing:${key}`);
    }
    const date = fields.invoice_date;
    if (date && (!/^\d{4}-\d{2}-\d{2}$/.test(date) || Number.isNaN(Date.parse(date)))) reasons.push('invalid_date');
    if (fields.currency && !CURRENCIES.includes(fields.currency)) reasons.push('unexpected_currency');

    const lineSum = (fields.line_items ?? []).reduce((sum, line) => sum + cents(line.amount), 0);
    if (fields.line_items?.length && lineSum !== cents(fields.subtotal)) reasons.push('line_items_do_not_sum_to_subtotal');
    if (cents(fields.subtotal) + cents(fields.tax ?? 0) !== cents(fields.total_amount)) reasons.push('subtotal_plus_tax_not_total');

    if (poll.extraction_score_average === null || poll.extraction_score_average === undefined) {
      reasons.push('scores_unavailable');
    } else {
      for (const key of REQUIRED) {
        const score = fields[`${key}_score`]?.score;
        if (typeof score === 'number' && score < MIN_SCORE) reasons.push(`low_confidence:${key}`);
      }
    }

    const key = `${String(fields.vendor_name).toLowerCase()}|${fields.invoice_number}`;
    if (fields.invoice_number && seen.has(key)) reasons.push('duplicate_in_batch');
    seen.add(key);
  }

  const invoice = Object.fromEntries(
    [...REQUIRED, 'subtotal', 'tax'].map((key) => [key, fields[key] ?? null]),
  );
  return {
    json: { ...source, ...invoice, reasons, needs_review: reasons.length > 0 },
    pairedItem: { item: index },
  };
});
```

None of these checks use AI. The model reads the invoice, and plain code decides whether that reading is fit to store. The same input gets the same answer every time.

Amounts are compared in whole cents. Computers store decimals like 0.1 slightly off, and comparing in cents stops that rounding from passing a total that's wrong by a fraction.

## 4. Read the eight results

| Fixture | What is wrong | Route | Reason recorded |
| --- | --- | --- | --- |
| `clean.pdf` | Nothing | Accepted | |
| `total_mismatch.pdf` | Total 1,008 where subtotal plus tax is 1,080 | Review | `subtotal_plus_tax_not_total` |
| `missing_number.pdf` | No invoice number | Review | `missing:invoice_number` |
| `low_confidence.pdf` | Total scored 2 of 5 | Review | `low_confidence:total_amount` |
| `duplicate.pdf` | Same vendor and number as `clean.pdf` | Review | `duplicate_in_batch` |
| `failed.pdf` | Extraction job failed | Review | `extraction_failed: ...` |
| `no_scores.pdf` | Scoring never arrived | Review | `scores_unavailable` |
| `clean_eur.pdf` | Nothing, in euros | Accepted | |

An accepted row from the recorded run:

```json
{
  "invoice_number": "INV-1001",
  "vendor_name": "Acme Supply Co.",
  "invoice_date": "2026-09-14",
  "currency": "USD",
  "total_amount": 1080,
  "source_file": "clean.pdf",
  "message_id": "msg-1",
  "status": "accepted"
}
```

These counts describe the rules, not an extractor. Eight test cases in, six to review, two accepted. A real inbox will have a very different mix. [Measuring extraction accuracy field by field](/blog/measuring-document-extraction-accuracy) is how you find out what yours is.

Now change one rule and run it again. Open **Validate invoice fields** and change `const MIN_SCORE = 4;` to `const MIN_SCORE = 2;`. Execute again. The low-confidence test case now passes, and **Needs review?** shows 5 and 3.

That one number is your review bar. Lower it and people review less, but more bad readings get saved. Put it back to 4 before you continue.

## 5. Swap in the live nodes

This half is setup taken from the docs, not a recorded run. Build it in a copy of the workflow, keep the copy inactive, and test it with a handful of invoices you're allowed to send to an outside company's API.

**Intake: Gmail Trigger.** Replace **Run the lab** with a [Gmail Trigger](https://docs.n8n.io/integrations/builtin/trigger-nodes/n8n-nodes-base.gmailtrigger/). Use the **Search** filter to narrow it, for example to messages with a PDF attachment sent to an invoices address. Turn **Simplify** off. In the node's 2.40.7 source, the **Options** collection with **Download Attachments** only appears then. Switch **Download Attachments** on. The first attachment arrives as binary data named `attachment_0`, from the default **Attachment Prefix**. If invoices land in a folder instead, n8n's [Local File Trigger](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.localfiletrigger/) watches a path, but its docs say it is self-hosted only and disabled by default from n8n 2.0.

**Extract: HTTP Request to Datalab.** Replace **Simulated Datalab results** with three nodes.

1. **Submit to Datalab**, an [HTTP Request](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.httprequest/) node. Method POST, URL `https://www.datalab.to/api/v1/extract`. Authentication: a Header Auth credential with the header name `X-API-Key`, which is the header Datalab's docs use. Body Content Type **Form-Data**. Add a parameter of type **n8n Binary File** named `file` with **Input Data Field Name** set to `attachment_0`. Add text parameters `page_schema`, holding your JSON schema as a string, and `extraction_mode` set to `fast` so scores come back.
2. **Wait**, a [Wait](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.wait/) node set to **After Time Interval**, a few seconds.
3. **Check extraction status**, a second HTTP Request with method GET, the same credential, and the URL set to the `request_check_url` from the submit response. Follow it with an [If](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.if/) node that sends anything whose `status` is not `complete` or `failed` back to **Wait**. Cap the loop with a counter so a stuck job becomes a review item instead of an endless execution.

The Datalab docs also list a `webhook_url` parameter on the extract endpoint. Instead of you checking back, Datalab calls an n8n Webhook node when the job is done. That splits the pipeline into two workflows, so start with polling.

**Attach source.** The validator expects each item as `source` plus `poll`. Add an Edit Fields (Set) or Code node that builds `source` from the Gmail message ID and attachment file name, and sets `poll` to the status response. Keep the message ID: it is what a reviewer uses to find the original email.

**Validate and route.** Leave **Validate invoice fields** and **Needs review?** as they are. One catch: the duplicate check only sees one execution. Each email starts a fresh execution, so an invoice sent twice would pass. Before going live, look up the vendor and invoice number in the Invoices sheet or a database, and send matches to review.

**Write: Google Sheets.** Replace both Code nodes at the end with [Google Sheets](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-base.googlesheets/) nodes using the **Append Row** operation, one pointed at an Invoices tab and one at a Review tab. Keep the Code nodes' output shape as your column list. The review tab becomes the queue: a reviewer fills `decision` and `reviewer`, and a separate workflow picks up approved rows. The [review queue post](/blog/designing-the-document-review-queue) covers what that screen needs.

**Errors.** Set **Retry On Fail** in the settings of both HTTP Request nodes for rate limits, and add an error workflow with an [Error Trigger](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.errortrigger/) so a failed execution alerts someone. On 2026-09-26 Datalab's [limits page](https://documentation.datalab.to/docs/common/limits) listed 10 requests per minute for the free tier and its pricing page listed 25, so plan for the lower number until you confirm yours. The [ticket-triage lab](/blog/how-to-use-n8n-for-advanced-ai-workflow-automation) explains why an expected rejection and an unexpected crash deserve different handling.

## 6. Before real invoices go through

- **Test the live half with the same eight cases.** Make PDFs that reproduce each fixture, send them through, and check you get the same routes. If a fixture that should go to review lands in the Invoices tab, stop there.
- **Keep the original file.** Store the attachment or its Gmail message ID with every row, accepted or not. An auditor or a reviewer will need it.
- **Decide what the sheet is.** A sheet is fine for a few dozen invoices a week. Past that, or once two people review at the same time, move the queue to a database that refuses a second row with the same vendor and invoice number.
- **Check the data terms.** Sending invoices to any extraction API sends vendor names, bank details and amounts to a third party. Confirm retention and processing location with the vendor first.

By now you should have the lab workflow imported, the 6 and 2 split, and the 5 and 3 split after the threshold change. Next in the series: [measure extraction accuracy field by field](/blog/measuring-document-extraction-accuracy), so the threshold you just moved rests on numbers. The terms used here are defined in the [Document AI glossary](/blog/document-ai-glossary). For background on Datalab's modes, see [Datalab in practice](/blog/datalab-in-practice-marker-surya-chandra).]]></content:encoded>
            <author>Zarif</author>
            <category>document ai</category>
            <category>document processing</category>
            <category>ai invoice processing workflow</category>
            <category>n8n workflow</category>
            <category>invoice ocr</category>
        </item>
        <item>
            <title><![CDATA[Build an n8n Ticket-Triage Workflow and Test Its Failure Paths]]></title>
            <link>https://www.zarifautomates.com/blog/how-to-use-n8n-for-advanced-ai-workflow-automation</link>
            <guid isPermaLink="false">https://www.zarifautomates.com/blog/how-to-use-n8n-for-advanced-ai-workflow-automation</guid>
            <pubDate>Thu, 17 Sep 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Import a credential-free n8n workflow, run eight ticket-triage fixtures, and inspect review, duplicate, invalid-output and stale-record branches.]]></description>
            <content:encoded><![CDATA[A workflow that labels one clean support ticket is easy to show off. The real test is what happens when the same event arrives twice, the ticket doesn't exist, or the model sends back something your app can't use.

This lesson gives you an n8n workflow with those cases already built in. You import it, run it, and watch eight made-up events go through it. Each one gets checked, matched to a ticket, given a canned model answer, and either held for a person to review or rejected. Two end up waiting for review. Six are rejected, each with a reason. Nothing sends a message or changes a ticket.

[Download the inactive workflow JSON](/downloads/agent-course/n8n-ticket-triage-v1.json) or [get the workflow, input fixtures and recorded results together](/downloads/agent-course/n8n-ticket-example-v1.zip).

The workflow was executed locally with **n8n 2.39.7 and Node 24.19.0 on September 17, 2026**. It runs on the real n8n engine with JavaScript Code nodes. The model's answers are written in advance, not generated, so the results show how the workflow routes things, not how good any model is.

## 1. Import it without publishing

If you already use n8n's editor, create a new workflow, open its menu and choose **Import from File**. Select the downloaded JSON, look over the ten nodes, and leave the workflow unpublished. The file has `active: false`, one Manual Trigger, no credentials, no HTTP Request node and no schedule, so it can't reach anything outside n8n. The [official import guide](https://docs.n8n.io/build/manage-workflows/export-and-import) explains the import options.

The Manual Trigger means it only runs when you click. Select **Execute Workflow**, then open the three nodes at the end of the flow: **Review items**, **Rejected events**, and **Rejected proposals**. They should hold two, two and four items.

To run it from the command line instead, make a new empty folder on a machine with Node 24 installed. Save the JSON there as `ticket-triage.json`. These macOS/Linux commands install the tested n8n version and keep its data in its own folder:

```bash
node --version
npm init -y
npm install n8n@2.39.7
export N8N_USER_FOLDER="$PWD/n8n-test-state"
export N8N_DIAGNOSTICS_ENABLED=false
export N8N_VERSION_NOTIFICATIONS_ENABLED=false
export N8N_TEMPLATES_ENABLED=false
export N8N_PERSONALIZATION_ENABLED=false
export N8N_RUNNERS_BROKER_LISTEN_ADDRESS=127.0.0.1
export N8N_RUNNERS_BROKER_PORT=15689
npx n8n import:workflow --input=ticket-triage.json
npx n8n execute --id=ZarifTicketLab01 --rawOutput
```

Keep that separate folder for this exercise. If you import into an n8n setup that already has a workflow with the same ID, the import can overwrite it. If port 15689 is taken, pick another local port. You don't need a public server or tunnel.

The [Server CLI documentation](https://docs.n8n.io/deploy/host-n8n/configure-n8n/use-the-command-line) covers importing a saved workflow and running it by ID. The tested release rejects the older `execute --file` shortcut, so import first. You may see startup messages before the JSON results. The recorded run also logged that the optional Python runner was unavailable. That's expected here. The JS Task Runner started and ran the Code nodes.

## 2. Follow the data through the nodes

```text
Manual test → Synthetic events → Validate events → Event valid?
                                                   ├─ false → Rejected events
                                                   └─ true  → Lookup and model fixture
                                                              → Validate proposals
                                                              → Proposal valid?
                                                                 ├─ true  → Review items
                                                                 └─ false → Rejected proposals
```

Every Code node is set to **Run Once for All Items**, so it sees the whole batch at once. In the [Code node's all-items mode](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.code), `$input.all()` hands you every input item. Each node returns objects with `json` data and uses `pairedItem` to remember which input each output came from.

| Node | Configuration to inspect |
| --- | --- |
| Synthetic events | Eight explicit input objects, including failures |
| Validate events | Required field types; integer version; duplicate IDs within this batch |
| Event valid? | Strict Boolean condition on `event_valid`; false output goes to Rejected events |
| Lookup and model fixture | Two synthetic tickets at version 3; controlled good, invalid and malformed model output |
| Validate proposals | Ticket exists; version matches; JSON has exactly one allowed label |
| Proposal valid? | Strict Boolean condition on `proposal_valid` |
| Review items | Emits a proposal with `state: awaiting_review` and `applied: false` |
| Rejected events / proposals | Retain event ID and reason; never mark the change applied |

The lookup and model step is a fixture on purpose, meaning it returns answers written in advance. You can see every input that reaches it and make it fail on demand, without paying for a model call or touching another system.

## 3. Read the eight results

The event `evt-1` appears twice. The first copy is accepted for review. The second is rejected as a repeat in the same run. Here's what the recorded run produced:

| Event | Case | Result |
| --- | --- | --- |
| `evt-1`, first copy | Valid billing proposal | Awaiting review |
| `evt-1`, second copy | Repeated event ID | `duplicate_event_in_batch` |
| `evt-2` | Missing ticket | `ticket_not_found` |
| `evt-3` | Label `delete-account` | `invalid_label_contract` |
| `evt-4` | Version supplied as a string | `invalid_event` |
| `evt-5` | Valid technical proposal | Awaiting review |
| `evt-6` | Text that is not JSON | `invalid_json` |
| `evt-7` | Version 2 against current version 3 | `stale_version` |

An accepted review item looks like this:

```json
{
  "event_id": "evt-1",
  "ticket_id": "DEMO-42",
  "expected_version": 3,
  "proposed_label": "billing",
  "state": "awaiting_review",
  "applied": false
}
```

That's **eight input events**, **two review items**, **six rejections**, and **zero applied changes**. Those are counts for this run, not an accuracy score. A workflow can route every item exactly as designed while the model behind it still picks the wrong labels.

## 4. Change one failure and rerun

Open **Synthetic events** and change `evt-3` from the `invalid-label` fixture to the default case by removing its `fixture` field. Execute the workflow again. You should now see three review items and five rejections.

Next, put `evt-3` back and change `evt-7` to `expected_version: 3`. Its stale-version rejection should turn into a review item. Keep a copy of the original export so you can get back to the eight-case starting point.

Then open **Validate proposals**. It parses the model's JSON and checks the label against the allowed list. That's what decides whether an answer moves forward. If you wired the model straight to a node that writes to your ticket system, nothing would check it. Keep this step in place even after everything works on clean input.

## 5. Know what must change for a real integration

The repeat check here is a JavaScript `Set` that only lives for one run. Run the workflow again and it starts empty, so the same review items come back. It is **not durable deduplication across executions or restarts**.

Picture a real ticket system sending the same event twice, a few seconds apart, to two copies of your workflow. Both check, both see nothing, both act. To stop that, save each event ID in a database that rejects duplicates, and have each run claim the event in a single step before doing any work. Test it by sending the same event twice at the same time.

The review items also only exist in the run's output. Nobody is watching a queue. To take this further, send them somewhere that lasts and record the exact proposal, the ticket version, the decision, who reviewed it and when it expires. Whatever applies an approved change should check the version again first, in case the ticket changed while it waited.

Swap the fixed lookup and model answers for real nodes only after you've decided which credentials they use and which records they can touch. Keep the same rules for what a valid label looks like, and run the failure cases again. Test the model's accuracy separately, with realistic data you're allowed to use. Passing these fixture cases says nothing about how a live model will do.

Last, add your provider's webhook verification and a limit on retries. n8n's [error-handling guide](https://docs.n8n.io/flow-logic/error-handling) covers error workflows, but a rejected input and an unexpected crash need different handling. And if a write to another system already went through but you lost the response, don't just retry it. You could make the change twice.

When you're done, you should have the imported workflow, the eight-case baseline, and one changed fixture with the new counts you expected. Keep it unpublished until you've designed and tested every connection to the outside. Then continue to the [agent capstone](/blog/ticket-agent-workflow-capstone), which connects the course's pieces into one app you can inspect.

## Related Guides

- [How to Build a Lead Generation Workflow in n8n Step by Step](/blog/how-to-build-lead-gen-workflow-n8n)
- [How to Build a Weekly AI Article Recommendation Workflow](/blog/how-to-build-weekly-ai-article-recommendation-workflow)
- [How to Create an AI Video Production Workflow](/blog/ai-video-production-workflow)]]></content:encoded>
            <author>Zarif</author>
            <category>agent-course</category>
            <category>ai-engineering</category>
            <category>practical-guide</category>
        </item>
        <item>
            <title><![CDATA[How to Build a Weekly AI Article Recommendation Workflow]]></title>
            <link>https://www.zarifautomates.com/blog/how-to-build-weekly-ai-article-recommendation-workflow</link>
            <guid isPermaLink="false">https://www.zarifautomates.com/blog/how-to-build-weekly-ai-article-recommendation-workflow</guid>
            <pubDate>Wed, 12 Aug 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Build a weekly n8n workflow that pulls new articles from your sources, drops repeats, has AI rank the rest, checks every link, and emails a short list.]]></description>
            <content:encoded><![CDATA[Once a week, this workflow sends you a short list of articles worth reading, each with a working link and one line on why it matters.

It does six things. It collects new links from a small list of sources you trust, cleans up their details, drops anything old or already sent, has AI score what's left against your interests, checks that every link still works, and sends the list. The AI ranks and explains. It never makes up the reading list.

The simplest version runs on n8n with RSS feeds, an n8n Data Table, one language-model call, and Gmail or Slack. Run it weekly, look over what it picks, and let your feedback shape the next list.

If the picks are headed for a public newsletter, hand the approved items to a separate newsletter workflow. This guide only covers finding and ranking the articles.

## How the workflow fits together

Here's the full path:

```text
Weekly schedule
  -> Source list
  -> Read feeds
  -> Normalize article fields
  -> Reject old and previously seen URLs
  -> Score remaining articles with AI
  -> Apply quality threshold
  -> Sort and keep the top items
  -> Verify URLs
  -> Build digest
  -> Send email or Slack message
  -> Record delivered URLs and feedback fields
```

The order matters. Plain rules are cheaper and more reliable than asking a model. A date check can tell you an article is seven days old. A lookup in your history can tell you a link already went out. Neither needs AI, so they run first and the model only sees what's left.

<table>
<thead><tr><th>Stage</th><th>Best mechanism</th><th>Why</th></tr></thead>
<tbody>
<tr><td>Weekly timing</td><td>Schedule Trigger</td><td>Predictable cadence and timezone</td></tr>
<tr><td>Source collection</td><td>RSS Read or source API</td><td>Preserves real titles, URLs, and timestamps</td></tr>
<tr><td>Freshness</td><td>Date rule</td><td>Objective and inexpensive</td></tr>
<tr><td>Exact deduplication</td><td>Canonical URL lookup</td><td>Prevents repeat recommendations</td></tr>
<tr><td>Semantic relevance</td><td>Language model</td><td>Understands topic fit and usefulness</td></tr>
<tr><td>Final availability</td><td>HTTP status check</td><td>Stops dead links reaching the digest</td></tr>
<tr><td>History</td><td>Data Table</td><td>Provides memory across weekly runs</td></tr>
</tbody>
</table>

## Step 1: Decide what deserves a spot

Don't start with nodes. Start by writing down, on one screen, what a good pick looks like.

Cover five things:

1. **Topics:** what you actually want to learn about.
2. **Reader:** who the list is for.
3. **How recent:** usually seven to ten days for a weekly list.
4. **What counts as solid:** original sources, technical docs, research, or write-ups from people doing the work.
5. **What to skip:** rewritten press releases, thin listicles, the same announcement covered five times, paywalled pages, topics you don't care about.

Here's an example for someone running AI automations:

```text
Recommend articles about AI agents, workflow automation, model releases,
enterprise adoption, and measurable small-business use cases.

Prefer primary sources, technical implementation detail, original data,
and credible operator lessons. Reject generic trend summaries, copied
launch announcements, unsupported predictions, and articles older than
10 days. The reader should learn something they can apply this month.
```

Without this, "best" means nothing. A viral article can be a bad pick for your reader, while a quiet product changelog can change something you run every day.

## Step 2: Make a short list of sources

Start with 10 to 20 sources. Give each one these fields:

- source name
- feed or endpoint URL
- topic lane
- source type
- trust tier
- active status

A Google Sheet is easy to edit by hand. An n8n Data Table keeps everything inside the workflow. Either way, use one row per source, so you can switch off a noisy feed without touching the automation.

Favor sources that publish their own work: AI labs, product changelogs, research groups, standards bodies, and people writing up what they built. Add general news sites only when they keep catching stories your list misses.

RSS is still the cleanest input when a site offers it. n8n has an official [RSS Read node](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.rssfeedread/) for pulling a feed. When there's no feed, use the site's official API. Scraping the page is a last resort, because a layout change can break it without warning.

## Step 3: Pick a weekly time

Use the [n8n Schedule Trigger](https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-base.scheduletrigger/) and set the workflow's timezone yourself. Thursday morning is a good default. The list arrives before end-of-week reading time and misses the Monday inbox pile.

Name the workflow for what it does, like Send weekly AI reading recommendations. Name each node for its job too, not "HTTP Request 3": Load active sources, Reject previously sent URLs, Score editorial value. When a feed breaks three months from now, those names are how you'll find the problem.

Once a week is enough unless speed actually matters. The point is a thoughtful list, not breaking news.

## Step 4: Put every article in the same shape

Feeds name their fields differently and write dates differently. Before you filter anything, convert every item into one common record:

```json
{
  "title": "Article title",
  "url": "https://publisher.example/article",
  "canonicalUrl": "https://publisher.example/article",
  "publishedAt": "2026-08-10T09:00:00Z",
  "source": "Publisher",
  "sourceTier": "primary",
  "topicLane": "ai-agents",
  "excerpt": "Feed-provided description",
  "collectedAt": "2026-08-12T02:00:00Z"
}
```

The `canonicalUrl` is the clean version of the link, the one you'll use to spot repeats. To get it, strip tracking tags like `utm_source`, `utm_medium`, and `utm_campaign`, lowercase the domain, drop anything after a `#`, and pick one rule for trailing slashes. That way the same article shared in three campaigns counts as one.

Don't let AI fill in missing dates or links. If a required field is missing, send the item to a review list or drop it. A made-up date makes the freshness check meaningless.

## Step 5: Drop old, repeated, and empty items

Run the cheap checks first:

1. URL uses HTTP or HTTPS.
2. Publication date is inside the freshness window.
3. Title and excerpt aren't empty.
4. Canonical URL hasn't appeared in the current batch.
5. Canonical URL doesn't exist in delivery history.
6. Source is active.

Keep your sent history in a Data Table with `canonicalUrl`, `firstSeenAt`, `sentAt`, `digestId`, `score`, and an optional `feedback` field. n8n describes [Data Tables](https://docs.n8n.io/data/data-tables/) as storage that stays around between workflow runs. A spreadsheet or database works too. What matters is that the history survives after each run ends.

Matching links won't catch the same story on two different sites. So add a second repeat check after scoring. Compare cleaned-up titles, or ask the model for a short `storyKey` like `openai-new-agents-sdk-release`. Keep the best source for each story key. Original sources win ties.

## Step 6: Have AI score what's left

Only send the model the details that survived. Sending full articles costs more, runs slower, raises copyright questions, and opens the door to prompt injection, where text inside an article tries to give the model instructions. For most feeds, the title, source, excerpt, date, and your Step 1 rules are enough for a first ranking.

Ask for one JSON object per article:

```json
{
  "relevance": 0,
  "originality": 0,
  "actionability": 0,
  "credibility": 0,
  "overallScore": 0,
  "topic": "",
  "storyKey": "",
  "summary": "",
  "whyRead": "",
  "confidence": 0,
  "rejectReason": ""
}
```

Use a 0-to-100 scale and set the weights yourself:

```text
overallScore =
  relevance * 0.35 +
  actionability * 0.30 +
  credibility * 0.20 +
  originality * 0.15
```

Then apply a fixed cutoff after the model answers. For example, require an overall score of at least 72, confidence of at least 0.7, and no reject reason.

The model never touches the title, source, link, or date. Carry those straight from the feed record and attach the AI's scores and summary to them. This is the main thing that stops the list from containing made-up articles.

## A prompt that works

Use a prompt shaped like this:

```text
You are ranking a candidate article for a weekly reading digest.

Editorial policy:
[insert the saved policy]

Candidate metadata:
[insert title, source, source tier, date, topic lane, and excerpt]

Score relevance, actionability, credibility, and originality from 0 to 100.
Recommend only material that teaches the audience something usable or
changes an important decision. Penalize generic summaries, promotional
copy, duplicated announcements, and claims unsupported by the supplied
metadata.

Return only the required structured fields. Do not create, rewrite, or
infer a URL. If the metadata is insufficient, lower confidence and explain
the rejection briefly.
```

Add two or three examples from past weeks: one clear yes, one clear no, and one borderline case. Examples keep the model's taste steady far better than words like "excellent" or "insightful."

## Step 7: Keep the list varied

Sorting by score alone often gives you five takes on the same announcement. Add limits after scoring:

- maximum two articles per topic lane
- maximum one article per story key
- maximum two articles per publisher
- at least one technical or primary source
- five to ten recommendations total

If only three articles clear the bar, send three. A short list you can trust trains you to open it. A padded one trains you to ignore it.

For each pick, show:

- linked original title
- publisher and date
- two-sentence factual summary
- one sentence explaining why it matters to this reader
- topic label
- optional estimated reading time only when the source supplies it

## Step 8: Check every link right before sending

Send a quick request to each chosen link. Accept pages that load and redirects that are clearly intentional. Reject errors, redirect loops, and links that land on a parked domain.

If a link fails, don't swap in one the model suggests. Use a working backup you already collected, or drop the item.

This last check catches articles taken down after collection, broken tracking links, and sites that moved. It's also the difference between a real reading list and an AI-written list of links that only look real.

## Step 9: Send it and save what went out

Email is the best default for a personal weekly list. Slack works for a team. Notion or Google Docs work when people mark up the list before a meeting.

Make the subject line say exactly what's inside:

```text
Your 7 AI reads for August 10-16
```

After the send succeeds, write every sent link to your history. Don't write `sentAt` before it succeeds. If the email fails, those articles would otherwise be marked as sent and never show up again.

Add simple feedback buttons:

- useful
- not relevant
- already knew this
- source quality issue

Look at the feedback once a month and update topics, source trust levels, and exclusions yourself. Don't let the model rewrite its own rules after every click. Rules you set should change because you decided to change them.

## Keep it from failing quietly

A scheduled workflow that breaks without telling you is worse than no workflow. You just stop noticing what you're missing.

Add these:

- retry network and model calls up to three times with a short backoff
- configure a workflow-level error workflow that sends the failed workflow name, execution ID, and error
- store the current digest ID so a retried run cannot send the same email twice
- cap the number of candidates entering the model step
- record counts at every gate: collected, fresh, unseen, scored, accepted, verified, delivered
- alert when collected items fall to zero or change unusually from the normal range

The digest ID matters more than it looks. Picture a run that sends the email, then crashes before it records that it did. The retry would send the same email again. Saving the digest ID lets the retry see the work is already done. That property, where running something twice has the same effect as running it once, is called idempotency.

n8n's [error-handling documentation](https://docs.n8n.io/flow-logic/error-handling/) covers error workflows and the Error Trigger. The rule is simple: every failure should be visible, and every retry should be safe.

## Cost and scale

It stays cheap because rules shrink the pile before the model sees it. Say 20 feeds produce 300 items a week. The date check and history lookup might cut that to 80. Source rules and basic checks might cut it again to 30. The model scores 30 short records, not 300 full articles.

As it grows, split it into two workflows:

1. a daily ingestion workflow collects, normalizes, and deduplicates
2. a weekly recommendation workflow reads unseen candidates, scores them, and sends the digest

That way a broken feed doesn't stop the weekly send, and you can test each part on its own. If you build reusable sub-workflows, have each one take an article in and hand an article back, without depending on anything else from the run.

## Common mistakes

### Searching the whole web every run

You get noisy results that change from week to week. Start with your source list. Add wider discovery later as a separate, lower-trust lane.

### Letting AI write or rewrite links

Links are data you collected, not text the model writes. Keep the source link exactly as it came in and check it before sending.

### Only checking for repeats within one week

The same article will show up again next week. Keep your sent history between runs.

### Summarizing before filtering

You end up paying to summarize items a date check or history lookup would have dropped for free. Filter first, score second, and summarize only the finalists, only when you need to.

### Publishing without a person checking

For a private list, sending automatically is usually fine. For a public newsletter or a client brief, add an approval step before anything goes out. The cost of a bad pick is much higher.

### No error alert

A broken feed, an expired login, or a model rate limit can all look like a quiet week. Nothing arrives and nothing complains. An error alert turns that silence into something you can fix.

## Checklist

- [ ] Write the editorial policy and exclusions
- [ ] Create a 10-to-20-source registry
- [ ] Set an explicit workflow timezone
- [ ] Normalize title, canonical URL, source, excerpt, and date
- [ ] Create persistent URL history
- [ ] Filter freshness and exact duplicates before AI
- [ ] Require structured scoring output
- [ ] Preserve source URLs outside the model output
- [ ] Enforce diversity and quality thresholds
- [ ] Verify finalist URLs
- [ ] Make delivery idempotent
- [ ] Add retries and a workflow-level error alert
- [ ] Test with a good feed item, an old item, a duplicate, a missing date, and a dead URL
- [ ] Review feedback monthly

## Where to start

Build the small version first: trusted RSS feeds, a seven-day window, sent history, one scoring call, five picks, email delivery. It's useful, you can explain every pick, and it's easy to keep running.

Add wider web search, embeddings, per-person profiles, or more delivery channels only after the list keeps surfacing articles you actually read. Your source list and your Step 1 rules will matter more than how clever the model is.

## Related Guides

- [How to Build a Lead Generation Workflow in n8n Step by Step](/blog/how-to-build-lead-gen-workflow-n8n)
- [Build an n8n Ticket-Triage Workflow and Test Its Failure Paths](/blog/how-to-use-n8n-for-advanced-ai-workflow-automation)
- [How to Create an AI Video Production Workflow](/blog/ai-video-production-workflow)]]></content:encoded>
            <author>Zarif</author>
            <category>weekly article recommendations</category>
            <category>AI content curation</category>
            <category>n8n workflow</category>
            <category>RSS automation</category>
            <category>research automation</category>
        </item>
        <item>
            <title><![CDATA[How to Build Your First AI Automation: Email Triage in n8n]]></title>
            <link>https://www.zarifautomates.com/blog/how-to-build-your-first-ai-automation-in-under-30-minutes</link>
            <guid isPermaLink="false">https://www.zarifautomates.com/blog/how-to-build-your-first-ai-automation-in-under-30-minutes</guid>
            <pubDate>Sat, 30 May 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Build an n8n workflow that reads new Gmail, asks a small OpenAI model for JSON, and appends each result to a Google Sheet. No automation experience needed.]]></description>
            <content:encoded><![CDATA[By the end of this, every new email in your inbox becomes a row in a Google Sheet: who sent it, what company they're from, what they want, how urgent it is, and a one-line summary. It's four nodes in n8n, and the model costs a fraction of a cent per email.

The shape is simple. A trigger notices something happened. An AI step turns messy text into tidy fields. An action writes those fields somewhere useful. Once you've built it for email, the same shape works for routing tickets, scoring leads, and sorting documents.

## What you will build

The workflow watches a Gmail inbox. When a new email arrives, it sends the subject and body to a small OpenAI model. The model sends back JSON, a simple structured format, with the sender's name, company, intent (sales, support, recruiting, spam), urgency (low, medium, high), and a one-sentence summary. n8n adds that as a row in a Google Sheet. That's a starter CRM for incoming leads, built in one sitting.

## What you need before you start

Three accounts. The OpenAI one is the only one that needs money up front.

- An n8n cloud account at n8n.io: a [14-day free trial with no credit card](https://docs.n8n.io/deploy/use-n8n-cloud/start-your-free-trial), then the [Starter plan at 20 dollars a month billed annually or 24 billed monthly](https://n8n.io/pricing/) as of September 2026. Or self-host the free Community Edition instead.
- A Google account with Gmail and Sheets access
- An OpenAI API account with prepaid credit. [New API accounts use prepaid billing](https://help.openai.com/en/articles/8264644-setting-up-and-managing-prepaid-api-billing), and the minimum purchase is 5 dollars, so add a payment method and buy the minimum before step 2. This tutorial uses `gpt-6-luna`, which [OpenAI's pricing page](https://developers.openai.com/api/docs/pricing) lists at 0.10 dollars per million input tokens and 0.50 dollars per million output tokens as of September 2026. A typical email is well under a cent.

If you want a path with no payment at all, run n8n self-hosted on your laptop, and swap OpenAI for a provider with a free API tier: [Gemini's Flash models](https://ai.google.dev/gemini-api/docs/pricing) or [Groq](https://console.groq.com/docs/rate-limits), both free within rate limits as of September 2026. Google says free-tier content may be used to improve its products, so don't send real customer email through it. Everything else in this guide stays the same.

OpenAI renames and retires its small models often. If `gpt-6-luna` has been replaced by the time you read this, use whichever model the [models page](https://developers.openai.com/api/docs/models) recommends for high-volume work, as long as it supports structured outputs.

## Step 1: Set up the trigger

Sign in to n8n cloud and create a new workflow. Add a Gmail Trigger node and connect your Google account when it asks you to sign in (that's the OAuth flow). Set the trigger to "On Message Received" and have it check every minute. Filter to one label, like `inbox` or a custom `automate-me` label, so you can test without flooding your sheet with every email you already have.

Click "Listen for Test Event" and send yourself an email from another account. The node should turn green, with the subject, body, and sender showing in the right panel. If it doesn't, check two things. First, the Gmail permissions: sign in again and make sure you grant the access it asks for. Second, the label filter: the name has to match exactly.

## Step 2: Send the email content to an LLM

Add an OpenAI node after the Gmail trigger. Choose the [Generate a Chat Completion](https://docs.n8n.io/integrations/builtin/app-nodes/n8n-nodes-langchain.openai/text-operations/) text operation, pick model `gpt-6-luna`, and turn on the Output Content as JSON option.

Leave temperature unset. Current OpenAI models are reasoning models, and their [model guidance](https://developers.openai.com/api/docs/guides/latest-model) says to remove `temperature` unless reasoning effort is `none`.

The system message, the standing instructions the model gets before each email, goes:

```
You are a strict JSON extraction service. Given an email, return ONLY valid JSON matching this schema:
{
  "sender_name": "string",
  "company": "string or null",
  "intent": "sales | support | recruiting | spam | other",
  "urgency": "low | medium | high",
  "summary": "one sentence summary"
}
Do not include any text outside the JSON.
```

The user message is the email itself, pulled from the trigger's output:

```
Subject: {{ $json.subject }}
From: {{ $json.from.value[0].address }}
Body: {{ $json.text }}
```

Run the node. The output panel should show the five fields under the message content. If you get a paragraph instead of JSON, check that Output Content as JSON is on, then add the phrase "ONLY JSON, no prose" to the system message.

## Step 3: Parse the JSON response

Add a Code node after the OpenAI node and replace the default JavaScript with:

```
const content = $input.first().json.message?.content;
const fallback = { sender_name: 'unknown', company: null, intent: 'other', urgency: 'low', summary: 'JSON parse failed' };
let parsed;
try {
  parsed = typeof content === 'string' ? JSON.parse(content) : content;
  if (!parsed || typeof parsed !== 'object') parsed = fallback;
} catch (e) {
  parsed = fallback;
}
return [{ json: parsed }];
```

The code handles the reply whether it arrives as text or as JSON n8n already unpacked, since the JSON option can give you either. If your node version puts the reply somewhere else, click the field in the OpenAI node's output panel and copy its path into the first line.

This is the most important node in the workflow. Now and then a model sends back broken JSON. Without the try/catch, which tells the code what to do when something fails, the whole workflow stops. With it, a bad reply writes a row marked "JSON parse failed" that you can look at later.

Always wrap the step that reads a model's JSON in a try/catch with fallback values. Models sometimes reply in prose when you asked for JSON, or leave out a field. Plan for both.

## Step 4: Write the row to Google Sheets

Create a new sheet called `email-triage` with these columns: `received_at`, `sender_name`, `company`, `intent`, `urgency`, `summary`, `original_subject`.

Add a Google Sheets node and connect your Google account. Set the operation to "Append Row" and fill each column from the earlier nodes: `received_at` from the Gmail trigger's date, `sender_name` through `summary` from the Code node, and `original_subject` from the Gmail trigger.

Run the whole workflow with a test email. A new row should show up in your sheet within seconds.

## Step 5: Activate and test

Click the Active toggle at the top right of the workflow. Send three different test emails: a sales inquiry, a support question, and an obvious recruiter pitch. Check your sheet after a minute. All three should be there, each tagged with the right intent.

That's a working AI automation in four nodes. At [OpenAI's published price](https://developers.openai.com/api/docs/pricing) for `gpt-6-luna`, a 1,000-token email with a 150-token reply costs about 0.0002 dollars before reasoning tokens, which are billed as output.

## What to do when it breaks

It will break at some point. Here are three ways it can go wrong and how to fix each.

**The model replies in prose instead of JSON.** Repeat the JSON-only rule in the user message. If it still happens, switch the OpenAI node to the Generate a Model Response operation, set Output Format to JSON Schema, and paste in the schema from the system message. With [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs), the model can only reply in that shape. It isn't just asked to.

**The model makes up a sender name or company.** Usually the email didn't contain it, and the prompt asked for it anyway. Let the field be empty (null) in the schema, and tell the model to return null when the value isn't there.

**Google Sheets throws a quota error.** [Google's published limit](https://developers.google.com/workspace/sheets/api/limits) is 60 write requests per minute per user. Personal use won't come close. For higher volume, write to Airtable or a Postgres table instead.

## The pattern, generalized

Trigger, AI step, action. That shape is behind most useful AI automations. A few that fit the same template:

- Trigger: new Slack message in a channel. AI: classify whether this needs the on-call engineer. Action: page on-call if yes.
- Trigger: new Stripe charge. AI: write a personalized thank-you email referencing the customer's plan and history. Action: send via SendGrid.
- Trigger: new podcast episode in an RSS feed. AI: summarize the episode and extract three key claims. Action: post to a Notion database.
- Trigger: new GitHub issue. AI: classify priority and tag the right component. Action: update the issue with the labels.

Each is the same four nodes with different apps plugged in. Once you've built one, the rest are mostly a new trigger and a new prompt.

## What to do next

Three ways to extend it:

1. Add a Filter node before the OpenAI call to skip newsletters and automated emails. That saves money and cuts noise.
2. Add a Slack node next to the Sheets node that pings you right away when an email is tagged high urgency.
3. Swap the Google Sheet for an Airtable base, add columns to track follow-ups, and you have a small working CRM.

Keep costs in check while you do. Prepaid billing already stops requests when your credit runs out, but turn off auto-reload in OpenAI's billing settings until you've watched a week of real traffic, since [the help article](https://help.openai.com/en/articles/8264644-setting-up-and-managing-prepaid-api-billing) says it's on by default. If you later want to compare n8n with Make or Zapier, [the automation playbook](/blog/complete-ai-automation-playbook-2026) prices the same workflow on each.

The model was one node out of four. Most of the work in any automation is the rest: a trigger that fires at the right time, a prompt that gives the same shape of answer every time, and a destination someone actually looks at. For a bigger build on the same pattern, try the [n8n lead generation workflow](/blog/how-to-build-lead-gen-workflow-n8n).

## Related Guides

- [How to Build a Lead Generation Workflow in n8n Step by Step](/blog/how-to-build-lead-gen-workflow-n8n)
- [The AI Automation Playbook: Tools, Workflows and ROI](/blog/complete-ai-automation-playbook-2026)
- [How to Build a Weekly AI Article Recommendation Workflow](/blog/how-to-build-weekly-ai-article-recommendation-workflow)]]></content:encoded>
            <author>Zarif</author>
            <category>first ai automation tutorial</category>
            <category>n8n</category>
            <category>ai workflow</category>
            <category>no code</category>
        </item>
        <item>
            <title><![CDATA[How to Create an AI Video Production Workflow]]></title>
            <link>https://www.zarifautomates.com/blog/ai-video-production-workflow</link>
            <guid isPermaLink="false">https://www.zarifautomates.com/blog/ai-video-production-workflow</guid>
            <pubDate>Sat, 16 May 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Build an AI video workflow: draft the script, generate the video, add captions and formats, review it, and post it everywhere from one pipeline.]]></description>
            <content:encoded><![CDATA[Small teams run out of time for video long before they get budget for another editor. Working longer hours doesn't fix that. What helps is finding the parts of production that don't need a person and automating those, while a person still reviews the parts that do.

This guide walks through the four stages of making a video, which tools fit each one, and how to wire them together with n8n or Make. It ends with a cost calculation you can redo with your own numbers.

## Start by timing one video

A video is more than the creative work. Someone also transcribes it, captions it, resizes it for each platform, renders it, uploads it, and writes the description.

Before you automate anything, time one of your own videos, stage by stage. The mechanical parts are where automation helps, and how much of your time they take varies a lot between teams.

Plenty of teams are already doing this. The IAB's 2025 Digital Video Ad Spend and Strategy Report found that [30% of digital video ads were built from scratch or enhanced with generative AI, and buyers expected that share to reach 39% in 2026](https://www.marketingdive.com/news/over-half-of-ad-buyers-are-using-generative-ai-for-video-creation-iab/753048/), with [86% of buyers using or planning to use it for video creative](https://www.iab.com/news/nearly-90-of-advertisers-will-use-gen-ai-to-build-video-ads/). Those are survey answers from advertisers. They don't prove any particular workflow pays off.

Loosely connected tools tend to produce video that looks different every time. The rest of this guide is about building one that holds together.

## The four stages

Every video goes through script, production, editing, and distribution. Skip one and it shows.

### Stage 1: Script and plan

The script matters most. No avatar or effect saves a bad one.

AI can draft it faster, but check that. Time how long scripting takes you now, then time the draft-plus-edit version on the same kind of video.

Start with a short brief. What's the video about? Who's watching? How long should it be? What should they do at the end? Write it down and be specific.

Give that brief to a model like Claude or ChatGPT along with a prompt template. Here's a starter:

"Create a 90-second YouTube Shorts script about [TOPIC] for [AUDIENCE]. Structure: Hook (5s), Problem (20s), Solution (45s), CTA (20s). Use casual language. Include [X] key points. No marketing jargon. Make it memorable."

You get a rough draft. Then you edit it into your voice and your brand's rules. Don't skip that. The draft saves you a blank page, and the edit is where the quality comes from.

Once the script is locked, plan the visuals line by line. For an avatar video, note which lines go with which visuals. For motion graphics or product demos, note what happens when. This is how you avoid an avatar talking for 10 seconds while nothing happens on screen.

Plan it in a spreadsheet. Column A is the script line, Column B is the visual or effect, Column C is duration and notes. When you move to production, that sheet becomes your shot list or your generation prompt.

### Stage 2: Generate the video

Three kinds of tools cover most needs.

**Synthesia** is for talking-head videos. You paste in a script, pick an avatar, and it generates a video of the avatar saying your words, with lip-sync and multiple languages. Its [current monthly pricing lists Basic at $0, Starter at $29, and Creator at $89](https://www.synthesia.io/pricing), with 10, 10, and 30 video minutes per month respectively. It fits explainers and training videos.

**HeyGen** also does avatar video and [translation into other languages](/blog/best-ai-tools-for-translation-and-localization). Its [current monthly plans list Free at three one-minute videos, Creator at $29, and Pro at $49](https://www.heygen.com/pricing). Try both with your own scripts before deciding which sounds more natural.

If your scripts have product names or unusual words, both tools let you fix how a word is pronounced and reuse that fix in every video. Synthesia does it through its [pronunciation controls and workspace glossary](https://help.synthesia.io/en/articles/8469030-how-do-i-change-pronunciation), HeyGen through its [Brand Glossary](https://help.heygen.com/en/articles/8830251-how-to-use-brand-glossary). Set those up before you generate a batch.

**Runway** and **Kling AI** make generated scenes rather than a presenter on screen. Runway's [annual-billing view lists Free with 125 one-time credits, Standard at $12/month, and Pro at $28/month](https://runway.com/pricing). Check Kling's plans and credit costs on its site before you budget. Use these when you need visuals an avatar can't give you.

| Tool | Best For | Cost | Learning Curve |
|---|---|---|---|
| Synthesia | Talking-head, corporate, educational | $29-$89/mo | Low |
| HeyGen | Avatar video and localization | $29-$49/mo | Low |
| RunwayML Gen-4 | Custom visuals, creative scenes | $12-$28/mo | Medium |
| Kling AI | Generative video scenes | Check live pricing | Medium |

Pick by what you make. Twenty sales explainers a month points to Synthesia: build one template video, swap the script, and generate a batch overnight. Shorts with custom visuals point to Runway or Kling.

Don't generate each video by hand. The automation in stage 4 can start generation for you. The automation itself is cheap. The avatar minutes and generation credits it uses are not, so work out your volume from each vendor's plan limits.

### Stage 3: Edit, caption, and polish

This stage turns a raw render into something you'd post, and a lot of it can be automated.

**Captions.** In a 2019 Verizon Media and Publicis Media survey of 5,616 U.S. adults, [69% said they watch video with the sound off in public and 25% do so even in private](https://www.streamingmedia.com/Articles/ReadArticle.aspx?ArticleID=131860). So burn the captions into the video itself, not just a separate caption file.

Rev, Descript, and CapCut all generate timed captions. [Descript's Free plan includes 60 transcription minutes a month and Hobbyist is $24/month billed monthly](https://www.descript.com/pricing). CapCut has a free tier. n8n or Make can run the whole step: upload the video, caption it, format it for the platform, done.

**Sizes for each platform.** Posting to six platforms means six formats: Instagram Reels (9:16), YouTube Shorts (9:16), LinkedIn (1:1), TikTok (9:16), Twitter (16:9), YouTube long-form (16:9). Adobe Premiere Pro's Auto Reframe does this ([$22.99/month as a single app on an annual plan billed monthly](https://www.adobe.com/products/premiere/plans.html)). So does ffmpeg, a free command-line tool you can script into your workflow. One video in, six formats out.

**Color.** Avatar video can look flat. Use DaVinci Resolve (free) or Premiere Pro to make a LUT, a saved color preset that matches your brand. Apply it to every video automatically so they all look like they belong together.

**Audio.** Weak audio sinks an otherwise good video. Normalize your levels to -3dB peak. Add quiet background music from a royalty-free library like Epidemic Sound, Artlist, or the YouTube Audio Library. Let the automation layer music and voice the same way every time.

The easy way to get all of this right is a template. Make one finished video in your editor with the color, effects, music, and caption style set. Save the project file. Then the automation copies that template, swaps in new footage, and produces the next 20.

Always review at this stage. An avatar can mispronounce a word. A generated scene can have strange glitches. One platform can end up with the wrong size. A spot-check before posting is what keeps a broken video from going out to everyone who follows you.

### Stage 4: Post everywhere

A finished video still has to go to YouTube, TikTok, LinkedIn, Instagram, Twitter, and your website, each with its own description and thumbnail.

Time yourself doing that by hand once. That number is what you're trying to beat.

**n8n and Make** can handle posting. Both let you build workflows that:
- Start when a video finishes
- Upload to several platforms at once
- Draft descriptions and tags
- Size thumbnails for each platform
- Schedule posts for when your audience is online
- Add UTM tags to links, so you can see which post sent the traffic
- Log results in a spreadsheet

Here's one shape it can take. The video finishes rendering. n8n notices. It prepares the YouTube, TikTok, LinkedIn, and Instagram uploads side by side and emails your team for review. YouTube gets a search-friendly description and timestamps. LinkedIn gets a short text summary. X gets a teaser.

Keep the approval step before anything publishes. The automation packages the video. A person decides it's ready.

Cost: [n8n Cloud Starter lists €20/month billed annually](https://n8n.io/pricing/), and the self-hosted community edition costs only your server. [Make lists a Free plan and Core from $12/month](https://www.make.com/en/pricing). Whether that pays for itself depends on the time you measured multiplied by how many videos you post a month.

## Building your workflow

### Pick one slow task first

Don't connect the whole pipeline on day one. Pick one recurring task, like captions, script outlines, or platform descriptions. Time the manual version. Then try AI help on one approved video, count the time spent fixing its mistakes, and keep a person reviewing before anything posts.

### The smallest stack that works

1. **Script:** ChatGPT or Claude, either a consumer subscription or pay-per-use API calls. Script drafts are short, so check the current rates.
2. **Video:** Synthesia or HeyGen ([$29–$89/month](https://www.synthesia.io/pricing) or [$29–$49/month](https://www.heygen.com/pricing) on current self-serve plans)
3. **Automation:** [n8n Cloud from €20/month](https://n8n.io/pricing/) or [Make from $12/month](https://www.make.com/en/pricing), or self-hosted n8n

That covers brief, script, avatar video, and posting. The subscriptions alone come to roughly $50–$140 a month at the time of writing, before any video minutes over your plan and any model usage. Compare that to what the work costs today, using your own hourly rate and your own timed baseline, not a generic editor salary.

### If you need custom visuals

Add Runway or Kling AI. The flow becomes:

Brief → Script → Generate visuals with RunwayML → Composite in Synthesia or manually in Premiere → Captions → Multi-platform distribution

That adds $12–28 a month.

### The steps, in order

**Setup, once**

1. Create a template in Synthesia or HeyGen. Pick the avatar, background, outfit, and tone.
2. Build an n8n workflow that watches a Dropbox folder for new video files.
3. Add the steps that caption, resize, and upload.
4. Write down your script template, review checklist, and quality bar.

**Every video after that**

1. Write the brief.
2. Give the brief and your script template to ChatGPT or Claude.
3. Edit the script.
4. Paste it into Synthesia or HeyGen.
5. Generate the video.
6. Review it. Fix mistakes or regenerate if needed.
7. Drop it in the watched folder. The automation does the rest.

Time each step for your first few videos. Those numbers are what the cost math below runs on.

### What to track

A faster process nobody times isn't proven to be worth the subscriptions. Track these:

- **Time per video:** what it takes today, stage by stage. Measure weekly and set your goal from your own baseline, not a vendor's claim.
- **Cost per video:** everything you spend divided by videos made. Include subscriptions, video minutes, your time, and hosting. Compare it with the manual cost per video.
- **Videos per month:** compare to last quarter, and check that the extra videos are still getting reviewed.
- **Engagement:** views, watch time, clicks. AI-assisted videos shouldn't do worse than manual ones. If they do, stop adding volume and fix the script or the review step.
- **Error rate:** the share of videos that went out with a mistake, like the wrong size, a mispronounced word, or a broken link. Pick a level you'd be embarrassed to pass, and pause the automation when you pass it.

## Common mistakes

**A vague brief.** "Make a video about productivity" gets you a vague video. Low-quality source images do the same to generated footage.

Be specific instead: "Create a 60-second video showing a freelancer using time-blocking to finish a project 2 days early. Start with chaos (papers everywhere), show the time-blocking technique, end with calm (clean desk, finished work)."

**Trusting the automation completely.** An avatar can skip a word. A generated scene can glitch. Caption timing can drift. None of that gets caught unless a person looks. Build a review step into every video, and count it in your time-per-video number.

**Too many effects.** Fancy transitions pull attention away from the point. Viewers care whether they understood you. Keep it simple: one clean background, natural avatar movement, clear visuals, readable captions.

**The wrong size for the platform.** A 16:9 video in TikTok's 9:16 feed wastes most of the screen. YouTube long-form needs different details than Shorts. Automate the wrong setting and you get 20 unusable videos instead of one. Post by hand on each platform first, lock the settings, then automate, and check the first three automated videos yourself.

**Forgetting the story.** AI can generate the video. It won't give you a reason to watch. The script still needs a hook, a problem, a solution, and a reason to care. Treat the script as the real creative work and give it about half your production time.

## Once one video works

**Test versions.** Make three versions of the same script with different openings. One leads with the problem, one with the benefit, one with proof. Post all three, see which does best, and use that next time.

**Cut one video into many.** One long video can become 5 shorts, 3 LinkedIn posts, 1 TikTok, and 1 Twitter thread. Build a workflow that cuts the video into pieces, drafts hooks, and holds each piece for review.

**Personal sales videos.** Generate versions with each prospect's name, company, and details. Test personalized against generic before you assume it helps with your audience.

**Seasonal batches.** For a holiday push, use one script template with different visuals and avatars to make 20 versions at once.

## The cost math

**Method note:** the figures below are an illustrative calculation, not measured results from an actual production run. Every input is an assumption you should replace with your own timed baseline and quoted prices. The arithmetic is shown so you can check it.

**Assumptions**

- Labor rate: $25/hour for whoever does the work
- Manual process: 1 video per week, 6 hours per video (scripting, filming, editing, captions, upload)
- AI-assisted process: 1.5 hours of human time per video (script refinement, generation, review, distribution approval)
- Tool subscriptions after setup: $150/month, or $1,800/year
- Setup time (2–4 weeks) and generation minutes above plan limits are excluded, which flatters the AI-assisted case

**Manual baseline**

- 52 videos per year
- 52 × 6 hours × $25 = $7,800 per year
- Cost per video: $150

**Scenario A: same output, less time**

- 52 videos × 1.5 hours × $25 = $1,950 labor
- Plus $1,800 tools = $3,750 per year
- Cost per video: about $72, a saving of about $4,050 a year against the manual baseline

**Scenario B: same annual budget, more output**

- $7,800 minus $1,800 tools leaves $6,000 for labor, or 240 hours
- 240 hours ÷ 1.5 hours per video = 160 videos, about 3 per week
- Roughly 3× the output for the same spend, if you have 3 videos' worth of things to say each week

**Scenario C: 15 videos per week**

- 780 videos × 1.5 hours × $25 = $29,250 labor
- Plus $1,800 tools = $31,050 per year, about 4× the manual budget for 15× the output
- Cost per video: about $40

Scenario C also breaks the tool assumption. Fifteen 90-second videos a week is roughly 98 avatar minutes a month, and [Synthesia's Creator plan includes 30 minutes a month](https://www.synthesia.io/pricing), so you'd need custom pricing or extra minutes. Get the vendor's real quote before planning at that volume.

For a small team, the realistic win is usually A or B, not C. And it all depends on that six-hour figure. If your manual process already takes 2 hours per video, the savings shrink to match. Time your own first.

## Tools

**Video generation**
- Google Flow or Luma Dream Machine: generated video. Test both on your own source footage before choosing.
- Synthesia (avatar, talking-head): synthesia.io
- HeyGen (avatar video and translation): heygen.com
- Runway (generated scenes, custom visuals): runway.com
- Kling AI (generated scenes): klingai.com

**Automation**
- n8n (can self-host): n8n.io
- Make (visual builder): make.com
- Zapier (easiest to start, priced per task): zapier.com

**Script and editing**
- ChatGPT or Claude for scripts: openai.com or claude.ai
- Descript for captions: descript.com
- CapCut for effects and resizing (free tier): capcut.com
- DaVinci Resolve for color (free): davinciresolve.com

**Posting**
- YouTube, TikTok, LinkedIn, Instagram native uploads (free)
- Buffer or Later for scheduling if you're not automating it: buffer.com

## Related Guides

- [How to Create AI-Powered SOPs for Your Entire Business](/blog/how-to-create-ai-powered-sops-for-business)
- [How to Build a Lead Generation Workflow in n8n Step by Step](/blog/how-to-build-lead-gen-workflow-n8n)
- [How to Build a Weekly AI Article Recommendation Workflow](/blog/how-to-build-weekly-ai-article-recommendation-workflow)]]></content:encoded>
            <author>Zarif</author>
            <category>ai video production</category>
            <category>video workflow</category>
            <category>ai video tools</category>
            <category>video automation</category>
            <category>content automation</category>
        </item>
        <item>
            <title><![CDATA[The AI Automation Playbook: Tools, Workflows and ROI]]></title>
            <link>https://www.zarifautomates.com/blog/complete-ai-automation-playbook-2026</link>
            <guid isPermaLink="false">https://www.zarifautomates.com/blog/complete-ai-automation-playbook-2026</guid>
            <pubDate>Sun, 12 Apr 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Compare n8n, Make, and Zapier, pick a model for each step, adapt five workflow blueprints, and price a workflow from published rates before you build it.]]></description>
            <content:encoded><![CDATA[This playbook helps you pick an automation tool and a model, gives you five workflows you can copy, and shows how to price one from published rates before you build it.

The goal isn't the dollar figure. It's getting hours back from work you do the same way every week, so you can spend them on the work only a person can do.

## Three kinds of automation

People use three terms as if they mean the same thing. They don't, and knowing which one you're building saves money.

**Rule-based automation** (often called RPA, robotic process automation) follows a fixed script. When an email arrives, pull the attachment, move it to this folder, send a notification. It does exactly that. If something doesn't fit the script, it breaks.

**AI automation** is what most people need right now. It's the same kind of workflow connecting your apps, with an AI step where judgment is needed. When an inquiry comes in, Claude reads the tone, sends it to the right team, and drafts a first reply. The AI interprets, but it still runs inside steps you designed.

**Agentic AI** is the newest. Instead of fixed steps, an AI agent gets a goal, like "onboard new customers," and picks from the tools it's allowed to use to get there. That flexibility means more testing, more rules about what it can touch, and more planning for when it fails. Adoption forecasts vary a lot, so don't treat them as proof that your process is ready for an agent.

The practical advice: don't start with agents. Start with AI automation, a simple workflow plus one model call. Show it saves time. Move to agents only when the simple workflows can't handle the variety anymore.

## The tools

AI automation needs three layers: a workflow platform (n8n, Make, Zapier), a model (Claude, ChatGPT, Gemini), and connections to your other systems (APIs, webhooks, databases). Start with the platform. Prices and integration counts below are from each vendor's site on September 27, 2026, in USD.

| Feature | N8n | Make | Zapier |
| --- | --- | --- | --- |
| Best For | Teams with developers or serious budgets. Complex workflows. Full control. | Balanced. Visual-first. Good if you want power without being technical. | Simple, low-volume automations. Lowest friction entry point. |
| Pricing (starter) | Community Edition self-hosted, or Starter at $20/mo billed annually ($24 monthly) for 2,500 executions | Core at $12/mo billed annually ($16 monthly) for 10,000 credits | Professional at $19.99/mo billed yearly ($29.99 monthly) for 750 tasks |
| Flexibility | Unlimited. Custom code, custom logic, full API access. | High. Routers, scenarios, branching logic. | Branching with Paths on paid plans, custom code through Code by Zapier. |
| Learning Curve | Steep for non-developers, worth it. | Moderate. Visual builder is intuitive. | Shallow. Easiest to learn, but also the ceiling. |
| Integrations | 2,000+ listed, plus any API through the HTTP Request node | 3,000+ apps | 10,000+ apps (quantity, but sometimes shallow) |

### Why n8n over Zapier

For anything past a few simple automations, n8n is the better pick. Four reasons:

1. **They charge differently.** [Zapier prices paid plans by monthly task allowance](https://zapier.com/pricing), while [n8n Cloud bills full workflow executions with unlimited steps inside each execution](https://n8n.io/pricing/). A Zap with five actions can use five tasks every time it runs. Compare the same real workflow at your expected volume, not the headline plan prices.

2. **You run out of room in Zapier.** "Filter by Zapier" handles if-this-then-that logic, but it's clunky, and Code by Zapier adds custom code with extra steps. n8n has code nodes built in, so you can fix a mistake right in the editor.

3. **AI is built into n8n.** n8n 2.0 added AI agents to the platform itself, with LangChain integration, the AI Agent Tool Node, and setups where several agents work together. Zapier's Copilot and Agents features are newer additions. Zapier is adding AI to automation. n8n is building automation around AI.

4. **You can keep your data.** Zapier only runs as a hosted service. n8n offers a self-hosted Community Edition. Self-hosting means you handle the server, security, backups, upgrades, and outages yourself, so it isn't free once you count that work and the hosting bill.

If your automations are tiny (5 to 10 tasks a month), staying on Zapier is fine.

**n8n** — Open-source workflow automation platform built for technical teams and enterprises. Unlimited executions on self-hosted, pay-per-execution on cloud. Native AI agent support and full code extensibility. (https://n8n.io)

## Choosing a model: Claude vs ChatGPT vs Gemini

Model names change every few months. Pick a provider for what it's good at, then check its current lineup when you build.

**Claude (Anthropic)** is the default pick here. It follows instructions well and writes cleanly without heavy prompting. As of September 2026, Anthropic's [models overview](https://platform.claude.com/docs/en/models/overview) runs from Haiku 4.5 for cheap, high-volume steps to Sonnet 5 and Opus 5.5 for harder reasoning, and Opus 5.5 sits at the top of the [Artificial Analysis Intelligence Index](https://artificialanalysis.ai/leaderboards/models). For automation, what matters is that it gives consistent answers run after run.

**ChatGPT (OpenAI)** has a mature API, clear pricing, and clean connections to n8n and Make. As of September 2026 its GPT-6 family runs from Luna, which OpenAI describes as its most efficient model for focused, high-volume tasks, up to Sol and Astra ([models](https://developers.openai.com/api/docs/models)). Luna is a sensible default for sorting and pulling data out of text, steps that run thousands of times.

**Gemini (Google)** is strong with images and video as well as text. If your automation reads scanned documents, sorts images, or processes video, Gemini has the edge. For text-only work, Claude or ChatGPT are simpler. Its Flash and Flash-Lite models have a [free tier](https://ai.google.dev/gemini-api/docs/pricing) for testing, though Google may use free-tier content to improve its products.

You don't need one model for everything. Use a small, cheap model for sorting and pulling out fields, and a stronger one for steps where a mistake costs real money, like approving an invoice or writing to a customer.

For your first week, pick Claude.

## Five workflows to copy

Each of these has enough detail to build yourself.

### 1. Lead qualification (sales)

**Trigger**: New form submission → **Webhook to n8n** → **Claude analyzes** → **Route to CRM**

How it works:
1. New lead submits form on your landing page
2. Webhook fires to n8n with name, email, company, message
3. n8n calls Claude API with prompt: "Analyze this lead. Rate fit (hot/warm/cold). Summarize objection if any. Recommend routing (AE / SDR / nurture)."
4. Claude returns structured JSON with rating and routing
5. n8n branches: hot leads → immediately add to AE's Salesforce, warm → nurture sequence in HubSpot, cold → archive
6. Optional: n8n sends Slack notification to AE with lead summary

Cost: one model call per lead. Price it with the token math in the cost section below, using your own prompt and reply lengths. For a full build of this one, see the [n8n lead generation guide](/blog/how-to-build-lead-gen-workflow-n8n).

### 2. Support ticket escalation

**Trigger**: New support email → **Claude sentiment/urgency detection** → **Route + draft response**

How it works:
1. Support email arrives (IMAP trigger in n8n)
2. n8n extracts subject, body, sender
3. Call Claude: "Rate this ticket: urgency (1-10), sentiment (angry/frustrated/neutral/happy), category (bug/billing/feature-request/other). Draft a response that acknowledges their concern and sets expectations."
4. If urgency ≥ 8, immediately create Jira ticket with high priority
5. If urgency &#60; 5, send Claude-drafted response automatically, log in support database
6. If urgency 5-7, queue for human review but include Claude's draft

Cost: one model call per ticket, plus the Jira and email actions.

### 3. Invoice processing and payment routing

**Trigger**: Invoice PDF arrives → **Gemini extracts data** → **Claude validates** → **Post to accounting**

How it works:
1. Invoices land in a specific Slack channel (vendor sends there)
2. n8n downloads the file and calls Gemini API to extract: vendor name, invoice number, amount, due date, line items
3. n8n calls Claude to validate: "Does this invoice look legitimate? Any red flags? Recommended approval tier (auto-approve/manager-review/executive)?"
4. If auto-approve: n8n creates bill in QuickBooks, assigns GL code, updates vendor record
5. If manager-review: n8n sends Slack to accounting manager with Gemini extraction + Claude recommendation
6. Logging to Google Sheets for audit trail

Cost: two model calls per invoice, one to read it and one to check it. A long PDF costs more than a one-page invoice.

### 4. Turn one video into a blog post and social posts

**Trigger**: New YouTube video published → **Extract transcript** → **Claude creates variations** → **Post to blog + social**

How it works:
1. Webhook trigger when new video is uploaded to YouTube
2. n8n calls YouTube Data API to fetch transcript and metadata
3. n8n calls Claude API with prompt: "Create a 2,500-word blog post from this transcript, optimize for SEO, include data/examples, add CTAs. Also create 5 LinkedIn posts (different angles) and 10 tweet variations."
4. n8n saves blog post as MDX to GitHub repo (triggers rebuild), posts Markdown version to WordPress
5. n8n posts LinkedIn variations to Buffer (scheduled)
6. n8n tweets variations over next week (one per day)
7. Slack notification with links to all published content

Cost: one long model call per video. A full transcript is the biggest input in these five workflows, so measure one before you estimate a month.

Result: one video becomes one blog post, five LinkedIn posts, and ten tweets.

### 5. Customer onboarding with an agent (when you're ready)

**Trigger**: New customer signup → **Agentic loop** → **Multi-step onboarding autonomously**

How it works:
1. New SaaS customer signs up
2. n8n spawns an agentic loop: "Onboard this customer (company name, plan tier, use case). Figure out: 1) Send welcome email tailored to their plan, 2) Create user accounts in the tool, 3) Set up integrations they selected, 4) Schedule first check-in call, 5) Monitor usage for first 7 days and proactively help if they're stuck."
3. Agent runs in a loop, calling functions: send_email, create_account, check_integration_status, schedule_call, query_usage_metrics
4. If something breaks (integration fails), agent troubleshoots, updates Jira, loops back
5. Agent completes task and hands off to human for final call

Why an agent here: onboarding is different for every plan and use case. A company with 50 users needs different steps than a solo creator. An agent can adjust. A fixed workflow would need 20 if-then branches.

Cost: the most expensive of the five per run, because the agent decides how many calls to make. Set a limit on loops and spending per customer before you turn it on.

## When an agent makes sense

**Use an agent when:**
- The workflow has so many branches (10 or more) that you can't keep track of them
- Decisions depend on context, not just rules
- The work varies a lot: different customers, different documents, odd cases
- Your simple automations are already running and have hit their limit
- You have budget to experiment and fail

**Don't use an agent when:**
- The workflow is a straight line (upload file, pull out data, save to database)
- The rules are simple: if this, do that
- You need to prove exactly what happened, like in finance
- The basic workflow hasn't proven itself yet
- The only goal is to say the word "agents"

Most businesses don't need agents. They need better automation. Build the simple version first and get it saving real time. If complex processes are still eating hours after that, then look at agents.

## The data underneath

A lot of automation projects stall here, and it isn't the model's fault.

The best model and the best platform don't help if your data is scattered across systems that don't talk to each other. Four things have to be in place:

1. **The API calls actually run.** Data goes into the CRM and comes out of the database. The webhook URLs on both ends have to exist and keep working.

2. **Database access.** Looking up a customer's history, checking a user, or logging a result means querying a database. n8n has a PostgreSQL node for that. Whether your database admin lets an automation query the live database is a policy question, not a technical one.

3. **Logins and permissions.** Every connection needs credentials, like API keys or OAuth tokens. Handled carelessly, they become a security problem instead of an automation.

4. **What happens on failure.** n8n can retry failed steps on its own, but someone still has to decide when to retry, when to alert a person, and when to stop cleanly.

The tools are the smaller part of the work. If nobody on your team understands APIs, databases, and failure handling, hire someone or work with an agency before you scale.

For small teams this is solvable. Make and n8n both have HTTP nodes, so you can reach any API. Start there, then move to direct database connections and proper OAuth setups as the workflows grow.

## What it actually costs

Three layers add up to your bill.

**Layer 1: Workflow Platform**

- **n8n Cloud (baseline)**: [Starter is $20/month billed annually, or $24 billed monthly](https://n8n.io/pricing/), for 2,500 workflow executions with unlimited steps. The page shows euros in some regions.
- **n8n Self-Hosted**: $0 for the Community Edition. You pay for the server and do the operating yourself.
- **Make**: [Core is $12/month billed annually, or $16 billed monthly](https://www.make.com/en/pricing), for 10,000 credits. Each module action generally consumes a credit.
- **Zapier**: [Professional is $19.99/month billed yearly, or $29.99 billed monthly](https://zapier.com/pricing), for 750 tasks a month. At 2,000 tasks it's $49 billed yearly or $73.50 billed monthly.

**Layer 2: Model API Costs**

Prices below are the published standard rates as of September 27, 2026. Models charge by the token, roughly a short word or piece of a word, with separate rates for what you send (input) and what comes back (output).

- **Claude (Anthropic)**: [Claude Sonnet 5 is listed at $2 per million input tokens and $10 per million output tokens](https://platform.claude.com/docs/en/about-claude/pricing). A 500-input, 200-output-token call is about $0.003 before caching or other features. Haiku 4.5, at $1 and $5, halves that.
- **OpenAI**: [GPT-6 Luna is listed at $0.10 per million input tokens and $0.50 per million output tokens](https://developers.openai.com/api/docs/pricing). The same token shape is about $0.00015, plus any reasoning tokens, which bill as output.
- **Gemini**: [Gemini 3.5 Flash-Lite is listed at $0.30 per million text input tokens and $2.50 per million output tokens](https://ai.google.dev/gemini-api/docs/pricing). The same token shape is about $0.00065 on the paid standard tier.

**Layer 3: Integration Costs**

- **Stripe**: [Standard U.S. domestic card pricing is 2.9% + $0.30 per successful transaction](https://stripe.com/pricing). API data lookups aren't card transactions.
- **Salesforce API**: API access depends on your Salesforce edition, so confirm yours includes it before designing around it.
- **Slack**: No per-message fee for posting through an incoming webhook, but [Slack allows about one message per second per channel](https://docs.slack.dev/apis/web-api/rate-limits/), so batch high-volume alerts.
- **Database queries**: If you're querying PostgreSQL or MySQL, cost is on your hosting bill, not the tool.

**Example: the lead workflow, priced**

Lead qualification workflow (100 leads/month), both platforms on annual billing:
- n8n: $20/mo (covers 2,500 executions, and 100 leads means 100 executions)
- Claude Sonnet 5 calls: 100 leads × $0.003 per call = $0.30/mo
- **Total: about $20.30/month before tax**

On Zapier, the same workflow would be:
- 100 leads × 2 actions per lead = 200 tasks
- Professional's entry tier covers 750 tasks at $19.99/mo
- Claude calls: $0.30/mo
- **Total: about $20.29/month**

At this volume they cost the same. Scale to 1,000 leads/month:
- n8n: $20/mo, since 1,000 executions still fit in Starter's 2,500, plus $3 of Claude calls: **about $23/month**
- Zapier: 1,000 leads × 2 actions = 2,000 tasks, which moves Professional to the 2,000-task tier at $49/mo, plus $3 of Claude calls: **about $52/month**

At 1,000 leads a month, n8n costs less than half as much in this example. The gap grows with volume and with every action you add, because Zapier charges for each action while n8n charges for the whole run. On monthly billing, every figure above is higher.

## Your first week

**Day 1: Get model access**
- Create an Anthropic account, get your API key, and choose a current model that fits the task
- Test a simple prompt in their playground
- Set a small spend cap and look at current API pricing before testing

**Days 2-3: Set up the platform**

n8n is the better pick when flexible logic and control matter most. Download the Community Edition if you're ready to run your own server, or use the hosted Starter plan, listed at $20 a month on annual billing as of September 2026. The [cloud trial](https://docs.n8n.io/deploy/use-n8n-cloud/start-your-free-trial) runs 14 days without a credit card.
- Watch one n8n tutorial (their docs are good)
- Build a "hello world" workflow: trigger → HTTP request → log output
- Connect your first app. Slack is easiest: send yourself a test message.

**Days 4-5: Build your first real automation**

Pick something small that saves real time:
- Lead inquiry → store in spreadsheet
- New email → pull out the details + log to a database
- Slack message → post to a GitHub issue

Use one of the five workflows above. Don't overthink it. If you want a step-by-step build, [the email triage tutorial](/blog/how-to-build-your-first-ai-automation-in-under-30-minutes) walks through one from scratch.

**Days 6-7: Test and measure**
- Run the workflow by hand 5 times to check it works
- Turn it on for real data
- Write down the time it saves
- Note what you learned

By day 7 you have a working automation doing real work, for the price of one platform plan plus cents of model usage, or model usage alone if you self-host n8n.

## Where companies actually are

Most companies have a plan for AI. Far fewer have it working at scale.

[KPMG's Q1 2026 Global AI Pulse](https://assets.kpmg.com/content/dam/kpmgsites/xx/pdf/2026/04/global-ai-pulse.pdf) found that 95% of surveyed organizations had an AI strategy, but only 39% were scaling AI or driving organization-wide adoption.

In the [same KPMG survey](https://assets.kpmg.com/content/dam/kpmgsites/xx/pdf/2026/04/global-ai-pulse.pdf), 64% reported meaningful business value, but only 8% reported established ROI. Being busy with AI isn't the same as making money from it.

That gap is the opening. While others are still talking about pilots, you can ship small workflows, measure the time and errors they save, and expand only where the numbers hold up.

## What to do next

You don't need to be technical to start. You need a platform (n8n, Make, or Zapier for the simplest jobs), a model (Claude, ChatGPT, or Gemini), and a short list: the three processes eating most of your time.

Pick one of them this week. Build it, measure it, then build the next. The [first automation tutorial](/blog/how-to-build-your-first-ai-automation-in-under-30-minutes) is the fastest way in.

## Related Guides

- [How to Build Your First AI Automation: Email Triage in n8n](/blog/how-to-build-your-first-ai-automation-in-under-30-minutes)
- [Best AI Tools for Translation and Localization](/blog/best-ai-tools-for-translation-and-localization)
- [What Is Model Context Protocol (MCP)? The Complete 2026 Guide](/blog/what-is-model-context-protocol-mcp)
- [How to Create AI-Powered SOPs for Your Entire Business](/blog/how-to-create-ai-powered-sops-for-business)]]></content:encoded>
            <author>Zarif</author>
            <category>ai automation 2026</category>
            <category>ai automation playbook</category>
            <category>n8n automation</category>
            <category>ai workflow guide</category>
            <category>automation ROI</category>
        </item>
        <item>
            <title><![CDATA[How to Create AI-Powered SOPs for Your Entire Business]]></title>
            <link>https://www.zarifautomates.com/blog/how-to-create-ai-powered-sops-for-business</link>
            <guid isPermaLink="false">https://www.zarifautomates.com/blog/how-to-create-ai-powered-sops-for-business</guid>
            <pubDate>Fri, 03 Apr 2026 00:00:00 GMT</pubDate>
            <description><![CDATA[Write SOPs with AI in seven steps: list your processes, pick one template, let AI draft, test it on a new reader, and keep each one current.]]></description>
            <content:encoded><![CDATA[A new hire asks how refunds work. Someone points them to a doc from last year that mentions a tool you stopped using. They ask a coworker instead, who explains it slightly differently than the last person did.

That's what a missing or stale SOP looks like. An SOP, a standard operating procedure, is just the written steps for a job your team does over and over. This guide shows how to use AI to write them faster and keep them current, in seven steps.

## Why SOPs fail

Every business runs on procedures, written down or not: onboarding, invoice approval, publishing content. They break down for three reasons.

**They take too long to write.** So teams write a few and stop. Describing the process to a model and having it lay out the steps cuts that to something a busy person will actually do.

**They go stale.** Tools get swapped, steps change, and the document just sits there being wrong. People skip steps because the real instructions are buried in an old file, and new hires spend their first weeks guessing. A model can compare a procedure against what changed and flag it.

**Nobody follows them.** A forty-page PDF nobody can find or open on a phone gets skipped. A short, searchable, current procedure gets used.

Fix those three and the rest is mechanics.

## Step 1: List your processes

Write down every job in the business that repeats: marketing campaigns, qualifying sales leads, sorting support tickets, managing vendors, approving expenses, onboarding customers.

For each one, ask:

- Who owns it?
- How long does it take right now?
- How many people need to learn it?
- How often does it go wrong?
- What does a mistake here cost?

Fix the expensive ones first. A customer onboarding process that runs all the time and eats hours for every new hire comes before the yearly board-meeting agenda.

You'll end up with more processes than you can handle at once. Pick the few that cost the most time or cause the most mistakes, and start there.

Gather whatever notes already exist, even if they're scattered: Slack threads, email templates, Google Docs, wiki pages. Give them all to the model. Turning fragments into a clean draft is much faster than starting from a blank page.

## Step 2: Pick one template

Every SOP should follow the same layout. Once people learn where things are in one, they can find them in all of them.

**A standard layout:**

- **Overview**: what this process is and why it matters
- **Prerequisites**: what needs to be true before starting
- **Numbered steps**: clear actions in sequence
- **Decision points**: "If X, then do Y"
- **Common mistakes**: errors people actually make
- **Compliance notes**: regulatory requirements, if any apply
- **Glossary**: team-specific terms

Give this layout to the model with your notes, and every draft comes back in the same shape without you policing it.

Choose the template before you generate anything. If every SOP looks different, people have to relearn how to read each one.

## Step 3: Write the first draft with AI

There are two ways to do it: record yourself doing the task, or describe it in writing.

### Record the task

Scribe, Tango, and Glitter watch your screen while you do the task. They grab screenshots, read what's on screen, and turn it into a step-by-step guide.

**Best for:** click-by-click computer work, like software setup, data entry, and publishing content.

**How:** install the browser extension, do the task, let the tool make a draft, then edit and publish.

You'll need to fix clicks it labeled wrong and add context the screenshots miss. But you skip writing the steps from scratch.

### Describe it in writing

Claude, ChatGPT, Waybook's SOP writer, and Process Street's AI Workflow Generator take a written description of a process and turn it into an SOP.

**Best for:** processes with lots of judgment calls, and anything that doesn't happen on a screen.

**How:** write an overview of the process, list the tools and the decision points, let the model write a full draft, then have the team review and fix it.

Expect more editing than with a recorded draft, since the model is working from your description instead of watching the work happen.

### Your first one

Start with a process you know cold. Write a short overview of what happens and why, and note the tools, systems, and people involved.

Give that to Claude, or whichever tool you picked, with a prompt like this:

```
Create a comprehensive SOP for [process name]
following this structure:

Overview
Prerequisites
Steps (numbered)
Decision points
Common mistakes
Compliance notes (if applicable)

Use clear, direct language. Each step should be
actionable in under 60 seconds. Target audience:
team members with basic platform familiarity.
```

The model gives you a full first draft. Your team reviews it, you fix what's wrong, add what's specific to your company, and publish. Writing the draft is quick. The review is where the time goes.

## Step 4: Choose where they live

Decide this before you write many of them. If people can't find a procedure, they won't use it.

Options:

- **Notion**: free plan, connects to most tools, searchable, easy to edit together
- **Confluence**: better for large company wikis with lots of cross-links
- **Waybook**: built for SOPs, with AI drafting included
- **Process Street**: turns procedures into checklists and assigns tasks
- **Internal wiki**: GitHub, GitBook, or similar
- **A plain Google Drive folder**: not ideal, but better than docs scattered everywhere

What matters most is that people can search for an SOP and link to it. An SOP nobody can find might as well not exist.

Organize by department. Marketing SOPs in one place, sales in another, and one index page linking to all of them.

Prices below are from each vendor's pricing page on September 27, 2026, in USD. Most charge per user, so multiply by your team size before comparing.

| Tool | Best for | Where the AI comes in | Free plan | Paid from |
|------|----------|-----------------------|-----------|-----------|
| [Scribe](https://scribe.com/pricing) | Screen-capture how-tos | Writes steps from a recorded session | Yes | $25 per seat a month, billed yearly |
| [Tango](https://www.tango.ai/pricing) | Visual step documentation | Captures screenshots and drafts steps | Yes, 5 shared workflows | $22 per user a month billed annually, $15 at 3+ users |
| [Waybook](https://www.waybook.com/pricing) | A dedicated SOP library | [AI SOP writer](https://www.waybook.com/tools/free-ai-sop-creator) | No, 7-day trial | $99 a month billed annually, for 20 seats |
| [Process Street](https://www.process.st/pricing/) | Enforcing a checklist | [AI Workflow Generator](https://www.process.st/help/docs/ai-workflow-generator/) | No, 14-day trial | Contact sales |
| [Notion](https://www.notion.com/pricing) | Flexible documentation | Paste in drafts from any AI assistant | Yes | $10 per member a month, billed yearly |
| [Confluence](https://www.atlassian.com/software/confluence/pricing) | Enterprise wikis | Paste in drafts from any AI assistant | Yes, up to 10 users | $6.70 per user a month at 10 users, billed monthly |

Notion, Scribe, and Tango all have free plans, so any of them is a cheap place to start. Move to a specialized tool later if you outgrow it.

## Step 5: Test it on someone new

You don't know if an SOP works until someone who didn't write it tries to follow it.

Pick someone with the least inside knowledge, like a new hire or someone from another team. Hand them the SOP and ask them to do the task using only the document. Don't help. Watch where they get stuck.

Note:

- How long does it actually take?
- Where do they get stuck?
- What did we assume that isn't obvious to someone else?
- What steps are missing?
- What terminology confused them?

Fix what you saw, not what you expected. Most SOPs need more than one round.

Write for someone who knows nothing about your business. "Open Salesforce" is clear. "Pull the contact list" isn't. Which list, in which system, with which fields?

## Step 6: Roll them out

An SOP nobody's told about sits in a folder nobody opens.

1. **Announce them.** Tell the team these are now the way the work gets done.
2. **Walk through them.** Go through the first one together instead of assuming people will read it on their own.
3. **Watch whether people follow them.** You can't tell if it's working otherwise.
4. **Ask for feedback.** After the first week, ask what was confusing or missing.
5. **Update often at first.** Revise a lot in the first month, then settle into a slower schedule.

For onboarding, pair each new SOP with a walk-through from a team lead. People can't use a procedure they don't know exists.

## Step 7: Keep them current

This is where most SOP efforts stall. The docs get written and rolled out, then the business changes and the docs don't.

**Set a review date.** Look at each SOP on a schedule. Quarterly is reasonable. Tools change, processes improve, rules shift.

**Give each one an owner.** One person keeps it current. Not the original writer, but whoever does the work now.

**Notice when people skip steps.** When someone skips a step or something goes wrong, check the SOP first. Usually either the steps are unclear or the process itself needs to change.

**Date your changes.** "Updated March 2026, added new approval workflow" tells people more than "Current" does.

Confluence and Notion both keep page history. Use it, and still write the change note, because history shows what changed but not why.

## What you get back

The payoff from current SOPs comes in a few concrete ways.

**Faster onboarding.** A new hire with clear steps gets to working on their own sooner than one guessing from a stale doc or asking around.

**Fewer mistakes.** A current procedure catches the mistakes a stale one lets through. That means less redoing work and fewer problems sent up the chain.

**Fewer interruptions.** Every question an SOP answers is one your most experienced people don't have to answer in person.

**Room to grow.** Written-down processes let you add people without adding the same amount of supervision. Undocumented ones depend on someone heroic remembering everything.

**Easier audits.** Current, followed procedures are what an auditor wants to see.

None of this shows up right away. It shows up as fewer "how do I..." questions and new hires who stop needing someone to shadow.

## Common mistakes

**Covering every case at once.** The first version doesn't need every exception. Write the normal path and add exceptions when they actually come up.

**Writing like a contract.** SOPs are for people. Use plain words, short sentences, and say who does what. A procedure that reads like a legal document won't get followed.

**Leaving out the why.** People follow a step better when they know the reason. "Use this format" lands worse than "use this format so the system can read it."

**Writing it alone.** Include the people who actually do the work. How you think a process runs and how it actually runs are usually different.

**Treating them as finished.** A procedure starts going stale the day you publish it. Plan regular updates and give people an easy way to flag what's wrong.

**Skipping the test.** An SOP nobody outside the team has followed is still a draft.

## Start with one process

Pick the process from your list that costs the most time or causes the most mistakes. Write down what happens, let the model draft it in your template, have someone who didn't write it follow it, fix it once, and publish it where people already look.

Then do the next one. Give each SOP an owner and a review date the day it goes live. Procedures that stay current are worth more than a perfect first batch.

## Related Guides

- [How to Create an AI Video Production Workflow](/blog/ai-video-production-workflow)
- [CLAUDE.md and AGENTS.md: What Coding Agents Read](/blog/claude-md-and-agents-md-for-coding-agents)
- [The AI Automation Playbook: Tools, Workflows and ROI](/blog/complete-ai-automation-playbook-2026)]]></content:encoded>
            <author>Zarif</author>
            <category>ai powered sops</category>
            <category>ai sops</category>
            <category>standard operating procedures</category>
            <category>business automation</category>
            <category>ai workflows</category>
        </item>
        <item>
            <title><![CDATA[How to Build a Lead Generation Workflow in n8n Step by Step]]></title>
            <link>https://www.zarifautomates.com/blog/how-to-build-lead-gen-workflow-n8n</link>
            <guid isPermaLink="false">https://www.zarifautomates.com/blog/how-to-build-lead-gen-workflow-n8n</guid>
            <pubDate>Tue, 25 Feb 2025 00:00:00 GMT</pubDate>
            <description><![CDATA[Build an n8n lead workflow: catch a form, look up the company, have a model score the lead against your ideal customer, and send it to your CRM.]]></description>
            <content:encoded><![CDATA[Someone fills out the contact form on your site. By the time a salesperson sees it, it should already say who they are, what company they work for, and whether they're worth a call today.

This guide builds that in n8n with five pieces: a form catcher, a data lookup, an AI score, a CRM write, and an alert when something fails. The scoring step is a prompt, not code.

You'll need an n8n account (cloud or self-hosted), an enrichment API key, a model API key, and access to your CRM.

This guide first went up in February 2025 and was rechecked in September 2026. Two things changed since then. Clearbit no longer sells new accounts, so the lookup step points elsewhere. And the scoring step works with any current small model from OpenAI, Anthropic, or Google.

## Why n8n for this

n8n can call any API, run your own logic, and put an AI model in the middle of the flow. You can also run it on your own server, which keeps prospect data with you.

The self-hosted Community Edition is free under n8n's [Sustainable Use License](https://docs.n8n.io/n8n-community-license). That license allows internal business use, but it isn't an open-source license.

**n8n** (https://n8n.io)

## Step 1: Catch the lead

Every workflow starts with a trigger, the thing that kicks it off. n8n gives you a few ways to catch leads:

- **Webhook node**: a URL your site's form posts to directly
- **Email trigger**: watches an inbox for inquiries
- **Scheduled scrape**: pulls leads from directories or databases on a timer, using HTTP Request nodes
- **Typeform or Google Forms**: built-in connections to those form tools

Start with the webhook. Create a new workflow, add a Webhook node, and set it to accept POST requests. n8n gives you a URL. Point your website's contact form at it.

## Step 2: Look up who they are

A form usually gives you a name and an email. That's not enough to judge a lead. Enrichment means sending that email to a data service and getting back the rest: company name, job title, company size, industry.

Add an HTTP Request node after the trigger and point it at an enrichment API. As of September 2026, three with public API docs are:

- **Hunter**: [Email, Company, and Combined Enrichment endpoints](https://hunter.io/api-documentation/v2). Its [free plan](https://hunter.io/pricing) includes 50 credits a month, enough to test the pipeline.
- **People Data Labs**: a [person enrichment API](https://docs.peopledatalabs.com/docs/reference-person-enrichment-api) with a small free monthly allowance that hides contact fields.
- **Apollo**: a [people enrichment endpoint](https://docs.apollo.io/reference/people-enrichment). How much API access you get depends on your [plan](https://www.apollo.io/pricing), so check before you build on it.

Only map the fields your scoring prompt will actually use. The rest is clutter.

Older versions of this guide recommended Clearbit. Don't use it for a new build. After HubSpot bought it, Clearbit stopped selling new accounts and [points new buyers to HubSpot](https://help.clearbit.com/hc/en-us/articles/20717192156695-How-Can-I-Buy-Clearbit), and its [free tools were shut down in 2025](https://help.clearbit.com/hc/en-us/articles/31990018203031-Clearbit-Free-Tools-Sunset-April-30th-2025).

If your CRM is HubSpot, you may not need a separate lookup at all. HubSpot now calls the Clearbit-based feature [data enrichment](https://knowledge.hubspot.com/records/get-started-with-data-enrichment) (it was sold as Breeze Intelligence) and [includes it in all paid Smart CRM plans](https://www.hubspot.com/products/crm/data-enrichment). In that case, create the contact in HubSpot first and let HubSpot fill in the company fields.

Start with Hunter's free plan to check that email addresses are real before you pay for a bigger data provider. It weeds out bad emails early and costs nothing while you test.

## Step 3: Score the lead with AI

Add an AI node (OpenAI, Anthropic, Google, or any model n8n supports) after the lookup. Its job is to read the lead's details and give it a score.

A small, cheap model is enough. Pick one that supports structured output, which means it returns the score as JSON your workflow can read instead of a paragraph of prose.

Write a prompt that compares the lead to your ideal customer: company size, industry, how senior their title is, and where they're located. Ask for a score from 1 to 10 and a one-line reason.

Then add an If node to split the flow. High scores go straight to sales. Lower scores go into a nurture sequence.

## Step 4: Send it to your CRM

n8n has built-in nodes for HubSpot, Salesforce, Pipedrive, Airtable, and Google Sheets. Add the one you use and match each lead field to the CRM field it belongs in.

For the best leads, add a branch that sends a Slack message or email to sales. Speed matters. [InsideSales' research](https://www.insidesales.com/response-time-matters/) found conversion rates run far higher when a lead is contacted in the first five minutes rather than later.

If a lead comes in overnight, still write it to the CRM right away. Just hold the Slack alert with a time check until business hours, so sales sees it when they can act on it.

## Step 5: Know when it breaks

Things will fail: the lookup service hits its rate limit, someone types a bad email, the CRM connection times out. Set up an Error Trigger workflow in n8n that catches failures and messages you.

Log every lead in a simple Google Sheet or Airtable base with its score and whether it reached the CRM. Look at it once a week. That log is how you'll tune the scoring prompt and decide which data sources are worth keeping.

Most of the running cost is per lead: one lookup call and one model call. Self-hosting n8n removes the platform fee. If you'd rather not run a server, n8n's [hosted plans](https://n8n.io/pricing/) charge per workflow run.

## Make it better over time

Track how many captured leads turn into real sales opportunities. Then adjust the scoring prompt based on which leads actually bought. Drop lookup fields that never change the score. Add a new data source once you notice a pattern in your best customers.

Run 50 leads through the workflow before you turn it on for real. That's enough to surface the odd cases in lookup and scoring that a handful of test submissions won't show you.

## Related Guides

- [How to Build Your First AI Automation: Email Triage in n8n](/blog/how-to-build-your-first-ai-automation-in-under-30-minutes)
- [Build an n8n Ticket-Triage Workflow and Test Its Failure Paths](/blog/how-to-use-n8n-for-advanced-ai-workflow-automation)
- [How to Build a Weekly AI Article Recommendation Workflow](/blog/how-to-build-weekly-ai-article-recommendation-workflow)]]></content:encoded>
            <author>Zarif</author>
            <category>n8n</category>
            <category>lead generation</category>
            <category>workflow</category>
            <category>automation</category>
        </item>
    </channel>
</rss>