Tailwinds - The UI for AI
  • Welcome to Tailwinds
    • Chatflows
      • LangChain
        • Agents
          • Airtable Agent
          • AutoGPT
          • BabyAGI
          • CSV Agent
          • Conversational Agent
          • OpenAI Assistant
            • Threads
          • ReAct Agent Chat
          • ReAct Agent LLM
          • Tool Agent
          • XML Agent
        • Cache
          • InMemory Cache
          • InMemory Embedding Cache
          • Momento Cache
          • Redis Cache
          • Redis Embeddings Cache
          • Upstash Redis Cache
        • Chains
          • GET API Chain
          • OpenAPI Chain
          • POST API Chain
          • Conversation Chain
          • Conversational Retrieval QA Chain
          • LLM Chain
          • Multi Prompt Chain
          • Multi Retrieval QA Chain
          • Retrieval QA Chain
          • Sql Database Chain
          • Vectara QA Chain
          • VectorDB QA Chain
        • Chat Models
          • AWS ChatBedrock
          • Azure ChatOpenAI
          • NIBittensorChat
          • ChatAnthropic
          • ChatCohere
          • Chat Fireworks
          • ChatGoogleGenerativeAI
          • ChatGooglePaLM
          • Google VertexAI
          • ChatHuggingFace
          • ChatMistralAI
          • ChatOllama
          • ChatOllama Funtion
          • ChatOpenAI
          • ChatOpenAI Custom
          • ChatTogetherAI
          • GroqChat
        • Document Loaders
          • API Loader
          • Airtable
          • Apify Website Content Crawler
          • Cheerio Web Scraper
          • Confluence
          • Csv File
          • Custom Document Loader
          • Document Store
          • Docx File
          • Figma
          • FireCrawl
          • Folder with Files
          • GitBook
          • Github
          • Json File
          • Json Lines File
          • Notion Database
          • Notion Folder
          • Notion Page
          • PDF Files
          • Plain Text
          • Playwright Web Scraper
          • Puppeteer Web Scraper
          • AWS S3 File Loader
          • SearchApi For Web Search
          • SerpApi For Web Search
          • Spider Web Scraper/Crawler
          • Text File
          • Unstructured File Loader
          • Unstructured Folder Loader
          • VectorStore To Document
        • Embeddings
          • AWS Bedrock Embeddings
          • Azure OpenAI Embeddings
          • Cohere Embeddings
          • Google GenerativeAI Embeddings
          • Google PaLM Embeddings
          • Google VertexAI Embeddings
          • HuggingFace Inference Embeddings
          • MistralAI Embeddings
          • Ollama Embeddings
          • OpenAI Embeddings
          • OpenAI Embeddings Custom
          • TogetherAI Embedding
          • VoyageAI Embeddings
        • LLMs
          • AWS Bedrock
          • Azure OpenAI
          • NIBittensorLLM
          • Cohere
          • GooglePaLM
          • GoogleVertex AI
          • HuggingFace Inference
          • Ollama
          • OpenAI
          • Replicate
        • Memory
          • Buffer Memory
          • Buffer Window Memory
          • Conversation Summary Memory
          • Conversation Summary Buffer Memory
          • DynamoDB Chat Memory
          • MongoDB Atlas Chat Memory
          • Redis-Backed Chat Memory
          • Upstash Redis-Backed Chat Memory
        • Moderation
          • OpenAI Moderation
          • Simple Prompt Moderation
        • Output Parsers
          • CSV Output Parser
          • Custom List Output Parser
          • Structured Output Parser
          • Advanced Structured Output Parser
        • Prompts
          • Chat Prompt Template
          • Few Shot Prompt Template
          • Prompt Template
        • Record Managers
        • Retrievers
          • Cohere Rerank Retriever
          • Embeddings Filter Retriever
          • HyDE Retriever
          • LLM Filter Retriever
          • Multi Query Retriever
          • Prompt Retriever
          • Reciprocal Rank Fusion Retriever
          • Similarity Score Threshold Retriever
          • Vector Store Retriever
          • Voyage AI Rerank Retriever
        • Text Splitters
          • Character Text Splitter
          • Code Text Splitter
          • Html-To-Markdown Text Splitter
          • Markdown Text Splitter
          • Recursive Character Text Splitter
          • Token Text Splitter
        • Tools
          • BraveSearch API
          • Calculator
          • Chain Tool
          • Chatflow Tool
          • Custom Tool
          • Exa Search
          • Google Custom Search
          • OpenAPI Toolkit
          • Python Interpreter
          • Read File
          • Request Get
          • Request Post
          • Retriever Tool
          • SearchApi
          • SearXNG
          • Serp API
          • Serper
          • Web Browser
          • Write File
        • Vector Stores
          • AstraDB
          • Chroma
          • Elastic
          • Faiss
          • In-Memory Vector Store
          • Milvus
          • MongoDB Atlas
          • OpenSearch
          • Pinecone
          • Postgres
          • Qdrant
          • Redis
          • SingleStore
          • Supabase
          • Upstash Vector
          • Vectara
          • Weaviate
          • Zep Collection - Open Source
          • Zep Collection - Cloud
      • LlamaIndex
        • Agents
          • OpenAI Tool Agent
          • Anthropic Tool Agent
        • Chat Models
          • AzureChatOpenAI
          • ChatAnthropic
          • ChatMistral
          • ChatOllama
          • ChatOpenAI
          • ChatTogetherAI
          • ChatGroq
        • Embeddings
          • Azure OpenAI Embeddings
          • OpenAI Embedding
        • Engine
          • Query Engine
          • Simple Chat Engine
          • Context Chat Engine
          • Sub-Question Query Engine
        • Response Synthesizer
          • Refine
          • Compact And Refine
          • Simple Response Builder
          • Tree Summarize
        • Tools
          • Query Engine Tool
        • Vector Stores
          • Pinecone
          • SimpleStore
    • Agentflows
      • Multi-Agents (Supervisor/Worker)
      • Sequential Agents
    • API
      • Chatflows and APIs
    • Document Stores
    • Embed
      • Rate Limit
    • API Streaming
    • Analytics
    • Credentials
      • Amazon Bedrock Credential Setup
      • IBM Watsonx.AI Credential Setup
    • Variables
    • Utilities
      • Custom JS Function
      • Set/Get Variable
      • If Else
      • Sticky Note
    • Example Flows
      • Calling Children Flows
      • Calling Webhook
      • Interacting with API
      • Multiple Documents QnA
      • SQL QnA
      • Upserting Data
      • Web Scrape QnA
    • Monitoring & Auditing
      • Configuring Monitoring and Traces
    • Tailwinds Security and Deployment
  • Release Notes
    • 12/17/2024 - v2.2.1
    • 10/11/2024 - v2.1.2
    • 9/27/2024- v2.1
    • 8/16/2024 - v2.0.5
  • Demos and Use-cases
    • Create a Basic Chatbot
    • Build an AI-Powered Translator
    • Create research-powered call scripts
    • Extract information from Medical Documents
    • Identify ICD10 medical codes
  • GenAI University
    • Syllabus
    • 101-Prompt Engineering
    • 101-System Prompts
    • 101-Human (User) Prompts
    • 101-Context Window
    • 101-Prompt Chains
    • 201-Documents and Vector Databases (RAG)
    • 301-AI Agents
    • 301-Agent Tools
    • 401-Multi-Agent
