Skip to content

Embedding SQLGuardLLM in a library

Install the core package with pip install --pre sqlguardllm. Create a guard from an application-owned policy and use it at the database execution boundary.

from sqlguardllm import Guard, Policy

guard = Guard(Policy(dialect="postgres", tables={"invoices"}, max_rows=100))

def execute_generated_sql(connection, generated_sql, trusted_context):
    approved_sql = guard.enforce(generated_sql, context=trusted_context)
    with connection.cursor() as cursor:
        cursor.execute(approved_sql)
        return cursor.fetchall()

Use a read-only database identity and supply context from the authenticated application session. If validation rejects the query or raises an error, let that stop execution. Never fall back to executing the original query. Configure column and row rules explicitly when the application needs them.

Use Guard.check() and its CheckResult when the integration needs structured policy decisions and violation codes. The current release is alpha. Pin the version in an integration test and check the published dependency constraints before sharing a Python environment with another SQLGlot consumer.