{
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "d94e086d-1845-420c-a8d0-659f2985dfb4",
      "name": "Gmail Trigger1",
      "type": "n8n-nodes-base.gmailTrigger",
      "position": [
        -2848,
        1440
      ],
      "parameters": {
        "filters": {},
        "pollTimes": {
          "item": [
            {
              "mode": "everyMinute"
            }
          ]
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "923af877-ba1b-4765-b297-93fb9ffcbda1",
      "name": "Structured Output Parser1",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        -1760,
        1664
      ],
      "parameters": {
        "autoFix": true,
        "jsonSchemaExample": "{\n\t\"label\": \"Label name\", \n\"label ID\": \"label ID\" \n}"
      },
      "typeVersion": 1.2
    },
    {
      "id": "a289e623-df2d-4e2d-b324-544e2d350535",
      "name": "Check Sent2",
      "type": "n8n-nodes-base.gmailTool",
      "position": [
        -2016,
        1664
      ],
      "parameters": {
        "filters": {
          "q": "=to:{{ $fromAI('email') }}",
          "labelIds": [
            "SENT"
          ]
        },
        "operation": "getAll"
      },
      "typeVersion": 2.1
    },
    {
      "id": "019e8526-436c-4619-9da1-d9f958905e54",
      "name": "Create Label if Doesn't exist1",
      "type": "n8n-nodes-base.gmail",
      "onError": "continueRegularOutput",
      "position": [
        -1056,
        1440
      ],
      "parameters": {
        "name": "={{ $json.output.label }}",
        "options": {},
        "resource": "label",
        "operation": "create"
      },
      "typeVersion": 2.1
    },
    {
      "id": "cc545b7e-f5ae-44f0-98ab-6de8161905b2",
      "name": "Get Existing Labels1",
      "type": "n8n-nodes-base.gmail",
      "position": [
        -704,
        1440
      ],
      "parameters": {
        "resource": "label",
        "returnAll": true
      },
      "typeVersion": 2.1
    },
    {
      "id": "ead0e438-b7df-4432-a241-a5acfe85c550",
      "name": "Loop Over Items1",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        -1392,
        1440
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "708905c5-51de-49a4-9955-04bda21371de",
      "name": "Filter1",
      "type": "n8n-nodes-base.filter",
      "position": [
        -480,
        1440
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "e36a5069-09dd-424d-a2b8-096cefa059d7",
              "operator": {
                "name": "filter.operator.equals",
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.name }}",
              "rightValue": "={{ $('Loop Over Items1').item.json.output.label }}"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "3f784595-5df0-4809-8bfc-fbb613f26493",
      "name": "Check Sent3",
      "type": "n8n-nodes-base.gmailTool",
      "position": [
        -1888,
        1664
      ],
      "parameters": {
        "resource": "label"
      },
      "typeVersion": 2.1
    },
    {
      "id": "44cd8d9e-4a22-4dc1-aff7-83cdda5743d8",
      "name": "Add label to thread1",
      "type": "n8n-nodes-base.gmail",
      "position": [
        -256,
        1504
      ],
      "parameters": {
        "labelIds": "={{ $json.id }}",
        "resource": "thread",
        "threadId": "={{ $('Get a message1').item.json.threadId }}",
        "operation": "addLabels"
      },
      "typeVersion": 2.1
    },
    {
      "id": "11bf73c9-645b-4166-a1bf-b21daf52b443",
      "name": "Code1",
      "type": "n8n-nodes-base.code",
      "onError": "continueErrorOutput",
      "position": [
        -768,
        784
      ],
      "parameters": {
        "jsCode": "const raw = $json.output;\n\n// Fully remove any Markdown code block wrapping\nconst clean = raw\n  .replace(/^\\s*```json\\s*/i, '')  // Remove opening ```json\n  .replace(/^\\s*```\\s*/i, '')      // Remove opening ``` if no json\n  .replace(/\\s*```$/, '')          // Remove trailing ```\n  .trim();\n\nlet parsed;\n\ntry {\n  parsed = JSON.parse(clean);\n} catch (e) {\n  throw new Error('Failed to parse JSON: ' + e.message + '\\nContent: ' + clean);\n}\n\nreturn [\n  {\n    json: {\n      urgency: parsed.urgency || 'normal',\n      summary: parsed.summary || ''\n    }\n  }\n];\n"
      },
      "typeVersion": 2
    },
    {
      "id": "bcd51860-5e8c-4a25-a138-8c716c71843e",
      "name": "If1",
      "type": "n8n-nodes-base.if",
      "position": [
        -544,
        736
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "08d94b28-1974-422c-ab84-5fe541b6be22",
              "operator": {
                "name": "filter.operator.equals",
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.urgency }}",
              "rightValue": "urgent"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "5853e3f7-fd73-442f-8c78-f7ac05903495",
      "name": "Send message1",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        -320,
        640
      ],
      "parameters": {
        "textBody": "=\nto :{{ $('Gmail Trigger1').first().json.To }}\n\n{{ $json.summary }}\n\n\n{{ $('Gmail Trigger1').item.json.snippet }}\n",
        "operation": "send",
        "phoneNumberId": "[REDACTED_PHONE_NUMBER_ID]",
        "additionalFields": {
          "previewUrl": false
        },
        "recipientPhoneNumber": "[REDACTED_RECIPIENT_PHONE_NUMBER]"
      },
      "typeVersion": 1
    },
    {
      "id": "c985b440-5e29-4441-beec-ebf85d64367d",
      "name": "Send a text message1",
      "type": "n8n-nodes-base.telegram",
      "position": [
        -320,
        864
      ],
      "parameters": {
        "text": "=\nto :{{ $('Gmail Trigger1').first().json.To }}\n\n{{ $json.summary }}\n\n\n{{ $('Gmail Trigger1').item.json.snippet }}\n",
        "chatId": "[REDACTED_CHAT_ID]",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "retryOnFail": true,
      "typeVersion": 1.2
    },
    {
      "id": "6fd66034-4fd6-49f7-87c0-f254b2eb1a3c",
      "name": "OpenRouter Chat Model2",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "position": [
        -2144,
        1664
      ],
      "parameters": {
        "model": "deepseek/deepseek-chat-v3-0324:free",
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "7f49e491-2774-4ecf-9cb0-8fca4c1a799d",
      "name": "Wait1",
      "type": "n8n-nodes-base.wait",
      "position": [
        -544,
        960
      ],
      "parameters": {
        "amount": 15
      },
      "typeVersion": 1.1
    },
    {
      "id": "992e1bb0-b068-4e72-8509-eceede49581c",
      "name": "AI Agent3",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -2112,
        1440
      ],
      "parameters": {
        "text": "Run the task.",
        "options": {
          "systemMessage": "=Objective:\nClassify the given email into the most appropriate domain-specific label by analyzing the sender, subject, content, metadata, and prior engagement history. Return only the corresponding Label ID based on the classification criteria. Use unsubscribe headers, auto-submission flags, and sender reputation to improve accuracy.\n\n\ud83d\udce7 Input Email Metadata\nSender: {{ $json.from.value[0].name }} <{{ $json.from.value[0].address }}>\n\nTo: {{ $json.to.value.map(r => r.address).join(', ') }}\n\nSubject: {{ $json.subject }}\n\nBody (Text): {{ $json.text }}\n\nGmail Labels: {{ $json.labelIds.join(', ') }}\n\nHeaders:\n\nAuto-Submitted: {{ $json.headers['auto-submitted'] }}\n\nList-Unsubscribe: {{ $json.headers['list-unsubscribe'] }}\n\nPrecedence: {{ $json.headers['precedence'] }}\n\nIn-Reply-To: {{ $json.headers['in-reply-to'] }}\n\nReferences: {{ $json.headers['references'] }}\n\nPrior Email History with Sender: (from user logs or database)\n\n\ud83e\udde0 Label Classification Criteria\nLabel Name\tLabel ID\tDescription\nFinance\tLabel_FIN_90210\tStatements, invoices, bank alerts, credit cards, UPI summaries.\nEducation\tLabel_EDU_90211\tCourses, admissions, certifications, university updates.\nMarketing\tLabel_MKT_90212\tPromotions, upsells, newsletters selling something.\nNotification\tLabel_NOTIFY_90213\tBilling, system alerts, policy changes, service updates.\nTo Respond\tLabel_ACTION_90214\tRequires user's reply, task-YOUR_OPENAI_KEY_HERE, follow-up needed.\nFYI\tLabel_FYI_90215\tInformational only, no reply needed.\nComment/Feedback\tLabel_COMMENT_90216\tComments on docs, feedback, inline annotations.\nMeeting Update\tLabel_MEETING_90217\tInvites, schedule changes, meeting summaries.\nCloud Services\tLabel_CLOUD_90218\tEmails from AWS, Azure, GCP, Cloudflare, etc.\nDev Tools\tLabel_DEV_90219\tGitHub, GitLab, Docker, CI/CD pipelines, webhooks, etc.\nTech Updates\tLabel_TECH_90220\tProduct launches, changelogs, software feature rollouts.\nCommunity/Forum\tLabel_COMM_90221\tThreads from Reddit, StackOverflow, Discord, forums.\nSecurity Alert\tLabel_SEC_90222\tLogin attempts, MFA alerts, password resets.\n\n\u2699\ufe0f Classification Rules (Heuristics)\nAuto-Submitted = yes OR Precedence = bulk: Likely Notification, FYI, or Marketing.\n\nList-Unsubscribe exists AND No prior history: Prefer Marketing.\n\nSender is GitHub, CI/CD, or version control tool \u2192 Dev Tools.\n\nSubject/body mentions login attempt, MFA, password reset \u2192 Security Alert.\n\nFrom AWS, Cloudflare, or similar \u2192 Cloud Services.\n\nRelease notes, update logs, patch info \u2192 Tech Updates.\n\nCommunity replies, thread responses \u2192 Community/Forum.\n\nDirect task requests or questions \u2192 To Respond.\n\nInvoices/statements with no promo \u2192 Finance.\n\nSchool/university address or edu domain \u2192 Education.\n\n\u2705 Final Instruction:\nReturn ONLY the Label ID that best matches the email based on the above logic. No extra output, just the correct ID.\n\n\ud83d\udccc Sample Email Analysis (Example)\nFrom: GitHub noreply@github.com\nSubject: [your-repo] New pull request opened\nContent: Contributor opened PR with description and change log. No reply needed unless assigned.\nHeaders: auto-submitted: yes\nPrior history: Yes (developer account)\n\n\ud83d\udc49 Result:\nLabel_DEV_90219"
        },
        "promptType": "define",
        "needsFallback": true,
        "hasOutputParser": true
      },
      "executeOnce": false,
      "typeVersion": 2.1
    },
    {
      "id": "ea93f6d2-14ed-44ae-a13d-e283aedea9b6",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        -1680,
        1872
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-nano",
          "cachedResultName": "gpt-4.1-nano"
        },
        "options": {}
      },
      "typeVersion": 1.2
    },
    {
      "id": "48d11f0f-6f8d-43ff-baa7-6676e338d68c",
      "name": "AI Agent1",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -1184,
        752
      ],
      "parameters": {
        "text": "=You are an intelligent email assistant.\n\nYour task is to:\n1. Analyze the following email.\n2. Decide whether it is **urgent** or **normal**.\n3. Provide a **short summary** of what the email is about (max 2 sentences).\n\nUse urgency judgment based on:\n- Urgent = Requires immediate action (e.g., OTP, payment due, failed transaction, security alert, verification, deadline)\n- Normal = Informational emails like statements, newsletters, general notifications, or promotions\n\n\n---\n\nEmail Details:\n\nFrom: {{ $('Get a message1').item.json.from.value[0].address }}\nSubject: {{ $('Get a message1').item.json.subject }}\nBody:{{ $('Get a message1').item.json.text }}\n\n---\n\nRespond in the following JSON format:\n{\n  \"urgency\": \"urgent\" | \"normal\",\n  \"summary\": \"[short explanation of the email]\"\n}\n",
        "options": {},
        "promptType": "define",
        "needsFallback": true
      },
      "executeOnce": true,
      "typeVersion": 2.1,
      "alwaysOutputData": true
    },
    {
      "id": "730c73a2-3058-4149-ae56-7636c4c18612",
      "name": "Google Gemini Chat Model2",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        -2272,
        1664
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "9d73b218-17ea-4d59-8bfd-ce03c7ceed56",
      "name": "Google Gemini Chat Model3",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        -1232,
        976
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "022c035e-793d-44ec-a797-c928fcef0cc4",
      "name": "Simple Memory1",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        -976,
        976
      ],
      "parameters": {
        "sessionKey": "={{ $('Get Existing Labels1').first().json.id }}",
        "sessionIdType": "customKey"
      },
      "typeVersion": 1.3
    },
    {
      "id": "b466f7b4-a0e5-4d08-870d-bc33d4760667",
      "name": "OpenRouter Chat Model3",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "position": [
        -1104,
        976
      ],
      "parameters": {
        "model": "deepseek/deepseek-chat-v3-0324:free",
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "4d33199c-a9d7-47aa-adc0-8920d23fe982",
      "name": "Get a message1",
      "type": "n8n-nodes-base.gmail",
      "position": [
        -2624,
        1440
      ],
      "parameters": {
        "simple": false,
        "options": {},
        "messageId": "={{ $json.id }}",
        "operation": "get"
      },
      "typeVersion": 2.1
    },
    {
      "id": "bde50502-712e-4761-b1ea-cc7861a825ae",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2944,
        1328
      ],
      "parameters": {
        "color": 4,
        "width": 256,
        "height": 272,
        "content": "## Trigger: New Email Received"
      },
      "typeVersion": 1
    },
    {
      "id": "8b8451df-b8d5-40ec-875b-52de0ab37460",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2672,
        1248
      ],
      "parameters": {
        "color": 4,
        "width": 256,
        "height": 352,
        "content": "## Fetch Full Email Content\n*It takes the ID of the new email from the trigger and fetches the complete message body, subject, sender, and headers.*"
      },
      "typeVersion": 1
    },
    {
      "id": "5d08f0c3-d647-4c51-8c9f-0a36e0132d39",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2384,
        1248
      ],
      "parameters": {
        "color": 4,
        "width": 960,
        "height": 752,
        "content": "## AI-Powered Categorization\n*This AI agent analyzes the full email content. Based on a detailed prompt that includes classification rules (e.g., if the sender is GitHub, classify as \"Dev Tools\"), it determines the most appropriate category and outputs the corresponding Label ID.*"
      },
      "typeVersion": 1
    },
    {
      "id": "faceff2c-c767-411e-b7ad-389bf59c1d0a",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1408,
        1248
      ],
      "parameters": {
        "color": 4,
        "width": 1392,
        "height": 560,
        "content": "## Label Management and Application\n*This sequence ensures the email gets the correct label.\nIt first attempts to create the Gmail label suggested by the AI. The node is set to continue even if the label already exists.\nIt then fetches a list of all your current Gmail labels.\nA Filter node finds the exact ID of the label that matches the AI's suggestion.\nFinally, it applies this label to the email thread, neatly organizing it in your inbox.*"
      },
      "typeVersion": 1
    },
    {
      "id": "ed965f5c-7f2d-44a1-a893-96c2de3a6616",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1568,
        592
      ],
      "parameters": {
        "color": 4,
        "width": 1568,
        "height": 576,
        "content": "## Urgency Analysis and Summarization\n\n*Concurrently, a second AI agent analyzes the email to determine its urgency (classifying it as \"urgent\" or \"normal\") and generates a two-sentence summary.\nIf an email is deemed urgent, the workflow immediately sends an alert containing the email summary to your specified Telegram chat and WhatsApp number.*"
      },
      "typeVersion": 1
    }
  ],
  "connections": {
    "If1": {
      "main": [
        [
          {
            "node": "Send a text message1",
            "type": "main",
            "index": 0
          },
          {
            "node": "Send message1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Code1": {
      "main": [
        [
          {
            "node": "If1",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Wait1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait1": {
      "main": [
        [
          {
            "node": "AI Agent1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter1": {
      "main": [
        [
          {
            "node": "Add label to thread1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent1": {
      "main": [
        [
          {
            "node": "Code1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent3": {
      "main": [
        [
          {
            "node": "Loop Over Items1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Sent2": {
      "ai_tool": [
        [
          {
            "node": "AI Agent3",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Check Sent3": {
      "ai_tool": [
        [
          {
            "node": "AI Agent3",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Get a message1": {
      "main": [
        [
          {
            "node": "AI Agent3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail Trigger1": {
      "main": [
        [
          {
            "node": "Get a message1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simple Memory1": {
      "ai_memory": [
        [
          {
            "node": "AI Agent1",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items1": {
      "main": [
        [
          {
            "node": "AI Agent1",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Create Label if Doesn't exist1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Structured Output Parser1",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Add label to thread1": {
      "main": [
        [
          {
            "node": "Loop Over Items1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Existing Labels1": {
      "main": [
        [
          {
            "node": "Filter1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter Chat Model2": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent3",
            "type": "ai_languageModel",
            "index": 1
          }
        ]
      ]
    },
    "OpenRouter Chat Model3": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent1",
            "type": "ai_languageModel",
            "index": 1
          }
        ]
      ]
    },
    "Google Gemini Chat Model2": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent3",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Google Gemini Chat Model3": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent1",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser1": {
      "ai_outputParser": [
        [
          {
            "node": "AI Agent3",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Create Label if Doesn't exist1": {
      "main": [
        [
          {
            "node": "Get Existing Labels1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}