Today
About 50 production call sites reach a model provider, almost all Gemini, and almost all build their owngoogle(...), gateway(...) or
createGoogleGenerativeAI(...) from the shared server key
GOOGLE_GENERATIVE_AI_API_KEY. There is no shared model resolver. Existing
pieces the router reuses:
Goals
- One layer decides model, provider, credential, metering and run recording for every AI request, so BYOK works everywhere without per-feature code.
- No behavior change by default: a workspace with no key and no routing rows gets today’s model, provider and metering.
- The layer is framework-independent: request identity, the key resolver, credits and storage are injected by each app’s adapter, per the repository’s domain-library rule.
Design
New modulepackages/ai/src/routing/, exported as @tuturuuu/ai/routing.
Feature registry
AI_FEATURE_REGISTRY lists every feature key with its capability, default
model, credit feature (an AI_FEATURES value), metering mode and whether BYOK
may serve it:
The
metering field preserves each feature’s current behavior. Routing a
feature through the layer never starts charging credits it does not charge
today; changing a feature from unmetered is a separate product decision.
API
router.run does, in order:
- Resolve the route: the workspace’s feature row, else the registry
default; the model must be in the catalog (
private.ai_gateway_models), pass AI Studio model policy (private.workspace_ai_studio_policies: denied, then allowed) and the plan (resolvePlanModel). - Begin the run (
begin_ai_studio_run). On a BYOK route it takes the zero-credit path, checks the workspace daily BYOK caps and returns the run-scoped proof secret thatkeys.resolveneeds (see proof of use). - For each credential in the fallback order:
byok:keys.resolve(...); on a key, build a direct provider instance (createGoogleGenerativeAI,createOpenAIorcreateAnthropicwith that key and the injectedfetch); no credit reservation; the fee meter counts one request.platform: today’s choice (google(bare)orgateway(id)with the platform key), with the feature’s metering (reservation, then settlement).- Wrap the model with
withAiMemorywhere the feature uses memory.
- Execute. On an error, classify it (see error classes). Move to the next credential only when the class allows it and no output has reached the caller: once a stream has emitted a token, the error is returned, never retried on another credential.
- Settle usage, cost, latency, first-token latency, error class,
credential_sourceandprovider_key_idon the run.
router.credential does the same route, run and key steps, and returns the
key and a settle function to transports that need a raw key: GoogleGenAI in
the Meet Live Durable Object, authTokens.create for web and mobile Live
ephemeral tokens (the browser still receives only the ephemeral token), and
the Gemini TTS fetch.
Ephemeral Live tokens. A token minted with a workspace key is a bearer
credential for that key, so authTokens.create always sets:
uses: 1, so one token opens one session;newSessionExpireTime60 seconds after minting, andexpireTimeno later than the feature’s session limit;liveConnectConstraintspinning the model and the session config (response modality, system instruction and tools) the server chose, so a client cannot redirect the token to another model or enable tools.
fetch uses a fixed
base URL constant in packages/ai/src/routing
(https://generativelanguage.googleapis.com, https://api.openai.com,
https://api.anthropic.com), never a value from configuration, the database
or a request. Keys travel only in headers (x-goog-api-key,
Authorization: Bearer, x-api-key), never as a ?key= query parameter,
and a test asserts that no routed request URL contains a key.
Embeddings
Stored vectors must come from one model and dimension (gemini-embedding-2,
3072 dimensions). BYOK can serve embeddings only with the same model id on the
workspace’s Google key; a route can never switch embeddings to another
provider or model, because mixed vectors break search.
Per-feature model selection
fallback_orderholds one or both ofbyokandplatform, without repeats (a check constraint). The UI offers Workspace key, then platform credits (default), Workspace key only and Platform credits only.- Mira channels with
keyMode: 'byok'force{byok}, matching their rule that a failing tenant key never falls back. - Only service-role definer RPCs read or write these tables, like the key
tables. Every change writes a
routing_changedkey event. - Edit requires
manage_ai_policy, the existing model-policy permission; view requiresmanage_workspace_secretsoruse_ai_studio. - UI: a Per-feature models section in AI Studio → Governance → Model
policy (
/<wsId>/model-policy), beside the allow and deny lists, with one row per feature: model picker (only policy- and plan-allowed models), fallback order, and the provider whose key will be used. The keys tab links to it.
Fallback rules
A request that falls back to
platform needs credits like any platform
request; without them it fails with the usual credit error. A Live session
changes credential only at connect or reconnect, after its gate recheck.
Health check and Test key
- Passive health comes from the hourly usage rollups:
failing: anauthorquotaerror in the last 15 minutes and no success since;degraded: at least 20 requests in the last hour with an error rate of 5 % or more, or 20 % or more rate-limited;healthy: otherwise, when requests exist;unused: no requests for 7 days.
- Test key (
POST …/ai-provider-keys/{provider}/test): the list-models call plus a one-token generation on the provider’s test model (test_model_idonprivate.ai_provider_key_providers, for example the provider’s cheapest text model). It reports success or an error class and the latency, writes atestedevent, is limited to 6 tests per key per hour, and the UI states that it sends one small request billed by the provider. - Recovery probe: after a
quotafailure, a Cron Control job re-tests the key at most once an hour and 3 times a day, with bounded batches, idempotent progress and the job’s stop fence; success writesrestored. Anauthfailure is never probed automatically; only an admin’s Test key or a new key restores it.
Call-site inventory and migration order
Migration is one call site per change, each with routing, fallback and billing tests; unmigrated sites keep working on the platform path.
Out of scope: the Vertex year-plan route, the meeting eval tool, the roadmap
changelog script, and ChatGPT subscriptions, which stay a per-user OAuth path
recorded as
credential_source = 'subscription'.