7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(routing): per-model weight overrides via MODEL_ROUTING_OVERRIDES (#747)
suantea (asuan_suan)c3f538e6c133
diff --git a/.env.example b/.env.exampleindex 988bd0fb..41c03917 100644--- a/.env.example+++ b/.env.example@@ -243,6 +243,12 @@ REQUEST_ANALYTICS_MAX_ROWS=100000# false: force it off even behind HTTPS (e.g. mixed-content reverse proxies).# CSP_UPGRADE_INSECURE_REQUESTS=false+# Per-model routing score multipliers (#738), JSON object of model id → 0..2.+# 1.0 leaves a model unchanged, below 1 demotes it, above 1 promotes it, and 0+# means the automatic router never picks it (Manual priority still can).+# Matching is by model id alone, across all platforms serving that id.+# MODEL_ROUTING_OVERRIDES={"gpt-4o": 0.2, "deepseek-v3": 1.5}+# --- Advanced / embedding ---------------------------------------------------# Path to a prebuilt client `dist` directory to serve. Defaults to the bundled# client build; set this only if you build the dashboard separately.diff --git a/server/src/__tests__/services/model-weight-overrides.test.ts b/server/src/__tests__/services/model-weight-overrides.test.tsnew file mode 100644index 00000000..dc97619f--- /dev/null+++ b/server/src/__tests__/services/model-weight-overrides.test.ts@@ -0,0 +1,78 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest';+import {+ parseModelWeightOverrides,+ applyModelWeightOverride,+ getModelWeightOverrides,+ resetModelWeightOverrides,+} from '../../services/model-weight-overrides.js';++const ORIGINAL_ENV = process.env.MODEL_ROUTING_OVERRIDES;++describe('model weight overrides', () => {+ beforeEach(() => {+ resetModelWeightOverrides();+ });++ afterEach(() => {+ resetModelWeightOverrides();+ if (ORIGINAL_ENV === undefined) {+ delete process.env.MODEL_ROUTING_OVERRIDES;+ } else {+ process.env.MODEL_ROUTING_OVERRIDES = ORIGINAL_ENV;+ }+ });++ it('parses a valid JSON object of model multipliers', () => {+ const map = parseModelWeightOverrides('{"gpt-4o": 0.2, "deepseek-v3": 0.8, "claude-3.5": 1}');+ expect([...map.entries()]).toEqual([+ ['gpt-4o', 0.2],+ ['deepseek-v3', 0.8],+ ['claude-3.5', 1],+ ]);+ });++ it('drops out-of-range, non-finite and non-number values instead of applying them', () => {+ const map = parseModelWeightOverrides('{"ok": 0.5, "neg": -1, "big": 3, "nan": "x", "inf": 1e999}');+ expect([...map.entries()]).toEqual([['ok', 0.5]]);+ });++ it('ignores blank, malformed or non-object input', () => {+ expect(parseModelWeightOverrides(undefined).size).toBe(0);+ expect(parseModelWeightOverrides('').size).toBe(0);+ expect(parseModelWeightOverrides(' ').size).toBe(0);+ expect(parseModelWeightOverrides('not json').size).toBe(0);+ expect(parseModelWeightOverrides('42').size).toBe(0);+ expect(parseModelWeightOverrides('[1,2]').size).toBe(0);+ });++ it('accepts the extremes: 0 demotes hard, 2 promotes', () => {+ const map = parseModelWeightOverrides('{"never": 0, "boost": 2}');+ expect(map.get('never')).toBe(0);+ expect(map.get('boost')).toBe(2);+ });++ it('multiplies only the scores of overridden models', () => {+ const overrides = new Map([['gpt-4o', 0.2]]);+ expect(applyModelWeightOverride(0.8, 'gpt-4o', overrides)).toBeCloseTo(0.16);+ expect(applyModelWeightOverride(0.8, 'other-model', overrides)).toBe(0.8);+ });++ it('a zero multiplier zeros the score without disabling the model', () => {+ const overrides = new Map([['slow', 0]]);+ expect(applyModelWeightOverride(0.7, 'slow', overrides)).toBe(0);+ expect(applyModelWeightOverride(0.7, 'fine', overrides)).toBe(0.7);+ });++ it('reads the process env lazily and caches it', () => {+ process.env.MODEL_ROUTING_OVERRIDES = '{"cached": 0.3}';+ expect(getModelWeightOverrides().get('cached')).toBe(0.3);++ // The cache is stable even if the env changes afterwards (fixed at boot).+ process.env.MODEL_ROUTING_OVERRIDES = '{"other": 0.9}';+ expect(getModelWeightOverrides().get('cached')).toBe(0.3);++ // ...and the test seam forgets it so a new value takes effect.+ resetModelWeightOverrides();+ expect(getModelWeightOverrides().get('other')).toBe(0.9);+ });+});diff --git a/server/src/__tests__/services/router-bandit.test.ts b/server/src/__tests__/services/router-bandit.test.tsindex 2c0a508f..37823735 100644--- a/server/src/__tests__/services/router-bandit.test.ts+++ b/server/src/__tests__/services/router-bandit.test.ts@@ -4,6 +4,7 @@ import {getCustomWeights, setCustomWeights, getExploreEnabled, setExploreEnabled,getCommunityPrior, setCommunityPriors, getCommunityPriorEnabled, setCommunityPriorEnabled,} from '../../services/router.js';+import { resetModelWeightOverrides } from '../../services/model-weight-overrides.js';import * as ratelimit from '../../services/ratelimit.js';import { getDb, initDb } from '../../db/index.js';@@ -225,6 +226,30 @@ describe('bandit router', () => {expect(withExplore['new'] ?? 0).toBeGreaterThan(0);});+ it('exploration never probes a model zeroed out via MODEL_ROUTING_OVERRIDES (#738)', () => {+ // A weight-0 model never wins a bandit draw, so it never accumulates the+ // samples that would graduate it out of the unmeasured pool — without the+ // probe exclusion it would receive explore traffic forever.+ addModel({ platform: 'google', modelId: 'old', name: 'Old', intelligenceRank: 1, sizeLabel: 'Frontier', budget: '~50M', priority: 1 });+ addModel({ platform: 'groq', modelId: 'new', name: 'New', intelligenceRank: 1, sizeLabel: 'Frontier', budget: '~50M', priority: 2 });+ addHistory('google', 'old', { successes: 500, failures: 0, outTokens: 1000, latencyMs: 300, ttfbMs: 100 });+ setRoutingStrategy('balanced');+ refreshStatsCache(getDb(), true);+ setExploreEnabled(true);++ const prev = process.env.MODEL_ROUTING_OVERRIDES;+ process.env.MODEL_ROUTING_OVERRIDES = '{"new": 0}';+ resetModelWeightOverrides();+ try {+ const counts = pickCounts(500);+ expect(counts['new'] ?? 0).toBe(0);+ } finally {+ if (prev === undefined) delete process.env.MODEL_ROUTING_OVERRIDES;+ else process.env.MODEL_ROUTING_OVERRIDES = prev;+ resetModelWeightOverrides();+ }+ });+it('community priors persist, drop invalid entries, and cap effective sample size (#685)', () => {expect(getCommunityPrior('groq', 'llama', undefined)).toBeUndefined();diff --git a/server/src/services/model-weight-overrides.ts b/server/src/services/model-weight-overrides.tsnew file mode 100644index 00000000..4d8ceeeb--- /dev/null+++ b/server/src/services/model-weight-overrides.ts@@ -0,0 +1,76 @@+// ── Per-model routing weight overrides (#738) ────────────────────────────────+//+// Operators who run a relay with several models sometimes want to keep a model+// around (manual priority may still select it) while making the bandit far less+// likely to pick it — a slow, poor-quality, or just less-preferred model should+// be demoted without being disabled outright. The routing strategies only offer+// GLOBAL weight vectors (per-strategy presets or the user's 'custom' vector), so+// there was no way to single out one model.+//+// `MODEL_ROUTING_OVERRIDES` is a JSON object mapping model ids to a score+// multiplier, e.g.+//+// MODEL_ROUTING_OVERRIDES='{"gpt-4o": 0.2, "deepseek-v3": 0.8}'+//+// The multiplier is applied to a model's bandit score AFTER combineScore:+// 1.0 → unchanged (explicit no-op)+// <1.0 → demoted (0.0 is the extreme: never picked by the bandit, but a+// manual 'priority' chain can still route to it — "not disabled")+// >1.0 → promoted+// Out-of-range (negative, >2) or non-finite values are dropped, never applied;+// an empty or malformed variable is ignored entirely. Matching is by model_id+// alone (not platform-qualified), consistent with "individual models" in #738.+//+// The override is orthogonal to the strategy's weight vector: it multiplies the+// final score rather than replacing any weight, so it composes with every+// strategy (except 'priority', which has no score — the bandit branch only).++export type ModelWeightOverrides = ReadonlyMap<string, number>;++/** Overrides parsed from `MODEL_ROUTING_OVERRIDES`, cached after first read. */+let cache: ModelWeightOverrides | null = null;++/** Parse the env var. Pure and exported for tests: unknown keys are dropped,+ * values must be finite and in [0, 2]. Returns an empty map on any malformed+ * input (not an object, or unparsable JSON) rather than throwing. */+export function parseModelWeightOverrides(raw: string | undefined): Map<string, number> {+ if (raw === undefined || raw.trim() === '') return new Map();+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return new Map();+ }+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return new Map();++ const out = new Map<string, number>();+ for (const [modelId, value] of Object.entries(parsed)) {+ if (!modelId.trim()) continue;+ if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 2) continue;+ out.set(modelId, value);+ }+ return out;+}++/** The active overrides — parsed lazily from the environment on first use and+ * cached for the life of the process (the env is fixed at boot). */+export function getModelWeightOverrides(): ModelWeightOverrides {+ if (cache === null) cache = parseModelWeightOverrides(process.env.MODEL_ROUTING_OVERRIDES);+ return cache;+}++/** Test seam: forget the cached parse so a changed env var takes effect. */+export function resetModelWeightOverrides(): void {+ cache = null;+}++/** Apply a model's override to a bandit score. `overrides` is injectable for+ * tests; it defaults to the process-wide parsed map. */+export function applyModelWeightOverride(+ score: number,+ modelId: string,+ overrides: ModelWeightOverrides = getModelWeightOverrides(),+): number {+ const override = overrides.get(modelId);+ return override === undefined ? score : score * override;+}diff --git a/server/src/services/router.ts b/server/src/services/router.tsindex 67d7bcc4..52aaa2c6 100644--- a/server/src/services/router.ts+++ b/server/src/services/router.ts@@ -21,6 +21,7 @@ import {observedSpeedRank, TIMEOUT_LATENCY_CAP_MS,} from './scoring.js';import { TIMEOUT_ERROR_MARKERS } from '../lib/error-classify.js';+import { applyModelWeightOverride, getModelWeightOverrides } from './model-weight-overrides.js';import { modelsWithOverriddenField } from './model-state.js';import { parseBudget } from '../lib/budget.js';import { platformDropsResponseFormat } from '../lib/sampling-params.js';@@ -839,7 +840,13 @@ function scoreChainEntry(const headroom = headroomFactor(stats?.monthlyUsedTokens ?? 0, budget);const rl = rateLimitFactor(getPenalty(entry.model_db_id));- const score = combineScore({ reliability, speed, intelligence, headroom, rateLimit: rl }, weights);+ // Per-model env overrides (#738) scale the final score so a slow or+ // poor-quality model is demoted without being disabled outright — a manual+ // 'priority' chain can still select it.+ const score = applyModelWeightOverride(+ combineScore({ reliability, speed, intelligence, headroom, rateLimit: rl }, weights),+ entry.model_id,+ );return { axes: { reliability, speed, intelligence }, headroom, rateLimit: rl, score };}@@ -1551,7 +1558,12 @@ export function routeRequest(estimatedTokens = 1000, skipKeys?: Set<string>, pre// fails, the loop falls through to the scored order as usual. Only for// bandit strategies — Manual is the operator's explicit order.if (strategy !== 'priority' && getExploreEnabled() && Math.random() < EXPLORE_CHANCE) {+ // A model the operator zeroed out via MODEL_ROUTING_OVERRIDES never wins a+ // bandit draw, so it would stay under EXPLORE_MIN_SAMPLES forever and become+ // a perpetual probe target — the explicit ban outranks exploration.+ const overrides = getModelWeightOverrides();const unmeasured = sortedChain.filter(e => {+ if (overrides.get(e.model_id) === 0) return false;const stats = statsCache?.get(modelStatsKey(e.platform, e.model_id, e.endpoint_scope));return (stats?.successes ?? 0) + (stats?.failures ?? 0) < EXPLORE_MIN_SAMPLES;});