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
22 changes: 22 additions & 0 deletions src/lang2sql/adapters/llm/openai_.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,23 @@ async def complete(
self,
messages: Sequence[Message],
tools: Sequence[ToolSpec] = (),
) -> Completion:
return await self._complete(messages, tools)

async def complete_with_required_tool(
self,
messages: Sequence[Message],
tools: Sequence[ToolSpec],
tool_name: str,
) -> Completion:
return await self._complete(messages, tools, required_tool=tool_name)

async def _complete(
self,
messages: Sequence[Message],
tools: Sequence[ToolSpec],
*,
required_tool: str | None = None,
) -> Completion:
if not self._api_key:
raise RuntimeError("OPENAI_API_KEY not set")
Expand All @@ -56,6 +73,11 @@ async def complete(
}
if tools:
payload["tools"] = [_encode_tool(t) for t in tools]
if required_tool is not None:
payload["tool_choice"] = {
"type": "function",
"function": {"name": required_tool},
}

raw = await asyncio.to_thread(self._post, payload)
return _decode_completion(raw)
Expand Down
12 changes: 12 additions & 0 deletions src/lang2sql/core/ports/llm.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,15 @@ async def complete(
) -> Completion:
"""Run one completion. May return tool calls, a final answer, or both."""
...


@runtime_checkable
class RequiredToolLLMPort(LLMPort, Protocol):
"""An LLM adapter that can require a specific tool on one request."""

async def complete_with_required_tool(
self,
messages: Sequence[Message],
tools: Sequence[ToolSpec],
tool_name: str,
) -> Completion: ...
3 changes: 2 additions & 1 deletion src/lang2sql/core/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,12 @@ class ToolCall:

@dataclass
class ToolResult:
"""Outcome of running a :class:`ToolCall`, fed back to the model."""
"""Tool response text and the tables whose columns appear in that text."""

call_id: str
content: str
is_error: bool = False
tables_with_columns: tuple[str, ...] = ()


@dataclass
Expand Down
8 changes: 7 additions & 1 deletion src/lang2sql/frontends/cli/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ async def execute(ctx, calls):
call_id = uuid.uuid4().hex
logger.info("cli_tool_start tool=%s call_id=%s", call["name"], call_id)
result = await ctx.tools.dispatch(call["name"], call["arguments"], ctx, call_id)
results.append(asdict(result))
results.append(
{
"call_id": result.call_id,
"content": result.content,
"is_error": result.is_error,
}
)
if result.is_error:
logger.warning("cli_tool_failed tool=%s call_id=%s", call["name"], call_id)
break
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
158 changes: 148 additions & 10 deletions src/lang2sql/harness/loop.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,162 @@

from __future__ import annotations

from ..core.types import Message, Role
from dataclasses import replace
from typing import Callable

from ..core.ports.llm import RequiredToolLLMPort
from ..core.types import Message, Role, ToolResult, ToolSpec
from .context import HarnessContext
from .sql_candidate import is_database_query, sql_from_answer
from .system_prompt import build_system_prompt

_SCHEMA_TOOL = "explore_schema"
_SQL_WITHHELD = (
"SQL withheld because no table columns were provided to the model. "
"Use column information from explore_schema before rewriting the query."
)
_NEEDS_SCHEMA = (
"Call explore_schema with a non-empty tables list to obtain the missing columns."
)
_REWRITE_SQL = (
"A previous SQL query was withheld. Use the columns in the schema results to "
"rewrite the query before running it or returning it as the final answer."
)


def _recovery_specs(specs: list[ToolSpec], schema: ToolSpec) -> list[ToolSpec]:
tables_parameter = schema.parameters["properties"]["tables"]
schema_for_recovery = replace(
schema,
description="Return the columns for one or more relevant tables.",
parameters={
"type": "object",
"properties": {
"tables": {
**tables_parameter,
"description": "Names of tables needed to rewrite the query.",
}
},
"required": ["tables"],
"additionalProperties": False,
},
)
return [schema_for_recovery if spec is schema else spec for spec in specs]


