TiDonna — AI Assistant & Invoice Engine

A role-scoped AI assistant over a live B2B telecom portal, and a serverless AWS engine that generates outgoing membership invoices and ingests incoming provider invoices with provable text provenance.

Stack:
Laravel, React, Node.js, AWS (Lambda, S3, SES, DynamoDB, EventBridge), OpenAI, Anthropic
Status:
Live platform; ongoing improvements
Role:
Generative AI Developer, ElevateCode IT Services
Deep Dive:
Read Context & Guardrails Blog

Overview

TiDonna is a business-to-business telecom platform (116 customers, 4,354 contracts). Customers manage contracts, devices, support tickets, memberships, and invoices through a web portal; internal staff manage the same data through an admin application.

Two problems were in scope. First, customers wanted to ask questions about their own data in plain language instead of navigating multi-tab tables, which meant putting an LLM next to commercial data that customers must never see in full, such as provider pricing, margins, and internal commissions. Second, invoicing was manual on both sides: outgoing membership invoices were assembled by hand from free-text German pricing notes, and incoming provider PDFs arrived by email with no automated line reconciliation.

I joined an existing production platform rather than starting greenfield, so both systems had to ship without breaking existing portal endpoints.

69% → 91% Live hand-graded assistant pass rate (60/87 to 79/87)
21 / 21 Confidentiality & adversarial cases clean
210 + 96 PHPUnit assistant tests + Jest invoice test files
16 Lambdas Serverless AWS invoice, SES ingestion & report stack

My contribution

The portal, its MySQL data model, and its existing controllers were already in place. What I built:

  • Assistant Data Layer (ADL): A gateway that resolves caller scope from the Sanctum session token, delegates to existing portal controllers, filters fields against per-tool allow-lists, and returns a summary plus a dataset reference rather than raw rows.
  • Two-tier guard stack: A central forbidden-field registry and fail-closed ForbiddenScanner on tool payloads, plus ReplyGuard to compare figures in the drafted reply against retrieved provenance.
  • Provider-agnostic LLM seam: Unified LlmProvider driver over Anthropic and OpenAI with prompt-cache accounting and a fail-closed check on EU inference residency (inference_geo=eu).
  • Deterministic dataset operations & guarded CSV exports: Count, sum, group-by, filter, sort, and top-n run in PHP over cached rowsets; CSV exports use locale-aware formatting, spreadsheet-injection guards, and short-lived owner-scoped links.
  • Second principal on one guard stack: Extended the assistant to internal staff under an inverted disclosure policy while separating cache namespaces by actor type (preventing customer/employee ID collisions).
  • Serverless invoice engine & duplicate-send gate: Monthly German pricing-note parsing, credit notes for cancellations, SES-to-S3 PDF ingestion with coordinate-anchored extraction, integer minor-unit math, and content-fingerprinted dispatch authorization.

Architecture

1. Assistant Data Layer & Two-Tier Guard Boundary

Diagram 1: Reference-Handle Assistant Pipeline (Customer & Staff) Raw Rows Never Enter Model Context
TiDonna Assistant Data Layer and Guard Pipeline Shows browser sending question with Sanctum token, chat service invoking LLM with only tool arguments, gateway calling real portal controllers, allow-listing and ForbiddenScanner checking payloads, caching full rows server-side, returning summary and dataset reference, ReplyGuard validating reply figures, and browser downloading full table and CSV directly from backend. React Portal Sanctum Token 10/min · 100/day Question + Locale Chat Service Bounded Tool Loop Claude / OpenAI EU residency fail-closed tool args ASSISTANT DATA LAYER (SERVER ONLY) Portal Controllers Token scope (never LLM arg) Tier A Guard Allow-list + Scan Owner-Bound DatasetCache (Redis) PHP ops: count · sum · group_by · sort · top_n · CSV summary + dataset_ref + <= 5 rows Tier B: ReplyGuard Checks numbers & claims in reply against retrieved provenance Direct Backend → Browser Data Full table fetched via dataset_ref export_id → signed 600s CSV (DE/EN)
The answer, the UI data table, and the CSV file are three views of a single role-filtered dataset stored in Redis. The LLM routes tools and phrases answers; it never holds raw business records or performs arithmetic.
Anti-Pattern (Avoided)

