{
  "name": "Guarded email reply agent",
  "nodes": [
    {
      "parameters": {
        "content": "## Guarded email reply agent\n\nPortfolio demo only. This workflow is an original example for demonstration. It is not client work and it does not represent a deployment for any customer.\n\nRun **Run demo** to execute the offline rules engine. The live branch is used only when the incoming item sets `demo` to false and the placeholder credentials have been replaced.",
        "height": 220,
        "width": 520,
        "color": 4
      },
      "id": "1a3b3a72-6c1f-444a-825e-689ae577d3ef",
      "name": "Overview",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -40,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "fbebe334-1d3f-4190-8e67-b5ee0640808a",
      "name": "Run demo",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        40,
        280
      ],
      "notes": "CLI and the n8n editor start here. An empty manual run loads the bundled sample.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "guarded-email-reply-agent",
        "authentication": "none",
        "responseMode": "lastNode",
        "responseData": "firstEntryJson",
        "options": {}
      },
      "id": "5934f88e-226a-434c-9118-a65316eb8d8c",
      "name": "Inbound webhook",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        40,
        460
      ],
      "notes": "POST JSON to this path. Include demo:false only after credentials are connected.",
      "notesInFlow": true,
      "webhookId": "fffe445a-32eb-4b7f-bb4d-7a593608b21f"
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "event": "messageReceived",
        "simple": true
      },
      "id": "bfd16f45-4292-44fe-aa43-4a883ec7d444",
      "name": "Gmail trigger",
      "type": "n8n-nodes-base.gmailTrigger",
      "typeVersion": 1.2,
      "position": [
        40,
        640
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "PLACEHOLDER_GMAILOAUTH2",
          "name": "Gmail account"
        }
      },
      "notes": "Polls the mailbox once credentials replace the placeholder. Tests do not call Gmail.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const sample = {\n  \"demo\": true,\n  \"prompt\": \"Customer asked for a refund of last Tuesday's charge.\",\n  \"sessionId\": \"inbox\"\n};\nconst incoming = $input.first()?.json ?? {};\nconst provided = Object.keys(incoming).filter((key) => incoming[key] !== undefined && incoming[key] !== null && incoming[key] !== '');\nconst base = provided.length ? { ...sample, ...incoming } : { ...sample };\nconst flag = incoming.demo;\nbase.demo = !(flag === false || flag === 'false' || flag === 0 || flag === '0');\nreturn [{ json: base }];\n"
      },
      "id": "e4c36688-500b-4d5d-ab9c-a85b3e641f90",
      "name": "Normalize input",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        340,
        360
      ],
      "notes": "Merges the request over the bundled sample. demo stays true unless the caller explicitly turns it off.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const item = $input.first().json;\nconst produced = (() => {\n\nconst book = {\n  'refund': 'We can refund a charge within 14 days. Draft the reply. Do not send it.'\n};\nconst prompt = String(item.prompt || item.question || item.text || '').toLowerCase();\nconst keys = Object.keys(book);\nconst hit = keys.find((key) => prompt.includes(key)) || null;\nconst answer = hit ? book[hit] : 'I do not have a grounded answer for that in the demo knowledge set. Ask about: ' + keys.join(', ') + '.';\nconst record = { answer, topic: hit, persona: 'inbox agent', sessionId: item.sessionId || 'portfolio-demo' };\nreturn {\n  summary: answer,\n  route: hit ? 'answered' : 'fallback',\n  prompt: item.prompt || item.question || item.text || '',\n  record,\n  slackText: (hit ? 'Answered' : 'Fallback') + ': ' + answer,\n  actions: [{ app: 'agent', operation: 'reply', payload: record }],\n};\n\n})();\nif (!produced || typeof produced.summary !== 'string' || !produced.summary.trim()) {\n  throw new Error('Apply rules must return a summary string');\n}\nreturn [{\n  json: {\n    ...item,\n    ...produced,\n    demo: item.demo !== false,\n  },\n}];\n"
      },
      "id": "236273f3-415b-47f2-8780-e5ad36283c53",
      "name": "Apply rules",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        620,
        360
      ],
      "notes": "Deterministic stand-in for the model or enrichment API. Replace or precede this with a live model node when you turn demo mode off.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "1c7b2202-5aac-40dd-a409-75a0d458e30f",
              "leftValue": "={{ $json.demo }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "bbc662a3-ffa1-4707-a345-d0d05ed780bb",
      "name": "Demo mode?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        900,
        360
      ],
      "notes": "True: package the offline result. False: run the credentialed apps.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "language": "javaScript",
        "jsCode": "const item = $input.first().json;\nreturn [{\n  json: {\n    demo: true,\n    status: 'demo_ready',\n    workflow: 'guarded-email-reply-agent',\n    summary: item.summary,\n    route: item.route ?? null,\n    record: item.record ?? {},\n    actions: item.actions ?? [],\n    slackText: item.slackText ?? item.summary,\n    notes: 'Demo mode did not call external apps. Send {\"demo\": false} after placeholder credentials are replaced.',\n  },\n}];\n"
      },
      "id": "44c1f0b8-8ec6-40bf-a3b6-fec74841d015",
      "name": "Package demo result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1180,
        180
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.prompt || $json.summary }}",
        "options": {
          "systemMessage": "You are a careful operations assistant. Use tools for facts. Never invent prices, dates, or customer data."
        }
      },
      "id": "56cae6fd-a3b7-428c-b67b-7af24c54bef9",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        1220,
        780
      ],
      "notes": "Live agent. Demo mode answers from Apply rules so tests do not spend model credits.",
      "notesInFlow": true
    },
    {
      "parameters": {
        "model": "llama-3.3-70b-versatile",
        "options": {
          "temperature": 0.2
        }
      },
      "id": "b464087d-4afb-41e0-bcb1-9d752774ba30",
      "name": "Groq chat model",
      "type": "@n8n/n8n-nodes-langchain.lmChatGroq",
      "typeVersion": 1,
      "position": [
        980,
        980
      ],
      "credentials": {
        "groqApi": {
          "id": "PLACEHOLDER_GROQAPI",
          "name": "Groq account"
        }
      }
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $json.sessionId || 'portfolio-demo' }}",
        "contextWindowLength": 8
      },
      "id": "d97f1387-5c47-4c84-b0db-e89c0d201f72",
      "name": "Window memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.4,
      "position": [
        1220,
        1040
      ]
    },
    {
      "parameters": {
        "name": "lookup_policy",
        "description": "Return the refund or shipping policy.",
        "language": "javaScript",
        "jsCode": "const topic = String(query.topic || query || '').toLowerCase();\nif (topic.includes('refund')) return { policy: '14 days' };\nreturn { policy: null };"
      },
      "id": "0d48d97e-0d9e-4cda-8efa-cfd9f5a967f2",
      "name": "lookup_policy",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "typeVersion": 1.3,
      "position": [
        1460,
        1040
      ]
    },
    {
      "parameters": {
        "authentication": "oAuth2",
        "resource": "draft",
        "operation": "create",
        "sendTo": "={{ $json.record.email || $json.email || 'lead@example.com' }}",
        "subject": "={{ $json.record.subject || $json.summary }}",
        "message": "={{ $json.record.body || $json.record.message || $json.summary }}",
        "emailType": "text",
        "messageId": "={{ $json.record.messageId || 'MESSAGE_ID' }}",
        "labelIds": [
          "Label_1"
        ]
      },
      "id": "bb8cada9-1c20-4787-b288-8f60602568bf",
      "name": "Create Gmail draft",
      "type": "n8n-nodes-base.gmail",
      "typeVersion": 2.1,
      "position": [
        1560,
        780
      ],
      "credentials": {
        "gmailOAuth2": {
          "id": "PLACEHOLDER_GMAILOAUTH2",
          "name": "Gmail account"
        }
      }
    },
    {
      "parameters": {
        "content": "## Live path\n\nReplace every `PLACEHOLDER_*` credential, then POST the sample with `\"demo\": false`.\n\nThe nodes on this branch use the `record` and `actions` fields produced by Apply rules.",
        "height": 180,
        "width": 420,
        "color": 6
      },
      "id": "0a5f9c88-e284-4667-be5e-d790979f11ed",
      "name": "Live path",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1120,
        520
      ]
    }
  ],
  "connections": {
    "Run demo": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Inbound webhook": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail trigger": {
      "main": [
        [
          {
            "node": "Normalize input",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Normalize input": {
      "main": [
        [
          {
            "node": "Apply rules",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Apply rules": {
      "main": [
        [
          {
            "node": "Demo mode?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Demo mode?": {
      "main": [
        [
          {
            "node": "Package demo result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Groq chat model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Window memory": {
      "ai_memory": [
        [
          {
            "node": "AI Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "lookup_policy": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "Create Gmail draft",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "meta": {
    "templateCredsSetupCompleted": false,
    "description": "A reply is drafted from a policy book. The live agent may call Gmail only to create a draft, never to send."
  },
  "active": false
}
