FlowiseAI
Español
Español
  • Introduction
  • Partes
    • Parte 1: Introducción
      • Recursos
    • Parte 2: Chains Avanzadas
      • Desafío 1: Traductor de Lenguas Antiguas
    • Parte 3: Gestión de Documentos y Memoria
      • Desafío 2: Chatbot Nikola Tesla
    • Parte 4: Despliegue y API
    • Parte 5: Introducción a Agentes
      • Desafíos
    • Parte 6: Agentes Avanzados
      • Desafíos
    • Parte 7: Multi-Agentes
      • Desafíos
    • Parte 8: AgentFlows
      • Desafíos
    • Parte 9: Agentes Secuenciales
      • Desafíos
    • Parte 10: Sequential Agents Avanzados
  • Recursos
    • Enlaces Útiles
    • Documentación Oficial
    • Ejemplos de Código
    • Mejores Prácticas
  • Documentación Oficial
    • Introduction
    • Primeros Pasos
    • Guía de Contribución
      • Building Node
    • Referencia de API
      • Assistants
      • Attachments
      • Chat Message
      • Chatflows
      • Document Store
      • Feedback
      • Leads
      • Ping
      • Prediction
      • Tools
      • Upsert History
      • Variables
      • Vector Upsert
    • Usar Flowise
      • Agentflows
        • Multi-Agents
        • Sequential Agents
          • Tutoriales en Video
      • API
      • Analytic
      • Almacenes de Documentos
      • Embed
      • Monitoring
      • Streaming
      • Telemetry
      • Subidas
      • Variables
      • Workspaces
      • Evaluaciones
    • Configuración
      • Auth
        • Nivel de App
        • Nivel de Chatflow
      • Databases
      • Deployment
        • AWS
        • Azure
        • Alibaba Cloud
        • Digital Ocean
        • Elestio
        • GCP
        • Hugging Face
        • Kubernetes using Helm
        • Railway
        • Render
        • Replit
        • RepoCloud
        • Sealos
        • Zeabur
      • Variables de Entorno
      • Rate Limit
      • Ejecutar Flowise detrás de proxy corporativo
      • SSO
    • Integraciones
      • LangChain
        • Agents
          • Airtable Agent
          • AutoGPT
          • BabyAGI
          • CSV Agent
          • Conversational Agent
          • Conversational Retrieval Agent
          • MistralAI Tool Agent
          • OpenAI Assistant
            • Threads
          • OpenAI Function Agent
          • OpenAI Tool Agent
          • 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
          • NVIDIA NIM
          • ChatAnthropic
          • ChatCohere
          • Chat Fireworks
          • ChatGoogleGenerativeAI
          • Google VertexAI
          • ChatHuggingFace
          • ChatLocalAI
          • ChatMistralAI
          • IBM Watsonx
          • ChatOllama
          • ChatOpenAI
          • ChatTogetherAI
          • GroqChat
        • Document Loaders
          • API Loader
          • Airtable
          • Apify Website Content Crawler
          • Cheerio Web Scraper
          • Confluence
          • Csv File
          • Custom Document Loader
          • Document Store
          • Docx File
          • File Loader
          • 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
          • 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 VertexAI Embeddings
          • HuggingFace Inference Embeddings
          • LocalAI Embeddings
          • MistralAI Embeddings
          • Ollama Embeddings
          • OpenAI Embeddings
          • OpenAI Embeddings Custom
          • TogetherAI Embedding
          • VoyageAI Embeddings
        • LLMs
          • AWS Bedrock
          • Azure OpenAI
          • Cohere
          • 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
          • Zep 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
          • Custom Retriever
          • 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
          • Code Interpreter by E2B
          • 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
      • LiteLLM Proxy
      • 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
      • Utilities
        • Custom JS Function
        • Set/Get Variable
        • If Else
        • Sticky Note
      • External Integrations
        • Zapier Zaps
    • Migration Guide
      • v1.3.0 Migration Guide
      • v1.4.3 Migration Guide
      • v2.1.4 Migration Guide
    • Use Cases
      • Calling Children Flows
      • Calling Webhook
      • Interacting with API
      • Multiple Documents QnA
      • SQL QnA
      • Upserting Data
      • Web Scrape QnA
  • Flowise
    • Flowise GitHub
    • Flowise Cloud
