Animated data flow diagram

AI SQL Query Agent with Memory (n8n + OpenAI + LangChain)

Version: 1.0.0 | Last Updated: 2025-05-16

Integrates with:

OpenAI LangChain SQLite

Overview

Unlock Conversational Database Insights with this AI Agent

This n8n workflow transforms how you interact with your SQLite databases. It acts as an intelligent AI Agent, enabling you to query data, understand database schemas, and perform data analysis using simple English. Powered by LangChain's SQL Agent capabilities and OpenAI's GPT-4-turbo model, the agent translates your natural language questions into SQL queries, executes them against the connected database, and provides you with clear, understandable answers. It even remembers the context of your conversation for more natural follow-up questions, thanks to its built-in memory.

Key Features & Benefits

  • Natural Language Database Interaction: Ask questions to your SQLite database in plain English, no SQL knowledge required for basic queries.
  • AI-Powered SQL Generation: Leverages OpenAI (gpt-4-turbo) and LangChain to intelligently convert your questions into executable SQL queries.
  • Contextual Conversations: Remembers previous parts of the conversation (configurable window size) for follow-up questions and a more natural chat experience.
  • Automated Data Analysis: Get quick answers and insights from your data without manual querying or complex BI tools.
  • Sample Database Included: Comes with a setup to download and use the 'Chinook' sample database for immediate testing and understanding.
  • Flexible Integration: Easily adapt to query your own SQLite databases by changing the file path.
  • Empowerment for All: Enables non-technical users (founders, marketers) to access database insights directly, while speeding up data exploration for technical users (CTOs, developers).
  • Increased Efficiency: Reduces time spent on writing repetitive SQL queries or waiting for data reports.

Use Cases

  • For B2C E-commerce: Quickly analyze sales trends by asking 'What were the top-selling products last month?' or 'Show customer demographics for recent orders from our SQLite customer database.'
  • For B2B SaaS: Enable product managers to query user activity data stored in SQLite, e.g., 'How many users from cohort X tried the new feature Y this week?' or 'List companies with high engagement scores based on recent activity.'
  • Streamline ad-hoc reporting for marketing teams: 'What are the conversion rates for different campaigns reflected in our leads database?' directly via chat.
  • Empower founders and solopreneurs to directly interrogate their business data (inventory, sales, user feedback in SQLite) for rapid decision-making.
  • Reduce reliance on data analysts for common data queries from SQLite databases, freeing them for more complex analytical tasks.

Prerequisites

  • An n8n instance (Cloud or self-hosted) with sufficient permissions to write files to its local directory if using the example database setup.
  • OpenAI API Key with access to a suitable model (e.g., gpt-4-turbo is used in the template).
  • If using your own SQLite database, the .db file must be accessible by the n8n instance.

Setup Instructions

  1. Download the n8n workflow JSON file.
  2. Import the workflow into your n8n instance.
  3. Initial Setup - OpenAI Credentials:
    • Open the 'OpenAI Chat Model' node.
    • Select or create your OpenAI API credentials. Ensure the chosen model (e.g., gpt-4-turbo) is available for your API key.
  4. Option A: Using the Example chinook.db Database (Recommended for first-time use):
    • Locate the 'When clicking "Test workflow"' node.
    • Run this starting node (or the subsequent 'Get chinook.zip example', 'Extract zip file', 'Save chinook.db locally' nodes sequentially) by clicking its play button. This will download the chinook.db sample SQLite database and save it as ./chinook.db in your n8n instance's root directory.
    • This step only needs to be done once.
  5. Option B: Using Your Own SQLite Database:
    • Ensure your SQLite .db file is accessible by your n8n instance (e.g., uploaded to the n8n data directory or available at a known path).
    • Modify the 'Load local chinook.db' node: Update the 'File Path' parameter to point to your SQLite database file.
    • You can disable or delete the initial example database download nodes ('When clicking "Test workflow"' through 'Save chinook.db locally').
  6. Understanding the Flow:
    • The 'Chat Trigger' node provides the chat interface (accessible via webhook or n8n's chat UI).
    • 'Load local chinook.db' (or your configured DB node) loads the database file as binary data.
    • 'Combine chat input with the binary' merges your typed question with the database file for the AI Agent.
    • The 'AI Agent' node (type: LangChain SQL Agent) uses the 'OpenAI Chat Model' and 'Window Buffer Memory' to process your question against the database.
  7. Adjust Memory (Optional):
    • The 'Window Buffer Memory' node is set to remember the last 10 interactions. You can adjust the Context Window Length parameter as needed.
  8. Activate and Test:
    • Activate the workflow.
    • Open the chat interface provided by the 'Chat Trigger' node.
    • Start asking questions! For the Chinook example, try: "Describe the database tables.", "How many tracks are there?", "What are the total sales per country?", "List all albums by Iron Maiden."
    • The agent may make several internal queries to answer complex questions. The final answer is returned to you and stored in memory for context.

Tags:

AI AgentSQLOpenAILangChainData AnalysisNLPAutomationDatabaseChatbot

Want your own unique AI agent?

Talk to us - we know how to build custom AI agents for your specific needs.

Schedule a Consultation