{
  "name": "YT Tutorial",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "ff2fa871-3df1-48bd-8e9a-682958ae393b",
        "options": {}
      },
      "id": "911b54ed-96c8-4c41-bf5b-e23b3114841a",
      "name": "Generate AI Response",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        820,
        380
      ],
      "webhookId": "ff2fa871-3df1-48bd-8e9a-682958ae393b"
    },
    {
      "parameters": {
        "jsCode": "const lastInput = $node[\"Generate AI Response\"].json[\"body\"][\"custom_fields\"][\"User Response\"];\nconst username = $node[\"Generate AI Response\"].json[\"body\"][\"ig_username\"]; // Use the actual node name here\n\nconst data = {\n    \"question\": lastInput,\n    \"overrideConfig\": {\n        \"sessionId\": username,\n    }\n};\n\nreturn [{ json: data }];"
      },
      "id": "a8943413-9943-46d6-bc21-679001f41d60",
      "name": "Structured JSON Body",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1040,
        380
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://flowiseai-railway-production-c18f.up.railway.app/api/v1/prediction/9a915d5c-a780-43de-a1e1-ee01268795c7",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json }}",
        "options": {}
      },
      "id": "fc3b53e0-c488-4eec-a26a-2f1b770004ca",
      "name": "Send User Response to Flowise",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1260,
        380
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "a25f527e-fb67-476a-ba5d-537e03e2aa06",
              "name": "AI Response",
              "value": "={{ $json.text }}",
              "type": "string"
            },
            {
              "id": "136a5609-0b2e-43d6-bc9e-f52fecca84a6",
              "name": "sessionId",
              "value": "={{ $json.sessionId }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "e61fa8c7-0c0b-46d0-88ee-faa1bc8b0d59",
      "name": "Set Variables",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1480,
        380
      ]
    },
    {
      "parameters": {
        "operation": "insert",
        "collection": "AI Responses",
        "fields": "sessionId,AI Response",
        "options": {}
      },
      "id": "6849ffaa-b5c7-4a49-8381-5aaebf51c9e5",
      "name": "Insert AI Response in Database",
      "type": "n8n-nodes-base.mongoDb",
      "typeVersion": 1.1,
      "position": [
        1700,
        380
      ],
      "credentials": {
        "mongoDb": {
          "id": "aFBCgrGXHXFQrp9c",
          "name": "MongoDB account"
        }
      }
    },
    {
      "parameters": {
        "collection": "AI Responses",
        "options": {},
        "query": "={\n  \"sessionId\":\"{{ $json.body.Username }}\"\n}"
      },
      "id": "ac788bf7-f2bc-49db-9a87-af7fcf72c744",
      "name": "Find AI Response",
      "type": "n8n-nodes-base.mongoDb",
      "typeVersion": 1.1,
      "position": [
        1020,
        620
      ],
      "credentials": {
        "mongoDb": {
          "id": "aFBCgrGXHXFQrp9c",
          "name": "MongoDB account"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "b7e4ece4-c0dd-4c1c-bc9f-7bdfe163b6bc",
              "leftValue": "={{ $json['AI Response'] }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notEmpty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "c4964929-06ba-4de4-9b8c-dc21d1d51f00",
      "name": "If Response Exists",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1240,
        620
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\n  \"response_exists\": \"true\"\n}",
        "options": {}
      },
      "id": "95921c18-d99d-43dc-8b3a-3b76204194d4",
      "name": "Exists",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1540,
        600
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "{\n  \"response_exists\": \"false\"\n}",
        "options": {}
      },
      "id": "3e2f1722-535b-482d-975d-025c9420a0dc",
      "name": "Does not exist",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        1540,
        780
      ]
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "9f1ecfa4-119f-405c-8aa9-cc0d0fa67cec",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "6fd23bb3-ef08-4253-8a41-0f23fa6d3623",
      "name": "Check AI Response",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        800,
        620
      ],
      "webhookId": "9f1ecfa4-119f-405c-8aa9-cc0d0fa67cec"
    },
    {
      "parameters": {
        "collection": "AI Responses",
        "options": {},
        "query": "={\n  \"sessionId\":\"{{ $json.body.ig_username }}\"\n}"
      },
      "id": "25d94817-ba78-4b05-9b07-99b1f839aa08",
      "name": "MongoDB",
      "type": "n8n-nodes-base.mongoDb",
      "typeVersion": 1.1,
      "position": [
        1020,
        1020
      ],
      "credentials": {
        "mongoDb": {
          "id": "aFBCgrGXHXFQrp9c",
          "name": "MongoDB account"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "bce329ea-6873-4a18-81e3-db616871006d",
              "name": "AI Response",
              "value": "={{ $json['AI Response'] }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "0e205932-0088-4ccd-9526-a69b5b1bc3c5",
      "name": "Set AI Response",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1240,
        1020
      ]
    },
    {
      "parameters": {
        "jsCode": "const words = [\"brotha\", \"bro\", \"mate\", \"btw\", \"haha\", \"man\", \"@\", \"actually\", \"back to you\"];\n// Escape special characters in words and join them with a regex alternation \"|\"\nconst escapedWords = words.map(word => word.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'));\nconst commaRegex = new RegExp(`,\\\\s*(?=\\\\b(?:${escapedWords.join(\"|\")})\\\\b|[A-Z])`, 'g');\nconst parenRegex = /\\(.*?\\)/g; // Regex to match content inside parentheses\nconst exclamRegex = /!/g; // Regex to match exclamation marks\nconst asteriskRegex = /\\*/g; // Regex to match asterisks\n\n// Function to process text according to the new rules\nfunction processText(inputString) {\n    // Remove content inside parentheses\n    let result = inputString.replace(parenRegex, \"\");\n    // Remove commas under specific conditions\n    result = result.replace(commaRegex, \" \");\n    // Replace exclamation marks with periods\n    result = result.replace(exclamRegex, \".\");\n    // Remove all asterisks\n    result = result.replace(asteriskRegex, \"\");\n    return result;\n}\n\n// Assume that the incoming items are structured with a text property\nreturn items.map(item => {\n    const text = $json[\"AI Response\"];\n    const correctedText = processText(text);\n    return { json: { correctedText } };\n});"
      },
      "id": "84417f6c-6af9-483f-bb83-31a412afe5d6",
      "name": "Comma Remover",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1460,
        1020
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "be7c5b22-cf79-4495-a6d2-412f95c7dde5",
              "name": "Final Output",
              "value": "={{ $json['correctedText'] }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "f3d48d27-db21-4413-8018-409b1061150f",
      "name": "Save New AI Response",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1680,
        1020
      ]
    },
    {
      "parameters": {
        "jsCode": "function parseTextToSentences(inputText) {\n  const splitIntoSentences = (text) => {\n    return text.split(/(?<!\\w\\.\\w)(?<=\\.)\\s+|(?<!\\w\\?\\w)(?<=\\?)\\s+|[\\n]+/).map(sentence => {\n      return sentence.replace(/\\.$/, '').trim();\n    }).filter(sentence => sentence.length > 0);\n  };\n\n  const sentences = splitIntoSentences(inputText);\n  let sentenceObject = {};\n\n  sentences.forEach((sentence, index) => {\n    const key = `Sentence ${index + 1}`;\n    sentenceObject[key] = sentence;\n  });\n\n  return [sentenceObject];\n}\n\nfunction organizeSentencesIntoResponses(sentencesObj) {\n  const sentences = Object.values(sentencesObj[0]);\n  const maxResponses = 6;\n  const responses = Array(maxResponses).fill(null);\n\n  if (sentences.length <= maxResponses) {\n    // If the number of sentences is less than or equal to maxResponses, distribute them one per response\n    sentences.forEach((sentence, index) => {\n      responses[index] = sentence;\n    });\n  } else {\n    // If the number of sentences is more than maxResponses\n    const numSentencesForFirstFive = sentences.length - 1; // Exclude the last sentence for AI Response 6\n    const baseSentencesPerResponse = Math.floor(numSentencesForFirstFive / (maxResponses - 1));\n    const extraSentences = numSentencesForFirstFive % (maxResponses - 1);\n\n    let sentenceIndex = 0;\n    for (let i = 0; i < maxResponses - 1; i++) {\n      let sentencesForThisResponse = baseSentencesPerResponse;\n      if (i >= maxResponses - 1 - extraSentences) {\n        sentencesForThisResponse++;\n      }\n      responses[i] = sentences.slice(sentenceIndex, sentenceIndex + sentencesForThisResponse).join('. ');\n      sentenceIndex += sentencesForThisResponse;\n    }\n\n    // Assign the last sentence to AI Response 6\n    responses[maxResponses - 1] = sentences[sentences.length - 1];\n  }\n\n  return {\n    \"AI Response 1\": responses[0],\n    \"AI Response 2\": responses[1],\n    \"AI Response 3\": responses[2],\n    \"AI Response 4\": responses[3],\n    \"AI Response 5\": responses[4],\n    \"AI Response 6\": responses[5],\n  };\n}\n\nconst inputText = $json[\"Final Output\"];\n\n// Fragment the text into sentences\nconst sentencesObj = parseTextToSentences(inputText);\n\n// Organize the sentences into AI responses\nconst organizedResponses = organizeSentencesIntoResponses(sentencesObj);\n\nreturn [{ json: organizedResponses }];"
      },
      "id": "f019ca2a-6988-4b52-8716-14330cf43574",
      "name": "AI Response Splitter",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1900,
        1020
      ]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ $json }}",
        "options": {}
      },
      "id": "5bb60d69-ab5d-42b2-8f5f-b98ea5774ca5",
      "name": "Respond to Webhook",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [
        2120,
        1020
      ]
    },
    {
      "parameters": {
        "operation": "delete",
        "collection": "AI Responses",
        "query": "={ \"$expr\": { \"$eq\": [\"$_id\", { \"$toObjectId\": \"{{ $('MongoDB').first().json._id }}\" }] } }  "
      },
      "id": "6e24d89f-8635-40a2-b81b-fc973418d524",
      "name": "MongoDB1",
      "type": "n8n-nodes-base.mongoDb",
      "typeVersion": 1.1,
      "position": [
        2340,
        1020
      ],
      "credentials": {
        "mongoDb": {
          "id": "aFBCgrGXHXFQrp9c",
          "name": "MongoDB account"
        }
      }
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "ef1cec51-32e2-4277-a164-ec28a1454f25",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "c7813f1c-f3dc-43ba-a682-a221066ef36e",
      "name": "Send AI Response",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        800,
        1020
      ],
      "webhookId": "ef1cec51-32e2-4277-a164-ec28a1454f25"
    }
  ],
  "pinData": {},
  "connections": {
    "Generate AI Response": {
      "main": [
        [
          {
            "node": "Structured JSON Body",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Structured JSON Body": {
      "main": [
        [
          {
            "node": "Send User Response to Flowise",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send User Response to Flowise": {
      "main": [
        [
          {
            "node": "Set Variables",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Variables": {
      "main": [
        [
          {
            "node": "Insert AI Response in Database",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Find AI Response": {
      "main": [
        [
          {
            "node": "If Response Exists",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If Response Exists": {
      "main": [
        [
          {
            "node": "Exists",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Does not exist",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check AI Response": {
      "main": [
        [
          {
            "node": "Find AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "MongoDB": {
      "main": [
        [
          {
            "node": "Set AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set AI Response": {
      "main": [
        [
          {
            "node": "Comma Remover",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Comma Remover": {
      "main": [
        [
          {
            "node": "Save New AI Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save New AI Response": {
      "main": [
        [
          {
            "node": "AI Response Splitter",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Response Splitter": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Respond to Webhook": {
      "main": [
        [
          {
            "node": "MongoDB1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send AI Response": {
      "main": [
        [
          {
            "node": "MongoDB",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": true,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "88e0915f-b5e0-4b87-b02f-6e513709f34f",
  "meta": {
    "templateCredsSetupCompleted": true,
    "instanceId": "841e26a9e8402291cc94494e854fb04424a9d92497629cfffdd5708ba5ffa7e8"
  },
  "id": "Rvlx4cpuisAfINgJ",
  "tags": [
    {
      "createdAt": "2024-11-29T15:37:03.272Z",
      "updatedAt": "2024-11-29T15:37:03.272Z",
      "id": "nSe8kUl3xdUgBePY",
      "name": "YT"
    }
  ]
}