Powered by GitBook
On this page
  • TL;DR
  • 1. SQL Database Schema + Example Rows
  • 2. Return a SQL query with few shot prompting
  • 3. Validate the SQL query using If Else node
  • 4. Custom function to execute SQL query, and get the response
  • 5. Return a natural response from the executed SQL response
  • Query
  • Conclusion

Was this helpful?

  1. Welcome to Tailwinds
  2. Example Flows

SQL QnA

Learn how to query structured data

PreviousMultiple Documents QnANextUpserting Data

Last updated 9 months ago

Was this helpful?


Unlike previous examples like and , querying structured data does not require a vector database. At the high-level, this can be achieved with following steps:

  1. Providing the LLM:

    • overview of the SQL database schema

    • example rows data

  2. Return a SQL query with few shot prompting

  3. Validate the SQL query using an node

  4. Create a custom function to execute the SQL query, and get the response

  5. Return a natural response from the executed SQL response

In this example, we are going to create a QnA chatbot that can interact with a SQL database stored in SingleStore

TL;DR

You can find the chatflow template:

1. SQL Database Schema + Example Rows

Use a Custom JS Function node to connect to SingleStore, retrieve database schema and top 3 rows.

CREATE TABLE samples (firstName varchar NOT NULL, lastName varchar)
SELECT * FROM samples LIMIT 3
firstName lastName
Stephen Tyler
Jack McGinnis
Steven Repici
Full Javascript Code
const HOST = 'singlestore-host.com';
const USER = 'admin';
const PASSWORD = 'mypassword';
const DATABASE = 'mydb';
const TABLE = 'samples';
const mysql = require('mysql2/promise');

