{
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "name": "Qualify AI chat to Google Sheets and Slack with self-optimization",
  "nodes": [
    {
      "id": "46451b10-ea57-483d-a07f-82ce9d7ce043",
      "name": "Chat Logic Brain",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        -672,
        400
      ],
      "parameters": {
        "options": {},
        "modelName": "models/gemini-1.5-flash"
      },
      "typeVersion": 1
    },
    {
      "id": "3ae26212-48b8-436a-9be0-3b697d9c461c",
      "name": "Scoring Logic",
      "type": "n8n-nodes-base.code",
      "position": [
        -688,
        128
      ],
      "parameters": {
        "jsCode": "// Get the output directly from the \"Extract Lead State\" node\nconst data = $node[\"Extract Lead State\"].json;\n\nreturn {\n  ...data,\n  score: data.budget > 10000 ? 80 : 30,\n  isHot: data.budget > 10000\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "75180d9a-bb6c-4621-8edd-30e1a1e02b05",
      "name": "AI Council: Strategist",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "position": [
        -528,
        128
      ],
      "parameters": {
        "text": "=As an AI Strategist, suggest 3 growth tactics for a company in the {{$json.industry}} industry with a budget of ${{$json.budget}}. Keep it concise.",
        "promptType": "define",
        "hasOutputParser": true
      },
      "typeVersion": 1.4
    },
    {
      "id": "f7ff1666-0bca-4eb1-90a8-1f9cbc7529aa",
      "name": "Is High ROI?",
      "type": "n8n-nodes-base.if",
      "position": [
        -256,
        128
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 1,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "7b8c9d0e",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{ $('Scoring Logic').item.json.isHot }}",
              "rightValue": "true"
            }
          ]
        }
      },
      "typeVersion": 2
    },
    {
      "id": "141964e7-9f38-48c1-932f-d7985b764d3c",
      "name": "Log Lead to Spreadsheet",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        0,
        160
      ],
      "parameters": {
        "columns": {
          "value": {
            "Lead": "=Name: {{ $('Extract Lead State').item.json.name }}\\nIndustry: {{ $('Extract Lead State').item.json.industry }}\\nBudget: {{ $('Extract Lead State').item.json.budget }}",
            "Suggestion": "={{ $json.text }}"
          },
          "mappingMode": "defineBelow"
        },
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "[YOUR_GOOGLE_SHEET_ID]"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "2c06119e-9188-43f8-bbec-25d85a3bdd6e",
      "name": "Chat Session Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        -1328,
        288
      ],
      "parameters": {
        "contextWindowLength": 4
      },
      "typeVersion": 1.3
    },
    {
      "id": "785ae002-59ec-4e23-b852-8e1f60d2cf42",
      "name": "Log Strategy to Backup",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        0,
        368
      ],
      "parameters": {
        "columns": {
          "value": {
            "Lead": "=Name: {{ $('Extract Lead State').item.json.name }}\\nIndustry: {{ $('Extract Lead State').item.json.industry }}\\nBudget: {{ $('Extract Lead State').item.json.budget }}",
            "Suggestion": "={{ $json.text }}"
          },
          "mappingMode": "defineBelow"
        },
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Sheet2"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "[YOUR_GOOGLE_SHEET_ID]"
        }
      },
      "typeVersion": 4.5
    },
    {
      "id": "216335ad-32bc-4d6c-8af1-a78e85b20dca",
      "name": "Notify Sales of Hot Lead",
      "type": "n8n-nodes-base.slack",
      "position": [
        0,
        0
      ],
      "parameters": {
        "text": "=New High-Priority Lead: {{ $('Extract Lead State').item.json.name }}. Council Status: {{ $('AI Council: Strategist').item.json.text }}.",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "[YOUR_SLACK_CHANNEL_ID]"
        },
        "otherOptions": {
          "mrkdwn": false
        }
      },
      "typeVersion": 2.4
    },
    {
      "id": "82b7adfe-03f2-4017-9f20-8d4685b5af64",
      "name": "Main Instructions",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -2080,
        -96
      ],
      "parameters": {
        "width": 528,
        "height": 672,
        "content": "How it works\nThe template operates in two distinct phases:\n\nThe Lead Engine: A user interacts with a chat bubble. A Gemini-powered agent conversationally qualifies the lead (Name, Industry, Budget). A custom JavaScript node ensures data integrity before an \"AI Council\" node generates three industry-specific growth tactics. High-value leads are then routed to Slack and logged in Google Sheets.\nThe Self-Optimization Loop: A scheduled trigger audits lead data in Google Sheets daily. It uses Gemini to identify friction points and sends a \"System Audit\" report to Slack, suggesting prompt improvements to increase conversion rates.\n\nHow to set up\nCredentials: Connect your Google Gemini (API Key), Google Sheets (OAuth2), and Slack (OAuth2) accounts.\nGoogle Sheets: Create a spreadsheet with headers: Lead, Suggestion, and Status. Copy the Spreadsheet ID into the Google Sheets nodes.\nSlack: Invite your n8n bot to a specific channel (e.g., /invite @n8n) and select that channel in the Slack nodes.\nMemory: Ensure the Window Buffer Memory node is connected to the AI Agent to maintain conversation state.\n\nRequirements\nGoogle AI (Gemini) API Key.\nGoogle Sheets for data logging.\nSlack for real-time notifications.\nn8n version 1.0+ (supporting AI Agent nodes).\n\nHow to customize\nScoring Logic: Adjust the Scoring Logic code node to change what constitutes a \"Hot\" lead (currently set to a budget > $10,000).\nAI Strategist: Modify the prompt in the AI Council: Strategist node to provide different types of value (e.g., free audits instead of growth tactics)."
      },
      "typeVersion": 1
    },
    {
      "id": "929cecbd-c42c-4cdf-b9ee-5466a6f9ec50",
      "name": "Lead Chat Trigger",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        -1488,
        128
      ],
      "parameters": {
        "public": true,
        "options": {}
      },
      "typeVersion": 1.4
    },
    {
      "id": "0a97b388-c0b2-472a-98d1-da8d3e98981e",
      "name": "Qualify Lead Conversationally",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -1312,
        128
      ],
      "parameters": {
        "options": {
          "systemMessage": "You are a Lead Qualifier. Your goal is to find the user's Name, Industry, and Budget. Instructions: Look at the chat history. If you already know a piece of info, do not ask for it again. CRITICAL: Every time you reply, you must include a hidden JSON block at the end of your message. Format: { 'name': '...', 'industry': '...', 'budget': ... }"
        }
      },
      "typeVersion": 1.7
    },
    {
      "id": "4cb94e2b-cad6-449a-a10f-059771d075b7",
      "name": "Extract Lead State",
      "type": "n8n-nodes-base.code",
      "position": [
        -1008,
        128
      ],
      "parameters": {
        "jsCode": "// Extract JSON data from AI output\\nconst rawOutput = $node[\"Qualify Lead Conversationally\"].json.output || \"\";\\nlet state = { name: \"unknown\", industry: \"unknown\", budget: 0, isReady: false };\\ntry {\\n  const jsonMatch = rawOutput.match(/\\{[\\s\\S]*\\}/);\\n  if (jsonMatch) {\\n    let jsonString = jsonMatch[0].replace(/'/g, '\"');\\n    const newData = JSON.parse(jsonString);\\n    state.name = newData.name || \"unknown\";\\n    state.industry = newData.industry || \"unknown\";\\n    state.budget = Number(newData.budget) || 0;\\n  }\\n} catch (e) {}\\nif (state.name !== \"unknown\" && state.industry !== \"unknown\" && state.budget > 0) state.isReady = true;\\nreturn state;"
      },
      "typeVersion": 2
    },
    {
      "id": "ff010bc9-0899-4260-a75e-ba71c06ecfed",
      "name": "Lead Ingestion Group",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1536,
        48
      ],
      "parameters": {
        "color": 6,
        "width": 496,
        "height": 400,
        "content": "This section captures user input via chat and maintains a stateful conversation to qualify leads."
      }
    },
    {
      "id": "988a2dae-3e9a-4334-a72c-153464ca9ec0",
      "name": "Data Processing Group",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1024,
        48
      ],
      "parameters": {
        "color": 4,
        "width": 448,
        "height": 272,
        "content": "Extracts JSON data from the chat and validates that all required fields are present before scoring."
      }
    },
    {
      "id": "a6919265-c647-435b-ab8f-3207f6af7c5d",
      "name": "Audit Analyst Brain",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        -1040,
        928
      ],
      "parameters": {
        "options": {},
        "modelName": "models/gemini-1.5-flash"
      },
      "typeVersion": 1
    },
    {
      "id": "d1316dcb-fb51-4fc1-a014-acf704224e2a",
      "name": "Audit Lead Performance",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        -1024,
        720
      ],
      "parameters": {
        "text": "=You are an AI System Auditor. Review the following lead data: {{ $json.text }}. Identify patterns and propose improvements.",
        "options": {
          "systemMessage": "You are a helpful assistant"
        },
        "promptType": "define"
      },
      "typeVersion": 3.1
    },
    {
      "id": "3b9aad85-8753-4ff2-aff1-1bfd45c3bcad",
      "name": "Send Optimization Report",
      "type": "n8n-nodes-base.slack",
      "position": [
        -704,
        720
      ],
      "parameters": {
        "text": "=Optimization Report: Based on performance, update prompt to: {{ $json.output }}",
        "select": "channel",
        "channelId": {
          "__rl": true,
          "mode": "id",
          "value": "[YOUR_SLACK_CHANNEL_ID]"
        },
        "otherOptions": {}
      },
      "typeVersion": 2.4
    },
    {
      "id": "19e2340e-242e-4e7d-a4ac-0d3f7d095d69",
      "name": "Self-Optimization Group",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1456,
        656
      ],
      "parameters": {
        "color": 3,
        "width": 944,
        "height": 416,
        "content": "Feedback Loop: An autonomous loop that audits daily lead performance to suggest prompt improvements."
      }
    },
    {
      "id": "9147a451-5e38-44c9-865b-009c4c8b9698",
      "name": "Output Group",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -96,
        -96
      ],
      "parameters": {
        "color": 7,
        "width": 272,
        "height": 640,
        "content": "Logs lead data to Google Sheets and alerts the team via Slack."
      }
    },
    {
      "id": "b96a8cb7-74da-4320-a4f3-a33c41450052",
      "name": "Check if Lead is Qualified",
      "type": "n8n-nodes-base.filter",
      "position": [
        -832,
        128
      ],
      "parameters": {
        "conditions": {
          "options": {
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "99ec78c9",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{ $json.isReady }}"
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "bd7e8fee-2b41-4704-81c2-42ad3560dc89",
      "name": "Daily Performance Audit Trigger",
      "type": "n8n-nodes-base.scheduleTrigger",
      "position": [
        -1408,
        720
      ],
      "parameters": {
        "rule": {
          "interval": [
            {}
          ]
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "c156f503-ef8b-4487-8a5d-21254ce1b904",
      "name": "Send Response to Chat Interface",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        -1184,
        288
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1.5
    },
    {
      "id": "7ffb5f5b-ff3b-42f7-8e40-9420da81e7fa",
      "name": "Fetch Historical Lead Data",
      "type": "n8n-nodes-base.googleSheets",
      "position": [
        -1232,
        720
      ],
      "parameters": {
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "Sheet1"
        },
        "documentId": {
          "__rl": true,
          "mode": "id",
          "value": "[YOUR_GOOGLE_SHEET_ID]"
        }
      },
      "typeVersion": 4.7
    },
    {
      "id": "97b8118a-2057-4d39-b6ef-91c5e079d45f",
      "name": "AI Council Group",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -560,
        48
      ],
      "parameters": {
        "color": 5,
        "width": 448,
        "height": 240,
        "content": "Uses Gemini to generate industry-specific growth tactics for qualified leads."
      }
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "connections": {
    "Is High ROI?": {
      "main": [
        [
          {
            "node": "Log Lead to Spreadsheet",
            "type": "main",
            "index": 0
          },
          {
            "node": "Notify Sales of Hot Lead",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Log Strategy to Backup",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Scoring Logic": {
      "main": [
        [
          {
            "node": "AI Council: Strategist",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Chat Logic Brain": {
      "ai_languageModel": [
        [
          {
            "node": "Qualify Lead Conversationally",
            "type": "ai_languageModel",
            "index": 0
          },
          {
            "node": "AI Council: Strategist",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Lead Chat Trigger": {
      "main": [
        [
          {
            "node": "Qualify Lead Conversationally",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Lead State": {
      "main": [
        [
          {
            "node": "Check if Lead is Qualified",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Audit Analyst Brain": {
      "ai_languageModel": [
        [
          {
            "node": "Audit Lead Performance",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Chat Session Memory": {
      "ai_memory": [
        [
          {
            "node": "Qualify Lead Conversationally",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "AI Council: Strategist": {
      "main": [
        [
          {
            "node": "Is High ROI?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Audit Lead Performance": {
      "main": [
        [
          {
            "node": "Send Optimization Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check if Lead is Qualified": {
      "main": [
        [
          {
            "node": "Scoring Logic",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Historical Lead Data": {
      "main": [
        [
          {
            "node": "Audit Lead Performance",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Qualify Lead Conversationally": {
      "main": [
        [
          {
            "node": "Extract Lead State",
            "type": "main",
            "index": 0
          },
          {
            "node": "Send Response to Chat Interface",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Daily Performance Audit Trigger": {
      "main": [
        [
          {
            "node": "Fetch Historical Lead Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}