Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

feat(ui): the model and wire layer for operator-defined auto-router tier sets (#38602)

tin-berri3002994c0e7f
diff --git a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
index de6c9cd72fb..9894e26d552 100644
--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
@@ -24,7 +24,8 @@ import EscalationKeywords from "./EscalationKeywords";
import KeywordTierRules, { KeywordTierRule } from "./KeywordTierRules";
import SemanticKeywordMatching from "./SemanticKeywordMatching";
import { type DimensionWeights, type TierBoundaries, type TokenThresholds } from "./heuristic_scoring_knobs";
-import { type TierRow, activeTierRows, resolveComplexityDefaultModel } from "./tier_rows";
+import { type CustomTierSet, type TierRow, activeTierRows, resolveComplexityDefaultModel } from "./tier_rows";
+export type { CustomTierSet, TierRow } from "./tier_rows";
export type { DimensionWeights, TierBoundaries, TokenThresholds };
@@ -133,7 +134,12 @@ export const heuristicScoringRoleFor = (
};
export const heuristicScoringRole = (value: ComplexityRouterConfigValue): HeuristicScoringRole =>
- heuristicScoringRoleFor(value.classifier_type, value.classifier_fallback);
+ value.custom_tier_set ? "never" : heuristicScoringRoleFor(value.classifier_type, value.classifier_fallback);
+
+// Derived, never written into the value, so undoing a tier edit reverts the form with nothing left behind.
+export const effectiveClassifierType = (
+ value: Pick<ComplexityRouterConfigValue, "custom_tier_set" | "classifier_type">,
+): ClassifierType => (value.custom_tier_set ? "llm" : value.classifier_type);
export type AdaptiveEligible = "all" | "classified_tier";
@@ -179,6 +185,7 @@ export interface ComplexityRouterConfigValue {
* params object is held, not just reasoning_effort, so keys authored in config.yaml survive an
* edit round-trip.
*/
+ custom_tier_set?: CustomTierSet;
tier_model_params?: TierModelParamsByTier;
}
@@ -242,6 +249,104 @@ export const DEFAULT_HEURISTIC_FIRST_MAX_TIER = "SIMPLE";
*/
export const HEURISTIC_FIRST_MAX_TIER_KEYS = TIER_KEYS.slice(0, -1);
+const AffinityControls: React.FC<{
+ value: ComplexityRouterConfigValue;
+ onChange: (value: ComplexityRouterConfigValue) => void;
+}> = ({ value, onChange }) => (
+ <>
+ <div className="flex items-center gap-2 mb-2">
+ <Switch
+ checked={value.deployment_affinity ?? DEFAULT_DEPLOYMENT_AFFINITY}
+ onCheckedChange={(deploymentAffinity) => onChange({ ...value, deployment_affinity: deploymentAffinity })}
+ aria-label="Pin a session to one deployment per model group"
+ />
+ <strong className="font-semibold">Pin a session to one deployment per model group</strong>
+ </div>
+ <span className="block text-xs mb-3 text-muted-foreground">
+ Keeps a session on the same deployment within a group, so provider prompt caches stay warm. Turn off to
+ load-balance every turn.
+ </span>
+ <div className="flex items-center gap-2 mb-2">
+ <Switch
+ checked={value.session_affinity ?? DEFAULT_SESSION_AFFINITY}
+ onCheckedChange={(sessionAffinity) => onChange({ ...value, session_affinity: sessionAffinity })}
+ aria-label="Pin a session to its first model"
+ />
+ <strong className="font-semibold">Pin a session to its first model</strong>
+ </div>
+ <span className="block text-xs text-muted-foreground">
+ Keeps a session on its first turn&apos;s model instead of re-classifying each turn. Also pins the deployment.
+ </span>
+ </>
+);
+
+const PlanModeOverrideControls: React.FC<{
+ value: ComplexityRouterConfigValue;
+ onChange: (value: ComplexityRouterConfigValue) => void;
+ planModeTierOptions: { value: string; label: string }[];
+}> = ({ value, onChange, planModeTierOptions }) => (
+ <>
+ <div className="flex items-center gap-2 mb-2">
+ <Switch
+ checked={value.plan_mode_min_tier !== undefined}
+ disabled={planModeTierOptions.length === 0}
+ onCheckedChange={(enabled) =>
+ onChange({
+ ...value,
+ plan_mode_min_tier: enabled ? planModeTierOptions.at(-1)?.value : undefined,
+ })
+ }
+ aria-label="Route plan-mode requests to a minimum tier"
+ />
+ <strong className="font-semibold">Route plan-mode requests to a minimum tier</strong>
+ </div>
+ <span className="block text-xs mb-3 text-muted-foreground">
+ Requests from coding agents in plan mode (Claude Code, GitHub Copilot) route to at least this tier. The classifier
+ still wins when it picks higher, and the override only lasts while plan mode is active.
+ {planModeTierOptions.length === 0 && " Add models to a tier to enable this."}
+ </span>
+ {value.plan_mode_min_tier !== undefined && (
+ <div style={{ maxWidth: 320 }}>
+ <Select
+ items={planModeTierOptions}
+ value={value.plan_mode_min_tier}
+ onValueChange={(tier: string | null) => tier && onChange({ ...value, plan_mode_min_tier: tier })}
+ >
+ <SelectTrigger aria-label="Plan-mode minimum tier" className="w-full">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {planModeTierOptions.map((option) => (
+ <SelectItem key={option.value} value={option.value}>
+ {option.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ )}
+ </>
+);
+
+const ResponseFormatControls: React.FC<{
+ value: ComplexityRouterConfigValue;
+ onChange: (value: ComplexityRouterConfigValue) => void;
+}> = ({ value, onChange }) => (
+ <>
+ <div className="flex items-center gap-2 mb-2">
+ <Switch
+ checked={value.return_raw_model_name ?? false}
+ onCheckedChange={(returnRawModelName) => onChange({ ...value, return_raw_model_name: returnRawModelName })}
+ aria-label="Return raw model name"
+ />
+ <strong className="font-semibold">Return raw model name</strong>
+ </div>
+ <span className="block text-xs text-muted-foreground">
+ Return the resolved underlying model name in responses instead of the autorouter alias.
+ </span>
+ </>
+);
+
const ComplexityRouterConfig: React.FC<ComplexityRouterConfigProps> = ({
modelInfo,
value,
@@ -459,104 +564,19 @@ const ComplexityRouterConfig: React.FC<ComplexityRouterConfigProps> = ({
{
key: "affinity",
label: <strong className="text-foreground font-semibold">Advanced: Affinity</strong>,
- children: (
- <>
- <div className="flex items-center gap-2 mb-2">
- <Switch
- checked={value.deployment_affinity ?? DEFAULT_DEPLOYMENT_AFFINITY}
- onCheckedChange={(deploymentAffinity) =>
- onChange({ ...value, deployment_affinity: deploymentAffinity })
- }
- aria-label="Pin a session to one deployment per model group"
- />
- <strong className="font-semibold">Pin a session to one deployment per model group</strong>
- </div>
- <span className="block text-xs mb-3 text-muted-foreground">
- Keeps a session on the same deployment within a group, so provider prompt caches stay warm. Turn off
- to load-balance every turn.
- </span>
- <div className="flex items-center gap-2 mb-2">
- <Switch
- checked={value.session_affinity ?? DEFAULT_SESSION_AFFINITY}
- onCheckedChange={(sessionAffinity) => onChange({ ...value, session_affinity: sessionAffinity })}
- aria-label="Pin a session to its first model"
- />
- <strong className="font-semibold">Pin a session to its first model</strong>
- </div>
- <span className="block text-xs text-muted-foreground">
- Keeps a session on its first turn&apos;s model instead of re-classifying each turn. Also pins the
- deployment.
- </span>
- </>
- ),
+ children: <AffinityControls value={value} onChange={onChange} />,
},
{
key: "plan-mode",
label: <strong className="text-foreground font-semibold">Advanced: Plan-Mode Override</strong>,
children: (
- <>
- <div className="flex items-center gap-2 mb-2">
- <Switch
- checked={value.plan_mode_min_tier !== undefined}
- disabled={planModeTierOptions.length === 0}
- onCheckedChange={(enabled) =>
- onChange({
- ...value,
- plan_mode_min_tier: enabled ? planModeTierOptions.at(-1)?.value : undefined,
- })
- }
- aria-label="Route plan-mode requests to a minimum tier"
- />
- <strong className="font-semibold">Route plan-mode requests to a minimum tier</strong>
- </div>
- <span className="block text-xs mb-3 text-muted-foreground">
- Requests from coding agents in plan mode (Claude Code, GitHub Copilot) route to at least this tier.
- The classifier still wins when it picks higher, and the override only lasts while plan mode is active.
- {planModeTierOptions.length === 0 && " Add models to a tier to enable this."}
- </span>
- {value.plan_mode_min_tier !== undefined && (
- <div style={{ maxWidth: 320 }}>
- <Select
- items={planModeTierOptions}
- value={value.plan_mode_min_tier}
- onValueChange={(tier: string | null) => tier && onChange({ ...value, plan_mode_min_tier: tier })}
- >
- <SelectTrigger aria-label="Plan-mode minimum tier" className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {planModeTierOptions.map((option) => (
- <SelectItem key={option.value} value={option.value}>
- {option.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- )}
- </>
+ <PlanModeOverrideControls value={value} onChange={onChange} planModeTierOptions={planModeTierOptions} />
),
},
{
key: "response",
label: <strong className="text-foreground font-semibold">Advanced: Response Format</strong>,
- children: (
- <>
- <div className="flex items-center gap-2 mb-2">
- <Switch
- checked={value.return_raw_model_name ?? false}
- onCheckedChange={(returnRawModelName) =>
- onChange({ ...value, return_raw_model_name: returnRawModelName })
- }
- aria-label="Return raw model name"
- />
- <strong className="font-semibold">Return raw model name</strong>
- </div>
- <span className="block text-xs text-muted-foreground">
- Return the resolved underlying model name in responses instead of the autorouter alias.
- </span>
- </>
- ),
+ children: <ResponseFormatControls value={value} onChange={onChange} />,
},
...(onEscalationKeywordsChange
? [
diff --git a/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.test.ts b/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.test.ts
index 325122f755a..ea9ee1bb305 100644
--- a/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.test.ts
+++ b/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.test.ts
@@ -5,13 +5,14 @@ import {
getKeywordTierRulesError,
getClassifierModelError,
getMissingTiersError,
+ hydrateCustomTierSet,
getSemanticConfigError,
getTierLabelsError,
hydrateTierLabels,
BuildComplexityRouterConfigParams,
dryRunRejection,
} from "./build_complexity_router_config";
-import { activeTierRows } from "./tier_rows";
+import { CUSTOM_TIER_RESTRICTIONS, activeTierRows } from "./tier_rows";
const tiers = {
SIMPLE: ["gpt-4o-mini"],
@@ -47,13 +48,14 @@ const baseParams: BuildComplexityRouterConfigParams = {
describe("buildComplexityRouterConfig", () => {
it("emits tiers, classifier_type, and escalation_keywords when nothing else is configured", () => {
const config = buildComplexityRouterConfig(baseParams);
- expect(config).toEqual({
+ const expected = {
tiers,
classifier_type: "heuristic",
session_affinity: false,
deployment_affinity: true,
escalation_keywords: ["LITELLM ESCALATE"],
- });
+ };
+ expect(config).toEqual(expected);
});
it("trims escalation keywords and drops blank entries", () => {
@@ -215,13 +217,14 @@ describe("buildComplexityRouterConfig", () => {
});
it("omits adaptive fields when adaptive is disabled even if weights linger in state", () => {
- const config = buildComplexityRouterConfig({
+ const params = {
...baseParams,
adaptive: false,
adaptiveWeights: { quality: 0.9, cost: 0.1 },
tierDistancePenalty: 2,
- adaptiveEligible: "classified_tier",
- });
+ adaptiveEligible: "classified_tier" as const,
+ };
+ const config = buildComplexityRouterConfig(params);
expect(config.adaptive).toBeUndefined();
expect(config.adaptive_weights).toBeUndefined();
expect(config.tier_distance_penalty).toBeUndefined();
@@ -249,13 +252,14 @@ describe("buildComplexityRouterConfig", () => {
});
it("includes tier_distance_penalty when adaptive is enabled with eligible='all'", () => {
- const config = buildComplexityRouterConfig({
+ const params = {
...baseParams,
adaptive: true,
adaptiveWeights: { quality: 0.6, cost: 0.4 },
tierDistancePenalty: 0.75,
- adaptiveEligible: "all",
- });
+ adaptiveEligible: "all" as const,
+ };
+ const config = buildComplexityRouterConfig(params);
expect(config.adaptive).toBe(true);
expect(config.adaptive_weights).toEqual({ quality: 0.6, cost: 0.4 });
expect(config.tier_distance_penalty).toBe(0.75);
@@ -263,13 +267,14 @@ describe("buildComplexityRouterConfig", () => {
});
it("omits tier_distance_penalty when eligible='classified_tier', since the penalty doesn't apply there", () => {
- const config = buildComplexityRouterConfig({
+ const params = {
...baseParams,
adaptive: true,
adaptiveWeights: { quality: 0.6, cost: 0.4 },
tierDistancePenalty: 0.75,
- adaptiveEligible: "classified_tier",
- });
+ adaptiveEligible: "classified_tier" as const,
+ };
+ const config = buildComplexityRouterConfig(params);
expect(config.adaptive).toBe(true);
expect(config.adaptive_eligible).toBe("classified_tier");
expect(config.tier_distance_penalty).toBeUndefined();
@@ -695,6 +700,19 @@ describe("getClassifierModelError", () => {
);
});
+ it("asks for a model under an edited tier set even while the stored type still reads heuristic", () => {
+ const customSet = {
+ tiers: [
+ { id: "a", name: "CASUAL", definition: "d", models: ["m"] },
+ { id: "b", name: "AUDIT", definition: "d", models: ["m"] },
+ ],
+ fallback_tier_id: "a",
+ };
+ expect(getClassifierModelError({ classifier_type: "heuristic", custom_tier_set: customSet })).toContain(
+ "an edited tier set routes with the LLM classifier",
+ );
+ });
+
it("stays quiet once a model is chosen", () => {
expect(
getClassifierModelError({ classifier_type: "llm", classifier_llm_config: { model: "m", timeout_ms: 3000 } }),
@@ -761,6 +779,170 @@ describe("heuristic_first", () => {
});
});
+describe("buildComplexityRouterConfig with an edited tier set", () => {
+ const customTierSet = {
+ tiers: [
+ { id: "CASUAL", name: "CASUAL", definition: "small talk", models: ["gpt-4o-mini"] },
+ { id: "sec", name: " SECURITY_REVIEW ", definition: " audits and vulnerability review ", models: ["o1-preview"] },
+ ],
+ fallback_tier_id: "CASUAL",
+ };
+ const build = (overrides: Partial<BuildComplexityRouterConfigParams> = {}) => {
+ const params: BuildComplexityRouterConfigParams = {
+ ...baseParams,
+ customTierSet,
+ classifierType: "llm",
+ classifierLlmConfig: { model: "gpt-4o-mini", timeout_ms: 3000 },
+ ...overrides,
+ };
+ return buildComplexityRouterConfig(params);
+ };
+
+ it("writes tiers, tier_definitions and fallback_tier from the rows, trimmed to what the backend matches", () => {
+ const payload = build();
+ expect(payload.tiers).toEqual({ CASUAL: ["gpt-4o-mini"], SECURITY_REVIEW: ["o1-preview"] });
+ expect(payload.tier_definitions).toEqual([
+ { name: "CASUAL", description: "small talk" },
+ { name: "SECURITY_REVIEW", description: "audits and vulnerability review" },
+ ]);
+ expect(payload.fallback_tier).toBe("CASUAL");
+ });
+
+ it("forces the LLM classifier even when the form still holds heuristic, which the backend rejects", () => {
+ expect(build({ classifierType: "heuristic" }).classifier_type).toBe("llm");
+ });
+
+ it("turns session pinning off rather than leaving a stale true the backend rejects", () => {
+ expect(build({ sessionAffinity: true }).session_affinity).toBe(false);
+ });
+
+ it("omits a definition on a built-in name, letting the backend rubric supply it", () => {
+ const payload = build({
+ customTierSet: {
+ tiers: [{ id: "SIMPLE", name: "SIMPLE", definition: "", models: ["gpt-4o-mini"] }, customTierSet.tiers[1]],
+ fallback_tier_id: "SIMPLE",
+ },
+ });
+ expect(payload.tier_definitions?.[0]).toEqual({ name: "SIMPLE" });
+ });
+
+ it("drops the replacement prompt and the rubric preset, which live inside classifier_llm_config", () => {
+ const payload = build({
+ classifierLlmConfig: {
+ model: "gpt-4o-mini",
+ timeout_ms: 3000,
+ system_prompt: "replace the whole rubric",
+ classification_rubric: "agentic",
+ },
+ });
+ expect(payload.classifier_llm_config).toEqual({ model: "gpt-4o-mini", timeout_ms: 3000 });
+ });
+
+ it.each(
+ Object.entries(CUSTOM_TIER_RESTRICTIONS).flatMap(([name, restriction]) =>
+ restriction.omit.map((key) => [name, key] as const),
+ ),
+ )("drops %s's %s key, which an edited tier set never uses", (_name, key) => {
+ const loaded: Partial<BuildComplexityRouterConfigParams> = {
+ tierLabels: { SIMPLE: "Cheap" },
+ escalationKeywords: ["LITELLM ESCALATE"],
+ adaptive: true,
+ classifierFallback: "heuristic",
+ tierBoundaries: { simple_medium: 0.1, medium_complex: 0.25, complex_reasoning: 0.5 },
+ tokenThresholds: { short: 1, long: 2 },
+ dimensionWeights: { length: 1 },
+ reasoningOverrideMinScore: 0.5,
+ heuristicFirstMaxTier: "SIMPLE",
+ customTechnicalKeywords: ["kubernetes"],
+ };
+ const emittingType = key === "heuristic_first_max_tier" ? "heuristic_first" : "llm";
+ expect(buildComplexityRouterConfig({ ...baseParams, ...loaded, classifierType: emittingType })).toHaveProperty(key);
+ expect(build(loaded)).not.toHaveProperty(key);
+ });
+
+ it("drops the local-scorer threshold left behind by a heuristic_first router, which the backend rejects here", () => {
+ const payload = build({ classifierType: "heuristic_first", heuristicFirstMaxTier: "SIMPLE" });
+ expect(payload).not.toHaveProperty("heuristic_first_max_tier");
+ expect(payload.classifier_type).toBe("llm");
+ });
+
+ it("keeps the classifier context knobs the operator set, which the forced LLM classifier reads", () => {
+ const payload = build({ classifierType: "heuristic", classifierContextWindowSize: 5 });
+ expect(payload.classifier_context_window_size).toBe(5);
+ expect(payload.classifier_llm_config).toEqual({ model: "gpt-4o-mini", timeout_ms: 3000 });
+ });
+
+ it("carries the plan-mode floor as the row's name, not the row id the form holds", () => {
+ expect(build({ planModeMinTier: "sec" }).plan_mode_min_tier).toBe("SECURITY_REVIEW");
+ });
+
+ it("leaves the floor off when its row is gone, the same rule hydration and the editor apply", () => {
+ expect(build({ planModeMinTier: "removed-row" })).not.toHaveProperty("plan_mode_min_tier");
+ });
+
+ it("keys per-model params by tier name on the wire while the editor keys them by row id", () => {
+ const payload = build({ tierModelParams: { sec: { "o1-preview": { reasoning_effort: "high" } } } });
+ expect(payload.tier_model_configs).toEqual({
+ SECURITY_REVIEW: [{ model_name: "o1-preview", litellm_params: { reasoning_effort: "high" } }],
+ });
+ });
+
+ it("leaves behind no params for a row that is no longer in the set", () => {
+ const payload = build({ tierModelParams: { removed: { "o1-preview": { reasoning_effort: "high" } } } });
+ expect(payload).not.toHaveProperty("tier_model_configs");
+ });
+});
+
+describe("hydrateCustomTierSet", () => {
+ it("returns nothing when the stored config has no tier_definitions, keeping built-in routers built-in", () => {
+ expect(hydrateCustomTierSet({ tiers: { SIMPLE: ["a"] } })).toBeUndefined();
+ });
+
+ it("round-trips a payload this form built, so an edit save cannot lose a key", () => {
+ const roundTripParams: BuildComplexityRouterConfigParams = {
+ ...baseParams,
+ classifierType: "llm",
+ classifierLlmConfig: { model: "gpt-4o-mini", timeout_ms: 3000 },
+ customTierSet: {
+ tiers: [
+ { id: "CASUAL", name: "CASUAL", definition: "small talk", models: ["gpt-4o-mini"] },
+ { id: "sec", name: "SECURITY_REVIEW", definition: "audits", models: ["o1-preview"] },
+ ],
+ fallback_tier_id: "sec",
+ },
+ };
+ const payload = buildComplexityRouterConfig(roundTripParams);
+ const hydrated = hydrateCustomTierSet(payload);
+ expect(hydrated?.tiers).toEqual([
+ { id: "stored-0", name: "CASUAL", definition: "small talk", models: ["gpt-4o-mini"] },
+ { id: "stored-1", name: "SECURITY_REVIEW", definition: "audits", models: ["o1-preview"] },
+ ]);
+ expect(hydrated?.tiers.find((row) => row.id === hydrated.fallback_tier_id)?.name).toBe("SECURITY_REVIEW");
+ });
+
+ it("mints the canonical key for a built-in name so every pointer into the set is a row id", () => {
+ const hydrated = hydrateCustomTierSet({
+ tier_definitions: [{ name: "SIMPLE" }, { name: "AUDIT", description: "audits" }],
+ tiers: { SIMPLE: ["a"], AUDIT: ["b"] },
+ fallback_tier: "AUDIT",
+ });
+ expect(hydrated?.tiers.map((row) => row.id)).toEqual(["SIMPLE", "stored-1"]);
+ });
+
+ it("matches a hand-written config's tier pool case-insensitively rather than losing its models", () => {
+ const hydrated = hydrateCustomTierSet({
+ tier_definitions: [
+ { name: "audit", description: "x" },
+ { name: "CASUAL", description: "y" },
+ ],
+ tiers: { Audit: ["m1"], CASUAL: ["m2"] },
+ fallback_tier: " audit ",
+ });
+ expect(hydrated?.tiers[0].models).toEqual(["m1"]);
+ expect(hydrated?.fallback_tier_id).toBe(hydrated?.tiers[0].id);
+ });
+});
+
describe("dryRunRejection", () => {
it("blocks the save on a rejection whose message is missing, which the write would return as a raw 400", () => {
expect(dryRunRejection({ valid: false })).toBe("The proxy rejected this auto-router configuration");
diff --git a/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.ts b/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.ts
index eb014092ec2..9ff256323d6 100644
--- a/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.ts
+++ b/ui/litellm-dashboard/src/components/add_model/build_complexity_router_config.ts
@@ -1,7 +1,21 @@
import { KeywordTierRule } from "./KeywordTierRules";
-import { type TierRow, activeTierName, tierRowById } from "./tier_rows";
+import {
+ type CustomTierSet,
+ type TierRow,
+ CUSTOM_TIER_OMITTED_KEYS,
+ activeTierName,
+ sameTierIdentity,
+ tierDefinitionsFromRows,
+ tierRowById,
+ tierRowByName,
+} from "./tier_rows";
import { emptyKeywordTierRuleIndexes, serializeKeywordTierRules } from "./complexity_router_keywords";
-import { TierModelParams, TierModelParamsByTier, serializeTierModelConfigs } from "./complexity_router_tiers";
+import {
+ TierModelParams,
+ TierModelParamsByTier,
+ normalizeTierModels,
+ serializeTierModelConfigs,
+} from "./complexity_router_tiers";
import {
AdaptiveEligible,
AdaptiveRouterWeights,
@@ -13,6 +27,7 @@ import {
ComplexityTiers,
DimensionWeights,
TIER_KEYS,
+ effectiveClassifierType,
TIER_DESCRIPTIONS,
TierBoundaries,
TokenThresholds,
@@ -78,6 +93,7 @@ const scorerKnobPayload = ({
export interface BuildComplexityRouterConfigParams {
tiers: ComplexityTiers;
+ customTierSet?: CustomTierSet;
defaultModel: string | undefined;
planModeMinTier: string | undefined;
tierLabels: ComplexityTierLabels | undefined;
@@ -108,11 +124,26 @@ export interface BuildComplexityRouterConfigParams {
tierModelParams?: TierModelParamsByTier;
}
+/**
+ * The message to surface when the dry-run rejects a save, or null to let it through.
+ *
+ * Gated on `valid` alone. The verdict's `valid` is derived from `error` server side today, but the
+ * two arrive as independent fields, so reading `error` as the gate would let a rejection whose
+ * message is missing or blank through to the write and back as a raw 400. A transport failure fails
+ * open as `{valid: true}`, which this passes, leaving the write gate authoritative.
+ */
export const dryRunRejection = (verdict: { valid: boolean; error?: string | null }): string | null =>
verdict.valid ? null : verdict.error?.trim() || "The proxy rejected this auto-router configuration";
+export interface TierDefinitionPayload {
+ name: string;
+ description?: string;
+}
+
export interface ComplexityRouterConfigPayload {
- tiers: ComplexityTiers;
+ tiers: ComplexityTiers | Record<string, string[]>;
+ tier_definitions?: TierDefinitionPayload[];
+ fallback_tier?: string;
default_model?: string;
plan_mode_min_tier?: string;
tier_labels?: ComplexityTierLabels;
@@ -180,7 +211,7 @@ export const getTierLabelsError = (tierLabels: ComplexityTierLabels | undefined)
// Requires every active tier non-empty, so the create form can never reach the
// resolveComplexityDefaultModel === undefined case. The edit modal allows a partially filled
-// set, which is why it keeps its own !defaultModel guard after deriving.
+// built-in set, which is why it keeps its own !defaultModel guard after deriving.
export const getMissingTiersError = (rows: readonly TierRow[]): string | null => {
const missing = rows.filter((row) => row.models.length === 0).map(activeTierName);
if (missing.length === 0) return null;
@@ -194,8 +225,9 @@ export const getPlanModeTierError = (planModeMinTier: string | undefined, rows:
return `The plan-mode minimum tier (${floor ? activeTierName(floor) : planModeMinTier}) has no models. Add one or turn the override off.`;
};
-// The tier is a free string since #37413, and _validate_keyword_rule_tiers matches it EXACTLY, so a
-// rule naming a tier this router does not have is a raw 400 unless the gate catches it first.
+// The orphan check compares exactly, not casefold: _validate_keyword_rule_tiers is exact
+// membership, so a rule left pointing at a differently cased name would clear a gate the
+// backend then rejects.
export const getKeywordTierRulesError = (
keywordTierRules: KeywordTierRule[],
rows: readonly TierRow[],
@@ -209,14 +241,16 @@ export const getKeywordTierRulesError = (
return `Keyword rule(s) ${orphaned.join(", ")} route to a tier this router no longer has`;
};
-// The submit gate and the submit handler both read this, so a disabled button and a refused submit
-// cannot disagree about why.
+// An edited tier set forces the LLM classifier, so the model requirement follows the EFFECTIVE type.
+// Both forms' submit gates and their submit handlers read this one answer so they cannot drift.
export const getClassifierModelError = (
- config: Pick<ComplexityRouterConfigValue, "classifier_type" | "classifier_llm_config">,
-): string | null =>
- usesLlmClassifier(config.classifier_type) && !config.classifier_llm_config?.model
- ? "Please select a classifier model, or switch back to Heuristic"
- : null;
+ config: Pick<ComplexityRouterConfigValue, "custom_tier_set" | "classifier_type" | "classifier_llm_config">,
+): string | null => {
+ if (!usesLlmClassifier(effectiveClassifierType(config)) || config.classifier_llm_config?.model) return null;
+ return config.custom_tier_set
+ ? "Please select a classifier model: an edited tier set routes with the LLM classifier"
+ : "Please select a classifier model, or switch back to Heuristic";
+};
export const getSemanticConfigError = ({
semanticMatchingEnabled,
@@ -231,8 +265,115 @@ export const getSemanticConfigError = ({
return null;
};
+export const customTierWireFields = (
+ customTierSet: CustomTierSet,
+ classifierLlmConfig: ClassifierLLMConfig | undefined,
+ planModeMinTierId: string | undefined,
+): Partial<ComplexityRouterConfigPayload> => {
+ const rows = customTierSet.tiers;
+ const fallback = tierRowById(rows, customTierSet.fallback_tier_id);
+ const floor = tierRowById(rows, planModeMinTierId);
+ return {
+ tiers: Object.fromEntries(rows.map((row) => [activeTierName(row), row.models])),
+ tier_definitions: tierDefinitionsFromRows(rows),
+ ...(fallback && { fallback_tier: activeTierName(fallback) }),
+ classifier_type: "llm",
+ // Rebuilt from the two fields an edited tier set allows. The backend rejects system_prompt and
+ // classification_rubric beside tier_definitions, and both live inside this object rather than at
+ // the top level the omit list covers.
+ ...(classifierLlmConfig && {
+ classifier_llm_config: { model: classifierLlmConfig.model, timeout_ms: classifierLlmConfig.timeout_ms },
+ }),
+ session_affinity: false,
+ ...(floor && { plan_mode_min_tier: activeTierName(floor) }),
+ };
+};
+
+// plan_mode_min_tier rides the strip list because the base payload carries it as a row id;
+// customTierWireFields re-emits it as the row's name, and an unresolvable floor stays off.
+const CUSTOM_TIER_STRIPPED_KEYS: readonly string[] = [...CUSTOM_TIER_OMITTED_KEYS, "plan_mode_min_tier"];
+
+export const hydrateCustomTierSet = (parsedConfig: {
+ tier_definitions?: unknown;
+ fallback_tier?: unknown;
+ tiers?: unknown;
+}): CustomTierSet | undefined => {
+ if (!Array.isArray(parsedConfig.tier_definitions) || parsedConfig.tier_definitions.length === 0) return undefined;
+ const storedTiers =
+ typeof parsedConfig.tiers === "object" && parsedConfig.tiers !== null && !Array.isArray(parsedConfig.tiers)
+ ? Object.entries(parsedConfig.tiers as Record<string, unknown>)
+ : [];
+ const rows = parsedConfig.tier_definitions.flatMap((entry, index): TierRow[] => {
+ if (typeof entry !== "object" || entry === null) return [];
+ const { name, description } = entry as { name?: unknown; description?: unknown };
+ if (typeof name !== "string" || !name.trim()) return [];
+ return [
+ {
+ id: TIER_KEYS.find((tier) => sameTierIdentity(tier, name)) ?? `stored-${index}`,
+ name: name.trim(),
+ definition: typeof description === "string" ? description.trim() : "",
+ models: normalizeTierModels(storedTiers.find(([tier]) => sameTierIdentity(tier, name))?.[1]),
+ },
+ ];
+ });
+ if (rows.length === 0) return undefined;
+ const storedFallback = typeof parsedConfig.fallback_tier === "string" ? parsedConfig.fallback_tier : "";
+ return { tiers: rows, fallback_tier_id: tierRowByName(rows, storedFallback)?.id ?? "" };
+};
+
+// Ids are session-ephemeral, so a stored floor hydrates by name; unresolvable means off, the same
+// rule the editor and the wire apply.
+export const hydratePlanModeMinTier = (
+ stored: unknown,
+ customTierSet: CustomTierSet | undefined,
+): string | undefined => {
+ if (typeof stored !== "string" || !stored.trim()) return undefined;
+ if (!customTierSet) return stored;
+ return tierRowByName(customTierSet.tiers, stored)?.id;
+};
+
+const classifierWireFields = (
+ effectiveType: ClassifierType,
+ {
+ classifierLlmConfig,
+ classifierFallback,
+ heuristicFirstMaxTier,
+ classifierContextWindowSize,
+ classifierContextBudgetChars,
+ classifierContextIncludeAssistantTurns,
+ }: Pick<
+ BuildComplexityRouterConfigParams,
+ | "classifierLlmConfig"
+ | "classifierFallback"
+ | "heuristicFirstMaxTier"
+ | "classifierContextWindowSize"
+ | "classifierContextBudgetChars"
+ | "classifierContextIncludeAssistantTurns"
+ >,
+): Partial<ComplexityRouterConfigPayload> => ({
+ ...(usesLlmClassifier(effectiveType) &&
+ classifierLlmConfig && { classifier_llm_config: normalizeClassifierLlmConfig(classifierLlmConfig) }),
+ ...(usesLlmClassifier(effectiveType) &&
+ classifierFallback !== undefined && { classifier_fallback: classifierFallback }),
+ ...(effectiveType === "heuristic_first" &&
+ heuristicFirstMaxTier?.trim() && { heuristic_first_max_tier: heuristicFirstMaxTier }),
+ ...(usesLlmClassifier(effectiveType) &&
+ classifierContextWindowSize !== undefined && {
+ classifier_context_window_size: classifierContextWindowSize,
+ }),
+ ...(usesLlmClassifier(effectiveType) &&
+ classifierContextBudgetChars !== undefined && {
+ classifier_context_budget_chars: classifierContextBudgetChars,
+ }),
+ ...(usesLlmClassifier(effectiveType) &&
+ classifierContextIncludeAssistantTurns !== undefined && {
+ classifier_context_include_assistant_turns: classifierContextIncludeAssistantTurns,
+ }),
+});
+
export const buildComplexityRouterConfig = ({
tiers,
+ customTierSet,
defaultModel,
planModeMinTier,
tierLabels,
@@ -262,7 +403,12 @@ export const buildComplexityRouterConfig = ({
reasoningOverrideMinScore,
tierModelParams,
}: BuildComplexityRouterConfigParams): ComplexityRouterConfigPayload => {
- const serializedTierModelConfigs = serializeTierModelConfigs(tiers, tierModelParams);
+ const serializedTierModelConfigs = customTierSet
+ ? serializeTierModelConfigs(
+ Object.fromEntries(customTierSet.tiers.map((row) => [activeTierName(row), row.models])),
+ Object.fromEntries(customTierSet.tiers.map((row) => [activeTierName(row), tierModelParams?.[row.id] ?? {}])),
+ )
+ : serializeTierModelConfigs(tiers, tierModelParams);
const cleanedEscalationKeywords = escalationKeywords.map((keyword) => keyword.trim()).filter(Boolean);
const cleanedKeywordTierRules = serializeKeywordTierRules(keywordTierRules);
const cleanedTierLabels = serializeTierLabels(tierLabels);
@@ -275,32 +421,26 @@ export const buildComplexityRouterConfig = ({
reasoningOverrideMinScore,
};
const scorerKnobs = scorerKnobPayload(scorerInputs);
+ const classifierInputs = {
+ classifierLlmConfig,
+ classifierFallback,
+ heuristicFirstMaxTier,
+ classifierContextWindowSize,
+ classifierContextBudgetChars,
+ classifierContextIncludeAssistantTurns,
+ };
+ // An edited tier set forces the LLM classifier, so llm-only inputs must survive a classifier_type
+ // the form never rewrote. The UI gates the same controls on this, not on the raw value.
+ const effectiveType: ClassifierType = customTierSet ? "llm" : classifierType;
- return {
+ const payload: ComplexityRouterConfigPayload = {
tiers,
...(serializedTierModelConfigs && { tier_model_configs: serializedTierModelConfigs }),
...(defaultModel?.trim() && { default_model: defaultModel }),
...(planModeMinTier?.trim() && { plan_mode_min_tier: planModeMinTier }),
...(cleanedTierLabels && { tier_labels: cleanedTierLabels }),
classifier_type: classifierType,
- ...(usesLlmClassifier(classifierType) &&
- classifierLlmConfig && { classifier_llm_config: normalizeClassifierLlmConfig(classifierLlmConfig) }),
- ...(usesLlmClassifier(classifierType) &&
- classifierFallback !== undefined && { classifier_fallback: classifierFallback }),
- ...(classifierType === "heuristic_first" &&
- heuristicFirstMaxTier?.trim() && { heuristic_first_max_tier: heuristicFirstMaxTier }),
- ...(usesLlmClassifier(classifierType) &&
- classifierContextWindowSize !== undefined && {
- classifier_context_window_size: classifierContextWindowSize,
- }),
- ...(usesLlmClassifier(classifierType) &&
- classifierContextBudgetChars !== undefined && {
- classifier_context_budget_chars: classifierContextBudgetChars,
- }),
- ...(usesLlmClassifier(classifierType) &&
- classifierContextIncludeAssistantTurns !== undefined && {
- classifier_context_include_assistant_turns: classifierContextIncludeAssistantTurns,
- }),
+ ...classifierWireFields(effectiveType, classifierInputs),
session_affinity: sessionAffinity,
deployment_affinity: deploymentAffinity,
...(customTechnicalKeywords.length > 0 && { custom_technical_keywords: customTechnicalKeywords }),
@@ -320,4 +460,12 @@ export const buildComplexityRouterConfig = ({
...(returnRawModelName && { return_raw_model_name: true }),
...scorerKnobs,
};
+ if (!customTierSet) return payload;
+ const kept = Object.fromEntries(
+ Object.entries(payload).filter(([key]) => !CUSTOM_TIER_STRIPPED_KEYS.includes(key)),
+ ) as ComplexityRouterConfigPayload;
+ return {
+ ...kept,
+ ...customTierWireFields(customTierSet, classifierLlmConfig, planModeMinTier),
+ };
};
diff --git a/ui/litellm-dashboard/src/components/add_model/complexity_router_tiers.test.ts b/ui/litellm-dashboard/src/components/add_model/complexity_router_tiers.test.ts
index be48ff4958d..b0fab49e80a 100644
--- a/ui/litellm-dashboard/src/components/add_model/complexity_router_tiers.test.ts
+++ b/ui/litellm-dashboard/src/components/add_model/complexity_router_tiers.test.ts
@@ -5,6 +5,7 @@ import {
normalizeTierModels,
pruneTierModelParams,
serializeTierModelConfigs,
+ tierRowLabel,
setTierModelReasoningEffort,
} from "./complexity_router_tiers";
import { resolveComplexityDefaultModel } from "./tier_rows";
@@ -234,3 +235,22 @@ describe("pruneTierModelParams", () => {
expect(pruneTierModelParams(current, "MEDIUM", [])).toBe(current);
});
});
+
+describe("tierRowLabel", () => {
+ it("shows a built-in row's display label while it is untouched", () => {
+ expect(tierRowLabel({ id: "COMPLEX", name: "COMPLEX" })).toBe("Complex");
+ expect(tierRowLabel({ id: "COMPLEX", name: "COMPLEX" }, { COMPLEX: "Deep" })).toBe("Deep");
+ });
+
+ it("shows the operator's name once a built-in row is renamed, since the id stays canonical", () => {
+ expect(tierRowLabel({ id: "COMPLEX", name: "SECURITY_REVIEW" })).toBe("SECURITY_REVIEW");
+ });
+
+ it("shows a custom row's name", () => {
+ expect(tierRowLabel({ id: "stored-1", name: "AUDIT" })).toBe("AUDIT");
+ });
+
+ it("calls an unnamed new row New rather than rendering an empty label", () => {
+ expect(tierRowLabel({ id: "uuid", name: " " })).toBe("New");
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/add_model/complexity_router_tiers.ts b/ui/litellm-dashboard/src/components/add_model/complexity_router_tiers.ts
index ea0d34f6581..8cdb730cfa6 100644
--- a/ui/litellm-dashboard/src/components/add_model/complexity_router_tiers.ts
+++ b/ui/litellm-dashboard/src/components/add_model/complexity_router_tiers.ts
@@ -133,7 +133,30 @@ export const DEFAULT_TIER_LABELS: Record<ComplexityTier, string> = {
REASONING: "Reasoning",
};
+const isBuiltInTier = (tier: string): tier is ComplexityTier => (TIER_ORDER as string[]).includes(tier);
+
+const builtInTierLabel = (
+ tierLabels: Partial<Record<ComplexityTier, string>> | undefined,
+ tier: ComplexityTier,
+): string => tierLabels?.[tier]?.trim() || DEFAULT_TIER_LABELS[tier];
+
+// What a tier row is called on screen. A row the operator named shows that name; an untouched
+// built-in row shows its display label. The one owner for every surface that renders a tier.
+export const tierRowLabel = (
+ row: { id: string; name: string },
+ tierLabels?: Partial<Record<ComplexityTier, string>>,
+): string => {
+ const builtIn = TIER_ORDER.find((tier) => tier === row.id);
+ const named = row.name.trim();
+ if (!builtIn || named !== builtIn) return named || "New";
+ return builtInTierLabel(tierLabels, builtIn);
+};
+
export const tierOptions = (
tierLabels: Partial<Record<ComplexityTier, string>> | undefined,
-): { value: ComplexityTier; label: string }[] =>
- TIER_ORDER.map((tier) => ({ value: tier, label: tierLabels?.[tier]?.trim() || DEFAULT_TIER_LABELS[tier] }));
+ tierNames?: readonly string[],
+): { value: string; label: string }[] =>
+ (tierNames ?? TIER_ORDER).map((tier) => ({
+ value: tier,
+ label: isBuiltInTier(tier) ? builtInTierLabel(tierLabels, tier) : tier,
+ }));
diff --git a/ui/litellm-dashboard/src/components/add_model/tier_rows.test.ts b/ui/litellm-dashboard/src/components/add_model/tier_rows.test.ts
index 54d9e4f3f0a..df50f116f60 100644
--- a/ui/litellm-dashboard/src/components/add_model/tier_rows.test.ts
+++ b/ui/litellm-dashboard/src/components/add_model/tier_rows.test.ts
@@ -1,12 +1,18 @@
import { describe, expect, it } from "vitest";
+import type { ActiveTierRow, CustomTierSet, TierRow } from "./tier_rows";
import {
+ CUSTOM_TIER_OMITTED_KEYS,
+ CUSTOM_TIER_RESTRICTIONS,
+ MAX_TIER_COUNT,
activeTierName,
activeTierRows,
isBuiltInTierName,
resolveComplexityDefaultModel,
sameTierIdentity,
tierRowById,
+ getCustomTierRowsError,
+ tierParamsByRowId,
tierRowByName,
} from "./tier_rows";
@@ -15,19 +21,17 @@ const tiers = { SIMPLE: ["a"], MEDIUM: ["b"], COMPLEX: ["c"], REASONING: ["d"] }
describe("activeTierRows", () => {
it("reads the tier set as rows whose id is the canonical tier key, in severity order", () => {
expect(activeTierRows({ tiers })).toEqual([
- { id: "SIMPLE", name: "SIMPLE", models: ["a"] },
- { id: "MEDIUM", name: "MEDIUM", models: ["b"] },
- { id: "COMPLEX", name: "COMPLEX", models: ["c"] },
- { id: "REASONING", name: "REASONING", models: ["d"] },
+ { id: "SIMPLE", name: "SIMPLE", definition: "", models: ["a"], params: {} },
+ { id: "MEDIUM", name: "MEDIUM", definition: "", models: ["b"], params: {} },
+ { id: "COMPLEX", name: "COMPLEX", definition: "", models: ["c"], params: {} },
+ { id: "REASONING", name: "REASONING", definition: "", models: ["d"], params: {} },
]);
});
it("gives a tier with no models an empty pool rather than dropping the row", () => {
- expect(activeTierRows({ tiers: { ...tiers, COMPLEX: [] } })[2]).toEqual({
- id: "COMPLEX",
- name: "COMPLEX",
- models: [],
- });
+ const withEmptyComplex = { tiers: { ...tiers, COMPLEX: [] } };
+ const emptyComplexRow: ActiveTierRow = { id: "COMPLEX", name: "COMPLEX", definition: "", models: [], params: {} };
+ expect(activeTierRows(withEmptyComplex)[2]).toEqual(emptyComplexRow);
});
it("finds a row by id and by name", () => {
@@ -53,7 +57,8 @@ describe("sameTierIdentity", () => {
});
it("trims a row name, since the backend matches fallback_tier and keyword rules exactly", () => {
- expect(activeTierName({ id: "1", name: " AUDIT ", models: [] })).toBe("AUDIT");
+ const padded: TierRow = { id: "1", name: " AUDIT ", definition: "", models: [] };
+ expect(activeTierName(padded)).toBe("AUDIT");
});
});
@@ -68,3 +73,98 @@ describe("resolveComplexityDefaultModel", () => {
expect(resolveComplexityDefaultModel({ tiers: { ...tiers, SIMPLE: [], MEDIUM: [] } })).toBeUndefined();
});
});
+
+const definedRow = (name: string, models: string[] = ["m"], definition = "what belongs here"): TierRow => ({
+ id: name.toLowerCase(),
+ name,
+ definition,
+ models,
+});
+
+const set = (rows: TierRow[], fallback?: string): CustomTierSet => ({
+ tiers: rows,
+ fallback_tier_id: fallback ?? rows[0]?.id ?? "",
+});
+
+describe("activeTierRows with an edited set", () => {
+ it("reads the edited rows instead of the built-in record once a set is present", () => {
+ const custom = set([definedRow("CASUAL"), definedRow("AUDIT")]);
+ expect(activeTierRows({ tiers, custom_tier_set: custom }).map((r) => r.name)).toEqual(["CASUAL", "AUDIT"]);
+ });
+
+ it("prefers the fallback tier's pool for the default model, mirroring init_complexity_router_deployment", () => {
+ const custom = set([definedRow("CASUAL", ["casual-model"]), definedRow("AUDIT", ["audit-model"])], "audit");
+ expect(resolveComplexityDefaultModel({ tiers, custom_tier_set: custom })).toBe("audit-model");
+ });
+});
+
+describe("CUSTOM_TIER_RESTRICTIONS", () => {
+ it("gives every restriction a reason, since each one replaces or explains a control", () => {
+ const reasons = Object.values(CUSTOM_TIER_RESTRICTIONS).map((restriction) => restriction.reason);
+ expect(reasons.every((reason) => reason.length > 0)).toBe(true);
+ expect(new Set(reasons).size).toBe(reasons.length);
+ });
+
+ it("collects every omitted key exactly once, so no key is dropped by two owners", () => {
+ expect(new Set(CUSTOM_TIER_OMITTED_KEYS).size).toBe(CUSTOM_TIER_OMITTED_KEYS.length);
+ });
+
+ it("omits the keys the backend rejects beside tier_definitions", () => {
+ expect(CUSTOM_TIER_OMITTED_KEYS).toEqual(
+ expect.arrayContaining(["tier_labels", "escalation_keywords", "adaptive", "classifier_fallback"]),
+ );
+ });
+});
+
+describe("getCustomTierRowsError", () => {
+ it("accepts a complete set", () => {
+ expect(getCustomTierRowsError(set([definedRow("CASUAL"), definedRow("AUDIT")]))).toBeNull();
+ });
+
+ it.each([
+ [set([definedRow("CASUAL")]), "A tier set needs 2 to 8 tiers"],
+ [
+ set(Array.from({ length: MAX_TIER_COUNT + 1 }, (_, index) => definedRow(`T${index}`))),
+ "A tier set needs 2 to 8 tiers",
+ ],
+ [set([definedRow(""), definedRow("AUDIT")], "audit"), "Name every tier"],
+ [set([definedRow("AUDIT"), { ...definedRow("audit"), id: "second" }]), "Tier names must be unique, ignoring case"],
+ [
+ set([definedRow("CASUAL"), { ...definedRow("AUDIT"), definition: " " }]),
+ "Every custom tier needs a definition: it is the rubric the classifier routes on",
+ ],
+ [set([definedRow("CASUAL"), definedRow("AUDIT")], "gone"), "Pick a Fallback Tier for classifier failures"],
+ ])("reports the row problem the backend would reject", (customTierSet, expected) => {
+ expect(getCustomTierRowsError(customTierSet)).toBe(expected);
+ });
+
+ it("lets a built-in name inherit its definition, which is the one blank the backend allows", () => {
+ expect(getCustomTierRowsError(set([{ ...definedRow("SIMPLE"), definition: "" }, definedRow("AUDIT")]))).toBeNull();
+ });
+});
+
+describe("tierParamsByRowId", () => {
+ const rows = [
+ { id: "SIMPLE", name: "SIMPLE", definition: "", models: ["a"] },
+ { id: "stored-1", name: "SECURITY_REVIEW", definition: "audits", models: ["b"] },
+ ];
+
+ it("re-keys a stored tier name onto the ephemeral row id the editor reads", () => {
+ const stored = { SECURITY_REVIEW: { b: { reasoning_effort: "high" } } };
+ expect(tierParamsByRowId(stored, rows)).toEqual({ "stored-1": { b: { reasoning_effort: "high" } } });
+ });
+
+ it("leaves a built-in tier untouched, because its row id is already the tier name", () => {
+ const stored = { SIMPLE: { a: { reasoning_effort: "low" } } };
+ expect(tierParamsByRowId(stored, rows)).toEqual(stored);
+ });
+
+ it("passes a tier this editor does not render straight through instead of dropping its params", () => {
+ const stored = { DEEP_RESEARCH: { c: { reasoning_effort: "high" } } };
+ expect(tierParamsByRowId(stored, rows)).toEqual(stored);
+ });
+
+ it("returns nothing when there are no stored params, keeping the key out of the payload", () => {
+ expect(tierParamsByRowId(undefined, rows)).toBeUndefined();
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/add_model/tier_rows.ts b/ui/litellm-dashboard/src/components/add_model/tier_rows.ts
index c320980916a..df3a26b7a53 100644
--- a/ui/litellm-dashboard/src/components/add_model/tier_rows.ts
+++ b/ui/litellm-dashboard/src/components/add_model/tier_rows.ts
@@ -1,40 +1,170 @@
import type { ComplexityTiers } from "./ComplexityRouterConfig";
import type { ComplexityTier } from "./KeywordTierRules";
+import type { TierModelParams, TierModelParamsByTier } from "./complexity_router_tiers";
export const TIER_ORDER: ComplexityTier[] = ["SIMPLE", "MEDIUM", "COMPLEX", "REASONING"];
export interface TierRow {
id: string;
name: string;
+ definition: string;
models: string[];
}
+/** A row plus the per-model params it owns, so the two can never be keyed differently. */
+export type ActiveTierRow = TierRow & { params: Record<string, TierModelParams> };
+
+export interface CustomTierSet {
+ tiers: TierRow[];
+ fallback_tier_id: string;
+}
+
+// Mirrors TierDefinition in litellm/router_strategy/complexity_router/config.py
+export const MIN_TIER_COUNT = 2;
+export const MAX_TIER_COUNT = 8;
+export const MAX_TIER_NAME_CHARS = 64;
+export const MAX_TIER_DEFINITION_CHARS = 500;
+
export interface ActiveTierSet {
tiers: ComplexityTiers;
+ custom_tier_set?: CustomTierSet;
+ tier_model_params?: TierModelParamsByTier;
}
export const activeTierName = (row: TierRow): string => row.name.trim();
+// Casefold, matching the backend's name-uniqueness rule. NOT the comparison the keyword-rule gate
+// uses: _validate_keyword_rule_tiers is exact membership, so folding there clears a save the
+// backend then rejects.
export const sameTierIdentity = (left: string, right: string): boolean =>
left.trim().toLowerCase() === right.trim().toLowerCase();
export const isBuiltInTierName = (name: string): boolean => TIER_ORDER.some((tier) => sameTierIdentity(tier, name));
-// The only reader of the tier set. A row's id is the canonical tier key, so anything pointing into
-// the set (the plan-mode floor, per-model params) points at a row rather than at a position.
-export const activeTierRows = (value: ActiveTierSet): TierRow[] =>
- TIER_ORDER.map((tier) => ({ id: tier, name: tier, models: value.tiers[tier] ?? [] }));
+const builtInRow = (tier: keyof ComplexityTiers, tiers: ComplexityTiers): TierRow => ({
+ id: tier,
+ name: tier,
+ definition: "",
+ models: tiers[tier] ?? [],
+});
-export const tierRowById = (rows: readonly TierRow[], id: string | undefined): TierRow | undefined =>
+// The only reader of the tier set. Built-in rows carry the canonical tier key as their id, so every
+// pointer into the set is a row id in both modes and nothing downstream branches on the mode.
+export const activeTierRows = (value: ActiveTierSet): ActiveTierRow[] => {
+ const rows = value.custom_tier_set?.tiers ?? TIER_ORDER.map((tier) => builtInRow(tier, value.tiers));
+ return rows.map((row) => ({ ...row, params: value.tier_model_params?.[row.id] ?? {} }));
+};
+
+// The wire shape of an edited tier set, shared by the payload builder and the prompt preview so the
+// preview cannot ask the proxy to render definitions the save would not send.
+export const tierDefinitionsFromRows = (rows: readonly TierRow[]): { name: string; description?: string }[] =>
+ rows.map((row) => ({
+ name: activeTierName(row),
+ ...(row.definition.trim() && { description: row.definition.trim() }),
+ }));
+
+export const tierRowById = <T extends TierRow>(rows: readonly T[], id: string | undefined): T | undefined =>
id === undefined ? undefined : rows.find((row) => row.id === id);
-export const tierRowByName = (rows: readonly TierRow[], name: string): TierRow | undefined =>
+export const tierRowByName = <T extends TierRow>(rows: readonly T[], name: string): T | undefined =>
rows.find((row) => sameTierIdentity(row.name, name));
-// Mirrors init_complexity_router_deployment (litellm/router.py): a pin wins, then MEDIUM or SIMPLE
-// looked up by exact name.
+// Mirrors init_complexity_router_deployment (litellm/router.py): a pin wins, then the fallback
+// tier's pool, then MEDIUM or SIMPLE looked up by exact name, so a row named `medium` is no match.
export const resolveComplexityDefaultModel = (value: ActiveTierSet, pinned?: string): string | undefined => {
const rows = activeTierRows(value);
const named = (name: string) => rows.find((row) => activeTierName(row) === name)?.models[0];
- return pinned?.trim() || named("MEDIUM") || named("SIMPLE");
+ const fallbackPoolModel = tierRowById(rows, value.custom_tier_set?.fallback_tier_id)?.models[0];
+ const builtInDefault = named("MEDIUM") || named("SIMPLE");
+ return pinned?.trim() || fallbackPoolModel || builtInDefault;
+};
+
+// Stored params arrive keyed by the wire tier name while the editor keys them by row id, which is
+// ephemeral for a custom row. A key matching no row passes through, so a tier this editor does not
+// render keeps its params.
+export const tierParamsByRowId = (
+ params: TierModelParamsByTier | undefined,
+ rows: readonly TierRow[],
+): TierModelParamsByTier | undefined =>
+ params &&
+ Object.fromEntries(Object.entries(params).map(([tier, byModel]) => [tierRowByName(rows, tier)?.id ?? tier, byModel]));
+
+// Params keyed by the rows that own them, dropping the rows with none so an untouched router keeps
+// the key out of its payload.
+export const rowParamsByTier = (rows: readonly ActiveTierRow[]): TierModelParamsByTier | undefined => {
+ const owned = rows.filter((row) => Object.keys(row.params).length > 0);
+ return owned.length > 0 ? Object.fromEntries(owned.map((row) => [row.id, row.params])) : undefined;
+};
+
+export interface TierRestriction {
+ omit: readonly string[];
+ reason: string;
+}
+
+// One source for both the disabled control and the wire, so a control cannot grey out while its
+// value still ships. All but heuristicScoring are rejected outright by _validate_tier_definitions;
+// heuristicScoring the backend accepts, and it is dropped because that scorer never runs here.
+export const CUSTOM_TIER_RESTRICTIONS = {
+ displayNames: {
+ omit: ["tier_labels"],
+ reason: "Display names rename the built-in tiers, which your tier set replaces. Name each tier directly",
+ },
+ escalation: {
+ omit: ["escalation_keywords"],
+ reason: "Escalation bumps a request along the built-in tier ladder, which your tier set replaces",
+ },
+ adaptive: {
+ omit: ["adaptive", "adaptive_weights", "tier_distance_penalty", "adaptive_eligible"],
+ reason: "Adaptive routing scores models along the built-in tier ladder, which your tier set replaces",
+ },
+ sessionAffinity: {
+ omit: [],
+ reason: "Session pinning escalates along the built-in tier ladder, which your tier set replaces",
+ },
+ heuristicClassifier: {
+ omit: ["heuristic_first_max_tier"],
+ reason:
+ "The heuristic scorer only produces the built-in tiers, so an edited set needs the LLM classifier. " +
+ "Heuristic first is out for the same reason: its local scorer decides the cheap traffic",
+ },
+ heuristicScoring: {
+ omit: [
+ "tier_boundaries",
+ "token_thresholds",
+ "dimension_weights",
+ "reasoning_override_min_score",
+ "custom_technical_keywords",
+ ],
+ reason: "The heuristic scorer never runs under an edited tier set, so its inputs have no effect",
+ },
+ classifierPrompt: {
+ omit: [],
+ reason: "A replacement prompt drops the tier bullets and the injection guard. Your definitions are the rubric",
+ },
+ classificationRubric: {
+ omit: [],
+ reason: "The preset calibration examples are written against the built-in tiers, which your tier set replaces",
+ },
+ classifierFallback: {
+ omit: ["classifier_fallback"],
+ reason: "Fallback Tier is where an edited tier set routes when the classifier fails",
+ },
+} as const satisfies Record<string, TierRestriction>;
+
+export const CUSTOM_TIER_OMITTED_KEYS: readonly string[] = Object.values(CUSTOM_TIER_RESTRICTIONS).flatMap(
+ (restriction) => restriction.omit,
+);
+
+// Row-shape errors the backend cannot phrase per row. Payload validity is the dry-run's job.
+export const getCustomTierRowsError = (customTierSet: CustomTierSet): string | null => {
+ const rows = customTierSet.tiers;
+ if (rows.length < MIN_TIER_COUNT || rows.length > MAX_TIER_COUNT)
+ return `A tier set needs ${MIN_TIER_COUNT} to ${MAX_TIER_COUNT} tiers`;
+ if (rows.some((row) => !activeTierName(row))) return "Name every tier";
+ const folded = rows.map((row) => row.name.trim().toLowerCase());
+ if (new Set(folded).size !== folded.length) return "Tier names must be unique, ignoring case";
+ if (rows.some((row) => !row.definition.trim() && !isBuiltInTierName(row.name)))
+ return "Every custom tier needs a definition: it is the rubric the classifier routes on";
+ if (!tierRowById(rows, customTierSet.fallback_tier_id)) return "Pick a Fallback Tier for classifier failures";
+ return null;
};
diff --git a/ui/litellm-dashboard/src/components/add_model/tier_set_actions.test.ts b/ui/litellm-dashboard/src/components/add_model/tier_set_actions.test.ts
new file mode 100644
index 00000000000..f939eb95bca
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/tier_set_actions.test.ts
@@ -0,0 +1,171 @@
+import { describe, expect, it } from "vitest";
+import type { ComplexityRouterConfigValue } from "./ComplexityRouterConfig";
+import { applyTierSetAction, setFallbackTier } from "./tier_set_actions";
+
+const tiers = {
+ SIMPLE: ["gpt-3.5-turbo"],
+ MEDIUM: ["gpt-3.5-turbo"],
+ COMPLEX: ["gpt-4"],
+ REASONING: ["claude-3-opus"],
+};
+const builtIn: ComplexityRouterConfigValue = { tiers, classifier_type: "llm" };
+const custom: ComplexityRouterConfigValue = {
+ ...builtIn,
+ custom_tier_set: {
+ tiers: [
+ { id: "CASUAL", name: "CASUAL", definition: "small talk", models: ["gpt-3.5-turbo"] },
+ { id: "sec", name: "SECURITY_REVIEW", definition: "audits", models: ["gpt-4"] },
+ ],
+ fallback_tier_id: "CASUAL",
+ },
+};
+const apply = (value: ComplexityRouterConfigValue, action: Parameters<typeof applyTierSetAction>[2], rules = []) =>
+ applyTierSetAction(value, rules, action);
+
+describe("applyTierSetAction", () => {
+ it("adds a row and moves the form into an edited set, which the built-in record never leaves", () => {
+ const { value } = apply(builtIn, { kind: "add" });
+ expect(value.custom_tier_set?.tiers).toHaveLength(5);
+ expect(value.tiers).toEqual(tiers);
+ });
+
+ it("renames a built-in tier, which is what makes the set custom", () => {
+ const { value } = apply(builtIn, { kind: "patch", id: "COMPLEX", patch: { name: "SECURITY_REVIEW" } });
+ expect(value.custom_tier_set?.tiers.map((row) => row.name)).toEqual([
+ "SIMPLE",
+ "MEDIUM",
+ "SECURITY_REVIEW",
+ "REASONING",
+ ]);
+ expect(value.tiers).toEqual(tiers);
+ });
+
+ it("carries a renamed tier's keyword rules across, so a rule cannot be orphaned by a rename", () => {
+ const rules = [{ id: "r1", keywords: ["audit"], tier: "COMPLEX" }];
+ const next = applyTierSetAction(builtIn, rules, { kind: "patch", id: "COMPLEX", patch: { name: "AUDIT" } });
+ expect(next.keywordTierRules).toEqual([{ id: "r1", keywords: ["audit"], tier: "AUDIT" }]);
+ });
+
+ it("leaves the rules alone when another row still answers to the old name", () => {
+ const shared: ComplexityRouterConfigValue = {
+ ...builtIn,
+ custom_tier_set: {
+ tiers: [
+ { id: "a", name: "AUDIT", definition: "d", models: ["gpt-4"] },
+ { id: "b", name: "audit", definition: "d", models: ["gpt-4"] },
+ ],
+ fallback_tier_id: "a",
+ },
+ };
+ const rules = [{ id: "r1", keywords: ["x"], tier: "AUDIT" }];
+ const next = applyTierSetAction(shared, rules, { kind: "patch", id: "a", patch: { name: "RENAMED" } });
+ expect(next.keywordTierRules).toBe(rules);
+ });
+
+ it("prunes the per-model params of a model dropped from a row", () => {
+ const withParams: ComplexityRouterConfigValue = {
+ ...custom,
+ tier_model_params: { sec: { "gpt-4": { reasoning_effort: "high" } } },
+ };
+ const { value } = apply(withParams, { kind: "models", id: "sec", models: [] });
+ expect(value.tier_model_params?.sec ?? {}).toEqual({});
+ });
+
+ it("snapshots a removed built-in row's models back into the record it came from", () => {
+ const { value } = apply(builtIn, { kind: "remove", id: "COMPLEX" });
+ expect(value.custom_tier_set?.tiers.map((row) => row.id)).toEqual(["SIMPLE", "MEDIUM", "REASONING"]);
+ expect(value.tiers.COMPLEX).toEqual(["gpt-4"]);
+ });
+
+ it("re-points a fallback whose row was removed rather than leaving it dangling", () => {
+ const { value } = apply(custom, { kind: "remove", id: "CASUAL" });
+ expect(value.custom_tier_set?.fallback_tier_id).toBe("sec");
+ });
+
+ it("turns the plan-mode floor off when its row is gone, in the same write", () => {
+ const withFloor: ComplexityRouterConfigValue = { ...custom, plan_mode_min_tier: "sec" };
+ const { value } = apply(withFloor, { kind: "remove", id: "sec" });
+ expect(value.plan_mode_min_tier).toBeUndefined();
+ });
+
+ it("leaves no custom row's effort settings behind when restoring the built-in tiers", () => {
+ const withEfforts: ComplexityRouterConfigValue = {
+ ...custom,
+ tier_model_params: { sec: { "gpt-4": { reasoning_effort: "high" } }, SIMPLE: { "gpt-3.5-turbo": {} } },
+ };
+ const { value } = apply(withEfforts, { kind: "restore" });
+ expect(value.custom_tier_set).toBeUndefined();
+ expect(Object.keys(value.tier_model_params ?? {})).toEqual(["SIMPLE"]);
+ });
+
+ it("keeps a renamed built-in row's effort settings across a restore", () => {
+ const renamed: ComplexityRouterConfigValue = {
+ ...custom,
+ tier_model_params: { COMPLEX: { "gpt-4": { reasoning_effort: "high" } } },
+ custom_tier_set: {
+ tiers: [
+ { id: "SIMPLE", name: "SIMPLE", definition: "", models: ["gpt-3.5-turbo"] },
+ { id: "COMPLEX", name: "DEEP_WORK", definition: "renamed built-in", models: ["gpt-4"] },
+ ],
+ fallback_tier_id: "SIMPLE",
+ },
+ };
+ const { value } = apply(renamed, { kind: "restore" });
+ expect(value.tiers.COMPLEX).toEqual(["gpt-4"]);
+ expect(value.tier_model_params).toEqual({ COMPLEX: { "gpt-4": { reasoning_effort: "high" } } });
+ });
+
+ it("re-points a rule that followed a renamed built-in back to its tier on restore", () => {
+ const renamed: ComplexityRouterConfigValue = {
+ ...builtIn,
+ custom_tier_set: {
+ tiers: [
+ { id: "SIMPLE", name: "SIMPLE", definition: "", models: ["gpt-3.5-turbo"] },
+ { id: "COMPLEX", name: "DEEP_WORK", definition: "", models: ["gpt-4"] },
+ ],
+ fallback_tier_id: "SIMPLE",
+ },
+ };
+ const rules = [{ id: "r1", keywords: ["proof"], tier: "DEEP_WORK" }];
+ const next = applyTierSetAction(renamed, rules, { kind: "restore" });
+ expect(next.keywordTierRules).toEqual([{ id: "r1", keywords: ["proof"], tier: "COMPLEX" }]);
+ });
+
+ it("leaves a rule on a tier restore removes, so the save gate flags it rather than dropping it", () => {
+ const rules = [{ id: "r1", keywords: ["smalltalk"], tier: "CASUAL" }];
+ const next = applyTierSetAction(custom, rules, { kind: "restore" });
+ expect(next.keywordTierRules).toBe(rules);
+ });
+
+ it("keeps a removed row's rule in the same write, for the save gate to name", () => {
+ const rules = [{ id: "r1", keywords: ["audit"], tier: "SECURITY_REVIEW" }];
+ const next = applyTierSetAction(custom, rules, { kind: "remove", id: "sec" });
+ expect(next.keywordTierRules).toBe(rules);
+ });
+
+ it("resets a full set to the four built-ins rather than stacking them on top", () => {
+ const six: ComplexityRouterConfigValue = {
+ ...custom,
+ custom_tier_set: {
+ tiers: Array.from({ length: 6 }, (_, i) => ({
+ id: `row-${i}`,
+ name: `TIER_${i}`,
+ definition: "d",
+ models: ["gpt-4"],
+ })),
+ fallback_tier_id: "row-0",
+ },
+ };
+ const { value } = apply(six, { kind: "restore" });
+ expect(value.custom_tier_set).toBeUndefined();
+ expect(Object.keys(value.tiers)).toEqual(["SIMPLE", "MEDIUM", "COMPLEX", "REASONING"]);
+ });
+});
+
+describe("setFallbackTier", () => {
+ it("re-points the fallback without disturbing the rows", () => {
+ const next = setFallbackTier(custom, "sec");
+ expect(next.custom_tier_set?.fallback_tier_id).toBe("sec");
+ expect(next.custom_tier_set?.tiers).toHaveLength(2);
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/add_model/tier_set_actions.ts b/ui/litellm-dashboard/src/components/add_model/tier_set_actions.ts
new file mode 100644
index 00000000000..c8254b6bff9
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/tier_set_actions.ts
@@ -0,0 +1,150 @@
+import type { KeywordTierRule } from "./KeywordTierRules";
+import type { ComplexityRouterConfigValue } from "./ComplexityRouterConfig";
+import { pruneTierModelParams } from "./complexity_router_tiers";
+import {
+ type ActiveTierRow,
+ type TierRow,
+ TIER_ORDER,
+ activeTierName,
+ activeTierRows,
+ rowParamsByTier,
+ sameTierIdentity,
+ tierRowById,
+ tierRowByName,
+} from "./tier_rows";
+
+export type TierSetAction =
+ | { kind: "models"; id: string; models: string[] }
+ | { kind: "patch"; id: string; patch: Partial<Omit<TierRow, "id">> }
+ | { kind: "add" }
+ | { kind: "remove"; id: string }
+ | { kind: "restore" };
+
+/** What an action produces: the next config, and the keyword rules that followed their rows. */
+export interface TierSetResult {
+ value: ComplexityRouterConfigValue;
+ keywordTierRules: readonly KeywordTierRule[];
+}
+
+// The sole tier-set writer: it owns where rows live and reconciles both row-id pointers, so a
+// fallback re-points and a floor whose row is gone turns off in the same write.
+const commitTierRows = (
+ rows: TierRow[],
+ fallbackTierId: string,
+ base: ComplexityRouterConfigValue,
+): ComplexityRouterConfigValue => {
+ const floorGone = base.plan_mode_min_tier !== undefined && !rows.some((row) => row.id === base.plan_mode_min_tier);
+ const next = floorGone ? { ...base, plan_mode_min_tier: undefined } : base;
+ if (!next.custom_tier_set) {
+ return { ...next, tiers: { ...next.tiers, ...Object.fromEntries(rows.map((row) => [row.id, row.models])) } };
+ }
+ const fallback_tier_id = rows.some((row) => row.id === fallbackTierId)
+ ? fallbackTierId
+ : (tierRowByName(rows, "MEDIUM") ?? rows[0])?.id ?? "";
+ return { ...next, custom_tier_set: { tiers: rows, fallback_tier_id } };
+};
+
+const asCustomBase = (base: ComplexityRouterConfigValue): ComplexityRouterConfigValue =>
+ base.custom_tier_set
+ ? base
+ : { ...base, custom_tier_set: { tiers: activeTierRows(base), fallback_tier_id: "MEDIUM" } };
+
+// A rule follows the row holding its name through any action, so neither a rename nor a restore can
+// orphan it. A rule whose name is ambiguous across rows, or whose row the action deleted, stays put
+// for the save gate to name loudly rather than being dropped or rewritten by guess.
+const followedRuleTier = (before: readonly TierRow[], after: readonly TierRow[], tier: string): string | undefined => {
+ const holders = before.filter((row) => sameTierIdentity(row.name, tier));
+ if (holders.length !== 1 || activeTierName(holders[0]) !== tier) return undefined;
+ const target = tierRowById(after, holders[0].id);
+ return target === undefined ? undefined : activeTierName(target);
+};
+
+const rulesFollowingRows = (
+ before: readonly TierRow[],
+ after: readonly TierRow[],
+ rules: readonly KeywordTierRule[],
+): readonly KeywordTierRule[] => {
+ const followed = rules.map((rule) => {
+ const tier = followedRuleTier(before, after, rule.tier);
+ return tier === undefined || tier === rule.tier ? rule : { ...rule, tier };
+ });
+ return followed.every((rule, index) => rule === rules[index]) ? rules : followed;
+};
+
+// Models and params both come from these rows, so the two cannot be keyed differently.
+const exitToBuiltInTiers = (value: ComplexityRouterConfigValue, rows: readonly ActiveTierRow[]) => {
+ const { custom_tier_set: _dropped, ...rest } = value;
+ const builtInRows: ActiveTierRow[] = TIER_ORDER.map(
+ (tier) =>
+ tierRowById(rows, tier) ?? {
+ id: tier,
+ name: tier,
+ definition: "",
+ models: value.tiers[tier],
+ params: value.tier_model_params?.[tier] ?? {},
+ },
+ );
+ const restored: ComplexityRouterConfigValue = {
+ ...rest,
+ tier_model_params: rowParamsByTier(builtInRows),
+ tiers: { ...value.tiers, ...Object.fromEntries(builtInRows.map((row) => [row.id, row.models])) },
+ };
+ return commitTierRows(activeTierRows(restored), "", restored);
+};
+
+const nextTierSetValue = (
+ value: ComplexityRouterConfigValue,
+ rows: ActiveTierRow[],
+ action: TierSetAction,
+): ComplexityRouterConfigValue => {
+ const fallbackId = value.custom_tier_set?.fallback_tier_id ?? "MEDIUM";
+
+ switch (action.kind) {
+ case "models":
+ return commitTierRows(
+ rows.map((row) => (row.id === action.id ? { ...row, models: action.models } : row)),
+ fallbackId,
+ { ...value, tier_model_params: pruneTierModelParams(value.tier_model_params, action.id, action.models) },
+ );
+ case "patch":
+ return commitTierRows(
+ rows.map((row) => (row.id === action.id ? { ...row, ...action.patch } : row)),
+ fallbackId,
+ asCustomBase(value),
+ );
+ case "add":
+ return commitTierRows(
+ [...rows, { id: crypto.randomUUID(), name: "", definition: "", models: [] }],
+ fallbackId,
+ asCustomBase(value),
+ );
+ case "remove": {
+ const removed = tierRowById(rows, action.id);
+ const snapshot =
+ removed && (TIER_ORDER as string[]).includes(action.id)
+ ? { ...value, tiers: { ...value.tiers, [action.id]: removed.models } }
+ : value;
+ return commitTierRows(
+ rows.filter((row) => row.id !== action.id),
+ fallbackId,
+ asCustomBase(snapshot),
+ );
+ }
+ case "restore":
+ return exitToBuiltInTiers(value, rows);
+ }
+};
+
+export const applyTierSetAction = (
+ value: ComplexityRouterConfigValue,
+ keywordTierRules: readonly KeywordTierRule[],
+ action: TierSetAction,
+): TierSetResult => {
+ const rows = activeTierRows(value);
+ const next = nextTierSetValue(value, rows, action);
+ return { value: next, keywordTierRules: rulesFollowingRows(rows, activeTierRows(next), keywordTierRules) };
+};
+
+/** The fallback-tier select is the only writer that re-points rather than reconciling. */
+export const setFallbackTier = (value: ComplexityRouterConfigValue, id: string): ComplexityRouterConfigValue =>
+ commitTierRows(activeTierRows(value), id, value);