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."
Andrej Karpathy, Context Engineering (June 2025)
Naive Tool Pattern

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.

Production ADL Pattern

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).

Reference-Handle Data Separation Answer, Table & CSV Share One Scoped Cache
Reference Handle Pattern Diagram Shows gateway delegating to portal controller, scanning fields, storing full rowset in Redis under actorKey:ref, sending only summary and 5-row preview to LLM, and serving full table and CSV directly to the browser. Portal Controller Scope from token Allow-list + Scan DatasetCache[actor:ref] 100% scoped rows in Redis query_dataset ops in PHP LLM (Claude / OpenAI) summary + ref + <= 5 preview rows EU residency fail-closed (503) Browser Direct Fetch & Export UI renders full table by dataset_ref · CSV built server-side via export_id (600s signed link)
When a user asks a narrowing question ("top 5 by monthly cost"), 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)."
Anthropic Engineering, Building effective agents

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!"
Simon Willison, The lethal trifecta for AI agents

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, then ForbiddenScanner scans 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 (ReplyGuard Provenance Check): Before the final response leaves the backend, ReplyGuard checks 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_id instead; 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."
Hamel Husain, Your AI Product Needs Evals

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.
60 → 79 / 87 Pass count after 9 root-cause fixes (69% → 91%)
0 Fails Outright errors post-fix (8 partial cases remain)
21 / 21 Confidentiality & adversarial probes clean

5. Actionable Tips & Tricks Checklist

CHECK 01

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.

CHECK 02

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.

CHECK 03

Guard CSV formulas against injection

Prefix spreadsheet cell values starting with =, +, -, or @ when generating server-side CSV exports.

CHECK 04

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 →