The model never writes SQL: structured outputs as a safety boundary
A plain-English stock screener where the model fills a small JSON spec and my own compiler writes the query.
Text-to-SQL is one of the first things people build with a language model, and one of the riskiest. If the model writes the query, the model decides which tables it reads, how much data it scans and whether a clever question turns into something you didn't plan for.
In market-pulse you can type large-cap tech, P/E under 20, up 5% this week
and get a table of matching companies. The model is involved, but it never sees a line of SQL.
Give the model a form, not a keyboard
The model's only output is a QuerySpec: a list of filters, an optional sort and a limit. Each filter names a field from a fixed list of ten (price, market cap, P/E, dividend yield, sector, 1/5/30-day change and so on), an operator and a value.
class Filter(BaseModel):
field: FieldName # one of the ten known fields
op: Op # >, >=, <, <=, =, !=, in
number: float | None = None
text: list[str] | None = None
class QuerySpec(BaseModel):
filters: list[Filter] = Field(default_factory=list, max_length=10)
sort: Sort | None = None
limit: int = Field(default=20, ge=1, le=100)
explanation: str = ""
unsupported_reason: str | None = None
The same structure is sent to the API as a JSON schema, so the model's answer is constrained to that shape when it's generated. Then Pydantic validates it again, with rules the schema can't express: numeric fields only get numeric operators, sector must be a real sector, = takes exactly one value.
If a question can't be answered with these fields ("which CEO is the tallest?"), the model fills unsupported_reason instead of guessing.
The compiler is boring on purpose
Turning a validated spec into SQL is about thirty lines:
def compile_spec(spec):
where, params = [], []
for f in spec.filters:
col = f.field
assert col in FIELDS # identifiers only ever come from FIELDS
if f.op == "in":
where.append(f"{col} IN ({', '.join('?' for _ in f.text)})")
params.extend(f.text)
elif FIELDS[col].kind == "number":
where.append(f"{col} {f.op} ?")
params.append(f.number)
...
sql = f"SELECT {COLUMNS} FROM screener"
Column names come from my allowlist, never from the model. Values are always bound parameters. The query only ever reads one view, screener, and the limit is capped at 100. Injection and runaway queries aren't unlikely here; there's no way to express them.
What you gain besides safety
- It's testable without a model. The spec and the compiler have plain unit tests. Most of the system's behaviour is covered with no API key at all.
- It's explainable. The UI shows the spec next to the results, so you can see that "large-cap" became
market_cap_b >= 10and change it if you disagree. - It's cacheable. The same question always maps to the same spec, so the translation can be cached while the results stay live. More on that in the post on inference cost.
- It's easy to evaluate. The eval set is a list of questions with the filters each one must produce, compared as sets so order doesn't matter.
The trade-off
You give up range. The screener can't join arbitrary tables or answer questions outside its ten fields. For a product, I think that's the right trade: add a field when users need one, and every new capability goes through code review instead of appearing because a model improvised.
The same pattern works well past SQL: search filters, ticket routing, infrastructure requests. Have the model choose from options you defined, and let your code do the part that has consequences.
Try it in the screener demo. Companies and prices are simulated.