Extending contextlift
Both the database executor and the agent runner are structural Python protocols (typing.Protocol). You do not need to subclass a base class or modify package internals: implement the required methods and pass your instance to score(), ablate(), or run_round().
Writing a custom warehouse Executor
Any SQL engine (Trino, ClickHouse, Redshift, MotherDuck, or an internal query proxy) plugs in by implementing one method 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(ok=False, error=f"refused: {violation}")
cur = self._conn.cursor()
cur.execute(sql)
cols = [col[0] for col in (cur.description or ())]
fetched = cur.fetchmany(self._row_cap + 1)
truncated = len(fetched) > self._row_cap
rows = [tuple(r) for r in fetched[: self._row_cap]]
return ExecResult(
ok=True,
columns=tuple(cols),
rows=rows,
truncated=truncated,
)
Contract checklist for Executor
- Always call
read_only_violation(sql)first. Predicted SQL is untrusted model output; fail closed on non-SELECT statements, write keywords, stacked queries, and data-changing CTEs. - Fetch
row_cap + 1rows. Return at mostrow_caprows and settruncated=Truewhen more rows exist so the comparator marksROW_CAP_HIThonestly instead of comparing partial results as equal. - Return
ExecResult(ok=False, error=...)on SQL errors or timeouts. Never let an expected query syntax or permission error crash the scoring loop. - Optional
describe_tables(tables=..., datasets=...). Implement this method if you also wantschemaandinitauto-introspection to work on your custom dialect.
Writing a custom agent Runner
Any text-to-SQL agent (LangGraph, LlamaIndex, Vanna, an internal RAG API, or a multi-step agent loop) plugs into run_round() by implementing the Runner protocol from src/context_lift/runners/__init__.py:
from context_lift.runners import Answer, Arm, CostSheet
class MyAgentRunner:
"""Minimal Runner connecting a custom text-to-SQL agent to contextlift."""
name = "my-agent"
def __init__(self, client, *, 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_estimate=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) -> Answer:
# arm.tables, arm.table_descriptions, arm.field_descriptions,
# arm.system_instruction, arm.terms, arm.examples, arm.relationships
# hold the exact control (Arm 0d) or treatment (Arm 1) context.
resp = 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 Answer(
question_id=question_id,
arm_id=arm.arm_id,
sql=resp.sql,
error=resp.error,
)
Contract checklist for Runner
- Respect
armstrictly. Arm 0d (control) and Arm 1 (treatment) are passed through the exact sameanswer()call. Never hard-code extra rules, examples, or hidden prompts that bypassarm, or the paired ablation measures nothing. - Keep
cost_sheet()honest. Return a real call count (n_questions * n_arms * k) and a documentedusd_estimate(orNonewhen unknown) so pre-flight budget ceilings work. - Never raise on a single bad model reply. Return
Answer(question_id=question_id, arm_id=arm.arm_id, sql=None, error=str(exc))so the round recordsPRED_ERRORand keeps scoring the remaining questions.
Running without writing Python (--runner command)
If your agent already has a CLI entrypoint, you do not need to write a Python class at all. Pass --runner command --command "python3 agent.py" to round or generate. contextlift invokes the command with shell=False and exchanges JSON over stdin/stdout. See Warehouses and agents for the exact command recipe.