Extending contextlift
Both the database executor and the agent runner are structural Python protocols (typing.Protocol). Implement the required methods without subclassing package internals, then pass your class into context_lift.round.run() or load a custom runner from the CLI with --runner MODULE:ATTR.
Writing a custom warehouse Executor
Any SQL engine (Trino, ClickHouse, Redshift, MotherDuck, or an internal query proxy) plugs in by implementing execute() from src/context_lift/executor.py:
from context_lift.executor import ExecResult, read_only_violation
class TrinoExecutor:
"""Minimal read-only Executor for an arbitrary SQL engine."""
dialect = "trino"
def __init__(self, conn, *, row_cap: int = 500):
self._conn = conn
self._row_cap = row_cap
def execute(self, sql: str) -> ExecResult:
violation = read_only_violation(sql)
if violation:
return ExecResult(rows=[], error=f"refused: {violation}")
try:
cur = self._conn.cursor()
cur.execute(sql)
cols = tuple(col[0] for col in (cur.description or ()))
fetched = cur.fetchmany(self._row_cap + 1)
truncated = len(fetched) > self._row_cap
pos_rows = tuple(tuple(r) for r in fetched[: self._row_cap])
dict_rows = [dict(zip(cols, r)) for r in pos_rows]
return ExecResult(
rows=dict_rows,
error=None,
truncated=truncated,
columns=cols,
positional_rows=pos_rows,
)
except Exception as exc:
return ExecResult(rows=[], error=str(exc))
Executor checklist
- Call
read_only_violation(sql)first. Predicted SQL is untrusted model output; fail closed on write keywords, stacked statements, and data-changing CTEs. - Fetch
row_cap + 1rows. Return at mostrow_caprows and settruncated=Truewhen extra rows exist so the comparator marksROW_CAP_HIThonestly. - Return
ExecResult(rows=[], error=...)on SQL errors or timeouts.ExecResult.okis a read-only property (self.error is None), so leaveerror=Noneon success and pass an error string on failure. - Preserve
columnsandpositional_rowsalongsiderowsso duplicate column names compare cleanly.
Writing a custom agent Runner
Any text-to-SQL agent (LangGraph, LlamaIndex, Vanna, or an internal API) satisfies Runner from src/context_lift/runners/__init__.py:
from context_lift.runners import Arm, CostSheet, Prediction
class MyAgentRunner:
"""Minimal Runner connecting a custom text-to-SQL agent to contextlift."""
name = "my-agent"
def __init__(self, client=None, *, usd_per_call: float = 0.005):
self._client = client
self._usd_per_call = usd_per_call
def cost_sheet(self, n_questions: int, n_arms: int, k: int) -> CostSheet:
calls = n_questions * n_arms * k
return CostSheet(
calls=calls,
minutes_at_quota=calls / 30.0,
usd_estimate=calls * self._usd_per_call,
basis=f"${self._usd_per_call:.4f}/call configured estimate",
)
def answer(self, question_id: str, question: str, arm: Arm) -> Prediction:
try:
sql = self._client.generate_sql(
question=question,
tables=arm.tables,
instructions=arm.system_instruction,
field_descriptions=arm.field_descriptions,
examples=[(e.question, e.sql) for e in arm.examples],
)
return Prediction(
question_id=question_id,
arm_id=arm.arm_id,
pred_sql=sql,
)
except Exception as exc:
return Prediction(
question_id=question_id,
arm_id=arm.arm_id,
pred_sql=None,
error_class=type(exc).__name__,
note=str(exc),
)
Runner checklist
- Respect
armstrictly. Control (Arm 0d) and treatment (Arm 1) flow through the exact sameanswer()method. Never hard-code rules or hidden examples outsidearm. - Keep
cost_sheet()honest. Return realcalls,minutes_at_quota, andusd_estimate(orNonewhen unknown) so budget ceilings trigger before spending money. - Catch per-question errors. Return
Prediction(question_id=..., arm_id=..., pred_sql=None, error_class=...)instead of aborting the whole round.
Running in Python or via --runner MODULE:ATTR
Pass your custom Executor and Runner directly into context_lift.round.run():
from context_lift.executor import SQLiteExecutor
from context_lift.round import Gold, run
from context_lift.runners import Arm, CostSheet, Prediction
class DemoAgentRunner:
name = "demo-agent"
def cost_sheet(self, n_questions: int, n_arms: int, k: int) -> CostSheet:
calls = n_questions * n_arms * k
return CostSheet(calls=calls, minutes_at_quota=0.0, usd_estimate=0.0, basis="local")
def answer(self, question_id: str, question: str, arm: Arm) -> Prediction:
if "ARR" in question:
sql = "SELECT 1200 AS arr" if arm.system_instruction else "SELECT 0 AS arr"
else:
sql = "SELECT 5 AS trials"
return Prediction(question_id=question_id, arm_id=arm.arm_id, pred_sql=sql)
executor = SQLiteExecutor(":memory:")
runner = DemoAgentRunner()
golds = [
Gold(id="q1", question="Active ARR?", gold_sql="SELECT 1200 AS arr"),
Gold(id="q2", question="Trial count?", gold_sql="SELECT 5 AS trials"),
]
control = Arm(label="control", tables=["subscriptions"])
treatment = Arm(
label="treatment",
tables=["subscriptions"],
system_instruction="Active ARR multiplies active MRR by 12.",
)
result = run(
golds=golds,
control=control,
treatment=treatment,
ask=runner.answer,
executor=executor,
k=1,
force_underpowered=True,
)
print(result.verdict.word)
To plug a custom Runner into the CLI without touching contextlift source, expose either a zero-argument class, a prebuilt instance, or a factory(args) callable and pass --runner MODULE:ATTR:
contextlift round \
--runner my_pkg.agent:MyAgentRunner \
--db warehouse.duckdb \
--spec spec/ \
--golds golds.csv \
--budget 5 --out round.json
If your agent already has a CLI entrypoint, use --runner command --command "python3 agent.py" (zero Python glue required). See Warehouses, agents, semantic layers, and MCP.