Repository Public MIT
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : VQuant8 * File : server/next/modelRouter.ts9 * Module : server10 * Repository : https://git.spboucher.ai/vquant11 * Project Website : https://vquant.spboucher.ai12 * Created : 2026-11-2013 * Last Modified : 2026-11-2014 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * SPDX Identifier : MIT34 * License : MIT License35 * License File : LICENSE36 *37 * Do not embed credentials, private keys, access tokens,38 * certificates or confidential personal information.39 *40 * =============================================================================41 * END OF SP BOUCHER SOURCE HEADER42 * =============================================================================43 */4445/**46 * Model router (contract: docs/next/CONTRACT.md §2.2).47 *48 * `routeModel` is a pure function: same inputs, same decision, and every candidate carries the reason for its49 * score. No model is called to choose a model. Inputs are the mode of the request, whether an image is attached,50 * the estimated size of the context, the person's routing preference (strategy and allowed providers), the health51 * of each provider and the prices in the registry.52 */53import { DEFAULT_MODEL_ID, getRegistry, type ModelTier, type ProviderId, type RegistryModel, type RegistryProvider } from "./providers";5455export type ChatMode = "fast" | "standard" | "deep" | "ultra" | "research";56export type RoutingStrategy = "quality" | "balanced" | "economy";57export const ROUTING_STRATEGIES: RoutingStrategy[] = ["quality", "balanced", "economy"];58/** Providers Auto may use when the person has not chosen: the three the app has always run on. */59export const DEFAULT_ROUTING_PROVIDERS: ProviderId[] = ["anthropic", "openai", "google"];6061export interface RouteInput {62 mode: ChatMode;63 vision: boolean;64 /** estimated tokens of the conversation that will be sent (history + question), without the fixed instructions */65 estimatedTokens: number;66 strategy: RoutingStrategy;67 /** provider ids Auto may use; empty = DEFAULT_ROUTING_PROVIDERS */68 providers: string[];69 registry: RegistryProvider[];70 defaultModel?: string;71}7273export interface RouteCandidate {74 model: string;75 score: number;76 why: string;77}7879export interface RouteDecision {80 requested: string;81 model: string;82 provider: ProviderId;83 reason: string;84 strategy: RoutingStrategy;85 candidates: RouteCandidate[];86}8788// The tier a request calls for. Rows: strategy; columns: mode.89const TARGET_TIER: Record<RoutingStrategy, Record<ChatMode, ModelTier>> = {90 quality: { fast: "balanced", standard: "frontier", deep: "frontier", ultra: "frontier", research: "frontier" },91 balanced: { fast: "fast", standard: "balanced", deep: "frontier", ultra: "frontier", research: "frontier" },92 economy: { fast: "fast", standard: "fast", deep: "balanced", ultra: "balanced", research: "balanced" },93};94const TIER_RANK: Record<ModelTier, number> = { fast: 0, balanced: 1, frontier: 2 };95const WEIGHTS: Record<RoutingStrategy, { tier: number; price: number }> = {96 quality: { tier: 0.7, price: 0.05 },97 balanced: { tier: 0.6, price: 0.2 },98 economy: { tier: 0.6, price: 0.3 },99};100/** The instructions and the tool list are sent with every request: about 160 000 characters, i.e. some 40 000 tokens at four characters per token, plus the mode directive and the workspace context. */101const FIXED_PROMPT_TOKENS = 45_000;102/** A model whose context size nobody states is only trusted with a context this small (the limit the OpenAI-compatible path already summarises at). */103const UNKNOWN_CONTEXT_LIMIT = 100_000;104105const round = (x: number) => Math.round(x * 1000) / 1000;106const blended = (m: RegistryModel): number | null => (m.pricing ? m.pricing.inputPerMTok * 0.75 + m.pricing.outputPerMTok * 0.25 : null);107108/** Chooses a model. Deterministic; ties go to the default model, then to the provider order, then to the id. */109export function routeModel(input: RouteInput): RouteDecision {110 const strategy = ROUTING_STRATEGIES.includes(input.strategy) ? input.strategy : "balanced";111 const allowed = new Set<string>(input.providers.length > 0 ? input.providers : DEFAULT_ROUTING_PROVIDERS);112 const fallback = input.defaultModel ?? DEFAULT_MODEL_ID;113 const need = Math.max(0, input.estimatedTokens) + FIXED_PROMPT_TOKENS;114 const target = TARGET_TIER[strategy][input.mode];115 const w = WEIGHTS[strategy];116117 const pool: RegistryModel[] = [];118 for (const p of input.registry) {119 if (!allowed.has(p.id) || !p.configured) continue;120 for (const m of p.models) {121 if (!m.selectable) continue;122 if (input.vision && !m.capabilities.vision) continue;123 if (m.contextWindow !== null ? m.contextWindow < need * 1.15 : need > UNKNOWN_CONTEXT_LIMIT) continue;124 pool.push(m);125 }126 }127128 // Price is compared inside the pool, on a log scale (prices span three orders of magnitude).129 const prices = pool.map(blended).filter((x): x is number => x !== null && x > 0).map(Math.log);130 const lo = Math.min(...prices);131 const hi = Math.max(...prices);132 const priceScore = (m: RegistryModel): number => {133 const b = blended(m);134 if (b === null) return 0; // an unknown price never wins on price135 if (b <= 0 || hi === lo) return 1;136 return 1 - (Math.log(b) - lo) / (hi - lo);137 };138 const health = new Map(input.registry.map((p) => [p.id, p]));139 const providerOrder = new Map(input.registry.map((p, i) => [p.id, i]));140141 const scored = pool.map((m) => {142 const gap = Math.abs(TIER_RANK[m.tier] - TIER_RANK[target]);143 const tierFit = gap === 0 ? 1 : gap === 1 ? 0.4 : 0.1;144 const price = priceScore(m);145 const vetted = m.source === "curated" ? 0.1 : 0; // run with this app's tool loop before146 const reasoning = (input.mode === "deep" || input.mode === "ultra" || input.mode === "research") && m.capabilities.reasoning ? 0.05 : 0;147 const p = health.get(m.provider)!;148 // A provider whose last listing failed is still usable (stale listing) but ranks behind a healthy one.149 const unhealthy = p.checkedAt > 0 && !p.ok ? 0.15 : 0;150 // The agent loop (tool schema, thinking blocks, prompt caching, sub-analysts) is built around Anthropic models and151 // is exercised with them every day; outside the economy strategy that track record outweighs a lower price.152 const home = m.provider === "anthropic" && strategy !== "economy" ? 0.25 : 0;153 const score = round(w.tier * tierFit + w.price * price + vetted + reasoning + home - unhealthy);154 const why = [155 `${m.tier} tier ${gap === 0 ? "matches" : gap === 1 ? "is one step from" : "is far from"} the ${target} target`,156 m.pricing ? `$${m.pricing.inputPerMTok}/$${m.pricing.outputPerMTok} per MTok` : "price unknown",157 m.source === "curated" ? "validated with this app" : "listed by the provider",158 ...(reasoning ? ["reasoning model"] : []),159 ...(home ? ["the agent loop is built around this provider"] : []),160 ...(unhealthy ? [`${p.name} listing failing`] : []),161 ].join("; ");162 return { m, score, why };163 });164165 scored.sort(166 (a, b) =>167 b.score - a.score ||168 Number(b.m.id === fallback) - Number(a.m.id === fallback) ||169 (providerOrder.get(a.m.provider) ?? 99) - (providerOrder.get(b.m.provider) ?? 99) ||170 a.m.id.localeCompare(b.m.id),171 );172 const candidates = scored.slice(0, 5).map((s) => ({ model: s.m.id, score: s.score, why: s.why }));173174 if (scored.length === 0) {175 const any = input.registry.flatMap((p) => p.models).find((m) => m.id === fallback);176 return {177 requested: "auto",178 model: fallback,179 provider: any?.provider ?? "anthropic",180 reason: `No selectable model fits this request among the allowed providers (${[...allowed].join(", ")})${input.vision ? " with image input" : ""}; the default model is used.`,181 strategy,182 candidates: [],183 };184 }185186 const best = scored[0];187 const label = best.m.label === best.m.id ? best.m.id : `${best.m.label}`;188 const reason = `${label} was chosen for a ${input.mode} request under the ${strategy} strategy: ${best.why}${input.vision ? "; accepts images" : ""}${need > 200_000 ? `; fits a context of about ${Math.round(need / 1000)}k tokens` : ""}.`;189 return { requested: "auto", model: best.m.id, provider: best.m.provider, reason, strategy, candidates };190}191192/** Rough size of what will be sent: four characters per token, as elsewhere in this server. */193export function estimateRequestTokens(query: string, history: Array<{ question: string; answer: string }> = [], hasImage = false): number {194 let chars = query.length;195 for (const h of history) chars += h.question.length + h.answer.length;196 return Math.ceil(chars / 4) + (hasImage ? 1_500 : 0);197}198199export interface PersonPreference {200 strategy: RoutingStrategy;201 providers: string[];202 budget: { maxCostUsd: number | null; maxMinutes: number | null };203}204205const positive = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null);206207/** Reads the routing and budget parts of a stored `preference/default` data object, tolerating anything. Pure. */208export function parsePreference(data: unknown): PersonPreference {209 const d = (data && typeof data === "object" ? data : {}) as Record<string, any>;210 const strategy = ROUTING_STRATEGIES.includes(d.routing?.strategy) ? (d.routing.strategy as RoutingStrategy) : "balanced";211 const providers = Array.isArray(d.routing?.providers) ? d.routing.providers.filter((p: unknown): p is string => typeof p === "string").slice(0, 10) : [];212 return { strategy, providers, budget: { maxCostUsd: positive(d.budget?.maxCostUsd), maxMinutes: positive(d.budget?.maxMinutes) } };213}214215/** The person's routing and budget preference; defaults when nothing is stored or the object store cannot be read. */216export async function loadPreference(owner: string): Promise<PersonPreference> {217 try {218 const { getObject } = await import("./objects");219 return parsePreference(getObject(owner, "preference", "default")?.data);220 } catch {221 return parsePreference(null);222 }223}224225/** The decision `model: "auto"` would get for this person, without running anything. */226export async function previewRoute(owner: string, o: { mode: ChatMode; vision: boolean; query: string; history?: Array<{ question: string; answer: string }> }): Promise<RouteDecision> {227 const [pref, registry] = await Promise.all([loadPreference(owner), getRegistry()]);228 return routeModel({ mode: o.mode, vision: o.vision, estimatedTokens: estimateRequestTokens(o.query, o.history, o.vision), strategy: pref.strategy, providers: pref.providers, registry });229}230