Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Ensure vertex-gemini anchor is preserved for anonymous callers and during cooldowns in fallback chain

nirholas1f8833a6478d
diff --git a/api/chat.js b/api/chat.js
index c49922ba6..b302cc8ef 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -569,10 +569,17 @@ export default wrap(async (req, res) => {
// Provider/model failover chain. The first entry is the picked route; if it
// returns 429 (rate-limit) or 5xx (provider down) we cycle through a
// pre-built fallback list before surfacing an error.
- let fallbackRoutes = buildFallbackChain(route, userProviderKeys, cooldown);
+ let fallbackRoutes = buildFallbackChain(
+ route,
+ userProviderKeys,
+ cooldown,
+ anonymous ? ANON_PROVIDERS : null,
+ );
// Anonymous traffic must never fail over onto paid providers (OpenAI/
- // Anthropic). Clamp the whole chain to the free-tier anon providers so a
- // rate-limited free model degrades to another free model, never paid keys.
+ // Anthropic). buildFallbackChain already excludes them from the capped chain
+ // for anon callers (via the allow-set above) so they can't evict the free-tier
+ // vertex-gemini anchor; this post-build clamp stays as a defensive no-op in case
+ // the primary route itself is ever non-anon.
if (anonymous) fallbackRoutes = fallbackRoutes.filter((r) => ANON_PROVIDERS.has(r.name));
let upstream;
@@ -1186,12 +1193,21 @@ function eligibleAsFallback(modelId) {
return meta.tools === true && !meta.moderationGated;
}
-export function buildFallbackChain(primary, userKeys = {}, cooldown = new Map()) {
+export function buildFallbackChain(primary, userKeys = {}, cooldown = new Map(), allow = null) {
const chain = [primary];
const seen = new Set([`${primary.name}:${primary.model}`]);
const tryAdd = (name, model) => {
if (chain.length >= MAX_FALLBACK_ATTEMPTS) return;
+ // Honour the caller's allow-set (anonymous traffic → ANON_PROVIDERS only)
+ // BEFORE a capped slot is consumed. Filtering the chain *after* it was built
+ // (the old approach, still kept as a defensive clamp at the call site) let a
+ // paid provider whose host key is present — e.g. OPENAI_API_KEY — take one of
+ // the MAX_FALLBACK_ATTEMPTS slots and then get stripped, which pushed the
+ // credits-funded vertex-gemini anchor out of the chain entirely and 503'd
+ // anonymous chat whenever groq/openrouter/nvidia all throttled at once. The
+ // primary (position 0) is exempt: it is picked upstream and always kept.
+ if (allow && name !== primary.name && !allow.has(name)) return;
const key = `${name}:${model}`;
if (seen.has(key)) return;
if (!eligibleAsFallback(model)) return;
@@ -1220,8 +1236,28 @@ export function buildFallbackChain(primary, userKeys = {}, cooldown = new Map())
tryAdd(name, PROVIDERS[name].defaultModel);
}
- // The chain is bounded to MAX_FALLBACK_ATTEMPTS so a single request can't
- // churn through every provider before timing out.
+ // Guarantee the credits-funded Vertex anchor as the final rung. It is keyless
+ // (GCP credits, no third-party quota) and is the whole reason a failover chain
+ // can promise never to 503 while a healthy quota-free provider exists. Neither
+ // the MAX_FALLBACK_ATTEMPTS cap nor a transient per-provider cooldown may evict
+ // it — both used to (a present paid key filled the cap; a cooldown from one
+ // transient blip dropped it), which is what made anonymous chat 503 whenever the
+ // free lanes throttled together. Appended only when it is available and allowed,
+ // deduped, so it never leads and never doubles up.
+ for (const anchor of ['vertex-gemini', 'vertex']) {
+ if (!keylessVertexAvailable(anchor)) continue;
+ if (allow && !allow.has(anchor)) continue;
+ if (chain.some((r) => r.name === anchor)) continue;
+ const cfg = PROVIDERS[anchor];
+ const model = cfg.defaultModel;
+ if (seen.has(`${anchor}:${model}`)) continue;
+ seen.add(`${anchor}:${model}`);
+ chain.push(makeRoute(anchor, cfg, 'vertex', model));
+ }
+
+ // The chain is bounded to MAX_FALLBACK_ATTEMPTS (plus the guaranteed keyless
+ // anchor above) so a single request can't churn through every provider before
+ // timing out.
return chain;
}
diff --git a/tests/api/chat-vertex-anchor.test.js b/tests/api/chat-vertex-anchor.test.js
index fded89e26..ef07dff54 100644
--- a/tests/api/chat-vertex-anchor.test.js
+++ b/tests/api/chat-vertex-anchor.test.js
@@ -71,4 +71,47 @@ describe('anonymous-chat vertex-gemini anchor wiring', () => {
const chain = buildFallbackChain(primary, {}, new Map());
expect(chain.find((r) => r.name === 'vertex-gemini')).toBeUndefined();
});
+
+ // Production repro: OPENAI_API_KEY is set on the Cloud Run service. The old
+ // buildFallbackChain filled its MAX_FALLBACK_ATTEMPTS (4) slots with
+ // [groq, openrouter, nvidia, openai], then the handler's anon clamp stripped
+ // `openai` — leaving [groq, openrouter, nvidia] with NO anchor. A simultaneous
+ // throttle of all three free lanes then 503'd signed-out chat. The earlier test
+ // above missed this because CI has no OPENAI_API_KEY, so nothing competed for
+ // the capped slot. The allow-set must exclude paid providers from the cap so the
+ // credits-funded anchor keeps its place.
+ it('keeps the anchor for anon callers even when a paid host key (OPENAI_API_KEY) is present', () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'test-project';
+ setEnv('OPENAI_API_KEY', 'sk-test');
+ setEnv('GROQ_API_KEY', 'gsk-test');
+ setEnv('OPENROUTER_API_KEY', 'or-test');
+ setEnv('NVIDIA_API_KEY', 'nv-test');
+ const allow = new Set(ANON_PROVIDER_LIST);
+ const primary = { name: 'groq', model: 'llama-3.3-70b-versatile' };
+ const names = buildFallbackChain(primary, {}, new Map(), allow).map((r) => r.name);
+ expect(names).toContain('vertex-gemini');
+ expect(names).not.toContain('openai'); // a paid provider never consumes an anon slot
+ for (const n of names) expect(ANON_PROVIDER_LIST).toContain(n);
+ });
+
+ it('force-appends the anchor even when it is in a cooldown — the last resort must never be skipped', () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'test-project';
+ setEnv('GROQ_API_KEY', 'gsk-test');
+ const allow = new Set(ANON_PROVIDER_LIST);
+ const primary = { name: 'groq', model: 'llama-3.3-70b-versatile' };
+ const cooldown = new Map([['vertex-gemini', 'auth']]);
+ const names = buildFallbackChain(primary, {}, cooldown, allow).map((r) => r.name);
+ expect(names).toContain('vertex-gemini');
+ });
+
+ it('authenticated callers (no allow-set) still reach the anchor past present paid keys', () => {
+ process.env.GOOGLE_CLOUD_PROJECT = 'test-project';
+ setEnv('OPENAI_API_KEY', 'sk-test');
+ setEnv('GROQ_API_KEY', 'gsk-test');
+ setEnv('OPENROUTER_API_KEY', 'or-test');
+ setEnv('NVIDIA_API_KEY', 'nv-test');
+ const primary = { name: 'groq', model: 'llama-3.3-70b-versatile' };
+ const names = buildFallbackChain(primary, {}, new Map()).map((r) => r.name); // allow=null
+ expect(names).toContain('vertex-gemini');
+ });
});