1. Why dumping SQL rows into context breaks in production
The fastest prototype for any database assistant is straightforward: run a query, serialize the JSON array into a tool response, and let the LLM answer questions and compute totals. On a multi-tenant B2B telecom platform with 116 customers, 4,354 contracts, wholesale margins, and commission tables, that naive architecture creates three immediate failures:
- Confidentiality & GDPR exposure: Raw rows sent to external model providers include internal fields unless explicitly stripped per endpoint, and even allowed fields expand the provider data-processing surface.
- Unreliable arithmetic: Asking an autoregressive language model to sum 48 recurring EUR contract lines or group devices by tariff status introduces subtle rounding and counting drift.
- Context pollution & cost: Large tables crowd out tool rules and explode prompt token cost on every follow-up turn.
"In every industrial-strength LLM app, context engineering is the delicate art and science of filling the context window with just the right information for the next step."
Return rows[] to the model
Model sees full table rows, sums EUR totals via token prediction, and receives signed export URLs in its conversation trace.
Return {summary, dataset_ref, preview}
Full rows live in owner-bound Redis. Application code executes
count/sum/group_by/sort; UI pulls full tables directly by handle.
2. Architecture: The Assistant Data Layer (ADL)
Instead of building a parallel database layer for AI, the Assistant Data Layer delegates to the exact same Laravel portal controllers used by the React frontend, passing identity derived strictly from the caller's Sanctum token (never from a model tool argument).
query_dataset filters/sorts the cached PHP array and mints a fresh child
dataset_ref without ever re-querying the LLM over raw rows.Anthropic's engineering team puts the tool-design principle well:
"One rule of thumb is to think about how much effort goes into human-computer interfaces (HCI), and plan to invest just as much effort in creating good agent-computer interfaces (ACI)."
Designing the ACI meant deriving tool parameter schemas directly from the exact PHP config
that the gateway enforces, keeping prompt prefixes byte-stable (~1,500 cached tokens), and
sharing one guard stack between customer and internal employee principals via an
AssistantPrincipal interface (which also caught a cross-table integer ID
collision between cust:5 and emp:5 before launch).
3. Cutting the Lethal Trifecta: Two-Tier Guards & LEAK-02
"The lethal trifecta for AI agents: private data, untrusted content, and external communication. ... the only way to reliably prevent that class of attacks is to cut off one of the three legs!"
Every tool call passes through two independent deterministic checks before anything reaches the user:
- Tier A (Payload Gate):
AssistantArr::pick()keeps only allow-listed columns per tool, thenForbiddenScannerscans recursively against a central registry (margins, wholesale prices,ti_share, internal ticket notes, staff HR fields) and aborts the entire request if a forbidden key ever appears. - Tier B (
ReplyGuardProvenance Check): Before the final response leaves the backend,ReplyGuardchecks figures in the drafted prose against the data actually retrieved in that turn to catch hallucinated numbers. (This also caught a real two-way substring match bug and German phone-shaped dates during testing.) - Fixing LEAK-02: An early export implementation returned a signed
CSV download URL inside the tool payload, meaning the LLM provider received a live
authenticated download URL on every export turn. We stripped all URLs from tool
outputs and handed the model an opaque
export_idinstead; the browser mints the 600-second owner-scoped URL on click.
4. Eval Teardown: Lifting Pass Rate from 69% to 91%
"I've seen many successful and unsuccessful approaches to building LLM products. I've found that unsuccessful products almost always share a common root cause: a failure to create robust evaluation systems."
On 20 August 2026, I ran 87 real customer-style questions against the production assistant configuration and hand-graded every answer against the governing prompt rule and raw database state. The baseline run scored 60 / 87 (69%). Inspecting all 16 outright wrong answers revealed 9 distinct root causes rather than random model noise:
- The worked-example hallucination trap: One system prompt example contained realistic sample numbers. The model treated those example numbers as live tenant records and answered directly without invoking any tool. Fix: purge concrete figures from prompt examples and add a PHPUnit assertion failing CI if real figures ever reappear in the cached prefix.
- Lookup & multi-match ambiguity: Phone/contract lookups needed explicit clarification behavior when multiple records matched, rather than guessing the first row.
- Fake-controller test blind spot: A seven-lens adversarial review exposed that our earlier tenant-isolation suite ran against a stubbed controller. We rewrote it to drive the real controller and assert a canary token is absent from gateway output, Redis cache, export payload, and the final CSV bytes.
5. Actionable Tips & Tricks Checklist
Prefix cache names with principal type
Use cust:5 and emp:5 instead of bare numeric IDs so
multi-table principals can never collide in shared Redis.
Pin EU residency fail-closed
If inference_geo=eu is absent or unverified on a strict tenant, fail
with HTTP 503 rather than falling back silently to a US endpoint.
Guard CSV formulas against injection
Prefix spreadsheet cell values starting with =, +,
-, or @ when generating server-side CSV exports.
Keep eval scopes honest
Never extrapolate one 87-question assistant evaluation to separate subsystems like PDF invoice extraction, which requires its own corpus.
Read full TiDonna case study Next article: Voice AI Control Planes →