{
  "name": "Use Case - Messenger AI Agent (AgentHub)",
  "nodes": [
    {
      "name": "Xác minh Meta (GET)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        0,
        0
      ],
      "parameters": {
        "path": "messenger-webhook",
        "responseMode": "responseNode",
        "options": {}
      }
    },
    {
      "name": "Kiểm tra verify_token",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        240,
        0
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Thay YOUR_VERIFY_TOKEN_HERE bằng chuỗi bí mật tự chọn, nhập đúng chuỗi này khi khai báo Webhook trong Meta App Dashboard.\nconst VERIFY_TOKEN = 'YOUR_VERIFY_TOKEN_HERE';\nconst q = $json.query || {};\nif (q['hub.mode'] === 'subscribe' && q['hub.verify_token'] === VERIFY_TOKEN) {\n  return { json: { ok: true, challenge: q['hub.challenge'] } };\n}\nthrow new Error('Xac minh that bai: sai verify_token hoac mode.');"
      }
    },
    {
      "name": "Trả lại hub.challenge",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        480,
        0
      ],
      "parameters": {
        "respondWith": "text",
        "responseBody": "={{ $json.challenge }}",
        "options": {}
      }
    },
    {
      "name": "Nhận sự kiện Messenger (POST)",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 2,
      "position": [
        -256,
        224
      ],
      "parameters": {
        "httpMethod": "POST",
        "path": "messenger-webhook",
        "responseMode": "responseNode",
        "options": {}
      }
    },
    {
      "name": "Phản hồi 200 (tạm)",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.4,
      "position": [
        240,
        224
      ],
      "parameters": {
        "respondWith": "text",
        "responseBody": "=EVENT_RECEIVED",
        "options": {}
      }
    },
    {
      "name": "Trích xuất tin nhắn",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        0,
        224
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const entry = ($json.body.entry || [])[0];\nconst messaging = (entry && entry.messaging || [])[0];\nif (!messaging || !messaging.message || !messaging.message.text) {\n  throw new Error('Bo qua: khong phai tin nhan van ban (co the la postback/delivery/read receipt).');\n}\nif (messaging.message.is_echo) {\n  throw new Error('Bo qua: day la tin nhan do chinh Page gui (echo), tranh vong lap.');\n}\nreturn { json: { senderId: messaging.sender.id, text: messaging.message.text } };"
      }
    },
    {
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "typeVersion": 3.1,
      "position": [
        464,
        224
      ],
      "parameters": {
        "promptType": "define",
        "text": "={{ $json.senderName }}: {{ $json.text }}",
        "options": {
          "systemMessage": "Bạn là trợ lý AI trả lời tin nhắn Messenger của Trang AgentHub (kênh AI Agent & Automation). Tin nhắn khách sẽ ở dạng 'Tên khách: nội dung'. Nếu biết tên khách (không phải '(không rõ tên)'), hãy xưng hô đúng tên khi trả lời, thân thiện. Nếu không rõ tên thì xưng hô lịch sự chung chung (anh/chị). Trả lời ngắn gọn, bằng tiếng Việt.\n\nTHÔNG TIN THẬT (dùng đúng khi được hỏi, không đổi):\n- Email liên hệ: contact@agenthub.io.vn\n- Website: https://agenthub.io.vn\n- Kênh YouTube: https://www.youtube.com/@AgentHubVN\n\nQUY TẮC BẮT BUỘC: Khi khách hỏi về AgentHub (nội dung, khoá học, video, bài viết, chính sách...), LUÔN dùng công cụ tra cứu trước khi trả lời. TUYỆT ĐỐI KHÔNG bịa thông tin (số điện thoại, địa chỉ, chính sách, email khác, giá cả...) nếu không có trong công cụ tra cứu hoặc trong THÔNG TIN THẬT ở trên. Nếu không tìm thấy thông tin, nói thẳng là chưa có thông tin đó và gợi ý khách để lại câu hỏi hoặc liên hệ qua email/website ở trên."
        }
      }
    },
    {
      "name": "Google Gemini Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "typeVersion": 1.1,
      "position": [
        400,
        400
      ],
      "parameters": {
        "modelName": "models/gemini-3.1-flash-lite",
        "options": {}
      }
    },
    {
      "name": "Gửi trả lời Messenger",
      "type": "n8n-nodes-base.facebookGraphApi",
      "typeVersion": 1,
      "position": [
        848,
        224
      ],
      "parameters": {
        "httpRequestMethod": "POST",
        "graphApiVersion": "v20.0",
        "node": "me",
        "edge": "messages",
        "options": {
          "queryParameters": {
            "parameter": [
              {
                "name": "recipient",
                "value": "={{ JSON.stringify({id: $('Trích xuất tin nhắn').item.json.senderId}) }}"
              },
              {
                "name": "message",
                "value": "={{ JSON.stringify({text: $json.output}) }}"
              }
            ]
          }
        }
      }
    },
    {
      "name": "Simple Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "typeVersion": 1.4,
      "position": [
        560,
        400
      ],
      "parameters": {
        "sessionIdType": "customKey",
        "sessionKey": "={{ $('Trích xuất tin nhắn').item.json.senderId }}",
        "contextWindowLength": 10
      }
    },
    {
      "name": "Lấy tên người dùng",
      "type": "n8n-nodes-base.facebookGraphApi",
      "typeVersion": 1,
      "onError": "continueRegularOutput",
      "position": [
        350,
        220
      ],
      "parameters": {
        "authType": "accessToken",
        "hostUrl": "graph.facebook.com",
        "httpRequestMethod": "GET",
        "graphApiVersion": "v20.0",
        "node": "={{ $json.senderId }}",
        "edge": "",
        "options": {
          "queryParameters": {
            "parameter": [
              {
                "name": "fields",
                "value": "first_name,last_name"
              }
            ]
          }
        }
      }
    },
    {
      "name": "Gộp tên + tin nhắn",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        460,
        220
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "language": "javaScript",
        "jsCode": "const extracted = $('Trích xuất tin nhắn').item.json;\nlet name = '';\nif ($json.first_name) { name = $json.first_name + ($json.last_name ? ' ' + $json.last_name : ''); }\nreturn { json: { senderId: extracted.senderId, text: extracted.text, senderName: name || '(không rõ tên)' } };"
      }
    },
    {
      "name": "Nạp RAG AgentHub (chạy 1 lần)",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        600
      ],
      "parameters": {}
    },
    {
      "name": "Odoo - Lấy bài blog đã đăng",
      "type": "n8n-nodes-base.odoo",
      "typeVersion": 2,
      "position": [
        260,
        600
      ],
      "parameters": {
        "authentication": "odooApi",
        "resource": "custom",
        "operation": "getAll",
        "customResource": "blog.post",
        "returnAll": true,
        "options": {
          "fieldsList": "name,content,teaser_manual,website_url"
        },
        "filters": {
          "filter": [
            {
              "fieldName": "is_published",
              "operator": "equal",
              "value": "true"
            }
          ]
        }
      }
    },
    {
      "name": "Gộp nội dung bài viết",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        480,
        600
      ],
      "parameters": {
        "mode": "runOnceForEachItem",
        "language": "javaScript",
        "jsCode": "const clean = (html) => (html || '').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g,' ').replace(/\\s+/g,' ').trim();\nconst title = $json.name || '';\nconst teaser = clean($json.teaser_manual);\nconst body = clean($json.content);\nconst text = `Tiêu đề: ${title}\\nTóm tắt: ${teaser}\\nNội dung: ${body}\\nNguồn: ${$json.website_url || ''}`;\nreturn { json: { text } };"
      }
    },
    {
      "name": "Vector Store - Nạp",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePGVector",
      "typeVersion": 1.3,
      "position": [
        700,
        600
      ],
      "parameters": {
        "mode": "insert",
        "tableName": "agenthub_kb"
      }
    },
    {
      "name": "Tải tài liệu blog",
      "type": "@n8n/n8n-nodes-langchain.documentDefaultDataLoader",
      "typeVersion": 1,
      "position": [
        700,
        780
      ],
      "parameters": {
        "dataType": "json",
        "jsonMode": "expressionData",
        "jsonData": "={{ $json.text }}"
      }
    },
    {
      "name": "Chia nhỏ văn bản blog",
      "type": "@n8n/n8n-nodes-langchain.textSplitterRecursiveCharacterTextSplitter",
      "typeVersion": 1,
      "position": [
        620,
        900
      ],
      "parameters": {
        "chunkSize": 800,
        "chunkOverlap": 80
      }
    },
    {
      "name": "Embeddings Gemini RAG",
      "type": "@n8n/n8n-nodes-langchain.embeddingsGoogleGemini",
      "typeVersion": 1,
      "position": [
        900,
        780
      ],
      "parameters": {}
    },
    {
      "name": "Vector Store - Tra cứu AgentHub (Tool)",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePGVector",
      "typeVersion": 1.3,
      "position": [
        900,
        400
      ],
      "parameters": {
        "mode": "retrieve-as-tool",
        "toolName": "tra_cuu_thong_tin_agenthub",
        "toolDescription": "Dùng khi khách hỏi về AgentHub: kênh/dự án là gì, dạy gì, có khoá học/video nào, nội dung các bài viết trên blog AgentHub.",
        "tableName": "agenthub_kb"
      }
    }
  ],
  "connections": {
    "Xác minh Meta (GET)": {
      "main": [
        [
          {
            "node": "Kiểm tra verify_token",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Kiểm tra verify_token": {
      "main": [
        [
          {
            "node": "Trả lại hub.challenge",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Nhận sự kiện Messenger (POST)": {
      "main": [
        [
          {
            "node": "Phản hồi 200 (tạm)",
            "type": "main",
            "index": 0
          },
          {
            "node": "Trích xuất tin nhắn",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Trích xuất tin nhắn": {
      "main": [
        [
          {
            "node": "Lấy tên người dùng",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        [
          {
            "node": "Gửi trả lời Messenger",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Google Gemini Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Simple Memory": {
      "ai_memory": [
        [
          {
            "node": "AI Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Lấy tên người dùng": {
      "main": [
        [
          {
            "node": "Gộp tên + tin nhắn",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gộp tên + tin nhắn": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Nạp RAG AgentHub (chạy 1 lần)": {
      "main": [
        [
          {
            "node": "Odoo - Lấy bài blog đã đăng",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Odoo - Lấy bài blog đã đăng": {
      "main": [
        [
          {
            "node": "Gộp nội dung bài viết",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gộp nội dung bài viết": {
      "main": [
        [
          {
            "node": "Vector Store - Nạp",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tải tài liệu blog": {
      "ai_document": [
        [
          {
            "node": "Vector Store - Nạp",
            "type": "ai_document",
            "index": 0
          }
        ]
      ]
    },
    "Chia nhỏ văn bản blog": {
      "ai_textSplitter": [
        [
          {
            "node": "Tải tài liệu blog",
            "type": "ai_textSplitter",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings Gemini RAG": {
      "ai_embedding": [
        [
          {
            "node": "Vector Store - Nạp",
            "type": "ai_embedding",
            "index": 0
          }
        ],
        [
          {
            "node": "Vector Store - Tra cứu AgentHub (Tool)",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Vector Store - Tra cứu AgentHub (Tool)": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  }
}