Getting Started
Install Text2SQL and run your first natural language query
This guide walks you through installing Text2SQL and running your first natural language to SQL query.
Installation
npm install @deepagents/text2sqlBasic Setup
Text2SQL requires four components:
- Adapter - Connects to your database (PostgreSQL, SQLite, or SQL Server)
- Grounding - Configures database introspection (see Grounding for advanced options)
- Version - A string used to manage cache invalidation (bump when schema changes)
- History - Stores conversation history (optional for single queries)
import { DatabaseSync } from 'node:sqlite';
import { InMemoryHistory, Text2Sql } from '@deepagents/text2sql';
import { Sqlite } from '@deepagents/text2sql/sqlite';
import * as sqlite from '@deepagents/text2sql/sqlite';
// Connect to your database
const db = new DatabaseSync('./your-database.db', { readOnly: true });
// Create the Text2SQL instance
const text2sql = new Text2Sql({
version: 'v1', // Bump this when your schema changes
adapter: new Sqlite({
execute: (sql) => db.prepare(sql).all(),
grounding: [sqlite.tables(), sqlite.info()],
}),
history: new InMemoryHistory(),
});import pg from 'pg';
import { InMemoryHistory, Text2Sql } from '@deepagents/text2sql';
import { Postgres } from '@deepagents/text2sql/postgres';
import * as postgres from '@deepagents/text2sql/postgres';
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
});
const text2sql = new Text2Sql({
version: 'v1', // Bump this when your schema changes
adapter: new Postgres({
execute: async (sql) => {
const result = await pool.query(sql);
return result.rows;
},
grounding: [postgres.tables(), postgres.info()],
}),
history: new InMemoryHistory(),
});import sql from 'mssql';
import { InMemoryHistory, Text2Sql } from '@deepagents/text2sql';
import { SqlServer } from '@deepagents/text2sql/sqlserver';
import * as sqlserver from '@deepagents/text2sql/sqlserver';
const pool = await sql.connect({
server: process.env.DB_HOST,
database: process.env.DB_NAME,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
options: { encrypt: true, trustServerCertificate: true },
});
const text2sql = new Text2Sql({
version: 'v1', // Bump this when your schema changes
adapter: new SqlServer({
execute: async (query) => {
const result = await pool.request().query(query);
return result.recordset;
},
grounding: [sqlserver.tables(), sqlserver.info()],
}),
history: new InMemoryHistory(),
});Your First Query
Generate SQL Only
Use toSql() to generate SQL without executing it:
const sql = await text2sql.toSql(
'Show me the top 10 customers by total purchases',
);
console.log(sql);
// SELECT c.CustomerId, c.FirstName, c.LastName, SUM(i.Total) as TotalPurchases
// FROM Customer c
// JOIN Invoice i ON c.CustomerId = i.CustomerId
// GROUP BY c.CustomerId
// ORDER BY TotalPurchases DESC
// LIMIT 10Chat with Streaming
Use chat() for streaming responses with conversation history:
const stream = await text2sql.chat(
[{ role: 'user', content: 'What are the most popular genres?' }],
{ chatId: 'chat-123', userId: 'user-456' },
);
for await (const chunk of stream) {
if (chunk.type === 'text-delta') {
process.stdout.write(chunk.textDelta);
}
}Understanding the Response
When Text2SQL processes a query, it:
- Runs grounding - Introspects your database schema (tables, columns, relationships, indexes, constraints)
- Applies teachables - Injects domain knowledge (terms, hints, guardrails, examples) into the prompt
- Assembles context - Builds the agent prompt with schema + teachables + step-back reasoning examples
- Generates & validates SQL - Drafts SQL, validates syntax with
validate_querytool - Returns results -
toSql()returns the SQL string;chat()streams the response with explanation
Text2SQL includes default teachables that enforce best practices like read-only queries, row limits, and proper validation workflows.
Environment Variables
Text2SQL uses Groq for AI inference. Set your API key:
export GROQ_API_KEY=your-api-keyNext Steps
- Grounding - Configure database introspection for richer context
- PostgreSQL Adapter - PostgreSQL-specific features
- SQLite Adapter - SQLite-specific features
- SQL Server Adapter - SQL Server-specific features
- Generate SQL - Deep dive into SQL generation
- Teach the System - Add domain knowledge