The @deepagents/text2sql package converts natural language questions into validated, executable SQL queries. It supports multiple databases, domain knowledge injection, conversational context, and is safe by default.
import { groq } from '@ai-sdk/groq';import pg from 'pg';import { InMemoryContextStore } from '@deepagents/context';import { Text2Sql } from '@deepagents/text2sql';import { Postgres, tables, constraints } from '@deepagents/text2sql/postgres';const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL,});const text2sql = new Text2Sql({ version: 'v1', model: groq('llama-3.3-70b-versatile'), adapter: new Postgres({ execute: async (sql) => { const result = await pool.query(sql); return result.rows; }, grounding: [ tables(), constraints(), indexes(), lowCardinality(), ], }), store: new InMemoryContextStore(),});// Generate SQLconst sql = await text2sql.toSql('Show me the top 10 customers by revenue');console.log(sql);// SELECT customer_name, SUM(revenue) as total_revenue// FROM customers// GROUP BY customer_name// ORDER BY total_revenue DESC// LIMIT 10
const sql = await text2sql.toSql( 'What are the top 5 products by sales?');console.log(sql);// SELECT product_name, SUM(sales) as total_sales// FROM products// GROUP BY product_name// ORDER BY total_sales DESC// LIMIT 5
const explanation = await text2sql.explain( 'SELECT * FROM users WHERE created_at > NOW() - INTERVAL \'7 days\'');console.log(explanation);// "Show all users created in the last 7 days"
const adapter = new Postgres({ execute: executeQuery, grounding: [ tables(), // Always include constraints(), // Helpful for joins lowCardinality(), // For filtering // Skip rowCount() if not needed ],});
import { term, hint, guardrail, example } from '@deepagents/context';const text2sql = new Text2Sql({ version: 'v1', model: groq('llama-3.3-70b-versatile'), adapter, store, instructions: [ // Business terms term('MRR', 'monthly recurring revenue'), term('ARR', 'annual recurring revenue'), term('churn', 'customers who cancelled subscription'), // Behavioral hints hint('Always exclude test accounts with email ending in @test.com'), hint('Use fiscal year starting in July'), // Safety guardrails guardrail({ rule: 'Never expose individual salaries', reason: 'Confidential HR data', action: 'Aggregate by department instead', }), // Examples example({ question: 'show me churned customers', answer: `SELECT * FROM customers WHERE status = 'churned' ORDER BY churned_at DESC`, note: 'Always order by churned_at for recent first', }), ],});