Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions .github/workflows/llamaindex-package.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
name: llama-index-tools-sqlguardllm

on:
pull_request:
paths:
- "clients/llamaindex/**"
- ".github/workflows/llamaindex-package.yml"
workflow_dispatch:
schedule:
- cron: "0 6 * * 1"

permissions:
contents: read

jobs:
package:
name: Build, test and lint
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5
with:
python-version: "3.12"
- name: Build
run: uv build clients/llamaindex --out-dir dist
- name: Smoke-test wheel with runtime dependencies only
run: |
wheel=$(find dist -maxdepth 1 -name 'llama_index_tools_sqlguardllm-*.whl')
test -n "$wheel"
uv run --isolated --no-project --with "./$wheel" python -c 'import llama_index.tools.sqlguardllm'
- name: Tests
run: >
uv run --with "./clients/llamaindex[test]" --with pytest
pytest clients/llamaindex/tests -q
- name: Lint
run: uvx ruff check clients/llamaindex
71 changes: 71 additions & 0 deletions .github/workflows/publish-llamaindex.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
name: Publish llama-index-tools-sqlguardllm

# Publishes the llama-index-tools-sqlguardllm package (clients/llamaindex) to PyPI with Trusted Publishing
# (OIDC): no token is stored. It is separate from release.yml on purpose: this package has its own
# version and release cadence. Run it by hand from main with the exact version.
#
# One-time setup, on PyPI (https://pypi.org/manage/account/publishing/), a pending publisher:
# project llama-index-tools-sqlguardllm
# owner jmmana repository sqlguardllm
# workflow publish-llamaindex.yml environment pypi-llamaindex
# and create the environment `pypi-llamaindex` in the repository settings.
on:
workflow_dispatch:
inputs:
version:
description: Exact version of clients/llamaindex on main (for example 0.1.0a1)
required: true
type: string

permissions:
contents: read

concurrency:
group: publish-llamaindex
cancel-in-progress: false

jobs:
build:
name: Build and verify
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
- uses: astral-sh/setup-uv@d4b2f3b6ecc6e67c4457f6d3e41ec42d3d0fcb86 # v5
- name: The requested version is the one in the package
env:
REQUESTED_VERSION: ${{ inputs.version }}
run: |
actual=$(grep -m1 '^version = ' clients/llamaindex/pyproject.toml | cut -d'"' -f2)
if [ "$actual" != "$REQUESTED_VERSION" ]; then
echo "clients/llamaindex is $actual, not $REQUESTED_VERSION" >&2
exit 1
fi
- name: Tests against the current LlamaIndex
run: uv run --with "./clients/llamaindex[test]" --with pytest pytest clients/llamaindex/tests -q
- run: uv build clients/llamaindex --out-dir dist
- name: Smoke-test wheel with runtime dependencies only
run: |
wheel=$(find dist -maxdepth 1 -name 'llama_index_tools_sqlguardllm-*.whl')
test -n "$wheel"
uv run --isolated --no-project --with "./$wheel" python -c 'import llama_index.tools.sqlguardllm'
- uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
with:
name: dist
path: dist/

pypi:
name: Publish to PyPI
needs: build
runs-on: ubuntu-latest
environment:
name: pypi-llamaindex
url: https://pypi.org/project/llama-index-tools-sqlguardllm/
permissions:
id-token: write
steps:
- uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4
with:
name: dist
path: dist/
- uses: pypa/gh-action-pypi-publish@7245906fb61fa33a13554f9d5fb856fe61758086 # release/v1
51 changes: 51 additions & 0 deletions clients/llamaindex/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# llama-index-tools-sqlguardllm