async def agent_loop(ctx: HarnessContext, user_text: str) -> str:
"""Run one user turn to completion; return the final assistant text."""
async def agent_loop(
ctx: HarnessContext,
user_text: str,
*,
extract_final_sql: Callable[[str], str] | None = None,
) -> str:
"""Run one user turn.

Evaluators can supply their final SQL parser to apply the same output
contract before scoring. The parser raises ValueError for other answers.
"""
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()
schema_spec = next((spec for spec in specs if spec.name == _SCHEMA_TOOL), None)
tables_with_columns = system.tables_with_columns
sql_withheld = False
deferred_answer: tuple[int, Message] | None = None
failure: str | None = None

for _ in range(ctx.max_turns):
messages = [Message(role=Role.SYSTEM, content=system), *ctx.session.history()]
completion = await ctx.llm.complete(messages, specs)
# Every tool call in this response was authored with the same context.
model_has_columns = bool(tables_with_columns)
needs_recovery = sql_withheld and not model_has_columns
prompt = system.content
if sql_withheld:
prompt += "\n\n" + (
f"{_SQL_WITHHELD} {_NEEDS_SCHEMA}" if needs_recovery else _REWRITE_SQL
)
history = ctx.session.history()
if deferred_answer is not None:
# Keep the rejected draft available to the model for schema selection.
index, draft = deferred_answer
history.insert(index, draft)
messages = [Message(role=Role.SYSTEM, content=prompt), *history]

try:
if needs_recovery:
if schema_spec is None or ctx.explorer is None:
failure = "schema lookup is unavailable"
break
if not isinstance(ctx.llm, RequiredToolLLMPort):
failure = "the model adapter cannot require schema lookup"
break
completion = await ctx.llm.complete_with_required_tool(
messages, _recovery_specs(specs, schema_spec), _SCHEMA_TOOL
)
else:
completion = await ctx.llm.complete(messages, specs)
except Exception as exc:
if not sql_withheld:
raise
step = "schema lookup" if needs_recovery else "SQL rewrite"
failure = f"model request failed during {step}: {type(exc).__name__}"
break

assistant = Message(
role=Role.ASSISTANT,
content=completion.content,
content="" if needs_recovery else completion.content,
tool_calls=completion.tool_calls,
)
ctx.session.add(assistant)

if not completion.tool_calls:
if needs_recovery:
continue
if not model_has_columns and is_database_query(
sql_from_answer(completion.content, extract_final_sql)
):
sql_withheld = True
deferred_answer = (len(history), assistant)
continue
if sql_withheld and (
completion.finish_reason == "length"
or not completion.content.strip()
or (
extract_final_sql is not None
and sql_from_answer(completion.content, extract_final_sql) is None
)
):
continue
ctx.session.add(assistant)
return completion.content

ctx.session.add(assistant)
for call in completion.tool_calls:
result = await ctx.tools.dispatch(call.name, call.arguments, ctx, call.id)
if needs_recovery and (
call.name != _SCHEMA_TOOL
or not isinstance(call.arguments, dict)
or call.arguments.keys() != {"tables"}
):
result = ToolResult(
call_id=call.id, content=_NEEDS_SCHEMA, is_error=True
)
elif (
not model_has_columns
and call.name == "run_sql"
and ctx.explorer is not None
and isinstance(call.arguments, dict)
and is_database_query(call.arguments.get("sql"))
):
sql_withheld = True
# Keep the candidate in the tool call, outside the persisted reply.
assistant.content = ""
result = ToolResult(
call_id=call.id, content=_SQL_WITHHELD, is_error=True
)
else:
result = await ctx.tools.dispatch(
call.name, call.arguments, ctx, call.id
)
tables_with_columns.update(result.tables_with_columns)
ctx.session.add(
Message(
role=Role.TOOL,
Expand All @@ -45,4 +173,14 @@ async def agent_loop(ctx: HarnessContext, user_text: str) -> str:
)
)

return "(reached max turns without a final answer)"
if not sql_withheld:
return "(reached max turns without a final answer)"
if failure is None:
failure = (
"reached max turns before receiving a rewritten final answer"
if tables_with_columns
else "no table columns obtained before reaching max turns"
)
answer = f"(SQL withheld: {failure})"
ctx.session.add(Message(role=Role.ASSISTANT, content=answer))
return answer
Loading