Chat with PostgreSQL Database via AI Agent

Overview

This workflow enables you to interact with any PostgreSQL database using natural language. An AI agent (powered by OpenAI) translates user questions into SQL queries, executes them against your database, and returns the results in a conversational chat interface. It is ideal for non-technical team members who need to query data without writing SQL, or for developers who want a quick, interactive way to explore their database.

How It Works

The workflow consists of a chat trigger that receives messages, an AI agent that orchestrates the conversation, an OpenAI model for language understanding, and three PostgreSQL tools that the agent can call to inspect the database schema and run queries. A memory buffer keeps the conversation context for multi-turn interactions.

Node-by-Node Breakdown

  • When chat message received (@n8n/n8n-nodes-langchain.chatTrigger) — No auth. This node creates a webhook URL that n8n’s built-in chat interface uses. When a user sends a message, it triggers the workflow. Parameters: no additional options.

  • AI Agent (@n8n/n8n-nodes-langchain.agent) — No auth. This is the brain of the workflow. It uses the OpenAI Functions agent pattern and receives a system message instructing it to act as a database assistant. It can call the three PostgreSQL tools defined below. Parameters: agent = openAiFunctionsAgent, options.systemMessage = detailed instructions.

  • OpenAI Chat Model (@n8n/n8n-nodes-langchain.lmChatOpenAi) — API Key auth (requires an OpenAI API key). This node provides the language model (gpt-4o-mini) that powers the AI agent. Parameters: model = gpt-4o-mini.

  • Chat History (@n8n/n8n-nodes-langchain.memoryBufferWindow) — No auth. Stores the last few messages (default 5) to maintain conversation context. Parameters: none.

  • Execute SQL Query (n8n-nodes-base.postgresTool) — Database credentials (PostgreSQL). This tool executes any SQL query generated by the AI agent. The query is dynamically filled using $fromAI("sql_query"). Parameters: operation = executeQuery, toolDescription = instructs the agent to append schema prefixes.

  • Get DB Schema and Tables List (n8n-nodes-base.postgresTool) — Database credentials (PostgreSQL). This tool returns a list of all tables and their schemas by querying information_schema.tables. Parameters: static query, operation = executeQuery, toolDescription = describes the output.

  • Get Table Definition (n8n-nodes-base.postgresTool) — Database credentials (PostgreSQL). This tool returns column details, types, foreign keys, etc., for a given table and schema. The parameters use $fromAI("table_name") and $fromAI("schema_name") to get the table name from the AI. Parameters: query with joins, operation = executeQuery, toolDescription = describes the output.

Setup Instructions

  1. PostgreSQL Credentials: You need a PostgreSQL database accessible from n8n. Create a database credential in n8n with the host, port, database name, username, and password. The user must have read access to information_schema and to the tables you want to query.

  2. OpenAI API Key: Obtain an API key from OpenAI. Create an OpenAI credential in n8n and paste the key.

  3. Activate the Workflow: After adding credentials, save and activate the workflow. A chat button will appear in the n8n editor. Click it to start a conversation.

  4. Make Public (Optional): The workflow can be made publicly accessible by sharing the webhook URL from the chat trigger node. Ensure your database is secure before exposing it publicly.

Use Cases & Customization

  • Analytics for non-technical users: Let business analysts ask questions like “Show me total sales by region last quarter” without writing SQL.
  • Database exploration: Quickly understand your schema by asking “What tables are in the public schema?”.
  • Custom model: Swap the OpenAI model with another provider (e.g., Anthropic, Ollama) by replacing the OpenAI Chat Model node.
  • Security: You can restrict the AI agent by limiting the tools or modifying the system prompt to only allow SELECT queries.
  • Multi-turn conversations: The memory buffer keeps context, so follow-up questions like “And for the previous month?” work seamlessly.

This workflow turns your database into a conversational assistant, saving time and lowering the barrier to data access.

11 nodesmanual triggerAI
AgentLm Chat Open AIPostgres ToolSticky NoteMemory Buffer Window

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,
// ... truncated (copy to see full JSON)

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

Telegram AI Bot with DALL-E Image Generation using LangChain