Pass full SQL rows into the prompt

Dumping raw contract or invoice arrays into model context sends commercial margins and PII to third-party APIs, explodes token spend, and breaks totals on LLM arithmetic.

Shipped Pattern (ADL)

Pass an opaque dataset_ref handle

The gateway stores full scoped rows under actorKey:ref and returns only summary stats, column names, and ≤ 5 preview rows. Deterministic PHP code computes sums and CSVs.

Sanitized Gateway Envelope Returned to Model JSON Contract
{
  "dataset_ref": "ds_8f91c2a4",
  "row_count": 48,
  "columns": ["contract_id", "tariff", "status", "monthly_net_eur"],
  "aggregates": { "sum_monthly_net_eur": "1420.80" },
  "preview_rows": [ "...at most 5 sanitized, allow-listed rows..." ],
  "export_id": "exp_3d02b1"  // Signed download URL minted only at UI click time
}

2. Serverless Invoice Engine & Duplicate-Charge Gate

Diagram 2: Outgoing Billing & Incoming Provider PDF Ingestion (AWS SAM) 16 Lambdas · DynamoDB · S3 · SES
TiDonna Serverless Invoice Engine Flows Top track shows EventBridge monthly batch parsing German pricing notes, running integer minor-unit review checks, binding approval to content fingerprint, and claiming dispatch atomically before SES email send. Bottom track shows SES inbound email routed from S3 into layout-preserving PDF modeling, coordinate-anchored extraction where printed text overrides model guesses, and MSISDN verification. MODULE 1 · OUTGOING MEMBERSHIP INVOICES (25TH MONTHLY BATCH) EventBridge SEPA batch run DE Notes Parser Structured Outputs + Price diff explain Review & Hash Integer minor units HMAC content fingerprint Send Boundary Gate DynamoDB atomic claim Ambiguous = "unknown" MODULE 2 · INCOMING PROVIDER PDF PIPELINE SES → S3 MIME + slug route PDF Page Model Digital/scan/mixed Preserves coordinates Anchored Extract Page, line & section Printed text wins Verification Engine MSISDN reconciliation Flags diffs for review
Two serverless workflows backed by a single DynamoDB table and versioned S3 buckets hardened against accidental expiry.

Engineering decisions

Keep full datasets server-side and hand the model a reference

Problem: Putting retrieved rows directly into model context leaks commercial data to external providers, increases token cost linearly with table size, and leaves totals at the mercy of model arithmetic.

Approach: The gateway caches the full role-scoped rowset behind an owner-bound Redis handle and hands the model only a summary, reference token, columns, and up to five preview rows. Aggregation runs in deterministic PHP over cached rows.

Tradeoff: New analytical questions require defining explicit tool operations rather than tweaking prompt prose, in exchange for reproducible math and strict data containment.

Trace every extracted invoice value back to the printed document

Problem: An LLM reading a PDF produces plausible values even for missing fields. In B2B billing, a confidently wrong amount is worse than a missing one.

Approach: A layout-preserving page model captures text coordinates across digital, scanned, and mixed pages without chunk-splitting loss. Every extracted figure is anchored to printed text with page, line, and section provenance, and printed text overrides model proposals. Currency is computed in integer minor units.

Tradeoff: Layouts that defeat anchoring raise a human review flag instead of guessing, prioritizing correctness over silent automation.

Bind approval to invoice content, and gate sending at the boundary

Problem: Approval tied to an invoice ID stays valid after edits, and guards sitting in controller handlers get bypassed by batch scripts or regeneration jobs.

Approach: Reviewer approval is cryptographically bound to a fingerprint of the invoice content, so edits drop approval automatically. Dispatch checks run inside the email service itself with conditional DynamoDB claims, and ambiguous SES outcomes record as unknown rather than failed so retries cannot double-bill.

Tradeoff: Any edit forces re-approval, which introduces friction by design.

Tips & tricks from building TiDonna

TIP 01 · PROMPT TRAP

Never put real-looking domain figures in few-shot examples

During live evals, the assistant answered a user question without calling a tool because it mistook numbers in a worked system-prompt example for live database records.

