Repository Public MIT
1// @vitest-environment node2/**3 * =============================================================================4 * SP BOUCHER | SOFTWARE & RESEARCH5 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6 * =============================================================================7 *8 * Project : VQuant9 * File : server/next/modelRouter.test.ts10 * Module : server11 * Repository : https://git.spboucher.ai/vquant12 * Project Website : https://vquant.spboucher.ai13 * Created : 2026-11-2014 * Last Modified : 2026-11-2015 *16 * Author : Simon-Pierre Boucher17 * Position : Professor of Finance18 * Institution : Université du Québec en Outaouais (UQO)19 * Organization : SP Boucher20 * Website : https://spboucher.ai21 * Git : https://git.spboucher.ai22 *23 * Preferred Contact: contact@spboucher.ai24 * Development : dev@spboucher.ai25 * Support : support@spboucher.ai26 * Security/Admin : admin@spboucher.ai27 *28 * Copyright (c) 202629 * Simon-Pierre Boucher30 * All rights reserved where applicable. This file is governed by the31 * applicable project license, copyright notices and relevant law.32 * Existing third-party rights and notices remain unaffected.33 *34 * SPDX Identifier : MIT35 * License : MIT License36 * License File : LICENSE37 *38 * Do not embed credentials, private keys, access tokens,39 * certificates or confidential personal information.40 *41 * =============================================================================42 * END OF SP BOUCHER SOURCE HEADER43 * =============================================================================44 */4546/**47 * Model router (contract §2.2): a pure function of the request, the preference and the registry state.48 */49import { describe, expect, it } from "vitest";50import { estimateRequestTokens, parsePreference, routeModel, type RouteInput } from "./modelRouter";51import type { ModelTier, ProviderId, RegistryModel, RegistryProvider } from "./providers";5253const model = (id: string, provider: ProviderId, tier: ModelTier, price: [number, number] | null, over: Partial<RegistryModel> = {}): RegistryModel => ({54 id, label: id, provider, tier, contextWindow: 1_000_000, maxOutput: 64_000, pricing: price ? { inputPerMTok: price[0], outputPerMTok: price[1] } : null,55 capabilities: { tools: true, vision: true, reasoning: true, streaming: true }, available: true, source: "curated", selectable: true, ...over,56});57const provider = (id: ProviderId, models: RegistryModel[], over: Partial<RegistryProvider> = {}): RegistryProvider => ({ id, name: id, configured: true, ok: true, checkedAt: 1, error: null, logo: "", models, ...over });5859const registry = (): RegistryProvider[] => [60 provider("anthropic", [model("a-frontier", "anthropic", "frontier", [8, 40]), model("a-balanced", "anthropic", "balanced", [2, 10]), model("a-fast", "anthropic", "fast", [0.1, 0.5])]),61 provider("openai", [model("o-frontier", "openai", "frontier", [5, 30], { contextWindow: null }), model("o-fast", "openai", "fast", [0.25, 2], { contextWindow: null })]),62 provider("google", [model("g-balanced", "google", "balanced", [1.5, 9], { contextWindow: null })]),63 provider("openrouter", [model("openrouter:x/cheap", "openrouter", "fast", [0.01, 0.02], { source: "api", contextWindow: 128_000 })]),64 provider("local", [model("local:qwen", "local", "balanced", null, { source: "api", contextWindow: null, capabilities: { tools: true, vision: false, reasoning: false, streaming: true } })]),65];66const input = (over: Partial<RouteInput> = {}): RouteInput => ({ mode: "standard", vision: false, estimatedTokens: 2_000, strategy: "balanced", providers: [], registry: registry(), defaultModel: "a-frontier", ...over });6768describe("routeModel", () => {69 it("is deterministic and explains itself", () => {70 const a = routeModel(input());71 const b = routeModel(input());72 expect(a).toEqual(b);73 expect(a.requested).toBe("auto");74 expect(a.reason).toMatch(/standard request under the balanced strategy/);75 expect(a.candidates.length).toBeGreaterThan(1);76 expect(a.candidates[0].model).toBe(a.model);77 expect(a.candidates.map((c) => c.score)).toEqual([...a.candidates.map((c) => c.score)].sort((x, y) => y - x));78 for (const c of a.candidates) expect(c.why).toMatch(/tier/);79 });8081 it("aims at the tier the mode and the strategy call for", () => {82 const tierOf = (id: string) => registry().flatMap((p) => p.models).find((m) => m.id === id)!.tier;83 expect(tierOf(routeModel(input({ mode: "fast", strategy: "balanced" })).model)).toBe("fast");84 expect(tierOf(routeModel(input({ mode: "standard", strategy: "balanced" })).model)).toBe("balanced");85 expect(tierOf(routeModel(input({ mode: "deep", strategy: "balanced" })).model)).toBe("frontier");86 expect(tierOf(routeModel(input({ mode: "ultra", strategy: "quality" })).model)).toBe("frontier");87 expect(tierOf(routeModel(input({ mode: "standard", strategy: "quality" })).model)).toBe("frontier");88 expect(tierOf(routeModel(input({ mode: "standard", strategy: "economy" })).model)).toBe("fast");89 expect(tierOf(routeModel(input({ mode: "deep", strategy: "economy" })).model)).toBe("balanced");90 });9192 it("keeps the agent's home provider ahead of a cheaper rival, except under economy where price decides", () => {93 // Frontier tier: openai (5/30) is cheaper than anthropic (8/40), but the agent loop is built around Anthropic.94 expect(routeModel(input({ mode: "deep" })).model).toBe("a-frontier");95 expect(routeModel(input({ mode: "deep" })).candidates[0].why).toMatch(/built around this provider/);96 expect(routeModel(input({ mode: "deep", strategy: "economy", providers: ["openai", "anthropic"] })).provider).not.toBeUndefined();97 // Fast tier: anthropic (0.1/0.5) is cheaper than openai (0.25/2).98 expect(routeModel(input({ mode: "fast", strategy: "economy" })).model).toBe("a-fast");99 });100101 it("only uses the allowed providers; by default the three native ones", () => {102 const all = routeModel(input({ mode: "fast" }));103 expect(all.candidates.some((c) => c.model.startsWith("openrouter:") || c.model.startsWith("local:"))).toBe(false);104 const onlyGoogle = routeModel(input({ providers: ["google"], mode: "deep" }));105 expect(onlyGoogle).toMatchObject({ model: "g-balanced", provider: "google" });106 expect(onlyGoogle.candidates).toHaveLength(1);107 const withRouter = routeModel(input({ providers: ["openrouter"], mode: "fast" }));108 expect(withRouter.model).toBe("openrouter:x/cheap");109 expect(withRouter.candidates[0].why).toMatch(/listed by the provider/);110 });111112 it("keeps a validated model ahead of a merely listed one at equal fit", () => {113 const reg = [provider("anthropic", [model("a", "anthropic", "balanced", [2, 10])]), provider("openrouter", [model("openrouter:b", "openrouter", "balanced", [2, 10], { source: "api" })])];114 expect(routeModel(input({ registry: reg, providers: ["anthropic", "openrouter"] })).model).toBe("a");115 });116117 it("requires image input when an image is attached", () => {118 const d = routeModel(input({ providers: ["local", "google"], vision: true }));119 expect(d.model).toBe("g-balanced");120 expect(d.candidates.some((c) => c.model === "local:qwen")).toBe(false);121 expect(d.reason).toMatch(/accepts images/);122 });123124 it("excludes models whose context cannot hold the conversation", () => {125 // 300k tokens: models without a stated context are not trusted with it; 1M-context models are.126 const big = routeModel(input({ estimatedTokens: 300_000, mode: "deep" }));127 expect(big.model).toBe("a-frontier");128 expect(big.candidates.every((c) => c.model.startsWith("a-"))).toBe(true);129 expect(big.reason).toMatch(/context of about/);130 // A 128k model is out once prompt + fixed instructions pass it.131 expect(routeModel(input({ providers: ["openrouter"], estimatedTokens: 100_000 })).candidates).toHaveLength(0);132 });133134 it("skips unselectable models and unconfigured providers, and ranks a failing provider behind a healthy one", () => {135 const reg = registry();136 reg[1].ok = false; // openai listing failing137 expect(routeModel(input({ registry: reg, mode: "deep" })).model).toBe("a-frontier");138 reg[0].configured = false;139 expect(routeModel(input({ registry: reg, mode: "deep" })).model).toBe("o-frontier"); // still usable when it is all there is140 reg[1].models.forEach((m) => (m.selectable = false));141 expect(routeModel(input({ registry: reg, mode: "deep" })).model).toBe("g-balanced");142 });143144 it("never lets an unknown price win on price", () => {145 const reg = [provider("local", [model("local:free", "local", "fast", null, { source: "api" }), model("local:priced", "local", "fast", [1, 2], { source: "api" })])];146 expect(routeModel(input({ registry: reg, providers: ["local"], mode: "fast", strategy: "economy" })).model).toBe("local:priced");147 });148149 it("breaks ties with the default model, then the provider order, then the id", () => {150 const twin = (id: string, p: ProviderId) => model(id, p, "balanced", [2, 10]);151 const reg = [provider("openai", [twin("zeta", "openai"), twin("alpha", "openai")]), provider("google", [twin("beta", "google")])];152 expect(routeModel(input({ registry: reg, defaultModel: "beta" })).model).toBe("beta");153 expect(routeModel(input({ registry: reg, defaultModel: "none" })).candidates.map((c) => c.model)).toEqual(["alpha", "zeta", "beta"]);154 });155156 it("falls back to the default model, and says so, when nothing fits", () => {157 const d = routeModel(input({ providers: ["local"], vision: true }));158 expect(d).toMatchObject({ model: "a-frontier", provider: "anthropic", candidates: [] });159 expect(d.reason).toMatch(/No selectable model fits/);160 });161162 it("treats an unknown strategy as balanced", () => {163 expect(routeModel(input({ strategy: "whatever" as never })).strategy).toBe("balanced");164 });165});166167describe("helpers", () => {168 it("estimates the request size from the text", () => {169 expect(estimateRequestTokens("abcd")).toBe(1);170 expect(estimateRequestTokens("abcd", [{ question: "x".repeat(400), answer: "y".repeat(400) }])).toBe(201);171 expect(estimateRequestTokens("abcd", [], true)).toBe(1501);172 });173174 it("reads a stored preference defensively", () => {175 expect(parsePreference(null)).toEqual({ strategy: "balanced", providers: [], budget: { maxCostUsd: null, maxMinutes: null } });176 expect(parsePreference({ routing: { strategy: "economy", providers: ["anthropic", 3, "local"] }, budget: { maxCostUsd: 2.5, maxMinutes: "10" } })).toEqual({ strategy: "economy", providers: ["anthropic", "local"], budget: { maxCostUsd: 2.5, maxMinutes: null } });177 expect(parsePreference({ routing: { strategy: "fastest" }, budget: { maxCostUsd: -1 } })).toEqual({ strategy: "balanced", providers: [], budget: { maxCostUsd: null, maxMinutes: null } });178 expect(parsePreference("nonsense").strategy).toBe("balanced");179 });180});181