Chat with Postgresql Database

Empower your users to interact with your PostgreSQL database using natural language by automating the process of querying and retrieving information. This workflow connects a chat interface, triggered by a new message, to an AI Agent that leverages OpenAI's powerful language model to understand user requests. The AI Agent intelligently utilizes a suite of PostgreSQL tools, including "Get Table Definition," "Execute SQL Query," and "Get DB Schema and Tables List," to dynamically fetch database schema, generate appropriate SQL queries, and execute them against your database. Chat history is maintained using an AI memory buffer, allowing for contextual conversations. This solution is ideal for support teams needing quick data lookups, business analysts exploring data without writing SQL, or developers building interactive data dashboards. It eliminates the need for manual SQL query writing, speeds up data access, and reduces the training burden for non-technical users, saving significant time and resources while improving data accessibility.

11 nodesmanual trigger64 views0 copiesData
PostgreSQLOpenAI

Workflow JSON

{"id": "eOUewYsEzJmQixI6", "meta": {"instanceId": "77c4feba8f41570ef06dc76ece9a6ded0f0d44f7f1477a64c2d71a8508c11faa", "templateCredsSetupCompleted": true}, "name": "Chat with Postgresql Database", "tags": [], "nodes": [{"id": "6501a54f-a68c-452d-b353-d7e871ca3780", "name": "When chat message received", "type": "@n8n/n8n-nodes-langchain.chatTrigger", "position": [-300, -80], "webhookId": "cf1de04f-3e38-426c-89f0-3bdb110a5dcf", "parameters": {"options": {}}, "typeVersion": 1.1}, {"id": "cd32221b-2a36-408d-b57e-8115fcd810c9", "name": "AI Agent", "type": "@n8n/n8n-nodes-langchain.agent", "position": [0, -80], "parameters": {"agent": "openAiFunctionsAgent", "options": {"systemMessage": "You are DB assistant. You need to run queries in DB aligned with user requests.\n\nRun custom SQL query to aggregate data and response to user. Make sure every table has schema prefix to it in sql query which you can get from `Get DB Schema and Tables List` tool.\n\nFetch all data to analyse it for response if needed.\n\n## Tools\n\n- Execute SQL query - Executes any sql query generated by AI\n- Get DB Schema and Tables List - Lists all the tables in database with its schema name\n- Get Table Definition - Gets the table definition from db using table name and schema name"}}, "typeVersion": 1.7}, {"id": "8accbeeb-7eaf-4e9e-aabc-de8ab3a0459b", "name": "OpenAI Chat Model", "type": "@n8n/n8n-nodes-langchain.lmChatOpenAi", "position": [-60, 160], "parameters": {"model": {"__rl": true, "mode": "list", "value": "gpt-4o-mini"}, "options": {}}, "credentials": {"openAiApi": {"id": "", "name": "[Your openAiApi]"}}, "typeVersion": 1.2}, {"id": "11f2013f-a080-4c9e-8773-c90492e2c628", "name": "Get Table Definition", "type": "n8n-nodes-base.postgresTool", "position": [780, 140], "parameters": {"query": "select\n c.column_name,\n c.data_type,\n c.is_nullable,\n c.column_default,\n tc.constraint_type,\n ccu.table_name AS referenced_table,\n ccu.column_name AS referenced_column\nfrom\n information_schema.columns c\nLEFT join\n information_schema.key_column_usage kcu\n ON c.table_name = kcu.table_name\n AND c.column_name = kcu.column_name\nLEFT join\n information_schema.table_constraints tc\n ON kcu.constraint_name = tc.constraint_name\n AND tc.constraint_type = 'FOREIGN KEY'\nLEFT join\n information_schema.constraint_column_usage ccu\n ON tc.constraint_name = ccu.constraint_name\nwhere\n c.table_name = '{{ $fromAI(\"table_name\") }}'\n AND c.table_schema = '{{ $fromAI(\"schema_name\") }}'\norder by\n c.ordinal_position", "options": {}, "operation": "executeQuery", "descriptionType": "manual", "toolDescription": "Get table definition to find all columns and types"}, "credentials": {"postgres": {"id": "", "name": "[Your postgres]"}}, "typeVersion": 2.5}, {"id": "760bc9bc-0057-4088-b3f0-3ee37b3519df", "name": "Sticky Note", "type": "n8n-nodes-base.stickyNote", "position": [-300, -240], "parameters": {"color": 5, "width": 560, "height": 120, "content": "### \ud83d\udc68\u200d\ud83c\udfa4 Setup\n1. Add your **postgresql** and **OpenAI** credentials.\n2. Click **Chat** button and start asking questions to your database.\n3. Activate the workflow and you can make the chat publicly available."}, "typeVersion": 1}, {"id": "0df33341-c859-4a54-b6d9-a99670e8d76d", "name": "Chat History", "type": "@n8n/n8n-nodes-langchain.memoryBufferWindow", "position": [120, 160], "parameters": {}, "typeVersion": 1.3}, {"id": "4938b22e-f187-4ca0-b9f1-60835e823799", "name": "Sticky Note3", "type": "n8n-nodes-base.stickyNote", "position": [360, 300], "parameters": {"color": 7, "width": 562, "height": 156, "content": "\ud83d\udee0\ufe0f Tools Used:\n1. Execute SQL Query: Used to execute any query generated by the agent.\n2. Get DB Schema and Tables List: It returns the list of all the tables with its schema name.\n3. Get Table Definition: It returns table details like column names, foreign keys and more of a particular table in a schema."}, "typeVersion": 1}, {"id": "39780c78-4fbc-403e-a220-aa6a4b06df8c", "name": "Sticky Note1", "type": "n8n-nodes-base.stickyNote", "position": [-100, 300], "parameters": {"color": 7, "width": 162, "height": 99, "content": "\ud83d\udc46 You can exchange this with any other chat model of your choice."}, "typeVersion": 1}, {"id": "28a5692c-5003-46cb-9a09-b7867734f446", "name": "Sticky Note2", "type": "n8n-nodes-base.stickyNote", "position": [100, 300], "parameters": {"color": 7, "width": 162, "height": 159, "content": "\ud83d\udc46 You can change how many number of messages to keep using `Context Window Length` option. It's 5 by default."}, "typeVersion": 1}, {"id": "c18ced71-6330-4ba0-9c52-1bb5852b3039", "name": "Execute SQL Query", "type": "n8n-nodes-base.postgresTool", "position": [380, 140], "parameters": {"query": "{{ $fromAI(\"sql_query\", \"SQL Query\") }}", "options": {}, "operation": "executeQuery", "descriptionType": "manual", "toolDescription": "Get all the data from Postgres, make sure you append the tables with correct schema. Every table is associated with some schema in the database."}, "credentials": {"postgres": {"id": "", "name": "[Your postgres]"}}, "typeVersion": 2.5}, {"id": "557623c6-e499-48a6-a066-744f64f8b6f3", "name": "Get DB Schema and Tables List", "type": "n8n-nodes-base.postgresTool", "position": [580, 140], "parameters": {"query": "SELECT \n table_schema,\n table_name\nFROM information_schema.tables\nWHERE table_type = 'BASE TABLE'\n AND table_schema NOT IN ('pg_catalog', 'information_schema')\nORDER BY table_schema, table_name;", "options": {}, "operation": "executeQuery", "descriptionType": "manual", "toolDescription": "Get list of all tables with their schema in the database"}, "credentials": {"postgres": {"id": "", "name": "[Your postgres]"}}, "typeVersion": 2.5}], "active": false, "pinData": {}, "settings": {"executionOrder": "v1"}, "versionId": "10c7c74e-b383-4ac7-8cb2-c9a15a2818fe", "connections": {"Chat History": {"ai_memory": [[{"node": "AI Agent", "type": "ai_memory", "index": 0}]]}, "Execute SQL Query": {"ai_tool": [[{"node": "AI Agent", "type": "ai_tool", "index": 0}]]}, "OpenAI Chat Model": {"ai_languageModel": [[{"node": "AI Agent", "type": "ai_languageModel", "index": 0}]]}, "Get Table Definition": {"ai_tool": [[{"node": "AI Agent", "type": "ai_tool", "index": 0}]]}, "When chat message received": {"main": [[{"node": "AI Agent", "type": "main", "index": 0}]]}, "Get DB Schema and Tables List": {"ai_tool": [[{"node": "AI Agent", "type": "ai_tool", "index": 0}]]}}}

