{
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "7959f62a-c7bd-4c30-ba81-73fa5f120d48",
      "name": "Gmail Trigger",
      "type": "n8n-nodes-base.gmailTrigger",
      "position": [
        500,
        -140
      ],
      "parameters": {
        "filters": {
          "labelIds": [
            "INBOX"
          ],
          "includeSpamTrash": false
        },
        "pollTimes": {
          "item": [
            {
              "mode": "=everyMinute"
            }
          ]
        }
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "cba3842f-57f3-43a5-a436-868c81712967",
      "name": "Text Classifier",
      "type": "@n8n/n8n-nodes-langchain.textClassifier",
      "position": [
        780,
        -140
      ],
      "parameters": {
        "options": {},
        "inputText": "=From: {{ $json.From }}\nSubject: {{ $json.Subject }}\nEmail body: {{ $json.snippet }}",
        "categories": {
          "categories": [
            {
              "category": "Sales/Leads/Inquiries",
              "description": "Any email about new inquiries, booking calls, interested leads. This is for sales/inquiries/leads"
            },
            {
              "category": "Clients/Active Projects",
              "description": "Any email that's active client communication. Can be project updates, feedback, deliverables etc.\n\n"
            },
            {
              "category": "Reports/Results",
              "description": "Any email about Performance updates (ads, analytics), Campaign reviews, KPIs, dashboards"
            },
            {
              "category": "Billing/Admin",
              "description": "Any emails about Invoices, contracts, payment confirmations, Tool subscriptions, platform updates etc."
            },
            {
              "category": "Other/Low Priority",
              "description": "Any emails that don't fit into any of the other categories. Can be Newsletters, cold emails, updates from tools etc. Anything that\u2019s not urgent or important"
            }
          ]
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "28dbe8df-9fa6-47fa-9891-48a88d703021",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        780,
        40
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "gpt-4.1-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "67aa2083-c8ef-4405-893e-53247b3ab6a2",
      "name": "Sales / Leads",
      "type": "n8n-nodes-base.gmail",
      "position": [
        1220,
        -500
      ],
      "parameters": {
        "labelIds": [
          "Label_8604649380419238342",
          "IMPORTANT"
        ],
        "messageId": "={{ $('Gmail Trigger').item.json.id }}",
        "operation": "addLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "7b27e516-9515-45fe-aa4c-709c3f761b47",
      "name": "Client Comm",
      "type": "n8n-nodes-base.gmail",
      "position": [
        1220,
        -320
      ],
      "parameters": {
        "labelIds": [
          "Label_3864215407576145230",
          "IMPORTANT"
        ],
        "messageId": "={{ $('Gmail Trigger').item.json.id }}",
        "operation": "addLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "7d7f705b-e6ab-4b2a-aafd-0cd9ad4225fb",
      "name": "Reports / Results",
      "type": "n8n-nodes-base.gmail",
      "position": [
        1220,
        -140
      ],
      "parameters": {
        "labelIds": [
          "Label_6284269275653839225"
        ],
        "messageId": "={{ $('Gmail Trigger').item.json.id }}",
        "operation": "addLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "6a8339bb-3c7d-49ab-a03d-380d705d884b",
      "name": "Billing / Admin",
      "type": "n8n-nodes-base.gmail",
      "position": [
        1220,
        40
      ],
      "parameters": {
        "labelIds": [
          "Label_295304589470276513"
        ],
        "messageId": "={{ $('Gmail Trigger').item.json.id }}",
        "operation": "addLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "efb203a1-f643-40c2-81d0-da388d9c34bd",
      "name": "Other",
      "type": "n8n-nodes-base.gmail",
      "position": [
        1220,
        220
      ],
      "parameters": {
        "labelIds": [
          "Label_8092655313303559301"
        ],
        "messageId": "={{ $('Gmail Trigger').item.json.id }}",
        "operation": "addLabels"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "30468c6d-1b64-4953-a207-3f358b9c4910",
      "name": "Mark as Read3",
      "type": "n8n-nodes-base.gmail",
      "position": [
        1440,
        220
      ],
      "parameters": {
        "messageId": "={{ $json.id }}",
        "operation": "markAsRead"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "9c319421-1609-4d9b-875e-567ebc64f03d",
      "name": "Structured Output Parser2",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        3020,
        -240
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"emailBody\": {\n      \"type\": \"string\",\n      \"description\": \"The HTML-formatted body content of the email reply to be sent to the prospect. Use <p>, <br>, and <a> tags for formatting. (If escalate is true, this is not required.)\"\n    },\n    \"reason\": {\n      \"type\": \"string\",\n      \"description\": \"Short explanation for why this email response was generated. E.g. what the user asked for, what info was found, and why this response was appropriate.\"\n    },\n    \"escalate\": {\n      \"type\": \"boolean\",\n      \"description\": \"True if you're unsure or can't confidently answer the question using available knowledge. False if you\u2019re confident in your response and can proceed without human help.\"\n    },\n    \"knowledgeDatabase\": {\n      \"type\": \"string\",\n      \"description\": \"A summary of the facts retrieved from the Knowledge Database that were used to answer the email.\"\n    }\n  },\n  \"required\": [\n    \"emailBody\",\n    \"reason\",\n    \"escalate\"\n  ]\n}\n"
      },
      "typeVersion": 1.2
    },
    {
      "id": "9c150470-5d5a-4228-adc6-384ebce2c514",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2480,
        -480
      ],
      "parameters": {
        "color": 5,
        "width": 1120,
        "height": 940,
        "content": "# Check Knowledge Base + Draft Email"
      },
      "typeVersion": 1
    },
    {
      "id": "7a1cdf33-7419-42cf-b8eb-05a29bf5512b",
      "name": "get_events",
      "type": "n8n-nodes-base.googleCalendarTool",
      "position": [
        2820,
        -740
      ],
      "parameters": {
        "options": {},
        "timeMax": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Before', `the day after the date the user requested`, 'string') }}",
        "timeMin": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('After', `the day before the date the user requested`, 'string') }}",
        "calendar": {
          "__rl": true,
          "mode": "list",
          "value": "user@example.com",
          "cachedResultName": "user@example.com"
        },
        "operation": "getAll"
      },
      "credentials": {
        "googleCalendarOAuth2Api": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "90fbe187-df56-45a5-b0ee-6fb68b1e0fba",
      "name": "Structured Output Parser",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        3060,
        -860
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"emailBody\": {\n      \"type\": \"string\",\n      \"description\": \"The HTML-formatted body content of the email to be sent. Use <p>, <br>, and <a> tags for proper formatting.\"\n    },\n    \"eventName\": {\n      \"type\": \"string\",\n      \"description\": \"The name of the event. (If just sending availabilities, you can leave this empty.)\"\n    },\n    \"startTime\": {\n      \"type\": \"string\",\n      \"description\": \"The start time of the event, in ISO 8601 format. (If just sending availabilities, you can leave this empty.)\"\n    },\n    \"endTime\": {\n      \"type\": \"string\",\n      \"description\": \"The end time of the event, in ISO 8601 format. (If just sending availabilities, you can leave this empty.)\"\n    },\n    \"bookCall\": {\n      \"type\": \"boolean\",\n      \"description\": \"True if booking a call for a specific time slot. False if sending availabilities.\"\n    },\n    \"calendarAvailabilities\": {\n      \"type\": \"string\",\n      \"description\": \"Detailed calendar availabilities for the time as specified by manager. Optional.\"\n    }\n  },\n  \"required\": [\n    \"emailBody\",\n    \"eventName\",\n    \"startTime\",\n    \"endTime\",\n    \"bookCall\"\n  ]\n}\n"
      },
      "typeVersion": 1.2
    },
    {
      "id": "c634a163-41f4-4dba-81d9-d7b56e1252ca",
      "name": "Calendar Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        2680,
        -1060
      ],
      "parameters": {
        "text": "=Here's the email:\n{{ $('Gmail Trigger').item.json.snippet }}\n\nHere's the full thread for context:\n{{ $('Get Thread').item.json.messages.map((msg, index) => `Message ${index + 1}: ${msg.fullBody || msg.snippet}`).join('\\n\\n---\\n\\n') }}\n\n",
        "options": {
          "systemMessage": "=You are a sales agent at Marketing Ladder (a Marketing Agency). Your job is to handle calendar enquiries via email and reply with either available time slots or booking confirmations. Keep responses short, friendly, and conversational.\n\nTools\nget_events: Use this to check availability for a specific day or time\n\nthink_tool: Use this to decide next steps after getting calendar data\n\nResponse Logic\nIf the email includes a specific date only (no time):\nUse get_events to check availability that day\n\nIf there are open 30-minute slots, casually mention a time range (e.g., \u201cI should be free 9\u201311AM\u201d) instead of exact times\n\nInclude your calendar link in the messages\n\nExample phrasing:\n\n\u201cHow about we set something up for tomorrow? I should be free 9\u201311AM (Chicago Time).\u201d\n\nIf the email includes both a date and time:\nUse get_events to check if that time is available\n\nIf available:\n\nAssume the meeting is 30 minutes\n\nConfirm the time in a casual tone (e.g., \u201cYup, I should be good then\u201d)\n\nCreate the calendar event\n\nIf unavailable:\n\nSuggest 2 alternative slots in a natural way (e.g., \u201cI'm tied up then \u2014 how about 9:30 or 10:15 instead?\u201d)\n\nOffer your calendar link as well\n\nExtra Rules:\n-If they say \u201cMonday\u201d (or any weekday), treat it as the next upcoming one\n\n-Never mention what\u2019s booked \u2014 just say \u201cI'm already tied up then\u201d or \u201cI\u2019m booked at that time\u201d\n\n-Default meeting length is 30 minutes unless stated otherwise\n\n-Always mention the time zone: Chicago Time (CST/CDT)\n\n-Sign off every email as: Abdul\n\n-If they ask for your calendar link, always give: https://cal.com/builtbyabdul/freeconsultation\n\nToday is: {{ $now.format('EEEE') }}, {{ $now.format('yyyy-MM-dd') }}\n\nExample response:\n\n\"\"<p>Thanks for reaching out and your interest in our LinkedIn Growth services!</p>\n\n<p>I'm free for a call tomorrow (Sunday) between 11\u201311:45AM Chicago Time (CDT). Let me know if that works for you, or feel free to grab a slot that fits your schedule using my calendar here:<br>\n<a href=\"https://cal.com/builtbyabdul/freeconsultation\">https://cal.com/builtbyabdul/freeconsultation</a></p>\n\n<p>Looking forward to chatting!</p>\n\n<p>Best,<br>\nAbdul</p>\"\"\n"
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 1.9
    },
    {
      "id": "4ae6b1e3-fc83-4bde-a9bc-49a18cf46b32",
      "name": "think_tool",
      "type": "@n8n/n8n-nodes-langchain.toolThink",
      "position": [
        2940,
        -800
      ],
      "parameters": {},
      "typeVersion": 1
    },
    {
      "id": "fc68e100-043b-4fb7-8388-1db3e5c07a9b",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2480,
        -1180
      ],
      "parameters": {
        "color": 5,
        "width": 1120,
        "height": 640,
        "content": "# Check Calendar Availability + Draft Email"
      },
      "typeVersion": 1
    },
    {
      "id": "fd8404b2-522e-480c-b882-8fc94239e88f",
      "name": "OpenAI Chat Model5",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        2540,
        -840
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1",
          "cachedResultName": "gpt-4.1"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "0c5ec3ff-1ad1-4d26-9340-f4ed1ff0846a",
      "name": "OpenAI Chat Model7",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1840,
        -280
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "gpt-4.1-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "cf89e12e-6778-4c2f-8be1-6465a3afa9d7",
      "name": "Calendar or Email",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "position": [
        1840,
        -500
      ],
      "parameters": {
        "text": "=New email just came in. \n\nHere's the email: \n\n{{ $('Gmail Trigger').item.json.id }}\n\nHere's the thread for context:\n\n{{ $json.messages.map((msg, index) => `Message ${index + 1}: ${msg.fullBody || msg.snippet}`).join('\\n\\n---\\n\\n') }}\n\n\nClassify it. ",
        "messages": {
          "messageValues": [
            {
              "message": "=You're a sales inbox manager. \nThe emails coming in from clients are sales-related, either leads/inquiries reaching out to book a call or to get more info. \n\nYour job is to classify each email as a calendar or information email. \n\nCalendar emails are those where the prospect suggests being booked in for a call. \n\nInformation emails are those which require a reply from the sales team to progress further. This could be the prospect asking for information or making an enquiry. "
            }
          ]
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 1.6
    },
    {
      "id": "db6386bf-32a6-4e61-ab47-9710011f20c7",
      "name": "Gmail",
      "type": "n8n-nodes-base.gmail",
      "position": [
        1440,
        -500
      ],
      "parameters": {
        "simple": false,
        "options": {},
        "resource": "thread",
        "threadId": "={{ $json.threadId }}",
        "operation": "get"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "0e016ea3-bfa9-4f2b-a096-64a34e936e82",
      "name": "Get Thread",
      "type": "n8n-nodes-base.code",
      "position": [
        1600,
        -500
      ],
      "parameters": {
        "jsCode": "// Get the Gmail thread data from the previous node\nconst threadData = $input.all();\n\n// Array to store all messages\nconst allMessages = [];\n\n// Function to extract text from message payload\nfunction extractMessageBody(payload) {\n  let body = '';\n  \n  if (payload.body && payload.body.data) {\n    // Single part message\n    body = Buffer.from(payload.body.data, 'base64').toString('utf-8');\n  } else if (payload.parts) {\n    // Multi-part message\n    for (const part of payload.parts) {\n      if (part.mimeType === 'text/plain' && part.body && part.body.data) {\n        body += Buffer.from(part.body.data, 'base64').toString('utf-8');\n      } else if (part.mimeType === 'text/html' && part.body && part.body.data && !body) {\n        // Use HTML if no plain text found\n        body = Buffer.from(part.body.data, 'base64').toString('utf-8');\n      } else if (part.parts) {\n        // Nested parts (recursive)\n        body += extractMessageBody(part);\n      }\n    }\n  }\n  \n  return body.trim();\n}\n\n// Loop through each item from the Gmail node\nfor (const item of threadData) {\n  // Check if messages exist in the item\n  if (item.json.messages && Array.isArray(item.json.messages)) {\n    // Loop through each message in the thread\n    for (let i = 0; i < item.json.messages.length; i++) {\n      const message = item.json.messages[i];\n      \n      // Extract the full message body\n      const fullBody = message.payload ? extractMessageBody(message.payload) : message.snippet || '';\n      \n      if (fullBody) {\n        allMessages.push({\n          messageIndex: i,\n          threadId: item.json.id || 'unknown',\n          snippet: message.snippet || '',\n          fullBody: fullBody,\n          messageId: message.id || 'unknown',\n          subject: message.payload?.headers?.find(h => h.name === 'Subject')?.value || '',\n          from: message.payload?.headers?.find(h => h.name === 'From')?.value || '',\n          date: message.payload?.headers?.find(h => h.name === 'Date')?.value || ''\n        });\n      }\n    }\n  }\n}\n\n// Return all messages as a single item with an array\nreturn [{\n  json: {\n    threadId: threadData[0]?.json?.id || 'unknown',\n    totalMessages: allMessages.length,\n    messages: allMessages\n  }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "49dc5b26-b1e0-4969-82d2-eb0c91a631fe",
      "name": "Structured Output Parser6",
      "type": "@n8n/n8n-nodes-langchain.outputParserStructured",
      "position": [
        2020,
        -280
      ],
      "parameters": {
        "schemaType": "manual",
        "inputSchema": "{\n  \"type\": \"object\",\n  \"properties\": {\n    \"calendar\": {\n      \"type\": \"boolean\",\n      \"description\": \"True if Calendar Email and False if Information Email\"\n    }\n  },\n  \"required\": [\n    \"newProspectEmail\"\n  ]\n}"
      },
      "typeVersion": 1.2
    },
    {
      "id": "85623967-3d14-49fe-ba1a-f0cd9b248d21",
      "name": "Switch",
      "type": "n8n-nodes-base.switch",
      "position": [
        2160,
        -500
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "Calendar",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "925bd4a7-f8a4-4b93-8fb9-47f6a238c89d",
                    "operator": {
                      "type": "boolean",
                      "operation": "true",
                      "singleValue": true
                    },
                    "leftValue": "={{ $json.output.calendar }}",
                    "rightValue": "Calendar"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Email",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "a2580899-2579-496c-9f96-ea14fb997c4f",
                    "operator": {
                      "type": "boolean",
                      "operation": "false",
                      "singleValue": true
                    },
                    "leftValue": "={{ $json.output.calendar }}",
                    "rightValue": "Email"
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.2
    },
    {
      "id": "1a05e73f-25d4-4689-8c67-78aebf86b2de",
      "name": "Gmail2",
      "type": "n8n-nodes-base.gmail",
      "position": [
        3180,
        -1060
      ],
      "parameters": {
        "message": "={{ $json.output.emailBody }}",
        "options": {
          "replyTo": "={{ $('Gmail Trigger').item.json.From.extractEmail() }}",
          "threadId": "={{ $('Gmail Trigger').item.json.threadId }}"
        },
        "subject": "=re: {{ $('Gmail Trigger').item.json.Subject }}",
        "resource": "draft",
        "emailType": "html"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "b7176cee-5122-4c95-bf73-6aad17a2f643",
      "name": "Window Buffer Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        2680,
        -140
      ],
      "parameters": {
        "sessionKey": "=123456",
        "sessionIdType": "customKey"
      },
      "typeVersion": 1.3
    },
    {
      "id": "2053b536-f8c1-4ab1-85ea-b2ec3532c401",
      "name": "OpenAI Chat Model1",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        3020,
        80
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "gpt-4.1-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "cec9545a-4f17-455b-be75-a894563424f0",
      "name": "Supabase Vector Store2",
      "type": "@n8n/n8n-nodes-langchain.vectorStoreSupabase",
      "position": [
        2660,
        100
      ],
      "parameters": {
        "options": {
          "queryName": "match_documents"
        },
        "tableName": {
          "__rl": true,
          "mode": "list",
          "value": "documents",
          "cachedResultName": "documents"
        }
      },
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "8908e09d-a7aa-48d8-a6fe-b85eec59233b",
      "name": "Embeddings OpenAI2",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "position": [
        2680,
        280
      ],
      "parameters": {
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "45bf5a88-9986-45dd-a6f5-3d1aa58aa9ee",
      "name": "OpenAI Chat Model2",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        2500,
        -180
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini",
          "cachedResultName": "gpt-4.1-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "07f2df75-ce13-425f-9fec-e8bf079975a0",
      "name": "Knowledge Database",
      "type": "@n8n/n8n-nodes-langchain.toolVectorStore",
      "position": [
        2800,
        -80
      ],
      "parameters": {
        "name": "KnowledgeDatabase",
        "topK": "=5",
        "description": "A list of frequently asked questions and answers and services we provide."
      },
      "typeVersion": 1
    },
    {
      "id": "a33d5b62-974b-492f-90da-647d657d51ba",
      "name": "Gmail3",
      "type": "n8n-nodes-base.gmail",
      "position": [
        3260,
        -260
      ],
      "parameters": {
        "message": "={{ $json.output.emailBody }}",
        "options": {
          "replyTo": "={{ $('Gmail Trigger').item.json.From.extractEmail() }}",
          "threadId": "={{ $('Gmail Trigger').item.json.threadId }}"
        },
        "subject": "=re: {{ $('Gmail Trigger').item.json.Subject }}",
        "resource": "draft",
        "emailType": "html"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.1
    },
    {
      "id": "acdac639-c864-46b3-8108-4fbbf917b738",
      "name": "Telegram",
      "type": "n8n-nodes-base.telegram",
      "position": [
        3460,
        -260
      ],
      "parameters": {
        "text": "=\ud83d\udce5 New lead: {{ $('Gmail Trigger').item.json.From.split('<')[0].trim() }} \nThey were asking a question. I searched the knowledge database and drafted a reply for you. \nCheck your email!",
        "chatId": "123456789",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "f5cc67cf-5494-4779-ba92-b1f38f63314c",
      "name": "Telegram2",
      "type": "n8n-nodes-base.telegram",
      "position": [
        3240,
        -440
      ],
      "parameters": {
        "text": "=\ud83d\udce5 New lead: {{ $('Gmail Trigger').item.json.From.split('<')[0].trim() }} \nThey were asking a question, I searched the knowledge database but I wasn't sure how to respond.\nCheck your email!",
        "chatId": "123456789",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "90e8a7e7-e944-4225-808e-5f7246a2d3ef",
      "name": "Inbox Bot",
      "type": "n8n-nodes-base.telegram",
      "position": [
        3380,
        -1060
      ],
      "parameters": {
        "text": "=\ud83d\udce5 New lead: {{ $('Gmail Trigger').item.json.From.split('<')[0].trim() }} \nThey want to book a call. I checked your calendar and drafted a reply for you. \nCheck your email!",
        "chatId": "123456789",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "credentials": {
        "telegramApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "623dd1d3-c4e0-4974-ae5d-c413fdc7f08a",
      "name": "Escalate?",
      "type": "n8n-nodes-base.if",
      "position": [
        3040,
        -400
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "8c816866-eec9-4c02-a7df-e37a4c1fc89f",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{ $json.output.escalate }}",
              "rightValue": "true"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "7551ab07-435c-4245-b1d8-5de3225cd7ba",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        460,
        -540
      ],
      "parameters": {
        "color": 3,
        "width": 1100,
        "height": 940,
        "content": "# Categorize incoming emails\n"
      },
      "typeVersion": 1
    },
    {
      "id": "9457d233-f70d-4b4b-9fe2-6ca2469c8e21",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1580,
        -600
      ],
      "parameters": {
        "color": 4,
        "width": 880,
        "height": 540,
        "content": "# New lead? Send to calendar/knowledge agent"
      },
      "typeVersion": 1
    },
    {
      "id": "149f284f-01ec-4910-9543-59766fc8c51e",
      "name": "Knowledge Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        2660,
        -400
      ],
      "parameters": {
        "text": "=Here's the email:\n{{ $('Gmail Trigger').item.json.snippet }}\n\nHere's the full thread for context:\n{{ $('Get Thread').item.json.messages.map((msg, index) => `Message ${index + 1}: ${msg.fullBody || msg.snippet}`).join('\\n\\n---\\n\\n') }}\n",
        "options": {
          "systemMessage": "=You work in the sales team at Marketing Ladder, a Marketing Agency. Your job is to respond to outbound/inbound emails from prospects.\n\nEmails may include:\n- A reply to a cold email we sent\n- A new inquiry from a prospect\n- A general question about our services\n\nYour steps:\n1. Use the \"knowledge database\" tool (RAG database) to find accurate answers to their question.\n2. Write a clear, human reply that:\n   - Answers their question\n   - Encourages them to book a consultation **if** you see fit (include this link if relevant: https://cal.com/builtbyabdul/freeconsultation)\n\nRules:\n-Never hallucinate/make up stuff. If you don't know the answer or can't find relevant info in your knowledge database, set \"escalate\": true so a human can take over.\n-Sign off every email as Abdul.\n\nCurrent date/time in Chicago (CDT): {{ $now.weekdayLong }}, {{ $now.format('dd LLL yyyy') }} at {{ $now.format('t') }}\n\nExample email:\n\"\"Hey Abdul, I came across your LinkedIn. \nI'm very interested after I checked out your beautifully designed website.\nWhat services do you guys offer? Anything related to LinkedIn? I gotta say, mine is pretty trash\"\"\n\nExample response:\n\"<p>Hey \u2014 appreciate you checking out the site, and glad it resonated.</p>\n\n<p>Yes, we offer LinkedIn-focused services. Mainly building out high-converting profiles, content systems that attract leads, and automated outreach funnels. If your profile needs work, we can help fix both the look and the backend strategy.</p>\n\n<p>Happy to walk you through more details over a call if you want. When are you free? Feel free to check my calendar here: <br>\n<a href=\"https://cal.com/builtbyabdul/freeconsultation\">https://cal.com/builtbyabdul/freeconsultation</a></p>\n\n<p>Best,<br>Abdul</p>\"\n"
        },
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 1.9
    },
    {
      "id": "07d606ce-4624-4a30-a7c2-3b72fb2994b9",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4520,
        -1160
      ],
      "parameters": {
        "color": 5,
        "width": 860,
        "height": 840,
        "content": "## Example Draft + Telegram Notification\n![](https://i.imgur.com/ghJlqjU.png)\n\n![](https://i.imgur.com/nbIMIAZ.png)\n"
      },
      "typeVersion": 1
    },
    {
      "id": "44ccb83b-6cdd-448e-b7ca-4a42bd6bc504",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3700,
        -1160
      ],
      "parameters": {
        "color": 3,
        "width": 800,
        "height": 360,
        "content": "## Example Customer Email\n![](https://i.imgur.com/JaS0BsG.png)"
      },
      "typeVersion": 1
    },
    {
      "id": "ca2e568b-79af-48b6-8fff-f00daba40c84",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1820,
        60
      ],
      "parameters": {
        "color": 5,
        "width": 440,
        "height": 240,
        "content": "## Hey, I'm Abdul \ud83d\udc4b\n### I build growth systems for consultants & agencies. If you want to work together or need help automating your business, check out my website: \n### **https://www.builtbyabdul.com/**\n### Or email me at **abdul@buildabdul.com**\n### Have a lovely day ;)`"
      },
      "typeVersion": 1
    },
    {
      "id": "606d1ce2-c0e4-4512-87c6-9d26af0ca2fb",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -380,
        -760
      ],
      "parameters": {
        "width": 780,
        "height": 1380,
        "content": "# AI Inbox Manager that categorizes emails, books calls, and replies automatically\n## Overview\nTurn your cluttered inbox into a smart, autonomous assistant that categorizes emails, replies to leads, checks your calendar, and notifies you on Telegram\u2014all without lifting a finger.\n\nThis workflow is designed for a marketing agency, but can be adapted for any business. It classifies incoming emails into categories like Sales, Client Communication, Reports, Billing, and Other. If it detects a new lead or priority message, it routes the email to one of two agents:\n- The **Calendar Agent** checks your availability in Google Calendar and drafts a consultation reply  \n- The **Knowledge Agent** answers FAQs using your business knowledge base (with Supabase embeddings)  \n\nBoth agents create draft email responses and send a Telegram alert so you're always in the loop.\n\n### Who\u2019s it for\n- Founders and agency owners buried in emails  \n- Marketing teams handling lots of inbound leads  \n- Customer support managers automating Tier 1 replies  \n- Anyone who wants a cleaner, smarter inbox without hiring a VA  \n\n### How it works\n- Gmail trigger watches for incoming emails  \n- Email content is passed to an AI classifier to apply a label (Sales, Client, Billing, etc.)  \n- If the message is a new inquiry or lead, it\u2019s routed to:\n  - **Calendar Agent** \u2192 checks Google Calendar and drafts a reply with available slots  \n  - **Knowledge Agent** \u2192 searches vector DB and drafts a helpful reply from documentation  \n- Both agents create a Gmail draft response and send a Telegram notification with summary  \n\n### Example use case\n> A lead emails you asking for a discovery call.  \n>  \n> \u2705 Email is labeled \"Sales\"  \n> \u2705 AI Calendar Agent checks your Google Calendar  \n> \u2705 A reply is drafted offering free time slots  \n> \u2705 You get a Telegram ping:  \n> _\"New lead: Abdul Mir. I checked your calendar and drafted a reply. Check your email!\"_  \n\n### How to set up\n1. Connect your Gmail and set up a trigger for new messages  \n2. Train the AI classifier with example categories and emails  \n3. Connect Google Calendar API for availability checks  \n4. Upload your internal docs and sync to Supabase vector store  \n5. Connect Telegram for alerts  \n6. Customize AI prompts and escalation logic as needed  \n\n### Requirements\n- Gmail integration  \n- OpenAI or Claude API (for classification + chat agents)  \n- Google Calendar API  \n- Supabase (or Pinecone, Weaviate) for RAG vector DB  \n- Telegram bot API key\n\n### How to customize\n- Add custom labels like \u201cRecruiting,\u201d \u201cInvestor,\u201d or \u201cSupport\u201d  \n- Replace Telegram with Slack or SMS alerts  \n- Add CRM sync to update lead status  \n- Escalate complicated replies to a human via task creation  \n- Add auto-send (instead of drafts) after review or based on confidence score\n"
      },
      "typeVersion": 1
    }
  ],
  "connections": {
    "Gmail": {
      "main": [
        [
          {
            "node": "Get Thread",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Other": {
      "main": [
        [
          {
            "node": "Mark as Read3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail2": {
      "main": [
        [
          {
            "node": "Inbox Bot",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gmail3": {
      "main": [
        [
          {
            "node": "Telegram",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Calendar Agent",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Knowledge Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Escalate?": {
      "main": [
        [
          {
            "node": "Telegram2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Gmail3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Thread": {
      "main": [
        [
          {
            "node": "Calendar or Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "get_events": {
      "ai_tool": [
        [
          {
            "node": "Calendar Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "think_tool": {
      "ai_tool": [
        [
          {
            "node": "Calendar Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Gmail Trigger": {
      "main": [
        [
          {
            "node": "Text Classifier",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sales / Leads": {
      "main": [
        [
          {
            "node": "Gmail",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calendar Agent": {
      "main": [
        [
          {
            "node": "Gmail2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Knowledge Agent": {
      "main": [
        [
          {
            "node": "Escalate?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Text Classifier": {
      "main": [
        [
          {
            "node": "Sales / Leads",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Client Comm",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Reports / Results",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Billing / Admin",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Other",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Calendar or Email": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "Text Classifier",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings OpenAI2": {
      "ai_embedding": [
        [
          {
            "node": "Supabase Vector Store2",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Knowledge Database": {
      "ai_tool": [
        [
          {
            "node": "Knowledge Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model1": {
      "ai_languageModel": [
        [
          {
            "node": "Knowledge Database",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model2": {
      "ai_languageModel": [
        [
          {
            "node": "Knowledge Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model5": {
      "ai_languageModel": [
        [
          {
            "node": "Calendar Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model7": {
      "ai_languageModel": [
        [
          {
            "node": "Calendar or Email",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Supabase Vector Store2": {
      "ai_vectorStore": [
        [
          {
            "node": "Knowledge Database",
            "type": "ai_vectorStore",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser": {
      "ai_outputParser": [
        [
          {
            "node": "Calendar Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser2": {
      "ai_outputParser": [
        [
          {
            "node": "Knowledge Agent",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    },
    "Structured Output Parser6": {
      "ai_outputParser": [
        [
          {
            "node": "Calendar or Email",
            "type": "ai_outputParser",
            "index": 0
          }
        ]
      ]
    }
  }
}