Overview This workflow creates an intelligent Telegram bot that leverages OpenAI's GPT-4o and DALL-E 3 models through n8n's LangChain integration. The bot can hold context-aware conversations (remembering the last 10 messages per user) and generate images on demand—all via simple Telegram messages. It's ideal for building personal assistants, creative bots, or customer support agents that need visual output. Node-by-Node Walkthrough Here's every node in the workflow, along with its authentication method and key configuration: Listen for incoming events (Telegram Trigger — No auth; bot token set in node credential) – Listens for all types of Telegram updates (messages, commands, etc.). No authentication parameters are required directly on the node; the Telegram bot token is configured via the node's credential settings. AI Agent (LangChain Agent — No auth; relies on connected sub‑nodes) – The core of the workflow. It receives the incoming message text and uses the attached language model (OpenAI Chat Model), memory (Window Buffer Memory), and tools (Send back an image / Generate image in Dalle) to decide what action to take. OpenAI Chat Model (LangChain Chat Model — API Key auth via credential) – Uses with a temperature of 0.7 and frequency penalty of 0.2. This model powers the agent's text responses. Window Buffer Memory (LangChain Memory — No auth) – Stores the last 10 messages per user (keyed by Telegram chat ID) to maintain conversational context. Generate image in Dalle (LangChain HTTP Request Tool — API Key auth via credential) – A custom tool that sends a POST request to with model and a prompt (provided by the AI agent). The tool description tells the agent to call it when the user asks to draw something. Send back an image (Telegram Tool — API Key auth via Telegram credential) – Sends a file (image URL from the DALL-E response) to the user's chat ID using the operation. This is exposed as a tool the AI agent can call. Send final reply (Telegram Node — API Key auth via Telegram credential) – Sends the AI agent's text output (from ) back to the user. Note: On error, the workflow continues to the error output (useful for debugging). Detailed Flow The Telegram Trigger catches any incoming message from your bot. The message text is passed to the AI Agent. The agent uses the OpenAI Chat Model to understand the request and generate a response. It also checks the Window Buffer Memory for recent conversation history. If the user asks for an image, the agent calls the Generate image in Dalle tool, which returns an image URL. The agent then uses the Send back an image tool to send that image to the user. For all other requests, the agent produces a text response, which is sent via the Send final reply node. Setup Instructions Telegram Bot – Create a bot via @BotFather and get the API token. In n8n, create a Telegram credential and paste the token. OpenAI Account – Obtain an API key from OpenAI's platform. Create an credential in n8n and paste the key. This credential is used by both the Chat Model and the DALL-E tool. Workflow Activation – After configuring the credentials, activate the workflow. n8n will automatically set up the webhook for the Telegram trigger (no manual URL needed—n8n handles it internally). Test – Send a message to your bot on Telegram. Try asking a question or say “Draw a cat wearing a hat” to trigger image generation. Use Cases & Variations Personal Assistant – Extend with additional tools (web search, calendar lookup, weather API) to make a full‑fledged chatbot. Customer Support – Replace the OpenAI model with a fine‑tuned model or add a fallback to a human agent using n8n's error handling. Image Editor – Modify the DALL-E tool to accept style parameters or multiple images. Multi‑Language – Add a translation node before the AI agent to support multiple languages. Logging – Insert a database node (e.g., Google Sheets, PostgreSQL) to store conversation logs for analysis.

8 nodes

Convert Text to Speech Using OpenAI TTS API

Overview This workflow converts any text into natural-sounding speech using OpenAI's Text-to-Speech (TTS) API. It is ideal for generating audio content for accessibility, voiceovers, podcasts, or language learning. The workflow is triggered manually for testing, but can easily be adapted to run on a schedule, via webhook, or as part of a larger automation. Node-by-Node Breakdown When clicking "Test workflow" (Manual Trigger) — No auth. This node starts the workflow when you click the "Execute Workflow" button in the n8n editor. It has no parameters and is used for testing. Set input text and TTS voice (Set) — No auth. This node defines the text to be converted and the voice to use. It outputs a JSON object with two fields: - : The text you want to turn into speech (e.g., "The quick brown fox jumped over the lazy dog.") - : The voice model to use (e.g., "alloy"). Other options include "echo", "fable", "onyx", "nova", and "shimmer". Send HTTP Request to OpenAI's TTS Endpoint (HTTP Request) — API Key auth (via OpenAI credential). This node sends a POST request to with the following body parameters: - : (the TTS model) - : The text from the previous node (using expression ) - : The voice from the previous node (using expression ) The request is authenticated using an OpenAI API key stored in an n8n credential. The response is a binary MP3 audio file. Setup Instructions OpenAI Account: You need an OpenAI account with API access. Obtain an API key from the OpenAI dashboard. n8n Credential: In n8n, create a new credential of type "OpenAI". Paste your API key into the credential. Configure the HTTP Request Node: The node is already set to use the OpenAI credential. Ensure the credential is selected in the node's settings. Customize Text and Voice: Modify the and values in the Set node as needed. The maximum input length is 4,000 tokens. Use Cases and Variations Automated Podcast Generation: Replace the manual trigger with a Schedule Trigger to generate daily audio summaries from a news feed. Accessibility: Use a Webhook Trigger to accept text from a form or chat, then return the audio file to the user. Language Learning: Combine with a Translate node to convert foreign language text into speech. Content Creation: Integrate with a Google Drive node to save the generated MP3 files automatically. Voice Customization: Experiment with different voice options (alloy, echo, fable, etc.) to match the tone of your content.

