Deep Agents
AgentOrchestratorRetrievalText2SQLToolbox

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/text2sql

Basic Setup

Text2SQL requires four components:

  1. Adapter - Connects to your database (PostgreSQL, SQLite, or SQL Server)
  2. Grounding - Configures database introspection (see Grounding for advanced options)
  3. Version - A string used to manage cache invalidation (bump when schema changes)
  4. 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 10

Chat 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:

  1. Runs grounding - Introspects your database schema (tables, columns, relationships, indexes, constraints)
  2. Applies teachables - Injects domain knowledge (terms, hints, guardrails, examples) into the prompt
  3. Assembles context - Builds the agent prompt with schema + teachables + step-back reasoning examples
  4. Generates & validates SQL - Drafts SQL, validates syntax with validate_query tool
  5. 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-key

Next Steps