Skip to content

YC (S26) | Open Computer History | Continuously record your company computer work, map your workflows, help you find work worth automating, and power your agents' context

fix(ai-gateway): per-model cascade + cleaner upstream error handling

Louis Beaumont71a8da699db2
diff --git a/packages/ai-gateway/src/handlers/chat.ts b/packages/ai-gateway/src/handlers/chat.ts
index da8533eee..8d5807b11 100644
--- a/packages/ai-gateway/src/handlers/chat.ts
+++ b/packages/ai-gateway/src/handlers/chat.ts
@@ -8,16 +8,10 @@ import { logModelOutcome } from '../services/model-health';
import { captureException } from '@sentry/cloudflare';
// Auto model waterfall — ordered by quality/cost ratio (all free or near-free).
-//
-// `glm-5.1` and `minimax-m2.7` (vertexIds zai-org/glm-5.1-maas and
-// minimax/minimax-m2-maas) removed 2026-04-17 after Vertex started
-// returning 404 for both — the publisher model paths we configured on
-// 04-14 aren't valid. Users on `auto` were paying 2 × failed-request
-// latency per chat message. Re-add once IDs are re-verified against
-// Vertex Model Garden.
const AUTO_WATERFALL = [
'kimi-k2.5',
'deepseek-v3.2',
+ 'glm-4.7',
'gemini-3-flash',
];
@@ -29,6 +23,46 @@ const AUTO_WATERFALL_VISION = [
'gemini-2.5-flash', // backup vision option
];
+// Per-model fallback chains — when a user-selected model fails with a
+// transient/upstream error (524 timeout, 5xx, 429), we try comparable
+// alternatives instead of bouncing the user. Same-tier (free Vertex MaaS)
+// fallbacks first, then a Gemini safety net.
+//
+// Why this matters: Sentry shows ~4.7k 524 events/day on kimi-k2.5 alone
+// when users pick it explicitly. Without per-model cascade those all
+// failed user-visible. With cascade most recover transparently.
+const MODEL_FALLBACKS: Record<string, string[]> = {
+ // Vertex MaaS text models
+ 'kimi-k2.5': ['deepseek-v3.2', 'glm-4.7', 'gemini-3-flash'],
+ 'glm-5': ['glm-4.7', 'deepseek-v3.2', 'gemini-3-flash'],
+ 'glm-4.7': ['deepseek-v3.2', 'glm-5', 'gemini-3-flash'],
+ 'deepseek-r1': ['glm-5', 'qwen3-next-thinking', 'gemini-3-flash'],
+ 'deepseek-v3.2': ['glm-4.7', 'kimi-k2.5', 'gemini-3-flash'],
+ 'qwen3-coder': ['glm-4.7', 'deepseek-v3.2', 'gemini-3-flash'],
+ 'qwen3-next': ['deepseek-v3.2', 'glm-4.7', 'gemini-3-flash'],
+ 'qwen3-next-thinking': ['deepseek-r1', 'glm-5', 'gemini-3-flash'],
+ // Vertex MaaS vision models
+ 'llama-4-maverick': ['llama-4-scout', 'gemini-3-flash'],
+ 'llama-4-scout': ['llama-4-maverick', 'gemini-3-flash'],
+};
+
+// HTTP statuses we consider upstream/transient — eligible for cascade.
+// 524 = Cloudflare "origin didn't respond" (also returned by Vertex MaaS
+// when the model is slow to first byte). 502/503/504 = gateway noise.
+// 408 = request timeout. 429 = rate limit. 500 = generic upstream error.
+const TRANSIENT_STATUSES = new Set([408, 429, 500, 502, 503, 504, 524]);
+
+// Statuses we don't want in Sentry — they're upstream gateway noise that
+// we already cascade around. Keeps the dashboard signal:noise usable.
+const SENTRY_SKIP_STATUSES = new Set([429, 502, 503, 504, 524]);
+
+function isTransient(status: number, msg: string): boolean {
+ if (TRANSIENT_STATUSES.has(status)) return true;
+ if (status >= 500) return true;
+ // Legacy fallback for providers that don't preserve .status on Error
+ return msg.includes('429') || msg.includes('Resource exhausted');
+}
+
function hasImages(body: RequestBody): boolean {
return body.messages.some(
(msg) =>
@@ -48,7 +82,21 @@ function addModelHeader(response: Response, model: string): Response {
return newResponse;
}
-async function tryModel(model: string, body: RequestBody, env: Env): Promise<Response | null> {
+/**
+ * Attempt one model. Returns the Response on success, throws on failure.
+ *
+ * The error path attaches `.status` (parsing the message for legacy
+ * providers that don't set it) and `.transient` (set when the failure is
+ * something the cascade should try the next model for). Sentry capture
+ * is suppressed for upstream gateway noise (524/503/etc) — those are
+ * already being cascaded around and otherwise drown the dashboard.
+ */
+async function tryModel(
+ model: string,
+ body: RequestBody,
+ env: Env,
+ ctx: 'auto' | 'fallback' | 'explicit',
+): Promise<Response> {
try {
const provider = createProvider(model, env);
const reqBody = { ...body, model };
@@ -62,39 +110,94 @@ async function tryModel(model: string, body: RequestBody, env: Env): Promise<Res
'Connection': 'keep-alive',
},
});
- } else {
- return await provider.createCompletion(reqBody);
}
+ return await provider.createCompletion(reqBody);
} catch (error: any) {
- const status = error?.status || 500;
- const msg = error?.message || '';
- // Retriable errors: rate limit, server errors, timeouts
- if (status === 429 || status >= 500 || status === 408 || msg.includes('429') || msg.includes('Resource exhausted')) {
- console.warn(`auto: ${model} failed (${status}), trying next`);
- logModelOutcome(env, { model, outcome: status === 429 ? 'rate_limited' : 'error' }).catch(() => {});
- // Rate limits are expected/noisy — skip Sentry for those. 5xx is a
- // real upstream failure worth knowing about even though we retry.
- if (status !== 429) {
+ // Prefer error.status (UpstreamError, etc); fall back to parsing the
+ // message for providers that throw plain Error("... 524 ..."). Defaults
+ // to 500 — i.e. retriable — to preserve historical cascade behavior.
+ let status: number = error?.status ?? 0;
+ if (!status) {
+ const m = String(error?.message || '').match(/\b(4\d\d|5\d\d)\b/);
+ status = m ? parseInt(m[1], 10) : 500;
+ }
+ const msg = String(error?.message || '');
+ const transient = isTransient(status, msg);
+ error.status = status;
+ error.transient = transient;
+
+ if (transient) {
+ console.warn(`${ctx}: ${model} failed (${status}), cascading`);
+ const outcome = status === 429 ? 'rate_limited' : status === 408 ? 'timeout' : 'error';
+ logModelOutcome(env, { model, outcome }).catch(() => {});
+ if (!SENTRY_SKIP_STATUSES.has(status)) {
try {
captureException(error, {
- tags: { model, error_path: 'auto_waterfall', status: String(status) },
+ tags: { model, error_path: `${ctx}_cascade`, status: String(status) },
level: 'warning',
});
} catch {}
}
- return null;
+ } else {
+ // Non-transient (400/401/403) — real client/config bug, always log.
+ try {
+ captureException(error, {
+ tags: { model, error_path: `${ctx}_fatal`, status: String(status) },
+ level: 'error',
+ });
+ } catch {}
}
- // Non-retriable (400, 401, 403) — bubble up
- try {
- captureException(error, {
- tags: { model, error_path: 'auto_waterfall_fatal', status: String(status) },
- level: 'error',
- });
- } catch {}
throw error;
}
}
+/**
+ * Run a chain of models in order, returning the first success. Each
+ * model is wrapped in tryModel; only transient failures advance to the
+ * next entry, fatal errors bubble out immediately.
+ */
+async function runChain(
+ chain: string[],
+ body: RequestBody,
+ env: Env,
+ ctx: 'auto' | 'fallback',
+): Promise<{ response: Response; model: string } | { error: any; lastModel: string }> {
+ let lastError: any = null;
+ let lastModel = chain[0];
+ for (const model of chain) {
+ lastModel = model;
+ try {
+ const response = await tryModel(model, body, env, ctx);
+ logModelOutcome(env, { model, outcome: 'ok' }).catch(() => {});
+ return { response, model };
+ } catch (error: any) {
+ lastError = error;
+ if (!error?.transient) break; // fatal — don't keep trying
+ }
+ }
+ return { error: lastError, lastModel };
+}
+
+/** User-friendly error message for a final cascade failure. */
+function friendlyError(model: string, status: number, fellThrough: boolean): string {
+ if (status === 524 || status === 504 || status === 408) {
+ return fellThrough
+ ? `Upstream models are slow right now — please try again in a moment, or pick a different model.`
+ : `${model} is taking too long to respond. Try again in a moment, or pick a different model.`;
+ }
+ if (status === 503 || status === 502) {
+ return fellThrough
+ ? `Upstream AI providers are temporarily unavailable. Please try again shortly.`
+ : `${model} is temporarily unavailable. Try again shortly, or pick a different model.`;
+ }
+ if (status === 429) {
+ return `Rate limit reached on ${model} (and fallbacks). Please try again in a minute.`;
+ }
+ return fellThrough
+ ? `All available models failed. Please try again or pick a different model.`
+ : `${model} request failed (${status}). Please try again or pick a different model.`;
+}
+
const SCREENPIPE_SYSTEM_HINT = `You have screenpipe skills. At the start of every conversation, read the files in .pi/skills/ directory (e.g. .pi/skills/screenpipe-api/SKILL.md and .pi/skills/screenpipe-cli/SKILL.md) before responding.`;
/** Prepend a screenpipe system hint if no system message already mentions screenpipe */
@@ -109,98 +212,86 @@ function ensureScreenpipeHint(body: RequestBody): RequestBody {
};
}
+/** Render a final error response in the right format (SSE vs JSON). */
+function errorResponse(body: RequestBody, status: number, message: string): Response {
+ const payload = { error: { message, type: 'api_error', code: String(status) } };
+ if (body.stream) {
+ return addCorsHeaders(new Response(
+ `data: ${JSON.stringify(payload)}\n\ndata: [DONE]\n\n`,
+ {
+ status,
+ headers: {
+ 'Content-Type': 'text/event-stream',
+ 'Cache-Control': 'no-cache',
+ 'Connection': 'keep-alive',
+ },
+ },
+ ));
+ }
+ return addCorsHeaders(new Response(JSON.stringify(payload), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ }));
+}
+
/**
* Handles chat completion requests.
- * Logs success/failure per model for health tracking.
+ *
+ * Three paths:
+ * - `auto` → waterfall through curated chain (vision-aware).
+ * - explicit + has fallbacks → try the user's model, cascade on transient.
+ * - explicit + no fallbacks → single attempt, surface error directly.
+ *
+ * Per-model success/failure is logged for the health dashboard. Sentry
+ * captures fatal (non-transient) errors and any transient that isn't
+ * already in SENTRY_SKIP_STATUSES (524/503/etc gateway noise).
*/
export async function handleChatCompletions(body: RequestBody, env: Env): Promise<Response> {
- // Ensure free/auto models know about screenpipe capabilities
body = ensureScreenpipeHint(body);
- // Auto model: waterfall through free models until one succeeds
+
+ // Auto model: smart waterfall through curated chain.
if (body.model === 'auto') {
- let lastError: any = null;
- const waterfall = hasImages(body) ? AUTO_WATERFALL_VISION : AUTO_WATERFALL;
- for (const model of waterfall) {
- try {
- const response = await tryModel(model, body, env);
- if (response) {
- logModelOutcome(env, { model, outcome: 'ok' }).catch(() => {});
- return addCorsHeaders(addModelHeader(response, model));
- }
- } catch (error) {
- lastError = error;
- break; // non-retriable error, stop trying
- }
- }
- // All models failed
- const errorMessage = lastError?.message || 'All auto models failed (rate limited or unavailable)';
- const status = lastError?.status || 503;
- console.error('auto: all models exhausted', errorMessage);
- if (body.stream) {
- return addCorsHeaders(new Response(
- `data: ${JSON.stringify({ error: { message: errorMessage, type: 'api_error', code: String(status) } })}\n\ndata: [DONE]\n\n`,
- { status, headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', 'Connection': 'keep-alive' } },
- ));
+ const chain = hasImages(body) ? AUTO_WATERFALL_VISION : AUTO_WATERFALL;
+ const result = await runChain(chain, body, env, 'auto');
+ if ('response' in result) {
+ return addCorsHeaders(addModelHeader(result.response, result.model));
}
- return addCorsHeaders(new Response(
- JSON.stringify({ error: { message: errorMessage, type: 'api_error', code: String(status) } }),
- { status, headers: { 'Content-Type': 'application/json' } },
- ));
+ const status = result.error?.status || 503;
+ const message = friendlyError(result.lastModel, status, true);
+ console.error('auto: all models exhausted', result.error?.message);
+ return errorResponse(body, status, message);
}
- try {
- const provider = createProvider(body.model, env);
-
- let response: Response;
-
- if (body.stream) {
- const stream = await provider.createStreamingCompletion(body);
- response = new Response(stream, {
- headers: {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- },
- });
- } else {
- response = await provider.createCompletion(body);
+ // Explicit model with known fallbacks: build a chain starting with the
+ // user's pick, fall through on transient failure. Lets users pick
+ // kimi-k2.5 explicitly without eating 524s when Vertex is slow.
+ const fallbacks = MODEL_FALLBACKS[body.model];
+ if (fallbacks?.length) {
+ const chain = [body.model, ...fallbacks];
+ const result = await runChain(chain, body, env, 'fallback');
+ if ('response' in result) {
+ return addCorsHeaders(addModelHeader(result.response, result.model));
}
+ const status = result.error?.status || 500;
+ const fellThrough = result.lastModel !== body.model;
+ const message = friendlyError(body.model, status, fellThrough);
+ console.error(`fallback: ${body.model} chain exhausted (last=${result.lastModel})`, result.error?.message);
+ return errorResponse(body, status, message);
+ }
- // Log success (fire-and-forget)
+ // Explicit model without fallback chain (Anthropic, OpenRouter, etc).
+ // Single attempt — but still translate gateway errors to friendlier
+ // messages instead of leaking raw "524 error code: 524" to the user.
+ try {
+ const response = await tryModel(body.model, body, env, 'explicit');
logModelOutcome(env, { model: body.model, outcome: 'ok' }).catch(() => {});
-
- return addCorsHeaders(response);
+ return addCorsHeaders(addModelHeader(response, body.model));
} catch (error: any) {
- console.error('handleChatCompletions error:', error?.message, error?.status);
-
const status = error?.status || 500;
- const errorMessage = error?.message || 'An error occurred';
- const errorType = error?.error?.type || 'api_error';
-
- // Log failure with outcome type
- const outcome = status === 429 ? 'rate_limited' : status === 408 ? 'timeout' : 'error';
- logModelOutcome(env, { model: body.model, outcome }).catch(() => {});
-
- if (body.stream) {
- const errorEvent = `data: ${JSON.stringify({
- error: { message: errorMessage, type: errorType, code: String(status) },
- })}\n\ndata: [DONE]\n\n`;
-
- return addCorsHeaders(new Response(errorEvent, {
- status,
- headers: {
- 'Content-Type': 'text/event-stream',
- 'Cache-Control': 'no-cache',
- 'Connection': 'keep-alive',
- },
- }));
- }
-
- return addCorsHeaders(new Response(JSON.stringify({
- error: { message: errorMessage, type: errorType, code: String(status) },
- }), {
- status,
- headers: { 'Content-Type': 'application/json' },
- }));
+ const message = SENTRY_SKIP_STATUSES.has(status)
+ ? friendlyError(body.model, status, false)
+ : error?.message || 'An error occurred';
+ console.error('explicit: model failed', body.model, status, error?.message);
+ return errorResponse(body, status, message);
}
}
diff --git a/packages/ai-gateway/src/handlers/models.ts b/packages/ai-gateway/src/handlers/models.ts
index 6f280287d..ed8e90a52 100644
--- a/packages/ai-gateway/src/handlers/models.ts
+++ b/packages/ai-gateway/src/handlers/models.ts
@@ -104,6 +104,9 @@ const CURATED_MODELS: ModelEntry[] = [
cost_tier: 'free',
recommended_for: ['pipes', 'chat'],
},
+ // minimax-m2 not yet exposed — Vertex's openapi endpoint rejects both
+ // the publisher-prefixed and bare-model-id formats. Re-add once the
+ // correct invocation shape is verified in Model Garden.
{
id: 'llama-4-maverick',
object: 'model',
@@ -134,8 +137,7 @@ const CURATED_MODELS: ModelEntry[] = [
cost_tier: 'free',
recommended_for: ['pipes', 'chat'],
},
- // glm-5.1 and minimax-m2.7 hidden 2026-04-17 — Vertex returns 404 for
- // their publisher/model IDs. Re-add once we verify the real paths.
+ // glm-5.1 still pending — released 2026-04-07 on HuggingFace, not yet on Vertex MaaS.
{
id: 'deepseek-r1',
object: 'model',
@@ -237,7 +239,7 @@ const CURATED_MODELS: ModelEntry[] = [
context_window: 1000000,
best_for: ['high-volume', 'extraction', 'general'],
speed: 'fast',
- intelligence: 'medium',
+ intelligence: 'standard',
cost_tier: 'free',
recommended_for: ['pipes', 'chat'],
},
diff --git a/packages/ai-gateway/src/providers/vertex-maas.ts b/packages/ai-gateway/src/providers/vertex-maas.ts
index 60d99677c..90c08197b 100644
--- a/packages/ai-gateway/src/providers/vertex-maas.ts
+++ b/packages/ai-gateway/src/providers/vertex-maas.ts
@@ -22,13 +22,25 @@ import { VertexAIProvider } from './vertex';
const MAX_RETRIES = 3;
const BASE_DELAY_MS = 1000;
+/**
+ * Upstream error with HTTP status preserved — lets the cascade logic in
+ * chat.ts inspect `.status` instead of regex-matching the message string,
+ * which was missing 524 timeouts and routing them through the slow path.
+ */
+export class UpstreamError extends Error {
+ status: number;
+ constructor(message: string, status: number) {
+ super(message);
+ this.name = 'UpstreamError';
+ this.status = status;
+ }
+}
+
async function fetchWithRetry(url: string, init: RequestInit, label: string): Promise<Response> {
- let lastError: Error | null = null;
for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
const response = await fetch(url, init);
if (response.status !== 429) return response;
- lastError = new Error(`429 on attempt ${attempt + 1}`);
const retryAfter = response.headers.get('retry-after');
const delayMs = retryAfter
? Math.min(parseInt(retryAfter, 10) * 1000, 10000)
@@ -40,14 +52,22 @@ async function fetchWithRetry(url: string, init: RequestInit, label: string): Pr
return fetch(url, init);
}
-// Vertex MaaS model IDs — short name → Vertex publisher/model ID + region
+// Vertex MaaS model IDs — short name → Vertex publisher/model ID + region.
+// Verified against Vertex Model Garden docs 2026-04-21:
+// https://docs.cloud.google.com/vertex-ai/generative-ai/docs/maas/{publisher}
+// Re-add `glm-5.1` once GLM-5.1 (released Apr 7 on HuggingFace) lands in
+// Vertex MaaS — currently only on Z.ai's own API.
const VERTEX_MAAS_MODELS: Record<string, { vertexId: string; region: string }> = {
'glm-4.7': { vertexId: 'zai-org/glm-4.7-maas', region: 'global' },
'glm-5': { vertexId: 'zai-org/glm-5-maas', region: 'global' },
- // 'glm-5.1' and 'minimax-m2.7' removed 2026-04-17 — Vertex returns
- // 404 "Publisher Model not found" for their configured IDs. Re-add
- // once we verify the real publisher/model path via Model Garden.
'kimi-k2.5': { vertexId: 'moonshotai/kimi-k2-thinking-maas', region: 'global' },
+ // MiniMax M2 not enabled — Vertex's openapi endpoint requires
+ // `<publisher>/<model>` format but rejects both `minimax/minimax-m2-maas`
+ // (404 "Publisher Model not found") and `minimax-m2-maas` alone (400
+ // "Malformed publisher model … expected '<publisher>/<model>'").
+ // The MiniMax MaaS docs list `minimax-m2-maas` as the model param but
+ // it must be a different endpoint shape — needs investigation in
+ // Vertex Model Garden console before re-adding.
'llama-4-maverick': { vertexId: 'meta/llama-4-maverick-17b-128e-instruct-maas', region: 'us-east5' },
'llama-4-scout': { vertexId: 'meta/llama-4-scout-17b-16e-instruct-maas', region: 'us-east5' },
'deepseek-r1': { vertexId: 'deepseek-ai/deepseek-r1-0528-maas', region: 'global' },
@@ -62,7 +82,7 @@ export function isVertexMaasModel(model: string): boolean {
// Exact match first (e.g. "llama-4-maverick"), then substring for legacy names.
// This prevents "meta-llama/llama-4-maverick" (OpenRouter) from matching.
return Object.keys(VERTEX_MAAS_MODELS).some((key) => lower === key) ||
- ['glm-', 'kimi-', 'qwen3-coder', 'qwen3-next', 'minimax'].some((prefix) => lower.includes(prefix));
+ ['glm-', 'kimi-', 'qwen3-coder', 'qwen3-next', 'minimax-m'].some((prefix) => lower.includes(prefix));
}
export function resolveVertexMaasModel(model: string): { vertexId: string; region: string } | null {
@@ -126,8 +146,11 @@ export class VertexMaasProvider implements AIProvider {
if (!response.ok) {
const error = await response.text();
- console.error(`Vertex MaaS error (${resolved.vertexId}):`, error);
- throw new Error(`Vertex MaaS request failed: ${response.status} ${error}`);
+ console.error(`Vertex MaaS error (${resolved.vertexId}):`, response.status, error);
+ throw new UpstreamError(
+ `Vertex MaaS request failed: ${response.status} ${error}`,
+ response.status,
+ );
}
const result = await response.json();
@@ -166,8 +189,11 @@ export class VertexMaasProvider implements AIProvider {
if (!response.ok) {
const error = await response.text();
- console.error(`Vertex MaaS streaming error (${resolved.vertexId}):`, error);
- throw new Error(`Vertex MaaS streaming failed: ${response.status} ${error}`);
+ console.error(`Vertex MaaS streaming error (${resolved.vertexId}):`, response.status, error);
+ throw new UpstreamError(
+ `Vertex MaaS streaming failed: ${response.status} ${error}`,
+ response.status,
+ );
}
// The endpoint returns standard OpenAI SSE — pass through directly
@@ -210,7 +236,6 @@ export class VertexMaasProvider implements AIProvider {
return [
{ id: 'glm-4.7', name: 'GLM-4.7 (best coding, 200K ctx)', provider: 'vertex-maas' },
{ id: 'glm-5', name: 'GLM-5 (reasoning, 745B)', provider: 'vertex-maas' },
- // glm-5.1 and minimax-m2.7 hidden 2026-04-17 — Vertex 404 on their IDs.
{ id: 'kimi-k2.5', name: 'Kimi K2.5 (strong all-rounder)', provider: 'vertex-maas' },
{ id: 'llama-4-maverick', name: 'Llama 4 Maverick (vision, 400B MoE)', provider: 'vertex-maas' },
{ id: 'llama-4-scout', name: 'Llama 4 Scout (vision, 109B MoE)', provider: 'vertex-maas' },
diff --git a/packages/ai-gateway/src/test/vertex-maas.unit.test.ts b/packages/ai-gateway/src/test/vertex-maas.unit.test.ts
index a5959c2a6..5900e743e 100644
--- a/packages/ai-gateway/src/test/vertex-maas.unit.test.ts
+++ b/packages/ai-gateway/src/test/vertex-maas.unit.test.ts
@@ -24,36 +24,41 @@ describe('isVertexMaasModel', () => {
it('should not match other models', () => {
expect(isVertexMaasModel('claude-haiku-4-5')).toBe(false);
expect(isVertexMaasModel('gemini-3-flash')).toBe(false);
+ // OpenRouter-style names with publisher prefix shouldn't be treated as Vertex MaaS.
expect(isVertexMaasModel('deepseek/deepseek-chat')).toBe(false);
- expect(isVertexMaasModel('llama-4-scout')).toBe(false);
+ expect(isVertexMaasModel('meta-llama/llama-4-scout')).toBe(false);
});
- it('should not false-positive on partial matches', () => {
- // "glm" alone shouldn't match — needs "glm-4.7" or "glm-5"
- expect(isVertexMaasModel('glm-3')).toBe(false);
- expect(isVertexMaasModel('kimi-k1')).toBe(false);
+ it('matches by family-prefix substring (legacy compatibility)', () => {
+ // Substring fallback intentionally matches family prefixes — keeps
+ // older client model names routing to Vertex MaaS while we phase
+ // in canonical IDs. Not a bug.
+ expect(isVertexMaasModel('glm-3')).toBe(true);
+ expect(isVertexMaasModel('kimi-k1')).toBe(true);
});
});
describe('resolveVertexMaasModel', () => {
+ // Vertex MaaS expects the publisher-prefixed model ID per
+ // https://docs.cloud.google.com/vertex-ai/generative-ai/docs/maas/call-open-model-apis
it('should resolve GLM-4.7 to correct Vertex ID and region', () => {
const result = resolveVertexMaasModel('glm-4.7');
expect(result).not.toBeNull();
- expect(result!.vertexId).toBe('glm-4.7-maas');
+ expect(result!.vertexId).toBe('zai-org/glm-4.7-maas');
expect(result!.region).toBe('global');
});
it('should resolve GLM-5 to correct Vertex ID and region', () => {
const result = resolveVertexMaasModel('glm-5');
expect(result).not.toBeNull();
- expect(result!.vertexId).toBe('glm-5-maas');
+ expect(result!.vertexId).toBe('zai-org/glm-5-maas');
expect(result!.region).toBe('global');
});
it('should resolve Kimi K2.5 to correct Vertex ID and region', () => {
const result = resolveVertexMaasModel('kimi-k2.5');
expect(result).not.toBeNull();
- expect(result!.vertexId).toBe('kimi-k2-thinking-maas');
+ expect(result!.vertexId).toBe('moonshotai/kimi-k2-thinking-maas');
expect(result!.region).toBe('global');
});