Fix: Replace concrete numbers with abstract placeholders and enforce a unit test verifying zero real figures exist in the cached prefix.

TIP 02 · LEAK-02

Strip signed URLs before tool responses reach the LLM

Signed CSV download links returned by the export tool were initially sent back to the LLM provider on every turn.

Fix: Hand the LLM only an opaque export_id and let the frontend mint the short-lived signed URL at click time.

TIP 03 · TEXT IDENTITY

Normalize diacritics when deduplicating billing lines

German display strings like 24 Verträge vs 25 Verträge need umlaut folding and quantity normalization so line identity checks detect duplicate obligations.

Fix: Build canonical billing keys in invoiceLineIdentity and reconcile totals in integer minor units.

TIP 04 · RETENTION GUARD

Test infrastructure templates against accidental data deletion

An unscoped 90-day S3 lifecycle rule once destroyed 241 invoice PDFs across 43 customers.

Fix: Replace expiry with prefix-scoped storage-class transitions, disable DynamoDB TTL, and write Jest tests over template.yaml.

Validation & live evaluation

Live Evaluation Progression (20 August 2026 · 87 Hand-Graded Questions) Database-Verified Grading
TiDonna 87-question live evaluation results Bar chart showing pass rate improving from 60 of 87 (69 percent) to 79 of 87 (91 percent) with 8 partial results, zero outright failures, and 21 of 21 confidentiality and adversarial cases passing. Baseline pass rate: 60 / 87 (69%) Post-fix pass rate: 79 / 87 (91%) · 8 partial · 0 outright failures Confidentiality & adversarial subset: 21 / 21 clean · 16 baseline misses traced to 9 root causes
Every failing answer in the baseline run was root-caused against logs and database state, repaired once in shared code, and locked with a PHPUnit regression test.

Automated tests

  • 210 PHPUnit assistant tests (661 assertions) covering allow-list snapshots, ForbiddenScanner, owner-bound cache keys, CSV export bytes, and EU inference envelopes.
  • A real-controller tenant-isolation test driving the actual controller (replacing an earlier mock-controller test) that asserts a cross-tenant canary value is absent from gateway results, cached datasets, export payloads, and downloaded CSV bytes.
  • 96 Jest files on the invoice engine with a 70% coverage gate, golden document fixtures, and IaC retention guard tests.

What this number does and does not mean. The 69% → 91% result measures the assistant on one 87-question set, on one date (20 August 2026), in one configuration. It is not a general accuracy claim across all providers or users, and it does not measure the separate invoice parser.

Not yet proven

Cross-provider parity on invoice extraction remains documented as unproven without live keys for every transport and an annotated ground-truth PDF corpus. The evaluation harness outputs graded reports locally and is not yet wired as a mandatory CI merge gate.

Outcome

  • Both customers and internal employees use working assistants over one shared guard stack with inverted disclosure policies.
  • Live evaluation pass rate rose from 60/87 (69%) to 79/87 (91%) with 21/21 confidentiality and adversarial cases passing.
  • Monthly membership invoicing runs on schedule with German price-change explanations and audit credit notes, at a documented unit cost of ~$55–70/month in prompt-cached AI parsing for ~1,740 monthly invoice emails.
  • Every email-sending code path routes through one authorization and atomic claim step.

Current status and limitations

  • SSE response streaming and a written conversation-retention policy are in progress; responses currently return complete after both guard tiers finish.
  • Production Redis and dedicated FPM pool provisioning for shared assistant state is complete in code and pending environment rollout.
  • ReplyGuard blocks hard leakage rules and logs soft rules until eval evidence justifies promoting them to blocking.
  • One planned support-handoff tool is specified but intentionally blocked with a regression test so the assistant invents no contact numbers until the client supplies them.
  • Invoice extraction fidelity has a target but no annotated ground-truth corpus yet, so that target is reported as a goal rather than a result.

Client work in a private repository; no public code or demo. I am happy to walk through the guard architecture, evaluation harness, or invoice pipeline in an interview.

Related reading & case studies

Email Sunny.work70@gmail.com or connect on LinkedIn.

Back to selected projects Download resume (PDF)