Powered by GitBook
On this page
  • TL;DR
  • 1. Esquema de Base de Datos SQL + Filas de Ejemplo
  • 2. Devolver una consulta SQL con few shot prompting
  • 3. Validar la consulta SQL usando el nodo If Else
  • 4. Función personalizada para ejecutar la consulta SQL y obtener la respuesta
  • 5. Devolver una respuesta natural de la respuesta SQL ejecutada
  • Query
  • Conclusion
Edit on GitHub
  1. Documentación Oficial
  2. Use Cases

SQL QnA

Aprende cómo consultar datos estructurados

PreviousMultiple Documents QnANextUpserting Data

Last updated 3 months ago


A diferencia de ejemplos anteriores como y , consultar datos estructurados no requiere una base de datos vectorial. A alto nivel, esto se puede lograr con los siguientes pasos:

  1. Proporcionar al LLM:

    • visión general del esquema de la base de datos SQL

    • datos de ejemplo de filas

  2. Devolver una consulta SQL con few shot prompting

  3. Validar la consulta SQL usando un nodo

  4. Crear una función personalizada para ejecutar la consulta SQL y obtener la respuesta

  5. Devolver una respuesta natural de la respuesta SQL ejecutada

En este ejemplo, vamos a crear un chatbot QnA que pueda interactuar con una base de datos SQL almacenada en SingleStore

TL;DR

Puedes encontrar la plantilla del chatflow:

1. Esquema de Base de Datos SQL + Filas de Ejemplo

Usa un nodo Custom JS Function para conectarte a SingleStore, recuperar el esquema de la base de datos y las 3 primeras filas.

CREATE TABLE samples (firstName varchar NOT NULL, lastName varchar)
SELECT * FROM samples LIMIT 3
firstName lastName
Stephen Tyler
Jack McGinnis
Steven Repici
Código Javascript Completo
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;

Ahora podemos ver que se ha generado el formato correcto. El siguiente paso es llevarlo al Prompt Template.

2. Devolver una consulta SQL con few shot prompting

Crea un nuevo Chat Model + Prompt Template + LLMChain

Especifica el siguiente prompt en el Prompt Template:

Basado en el esquema de tabla SQL proporcionado y la pregunta a continuación, devuelve una consulta SQL SELECT ALL que respondería la pregunta del usuario. Por ejemplo: SELECT * FROM table WHERE id = '1'.
------------
SCHEMA: {schema}
------------
QUESTION: {question}
------------
SQL QUERY:

Como estamos usando 2 variables: {schema} y {question}, especifica sus valores en Format Prompt Values:

A veces la consulta SQL es inválida, y no queremos desperdiciar recursos ejecutando una consulta SQL inválida. Por ejemplo, si un usuario está haciendo una pregunta general que es irrelevante para la base de datos SQL. Podemos usar un nodo If Else para enrutar a diferentes caminos.

Por ejemplo, podemos realizar una verificación básica para ver si SELECT y WHERE están incluidos en la consulta SQL dada por el LLM.

const sqlQuery = $sqlQuery.trim();

const regex = /SELECT\s.*?(?:\n|$)/gi;

// Extracting the SQL part
const matches = sqlQuery.match(regex);
const cleanSql = matches ? matches[0].trim() : "";

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

En la Else Function, enrutaremos a un Prompt Template + LLMChain que básicamente le dice al LLM que no puede responder la consulta del usuario:

4. Función personalizada para ejecutar la consulta SQL y obtener la respuesta

Si es una consulta SQL válida, necesitamos ejecutarla. Conecta la salida True del nodo If Else a un nodo Custom JS Function:

Código Javascript Completo
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. Devolver una respuesta natural de la respuesta SQL ejecutada

Crea un nuevo 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:

Según el , se recomienda generar un prompt con el siguiente formato de ejemplo:

Puedes encontrar más información sobre cómo obtener el HOST, USER, PASSWORD en esta . Una vez terminado, haz clic en Execute:

Puedes proporcionar más ejemplos al prompt (es decir, few-shot prompting) para que el LLM aprenda mejor. O toma referencia del

3. Validar la consulta SQL usando el nodo

paper de investigación
guía
dialect-specific prompting
If Else
QnA con Web Scraping
QnA con Múltiples Documentos
If Else
54KB
SQL Chatflow.json
67KB
SQL Chatflow (1).json