{
  "name": "RAG E-commerce Recommender System",
  "nodes": [
    {
      "parameters": {
        "httpMethod": "POST",
        "path": "recommend",
        "responseMode": "responseNode",
        "options": {}
      },
      "id": "webhook-trigger",
      "name": "Webhook Trigger",
      "type": "n8n-nodes-base.webhook",
      "typeVersion": 1.1,
      "position": [240, 300],
      "webhookId": "rag-recommend-webhook"
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "user_id",
              "name": "user_id",
              "value": "={{ $json.body.user_id || $json.body.email }}",
              "type": "string"
            },
            {
              "id": "email",
              "name": "email",
              "value": "={{ $json.body.email }}",
              "type": "string"
            },
            {
              "id": "page_type",
              "name": "page_type",
              "value": "={{ $json.body.pageType || 'homepage' }}",
              "type": "string"
            },
            {
              "id": "current_sku",
              "name": "current_sku",
              "value": "={{ $json.body.sku || '' }}",
              "type": "string"
            },
            {
              "id": "session_id",
              "name": "session_id",
              "value": "={{ $json.body.session_id || '' }}",
              "type": "string"
            }
          ]
        },
        "options": {}
      },
      "id": "parse-request",
      "name": "Parse Request",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.3,
      "position": [460, 300]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT user_id, email, recent_categories, rfm_segment, last_purchase_date, avg_order_value, preferred_brands, browsing_history FROM users WHERE user_id = '{{ $json.user_id }}' OR email = '{{ $json.email }}' LIMIT 1;",
        "options": {}
      },
      "id": "fetch-user-profile",
      "name": "Fetch User Profile",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.4,
      "position": [680, 300],
      "credentials": {
        "postgres": {
          "id": "postgres-main-db",
          "name": "Main DB"
        }
      }
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT product_id, score FROM collaborative_recommendations WHERE user_id = '{{ $('Parse Request').item.json.user_id }}' ORDER BY score DESC LIMIT 20;",
        "options": {}
      },
      "id": "fetch-cf-candidates",
      "name": "Fetch CF Candidates",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.4,
      "position": [900, 200],
      "credentials": {
        "postgres": {
          "id": "postgres-main-db",
          "name": "Main DB"
        }
      }
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.pinecone.io/query",
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "pineconeApi",
        "sendBody": true,
        "bodyParameters": {
          "parameters": [
            {
              "name": "vector",
              "value": "={{ $json.query_embedding }}"
            },
            {
              "name": "topK",
              "value": "30"
            },
            {
              "name": "includeMetadata",
              "value": "true"
            },
            {
              "name": "filter",
              "value": "={{ { \"in_stock\": true, \"category\": $('Fetch User Profile').item.json.recent_categories } }}"
            }
          ]
        },
        "options": {}
      },
      "id": "vector-search-products",
      "name": "Vector Search Products",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [900, 400],
      "credentials": {
        "pineconeApi": {
          "id": "pinecone-vector-db",
          "name": "Pinecone Vector DB"
        }
      }
    },
    {
      "parameters": {
        "model": "text-embedding-3-small",
        "text": "={{ $('Fetch User Profile').item.json.recent_categories.join(' ') + ' ' + $('Parse Request').item.json.page_type + ' ' + $('Parse Request').item.json.current_sku }}",
        "options": {}
      },
      "id": "generate-query-embedding",
      "name": "Generate Query Embedding",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "typeVersion": 1,
      "position": [900, 300],
      "credentials": {
        "openAiApi": {
          "id": "openai-main",
          "name": "OpenAI Account"
        }
      }
    },
    {
      "parameters": {
        "mode": "combine",
        "combinationMode": "mergeByPosition",
        "options": {}
      },
      "id": "merge-candidates",
      "name": "Merge Candidates",
      "type": "n8n-nodes-base.merge",
      "typeVersion": 2.1,
      "position": [1120, 300]
    },
    {
      "parameters": {
        "jsCode": "// Combine CF and Vector search candidates, deduplicate, apply filters\nconst cfCandidates = $input.first().json.cf_results || [];\nconst vectorCandidates = $input.first().json.vector_matches || [];\nconst userProfile = $('Fetch User Profile').first().json;\nconst pageType = $('Parse Request').first().json.page_type;\n\n// Combine and deduplicate\nconst candidateMap = new Map();\n\ncfCandidates.forEach(item => {\n  candidateMap.set(item.product_id, {\n    product_id: item.product_id,\n    cf_score: item.score || 0,\n    vector_score: 0,\n    source: 'cf'\n  });\n});\n\nvectorCandidates.forEach(item => {\n  const pid = item.metadata?.product_id || item.id;\n  if (candidateMap.has(pid)) {\n    candidateMap.get(pid).vector_score = item.score || 0;\n    candidateMap.get(pid).source = 'hybrid';\n  } else {\n    candidateMap.set(pid, {\n      product_id: pid,\n      cf_score: 0,\n      vector_score: item.score || 0,\n      source: 'vector',\n      metadata: item.metadata\n    });\n  }\n});\n\n// Re-rank: hybrid score\nconst candidates = Array.from(candidateMap.values()).map(c => ({\n  ...c,\n  hybrid_score: (c.cf_score * 0.6) + (c.vector_score * 0.4)\n}));\n\n// Sort and limit\ncandidates.sort((a, b) => b.hybrid_score - a.hybrid_score);\nconst topCandidates = candidates.slice(0, 15);\n\nreturn topCandidates.map(c => ({ json: c }));"
      },
      "id": "rerank-filter",
      "name": "Re-rank & Filter",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1340, 300]
    },
    {
      "parameters": {
        "operation": "executeQuery",
        "query": "SELECT product_id, title, category, price, brand, description, image_url, in_stock, attributes FROM products WHERE product_id IN ({{ $json.map(i => \"'\" + i.product_id + \"'\").join(',') }});",
        "options": {}
      },
      "id": "fetch-product-details",
      "name": "Fetch Product Details",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.4,
      "position": [1560, 300],
      "credentials": {
        "postgres": {
          "id": "postgres-main-db",
          "name": "Main DB"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Build LLM prompt with user context and candidate products\nconst userProfile = $('Fetch User Profile').first().json;\nconst pageType = $('Parse Request').first().json.page_type;\nconst products = $input.all().map(i => i.json);\n\nconst userContext = `User segment: ${userProfile.rfm_segment || 'new'}. Recent categories: ${userProfile.recent_categories?.join(', ') || 'none'}. Avg order value: $${userProfile.avg_order_value || 0}. Page: ${pageType}.`;\n\nconst productList = products.map((p, idx) => \n  `${idx + 1}. ${p.title} (${p.brand}) - ${p.category} - $${p.price} - ${p.in_stock ? 'In stock' : 'Out of stock'}\\nKey features: ${p.attributes || p.description?.substring(0, 100)}`\n).join('\\n\\n');\n\nconst prompt = `You are a personalized e-commerce recommendation assistant. Your task is to recommend products from the candidate list below, tailored to the user profile and page context.\n\n## User Context\n${userContext}\n\n## Candidate Products\n${productList}\n\n## Instructions\n- Recommend 3-5 products from the list above that best match the user's profile and page context.\n- Write a short, engaging intro paragraph (2-3 sentences) explaining why these products fit.\n- For each product, include: product number from the list, title, and a 1-sentence personalized reason.\n- Use a friendly, conversational brand voice.\n- Only recommend in-stock products.\n- Format as JSON with structure: { \"intro\": \"...\", \"recommendations\": [{\"product_id\": \"...\", \"title\": \"...\", \"reason\": \"...\"}] }\n\nGenerate the recommendation now:`;\n\nreturn [{ json: { prompt, user_context: userContext, product_count: products.length } }];"
      },
      "id": "build-llm-prompt",
      "name": "Build LLM Prompt",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [1780, 300]
    },
    {
      "parameters": {
        "model": "gpt-4o-mini",
        "messages": {
          "values": [
            {
              "role": "system",
              "content": "You are a helpful product recommendation assistant. Always respond with valid JSON only."
            },
            {
              "role": "user",
              "content": "={{ $json.prompt }}"
            }
          ]
        },
        "options": {
          "temperature": 0.7,
          "maxTokens": 800,
          "responseFormat": "json_object"
        }
      },
      "id": "llm-generate",
      "name": "LLM Generate",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "typeVersion": 1.3,
      "position": [2000, 300],
      "credentials": {
        "openAiApi": {
          "id": "openai-main",
          "name": "OpenAI Account"
        }
      }
    },
    {
      "parameters": {
        "jsCode": "// Parse LLM output and enrich with product data\nconst llmOutput = JSON.parse($input.first().json.choices[0].message.content);\nconst products = $('Fetch Product Details').all().map(i => i.json);\nconst productMap = new Map(products.map(p => [p.product_id, p]));\n\n// Enrich recommendations with full product data\nconst enrichedRecommendations = llmOutput.recommendations.map(rec => {\n  const product = productMap.get(rec.product_id);\n  return {\n    ...rec,\n    price: product?.price,\n    image_url: product?.image_url,\n    category: product?.category,\n    in_stock: product?.in_stock\n  };\n});\n\nconst response = {\n  status: 'success',\n  user_id: $('Parse Request').first().json.user_id,\n  page_type: $('Parse Request').first().json.page_type,\n  intro: llmOutput.intro,\n  recommendations: enrichedRecommendations,\n  generated_at: new Date().toISOString()\n};\n\nreturn [{ json: response }];"
      },
      "id": "format-response",
      "name": "Format Response",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [2220, 300]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ $json }}",
        "options": {
          "responseHeaders": {
            "entries": [
              {
                "name": "Content-Type",
                "value": "application/json"
              }
            ]
          }
        }
      },
      "id": "respond-to-webhook",
      "name": "Respond to Webhook",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [2440, 300]
    },
    {
      "parameters": {
        "operation": "insert",
        "table": "recommendation_logs",
        "columns": "user_id, page_type, session_id, recommendations, created_at",
        "values": "={{ $('Parse Request').first().json.user_id }}, {{ $('Parse Request').first().json.page_type }}, {{ $('Parse Request').first().json.session_id }}, {{ JSON.stringify($json.recommendations) }}, NOW()",
        "options": {}
      },
      "id": "log-recommendation",
      "name": "Log Recommendation",
      "type": "n8n-nodes-base.postgres",
      "typeVersion": 2.4,
      "position": [2440, 480],
      "credentials": {
        "postgres": {
          "id": "postgres-main-db",
          "name": "Main DB"
        }
      }
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": false,
            "leftValue": ""
          },
          "conditions": [
            {
              "leftValue": "={{ $json.error }}",
              "rightValue": "",
              "operator": {
                "type": "string",
                "operation": "notEmpty"
              }
            }
          ],
          "combinator": "or"
        },
        "options": {}
      },
      "id": "check-errors",
      "name": "Check Errors",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [1340, 520]
    },
    {
      "parameters": {
        "assignments": {
          "assignments": [
            {
              "id": "status",
              "name": "status",
              "value": "error",
              "type": "string"
            },
            {
              "id": "message",
              "name": "message",
              "value": "Unable to generate recommendations. Please try again.",
              "type": "string"
            },
            {
              "id": "fallback_products",
              "name": "fallback_products",
              "value": "={{ $('Fetch Product Details').all().slice(0, 5) }}",
              "type": "object"
            }
          ]
        },
        "options": {}
      },
      "id": "fallback-response",
      "name": "Fallback Response",
      "type": "n8n-nodes-base.set",
      "typeVersion": 3.3,
      "position": [1560, 620]
    },
    {
      "parameters": {
        "respondWith": "json",
        "responseBody": "={{ $json }}",
        "options": {
          "responseCode": 200
        }
      },
      "id": "respond-fallback",
      "name": "Respond Fallback",
      "type": "n8n-nodes-base.respondToWebhook",
      "typeVersion": 1.1,
      "position": [1780, 620]
    }
  ],
  "connections": {
    "Webhook Trigger": {
      "main": [
        [
          {
            "node": "Parse Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Request": {
      "main": [
        [
          {
            "node": "Fetch User Profile",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch User Profile": {
      "main": [
        [
          {
            "node": "Fetch CF Candidates",
            "type": "main",
            "index": 0
          },
          {
            "node": "Generate Query Embedding",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch CF Candidates": {
      "main": [
        [
          {
            "node": "Merge Candidates",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate Query Embedding": {
      "main": [
        [
          {
            "node": "Vector Search Products",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Vector Search Products": {
      "main": [
        [
          {
            "node": "Merge Candidates",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "Merge Candidates": {
      "main": [
        [
          {
            "node": "Re-rank & Filter",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Re-rank & Filter": {
      "main": [
        [
          {
            "node": "Fetch Product Details",
            "type": "main",
            "index": 0
          },
          {
            "node": "Check Errors",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Product Details": {
      "main": [
        [
          {
            "node": "Build LLM Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build LLM Prompt": {
      "main": [
        [
          {
            "node": "LLM Generate",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "LLM Generate": {
      "main": [
        [
          {
            "node": "Format Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Format Response": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          },
          {
            "node": "Log Recommendation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Check Errors": {
      "main": [
        [
          {
            "node": "Fallback Response",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fallback Response": {
      "main": [
        [
          {
            "node": "Respond Fallback",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "settings": {
    "executionOrder": "v1"
  },
  "staticData": null,
  "tags": [],
  "triggerCount": 1,
  "updatedAt": "2025-12-19T08:00:00.000Z",
  "versionId": "1"
}
