langchain-sqlguardllm 0.1.0a1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- langchain_sqlguardllm-0.1.0a1/.gitignore +29 -0
- langchain_sqlguardllm-0.1.0a1/PKG-INFO +117 -0
- langchain_sqlguardllm-0.1.0a1/README.md +85 -0
- langchain_sqlguardllm-0.1.0a1/pyproject.toml +51 -0
- langchain_sqlguardllm-0.1.0a1/src/langchain_sqlguardllm/__init__.py +23 -0
- langchain_sqlguardllm-0.1.0a1/src/langchain_sqlguardllm/community.py +48 -0
- langchain_sqlguardllm-0.1.0a1/src/langchain_sqlguardllm/py.typed +1 -0
- langchain_sqlguardllm-0.1.0a1/src/langchain_sqlguardllm/tools.py +72 -0
- langchain_sqlguardllm-0.1.0a1/tests/test_agent.py +84 -0
- langchain_sqlguardllm-0.1.0a1/tests/test_community.py +78 -0
- langchain_sqlguardllm-0.1.0a1/tests/test_tools.py +106 -0
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
.venv/
|
|
4
|
+
.pytest_cache/
|
|
5
|
+
.mypy_cache/
|
|
6
|
+
.ruff_cache/
|
|
7
|
+
.coverage
|
|
8
|
+
htmlcov/
|
|
9
|
+
dist/
|
|
10
|
+
build/
|
|
11
|
+
!clients/dotnet/build/
|
|
12
|
+
*.egg-info/
|
|
13
|
+
site/
|
|
14
|
+
.env
|
|
15
|
+
.env.*
|
|
16
|
+
.DS_Store
|
|
17
|
+
.idea/
|
|
18
|
+
.vscode/
|
|
19
|
+
.venv-research/
|
|
20
|
+
research/node_modules/
|
|
21
|
+
research/paper/*.aux
|
|
22
|
+
research/paper/*.bbl
|
|
23
|
+
research/paper/*.blg
|
|
24
|
+
research/paper/*.log
|
|
25
|
+
research/paper/*.out
|
|
26
|
+
research/paper/*.fls
|
|
27
|
+
research/paper/*.fdb_latexmk
|
|
28
|
+
docs/assets/demo-contact.*.png
|
|
29
|
+
.hypothesis/
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: langchain-sqlguardllm
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: LangChain tools and wrappers that only run SQL made safe by sqlguardllm.
|
|
5
|
+
Project-URL: Homepage, https://github.com/jmmana/sqlguardllm
|
|
6
|
+
Project-URL: Repository, https://github.com/jmmana/sqlguardllm
|
|
7
|
+
Project-URL: Issues, https://github.com/jmmana/sqlguardllm/issues
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
Classifier: Development Status :: 3 - Alpha
|
|
10
|
+
Classifier: Intended Audience :: Developers
|
|
11
|
+
Classifier: License :: OSI Approved :: Apache Software License
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
17
|
+
Classifier: Topic :: Database
|
|
18
|
+
Classifier: Topic :: Security
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.10
|
|
21
|
+
Requires-Dist: langchain-core<2,>=1.0
|
|
22
|
+
Requires-Dist: sqlguardllm>=0.5.0a8
|
|
23
|
+
Provides-Extra: agent
|
|
24
|
+
Requires-Dist: langchain<2,>=1.0; extra == 'agent'
|
|
25
|
+
Provides-Extra: community
|
|
26
|
+
Requires-Dist: langchain-community<0.5,>=0.4; extra == 'community'
|
|
27
|
+
Provides-Extra: test
|
|
28
|
+
Requires-Dist: langchain-community<0.5,>=0.4; extra == 'test'
|
|
29
|
+
Requires-Dist: langchain<2,>=1.0; extra == 'test'
|
|
30
|
+
Requires-Dist: pytest>=8; extra == 'test'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
# langchain-sqlguardllm
|
|
34
|
+
|
|
35
|
+
A guarded SQL tool for LangChain / LangGraph agents, built on
|
|
36
|
+
[sqlguardllm](https://github.com/jmmana/sqlguardllm), a deterministic SQL firewall: the model
|
|
37
|
+
writes SQL, sqlguardllm checks and rewrites it against your policy, and only then does it run.
|
|
38
|
+
|
|
39
|
+
**Status: alpha. This package is not on PyPI until the maintainer publishes it.** Install it
|
|
40
|
+
from a checkout of the repository for now:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
pip install ./clients/langchain # the tool (langchain-core)
|
|
44
|
+
pip install "./clients/langchain[agent]" # plus langchain 1.x for create_agent
|
|
45
|
+
pip install "./clients/langchain[community]" # plus langchain-community for GuardedSQLDatabase
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
## Quick start
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
import sqlite3
|
|
52
|
+
from contextlib import closing
|
|
53
|
+
|
|
54
|
+
from langchain_sqlguardllm import sql_query_tool
|
|
55
|
+
from sqlguardllm import Guard, Policy
|
|
56
|
+
|
|
57
|
+
policy = Policy(
|
|
58
|
+
dialect="sqlite",
|
|
59
|
+
tables={"customers", "invoices"},
|
|
60
|
+
hidden_columns={"customers.email"},
|
|
61
|
+
row_filters={"invoices": "branch_id IN ({user.branches})"},
|
|
62
|
+
max_rows=100,
|
|
63
|
+
)
|
|
64
|
+
guard = Guard(policy)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def execute(sql: str) -> list[tuple]:
|
|
68
|
+
with closing(sqlite3.connect("file:sales.db?mode=ro", uri=True)) as conn:
|
|
69
|
+
return conn.execute(sql).fetchall()
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
tool = sql_query_tool(guard, execute, lambda: {"user": {"branches": [1, 2]}})
|
|
73
|
+
print(tool.invoke({"query": "SELECT SUM(total) FROM invoices"}))
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
For SQLAlchemy, `sqlalchemy_executor(engine)` returns an `execute` that opens a connection
|
|
77
|
+
per call and always rolls back.
|
|
78
|
+
|
|
79
|
+
## In an agent
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
from langchain.agents import create_agent
|
|
83
|
+
|
|
84
|
+
agent = create_agent(model, [sql_query_tool(guard, execute, current_user_context)])
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
A rejected query comes back to the model as `Error: <reasons>` (for example
|
|
88
|
+
`customers.email is a hidden column`), so it can rewrite the query. Any other failure of
|
|
89
|
+
`execute` is returned as a generic error without internals.
|
|
90
|
+
|
|
91
|
+
## langchain-community variant
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from langchain_community.agent_toolkits import SQLDatabaseToolkit
|
|
95
|
+
from langchain_sqlguardllm import GuardedSQLDatabase
|
|
96
|
+
|
|
97
|
+
db = GuardedSQLDatabase.from_uri(
|
|
98
|
+
DATABASE_URL,
|
|
99
|
+
guard=guard,
|
|
100
|
+
context_fn=current_user_context,
|
|
101
|
+
include_tables=sorted(policy.tables),
|
|
102
|
+
sample_rows_in_table_info=0,
|
|
103
|
+
)
|
|
104
|
+
tools = SQLDatabaseToolkit(db=db, llm=model).get_tools()
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
langchain-community 0.4 was archived; prefer `sql_query_tool` for new code.
|
|
108
|
+
|
|
109
|
+
## Safety notes
|
|
110
|
+
|
|
111
|
+
- Keep the layers under the guard: connect with a **read-only database user** and set a
|
|
112
|
+
statement timeout.
|
|
113
|
+
- The **context comes from the authenticated session**, never from the model.
|
|
114
|
+
- **Sample rows**: `GuardedSQLDatabase` refuses `sample_rows_in_table_info` other than `0`,
|
|
115
|
+
because sample rows are read outside the guard. Don't give agents a schema tool that reads them.
|
|
116
|
+
|
|
117
|
+
More at https://github.com/jmmana/sqlguardllm.
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# langchain-sqlguardllm
|
|
2
|
+
|
|
3
|
+
A guarded SQL tool for LangChain / LangGraph agents, built on
|
|
4
|
+
[sqlguardllm](https://github.com/jmmana/sqlguardllm), a deterministic SQL firewall: the model
|
|
5
|
+
writes SQL, sqlguardllm checks and rewrites it against your policy, and only then does it run.
|
|
6
|
+
|
|
7
|
+
**Status: alpha. This package is not on PyPI until the maintainer publishes it.** Install it
|
|
8
|
+
from a checkout of the repository for now:
|
|
9
|
+
|
|
10
|
+
```bash
|
|
11
|
+
pip install ./clients/langchain # the tool (langchain-core)
|
|
12
|
+
pip install "./clients/langchain[agent]" # plus langchain 1.x for create_agent
|
|
13
|
+
pip install "./clients/langchain[community]" # plus langchain-community for GuardedSQLDatabase
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
## Quick start
|
|
17
|
+
|
|
18
|
+
```python
|
|
19
|
+
import sqlite3
|
|
20
|
+
from contextlib import closing
|
|
21
|
+
|
|
22
|
+
from langchain_sqlguardllm import sql_query_tool
|
|
23
|
+
from sqlguardllm import Guard, Policy
|
|
24
|
+
|
|
25
|
+
policy = Policy(
|
|
26
|
+
dialect="sqlite",
|
|
27
|
+
tables={"customers", "invoices"},
|
|
28
|
+
hidden_columns={"customers.email"},
|
|
29
|
+
row_filters={"invoices": "branch_id IN ({user.branches})"},
|
|
30
|
+
max_rows=100,
|
|
31
|
+
)
|
|
32
|
+
guard = Guard(policy)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def execute(sql: str) -> list[tuple]:
|
|
36
|
+
with closing(sqlite3.connect("file:sales.db?mode=ro", uri=True)) as conn:
|
|
37
|
+
return conn.execute(sql).fetchall()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
tool = sql_query_tool(guard, execute, lambda: {"user": {"branches": [1, 2]}})
|
|
41
|
+
print(tool.invoke({"query": "SELECT SUM(total) FROM invoices"}))
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
For SQLAlchemy, `sqlalchemy_executor(engine)` returns an `execute` that opens a connection
|
|
45
|
+
per call and always rolls back.
|
|
46
|
+
|
|
47
|
+
## In an agent
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
from langchain.agents import create_agent
|
|
51
|
+
|
|
52
|
+
agent = create_agent(model, [sql_query_tool(guard, execute, current_user_context)])
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
A rejected query comes back to the model as `Error: <reasons>` (for example
|
|
56
|
+
`customers.email is a hidden column`), so it can rewrite the query. Any other failure of
|
|
57
|
+
`execute` is returned as a generic error without internals.
|
|
58
|
+
|
|
59
|
+
## langchain-community variant
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
from langchain_community.agent_toolkits import SQLDatabaseToolkit
|
|
63
|
+
from langchain_sqlguardllm import GuardedSQLDatabase
|
|
64
|
+
|
|
65
|
+
db = GuardedSQLDatabase.from_uri(
|
|
66
|
+
DATABASE_URL,
|
|
67
|
+
guard=guard,
|
|
68
|
+
context_fn=current_user_context,
|
|
69
|
+
include_tables=sorted(policy.tables),
|
|
70
|
+
sample_rows_in_table_info=0,
|
|
71
|
+
)
|
|
72
|
+
tools = SQLDatabaseToolkit(db=db, llm=model).get_tools()
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
langchain-community 0.4 was archived; prefer `sql_query_tool` for new code.
|
|
76
|
+
|
|
77
|
+
## Safety notes
|
|
78
|
+
|
|
79
|
+
- Keep the layers under the guard: connect with a **read-only database user** and set a
|
|
80
|
+
statement timeout.
|
|
81
|
+
- The **context comes from the authenticated session**, never from the model.
|
|
82
|
+
- **Sample rows**: `GuardedSQLDatabase` refuses `sample_rows_in_table_info` other than `0`,
|
|
83
|
+
because sample rows are read outside the guard. Don't give agents a schema tool that reads them.
|
|
84
|
+
|
|
85
|
+
More at https://github.com/jmmana/sqlguardllm.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "langchain-sqlguardllm"
|
|
7
|
+
version = "0.1.0a1"
|
|
8
|
+
description = "LangChain tools and wrappers that only run SQL made safe by sqlguardllm."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
classifiers = [
|
|
13
|
+
"Development Status :: 3 - Alpha",
|
|
14
|
+
"Intended Audience :: Developers",
|
|
15
|
+
"License :: OSI Approved :: Apache Software License",
|
|
16
|
+
"Programming Language :: Python :: 3",
|
|
17
|
+
"Programming Language :: Python :: 3.10",
|
|
18
|
+
"Programming Language :: Python :: 3.11",
|
|
19
|
+
"Programming Language :: Python :: 3.12",
|
|
20
|
+
"Programming Language :: Python :: 3.13",
|
|
21
|
+
"Topic :: Database",
|
|
22
|
+
"Topic :: Security",
|
|
23
|
+
"Typing :: Typed",
|
|
24
|
+
]
|
|
25
|
+
dependencies = [
|
|
26
|
+
"sqlguardllm>=0.5.0a8",
|
|
27
|
+
"langchain-core>=1.0,<2",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
[project.optional-dependencies]
|
|
31
|
+
community = ["langchain-community>=0.4,<0.5"]
|
|
32
|
+
agent = ["langchain>=1.0,<2"]
|
|
33
|
+
test = [
|
|
34
|
+
"pytest>=8",
|
|
35
|
+
"langchain>=1.0,<2",
|
|
36
|
+
"langchain-community>=0.4,<0.5",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
[project.urls]
|
|
40
|
+
Homepage = "https://github.com/jmmana/sqlguardllm"
|
|
41
|
+
Repository = "https://github.com/jmmana/sqlguardllm"
|
|
42
|
+
Issues = "https://github.com/jmmana/sqlguardllm/issues"
|
|
43
|
+
|
|
44
|
+
[tool.hatch.build.targets.wheel]
|
|
45
|
+
packages = ["src/langchain_sqlguardllm"]
|
|
46
|
+
|
|
47
|
+
[tool.ruff]
|
|
48
|
+
line-length = 100
|
|
49
|
+
|
|
50
|
+
[tool.pytest.ini_options]
|
|
51
|
+
testpaths = ["tests"]
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
"""LangChain integrations for sqlguardllm: a guarded SQL tool and a guarded SQLDatabase."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import TYPE_CHECKING, Any
|
|
6
|
+
|
|
7
|
+
from langchain_sqlguardllm.tools import sql_query_tool, sqlalchemy_executor
|
|
8
|
+
|
|
9
|
+
if TYPE_CHECKING:
|
|
10
|
+
from langchain_sqlguardllm.community import GuardedSQLDatabase
|
|
11
|
+
|
|
12
|
+
__version__ = "0.1.0a1"
|
|
13
|
+
|
|
14
|
+
__all__ = ["GuardedSQLDatabase", "__version__", "sql_query_tool", "sqlalchemy_executor"]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def __getattr__(name: str) -> Any:
|
|
18
|
+
# Imported lazily so langchain-community stays an optional dependency.
|
|
19
|
+
if name == "GuardedSQLDatabase":
|
|
20
|
+
from langchain_sqlguardllm.community import GuardedSQLDatabase
|
|
21
|
+
|
|
22
|
+
return GuardedSQLDatabase
|
|
23
|
+
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""A guarded langchain-community ``SQLDatabase``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from langchain_community.utilities import SQLDatabase
|
|
9
|
+
from sqlguardllm import Guard, GuardViolation
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class GuardedSQLDatabase(SQLDatabase):
|
|
13
|
+
"""A LangChain ``SQLDatabase`` whose ``run`` only executes SQL rewritten by sqlguardllm.
|
|
14
|
+
|
|
15
|
+
Every tool of ``SQLDatabaseToolkit`` that runs SQL goes through ``run``. A rejected query
|
|
16
|
+
comes back to the model as ``"Error: <reasons>"``, like a database error, so it can fix it.
|
|
17
|
+
|
|
18
|
+
Create it with ``sample_rows_in_table_info=0``: sample rows are read straight from the
|
|
19
|
+
tables, outside ``run``, and would show hidden columns and rows of other users to the model.
|
|
20
|
+
Any other value raises ``ValueError``.
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
*args: Any,
|
|
26
|
+
guard: Guard,
|
|
27
|
+
context_fn: Callable[[], Mapping[str, Any]],
|
|
28
|
+
**kwargs: Any,
|
|
29
|
+
) -> None:
|
|
30
|
+
super().__init__(*args, **kwargs)
|
|
31
|
+
if self._sample_rows_in_table_info != 0:
|
|
32
|
+
raise ValueError(
|
|
33
|
+
"GuardedSQLDatabase requires sample_rows_in_table_info=0: sample rows are "
|
|
34
|
+
"read outside the guard and would expose hidden columns and rows"
|
|
35
|
+
)
|
|
36
|
+
self.guard = guard
|
|
37
|
+
self.context_fn = context_fn
|
|
38
|
+
|
|
39
|
+
def run(self, command: Any, *args: Any, **kwargs: Any) -> Any:
|
|
40
|
+
if not isinstance(command, str): # a SQLAlchemy statement can't be checked
|
|
41
|
+
raise TypeError("GuardedSQLDatabase only runs SQL strings")
|
|
42
|
+
return super().run(self.guard.enforce(command, self.context_fn()), *args, **kwargs)
|
|
43
|
+
|
|
44
|
+
def run_no_throw(self, command: str, *args: Any, **kwargs: Any) -> Any:
|
|
45
|
+
try:
|
|
46
|
+
return super().run_no_throw(command, *args, **kwargs) # calls self.run
|
|
47
|
+
except GuardViolation as exc:
|
|
48
|
+
return f"Error: {exc}"
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""A LangChain tool that only runs SQL sqlguardllm has made safe."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Callable, Mapping
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
from langchain_core.tools import BaseTool, StructuredTool
|
|
9
|
+
from sqlalchemy.engine import Engine
|
|
10
|
+
from sqlguardllm import Guard, GuardViolation
|
|
11
|
+
|
|
12
|
+
_DEFAULT_DESCRIPTION = (
|
|
13
|
+
"Run a read-only SQL query and return the rows. If the query is rejected, the "
|
|
14
|
+
"error says why: rewrite the query and try again."
|
|
15
|
+
)
|
|
16
|
+
_GENERIC_ERROR = "Error: the query could not be executed."
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def sql_query_tool(
|
|
20
|
+
guard: Guard,
|
|
21
|
+
execute: Callable[[str], Any],
|
|
22
|
+
context_fn: Callable[[], Mapping[str, Any]],
|
|
23
|
+
*,
|
|
24
|
+
name: str = "sql_db_query",
|
|
25
|
+
description: str | None = None,
|
|
26
|
+
) -> BaseTool:
|
|
27
|
+
"""Build a tool that runs ``execute`` only on SQL returned by ``guard.enforce``.
|
|
28
|
+
|
|
29
|
+
``execute`` should use a read-only connection. A rejected query is returned as
|
|
30
|
+
``"Error: <reasons>"`` so the model can repair it; any other failure of ``execute`` is
|
|
31
|
+
returned as a generic error without internals.
|
|
32
|
+
"""
|
|
33
|
+
|
|
34
|
+
def run(query: str) -> str:
|
|
35
|
+
try:
|
|
36
|
+
safe_sql = guard.enforce(query, context_fn())
|
|
37
|
+
except GuardViolation as exc:
|
|
38
|
+
return f"Error: {exc}"
|
|
39
|
+
try:
|
|
40
|
+
return repr(execute(safe_sql))
|
|
41
|
+
except Exception: # noqa: BLE001 - the model must never see driver internals
|
|
42
|
+
return _GENERIC_ERROR
|
|
43
|
+
|
|
44
|
+
return StructuredTool.from_function(
|
|
45
|
+
func=run,
|
|
46
|
+
name=name,
|
|
47
|
+
description=description or _DEFAULT_DESCRIPTION,
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def sqlalchemy_executor(
|
|
52
|
+
engine: Engine, *, read_only: bool = True
|
|
53
|
+
) -> Callable[[str], list[tuple[Any, ...]]]:
|
|
54
|
+
"""Return an ``execute`` callable for a SQLAlchemy engine.
|
|
55
|
+
|
|
56
|
+
Each call opens its own connection and runs the SQL with ``exec_driver_sql`` inside a
|
|
57
|
+
transaction that is always rolled back, so nothing is ever committed.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
def execute(sql: str) -> list[tuple[Any, ...]]:
|
|
61
|
+
with engine.connect() as conn:
|
|
62
|
+
if read_only:
|
|
63
|
+
conn = conn.execution_options(postgresql_readonly=True)
|
|
64
|
+
trans = conn.begin()
|
|
65
|
+
try:
|
|
66
|
+
result = conn.exec_driver_sql(sql)
|
|
67
|
+
rows = [tuple(row) for row in result.fetchall()] if result.returns_rows else []
|
|
68
|
+
finally:
|
|
69
|
+
trans.rollback()
|
|
70
|
+
return rows
|
|
71
|
+
|
|
72
|
+
return execute
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
pytest.importorskip("langchain")
|
|
10
|
+
pytest.importorskip("langchain_community")
|
|
11
|
+
pytest.importorskip("sqlalchemy")
|
|
12
|
+
|
|
13
|
+
import sqlalchemy
|
|
14
|
+
from langchain.agents import create_agent
|
|
15
|
+
from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
|
|
16
|
+
from langchain_core.messages import AIMessage, ToolMessage
|
|
17
|
+
from sqlguardllm import Guard, Policy
|
|
18
|
+
|
|
19
|
+
from langchain_sqlguardllm import sql_query_tool, sqlalchemy_executor
|
|
20
|
+
|
|
21
|
+
POLICY = Policy(
|
|
22
|
+
dialect="sqlite",
|
|
23
|
+
tables={"customers", "invoices"},
|
|
24
|
+
hidden_columns={"customers.email"},
|
|
25
|
+
row_filters={"invoices": "branch_id IN ({user.branches})"},
|
|
26
|
+
max_rows=100,
|
|
27
|
+
)
|
|
28
|
+
CONTEXT: dict[str, Any] = {"user": {"branches": [1, 2]}}
|
|
29
|
+
SECRET = "ana@example.com"
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
class _FakeToolModel(GenericFakeChatModel):
|
|
33
|
+
"""The fake chat model with a no-op ``bind_tools`` so ``create_agent`` can use it."""
|
|
34
|
+
|
|
35
|
+
def bind_tools(self, tools: Any, **kwargs: Any) -> Any:
|
|
36
|
+
return self
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def test_agent_gets_guarded_error_then_answers(tmp_path: Path) -> None:
|
|
40
|
+
path = tmp_path / "sales.db"
|
|
41
|
+
conn = sqlite3.connect(path)
|
|
42
|
+
conn.executescript(
|
|
43
|
+
f"""
|
|
44
|
+
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
|
|
45
|
+
CREATE TABLE invoices (id INTEGER PRIMARY KEY, branch_id INTEGER, total REAL);
|
|
46
|
+
INSERT INTO customers VALUES (1, 'Ana', '{SECRET}');
|
|
47
|
+
INSERT INTO invoices VALUES (10, 1, 100.0);
|
|
48
|
+
"""
|
|
49
|
+
)
|
|
50
|
+
conn.commit()
|
|
51
|
+
conn.close()
|
|
52
|
+
engine = sqlalchemy.create_engine(f"sqlite:///{path}")
|
|
53
|
+
try:
|
|
54
|
+
tool = sql_query_tool(Guard(POLICY), sqlalchemy_executor(engine), lambda: CONTEXT)
|
|
55
|
+
messages = iter(
|
|
56
|
+
[
|
|
57
|
+
AIMessage(
|
|
58
|
+
content="",
|
|
59
|
+
tool_calls=[
|
|
60
|
+
{
|
|
61
|
+
"name": "sql_db_query",
|
|
62
|
+
"args": {"query": "SELECT email FROM customers"},
|
|
63
|
+
"id": "call_1",
|
|
64
|
+
}
|
|
65
|
+
],
|
|
66
|
+
),
|
|
67
|
+
AIMessage(content="I cannot read customer emails."),
|
|
68
|
+
]
|
|
69
|
+
)
|
|
70
|
+
model = _FakeToolModel(messages=messages)
|
|
71
|
+
agent = create_agent(model, [tool])
|
|
72
|
+
result = agent.invoke({"messages": [("user", "What is Ana's email?")]})
|
|
73
|
+
finally:
|
|
74
|
+
engine.dispose()
|
|
75
|
+
|
|
76
|
+
tool_messages = [m for m in result["messages"] if isinstance(m, ToolMessage)]
|
|
77
|
+
assert len(tool_messages) == 1
|
|
78
|
+
content = str(tool_messages[0].content)
|
|
79
|
+
assert content.startswith("Error: ")
|
|
80
|
+
assert "customers.email" in content
|
|
81
|
+
assert SECRET not in content
|
|
82
|
+
final = result["messages"][-1]
|
|
83
|
+
assert isinstance(final, AIMessage)
|
|
84
|
+
assert final.content
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
import pytest
|
|
8
|
+
|
|
9
|
+
pytest.importorskip("langchain_community")
|
|
10
|
+
pytest.importorskip("sqlalchemy")
|
|
11
|
+
|
|
12
|
+
from sqlguardllm import Guard, Policy
|
|
13
|
+
|
|
14
|
+
from langchain_sqlguardllm import GuardedSQLDatabase
|
|
15
|
+
|
|
16
|
+
POLICY = Policy(
|
|
17
|
+
dialect="sqlite",
|
|
18
|
+
tables={"customers", "invoices"},
|
|
19
|
+
hidden_columns={"customers.email"},
|
|
20
|
+
row_filters={"invoices": "branch_id IN ({user.branches})"},
|
|
21
|
+
max_rows=100,
|
|
22
|
+
)
|
|
23
|
+
CONTEXT: dict[str, Any] = {"user": {"branches": [1, 2]}}
|
|
24
|
+
SECRET = "ana@example.com"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@pytest.fixture()
|
|
28
|
+
def uri(tmp_path: Path) -> str:
|
|
29
|
+
path = tmp_path / "sales.db"
|
|
30
|
+
conn = sqlite3.connect(path)
|
|
31
|
+
conn.executescript(
|
|
32
|
+
f"""
|
|
33
|
+
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
|
|
34
|
+
CREATE TABLE invoices (id INTEGER PRIMARY KEY, branch_id INTEGER, total REAL);
|
|
35
|
+
INSERT INTO customers VALUES (1, 'Ana', '{SECRET}');
|
|
36
|
+
INSERT INTO invoices VALUES (10, 1, 100.0), (11, 2, 250.0), (12, 3, 900.0);
|
|
37
|
+
"""
|
|
38
|
+
)
|
|
39
|
+
conn.commit()
|
|
40
|
+
conn.close()
|
|
41
|
+
return f"sqlite:///{path}"
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def make_db(uri: str, **kwargs: Any) -> GuardedSQLDatabase:
|
|
45
|
+
return GuardedSQLDatabase.from_uri(
|
|
46
|
+
uri,
|
|
47
|
+
guard=Guard(POLICY),
|
|
48
|
+
context_fn=lambda: CONTEXT,
|
|
49
|
+
include_tables=sorted(POLICY.tables or ()),
|
|
50
|
+
**kwargs,
|
|
51
|
+
)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_sample_rows_must_be_zero(uri: str) -> None:
|
|
55
|
+
with pytest.raises(ValueError, match="sample_rows_in_table_info=0"):
|
|
56
|
+
make_db(uri, sample_rows_in_table_info=3)
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def test_run_filters_rows(uri: str) -> None:
|
|
60
|
+
db = make_db(uri, sample_rows_in_table_info=0)
|
|
61
|
+
out = db.run("SELECT id FROM invoices ORDER BY id")
|
|
62
|
+
assert "10" in out and "11" in out
|
|
63
|
+
assert "12" not in out
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def test_run_no_throw_returns_error_string(uri: str) -> None:
|
|
67
|
+
db = make_db(uri, sample_rows_in_table_info=0)
|
|
68
|
+
out = db.run_no_throw("SELECT email FROM customers")
|
|
69
|
+
assert isinstance(out, str)
|
|
70
|
+
assert out.startswith("Error: ")
|
|
71
|
+
assert "customers.email" in out
|
|
72
|
+
assert SECRET not in out
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_run_rejects_non_string(uri: str) -> None:
|
|
76
|
+
db = make_db(uri, sample_rows_in_table_info=0)
|
|
77
|
+
with pytest.raises(TypeError):
|
|
78
|
+
db.run(object())
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import sqlite3
|
|
4
|
+
from collections.abc import Iterator
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
import pytest
|
|
9
|
+
|
|
10
|
+
pytest.importorskip("langchain_core")
|
|
11
|
+
sqlalchemy = pytest.importorskip("sqlalchemy")
|
|
12
|
+
|
|
13
|
+
from sqlalchemy.engine import Engine
|
|
14
|
+
from sqlguardllm import Guard, Policy
|
|
15
|
+
|
|
16
|
+
from langchain_sqlguardllm import sql_query_tool, sqlalchemy_executor
|
|
17
|
+
|
|
18
|
+
POLICY = Policy(
|
|
19
|
+
dialect="sqlite",
|
|
20
|
+
tables={"customers", "invoices"},
|
|
21
|
+
hidden_columns={"customers.email"},
|
|
22
|
+
row_filters={"invoices": "branch_id IN ({user.branches})"},
|
|
23
|
+
max_rows=100,
|
|
24
|
+
)
|
|
25
|
+
CONTEXT: dict[str, Any] = {"user": {"branches": [1, 2]}}
|
|
26
|
+
SECRET = "ana@example.com"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@pytest.fixture()
|
|
30
|
+
def db_path(tmp_path: Path) -> Path:
|
|
31
|
+
path = tmp_path / "sales.db"
|
|
32
|
+
conn = sqlite3.connect(path)
|
|
33
|
+
conn.executescript(
|
|
34
|
+
f"""
|
|
35
|
+
CREATE TABLE customers (id INTEGER PRIMARY KEY, name TEXT, email TEXT);
|
|
36
|
+
CREATE TABLE invoices (id INTEGER PRIMARY KEY, branch_id INTEGER, total REAL);
|
|
37
|
+
INSERT INTO customers VALUES (1, 'Ana', '{SECRET}');
|
|
38
|
+
INSERT INTO invoices VALUES (10, 1, 100.0), (11, 2, 250.0), (12, 3, 900.0);
|
|
39
|
+
"""
|
|
40
|
+
)
|
|
41
|
+
conn.commit()
|
|
42
|
+
conn.close()
|
|
43
|
+
return path
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@pytest.fixture()
|
|
47
|
+
def engine(db_path: Path) -> Iterator[Engine]:
|
|
48
|
+
eng = sqlalchemy.create_engine(f"sqlite:///{db_path}")
|
|
49
|
+
yield eng
|
|
50
|
+
eng.dispose()
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def test_allowed_query_returns_only_user_rows(engine: Engine) -> None:
|
|
54
|
+
tool = sql_query_tool(Guard(POLICY), sqlalchemy_executor(engine), lambda: CONTEXT)
|
|
55
|
+
out = tool.invoke({"query": "SELECT id FROM invoices ORDER BY id"})
|
|
56
|
+
assert "10" in out and "11" in out
|
|
57
|
+
assert "12" not in out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def test_hidden_column_is_error_string(engine: Engine) -> None:
|
|
61
|
+
tool = sql_query_tool(Guard(POLICY), sqlalchemy_executor(engine), lambda: CONTEXT)
|
|
62
|
+
out = tool.invoke({"query": "SELECT email FROM customers"})
|
|
63
|
+
assert out.startswith("Error: ")
|
|
64
|
+
assert "customers.email" in out
|
|
65
|
+
assert SECRET not in out
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def test_write_is_error_string(engine: Engine) -> None:
|
|
69
|
+
tool = sql_query_tool(Guard(POLICY), sqlalchemy_executor(engine), lambda: CONTEXT)
|
|
70
|
+
out = tool.invoke({"query": "DELETE FROM invoices"})
|
|
71
|
+
assert out.startswith("Error: ")
|
|
72
|
+
assert "write" in out.lower() or "read" in out.lower() or "select" in out.lower()
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def test_execute_failure_is_generic(engine: Engine) -> None:
|
|
76
|
+
def boom(sql: str) -> list[tuple[Any, ...]]:
|
|
77
|
+
raise RuntimeError("secret-internal-detail /var/db/path")
|
|
78
|
+
|
|
79
|
+
tool = sql_query_tool(Guard(POLICY), boom, lambda: CONTEXT)
|
|
80
|
+
out = tool.invoke({"query": "SELECT id FROM invoices"})
|
|
81
|
+
assert out.startswith("Error")
|
|
82
|
+
assert "secret-internal-detail" not in out
|
|
83
|
+
assert "/var/db/path" not in out
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_custom_name_and_description(engine: Engine) -> None:
|
|
87
|
+
tool = sql_query_tool(
|
|
88
|
+
Guard(POLICY),
|
|
89
|
+
sqlalchemy_executor(engine),
|
|
90
|
+
lambda: CONTEXT,
|
|
91
|
+
name="run_sql",
|
|
92
|
+
description="Run SQL.",
|
|
93
|
+
)
|
|
94
|
+
assert tool.name == "run_sql"
|
|
95
|
+
assert tool.description == "Run SQL."
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def test_sqlalchemy_executor_never_commits(engine: Engine, db_path: Path) -> None:
|
|
99
|
+
execute = sqlalchemy_executor(engine)
|
|
100
|
+
execute("INSERT INTO invoices VALUES (99, 1, 1.0)")
|
|
101
|
+
execute("DELETE FROM invoices")
|
|
102
|
+
conn = sqlite3.connect(db_path)
|
|
103
|
+
try:
|
|
104
|
+
assert conn.execute("SELECT COUNT(*) FROM invoices").fetchone() == (3,)
|
|
105
|
+
finally:
|
|
106
|
+
conn.close()
|