How to Import This Workflow

  1. 1Copy the workflow JSON above using the Copy Workflow JSON button.
  2. 2Open your n8n instance and go to Workflows.
  3. 3Click Import from JSON and paste the copied workflow.

Don't have an n8n instance? Start your free trial at n8nautomation.cloud

Related Templates

Supabase Insertion & Upsertion & Retrieval

Efficiently manage and query your data with the Supabase Insertion & Upsertion & Retrieval workflow, a powerful solution for integrating document management with intelligent data processing. This 21-node workflow, triggered manually, connects Google Drive, Supabase, and OpenAI to automate the ingestion, updating, and retrieval of information. It allows you to upload documents from Google Drive, which are then processed by a Recursive Character Text Splitter and embedded using OpenAI Embeddings for insertion or upsertion into your Supabase vector store via the Insert Documents and Update Documents nodes. When a chat message is received, the workflow leverages OpenAI's Chat Model and a Question and Answer Chain to retrieve relevant information from Supabase using the Retrieve by Query node, providing intelligent responses based on your stored documents. This workflow is ideal for businesses and individuals who need to maintain an up-to-date knowledge base, power AI-driven chatbots with proprietary information, or automate the synchronization of document content with a searchable database, significantly reducing manual data entry and improving information accessibility.

21 nodes

