{
  "meta": {
    "templateCredsSetupCompleted": true
  },
  "nodes": [
    {
      "id": "546667a2-bbc4-448b-bf5f-453c79b393b2",
      "name": "Embeddings OpenAI1",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "position": [
        2192,
        1424
      ],
      "parameters": {
        "options": {
          "dimensions": 1536
        }
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "41140d7a-85c0-4fd5-ba18-ffaea4cec4e0",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1984,
        1776
      ],
      "parameters": {
        "color": 7,
        "width": 864,
        "height": 592,
        "content": "## RAG pipeline\nSet the embedding Dimension to 1536 for openAI or 1024 for cohere\n"
      },
      "typeVersion": 1
    },
    {
      "id": "7ef686c2-e88a-4946-8f4a-1c40d4bb8bf4",
      "name": "Knowledgebase",
      "type": "@n8n/n8n-nodes-langchain.vectorStoreSupabase",
      "position": [
        2176,
        1120
      ],
      "parameters": {
        "mode": "retrieve-as-tool",
        "options": {
          "queryName": "match_documents"
        },
        "tableName": {
          "__rl": true,
          "mode": "list",
          "value": "documents",
          "cachedResultName": "documents"
        },
        "toolDescription": "Use this tool to retrieve the knowledge about customCX"
      },
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "4fe36bc9-c459-4e32-bca4-ce253b8fadf4",
      "name": "Recursive Character Text Splitter",
      "type": "@n8n/n8n-nodes-langchain.textSplitterRecursiveCharacterTextSplitter",
      "position": [
        2384,
        2288
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "076d68f9-7ae6-4aa6-a848-bdcf1c8e7e1f",
      "name": "Default Data Loader",
      "type": "@n8n/n8n-nodes-langchain.documentDefaultDataLoader",
      "position": [
        2304,
        2080
      ],
      "parameters": {
        "loader": "docxLoader",
        "options": {
          "metadata": {
            "metadataValues": [
              {
                "name": "file_id",
                "value": "={{ $('Set the fields for mapping').item.json.file_id }}"
              }
            ]
          }
        },
        "dataType": "binary",
        "textSplittingMode": "custom"
      },
      "typeVersion": 1.1
    },
    {
      "id": "d2a06568-b7d8-4055-8b0c-8af96b3d9295",
      "name": "Supabase Vector Store",
      "type": "@n8n/n8n-nodes-langchain.vectorStoreSupabase",
      "position": [
        2304,
        1856
      ],
      "parameters": {
        "mode": "insert",
        "options": {
          "queryName": "match_documents"
        },
        "tableName": {
          "__rl": true,
          "mode": "list",
          "value": "documents",
          "cachedResultName": "documents"
        }
      },
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "3e6861ac-651b-47af-ae72-943445a91f85",
      "name": "Route Types",
      "type": "n8n-nodes-base.switch",
      "position": [
        80,
        912
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "outputKey": "Text",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "2fc5c912-629b-4cbe-b5e3-7e3f0651c628",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.messages[0].type }}",
                    "rightValue": "text"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Audio",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "26a3d85c-0815-48ff-85ce-713129a1107c",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.messages[0].type }}",
                    "rightValue": "audio"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Image",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "840b95b8-6559-4fb7-b32c-651451d6d0d2",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.messages[0].type }}",
                    "rightValue": "image"
                  }
                ]
              },
              "renameOutput": true
            },
            {
              "outputKey": "Document",
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "3e7a07f9-b785-450c-8c68-f6b276838503",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $json.messages[0].type }}",
                    "rightValue": "document"
                  }
                ]
              },
              "renameOutput": true
            }
          ]
        },
        "options": {
          "fallbackOutput": "none"
        }
      },
      "typeVersion": 3.2
    },
    {
      "id": "e28e5b40-9c86-4242-a439-4200166a705d",
      "name": "Download Image",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1088,
        1280
      ],
      "parameters": {
        "url": "={{ $json.url }}",
        "options": {},
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi"
      },
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        },
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "092771f3-177a-477d-92b0-494d4469dd4f",
      "name": "Download Voicemail",
      "type": "n8n-nodes-base.httpRequest",
      "position": [
        1184,
        928
      ],
      "parameters": {
        "url": "={{ $json.url }}",
        "options": {},
        "authentication": "predefinedCredentialType",
        "nodeCredentialType": "whatsAppApi"
      },
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        },
        "httpHeaderAuth": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "10e2b196-3e13-4c72-a7f5-b482f0dad11b",
      "name": "Gets WhatsApp Image Source URL",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        864,
        1280
      ],
      "parameters": {
        "resource": "media",
        "operation": "mediaUrlGet",
        "mediaGetId": "={{ $json.messages[0].image.id }}"
      },
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "4e475e15-7da1-4841-be5b-e3a592205ffa",
      "name": "Gets WhatsApp Voicemail Source URL",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        944,
        928
      ],
      "parameters": {
        "resource": "media",
        "operation": "mediaUrlGet",
        "mediaGetId": "={{ $json.messages[0].audio.id}}"
      },
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "aeb70664-261b-4737-8938-39fc546d63cc",
      "name": "Map text prompt",
      "type": "n8n-nodes-base.set",
      "position": [
        1200,
        576
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "38aec976-a32c-4b0e-85f4-c90adc16abc9",
              "name": "text",
              "type": "string",
              "value": "={{ $json.messages[0].text.body }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "66612dd9-6790-4322-a2cb-da2297290235",
      "name": "Map image prompt",
      "type": "n8n-nodes-base.set",
      "position": [
        1536,
        1280
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "48af2dcc-4ce9-45fc-abfc-54f803930092",
              "name": "text",
              "type": "string",
              "value": "=User image description: {{ $json.content }}\n\nUser image caption: {{ $('Route Types').item.json.messages[0].image.caption }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "964af1dd-84eb-444c-ad39-5fdd026334bd",
      "name": "OpenAI1",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        1312,
        1280
      ],
      "parameters": {
        "text": "What's in this image? describe in relation to furnitures",
        "modelId": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4o-mini",
          "cachedResultName": "GPT-4O-MINI"
        },
        "options": {
          "detail": "auto"
        },
        "resource": "image",
        "inputType": "base64",
        "operation": "analyze"
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.8
    },
    {
      "id": "4af1715a-8d6c-4947-a5fd-d7fffe7cb40d",
      "name": "OpenAI",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        1408,
        928
      ],
      "parameters": {
        "options": {},
        "resource": "audio",
        "operation": "translate"
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.8
    },
    {
      "id": "ceca7fba-f1c8-4f09-a656-e14182729be6",
      "name": "WhatsApp Trigger",
      "type": "n8n-nodes-base.whatsAppTrigger",
      "position": [
        -224,
        944
      ],
      "parameters": {
        "options": {},
        "updates": [
          "messages"
        ]
      },
      "credentials": {
        "whatsAppTriggerApi": {
          "name": "<your credential>"
        }
      },
      "retryOnFail": true,
      "typeVersion": 1
    },
    {
      "id": "dafd9fc8-7e97-422e-9c75-a8d01f5f668d",
      "name": "Web Search",
      "type": "@n8n/n8n-nodes-langchain.toolSerpApi",
      "position": [
        2464,
        1120
      ],
      "parameters": {
        "options": {
          "google_domain": "google.com"
        }
      },
      "credentials": {
        "serpApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1
    },
    {
      "id": "2f3a3d0d-498a-468d-b2b1-50ec4d0aa9a9",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -832,
        320
      ],
      "parameters": {
        "width": 560,
        "height": 800,
        "content": "### How it works\nAn AI-powered sales agent on WhatsApp that handles product inquiries using your Supabase knowledge base and n8n catalog. Customers can send text, voice notes, or images to ask about products, pricing, and specs. The agent responds with detailed answers, product images, and FAQs, creating a complete self-service sales experience.\n(I primarily designed this for furniture business, consider tailoring it)\n### Setup steps\n\nConnect Supabase credentials for your knowledge base and FAQs\nConfigure n8n tables with your product catalog (prices, descriptions, image links)\nSet up WhatsApp Business API integration\nAdd your product categories and common queries to the AI context\nTest with sample product questions and image uploads\n\n### Customization tips\n\nStructure your catalog tables with clear columns (SKU, price, description, image_url)\nAdd industry-specific terminology to the AI prompt\nCreate templated responses for common FAQs to ensure consistency\nEnable voice-to-text transcription for better voice note handling\nAdd product recommendation logic based on customer queries\nSet up image recognition for customers sending product photos to identify items"
      },
      "typeVersion": 1
    },
    {
      "id": "fb01e422-f886-47a4-a7ad-82a5cee9368c",
      "name": "search_products_inventory",
      "type": "n8n-nodes-base.dataTableTool",
      "position": [
        2624,
        1120
      ],
      "parameters": {
        "operation": "get",
        "returnAll": true,
        "dataTableId": {
          "__rl": true,
          "mode": "list",
          "value": "7fZJtw2Bl8tyPLo8",
          "cachedResultUrl": "/projects/HwAYPGrWss6gpNyP/datatables/7fZJtw2Bl8tyPLo8",
          "cachedResultName": "ISTANBUL TURKISH FURNITURE"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "00e4b472-9565-4d55-b2c3-6909a2483764",
      "name": "If",
      "type": "n8n-nodes-base.if",
      "position": [
        3072,
        896
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 3,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "c619d220-e42e-4eb4-b54d-c68f7ed1bba5",
              "operator": {
                "type": "string",
                "operation": "empty",
                "singleValue": true
              },
              "leftValue": "={{ $json.imageUrl }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.3
    },
    {
      "id": "d46ff732-a7a5-4f03-98f7-4df50d6005a4",
      "name": "Send message1",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        1120,
        1648
      ],
      "parameters": {
        "textBody": "Please we do not support document upload",
        "operation": "send",
        "phoneNumberId": "={{ $('WhatsApp Trigger').item.json.metadata.phone_number_id }}",
        "additionalFields": {},
        "recipientPhoneNumber": "={{ $('WhatsApp Trigger').item.json.messages[0].from }}"
      },
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "67e0577d-1724-4454-88f8-bddede9eefe9",
      "name": "On form submission1",
      "type": "n8n-nodes-base.formTrigger",
      "position": [
        1712,
        1856
      ],
      "parameters": {
        "options": {
          "appendAttribution": false
        },
        "formTitle": "Turkey Furnitures KB",
        "formFields": {
          "values": [
            {
              "fieldName": "Knowledgebase",
              "fieldType": "file",
              "fieldLabel": "docs",
              "requiredField": true,
              "acceptFileTypes": ".pdf"
            }
          ]
        },
        "authentication": "basicAuth",
        "formDescription": "Upload FAQs docs"
      },
      "credentials": {
        "httpBasicAuth": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.4
    },
    {
      "id": "eb5249d4-a837-4998-86d8-231d3fde1e82",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        912,
        848
      ],
      "parameters": {
        "color": 7,
        "width": 592,
        "height": 256,
        "content": "## Upload Audio files\nFor processing audio"
      },
      "typeVersion": 1
    },
    {
      "id": "bd742123-4bd3-4ec9-bb3c-20424835a94d",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        832,
        1184
      ],
      "parameters": {
        "color": 7,
        "width": 784,
        "height": 272,
        "content": "## Upload image files\nFor processing images"
      },
      "typeVersion": 1
    },
    {
      "id": "4692e05b-87be-41ad-91cd-a5e953ed7996",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1072,
        1536
      ],
      "parameters": {
        "color": 7,
        "width": 224,
        "height": 256,
        "content": "## fall back response"
      },
      "typeVersion": 1
    },
    {
      "id": "ee835434-3d7d-4212-888f-c24bc08a7a91",
      "name": "the brain",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1888,
        1120
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-4.1-mini"
        },
        "options": {},
        "builtInTools": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "c220cf2a-dc93-4614-9271-b0d8eeb19829",
      "name": "System Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        2048,
        1120
      ],
      "parameters": {
        "sessionKey": "=memory_{{ $('WhatsApp Trigger').item.json.contacts[0].wa_id }}",
        "sessionIdType": "customKey",
        "contextWindowLength": 20
      },
      "typeVersion": 1.3
    },
    {
      "id": "da9e4a63-55f4-493e-829d-29117c60c0d0",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2656,
        672
      ],
      "parameters": {
        "color": 7,
        "width": 640,
        "height": 368,
        "content": "### Logic\n**Code node** \nIdentifies if output has image urls and then cleans them fto be sent to whatsapp as part of response\n\nThe code also validates the urls\n\n**If node** routes the  responses with no image to whatsapp text only\nwhile the other goes to media and caption"
      },
      "typeVersion": 1
    },
    {
      "id": "e92cae00-9599-4d38-aebb-0c8fdbff8f7e",
      "name": "Response_validation",
      "type": "n8n-nodes-base.code",
      "position": [
        2800,
        896
      ],
      "parameters": {
        "jsCode": "// ============================================================================\n// AI Response Parser & Cleaner\n// Purpose: Extract image URLs, remove annotations, clean ANSI codes, parse markdown\n// ============================================================================\n\n// Get AI response from multiple possible input fields\nconst aiResponse = \n    $input.item.json.output || \n    $input.item.json.message || \n    $input.item.json.response || \n    $input.item.json.text || \n    '';\n\n// If no response, return empty\nif (!aiResponse || typeof aiResponse !== 'string') {\n    return [{\n        json: {\n            message: '',\n            imageUrl: null,\n            hasImage: false\n        }\n    }];\n}\n\n// ============================================================================\n// STEP 1: Remove ANSI escape codes and annotations\n// ============================================================================\nfunction cleanAnnotations(text) {\n    let cleaned = text;\n    \n    // Remove ANSI escape codes (e.g., [32m[1m[0m)\n    cleaned = cleaned.replace(/\\[\\d+m/g, '');\n    cleaned = cleaned.replace(/\\x1b\\[\\d+m/g, ''); // Alternative ANSI format\n    \n    // Remove empty square brackets\n    cleaned = cleaned.replace(/\\[\\s*\\]/g, '');\n    \n    // Remove annotation patterns like [thought], [reasoning], [internal], etc.\n    cleaned = cleaned.replace(/\\[[a-zA-Z_]+\\]/g, '');\n    \n    // Remove multiple consecutive newlines (keep max 2)\n    cleaned = cleaned.replace(/\\n{3,}/g, '\\n\\n');\n    \n    return cleaned;\n}\n\n// ============================================================================\n// STEP 2: Extract image URL from various formats\n// ============================================================================\nfunction extractImageUrl(text) {\n    let imageUrl = null;\n    let cleanedText = text;\n    \n    // Pattern 1: ||IMG:url|| format (your custom format)\n    const customPattern = /\\|\\|IMG:(.*?)\\|\\|/;\n    const customMatch = text.match(customPattern);\n    if (customMatch) {\n        imageUrl = customMatch[1].trim();\n        cleanedText = text.replace(customPattern, '').trim();\n        return { imageUrl, cleanedText };\n    }\n    \n    // Pattern 2: Markdown image format ![alt](url)\n    const markdownPattern = /!\\[.*?\\]\\((https?:\\/\\/[^\\)]+)\\)/;\n    const markdownMatch = text.match(markdownPattern);\n    if (markdownMatch) {\n        imageUrl = markdownMatch[1].trim();\n        // Remove the entire markdown image syntax\n        cleanedText = text.replace(markdownPattern, '').trim();\n        return { imageUrl, cleanedText };\n    }\n    \n    // Pattern 3: Raw URL starting with https://www.buyfromturkeynj.com/image/\n    const urlPattern = /(https?:\\/\\/www\\.buyfromturkeynj\\.com\\/image\\/[^\\s<>\\)]+\\.(?:jpg|jpeg|png|gif|webp))/i;\n    const urlMatch = text.match(urlPattern);\n    if (urlMatch) {\n        imageUrl = urlMatch[1].trim();\n        // Remove the URL from text\n        cleanedText = text.replace(urlPattern, '').trim();\n        return { imageUrl, cleanedText };\n    }\n    \n    // Pattern 4: Generic image URL (fallback)\n    const genericUrlPattern = /(https?:\\/\\/[^\\s<>\\)]+\\.(?:jpg|jpeg|png|gif|webp))/i;\n    const genericMatch = text.match(genericUrlPattern);\n    if (genericMatch) {\n        imageUrl = genericMatch[1].trim();\n        cleanedText = text.replace(genericUrlPattern, '').trim();\n        return { imageUrl, cleanedText };\n    }\n    \n    // No image found\n    return { imageUrl: null, cleanedText };\n}\n\n// ============================================================================\n// STEP 3: Process the response\n// ============================================================================\n\n// First, clean annotations\nlet processedText = cleanAnnotations(aiResponse);\n\n// Then, extract image URL\nconst { imageUrl, cleanedText } = extractImageUrl(processedText);\n\n// Final cleanup\nlet finalMessage = cleanedText\n    .replace(/\\n{3,}/g, '\\n\\n')  // Remove excessive newlines\n    .trim();\n\n// ============================================================================\n// STEP 4: Return formatted output for n8n\n// ============================================================================\nreturn [{\n    json: {\n        message: finalMessage,\n        imageUrl: imageUrl,\n        hasImage: imageUrl !== null,\n        // Optional: Include original for debugging\n        // originalOutput: aiResponse\n    }\n}];"
      },
      "typeVersion": 2
    },
    {
      "id": "61761fb7-4e69-4abd-b00d-34b115b72086",
      "name": "Send text message",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        3440,
        688
      ],
      "parameters": {
        "textBody": "={{ $json.message }}",
        "operation": "send",
        "phoneNumberId": "={{ $('WhatsApp Trigger').item.json.metadata.phone_number_id }}",
        "additionalFields": {},
        "recipientPhoneNumber": "={{ $('WhatsApp Trigger').item.json.messages[0].from }}"
      },
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "3b4c3708-1392-4d71-b7ca-28c22c7e8f12",
      "name": "Send media&caption message",
      "type": "n8n-nodes-base.whatsApp",
      "position": [
        3504,
        1120
      ],
      "parameters": {
        "mediaLink": "={{ $json.imageUrl }}",
        "operation": "send",
        "messageType": "image",
        "phoneNumberId": "={{ $('WhatsApp Trigger').item.json.metadata.phone_number_id }}",
        "additionalFields": {
          "mediaCaption": "={{ $json.message }}"
        },
        "recipientPhoneNumber": "={{ $('WhatsApp Trigger').item.json.messages[0].from }}"
      },
      "credentials": {
        "whatsAppApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "043f02cc-4dcc-4f5d-bc57-58decf10062b",
      "name": "Sales AI agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        2192,
        896
      ],
      "parameters": {
        "text": "=whatsapp message:{{ $json.text }}",
        "options": {
          "systemMessage": "=# TURK - AI Sales Agent System Prompt v2.0\n**Istanbul Turkish Furniture (BuyFromTurkeyNJ.com)**\n\n---\n\n## CORE IDENTITY\nYou are TURK, a professional furniture consultant representing Istanbul Turkish Furniture. You help customers worldwide discover premium Turkish furniture with expert guidance and accurate product information.\n\n**Brand Voice**: Warm, knowledgeable, customer-focused consultant (NOT a robotic chatbot)\n**Response Style**: Conversational, concise (2-4 sentences), naturally helpful\n**Primary Goal**: Understand customer needs, provide accurate product info, qualify serious buyers\n\n---\n\n## AVAILABLE TOOLS & WHEN TO USE THEM\n\n### 1. **search_products_inventory** \n**USE THIS TOOL for ANY product-related questions:**\n- Customer asks about specific products (e.g., \"show me dining sets\")\n- Customer wants to see furniture types (e.g., \"bedroom furniture\")\n- Customer asks about prices, availability, or models\n- Customer sends an image asking \"do you have this?\"\n\n**What this tool provides:**\n- ProductID, ProductName, ProductModel\n- Price (accurate, current pricing)\n- StockStatus (In Stock / Out of Stock)\n- ProductDescription\n- ProductLink (for purchase)\n- MainImage & AdditionalImages (URLs to send)\n\n**How to use:**\n- Query with customer's search terms (e.g., \"dining\", \"sofa\", \"bedroom\")\n- ALWAYS get MainImage link to send to customer\n- ALWAYS mention exact price from tool results\n- ALWAYS share ProductLink for more details\n\n### 2. **web_search**\n**USE THIS TOOL for:**\n- Real-time information not in your knowledge (e.g., \"latest design trends\")\n- Current shipping rates to specific countries\n- Currency conversions\n- Competitor comparisons customer asks about\n- Industry information\n\n**DO NOT use for:** Product catalog queries (use search_products_inventory instead)\n\n### 3. **removeAnnotations_tool**\n**ALWAYS execute this tool** before sending your final response to remove AI-like artifacts and ensure clean, natural communication.\n\n### 4. **Knowledge Base (FAQs)**\n**Contains information about:**\n- Shipping policies and timelines\n- Company background\n- General furniture care\n- Return policies\n- Customization options\n\n**Use for:** General company questions, policies, procedures\n\n---\n\n## CUSTOMER DATA AVAILABLE TO YOU\n\n**From WhatsApp Trigger:**\n- Customer Name: `{{ $('WhatsApp Trigger').item.json.contacts[0].profile.name }}`\n- Phone Number: `{{ $('WhatsApp Trigger').item.json.contacts[0].wa_id }}`\n\n**How to use:**\n- Use customer's name naturally 1-2 times per conversation (not every message)\n- Identify country from phone country code (first 1-3 digits of wa_id)\n- Personalize shipping information based on detected country\n\n---\n\n## CONVERSATION FLOW & RESPONSES\n\n### OPENING MESSAGE (New Customer)\n```\nHi [Name]! \ud83d\udc4b I'm TURK from Istanbul Turkish Furniture. \n\nWhat type of furniture are you looking for today? I can show you our latest collections with images and prices.\n```\n\n### WHEN CUSTOMER ASKS ABOUT PRODUCTS\n\n**Step 1:** Call `search_products_inventory` with their search terms\n**Step 2:** Send product image(s) via WhatsApp Media\n**Step 3:** Respond with:\n```\n[Product Name]\n\ud83d\udcb0 Price: $[exact price from tool]\n\ud83d\udce6 [Stock status from tool]\n\n[Brief 1-sentence description]\n\n\ud83d\udd17 Full details: [ProductLink from tool]\n\nWould you like to see more options or get specific details about this piece?\n```\n\n**CRITICAL:** Never make up prices. Always use exact data from search_products_inventory tool.\n\n### WHEN CUSTOMER SENDS AN IMAGE\n\n**Step 1:** Acknowledge the image\n```\nI can see you're interested in [describe style/type]. Let me find similar pieces in our collection.\n```\n\n**Step 2:** Call `search_products_inventory` based on what you see\n**Step 3:** Send matching product images with details\n\n### WHEN CUSTOMER ASKS ABOUT SHIPPING\n\n**Step 1:** Check knowledge base for shipping policies\n**Step 2:** Identify customer's country from phone code\n**Step 3:** Provide region-specific information:\n\n**Example:**\n```\nWe ship worldwide! Based on your location in [Country], typical delivery is [X weeks].\n\nShipping includes:\n\u2713 Sea freight to major ports\n\u2713 Customs documentation\n\u2713 Door-to-door delivery options\n\nFor accurate shipping costs, I'll need your full delivery address. Would you like me to connect you with our logistics team?\n```\n\n### WHEN CUSTOMER ASKS ABOUT PRICING\n\n**Always:**\n1. Use search_products_inventory for accurate prices\n2. Mention prices are in USD\n3. Note: \"Price shown is for the furniture only. Shipping calculated separately based on your location.\"\n4. Offer currency conversion if customer mentions local currency\n\n**Example:**\n```\nThe [Product Name] is $[exact price] USD (approximately [X] in your local currency).\n\nThis is for the furniture piece only. Shipping to [Country] is calculated separately based on:\n- Destination city\n- Delivery timeline preference\n- Sea vs. air freight\n\nWould you like a full quote including shipping?\n```\n\n### LEAD QUALIFICATION QUESTIONS\n\n**Ask naturally during conversation (not all at once):**\n1. \"What type of furniture are you looking for?\" (Discovery)\n2. \"Is this for your home or a commercial project?\" (Scope)\n3. \"What's your timeline for delivery?\" (Urgency)\n4. \"Where should we ship this to?\" (Location specifics)\n5. \"Do you have a budget range in mind?\" (Financial qualification)\n\n**Capture for handoff to sales team:**\n- \u2705 Name\n- \u2705 Email or WhatsApp number\n- \u2705 Country & City\n- \u2705 Furniture type/quantity\n- \u2705 Budget range (if shared)\n- \u2705 Timeline\n\n---\n\n## PRODUCT RECOMMENDATIONS\n\n### When Customer is Browsing:\n1. Show 2-3 products maximum per message (avoid overwhelming)\n2. Always include images\n3. Mention bestsellers: \"This is very popular with customers in [their region]\"\n4. Suggest alternatives: \"If you prefer [style], let me show you...\"\n\n### Cross-Selling (After Interest Shown):\n```\nLove this [dining set]? Customers often pair it with our [matching console/chairs]. \n\nWould you like to see complementary pieces?\n```\n\n---\n\n## HANDLING DIFFERENT MEDIA TYPES\n\n### VOICE NOTES:\n1. Listen/transcribe the key points\n2. Acknowledge: \"Thanks for the voice note! I understand you're looking for [summary].\"\n3. Respond with relevant product search results\n4. Ask clarifying questions if needed\n\n### DOCUMENTS (PDFs, Images of Requirements):\n1. Acknowledge: \"Thanks for sharing your requirements.\"\n2. Summarize what you see: \"I see you need [X quantity] of [furniture type]\"\n3. Call search_products_inventory for matching items\n4. Offer: \"Would you like me to connect you with our custom manufacturing team for this project?\"\n\n### MULTIPLE IMAGES:\n1. \"I see you've shared [X] images. Let me find pieces that match this style.\"\n2. Search for each relevant type\n3. Present in organized manner with clear product separation\n\n---\n\n## ESCALATION TO SALES TEAM\n\n### Escalate When:\n- Customer requests formal quote with shipping\n- Large commercial/bulk orders\n- Custom manufacturing requests\n- Specific import/regulatory questions\n- Payment and order placement\n\n### Handoff Message:\n```\nPerfect! I'll connect you with our sales team who can provide:\n\u2713 Detailed quote with shipping to [City, Country]\n\u2713 Customization options\n\u2713 Payment terms\n\u2713 Delivery timeline\n\nMay I have your email to send the introduction? They typically respond within 24 hours.\n```\n\n**DO NOT:**\n- Promise exact delivery dates\n- Guarantee customs clearance\n- Process payments yourself\n- Make custom manufacturing commitments without sales team\n\n---\n\n## RESPONSE QUALITY RULES\n\n### \u2705 DO:\n- Use customer's name naturally (1-2 times per conversation)\n- Send product images for EVERY product discussed\n- Provide exact prices from search_products_inventory\n- Share product links for customer self-service\n- Ask one question at a time\n- Use emojis sparingly (1-2 per message max)\n- Be concise (2-4 sentences ideal)\n- Match customer's energy and formality\n\n### \u274c DON'T:\n- Sound robotic or overly formal\n- Use corporate jargon (\"leverage\", \"utilize\", \"facilitate\")\n- Make up prices or availability\n- Over-use emojis (\u274c no emoji spam)\n- Send walls of text\n- Ask multiple questions in one message\n- Use phrases like \"I'd be happy to assist you today\" (too robotic)\n- Say \"How may I help you?\" (use \"What are you looking for?\")\n\n---\n\n## TONE EXAMPLES\n\n### \u274c ROBOTIC (Avoid):\n\"Greetings! I would be delighted to assist you in finding the perfect furniture solution for your residential or commercial establishment today. How may I be of service?\"\n\n### \u2705 NATURAL (Use):\n\"Hi! What type of furniture are you shopping for? I can show you some great options with prices.\"\n\n---\n\n### \u274c ROBOTIC (Avoid):\n\"Thank you for your inquiry regarding our dining set collection. I am pleased to inform you that we have several options available in our inventory.\"\n\n### \u2705 NATURAL (Use):\n\"We have some beautiful dining sets! Let me show you a few with prices and photos.\"\n\n---\n\n## REGIONAL SHIPPING INTELLIGENCE\n\n**Detect country from phone code, then mention:**\n\n### North America (US/Canada):\n- \"We have a warehouse in New Jersey for faster US delivery\"\n- \"Typical delivery: 2-3 weeks from our NJ location\"\n- \"White-glove delivery available\"\n\n### Europe:\n- \"Delivery to [Country]: 3-5 weeks\"\n- \"VAT documentation provided\"\n- \"CE certified furniture\"\n\n### Middle East:\n- \"Popular destination for us! Delivery: 2-4 weeks\"\n- \"We specialize in styles popular in the Gulf region\"\n\n### Asia/Australia:\n- \"Delivery: 8-10 weeks via sea freight\"\n- \"We treat woods for tropical climates\"\n\n### Africa:\n- \"We work with reliable logistics partners in [Region]\"\n- \"Delivery: 6-9 weeks\"\n\n---\n\n## SAMPLE CONVERSATIONS\n\n### Conversation 1: Product Inquiry\n**Customer:** \"Do you have dining sets?\"\n\n**TURK:** \n*[Calls search_products_inventory with query: \"dining\"]*\n*[Gets results with 3 products]*\n*[Sends WhatsApp Media with first product image]*\n\n\"Yes! Here's our TIGER Luxury Dining Set - very popular.\n\n\ud83d\udcb0 Price: $3,500\n\ud83d\udce6 In Stock\n\nIncludes: Dining table, 6 chairs, console & mirror\n\n\ud83d\udd17 https://www.buyfromturkeynj.com/tiger-luxury-dining-set\n\nWant to see more dining options or details about this one?\"\n\n---\n\n### Conversation 2: Price Question\n**Customer:** \"How much is the Versace sofa?\"\n\n**TURK:**\n*[Calls search_products_inventory with query: \"Versace sofa\"]*\n*[Gets exact price: $4,424]*\n*[Sends product image]*\n\n\"The Versace Avangard Sofa Set is $4,424 USD.\n\n\ud83d\udce6 In Stock\nIncludes: 3-seat sofa + 2 single chairs\n\nThis is furniture price only - shipping to your location calculated separately. Where are you located?\"\n\n---\n\n### Conversation 3: Shipping Question\n**Customer:** \"Do you ship to Dubai?\"\n\n**TURK:**\n*[Detects country from phone code or mentioned location]*\n*[Checks knowledge base for shipping info]*\n\n\"Yes, we ship to Dubai regularly! \n\nDelivery time: 2-4 weeks\nWe handle all customs documentation for UAE.\n\nWhat type of furniture are you interested in? I can show you pieces popular in the Gulf region.\"\n\n---\n\n## CLOSING & LEAD CAPTURE\n\n### When Customer Shows Strong Interest:\n```\nGreat choice! To provide a complete quote including shipping to [City, Country], our sales team will need:\n\n\u2022 Your email address\n\u2022 Exact delivery address\n\u2022 Preferred delivery timeline\n\nMay I have your email to connect you with them?\n```\n\n### After Information Collected:\n```\nPerfect! I'll have our sales team reach out within 24 hours with:\n\u2713 Full quote (furniture + shipping)\n\u2713 Payment options\n\u2713 Delivery timeline\n\nThey'll email you at [email]. Feel free to message here if you have more questions!\n```\n\n---\n\n## IMPORTANT REMINDERS\n\n1. **ALWAYS use search_products_inventory for product info** - Never guess prices or availability\n2. **ALWAYS send product images** - Visual confirmation is critical\n3. **ALWAYS use removeAnnotations_tool** - Clean output before sending\n4. **Be conversational, not corporate** - You're a helpful consultant, not a bot\n5. **One question at a time** - Don't interrogate customers\n6. **Accurate information only** - When unsure, check knowledge base or escalate\n\n---\n\n## ERROR HANDLING\n\n### If search_products_inventory returns no results:\n```\nI don't see that exact item in our current catalog, but we have similar pieces. What specific style or type are you looking for? I can show you alternatives.\n```\n\n### If customer asks something outside your knowledge:\n```\nGreat question! Let me connect you with our team who specializes in [topic]. They can give you detailed information. May I have your email?\n```\n\n### If tool fails:\n```\nLet me look that up for you - one moment please.\n[Try again, or if repeated failure]: I'm having a brief technical issue. May I have your email so our team can send you this information directly?\n```\n\n---\n\n**Remember: You're a knowledgeable furniture consultant who helps customers find exactly what they need with accurate, real-time information. Be helpful, be accurate, be human.**\n\n##Remember\nif a client asks for office chair or table your can never respond nor retrieve a TV stand nor any electroncis. *context is key here"
        },
        "promptType": "define"
      },
      "typeVersion": 1.9
    }
  ],
  "connections": {
    "If": {
      "main": [
        [
          {
            "node": "Send text message",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send media&caption message",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI": {
      "main": [
        [
          {
            "node": "Sales AI agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI1": {
      "main": [
        [
          {
            "node": "Map image prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "the brain": {
      "ai_languageModel": [
        [
          {
            "node": "Sales AI agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Web Search": {
      "ai_tool": [
        [
          {
            "node": "Sales AI agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Route Types": {
      "main": [
        [
          {
            "node": "Map text prompt",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Gets WhatsApp Voicemail Source URL",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Gets WhatsApp Image Source URL",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Send message1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Knowledgebase": {
      "ai_tool": [
        [
          {
            "node": "Sales AI agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "System Memory": {
      "ai_memory": [
        [
          {
            "node": "Sales AI agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Download Image": {
      "main": [
        [
          {
            "node": "OpenAI1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sales AI agent": {
      "main": [
        [
          {
            "node": "Response_validation",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Map text prompt": {
      "main": [
        [
          {
            "node": "Sales AI agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Map image prompt": {
      "main": [
        [
          {
            "node": "Sales AI agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "WhatsApp Trigger": {
      "main": [
        [
          {
            "node": "Route Types",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Send text message": {
      "main": [
        []
      ]
    },
    "Download Voicemail": {
      "main": [
        [
          {
            "node": "OpenAI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings OpenAI1": {
      "ai_embedding": [
        [
          {
            "node": "Knowledgebase",
            "type": "ai_embedding",
            "index": 0
          },
          {
            "node": "Supabase Vector Store",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Default Data Loader": {
      "ai_document": [
        [
          {
            "node": "Supabase Vector Store",
            "type": "ai_document",
            "index": 0
          }
        ]
      ]
    },
    "On form submission1": {
      "main": [
        [
          {
            "node": "Supabase Vector Store",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Response_validation": {
      "main": [
        [
          {
            "node": "If",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "search_products_inventory": {
      "ai_tool": [
        [
          {
            "node": "Sales AI agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Gets WhatsApp Image Source URL": {
      "main": [
        [
          {
            "node": "Download Image",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Recursive Character Text Splitter": {
      "ai_textSplitter": [
        [
          {
            "node": "Default Data Loader",
            "type": "ai_textSplitter",
            "index": 0
          }
        ]
      ]
    },
    "Gets WhatsApp Voicemail Source URL": {
      "main": [
        [
          {
            "node": "Download Voicemail",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}