Overview
Convert natural language to SQL queries with AI-powered understanding of your database schema
Text2SQL is a package that converts natural language questions into SQL queries. It understands your database schema, learns domain-specific terminology, and generates safe, read-only queries.
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, and SQL Server
- Teachable: Add domain knowledge through terms, hints, guardrails, and examples
- Conversation Memory: Multi-turn chat with persistent history and user profiles
- Safe by Default: Generates read-only queries with output limits
Quick Example
import { DatabaseSync } from 'node:sqlite';
import { InMemoryHistory, Text2Sql } from '@deepagents/text2sql';
import { Sqlite } from '@deepagents/text2sql/sqlite';
const db = new DatabaseSync('./chinook.db', { readOnly: true });
const text2sql = new Text2Sql({
version: 'v1', // Bump this when your schema changes
adapter: new Sqlite({
execute: (sql) => db.prepare(sql).all(),
}),
history: new InMemoryHistory(),
});
// Generate SQL from natural language
const sql = await text2sql.toSql('Show me top 10 customers by total purchases');
// 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 10Core Methods
| Method | Description |
|---|---|
toSql(input) | Generate SQL without executing |
chat(messages, params) | Multi-turn conversation with history and user profiles |
explain(sql) | Explain SQL in plain English |
instruct(...teachables) | Manually add teachables to the system |
inspect(agent) | View the full system prompt with all context |
index() | Introspect database schema (cached) |
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)
└─────────────────┘
│
▼
┌─────────────────┐
│ Teachables │ ← Domain knowledge (terms, hints, guardrails, etc.)
│ System │
└─────────────────┘
│
▼
┌─────────────────┐
│ Text2SQL Agent │ ← Step-back prompting + validation + execution
└─────────────────┘
│
├─────────────────────┐
│ │
▼ ▼
┌─────────────┐ ┌──────────────┐
│ Explainer │ │ User Profile │
│ Agent │ │ Memory │
└─────────────┘ └──────────────┘
│
▼
ResultsNext Steps
- Getting Started - Installation and first query
- Adapters - Database-specific setup
- Teach the System - Add domain knowledge