Explain Queries
Get plain English explanations of SQL queries
Text2SQL does not currently expose a public text2sql.explain() helper. Use one
of the supported patterns below when you need plain English explanations of SQL.
Option 1: Use chat() for Execution + Explanation
Build the chat agent with primitives from @deepagents/context, wired to
Text2SQL's instructions() and indexed schema fragments:
import { agent, chat, user } from '@deepagents/context';
import { instructions } from '@deepagents/text2sql';
const indexResult = await sandbox.sandbox.executeCommand('sql index');
if (indexResult.exitCode !== 0) throw new Error(indexResult.stderr);
const manifest = JSON.parse(indexResult.stdout) as { fragmentsPath: string };
const fragments = JSON.parse(await sandbox.sandbox.readFile(manifest.fragmentsPath));
context.set(...instructions(), ...fragments);
const ai = agent({ name: 'sql-assistant', sandbox, model, context });
await context.continue(
user('Show revenue by month and explain the result in plain English.'),
);
const stream = await chat(ai);
for await (const chunk of stream) {
// render
}Use this when you want one turn to validate SQL, run it, and explain the result.
Option 2: Explain Saved SQL with Your Own Agent
If you already have SQL text and only need an explanation, build a small
explainer agent with @deepagents/context:
import { groq } from '@ai-sdk/groq';
import {
ContextEngine,
InMemoryContextStore,
agent,
role,
user,
} from '@deepagents/context';
const context = new ContextEngine({
store: new InMemoryContextStore(),
chatId: 'sql-explainer',
userId: 'system',
}).set(
role(
'Explain SQL queries in plain English. Focus on what the query answers, not SQL syntax.',
),
);
context.set(
user(`
Explain this SQL:
SELECT c.name, SUM(o.total_amount) AS revenue
FROM customers c
JOIN orders o ON c.id = o.customer_id
GROUP BY c.id, c.name
ORDER BY revenue DESC
LIMIT 10
`),
);
await context.save();
const explainer = agent({
name: 'sql-explainer',
model: groq('openai/gpt-oss-20b'),
context,
});
const result = await explainer.generate({});
console.log(result.text);When to Use Each Pattern
| Need | Recommended approach |
|---|---|
| Explain a live query result to the end user | chat() helper with a Text2SQL-configured agent |
| Explain saved SQL in an audit screen or admin tool | Custom explainer agent |
| Review generated SQL before execution | text2sql.toSql() plus your own explainer step |
Good Explanation Style
Aim for explanations that are:
- Intent-focused: what the query answers
- Business-friendly: use domain terms the reader already knows
- Concrete: mention filters, grouping, ranking, and time windows when they matter
- Short: one or two paragraphs are usually enough