Design an NL-to-Formula Assistant for a No-Code Spreadsheet Tool
Machine LearningModel answerLast updated
Design an ML system that converts natural-language requests into validated formula expressions grounded in a live table schema, with optional write-back to the data source.
Context
You are building a feature for a no-code spreadsheet product (think: a product where users define tables with typed columns and write formulas to compute derived values). Non-technical users want to describe what they want in plain English and have the system produce a correct, validated formula — and optionally apply it to their live table.
You have two API keys: one for the table product (read/write access to a base and table), and one for an LLM provider. The table product has its own formula language with typed functions (IF, AND, DATETIME_DIFF, etc.) and typed fields (number, currency, date, checkbox, single-select, text).
Example user requests:
- "Add 2 to
salary." - "If
Statusis 'Won' andAmountis over 1000, give me 10% ofAmount, otherwise 0." - "Create a column that flags a row as 'Late' if
Due Datepassed today andCompletedis unchecked." - "Extract the domain part of the
Emailfield." - "Set
bonusto 10% ofsalaryonly whenStatusis 'active'."
What to cover
Design the full system end to end. Walk through:
-
Architecture. Components (client, orchestrator, LLM layer, schema service, validators, write executor, observability) and how data flows through them.
-
Formula generation strategy. How you prompt the model, why a typed intermediate representation (IR) is better than asking the model to emit raw formula text, and how the IR gets compiled deterministically into a formula string.
-
Output contract. What the system returns beyond the formula itself — explanation, assumptions, sample test cases — and how those are generated and verified.
-
Schema grounding and type checking. How you pass the live schema to the model, prevent hallucinated field names or functions, and enforce type correctness.
-
Ambiguity resolution. When and how to ask clarifying questions (e.g. two fields that could both match "salary", an underspecified date boundary), and how to carry state across a multi-turn refinement loop.
-
Validation before any write. Both static (parse to AST, type-check, lint) and dynamic (sandbox evaluation on sampled rows) checks, and a bounded repair loop that feeds errors back to the model.
-
Applying changes to the live table. Two execution modes — (a) creating/updating a formula-typed column and (b) materializing computed values into a regular column — with a preview diff and explicit user confirmation gating any destructive write.
-
Safety. Prompt-injection defense, credential isolation (the LLM never sees API keys), PII redaction in samples, a capability whitelist, and confirmation gates for bulk or destructive operations.
-
Latency and reliability. How to hit a P95 of ~2–3 s for the suggestion, and how to handle API rate limits, retries, and partial failures during bulk writes.
-
Evaluation. Offline metrics (AST equivalence, execution accuracy on labeled test rows, validation pass rate) and online metrics (acceptance rate, edit distance, turns to success, post-apply undo rate).
-
Key failure modes. Hallucinated fields/functions, operator precedence bugs, null/blank handling, type mismatches, locale quirks (percentages, currency), timezone edge cases, and schema changes between preview and apply.
Hints
Hint 1
Before describing components, pin down the hardest constraint: the table product's API may not support creating formula-typed fields, which makes materialization a first-class path, not a fallback. That shapes the whole write path.
Hint 2
Ask the model to emit a structured JSON AST (an IR), not a raw formula string. Constrained decoding over an enum of real field IDs and a whitelist of functions prevents hallucination by construction, and a deterministic compiler handles all quoting, bracing, and parenthesization.
Hint 3
The repair loop (feed structured validation errors back to the model) should be bounded at 2 iterations and should escalate to a larger model on the first failure. Returning a broken formula silently is worse than returning an 'unsupported' status with a clear reason.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify scope and constraints first
Before drawing any boxes, surface the constraints that shape the design.
Users: non-technical builders. Correctness and explainability matter more than raw capability.
Scope for v1: single-table formulas only; cross-table lookups and rollups are out of scope. Output is a formula string, an explanation, and test cases. Optionally apply the change.
Scale assumptions:
- ~1M weekly active users, ~5% using this feature → ~500k requests/day, peak ~20 QPS.
- Tables up to ~500 fields, ~100k rows.
Critical API constraints:
- Rate limit: ~5 requests/sec per base; 429s carry a 30s penalty.
- Batch writes: capped at 10 records per call.
- Formula-field creation via the public API may not be supported depending on tier. Verify this early — it determines whether mode (a) is even available, and is why materialization must be a first-class path, not a fallback.
Latency target: interactive P95 of 2–3 s for the suggestion. Bulk writes can be async.
2. End-to-end architecture
Client UI
│
▼
Orchestrator API
├── Schema Service (Airtable connector; cache keyed by schema hash)
├── LLM Gateway (small model first; escalate to large on failure)
├── IR Compiler + Static Validator (parser, type checker, linter)
├── Sandbox Evaluator (formula interpreter on ~20 sampled, redacted rows)
└── Write Executor (Airtable API; whitelist, idempotency keys, batching)
│
└── Observability (traces, redacted prompt logs, metrics, eval store)
Request flow (seven steps):
- User sends a request with
baseId/tableId. - Orchestrator fetches the schema summary (cache hit) or calls the Airtable API (miss).
- Sample ~20 rows; redact PII.
- Call the LLM for a typed IR (not raw formula text).
- Compile the IR; run static then dynamic validation.
- Stream the explanation and row preview to the client.
- Only after explicit user confirmation does the Write Executor touch the base.
The LLM never holds credentials. It emits structured intents; server-side tools execute them.
3. Formula generation with a typed IR
Why IR over raw text: asking the model to emit raw formula strings leads to quoting bugs, wrong brace syntax, incorrect operator precedence, and hallucinated field names. A typed JSON AST is a better target because:
- Constrained decoding. JSON Schema mode restricts
fieldto an enum of real field IDs andopto a whitelist of supported functions. The model cannot invent either. - Correct syntax by construction. A deterministic compiler handles all
{Field Name}bracing, string quoting, escaping, and parenthesization. Precedence bugs disappear. - Type-checkable before any string exists. The tree carries
output_typeat every node. - Rename-resilient. Store field IDs in the IR; resolve to current display names at compile time.
Example IR for "If Status is Won and Amount > 1000, return 10% of Amount, else 0":
{
"op": "IF",
"args": [
{"op": "AND", "args": [
{"op": "=", "args": [{"field": "fldStatus"}, {"lit": "Won", "type": "text"}]},
{"op": ">", "args": [{"field": "fldAmount"}, {"lit": 1000, "type": "number"}]}
]},
{"op": "*", "args": [{"field": "fldAmount"}, {"lit": 0.1, "type": "number"}]},
{"lit": 0, "type": "number"}
],
"output_type": "number"
}
Prompt contents: compact schema as (field_id, name, type, options) (single-select options included for exact matching), function whitelist with type signatures, 3–5 few-shot examples retrieved by similarity, and redacted sample rows.
4. Output contract
class Suggestion:
status: Literal["ok", "needs_clarification", "unsupported"]
formula: str # compiled formula string
ir: dict # typed AST
output_type: str # number | text | bool | date | ...
explanation: str # 1–3 plain-language sentences
assumptions: list[str] # e.g. "Blank Salary → result is blank"
test_cases: list[dict] # {inputs, expected} including one blank/edge row
clarifying_question: str | None
options: list[str] | None # candidate interpretations when ambiguous
The model proposes test cases; the sandbox computes their actual values. A mismatch is a strong error signal worth surfacing to the user.
5. Ambiguity handling
Return needs_clarification when the top two candidate interpretations diverge meaningfully, or when string similarity is high for multiple field names (e.g. Base Salary vs Salary (USD) for "salary").
Rules:
- Ask one question at a time, with buttons not free text where possible.
- Keep session state (IR, chosen field IDs, assumptions) so follow-ups modify the existing IR rather than regenerating from scratch.
- Prefer a stated assumption over a question when the risk of a wrong default is low — this keeps the clarification rate down and the flow fast.
6. Validation before any write
Static checks (in order):
- Compile IR to formula string.
- Re-parse the string with an independent grammar; compare the resulting AST to the IR (round-trip check).
- Verify every referenced field ID exists in the current schema.
- Run the type checker against function signatures.
- Lint for known pitfalls: division without a zero guard, arithmetic on nullable fields, comparing a single-select value to a literal not in its option set.
Dynamic checks: run a faithful interpreter of the formula language over ~20 sampled rows. Deliberately include rows with blanks, zeros, and boundary values. Catch #ERROR, NaN, divide-by-zero, all-blank output, and type drift.
Repair loop:
- On failure, send the structured error message back to the model (e.g., "field fldX has type text;
*requires number; sample value was 'N/A'"). - Cap at 2 repair iterations. Escalate to the larger model on the first failure.
- If repairs exhaust, return
status: "unsupported"with the reason. Never silently return a broken formula.
7. Applying changes
Both modes share the same front end: a preview diff on ~10 rows showing current → new values, plus aggregate counts ("affects 8,412 records; 37 will be blank"). User must confirm before anything is written.
Mode (a): formula-typed column (preferred, non-destructive). Create a new formula field or update an existing one. Computed values stay dynamic and can be undone by deleting the field.
Mode (b): materialize values into a regular column. Used when formula fields are not supported for the target column type. Write values in batches of 10 records with idempotency keys, exponential backoff on 429/5xx, and partial-failure reporting (failed record IDs returned to the client).
Gate mode (b) behind an explicit second confirmation because it overwrites existing data.
8. Safety
- The LLM emits intents only; a server-side tool executes them after whitelist checks.
- Treat all user-provided text as untrusted. Sanitize it before interpolating into prompts to limit injection surface.
- Redact PII from sampled rows before they enter any prompt.
- Enforce a capability whitelist: read schema, read rows, create formula field, update formula field, write values to existing field. Schema deletions and cross-table changes are out of scope and rejected at the tool layer.
- Gate any bulk write above a configurable row threshold and any overwrite of a non-formula field behind explicit confirmation.
9. Latency and reliability
To hit the 2–3 s P95 target:
- Cache schema summaries keyed by schema hash; invalidate on webhook or TTL.
- Use a small/fast model on the first pass; escalate to a larger model only on repair.
- Stream the explanation to the client while the formula finalizes.
- Cap repair iterations (see §6) to bound worst-case LLM call time.
For writes: idempotency keys on every Airtable request, exponential backoff with jitter on 429/5xx, batch size ≤ 10, async job for tables over ~500 rows with progress streaming.
10. Evaluation
Offline:
- A labeled dataset of
(schema, request) → expected formula, scored by AST equivalence and execution accuracy on held-out test rows. - Validation pass rate (static + dynamic) on the generated formulas.
- Repair success rate and mean iterations to success.
Online:
- Acceptance rate (formula inserted without edits).
- Edit distance between suggestion and final submitted formula.
- Clarification rate and average turns to success.
- Preview-to-apply conversion rate.
- Post-apply undo or correction rate (the highest-signal quality metric — it means the formula was wrong in production).
11. Key failure modes
| Failure | Mitigation |
|---|---|
| Hallucinated field names or functions | Constrained decoding over real field IDs and function whitelist |
| Operator precedence bugs | Deterministic compiler, not model-generated strings |
| Null/blank handling | Linter flags nullable arithmetic; IR includes explicit BLANK() nodes |
| Type mismatches (text vs. number) | Static type checker before any string is emitted |
| Locale quirks ("10%" → 0.1, currency symbols) | Normalize literals in the IR compiler; cover in few-shot examples |
| Timezone ambiguity | Ask clarifying question; default to base timezone with stated assumption |
| Schema changes between preview and apply | Re-fetch and diff schema at apply time; use field IDs, not names |
| Prompt injection via cell values | Redact sample rows; do not interpolate raw cell values into instruction context |