{
  "id": "nhcmCVgnjXWcFG0W",
  "name": "Email Automation",
  "tags": [],
  "nodes": [
    {
      "id": "1d609dce-2e65-4057-a331-2bc4d8dd7389",
      "name": "Email Category Classifier",
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "position": [
        1936,
        352
      ],
      "parameters": {
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "models/gemini-2.5-flash",
          "cachedResultName": "models/gemini-2.5-flash"
        },
        "options": {},
        "messages": {
          "values": [
            {
              "content": "=You are an email classifier for Nexus Integrations.  Classify the email into one category only:  \npricing \nsetup \nsecurity \nhr \nescalate_sales \nescalate_support \nescalate_legal \nspam \nmisdirected  \nEmail: \nSubject: {{ $json.conversation.subject }}\nBody: {{ $json.body }}\n\nReturn only the category."
            }
          ]
        },
        "jsonOutput": true,
        "builtInTools": {}
      },
      "credentials": {
        "googlePalmApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "f0f808d2-3929-48d1-9c19-d8e262f6f580",
      "name": "LLM Response Generator",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        2288,
        576
      ],
      "parameters": {
        "options": {
          "topP": 1,
          "temperature": 0
        }
      },
      "credentials": {
        "googlePalmApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "c5a5fa56-632e-4890-b929-e282bea45fac",
      "name": "Structured Response",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        2544,
        576
      ],
      "parameters": {
        "jsonSchemaExample": "{\n       \"category\": \"...\",\n       \"draft_reply\": \"...\"\n      }"
      },
      "typeVersion": 1.3
    },
    {
      "id": "2d84abda-69d1-4d8a-a6c7-f82daaf289cf",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        0,
        0
      ],
      "parameters": {
        "width": 476,
        "height": 1136,
        "content": "## Try It Out!\n### This template demonstrates a production-ready AI support automation system built specifically for Re:amaze, enabling automated email handling, intent classification & SOP-based decisioning (Knowledge Base).\n\n\ud83d\udd39 Ideal for:\n- Customer support teams handling high volumes of email queries (e.g., e-commerce, SaaS)\n- Businesses looking to automate SOP-based responses with AI while integrating actions like order lookup or issue logging\n\n### What this workflow does\n- Fetches incoming customer emails from Re:amaze\n- Filters only customer messages (ignores agent replies)\n- Classifies email intent (e.g. security, pricing, setup etc.)\n- Matches the request against a structured SOP knowledge base\n- Generates a response using AI based strictly on SOP\n- Sends reply back to the customer automatically\n\n\n### Key Features:\n- Prevents duplicate replies using deduplication logic\n- Ensures responses follow SOP (reduces hallucination)\n- Scalable for high-volume email handling\n\n### Requirements\n- Re:amaze API access (for fetching & replying to conversations)\n- AI model (e.g., OpenAI / Gemini configured in n8n)\n- SOP knowledge base (Google Sheets or Code tool)\n\n### How to set up\n1. Add your Re:amaze API credentials in HTTP nodes\n\nTo get the API Key, you have to login to the Re:amaze plateform(https://www.reamaze.com/)\n\nHere is the API documentation -https://www.reamaze.com/api/get_messages\n\n2. Configure your AI model credentials\n3. Connect your SOP knowledge base (Google Sheets or internal tool)\n4. Test the workflow using sample customer emails\n\n\ud83d\ude80 This template can be extended to support multi-channel support (chat, tickets, etc.)\n\n### Need Help?\nask in the [Forum](https://community.n8n.io/)!\n\nHappy Hacking!"
      },
      "typeVersion": 1
    },
    {
      "id": "64ac5650-5c50-489d-b345-9dac668fee4b",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        768,
        16
      ],
      "parameters": {
        "color": 7,
        "width": 632,
        "height": 492,
        "content": "## \ud83d\udce5 Fetch & Prepare Conversations\n\nThis section retrieves conversations from Re:amaze using API.\n\nSteps:\n- Fetch all conversations\n- Split them into individual messages\n- Sort messages so the latest ones are processed first\n\nThis ensures the workflow always works on the most recent customer queries."
      },
      "typeVersion": 1
    },
    {
      "id": "1daacb63-e1b3-408a-9438-e4d143d8911a",
      "name": "AI Support Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        2352,
        352
      ],
      "parameters": {
        "text": "=Customer Email:\n\nFrom: {{ $('Filter Only Customer Emails').item.json.user.email }}\nBody: {{ $('Filter Only Customer Emails').item.json.body }}\n\nEmail Category:\n{{ $json.content.parts[0].text }}\n\nWrite the reply.",
        "options": {
          "systemMessage": "You are a Nexus Integrations customer support assistant.\n\nYour job is to read the customer email and produce a correct support reply using the Nexus documentation provided by the system. The documentation is the single source of truth.\n\nGeneral Rules\n\n1. Always search the documentation before answering.\n2. Extract facts directly from the documentation and use them in your reply.\n3. Prefer quoting or closely paraphrasing documentation sentences whenever possible.\n4. Never say that information is missing or unavailable in documentation.\n5. Do not invent features, pricing details, security claims, or policies that are not present in the documentation.\n\nAnswering Rules\n6. If the documentation contains the answer, provide the information directly instead of escalating.\n7. When answering pricing questions, include exact details such as:\n\n* integration limits\n* API call limits\n* overage pricing\n* sync frequency\n* feature availability (SSO, IP whitelisting, connectors, etc.)\n\n8. When answering setup questions, provide clear steps based on documented setup procedures (authentication, API access, field mapping, connectors, sync modes, etc.).\n\n9. When answering security questions, include specific documented facts such as:\n\n   * encryption in transit and at rest\n   * SOC2 compliance\n   * GDPR compliance\n   * HIPAA availability for Enterprise plans\n   * security features like SSO, audit logs, or IP whitelisting\n\nEscalation Rules\n10. Only escalate when the documentation explicitly requires escalation.\n11. If escalation is required, clearly state that the request has been forwarded and mention the correct team or contact email from the documentation.\n\nExamples of escalation situations:\n\n* Technical integration failures \u2192 support team\n* Enterprise pricing or partnership requests \u2192 sales team\n* Legal agreements or compliance documents \u2192 legal team\n* Security incidents or vulnerability reports \u2192 security team\n* HR or career inquiries \u2192 HR team\n\nCategory Behavior Rules\n12. Setup questions should normally be answered with guidance instead of escalation.\n13. Pricing questions should normally be answered using plan details rather than escalated.\n14. HR or career inquiries should be routed to the HR team.\n15. Spam or promotional emails should be ignored or responded to with a brief polite decline.\n16. Misdirected emails should receive a short \u201cwrong recipient\u201d response.\n\nResponse Style\n17. Responses should be professional, helpful, and concise.\n18. Avoid speculation, uncertainty, or generic statements when specific documentation facts exist.\n19. Always prefer factual statements derived from documentation.\n\nOutput Format\nYour response must be valid JSON and contain exactly the following fields:\n\n{\n\"category\": \"<final category>\",\n\"draft_reply\": \"<customer support reply>\"\n}\n"
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 3.1
    },
    {
      "id": "8b62ff65-7d41-4072-bd2d-3e5df0a49dcb",
      "name": "Manual Trigger (Test Workflow)",
      "type": "n8n-nodes-base.manualTrigger",
      "position": [
        592,
        352
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "68c6ef93-566c-4de4-98e4-189d6fa67012",
      "name": "Fetch Conversations from Re:amaze API",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        816,
        352
      ],
      "parameters": {
        "url": "https://divyanshu.reamaze.com/api/v1/messages",
        "options": {},
        "sendHeaders": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json"
            }
          ]
        }
      },
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.4
    },
    {
      "id": "f422ca93-dd2f-4b2a-9faa-de67e8890446",
      "name": "Split Conversations into Individual Messages",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        1040,
        352
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "messages"
      },
      "typeVersion": 1
    },
    {
      "id": "4a29db83-1d66-45a6-b79a-bf54a01c7001",
      "name": "Sort Messages by Latest First",
      "type": "n8n-nodes-base.sort",
      "position": [
        1264,
        352
      ],
      "parameters": {
        "options": {},
        "sortFieldsUi": {
          "sortField": [
            {
              "order": "descending",
              "fieldName": "created_at"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "9b8e3e4d-f30a-44e6-8527-cc665889b96e",
      "name": "Remove Duplicate Conversations (Prevent Double Reply)",
      "type": "n8n-nodes-base.removeDuplicates",
      "position": [
        1488,
        352
      ],
      "parameters": {
        "compare": "selectedFields",
        "options": {},
        "fieldsToCompare": "conversation.slug"
      },
      "typeVersion": 2
    },
    {
      "id": "771fcd2c-3a87-417f-b0ce-bcac9eeb8ae6",
      "name": "Filter Only Customer Emails",
      "type": "n8n-nodes-base.if",
      "position": [
        1712,
        352
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 3,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "6b803965-281f-46e4-aa5c-7a439c0ebb3e",
              "operator": {
                "type": "number",
                "operation": "equals"
              },
              "leftValue": "={{ $json.origin }}",
              "rightValue": 1
            },
            {
              "id": "4a0805e5-6c17-4747-b005-fa21f9076bdd",
              "operator": {
                "type": "boolean",
                "operation": "equals"
              },
              "leftValue": "={{ $json.user['staff?'] }}",
              "rightValue": false
            },
            {
              "id": "a221f86a-448f-4217-841f-3e240f6e6f44",
              "operator": {
                "type": "number",
                "operation": "equals"
              },
              "leftValue": "={{ $json.visibility }}",
              "rightValue": 0
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "34ddfabc-8275-47f1-9b23-6349d65bcc90",
      "name": "\ud83d\udcda Knowledge Base",
      "type": "@n8n/n8n-nodes-langchain.toolCode",
      "position": [
        2416,
        576
      ],
      "parameters": {
        "jsCode": "// Nexus Knowledge Base Tool\n// Full dataset from Excel (single source of truth)\n\nconst docs = [\n{category:\"pricing\",title:\"starter_plan\",content:`Plan: Starter. Monthly price: $299. Annual price: $249 with 17% savings. Ideal for small teams starting integrations. Maximum integrations: 3. API calls per month: 10,000. Overage cost: $25 per 1,000 API calls. Support: Email support with 48 hour response. Sync frequency: Scheduled sync. Connectors tier: Standard. Webhooks: Basic. Field mapping: Standard. SSO: Not available. Audit logs: Basic activity logs. IP whitelisting: Not available. Dedicated account manager: No. Custom connectors: 0 per year. Onboarding: Community access. Free trial: 14 days. Cancel anytime: Yes.`},\n\n{category:\"pricing\",title:\"professional_plan\",content:`Plan: Professional. Monthly price: $799. Annual price: $649 with 19% savings. Ideal for growing businesses. Maximum integrations: 10. API calls per month: 50,000. Overage cost: $20 per 1,000 API calls. Support: Email and phone support with 24 hour response. Sync frequency: Real-time every 5 minutes. Connectors tier: Standard and Premium connectors. Webhooks: Advanced with retry logic. Field mapping: Custom mapping supported. SSO: Not available. Audit logs: Basic logs. IP whitelisting: Not available.`},\n\n{category:\"pricing\",title:\"enterprise_plan\",content:`Plan: Enterprise. Custom pricing starting around $2500+. Ideal for large organizations. Maximum integrations: Unlimited. API calls: 250,000+ starting limit. Support: 24/7 premium support with 4 hour response. Sync frequency: Real-time every 30 seconds. Connectors tier: All connectors including enterprise-exclusive connectors. Webhooks: Advanced with retry logic. Field mapping: Custom mapping supported. SSO: Supported with SAML 2.0. Audit logs: Comprehensive logs. IP whitelisting: Supported. Dedicated account manager: Yes. Custom connectors: Up to 2 per year.`},\n\n{category:\"pricing\",title:\"nonprofit_discount\",content:`Nonprofit organizations receive 25% discount on annual Nexus subscriptions.`},\n\n{category:\"setup\",title:\"integration_setup\",content:`Nexus integrates platforms such as Salesforce, HubSpot, SAP, and Microsoft Dynamics. Setup: Click Connect Integration, authorize platform, ensure admin permissions and API access enabled.`},\n\n{category:\"setup\",title:\"real_time_sync\",content:`Enterprise sync: about 30 seconds using webhooks. Professional sync: about 5 minutes.`},\n\n{category:\"setup\",title:\"manual_sync\",content:`Manual sync allows users to trigger synchronization manually instead of waiting for scheduled intervals.`},\n\n{category:\"setup\",title:\"scheduled_sync\",content:`Scheduled sync runs periodically at configured intervals rather than real-time.`},\n\n{category:\"security\",title:\"encryption\",content:`Nexus encrypts data both in transit and at rest using industry standard encryption protocols.`},\n\n{category:\"security\",title:\"soc2_compliance\",content:`Nexus is SOC2 compliant and follows strict security controls.`},\n\n{category:\"security\",title:\"gdpr_compliance\",content:`Nexus complies with GDPR regulations for protecting EU personal data.`},\n\n{category:\"security\",title:\"hipaa_availability\",content:`HIPAA compliance available only for Enterprise customers with signed Business Associate Agreement.`},\n\n{category:\"security\",title:\"sso_support\",content:`Single Sign-On using SAML 2.0 supported for Enterprise customers.`},\n\n{category:\"security\",title:\"ip_whitelisting\",content:`IP whitelisting available for Enterprise customers.`},\n\n{category:\"security\",title:\"audit_logs\",content:`Nexus provides audit logs tracking integration activities.`},\n\n{category:\"security\",title:\"soc2_report_request\",content:`SOC2 audit reports available under NDA upon request.`},\n\n{category:\"escalate_support\",title:\"technical_support\",content:`Integration failures, authentication errors, sync issues should be escalated to user@example.com.`},\n\n{category:\"escalate_support\",title:\"integration_failure\",content:`If integration fails repeatedly escalate to Nexus support team.`},\n\n{category:\"escalate_sales\",title:\"enterprise_sales\",content:`Enterprise pricing requests, partnerships and custom integrations escalate to user@example.com.`},\n\n{category:\"escalate_sales\",title:\"partnership_requests\",content:`Partnership inquiries should be escalated to the Nexus sales department.`},\n\n{category:\"escalate_legal\",title:\"contract_review\",content:`Legal agreements and contract related questions escalate to user@example.com.`},\n\n{category:\"hr\",title:\"careers\",content:`Job applications or career inquiries should be directed to HR team user@example.com.`},\n\n{category:\"spam\",title:\"spam_email\",content:`Promotional or malicious emails should be marked as spam and ignored.`},\n\n{category:\"misdirected\",title:\"wrong_recipient\",content:`Emails unrelated to Nexus should be marked as misdirected and optionally replied with a wrong recipient message.`}\n];\n\n// input from AI agent\nconst category = $json.category || \"\";\n\n// filter docs for that category\nconst filtered = docs.filter(d => d.category === category);\n\n// full context\nconst full_context = docs.map(d => `[${d.category}] ${d.title}: ${d.content}`).join(\"\\n\\n\");\n\n// category context\nconst category_context = filtered.map(d => `${d.title}: ${d.content}`).join(\"\\n\\n\");\n\nreturn {\ncategory,\ncategory_context,\nfull_context\n};"
      },
      "typeVersion": 1.3
    },
    {
      "id": "7361bcc6-1dd4-4f92-90e7-d092e991c1ed",
      "name": "Prepare Final Response",
      "type": "n8n-nodes-base.set",
      "position": [
        2752,
        352
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "6fa08d3d-14b2-4526-b1c2-6b57d3d58b3e",
              "name": "clean_reply",
              "type": "string",
              "value": "={{ $json.output.draft_reply.replace(/\\n/g, \"\\\\n\").replace(/\"/g, '\\\\\"') }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "e59fc69f-e2a1-4041-bb9b-2fdf764fecfc",
      "name": "Send Reply to Customer (Re:amaze API)",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        2976,
        352
      ],
      "parameters": {
        "url": "=https://divyanshu.reamaze.com/api/v1/conversations/{{ $('Filter Only Customer Emails').item.json.conversation.slug }}/messages",
        "body": "={\n  \"message\": {\n    \"body\": \"{{ $json.clean_reply }}\",\n    \"visibility\": 0\n  }\n}",
        "method": "POST",
        "options": {},
        "sendBody": true,
        "contentType": "raw",
        "sendHeaders": true,
        "authentication": "genericCredentialType",
        "rawContentType": "=application/json",
        "genericAuthType": "httpBasicAuth",
        "headerParameters": {
          "parameters": [
            {
              "name": "Accept",
              "value": "application/json"
            },
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        }
      },
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.4
    },
    {
      "id": "c4f1a478-8065-42d9-93e8-c024d58ea6c0",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1440,
        16
      ],
      "parameters": {
        "color": 7,
        "width": 472,
        "height": 492,
        "content": "## \u26a0\ufe0f Deduplication & Filtering\n\nThis section ensures only valid customer messages are processed.\n\n- Removes duplicate conversations to prevent multiple replies\n- Filters only customer emails using:\n  origin = 1 \u2192 Customer\n  origin = 7 \u2192 Agent (ignored)\n\nThis guarantees:\n\u2714 No duplicate replies\n\u2714 No replies to internal/agent messages"
      },
      "typeVersion": 1
    },
    {
      "id": "5ab619b0-30b2-4b2b-a6f3-91ecfc76c0f5",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1936,
        0
      ],
      "parameters": {
        "color": 7,
        "width": 354,
        "height": 512,
        "content": "## \ud83e\udde0 Email Intent Classification\nThe model analyzes the email and predicts a category.\n\nSupported categories:\n\u2022 setup\n\u2022 pricing\n\u2022 security\n\u2022 hr\n\u2022 escalate_support\n\u2022 escalate_sales\n\u2022 escalate_legal\n\u2022 spam\n\u2022 misdirected\n\nThis category guides how the AI agent responds."
      },
      "typeVersion": 1
    },
    {
      "id": "299d325a-f72d-4887-ba68-91d7ffd77c1b",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2320,
        0
      ],
      "parameters": {
        "color": 7,
        "width": 776,
        "height": 508,
        "content": "## \ud83e\udd16 AI Response Generation & Reply\n\nThis section generates and sends the final response.\n\n- AI uses SOP-based knowledge to create accurate replies\n- Ensures responses are consistent and controlled (no hallucination)\n- Formats the response payload\n- Sends reply back to customer via Re:amaze API\n\nResult:\n\u2714 Automated, high-quality customer support replies\n\u2714 Consistent tone and policy adherence"
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "binaryMode": "separate",
    "availableInMCP": false,
    "executionOrder": "v1"
  },
  "versionId": "67b55f0b-1190-47e5-b142-668b1f8970d4",
  "connections": {
    "AI Support Agent": {
      "main": [
        [
          {
            "node": "Prepare Final Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Structured Response": {
      "ai_outputParser": [
        [
          {
            "node": "AI Support Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "\ud83d\udcda Knowledge Base": {
      "ai_tool": [
        [
          {
            "node": "AI Support Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "LLM Response Generator": {
      "ai_languageModel": [
        [
          {
            "node": "AI Support Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Final Response": {
      "main": [
        [
          {
            "node": "Send Reply to Customer (Re:amaze API)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Email Category Classifier": {
      "main": [
        [
          {
            "node": "AI Support Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter Only Customer Emails": {
      "main": [
        [
          {
            "node": "Email Category Classifier",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sort Messages by Latest First": {
      "main": [
        [
          {
            "node": "Remove Duplicate Conversations (Prevent Double Reply)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Manual Trigger (Test Workflow)": {
      "main": [
        [
          {
            "node": "Fetch Conversations from Re:amaze API",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Conversations from Re:amaze API": {
      "main": [
        [
          {
            "node": "Split Conversations into Individual Messages",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Conversations into Individual Messages": {
      "main": [
        [
          {
            "node": "Sort Messages by Latest First",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Remove Duplicate Conversations (Prevent Double Reply)": {
      "main": [
        [
          {
            "node": "Filter Only Customer Emails",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}