{
  "id": "dlA7uMt2f1hTW3xd",
  "name": "n8n Local AI Agentic RAG Template",
  "tags": [],
  "nodes": [
    {
      "id": "397d00eb-8034-49e5-a8f6-0a0fd9b97d5b",
      "name": "Default Data Loader",
      "type": "@n8n/n8n-nodes-langchain.documentDefaultDataLoader",
      "position": [
        3312,
        1280
      ],
      "parameters": {
        "options": {
          "metadata": {
            "metadataValues": [
              {
                "name": "=file_id",
                "value": "={{ $('Set File ID').first().json.file_id }}"
              },
              {
                "name": "file_title",
                "value": "={{ $('Set File ID').first().json.file_title }}"
              }
            ]
          }
        },
        "jsonData": "={{ $json.data || $json.text || $json.concatenated_data }}",
        "jsonMode": "expressionData"
      },
      "typeVersion": 1
    },
    {
      "id": "e57065a2-9087-48e9-839e-d9c5c5fb477f",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2304,
        144
      ],
      "parameters": {
        "color": 4,
        "width": 583.4552380860637,
        "height": 528.85546469693,
        "content": "## Agent Tools for RAG"
      },
      "typeVersion": 1
    },
    {
      "id": "f7efaf27-78fb-4429-beba-74ffcc700342",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        560,
        688
      ],
      "parameters": {
        "color": 5,
        "width": 3073,
        "height": 867,
        "content": "## Tool to Add a Google Drive File to Vector DB"
      },
      "typeVersion": 1
    },
    {
      "id": "a137d00b-fb01-408c-9963-645e2beb44d9",
      "name": "Extract Document Text",
      "type": "n8n-nodes-base.extractFromFile",
      "position": [
        2512,
        1280
      ],
      "parameters": {
        "options": {},
        "operation": "text"
      },
      "typeVersion": 1,
      "alwaysOutputData": true
    },
    {
      "id": "1aec304d-7264-4e65-8654-cb9294c96c82",
      "name": "Postgres Chat Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryPostgresChat",
      "position": [
        1712,
        512
      ],
      "parameters": {},
      "notesInFlow": false,
      "typeVersion": 1
    },
    {
      "id": "9c407f2b-4f6a-46d6-a607-225c1c628ae5",
      "name": "Set File ID",
      "type": "n8n-nodes-base.set",
      "position": [
        992,
        960
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "10646eae-ae46-4327-a4dc-9987c2d76173",
              "name": "file_id",
              "type": "string",
              "value": "={{ $json.path }}"
            },
            {
              "id": "f4536df5-d0b1-4392-bf17-b8137fb31a44",
              "name": "file_type",
              "type": "string",
              "value": "={{ $json.path.split(/[\\\\/]/).pop().split('.').pop(); }}"
            },
            {
              "id": "77d782de-169d-4a46-8a8e-a3831c04d90f",
              "name": "file_title",
              "type": "string",
              "value": "={{ $json.path.split(/[\\\\/]/).pop().split('.').slice(0, -1).join('.'); }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "bc93aa94-10ec-4670-99f4-3bcec36be1ce",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1264,
        208
      ],
      "parameters": {
        "width": 1035.6381264595484,
        "height": 464.8027193303974,
        "content": "## RAG AI Agent with Chat Interface"
      },
      "typeVersion": 1
    },
    {
      "id": "8ccc451e-2fac-49b0-8700-085476add599",
      "name": "Respond to Webhook",
      "type": "n8n-nodes-base.respondToWebhook",
      "position": [
        2128,
        288
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1.1
    },
    {
      "id": "55abb8ac-7988-430a-ae41-5155471228a2",
      "name": "Edit Fields",
      "type": "n8n-nodes-base.set",
      "position": [
        1568,
        288
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "9a9a245e-f1a1-4282-bb02-a81ffe629f0f",
              "name": "chatInput",
              "type": "string",
              "value": "={{ $json?.chatInput || $json.body.chatInput }}"
            },
            {
              "id": "b80831d8-c653-4203-8706-adedfdb98f77",
              "name": "sessionId",
              "type": "string",
              "value": "={{ $json?.sessionId || $json.body.sessionId}}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "78b3fd17-23e9-4693-b782-918a5a8e5aed",
      "name": "When chat message received",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        1312,
        288
      ],
      "parameters": {
        "public": true,
        "options": {}
      },
      "typeVersion": 1.1
    },
    {
      "id": "06e362d1-d20c-407a-a75a-ed175c07439d",
      "name": "Webhook",
      "type": "n8n-nodes-base.webhook",
      "position": [
        1312,
        480
      ],
      "parameters": {
        "path": "bf4dd093-bb02-472c-9454-7ab9af97bd1d",
        "options": {},
        "httpMethod": "POST",
        "responseMode": "responseNode"
      },
      "typeVersion": 2
    },
    {
      "id": "e8ba5c17-3426-4d76-b69b-ff91dff7958f",
      "name": "Extract PDF Text",
      "type": "n8n-nodes-base.extractFromFile",
      "position": [
        2512,
        720
      ],
      "parameters": {
        "options": {},
        "operation": "pdf"
      },
      "typeVersion": 1
    },
    {
      "id": "b40eb123-d7fc-4799-b248-4b9516aee49e",
      "name": "Aggregate",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        2544,
        912
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData"
      },
      "typeVersion": 1
    },
    {
      "id": "0e3755e8-9532-447f-9137-f65d542c247e",
      "name": "Summarize",
      "type": "n8n-nodes-base.summarize",
      "position": [
        2752,
        992
      ],
      "parameters": {
        "options": {},
        "fieldsToSummarize": {
          "values": [
            {
              "field": "data",
              "aggregation": "concatenate"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "b185f2be-06bf-4a14-8d58-4b411a709f18",
      "name": "RAG AI Agent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        1792,
        288
      ],
      "parameters": {
        "text": "={{ $json.chatInput }}",
        "options": {
          "systemMessage": "You are a personal assistant who helps answer questions from a corpus of documents. The documents are either text based (Txt, docs, extracted PDFs, etc.) or tabular data (CSVs or Excel documents).\n\nYou are given tools to perform RAG in the 'documents' table, look up the documents available in your knowledge base in the 'document_metadata' table, extract all the text from a given document, and query the tabular files with SQL in the 'document_rows' table.\n\nAlways start by performing RAG unless the users asks you to check a document or the question requires a SQL query for tabular data (fetching a sum, finding a max, something a RAG lookup would be unreliable for). If RAG doesn't help, then look at the documents that are available to you, find a few that you think would contain the answer, and then analyze those.\n\nAlways tell the user if you didn't find the answer. Don't make something up just to please them."
        },
        "promptType": "define"
      },
      "typeVersion": 1.6
    },
    {
      "id": "2ee45951-3553-49b7-9f79-3cef3d065e8a",
      "name": "Switch",
      "type": "n8n-nodes-base.switch",
      "position": [
        1840,
        944
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "version": 1,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $('Set File ID').item.json.file_type }}",
                    "rightValue": "pdf"
                  }
                ]
              }
            },
            {
              "conditions": {
                "options": {
                  "version": 1,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "2ae7faa7-a936-4621-a680-60c512163034",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $('Set File ID').item.json.file_type }}",
                    "rightValue": "xlsx"
                  }
                ]
              }
            },
            {
              "conditions": {
                "options": {
                  "version": 1,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "fc193b06-363b-4699-a97d-e5a850138b0e",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $('Set File ID').item.json.file_type }}",
                    "rightValue": "=csv"
                  }
                ]
              }
            },
            {
              "conditions": {
                "options": {
                  "version": 1,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "b69f5605-0179-4b02-9a32-e34bb085f82d",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $('Set File ID').item.json.file_type }}",
                    "rightValue": "txt"
                  }
                ]
              }
            }
          ]
        },
        "options": {
          "fallbackOutput": 3
        }
      },
      "typeVersion": 3
    },
    {
      "id": "20bf7dde-e073-4288-a9d6-34df3973b5c3",
      "name": "Extract from Excel",
      "type": "n8n-nodes-base.extractFromFile",
      "position": [
        2320,
        912
      ],
      "parameters": {
        "options": {},
        "operation": "xlsx"
      },
      "typeVersion": 1
    },
    {
      "id": "f1840995-3f1c-4f4e-9d78-bc9225ecbe2b",
      "name": "Set Schema",
      "type": "n8n-nodes-base.set",
      "position": [
        3184,
        848
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "f422e2e0-381c-46ea-8f38-3f58c501d8b9",
              "name": "schema",
              "type": "string",
              "value": "={{ $('Extract from Excel').isExecuted ? $('Extract from Excel').first().json.keys().toJsonString() : $('Extract from CSV').first().json.keys().toJsonString() }}"
            },
            {
              "id": "bb07c71e-5b60-4795-864c-cc3845b6bc46",
              "name": "data",
              "type": "string",
              "value": "={{ $json.concatenated_data }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "b79ceb0b-f370-4ffb-9953-14b411acb5d9",
      "name": "Extract from CSV",
      "type": "n8n-nodes-base.extractFromFile",
      "position": [
        2320,
        1088
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "7067874e-4123-4a6c-a94d-89e4d1878309",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        560,
        368
      ],
      "parameters": {
        "color": 3,
        "width": 680,
        "height": 300,
        "content": "## Run Each Node Once to Set Up Database Tables"
      },
      "typeVersion": 1
    },
    {
      "id": "130c53e8-d507-4b6f-b1cf-f79dbc571c46",
      "name": "Create Document Metadata Table",
      "type": "n8n-nodes-base.postgres",
      "position": [
        688,
        464
      ],
      "parameters": {
        "query": "CREATE TABLE document_metadata (\n    id TEXT PRIMARY KEY,\n    title TEXT,\n    created_at TIMESTAMP DEFAULT NOW(),\n    schema TEXT\n);",
        "options": {},
        "operation": "executeQuery"
      },
      "typeVersion": 2.5
    },
    {
      "id": "421d2123-b68a-4c51-a482-db5bdffd3f76",
      "name": "Create Document Rows Table (for Tabular Data)",
      "type": "n8n-nodes-base.postgres",
      "position": [
        992,
        464
      ],
      "parameters": {
        "query": "CREATE TABLE document_rows (\n    id SERIAL PRIMARY KEY,\n    dataset_id TEXT REFERENCES document_metadata(id),\n    row_data JSONB  -- Store the actual row data\n);",
        "options": {},
        "operation": "executeQuery"
      },
      "typeVersion": 2.5
    },
    {
      "id": "55ff6535-bedb-479f-b3da-eb45e1127e77",
      "name": "List Documents",
      "type": "n8n-nodes-base.postgresTool",
      "position": [
        1840,
        512
      ],
      "parameters": {
        "table": {
          "__rl": true,
          "mode": "list",
          "value": "document_metadata",
          "cachedResultName": "document_metadata"
        },
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "options": {},
        "operation": "select",
        "returnAll": true,
        "descriptionType": "manual",
        "toolDescription": "Use this tool to fetch all available documents, including the table schema if the file is a CSV or Excel file."
      },
      "typeVersion": 2.5
    },
    {
      "id": "ffcb630b-5119-4ff6-b85a-d77eeb8d5713",
      "name": "Get File Contents",
      "type": "n8n-nodes-base.postgresTool",
      "position": [
        1984,
        512
      ],
      "parameters": {
        "query": "SELECT \n    string_agg(text, ' ') as document_text\nFROM documents_pg\n  WHERE metadata->>'file_id' = $1\nGROUP BY metadata->>'file_id';",
        "options": {
          "queryReplacement": "={{ $fromAI('file_id') }}"
        },
        "operation": "executeQuery",
        "descriptionType": "manual",
        "toolDescription": "Given a file ID, fetches the text from the document."
      },
      "typeVersion": 2.5
    },
    {
      "id": "f504b2f4-ffb5-4ef7-ba93-753151b77d9e",
      "name": "Query Document Rows",
      "type": "n8n-nodes-base.postgresTool",
      "position": [
        2144,
        512
      ],
      "parameters": {
        "query": "{{ $fromAI('sql_query') }}",
        "options": {},
        "operation": "executeQuery",
        "descriptionType": "manual",
        "toolDescription": "Run a SQL query - use this to query from the document_rows table once you know the file ID (which is the file path) you are querying. dataset_id is the file_id (file path) and you are always using the row_data for filtering, which is a jsonb field that has all the keys from the file schema given in the document_metadata table.\n\nExample query:\n\nSELECT AVG((row_data->>'revenue')::numeric)\nFROM document_rows\nWHERE dataset_id = '/data/shared/document.csv';\n\nExample query 2:\n\nSELECT \n    row_data->>'category' as category,\n    SUM((row_data->>'sales')::numeric) as total_sales\nFROM dataset_rows\nWHERE dataset_id = '/data/shared/document2.csv'\nGROUP BY row_data->>'category';"
      },
      "typeVersion": 2.5
    },
    {
      "id": "4abe03ca-297c-4509-b0db-7bed4338a158",
      "name": "Loop Over Items",
      "type": "n8n-nodes-base.splitInBatches",
      "position": [
        800,
        800
      ],
      "parameters": {
        "options": {
          "reset": false
        }
      },
      "typeVersion": 3
    },
    {
      "id": "e382d750-85ba-492d-9d3e-eb839af0bfc1",
      "name": "Insert Document Metadata",
      "type": "n8n-nodes-base.postgres",
      "position": [
        1488,
        832
      ],
      "parameters": {
        "table": {
          "__rl": true,
          "mode": "list",
          "value": "document_metadata",
          "cachedResultName": "document_metadata"
        },
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "columns": {
          "value": {
            "id": "={{ $('Set File ID').item.json.file_id }}",
            "title": "={{ $('Set File ID').item.json.file_title }}"
          },
          "schema": [
            {
              "id": "id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": true,
              "displayName": "id",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "title",
              "type": "string",
              "display": true,
              "required": false,
              "displayName": "title",
              "defaultMatch": false,
              "canBeUsedToMatch": false
            },
            {
              "id": "url",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "url",
              "defaultMatch": false,
              "canBeUsedToMatch": false
            },
            {
              "id": "created_at",
              "type": "dateTime",
              "display": true,
              "required": false,
              "displayName": "created_at",
              "defaultMatch": false,
              "canBeUsedToMatch": false
            },
            {
              "id": "schema",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "schema",
              "defaultMatch": false,
              "canBeUsedToMatch": false
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "id"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "upsert"
      },
      "executeOnce": true,
      "typeVersion": 2.5
    },
    {
      "id": "bbf6f704-b4a2-4ff2-ac09-27626526b35f",
      "name": "Insert Table Rows",
      "type": "n8n-nodes-base.postgres",
      "position": [
        2544,
        1088
      ],
      "parameters": {
        "table": {
          "__rl": true,
          "mode": "list",
          "value": "document_rows",
          "cachedResultName": "document_rows"
        },
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "columns": {
          "value": {
            "row_data": "={{ $json.toJsonString().replaceAll(/'/g, \"''\") }}",
            "dataset_id": "={{ $('Set File ID').item.json.file_id }}"
          },
          "schema": [
            {
              "id": "id",
              "type": "number",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "id",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "dataset_id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "dataset_id",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            },
            {
              "id": "row_data",
              "type": "object",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "row_data",
              "defaultMatch": false,
              "canBeUsedToMatch": true
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "id"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {}
      },
      "typeVersion": 2.5
    },
    {
      "id": "3265a7df-dd40-421e-b1fb-53293a7460f8",
      "name": "Update Schema for Document Metadata",
      "type": "n8n-nodes-base.postgres",
      "position": [
        3408,
        848
      ],
      "parameters": {
        "table": {
          "__rl": true,
          "mode": "list",
          "value": "document_metadata",
          "cachedResultName": "document_metadata"
        },
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "columns": {
          "value": {
            "id": "={{ $('Set File ID').item.json.file_id }}",
            "schema": "={{ $json.schema }}"
          },
          "schema": [
            {
              "id": "id",
              "type": "string",
              "display": true,
              "removed": false,
              "required": true,
              "displayName": "id",
              "defaultMatch": true,
              "canBeUsedToMatch": true
            },
            {
              "id": "title",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "title",
              "defaultMatch": false,
              "canBeUsedToMatch": false
            },
            {
              "id": "url",
              "type": "string",
              "display": true,
              "removed": true,
              "required": false,
              "displayName": "url",
              "defaultMatch": false,
              "canBeUsedToMatch": false
            },
            {
              "id": "created_at",
              "type": "dateTime",
              "display": true,
              "required": false,
              "displayName": "created_at",
              "defaultMatch": false,
              "canBeUsedToMatch": false
            },
            {
              "id": "schema",
              "type": "string",
              "display": true,
              "removed": false,
              "required": false,
              "displayName": "schema",
              "defaultMatch": false,
              "canBeUsedToMatch": false
            }
          ],
          "mappingMode": "defineBelow",
          "matchingColumns": [
            "id"
          ],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "upsert"
      },
      "typeVersion": 2.5
    },
    {
      "id": "53f9f045-bb08-4b22-a11e-dfd2c964b687",
      "name": "Sticky Note9",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        0,
        0
      ],
      "parameters": {
        "color": 6,
        "width": 540,
        "height": 1320,
        "content": "## \ud83d\ude80 n8n Local AI Agentic RAG Template\n\n**Author:** [Jadai kongolo](https://my.jadaikongolo.tech)\n\n## What is this?\nThis template provides an entirely local implementation of an **Agentic RAG (Retrieval Augmented Generation)** system in n8n that can be extended easily for your specific use case and knowledge base. Unlike standard RAG which only performs simple lookups, this agent can reason about your knowledge base, self-improve retrieval, and dynamically switch between different tools based on the specific question. \n\n## Why Agentic RAG?\nStandard RAG has significant limitations:\n- Poor analysis of numerical/tabular data\n- Missing context due to document chunking\n- Inability to connect information across documents\n- No dynamic tool selection based on question type\n\n## What makes this template powerful:\n- **Intelligent tool selection**: Switches between RAG lookups, SQL queries, or full document retrieval based on the question\n- **Complete document context**: Accesses entire documents when needed instead of just chunks\n- **Accurate numerical analysis**: Uses SQL for precise calculations on spreadsheet/tabular data\n- **Cross-document insights**: Connects information across your entire knowledge base\n- **Multi-file processing**: Handles multiple documents in a single workflow loop\n- **Efficient storage**: Uses JSONB in Supabase to store tabular data without creating new tables for each CSV\n\n## Getting Started\n1. Run the table creation nodes first to set up your database tables in Supabase\n2. Upload your documents to the folder on your computer that is mounted to /data/shared in the n8n container. This folder by default is the \"shared\" folder in the local AI package.\n3. The agent will process them automatically (chunking text, storing tabular data in Supabase)\n4. Start asking questions that leverage the agent's multiple reasoning approaches\n\n## Customization\nThis template provides a solid foundation that you can extend by:\n- Tuning the system prompt for your specific use case\n- Adding document metadata like summaries\n- Implementing more advanced RAG techniques\n- Optimizing for larger knowledge bases\n\n---\n\nThe non-local (\"cloud\") version of this Agentic RAG agent can be [found here](https://kongolo.gumroad.com/l/anxwv)."
      },
      "typeVersion": 1
    },
    {
      "id": "cdee87fe-e154-47ab-9330-32dee5c213d3",
      "name": "Local File Trigger",
      "type": "n8n-nodes-base.localFileTrigger",
      "position": [
        608,
        800
      ],
      "parameters": {
        "path": "/data/shared",
        "events": [
          "add",
          "change"
        ],
        "options": {
          "usePolling": true,
          "followSymlinks": true
        },
        "triggerOn": "folder"
      },
      "typeVersion": 1
    },
    {
      "id": "67311475-7928-4ddc-957a-79817c98d26d",
      "name": "Read/Write Files from Disk",
      "type": "n8n-nodes-base.readWriteFile",
      "position": [
        1648,
        960
      ],
      "parameters": {
        "options": {
          "dataPropertyName": "=data"
        },
        "fileSelector": "={{ $('Set File ID').item.json.file_id }}"
      },
      "typeVersion": 1
    },
    {
      "id": "366e800a-9bd7-4822-a11c-f555800bbba6",
      "name": "Embeddings Ollama",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOllama",
      "position": [
        3072,
        1280
      ],
      "parameters": {
        "model": "nomic-embed-text:latest"
      },
      "typeVersion": 1
    },
    {
      "id": "be37cfb9-ea40-4244-87d7-b562be315573",
      "name": "Embeddings Ollama1",
      "type": "@n8n/n8n-nodes-langchain.embeddingsOllama",
      "position": [
        2560,
        480
      ],
      "parameters": {
        "model": "nomic-embed-text:latest"
      },
      "typeVersion": 1
    },
    {
      "id": "1306b972-2b24-4c62-846e-f1c5b3d0482c",
      "name": "Recursive Character Text Splitter",
      "type": "@n8n/n8n-nodes-langchain.textSplitterRecursiveCharacterTextSplitter",
      "position": [
        3200,
        1408
      ],
      "parameters": {
        "options": {},
        "chunkSize": 400
      },
      "typeVersion": 1
    },
    {
      "id": "677ad468-8118-4f8f-9a47-f5429cdc7582",
      "name": "Ollama (Change Base URL)",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi",
      "position": [
        1568,
        512
      ],
      "parameters": {
        "model": {
          "__rl": true,
          "mode": "list",
          "value": "qwen2.5:14b-8k",
          "cachedResultName": "qwen2.5:14b-8k"
        },
        "options": {}
      },
      "typeVersion": 1.2
    },
    {
      "id": "b3e23401-8868-4b3c-a3fe-37fda44419d5",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        0,
        1344
      ],
      "parameters": {
        "color": 6,
        "width": 540,
        "height": 200,
        "content": "## NOTE\n\nThe Ollama chat model node doesn't work with the RAG nodes - known issue with n8n.\n\nSo for now, we are using the OpenAI chat model but changing the base URL to Ollama when creating the credentials (i.e. http://ollama:11434/v1). The API key can be set to whatever, it isn't used for local LLMs."
      },
      "typeVersion": 1
    },
    {
      "id": "987a6081-cdfd-457e-a2e5-4fa93fa018f4",
      "name": "Delete Old Doc Records",
      "type": "n8n-nodes-base.postgres",
      "position": [
        1168,
        832
      ],
      "parameters": {
        "query": "DO $$\nBEGIN\n    IF EXISTS (SELECT 1 FROM information_schema.tables WHERE table_name = 'documents_pg') THEN\n        EXECUTE 'DELETE FROM documents_pg WHERE metadata->>''file_id'' LIKE ''%' || $1 || '%''';\n    END IF;\nEND\n$$;",
        "options": {
          "queryReplacement": "={{ $json.file_id }}"
        },
        "operation": "executeQuery"
      },
      "typeVersion": 2.5
    },
    {
      "id": "619a8a54-5fb8-4d8f-9cac-5a1c2a58f44b",
      "name": "Delete Old Data Records",
      "type": "n8n-nodes-base.postgres",
      "position": [
        1328,
        960
      ],
      "parameters": {
        "query": "DELETE FROM document_rows\nWHERE dataset_id LIKE '%' || $1 || '%';",
        "options": {
          "queryReplacement": "={{ $('Set File ID').item.json.file_id }}"
        },
        "operation": "executeQuery"
      },
      "typeVersion": 2.5
    },
    {
      "id": "c975f943-3c05-45eb-9b11-4bd254845fbc",
      "name": "Postgres PGVector Store",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePGVector",
      "position": [
        3184,
        1072
      ],
      "parameters": {
        "mode": "insert",
        "options": {},
        "tableName": "documents_pg"
      },
      "typeVersion": 1
    },
    {
      "id": "9bba5830-ad14-454c-b653-48baf03844bb",
      "name": "Postgres PGVector Store1",
      "type": "@n8n/n8n-nodes-langchain.vectorStorePGVector",
      "position": [
        2464,
        288
      ],
      "parameters": {
        "mode": "retrieve-as-tool",
        "options": {},
        "toolName": "documents",
        "tableName": "documents_pg",
        "toolDescription": "Use RAG to look up information in the knowledgebase."
      },
      "typeVersion": 1
    }
  ],
  "active": false,
  "settings": {
    "executionOrder": "v1"
  },
  "versionId": "43f092c7-957d-42d3-8ea5-26108c4cd991",
  "connections": {
    "Switch": {
      "main": [
        [
          {
            "node": "Extract PDF Text",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Extract from Excel",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Extract from CSV",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Extract Document Text",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Webhook": {
      "main": [
        [
          {
            "node": "Edit Fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate": {
      "main": [
        [
          {
            "node": "Summarize",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Summarize": {
      "main": [
        [
          {
            "node": "Set Schema",
            "type": "main",
            "index": 0
          },
          {
            "node": "Postgres PGVector Store",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Schema": {
      "main": [
        [
          {
            "node": "Update Schema for Document Metadata",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Edit Fields": {
      "main": [
        [
          {
            "node": "RAG AI Agent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set File ID": {
      "main": [
        [
          {
            "node": "Delete Old Doc Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "RAG AI Agent": {
      "main": [
        [
          {
            "node": "Respond to Webhook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "List Documents": {
      "ai_tool": [
        [
          {
            "node": "RAG AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [],
        [
          {
            "node": "Set File ID",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract PDF Text": {
      "main": [
        [
          {
            "node": "Postgres PGVector Store",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract from CSV": {
      "main": [
        [
          {
            "node": "Aggregate",
            "type": "main",
            "index": 0
          },
          {
            "node": "Insert Table Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings Ollama": {
      "ai_embedding": [
        [
          {
            "node": "Postgres PGVector Store",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Get File Contents": {
      "ai_tool": [
        [
          {
            "node": "RAG AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Embeddings Ollama1": {
      "ai_embedding": [
        [
          {
            "node": "Postgres PGVector Store1",
            "type": "ai_embedding",
            "index": 0
          }
        ]
      ]
    },
    "Extract from Excel": {
      "main": [
        [
          {
            "node": "Aggregate",
            "type": "main",
            "index": 0
          },
          {
            "node": "Insert Table Rows",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Local File Trigger": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Default Data Loader": {
      "ai_document": [
        [
          {
            "node": "Postgres PGVector Store",
            "type": "ai_document",
            "index": 0
          }
        ]
      ]
    },
    "Query Document Rows": {
      "ai_tool": [
        [
          {
            "node": "RAG AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Postgres Chat Memory": {
      "ai_memory": [
        [
          {
            "node": "RAG AI Agent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "Extract Document Text": {
      "main": [
        [
          {
            "node": "Postgres PGVector Store",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Delete Old Doc Records": {
      "main": [
        [
          {
            "node": "Delete Old Data Records",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Delete Old Data Records": {
      "main": [
        [
          {
            "node": "Insert Document Metadata",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Postgres PGVector Store": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Insert Document Metadata": {
      "main": [
        [
          {
            "node": "Read/Write Files from Disk",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Ollama (Change Base URL)": {
      "ai_languageModel": [
        [
          {
            "node": "RAG AI Agent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Postgres PGVector Store1": {
      "ai_tool": [
        [
          {
            "node": "RAG AI Agent",
            "type": "ai_tool",
            "index": 0
          }
        ]
      ]
    },
    "Read/Write Files from Disk": {
      "main": [
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When chat message received": {
      "main": [
        [
          {
            "node": "Edit Fields",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Recursive Character Text Splitter": {
      "ai_textSplitter": [
        [
          {
            "node": "Default Data Loader",
            "type": "ai_textSplitter",
            "index": 0
          }
        ]
      ]
    }
  }
}