Skip to content

Self-heal agent SQL errors

Wrap raw agent SQL in a try/catch, branch on PerSQLError.detail.kind, feed the error plus db.describeCompact() back to the LLM, and retry once. One loop recovers from typos without human intervention.

import { PerSQL, PerSQLError } from "@persql/sdk";
const persql = new PerSQL({ token: process.env.PERSQL_TOKEN! });
const db = persql.database("acme/ledger");
async function queryWithHeal(sql: string) {
try {
return await db.query(sql);
} catch (err) {
if (err instanceof PerSQLError && err.detail) {
const compact = await db.describeCompact();
const prompt = `Error: ${err.detail.kind} (${err.detail.message})\nSchema:\n${compact}\nRewrite:\n${sql}`;
const fixed = await llm.complete(prompt);
return db.query(fixed);
}
throw err;
}
}

Recovers from unknown_column, unknown_table, and type_mismatch automatically.

Guard agent writes with propose