{
  "name": "RAG for B2B SaaS – Google Analytics Customer Lifecycle Pipeline",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "hours",
              "hoursInterval": 24
            }
          ]
        }
      },
      "id": "c3547e15-4c4c-499a-b56f-e2333e658953",
      "name": "Schedule Trigger (Daily 02:00)",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.2,
      "position": [
        0,
        1184
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://analyticsdata.googleapis.com/v1beta/properties/={{ $vars.GA4_PROPERTY_ID }}:runReport",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleAnalyticsOAuth2Api",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {}
          ]
        },
        "options": {}
      },
      "id": "c680e836-b0a6-40e3-a392-7406ed9dd522",
      "name": "GA4 – Pull Sessions by Lifecycle Stage",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        256,
        1056
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://analyticsdata.googleapis.com/v1beta/properties/={{ $vars.GA4_PROPERTY_ID }}:runFunnelReport",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "googleAnalyticsOAuth2Api",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {}
          ]
        },
        "options": {}
      },
      "id": "86014c50-c1ec-46bb-9d4e-0130918c27b8",
      "name": "GA4 – Pull User Journey Funnels",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        256,
        1264
      ]
    },
    {
      "parameters": {
        "mode": "combine",
        "options": {}
      },
      "id": "acf8f3d3-1e0b-4cb5-a2d3-15f9fd75e479",
      "name": "Merge GA4 Data Streams",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 3,
      "position": [
        528,
        1264
      ]
    },
    {
      "parameters": {
        "jsCode": "\nconst rows = $input.all();\nconst output = [];\n\nconst stageMap = {\n  \"demo_request\":          { stage: \"pre_sales\",   priority: \"high\" },\n  \"rfp_download\":          { stage: \"pre_sales\",   priority: \"high\" },\n  \"trial_start\":           { stage: \"onboarding\",  priority: \"critical\" },\n  \"sign_up\":               { stage: \"onboarding\",  priority: \"high\" },\n  \"onboarding_complete\":   { stage: \"activation\",  priority: \"high\" },\n  \"feature_activation\":    { stage: \"activation\",  priority: \"medium\" },\n  \"support_ticket_opened\": { stage: \"support\",     priority: \"medium\" },\n  \"churn_risk_flagged\":    { stage: \"retention\",   priority: \"critical\" },\n  \"subscription_upgrade\":  { stage: \"expansion\",   priority: \"high\" },\n  \"subscription_renew\":    { stage: \"retention\",   priority: \"high\" },\n  \"expansion_event\":       { stage: \"expansion\",   priority: \"high\" }\n};\n\nfor (const row of rows) {\n  const data = row.json;\n  const dims    = data.dimensionValues || [];\n  const metrics = data.metricValues   || [];\n\n  const eventName   = dims[3]?.value || \"page_view\";\n  const lifecycle   = stageMap[eventName] || { stage: \"awareness\", priority: \"low\" };\n  const channel     = dims[0]?.value || \"unknown\";\n  const landingPage = dims[1]?.value || \"/\";\n  const pagePath    = dims[2]?.value || \"/\";\n\n  const sessions    = parseInt(metrics[0]?.value || \"0\");\n  const engaged     = parseInt(metrics[1]?.value || \"0\");\n  const bounceRate  = parseFloat(metrics[2]?.value || \"0\");\n  const avgDuration = parseFloat(metrics[3]?.value || \"0\");\n  const conversions = parseInt(metrics[4]?.value || \"0\");\n  const revenue     = parseFloat(metrics[5]?.value || \"0\");\n\n  const engagementScore = sessions > 0\n    ? Math.round(((engaged / sessions) * 0.5 + (1 - bounceRate) * 0.3 + Math.min(avgDuration / 300, 1) * 0.2) * 100)\n    : 0;\n\n  const churnRisk = (lifecycle.stage === \"retention\" && sessions < 3) ? \"high\"\n                  : (engagementScore < 30) ? \"medium\" : \"low\";\n\n  const textContent = [\n    `Lifecycle Stage: ${lifecycle.stage}`,\n    `Event: ${eventName}`,\n    `Acquisition Channel: ${channel}`,\n    `Landing Page: ${landingPage}`,\n    `Page Path: ${pagePath}`,\n    `Sessions (30d): ${sessions}`,\n    `Engaged Sessions: ${engaged}`,\n    `Bounce Rate: ${(bounceRate * 100).toFixed(1)}%`,\n    `Avg Session Duration: ${avgDuration.toFixed(0)}s`,\n    `Conversions: ${conversions}`,\n    `Revenue: $${revenue.toFixed(2)}`,\n    `Engagement Score: ${engagementScore}/100`,\n    `Churn Risk: ${churnRisk}`,\n    `Priority: ${lifecycle.priority}`,\n    `Data Window: last 30 days`\n  ].join(\"\\n\");\n\n  output.push({\n    json: {\n      id: `ga4_${eventName}_${Date.now()}_${Math.random().toString(36).substr(2,6)}`,\n      lifecycle_stage: lifecycle.stage,\n      event_name: eventName,\n      channel,\n      landing_page: landingPage,\n      page_path: pagePath,\n      sessions,\n      engaged_sessions: engaged,\n      bounce_rate: bounceRate,\n      avg_duration: avgDuration,\n      conversions,\n      revenue,\n      engagement_score: engagementScore,\n      churn_risk: churnRisk,\n      priority: lifecycle.priority,\n      text_content: textContent,\n      metadata: {\n        source: \"google_analytics_4\",\n        lifecycle_stage: lifecycle.stage,\n        event_name: eventName,\n        channel,\n        churn_risk: churnRisk,\n        priority: lifecycle.priority,\n        engagement_score: engagementScore,\n        ingested_at: new Date().toISOString()\n      }\n    }\n  });\n}\nreturn output;\n"
      },
      "id": "41e0f3b8-c652-4736-9577-d90fbc26a5fd",
      "name": "Transform & Tag Lifecycle Stage",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        768,
        1264
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "combinator": "or"
          },
          "conditions": [
            {
              "leftValue": "={{ $json.sessions }}",
              "operator": {
                "type": "number",
                "operation": "gte"
              },
              "rightValue": 5
            },
            {
              "leftValue": "={{ $json.priority }}",
              "operator": {
                "type": "string",
                "operation": "equals"
              },
              "rightValue": "critical"
            }
          ]
        },
        "options": {}
      },
      "id": "49652e8d-2de5-49b2-905e-5dfe3ba4a961",
      "name": "Filter: Min 5 Sessions OR Critical Priority",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2,
      "position": [
        1008,
        1264
      ]
    },
    {
      "parameters": {
        "mode": "insert",
        "pineconeIndex": "={{ $vars.PINECONE_INDEX }}",
        "options": {}
      },
      "id": "d9b310fa-f0fa-483b-b74c-14cfb48b9abb",
      "name": "Pinecone – Insert Lifecycle Embeddings",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePinecone",
      "typeVersion": 1,
      "position": [
        1296,
        1232
      ],
      "credentials": {
        "pineconeApi": {
          "id": "MTSEamCpRUuY5Xt6",
          "name": "PineconeApi account"
        }
      }
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "46d8cc60-23af-4500-aae4-a9e1397c3ab8",
      "name": "Default Data Loader",
      "type": "@n8n/n8n-nodes-langchain.documentDefaultDataLoader",
      "typeVersion": 1,
      "position": [
        1424,
        1424
      ]
    },
    {
      "parameters": {
        "chunkSize": 500,
        "chunkOverlap": 80,
        "options": {}
      },
      "id": "7f795314-d2d2-4372-8e51-8280fd6269b0",
      "name": "Recursive Text Splitter",
      "type": "@n8n/n8n-nodes-langchain.textSplitterRecursiveCharacterTextSplitter",
      "typeVersion": 1,
      "position": [
        1536,
        1584
      ]
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "04faa041-f151-4d93-a36e-04eb65bb2782",
      "name": "OpenAI Embeddings – Ingestion",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "typeVersion": 1.2,
      "position": [
        1184,
        1456
      ]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO rag_ingestion_log (run_at, source, records_ingested, lifecycle_stages, status) VALUES (NOW(), 'google_analytics_4', {{ $input.all().length }}, 'pre_sales,onboarding,activation,support,retention,expansion', 'success');",
        "options": {}
      },
      "id": "d0dbcb85-5b7a-4440-9e15-fde5a45ec3ee",
      "name": "Postgres – Log Ingestion Run",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        1920,
        1264
      ]
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "ae0488de-fa47-4f69-8aec-621fd60a57a6",
      "name": "Chat Trigger – Lifecycle Query",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "typeVersion": 1.1,
      "position": [
        0,
        1888
      ],
      "webhookId": "chat-webhook-lifecycle-rag"
    },
    {
      "parameters": {
        "jsCode": "\nconst query = ($input.first().json.chatInput || \"\").toLowerCase();\n\nconst intents = [\n  { keywords: [\"churn\",\"risk\",\"retention\",\"cancel\",\"losing\"],\n    intent: \"churn_analysis\",\n    hint: \"Focus on churn_risk signals, low engagement scores, and accounts with fewer than 3 sessions in 14 days. Cite specific GA4 behavioral metrics.\" },\n  { keywords: [\"onboard\",\"time to value\",\"ttv\",\"activation\",\"setup\",\"getting started\"],\n    intent: \"onboarding_health\",\n    hint: \"Analyze trial_start, onboarding_complete, and feature_activation event sequences. Highlight gaps where onboarding_complete has not fired within 7 days of trial_start.\" },\n  { keywords: [\"upsell\",\"expand\",\"upgrade\",\"cross-sell\",\"growth\",\"revenue\",\"expansion\"],\n    intent: \"expansion_intelligence\",\n    hint: \"Identify accounts with expansion_event signals and high engagement scores (>70). Suggest timing, channel, and talking points for expansion conversations.\" },\n  { keywords: [\"proposal\",\"rfp\",\"demo\",\"sales\",\"presales\",\"pipeline\",\"lead\"],\n    intent: \"pre_sales\",\n    hint: \"Focus on demo_request and rfp_download events. Identify which channels and landing pages drive the highest-intent pre-sales traffic.\" },\n  { keywords: [\"support\",\"ticket\",\"issue\",\"bug\",\"help\",\"complaint\"],\n    intent: \"support_analysis\",\n    hint: \"Analyze support_ticket_opened events by lifecycle stage and channel. Identify patterns that correlate with high churn risk.\" },\n  { keywords: [\"brief\",\"account\",\"renewal\",\"qbr\",\"quarterly\",\"summary\"],\n    intent: \"account_brief\",\n    hint: \"Generate a structured account brief: lifecycle stage, engagement score, churn risk, last meaningful event, recommended next action.\" }\n];\n\nlet matched = { intent: \"general\", hint: \"Provide a comprehensive lifecycle overview grounded in GA4 behavioral data across all stages.\" };\nfor (const i of intents) {\n  if (i.keywords.some(k => query.includes(k))) { matched = i; break; }\n}\n\nreturn [{ json: { original_query: $input.first().json.chatInput, intent: matched.intent, system_prompt_hint: matched.hint, timestamp: new Date().toISOString() } }];\n"
      },
      "id": "cacc11d9-2efd-4b4c-9ada-a05c71c0e3cf",
      "name": "Classify Query Intent",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        256,
        1888
      ]
    },
    {
      "parameters": {
        "text": "={{ $('Classify Query Intent').item.json.original_query }}",
        "options": {
          "maxIterations": 5,
          "returnIntermediateSteps": false
        }
      },
      "id": "d1e5da95-d9a4-46a6-a986-29fa5019647a",
      "name": "AI Agent – Customer Lifecycle Analyst",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        576,
        1872
      ]
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "93f60cea-0630-4a46-a9a6-ddbea4f8e290",
      "name": "OpenAI Embeddings – Query",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "typeVersion": 1.2,
      "position": [
        1072,
        2224
      ]
    },
    {
      "parameters": {
        "mode": "retrieve-as-tool",
        "toolName": "lifecycle_knowledge_base",
        "toolDescription": "Use this tool to retrieve customer lifecycle analytics data from Google Analytics 4. It contains behavioral signals, engagement scores, churn risk indicators, funnel performance, and event data across pre-sales, onboarding, activation, support, retention, and expansion stages. ALWAYS query this tool before answering any question about customer behavior, lifecycle health, or SaaS metrics.",
        "pineconeIndex": "={{ $vars.PINECONE_INDEX }}",
        "options": {}
      },
      "id": "ff3b4b0d-3b94-49fd-b4a6-748168910bda",
      "name": "Pinecone – Lifecycle Knowledge Base Tool",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePinecone",
      "typeVersion": 1,
      "position": [
        976,
        2048
      ],
      "credentials": {
        "pineconeApi": {
          "id": "MTSEamCpRUuY5Xt6",
          "name": "PineconeApi account"
        }
      }
    },
    {
      "parameters": {
        "sessionKey": "={{ $json.sessionId || 'default_session' }}",
        "contextWindowLength": 10
      },
      "id": "adfb3965-2df1-4e0b-ae8e-bf060aa5aa4d",
      "name": "Buffer Memory (10 turns)",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.3,
      "position": [
        784,
        2192
      ]
    },
    {
      "parameters": {
        "model": "gpt-4o",
        "options": {
          "maxTokens": 1500,
          "temperature": 0.2
        }
      },
      "id": "3e54dc9a-e586-47a0-9f3f-4e2954068d3f",
      "name": "GPT-4o (LLM)",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.1,
      "position": [
        560,
        2176
      ]
    }
  ],
  "pinData": {},
  "connections": {
    "Schedule Trigger (Daily 02:00)": {
      "main": [
        [
          {
            "node": "GA4 – Pull Sessions by Lifecycle Stage",
            "type": "main",
            "index": 0
          },
          {
            "node": "GA4 – Pull User Journey Funnels",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GA4 – Pull Sessions by Lifecycle Stage": {
      "main": [
        [
          {
            "node": "Merge GA4 Data Streams",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GA4 – Pull User Journey Funnels": {
      "main": [
        [
          {
            "node": "Merge GA4 Data Streams",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Merge GA4 Data Streams": {
      "main": [
        [
          {
            "node": "Transform & Tag Lifecycle Stage",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Transform & Tag Lifecycle Stage": {
      "main": [
        [
          {
            "node": "Filter: Min 5 Sessions OR Critical Priority",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Filter: Min 5 Sessions OR Critical Priority": {
      "main": [
        [
          {
            "node": "Pinecone – Insert Lifecycle Embeddings",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Default Data Loader": {
      "ai_document": [
        [
          {
            "node": "Pinecone – Insert Lifecycle Embeddings",
            "type": "ai_document",
            "index": 0
          }
        ]
      ]
    },
    "Recursive Text Splitter": {
      "ai_textSplitter": [
        [
          {
            "node": "Default Data Loader",
            "type": "ai_textSplitter",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Embeddings – Ingestion": {
      "ai_embedding": [
        [
          {
            "node": "Pinecone – Insert Lifecycle Embeddings",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Pinecone – Insert Lifecycle Embeddings": {
      "main": [
        [
          {
            "node": "Postgres – Log Ingestion Run",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Chat Trigger – Lifecycle Query": {
      "main": [
        [
          {
            "node": "Classify Query Intent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Classify Query Intent": {
      "main": [
        [
          {
            "node": "AI Agent – Customer Lifecycle Analyst",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GPT-4o (LLM)": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent – Customer Lifecycle Analyst",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Buffer Memory (10 turns)": {
      "ai_memory": [
        [
          {
            "node": "AI Agent – Customer Lifecycle Analyst",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Pinecone – Lifecycle Knowledge Base Tool": {
      "ai_tool": [
        [
          {
            "node": "AI Agent – Customer Lifecycle Analyst",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Embeddings – Query": {
      "ai_embedding": [
        [
          {
            "node": "Pinecone – Lifecycle Knowledge Base Tool",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false
  },
  "versionId": "c055baf5-8f4c-4282-a59d-344b2c46bd53",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "ba1ee3cb283f555c8259933930d7eed40bbd9b6f053facc8f3835cd568408124"
  },
  "id": "3NZFMubW1xRrCd2I",
  "tags": []
}