Skip to content
Open
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
2 changes: 2 additions & 0 deletions src/lang2sql/adapters/db/d1_explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ async def list_tables(self) -> list[Table]:

async def describe_table(self, name: str) -> Table:
rows = await self._query(f"PRAGMA table_info({_ident(name)})")
if not rows:
raise KeyError(f"unknown table: {name}")
cols = [
Column(
name=r["name"], type=r["type"] or "", nullable=not bool(r["notnull"])
Expand Down
15 changes: 13 additions & 2 deletions src/lang2sql/adapters/db/sqlalchemy_explorer.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,29 @@ def _list_tables_sync(self) -> list[Table]:

def _describe_table_sync(self, name: str) -> Table:
from sqlalchemy import inspect
from sqlalchemy.exc import NoSuchTableError

insp = inspect(self._get_engine())
schema = self._schema
table_name = name.removeprefix(f"{schema}.") if schema else name
try:
columns = insp.get_columns(table_name, schema=schema)
except NoSuchTableError:
if table_name == name:
raise
# An identifier can also literally start with the schema prefix.
table_name = name
columns = insp.get_columns(table_name, schema=schema)
cols = [
Column(
name=c["name"],
type=str(c["type"]),
nullable=bool(c.get("nullable", True)),
description=c.get("comment") or "",
)
for c in insp.get_columns(name, schema=self._schema)
for c in columns
]
return Table(name=name, schema=self._schema or "", columns=cols)
return Table(name=table_name, schema=schema or "", columns=cols)

def _execute_sync(self, sql: str, limit: int) -> list[dict]:
from sqlalchemy import text
Expand Down
3 changes: 2 additions & 1 deletion src/lang2sql/harness/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
if TYPE_CHECKING:
from ..adapters.storage.sqlite_store import SqliteStore
from ..core.ports.audit import AuditPort
from ..core.ports.explorer import ExplorerPort
from ..core.ports.explorer import ExplorerPort, Table
from ..core.ports.llm import LLMPort
from ..core.ports.safety import SafetyPipelinePort
from .session import Session
Expand All @@ -35,3 +35,4 @@ class HarnessContext:
store: SqliteStore | None = None
okf_bundle_dir: str | None = None
max_turns: int = 8
known_tables: list[Table] | None = None
4 changes: 4 additions & 0 deletions src/lang2sql/harness/loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@

from __future__ import annotations

from dataclasses import replace

from ..core.types import Message, Role
from .context import HarnessContext
from .system_prompt import build_system_prompt
Expand All @@ -17,6 +19,8 @@ async def agent_loop(ctx: HarnessContext, user_text: str) -> str:
"""Run one user turn to completion; return the final assistant text."""
ctx.session.add(Message(role=Role.USER, content=user_text))

if ctx.explorer is not None:
ctx = replace(ctx, known_tables=await ctx.explorer.list_tables())
system = await build_system_prompt(ctx)
specs = ctx.tools.specs()

Expand Down
6 changes: 5 additions & 1 deletion src/lang2sql/harness/system_prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
- Only ever read data. Never modify the database.
- When you need data, call the run_sql tool with a single SELECT/WITH query.
- Discover schema with explore_schema before guessing table or column names.
For multiple tables, select names from Known tables and request their columns
together with the tables argument.
- Prefer definitions from the semantic layer below over your own assumptions.
- Answer concisely. Show only the final successful SQL you ran, not intermediate attempts.

Expand All @@ -32,7 +34,9 @@ async def build_system_prompt(ctx: HarnessContext) -> str:
parts: list[str] = [_BASE]

if ctx.explorer is not None:
tables = await ctx.explorer.list_tables()
tables = ctx.known_tables
if tables is None:
tables = await ctx.explorer.list_tables()
if tables:
scope = ctx.identity.kv_scope if ctx.store else None
has_enrichment = bool(
Expand Down
116 changes: 95 additions & 21 deletions src/lang2sql/tools/explore_schema.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
"""explore_schema — let the agent discover tables/columns before writing SQL.

Read-only introspection through the :class:`ExplorerPort`. With no ``table``
arg it lists tables; with one it returns full column detail.
Read-only introspection through the :class:`ExplorerPort`. List available
tables, or describe the columns of one or more selected tables.
"""

from __future__ import annotations

from dataclasses import replace
from typing import TYPE_CHECKING, Any

from ..core.ports.explorer import Column, Table
from ..core.ports.explorer import Column, ExplorerPort, Table
from ..core.types import ToolResult, ToolSpec

if TYPE_CHECKING:
Expand All @@ -33,43 +33,117 @@ def _apply_enrichment_cache(table: Table, ctx: "HarnessContext") -> Table:
return replace(table, columns=enriched_cols)


def _format_columns(table: Table, ctx: "HarnessContext") -> str:
table = _apply_enrichment_cache(table, ctx)
cols = (
"\n".join(
f"- {c.name}: {c.type}{'' if c.nullable else ' NOT NULL'}"
f"{(' — ' + c.description) if c.description else ''}"
for c in table.columns
)
or "(no columns)"
)
return f"{table.qualified}\n{cols}"


async def _list_tables(explorer: ExplorerPort, ctx: "HarnessContext") -> list[Table]:
if ctx.known_tables is not None:
return ctx.known_tables
return await explorer.list_tables()


async def _describe_tables(
names: list[str], explorer: ExplorerPort, ctx: "HarnessContext"
) -> ToolResult:
catalog = await _list_tables(explorer, ctx)
qualified_names = {table.qualified: table for table in catalog}
bare_names: dict[str, Table | None] = {}
for candidate in catalog:
bare_names[candidate.name] = (
candidate if candidate.name not in bare_names else None
)

sections: list[str] = []
seen: set[str] = set()
has_error = False
for name in dict.fromkeys(name.strip() for name in names):
table = qualified_names.get(name) or bare_names.get(name)
if table is None and name in bare_names:
sections.append(f"{name}: ambiguous table. Include its schema name.")
has_error = True
continue

if name in seen or (table is not None and table.qualified in seen):
continue
try:
described = await explorer.describe_table(name)
if described.qualified not in seen:
sections.append(_format_columns(described, ctx))
seen.update((name, described.qualified))
except Exception as exc:
sections.append(f"{name}: {type(exc).__name__}: {exc}")
has_error = True
return ToolResult(call_id="", content="\n\n".join(sections), is_error=has_error)


class ExploreSchema:
@property
def spec(self) -> ToolSpec:
return ToolSpec(
name="explore_schema",
description="List tables, or describe one table's columns. Call before writing SQL.",
description=(
"List tables or describe their columns before writing SQL. "
"Request multiple relevant tables together with 'tables'."
),
parameters={
"type": "object",
"properties": {
"table": {
"type": "string",
"description": "table name to describe; omit to list all tables",
"description": "one table name; use either 'table' or 'tables'",
},
"tables": {
"type": "array",
"items": {"type": "string", "minLength": 1},
"minItems": 1,
"description": (
"names of relevant tables; omit both arguments to list tables"
),
},
},
},
)

async def run(self, args: dict[str, Any], ctx: "HarnessContext") -> ToolResult:
if ctx.explorer is None:
explorer = ctx.explorer
if explorer is None:
return ToolResult(
call_id="", content="no DB connected (use /connect)", is_error=True
)

if "tables" in args:
if "table" in args:
return ToolResult(
call_id="", content="Use either 'table' or 'tables'.", is_error=True
)
names = args["tables"]
if (
not isinstance(names, list)
or not names
or any(not isinstance(name, str) or not name.strip() for name in names)
):
return ToolResult(
call_id="",
content="'tables' must be a non-empty list of table names.",
is_error=True,
)
return await _describe_tables(names, explorer, ctx)

table = (args.get("table") or "").strip()
if not table:
tables = await ctx.explorer.list_tables()
names = "\n".join(f"- {t.qualified}" for t in tables) or "(no tables)"
return ToolResult(call_id="", content="Tables:\n" + names)

t = await ctx.explorer.describe_table(table)
t = _apply_enrichment_cache(t, ctx)
cols = (
"\n".join(
f"- {c.name}: {c.type}{'' if c.nullable else ' NOT NULL'}"
f"{(' — ' + c.description) if c.description else ''}"
for c in t.columns
)
or "(no columns)"
)
return ToolResult(call_id="", content=f"{t.qualified}\n{cols}")
tables = await _list_tables(explorer, ctx)
listed = "\n".join(f"- {t.qualified}" for t in tables) or "(no tables)"
return ToolResult(call_id="", content="Tables:\n" + listed)

described = await explorer.describe_table(table)
return ToolResult(call_id="", content=_format_columns(described, ctx))
13 changes: 13 additions & 0 deletions tests/test_db_adapters.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,19 @@ def test_sqlalchemy_explorer_introspect_and_execute(tmp_path):
assert len(sample) == 1


def test_sqlalchemy_explorer_describes_names_in_its_configured_schema(tmp_path):
db = tmp_path / "demo.db"
_seed_sqlite(str(db))
exp = SqlAlchemyExplorer(f"sqlite:///{db}", schema="main")

qualified = asyncio.run(exp.describe_table("main.users"))
bare = asyncio.run(exp.describe_table("users"))

assert qualified == bare
assert qualified.qualified == "main.users"
assert [column.name for column in qualified.columns] == ["id", "email"]


# --- D1 explorer with mocked HTTP transport --------------------------------


Expand Down
41 changes: 40 additions & 1 deletion tests/test_harness_loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,15 @@

import asyncio

from lang2sql.adapters.db.postgres_explorer import PostgresExplorer
from lang2sql.adapters.llm.fake import FakeLLM
from lang2sql.core.identity import Identity
from lang2sql.core.types import Role
from lang2sql.core.types import Completion, Role, ToolCall
from lang2sql.harness.context import HarnessContext
from lang2sql.harness.loop import agent_loop
from lang2sql.harness.session import Session
from lang2sql.harness.tool_registry import ToolRegistry
from lang2sql.tools.explore_schema import ExploreSchema
from lang2sql.tools.ping import Ping


Expand Down Expand Up @@ -50,6 +52,43 @@ def test_tool_call_id_is_stamped():
assert tool_msgs and tool_msgs[0].tool_call_id


def test_schema_batch_uses_the_catalog_from_the_system_prompt():
class CountingExplorer(PostgresExplorer):
catalog_reads = 0

async def list_tables(self):
self.catalog_reads += 1
return await super().list_tables()

class SchemaLLM:
async def complete(self, messages, tools=()):
if messages[-1].role == Role.TOOL:
assert "- amount: numeric" in messages[-1].content
assert "- email: text" in messages[-1].content
return Completion(content="Found both tables.")
assert "## Known tables\npublic.orders, public.users" in messages[0].content
return Completion(
tool_calls=[
ToolCall(
id="schema",
name="explore_schema",
arguments={"tables": ["public.orders", "public.users"]},
)
]
)

ctx = _ctx()
explorer = CountingExplorer("postgresql://ignored")
ctx.explorer = explorer
ctx.llm = SchemaLLM()
ctx.tools = ToolRegistry([ExploreSchema()])

assert asyncio.run(agent_loop(ctx, "Show the schema for orders and users.")) == (
"Found both tables."
)
assert explorer.catalog_reads == 1


def test_scope_chain_orders_narrow_to_wide():
ident = Identity(user_id="u", guild_id="g", channel_id="c", thread_id="t")
levels = [s.level.value for s in ident.scope_chain()]
Expand Down
Loading