Overview
Convert natural language to SQL queries with AI-powered understanding of your database schema
Text2SQL converts natural language questions into SQL queries. It understands your database schema, carries conversation state through your context store, and can stream user-facing answers grounded in validated query results.
Key Features
- Natural Language to SQL: Ask questions in plain English, get executable SQL
- Schema-Aware: Automatically analyzes your database structure, relationships, and data patterns
- Multi-Database Support: Works with PostgreSQL, SQLite, SQL Server, MySQL/MariaDB, and BigQuery
- Teachable: Add domain knowledge through context fragments or low-level
toSql({ fragments })calls - Conversation Memory: Multi-turn chat backed by your
ContextEnginestore - Safe by Default: Generates read-only queries with output limits
Quick Example
import { groq } from '@ai-sdk/groq';
import { DatabaseSync } from 'node:sqlite';
import { Text2Sql } from '@deepagents/text2sql';
import { Sqlite } from '@deepagents/text2sql/sqlite';
import * as sqlite from '@deepagents/text2sql/sqlite';
const db = new DatabaseSync('./chinook.db', { readOnly: true });
const adapter = new Sqlite({
execute: (sql) => db.prepare(sql).all(),
grounding: [sqlite.tables(), sqlite.info()],
});
const text2sql = new Text2Sql({
version: 'v1', // Bump this when your schema changes
model: groq('openai/gpt-oss-20b'),
adapters: { main: adapter },
});
// Generate SQL from natural language
const sql = await text2sql.toSql(
'Show me top 10 customers by total purchases',
'main',
);
// 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 10main is the adapter-map key. Reuse that same name in
text2sql.toSql(..., 'main') and in any sql validate <db> "..." /
sql run <db> "..." calls from a sandbox where the package CLI is installed.
Adapter names must match /^[A-Za-z_][A-Za-z0-9_]*$/. If you build adapter
maps dynamically, validate the keys up front with isValidAdapterName(name)
or validateAdapterNames(names).
Core Methods
| API | Description |
|---|---|
Text2Sql#toSql(input, adapterName) | Generate SQL without executing, routed to one adapter |
Text2Sql#toPairs(adapterName, factory) | Generate training pairs from one configured adapter |
AdapterIndexer#index({ adapterNames?, onProgress? }) | Introspect adapters and return schema fragments, with optional progress events |
createSqlCommand(text2Sql, options?: CreateSqlCommandOptions): CreateSqlCommandResult | Wrap a Text2Sql instance as a customCommands entry for just-bash (sql run, sql validate) in virtual sandboxes |
sql index [adapter ...] | Index all adapters by default (or named subset), then write schema fragments + progress artifacts |
CreateSqlCommandOptions currently exposes outputDir (default /sql).
CreateSqlCommandResult contains command (for customCommands) plus
repair(raw) to normalize quoted SQL argv before execution.
createSqlCommand(...) does not expose index; use AdapterIndexer#index(...)
or the standalone sql index CLI flow when you need schema artifacts.
To run a streaming, multi-turn agent on top of Text2Sql, build the chat
loop yourself with agent + chat from @deepagents/context. See
Build Conversations.
When to Use Text2SQL
- Building analytics dashboards with natural language queries
- Creating chatbots that answer data questions
- Enabling non-technical users to query databases
- Prototyping data exploration interfaces
Architecture
User Question
│
▼
┌─────────────────┐
│ Grounding │ ← Schema introspection (tables, columns, relationships)
└─────────────────┘
│
▼
┌─────────────────┐
│ SQL Policies │ ← Built-in SQL guidance + optional context fragments
└─────────────────┘
│
▼
┌─────────────────┐
│ Text2SQL Runtime│ ← SQL generation + validation (+ execution in `chat()`)
└─────────────────┘
│
├─────────────────────┐
│ │
▼ ▼
┌─────────────┐ ┌──────────────┐
│ SQL Output │ │ ContextStore │
│ / Stream │ │ Persistence │
└─────────────┘ └──────────────┘
│
▼
ResultsNext Steps
- Getting Started - Installation and first query
- PostgreSQL Adapter - PostgreSQL-specific setup
- MySQL / MariaDB Adapter - MySQL and MariaDB-specific setup
- BigQuery Adapter - BigQuery-specific setup
- Teach the System - Add domain knowledge