{
  "workflow": {
    "id": 3680,
    "name": "Query PostgreSQL database with natural language using Groq AI chatbot",
    "views": 1076,
    "recentViews": 0,
    "totalViews": 1076,
    "createdAt": "2025-04-23T23:07:27.296Z",
    "description": "This guide shows you how to deploy a chatbot that lets you query your **PostgreSQL** database using natural language. You will build a system that accepts chat messages, retains conversation history, constructs dynamic SQL queries, and returns responses generated by an AI model. By following these instructions, you will have a working solution that integrates n8n’s AI Agent capabilities with **PostgreSQL**.\n\n![AI Chatbot PostgreSQL.png](fileId:1161)\n\n### Prerequisites\n\nBefore you begin, ensure that you have the following:\n\n* An active n8n instance (self-hosted or cloud) running version 1.50.0 or later.\n* Valid **PostgreSQL** credentials configured in n8n.\n* API credentials for the Groq Chat Model (or your preferred AI language model).\n* Basic familiarity with SQL (specifically **PostgreSQL** syntax) and n8n node concepts such as chat triggers and memory buffers.\n* Access to the n8n Docs on AI Agents for further reference.\n\n### Workflow Setup\n\n1.  **Chat Interface & Trigger**\n    * **When Chat Message Received:** This node listens for incoming chat messages via a webhook. When a message arrives, it triggers the workflow immediately.\n\n2.  **Conversation Memory**\n    * **Chat History:** This memory buffer node stores the last 10 interactions. It supplies conversation context to the AI Agent, ensuring that responses consider previous messages.\n\n3.  **AI Agent Core**\n    * **AI Agent (Tools Agent):** The AI Agent node orchestrates the conversation by receiving the chat input and conversation history. It dynamically generates **PostgreSQL**-compatible SQL queries based on your requests and coordinates calls to external tools (such as **PostgreSQL** nodes).\n\n4.  **Database Interactions**\n    * **PostgreSQL Node (Query Execution):** This node executes the SQL query generated by the AI Agent against your **PostgreSQL** database. You reference the query using an expression (e.g., `{{$node[\"AI Agent\"].json.sql_query}}`), allowing the agent’s output to control data retrieval.\n    * **PostgreSQL Node (Schema Retrieval):** This node (or a dedicated step using the **PostgreSQL** node) retrieves a list of relevant tables from your **PostgreSQL** database (e.g., from the `public` schema, excluding system schemas like `pg_catalog` or `information_schema`). The agent uses this information to understand the available tables. This typically involves executing a query like `SELECT table_name FROM information_schema.tables WHERE table_schema = 'public';`.\n    * **PostgreSQL Node (Table Definition Retrieval):** This node (or another dedicated step using the **PostgreSQL** node) fetches detailed metadata (such as column names, data types, and potentially relationships using foreign keys) for a specific table. The table name (and schema if necessary) is supplied dynamically by the AI Agent. This often involves querying `information_schema.columns`, e.g., `SELECT column_name, data_type FROM information_schema.columns WHERE table_name = '{{dynamic_table_name}}' AND table_schema = 'public';`.\n\n5.  **Language Model Processing**\n    * **Groq Chat Model:** This node connects to the Groq Chat API to generate text completions. It processes the combined input (chat message, context, and data fetched from **PostgreSQL**) and produces the final response.\n\n6.  **Guidance & Customization**\n    * **Sticky Notes:** These nodes provide guidance on:\n        * Switching the chat model if you wish to use another provider (e.g., OpenAI or Anthropic).\n        * Adjusting the maximum token count per interaction.\n        * Customizing the SQL queries (ensuring **PostgreSQL** compatibility) and the context window size.\n    * They help you modify the workflow to suit your environment and requirements.\n\n### Workflow Connections\n\n* The **Chat Trigger** passes the incoming message to the **AI Agent**.\n* The **Chat History** node supplies conversation context to the AI Agent.\n* The **AI Agent** calls the **PostgreSQL** nodes as external tools, generating and sending dynamic SQL queries.\n* The **Groq Chat Model** processes the consolidated input from the agent and outputs the natural language response delivered to the user.\n\n### Testing the Workflow\n\n1.  Send a chat message using the chat interface.\n2.  Observe how the AI Agent processes the input and generates a corresponding **PostgreSQL** SQL query.\n3.  Verify that the **PostgreSQL** nodes execute the query correctly against your database and return data.\n4.  Confirm that the Groq Chat Model produces a coherent natural language response based on the query results.\n5.  Refer to the sticky notes for guidance if you need to fine-tune any node settings or SQL queries.\n\n### Next Steps and References\n\n* **Customize Your AI Model:** Replace the Groq Chat Model with another language model (such as the OpenAI Chat Model) by updating the node credentials and configuration.\n* **Enhance Memory Settings:** Adjust the Chat History node’s context window to retain more or fewer messages based on your needs.\n* **Modify SQL Queries:** Update the SQL queries within the **PostgreSQL** nodes or refine the prompts for the AI Agent to ensure they match your specific database schema and desired data, adhering to **PostgreSQL** syntax.\n* **Further Reading:** Consult the n8n Docs on AI Agents for additional details and examples to expand your workflow’s capabilities.\n* **Set Up a Website Chatbot:** Copy & Paste and replace the placeholders in the following code to embed the chatbot into your personal or company’s website: [View in CodePen 🡥](https://codepen.io/olemai/pen/RNwPdVp)\n\nBy following these steps, you will deploy a robust AI chatbot workflow that integrates with your **PostgreSQL** database, allowing you to query data using natural language.",
    "workflow": {
      "id": "ow1aBANn8lQH0TbA",
      "meta": {
        "instanceId": "47d295a7329d3547e0e6b56de9e439dc1a0a49c6d827b2320629f54300c47e41",
        "templateCredsSetupCompleted": true
      },
      "name": "My workflow 4",
      "tags": [],
      "nodes": [
        {
          "id": "3be32b55-6c92-45e3-805f-3c582f6bb237",
          "name": "When chat message received",
          "type": "@n8n/n8n-nodes-langchain.chatTrigger",
          "position": [
            760,
            320
          ],
          "webhookId": "cf1de04f-3e38-426c-89f0-3bdb110a5dcf",
          "parameters": {},
          "typeVersion": 1.1
        },
        {
          "id": "c0685ca7-91bd-4177-848d-ea7f3a4c160f",
          "name": "Chat History",
          "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
          "position": [
            1100,
            520
          ],
          "parameters": {},
          "typeVersion": 1.3
        },
        {
          "id": "b2e6112c-451e-434f-a732-4c469721f364",
          "name": "AI Agent",
          "type": "@n8n/n8n-nodes-langchain.agent",
          "position": [
            1180,
            320
          ],
          "parameters": {},
          "typeVersion": 1.7
        },
        {
          "id": "52a55d14-7a46-43fb-9f8c-5fdd099cc4b8",
          "name": "Groq Chat Model",
          "type": "@n8n/n8n-nodes-langchain.lmChatGroq",
          "position": [
            920,
            520
          ],
          "parameters": {},
          "typeVersion": 1
        },
        {
          "id": "d9ff0f6e-e08d-49bc-bd29-1a6602b1562e",
          "name": "Sticky Note1",
          "type": "n8n-nodes-base.stickyNote",
          "position": [
            880,
            700
          ],
          "parameters": {
            "content": ""
          },
          "typeVersion": 1
        },
        {
          "id": "56b21c24-9a74-4f61-ad03-2e6c892350d6",
          "name": "Sticky Note2",
          "type": "n8n-nodes-base.stickyNote",
          "position": [
            1060,
            700
          ],
          "parameters": {
            "content": ""
          },
          "typeVersion": 1
        },
        {
          "id": "63a28a91-68e3-45a5-b236-559db54f87b7",
          "name": "Sticky Note3",
          "type": "n8n-nodes-base.stickyNote",
          "position": [
            1240,
            700
          ],
          "parameters": {
            "content": ""
          },
          "typeVersion": 1
        },
        {
          "id": "b6dad064-7699-4f07-99c5-cca3a5f3bb82",
          "name": "Sticky Note",
          "type": "n8n-nodes-base.stickyNote",
          "position": [
            760,
            100
          ],
          "parameters": {
            "content": ""
          },
          "typeVersion": 1
        },
        {
          "id": "36b9bf75-cb1d-45ed-8e01-99c272580fae",
          "name": "PostgreSQL Schema",
          "type": "n8n-nodes-base.postgresTool",
          "position": [
            1480,
            520
          ],
          "parameters": {},
          "typeVersion": 2.5
        },
        {
          "id": "71f57073-6857-4b7f-9ee9-e1dc3ce250c5",
          "name": "PostgreSQL Definition",
          "type": "n8n-nodes-base.postgresTool",
          "position": [
            1660,
            520
          ],
          "parameters": {},
          "typeVersion": 2.5
        },
        {
          "id": "95e64a15-03c5-44d9-9a33-4cbd392ab008",
          "name": "PostgreSQL",
          "type": "n8n-nodes-base.postgresTool",
          "position": [
            1280,
            520
          ],
          "parameters": {},
          "typeVersion": 2.5
        }
      ],
      "active": false,
      "pinData": {},
      "settings": {
        "executionOrder": "v1"
      },
      "versionId": "59656397-0d25-47f3-94f3-c00beb3bf8d8",
      "connections": {
        "PostgreSQL": {
          "ai_tool": [
            [
              {
                "node": "AI Agent",
                "type": "ai_tool",
                "index": 0
              }
            ]
          ]
        },
        "Chat History": {
          "ai_memory": [
            [
              {
                "node": "AI Agent",
                "type": "ai_memory",
                "index": 0
              }
            ]
          ]
        },
        "Groq Chat Model": {
          "ai_languageModel": [
            [
              {
                "node": "AI Agent",
                "type": "ai_languageModel",
                "index": 0
              }
            ]
          ]
        },
        "PostgreSQL Schema": {
          "ai_tool": [
            [
              {
                "node": "AI Agent",
                "type": "ai_tool",
                "index": 0
              }
            ]
          ]
        },
        "PostgreSQL Definition": {
          "ai_tool": [
            [
              {
                "node": "AI Agent",
                "type": "ai_tool",
                "index": 0
              }
            ]
          ]
        },
        "When chat message received": {
          "main": [
            [
              {
                "node": "AI Agent",
                "type": "main",
                "index": 0
              }
            ]
          ]
        }
      }
    },
    "lastUpdatedBy": 29,
    "workflowInfo": {
      "nodeCount": 11,
      "nodeTypes": {
        "n8n-nodes-base.stickyNote": {
          "count": 4
        },
        "n8n-nodes-base.postgresTool": {
          "count": 3
        },
        "@n8n/n8n-nodes-langchain.agent": {
          "count": 1
        },
        "@n8n/n8n-nodes-langchain.lmChatGroq": {
          "count": 1
        },
        "@n8n/n8n-nodes-langchain.chatTrigger": {
          "count": 1
        },
        "@n8n/n8n-nodes-langchain.memoryBufferWindow": {
          "count": 1
        }
      }
    },
    "status": "published",
    "readyToDemo": null,
    "user": {
      "name": "Gegenfeld",
      "username": "gegenfeld",
      "bio": "We at Gegenfeld are an EdTech platform dedicated to delivering high-quality on-demand courses and interactive training sessions for professional development at all skill levels. With our commitment to \"Accelerate your future,\" we empower professionals to enhance their expertise through engaging, industry-focused learning experiences. On n8n, we share some of the workflows used in our interactive training to provide deeper insights and practical applications.",
      "verified": true,
      "links": [
        "https://gegenfeld.com"
      ],
      "avatar": "https://gravatar.com/avatar/c8a1c789de3e9122a421139cc2d7dc9ab404dfb76ac84a17fa487e8f607ae9ab?r=pg&d=retro&size=200"
    },
    "nodes": [
      {
        "id": 565,
        "icon": "fa:sticky-note",
        "name": "n8n-nodes-base.stickyNote",
        "codex": {
          "data": {
            "alias": [
              "Comments",
              "Notes",
              "Sticky"
            ],
            "categories": [
              "Core Nodes"
            ],
            "nodeVersion": "1.0",
            "codexVersion": "1.0",
            "subcategories": {
              "Core Nodes": [
                "Helpers"
              ]
            }
          }
        },
        "group": "[\"input\"]",
        "defaults": {
          "name": "Sticky Note",
          "color": "#FFD233"
        },
        "iconData": {
          "icon": "sticky-note",
          "type": "icon"
        },
        "displayName": "Sticky Note",
        "typeVersion": 1,
        "nodeCategories": [
          {
            "id": 9,
            "name": "Core Nodes"
          }
        ]
      },
      {
        "id": 1119,
        "icon": "fa:robot",
        "name": "@n8n/n8n-nodes-langchain.agent",
        "codex": {
          "data": {
            "alias": [
              "LangChain",
              "Chat",
              "Conversational",
              "Plan and Execute",
              "ReAct",
              "Tools"
            ],
            "resources": {
              "primaryDocumentation": [
                {
                  "url": "https://docs.n8n.io/integrations/builtin/cluster-nodes/root-nodes/n8n-nodes-langchain.agent/"
                }
              ]
            },
            "categories": [
              "AI",
              "Langchain"
            ],
            "subcategories": {
              "AI": [
                "Agents",
                "Root Nodes"
              ]
            }
          }
        },
        "group": "[\"transform\"]",
        "defaults": {
          "name": "AI Agent",
          "color": "#404040"
        },
        "iconData": {
          "icon": "robot",
          "type": "icon"
        },
        "displayName": "AI Agent",
        "typeVersion": 3,
        "nodeCategories": [
          {
            "id": 25,
            "name": "AI"
          },
          {
            "id": 26,
            "name": "Langchain"
          }
        ]
      },
      {
        "id": 1163,
        "icon": "fa:database",
        "name": "@n8n/n8n-nodes-langchain.memoryBufferWindow",
        "codex": {
          "data": {
            "resources": {
              "primaryDocumentation": [
                {
                  "url": "https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.memorybufferwindow/"
                }
              ]
            },
            "categories": [
              "AI",
              "Langchain"
            ],
            "subcategories": {
              "AI": [
                "Memory"
              ],
              "Memory": [
                "For beginners"
              ]
            }
          }
        },
        "group": "[\"transform\"]",
        "defaults": {
          "name": "Simple Memory"
        },
        "iconData": {
          "icon": "database",
          "type": "icon"
        },
        "displayName": "Simple Memory",
        "typeVersion": 1,
        "nodeCategories": [
          {
            "id": 25,
            "name": "AI"
          },
          {
            "id": 26,
            "name": "Langchain"
          }
        ]
      },
      {
        "id": 1247,
        "icon": "fa:comments",
        "name": "@n8n/n8n-nodes-langchain.chatTrigger",
        "codex": {
          "data": {
            "resources": {
              "primaryDocumentation": [
                {
                  "url": "https://docs.n8n.io/integrations/builtin/core-nodes/n8n-nodes-langchain.chattrigger/"
                }
              ]
            },
            "categories": [
              "Core Nodes",
              "Langchain"
            ]
          }
        },
        "group": "[\"trigger\"]",
        "defaults": {
          "name": "When chat message received"
        },
        "iconData": {
          "icon": "comments",
          "type": "icon"
        },
        "displayName": "Chat Trigger",
        "typeVersion": 1,
        "nodeCategories": [
          {
            "id": 9,
            "name": "Core Nodes"
          },
          {
            "id": 26,
            "name": "Langchain"
          }
        ]
      },
      {
        "id": 1263,
        "icon": "file:groq.svg",
        "name": "@n8n/n8n-nodes-langchain.lmChatGroq",
        "codex": {
          "data": {
            "resources": {
              "primaryDocumentation": [
                {
                  "url": "https://docs.n8n.io/integrations/builtin/cluster-nodes/sub-nodes/n8n-nodes-langchain.lmchatgroq/"
                }
              ]
            },
            "categories": [
              "AI",
              "Langchain"
            ],
            "subcategories": {
              "AI": [
                "Language Models",
                "Root Nodes"
              ],
              "Language Models": [
                "Chat Models (Recommended)"
              ]
            }
          }
        },
        "group": "[\"transform\"]",
        "defaults": {
          "name": "Groq Chat Model"
        },
        "iconData": {
          "type": "file",
          "fileBuffer": "data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjxzdmcKICAgaWQ9IkxheWVyXzIiCiAgIHZpZXdCb3g9IjAgMCA0OTkuOTk5OTkgNDk5Ljk5OTk5IgogICB2ZXJzaW9uPSIxLjEiCiAgIHdpZHRoPSI1MDAiCiAgIGhlaWdodD0iNTAwIgogICB4bWw6c3BhY2U9InByZXNlcnZlIgogICB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciCiAgIHhtbG5zOnN2Zz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxkZWZzCiAgICAgaWQ9ImRlZnM0IiAvPjxnCiAgICAgaWQ9IlBBR0VTIj48Y2lyY2xlCiAgICAgICBzdHlsZT0iZmlsbDojZ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1MjcsOTcuMTIyOTk0IDI1MC41MzY2NCw5Ny4xMjI5OTQgWiIKICAgICAgIHN0eWxlPSJmaWxsOiNmZmZmZmY7c3Ryb2tlLXdpZHRoOjBweCIKICAgICAgIGlkPSJwYXRoMS0zIiAvPjwvZz48L3N2Zz4K"
        },
        "displayName": "Groq Chat Model",
        "typeVersion": 1,
        "nodeCategories": [
          {
            "id": 25,
            "name": "AI"
          },
          {
            "id": 26,
            "name": "Langchain"
          }
        ]
      }
    ],
    "categories": [
      {
        "id": 42,
        "name": "Internal Wiki"
      },
      {
        "id": 47,
        "name": "AI Chatbot"
      }
    ],
    "image": [
      {
        "id": 1161,
        "url": "https://n8niostorageaccount.blob.core.windows.net/n8nio-strapi-blobs-prod/assets/AI_Chatbot_Postgre_SQL_4a3e8eaf21.png"
      }
    ]
  }
}