8 nodes

Telegram RAG Chatbot with File Upload and Groq LLM

This workflow creates a Telegram chatbot that uses Retrieval-Augmented Generation (RAG) to answer questions based on documents you upload. Users can send PDF or CSV files to a Telegram chat, and the workflow processes them into a vector database. When a user then sends a text message, the AI agent retrieves relevant chunks from the stored documents and generates an answer using the Groq Llama 3.1 model. It's like having a personal assistant that learns from your files and responds via Telegram. Node-by-Node Walkthrough Telegram Message Trigger (Telegram Trigger, no authentication required on the node itself — authentication is handled via the Telegram Bot API credentials configured in the n8n credentials store). This trigger listens for all types of updates (messages, commands, etc.) from a Telegram bot. When a new update arrives, it starts the workflow. Get a chat1 (Telegram node, Telegram Bot API token auth). It extracts the from the incoming message and passes it to the next node, ensuring the AI agent knows which chat to reply to. AI Agent1 (LangChain Agent, no auth). This is the core of the workflow. It uses a system message that instructs the AI to answer only from the knowledge base. The agent has access to the Groq Chat Model as its language model and the Retrieve documents tool to fetch relevant document chunks. It also uses Simple Memory to keep conversation context within a session (keyed by the Telegram chat ID). Groq Chat Model (Groq LLM, Groq API key auth). Uses the model. This provides fast, coherent answers. Simple Memory (Memory Buffer Window, no auth). Stores the last few turns of conversation to give the agent context. The session key is set to the Telegram chat ID from the trigger. Retrieve documents (Vector Store as Tool, no auth). This tool allows the agent to query the in-memory vector store. It returns the top 10 most similar document chunks. Embeddings HuggingFace Inference1 (Hugging Face Inference, Hugging Face API key auth). Generates embeddings for the user's query so the vector store can find relevant documents. Upload your file here (Form Trigger, no auth). This form trigger provides a web form where users can upload or files. The uploaded file(s) are passed to the Default Data Loader1. Default Data Loader1 (Document Default Data Loader, no auth). Converts the uploaded binary file into a LangChain document object. Recursive Character Text Splitter (Text Splitter, no auth). Splits the document into chunks of up to 3,000 characters with 200 character overlap. This ensures the vector store indexes manageable pieces. Simple Vector Store (In-Memory Vector Store, no auth). Stores the document chunks along with their embeddings. The embedding model used is Embeddings HuggingFace Inference. Embeddings HuggingFace Inference (Hugging Face Inference, Hugging Face API key auth). Generates embeddings for each document chunk before storing them. Reply in Telegram1 (Telegram node, Telegram Bot API token auth). Sends the AI agent's output back to the same Telegram chat. Setup Instructions Telegram Bot: Create a bot via @BotFather and get its API token. In n8n, add a Telegram credential using this token. Groq: Sign up at GroqCloud to get an API key. Add a Groq credential in n8n. Hugging Face: Create a free account at Hugging Face and generate an Inference API token. Add a Hugging Face Inference credential in n8n. n8n Form Trigger: This node is built-in. Ensure your n8n instance is publicly accessible (or use a tunnel like ngrok) so the form can be accessed by users. Deploy: Activate the workflow. Share the Telegram bot username with users. They can upload files by visiting the form URL (the one generated by the Upload your file here node) and then send text messages to the bot. Use Cases and Variations Personal knowledge base: Upload company policies, technical documentation, or study materials and ask questions about them via Telegram. Customer support bot: Replace the file upload with an HTTP node that fetches FAQs from a database, and use the same RAG architecture to answer customer queries. Multi-user support: The session memory is already scoped by Telegram chat ID, so multiple users can use the bot simultaneously without interfering. Switch LLM: Replace Groq with OpenAI, Anthropic, or any other supported LLM provider by changing the model node. Persistent vector store: Swap the in-memory vector store for Pinecone, Weaviate, or Qdrant to retain documents across restarts.

15 nodes

Ready to automate with n8n?

Get affordable managed n8n hosting with 24/7 support.