A guarded SQL database and tool spec for LlamaIndex, built on
[sqlguardllm](https://github.com/jmmana/sqlguardllm), a deterministic SQL firewall: the model
writes SQL, sqlguardllm checks and rewrites it against your policy, and only then does it run.

**Status: alpha.**

```bash
pip install --pre llama-index-tools-sqlguardllm
```

## Quick start

```python
from llama_index.core.query_engine import NLSQLTableQueryEngine
from llama_index.tools.sqlguardllm import GuardedSQLDatabase, SQLGuardToolSpec
from sqlalchemy import create_engine
from sqlguardllm import Guard, Policy

policy = Policy(
dialect="sqlite",
tables={"customers", "invoices"},
hidden_columns={"customers.email"},
row_filters={"invoices": "branch_id IN ({user.branches})"},
max_rows=100,
)
db = GuardedSQLDatabase(
create_engine("sqlite:///sales.db"), # a read-only user in production
guard=Guard(policy),
context_fn=lambda: {"user": {"branches": [1, 2]}}, # from the session, never the model
)
engine = NLSQLTableQueryEngine(sql_database=db, tables=sorted(policy.tables), llm=llm)
tools = SQLGuardToolSpec(db).to_tool_list() # run_sql, list_tables, describe_table for agents
```

`GuardedSQLDatabase` is a drop-in for `NLSQLTableQueryEngine` and
`SQLTableRetrieverQueryEngine`. A refused query raises `QueryRefused` (a `GuardViolation`) whose
message lists the violation codes, for example
`Query refused: [hidden_column] customers.email is a hidden column`; the engines answer with it
and the tool spec returns it as `Error: ...` so the model can rewrite the query.

## Safety notes

- Hidden columns never appear in `describe_table` or in the schema shown to the model; only
tables in the policy are exposed.
- `sample_rows_in_table_info` must be `0` and `schema=` is not supported (both act outside the
guard); use the policy's `default_schema`.
- Keep the layers under the guard: a **read-only database user** and a statement timeout.

More at https://github.com/jmmana/sqlguardllm.
53 changes: 53 additions & 0 deletions clients/llamaindex/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[project]
name = "llama-index-tools-sqlguardllm"
version = "0.1.0a1"
description = "LlamaIndex SQLDatabase and tool spec that only run SQL made safe by sqlguardllm."
readme = "README.md"
license = "Apache-2.0"
requires-python = ">=3.10"
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: Database",
"Topic :: Security",
"Typing :: Typed",
]
dependencies = [
"sqlguardllm>=0.5.0a8",
"llama-index-core>=0.14,<0.15",
"sqlalchemy>=2.0,<3",
]

[project.optional-dependencies]
test = ["pytest>=8"]

[project.urls]
Homepage = "https://github.com/jmmana/sqlguardllm"
Repository = "https://github.com/jmmana/sqlguardllm"
Issues = "https://github.com/jmmana/sqlguardllm/issues"

[tool.hatch.build.targets.wheel]
packages = ["src/llama_index"]

[tool.ruff]
line-length = 100

[tool.mypy]
strict = true
python_version = "3.10"
mypy_path = "src"
namespace_packages = true
explicit_package_bases = true

[tool.pytest.ini_options]
testpaths = ["tests"]
11 changes: 11 additions & 0 deletions clients/llamaindex/src/llama_index/tools/sqlguardllm/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
"""LlamaIndex integrations for sqlguardllm: a guarded SQLDatabase and a tool spec."""

from llama_index.tools.sqlguardllm.base import (
GuardedSQLDatabase,
QueryRefused,
SQLGuardToolSpec,
)

__version__ = "0.1.0a1"

__all__ = ["GuardedSQLDatabase", "QueryRefused", "SQLGuardToolSpec", "__version__"]
116 changes: 116 additions & 0 deletions clients/llamaindex/src/llama_index/tools/sqlguardllm/base.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
"""A LlamaIndex ``SQLDatabase`` and tool spec that only run SQL sqlguardllm made safe."""

from __future__ import annotations

from collections.abc import Callable, Mapping
from typing import Any

from llama_index.core import SQLDatabase
from llama_index.core.tools.tool_spec.base import BaseToolSpec

from sqlguardllm import Guard, GuardViolation, Policy, Violation


class QueryRefused(GuardViolation):
"""A query the guard rejected; the message carries the violation codes and reasons."""

