@deepagents/text2sql
v0.6.0
Published
AI-powered natural language to SQL. Ask questions in plain English, get executable queries.
Readme
@deepagents/text2sql
AI-powered natural language to SQL. Ask questions in plain English, get executable queries.
Features
- Natural Language to SQL - Convert questions to validated, executable queries
- Multi-Database Support - PostgreSQL, SQLite, and SQL Server adapters
- Schema-Aware - Automatic introspection of tables, relationships, indexes, and constraints
- Domain Knowledge - Teach business terms, guardrails, and query patterns via teachables
- Conversational - Multi-turn conversations with history and user memory
- Explainable - Convert SQL back to plain English explanations
- Safe by Default - Read-only queries, validation, and configurable guardrails
Installation
npm install @deepagents/text2sqlRequires Node.js LTS (20+).
Quick Start
import pg from 'pg';
import { InMemoryHistory, Text2Sql } from '@deepagents/text2sql';
import {
Postgres,
constraints,
indexes,
info,
lowCardinality,
tables,
views,
} from '@deepagents/text2sql/postgres';
const pool = new pg.Pool({
connectionString: process.env.DATABASE_URL,
});
const text2sql = new Text2Sql({
version: 'v1',
adapter: new Postgres({
execute: async (sql) => {
const result = await pool.query(sql);
return result.rows;
},
grounding: [
tables(),
views(),
info(),
indexes(),
constraints(),
lowCardinality(),
],
}),
history: new InMemoryHistory(),
});
// Generate SQL
const sql = await text2sql.toSql('Show me the top 10 customers by revenue');
console.log(sql);AI Model Providers
Text2SQL works with any model provider supported by the Vercel AI SDK, including OpenAI, Anthropic, Google, Groq, and more.
Teachables
Inject domain knowledge to improve query accuracy:
import {
example,
guardrail,
hint,
term,
} from '@deepagents/text2sql/instructions';
text2sql.instruct(
term('MRR', 'monthly recurring revenue'),
hint('Always exclude test accounts with email ending in @test.com'),
guardrail({
rule: 'Never expose individual salaries',
reason: 'Confidential HR data',
action: 'Aggregate by department instead',
}),
example({
question: 'show me churned customers',
answer: `SELECT * FROM customers WHERE status = 'churned' ORDER BY churned_at DESC`,
}),
);10 teachable types available: term, hint, guardrail, example, explain, clarification, workflow, quirk, styleGuide, analogy.
Grounding
Control what schema metadata the AI receives:
| Function | Description |
| ------------------ | ---------------------------------------------- |
| tables() | Tables, columns, and primary keys |
| views() | Database views |
| info() | Database version and info |
| indexes() | Index information for performance hints |
| constraints() | Foreign keys and other constraints |
| rowCount() | Table sizes (tiny, small, medium, large, huge) |
| columnStats() | Min/max/null distribution for columns |
| lowCardinality() | Enum-like columns with distinct values |
Conversations
Build multi-turn conversations with context:
const chatId = 'chat-123';
const userId = 'user-456';
const stream = await text2sql.chat(
[{ role: 'user', content: 'Show me orders from last month' }],
{ chatId, userId },
);
for await (const chunk of stream) {
// handle streaming response
}
// Continue the conversation with the same chatId
const followUp = await text2sql.chat(
[{ role: 'user', content: 'Now filter to only completed ones' }],
{ chatId, userId },
);Explain Queries
Convert SQL to plain English:
const explanation = await text2sql.explain(`
SELECT department, AVG(salary)
FROM employees
GROUP BY department
`);
// "This query calculates the average salary for each department..."Documentation
Full documentation available at januarylabs.github.io/deepagents:
