{
  "name": "Agente IA WhatsApp - Template Oficial",
  "nodes": [
    {
      "id": "webhook-node",
      "name": "Webhook WhatsApp",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1,
      "position": [
        250,
        300
      ],
      "webhookId": "whatsapp-agente",
      "parameters": {
        "httpMethod": "POST",
        "path": "whatsapp-agente",
        "responseMode": "responseNode",
        "options": {}
      }
    },
    {
      "id": "if-verification",
      "name": "Verificacao Meta",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        450,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "={{ $json.query['hub.mode'] }}",
            "type": "string",
            "operation": {
              "name": "isNotEmpty"
            }
          }
        }
      }
    },
    {
      "id": "respond-verification",
      "name": "Responder Challenge",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1,
      "position": [
        450,
        500
      ],
      "parameters": {
        "options": {},
        "respondWith": "json",
        "responseBody": "={{ $json.query['hub.challenge'] }}"
      }
    },
    {
      "id": "code-extract",
      "name": "Extrair Dados Mensagem",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        650,
        300
      ],
      "parameters": {
        "jsCode": "const entrada = $json.body.entry[0];\nconst mudanca = entrada.changes[0];\nconst valor = mudanca.value;\n\n// Verifica se é mensagem (não status)\nif (!valor.messages || valor.messages.length === 0) {\n  return [];\n}\n\nconst mensagem = valor.messages[0];\nconst contato = valor.contacts ? valor.contacts[0] : { profile: { name: \"\" } };\n\nreturn [{\n  json: {\n    telefone: mensagem.from,\n    nome: contato.profile.name,\n    texto: mensagem.text ? mensagem.text.body : \"\",\n    idMensagem: mensagem.id,\n    timestamp: mensagem.timestamp,\n    idTelefone: valor.metadata.phone_number_id,\n    tipo: mensagem.type\n  }\n}];"
      }
    },
    {
      "id": "google-sheets-memory",
      "name": "Buscar Historico",
      "type": "n8n-nodes-base.googleSheets",
      "typeVersion": 4,
      "position": [
        850,
        300
      ],
      "parameters": {
        "operation": "search",
        "documentId": "SEU_ID_PLANILHA",
        "sheetName": "Conversas",
        "options": {
          "returnAllMatches": true,
          "limit": 10
        },
        "filters": {
          "conditions": [
            {
              "column": "telefone",
              "value": "={{ $json.telefone }}",
              "condition": "equals"
            }
          ]
        }
      }
    },
    {
      "id": "ai-agent",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 1.7,
      "position": [
        1050,
        300
      ],
      "parameters": {
        "options": {
          "systemMessage": "Voce e o assistente virtual da [NOME_EMPRESA].\n\nMISSAO:\n- Responder perguntas sobre produtos e servicos\n- Coletar dados para orcamentos\n- Transferir para humano quando solicitado\n\nREGRAS ABSOLUTAS:\n- Responda em portugues do Brasil, com tom cordial\n- Maximo 3 frases por resposta\n- Se nao souber, diga 'Nao tenho essa informacao, vou transferir voce'\n- Nunca invente precos, horarios ou disponibilidade\n- Para transferir, responda EXATAMENTE: TRANSFERIR_HUMANO: [motivo]\n\nDADOS DA EMPRESA:\n[Horario: seg a sex, 8h as 18h]\n[Convenios: Unimed, Bradesco, Amil]\n[Valor consulta: R$ 150 a R$ 300]"
        }
      }
    },
    {
      "id": "openai-model",
      "name": "OpenAI GPT-4o-mini",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1,
      "position": [
        1050,
        500
      ],
      "parameters": {
        "model": "gpt-4o-mini",
        "temperature": 0.7
      },
      "credentials": {
        "openAiApi": {
          "id": "SEU_ID_CREDENCIAL",
          "name": "OpenAI Account"
        }
      }
    },
    {
      "id": "http-send",
      "name": "Enviar Resposta WhatsApp",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.1,
      "position": [
        1250,
        300
      ],
      "parameters": {
        "method": "POST",
        "url": "={{ 'https://graph.facebook.com/v20.0/' + $json.idTelefone + '/messages' }}",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Type",
              "value": "application/json"
            }
          ]
        },
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "messaging_product",
              "value": "whatsapp"
            },
            {
              "name": "recipient_type",
              "value": "individual"
            },
            {
              "name": "to",
              "value": "={{ $json.telefone }}"
            },
            {
              "name": "type",
              "value": "text"
            },
            {
              "name": "text",
              "value": "={{ JSON.stringify({ body: $json.respostaAgente }) }}"
            }
          ]
        },
        "options": {
          "timeout": 10000
        }
      }
    },
    {
      "id": "if-transfer",
      "name": "Detectar Transferencia",
      "type": "n8n-nodes-base.if",
      "typeVersion": 1,
      "position": [
        1450,
        300
      ],
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "={{ $json.respostaAgente }}",
            "type": "string",
            "operation": {
              "name": "startsWith",
              "value": "TRANSFERIR_HUMANO"
            }
          }
        }
      }
    },
    {
      "id": "slack-notify",
      "name": "Notificar Slack",
      "type": "n8n-nodes-base.slack",
      "typeVersion": 2,
      "position": [
        1650,
        200
      ],
      "parameters": {
        "channel": "#atendimento",
        "text": "={{ 'Transferencia humana solicitada. Cliente: ' + $json.telefone + ' Motivo: ' + $json.respostaAgente }}"
      }
    }
  ],
  "connections": {
    "Webhook WhatsApp": {
      "main": [
        [
          {
            "node": "Verificacao Meta",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Verificacao Meta": {
      "main": [
        [
          {
            "node": "Extrair Dados Mensagem",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Responder Challenge",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extrair Dados Mensagem": {
      "main": [
        [
          {
            "node": "Buscar Historico",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Buscar Historico": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "Enviar Resposta WhatsApp",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Enviar Resposta WhatsApp": {
      "main": [
        [
          {
            "node": "Detectar Transferencia",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Detectar Transferencia": {
      "main": [
        [
          {
            "node": "Notificar Slack",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1",
    "saveExecutionProgress": true,
    "saveManualExecutions": true
  }
}