let sqlSchemaPrompt;

function getSQLPrompt() {
  return new Promise(async (resolve, reject) => {
    try {
      const singleStoreConnection = mysql.createPool({
        host: HOST,
        user: USER,
        password: PASSWORD,
        database: DATABASE,
      });
  
      // Get schema info
      const [schemaInfo] = await singleStoreConnection.execute(
        `SELECT * FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = "${TABLE}"`
      );
  
      const createColumns = [];
      const columnNames = [];
  
      for (const schemaData of schemaInfo) {
        columnNames.push(`${schemaData['COLUMN_NAME']}`);
        createColumns.push(`${schemaData['COLUMN_NAME']} ${schemaData['COLUMN_TYPE']} ${schemaData['IS_NULLABLE'] === 'NO' ? 'NOT NULL' : ''}`);
      }
  
      const sqlCreateTableQuery = `CREATE TABLE samples (${createColumns.join(', ')})`;
      const sqlSelectTableQuery = `SELECT * FROM samples LIMIT 3`;
  
      // Get first 3 rows
      const [rows] = await singleStoreConnection.execute(
          sqlSelectTableQuery,
      );
      
      const allValues = [];
      for (const row of rows) {
          const rowValues = [];
          for (const colName in row) {
              rowValues.push(row[colName]);
          }
          allValues.push(rowValues.join(' '));
      }
  
      sqlSchemaPrompt = sqlCreateTableQuery + '\n' + sqlSelectTableQuery + '\n' + columnNames.join(' ') + '\n' + allValues.join('\n');
      
      resolve();
    } catch (e) {
      console.error(e);
      return reject(e);
    }
  });
}

async function main() {
    await getSQLPrompt();
}

await main();

return sqlSchemaPrompt;

We can now see the correct format has been generated. Next step is to bring this into Prompt Template.

2. Return a SQL query with few shot prompting

Create a new Chat Model + Prompt Template + LLMChain

Specify the following prompt in the Prompt Template:

Based on the provided SQL table schema and question below, return a SQL SELECT ALL query that would answer the user's question. For example: SELECT * FROM table WHERE id = '1'.
------------
SCHEMA: {schema}
------------
QUESTION: {question}
------------
SQL QUERY:

Since we are using 2 variables: {schema} and {question}, specify their values in Format Prompt Values:

Sometimes the SQL query is invalid, and we do not want to waste resources the execute an invalid SQL query. For example, if a user is asking a general question that is irrelevant to the SQL database. We can use an If Else node to route to different path.

For instance, we can perform a basic check to see if SELECT and WHERE are included in the SQL query given by the LLM.

const sqlQuery = $sqlQuery.trim();

if (sqlQuery.includes("SELECT") && sqlQuery.includes("WHERE")) {
    return sqlQuery;
}
return $sqlQuery;

In the Else Function, we will route to a Prompt Template + LLMChain that basically tells LLM that it is unable to answer user query:

4. Custom function to execute SQL query, and get the response

If it is a valid SQL query, we need to execute the query. Connect the True output from If Else node to a Custom JS Function node:

