{
  "name": "05 Sort email: rules first, AI as fallback",
  "nodes": [
    {
      "id": "7841e7bf-da36-4d94-b208-5a4cd258a39a",
      "name": "New email",
      "type": "n8n-nodes-base.emailReadImap",
      "typeVersion": 2,
      "position": [
        0,
        300
      ],
      "parameters": {
        "mailbox": "INBOX",
        "postProcessAction": "read",
        "format": "simple",
        "options": {}
      }
    },
    {
      "id": "27503e03-6e41-42a9-833f-3ec9b414e2b4",
      "name": "Fixed rules",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        300
      ],
      "parameters": {
        "jsCode": "// Fixed rules on the sender: those are reliable, loose keywords are not.\n// Fill the lists with your own suppliers and regular senders.\nconst regels = [\n  { category: 'invoice',     sender: /^(accounts|accounting|billing|invoices?)@/i },\n  { category: 'supplier', sender: /@(supplier-one\\.example|supplier-two\\.example)$/i },\n];\nreturn $input.all().map(i => {\n  const from = ((i.json.from || '').match(/<([^>]+)>/) || [null, i.json.from || ''])[1].trim();\n  const hit = false ? null : regels.find(r => r.sender.test(from));\n  return { json: { ...i.json, category: hit ? hit.category : null, route: hit ? 'rule' : 'ai' } };\n});"
      }
    },
    {
      "id": "d9558ea4-7ae3-488d-af25-5e4adbfe89d9",
      "name": "Rule matched?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        480,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "r",
              "leftValue": "={{ $json.route }}",
              "rightValue": "rule",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      }
    },
    {
      "id": "c400cb10-0947-4f36-9a82-edcf2f40c813",
      "name": "AI picks category",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "typeVersion": 1.5,
      "position": [
        760,
        60
      ],
      "parameters": {
        "promptType": "define",
        "text": "=Subject: {{ $json.subject }}\n\n{{ ($json.textPlain || '').slice(0, 2000) }}",
        "messages": {
          "messageValues": [
            {
              "message": "You sort the inbox of a small business. Pick exactly one category for the user's email. Answer with only the category word, no explanation.\n\nCategories:\n- quote_request: Someone asks for a price, quote or availability for new work\n- client_question: An existing client has a question, complaint or change about ongoing or delivered work, including about an invoice\n- appointment: Planning, moving or confirming an appointment, visit, measuring, installation or handover\n- supplier: A message from a supplier about an order, delivery, stock or prices\n- invoice: An invoice, payment or credit note without a question or complaint\n- unsubscribe: Someone no longer wants to receive mailings\n- job_application: A job application, vacancy or internship\n- newsletter: A newsletter, webinar or promotional offer\n- other: Fits nowhere else, such as personal messages, parcel notifications or announcements"
            }
          ]
        }
      },
      "notes": "AI only for what the rules do not recognize",
      "notesInFlow": true,
      "retryOnFail": true,
      "maxTries": 2,
      "onError": "continueRegularOutput"
    },
    {
      "id": "b55a4f7c-3413-400b-8921-9e09d76c4a8b",
      "name": "Chat model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOllama",
      "typeVersion": 1,
      "position": [
        780,
        260
      ],
      "parameters": {
        "model": "qwen2.5:7b",
        "options": {
          "temperature": 0.2
        }
      }
    },
    {
      "id": "a1738c95-aaa6-4d94-bbde-05c2f486ec13",
      "name": "Check answer",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1060,
        60
      ],
      "parameters": {
        "jsCode": "// Any answer that is not a known category goes to a human.\nconst ok = [\"quote_request\", \"client_question\", \"appointment\", \"supplier\", \"invoice\", \"unsubscribe\", \"job_application\", \"newsletter\", \"other\"];\nreturn $input.all().map((i, n) => {\n  const mail = $('Rule matched?').all(1)[n]?.json || {};\n  const a = String(i.json.text || '').toLowerCase().replace(/[^a-z_]/g, '');\n  return { json: { ...mail, category: ok.includes(a) ? a : 'review', route: 'ai' } };\n});"
      }
    },
    {
      "id": "1cb6ac74-6f79-41ef-8a33-aeeb7712db74",
      "name": "Add to inbox log",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1,
      "position": [
        1340,
        300
      ],
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "list",
          "value": "",
          "cachedResultName": "inbox_log"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "sender": "={{ $json.from }}",
            "subject": "={{ $json.subject }}",
            "category": "={{ $json.category }}",
            "route": "={{ $json.route }}"
          },
          "matchingColumns": [],
          "schema": [
            {
              "id": "sender",
              "displayName": "sender",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "subject",
              "displayName": "subject",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "category",
              "displayName": "category",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            },
            {
              "id": "route",
              "displayName": "route",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": true
            }
          ]
        },
        "options": {}
      }
    },
    {
      "id": "2269045f-9200-4d7b-979c-f77926e2ea9b",
      "name": "Read me",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -160
      ],
      "parameters": {
        "content": "## Sort email: rules first, AI as fallback\nTested on November 11, 2026, with n8n 2.47.3. Model: qwen2.5:7b via Ollama, 50 test emails.\n\n**Fill in:** an IMAP account, a chat model, and the *inbox_log* table (sender, subject, category, route). Replace the sender lists in 'Fixed rules' with your own suppliers.\n\nAnswers that aren't a known category get 'review'.",
        "height": 220,
        "width": 520,
        "color": 7
      }
    }
  ],
  "connections": {
    "New email": {
      "main": [
        [
          {
            "node": "Fixed rules",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fixed rules": {
      "main": [
        [
          {
            "node": "Rule matched?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Rule matched?": {
      "main": [
        [
          {
            "node": "Add to inbox log",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "AI picks category",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI picks category": {
      "main": [
        [
          {
            "node": "Check answer",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check answer": {
      "main": [
        [
          {
            "node": "Add to inbox log",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Chat model": {
      "ai_languageModel": [
        [
          {
            "node": "AI picks category",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    }
  },
  "meta": {
    "templateCredsSetupCompleted": false
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  }
}