Tandem — Measure, Don't Guess
Every hybrid-AI app hardcodes a guess: "short and simple goes on-device, long and hard goes to the cloud." Tandem replaces the guess with measurement.
🌐 Live: tandem-hybrid.web.app (no sign-in)
📝 Notes app: tandem-hybrid.web.app/notes/
💻 Code (Apache-2.0): github.com/Madhavan20906/Tandem
Platform: Web (Chrome desktop) · Built on Firebase AI Logic hybrid inference: Gemini Nano in Chrome on-device, gemini-3.5-flash-lite in the cloud
Inspiration
Firebase AI Logic hybrid inference solved a hard problem with one line of configuration: run Gemini Nano inside Chrome when it is available, and fall back to the cloud when it is not.
But "is a local model available?" is only the first question. The next one, the one every developer actually ships with, is:
Which of my tasks can the on-device model do well enough, on which devices, at what latency cost, and what must never leave the device at all?
Today that question gets answered with a hardcoded heuristic: prompt shorter than N characters → local, otherwise → cloud. Nobody checks it. If it is too optimistic, users get broken JSON, missing facts or a fluent wrong answer from the local model. If it is too pessimistic, the app pays for cloud calls, sends private text off the machine, and stops working offline, for tasks the local model would have handled fine.
We noticed the same gap from a second angle. Many people in India keep tax notes, invoices and forms on a laptop, and those notes are full of PAN, Aadhaar, GSTIN and UPI identifiers. For them, "which model should answer this?" is a privacy question as much as a quality one. A routing heuristic based on prompt length has no idea what is in the prompt.
So we set out to build a tool that answers the routing question with evidence, keeps privacy as a hard constraint, and proves every routing decision afterwards.
What it does
Tandem is one engine with three faces: you measure in Studio, ship through Remote Config, and use it through the Router SDK (demonstrated by Notes).
1. Tandem Studio: measure, then compile a policy
Studio has five stages: Probe → Frontier → Policy → Deploy → Atlas.
- Device check. Asks Firebase AI Logic whether this Chrome can run Gemini Nano, then proves it by running a real
ONLY_ON_DEVICErequest and readinginferenceSourceback from the SDK. If Nano is not available, the screen says exactly why (not downloaded, unsupported browser, insufficient hardware) and how to enable it. - Probe. Two lanes race identical synthetic tasks: one forced on-device (
InferenceMode.ONLY_ON_DEVICE), one forced to the cloud (InferenceMode.ONLY_IN_CLOUD). The battery covers 8 task types (classify, extract, instruction-following, JSON reliability, QA, rewrite, summarise, translate) × 3 input lengths. Each answer is streamed so we capture time-to-first-token and total latency, then scored by deterministic validators: JSON schema, required facts, length bounds, refusal detection and output script/format. A Quick probe runs in about two minutes; a Full probe repeats each cell for statistical power. - Frontier. Shows, per task type and input length, where the local model matches the cloud and where it falls behind, both on quality and on latency.
- Policy. Compiles the measurements into a routing policy, and every rule carries its evidence: sample size n, local and cloud pass rates, the Wilson 95% lower bound, p50/p95 latency and estimated cloud tokens avoided. Click any rule to see why it went local-first or cloud-first. A policy diff shows which rules flipped between two runs, and a savings simulator estimates cloud cost for a workload mix. These are explicitly labelled estimates, using price constants held in Remote Config.
- Deploy. Exports the policy as
tandem_policy_v1into Firebase Remote Config. Every open app listening withonConfigUpdatepicks up the new policy in real time, with no redeploy. - Atlas. An opt-in, anonymous, coarse-bucketed map of which devices can actually run on-device AI and how fast, built from probe results with Firestore aggregation (
getCountFromServer). One laptop is not the world, and Atlas is our honest answer to that.
If your machine cannot run Nano, nothing breaks. The probe runs cloud-only and says so, and a clearly labelled Reference Run ("Measured on the author's machine, 27 Nov 2026, Chrome 158") fills every chart and policy view.
2. Tandem Router: the SDK that uses the policy at runtime
import { createTandem } from '@tandem/router';
import { TandemAI } from '@tandem/ai';
const tandem = createTandem({ ai: new TandemAI(firebaseApp), policy: remoteConfigPolicy });
const { output, receipt } = await tandem.run({ task: 'summarize', input: note });
// receipt.route: LOCAL | CLOUD | CLOUD_REDACTED | BLOCKED
// receipt.servedBy comes from the SDK; receipt.why comes from measured evidence
Every call goes through one pipeline:
Guard scan → policy lookup → dispatch (local or cloud) → validate → escalate? → rehydrate → receipt
The router separates two different reasons to use the cloud, which most hybrid apps conflate:
| Availability fallback | Quality escalation | |
|---|---|---|
| Trigger | The local model could not run (not downloaded, unsupported) | The local model ran, but its answer failed a validator |
| Who handles it | The Firebase SDK already does this | Tandem adds this |
| Receipt field | availabilityFallback: true + reason |
qualityEscalation.happened: true + which check failed |
Every request produces a receipt recording the route, servedBy (read from the SDK, never assumed), why (the policy rule and its evidence), Guard findings, validator results, timing and token counts. Receipts are SHA-256 hash-chained, so editing any past receipt breaks the chain.
3. Tandem Notes: a real app built only on the router
A private, local-first notes app (summarise, rewrite, extract tasks, translate, ask my notes) that uses nothing but @tandem/router. Every result shows a badge for where it ran (ON-DEVICE or CLOUD), why it ran there, and exactly what, if anything, left the device. It exists to prove the SDK is usable for a real product, not just a dashboard.
4. Tandem Guard: privacy as a routing constraint
Before any model sees a prompt, Tandem Guard scans it for Indian personal identifiers: Aadhaar (with Verhoeff checksum), PAN, GSTIN, IFSC, UPI IDs, bank accounts (context-anchored), phone numbers, passport, voter ID, driving licence and vehicle numbers, plus email, payment cards and names. It catches disguised identifiers too: Indic and fullwidth digits, spacing and line splits, zero-width characters, Cyrillic look-alike letters, spelled-out digits and base64.
When something sensitive is found, the content stays on-device. If no local model is available, it is sent redacted only with explicit per-request consent, and otherwise it is blocked. It is never silently sent.
Input: My PAN is BQKPS4821L and Aadhaar 4712 0938 5618
Redacted: My PAN is [PAN_1] and Aadhaar [AADHAAR_1] ← only this reaches the cloud
Rehydrated: the real values are restored locally, then a leak verifier re-checks the output
Guard Lab runs a 263-case adversarial corpus against the redactor live in your browser, scored by an independent oracle that shares no code with the detectors.
How we built it
Architecture
Studio (measure) Notes (use)
Probe → Frontier → Policy → Atlas summarise · rewrite · extract · translate · ask
│ │ │ │
@tandem/bench @tandem/policy ──── Remote Config ───► @tandem/router ── receipts (SHA-256 chain)
(tasks, (Wilson, rule, tandem_policy_v1 │ Guard → policy → dispatch → validate
validators, diff, export) (real-time) │ → escalate? → rehydrate → receipt
runner) ▼
@tandem/ai (only importer of firebase/ai)
ONLY_ON_DEVICE ─► Gemini Nano (Chrome Prompt API)
ONLY_IN_CLOUD ─► gemini-3.5-flash-lite (App Check)
@tandem/guard = Tandem Guard: detect · redact · leak-verify · rehydrate
It is a TypeScript/ESM pnpm monorepo with six packages, each with one job and its own tests:
| Package | Responsibility |
|---|---|
packages/spec |
Shared JSON schemas and test vectors: the contract between packages |
@tandem/ai |
The only package that imports firebase/ai. Wraps runOnDevice, runInCloud and runPrefer, streams responses, and reads inferenceSource and usageMetadata |
@tandem/bench |
Synthetic task battery, deterministic validators, probe runner |
@tandem/policy |
Pure statistics: Wilson intervals, the rule compiler, policy diff, Remote Config export, savings simulator. No I/O, so it is fully property-testable |
@tandem/guard |
Detect, redact, rehydrate, leak verifier, Guard Lab corpus, SHA-256 hash-chained ledger |
@tandem/router |
Public SDK: createTandem().run() → { output, receipt } |
apps/web |
Tandem Studio (/) and Tandem Notes (/notes/), built with Vite |
Keeping firebase/ai behind a single package means there is exactly one place where "served by" can come from, and it always comes from the SDK.
How Firebase AI Logic is used, mode by mode
ONLY_ON_DEVICE → probe local lane · Gate A on-device proof · Guard-forced routing of sensitive content
ONLY_IN_CLOUD → probe cloud lane · quality escalation · availability fallback target
PREFER_ON_DEVICE → exposed as the SDK's own baseline, for comparison only
The router deliberately does not use PREFER_ON_DEVICE. That mode routes by availability, and Tandem routes by evidence. We pick the mode explicitly per call so the receipt can say truthfully why each request went where it did.
The rest of the Firebase stack (all on the free Spark plan, no Cloud Functions)
- Firebase AI Logic (
getAIwithGoogleAIBackend) for all inference. There are no direct Gemini API calls and no other model providers. - App Check (reCAPTCHA), enforced on AI Logic, so the cloud lane cannot be abused from outside the app.
- Anonymous Authentication to scope per-session writes.
- Cloud Firestore for metadata only (never note content). Rules are owner-only with field whitelists, and Atlas contributions are create-only under
contrib/{sha256(uid)}. The rules are tested in the Firestore emulator in CI. - Remote Config for
tandem_policy_v1, kill switches and price constants, with anonConfigUpdatereal-time listener. - Firebase Hosting at
tandem-hybrid.web.app.
The policy rule, pre-registered
A (task type, input length) cell goes local-first only if all four checks pass:
- Sample size: $n \ge 8$ distinct tasks.
- Quality floor: the Wilson 95% lower bound of the on-device pass rate is at least $0.75$.
- Tolerance: the on-device pass rate is within 5 percentage points of the cloud's.
- Latency: on-device p95 fits the developer's budget (default 8 s for interactive use).
We use the Wilson score lower bound instead of the raw pass rate because it is honest about small samples:
$$ \text{LB} = \frac{\hat p + \frac{z^2}{2n} - z\sqrt{\frac{\hat p(1-\hat p)}{n} + \frac{z^2}{4n^2}}}{1 + \frac{z^2}{n}}, \qquad z = 1.96 $$
With a perfect 12/12, the raw rate says 100%, but the lower bound is $\frac{12}{12 + 3.84} \approx 0.76$. That is a much more honest number to route production traffic on. These thresholds were written down in docs/POLICY_RULE.md before any measurement existed, so we could not tune them to flatter the results.
Measuring honestly
- Gate A (on-device proof). A Playwright harness driving Chrome over the DevTools Protocol ran a Firebase AI Logic
ONLY_ON_DEVICErequest and gotinferenceSource: "on_device", both online and with the network disabled. The raw JSON is committed (eval/results/gate-a-2026-11-26.json). - Calibration and held-out split. The policy is compiled from a 192-run calibration probe, then replayed on 93 held-out tasks it never saw, measured on both models. Rate-limited (HTTP 429) and unavailable runs are recorded in the raw files and excluded from pass rates, never silently dropped.
- One source of truth.
eval/build-results.mjsreads the raw result files and generates the results blocks in the README and on the landing page, so the numbers on the website cannot drift from the data. - CI (GitHub Actions) typechecks every package, builds Studio and Notes, runs the Guard, policy (including property tests), bench and router suites, and runs the Guard benchmarks on both the dev and held-out sets.
What we found when we measured
All numbers below are measured on the author's machine (Intel Core i5-1334U, Intel Iris Xe integrated GPU, 16 GB RAM, Windows 11, Chrome 158.0.8127.38, 26–27 Nov 2026). The raw files are in eval/results/.
Held-out validation (93 tasks):
| Tandem, 8 s interactive budget | Tandem, 30 s background budget | All cloud | All on-device | |
|---|---|---|---|---|
| Tasks passing validators | 97.8% | 100.0% | 97.8% | 93.5% |
| Served on-device | 0% | 86% | 0% | 100% |
| p50 / p95 latency | 1.3 s / 5.3 s | 8.4 s / 17.9 s | 1.3 s / 5.3 s | 10.6 s / 45.0 s |
Three things measurement found that guessing would not have:
- Latency is the constraint here, not accuracy. Gemini Nano passed 12/12 on seven of the eight task types. But on integrated graphics, its median for structured extraction was 20.0 s, against 956 ms in the cloud. At an 8-second interactive budget, the honest policy keeps 0% on-device. At a 30-second budget for background work, 86% stays on-device with 100% passing validators. The developer chooses the budget; Tandem shows what each choice costs.
- Translation breaks on-device. English → Tamil/Hindi passed only 4/12 (33%) on-device against 12/12 in the cloud. A length heuristic would happily send a short translation to the local model. Measurement does not.
- The local model sometimes wins. On rewrite, Nano passed 12/12 while the cloud model passed 9/12 under the same validators. A hardcoded "cloud is always better" rule would have thrown that away.
Tandem Guard: our own 263-case adversarial corpus initially found 108 leaks. After the fixes it reports 259 caught, 2 blocked, 2 missed (bare account numbers inside base64). We show those 2 misses in Guard Lab rather than hide them. This is 0 leaks on nothing: it is 2 known misses on our 263-case corpus.
Challenges we ran into
- The on-device model kept crashing, and the cause wasn't the model. Gemini Nano would fail to load on our laptop. The cause turned out to be the C: drive: with under 1 GB free, Windows had no commit memory left for the model. We moved the measurement Chrome profile and temp directory to another drive, and documented the diagnosis instead of quietly working around it.
- Our own audit caught a fake hash. An early version of the receipt ledger called itself "SHA-256" but was really a 32-bit hash repeated to look like SHA-256. We found it in our engineering audit (
docs/AUDIT.md), replaced it with real SHA-256 (WebCrypto in the browser), and added a test against Node'scryptoso it cannot regress. - Attacking our own redactor. An early claim of "0 leaks" came from a corpus written by the same person who wrote the detectors, so it proved nothing. We wrote an adversarial corpus with an independent oracle, and it found 108 of 263 leaks: spaced and line-split IDs, fullwidth digits, Cyrillic look-alikes, spelled-out digits, base64, unknown UPI handles. The fixes (NFKC normalisation, all Unicode digit blocks, homoglyph folding, a gap-filling detector for split and encoded identifiers) brought it down to 2 misses.
- Statistics vs. reality. A 0.90 Wilson floor sounds rigorous, but you cannot reach it at sample sizes a judge can run in minutes ($n=12$ caps out at about 0.76). We set 0.75 before collecting data, explained why, and relied on runtime validation plus quality escalation as the safety net.
- Latency on integrated graphics. It was uncomfortable to report that our headline interactive policy routes 0% on-device. We decided that is the result, and built the latency-budget view so the trade-off is visible instead of hidden.
- Rate limits and availability in measurement. HTTP 429s and unavailable runs could quietly skew pass rates, so they are recorded explicitly and excluded with a count, never dropped silently.
- Designing every state. Because most judges' machines may not have Nano, every screen needed a real "unavailable" state, plus loading, empty, error, offline and rate-limited states, at 390 px and 1280 px, in light and dark, meeting WCAG AA.
Accomplishments that we're proud of
- A routing decision you can audit. Every rule shows its evidence, and every request shows its receipt. You can verify the SHA-256 chain in the browser, then run the tamper test and watch it break.
- Quality escalation as a first-class idea, kept separate from availability fallback, with distinct receipt fields and badges.
- Pre-registered thresholds and a held-out split. The policy was validated on 93 tasks it never saw, with thresholds fixed before any data existed.
- On-device proven, not assumed.
inferenceSource: "on_device"was recorded with the network disabled, and "served by" in the UI only ever comes from the SDK. - Real-time policy delivery. Publish a new policy in Remote Config and an open Notes tab changes its routing live, with no redeploy.
- A real app on the SDK. Tandem Notes uses only the public router API, which shows the SDK is usable beyond a dashboard.
- Privacy that holds up against disguise. Indian identifiers stay on-device even when written in Tamil digits or hidden behind zero-width characters, and the remaining gaps are published.
- Fully backend-free on the free tier. Everything runs client-side on the Spark plan with no Cloud Functions, and Firestore rules are tested in the emulator on every push.
- Negative results reported. 33% translate, 0% interactive on-device and 2 Guard misses are all on the landing page, not buried.
What we learned
- Measuring beats guessing in both directions. Nano did better than we expected on rewrite and structured extraction, and worse on Indian-language translation. No heuristic based on prompt length would have predicted either.
- On this class of hardware, latency is the real constraint. Accuracy was rarely what kept a task off the device; time-to-answer was. That makes the latency budget a product decision, and it should be an explicit, visible one.
- "Available" and "good enough" are different questions, and they deserve different code paths, receipt fields and UI.
- Small samples need honest statistics. The Wilson lower bound turned "12/12, ship it" into "76% lower bound, let's see". That is the right instinct for routing production traffic.
- Your own test corpus is not evidence. Only an adversarial corpus with an independent oracle told us the truth about the redactor.
- Single sources of truth prevent drift. Generating every published number from committed raw files stopped the website, README and demo from disagreeing with each other.
- The interesting product isn't the model call. It is the evidence around it: what ran where, why, and how you can check.
What's next for Tandem — Measure, Don't Guess
- More devices in the Atlas, so the policy can be compiled per device class (discrete GPU, Apple silicon, integrated graphics) instead of from one laptop.
- Policy-as-CI. Run the Quick Probe in a pipeline whenever an app's prompts change, and fail the build if a local-first rule loses its evidence.
- Richer validators, including an opt-in, capped cloud judge for summary faithfulness, which deterministic checks cannot catch.
- More task types and languages, re-measuring Indian-language translation as on-device models improve.
- Regional Guard packs. Detectors are modular, so identifiers for other regions are an addition, not a rewrite.
- Publishing
@tandem/routerand@tandem/policyas standalone packages, so any Firebase AI Logic web app can adopt measured routing in five lines.
All sample data is synthetic. Cost figures are estimates from Remote Config price constants. Tandem is designed around data-minimisation principles and makes no legal or compliance claim. All code was written during the submission period. AI coding assistants were used during development.
Built With
- chrome
- chrome-devtools-protocol
- chrome-prompt-api
- cloud-firestore
- css3
- firebase
- firebase-ai-logic
- firebase-app-check
- firebase-authentication
- firebase-emulator-suite
- firebase-hosting
- firebase-remote-config
- gemini-3.5-flash-lite
- gemini-nano
- github-actions
- html5
- json-schema
- node.js
- playwright
- pnpm
- recaptcha
- sha-256
- typescript
- vite
- webcrypto