Full Javascript Code
const HOST = 'singlestore-host.com';
const USER = 'admin';
const PASSWORD = 'mypassword';
const DATABASE = 'mydb';
const TABLE = 'samples';
const mysql = require('mysql2/promise');

let result;

function getSQLResult() {
  return new Promise(async (resolve, reject) => {
    try {
      const singleStoreConnection = mysql.createPool({
        host: HOST,
        user: USER,
        password: PASSWORD,
        database: DATABASE,
      });
     
      const [rows] = await singleStoreConnection.execute(
        $sqlQuery
      );
  
      result = JSON.stringify(rows)
      
      resolve();
    } catch (e) {
      console.error(e);
      return reject(e);
    }
  });
}

async function main() {
    await getSQLResult();
}

await main();

return result;

5. Return a natural response from the executed SQL response

Create a new Chat Model + Prompt Template + LLMChain

Write the following prompt in the Prompt Template:

Based on the question, and SQL response, write a natural language response, be details as possible:
------------
QUESTION: {question}
------------
SQL RESPONSE: {sqlResponse}
------------
NATURAL LANGUAGE RESPONSE:

Specify the variables in Format Prompt Values:

Voila! Your SQL chatbot is now ready for testing!

Query

First, let's ask something related to the database.

Looking at the logs, we can see the first LLMChain is able to give us a SQL query:

Input:

Based on the provided SQL table schema and question below, return a SQL SELECT ALL query that would answer the user's question. For example: SELECT * FROM table WHERE id = '1'.\n------------\nSCHEMA: CREATE TABLE samples (id bigint(20) NOT NULL, firstName varchar(300) NOT NULL, lastName varchar(300) NOT NULL, userAddress varchar(300) NOT NULL, userState varchar(300) NOT NULL, userCode varchar(300) NOT NULL, userPostal varchar(300) NOT NULL, createdate timestamp(6) NOT NULL)\nSELECT * FROM samples LIMIT 3\nid firstName lastName userAddress userState userCode userPostal createdate\n1125899906842627 Steven Repici 14 Kingston St. Oregon NJ 5578 Thu Dec 14 2023 13:06:17 GMT+0800 (Singapore Standard Time)\n1125899906842625 John Doe 120 jefferson st. Riverside NJ 8075 Thu Dec 14 2023 13:04:32 GMT+0800 (Singapore Standard Time)\n1125899906842629 Bert Jet 9th, at Terrace plc Desert City CO 8576 Thu Dec 14 2023 13:07:11 GMT+0800 (Singapore Standard Time)\n------------\nQUESTION: what is the address of John\n------------\nSQL QUERY:

Output

SELECT userAddress FROM samples WHERE firstName = 'John'

After executing the SQL query, the result is passed to the 2nd LLMChain:

Input

Based on the question, and SQL response, write a natural language response, be details as possible:\n------------\nQUESTION: what is the address of John\n------------\nSQL RESPONSE: [{\"userAddress\":\"120 jefferson st.\"}]\n------------\nNATURAL LANGUAGE RESPONSE:

Output

The address of John is 120 Jefferson St.

Now, we if ask something that is irrelevant to the SQL database, the Else route is taken.

For first LLMChain, a SQL query is generated as below:

SELECT * FROM samples LIMIT 3

However, it fails the If Else check because it doesn't contains both SELECT and WHERE, hence entering the Else route that has a prompt that says:

Politely say "I'm not able to answer query"

And the final output is:

I apologize, but I'm not able to answer your query at the moment.

Conclusion

In this example, we have successfully created a SQL chatbot that can interact with your database, and is also able to handle questions that are irrelevant to database. Further improvement includes adding memory to provide conversation history.

You can find the chatflow below:

From the , it is recommended to generate a prompt with following example format:

You can find more on how to get the HOST, USER, PASSWORD from this . Once finished, click Execute:

You can provide more examples to the prompt (i.e few-shot prompting) to let the LLM learns better. Or take reference from

3. Validate the SQL query using node

research paper
guide
dialect-specific prompting
If Else
Web Scrape QnA
Multiple Documents QnA
If Else
54KB
SQL Chatflow.json
54KB
SQL Chatflow.json