AutomationFlowsAI & RAG › Aura Bot

Aura Bot

Aura-bot. Uses postgres, lmChatOpenAi, memoryBufferWindow, httpRequest. Webhook trigger; 82 nodes.

Webhook trigger★★★★★ complexityAI-powered82 nodesPostgresOpenAI ChatMemory Buffer WindowHTTP RequestOpenAIGoogle Docs ToolGoogle Sheets ToolAgent
AI & RAG Trigger: Webhook Nodes: 82 Complexity: ★★★★★ AI nodes: yes Added:

This workflow follows the Agent → Googledocstool recipe pattern — see all workflows that pair these two integrations.

The workflow JSON

Copy or download the full n8n JSON below. Paste it into a new n8n workflow, add your credentials, activate. Full import guide →

Download .json
{
  "name": "Aura-bot",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "chatwoot-events",
        "options": {}
      },
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2.1,
      "position": [
        -3968,
        1872
      ],
      "id": "408713fb-1147-4faf-95bb-12a29c4ff255",
      "name": "Webhook"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT sender, content\nFROM chat_history\nWHERE client_id = $1\nORDER BY created_at DESC\nLIMIT 10; -- Le damos los \u00faltimos 10 mensajes de memoria",
        "options": {
          "queryReplacement": "={{ $('Client Add or Update').item.json.id }}",
          "replaceEmptyStrings": false
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        768,
        1296
      ],
      "id": "a709016a-1c61-4aeb-9653-dc24e2fcaa4c",
      "name": "Read History",
      "alwaysOutputData": true,
      "notesInFlow": false,
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "57bd6c6d-571c-4bf9-8314-3f80aa08ab9c",
              "leftValue": "={{ ($json.body.event === 'message_created')\n&& ($json.body.conversation.messages[0].sender_type) === 'Contact' || $json.body.conversation.messages[0].sender_type === 'User'\n\n}}",
              "rightValue": "incoming",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        -3824,
        1872
      ],
      "id": "aecda424-bd90-4f88-9462-a9be1c25129a",
      "name": "Event Filter"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO chat_history (client_id, sender, content)\nVALUES (\n  $1, \n  'human',\n  $2\n);",
        "options": {
          "queryReplacement": "={{ $json.sql_params }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        -2848,
        2080
      ],
      "id": "71b8b5ad-30b6-48a1-9073-c245deb902eb",
      "name": "Add History User",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "model": {
          "__rl": true,
          "value": "gpt-4o",
          "mode": "list",
          "cachedResultName": "gpt-4o"
        },
        "builtInTools": {},
        "options": {
          "temperature": 0
        }
      },
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "typeVersion": 1.3,
      "position": [
        2320,
        1120
      ],
      "id": "010580d8-c056-4afb-aa88-bbc185ce672f",
      "name": "OpenAI Chat Model",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Client Add or Update').first().json.id }}",
        "contextWindowLength": 0
      },
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.3,
      "position": [
        2448,
        1120
      ],
      "id": "45b69b35-795e-40c2-bb1f-61b885099978",
      "name": "Simple Memory"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO clients (phone_number, first_name, last_name)\nVALUES ($1, $2, $3)\nON CONFLICT (phone_number) DO UPDATE\nSET \n    first_name = EXCLUDED.first_name,\n    last_name = EXCLUDED.last_name\nRETURNING id;",
        "options": {
          "queryReplacement": "={{ $json.sender_number }}, {{ $json.sender_firstname }}, {{ $json.sender_lastname }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        -3232,
        2080
      ],
      "id": "d680819c-c884-4316-b563-6899555fcdfb",
      "name": "Owner Add or update Client",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Data Webhook').item.json.account_id }}/conversations/{{ $('Data Webhook').item.json.conversation_id }}/labels",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"labels\": [\"bot-off\"]\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        -2400,
        2080
      ],
      "id": "d730d595-f0fb-4c09-88a9-5d8a1df61291",
      "name": "Add Label Bot OFF",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o",
          "mode": "list",
          "cachedResultName": "GPT-4O"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=Eres el \"Router Neuronal\" de Florer\u00eda Aura.\nTU \u00daNICA FUNCI\u00d3N: Analizar el mensaje del usuario y extraer datos estructurados con L\u00d3GICA CONSERVADORA.\nNO debes redactar respuestas. Solo devuelve JSON.\n\nCONTEXTO:\n- Historial: {{ $json.formatted_history }}\n- Pedido Activo: {{ $json.formatted_order }}\n\nREGLAS CR\u00cdTICAS DE DECISI\u00d3N (Priority Chain):\n\n1. LA TRAMPA DEL \"QUIERO\":\n   - Si el usuario dice \"Quiero un ramo de...\", \"Busco rosas...\", \"Me gustar\u00eda comprar...\":\n   - ESTO ES \"INFO\", NO \"WANT_BUY\".\n   - RAZ\u00d3N: El usuario est\u00e1 *definiendo* el producto. A\u00fan no sabe el precio total ni si hay stock. A\u00fan no ha dicho \"S\u00ed, conf\u00edrmalo\".\n\n2. AN\u00c1LISIS DEL HISTORIAL:\n   - Antes de marcar \"WANT_BUY\", verifica en el historial: \u00bfYa se le dio el precio? \u00bfYa se discutieron los detalles? .\n   - Si es el PRIMER mensaje sobre un producto nuevo, SIEMPRE es \"INFO\".\n\nCLASIFICACI\u00d3N DE INTENCIONES:\n\n- \"HUMAN_INTERVENTION\":\n  Insultos, enojo evidente o pedir hablar con \"humano/due\u00f1a\".\n\n- \"INFO\": (Fase de Cotizaci\u00f3n y Dise\u00f1o)\n  - El usuario describe qu\u00e9 quiere (\"Quiero 4 lirios\").\n  - Preguntas de precios, fotos, stock o dudas generales.\n  - El usuario est\u00e1 configurando su pedido pero NO ha dado la orden final de \"Hacerlo\" SIMPRE VERIFICA ESTA PARTE Y PREGUNTA.\n\n- \"WANT_BUY\": (Fase de Cierre Transaccional)\n  - Solo \u00fasala en 2 casos estrictos:\n    A) CONFIRMACI\u00d3N EXPL\u00cdCITA: El usuario responde a una cotizaci\u00f3n previa con: \"Lo quiero\", \"Confirmo\", \"G\u00e9n\u00e9rame la orden\", \"Est\u00e1 bien el precio\". REVISA SIEMPRE EL HISTORIAL ANTES DE LLEGAR A UNA CONCLUSION.\n    B) LOG\u00cdSTICA: El usuario tiene un pedido YA EXISTENTE (ver Contexto Pedido Activo) y est\u00e1 dando datos de delivery/retiro.\n\n- \"DONT_UNDERSTAND\":\n  \u00daNICAMENTE puedes ayudar con temas relacionados con: \n\t- Flores y arreglos florales \n\t- Productos y servicios de la florister\u00eda \n\t- Pedidos, entregas y consultas sobre flores \n\t- Cuidado de flores y plantas \n\t- Ocasiones especiales (bodas, cumplea\u00f1os, eventos) \n\t- Recomendaciones florales \n\tDEBES RECHAZAR AMABLEMENTE cualquier solicitud fuera de este alcance: \n\t- Programaci\u00f3n, c\u00f3digo o desarrollo \n\t- Temas acad\u00e9micos generales \n\t- Consejos m\u00e9dicos, legales o financieros \n\t- Cualquier otro tema no relacionado con flores o florister\u00eda de nuestro local.\n\n\n\nFORMATO DE SALIDA (JSON ESTRICTO):\n{\n  \"user_intent\": \"HUMAN_INTERVENTION\" | \"WANT_BUY\" | \"INFO\" | \"DONT_UNDERSTAND\" ,\n \"reasoning\": \"Explica por qu\u00e9. Ej: 'Usuario pide producto pero no ha confirmado compra'\"\n}\n"
            },
            {
              "content": "=Analiza la situaci\u00f3n actual con estos datos:\n\nCONTEXTO 1 - HISTORIAL DE CHAT:\n{{ $json.formatted_history }}\n\nMENSAJE NUEVO DEL CLIENTE:\n\"{{ $('Client Message').first().json.message }}\""
            }
          ]
        },
        "builtInTools": {},
        "options": {
          "textFormat": {
            "textOptions": {
              "type": "json_object"
            }
          }
        }
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        1200,
        1296
      ],
      "id": "500e4627-196f-47c9-9aa1-a0789a29bda5",
      "name": "AI Brain",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "b97980a5-f17d-4c10-8bb3-ede22288b66d",
                    "leftValue": "={{ $json.output[0].content[0].text.user_intent }}",
                    "rightValue": "DONT_UNDERSTAND",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "6268a616-b8bc-489b-8a0b-40f96669a43a",
                    "leftValue": "={{ $json.output[0].content[0].text.user_intent }}",
                    "rightValue": "INFO",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "c58e8256-b0d6-4bc0-b081-40d14dfd3059",
                    "leftValue": "={{ $json.output[0].content[0].text.user_intent }}",
                    "rightValue": "WANT_BUY",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "365f98a8-9c25-42b2-af9b-67e8953bfb5b",
                    "leftValue": "={{ $json.output[0].content[0].text.user_intent }}",
                    "rightValue": "HUMAN_INTERVENTION",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    }
                  }
                ],
                "combinator": "and"
              }
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.4,
      "position": [
        1504,
        1280
      ],
      "id": "5158486c-7c83-44b5-bdc4-6121133ca6e0",
      "name": "Intent Router"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "1ca1f9d4-1f26-40b8-ac43-55e9941de3fe",
              "leftValue": "={{ $('Get Active Order').first().json.id}}",
              "rightValue": "",
              "operator": {
                "type": "number",
                "operation": "empty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        1936,
        1408
      ],
      "id": "7be437ab-5e4f-4580-856c-205fa879abca",
      "name": "Check Order Exists"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Data Webhook').first().json.account_id }}/conversations/{{ $('Data Webhook').first().json.conversation_id }}/custom_attributes",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"custom_attributes\": {\n    \"bot_state\": \"off\"\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        2304,
        1968
      ],
      "id": "bfc8fd95-181f-48bb-afee-33ada7183684",
      "name": "Change Bot State",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Data Webhook').first().json.account_id }}/conversations/{{ $('Data Webhook').first().json.conversation_id }}/labels",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"labels\": [\"atencion_inmediata\"]\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        2496,
        1968
      ],
      "id": "8f3c0d5d-b708-4974-8f5d-a1646c98ce6e",
      "name": "Add Label Immediate Attention",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "authentication": "serviceAccount",
        "operation": "get",
        "documentURL": "https://docs.google.com/document/d/YOUR_GOOGLE_DOC_ID/edit?usp=sharing"
      },
      "type": "n8n-nodes-base.googleDocsTool",
      "typeVersion": 2,
      "position": [
        2576,
        1120
      ],
      "id": "fe1448b1-b971-484f-b985-a94502143751",
      "name": "Get Aura Info",
      "credentials": {
        "googleApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "authentication": "serviceAccount",
        "documentId": {
          "__rl": true,
          "value": "YOUR_GOOGLE_SHEET_ID",
          "mode": "list",
          "cachedResultName": "Inventario_Aura",
          "cachedResultUrl": "https://docs.google.com/spreadsheets/d/YOUR_GOOGLE_SHEET_ID/edit?usp=drivesdk"
        },
        "sheetName": {
          "__rl": true,
          "mode": "name",
          "value": "={{ /*n8n-auto-generated-fromAI-override*/ $fromAI('Sheet', ``, 'string') }}"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.googleSheetsTool",
      "typeVersion": 4.7,
      "position": [
        2704,
        1120
      ],
      "id": "65626eb4-9d37-4592-8681-5b912849e764",
      "name": "Get Aura Data",
      "credentials": {
        "googleApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o",
          "mode": "list",
          "cachedResultName": "GPT-4O"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=Eres Aura, la asistente experta , c\u00e1lida y atenta de Florer\u00eda Aura \ud83c\udf39.\nTU OBJETIVO: Sintetizar informaci\u00f3n y transformar datos crudos en respuestas amables, naturales y breves.\n\nTUS FUENTES DE VERDAD:\n1. FUENTE A (Cat\u00e1logo/Docs): Info general.\n2. FUENTE B (Base de Datos): La verdad absoluta sobre el pedido.\n\nPROTOCOLO DE RESPUESTA:\n\nPASO 1: AN\u00c1LISIS DE FUENTE\n- Si el usuario pregunta por \"Mi Pedido\", IGNORA la Fuente A y c\u00e9ntrate totalmente en la FUENTE B.\n\nPASO 2: REGLA DE SUPRESI\u00d3N (No ser molestos)\n- Si est\u00e1s respondiendo detalles del pedido, NO agregues al final \"\u00bfTe recuerdo que tienes un pedido?\", porque ya estamos hablando de eso.\n\nPASO 3: NARRATIVA DE DATOS (Humanizaci\u00f3n - CR\u00cdTICO)\nNUNCA devuelvas una lista tipo \"Campo: Valor\". Transforma los datos en oraciones fluidas.\n\nGu\u00eda de Traducci\u00f3n:\n- ID: No digas \"ID: 2\". Di: \"Se trata de tu pedido #2\".\n- ESTADO 'validando_pedido': Trad\u00facelo como \"Actualmente lo estamos validando en bodega \u23f3\".\n- ESTADO 'aprobado': Trad\u00facelo como \"\u00a1Ya est\u00e1 aprobado y en preparaci\u00f3n! \u2705\".\n- PRODUCTO: Descr\u00edbelo con gusto. Ej: \"Incluye el ramo de [Nombre Producto] \ud83c\udf39\".\n- M\u00c9TODO 'Por definir': Di \"A\u00fan nos falta que nos confirmes si prefieres env\u00edo a domicilio o retiro en local\".\n\nPASO 4: ESTRUCTURA FINAL\n- Saluda brevemente si es necesario.\n- P\u00e1rrafo 1: La respuesta directa narrada (los detalles del pedido).\n- P\u00e1rrafo 2: Pregunta de cierre o siguiente paso l\u00f3gico.\n\nEJEMPLO DE RESPUESTA IDEAL:\n- Siempre coloca los fields en ingles.\nmessage:\n\"\u00a1Claro! Te cuento sobre tu pedido #2. \ud83d\udcc4\nEs el pedido por las 12 Rosas Lindas \ud83c\udf39. Actualmente est\u00e1 en proceso de validaci\u00f3n \u23f3 mientras verificamos el stock.\nPor ahora, solo nos falta definir la entrega. \u00bfTe gustar\u00eda que sea delivery o pasas por el local?\""
            },
            {
              "content": "=CONSULTA DEL CLIENTE: \"{{ $('Client Message').first().json.message }}\"\n\n--- FUENTE A: INFO GENERAL ---\nSTATUS: {{ $('Info AI').item.json.output.includes(\"PERSONAL_DATA\") ? \"IGNORAR_FUENTE_A\" : \"DISPONIBLE\" }}\nCONTENIDO: {{ $('Info AI').item.json.output }}\n\n--- FUENTE B: BASE DE DATOS (Prioridad Alta) ---\nINTENCI\u00d3N: {{ $('AI Brain').first().json.output[0].content[0].text.user_intent }}\nRAZONAMIENTO: {{ $('AI Brain').first().json.output[0].content[0].text.reasoning }}\n\nDATOS_PEDIDO_ACTIVO (Usar para responder detalles):\n{{ JSON.stringify($('History Code').first().json.formatted_order).replace(/_/g, ' ').replace(/\"/g, '') }}\n\nHistorial del Cliente:\n{{ $('History Code').first().json.formatted_history }}"
            }
          ]
        },
        "builtInTools": {},
        "options": {
          "maxTokens": 300,
          "textFormat": {
            "textOptions": {
              "type": "json_object"
            }
          }
        }
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        2912,
        992
      ],
      "id": "3b69083f-9eb4-4d5f-9383-40aaf57bc758",
      "name": "Info Message",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "promptType": "define",
        "text": "=Eres Aura, la asistente experta DE la FLORIA AURA.\nSOLICITUD DEL USUARIO PARA AN\u00c1LISIS:\n\"{{ $('Client Message').first().json.message }}\"\n\n",
        "hasOutputParser": true,
        "options": {
          "systemMessage": "Eres el \"Agente de Inteligencia y Recuperaci\u00f3n\" de Florer\u00eda Aura.\nTU MISI\u00d3N: Clasificar la intenci\u00f3n del usuario y ejecutar la herramienta correcta para extraer datos.\n\nREGLAS DE SELECCI\u00d3N DE HERRAMIENTAS (L\u00f3gica Estricta):\n\n1. HERRAMIENTA: `Get Aura Data` (Excel/Cat\u00e1logo)\n   - \u00dasala \u00daNICAMENTE si el usuario busca: Flores espec\u00edficas (rosas, lirios), Ramos, Precios, Disponibilidad/Stock o Cat\u00e1logo de productos.\n   - PROHIBIDO usar esta herramienta para buscar personas, historia o textos descriptivos.\n - SOLO EXISTEN 2 HOJAS DE CONSULTA QUE SON FLORES Y RAMOS PARA QUE CONSULTES EL CATALOGO, NO EXISTEN OTRAS HOJAS, ASI QUE NO INTENTES CONSULTAR HOJAS QUE NO EXISTEN.\n\n2. HERRAMIENTA: `Get Aura Info` (Docs/Conocimiento)\n   - \u00dasala para TODO lo que no sea venta de productos.\n   - Incluye: Horarios, Ubicaci\u00f3n, M\u00e9todos de Pago.\n   - Incluye: Historia de la marca, \"Vendedor Estrella\", Qui\u00e9n es la due\u00f1a, Personal, Curiosidades o Pol\u00edticas de la empresa.\n\n3. USO H\u00cdBRIDO:\n   - Si pide una combinaci\u00f3n (Ej: \"Precio de rosas y qui\u00e9n es el mejor vendedor\") -> EJECUTA AMBAS.\n\nREGLAS DE FORMATO DE SALIDA:\nCuando recibas la respuesta:\n- NO devuelvas JSON crudo.\n- Procesa la data en un bloque de texto legible.\n- Si usaste Excel: Lista los productos con guiones (Nombre - Precio).\n- Si usaste Docs: Resume la respuesta en 1-2 frases claras extra\u00eddas del texto.\n- Si la herramienta falla o devuelve vac\u00edo, escribe: \"DATA_NOT_FOUND\"."
        }
      },
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3,
      "position": [
        2448,
        896
      ],
      "id": "60a5de0f-da98-4441-bdc9-6441c30db685",
      "name": "Info AI",
      "alwaysOutputData": false,
      "executeOnce": false
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO chat_history (client_id, sender, content)\nVALUES (\n  $1, \n  'bot',\n  $2\n);",
        "options": {
          "queryReplacement": "={{ $json.sql_params }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        3392,
        992
      ],
      "id": "205088d4-7762-4e8b-8c48-430360aac751",
      "name": "Info Add History Bot",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Webhook').first().json.body.account.id }}/conversations/{{ $('Webhook').first().json.body.conversation.id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "content",
              "value": "={{ $('Info Message').item.json.output[0].content[0].text.message }}"
            },
            {
              "name": "message_type",
              "value": "outgoing"
            },
            {
              "name": "private",
              "value": "false"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        3568,
        992
      ],
      "id": "9e517485-b94a-4e79-8275-b5e2112fe89d",
      "name": "Info Send Message",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Webhook').first().json.body.account.id }}/conversations/{{ $('Webhook').first().json.body.conversation.id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "content",
              "value": "=\u00a1Recibido! He notado que tu consulta requiere un toque m\u00e1s personalizado para que todo quede perfecto.\n\nHe avisado a una de nuestras asesoras humanas para que revise tu mensaje y te atienda personalmente en unos minutos. \u00a1Est\u00e1s en las mejores manos! \ud83c\udf39\u2728"
            },
            {
              "name": "message_type",
              "value": "outgoing"
            },
            {
              "name": "private",
              "value": "false"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        1952,
        1968
      ],
      "id": "3568ac6d-638c-4f31-b6d8-a32ee2f173dc",
      "name": "End Conversation Message",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Webhook').first().json.body.account.id }}/conversations/{{ $('Webhook').first().json.body.conversation.id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "content",
              "value": "={{ $('Intent Router').first().json.output[0].content[0].text.reasoning }}"
            },
            {
              "name": "message_type",
              "value": "outgoing"
            },
            {
              "name": "private",
              "value": "true"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        2128,
        1968
      ],
      "id": "8767716d-e8ef-4c3f-8806-44a7ac9534b1",
      "name": "Add Private Note",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT id, status, product_details, delivery_method, total_amount\nFROM orders\nWHERE client_id = $1\nAND status NOT IN ('rechazado', 'cancelado') \nORDER BY created_at DESC\nLIMIT 1;",
        "options": {
          "queryReplacement": "={{ $('Client Add or Update').item.json.id }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        544,
        1296
      ],
      "id": "628516bc-81d0-4feb-b465-6a32725bb957",
      "name": "Get Active Order",
      "alwaysOutputData": true,
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO chat_history (client_id, sender, content)\nVALUES (\n  $1,'client',$2\n);",
        "options": {
          "queryReplacement": "={{ $json.sql_params }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        -128,
        1328
      ],
      "id": "b937eebe-fba2-40e0-b7ce-b415ba75e851",
      "name": "Add History Client",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO orders (client_id, product_details, total_amount, status)\nVALUES ($1, $2, $3, 'validando_pedido')\nRETURNING id;",
        "options": {
          "queryReplacement": "={{ $json.sql_params }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        3056,
        1328
      ],
      "id": "2777c726-b121-489d-b985-a784686a6b84",
      "name": "Insert Order",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o",
          "mode": "list",
          "cachedResultName": "GPT-4O"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=Eres el \"Auditor de Transacciones\" de Florer\u00eda Aura.\nTU MISI\u00d3N: Analizar la conversaci\u00f3n y extraer los datos estructurados para registrar o actualizar un pedido en la Base de Datos.\n\nTUS OBJETIVOS (SEG\u00daN CONTEXTO):\n\n1. SI ES UN NUEVO PEDIDO (Insert):\n   - Debes rastrear en el HISTORIAL DE CHAT qu\u00e9 producto y qu\u00e9 precio se acord\u00f3.\n   - Extrae el resumen final del producto.\n   - Extrae el valor monetario total.\n\n2. SI ES LOG\u00cdSTICA (Update):\n   - Detecta si el cliente eligi\u00f3 \"delivery\" (env\u00edo) o \"local\" (retiro/pasar viendo).\n\nREGLAS DE EXTRACCI\u00d3N DE DATOS:\n- \"product_details\": Debe ser una descripci\u00f3n clara y concisa (Ej: \"Ramo de 8 flores amarillas + Tarjeta\"). NO incluyas saludos.\n- \"total_amount\": Solo el n\u00famero decimal (Ej: 200.00). Si el precio no est\u00e1 claro en el chat, pon 0.00.\n- \"delivery_method\": Solo acepta valores: 'local', 'delivery' o null.\n\nFORMATO DE SALIDA JSON (Estricto para DB):\n{\n  \"sql_action\": \"INSERT\" | \"NONE\",\n  \"data\": {\n      \"product_details\": \"Texto descriptivo del ramo\",\n      \"total_amount\": 0.00,\n      \"delivery_method\": \"local\" | \"delivery\" | null\n  },\n  \"validation_message\": \"Mensaje corto confirmando qu\u00e9 datos encontraste (para uso interno)\"\n}"
            },
            {
              "content": "=ANALIZA ESTA CONVERSACI\u00d3N PARA EXTRAER DATOS DEL PEDIDO:\n\n--- HISTORIAL DE NEGOCIACI\u00d3N (De aqu\u00ed saca el producto y precio) ---\n{{ $('History Code').item.json.formatted_history }}\n\n--- MENSAJE ACTUAL (Confirmaci\u00f3n o Datos de Env\u00edo) ---\n{{ $('Client Message').first().json.message }}\n--- ESTADO ACTUAL DB ---\nTiene Pedido Activo: {{ $('Get Active Order').first().json.id ? 'SI' : 'NO' }}"
            }
          ]
        },
        "builtInTools": {},
        "options": {
          "textFormat": {
            "textOptions": {
              "type": "json_object"
            }
          }
        }
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        2336,
        1344
      ],
      "id": "6a81ce51-8e30-465c-afe1-72680a4d0ff7",
      "name": "Order Data Extractor",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "df46ce1a-84ac-4278-b49c-eab661810976",
              "leftValue": "={{ $json.output[0].content[0].text.sql_action }}",
              "rightValue": "INSERT",
              "operator": {
                "type": "string",
                "operation": "equals",
                "name": "filter.operator.equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        2640,
        1344
      ],
      "id": "197a3f8f-2637-45d3-b561-9c795653f925",
      "name": "Insert Order If"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO chat_history (client_id, sender, content)\nVALUES (\n  $1, \n  'bot',\n  $2\n);",
        "options": {
          "queryReplacement": "={{ $json.sql_params }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        4080,
        1328
      ],
      "id": "94d2f971-8657-4c86-9b86-ac3aabcd1893",
      "name": "Add Want History",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o",
          "mode": "list",
          "cachedResultName": "GPT-4O"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=CONTEXTO DE ROL:\nEres Aura, la anfitriona experta de Florer\u00eda Aura. Tu comunicaci\u00f3n es sofisticada, c\u00e1lida y vibrante.\nNo solo \"registras pedidos\", t\u00fa **inicias experiencias memorables**.\n\nTU OBJETIVO:\nConfirmar la creaci\u00f3n del pedido #[ID] haciendo sentir al cliente que ha tomado una decisi\u00f3n excelente. Debes balancear la emoci\u00f3n de la compra con la seguridad transaccional.\n\nESTRUCTURA DEL MENSAJE (Dise\u00f1o UX):\n\n1. EL \"HOOK\" EMOCIONAL (Apertura):\n   - Usa el nombre del cliente.\n   - Celebra la confirmaci\u00f3n con elegancia (Ej: \"\u00a1Maravillosas noticias!\", \"Todo est\u00e1 listo\").\n\n2. LA CONFIRMACI\u00d3N (Datos Duros):\n   - Menciona el N\u00daMERO DE PEDIDO (Obligatorio) con negritas.\n   - Resume el producto principal de forma atractiva (\"Esas [Flores] van a lucir espectaculares\").\n   - Confirma el valor total.\n\n3. SETTING EXPECTATIONS (Siguiente Paso):\n   - Explica proactivamente qu\u00e9 sigue para reducir la ansiedad: \"Ahora pasaremos a la etapa de validaci\u00f3n y preparaci\u00f3n de tus flores \ud83c\udfa8\".\n\n4. CIERRE ABIERTO:\n   - \"Quedo atenta por si deseas agregar un detalle extra o tienes alguna duda.\"\n\nTONO Y ESTILO:\n- Emojis: \u00dasalos como decoraci\u00f3n fina, no como spam (\u2728, \ud83c\udf39, \ud83d\udcdd, \ud83c\udf43).\n- Formato: \nmessage: Usa p\u00e1rrafos cortos y espacios para que sea visualmente ligero en WhatsApp en un solo mensaje igual.\n- Vocabulario: Usa palabras como \"exquisito\", \"fresco\", \"cuidado\", \"detalle\"."
            },
            {
              "content": "=DATOS CONFIRMADOS DE LA TRANSACCI\u00d3N (Postgres):\n\n- CLIENTE: {{ $('Data Webhook').first().json.sender_fullname }}\n- ORDER ID: {{ $('Insert Order').item.json.id }}\n- PRODUCTO: {{ $('Order Data Extractor').item.json.output[0].content[0].text.data.product_details }}\n- TOTAL A PAGAR: ${{ $('Order Data Extractor').item.json.output[0].content[0].text.data.total_amount }}\nTAREA:\nGenera el mensaje de confirmaci\u00f3n siguiendo el est\u00e1ndar de \"Experiencia Aura\"."
            }
          ]
        },
        "builtInTools": {},
        "options": {
          "maxTokens": 300,
          "textFormat": {
            "textOptions": {
              "type": "json_object"
            }
          }
        }
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        3600,
        1328
      ],
      "id": "d24e1d3e-e2bd-4ba9-8264-fd1289968e3a",
      "name": "Want Message",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Webhook').first().json.body.account.id }}/conversations/{{ $('Webhook').first().json.body.conversation.id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "content",
              "value": "={{ $('Want Message').item.json.output[0].content[0].text.message }}"
            },
            {
              "name": "message_type",
              "value": "outgoing"
            },
            {
              "name": "private",
              "value": "false"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        4272,
        1328
      ],
      "id": "41b680f5-92c4-43f9-8803-f51fad6079b1",
      "name": "Want Send Message",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o",
          "mode": "list",
          "cachedResultName": "GPT-4O"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=Eres el \"Analista de Estado de Pedidos\" de Florer\u00eda Aura.\nTU MISI\u00d3N: Evaluar el estado t\u00e9cnico de un pedido existente y determinar la estrategia de respuesta.\n\nREGLAS DE NEGOCIO (L\u00f3gica Estricta):\n\n1. REGLA DEL TIEMPO (Antig\u00fcedad):\n   - Recibir\u00e1s un dato \"hours_since_creation\".\n   - Si es MAYOR a 3.0 -> El pedido se considera \"OLVIDADO\" (Needs Reminder).\n   - Si es MENOR o IGUAL a 3.0 -> El pedido es \"RECIENTE\" (No molestar).\n\n2. REGLA DE COMPLETITUD (Delivery):\n   - Verifica el campo \"delivery_method\" de la base de datos.\n   - Si es 'null' o 'undefined' -> FALTA DATOS.\n   - Si dice 'local' o 'delivery' -> COMPLETO.\n\nSALIDA ESPERADA (JSON):\nDebes generar un JSON que gu\u00ede al redactor en el siguiente paso.\n{\n  \"order_age_status\": \"recent\" | \"old\",\n  \"missing_info\": \"none\" | \"delivery_method\",\n  \"response_strategy\": \"answer_only\" | \"ask_delivery\" | \"remind_old_order\",\n  \"reasoning\": \"Breve explicaci\u00f3n t\u00e9cnica de por qu\u00e9 elegiste esta estrategia\"\n}\n\nTABLA DE ESTRATEGIAS:\n- Si falta delivery: \"ask_delivery\" (Prioridad Alta).\n- Si todo est\u00e1 completo Y es viejo (>3h): \"remind_old_order\".\n- Si todo est\u00e1 completo Y es reciente (<3h): \"answer_only\" (Responder duda del usuario normalmente).\n- Si \"JUST_UPDATED\" es \"YES\": La estrategia debe ser \"confirm_completion\" (Celebrar que ya tenemos todo)."
            },
            {
              "content": "=AN\u00c1LISIS DE PEDIDO ACTUAL:\n\n--- DATOS DB ---\nID Pedido: {{ $('Get Active Order').first().json.id }}\nDelivery Method: {{ $('Delivery Detector').item.json.detected_method ? $('Delivery Detector').item.json.detected_method : $('Get Active Order').first().json.delivery_method }}\n\n--- EVENTOS RECIENTES ---\n// \u00bfAcabamos de actualizar?\nJUST_UPDATED: {{ $('Delivery Detector').item.json.detected_method ? 'YES' : 'NO' }}\n\n--- C\u00c1LCULO DE TIEMPO (Autom\u00e1tico) ---\nHoras desde creaci\u00f3n: {{ (new Date().getTime() - new Date($('Get Active Order').first().json.updated_at).getTime()) / (1000 * 60 * 60) }}\n(Nota: Si el n\u00famero es > 3, aplica regla de pedido olvidado).\n\n--- CONSULTA DEL USUARIO ---\n{{ $('Client Message').first().json.message }}"
            }
          ]
        },
        "builtInTools": {},
        "options": {
          "textFormat": {
            "textOptions": {
              "type": "json_object"
            }
          }
        }
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        3024,
        1568
      ],
      "id": "09d52b4b-33e3-457e-8b48-66def64c48f8",
      "name": "Order Data Delivery",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 3
          },
          "conditions": [
            {
              "id": "df46ce1a-84ac-4278-b49c-eab661810976",
              "leftValue": "={{ $json.output[0].content[0].text.detected_method }}",
              "rightValue": "INSERT",
              "operator": {
                "type": "string",
                "operation": "empty",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.3,
      "position": [
        2640,
        1584
      ],
      "id": "fd25dfb7-7751-48ca-b87e-738b9698eaa6",
      "name": "Has Delivery"
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "UPDATE orders\nSET delivery_method = $1, updated_at = NOW()\nWHERE id = $2;",
        "options": {
          "queryReplacement": "={{ $('Delivery Detector').item.json.output[0].content[0].text.detected_method }}, {{ $('Get Active Order').first().json.id }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        2848,
        1664
      ],
      "id": "5d146300-eb51-4a07-bcc2-75fd455313b5",
      "name": "Update Order",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o-mini",
          "mode": "list",
          "cachedResultName": "GPT-4O-MINI"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=Eres el \"Detector de Log\u00edstica\" de Florer\u00eda Aura.\nTU MISI\u00d3N: Analizar el mensaje del usuario y extraer SIEMPRE que sea posible el m\u00e9todo de entrega preferido.\n\nCONTEXTO: El usuario tiene un pedido pendiente que le falta definir si es \"Delivery\" o \"Retiro\".\n\nREGLAS DE EXTRACCI\u00d3N:\n- Si menciona \"env\u00edo\", \"a domicilio\", \"mi casa\", \"llevamelo\": Salida -> \"delivery\".\n- Si menciona \"paso viendo\", \"retiro\", \"local\", \"tienda\", \"voy yo\": Salida -> \"local\".\n- Si el mensaje NO tiene nada que ver con log\u00edstica (ej: \"\u00bfCu\u00e1nto cuestan las rosas?\"): Salida -> null.\n\nFORMATO JSON:\n{\n  \"detected_method\": \"delivery\" | \"local\" | null,\n}"
            },
            {
              "content": "=MENSAJE DEL CLIENTE: \"{{ $('Client Message').first().json.message }}\""
            }
          ]
        },
        "builtInTools": {},
        "options": {
          "textFormat": {
            "textOptions": {
              "type": "json_object"
            }
          }
        }
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        2336,
        1584
      ],
      "id": "c19bc184-70a0-424e-ae8a-363e8178002c",
      "name": "Delivery Detector",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "gpt-4o",
          "mode": "list",
          "cachedResultName": "GPT-4O"
        },
        "responses": {
          "values": [
            {
              "role": "system",
              "content": "=Eres Aura, la asistente experta y carism\u00e1tica de Florer\u00eda Aura \ud83c\udf38.\nTU OBJETIVO: Responder al cliente combinando su consulta actual con el estado de su pedido, siguiendo estrictamente la ESTRATEGIA DEFINIDA.\n\nESTILOS DE RESPUESTA SEG\u00daN LA ESTRATEGIA RECIBIDA:\n\nCASO 1: ESTRATEGIA \"ask_delivery\" (Falta M\u00e9todo de Env\u00edo)\n- PASO A: Responde la duda o comentario actual del usuario con naturalidad y carisma.\n- PASO B (El Puente): Usa una transici\u00f3n suave (\"Por cierto...\", \"Aprovechando...\", \"Para ir avanzando...\").\n- PASO C: Pregunta educadamente si prefiere \"Delivery\" \ud83d\udef5 o \"Retiro en el local\" \ud83c\udfea para completar su orden #[ID].\n\nCASO 2: ESTRATEGIA \"remind_old_order\" (Pedido Olvidado > 3 horas)\n- PASO A: Responde la duda actual del usuario.\n- PASO B: Haz un recordatorio sutil y amable: \"Vi que nos qued\u00f3 pendiente tu pedido #[ID] de hace un rato. \u00bfTe gustar\u00eda retomarlo o necesitas ayuda con eso? \u23f3\"\n\nCASO 3: ESTRATEGIA \"answer_only\" (Pedido Reciente y Completo)\n- PASO \u00daNICO: Responde la duda del usuario con total normalidad.\n- PROHIBICI\u00d3N: NO menciones el pedido pendiente. Asumimos que el cliente sabe lo que hace. No seas repetitiva.\n\n... (Mant\u00e9n los casos anteriores 1, 2 y 3) ...\n\nCASO 4: ESTRATEGIA \"confirm_completion\" (Acabamos de recibir el Delivery)\n- OBJETIVO: Confirmar que el dato se guard\u00f3 y dar tranquilidad.\n- ESTRUCTURA:\n  1. Confirma la elecci\u00f3n: \"\u00a1Perfecto! Queda anotado como [Delivery/Retiro] \ud83d\udef5/\ud83c\udfea.\"\n  2. Status Check: \"Con esto ya tenemos todos los datos de tu pedido #[ID].\"\n  3. Cierre: \"Ahora s\u00ed, procedemos a validar stock y te aviso en breve. \u00bfTienes alguna otra duda mientras tanto?\"\n\n\nTONO DE VOZ:\n- Profesional pero cercano.\n- Emp\u00e1tico: Si el cliente duda, dale seguridad.\n- Conciso: No escribas testamentos.\n\nFORMATO DE SALIDA (JSON):\n{\n  \"reply_to_user\": \"Tu mensaje redactado aqu\u00ed...\"\n}"
            },
            {
              "content": "=CONTEXTO PARA REDACCI\u00d3N:\n\n--- ESTRATEGIA MAESTRA (Del Nodo Anterior) ---\nESTRATEGIA A SEGUIR: \"{{ $json.output[0].content[0].text.response_strategy }}\"\nRAZ\u00d3N: \"{{ $json.output[0].content[0].text.reasoning }}\"\n\n--- DATOS DEL PEDIDO ---\nID PEDIDO: {{ $('Get Active Order').first().json.id }}\nPRODUCTO: {{ $('Get Active Order').first().json.product_details }}\n\n--- MENSAJE DEL CLIENTE ---\n\"{{ $('Client Message').first().json.message }}\"\n\n--- HISTORIAL DEL CLIENTE ---\n{{ $('History Code').item.json.formatted_history }}\nINSTRUCCI\u00d3N: Genera la respuesta JSON siguiendo la estrategia indicada."
            }
          ]
        },
        "builtInTools": {},
        "options": {
          "textFormat": {
            "textOptions": {
              "type": "json_object"
            }
          }
        }
      },
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 2.1,
      "position": [
        3328,
        1568
      ],
      "id": "4906fd41-e288-49d0-8808-373dc37064a7",
      "name": "Delivery Message",
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "INSERT INTO chat_history (client_id, sender, content)\nVALUES (\n  $1, \n  'bot',\n  $2\n);",
        "options": {
          "queryReplacement": "={{ $json.sql_params }}"
        }
      },
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.6,
      "position": [
        3824,
        1568
      ],
      "id": "843b6c95-e3cf-4830-9a8c-42a2adc9de6f",
      "name": "Add Delivery History",
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Webhook').first().json.body.account.id }}/conversations/{{ $('Webhook').first().json.body.conversation.id }}/messages",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "content",
              "value": "={{ $('Delivery Message').item.json.output[0].content[0].text.reply_to_user }}"
            },
            {
              "name": "message_type",
              "value": "outgoing"
            },
            {
              "name": "private",
              "value": "false"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        4032,
        1568
      ],
      "id": "3800a70b-c631-4d83-a2b2-6bc0bdb17744",
      "name": "Delivery Send Message",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        320,
        1392
      ],
      "id": "956f0d84-628b-41ac-9793-ecc4f10c2519",
      "name": "End Flow"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        3760,
        992
      ],
      "id": "cb2610a5-25b8-4c83-8dd7-e919b60cf31c",
      "name": "End Info Flow"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        4640,
        1328
      ],
      "id": "1a8681c4-a61e-4cbf-9f66-15465f70134d",
      "name": "End Want Flow"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        4224,
        1568
      ],
      "id": "2993a703-65e4-4f84-8320-5d7ee3e9a304",
      "name": "End Delivery Flow"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        2688,
        1968
      ],
      "id": "ed2a90d2-d674-4bbb-98a1-f6df690e4739",
      "name": "End Humman Intervention Flow"
    },
    {
      "parameters": {},
      "type": "n8n-nodes-base.noOp",
      "typeVersion": 1,
      "position": [
        -2176,
        2080
      ],
      "id": "0755ab49-c9bc-4856-822c-6b0a3ba50bb5",
      "name": "End Human Flow"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Data Webhook').first().json.account_id }}/conversations/{{ $('Data Webhook').first().json.conversation_id }}/labels",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"labels\": [\"validar_pedidos\"]\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        3248,
        1328
      ],
      "id": "d084a9bd-1320-4988-a8ec-4f8d590e5d76",
      "name": "Add Validation Order Label",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "push",
        "list": "=chat_{{ $('Data Webhook').item.json.conversation_id }}",
        "messageData": "={{ $('Data Webhook').item.json.message }}"
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        -3264,
        1504
      ],
      "id": "2a7f4295-86ff-4b7a-9fc3-6bf9e576aa15",
      "name": "Store",
      "credentials": {
        "redis": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "operation": "incr",
        "key": "=counter_{{ $('Data Webhook').item.json.conversation_id }}",
        "expire": true,
        "ttl": 25
      },
      "type": "n8n-nodes-base.redis",
      "typeVersion": 1,
      "position": [
        -3040,
        1504
      ],
      "id": "7e75744e-cb65-445b-add4-eab7661137d6",
      "name": "Count",
      "credentials": {
        "redis": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "leftValue": "={{ $('Data Webhook').item.json.bot_state }}",
                    "rightValue": "on",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "id": "14bf694d-38a3-41de-a985-1784689c7493"
                  }
                ],
                "combinator": "and"
              }
            },
            {
              "conditions": {
                "options": {
                  "caseSensitive": true,
                  "leftValue": "",
                  "typeValidation": "strict",
                  "version": 3
                },
                "conditions": [
                  {
                    "id": "f781cd46-9b84-4f23-a351-ae0f982c1c23",
                    "leftValue": "={{ $('Data Webhook').item.json.bot_state }}",
                    "rightValue": "off",
                    "operator": {
                      "type": "string",
                      "operation": "equals",
                      "name": "filter.operator.equals"
                    }
                  }
                ],
                "combinator": "and"
              }
            }
          ]
        },
        "options": {
          "fallbackOutput": "extra"
        }
      },
      "type": "n8n-nodes-base.switch",
      "typeVersion": 3.4,
      "position": [
        112,
        1312
      ],
      "id": "09eee693-7647-4d13-86c8-576c38ca371f",
      "name": "Bot State Switch"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Data Webhook').item.json.account_id }}/conversations/{{ $('Data Webhook').item.json.conversation_id }}/custom_attributes",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"custom_attributes\": {\n    \"bot_state\": \"on\"\n  }\n}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        320,
        1520
      ],
      "id": "c9fe7bf8-1b3b-4bba-ad41-d44fa3074d20",
      "name": "Change Bot State Null",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "652d5d60-d4a3-407d-94ba-f2759a6eeceb",
              "name": "sql_params",
              "value": "={{ [    $('Client Add or Update').item.json.id,    $('Client Message').item.json.message ] }}",
              "type": "array"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        -352,
        1328
      ],
      "id": "b5d8f047-e74b-499e-bf24-6ec9a9392df5",
      "name": "Array Message Client"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "652d5d60-d4a3-407d-94ba-f2759a6eeceb",
              "name": "sql_params",
              "value": "={{ [    $('Client Add or Update').first().json.id,   $json.output[0].content[0].text.message  ] }}",
              "type": "array"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        3216,
        992
      ],
      "id": "b773dfb7-77b6-4a98-a72e-59eecbc067b8",
      "name": "Array Message Info"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "652d5d60-d4a3-407d-94ba-f2759a6eeceb",
              "name": "sql_params",
              "value": "={{ [    $('Client Add or Update').first().json.id,   $json.output[0].content[0].text.message  ] }}",
              "type": "array"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        3904,
        1328
      ],
      "id": "9687924a-6faf-4558-a617-3e4f7cd05035",
      "name": "Array Message Want"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "652d5d60-d4a3-407d-94ba-f2759a6eeceb",
              "name": "sql_params",
              "value": "={{ [    $('Client Add or Update').first().json.id,   $json.output[0].content[0].text.reply_to_user  ] }}",
              "type": "array"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.4,
      "position": [
        3632,
        1568
      ],
      "id": "2186fe12-532b-4293-80a0-ca454ce5df42",
      "name": "Array Message Delivery"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "=https://YOUR_CHATWOOT_DOMAIN/api/v1/accounts/{{ $('Data Webhook').first().json.account_id }}/conversations/{{ $('Data Webhook').first().json.conversation_id }}/custom_attributes",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "{\n  \"custom_attributes\": {\n    \"bot_state\": \"on\",\n    \"estado_pedido\": \"Validando\"\n  }\n}\n",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.3,
      "position": [
        3440,
        1328
      ],
      "id": "e4620656-5636-4352-9b9f-206f97c485c4",
      "name": "Change Validation State",
      "credentials": {
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      }
    },
    {
      "parameters": {
        "content": "# Fase 1\n\n",
        "height": 336,
        "width": 800,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -4144,
        1776
      ],
      "typeVersion": 1,
      "id": "d9bf08fc-ffca-4ff9-9dc5-763d20b3e35c",
      "name": "Sticky Note"
    },
    {
      "parameters": {
        "content": "## Fase 2B\n\n",
        "height": 352,
        "width": 1344,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -3280,
        1968
      ],
      "typeVersion": 1,
      "id": "13f6523e-8d02-4f3a-801f-7e7f3088b101",
      "name": "Sticky Note1"
    },
    {
      "parameters": {
        "content": "## Fase 2A\n",
        "height": 544,
        "width": 2656,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -3328,
        1120
      ],
      "typeVersion": 1,
      "id": "a6b6f1e1-00c6-4558-a054-e1b9c985c0bf",
      "name": "Sticky Note2"
    },
    {
      "parameters": {
        "content": "## Fase 3",
        "height": 544,
        "width": 640,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -624,
        1120
      ],
      "typeVersion": 1,
      "id": "b95363df-2232-4127-83c6-b574f1430833",
      "name": "Sticky Note3"
    },
    {
      "parameters": {
        "content": "## Fase 4\n",
        "height": 544,
        "width": 448,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        48,
        1120
      ],
      "typeVersion": 1,
      "id": "c4358bc5-866a-4719-bb32-ee8c335b0cca",
      "name": "Sticky Note4"
    },
    {
      "parameters": {
        "content": "## Fase 5\n",
        "height": 544,
        "width": 1152,
        "color": 7
      },
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        528,
        1120
  

Credentials you'll need

Each integration node will prompt for credentials when you import. We strip credential IDs before publishing — you'll add your own.

Pro

For the full experience including quality scoring and batch install features for each workflow upgrade to Pro

About this workflow

Aura-bot. Uses postgres, lmChatOpenAi, memoryBufferWindow, httpRequest. Webhook trigger; 82 nodes.

Source: https://gist.github.com/STIXGT/345e759cf2f76c79122ce23059b077b6 — original creator credit. Request a take-down →

More AI & RAG workflows → · Browse all categories →

Related workflows

Workflows that share integrations, category, or trigger type with this one. All free to copy and import.

AI & RAG

Flux. Uses lmChatOpenAi, agent, googleGemini, httpRequest. Webhook trigger; 67 nodes.

OpenAI Chat, Agent, Google Gemini +8
AI & RAG

This workflow transforms WhatsApp into a powerful personal AI using n8n + Green-API. Send text or voice messages — the assistant understands intent and handles daily tasks automatically. 💰 Expense & i

Tool Calculator, Google Sheets Tool, OpenAI Chat +10
AI & RAG

Delivery. Uses memoryPostgresChat, lmChatOpenAi, toolCalculator, redis. Webhook trigger; 37 nodes.

Memory Postgres Chat, OpenAI Chat, Tool Calculator +6
AI & RAG

📝 Description

HTTP Request, OpenAI, Google Docs Tool +6
AI & RAG

L&D_AgentsAI_ATIVO. Uses httpRequest, agent, googleCalendarTool, toolSerpApi. Webhook trigger; 93 nodes.

HTTP Request, Agent, Google Calendar Tool +9