def __init__(self, violations: tuple[Violation, ...]) -> None:
super().__init__(violations)
detail = "; ".join(f"[{v.code.value}] {v.message}" for v in violations)
self.args = (f"Query refused: {detail}",)

def __str__(self) -> str:
return str(self.args[0])


def _hidden(policy: Policy, table: str) -> set[str]:
prefix = f"{table.lower()}."
return {
c.lower()[len(prefix) :]
for c in policy.hidden_columns or ()
if c.lower().startswith(prefix)
}


class GuardedSQLDatabase(SQLDatabase):
"""A ``SQLDatabase`` whose ``run_sql`` only executes SQL rewritten by sqlguardllm.

Drop-in for ``NLSQLTableQueryEngine`` and ``SQLTableRetrieverQueryEngine``. A rejected
query raises ``QueryRefused`` (a ``GuardViolation``); the engines turn it into an
``"Error: ..."`` answer. The context comes from ``context_fn``, supplied by the
application, never by the model. Hidden columns are left out of the schema text.

``sample_rows_in_table_info`` must be 0 and ``schema=`` is not supported: sample rows are
read outside ``run_sql``, and ``schema`` makes LlamaIndex edit SQL after it was checked.
Use the policy's ``default_schema`` instead.
"""

def __init__(
self,
engine: Any,
*,
guard: Guard,
context_fn: Callable[[], Mapping[str, Any]],
**kwargs: Any,
) -> None:
if kwargs.get("schema"):
raise ValueError("GuardedSQLDatabase does not support schema=; use default_schema")
if kwargs.get("sample_rows_in_table_info", 0) != 0:
raise ValueError("GuardedSQLDatabase requires sample_rows_in_table_info=0")
kwargs["sample_rows_in_table_info"] = 0
if not kwargs.get("include_tables") and not kwargs.get("ignore_tables"):
kwargs["include_tables"] = sorted(guard.policy.tables or ()) or None
super().__init__(engine, **kwargs)
self.guard = guard
self.context_fn = context_fn

def run_sql(self, command: str) -> tuple[str, dict[str, Any]]:
result = self.guard.check(command, self.context_fn())
if not result.ok or result.sql is None:
raise QueryRefused(tuple(result.violations))
return super().run_sql(result.sql)

def insert_into_table(self, table_name: str, data: dict[str, Any]) -> None:
"""Refused: ``SQLDatabase`` would write without going through the guard."""
raise PermissionError(
"GuardedSQLDatabase is read-only: insert_into_table bypasses the guard"
)

def get_table_columns(self, table_name: str) -> list[Any]:
hidden = _hidden(self.guard.policy, table_name)
return [c for c in super().get_table_columns(table_name) if c["name"].lower() not in hidden]

def get_single_table_info(self, table_name: str) -> str:
cols = [f"{c['name']} ({c['type']!s})" for c in self.get_table_columns(table_name)]
return f"Table '{table_name}' has columns: {', '.join(cols)}."


class SQLGuardToolSpec(BaseToolSpec):
"""Agent tools ``run_sql``, ``list_tables`` and ``describe_table`` behind a guard."""

spec_functions: list[str | tuple[str, str]] = ["run_sql", "list_tables", "describe_table"] # noqa: RUF012

def __init__(self, database: GuardedSQLDatabase) -> None:
self.database = database

def run_sql(self, query: str) -> str:
"""Run one read-only SQL query on the allowed tables and return the rows.

If the query is refused, the answer says why: rewrite it and try again.
"""
try:
return self.database.run_sql(query)[0]
except QueryRefused as exc:
return f"Error: {exc}"
except Exception: # noqa: BLE001 - the model must never see driver internals
return "Error: the query could not be executed."

def list_tables(self) -> str:
"""List the tables you may query."""
return ", ".join(sorted(self.database.get_usable_table_names()))

def describe_table(self, table_name: str) -> str:
"""Describe the visible columns of one allowed table."""
if table_name not in set(self.database.get_usable_table_names()):
return f"Error: unknown table {table_name!r}. Use list_tables."
return self.database.get_single_table_info(table_name)
Empty file.
Loading
Loading