{
  "name": "v2",
  "nodes": [
    {
      "parameters": {
        "content": "```\n █████   ██████  ███████ ███    ██ ████████ ███████     ██████  ███████     ██    ██ ███████ ███    ██ ██████   █████  ███████     ██    ██ ██████      ██████  \n██   ██ ██       ██      ████   ██    ██    ██          ██   ██ ██          ██    ██ ██      ████   ██ ██   ██ ██   ██ ██          ██    ██      ██    ██  ████ \n███████ ██   ███ █████   ██ ██  ██    ██    █████       ██   ██ █████       ██    ██ █████   ██ ██  ██ ██   ██ ███████ ███████     ██    ██  █████     ██ ██ ██ \n██   ██ ██    ██ ██      ██  ██ ██    ██    ██          ██   ██ ██           ██  ██  ██      ██  ██ ██ ██   ██ ██   ██      ██      ██  ██  ██         ████  ██ \n██   ██  ██████  ███████ ██   ████    ██    ███████     ██████  ███████       ████   ███████ ██   ████ ██████  ██   ██ ███████       ████   ███████ ██  ██████ \n```",
        "height": 140,
        "width": 1500,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        0
      ],
      "id": "575d1684-bcf2-4a8e-bd19-da84316d2d9b",
      "name": "Sticky Note31"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "2ce6eedd-cc88-4d50-b8a9-46f988ca1926",
              "name": "content",
              "value": "={{ $('Get Redis2').item.json.cacheMessage.map(item => item.parseJson().message).reverse().join('\\n') }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "7a0a7fa9-bd7c-4cbe-bf8d-11fa246de132",
      "name": "Set Message2",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        3620,
        1440
      ]
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $node['Settings v2'].json.base_url }}/{{ $node['Settings v2'].json.account_id }}/conversations/{{ $node['Settings v2'].json.conversation_id }}/messages",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "api_access_token",
              "value": "={{ $node['Settings v2'].json.dev_access_token }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json;charset=utf-8"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "content",
              "value": "={{ $json.json.message }}"
            },
            {
              "name": "message_type",
              "value": "outgoing"
            }
          ]
        },
        "options": {}
      },
      "id": "05f84e02-ff12-4985-8a54-e84e398dd70a",
      "name": "Chatwoot - SendMessage3",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        7440,
        1200
      ],
      "executeOnce": false,
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "content": "# Verifica o Tipo de Agente\n## Objetivo: Determinar se a conversa deve ser tratada por um agente humano ou pelo bot.\n\n## Chatwoot - Assign to Bot\n### Objetivo: Direcionar corretamente o atendimento.\n\n## Nodes typeMessage, agentType, checkFormat e editFields\n### Objetivo: Ajustar fluxo de acordo com o tipo de mensagem e contexto da conversa.",
        "height": 1461,
        "width": 669,
        "color": 2
      },
      "id": "c241031d-07ae-4c75-b78c-4588d74231c3",
      "name": "Sticky Note34",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1120,
        460
      ]
    },
    {
      "parameters": {
        "url": "={{ $('Settings v2').item.json.attachments[0].data_url }}",
        "options": {}
      },
      "id": "455fa359-109d-46ca-a8df-126ad47504dc",
      "name": "Get Audio4",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1920,
        960
      ],
      "retryOnFail": true
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "78b5c18c-808a-4b5c-bbbc-6e68d6c2e1c4",
              "name": "text",
              "value": "={{ $('Settings v2').item.json.message_text }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "17421a36-6342-4bbd-ad6c-aaa21d4d853e",
      "name": "Edit Fields4",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        1660,
        1280
      ]
    },
    {
      "parameters": {
        "content": "# Enviar Mensagem\n## Objetivo: Responder ao cliente com texto.\n\n## Set Response\n### Objetivo: Ajustar texto para envio.\n\n## Check Format / Loop Over Items\n### Objetivo: Garantir entregas corretas.\n\n## Chatwoot Send Message / Postgres Add to Followup / Wait\n### Objetivo: Fluxo contínuo de atendimento.",
        "height": 928,
        "width": 2013,
        "color": 5
      },
      "id": "ec3378c0-23a2-47aa-aa02-ff410f5bec17",
      "name": "Sticky Note35",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        6120,
        540
      ]
    },
    {
      "parameters": {
        "content": "# Tratamento de Áudio\n## Objetivo: Transcrever mensagens de áudio enviadas pelos clientes.\n\n## Get Audio\n### Objetivo: Disponibilizar arquivo para transcrição.\n\n## OpenAI - Transcribe Recording\n### Objetivo: Permitir interpretação e resposta pelo agente.\n\n## Normalize\n### Objetivo: Garantir consistência no processamento.",
        "height": 791,
        "width": 846,
        "color": 3
      },
      "id": "8966354a-e3df-4b62-a8a9-49196ef95361",
      "name": "Sticky Note36",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1800,
        460
      ]
    },
    {
      "parameters": {
        "content": "# Elimina Duplicidade\n## Redis - Check Message ID\n### Objetivo: Prevenir execução duplicada do fluxo.\n\n## IF Node (newMessage)\n### Objetivo: Evitar processamentos repetidos.\n\n## Redis - Push Message ID\n### Objetivo: Garantir controle de duplicidade.\n\n## Mensagem duplicada (ignorar)\n### Objetivo: Bloquear processamento redundante.",
        "height": 1459,
        "width": 529
      },
      "id": "4d34215b-54b1-4679-a5f2-f02edc413fe7",
      "name": "Sticky Note37",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        580,
        460
      ]
    },
    {
      "parameters": {
        "content": "# Enviar Presença\n## Objetivo: Simular digitação no WhatsApp.\n\n## WhatsApp API - Typing Indicator\n### Objetivo: Tornar a experiência mais humanizada.",
        "height": 1187,
        "width": 312
      },
      "id": "fdfb7093-df62-408c-b6be-0bbebf961ad5",
      "name": "Sticky Note39",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        3780,
        760
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "e9fc995b-a4aa-484d-94b7-cb823b830574",
              "name": "output",
              "value": "={{ $json.output.split(\"\\n\\n\").map(item => ({ json: { message: item } })) }}",
              "type": "array"
            }
          ]
        },
        "options": {}
      },
      "id": "25140182-0dff-47d6-9bae-a95eb1a85313",
      "name": "Set response3",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        6380,
        1060
      ]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "bd0f6971-8fea-4159-b6ff-aca489ff63e5",
              "name": "remoteJid",
              "value": "={{ $node['Settings v2'].json.channel }}::{{ $node['Settings v2'].json.contact_id }}",
              "type": "string"
            },
            {
              "id": "81e6df8a-3877-426b-8f28-9fc7504a27ae",
              "name": "message_id",
              "value": "=message-id::{{ $node['Settings v2'].json.message_id }}",
              "type": "string"
            },
            {
              "id": "bea1676f-6b8b-48c6-a3ef-f9a66d4ef3cd",
              "name": "timestamp",
              "value": "={{ $node['Settings v2'].json.message_created_at }}",
              "type": "string"
            },
            {
              "id": "700c4dd8-0820-43f6-a1ba-1c99595ee686",
              "name": "conversation_id",
              "value": "=conversation-id::{{ $node['Settings v2'].json.conversation_id }}",
              "type": "string"
            },
            {
              "id": "d893ddd3-584b-4ade-8cac-acbe315e0b98",
              "name": "message",
              "value": "={{ $json.text }}",
              "type": "string"
            },
            {
              "id": "1eb89858-7424-46d0-a997-0e4d115b0ea0",
              "name": "wait",
              "value": "={{ 25 }}",
              "type": "number"
            }
          ]
        },
        "options": {}
      },
      "id": "4c74bf9f-a1fd-45a6-9317-29a72c45b84e",
      "name": "NORMALIZE2",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2400,
        1060
      ]
    },
    {
      "parameters": {
        "amount": 1
      },
      "id": "426754d9-ccbd-4678-81d1-e1641165ec61",
      "name": "Wait4",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        3460,
        1640
      ],
      "webhookId": "41060c26-b5a0-4609-a0ff-71a0715a97cc"
    },
    {
      "parameters": {},
      "id": "cc4d0cba-aed9-4e3f-b0fd-873d448b87b2",
      "name": "No Operation, do nothing2",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        3460,
        1240
      ]
    },
    {
      "parameters": {
        "operation": "push",
        "list": "={{ $('NORMALIZE2').item.json.remoteJid }}",
        "messageData": "={{ $json.toJsonString() }}"
      },
      "id": "ff8f5e48-d90b-44fa-bd6f-3a97744caa20",
      "name": "Set Redis2",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        2780,
        1360
      ]
    },
    {
      "parameters": {
        "operation": "get",
        "propertyName": "cacheMessage",
        "key": "={{ $('NORMALIZE2').item.json.remoteJid }}",
        "keyType": "list",
        "options": {}
      },
      "id": "274a9c50-bfa9-449d-9c9f-94c184cf0835",
      "name": "Get Redis2",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        2960,
        1360
      ]
    },
    {
      "parameters": {
        "operation": "delete",
        "key": "={{ $('NORMALIZE2').item.json.remoteJid }}"
      },
      "id": "5d9887a6-78f7-4244-a748-d341a31f5408",
      "name": "Redis2",
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        3460,
        1440
      ]
    },
    {
      "parameters": {
        "content": "# Tempo de Espera (Debounce)\n## Objetivo: Evitar respostas múltiplas quando o cliente envia várias mensagens seguidas.\n\n## Set Redis / Get Redis\n### Objetivo: Controlar temporização de respostas.\n\n## Switch\n### Objetivo: Regular comportamento do fluxo.\n\n## Redis Delete / Wait\n### Objetivo: Preparar fluxo para próxima interação.\n\n",
        "height": 1179,
        "width": 1108
      },
      "id": "0a9f1422-3626-409f-9a32-b44d6367b167",
      "name": "Sticky Note40",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        2660,
        760
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "id": "3e0e2209-6f02-40a2-bd10-f7979955e409",
                    "leftValue": "={{ $('Settings v2').item.json.message_text }}",
                    "rightValue": "",
                    "operator": {
                      "type": "string",
                      "operation": "notEmpty",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "text"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "leftValue": "={{ $('Settings v2').item.json.attachments[0].file_type  }}",
                    "rightValue": "audio",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "4bfe8682-f119-4039-91ad-93f809743122"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "=audio"
            }
          ]
        },
        "options": {}
      },
      "id": "e6768afb-09cb-4bd9-91bb-ebd6b9bb3d1b",
      "name": "checkFormat6",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.1,
      "position": [
        6580,
        1060
      ]
    },
    {
      "parameters": {
        "operation": "upsert",
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "table": {
          "__rl": true,
          "value": "tb_followup",
          "mode": "list",
          "cachedResultName": "tb_followup"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "conversation_id": "={{ $json.conversation_id }}",
            "inbox_id": "={{ $node['Settings v2'].json.inbox_id }}",
            "contact_id": "={{ $node['Settings v2'].json.contact_id }}",
            "account_id": "={{ $node['Settings v2'].json.account_id }}",
            "agent_id": "=0",
            "message_id": "={{ $node['Settings v2'].json.message_id }}",
            "created_at": "={{ $now }}",
            "message_number": 1,
            "key": "={{ $('Settings v2').item.json.memory_key }}"
          },
          "matchingColumns": [
            "account_id",
            "inbox_id",
            "contact_id",
            "conversation_id"
          ],
          "schema": [
            {
              "id": "id",
              "displayName": "id",
              "required": false,
              "defaultMatch": true,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": true
            },
            {
              "id": "account_id",
              "displayName": "account_id",
              "required": true,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "inbox_id",
              "displayName": "inbox_id",
              "required": true,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "agent_id",
              "displayName": "agent_id",
              "required": true,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": false
            },
            {
              "id": "contact_id",
              "displayName": "contact_id",
              "required": true,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "message_id",
              "displayName": "message_id",
              "required": true,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": false
            },
            {
              "id": "conversation_id",
              "displayName": "conversation_id",
              "required": true,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": true,
              "removed": false
            },
            {
              "id": "whatsapp_number",
              "displayName": "whatsapp_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": false,
              "removed": true
            },
            {
              "id": "created_at",
              "displayName": "created_at",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "dateTime",
              "canBeUsedToMatch": false
            },
            {
              "id": "evo_url",
              "displayName": "evo_url",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false,
              "removed": true
            },
            {
              "id": "evo_instance",
              "displayName": "evo_instance",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false,
              "removed": true
            },
            {
              "id": "evo_apikey",
              "displayName": "evo_apikey",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false,
              "removed": true
            },
            {
              "id": "cw_inbox_token",
              "displayName": "cw_inbox_token",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false,
              "removed": true
            },
            {
              "id": "cw_agent_token",
              "displayName": "cw_agent_token",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false,
              "removed": true
            },
            {
              "id": "message_number",
              "displayName": "message_number",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "number",
              "canBeUsedToMatch": false,
              "removed": false
            },
            {
              "id": "key",
              "displayName": "key",
              "required": false,
              "defaultMatch": false,
              "display": true,
              "type": "string",
              "canBeUsedToMatch": false,
              "removed": false
            }
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "id": "3ab16ac8-a841-4050-8c8d-addc30b445e8",
      "name": "Postgres - Add to followup2",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.5,
      "position": [
        7620,
        1200
      ]
    },
    {
      "parameters": {
        "mode": "insert",
        "messages": {
          "messageValues": [
            {
              "type": "={{ $('checkFormat8').item.json.sender_type == \"Contact\"?\"system\":\"user\" }}",
              "message": "={{ $json.text }}"
            }
          ]
        }
      },
      "id": "13f9fe8e-8469-43c8-bb6b-e038dc9e4437",
      "name": "Chat Memory Manager2",
      "type": "@n8n/n8n-nodes-langchain.memoryManager",
      "typeVersion": 1.1,
      "position": [
        2360,
        2040
      ]
    },
    {
      "parameters": {
        "url": "={{ $('Webhook v2').first().json.body.messages[0].attachments[0].data_url }}",
        "options": {}
      },
      "id": "679e5587-58d7-474f-b2b9-cbc6730507a0",
      "name": "Get Audio5",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1980,
        1960
      ],
      "retryOnFail": true
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "78b5c18c-808a-4b5c-bbbc-6e68d6c2e1c4",
              "name": "text",
              "value": "={{ $('Settings v2').item.json.message_text }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "738302e6-1e55-4f7d-bbca-fd61cdefadb5",
      "name": "Edit Fields5",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        2000,
        2160
      ]
    },
    {
      "parameters": {
        "content": "## Stop AI\n\n- **Objetivo:** Esse bloco **filtra a execução** para impedir que a IA continue o atendimento quando um agente humano estiver assumindo a conversa.\n\n### **stopAI?2 (Filter Node)**\n- **Configuração típica:** Verificar se `agent_type === human` ou `assigned_to !== bot`.\n- **Objetivo:** Desviar o fluxo da IA em caso de atendimento manual.\n\n### **Chatwoot – Stop AI2**\n- **Objetivo:** Registrar ou aplicar o controle necessário para que a IA não interfira.\n\n> **Importante:** Este bloco não “pausa” a IA diretamente. Ele **impede que ela prossiga** no fluxo ao verificar o agente responsável atual.\n",
        "height": 748,
        "width": 432,
        "color": 2
      },
      "id": "ab9a1a35-42de-439a-be4b-dfbeddf6166a",
      "name": "Sticky Note41",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1360,
        1940
      ]
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Settings v2').item.json.memory_key }}"
      },
      "id": "a945f957-8c87-4cd3-8ab6-2b43dff4a76f",
      "name": "Postgres Chat Memory4",
      "type": "@n8n/n8n-nodes-langchain.memoryPostgresChat",
      "typeVersion": 1.1,
      "position": [
        2340,
        2220
      ]
    },
    {
      "parameters": {
        "content": "# Salvar Mensagem\n## Objetivo: Registrar mensagens para histórico e contexto futuro.\n\n## Get Audio\n### Objetivo: Processar informações multimodais.\n\n## OpenAI - Transcribe Recording\n### Objetivo: Armazenar conteúdo de áudio como texto.\n\n## Edit Fields\n### Objetivo: Preparar mensagem para armazenamento.\n\n## Chat Memory Manager + Postgres Chat Memory\n### Objetivo: Garantir histórico para consultas futuras e IA contextualizada.",
        "height": 1160,
        "width": 854,
        "color": 4
      },
      "id": "fb467330-228a-4af7-8d74-1a3cf6324aef",
      "name": "Sticky Note42",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        1800,
        1260
      ]
    },
    {
      "parameters": {
        "resource": "audio",
        "operation": "transcribe",
        "options": {}
      },
      "id": "20964f76-4fba-42b2-90d7-05efcb7f6095",
      "name": "OpenAI - Transcribe a Recording4",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.4,
      "position": [
        2180,
        1960
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "leftValue": "={{ $('Get Redis2').item.json.cacheMessage.last().parseJson().message_id }}",
                    "rightValue": "={{ $('NORMALIZE2').item.json.message_id }}",
                    "operator": {
                      "type": "string",
                      "operation": "notEquals"
                    },
                    "id": "a3d517df-d46b-4021-8ea3-7dca36de1b7e"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "ignore"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "id": "bceb1783-09f3-4ad6-b304-ecf584dcead7",
                    "leftValue": "={{ $('Get Redis2').item.json.cacheMessage.first().parseJson().timestamp.toDateTime('s') }}",
                    "rightValue": "={{ $now.minus($('NORMALIZE2').item.json.wait, 'seconds') }}",
                    "operator": {
                      "type": "dateTime",
                      "operation": "before"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "prosseguir"
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra",
          "renameFallbackOutput": "aguardar"
        }
      },
      "id": "6df86d11-fd30-4671-a1a2-2455ae5bb9ff",
      "name": "Switch3",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.1,
      "position": [
        3140,
        1360
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "leftValue": "={{ $('Settings v2').item.json.attachments[0].file_type == \"audio\" ? \"audio\" : \"\"   }}",
                    "rightValue": "audio",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "624e2843-3fe7-49d8-a0b8-05abd2eb7d89"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "=audio"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "id": "3e0e2209-6f02-40a2-bd10-f7979955e409",
                    "leftValue": "={{ $('Settings v2').item.json.message_text }}",
                    "rightValue": "",
                    "operator": {
                      "type": "string",
                      "operation": "notEmpty",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "text"
            }
          ]
        },
        "options": {}
      },
      "id": "ce5f3899-7d0b-45a0-8807-15370b43445c",
      "name": "checkFormat7",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.1,
      "position": [
        1520,
        1180
      ]
    },
    {
      "parameters": {
        "resource": "audio",
        "operation": "transcribe",
        "options": {}
      },
      "id": "9f37f4d5-e4d9-4565-a721-ede950970b3e",
      "name": "OpenAI - Transcribe a Recording5",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.4,
      "position": [
        2160,
        960
      ]
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "leftValue": "={{ $('Settings v2').item.json.attachments[0].file_type == \"audio\" ? \"audio\" : \"\"   }}",
                    "rightValue": "audio",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "c0eaaa53-f8f5-412f-a790-093aa80a0f54"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "=audio"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 1
                },
                "conditions": [
                  {
                    "id": "3e0e2209-6f02-40a2-bd10-f7979955e409",
                    "leftValue": "={{ $('Settings v2').item.json.message_text }}",
                    "rightValue": "",
                    "operator": {
                      "type": "string",
                      "operation": "notEmpty",
                      "singleValue": true
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "text"
            }
          ]
        },
        "options": {}
      },
      "id": "a507f5c1-8fa4-4182-afe0-101eb9272036",
      "name": "checkFormat8",
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.1,
      "position": [
        1580,
        1600
      ]
    },
    {
      "parameters": {
        "fieldToSplitOut": "output",
        "options": {}
      },
      "id": "4bfb9140-0cf3-4964-b18e-77023a6375d3",
      "name": "breakResponse2",
      "type": "n8n-nodes-base.splitOut",
      "typeVersion": 1,
      "position": [
        7040,
        1040
      ]
    },
    {
      "parameters": {
        "options": {}
      },
      "id": "ff1477b2-9b42-40f0-b055-b2bc15e7ff15",
      "name": "Loop Over Items2",
      "type": "n8n-nodes-base.splitInBatches",
      "typeVersion": 3,
      "position": [
        7260,
        1040
      ]
    },
    {
      "parameters": {
        "amount": "={{ $('Chatwoot - SendMessage3').item.json.content.length/1000*60 }}"
      },
      "id": "38fed2c3-1c87-4e44-bf39-2a56113559bc",
      "name": "Wait5",
      "type": "n8n-nodes-base.wait",
      "typeVersion": 1.1,
      "position": [
        7800,
        1200
      ],
      "webhookId": "76597508-61af-4769-92fa-8da6e067728f"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Settings v2').item.json.base_url }}/{{  $('Settings v2').item.json.account_id }}/conversations/{{  $('Settings v2').item.json.conversation_id }}/assignments",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json;charset=utf-8"
            },
            {
              "name": "api_access_token",
              "value": "={{ $node['Settings v2'].json.dev_access_token }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n\"assignee_id\": 11\n}",
        "options": {}
      },
      "id": "cedf0700-9966-46fa-9395-376e74de5715",
      "name": "Chatwoot - Stop AI2",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1600,
        2520
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "020efd22-52a5-42da-b505-1a540e14bd65",
              "leftValue": "={{ $(\"Supabase - Get lead by phone2\").item.json.id != null}}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        4360,
        1540
      ],
      "id": "44defb0f-4fc9-4eef-b692-c6a70861b22a",
      "name": "Lead existe2",
      "alwaysOutputData": false,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "tableId": "leads",
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "telefone",
              "fieldValue": "={{ $('Webhook v2').item.json.body.meta.sender.phone_number.replace(\"+\",\"\") }}"
            },
            {
              "fieldId": "status",
              "fieldValue": "Lead"
            },
            {
              "fieldId": "nome",
              "fieldValue": "={{ $('Webhook v2').item.json.body.meta.sender.name.split(\" \")[0] }}"
            },
            {
              "fieldId": "chatNome",
              "fieldValue": "={{ $('Webhook v2').item.json.body.meta.sender.name }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        4620,
        1640
      ],
      "id": "157b4d1e-41f7-4e31-a6f8-e788ccf24f6f",
      "name": "Criar Lead2",
      "alwaysOutputData": false,
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "operation": "get",
        "tableId": "leads",
        "filters": {
          "conditions": [
            {
              "keyName": "telefone",
              "keyValue": "={{ $('Settings v2').item.json.celPhone }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabase",
      "typeVersion": 1,
      "position": [
        4180,
        1720
      ],
      "id": "5abda9e7-a857-4cef-b5a7-f6db43fe036f",
      "name": "Supabase - Get lead by phone2",
      "alwaysOutputData": true
    },
    {
      "parameters": {
        "content": "# Buscar Dados do Lead\n## Objetivo: Obter ou criar dados do cliente na base.\n\n## Supabase - Get Lead by Phone\n### Objetivo: Identificar clientes existentes.\n\n## Lead Existe\n### Objetivo: Escolher entre atualizar dados ou criar lead.\n\n## Criar Lead\n### Objetivo: Registrar novos contatos.\n\n## Sort / Limit\n### Objetivo: Usar dados atualizados.\n\n## Set Lead Data\n### Objetivo: Preparar informações para a IA.",
        "height": 1180,
        "width": 1000
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4100,
        760
      ],
      "typeVersion": 1,
      "id": "c13ef97b-5dc1-43bc-8a1f-02d6c06a4f38",
      "name": "Sticky Note43"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $(\"Settings v2\").item.json.message_type }}",
                    "rightValue": "incoming",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "2b179c60-ead1-46ee-beb2-320679b97e32"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "incoming"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "2bca50b7-136c-42a9-a5d3-67668018159a",
                    "leftValue": "={{ $(\"Settings v2\").item.json.message_type }}",
                    "rightValue": "outgoing",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "outgoing"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        1140,
        1360
      ],
      "id": "db69fe9b-5c66-4ae6-b000-cbb885b69106",
      "name": "typeMessage2"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $(\"Settings v2\").item.json.agent_type }}",
                    "rightValue": "bot",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "a45be03e-8477-4d41-af71-4b5f5fb6717b"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "bot"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "957ae9fe-be55-4921-9d32-032e9745ff06",
                    "leftValue": "={{ $(\"Settings v2\").item.json.agent_type }}",
                    "rightValue": "human",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "human"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        1260,
        1180
      ],
      "id": "60240767-3276-49b4-bc53-313dee226ee9",
      "name": "agentType4"
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "id": "957ae9fe-be55-4921-9d32-032e9745ff06",
                    "leftValue": "={{ $(\"Settings v2\").item.json.agent_type }}",
                    "rightValue": "human",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "human"
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 2
                },
                "conditions": [
                  {
                    "leftValue": "={{ $(\"Settings v2\").item.json.agent_type }}",
                    "rightValue": "bot",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "a45be03e-8477-4d41-af71-4b5f5fb6717b"
                  }
                ],
                "combinator": "and"
              },
              "renameOutput": true,
              "outputKey": "bot"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.2,
      "position": [
        1260,
        1700
      ],
      "id": "9b66696e-2336-4357-9590-9917171436bd",
      "name": "agentType5"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "8278e142-b943-4c6f-ba6d-b4f6cbef97c1",
              "leftValue": "={{ $('Settings v2').item.json.stopAI }}",
              "rightValue": "outgoing",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "64ed1e3f-1f7b-4538-981d-9527dca7350a",
      "name": "stopAI?2",
      "type": "n8n-nodes-base.filter",
      "typeVersion": 2.2,
      "position": [
        1420,
        2520
      ]
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.limit",
      "typeVersion": 1,
      "position": [
        4700,
        1420
      ],
      "id": "1a0da73b-a26b-4856-9b81-bfa98e282261",
      "name": "Limit2"
    },
    {
      "parameters": {
        "sortFieldsUi": {
          "sortField": [
            {
              "fieldName": "id",
              "order": "descending"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.sort",
      "typeVersion": 1,
      "position": [
        4540,
        1420
      ],
      "id": "7ee28abe-ec3b-4c58-904a-50b80fe5efa6",
      "name": "Sort2"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "ed47e2c7-ad69-48de-8bc4-484f6456be20",
              "name": "nome",
              "value": "={{ $json.nome }}",
              "type": "string"
            },
            {
              "id": "70aae4e1-5528-4032-9d71-cb6f851e42d2",
              "name": "email",
              "value": "={{ $json.email }}",
              "type": "string"
            },
            {
              "id": "0e71515a-88d1-4ce0-ba89-6065f84dcb1c",
              "name": "telefone",
              "value": "={{ $json.telefone }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        4940,
        1540
      ],
      "id": "6eb71270-06d7-4ead-b6c2-0d2fd4edfb66",
      "name": "Set lead data2"
    },
    {
      "parameters": {
        "content": "# Recebe a Mensagem\n\n## Webhook v1\n### Configuração:\n- Método: POST\n\n- URL gerada deve ser configurada na aplicação de origem.\n\n- Ativar “Pin Data” para salvar dados de teste.\n\n### Objetivo: Iniciar o fluxo automaticamente ao receber mensagens de clientes.\n\n## Set Node\n### Objetivo: Organizar e normalizar dados para os próximos nodes.\n\n## Execution Data Node\n### Configuração:\n\n- Selecionar variáveis relevantes (ex.: message_id, telefone, mensagem).\n\n- Definir se os dados serão apenas exibidos ou utilizados em outros pontos.\n\n### Objetivo: Garantir rastreabilidade e facilitar a análise no histórico do N8N.\n\n",
        "height": 1359,
        "width": 569
      },
      "id": "0afcd77f-e839-4f80-a145-fc228539df62",
      "name": "Sticky Note44",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        0,
        200
      ]
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o",
          "mode": "list",
          "cachedResultName": "GPT-4O"
        },
        "messages": {
          "values": [
            {
              "content": "={{ $('AI Agent v2').item.json.output }}"
            },
            {
              "content": "=<objetivo>\nTransformar textos escritos em versões mais informais, naturais e conversacionais, otimizadas para serem enviadas como áudios com entonação emocional, pausas naturais e fluidez de fala. Além disso, normalizar os textos para leitura por mecanismos de TTS (Text-to-Speech), convertendo números, símbolos e abreviações em formas faladas, claras e compreensíveis.\n</objetivo>\n\n<contexto>\nEste agente é responsável por adaptar mensagens escritas para que soem como falas reais, prontas para serem gravadas em áudio por Renato, utilizando ferramentas de Text-to-Speech (TTS) ou gravações manuais.\n\nO conteúdo transformado deve soar como um áudio informal enviado por WhatsApp ou Instagram — com pausas naturais, entonação envolvente, ritmo agradável e expressões do dia a dia.\n\nAs técnicas recomendadas incluem:\n- Inserção de pausas naturais com `<break time=\"x.xs\" />`, com moderação (até 0.5 segundos).\n- Uso de figuras de linguagem, expressões orais e contrações (“tá”, “pra”, “cê”, etc.).\n- Escrita narrativa que guie emoção e ritmo.\n- Uso de marcações de emoção no estilo de roteiros: “eu falei sorrindo”, “respondi com animação”, etc.\n- Adaptação para pronúncia natural em português brasileiro, com variações ortográficas, se necessário (ex: “A.I.” pode virar “ei-ai”).\n</contexto>\n\n<limitacoes>\n- Nunca adicionar informações novas que não estão no texto original.\n- Não utilizar palavras ofensivas ou expressões regionais muito específicas.\n- Não exagerar nas pausas (limite recomendado: 3 por parágrafo).\n- Evitar sons ou efeitos escritos como “uh”, “ah”, “hmm”.\n- Não usar marcações de SSML que não sejam compatíveis com ElevenLabs.\n- **Nunca falar do Renato em terceira pessoa.** Ele é quem vai gravar o áudio, portanto, tudo deve ser escrito em primeira pessoa.\n</limitacoes>\n\n<estilo>\nTom leve, informal, empático e natural.\nFala como se estivesse mandando um áudio pra alguém próximo.\nPode usar expressões como “cara”, “então”, “tá ligado?”, “imagina só”, etc., desde que caibam no contexto e não soem forçadas.\nUsa frases curtas, respirações simuladas com pausas, e terminações que soem humanas — como perguntas leves e exclamações naturais.\nSempre escrito em primeira pessoa, como se o próprio Renato estivesse falando diretamente com o ouvinte.\n</estilo>\n\n<instrucoes>\n1. Leia o texto original e identifique trechos formais, engessados ou que possam causar ambiguidade ao serem lidos em voz alta.\n\n2. Reescreva com estilo oral: informal, direto, com frases que soem faladas.\n\n3. Normalize todos os elementos do texto para TTS, e também termos em inglês:\n   - **Números**: escreva por extenso. Ex: “R$ 42,50” → “quarenta e dois reais e cinquenta centavos”.\n   - **Datas**: converta para o formato falado com mês por extenso. Ex: “2024-01-01” → “primeiro de janeiro de dois mil e vinte e quatro”.\n   - **Horas**: converta com período do dia. Ex: “14:30” → “duas e meia da tarde”.\n   - **Porcentagens**: “100%” → “cem por cento”.\n   - **Frações**: “⅔” → “dois terços”.\n   - **Abreviações comuns**:\n     - “Dr.” → “Doutor”\n     - “Av.” ou “Ave.” → “Avenida”\n     - “St.” → “Rua” (ou “Santo/Santa” se for nome de santo)\n     - “Ctrl + Z” → “control zê”\n     - “AI” → “ei-ai”\n   - **Moedas e valores**:\n     - “$42.50” → “quarenta e dois dólares e cinquenta centavos”\n     - “£1,001.32” → “mil e um libras e trinta e dois pence”\n     - “100km” → “cem quilômetros”\n   - **Endereços e sites**:\n     - “123 Main St, Anytown, USA” → “cento e vinte e três rua Main, Anytown, Estados Unidos da América”\n     - “elevenlabs.io/docs” → “eleven labs ponto i o barra docs”\n   - **Números de telefone**: escreva dígito por dígito. Ex: “555-555-5555” → “cinco cinco cinco, cinco cinco cinco, cinco cinco cinco cinco”.\n   - **Números ordinais**:\n     - “2nd” → “segundo”\n     - “XIV” → “catorze” ou “décimo quarto” se for título.\n   - **Números decimais**:\n     - “3.14” → “três vírgula quatorze” (usar “vírgula” no lugar de “ponto” no português brasileiro)\n     - “3.5” → “três e meio”\n\n4. Use pausas naturais com `<break time=\"1.0s\" />` ou `<break time=\"1.5s\" />` SOMENTE em momentos de transição, surpresa ou conclusão.\n\n5. Se for relevante para o contexto, adicione marcações narrativas que guiem emoção (ex: “falei com empolgação”, “respondi mais calmo”, etc.).\n\n6. Use pontuação para simular entonação: reticências (...), travessões (—), vírgulas e interjeições.\n\n7. Finalize a nova versão com uma pergunta ou convite suave, mantendo o tom amigável.\n\n8. Certifique-se de que todo o texto esteja em primeira pessoa, como se Renato estivesse falando diretamente com quem vai ouvir.\n\n9. Retorne SOMENTE o texto final, sem nenhuma informação antes ou depois.\n</instrucoes>\n\n<exemplo>\nTexto original:\nA reunião foi marcada para 14:30 no dia 2024-01-01, na Av. Paulista, nº 123. O custo estimado é de R$ 42,50. Se quiser cancelar, aperte Ctrl + Z.\n\nTexto adaptado para áudio:\nA reunião tá marcada pra duas e meia da tarde, no dia primeiro de janeiro de dois mil e vinte e quatro... lá na Avenida Paulista, número cento e vinte e três. <break time=\"1s\" />\nO custo? Quarenta e dois reais e cinquenta centavos. <break time=\"1s\" />\nAh, e se quiser cancelar, é só apertar control zê.\n</exemplo>",
              "role": "system"
            }
          ]
        },
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.8,
      "position": [
        6520,
        1880
      ],
      "id": "352b008a-5fcf-4394-9f44-d63761181d84",
      "name": "Agente Audio2",
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.elevenlabs.io/v1/text-to-speech/xyz?output_format=opus_48000_64",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"voice_settings\": {\n    \"similarity_boost\": 1,\n    \"stability\": 0.5,\n    \"style\": 1.00,\n    \"speed\":1.00,\n    \"use_speaker_boost\": true\n  },\n  \"text\": \"{{ $json.message.content.replaceAll(\"\\n\",\"\").replace(/\"/g, '\\\\\"').replace(/\\n/g,'\\\\n') }}\",\n  \"model_id\": \"eleven_multilingual_v2\"\n}",
        "options": {}
      },
      "id": "deea385c-e5a7-421d-b40f-46883a028a4a",
      "name": "ElevenLabs2",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        6900,
        1880
      ]
    },
    {
      "parameters": {
        "content": "# Enviar Áudio\n## Objetivo: Enviar respostas da IA em formato de áudio.\n\n## Agente Áudio (Message Model)\n### Objetivo: Criar mensagens faladas.\n\n## ElevenLabs / WhatsApp Business Cloud / Chatwoot\n### Objetivo: Entregar resposta multimídia ao cliente.",
        "height": 608,
        "width": 2013,
        "color": 5
      },
      "id": "81d9ee49-e561-4615-b8bf-c0d49739063c",
      "name": "Sticky Note45",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        6120,
        1480
      ]
    },
    {
      "parameters": {
        "dataToSave": {
          "values": [
            {
              "key": "lead_phone",
              "value": "={{ $(\"Webhook v2\").item.json.body.meta.sender.phone_number.replaceAll(\"+\",\"\") }}"
            },
            {
              "key": "lead_name",
              "value": "={{ $('Webhook v2').item.json.body.meta.sender.name }}"
            },
            {
              "key": "message_type",
              "value": "={{ $json.message_type }}"
            },
            {
              "key": "agent_type",
              "value": "={{ $json.agent_type }}"
            },
            {
              "key": "inbox",
              "value": "={{ $json.inbox_id }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.executionData",
      "typeVersion": 1,
      "position": [
        280,
        1360
      ],
      "id": "bffd60db-9ae7-40d2-b323-8d82dea2ff22",
      "name": "Execution Data2",
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "operation": "get",
        "propertyName": "messageId",
        "key": "={{ $json.message_id }}",
        "keyType": "string",
        "options": {}
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        680,
        960
      ],
      "id": "60b74d3a-6848-4c87-a10f-97214e4b5f45",
      "name": "Redis - Check Message ID Existis2"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "loose",
            "version": 2
          },
          "conditions": [
            {
              "id": "ed859d32-8ce1-4efd-a469-6260f689ba3b",
              "leftValue": "={{ $json.messageId }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "empty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "looseTypeValidation": true,
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        680,
        1300
      ],
      "id": "3622bd7b-0bc5-4eab-bbf0-2ae42d1c5b5b",
      "name": "newMessage?2"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        680,
        1640
      ],
      "id": "30671bba-48b5-4f9b-b56f-7f6b90fb6262",
      "name": "Mensagem duplicada (Ignorar)2"
    },
    {
      "parameters": {
        "operation": "set",
        "key": "={{ $('Settings v2').item.json.message_id }}",
        "value": "={{ $('Settings v2').item.json.message_json }}",
        "keyType": "string",
        "expire": true,
        "ttl": 180
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        920,
        1320
      ],
      "id": "d435b9ea-d62a-4d3a-bad1-f349e7a9a13f",
      "name": "Redis - Push Message ID2"
    },
    {
      "parameters": {},
      "id": "9473d517-ad6c-4396-8d61-3fe31e1d5c39",
      "name": "Fim2",
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        7520,
        1020
      ]
    },
    {
      "parameters": {
        "resource": "media",
        "phoneNumberId": "291077834084907",
        "additionalFields": {
          "mediaFileName": "={{ $('Settings v2').item.json.celPhone }}_{{ $now.format('yyyyMMddHHmmss') }}"
        }
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1,
      "position": [
        7100,
        1880
      ],
      "id": "86199359-1cc9-4278-8cb8-0639742452e5",
      "name": "WhatsApp Business - Upload audio2",
      "webhookId": "dfbee11e-f91e-4fac-beb7-8637205a8290"
    },
    {
      "parameters": {
        "operation": "send",
        "phoneNumberId": "291077834084907",
        "recipientPhoneNumber": "=+{{ $('Settings v2').item.json.celPhone }}",
        "messageType": "audio",
        "mediaPath": "useMediaId",
        "mediaId": "={{ $json.id }}",
        "additionalFields": {}
      },
      "type": "n8n-nodes-base.whatsApp",
      "typeVersion": 1,
      "position": [
        7320,
        1880
      ],
      "id": "489c0b17-df68-4318-b343-aa55ec6cf47d",
      "name": "WhatsApp Business Cloud - Send audio2",
      "webhookId": "72edeec5-5ced-483d-a067-0baf1b8a8520"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://graph.facebook.com/v22.0/291077834084907/messages",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"messaging_product\": \"whatsapp\",\n  \"status\": \"read\",\n  \"message_id\": \"{{ $('Settings v2').item.json.whatsapp_message_id }}\",\n  \"typing_indicator\": {\n    \"type\": \"text\"\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        3880,
        1180
      ],
      "id": "7e25eae6-1b7b-443b-a39d-aa6dbe2b038f",
      "name": "WhatsApp API - Typing indicator2"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $node['Settings v2'].json.base_url }}/{{ $node['Settings v2'].json.account_id }}/conversations/{{ $node['Settings v2'].json.conversation_id }}/messages",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "api_access_token",
              "value": "={{ $node['Settings v2'].json.dev_access_token }}"
            },
            {
              "name": "Content-Type",
              "value": "application/json;charset=utf-8"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n\t\"content\": {{ JSON.stringify($('Agente Audio2').item.json.message.content) }},\n\t\"message_type\": \"outgoing\",\n    \"private\": true\n} ",
        "options": {}
      },
      "id": "d46dc50c-da8c-43de-af5b-b396a7c2516c",
      "name": "Chatwoot - Send note with audio transcription2",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        7520,
        1880
      ],
      "executeOnce": false,
      "retryOnFail": true,
      "waitBetweenTries": 5000
    },
    {
      "parameters": {
        "method": "POST",
        "url": "={{ $('Settings v2').item.json.base_url }}/{{  $('Settings v2').item.json.account_id }}/conversations/{{  $('Settings v2').item.json.conversation_id }}/assignments",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json;charset=utf-8"
            },
            {
              "name": "api_access_token",
              "value": "={{ $node['Settings v2'].json.dev_access_token }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n\"assignee_id\": 19\n}",
        "options": {}
      },
      "id": "22fc9a7b-3b8f-42e3-89ed-e28544bd3fe2",
      "name": "Chatwoot - Assign to bot2",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        1400,
        1020
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "d6f2c12d-3bc3-4a57-9be4-972a3840cd55",
              "leftValue": "={{ $('AI Agent v2').item.json.output }}",
              "rightValue": "https://",
              "operator": {
                "type": "string",
                "operation": "contains"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        6820,
        1280
      ],
      "id": "b2616776-48fd-48da-80b7-ab0359f6eb5d",
      "name": "Tem link?1"
    },
    {
      "parameters": {
        "content": "# Agent with Memory\n## Objetivo: Responder com base no contexto, histórico e dados adicionais.\n\n## AI Agent v2\n### Objetivo: Fornecer atendimento inteligente.\n\n## OpenAI Chat Model\n### Objetivo: Criar respostas contextuais.\n\n## Postgres Chat Memory\n### Objetivo: Melhorar a consistência da IA.\n\n## Supabase Vector Store + Embeddings\n### Objetivo: Enriquecer respostas.\n\n",
        "height": 1397,
        "width": 970,
        "color": 6
      },
      "id": "35285c0f-119b-488f-ae2c-e6c9a3c4b3d7",
      "name": "Sticky Note50",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        5120,
        540
      ]
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "value": "gpt-4.1",
          "mode": "list",
          "cachedResultName": "gpt-4.1"
        },
        "options": {
          "responseFormat": "text",
          "temperature": 1,
          "topP": 1
        }
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.2,
      "position": [
        5180,
        1500
      ],
      "id": "1f91ff10-cd45-444a-bc96-9d3c8974d21b",
      "name": "OpenAI Chat Model8"
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Webhook v2').item.json.body.meta.sender.phone_number.replace(\"+\",\"\") }}",
        "contextWindowLength": 50
      },
      "type": "@n8n/n8n-nodes-langchain.memoryPostgresChat",
      "typeVersion": 1.3,
      "position": [
        5300,
        1660
      ],
      "id": "a99ede1d-bb37-485e-a6c0-fe714e884c40",
      "name": "Postgres Chat Memory6"
    },
    {
      "parameters": {
        "mode": "retrieve-as-tool",
        "toolName": "query_database",
        "toolDescription": "Utilize esta ferramenta para responder todas as dúvidas ou mensagens do usuário. Não importa qual seja o assunto, utilize esta ferramenta antes de responder qualquer pergunta ou mensagem.\n\nCaso não encontre a resposta, retorne \"Não sei responder\"",
        "tableName": {
          "__rl": true,
          "value": "faq_vec",
          "mode": "list",
          "cachedResultName": "faq_vec"
        },
        "topK": 10,
        "options": {
          "queryName": "match_faq"
        }
      },
      "type": "@n8n/n8n-nodes-langchain.vectorStoreSupabase",
      "typeVersion": 1.1,
      "position": [
        5480,
        1580
      ],
      "id": "b3c0c860-f49b-46b0-bda0-a43da88dae97",
      "name": "Supabase Vector Store4"
    },
    {
      "parameters": {
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "typeVersion": 1.2,
      "position": [
        5520,
        1780
      ],
      "id": "99117971-c697-48a9-9858-e4aca3c10f98",
      "name": "Embeddings OpenAI4"
    },
    {
      "parameters": {
        "toolDescription": "Chame esta ferramenta apenas quando o usuário informar explicitamente a vontade de conversar com uma pessoa de verdade ou um atendente humano.",
        "method": "POST",
        "url": "={{ $('Settings v2').item.json.base_url }}/{{  $('Settings v2').item.json.account_id }}/conversations/{{  $('Settings v2').item.json.conversation_id }}/assignments",
        "sendHeaders": true,
        "parametersHeaders": {
          "values": [
            {
              "name": "api_access_token",
              "valueProvider": "fieldValue",
              "value": "={{ $('Settings v2').item.json.dev_access_token }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n\"assignee_id\": 11\n}"
      },
      "type": "@n8n/n8n-nodes-langchain.toolHttpRequest",
      "typeVersion": 1.1,
      "position": [
        5880,
        1480
      ],
      "id": "384db68b-ac34-4f9d-bb13-424d1550a11c",
      "name": "Atribuir conversa a humano3"
    },
    {
      "parameters": {
        "toolDescription": "Utilize esta ferramenta para adicionar notas na conversa.",
        "method": "POST",
        "url": "={{ $('Settings v2').item.json.base_url }}/{{  $('Settings v2').item.json.account_id }}/conversations/{{  $('Settings v2').item.json.conversation_id }}/messages",
        "sendHeaders": true,
        "parametersHeaders": {
          "values": [
            {
              "name": "api_access_token",
              "valueProvider": "fieldValue",
              "value": "={{ $('Settings v2').item.json.dev_access_token }}"
            }
          ]
        },
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={\n  \"content\": \"{resume}\",\n  \"message_type\": \"outgoing\",\n  \"private\": true\n}",
        "placeholderDefinitions": {
          "values": [
            {
              "name": "resume",
              "description": "Detailed resume of conversation between lead and AI"
            }
          ]
        }
      },
      "id": "fc33d814-4ec5-4766-8bb1-f835c78f48ee",
      "name": "Adicionar nota3",
      "type": "@n8n/n8n-nodes-langchain.toolHttpRequest",
      "position": [
        5940,
        1320
      ],
      "typeVersion": 1
    },
    {
      "parameters": {
        "descriptionType": "manual",
        "toolDescription": "Chame esta ferramenta quando o usuário informar o nome dele, corrigir o nome ou quando a IA tiver um contexto da conversa suficiente para identificar o objetivo, interesse e um resumo interessante que contenha as informações do objetivo e interesse. \n\n1. Objetivo: O usuário tem interesse em aprender sobre:\na. Criar aplicativos\nb. Construir agentes de IA\nc. Criar aplicativos e construir agentes de IA\n\n2. Interesse: O usuário tem interesse em aprender para:\na. Implementar na própria empresa\nb. Empreender\nc. Se tornar um desenvolvedor",
        "operation": "update",
        "tableId": "leads",
        "matchType": "allFilters",
        "filters": {
          "conditions": [
            {
              "keyName": "telefone",
              "condition": "eq",
              "keyValue": "={{ $('Webhook v2').item.json.body.meta.sender.phone_number.replace(\"+\",\"\") }}"
            }
          ]
        },
        "fieldsUi": {
          "fieldValues": [
            {
              "fieldId": "chatNome",
              "fieldValue": "={{ $fromAI('name', `Nome informado pelo lead.`, 'string') }}"
            },
            {
              "fieldId": "chatResumo",
              "fieldValue": "={{ $fromAI('resume', `Resumo da conversa com o lead. Deve conter informações do objetivo e interesse do usuário na plataforma sem codar.`, 'string') }}"
            },
            {
              "fieldId": "interesse",
              "fieldValue": "={{ $fromAI('interesse', ` Interesse do usuário na Comunidade Sem Codar: Implementar na própria empresa, Empreender ou Se tornar um desenvolvedor`, 'string') }}"
            }
          ]
        }
      },
      "type": "n8n-nodes-base.supabaseTool",
      "typeVersion": 1,
      "position": [
        5780,
        1680
      ],
      "id": "1d7956d0-1d54-4f32-a584-1f4cae5701bc",
      "name": "update_lead_information3"
    },
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "9a2f55df-244b-4c35-bd4f-6031723cdd8f",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        100,
        1120
      ],
      "id": "585ccc5e-6e09-4f5c-b260-b84a6bff1ba3",
      "name": "Webhook v2",
      "webhookId": "9a2f55df-244b-4c35-bd4f-6031723cdd8f"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "235e92af-e2b3-4508-8528-c0970661cd25",
              "name": "base_url",
              "value": "=-",
              "type": "string"
            },
            {
              "id": "4156a388-7649-4f41-8214-2445528e6e62",
              "name": "dev_access_token",
              "value": "=-",
              "type": "string"
            },
            {
              "id": "cd44a8d3-0144-45f8-a709-996049651bbe",
              "name": "ai_access_token",
              "value": "=-",
              "type": "string"
            },
            {
              "id": "29c2731d-3e47-4614-8941-65a09274c632",
              "name": "memory_key",
              "value": "={{ $json.body.messages[0].account_id }}::{{ $json.body.contact_inbox.inbox_id }}::{{ $json.body.contact_inbox.contact_id }}::{{ $json.body.messages[0].conversation_id }}",
              "type": "string"
            },
            {
              "id": "eb5cdad0-e58f-47d0-8bb1-40f635887179",
              "name": "account_id",
              "value": "={{ $json.body.messages[0].account_id }}",
              "type": "string"
            },
            {
              "id": "3577fc7f-4bdc-49ad-b5ad-ae052ef5bb50",
              "name": "conversation_id",
              "value": "={{ $json.body.messages[0].conversation_id }}",
              "type": "string"
            },
            {
              "id": "763f48ee-cf5d-4ce3-baa9-3743293277e1",
              "name": "inbox_id",
              "value": "={{ $json.body.messages[0].inbox_id }}",
              "type": "string"
            },
            {
              "id": "e9a05a72-6511-45e6-add6-6eb2ce3f66a5",
              "name": "contact_id",
              "value": "={{ $json.body.contact_inbox.contact_id }}",
              "type": "string"
            },
            {
              "id": "a3972fab-6ebd-4c4b-9c62-0966bda14fe2",
              "name": "message_id",
              "value": "={{ $json.body.messages[0].id }}",
              "type": "string"
            },
            {
              "id": "c60605a6-631b-44ad-92b2-d19d5d40fcd5",
              "name": "message_text",
              "value": "={{ $json.body.messages[0].content }}",
              "type": "string"
            },
            {
              "id": "37d69c9c-447e-425f-b3f0-16c7e49cce7e",
              "name": "message_type",
              "value": "={{ $json.body.messages[0].message_type == 0? \"incoming\" : \"outgoing\" }}",
              "type": "string"
            },
            {
              "id": "58273edd-faf4-47dc-ab84-7ad50c46783e",
              "name": "celPhone",
              "value": "={{ $json.body.meta.sender.phone_number.replaceAll(\"+\",\"\") }}",
              "type": "string"
            },
            {
              "id": "7a890deb-4a20-4775-9dfc-521730fbabfa",
              "name": "conversation_status",
              "value": "={{ $json.body.status }}",
              "type": "string"
            },
            {
              "id": "0788a159-9d95-4803-ae52-1f9f7cdc3845",
              "name": "sender_type",
              "value": "={{ $json.body.messages[0].sender_type }}",
              "type": "string"
            },
            {
              "id": "a710ae4b-0b4f-4215-8e09-94356a9df25c",
              "name": "labels",
              "value": "={{ $json.body.labels }}",
              "type": "array"
            },
            {
              "id": "05e89c05-e2e6-4261-94d5-5c2805d539bd",
              "name": "channel",
              "value": "={{ $json.body.channel }}",
              "type": "string"
            },
            {
              "id": "ed9ad306-88be-491f-a3b2-1073503ee049",
              "name": "message_created_at",
              "value": "={{ $json.body.messages[0].created_at }}",
              "type": "number"
            },
            {
              "id": "3f37b39c-dc76-4a7c-91b6-8aebcb988627",
              "name": "stopAI",
              "value": "={{ $json.body.messages[0].sender_type == \"User\" && $json.body.messages[0].conversation.assignee_id == 14 && $json.body.messages[0].sender_id != 14 }}",
              "type": "boolean"
            },
            {
              "id": "2b508358-8f2e-468a-a64c-c56d860611b7",
              "name": "attachments",
              "value": "={{ $json.body.messages[0].attachments }}",
              "type": "array"
            },
            {
              "id": "4b04d29d-08f8-4f62-ac7b-6f4de77171c0",
              "name": "thread",
              "value": "={{ $json.body.meta.sender.custom_attributes.thread?? \"thread\" }}",
              "type": "string"
            },
            {
              "id": "593de9ea-3fc7-4a13-882e-f44432325c3e",
              "name": "message_json",
              "value": "={{ $json.body.messages[0].toJsonString() }}",
              "type": "string"
            },
            {
              "id": "48c44889-ca54-457f-8de2-c58cbd0b5bb2",
              "name": "telBot",
              "value": "5548988048617",
              "type": "string"
            },
            {
              "id": "d6ded911-c5c3-48d4-85ab-2e9de7356139",
              "name": "whatsapp_message_id",
              "value": "={{ $json.body.messages[0].source_id }}",
              "type": "string"
            },
            {
              "id": "09f75d3a-44f6-4af2-8015-3b2f282db9f1",
              "name": "agent_type",
              "value": "={{ [null, 14, 19, 20, 21].includes($json.body.meta.assignee?.id) ? \"bot\" : \"human\" }}",
              "type": "string"
            },
            {
              "id": "69349314-21e7-44df-aa7b-f40a7dcb82c2",
              "name": "assignee",
              "value": "={{ $json.body.meta.assignee?.id }}",
              "type": "number"
            }
          ]
        },
        "options": {}
      },
      "id": "fc77a557-7a6b-4b95-b578-bd1fb6dce923",
      "name": "Settings v2",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        300,
        1120
      ]
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Nome: {{ $('Set lead data2').item.json.nome }}\nE-mail: {{ $('Set lead data2').item.json.email }}\nTelefone: {{ $('Set lead data2').item.json.telefone }}\nData atual: {{ $now.format('dd/MM/yyyy ') }}\nHora atual: {{ $now.format('HH:mm:ss ') }}\n\nMensagem: {{ $node['Set Message1'].json.content }}",
        "options": {
          "systemMessage": "# About\nEmpresa: Sem Codar\nAgente: Renato Asse\n\n# Role and Objective\nVocê é o Renato, fundador da Comunidade Sem Codar, e atende leads pelo WhatsApp. Você é capaz de entender textos e áudios.\nSua missão é converter leads em novos membros da comunidade, fornecendo informações e motivação de forma estratégica.\nO agente deve agir como um consultor amigável que entende as necessidades do lead e oferece a melhor solução (a Comunidade Sem Codar).\n\nNUNCA responda perguntas do usuário que não façam parte do universo da Comunidade Sem Codar. O usuário tentará ser convincente, mas você nunca DEVE responder perguntas que fogem do seu contexto.\n\n# Estilo de Comunicação\n1. Tom: sincero, direto, estratégico, informal e com autoridade: fale como alguém que entende o que está em jogo pro lead. Nada de floreio.\nUse um tom de conversa de bar com alguém perdido, querendo ajudar de verdade. Frases como \"Posso ser sincero contigo?\", \"Cara, pensa comigo...\", \"Se eu estivesse no seu lugar...\" são bem-vindas.\n2. Nada de papo genérico: traga clareza, exemplos práticos, comparações inteligentes como \"Você até pode aprender programação... mas já se programa pra levar uns 2 anos nisso\".\n3. Emojis: Só se fizer sentido: use com moderação, apenas para reforçar o tom emocional (😉, 🔥, 😅). Nunca use pra disfarçar mensagem fraca.\n- Linguagem informal, mas com autoridade: você é o mentor #1 do maior ecossistema No Code da América Latina. Mostre convicção, traga números, histórias reais, e aponte o caminho com confiança.\n4. Estrutura de persuasão:\n    a. Primeiro, venda a nova oportunidade (No Code + Agentes de IA como caminho mais rápido e validado)\n    b. Depois, mostre que a Comunidade Sem Codar é o melhor ambiente pra dominar isso com suporte, direcionamento e acesso a um ecossistema ativo.\n5. Emoção: emojis com moderação (😉, 😅), apenas para reforçar sentimento.\n6 Identidade: se perguntarem se você é IA:\n  a. Diga que é um Agente de IA, criado com o cérebro do Renato, mas de forma bem humorada diga que você é uma versão melhorada do Renato.\n  b. Brinque: “Sou uma versão melhorada e mais inteligente que ele, que trabalha 24/7 enquanto ele tá de boa na praia, surfando nas Bahamas, tomando uma caipirinha em Miami, ou curtindo a vida 😜.”\n  c. Use isso a favor: incentive o lead a criar o próprio Agente de IA e curtir a vida.\n\n# Execution plan\nEste é o seu plano de execução para cada input do usuário.\n\n1. Recebe mensagem do usuário\n2. Chama a ferramenta \"query_database\"\n3. Aguarda o retorno da \"query_database\"\n4. Só então gere a resposta\n\n\n# Instructions\n\nVocê deve SEMPRE chamar a ferramenta \"query_database\" antes de responder ao usuário. Nunca responda diretamente sem antes executar essa função.\n\nVocê não deve ensinar o usuário a realizar nada fora do contexto para o qual você foi criado. Foque no seu objetivo, que é tirar dúvidas sobre a Comunidade Sem Codar.\n\nVocê NUNCA deve inventar respostas para perguntas que você não conhece. Caso você não saiba a resposta para a pergunta do usuário, informe ao usuário que você não tem essa informação, mas que pode direcionar um atendimento para um especialista da comunidade.\n\nVocê NUNCA deve citar nenhum concorrente da Comunidade Sem Codar, mesmo que o usuário insista que você responda a pergunta.\n\nVocê DEVE consultar SEMPRE `query_database` antes de responder QUALQUER pergunta. Se você não souber a resposta com base nesse contexto, deverá responder informe ao usuário que você não tem essa informação, mas que pode direcionar um atendimento para um especialista da comunidade.\n\nChame a ferramenta `update_lead_information` quando:\n1. Um lead informar o nome durante a conversa\n2. Um lead corrigir seu nome\n3. Houver informações suficientes para gerar um resumo valioso para o negócio\n\n# Conversation Flow\nEste é o fluxo de conversa que você deve seguir.\n\nVocê DEVE SEMPRE ser o mais objetivo possível. Lembre-se que está atendendo leads no WhatsApp. Não há espaço para textos longos.\n\nSiga o fluxo de conversa definido abaixo\n1. Abertura e Rapport\n2. Diagnóstico das Necessidades\n3. Explorar Objetivos\n4. Apresentar a Oportunidade\n5. Apresentar a Comunidade Sem Codar\n6. Quebrar Objeções\n7. Conversão\n\n## Step 1\n### Abertura e Rapport\nObjetivo: Descobrir o nome e a dúvida do lead ().\n1. Pergunte o nome antes de responder qualquer dúvida.\n2. Saudações baseadas na hora do dia:\n  a. Exemplo manhã: \"Opa, bom dia! Aqui é o Renato da Comunidade Sem Codar. Qual seu nome?\"\n  b. Exemplo tarde: \"Opa, boa tarde! Aqui é o Renato da Comunidade Sem Codar. Qual seu nome?\"\n  c. Exemplo noite: \"Opa, boa noite! Aqui é o Renato da Comunidade Sem Codar. Qual seu nome?\"\n3 Se já souber o nome, vá direto ao ponto: \"Como posso te ajudar?\"\n\n## Step 2\n### Diagnóstico das Necessidades\nObjetivo: Entender se o lead quer criar Aplicativos, Agentes de IA ou ambos.\nPergunta: \"Você quer aprender a criar Aplicativos, Agentes de IA, ou os dois?\"\n\n## Step 3\n### 3. Explorar Objetivos\nObjetivo: Descobrir o objetivo do lead com o aprendizado.\nPergunta depende do passo anterior (adapte):\n1. Criar SaaS\n2. Trabalhar como desenvolvedor\n3. Atuar como gestor de IA\n4. Implementar na empresa\n\n## Step 4\n### 4. Apresentar a Oportunidade\nObjetivo: Mostrar que No Code é o caminho mais inteligente pra quem quer criar apps.\nUse comparações:\n1. \"Você pode aprender programação do zero... mas vai levar anos.\"\n2.  \"Com No Code, você faz em dias o que levaria meses.\"\n3. Finalize: \"Faz sentido isso pra você?\"\n\n## Step 5\n### 5. Apresentar a Comunidade Sem Codar\nObjetivo: Apresentar a Comunidade Sem Codar como melhor caminho.\nAdapte com base no perfil do lead:\n1. Empreendedor de SaaS\n2. Desenvolvedor No Code\n3. Gestor de IA\n4. Empresário que quer IA no negócio\n\nVocê DEVE trazer os benefícios certos, a trilha ideal, acesso à Acheumdev, mentorias e comunidade.\nVocê NUNCA deve criar, inventar ou utilizar alguma informação externa a sua base de conhecimento.\nVocê deve usar sua base de conhecimento através da ferramenta \"query_database\".\n\n\nPergunte: \"Ficou alguma dúvida ou já quer se inscrever?\"\n\n## Step 6\n### 6. Quebrar Objeções\nObjetivo: Quebrar objeções. Valide a dúvida, responda com dados, autoridade, histórias, e fale da garantia de 15 dias.\n  - Ex: “Temos garantia de 15 dias.”  \n  - Ex: “Muita gente pensava igual e hoje já lançaram seus apps.”\n\nVocê NUNCA deve criar, inventar ou utilizar alguma informação externa a sua base de conhecimento.\nVocê deve usar sua base de conhecimento através da ferramenta \"query_database\".\n\n## step 7\n### 7. Conversão\nObjetivo: Enviar o link e incentivar a inscrição. \n1. Exemplos:\n  a. “Bora entrar na comunidade e criar seu primeiro agente ainda este mês?”  \n  b. “Enquanto falamos, você já poderia estar desenvolvendo seu app.\n  \nVocê NUNCA deve criar, inventar ou utilizar alguma informação externa a sua base de conhecimento.\nVocê deve usar sua base de conhecimento através da ferramenta \"query_database\".\n\n\n# Persuasion techniques\n1. Storytelling e Prova Social\n2. Gatilhos mentais: Urgência, Escassez, Autoridade, Segurança\n3. Frases com impacto: \"Você já viu resultado só com os conteúdos gratuitos... imagina com a Comunidade.\"\n\nVocê NUNCA deve criar, inventar ou utilizar alguma informação externa a sua base de conhecimento.\nVocê deve usar sua base de conhecimento através da ferramenta \"query_database\".\n\n# Call to action\nQuando o lead não tiver mais dúvidas, direcione para a inscrição, adaptando conforme o desejo do lead.\nExemplos:\n  - \"Bora entrar na comunidade e criar seu primeiro agente ainda este mês?\"\n  - \"Enquanto falamos, você já poderia estar desenvolvendo seu app. Bora começar?\"\n\nVocê NUNCA deve criar, inventar ou utilizar alguma informação externa a sua base de conhecimento.\nVocê deve usar sua base de conhecimento através da ferramenta \"query_database\"."
        }
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.9,
      "position": [
        5520,
        1200
      ],
      "id": "94f19422-3255-42b3-a92d-16063a4822df",
      "name": "AI Agent v2"
    },
    {
      "parameters": {
        "content": "## 🎯 Objetivo Geral do Fluxo\nO fluxo “Agente de Vendas V2.0” tem como objetivo orquestrar um atendimento inteligente via canais como WhatsApp e CRM, alternando entre IA e agentes humanos. Ele gerencia desde o recebimento de mensagens até resposta com histórico contextual, transcrição de áudios, verificação de duplicidade, roteamento e persistência de dados.\n\n## 🛠 Ferramentas e Serviços Utilizados\n- n8n (plataforma principal de automação)\n\n- Redis (controle de duplicidade e debounce)\n\n- Supabase (armazenamento e vetorização de dados)\n\n- Chatwoot (gerenciador de atendimento humano e IA)\n\n- OpenAI API (transcrição e geração de resposta)\n\n- ElevenLabs API (geração de áudio a partir de texto)\n\n- WhatsApp Business API (envio de digitação e mensagens)\n\n- PostgreSQL (memória de chat e follow-ups)\n\n## ✅ Pré-requisitos\n### Antes de executar o fluxo, é necessário:\n#### Configurar credenciais de:\n- Redis ([Link para aula da Comunidade Sem Codar](https://comunidade.semcodar.com.br/aula/redis-02c-credenciaisn8n))\n\n- Supabase ([Link para aula da Comunidade Sem Codar](https://comunidade.semcodar.com.br/aula/n8ncrm-03f-credencialsupabase))\n\n- OpenAI ([Link para aula da Comunidade Sem Codar]())\n\n- Chatwoot ([Link para a documentação do Chatwoot](https://developers.chatwoot.com/api-reference/introduction))\n\n- ElevenLabs ([Link para a documentação do ElevenLabs](https://elevenlabs.io/docs/overview))\n\n- PostgreSQL (supabase) ([Link para aula da Comunidade Sem Codar](https://comunidade.semcodar.com.br/aula/n8nsaaswpp-02d-postgressupabase))\n\n## Observação: \nSe você não usa um CRM, veja as [aulas deste módulo](https://comunidade.semcodar.com.br/aula/n8nhuman-01a-intro) que mostramos como fazer a atribuição de agentes e intervenção humana usando somente o Redis. \n",
        "height": 960,
        "width": 780,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -800,
        200
      ],
      "typeVersion": 1,
      "id": "4bad07af-2fea-4853-b87b-dd7174dcd6d7",
      "name": "Sticky Note1"
    },
    {
      "parameters": {
        "content": "## 📄 Tabela: `leads`\n**O que é:** Lista principal de leads cadastrados.  \n\n**Para que serve:** Centralizar informações básicas e o status atual de cada lead.  \n\n**Principais colunas:**  \n- `nome`, `email`, `telefone`: dados de contato.  \n- `status`: situação do lead (ex.: Lead, Cliente, Prospect).  \n- `interesse`: produto ou serviço de interesse.  \n- `info`: campo em JSON para informações adicionais.  \n- `chatNome`, `chatStatus`, `chatResumo`: dados complementares vindos do atendimento via chat.  \n\n**Código da tabela:**\n```\ncreate table public.leads (\n  id bigint generated by default as identity not null,\n  created_at timestamp with time zone not null default now(),\n  nome text null,\n  email text null,\n  status public.lead_status not null default 'Lead'::lead_status,\n  interesse text null,\n  telefone text null,\n  info jsonb null,\n  \"chatNome\" text null,\n  \"chatStatus\" text null,\n  \"chatResumo\" text null,\n  constraint leads_pkey primary key (id)\n) TABLESPACE pg_default;\n```\n---\n\n## 📄 Tabela: `leads_eventos`\n**O que é:** Armazena os eventos e interações relacionados a um lead.  \n\n**Para que serve:** Guardar informações sobre campanhas, origem do lead, conversões e resumos de conversas.  \n\n**Principais colunas:**  \n- `lead`: referência ao ID do lead na tabela `leads`.  \n- `tipo`: tipo do evento (ex.: visita, clique, mensagem recebida).  \n- `utm_*`: parâmetros de campanha (source, medium, campaign, etc.).  \n- `conversion`: registra o tipo de conversão realizada.  \n- `chatResumo`: resumo de conversas ou interações.  \n\n**Código da tabela:**\n```\ncreate table public.leads_eventos (\n  id bigint generated by default as identity not null,\n  created_at timestamp with time zone not null default now(),\n  lead bigint null,\n  tipo text null,\n  utm_campaign text null,\n  utm_medium text null,\n  utm_source text null,\n  utm_term text null,\n  utm_content text null,\n  conversion text null,\n  aff text null,\n  \"chatResumo\" text null,\n  constraint leads_eventos_pkey primary key (id),\n  constraint leads_eventos_lead_fkey foreign KEY (lead) references leads (id)\n) TABLESPACE pg_default;\n```\n---\n\n## 📄 Tabela: `tb_followup`\n**O que é:** Agenda e controle de mensagens de acompanhamento (follow-up) no atendimento.  \n\n**Para que serve:** Organizar e registrar envios programados de mensagens para leads.  \n\n**Principais colunas:**  \n- `account_id`, `inbox_id`, `agent_id`, `contact_id`, `conversation_id`: identificadores do Chatwoot para saber onde e com quem o follow-up será feito.  \n- `message_id`, `message_number`: controle da mensagem que será enviada.  \n- `whatsapp_number`: número do WhatsApp do lead.  \n- `evo_url`, `evo_instance`, `evo_apikey`: credenciais para integração com o provedor de envio.  \n- `cw_inbox_token`, `cw_agent_token`: tokens de autenticação no Chatwoot.  \n\n**Código da tabela:** \n```\nCREATE TABLE public.tb_followup (\n    id bigserial NOT NULL,\n    account_id int8 NOT NULL,\n    inbox_id int8 NOT NULL,\n    agent_id int8 NOT NULL,\n    contact_id int8 NOT NULL,\n    message_id int8 NOT NULL,\n    conversation_id int8 NOT NULL,\n    whatsapp_number int8 NULL,\n    created_at timestamptz DEFAULT now() NULL,\n    evo_url varchar(255) NULL,\n    evo_instance varchar(50) NULL,\n    evo_apikey varchar(100) NULL,\n    cw_inbox_token varchar(100) NULL,\n    cw_agent_token varchar(100) NULL,\n    message_number int2 DEFAULT 1 NULL,\n    \"key\" varchar NULL,\n    CONSTRAINT \"tb_followup _pkey\" PRIMARY KEY (id),\n    CONSTRAINT tb_followup_un UNIQUE (account_id, inbox_id, contact_id, conversation_id)\n);\n```",
        "height": 2000,
        "width": 1060,
        "color": 4
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1880,
        200
      ],
      "typeVersion": 1,
      "id": "abd1b678-bcee-43d2-89f6-4603b8b95e30",
      "name": "Sticky Note2"
    }
  ],
  "pinData": {
    "Webhook v2": [
      {
        "json": {
          "headers": {
            "host": "whcsc.nocode.dev.br",
            "user-agent": "rest-client/2.1.0 (linux-musl x86_64) ruby/3.3.3p89",
            "content-length": "2886",
            "accept": "application/json",
            "accept-encoding": "gzip;q=1.0,deflate;q=0.6,identity;q=0.3",
            "content-type": "application/json",
            "x-forwarded-for": "172.18.0.1",
            "x-forwarded-host": "whcsc.nocode.dev.br",
            "x-forwarded-port": "443",
            "x-forwarded-proto": "https",
            "x-forwarded-server": "traefik_traefik.1",
            "x-real-ip": "172.18.0.1"
          },
          "params": {},
          "query": {},
          "body": {
            "additional_attributes": {},
            "can_reply": true,
            "channel": "Channel::Whatsapp",
            "contact_inbox": {
              "id": 19547,
              "contact_id": 13629,
              "inbox_id": 14,
              "source_id": "5548991919191",
              "created_at": "2025-06-26T23:23:50.130Z",
              "updated_at": "2025-06-26T23:23:50.130Z",
              "hmac_verified": false,
              "pubsub_token": "hzgNAgQJCUdJm4hRA6iujZMf"
            },
            "id": 14853,
            "inbox_id": 14,
            "messages": [
              {
                "id": 211400,
                "content": "Opa, tudo bem?",
                "account_id": 2,
                "inbox_id": 14,
                "conversation_id": 14853,
                "message_type": 0,
                "created_at": 1750980305,
                "updated_at": "2025-06-26T23:25:05.395Z",
                "private": false,
                "status": "sent",
                "source_id": "-",
                "content_type": "text",
                "content_attributes": {},
                "sender_type": "Contact",
                "sender_id": 13629,
                "external_source_ids": {},
                "additional_attributes": {},
                "processed_message_content": "Opa, tudo bem?",
                "sentiment": {},
                "conversation": {
                  "assignee_id": 14,
                  "unread_count": 3,
                  "last_activity_at": 1750980305,
                  "contact_inbox": {
                    "source_id": "5548991919191"
                  }
                },
                "sender": {
                  "additional_attributes": {},
                  "custom_attributes": {},
                  "email": null,
                  "id": 13629,
                  "identifier": "5548991919191@s.whatsapp.net",
                  "name": "Renato Asse",
                  "phone_number": "+5548991919191",
                  "thumbnail": "-",
                  "type": "contact"
                }
              }
            ],
            "labels": [],
            "meta": {
              "sender": {
                "additional_attributes": {},
                "custom_attributes": {},
                "email": null,
                "id": 13629,
                "identifier": "5548991919191@s.whatsapp.net",
                "name": "Renato Asse",
                "phone_number": "+5548991919191",
                "thumbnail": "-",
                "type": "contact"
              },
              "assignee": {
                "id": 14,
                "name": "AI Vendas",
                "available_name": "AI Vendas",
                "avatar_url": "",
                "type": "user",
                "availability_status": null,
                "thumbnail": ""
              },
              "team": null,
              "hmac_verified": false
            },
            "status": "open",
            "custom_attributes": {},
            "snoozed_until": null,
            "unread_count": 3,
            "first_reply_created_at": "2025-06-26T23:24:34.136Z",
            "priority": null,
            "waiting_since": 1750980305,
            "agent_last_seen_at": 0,
            "contact_last_seen_at": 0,
            "last_activity_at": 1750980305,
            "timestamp": 1750980305,
            "created_at": 1750980230,
            "event": "automation_event.message_created"
          },
          "webhookUrl": "-",
          "executionMode": "production"
        }
      }
    ]
  },
  "connections": {
    "Set Message2": {
      "main": [
        [
          {
            "node": "WhatsApp API - Typing indicator2",
            "type": "main",
            "index": 0
          },
          {
            "node": "Supabase - Get lead by phone2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Chatwoot - SendMessage3": {
      "main": [
        [
          {
            "node": "Postgres - Add to followup2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Audio4": {
      "main": [
        [
          {
            "node": "OpenAI - Transcribe a Recording5",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Edit Fields4": {
      "main": [
        [
          {
            "node": "NORMALIZE2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set response3": {
      "main": [
        [
          {
            "node": "checkFormat6",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "NORMALIZE2": {
      "main": [
        [
          {
            "node": "Set Redis2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait4": {
      "main": [
        [
          {
            "node": "Get Redis2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Redis2": {
      "main": [
        [
          {
            "node": "Get Redis2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Redis2": {
      "main": [
        [
          {
            "node": "Switch3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Redis2": {
      "main": [
        [
          {
            "node": "Set Message2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "checkFormat6": {
      "main": [
        [
          {
            "node": "breakResponse2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Tem link?1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Postgres - Add to followup2": {
      "main": [
        [
          {
            "node": "Wait5",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get Audio5": {
      "main": [
        [
          {
            "node": "OpenAI - Transcribe a Recording4",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Edit Fields5": {
      "main": [
        [
          {
            "node": "Chat Memory Manager2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Postgres Chat Memory4": {
      "ai_memory": [
        [
          {
            "node": "Chat Memory Manager2",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI - Transcribe a Recording4": {
      "main": [
        [
          {
            "node": "Chat Memory Manager2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch3": {
      "main": [
        [
          {
            "node": "No Operation, do nothing2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Redis2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Wait4",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "checkFormat7": {
      "main": [
        [
          {
            "node": "Get Audio4",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Edit Fields4",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI - Transcribe a Recording5": {
      "main": [
        [
          {
            "node": "NORMALIZE2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "checkFormat8": {
      "main": [
        [
          {
            "node": "Get Audio5",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Edit Fields5",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "breakResponse2": {
      "main": [
        [
          {
            "node": "Loop Over Items2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items2": {
      "main": [
        [
          {
            "node": "Fim2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Chatwoot - SendMessage3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Wait5": {
      "main": [
        [
          {
            "node": "Loop Over Items2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lead existe2": {
      "main": [
        [
          {
            "node": "Sort2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Criar Lead2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Criar Lead2": {
      "main": [
        [
          {
            "node": "Set lead data2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Supabase - Get lead by phone2": {
      "main": [
        [
          {
            "node": "Lead existe2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "typeMessage2": {
      "main": [
        [
          {
            "node": "agentType4",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "agentType5",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "agentType4": {
      "main": [
        [
          {
            "node": "checkFormat7",
            "type": "main",
            "index": 0
          },
          {
            "node": "Chatwoot - Assign to bot2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "checkFormat8",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "agentType5": {
      "main": [
        [
          {
            "node": "checkFormat8",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "stopAI?2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "stopAI?2": {
      "main": [
        [
          {
            "node": "Chatwoot - Stop AI2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Limit2": {
      "main": [
        [
          {
            "node": "Set lead data2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sort2": {
      "main": [
        [
          {
            "node": "Limit2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set lead data2": {
      "main": [
        [
          {
            "node": "AI Agent v2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Agente Audio2": {
      "main": [
        [
          {
            "node": "ElevenLabs2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "ElevenLabs2": {
      "main": [
        [
          {
            "node": "WhatsApp Business - Upload audio2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Redis - Check Message ID Existis2": {
      "main": [
        [
          {
            "node": "newMessage?2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "newMessage?2": {
      "main": [
        [
          {
            "node": "Redis - Push Message ID2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Mensagem duplicada (Ignorar)2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Redis - Push Message ID2": {
      "main": [
        [
          {
            "node": "typeMessage2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp Business - Upload audio2": {
      "main": [
        [
          {
            "node": "WhatsApp Business Cloud - Send audio2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp Business Cloud - Send audio2": {
      "main": [
        [
          {
            "node": "Chatwoot - Send note with audio transcription2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tem link?1": {
      "main": [
        [
          {
            "node": "breakResponse2",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Agente Audio2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model8": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent v2",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Postgres Chat Memory6": {
      "ai_memory": [
        [
          {
            "node": "AI Agent v2",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Supabase Vector Store4": {
      "ai_tool": [
        [
          {
            "node": "AI Agent v2",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings OpenAI4": {
      "ai_embedding": [
        [
          {
            "node": "Supabase Vector Store4",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Atribuir conversa a humano3": {
      "ai_tool": [
        [
          {
            "node": "AI Agent v2",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Adicionar nota3": {
      "ai_tool": [
        [
          {
            "node": "AI Agent v2",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "update_lead_information3": {
      "ai_tool": [
        [
          {
            "node": "AI Agent v2",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Webhook v2": {
      "main": [
        [
          {
            "node": "Settings v2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Settings v2": {
      "main": [
        [
          {
            "node": "Redis - Check Message ID Existis2",
            "type": "main",
            "index": 0
          },
          {
            "node": "Execution Data2",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent v2": {
      "main": [
        [
          {
            "node": "Set response3",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "ed6dc66e-d158-4cf7-a89a-a08959c7c03b",
  "meta": {
    "instanceId": "3121edf8183e00dacb0838add6abf49a5343bdab89d74a45f18f1b56947efe33"
  },
  "id": "sNng4HKt2md7wSqs",
  "tags": []
}