Chat with PDF docs using AI (quoting sources)

Chat with PDF docs using AI (quoting sources) Efficiently extract information and generate AI-powered responses directly from your Google Drive PDF documents with this powerful n8n workflow. This automation connects Google Drive, Pinecone, and OpenAI to enable intelligent querying of your document library. When you manually trigger the workflow, it first retrieves a specified PDF from Google Drive using the Download file node. The document content is then processed by the Recursive Character Text Splitter and embedded into a Pinecone vector store using the Embeddings OpenAI and Add to Pinecone vector store nodes, making it searchable. For each query, the Get top chunks matching query node retrieves the most relevant sections from Pinecone, which are then fed to the OpenAI Chat Model via the Answer the query based on chunks node. This allows the AI to provide accurate answers, complete with citations back to the original document sections, thanks to the Structured Output Parser. This workflow is ideal for researchers, legal professionals, and anyone needing to quickly find specific information within large PDF archives, saving significant time and effort in manual document review and ensuring factual accuracy in AI-generated summaries or answers.

22 nodes

Ask questions about a PDF using AI

Effortlessly transform your Google Drive PDFs into an interactive knowledge base with this powerful AI workflow. This n8n automation connects your Google Drive files, processes them with OpenAI embeddings, and stores them in a Pinecone vector database, allowing you to ask questions and receive intelligent answers directly from your document content. When a new PDF is uploaded to Google Drive, the workflow automatically extracts its text, splits it into manageable chunks using the Recursive Character Text Splitter, generates embeddings via OpenAI, and then inserts this structured data into Pinecone for efficient retrieval. Later, by clicking the 'Chat' button, you can engage in a natural language conversation with your document, powered by the OpenAI Chat Model and the Question and Answer Chain, which retrieves relevant information from Pinecone. This is ideal for researchers needing to quickly extract insights from large reports, legal professionals analyzing contracts, or businesses creating searchable knowledge bases from their documentation, saving countless hours of manual review and information searching.

16 nodes

Ready to automate with n8n?

Get affordable managed n8n hosting with 24/7 support.