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
Automate chat queries with n8n and PostgreSQL

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

Learn how to Build this Workflow with AI:

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.

Automate chat queries with n8n and PostgreSQL

Visit through Desktop to Interact with the Workflow.

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 Twist Channel Creation and Messaging with n8n

This workflow automates creating and updating a channel in Twist and sending a personalized message to specific users. It eliminates manual setup errors and saves time managing Twist communications.

Automate Ideogram Image Generation with Google Sheets & Gmail

This workflow automates graphic design image generation via Ideogram AI, storing image data in Google Sheets and Google Drive, with email alerts via Gmail. It saves designers hours by automating image creation, remixing, review, and record-keeping.

Automate IT Support with Slack and OpenAI in n8n

Streamline IT support by automating Slack message handling using n8n and OpenAI. This workflow handles Slack DMs, filters bots, queries a Confluence knowledge base, and delivers AI-generated responses, improving support efficiency and response time.

Automate Crypto Analysis with CoinMarketCap & n8n AI Agent

Discover how this unique n8n workflow leverages CoinMarketCap’s multi-agent AI to deliver precise, real-time cryptocurrency insights directly via Telegram. Manage crypto data analysis efficiently with automated multi-source API integration.

Automate Gumroad to Beehiiv Subscriber Sync with n8n

Learn how to automatically add new Gumroad sales customers as Beehiiv newsletter subscribers using n8n automation. This workflow saves time by syncing sales data to Google Sheets CRM and notifying your Telegram channel instantly.

Generate On-Brand Blog Articles Using n8n and OpenAI

This workflow automates the creation of on-brand blog articles by analyzing existing company content using n8n and OpenAI. It extracts article structures and brand voice to produce consistent draft articles, saving significant content creation time.
1:1 Free Strategy Session
Your competitors are already automating. Are you still paying for it manually?

Do you want to adopt AI Automation?

Every hour your team does repetitive work, you're burning real money.
While you wait, faster businesses are cutting costs and moving quicker.
AI and automations aren't the future anymore — they're the present.

Book a live 1-on-1 session where we show you exactly which of your daily tasks can be automated — and what it’s costing you not to.