Automate Chat-Based Queries with PostgreSQL and n8n LangChain

Learn how to build a chat automation that interacts with your PostgreSQL database using n8n and LangChain. Streamline querying with natural language, reducing time spent on manual SQL queries and ensuring accurate database insights.
chatTrigger
agent
lmChatOpenAi
+2
Workflow Identifier: 1745
NODES in Use: chatTrigger, agent, lmChatOpenAi, postgresTool, memoryBufferWindow

Press CTRL+F5 if the workflow didn't load.

Learn how to Build this Workflow with AI:

Visit through Desktop for Best experience

What This Automation Does ⚙️

This workflow helps users ask questions in plain English about a PostgreSQL database.
It fixes the slow and hard job of writing SQL queries by hand.
When users send a chat message, it turns the question into a database query automatically.
The system then runs that query and gives back easy answers.
This saves a lot of time and lowers mistakes in data answers.

The chat trigger starts when a new message comes in.
An AI Agent with OpenAI and LangChain looks at the question.
It learns from the database layout fetched live.
The AI runs the right SQL on the PostgreSQL database.
Chat history remembers past talks for smooth chat replies.
Finally, the OpenAI Chat Model makes the answers sound natural.


Tools and Services Used

  • n8n: Automation platform where the workflow runs.
  • PostgreSQL Database: Stores the data and schema.
  • OpenAI: Provides AI models for language processing and SQL creation.
  • LangChain AI Agent: Converts natural language to SQL and controls database queries.
  • PostgreSQL metadata tables: Source of database schema and structure details.

Beginner Step-by-Step: How to Use This Workflow in n8n

Import the Workflow

  1. Download the workflow file using the “Download” button on this page.
  2. Open the n8n editor where you work.
  3. Go to “Import from File” and select the downloaded workflow.

Configure Credentials

  1. Add your PostgreSQL Database credentials by going to Settings – Credentials – Create New – PostgreSQL.
  2. Save them with a clear name like “Your Postgresql Database Credentials”.
  3. Add OpenAI API key credentials in the same way, naming them “Your OpenAI Account Credentials”.

Update Workflow Parameters

  1. Check if the workflow needs any specific IDs, emails, tables, or channel names updated.
  2. Make sure the SQL queries or schema names in the nodes reflect your actual database.

Test the Workflow

  1. Send a test chat message to trigger the workflow.
  2. Watch the execution results in n8n’s run history to confirm it works properly.

Activate for Production

  1. Turn on the workflow with the activation switch.
  2. Use the webhook URL from the Webhook node to connect your chat interface or website.

Workflow Inputs, Processing, and Outputs

Inputs

  • User sends a question in natural language through chat.
  • Database connection info to access PostgreSQL.
  • OpenAI API key to use GPT-4o-mini model.

Processing Steps

  • The When chat message received node captures the question.
  • The AI Agent node reads the message.
  • It fetches the current PostgreSQL database schema using the Get DB Schema and Tables List node.
  • It retrieves full table definitions dynamically with the Get Table Definition node.
  • The AI generates an SQL query using schema info.
  • The Execute SQL Query node runs the AI’s SQL against PostgreSQL.
  • The Chat History node stores past dialogues to keep context.
  • The OpenAI Chat Model node creates clear, conversational answers.

Output

  • The user receives an accurate, readable answer to their database question through chat.

Customizations ✏️

  • Change the AI model in the OpenAI Chat Model node if needed for cost or speed.
  • Adjust how many past messages the Chat History node keeps to control memory.
  • Edit the system message text in the AI Agent to focus on specific topics.
  • Modify SQL queries in PostgreSQL nodes to add filters or join tables for richer answers.
  • Publish the workflow’s trigger webhook URL for real-time chat on websites or apps.
  • For self hosting n8n, visit self-host n8n for resources.

Troubleshooting 🔧

  • Connection refused or timeout errors in PostgreSQL nodes
    Check database host, port, user, and network firewall settings.
  • AI generates wrong or strange SQL
    Make sure the database schema info is current by running the Get DB Schema and Tables List node manually.
  • OpenAI authentication failures
    Recheck API key and permissions in OpenAI dashboard and update credentials.

Pre-Production Checklist ✅

  • Verify PostgreSQL and OpenAI credentials work in test runs.
  • Test the When chat message received node with sample questions.
  • Make sure metadata nodes return up-to-date schema info.
  • Run test queries generated by AI for correct SQL syntax.
  • Confirm final chat replies are clear and correct.

Deployment Guide

Enable the workflow by switching it on inside n8n.
Use the provided webhook URL in chat apps or websites to deliver questions.
Keep an eye on workflow runs for errors or delays.
Update keys and schema details often to stay accurate.


Summary

→ A chat system that answers questions about your PostgreSQL data.

→ By turning words into SQL automatically, it saves time.

✓ Works by reading your database layout live to make exact queries.

✓ Changes complex data access into easy conversation.

✓ Keeps chat context so replies feel natural and connected.

Frequently Asked Questions

No. The workflow uses PostgreSQL-specific SQL to get schema details and needs changes to work with MySQL.
Yes. Every call to the OpenAI GPT model consumes API credits based on the chosen plan.
It is secure because credentials are managed inside n8n and all data flows use secure connections.
Adjust the “Context Window Length” setting in the Chat History node to keep more or fewer past messages.

Promoted by BULDRR AI

Related Workflows

Automate Viral UGC Video Creation Using n8n + Degaus (Beginner-Friendly Guide)

Learn how to automate viral UGC video creation using n8n, AI prompts, and Degaus. This beginner-friendly guide shows how to import, configure, and run the workflow without technical complexity.
Form Trigger
Google Sheets
Gmail
+37
Free

AI SEO Blog Writer Automation Workflows in n8n

A complete beginner guide to building an AI SEO blog writer automation using n8n.
AI Agent
Google Sheets
httpRequest
+5
Free

Automate CrowdStrike Alerts with VirusTotal, Jira & Slack

This workflow automates processing of CrowdStrike detections by enriching threat data via VirusTotal, creating Jira tickets for incident tracking, and notifying teams on Slack for quick response. Save hours daily by transforming complex threat data into actionable alerts effortlessly.
scheduleTrigger
httpRequest
jira
+5
Free

Automate Telegram Invoices to Notion with AI Summaries & Reports

Save hours on financial tracking by automating invoice extraction from Telegram photos to Notion using Google Gemini AI. This workflow extracts data, records transactions, and generates detailed spending reports with charts sent on schedule via Telegram.
lmChatGoogleGemini
telegramTrigger
notion
+9
Free

Automate Email Replies with n8n and AI-Powered Summarization

Save hours managing your inbox with this n8n workflow that uses IMAP email triggers, AI summarization, and vector search to draft concise replies requiring minimal review. Automate business email processing efficiently with AI guidance and Gmail integration.
emailReadImap
vectorStoreQdrant
emailSend
+12
Free

Automate Email Campaigns Using n8n with Gmail & Google Sheets

This n8n workflow automates personalized email outreach campaigns by integrating Gmail and Google Sheets, saving hours of manual follow-up work and reducing errors in email sequences. It ensures timely follow-ups based on previous email interactions, optimizing communication efficiency.
googleSheets
gmail
code
+5
Free