{
  "id": "SC9zUkWz5rSIjWjr",
  "name": "AI-Enhanced SMS Conversational Flow",
  "tags": [],
  "nodes": [
    {
      "id": "ed7fc73c-b267-4f91-8fa1-4545b0e6a7e9",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -576,
        -496
      ],
      "parameters": {
        "color": 5,
        "width": 1088,
        "height": 256,
        "content": "## User Signup\n"
      },
      "typeVersion": 1
    },
    {
      "id": "b7657782-593c-4052-8915-4411d3b5c657",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -768,
        -208
      ],
      "parameters": {
        "color": 3,
        "width": 1584,
        "height": 464,
        "content": "## Verification Agent"
      },
      "typeVersion": 1
    },
    {
      "id": "6c4f0a1f-7c3c-4c74-acdd-711126a8b44f",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -896,
        320
      ],
      "parameters": {
        "color": 4,
        "width": 2000,
        "height": 416,
        "content": "## Escalation Agent"
      },
      "typeVersion": 1
    },
    {
      "id": "3d20321f-b131-48b7-9dae-4cde4e746cb2",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -864,
        784
      ],
      "parameters": {
        "color": 6,
        "width": 1952,
        "height": 704,
        "content": "## Response Agent"
      },
      "typeVersion": 1
    },
    {
      "id": "1e917a1b-226e-4781-a658-b386e171581b",
      "name": "Store Verification",
      "type": "n8n-nodes-base.postgres",
      "position": [
        -80,
        -400
      ],
      "parameters": {
        "table": "user_verifications",
        "schema": "public",
        "options": {}
      },
      "typeVersion": 2
    },
    {
      "id": "af1b2159-4d70-410b-9c32-633c3244ee82",
      "name": "Send Verification SMS (Twilio API)",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        128,
        -400
      ],
      "parameters": {
        "url": "https://api.twilio.com/2010-04-01/Accounts/{{ $credentials.accountSid }}/Messages.json",
        "options": {},
        "sendBody": true,
        "authentication": "genericCredentialType",
        "bodyParameters": {
          "parameters": [
            {
              "name": "To",
              "value": "={{ $json.phone_number }}"
            },
            {
              "name": "From",
              "value": "+1234567890"
            },
            {
              "name": "Body",
              "value": "Your verification code is: {{ $json.verification_code }}. Expires in 10 minutes."
            }
          ]
        },
        "genericAuthType": "httpBasicAuth"
      },
      "typeVersion": 4
    },
    {
      "id": "6352fdab-c3e1-467b-aa0c-ff3ebbc7204c",
      "name": "Check Verification",
      "type": "n8n-nodes-base.postgres",
      "position": [
        -288,
        -16
      ],
      "parameters": {
        "sort": {
          "values": [
            {
              "column": "created_at",
              "direction": "DESC"
            }
          ]
        },
        "limit": 1,
        "table": "user_verifications",
        "where": {
          "values": [
            {
              "value": "={{ $json.phone_number }}",
              "column": "phone_number"
            },
            {
              "value": "false",
              "column": "verified"
            }
          ]
        },
        "schema": "public",
        "options": {},
        "operation": "select"
      },
      "typeVersion": 2
    },
    {
      "id": "60594a25-df6b-43e0-9749-81ae28e6ae01",
      "name": "Validate Code",
      "type": "n8n-nodes-base.switch",
      "position": [
        -80,
        -16
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "version": 1,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "9df14424-8f64-426b-878d-f696ccba98cc",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "",
                    "rightValue": ""
                  }
                ]
              }
            },
            {}
          ]
        },
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "97e91597-6b1f-4eb1-afff-fd0e564e1785",
      "name": "Create Session",
      "type": "n8n-nodes-base.code",
      "position": [
        112,
        -128
      ],
      "parameters": {
        "jsCode": "const sessionId = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);\nreturn {\n  phone_number: $('Extract Verification Data1').item.json.phone_number,\n  session_id: sessionId,\n  verified_at: new Date().toISOString(),\n  intake_data: JSON.stringify({transcript: [], ai_metadata: {}, structured_data: {}}),\n  status: 'active',\n  created_at: new Date().toISOString()\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "d95fb2f3-99dd-49b5-b8fa-f21370fcc7f8",
      "name": "Mark Verified",
      "type": "n8n-nodes-base.postgres",
      "position": [
        320,
        -176
      ],
      "parameters": {
        "table": "user_verifications",
        "schema": "public",
        "options": {},
        "operation": "update"
      },
      "typeVersion": 2
    },
    {
      "id": "9f8cbc2e-0acd-4c57-abda-5505f84e5d87",
      "name": "Insert Session",
      "type": "n8n-nodes-base.postgres",
      "position": [
        320,
        0
      ],
      "parameters": {
        "table": "user_sessions",
        "schema": "public",
        "options": {}
      },
      "typeVersion": 2
    },
    {
      "id": "6bac846e-310c-48dd-a46c-35bc2a9909f6",
      "name": "Verify Success Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        560,
        -128
      ],
      "parameters": {
        "options": {},
        "respondWith": "json",
        "responseBody": "{\"success\": true, \"message\": \"Verified successfully\", \"session_id\": \"{{ $('Create Session').item.json.session_id }}\"}"
      },
      "typeVersion": 1
    },
    {
      "id": "52f8f128-a14c-477b-a3b2-48280925f6cd",
      "name": "Verify Failed Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        112,
        128
      ],
      "parameters": {
        "options": {},
        "respondWith": "json",
        "responseBody": "{\"success\": false, \"message\": \"Invalid or expired verification code\"}"
      },
      "typeVersion": 1
    },
    {
      "id": "00749335-1838-4ffa-9ae4-743d2aa9db76",
      "name": "Incoming SMS Webhook (Twilio)",
      "type": "n8n-nodes-base.webhook",
      "notes": "Configure this URL in your Twilio phone number settings",
      "position": [
        -832,
        448
      ],
      "parameters": {
        "path": "twilio_sms_incoming",
        "options": {},
        "httpMethod": "POST",
        "responseMode": "responseNode"
      },
      "typeVersion": 1
    },
    {
      "id": "38aded6e-ea7d-46ef-994e-cae14a0d480b",
      "name": "\ud83e\udd16 AI Sentiment Analysis",
      "type": "n8n-nodes-base.openAi",
      "notes": "AI NODE 1: Analyzes sentiment, urgency, intent from free-text",
      "position": [
        -224,
        448
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4"
        },
        "options": {
          "maxTokens": 500,
          "temperature": 0.3
        },
        "requestOptions": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "2d330b5b-ee12-4f51-b97d-371372b7ca5a",
      "name": "Process AI Analysis",
      "type": "n8n-nodes-base.code",
      "position": [
        -32,
        448
      ],
      "parameters": {
        "jsCode": "let aiAnalysis;\ntry {\n  const raw = $input.item.json.message?.content || '{}';\n  aiAnalysis = JSON.parse(raw.replace(/```json\\n?|```/g, ''));\n} catch (e) {\n  aiAnalysis = {\n    sentiment: 'neutral',\n    urgency_score: 5,\n    intent: 'continue_intake',\n    requires_escalation: false,\n    detected_keywords: [],\n    summary: $('Extract SMS Data1').item.json.message_body\n  };\n}\n\nconst sessionData = $('Find User Session1').item.json;\nlet intakeData = JSON.parse(sessionData.intake_data || '{}');\nif (!intakeData.transcript) intakeData.transcript = [];\nif (!intakeData.ai_metadata) intakeData.ai_metadata = {};\n\nintakeData.transcript.push({\n  message: $('Extract SMS Data1').item.json.message_body,\n  timestamp: $('Extract SMS Data1').item.json.received_at,\n  direction: 'incoming',\n  ai_analysis: aiAnalysis\n});\n\nintakeData.ai_metadata.last_sentiment = aiAnalysis.sentiment;\nintakeData.ai_metadata.last_intent = aiAnalysis.intent;\nintakeData.ai_metadata.max_urgency = Math.max(intakeData.ai_metadata.max_urgency || 0, aiAnalysis.urgency_score);\n\nreturn {\n  session_id: sessionData.session_id,\n  phone_number: sessionData.phone_number,\n  status: sessionData.status,\n  intake_data: JSON.stringify(intakeData),\n  ai_analysis: aiAnalysis,\n  original_message: $('Extract SMS Data1').item.json.message_body\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "7e897558-7fa2-45bf-9422-e3187ecf988f",
      "name": "\ud83e\udd16 AI Escalation Router",
      "type": "n8n-nodes-base.switch",
      "notes": "AI NODE 2: Routes escalations based on AI-detected frustration",
      "position": [
        176,
        448
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "version": 1,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "906d938e-3b91-4027-90ba-b30866c59d12",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "",
                    "rightValue": ""
                  }
                ]
              }
            },
            {}
          ]
        },
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "af73afcd-3a1c-4b12-a198-4920e2451509",
      "name": "Mark Session Escalated",
      "type": "n8n-nodes-base.postgres",
      "position": [
        576,
        448
      ],
      "parameters": {
        "table": "user_sessions",
        "schema": "public",
        "options": {},
        "operation": "update"
      },
      "typeVersion": 2
    },
    {
      "id": "1527d4a4-a488-422f-8b84-78e4d71c679a",
      "name": "Send Escalation Email",
      "type": "n8n-nodes-base.gmail",
      "position": [
        768,
        448
      ],
      "parameters": {
        "sendTo": "user@example.com",
        "message": "=AI-Detected Escalation Alert\n\nPhone: {{ $('Process AI Analysis').item.json.phone_number }}\nSession: {{ $('Process AI Analysis').item.json.session_id }}\n\nSentiment: {{ $('Process AI Analysis').item.json.ai_analysis.sentiment }}\nUrgency: {{ $('Process AI Analysis').item.json.ai_analysis.urgency_score }}/10\nIntent: {{ $('Process AI Analysis').item.json.ai_analysis.intent }}\n\nMessage: {{ $('Process AI Analysis').item.json.original_message }}\n\nAI Summary: {{ $('Process AI Analysis').item.json.ai_analysis.summary }}\nKeywords: {{ $('Process AI Analysis').item.json.ai_analysis.detected_keywords.join(', ') }}",
        "options": {},
        "subject": "\ud83d\udea8 AI Escalation: {{ $('Process AI Analysis').item.json.ai_analysis.sentiment }}"
      },
      "credentials": {
        "gmailOAuth2": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2
    },
    {
      "id": "dcbe49b5-e58f-4f17-92a5-5e1f09bfc81f",
      "name": "\ud83e\udd16 AI Intent Router",
      "type": "n8n-nodes-base.switch",
      "notes": "AI NODE 3: Routes based on AI-detected user intent",
      "position": [
        -608,
        1120
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "version": 1,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "631faa90-2d78-4990-b233-425e77f9d8a9",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "",
                    "rightValue": ""
                  }
                ]
              }
            },
            {}
          ]
        },
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "f50c06a8-78ff-44da-960a-4ca2580c59a7",
      "name": "\ud83e\udd16 AI Intake Enrichment",
      "type": "n8n-nodes-base.openAi",
      "notes": "AI NODE 4: Extracts structured data from free-text",
      "position": [
        -336,
        928
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4"
        },
        "options": {
          "maxTokens": 500,
          "temperature": 0.3
        },
        "requestOptions": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "c0ecc55a-f014-49d0-9d25-6a19558aa812",
      "name": "Merge Enriched Data",
      "type": "n8n-nodes-base.code",
      "position": [
        -144,
        928
      ],
      "parameters": {
        "jsCode": "let enrichment;\ntry {\n  const raw = $input.item.json.message?.content || '{}';\n  enrichment = JSON.parse(raw.replace(/```json\\n?|```/g, ''));\n} catch (e) {\n  enrichment = {extracted_info: {}, completeness_score: 0, suggested_next_question: 'Tell me more?', category: 'general'};\n}\n\nconst sessionData = $('Process AI Analysis').item.json;\nlet intakeData = JSON.parse(sessionData.intake_data);\n\nif (!intakeData.structured_data) intakeData.structured_data = {};\nObject.assign(intakeData.structured_data, enrichment.extracted_info);\n\nintakeData.ai_metadata.completeness_score = enrichment.completeness_score;\nintakeData.ai_metadata.category = enrichment.category;\nintakeData.ai_metadata.suggested_next_question = enrichment.suggested_next_question;\n\nreturn {\n  session_id: sessionData.session_id,\n  phone_number: sessionData.phone_number,\n  intake_data: JSON.stringify(intakeData),\n  updated_at: new Date().toISOString(),\n  suggested_response: enrichment.suggested_next_question,\n  completeness_score: enrichment.completeness_score\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "e17b6c77-172a-4d92-9d56-40a967d16ceb",
      "name": "\ud83e\udd16 AI Response Generator",
      "type": "n8n-nodes-base.openAi",
      "notes": "AI NODE 5: Generates contextual SMS responses",
      "position": [
        256,
        928
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4"
        },
        "options": {
          "maxTokens": 200,
          "temperature": 0.7
        },
        "requestOptions": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "2e1336bd-ca0f-44ff-9129-af5aa1975df4",
      "name": "Send AI Response SMS",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        464,
        928
      ],
      "parameters": {
        "url": "https://api.twilio.com/2010-04-01/Accounts/{{ $credentials.accountSid }}/Messages.json",
        "options": {},
        "sendBody": true,
        "authentication": "genericCredentialType",
        "bodyParameters": {
          "parameters": [
            {
              "name": "To",
              "value": "={{ $('Merge Enriched Data').item.json.phone_number }}"
            },
            {
              "name": "From",
              "value": "+1234567890"
            },
            {
              "name": "Body",
              "value": "={{ $json.message?.content }}"
            }
          ]
        },
        "genericAuthType": "httpBasicAuth"
      },
      "typeVersion": 4
    },
    {
      "id": "daba2444-d8ca-416c-a445-47804dd4eeac",
      "name": "Prepare Closeout",
      "type": "n8n-nodes-base.code",
      "position": [
        -256,
        1232
      ],
      "parameters": {
        "jsCode": "const sessionData = $('Process AI Analysis').item.json;\nlet intakeData = JSON.parse(sessionData.intake_data);\n\nintakeData.completed_at = new Date().toISOString();\nintakeData.status = 'completed';\n\nconst filename = `transcripts/${sessionData.session_id}_${Date.now()}.json`;\n\nreturn {\n  session_id: sessionData.session_id,\n  phone_number: sessionData.phone_number,\n  intake_data: JSON.stringify(intakeData),\n  status: 'completed',\n  completed_at: intakeData.completed_at,\n  final_transcript: JSON.stringify(intakeData, null, 2),\n  s3_filename: filename\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "8029ca3a-d4de-4ba2-8dd3-98b7b46affe9",
      "name": "Finalize Session",
      "type": "n8n-nodes-base.postgres",
      "position": [
        -32,
        1136
      ],
      "parameters": {
        "table": "user_sessions",
        "schema": "public",
        "options": {},
        "operation": "update"
      },
      "typeVersion": 2
    },
    {
      "id": "43644ecd-9484-48fb-a587-67e7eb74d9c9",
      "name": "Upload to S3",
      "type": "n8n-nodes-base.awsS3",
      "position": [
        -32,
        1280
      ],
      "parameters": {
        "fileKey": "={{ $('Prepare Closeout').item.json.s3_filename }}"
      },
      "typeVersion": 1
    },
    {
      "id": "4665d2ec-142f-489a-ac10-97be857bd65c",
      "name": "\ud83e\udd16 AI Personalized Closeout",
      "type": "n8n-nodes-base.openAi",
      "notes": "AI NODE 6: Generates personalized thank you",
      "position": [
        176,
        1216
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4"
        },
        "options": {
          "maxTokens": 200,
          "temperature": 0.8
        },
        "requestOptions": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "539b4702-b7de-4014-9600-96c81e40567d",
      "name": "Send Closeout SMS",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        368,
        1216
      ],
      "parameters": {
        "url": "https://api.twilio.com/2010-04-01/Accounts/{{ $credentials.accountSid }}/Messages.json",
        "options": {},
        "sendBody": true,
        "authentication": "genericCredentialType",
        "bodyParameters": {
          "parameters": [
            {
              "name": "To",
              "value": "={{ $('Prepare Closeout').item.json.phone_number }}"
            },
            {
              "name": "From",
              "value": "+1234567890"
            },
            {
              "name": "Body",
              "value": "={{ $json.message?.content }}"
            }
          ]
        },
        "genericAuthType": "httpBasicAuth"
      },
      "typeVersion": 4
    },
    {
      "id": "2d6c8470-6c1a-4504-aeaa-77de599261b8",
      "name": "SMS Webhook Response",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        880,
        1104
      ],
      "parameters": {
        "options": {},
        "respondWith": "text",
        "responseBody": "OK"
      },
      "typeVersion": 1
    },
    {
      "id": "9d632faa-1a2a-492b-a270-45f9c43a7d73",
      "name": "Follow-Up Cron (24h)",
      "type": "n8n-nodes-base.cron",
      "position": [
        -272,
        1632
      ],
      "parameters": {
        "triggerTimes": {
          "item": [
            {
              "hour": 23
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "3ba98821-8843-4810-beca-7ee280ba94a2",
      "name": "Find Inactive Sessions",
      "type": "n8n-nodes-base.postgres",
      "position": [
        -64,
        1632
      ],
      "parameters": {
        "table": "user_sessions",
        "where": {
          "values": [
            {
              "value": "active",
              "column": "status"
            },
            {
              "value": "={{ new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString() }}",
              "column": "updated_at",
              "condition": "smallerEqual"
            }
          ]
        },
        "schema": "public",
        "options": {},
        "operation": "select"
      },
      "typeVersion": 2
    },
    {
      "id": "626da322-0a2c-4621-b955-23e09c38d65c",
      "name": "\ud83e\udd16 AI Personalized Reminder",
      "type": "n8n-nodes-base.openAi",
      "notes": "AI NODE 7: Generates contextual follow-up reminders",
      "position": [
        160,
        1632
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4"
        },
        "options": {
          "maxTokens": 200,
          "temperature": 0.8
        },
        "requestOptions": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "eb954b83-6379-482b-b726-0fa2f25f486d",
      "name": "Send Reminder SMS",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        384,
        1632
      ],
      "parameters": {
        "url": "https://api.twilio.com/2010-04-01/Accounts/{{ $credentials.accountSid }}/Messages.json",
        "options": {},
        "sendBody": true,
        "authentication": "genericCredentialType",
        "bodyParameters": {
          "parameters": [
            {
              "name": "To",
              "value": "={{ $json.phone_number }}"
            },
            {
              "name": "From",
              "value": "+1234567890"
            },
            {
              "name": "Body",
              "value": "={{ $('\ud83e\udd16 AI Personalized Reminder').item.json.message?.content }}"
            }
          ]
        },
        "genericAuthType": "httpBasicAuth"
      },
      "typeVersion": 4
    },
    {
      "id": "106e3596-6282-451c-b5d7-2c99177c38eb",
      "name": "User Signup Webhook1",
      "type": "n8n-nodes-base.webhook",
      "position": [
        -480,
        -400
      ],
      "parameters": {
        "path": "user_signup",
        "options": {},
        "httpMethod": "POST",
        "responseMode": "responseNode"
      },
      "typeVersion": 1
    },
    {
      "id": "abc53c9c-8c51-4c7b-9153-150ee93033fe",
      "name": "Generate Verification Code1",
      "type": "n8n-nodes-base.code",
      "position": [
        -272,
        -400
      ],
      "parameters": {
        "jsCode": "const code = Math.floor(100000 + Math.random() * 900000).toString();\nconst phoneNumber = $input.item.json.phone_number;\nconst expiryTime = new Date(Date.now() + 10 * 60 * 1000).toISOString();\n\nreturn {\n  phone_number: phoneNumber,\n  verification_code: code,\n  expires_at: expiryTime,\n  created_at: new Date().toISOString(),\n  verified: false\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "159949cc-b1ba-4f82-bac6-1031eb22288d",
      "name": "Signup Response1",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        320,
        -400
      ],
      "parameters": {
        "options": {},
        "respondWith": "json",
        "responseBody": "{\"success\": true, \"message\": \"Verification code sent to {{ $('Generate Verification Code').item.json.phone_number }}\"}"
      },
      "typeVersion": 1
    },
    {
      "id": "508216e9-98b4-42d7-954c-e92b66e4d067",
      "name": "Verify Code Webhook1",
      "type": "n8n-nodes-base.webhook",
      "position": [
        -688,
        -16
      ],
      "parameters": {
        "path": "verify_code",
        "options": {},
        "httpMethod": "POST",
        "responseMode": "responseNode"
      },
      "typeVersion": 1
    },
    {
      "id": "aa25aec4-c813-49f3-8997-05467e73ecd3",
      "name": "Extract Verification Data1",
      "type": "n8n-nodes-base.code",
      "position": [
        -480,
        -16
      ],
      "parameters": {
        "jsCode": "return {\n  phone_number: $input.item.json.phone_number,\n  submitted_code: $input.item.json.verification_code,\n  current_time: new Date().toISOString()\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "fc2d58b1-bdec-4109-bbf1-d21204fda108",
      "name": "Extract SMS Data1",
      "type": "n8n-nodes-base.code",
      "position": [
        -624,
        448
      ],
      "parameters": {
        "jsCode": "return {\n  from_number: $input.item.json.From,\n  message_body: $input.item.json.Body || '',\n  message_sid: $input.item.json.MessageSid,\n  received_at: new Date().toISOString()\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "9a4aeb83-01a6-456a-87dc-37236d255a18",
      "name": "Find User Session1",
      "type": "n8n-nodes-base.postgres",
      "position": [
        -432,
        448
      ],
      "parameters": {
        "sort": {
          "values": [
            {
              "column": "created_at",
              "direction": "DESC"
            }
          ]
        },
        "limit": 1,
        "table": "user_sessions",
        "where": {
          "values": [
            {
              "value": "={{ $json.from_number }}",
              "column": "phone_number"
            }
          ]
        },
        "schema": "public",
        "options": {},
        "operation": "select"
      },
      "typeVersion": 2
    },
    {
      "id": "434fea61-dc4b-4be1-bd56-b92c95f77eb5",
      "name": "Prepare Escalation Data1",
      "type": "n8n-nodes-base.code",
      "position": [
        384,
        448
      ],
      "parameters": {
        "jsCode": "return {\n  session_id: $('Process AI Analysis').item.json.session_id,\n  status: 'escalated',\n  escalated_at: new Date().toISOString()\n};"
      },
      "typeVersion": 2
    },
    {
      "id": "8c5c51ab-feb6-4e31-8e91-1f1b3ea95294",
      "name": "Send Escalation SMS1",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        944,
        448
      ],
      "parameters": {
        "url": "https://api.twilio.com/2010-04-01/Accounts/{{ $credentials.accountSid }}/Messages.json",
        "options": {},
        "sendBody": true,
        "authentication": "genericCredentialType",
        "bodyParameters": {
          "parameters": [
            {
              "name": "To",
              "value": "={{ $('Process AI Analysis').item.json.phone_number }}"
            },
            {
              "name": "From",
              "value": "+1234567890"
            },
            {
              "name": "Body",
              "value": "We understand this is important to you. A team member will contact you shortly. Session ID: {{ $('Process AI Analysis').item.json.session_id }}"
            }
          ]
        },
        "genericAuthType": "httpBasicAuth"
      },
      "typeVersion": 4
    },
    {
      "id": "9e8c77ff-0e8b-4f9b-b79f-4e7f5f365c54",
      "name": "Save Enriched Intake1",
      "type": "n8n-nodes-base.postgres",
      "position": [
        64,
        928
      ],
      "parameters": {
        "table": "user_sessions",
        "schema": "public",
        "options": {},
        "operation": "update"
      },
      "typeVersion": 2
    },
    {
      "id": "f7f12917-d522-4e8c-96f6-81301984ae89",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -384,
        1536
      ],
      "parameters": {
        "color": 5,
        "width": 976,
        "height": 304,
        "content": "## Followup agent"
      },
      "typeVersion": 1
    },
    {
      "id": "2695223c-4024-4622-95de-d7a3a51dbb76",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -416,
        1120
      ],
      "parameters": {
        "color": 4,
        "width": 992,
        "height": 304,
        "content": "## Close Out"
      },
      "typeVersion": 1
    },
    {
      "id": "0a61ced3-3938-49aa-b5e3-bf78cb0e9b7f",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        336,
        400
      ],
      "parameters": {
        "color": 3,
        "width": 736,
        "height": 224,
        "content": "## Human Escalation "
      },
      "typeVersion": 1
    },
    {
      "id": "77fef9b3-32cc-4f76-b386-84eedeadc96e",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -416,
        880
      ],
      "parameters": {
        "color": 2,
        "width": 1024,
        "height": 208,
        "content": "## Help Request"
      },
      "typeVersion": 1
    },
    {
      "id": "f0979bbd-5c3f-4ca3-ab27-b2177ee7b252",
      "name": "Sticky Note8",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1808,
        -416
      ],
      "parameters": {
        "width": 560,
        "height": 816,
        "content": " ## How it works\n\n1. **User Signup & Verification:**  \n   The workflow starts when a user signs up. It generates a verification code and sends it via SMS using Twilio.\n\n2. **Code Validation:**  \n   The user replies with the code. The workflow checks the code and, if valid, creates a session for the user.\n\n3. **Conversational AI:**  \n   Incoming SMS messages are analyzed by Chat GPT AI for sentiment, intent, and urgency. The workflow stores the conversation context and generates smart, AI-powered replies.\n\n4. **Escalation Handling:**  \n   If the AI detects urgency or frustration, the workflow escalates the session\u2014alerting your team and sending a supportive SMS to the user.\n\n---\n\n## Set up steps\n\n- **Estimated setup time:** 10\u201320 minutes for most users.\n- **What you\u2019ll need:**  \n  - A free n8n account (self-hosted or cloud)\n  - Free Twilio account (for SMS)\n  - ChatGPT API key (for AI)\n  - A PostgreSQL database (Supabase, Neon, or local)\n\n- **Setup process:**  \n  1. Import this workflow into n8n.\n  2. Add your Twilio and Groq credentials as environment variables or n8n credentials.\n  3. Update webhook URLs in your Twilio console (for incoming SMS).\n  4. (Optional) Adjust sticky notes in the workflow for detailed, step-by-step guidance."
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "c134c971-6da1-4e43-9328-cce2b0d5c9a8",
  "connections": {
    "Upload to S3": {
      "main": [
        [
          {
            "node": "\ud83e\udd16 AI Personalized Closeout",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Mark Verified": {
      "main": [
        [
          {
            "node": "Verify Success Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Validate Code": {
      "main": [
        [
          {
            "node": "Create Session",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Verify Failed Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Create Session": {
      "main": [
        [
          {
            "node": "Mark Verified",
            "type": "main",
            "index": 0
          },
          {
            "node": "Insert Session",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Insert Session": {
      "main": [
        [
          {
            "node": "Verify Success Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Finalize Session": {
      "main": [
        [
          {
            "node": "\ud83e\udd16 AI Personalized Closeout",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Closeout": {
      "main": [
        [
          {
            "node": "Finalize Session",
            "type": "main",
            "index": 0
          },
          {
            "node": "Upload to S3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract SMS Data1": {
      "main": [
        [
          {
            "node": "Find User Session1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Closeout SMS": {
      "main": [
        [
          {
            "node": "SMS Webhook Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Verification": {
      "main": [
        [
          {
            "node": "Validate Code",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find User Session1": {
      "main": [
        [
          {
            "node": "\ud83e\udd16 AI Sentiment Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Store Verification": {
      "main": [
        [
          {
            "node": "Send Verification SMS (Twilio API)",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Merge Enriched Data": {
      "main": [
        [
          {
            "node": "Save Enriched Intake1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Process AI Analysis": {
      "main": [
        [
          {
            "node": "\ud83e\udd16 AI Escalation Router",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Follow-Up Cron (24h)": {
      "main": [
        [
          {
            "node": "Find Inactive Sessions",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send AI Response SMS": {
      "main": [
        [
          {
            "node": "SMS Webhook Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Escalation SMS1": {
      "main": [
        [
          {
            "node": "SMS Webhook Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "User Signup Webhook1": {
      "main": [
        [
          {
            "node": "Generate Verification Code1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verify Code Webhook1": {
      "main": [
        [
          {
            "node": "Extract Verification Data1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save Enriched Intake1": {
      "main": [
        [
          {
            "node": "\ud83e\udd16 AI Response Generator",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Escalation Email": {
      "main": [
        [
          {
            "node": "Send Escalation SMS1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\ud83e\udd16 AI Intent Router": {
      "main": [
        [
          {
            "node": "\ud83e\udd16 AI Intake Enrichment",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Prepare Closeout",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find Inactive Sessions": {
      "main": [
        [
          {
            "node": "\ud83e\udd16 AI Personalized Reminder",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Mark Session Escalated": {
      "main": [
        [
          {
            "node": "Send Escalation Email",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Escalation Data1": {
      "main": [
        [
          {
            "node": "Mark Session Escalated",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\ud83e\udd16 AI Escalation Router": {
      "main": [
        [
          {
            "node": "Prepare Escalation Data1",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "\ud83e\udd16 AI Intent Router",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\ud83e\udd16 AI Intake Enrichment": {
      "main": [
        [
          {
            "node": "Merge Enriched Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Verification Data1": {
      "main": [
        [
          {
            "node": "Check Verification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\ud83e\udd16 AI Response Generator": {
      "main": [
        [
          {
            "node": "Send AI Response SMS",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\ud83e\udd16 AI Sentiment Analysis": {
      "main": [
        [
          {
            "node": "Process AI Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Verification Code1": {
      "main": [
        [
          {
            "node": "Store Verification",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Incoming SMS Webhook (Twilio)": {
      "main": [
        [
          {
            "node": "Extract SMS Data1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\ud83e\udd16 AI Personalized Closeout": {
      "main": [
        [
          {
            "node": "Send Closeout SMS",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "\ud83e\udd16 AI Personalized Reminder": {
      "main": [
        [
          {
            "node": "Send Reminder SMS",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send Verification SMS (Twilio API)": {
      "main": [
        [
          {
            "node": "Signup Response1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}