AutomationFlowsAI & RAG › Generate & Test Sql Code with Gpt/openrouter AI and Postgresql Sandbox

Generate & Test Sql Code with Gpt/openrouter AI and Postgresql Sandbox

ByMuhammadumar @muhammad on n8n.io

This is the core AI agent used for queryverify.com.

Chat trigger trigger★★★★★ complexityAI-powered39 nodesChat TriggerMemory Buffer WindowPostgresOpenRouter ChatOpenAIAgentMySQL
AI & RAG Trigger: Chat trigger Nodes: 39 Complexity: ★★★★★ AI nodes: yes Added:
Generate & Test Sql Code with Gpt/openrouter AI and Postgresql Sandbox — n8n workflow card showing Chat Trigger, Memory Buffer Window, Postgres integration

This workflow corresponds to n8n.io template #6583 — 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
{
  "id": "H6iWWu9KK0XoaPXa",
  "name": "queryverify",
  "tags": [],
  "nodes": [
    {
      "id": "47f2b3b4-12f0-4e9c-82f4-54d2c32b77f0",
      "name": "When chat message received",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        -1824,
        128
      ],
      "parameters": {
        "mode": "webhook",
        "public": true,
        "options": {}
      },
      "typeVersion": 1.1
    },
    {
      "id": "424b2831-425b-4ee7-a3d5-b2713bfdf343",
      "name": "GenerateErrorPrompt",
      "type": "n8n-nodes-base.code",
      "position": [
        5264,
        752
      ],
      "parameters": {
        "jsCode": "let promptEnd = '';\nif( $('localVariables').last().json.autoErrorFixing ){\n  promptEnd = '. Please fix SQL query. Please decide how to solve and give fixed SQL query. You should give the fixed version of this current SQL query, that can be copied and run straightforward in SQL sandbox';\n} else {\n  promptEnd = '. Please suggest how we can resolve this error.  At the end of your response, ask: Does it work for us?';\n}\n\nreturn {\n  \"message\"     : $input.last().json.message,\n  \"description\" : $input.last().json.error.description,\n  \"prompt\"      : \"Recieved error while executing this query: \" + $input.last().json.message + \". Here detailed description: \" + $input.last().json.error.description + promptEnd\n}"
      },
      "typeVersion": 2
    },
    {
      "id": "07f2f95a-0958-4562-b5c4-1bb6504a02fd",
      "name": "Simple Memory",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        1248,
        400
      ],
      "parameters": {
        "sessionKey": "={{ $('localVariables').last().json.sessionId }}",
        "sessionIdType": "customKey",
        "contextWindowLength": 7
      },
      "typeVersion": 1.3
    },
    {
      "id": "7f42bf3b-5d99-41d4-94e7-0a34da39e285",
      "name": "AutoErrorFixing",
      "type": "n8n-nodes-base.if",
      "position": [
        3360,
        -64
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "e938b602-e816-4409-9c0b-190eae7952df",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              },
              "leftValue": "={{ $('localVariables').last().json.autoErrorFixing }}",
              "rightValue": 1
            }
          ]
        },
        "looseTypeValidation": true
      },
      "typeVersion": 2.2
    },
    {
      "id": "6e1fcee6-2c63-46e3-a48c-458180257b43",
      "name": "IfError",
      "type": "n8n-nodes-base.if",
      "position": [
        3072,
        32
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "3228bc02-986c-4159-bf24-b27336611473",
              "operator": {
                "name": "filter.operator.equals",
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $('GenerateErrorPrompt').isExecuted }}",
              "rightValue": "true"
            }
          ]
        },
        "looseTypeValidation": true
      },
      "typeVersion": 2.2
    },
    {
      "id": "4f3fcdf7-fe96-4137-9356-165890ea57d1",
      "name": "Execute_AI_result",
      "type": "n8n-nodes-base.postgres",
      "onError": "continueErrorOutput",
      "position": [
        4288,
        432
      ],
      "parameters": {
        "query": "{{ $json.output }}",
        "options": {},
        "operation": "executeQuery"
      },
      "credentials": {
        "postgres": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.6
    },
    {
      "id": "d4c60f3d-425e-4fef-923c-a2fa154f0a00",
      "name": "isAssistantExists",
      "type": "n8n-nodes-base.if",
      "position": [
        112,
        -464
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "cd96c88f-b4c7-4bb6-9082-b2a827740bea",
              "operator": {
                "name": "filter.operator.equals",
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.output }}",
              "rightValue": "1"
            }
          ]
        },
        "looseTypeValidation": true
      },
      "typeVersion": 2.2
    },
    {
      "id": "318a17bb-7566-4b2c-bd3f-d6e57daa1b95",
      "name": "isAssistantExistsCode",
      "type": "n8n-nodes-base.code",
      "position": [
        -208,
        -464
      ],
      "parameters": {
        "jsCode": "let isAssistantExists = 0;\nlet assistantId = null;\n\nfor (const item of $('getAssistantsList').all()) {\n  let trimmedGetAss = item.json.name ? item.json.name.trim() : '';\n  let trimmedAgentName = $(\"AgentName\").last().json.agentName.trim();\n  if (trimmedGetAss === trimmedAgentName) { \n    isAssistantExists = 1;\n    assistantId = item.json.id;\n  }\n}\n\nreturn {output: isAssistantExists, id: assistantId};"
      },
      "typeVersion": 2
    },
    {
      "id": "ff979107-3937-4feb-aaf3-4ff9337325da",
      "name": "isOpenAI",
      "type": "n8n-nodes-base.if",
      "position": [
        5488,
        752
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "fddc112b-8a31-4098-b283-df9d0c7b0acf",
              "operator": {
                "name": "filter.operator.equals",
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $('localVariables').last().json.aiProvider }}",
              "rightValue": "openai"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "6e2a2dd7-8ca7-4662-9c7d-5c7cab0dd314",
      "name": "assistant",
      "type": "n8n-nodes-base.set",
      "position": [
        592,
        -480
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "1f6867fd-d7d1-45c5-b01f-960e4ce6c883",
              "name": "id",
              "type": "string",
              "value": "={{ $json.id }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "af7314ea-60db-4873-838d-7a01dffc70ed",
      "name": "IfOpenAI",
      "type": "n8n-nodes-base.if",
      "position": [
        -1184,
        128
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "fddc112b-8a31-4098-b283-df9d0c7b0acf",
              "operator": {
                "name": "filter.operator.equals",
                "type": "string",
                "operation": "equals"
              },
              "leftValue": "={{ $json.aiProvider }}",
              "rightValue": "openai"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "db247d1d-8277-475b-98c8-4150326e0dfb",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1536,
        32
      ],
      "parameters": {
        "height": 260,
        "content": "use this to get neccessary local variables, like: instruction to AI, sessionId, and all inputed parameters from previous node\n"
      },
      "typeVersion": 1
    },
    {
      "id": "02dbf130-9e82-4d85-b743-2cb488fb0f46",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1904,
        -176
      ],
      "parameters": {
        "color": 4,
        "width": 260,
        "height": 460,
        "content": "Input parameters:\n1. sessionId: uuidv4\n2. threadId: nullable\n3. apiKey: string\n4. aiProvider: string\n5. model: string\n6. autoErrorFixing: boolean\n7. chatInput: string (users prompt)\n8. currentDbSchemaWithData: string (json architecture with data)\n9. selectedDatabaseType (postgresql, mysql)"
      },
      "typeVersion": 1
    },
    {
      "id": "e10c42db-8c9f-4052-8205-259b53ebdc3f",
      "name": "IsMaxAutoErrorReached",
      "type": "n8n-nodes-base.if",
      "position": [
        3760,
        -320
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "e35fea46-5373-427b-b3fa-6fab56627bde",
              "operator": {
                "type": "number",
                "operation": "gte"
              },
              "leftValue": "={{ $node['GenerateErrorPrompt'].runIndex }}",
              "rightValue": 4
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "1a3189fd-550e-4b1c-8720-65579fa39c44",
      "name": "OpenRouter Chat Model",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "position": [
        1120,
        400
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "20960f49-d573-45e0-a3e0-f5e181a8ef66",
      "name": "AgentName",
      "type": "n8n-nodes-base.set",
      "position": [
        -896,
        -464
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "527cbbeb-e3a7-4fb5-aaae-fd2b8085de85",
              "name": "agentName",
              "type": "string",
              "value": "={{ $('localVariables').last().json.selectedDatabaseType + '_AiDoubleCheck_' + $('localVariables').last().json.model }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "9f28f786-c999-4614-8d74-e67f945583e2",
      "name": "setOutputByProvider",
      "type": "n8n-nodes-base.set",
      "position": [
        2688,
        -208
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "569f9268-5b51-4fac-9d8b-132de0b77ef0",
              "name": "output",
              "type": "string",
              "value": "={{ \n$if ( $('localVariables').last().json.aiProvider === 'openai', \n  $('OpenAIMainBrain').last().json.output,\n  $('OpenRouterAgent').last().json.output\n) \n}}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "c1c4bc98-9f7f-459b-9c1e-8ce1de98f24c",
      "name": "OpenAIMainBrain",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        832,
        -480
      ],
      "parameters": {
        "text": "={{ \n\n  $if($('GenerateErrorPrompt').isExecuted, \n\n    `## ERROR HANDLING MODE\\n\\n  ${$json.prompt}.`,\n\n    $if($('localVariables').last().json.currentDbSchemaWithData !== '[]', 'Current DB tables: ' + $('localVariables').last().json.currentDbSchemaWithData + '; ',\n'') + $('localVariables').last().json.chatInput + '. Prefix for tables: ' + $('localVariables').last().json.sessionId) \n\n}}",
        "memory": "threadId",
        "prompt": "define",
        "options": {
          "timeout": 300000
        },
        "resource": "assistant",
        "threadId": "={{(() => {\n  if ($('GenerateErrorPrompt').isExecuted) {\n    return $('setThreadId').first().json.threadId;\n  }\n  return $ifEmpty($('localVariables').last().json.threadId, null);\n})()}}",
        "assistantId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('assistant').last().json.id }}"
        }
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.8
    },
    {
      "id": "723fd28e-628e-417a-826c-2fd025a8a026",
      "name": "askUserHowToHandleError",
      "type": "n8n-nodes-base.set",
      "position": [
        3632,
        -16
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "562ef9d0-d7c1-43f3-8ceb-608b6576f4e2",
              "name": "message",
              "type": "string",
              "value": "={{ $json.output }}"
            },
            {
              "id": "8ede156c-df3f-4da3-87b2-696457147762",
              "name": "type",
              "type": "string",
              "value": "autoErrorFixingFalse"
            },
            {
              "id": "ed5a54d3-29b1-4034-9a1b-595831f25585",
              "name": "error",
              "type": "string",
              "value": "={{ $('Execute_AI_result').last().json.message }}"
            },
            {
              "id": "20c03d57-09bd-4df7-afb1-286dbc94f19b",
              "name": "threadId",
              "type": "string",
              "value": "={{ \n$if ( $('localVariables').last().json.aiProvider === 'openai', \n  $('setThreadId').first().json.threadId,\n  null\n) \n}}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "0e4af952-6e07-4cb0-a4ff-6705ed3bbfc0",
      "name": "maxAutoErrorLimitReached",
      "type": "n8n-nodes-base.set",
      "position": [
        4560,
        -352
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "562ef9d0-d7c1-43f3-8ceb-608b6576f4e2",
              "name": "query",
              "type": "string",
              "value": "={{ $('setOutputByProvider').last().json.output }}"
            },
            {
              "id": "b9ddb8b4-56ab-4d7e-b3fa-2a72c5158d26",
              "name": "type",
              "type": "string",
              "value": "maxAutoErrorLimitReached"
            },
            {
              "id": "77c2c8a4-c5df-43c3-8803-4317a1e5e71f",
              "name": "details",
              "type": "string",
              "value": "={{ $('collectErrorLoopDetails1').last().json.details }}"
            },
            {
              "id": "82af0703-ecdf-44c1-ba37-466cc23edf70",
              "name": "threadId",
              "type": "string",
              "value": "={{ \n$if ( $('localVariables').last().json.aiProvider === 'openai', \n  $('setThreadId').first().json.threadId,\n  null\n) \n}}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "43a23e59-31f7-40fb-b911-9e3dd9bad912",
      "name": "If",
      "type": "n8n-nodes-base.if",
      "position": [
        -448,
        -464
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "01f2a48f-2018-483c-a667-3c184ca9b169",
              "operator": {
                "type": "string",
                "operation": "notExists",
                "singleValue": true
              },
              "leftValue": "={{ $json.error }}",
              "rightValue": "error"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "817ec035-7af7-41dd-b9f6-f51fff4b6c1d",
      "name": "wordsForUser1",
      "type": "n8n-nodes-base.set",
      "position": [
        1872,
        32
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "30b2c62f-e7cf-4b8e-85ad-e0d6e4ae5094",
              "name": "type",
              "type": "string",
              "value": "wordsForUser"
            },
            {
              "id": "cca814df-e535-46c6-bd6e-aa780e8cf12e",
              "name": "message",
              "type": "string",
              "value": "={{ $json.output }}"
            },
            {
              "id": "678dc066-d419-46d6-9340-1f7a7bb666aa",
              "name": "threadId",
              "type": "string",
              "value": "={{ \n$if ( $('localVariables').last().json.aiProvider === 'openai', \n  $('setThreadId').first().json.threadId,\n  null\n) \n}}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "1347b643-7109-4148-86bd-89b540861b06",
      "name": "isExecutable",
      "type": "n8n-nodes-base.if",
      "position": [
        1552,
        -176
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "strict"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "e52803c5-a6e2-4281-912f-a8c58867b9a8",
              "operator": {
                "type": "string",
                "operation": "notContains"
              },
              "leftValue": "={{ $json.output }}",
              "rightValue": "words_for_user"
            }
          ]
        }
      },
      "typeVersion": 2.2
    },
    {
      "id": "73bc7418-b260-4c38-bc15-ec3ed50086df",
      "name": "getAssistantsList",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "onError": "continueRegularOutput",
      "maxTries": 2,
      "position": [
        -656,
        -464
      ],
      "parameters": {
        "resource": "assistant",
        "operation": "list"
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "retryOnFail": true,
      "typeVersion": 1.8,
      "alwaysOutputData": true
    },
    {
      "id": "84f8b40b-c563-4b28-a70c-c4c5b7323d1b",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1264,
        32
      ],
      "parameters": {
        "color": 5,
        "height": 260,
        "content": "OpenAI has built-in assistant that handles chat history on their side. For open-router we should handle chat history on our side"
      },
      "typeVersion": 1
    },
    {
      "id": "efca8f7c-1115-4086-9b53-111574a00cee",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1472,
        -304
      ],
      "parameters": {
        "height": 260,
        "content": "Sometimes we can't answer with just code. This node is responsible for separation. If it is not a code for sandbox, than it will go to user as words."
      },
      "typeVersion": 1
    },
    {
      "id": "a793ec0d-97fc-49aa-8c2a-f3746946ed95",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3696,
        -416
      ],
      "parameters": {
        "height": 260,
        "content": "Error fixing loop will work only n times, defined in this node. It is done to prevent infinite loop"
      },
      "typeVersion": 1
    },
    {
      "id": "d12ff01c-662d-4204-a1a7-1c91b122a5cd",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3008,
        -128
      ],
      "parameters": {
        "color": 2,
        "width": 220,
        "height": 280,
        "content": "If the user has selected automatic error fixing, debugging will be performed automatically, otherwise the system will ask the user for further instruction"
      },
      "typeVersion": 1
    },
    {
      "id": "39a21d61-816d-4414-8f0b-d87adda9f350",
      "name": "OpenRouterAgent",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        1072,
        128
      ],
      "parameters": {
        "text": "={{ \n\n  $if($('GenerateErrorPrompt').isExecuted, \n\n    `## ERROR HANDLING MODE\\n\\n  ${$json.prompt}.`,\n\n    $if($('localVariables').last().json.currentDbSchemaWithData !== '[]', 'Current DB tables: ' + $('localVariables').last().json.currentDbSchemaWithData + '; ',\n'') + $('localVariables').last().json.chatInput + '. Prefix for tables: ' + $('localVariables').last().json.sessionId) \n\n}}",
        "options": {
          "systemMessage": "={{ $('localVariables').last().json.instruction }}"
        },
        "promptType": "define"
      },
      "typeVersion": 1.7
    },
    {
      "id": "ec49bd8d-05cd-4438-bdb9-864a92580d5e",
      "name": "createOpenAiAssistant",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        352,
        -304
      ],
      "parameters": {
        "name": "={{ $('AgentName').last().json.agentName }} ",
        "modelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('localVariables').last().json.model }}"
        },
        "options": {},
        "resource": "assistant",
        "operation": "create",
        "description": "will double check code directly in a playground",
        "instructions": "={{ $('localVariables').last().json.instruction }}"
      },
      "credentials": {
        "openAiApi": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 1.8
    },
    {
      "id": "1caf5dec-7cbd-4cbf-9687-48d4aa33cd35",
      "name": "localVariables",
      "type": "n8n-nodes-base.set",
      "position": [
        -1456,
        128
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "5ee9645b-83f9-4f0e-9fd3-4a75121bee9a",
              "name": "instruction",
              "type": "string",
              "value": "=You are a senior {{ $json['selectedDatabaseType'] }} developer helping users solve {{ $json['selectedDatabaseType'] }} tasks in a {{ $json['selectedDatabaseType'] }} Playground environment. Follow these rules:\n\n1. Your response must always contain fully executable SQL code \u2014 with no markdown formatting. Never explain or comment in natural language.\n2. Assume that the first user prompt starts with an empty {{ $json['selectedDatabaseType'] }} Playground. You must begin with `CREATE TABLE` statements to build a realistic schema related to the task. Follow {{ $json['selectedDatabaseType'] }} naming conventions for schema design: each table\u2019s primary key column must be named exactly id. Use plural nouns for table names and use snake_case to separate words. \n3. The user will provide a prefix for tables (e.g., session_abc199935). All table names must begin with that prefix and be enclosed in {{ $if($json['selectedDatabaseType'] == 'postgresql', 'double quotes.  Example: \"session_abc199935_users\"', 'backticks `.  Example: `session_abc199935_users`') }}. IMPORTANT: You must use this prefix exactly as provided \u2014 without modification.\n4. After creating tables, always include at least 3 rows of mock data using `INSERT INTO`. \n5. When designing schema and mock data, create diverse examples to demonstrate both positive and negative scenarios relevant to the task.\nFor example, if the user asks to identify which foreign key columns have indexes, include multiple foreign keys \u2014 some with indexes and some without \u2014 to provide broader, realistic, and testable variety.\nIf tables are related, they always should have standart SQL relation (by id PK and {table_name}_id FK) \n6. Finish each response with the actual query that solves the user\u2019s request. \n7. Always separate the final query from setup using this comment: -- ACTUAL_SOLUTION. Remember use only this comment for separation.\n8. If the task involves inspecting metadata (e.g., checking indexes, foreign keys, constraints), generate mock tables first (if none exist), and then use `information_schema` or similar things to provide introspective queries.\n9. If no SQL can be generated (e.g., conversational input like \"hello\", \"explain\", or messy texts etc.), respond with: words_for_user: followed by a helpful or polite message \u2014 but do not generate SQL. IMPORTANT! Use words_for_user only if there is a conversational input! If you will get error handling mode your goal is to fix it.\n\nThe goal is to always output SQL code that users can copy and run directly in a {{ $json['selectedDatabaseType'] }} Playground to verify the result. "
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "e4025036-da4e-4e6b-ad3e-97c5242aa861",
      "name": "executedSQLQuery",
      "type": "n8n-nodes-base.set",
      "position": [
        5376,
        272
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "cfc317f9-d9fa-4026-9b2a-1cd4b13b87c6",
              "name": "query",
              "type": "string",
              "value": "={{ $('setOutputByProvider').last().json.output }}"
            },
            {
              "id": "594046d1-9b2d-43cb-9609-04ee4f70364f",
              "name": "type",
              "type": "string",
              "value": "success"
            },
            {
              "id": "c6de1fb5-60a4-4050-a401-973139f42dfb",
              "name": "executionResult",
              "type": "string",
              "value": "={{ $('mergeExecutionsResult').last().json.mergedExecutionsResult }}"
            },
            {
              "id": "28e5e21b-7e05-431d-8e84-446884ff533c",
              "name": "details",
              "type": "string",
              "value": "={{ $('collectErrorLoopDetails').last().json.details }}"
            },
            {
              "id": "1f838390-16ec-4c90-a718-b7bb0d2735ce",
              "name": "threadId",
              "type": "string",
              "value": "={{ \n$if ( $('localVariables').last().json.aiProvider === 'openai', \n  $('setThreadId').first().json.threadId,\n  null\n) \n}}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "ff239015-892a-4762-8de6-537396e1d1c3",
      "name": "issueOnOpenAiSide",
      "type": "n8n-nodes-base.set",
      "position": [
        -240,
        -256
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "9cbea64a-8820-40df-9e88-f1d3ac5e5d06",
              "name": "type",
              "type": "string",
              "value": "error"
            },
            {
              "id": "d391b90b-79d7-45b4-b9f2-6bc4e45ab2c5",
              "name": "message",
              "type": "string",
              "value": "={{ $json.error }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "7743696c-4e2d-4195-8832-1624f4861075",
      "name": "mergeExecutionsResult",
      "type": "n8n-nodes-base.code",
      "position": [
        4816,
        352
      ],
      "parameters": {
        "jsCode": "return [\n  {\n    json: {\n      mergedExecutionsResult: items.map(item => item.json)\n    }\n  }\n];"
      },
      "typeVersion": 2
    },
    {
      "id": "55302cce-e5ae-4d33-8200-b455e3ca795e",
      "name": "collectErrorLoopDetails",
      "type": "n8n-nodes-base.code",
      "position": [
        5072,
        224
      ],
      "parameters": {
        "jsCode": "const autoErrorFixing = $('localVariables').last().json.autoErrorFixing;\nconst wasExecuted = $('GenerateErrorPrompt').isExecuted;\n\nif (!autoErrorFixing || !wasExecuted) {\n  return [{ json: { details: { errorLoop: [] } } }];\n}\n\nconst errorLoop = [];\n\nlet counter = 0;\ndo {\n  try {\n    const erroritems = $items(\"GenerateErrorPrompt\", 0, counter).map(erroritem => { return {errorMessage: erroritem.json.message, description: erroritem.json.error?.description} });\n    const outputitems = $items(\"setOutputByProvider\", 0, counter).map(item => { return {output: item.json.output}});\n    errorLoop.push([...outputitems, ...erroritems]);\n  } catch (error) {\n    return [ { json: { details: { errorLoop } } } ];  \n  }\n\n  counter++;\n} while(true);"
      },
      "typeVersion": 2
    },
    {
      "id": "607ac294-c68c-4599-af02-a9a7fc265de9",
      "name": "setThreadId",
      "type": "n8n-nodes-base.set",
      "position": [
        1184,
        -480
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "a7c8e1dd-c6bc-49a0-b7cd-8c8cb021f16e",
              "name": "",
              "type": "string",
              "value": ""
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "0db968fc-e44c-47df-a85b-97c08f7a3b20",
      "name": "collectErrorLoopDetails1",
      "type": "n8n-nodes-base.code",
      "position": [
        4208,
        -352
      ],
      "parameters": {
        "jsCode": "const autoErrorFixing = $('localVariables').last().json.autoErrorFixing;\nconst wasExecuted = $('GenerateErrorPrompt').isExecuted;\n\nif (!autoErrorFixing || !wasExecuted) {\n  return [{ json: { details: { errorLoop: [] } } }];\n}\n\nconst errorLoop = [];\n\nlet counter = 0;\ndo {\n  try {\n    const erroritems = $items(\"GenerateErrorPrompt\", 0, counter).map(erroritem => { return {errorMessage: erroritem.json.message, description: erroritem.json.error?.description} });\n    const outputitems = $items(\"setOutputByProvider\", 0, counter).map(item => { return {output: item.json.output}});\n    errorLoop.push([...outputitems, ...erroritems]);\n  } catch (error) {\n    return [ { json: { details: { errorLoop } } } ];  \n  }\n\n  counter++;\n} while(true);"
      },
      "typeVersion": 2
    },
    {
      "id": "2642435e-47db-4009-bc04-6a9014548669",
      "name": "Execute a SQL query",
      "type": "n8n-nodes-base.mySql",
      "onError": "continueErrorOutput",
      "position": [
        4304,
        608
      ],
      "parameters": {
        "query": "{{ $json.output }}",
        "options": {},
        "operation": "executeQuery"
      },
      "credentials": {
        "mySql": {
          "name": "<your credential>"
        }
      },
      "typeVersion": 2.5
    },
    {
      "id": "ab334954-c05c-403f-a688-aaa1824f47ea",
      "name": "Switch",
      "type": "n8n-nodes-base.switch",
      "position": [
        3984,
        384
      ],
      "parameters": {
        "rules": {
          "values": [
            {
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "1a425da8-5077-45db-b316-c6e5fca10983",
                    "operator": {
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $('localVariables').last().json.selectedDatabaseType }}",
                    "rightValue": "postgresql"
                  }
                ]
              }
            },
            {
              "conditions": {
                "options": {
                  "version": 2,
                  "leftValue": "",
                  "caseSensitive": true,
                  "typeValidation": "strict"
                },
                "combinator": "and",
                "conditions": [
                  {
                    "id": "535cc6ab-875f-4a0b-a89a-a4792cc2dc30",
                    "operator": {
                      "name": "filter.operator.equals",
                      "type": "string",
                      "operation": "equals"
                    },
                    "leftValue": "={{ $('localVariables').last().json.selectedDatabaseType }}",
                    "rightValue": "mysql"
                  }
                ]
              }
            }
          ]
        },
        "options": {}
      },
      "typeVersion": 3.2
    }
  ],
  "active": true,
  "settings": {
    "callerPolicy": "workflowsFromSameOwner",
    "errorWorkflow": "BLUvEJjOxACvh7gM",
    "executionOrder": "v1"
  },
  "versionId": "742ecb68-9a9f-4a88-899c-7f6c2a197be0",
  "connections": {
    "If": {
      "main": [
        [
          {
            "node": "isAssistantExistsCode",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "issueOnOpenAiSide",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Switch": {
      "main": [
        [
          {
            "node": "Execute_AI_result",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute a SQL query",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IfError": {
      "main": [
        [
          {
            "node": "AutoErrorFixing",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IfOpenAI": {
      "main": [
        [
          {
            "node": "AgentName",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "OpenRouterAgent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "isOpenAI": {
      "main": [
        [
          {
            "node": "OpenAIMainBrain",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "OpenRouterAgent",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AgentName": {
      "main": [
        [
          {
            "node": "getAssistantsList",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "assistant": {
      "main": [
        [
          {
            "node": "OpenAIMainBrain",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "setThreadId": {
      "main": [
        [
          {
            "node": "isExecutable",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "isExecutable": {
      "main": [
        [
          {
            "node": "setOutputByProvider",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "wordsForUser1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simple Memory": {
      "ai_memory": [
        [
          {
            "node": "OpenRouterAgent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "localVariables": {
      "main": [
        [
          {
            "node": "IfOpenAI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AutoErrorFixing": {
      "main": [
        [
          {
            "node": "IsMaxAutoErrorReached",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "askUserHowToHandleError",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAIMainBrain": {
      "main": [
        [
          {
            "node": "setThreadId",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouterAgent": {
      "main": [
        [
          {
            "node": "isExecutable",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "executedSQLQuery": {
      "main": [
        []
      ]
    },
    "Execute_AI_result": {
      "main": [
        [
          {
            "node": "mergeExecutionsResult",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "GenerateErrorPrompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "getAssistantsList": {
      "main": [
        [
          {
            "node": "If",
            "type": "main",
            "index": 0
          }
        ],
        []
      ]
    },
    "isAssistantExists": {
      "main": [
        [
          {
            "node": "assistant",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "createOpenAiAssistant",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Execute a SQL query": {
      "main": [
        [
          {
            "node": "mergeExecutionsResult",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "GenerateErrorPrompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "GenerateErrorPrompt": {
      "main": [
        [
          {
            "node": "isOpenAI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "setOutputByProvider": {
      "main": [
        [
          {
            "node": "IfError",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IsMaxAutoErrorReached": {
      "main": [
        [
          {
            "node": "collectErrorLoopDetails1",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Switch",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouter Chat Model": {
      "ai_languageModel": [
        [
          {
            "node": "OpenRouterAgent",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "createOpenAiAssistant": {
      "main": [
        [
          {
            "node": "assistant",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "isAssistantExistsCode": {
      "main": [
        [
          {
            "node": "isAssistantExists",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "mergeExecutionsResult": {
      "main": [
        [
          {
            "node": "collectErrorLoopDetails",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "collectErrorLoopDetails": {
      "main": [
        [
          {
            "node": "executedSQLQuery",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "collectErrorLoopDetails1": {
      "main": [
        [
          {
            "node": "maxAutoErrorLimitReached",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "maxAutoErrorLimitReached": {
      "main": [
        []
      ]
    },
    "When chat message received": {
      "main": [
        [
          {
            "node": "localVariables",
            "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

This is the core AI agent used for queryverify.com.

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

HDW Lead Geländewagen. Uses chatTrigger, lmChatOpenAi, memoryBufferWindow, outputParserStructured. Chat trigger; 92 nodes.

Chat Trigger, OpenAI Chat, Memory Buffer Window +5
AI & RAG

Community Node Disclaimer: This workflow uses KlickTipp community nodes.

Chat Trigger, OpenAI Chat, Memory Buffer Window +6
AI & RAG

Who is this workflow for? This workflow is designed for SEO analysts, content creators, marketing agencies, and developers who need to index a website and then interact with its content as if it were

Agent, OpenAI Chat, Memory Buffer Window +10
AI & RAG

Categories: AI Agents, Design Automation, Business Tools

Tool Workflow, HTTP Request Tool, Memory Buffer Window +7
AI & RAG

This workflow enables users to interact with a PostgreSQL database using natural language. It translates text inputs into SQL queries, retrieves the corresponding data, and generates visualizations us

Memory Buffer Window, Read Write File, Chat Trigger +4