Multi-AI Agent Chatbot for SQL Queries & QuickChart Visualization with n8n

Discover how this unique n8n workflow automates interactive AI-driven SQL database queries and dynamic chart generation with QuickChart. Eliminate manual database probing and chart creation, saving hours while enhancing data insights.
agent
toolWorkflow
postgresTool
+8
Workflow Identifier: 1318
NODES in Use: chatTrigger, postgresTool, toolWorkflow, executeWorkflowTrigger, agent, switch, httpRequest, outputParserStructured, lmChatOpenAi, memoryPostgresChat, set

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

Learn how to Build this Workflow with AI:

Visit through Desktop for Best experience

1. Opening Problem Statement

Imagine Sarah, a real estate analyst juggling multiple client presentations weekly. Sarah’s challenge is daunting: each time she needs to answer complex questions about her property database stored in Postgres, she manually crafts SQL queries and then separately uses charting tools to visualize data for client reports. This process wastes hours, introduces errors in query syntax, and delays insights—sometimes costing her lucrative opportunities.

This exact scenario calls for a smart, automated approach that merges conversational AI with direct database querying and instant chart creation. Rather than toggling between apps, Sarah wants to ask natural language questions and get precise data answers along with visual charts—all in one streamlined flow.

2. What This Automation Does

This n8n workflow offers a Multi-AI Agent Chatbot interface integrating Postgres database queries and QuickChart charting for visual insights. When users send a chat message to the system, here’s what happens:

  • AI interprets the user’s question and decides whether to query the database or generate a chart.
  • SQL queries are automatically generated by an AI agent, executed against the Postgres database, fetching relevant data.
  • Data responses can be converted into charts with another AI agent crafting Chart.js configurations for QuickChart.
  • Dynamic chart URLs are created and returned so users get instant visual data representation.
  • Multi-agent coordination ensures queries and chart generation are separately handled but seamlessly integrated.
  • Chat memory stored in Postgres keeps track of discussions to enhance future interactions with context.

Overall, this workflow eradicates repetitive manual SQL coding and separate chart building, saving hours weekly and reducing errors, enabling decision-makers to focus on insights, not tooling hassles.

3. Prerequisites ⚙️

  • n8n account with access to community nodes and workflow editor
  • Postgres-compatible database (e.g., Supabase) with access credentials 🔑
  • OpenAI API key for AI agents to generate queries and charts 🔐
  • QuickChart API accessible via HTTP request 🔌

4. Step-by-Step Guide

Step 1: Set Up Postgres Database Credentials in n8n

Navigate to Settings → Credentials → Postgres. Add your database credentials here. For example, host, database name, user, and password. Do a test connection to confirm.

You’ll see a green success message if connected.

Common mistake: Double-check user permissions to allow SELECT queries; otherwise, queries will fail.

Step 2: Add OpenAI Credentials

Go to Settings → Credentials → OpenAI and enter your API key. This allows n8n to connect to the GPT-4o-mini model used in this workflow.

Step 3: Understand the Trigger Node “When chat message received”

This node acts as an entry point to the workflow. It listens for incoming chat messages from users via a LangChain chat interface. The user’s text is captured here for AI processing.

Step 4: Explore the Primary AI Manager Agent Node

Named “🤖Primary Agent,” this LangChain Agent node interprets user instructions and decides which tool (database query or chart generation) to route the request to. Its system message defines two tools it can use: “query_database_tool” and “generate_chart_tool.”

Step 5: Configure the Tool Agent Router Node

This switch node routes based on a “route” string value returned from AI logic. When the route is “query_database_tool,” the workflow passes control to the Secondary Postgres Agent that generates and executes SQL queries. When the route is “generate_chart_tool,” it hands off to the Secondary QuickChart Agent to create charts.

Step 6: Secondary Postgres Agent and Execute SQL Query Nodes

The “🤖Secondary Postgres Agent” generates the SQL query based on AI-generated text and sends it to “Execute SQL Query” node, which actually runs it against the Postgres DB. Results are then passed along for further processing.

SQL Query example: SELECT * FROM properties WHERE city = 'Austin';

Step 7: Secondary QuickChart Agent and Chart Creation Nodes

The “🤖Secondary QuickChart Agent” receives database records and the original user prompt, then generates a Chart.js JSON configuration using LangChain’s output parser with a provided schema example. This config is set in “QuickChart GET URL” node that forms the QuickChart API URL and sends HTTP requests in “Create QuickChart” node.

Step 8: Store Chat History in Postgres Memory Node

The “Postgres Chat Memory” node records conversation history in a specified table. This enables context-aware responses on subsequent user requests.

Step 9: Test the Workflow

Trigger the webhook URL from the “When chat message received” node. Send a sample chat such as “Show me a bar chart of list prices for all properties.” The workflow will respond with query results and a chart URL.

5. Customizations ✏️

Customize the AI model

In the “gpt-4o-mini” nodes, switch to a more powerful OpenAI model like “gpt-4” by changing the model value. This may improve language understanding.

Adjust chart types and appearance

Modify the JSON schema in “QuickChart Object Schema” node to change chart type from “bar” to “line,” add colors, or tweak axes.

Add new database tools

Create additional LangChain tool workflows if you want to support other database operations like INSERT or UPDATE.

Enable Slack or email notification

Post-process the chat output node to integrate with Slack or Gmail nodes for alerting and reporting.

6. Troubleshooting 🔧

Problem: SQL query returns error or empty results

Cause: Database permissions or incorrect table/column names.

Solution: Validate your SQL statement in a database client first. Use the “DB Schema and Tables” and “Table Definitions” nodes here to verify schema and columns.

Problem: QuickChart responses do not render charts correctly

Cause: Chart JSON schema is malformed or incomplete.

Solution: Use the “QuickChart Object Schema” node example JSON as a strict template. Test JSON using QuickChart.io playground before deploying.

7. Pre-Production Checklist ✅

  • Verify Postgres credentials and test query execution
  • Confirm OpenAI API connection
  • Test webhook with sample chat input
  • Review chart JSON schema conformity with QuickChart standards
  • Backup Postgres chat memory table regularly if needed

8. Deployment Guide

Activate the workflow by setting it to active in n8n editor. Ensure your webhook URL is secured and accessible to your chat clients.

Monitor workflow executions and errors via n8n execution logs. Use Postgres chat memory for future tuning of prompts or context.

9. FAQs

Can I substitute Postgres with another SQL database?

Yes, but you need to ensure compatibility with the Postgres SQL tool node or adapt queries accordingly.

Does this consume OpenAI API credits?

Yes, because it uses GPT-4o-mini model for query and chart generation. Optimize prompts to reduce call frequency.

Is the user data stored securely?

Yes, all chat history and data reside securely in your Postgres database under your control.

Can this handle large data volumes?

It is suitable for moderate datasets typical of real-time chat scenarios. Large queries may require tuning or pagination.

10. Conclusion

By building this Multi-AI Agent Chatbot workflow in n8n, you have automated natural language querying of your Postgres database along with dynamic chart creation via QuickChart. This eliminates hours spent manually crafting SQL and creating charts separately, streamlining reporting and data exploration.

Sarah, our real estate analyst, now chats to her database and receives both precise data and custom charts instantly—saving time, reducing errors, and boosting client engagement.

Next, consider expanding this workflow to handle multi-database environments, integrate additional visualization libraries, or automate report emailing based on chat interactions.

Keep experimenting and refining your AI agent chatbot setup for smarter, faster data insights!

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 in n8n

A complete beginner guide to building an AI-powered 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