AutomationFlowsAI & RAG › Build an Advanced Multi-query RAG System with Supabase and Gpt-5

Build an Advanced Multi-query RAG System with Supabase and Gpt-5

ByGuillaume Duvernay @duv on n8n.io

Go beyond basic Retrieval-Augmented Generation (RAG) with this advanced template. While a simple RAG setup can answer straightforward questions, it often fails when faced with complex queries and can be polluted by irrelevant information. This workflow introduces a sophisticated…

Chat trigger trigger★★★★☆ complexityAI-powered22 nodesAgentChat TriggerOpenAI ChatMemory Buffer WindowExecute Workflow TriggerTool WorkflowSupabase Vector StoreOpenAI Embeddings
AI & RAG Trigger: Chat trigger Nodes: 22 Complexity: ★★★★☆ AI nodes: yes Added:

This workflow corresponds to n8n.io template #7779 — we link there as the canonical source.

This workflow follows the Agent → Chat Trigger 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
{
  "nodes": [
    {
      "id": "14e54443-1722-476a-9f7a-44be7bd2b2bf",
      "name": "AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        208,
        -704
      ],
      "parameters": {
        "options": {
          "systemMessage": "=You are a helpful assistant that answers based on a biology course.\n\nFor that, you always start by calling the tool \"Query knowledge base\" to send an array of 1 to 5 questions that are relevant to ask to the RAG knowledge base that contains all the content of the course and get as an output all chunks that seem to help to craft the final answer. The more the user query is complex, the more you will break it down into sub-queries (up to 5).\n\nFrom there, use the Think tool to critically analyse the initial user query and the content you've retrieved from the knowledge retrieval tool and reason to prepare the best answer possible, challenge the content to be sure that you actually have the right information to be able to respond.\n\nOnly answer based on the course content that you get from using the tool, if you receive any question outside that scope, redirect the conversation, if you don't have the right information to answer, be transparent and say so - don't try to reply anyway with general knowledge.",
          "enableStreaming": false
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "4df46be3-c8b7-4f88-9af2-a644ca1bab2d",
      "name": "When chat message received",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        -256,
        -704
      ],
      "parameters": {
        "public": true,
        "options": {
          "responseMode": "lastNode"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "5f07d924-7727-478a-abf6-eaf11543e19b",
      "name": "OpenAI Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        48,
        -480
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "gpt-5-mini",
          "cachedResultName": "gpt-5-mini"
        },
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "dfc7c805-79cc-4326-8edb-f53a88af285d",
      "name": "Simple Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        240,
        -480
      ],
      "parameters": {
        "contextWindowLength": 8
      },
      "typeVersion": 1.3
    },
    {
      "id": "7ade6fc1-84cc-48b2-bb20-672f0c5b4c27",
      "name": "Split Out",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        -160,
        96
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "queries"
      },
      "typeVersion": 1
    },
    {
      "id": "f4c92e45-e037-4477-ac50-1d6096fd902e",
      "name": "Aggregate chunks",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        1312,
        0
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData",
        "destinationFieldName": "All chunks for this question"
      },
      "typeVersion": 1
    },
    {
      "id": "cb5d42fe-9e27-4117-8a1c-9a78da8e770f",
      "name": "Aggregate items",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        352,
        -208
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData",
        "destinationFieldName": "Knowledge base retrieval"
      },
      "typeVersion": 1
    },
    {
      "id": "4e7f3e28-c316-4e21-b505-a211c1b23841",
      "name": "Any chunk?",
      "type": "n8n-nodes-base.if",
      "position": [
        1088,
        96
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "66402fe0-918e-4268-8928-f4e83cbb3c4f",
              "operator": {
                "type": "string",
                "operation": "exists",
                "singleValue": true
              },
              "leftValue": "={{ $json['Chunk content'] }}",
              "rightValue": ""
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "26d04029-da7f-4292-802a-4c233caef219",
      "name": "Clean RAG output",
      "type": "n8n-nodes-base.set",
      "position": [
        640,
        96
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "1eddb72f-9c99-465b-8f94-0ff0f686b542",
              "name": "Chunk content",
              "type": "string",
              "value": "={{ $json.document.pageContent }}"
            },
            {
              "id": "09fe6c91-2cce-40ff-9f8c-86a6857f0772",
              "name": "=Chunk metadata",
              "type": "object",
              "value": "={\n  \"Resource chapter name\": \"{{ $json.document.metadata['Chapter name'] }}\",\n  \"Retrieval relevance score\": {{ $json.score.round(2) }}\n}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "545514d9-107e-4af9-b407-7cdfc3770e3f",
      "name": "Loop Over Items1",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        64,
        96
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 3
    },
    {
      "id": "ebdbaea5-405f-4a58-b0b4-198154344329",
      "name": "RAG sub-workflow",
      "type": "n8n-nodes-base.executeWorkflowTrigger",
      "position": [
        -384,
        96
      ],
      "parameters": {
        "workflowInputs": {
          "values": [
            {
              "name": "queries",
              "type": "array"
            }
          ]
        }
      },
      "typeVersion": 1.1
    },
    {
      "id": "d2362d6f-a6a0-4651-9f2b-827b8f7eb1c1",
      "name": "Query knowledge base",
      "type": "@n8n/n8n-nodes-langchain.toolWorkflow",
      "position": [
        432,
        -480
      ],
      "parameters": {
        "workflowId": {
          "__rl": true,
          "mode": "list",
          "value": "c9FlK6mLuWAwqLsP",
          "cachedResultName": "TEMPLATE RAG with Supabase and GPT5"
        },
        "description": "Call this tool to get content about the biology course before crafting your final user answer. Send an array of queries to the knowledge base.",
        "workflowInputs": {
          "value": {
            "queries": "={{ $fromAI('queries', `The array of queries (between 1 and 5) that you've planned to ask to the RAG knowledge base of the course. \nUse an Array format even if there's only one question - this is necessary to not break the workflow format!\n\nExample array output: \n\n[\n  {\n    \"query\": \"What is Lorem ipsum sir amet?\"\n  },\n  {\n    \"query\": \"How to lorem ipsum dolor sir lorem when lorem ipsum?'?\"\n  },\n  {\n    \"query\": \"Lorem ipsum lorem ipsum dolor sir lorem when lorem ipsum??\"\n  }\n]\n`, 'json') }}"
          },
          "schema": [
            {
              "id": "queries",
              "type": "array",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "queries",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "queries"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "db958756-f1a2-4162-afcf-2b6a0f936200",
      "name": "Supabase Vector Store1",
      "type": "@n8n/n8n-nodes-langchain.vectorStoreSupabase",
      "position": [
        288,
        96
      ],
      "parameters": {
        "mode": "load",
        "prompt": "={{ $json.query }}",
        "options": {
          "queryName": "match_documents"
        },
        "tableName": {
          "__rl": true,
          "mode": "list",
          "value": "documents",
          "cachedResultName": "documents"
        }
      },
      "credentials": {
        "supabaseApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.3
    },
    {
      "id": "478c2c07-ec28-427e-b33a-85a0f72c576f",
      "name": "Embeddings OpenAI1",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOpenAi",
      "position": [
        368,
        320
      ],
      "parameters": {
        "options": {}
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "da138097-8c28-4662-b916-8de388894330",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -480,
        -832
      ],
      "parameters": {
        "color": 5,
        "width": 1472,
        "height": 528,
        "content": "# AI agent"
      },
      "typeVersion": 1
    },
    {
      "id": "93a8e212-2a8f-4e9f-8956-b1cca02da212",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -480,
        -272
      ],
      "parameters": {
        "color": 4,
        "width": 2320,
        "height": 768,
        "content": "# Sub-workflow, tool for agent\n"
      },
      "typeVersion": 1
    },
    {
      "id": "21ade708-3f0e-4419-9edb-bc57fb543963",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        816,
        -80
      ],
      "parameters": {
        "color": 7,
        "width": 688,
        "height": 432,
        "content": "## Filtering system\nOnly keeping chunks that have a score >0.4"
      },
      "typeVersion": 1
    },
    {
      "id": "ce4ce8ce-0f12-4dc6-ab24-585a81d71ca5",
      "name": "Think",
      "type": "@n8n/n8n-nodes-langchain.toolThink",
      "position": [
        608,
        -480
      ],
      "parameters": {
        "description": "Use this tool after you got the output of the knowledge retrieval tool to critically analyse the initial user query and the content you've retrieved from the knowledge retrieval tool and reason to prepare the best answer possible, challenge the content to be sure that you actually have the right information to be able to respond.\n\nBe very token efficient when using this tool, write 50 words max which is enough to reason."
      },
      "typeVersion": 1.1
    },
    {
      "id": "f1d619f3-42fb-4f48-83b3-3c0d1c43d574",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1024,
        -832
      ],
      "parameters": {
        "width": 512,
        "height": 784,
        "content": "# Advanced Multi-Query RAG Agent\n\nThis template demonstrates a sophisticated RAG (Retrieval-Augmented Generation) pattern for building high-quality AI agents. It's designed to overcome the limitations of a basic RAG setup.\n\n## How it works\n\nInstead of a simple query, this agent uses a more intelligent, four-step process:\n1.  **Decompose:** It breaks complex questions into multiple, simpler sub-queries.\n2.  **Retrieve:** It sends these queries to a smart sub-workflow that fetches data from your vector store.\n3.  **Filter:** The sub-workflow filters out any retrieved information that doesn't meet a minimum relevance score, ensuring high-quality context.\n4.  **Synthesize:** The agent uses a \"Think\" tool to reason over the filtered information before crafting a final, comprehensive answer.\n\n## How to use\n\n1.  **Connect your accounts:** You need to connect **Supabase** and **OpenAI** in both this main workflow and in the \"RAG sub-workflow\".\n2.  **Customize the agent:** Edit the **AI Agent's system prompt** to match your specific knowledge base (e.g., \"You are a helpful assistant that answers based on our company's internal documents.\").\n3.  **Adjust the relevance filter:** In the sub-workflow, you can change the similarity score in the **Filter** node (default is >0.4) to control the quality of the retrieved information."
      },
      "typeVersion": 1
    },
    {
      "id": "b26b291d-9f95-4012-b830-cd07a9b8015f",
      "name": "Keep score over 0.4",
      "type": "n8n-nodes-base.filter",
      "position": [
        864,
        96
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "9a3f844e-7d19-4631-9876-140118e61b6b",
              "operator": {
                "type": "number",
                "operation": "gt"
              },
              "leftValue": "={{ $json['Chunk metadata']['Retrieval relevance score'] }}",
              "rightValue": 0.4
            }
          ]
        }
      },
      "typeVersion": 2.2,
      "alwaysOutputData": true
    },
    {
      "id": "14d3efaf-dc35-491f-91df-f085829812ee",
      "name": "Say no chunk match",
      "type": "n8n-nodes-base.set",
      "position": [
        1312,
        192
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "245fe8f8-b217-4626-bc4d-84f53e47fbbf",
              "name": "Retrieval output",
              "type": "string",
              "value": "=No chunks reached the relevance threshold, the knowledge base was unable to provide information that would be helpful to answer this question."
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "e9eb2328-e9e2-4138-9d9e-468359a5e49d",
      "name": "Prepare loop output",
      "type": "n8n-nodes-base.set",
      "position": [
        1568,
        192
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "838f21a4-f7bc-414e-83da-99fbaca4fcca",
              "name": "Query to the knowledge base",
              "type": "string",
              "value": "={{ $('Loop Over Items1').first().json.query }}"
            },
            {
              "id": "10a89085-1937-459f-9721-8715cd51ad39",
              "name": "Chunks returned",
              "type": "string",
              "value": "={{ JSON.stringify($json, null, 2) }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    }
  ],
  "connections": {
    "Think": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "AI Agent": {
      "main": [
        []
      ]
    },
    "Split Out": {
      "main": [
        [
          {
            "node": "Loop Over Items1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Any chunk?": {
      "main": [
        [
          {
            "node": "Aggregate chunks",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Say no chunk match",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simple Memory": {
      "ai_memory": [
        [
          {
            "node": "AI Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate chunks": {
      "main": [
        [
          {
            "node": "Prepare loop output",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Clean RAG output": {
      "main": [
        [
          {
            "node": "Keep score over 0.4",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items1": {
      "main": [
        [
          {
            "node": "Aggregate items",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Supabase Vector Store1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "RAG sub-workflow": {
      "main": [
        [
          {
            "node": "Split Out",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAI Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings OpenAI1": {
      "ai_embedding": [
        [
          {
            "node": "Supabase Vector Store1",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Say no chunk match": {
      "main": [
        [
          {
            "node": "Prepare loop output",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Keep score over 0.4": {
      "main": [
        [
          {
            "node": "Any chunk?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare loop output": {
      "main": [
        [
          {
            "node": "Loop Over Items1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Query knowledge base": {
      "ai_tool": [
        [
          {
            "node": "AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Supabase Vector Store1": {
      "main": [
        [
          {
            "node": "Clean RAG output",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When chat message received": {
      "main": [
        [
          {
            "node": "AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}

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

Go beyond basic Retrieval-Augmented Generation (RAG) with this advanced template. While a simple RAG setup can answer straightforward questions, it often fails when faced with complex queries and can be polluted by irrelevant information. This workflow introduces a sophisticated…

Source: https://n8n.io/workflows/7779/ — 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

This workflow acts as a 24/7 sales agent, engaging leads across WhatsApp, Instagram, Facebook, Telegram, and your website. It intelligently transcribes audio messages, answers questions using a knowle

Chat Trigger, Memory Postgres Chat, Tool Workflow +20
AI & RAG

• Create a Google Drive folder to watch. • Connect your Google Drive account in n8n and authorize access. • Point the Google Drive Trigger node to this folder (new/modified files trigger the flow).

Agent, Chat Trigger, Memory Buffer Window +14
AI & RAG

The workflow operates through a three-step process that handles incoming chat messages with intelligent tool orchestration: Message Trigger: The node triggers whenever a user message arrives and passe

Chat Trigger, Memory Postgres Chat, OpenAI Embeddings +16
AI & RAG

Think Agents. Uses agent, chatTrigger, toolThink, lmChatAnthropic. Chat trigger; 38 nodes.

Agent, Chat Trigger, Tool Think +11
AI & RAG

Boost your productivity with this AI-powered email and calendar assistant:

Chat Trigger, OpenAI Chat, Memory Buffer Window +13