8
n8n 中文网amn8n.com

isra36

高级

这是一个Engineering, AI Chatbot领域的自动化工作流,包含 40 个节点。主要使用 If, Set, Code, Merge, Postgres 等节点。 使用GPT/OpenRouter AI和PostgreSQL沙盒生成并测试SQL代码

前置要求
  • PostgreSQL 数据库连接信息
  • OpenAI API Key
工作流预览
可视化展示节点连接关系,支持缩放和平移
导出工作流
复制以下 JSON 配置到 n8n 导入,即可使用此工作流
{
  "id": "H6iWWu9KK0XoaPXa",
  "meta": {
    "instanceId": "90a1d1cf1e9e6d9ee6e8c37df44d53777d9bc4425de96a5a0f770320161d5171"
  },
  "name": "isra36",
  "tags": [],
  "nodes": [
    {
      "id": "47f2b3b4-12f0-4e9c-82f4-54d2c32b77f0",
      "name": "当收到聊天消息时",
      "type": "@n8n/n8n-nodes-langchain.chatTrigger",
      "position": [
        -1820,
        120
      ],
      "webhookId": "a889d2ae-2159-402f-b326-5f61e90f602e",
      "parameters": {
        "mode": "webhook",
        "public": true,
        "options": {}
      },
      "typeVersion": 1.1
    },
    {
      "id": "424b2831-425b-4ee7-a3d5-b2713bfdf343",
      "name": "生成错误提示",
      "type": "n8n-nodes-base.code",
      "position": [
        4140,
        460
      ],
      "parameters": {
        "jsCode": "\n\nreturn {\n  \"message\" : $input.last().json.message,\n  \"prompt\" : \"Recieved error while executing this query: \" + $input.last().json.message + \". Here detailed description: \" + $input.last().json.error.description + \". Please fix SQL query. Please decide how to solve and give fixed SQL query.\"\n}"
      },
      "typeVersion": 2
    },
    {
      "id": "07f2f95a-0958-4562-b5c4-1bb6504a02fd",
      "name": "简单记忆",
      "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
      "position": [
        1040,
        400
      ],
      "parameters": {
        "sessionKey": "={{ $('localVariables').last().json.sessionId }}",
        "sessionIdType": "customKey",
        "contextWindowLength": 7
      },
      "typeVersion": 1.3
    },
    {
      "id": "7f42bf3b-5d99-41d4-94e7-0a34da39e285",
      "name": "自动错误修复",
      "type": "n8n-nodes-base.if",
      "position": [
        3080,
        -40
      ],
      "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": "如果错误",
      "type": "n8n-nodes-base.if",
      "position": [
        2860,
        20
      ],
      "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": "执行_AI_结果",
      "type": "n8n-nodes-base.postgres",
      "onError": "continueErrorOutput",
      "position": [
        3620,
        160
      ],
      "parameters": {
        "query": "{{ $json.output }}",
        "options": {},
        "operation": "executeQuery"
      },
      "credentials": {
        "postgres": {
          "id": "OunYREGTB5g2u3LA",
          "name": "Postgres account 2"
        }
      },
      "typeVersion": 2.6
    },
    {
      "id": "d4c60f3d-425e-4fef-923c-a2fa154f0a00",
      "name": "助手是否存在",
      "type": "n8n-nodes-base.if",
      "position": [
        100,
        -460
      ],
      "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": "助手存在代码",
      "type": "n8n-nodes-base.code",
      "position": [
        -200,
        -460
      ],
      "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 = $input.first().json.id;\n  }\n}\n\nreturn {output: isAssistantExists, id: assistantId};"
      },
      "typeVersion": 2
    },
    {
      "id": "ff979107-3937-4feb-aaf3-4ff9337325da",
      "name": "是否为OpenAI",
      "type": "n8n-nodes-base.if",
      "position": [
        4360,
        460
      ],
      "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": "助手",
      "type": "n8n-nodes-base.set",
      "position": [
        580,
        -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": "如果是OpenAI",
      "type": "n8n-nodes-base.if",
      "position": [
        -1180,
        120
      ],
      "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": "便签",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1540,
        20
      ],
      "parameters": {
        "height": 260,
        "content": "使用此工具获取必要的局部变量,例如:给AI的指令、sessionId,以及之前节点输入的所有参数"
      },
      "typeVersion": 1
    },
    {
      "id": "02dbf130-9e82-4d85-b743-2cb488fb0f46",
      "name": "便签2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1900,
        -180
      ],
      "parameters": {
        "color": 4,
        "width": 260,
        "height": 460,
        "content": "输入参数:"
      },
      "typeVersion": 1
    },
    {
      "id": "e10c42db-8c9f-4052-8205-259b53ebdc3f",
      "name": "是否达到最大自动错误次数",
      "type": "n8n-nodes-base.if",
      "position": [
        3340,
        -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聊天模型",
      "type": "@n8n/n8n-nodes-langchain.lmChatOpenRouter",
      "position": [
        900,
        400
      ],
      "parameters": {
        "options": {}
      },
      "typeVersion": 1
    },
    {
      "id": "20960f49-d573-45e0-a3e0-f5e181a8ef66",
      "name": "代理名称",
      "type": "n8n-nodes-base.set",
      "position": [
        -900,
        -460
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "527cbbeb-e3a7-4fb5-aaae-fd2b8085de85",
              "name": "agentName",
              "type": "string",
              "value": "={{ 'AiDoubleCheck_' + $('localVariables').last().json.model }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "9f28f786-c999-4614-8d74-e67f945583e2",
      "name": "按提供者设置输出",
      "type": "n8n-nodes-base.set",
      "position": [
        2480,
        -200
      ],
      "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": "OpenAI主脑",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        820,
        -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": {},
        "resource": "assistant",
        "threadId": "={{ $ifEmpty($('localVariables').last().json.threadId, null) }}",
        "assistantId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('assistant').last().json.id }}"
        }
      },
      "credentials": {
        "openAiApi": {
          "id": "YYAgs4Xc0ZRuGvPa",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.8
    },
    {
      "id": "723fd28e-628e-417a-826c-2fd025a8a026",
      "name": "询问用户如何处理错误",
      "type": "n8n-nodes-base.set",
      "position": [
        3320,
        -20
      ],
      "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 }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "0e4af952-6e07-4cb0-a4ff-6705ed3bbfc0",
      "name": "达到最大自动错误限制",
      "type": "n8n-nodes-base.set",
      "position": [
        3640,
        -340
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "562ef9d0-d7c1-43f3-8ceb-608b6576f4e2",
              "name": "output",
              "type": "string",
              "value": "={{ $json.output }}"
            },
            {
              "id": "b9ddb8b4-56ab-4d7e-b3fa-2a72c5158d26",
              "name": "type",
              "type": "string",
              "value": "maxAutoErrorLimitReached"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "43a23e59-31f7-40fb-b911-9e3dd9bad912",
      "name": "条件判断",
      "type": "n8n-nodes-base.if",
      "position": [
        -440,
        -460
      ],
      "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": "给用户的话1",
      "type": "n8n-nodes-base.set",
      "position": [
        1660,
        20
      ],
      "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 }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "1347b643-7109-4148-86bd-89b540861b06",
      "name": "是否可执行",
      "type": "n8n-nodes-base.if",
      "position": [
        1340,
        -180
      ],
      "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": "获取助手列表",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "onError": "continueRegularOutput",
      "position": [
        -660,
        -460
      ],
      "parameters": {
        "resource": "assistant",
        "operation": "list"
      },
      "credentials": {
        "openAiApi": {
          "id": "YYAgs4Xc0ZRuGvPa",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.8,
      "alwaysOutputData": true
    },
    {
      "id": "84f8b40b-c563-4b28-a70c-c4c5b7323d1b",
      "name": "便签1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -1260,
        20
      ],
      "parameters": {
        "color": 5,
        "height": 260,
        "content": "OpenAI内置了处理聊天历史的助手。对于open-router,我们应该在我们这边处理聊天历史"
      },
      "typeVersion": 1
    },
    {
      "id": "efca8f7c-1115-4086-9b53-111574a00cee",
      "name": "便签3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1280,
        -300
      ],
      "parameters": {
        "height": 260,
        "content": "有时我们无法仅用代码回答。此节点负责分离。如果不是沙盒代码,它将作为文字发送给用户。"
      },
      "typeVersion": 1
    },
    {
      "id": "a793ec0d-97fc-49aa-8c2a-f3746946ed95",
      "name": "便签4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3280,
        -420
      ],
      "parameters": {
        "height": 260,
        "content": "错误修复循环仅工作n次,在此节点中定义。这样做是为了防止无限循环"
      },
      "typeVersion": 1
    },
    {
      "id": "d12ff01c-662d-4204-a1a7-1c91b122a5cd",
      "name": "便签5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3020,
        -180
      ],
      "parameters": {
        "color": 2,
        "width": 220,
        "height": 280,
        "content": "如果用户选择了自动错误修复,将自动执行调试,否则系统将询问用户进一步指示"
      },
      "typeVersion": 1
    },
    {
      "id": "d004ab56-4a20-4a9d-ae2b-c899421af2af",
      "name": "获取所有表",
      "type": "n8n-nodes-base.postgres",
      "disabled": true,
      "position": [
        3720,
        1300
      ],
      "parameters": {
        "query": "SELECT tablename\nFROM pg_catalog.pg_tables\nWHERE schemaname = 'public';",
        "options": {},
        "operation": "executeQuery"
      },
      "credentials": {
        "postgres": {
          "id": "OunYREGTB5g2u3LA",
          "name": "Postgres account 2"
        }
      },
      "typeVersion": 2.6
    },
    {
      "id": "479c3308-8f3a-420a-8d2d-206ce6acb10b",
      "name": "合并",
      "type": "n8n-nodes-base.merge",
      "disabled": true,
      "position": [
        4780,
        1160
      ],
      "parameters": {},
      "typeVersion": 3.1
    },
    {
      "id": "a9832d33-f46e-4273-b7b3-0019bd33cc93",
      "name": "从整个查询中提取解决方案",
      "type": "n8n-nodes-base.code",
      "disabled": true,
      "position": [
        4400,
        980
      ],
      "parameters": {
        "jsCode": "const agentOutput = $(\"OpenRouterAgent\").all()[0]?.json?.output;\nconst commands = agentOutput.split(\"\\n\\n\");\nconst filteredCommands = commands.filter(\n  (command) =>\n    !command.includes(\"CREATE TABLE\") &&\n    !command.includes(\"INSERT INTO\"),\n);\nconst result = filteredCommands.join(\"\\n\\n\");\n\nreturn { result };\n"
      },
      "typeVersion": 2
    },
    {
      "id": "def0dfb5-e863-4712-83bd-e5d00599ac4d",
      "name": "为每个添加表名",
      "type": "n8n-nodes-base.code",
      "disabled": true,
      "position": [
        4600,
        1540
      ],
      "parameters": {
        "jsCode": "for (const item of $input.all()) {\n  item.json.tableName = $('Loop Over Items').first().json.Tables_in_sql5776769;\n}\n\nreturn $input.all();"
      },
      "typeVersion": 2
    },
    {
      "id": "d0ef4902-a0dc-4ad4-a970-db60e4716935",
      "name": "转换为HTML表格",
      "type": "n8n-nodes-base.code",
      "disabled": true,
      "position": [
        4420,
        1320
      ],
      "parameters": {
        "jsCode": "const items = $input.all().map((item) => item.json);\n\nlet result = {};\n\nitems.forEach((item) => {\n  const tableName = item.tableName;\n  delete item.tableName;\n\n  if (!result[tableName]) {\n    result[tableName] = [];\n  }\n\n  result[tableName].push(item);\n});\n\nreturn result;\n"
      },
      "typeVersion": 2
    },
    {
      "id": "d94e0429-8e30-429d-9cfc-c53422a557fd",
      "name": "遍历项目",
      "type": "n8n-nodes-base.splitInBatches",
      "disabled": true,
      "position": [
        4100,
        1300
      ],
      "parameters": {
        "options": {
          "reset": false
        }
      },
      "typeVersion": 3
    },
    {
      "id": "c152627d-5e33-4dfc-a0bc-db1aceb1d0da",
      "name": "选择所有数据",
      "type": "n8n-nodes-base.postgres",
      "disabled": true,
      "position": [
        4340,
        1540
      ],
      "parameters": {
        "table": {
          "__rl": true,
          "mode": "name",
          "value": "{{ $json.Tables_in_sql5776769 }}"
        },
        "schema": {
          "__rl": true,
          "mode": "list",
          "value": "public"
        },
        "options": {},
        "operation": "select",
        "returnAll": true
      },
      "credentials": {
        "postgres": {
          "id": "OunYREGTB5g2u3LA",
          "name": "Postgres account 2"
        }
      },
      "typeVersion": 2.6
    },
    {
      "id": "39a21d61-816d-4414-8f0b-d87adda9f350",
      "name": "OpenRouter代理",
      "type": "@n8n/n8n-nodes-langchain.agent",
      "position": [
        860,
        120
      ],
      "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": "创建OpenAI助手",
      "type": "@n8n/n8n-nodes-langchain.openAi",
      "position": [
        340,
        -300
      ],
      "parameters": {
        "name": "={{ $('AgentName').last().json.agentName }} ",
        "modelId": {
          "__rl": true,
          "mode": "id",
          "value": "={{ $('localVariables').last().json.model }}"
        },
        "options": {},
        "resource": "assistant",
        "operation": "create",
        "description": "将在playground中直接双重检查代码",
        "instructions": "={{ $('localVariables').last().json.instruction }}"
      },
      "credentials": {
        "openAiApi": {
          "id": "YYAgs4Xc0ZRuGvPa",
          "name": "OpenAi account"
        }
      },
      "typeVersion": 1.8
    },
    {
      "id": "1caf5dec-7cbd-4cbf-9687-48d4aa33cd35",
      "name": "局部变量",
      "type": "n8n-nodes-base.set",
      "position": [
        -1460,
        120
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "5ee9645b-83f9-4f0e-9fd3-4a75121bee9a",
              "name": "instruction",
              "type": "string",
              "value": "=You are a senior PostgreSQL developer helping users solve PostgreSQL tasks in a PostgreSQL Playground environment. Follow these rules:\n\n1. Your response must always contain fully executable SQL code — with no markdown formatting. Never explain or comment in natural language.\n2. Assume that the first user prompt starts with an empty PostgreSQL Playground. You must begin with `CREATE TABLE` statements to build a realistic schema related to the task.\n3. The user will provide a table name prefix (e.g., session_abc199935). All table names must begin with that prefix and be enclosed in double quotes. Example: \"session_abc199935_users\".\n4. After creating tables, always include at least 3 rows of mock data using `INSERT INTO`.\n5. Finish each response with the actual query that solves the user’s request. This query must run on the created (or existing) tables and produce a verifiable result.\n6. Always separate the final query from setup using this comment: \"\"\"-- ACTUAL_SOLUTION\"\"\". Remember use only this comment for separation.\n7. 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 `pg_catalog` views to provide introspective queries.\n8. This conversation may span multiple questions. In follow-up prompts, the schema and data already exist. You must use the current db tables as a foundation and ** create, alter, drop tables or data if the task requires it**.\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 — but generate no SQL.\n\nThe goal is to always output SQL code that users can copy and run directly in a PostgreSQL Playground to verify the result. In follow-ups, your SQL must adapt to the existing schema, expanding it or querying it intelligently as needed.\n"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "e4025036-da4e-4e6b-ad3e-97c5242aa861",
      "name": "已执行的SQL查询",
      "type": "n8n-nodes-base.set",
      "position": [
        4240,
        20
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "cfc317f9-d9fa-4026-9b2a-1cd4b13b87c6",
              "name": "query",
              "type": "string",
              "value": "={{ \n  $if($('localVariables').last().json.aiProvider === 'openai', \n    $('OpenAIMainBrain').last().json.output, \n    $('OpenRouterAgent').last().json.output\n  )\n}}"
            },
            {
              "id": "594046d1-9b2d-43cb-9609-04ee4f70364f",
              "name": "type",
              "type": "string",
              "value": "success"
            },
            {
              "id": "c6de1fb5-60a4-4050-a401-973139f42dfb",
              "name": "executionResult",
              "type": "string",
              "value": "={{ $json }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "ff239015-892a-4762-8de6-537396e1d1c3",
      "name": "OpenAI端的问题",
      "type": "n8n-nodes-base.set",
      "position": [
        -240,
        -260
      ],
      "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
    }
  ],
  "active": true,
  "pinData": {
    "When chat message received": [
      {
        "json": {
          "model": "gpt-4.1-mini",
          "apiKey": "YOURAPIKEY",
          "threadId": null,
          "chatInput": "how to check if all {pattern}_id columns have indexes through all tables prefix for tables.",
          "sessionId": "01981188-bba3-731e-abd0-ca8c5cfeef6b",
          "aiProvider": "openai",
          "autoErrorFixing": true,
          "currentDbSchemaWithData": "[]"
        }
      }
    ]
  },
  "settings": {
    "callerPolicy": "workflowsFromSameOwner",
    "errorWorkflow": "BLUvEJjOxACvh7gM",
    "executionOrder": "v1"
  },
  "versionId": "1bbe9a2a-23b3-469b-a4c8-3877c2baf140",
  "connections": {
    "If": {
      "main": [
        [
          {
            "node": "isAssistantExistsCode",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "issueOnOpenAiSide",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IfError": {
      "main": [
        [
          {
            "node": "AutoErrorFixing",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute_AI_result",
            "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
          }
        ]
      ]
    },
    "isExecutable": {
      "main": [
        [
          {
            "node": "setOutputByProvider",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "wordsForUser1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "SelectAllData": {
      "main": [
        [
          {
            "node": "Add TableName ForEach",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Simple Memory": {
      "ai_memory": [
        [
          {
            "node": "OpenRouterAgent",
            "type": "ai_memory",
            "index": 0
          }
        ]
      ]
    },
    "get_all_tables": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "localVariables": {
      "main": [
        [
          {
            "node": "IfOpenAI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "AutoErrorFixing": {
      "main": [
        [
          {
            "node": "IsMaxAutoErrorReached",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "askUserHowToHandleError",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Loop Over Items": {
      "main": [
        [
          {
            "node": "Extract Solution From Entire Query",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Transform for HTML table",
            "type": "main",
            "index": 0
          },
          {
            "node": "SelectAllData",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenAIMainBrain": {
      "main": [
        [
          {
            "node": "isExecutable",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "OpenRouterAgent": {
      "main": [
        [
          {
            "node": "isExecutable",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "executedSQLQuery": {
      "main": [
        []
      ]
    },
    "Execute_AI_result": {
      "main": [
        [
          {
            "node": "executedSQLQuery",
            "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
          }
        ]
      ]
    },
    "GenerateErrorPrompt": {
      "main": [
        [
          {
            "node": "isOpenAI",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "setOutputByProvider": {
      "main": [
        [
          {
            "node": "IfError",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Add TableName ForEach": {
      "main": [
        [
          {
            "node": "Loop Over Items",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "IsMaxAutoErrorReached": {
      "main": [
        [
          {
            "node": "maxAutoErrorLimitReached",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Execute_AI_result",
            "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
          }
        ]
      ]
    },
    "Transform for HTML table": {
      "main": [
        [
          {
            "node": "Merge",
            "type": "main",
            "index": 1
          }
        ]
      ]
    },
    "When chat message received": {
      "main": [
        [
          {
            "node": "localVariables",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Extract Solution From Entire Query": {
      "main": [
        [
          {
            "node": "Merge",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
常见问题

如何使用这个工作流?

复制上方的 JSON 配置代码,在您的 n8n 实例中创建新工作流并选择「从 JSON 导入」,粘贴配置后根据需要修改凭证设置即可。

这个工作流适合什么场景?

高级 - 工程, AI 聊天机器人

需要付费吗?

本工作流完全免费,您可以直接导入使用。但请注意,工作流中使用的第三方服务(如 OpenAI API)可能需要您自行付费。

工作流信息
难度等级
高级
节点数量40
分类2
节点类型12
难度说明

适合高级用户,包含 16+ 个节点的复杂工作流

外部链接
在 n8n.io 查看

分享此工作流