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): configure the auto router's heuristic scorer from the Admin UI (#37216)

tin-berri1648273469cb
diff --git a/litellm/proxy/public_endpoints/public_endpoints.py b/litellm/proxy/public_endpoints/public_endpoints.py
index 47e30555a4f..4d58a974bb8 100644
--- a/litellm/proxy/public_endpoints/public_endpoints.py
+++ b/litellm/proxy/public_endpoints/public_endpoints.py
@@ -28,6 +28,7 @@ from litellm.types.proxy.management_endpoints.model_management_endpoints import
)
from litellm.types.proxy.public_endpoints.public_endpoints import (
AgentCreateInfo,
+ ComplexityScorerDefaults,
ProviderCreateInfo,
PublicModelHubInfo,
SupportedEndpointsResponse,
@@ -398,6 +399,28 @@ async def get_provider_fields() -> list[ProviderCreateInfo]:
return provider_create_fields
+ "/public/complexity_router/scorer_defaults",
+ tags=["public", "auto router"],
+ response_model=ComplexityScorerDefaults,
+)
+async def get_complexity_scorer_defaults() -> ComplexityScorerDefaults:
+ """
+ Return the complexity router's shipped heuristic scorer defaults, for the dashboard to prefill with.
+ """
+ from litellm.router_strategy.complexity_router.config import (
+ DEFAULT_DIMENSION_WEIGHTS,
+ DEFAULT_TIER_BOUNDARIES,
+ DEFAULT_TOKEN_THRESHOLDS,
+ )
+
+ return ComplexityScorerDefaults(
+ tier_boundaries=DEFAULT_TIER_BOUNDARIES,
+ token_thresholds=DEFAULT_TOKEN_THRESHOLDS,
+ dimension_weights=DEFAULT_DIMENSION_WEIGHTS,
+ )
+
+
@router.get(
"/public/litellm_model_cost_map",
tags=["public", "model management"],
diff --git a/litellm/types/proxy/public_endpoints/public_endpoints.py b/litellm/types/proxy/public_endpoints/public_endpoints.py
index dbe34926f4b..f6ee054ceaa 100644
--- a/litellm/types/proxy/public_endpoints/public_endpoints.py
+++ b/litellm/types/proxy/public_endpoints/public_endpoints.py
@@ -1,3 +1,4 @@
+from collections.abc import Mapping
from typing import Any, Literal
from pydantic import BaseModel
@@ -68,3 +69,15 @@ class SupportedEndpoint(BaseModel):
class SupportedEndpointsResponse(BaseModel):
endpoints: list[SupportedEndpoint]
+
+
+class ComplexityScorerDefaults(BaseModel):
+ """The complexity router's shipped heuristic scorer defaults.
+
+ The dashboard prefills its Advanced scoring controls from these rather than keeping its own copy, so
+ a recalibration of the defaults cannot leave the form reporting numbers the router no longer uses.
+ """
+
+ tier_boundaries: Mapping[str, float]
+ token_thresholds: Mapping[str, int]
+ dimension_weights: Mapping[str, float]
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults.ts b/ui/litellm-dashboard/src/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults.ts
new file mode 100644
index 00000000000..9502eb33b35
--- /dev/null
+++ b/ui/litellm-dashboard/src/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults.ts
@@ -0,0 +1,16 @@
+import { ComplexityScorerDefaults, getComplexityScorerDefaults } from "@/components/networking";
+import { useQuery } from "@tanstack/react-query";
+import { createQueryKeys } from "../common/queryKeysFactory";
+
+const scorerDefaultsKeys = createQueryKeys("complexityScorerDefaults");
+
+export const useComplexityScorerDefaults = () => {
+ // 24 hours: the shipped defaults only change on a release.
+ const options = {
+ queryKey: scorerDefaultsKeys.list({}),
+ queryFn: async () => await getComplexityScorerDefaults(),
+ staleTime: 24 * 60 * 60 * 1000,
+ gcTime: 24 * 60 * 60 * 1000,
+ };
+ return useQuery<ComplexityScorerDefaults>(options);
+};
diff --git a/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.test.tsx b/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.test.tsx
index 200ca51527c..442d4121603 100644
--- a/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.test.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/AutoRouterRoutingTest.test.tsx
@@ -4,6 +4,10 @@ import { vi } from "vitest";
import AutoRouterRoutingTest from "./AutoRouterRoutingTest";
import { testAutoRouterRouting } from "../networking";
import { ComplexityRouterConfigPayload } from "./build_complexity_router_config";
+vi.mock(
+ "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults",
+ async () => await import("../../../tests/mocks/complexityScorerDefaults"),
+);
vi.mock("../networking", () => ({
testAutoRouterRouting: vi.fn(),
diff --git a/ui/litellm-dashboard/src/components/add_model/ClassificationMethodConfig.tsx b/ui/litellm-dashboard/src/components/add_model/ClassificationMethodConfig.tsx
index b1488e105be..03d8fbc2394 100644
--- a/ui/litellm-dashboard/src/components/add_model/ClassificationMethodConfig.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ClassificationMethodConfig.tsx
@@ -2,6 +2,8 @@ import { InfoCircleOutlined } from "@ant-design/icons";
import { Select as AntdSelect, Card, InputNumber, Radio, Space, Switch, Tooltip, Typography } from "antd";
import React from "react";
import ClassifierPromptEditor from "./ClassifierPromptEditor";
+import HeuristicScoringConfig from "./HeuristicScoringConfig";
+import { useComplexityScorerDefaults } from "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults";
import {
ClassifierFallback,
ClassifierType,
@@ -47,6 +49,62 @@ const scoringExplanation = (value: ComplexityRouterConfigValue): string => {
: CUSTOM_PROMPT_WITH_HEURISTIC_FALLBACK;
};
+/**
+ * The three boundaries this card states, as displayed strings, or null until the proxy's shipped defaults
+ * have arrived. Kept out of the component so the card cannot state a range the router stopped using, and
+ * so the derivation does not add branches to an already dense render.
+ */
+const boundaryRanges = (
+ shipped: Record<string, number> | undefined,
+ overrides: Record<string, number> | undefined,
+): { simpleMedium: string; mediumComplex: string; complexReasoning: string } | null => {
+ const effective: Record<string, number> = { ...shipped, ...overrides };
+ const [low, mid, high] = [effective.simple_medium, effective.medium_complex, effective.complex_reasoning];
+ if (low === undefined || mid === undefined || high === undefined) return null;
+ return { simpleMedium: low.toFixed(2), mediumComplex: mid.toFixed(2), complexReasoning: high.toFixed(2) };
+};
+
+const HowClassificationWorks: React.FC<{ value: ComplexityRouterConfigValue }> = ({ value }) => {
+ // The shipped boundaries come from the proxy, so this card cannot state ranges the router stopped using.
+ const { data: scorerDefaults, isError } = useComplexityScorerDefaults();
+ const ranges = boundaryRanges(scorerDefaults?.tier_boundaries, value.tier_boundaries);
+
+ return (
+ <Card className="bg-gray-50 mt-4">
+ <Text strong style={{ display: "block", marginBottom: 8 }}>
+ How Classification Works
+ </Text>
+ <Text type="secondary" style={{ fontSize: 13 }}>
+ {scoringExplanation(value)}
+ </Text>
+ {ranges && (
+ <ul style={{ marginTop: 8, marginBottom: 0, paddingLeft: 20, fontSize: 13, color: "rgba(0, 0, 0, 0.45)" }}>
+ <li>
+ <strong>{effectiveTierLabel("SIMPLE", value.tier_labels)}</strong>: Score &lt; {ranges.simpleMedium}
+ </li>
+ <li>
+ <strong>{effectiveTierLabel("MEDIUM", value.tier_labels)}</strong>: Score {ranges.simpleMedium} -{" "}
+ {ranges.mediumComplex}
+ </li>
+ <li>
+ <strong>{effectiveTierLabel("COMPLEX", value.tier_labels)}</strong>: Score {ranges.mediumComplex} -{" "}
+ {ranges.complexReasoning}
+ </li>
+ <li>
+ <strong>{effectiveTierLabel("REASONING", value.tier_labels)}</strong>: Score &gt; {ranges.complexReasoning}{" "}
+ (or 2+ reasoning markers)
+ </li>
+ </ul>
+ )}
+ {!ranges && isError && (
+ <Text type="secondary" style={{ fontSize: 13, display: "block", marginTop: 8 }}>
+ The tier score ranges could not be loaded from the proxy.
+ </Text>
+ )}
+ </Card>
+ );
+};
+
interface ClassificationMethodConfigProps {
value: ComplexityRouterConfigValue;
onChange: (value: ComplexityRouterConfigValue) => void;
@@ -375,29 +433,9 @@ const ClassificationMethodConfig: React.FC<ClassificationMethodConfigProps> = ({
</div>
)}
- <Card className="bg-gray-50 mt-4">
- <Text strong style={{ display: "block", marginBottom: 8 }}>
- How Classification Works
- </Text>
- <Text type="secondary" style={{ fontSize: 13 }}>
- {scoringExplanation(value)}
- </Text>
- <ul style={{ marginTop: 8, marginBottom: 0, paddingLeft: 20, fontSize: 13, color: "rgba(0, 0, 0, 0.45)" }}>
- <li>
- <strong>{effectiveTierLabel("SIMPLE", value.tier_labels)}</strong>: Score &lt; 0.15
- </li>
- <li>
- <strong>{effectiveTierLabel("MEDIUM", value.tier_labels)}</strong>: Score 0.15 - 0.35
- </li>
- <li>
- <strong>{effectiveTierLabel("COMPLEX", value.tier_labels)}</strong>: Score 0.35 - 0.60
- </li>
- <li>
- <strong>{effectiveTierLabel("REASONING", value.tier_labels)}</strong>: Score &gt; 0.60 (or 2+ reasoning
- markers)
- </li>
- </ul>
- </Card>
+ <HeuristicScoringConfig value={value} onChange={onChange} />
+
+ <HowClassificationWorks value={value} />
</>
);
};
diff --git a/ui/litellm-dashboard/src/components/add_model/ClassifierPromptEditor.integration.test.tsx b/ui/litellm-dashboard/src/components/add_model/ClassifierPromptEditor.integration.test.tsx
index c35457630a5..42b7fd72e9f 100644
--- a/ui/litellm-dashboard/src/components/add_model/ClassifierPromptEditor.integration.test.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ClassifierPromptEditor.integration.test.tsx
@@ -3,6 +3,10 @@ import userEvent from "@testing-library/user-event";
import { vi } from "vitest";
import ClassifierPromptEditor from "./ClassifierPromptEditor";
import { ClassificationRubric } from "./ComplexityRouterConfig";
+vi.mock(
+ "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults",
+ async () => await import("../../../tests/mocks/complexityScorerDefaults"),
+);
vi.mock("@/app/(dashboard)/hooks/useAuthorized", () => ({
default: () => ({ accessToken: "sk-test" }),
diff --git a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx
index 73364306a4f..199acfe8769 100644
--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.test.tsx
@@ -2,6 +2,10 @@ import { fireEvent, renderWithProviders, screen, within } from "../../../tests/t
import userEvent from "@testing-library/user-event";
import { vi } from "vitest";
import ComplexityRouterConfig, { ComplexityRouterConfigValue } from "./ComplexityRouterConfig";
+vi.mock(
+ "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults",
+ async () => await import("../../../tests/mocks/complexityScorerDefaults"),
+);
const mockModelInfo = [
{ model_group: "gpt-4", mode: "chat" },
diff --git a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
index cc9f3146a3a..84d07facbf0 100644
--- a/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/ComplexityRouterConfig.tsx
@@ -8,6 +8,9 @@ import { resolveComplexityDefaultModel } from "./complexity_router_tiers";
import EscalationKeywords from "./EscalationKeywords";
import KeywordTierRules, { KeywordTierRule } from "./KeywordTierRules";
import SemanticKeywordMatching from "./SemanticKeywordMatching";
+import { type DimensionWeights, type TierBoundaries, type TokenThresholds } from "./heuristic_scoring_knobs";
+
+export type { DimensionWeights, TierBoundaries, TokenThresholds };
const { Text } = Typography;
@@ -83,6 +86,24 @@ export interface AdaptiveRouterWeights {
export const DEFAULT_ADAPTIVE_WEIGHTS: AdaptiveRouterWeights = { quality: 0.3, cost: 0.7 };
+export type HeuristicScoringRole = "decides" | "fallback_only" | "never";
+
+/**
+ * Whether the heuristic scorer runs on this router at all, which is what gates its knobs. An LLM
+ * classifier still falls back to the scorer unless the fallback is the default model, so the gate cannot be
+ * a plain classifier_type check.
+ */
+export const heuristicScoringRoleFor = (
+ classifierType: ClassifierType,
+ classifierFallback: ClassifierFallback | undefined,
+): HeuristicScoringRole => {
+ if (classifierType === "heuristic") return "decides";
+ return (classifierFallback ?? DEFAULT_CLASSIFIER_FALLBACK) === "heuristic" ? "fallback_only" : "never";
+};
+
+export const heuristicScoringRole = (value: ComplexityRouterConfigValue): HeuristicScoringRole =>
+ heuristicScoringRoleFor(value.classifier_type, value.classifier_fallback);
+
export type AdaptiveEligible = "all" | "classified_tier";
export type ComplexityTierLabels = Partial<Record<keyof ComplexityTiers, string>>;
@@ -105,6 +126,13 @@ export interface ComplexityRouterConfigValue {
tier_distance_penalty?: number;
adaptive_eligible?: AdaptiveEligible;
return_raw_model_name?: boolean;
+ /**
+ * Heuristic scorer knobs. Undefined means the operator never touched them, which keeps the key out of the
+ * payload so the router tracks the backend defaults rather than freezing today's numbers.
+ */
+ tier_boundaries?: TierBoundaries;
+ token_thresholds?: TokenThresholds;
+ dimension_weights?: DimensionWeights;
}
interface ComplexityRouterConfigProps {
diff --git a/ui/litellm-dashboard/src/components/add_model/HeuristicScoringConfig.test.tsx b/ui/litellm-dashboard/src/components/add_model/HeuristicScoringConfig.test.tsx
new file mode 100644
index 00000000000..f1a79ab7c33
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/HeuristicScoringConfig.test.tsx
@@ -0,0 +1,201 @@
+import { fireEvent, renderWithProviders, screen } from "../../../tests/test-utils";
+import userEvent from "@testing-library/user-event";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { useComplexityScorerDefaults } from "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults";
+import ClassificationMethodConfig from "./ClassificationMethodConfig";
+import HeuristicScoringConfig from "./HeuristicScoringConfig";
+import { ClassifierFallback, ClassifierType, ComplexityRouterConfigValue } from "./ComplexityRouterConfig";
+import { DIMENSION_LABELS } from "./heuristic_scoring_knobs";
+import { LOADED_SCORER_DEFAULTS_QUERY, SHIPPED_SCORER_DEFAULTS } from "../../../tests/mocks/complexityScorerDefaults";
+
+vi.mock(
+ "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults",
+ async () => await import("../../../tests/mocks/complexityScorerDefaults"),
+);
+
+const BASE: ComplexityRouterConfigValue = {
+ tiers: { SIMPLE: ["gpt-4o-mini"], MEDIUM: ["gpt-4o"], COMPLEX: ["o3"], REASONING: ["o3"] },
+ classifier_type: "heuristic",
+};
+
+const render = async (value: ComplexityRouterConfigValue, onChange = vi.fn()) => {
+ renderWithProviders(<HeuristicScoringConfig value={value} onChange={onChange} />);
+ await userEvent.click(screen.getByText("Advanced scoring"));
+ return onChange;
+};
+
+const commit = async (label: string, raw: string) => {
+ const onChange = await render(BASE);
+ fireEvent.change(screen.getByLabelText(label), { target: { value: raw } });
+ return onChange.mock.calls.at(-1)?.[0] as ComplexityRouterConfigValue | undefined;
+};
+
+describe("HeuristicScoringConfig", () => {
+ it("counts overridden groups on the collapsed header", () => {
+ const tuned = { ...BASE, token_thresholds: { simple: 25, complex: 900 } };
+ renderWithProviders(<HeuristicScoringConfig value={tuned} onChange={vi.fn()} />);
+
+ expect(screen.getByTestId("advanced-scoring-override-count")).toHaveTextContent("1 override");
+ });
+
+ it("prefills the shipped defaults", async () => {
+ await render(BASE);
+
+ expect(screen.getByLabelText("Simple to Medium")).toHaveValue("0.15");
+ expect(screen.getByLabelText("Long above")).toHaveValue("400");
+ expect(screen.getByTestId("dimension-weight-total")).toHaveTextContent("total 1.00");
+ });
+
+ it("writes a whole dict, and keeps the decimal point typeable", async () => {
+ // A plain controlled number input renders Number("0.") as "0", so "0.22" would be untypeable.
+ const onChange = await render(BASE);
+ const field = screen.getByLabelText("Simple to Medium");
+
+ fireEvent.change(field, { target: { value: "0." } });
+ expect(field).toHaveValue("0.");
+ fireEvent.change(field, { target: { value: "0.22" } });
+
+ expect((onChange.mock.calls.at(-1)?.[0] as ComplexityRouterConfigValue).tier_boundaries).toEqual({
+ simple_medium: 0.22,
+ medium_complex: 0.35,
+ complex_reasoning: 0.6,
+ });
+ });
+
+ it("commits nothing for an emptied field, rather than NaN", async () => {
+ const onChange = await render(BASE);
+ fireEvent.change(screen.getByLabelText("Short below"), { target: { value: "" } });
+
+ expect(onChange).not.toHaveBeenCalled();
+ });
+
+ // min and max are inert attributes on a text input, so without the explicit clamp these would persist
+ // a weight of 999, or an infinite boundary, into the router config.
+ it.each([
+ ["Code presence", "999", 1],
+ ["Code presence", "-2", 0],
+ ["Long above", "100000", 100000],
+ ])("clamps %s = %s to %s", async (label, raw, expected) => {
+ const next = await commit(label, raw);
+ expect(
+ { ...next?.dimension_weights, ...next?.token_thresholds }[label === "Long above" ? "complex" : "codePresence"],
+ ).toBe(expected);
+ });
+
+ it.each(["Infinity", "1e999"])("refuses to commit %s", async (raw) => {
+ expect((await commit("Simple to Medium", raw))?.tier_boundaries).toBeUndefined();
+ });
+
+ it("resets a group back to undefined so it tracks the backend defaults again", async () => {
+ const tuned = { ...BASE, token_thresholds: { simple: 25, complex: 900 } };
+ const onChange = await render(tuned);
+
+ await userEvent.click(screen.getByRole("button", { name: "Reset to defaults" }));
+
+ expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ token_thresholds: undefined }));
+ });
+
+ it("flags decreasing boundaries as an error without blocking the save", async () => {
+ const bad = { ...BASE, tier_boundaries: { simple_medium: 0.5, medium_complex: 0.2, complex_reasoning: 0.6 } };
+ await render(bad);
+
+ expect(screen.getByRole("alert")).toHaveTextContent(/unreachable/);
+ });
+});
+
+describe("ClassificationMethodConfig scorer gating", () => {
+ const props = { onChange: vi.fn(), modelOptions: [{ value: "gpt-4o-mini", label: "gpt-4o-mini" }] };
+ const withClassifier = (type: ClassifierType, fallback?: ClassifierFallback): ComplexityRouterConfigValue => ({
+ ...BASE,
+ classifier_type: type,
+ classifier_llm_config: { model: "gpt-4o-mini", timeout_ms: 3000 },
+ classifier_fallback: fallback,
+ });
+
+ it.each([
+ ["heuristic decides the tier", "heuristic" as ClassifierType, undefined, true],
+ ["an LLM classifier falls back to the heuristic", "llm" as ClassifierType, "heuristic" as ClassifierFallback, true],
+ [
+ "an LLM classifier falls back to the default model",
+ "llm" as ClassifierType,
+ "default_model" as ClassifierFallback,
+ false,
+ ],
+ ])("offers the knobs when %s: %s", async (_case, type, fallback, expected) => {
+ renderWithProviders(<ClassificationMethodConfig {...props} value={withClassifier(type, fallback)} />);
+
+ expect(screen.queryByText("Advanced scoring") !== null).toBe(expected);
+ });
+
+ it("describes the tier ranges from the configured boundaries, not the shipped numbers", () => {
+ const tuned = { ...BASE, tier_boundaries: { simple_medium: 0.22, medium_complex: 0.44, complex_reasoning: 0.66 } };
+ renderWithProviders(<ClassificationMethodConfig {...props} value={tuned} />);
+
+ expect(screen.getByText(/Score < 0.22/)).toBeInTheDocument();
+ expect(screen.getByText(/Score 0.44 - 0.66/)).toBeInTheDocument();
+ expect(screen.queryByText(/0.15/)).not.toBeInTheDocument();
+ });
+
+ it("renders a row for every scored dimension", async () => {
+ await render(BASE);
+
+ for (const key of Object.keys(SHIPPED_SCORER_DEFAULTS.dimension_weights)) {
+ expect(screen.getByLabelText(DIMENSION_LABELS[key])).toBeInTheDocument();
+ }
+ });
+});
+
+describe("HeuristicScoringConfig when the defaults request fails", () => {
+ const failing = { data: undefined, isPending: false, isError: true, refetch: vi.fn() };
+ const pending = { data: undefined, isPending: true, isError: false, refetch: vi.fn() };
+
+ const renderWithQuery = async (query: unknown, value: ComplexityRouterConfigValue) => {
+ vi.mocked(useComplexityScorerDefaults).mockReturnValue(query as never);
+ renderWithProviders(<HeuristicScoringConfig value={value} onChange={vi.fn()} />);
+ await userEvent.click(screen.getByText("Advanced scoring"));
+ };
+
+ afterEach(() => vi.mocked(useComplexityScorerDefaults).mockReturnValue(LOADED_SCORER_DEFAULTS_QUERY));
+
+ it("says so instead of claiming to still be loading", async () => {
+ await renderWithQuery(failing, BASE);
+
+ expect(screen.queryByText(/Loading the shipped defaults/)).not.toBeInTheDocument();
+ expect(screen.getByRole("alert")).toHaveTextContent(/Could not load the shipped defaults/);
+ expect(screen.getByRole("button", { name: "Retry" })).toBeInTheDocument();
+ });
+
+ it("still shows and edits the values this router already overrides", async () => {
+ await renderWithQuery(failing, { ...BASE, token_thresholds: { simple: 25, complex: 900 } });
+
+ expect(screen.getByLabelText("Short below")).toHaveValue("25");
+ expect(screen.getByLabelText("Long above")).toHaveValue("900");
+ });
+
+ it("keeps saying loading while the request is genuinely in flight", async () => {
+ await renderWithQuery(pending, BASE);
+
+ expect(screen.getByText(/Loading the shipped defaults/)).toBeInTheDocument();
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ });
+});
+
+describe("HeuristicScoringConfig degraded states", () => {
+ afterEach(() => vi.mocked(useComplexityScorerDefaults).mockReturnValue(LOADED_SCORER_DEFAULTS_QUERY));
+
+ it("states no weight total when the dimension set is unknown, rather than one built from overrides alone", async () => {
+ vi.mocked(useComplexityScorerDefaults).mockReturnValue({
+ data: undefined,
+ isPending: false,
+ isError: true,
+ refetch: vi.fn(),
+ } as never);
+ renderWithProviders(
+ <HeuristicScoringConfig value={{ ...BASE, dimension_weights: { codePresence: 0.5 } }} onChange={vi.fn()} />,
+ );
+ await userEvent.click(screen.getByText("Advanced scoring"));
+
+ expect(screen.getByLabelText("Code presence")).toHaveValue("0.5");
+ expect(screen.queryByTestId("dimension-weight-total")).not.toBeInTheDocument();
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/add_model/HeuristicScoringConfig.tsx b/ui/litellm-dashboard/src/components/add_model/HeuristicScoringConfig.tsx
new file mode 100644
index 00000000000..1b0a781a33a
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/HeuristicScoringConfig.tsx
@@ -0,0 +1,226 @@
+import { ChevronDown } from "lucide-react";
+import React, { useState } from "react";
+import { useComplexityScorerDefaults } from "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import { Slider } from "@/components/ui/slider";
+import { type ComplexityRouterConfigValue, heuristicScoringRole } from "./ComplexityRouterConfig";
+import { dimensionLabel, weightTotal } from "./heuristic_scoring_knobs";
+
+export type KnobGroup = "tier_boundaries" | "token_thresholds" | "dimension_weights";
+
+interface GroupSpec {
+ group: KnobGroup;
+ title: string;
+ blurb: string;
+ min: number;
+ max?: number;
+ step: number;
+ withSlider: boolean;
+ labels: Record<string, string>;
+}
+
+const GROUPS: GroupSpec[] = [
+ {
+ group: "tier_boundaries",
+ title: "Tier boundaries",
+ blurb:
+ "The weighted score each tier starts at. Scores run from -1 to 1, and short or conversational prompts score below 0, so a negative boundary is a valid way to lift trivial traffic into a higher tier.",
+ min: -1,
+ max: 1,
+ step: 0.01,
+ withSlider: false,
+ labels: {
+ simple_medium: "Simple to Medium",
+ medium_complex: "Medium to Complex",
+ complex_reasoning: "Complex to Reasoning",
+ },
+ },
+ {
+ group: "token_thresholds",
+ title: "Token thresholds",
+ blurb:
+ "Estimated prompt length, in tokens, that pushes the token count dimension to its floor or ceiling. Lengths between the two score neutral.",
+ min: 0,
+ step: 1,
+ withSlider: false,
+ labels: { simple: "Short below", complex: "Long above" },
+ },
+ {
+ group: "dimension_weights",
+ title: "Dimension weights",
+ blurb: "How much each signal contributes to the score. Absolute multipliers, so the total need not be 1.00.",
+ min: 0,
+ max: 1,
+ step: 0.01,
+ withSlider: true,
+ labels: {},
+ },
+];
+
+/** Why a group is currently misconfigured, or null. Never blocks the save: a router written this way in
+ * config.yaml would otherwise be uneditable here for every unrelated change. */
+const warn = (group: KnobGroup, values: Record<string, number>): string | null => {
+ if (
+ group === "tier_boundaries" &&
+ (values.simple_medium > values.medium_complex || values.medium_complex > values.complex_reasoning)
+ )
+ return "These boundaries decrease, so every tier between them is unreachable and its traffic routes elsewhere.";
+ if (group === "token_thresholds" && values.simple >= values.complex)
+ return "The short threshold is not below the long one, so no prompt length scores neutral on length.";
+ return null;
+};
+
+interface HeuristicScoringConfigProps {
+ value: ComplexityRouterConfigValue;
+ onChange: (value: ComplexityRouterConfigValue) => void;
+}
+
+const HeuristicScoringConfig: React.FC<HeuristicScoringConfigProps> = ({ value, onChange }) => {
+ const [isOpen, setIsOpen] = useState(false);
+ const [draft, setDraft] = useState<{ id: string; raw: string } | null>(null);
+ const { data: defaults, isPending, isError, refetch } = useComplexityScorerDefaults();
+
+ // The panel owns its own visibility: the scorer does not run at all when an LLM classifier
+ // falls back to the default model, so there is nothing here to configure.
+ const scorerRuns = heuristicScoringRole(value) !== "never";
+
+ const overrides = GROUPS.filter((spec) => value[spec.group] !== undefined).length;
+
+ // min/max are inert on a text input, and a plain number input renders Number("0.") as "0" so a decimal
+ // cannot be typed. Hence the local draft plus an explicit clamp here.
+ const commit = (spec: GroupSpec, effective: Record<string, number>, key: string, raw: string) => {
+ const parsed = Number(raw);
+ if (raw.trim() === "" || !Number.isFinite(parsed)) return;
+ const clamped = Math.min(spec.max ?? Infinity, Math.max(spec.min, parsed));
+ onChange({
+ ...value,
+ [spec.group]: { ...effective, [key]: spec.step === 1 ? Math.round(clamped) : clamped },
+ });
+ };
+
+ if (!scorerRuns) return null;
+
+ return (
+ <Collapsible open={isOpen} onOpenChange={setIsOpen} className="mt-4">
+ <CollapsibleTrigger render={<button type="button" className="flex w-full items-center gap-2 text-left" />}>
+ <ChevronDown
+ className={`size-4 shrink-0 text-muted-foreground transition-transform ${isOpen ? "rotate-180" : ""}`}
+ />
+ <span className="text-sm font-medium">Advanced scoring</span>
+ {overrides > 0 && (
+ <Badge variant="secondary" data-testid="advanced-scoring-override-count">
+ {overrides} {overrides === 1 ? "override" : "overrides"}
+ </Badge>
+ )}
+ </CollapsibleTrigger>
+
+ <CollapsibleContent>
+ <div className="mt-3 space-y-6 pl-6">
+ <p className="text-xs text-muted-foreground">
+ Every knob below is optional. Left untouched, the router follows the shipped defaults, so it picks up any
+ recalibration of them rather than staying pinned to the numbers shown here.
+ </p>
+
+ {isPending ? (
+ <p className="text-xs text-muted-foreground">Loading the shipped defaults...</p>
+ ) : (
+ <>
+ {isError && (
+ <div className="flex items-start gap-2" role="alert">
+ <p className="text-xs font-medium text-destructive">
+ Could not load the shipped defaults, so only values this router already overrides are shown. Saving
+ still works, and an untouched knob keeps following the defaults.
+ </p>
+ <Button type="button" variant="link" size="xs" onClick={() => void refetch()}>
+ Retry
+ </Button>
+ </div>
+ )}
+ {GROUPS.map((spec) => {
+ const shipped = defaults?.[spec.group] ?? {};
+ const effective: Record<string, number> = { ...shipped, ...value[spec.group] };
+ const problem = warn(spec.group, effective);
+ return (
+ <section key={spec.group} className="space-y-2">
+ <div className="flex items-center justify-between">
+ <div className="flex items-center gap-2">
+ <span className="text-sm font-medium">{spec.title}</span>
+ {/* Only a known dimension set has a meaningful total; summing the overrides
+ alone would state a total that is not the router's. */}
+ {spec.withSlider && defaults !== undefined && (
+ <span className="text-xs text-muted-foreground" data-testid="dimension-weight-total">
+ total {weightTotal(effective).toFixed(2)}
+ </span>
+ )}
+ </div>
+ {value[spec.group] !== undefined && (
+ <Button
+ type="button"
+ variant="link"
+ size="xs"
+ onClick={() => onChange({ ...value, [spec.group]: undefined })}
+ >
+ Reset to defaults
+ </Button>
+ )}
+ </div>
+ <p className="text-xs text-muted-foreground">{spec.blurb}</p>
+
+ {Object.keys(effective).map((key) => {
+ const id = `${spec.group}-${key}`;
+ const label = spec.labels[key] ?? dimensionLabel(key);
+ return (
+ <div key={key} className="flex items-center gap-3">
+ <Label htmlFor={id} className="w-44 text-xs font-normal">
+ {label}
+ </Label>
+ {spec.withSlider && (
+ <Slider
+ min={spec.min}
+ max={spec.max}
+ step={spec.step}
+ value={[effective[key]]}
+ onValueChange={(next) =>
+ commit(spec, effective, key, String(Array.isArray(next) ? next[0] : next))
+ }
+ className="flex-1"
+ aria-label={`${label} weight`}
+ />
+ )}
+ <Input
+ id={id}
+ type="text"
+ inputMode="decimal"
+ className={spec.withSlider ? "w-24" : "w-28"}
+ value={draft?.id === id ? draft.raw : String(effective[key])}
+ onChange={(event) => {
+ setDraft({ id, raw: event.target.value });
+ commit(spec, effective, key, event.target.value);
+ }}
+ onBlur={() => setDraft(null)}
+ />
+ </div>
+ );
+ })}
+
+ {problem && (
+ <p className="text-xs font-medium text-destructive" role="alert">
+ {problem}
+ </p>
+ )}
+ </section>
+ );
+ })}
+ </>
+ )}
+ </div>
+ </CollapsibleContent>
+ </Collapsible>
+ );
+};
+
+export default HeuristicScoringConfig;
diff --git a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx
index 27ede9159a8..c2a7db1356e 100644
--- a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.test.tsx
@@ -8,6 +8,10 @@ import { getMissingTiersError } from "./build_complexity_router_config";
import { testAutoRouterRouting } from "../networking";
import { ModelGroup } from "@/components/llm_calls/fetch_models";
import { getAllPresets, getPresetByKey, getRequiredModelsInPreset } from "@/lib/autorouter_presets";
+vi.mock(
+ "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults",
+ async () => await import("../../../tests/mocks/complexityScorerDefaults"),
+);
const ANTHROPIC_PRESET = getPresetByKey("anthropic_family")!;
const ANTHROPIC_TIERS = ANTHROPIC_PRESET.complexity_router_config.tiers;
diff --git a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.tsx b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.tsx
index e4c8b9ac1f4..2abd4097bdf 100644
--- a/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.tsx
+++ b/ui/litellm-dashboard/src/components/add_model/add_auto_router_tab.tsx
@@ -303,6 +303,9 @@ const AddAutoRouterTab: React.FC<AddAutoRouterTabProps> = ({
tierDistancePenalty: complexityRouterConfig.tier_distance_penalty ?? DEFAULT_TIER_DISTANCE_PENALTY,
adaptiveEligible: complexityRouterConfig.adaptive_eligible ?? "all",
returnRawModelName: complexityRouterConfig.return_raw_model_name ?? false,
+ tierBoundaries: complexityRouterConfig.tier_boundaries,
+ tokenThresholds: complexityRouterConfig.token_thresholds,
+ dimensionWeights: complexityRouterConfig.dimension_weights,
};
const submitRecommendedRouter = (name: string) => {
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 440542345d1..703231ba5ee 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
@@ -575,3 +575,29 @@ describe("hydrateTierLabels", () => {
expect(hydrateTierLabels(["Cheap"])).toBeUndefined();
});
});
+
+describe("buildComplexityRouterConfig scorer knobs", () => {
+ const BOUNDARIES = { simple_medium: 0.22, medium_complex: 0.44, complex_reasoning: 0.66 };
+ const tuned: BuildComplexityRouterConfigParams = { ...baseParams, tierBoundaries: BOUNDARIES };
+ const llmWithDefaultFallback: BuildComplexityRouterConfigParams = {
+ ...tuned,
+ classifierType: "llm",
+ classifierLlmConfig: { model: "gpt-4o-mini", timeout_ms: 3000 },
+ classifierFallback: "default_model",
+ };
+
+ it("omits untouched knobs so the router tracks the backend defaults", () => {
+ const config = buildComplexityRouterConfig(baseParams);
+
+ expect(config).not.toHaveProperty("tier_boundaries");
+ expect(config).not.toHaveProperty("dimension_weights");
+ });
+
+ it("emits what was set", () => {
+ expect(buildComplexityRouterConfig(tuned).tier_boundaries).toEqual(BOUNDARIES);
+ });
+
+ it("drops them when the classifier falls back to the default model and nothing is scored", () => {
+ expect(buildComplexityRouterConfig(llmWithDefaultFallback)).not.toHaveProperty("tier_boundaries");
+ });
+});
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 a6dcb9a61cf..3ee3b6f0180 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
@@ -8,8 +8,12 @@ import {
ClassifierType,
ComplexityTierLabels,
ComplexityTiers,
+ DimensionWeights,
TIER_DESCRIPTIONS,
+ TierBoundaries,
+ TokenThresholds,
effectiveTierLabel,
+ heuristicScoringRoleFor,
} from "./ComplexityRouterConfig";
/**
@@ -36,6 +40,34 @@ export const normalizeClassifierLlmConfig = ({
? { model, timeout_ms, system_prompt }
: { model, timeout_ms, ...(classification_rubric && { classification_rubric }) };
+interface ScorerKnobInputs {
+ classifierType: ClassifierType;
+ classifierFallback: ClassifierFallback | undefined;
+ tierBoundaries: TierBoundaries | undefined;
+ tokenThresholds: TokenThresholds | undefined;
+ dimensionWeights: DimensionWeights | undefined;
+}
+
+/**
+ * The scorer knobs to persist, which is none of them on a router that never scores: an LLM classifier
+ * falling back to the default model would otherwise carry settings that can only mislead the next reader.
+ * Each is omitted while untouched, so the router keeps tracking the backend defaults.
+ */
+const scorerKnobPayload = ({
+ classifierType,
+ classifierFallback,
+ tierBoundaries,
+ tokenThresholds,
+ dimensionWeights,
+}: ScorerKnobInputs) =>
+ heuristicScoringRoleFor(classifierType, classifierFallback) === "never"
+ ? {}
+ : {
+ ...(tierBoundaries && { tier_boundaries: tierBoundaries }),
+ ...(tokenThresholds && { token_thresholds: tokenThresholds }),
+ ...(dimensionWeights && { dimension_weights: dimensionWeights }),
+ };
+
export interface BuildComplexityRouterConfigParams {
tiers: ComplexityTiers;
defaultModel: string | undefined;
@@ -59,6 +91,9 @@ export interface BuildComplexityRouterConfigParams {
tierDistancePenalty: number;
adaptiveEligible: AdaptiveEligible;
returnRawModelName: boolean;
+ tierBoundaries?: TierBoundaries;
+ tokenThresholds?: TokenThresholds;
+ dimensionWeights?: DimensionWeights;
}
export interface ComplexityRouterConfigPayload {
@@ -84,6 +119,9 @@ export interface ComplexityRouterConfigPayload {
tier_distance_penalty?: number;
adaptive_eligible?: AdaptiveEligible;
return_raw_model_name?: boolean;
+ tier_boundaries?: TierBoundaries;
+ token_thresholds?: TokenThresholds;
+ dimension_weights?: DimensionWeights;
}
const TIER_KEYS: Array<keyof ComplexityTiers> = ["SIMPLE", "MEDIUM", "COMPLEX", "REASONING"];
@@ -176,10 +214,15 @@ export const buildComplexityRouterConfig = ({
tierDistancePenalty,
adaptiveEligible,
returnRawModelName,
+ tierBoundaries,
+ tokenThresholds,
+ dimensionWeights,
}: BuildComplexityRouterConfigParams): ComplexityRouterConfigPayload => {
const cleanedEscalationKeywords = escalationKeywords.map((keyword) => keyword.trim()).filter(Boolean);
const cleanedKeywordTierRules = serializeKeywordTierRules(keywordTierRules);
const cleanedTierLabels = serializeTierLabels(tierLabels);
+ const scorerInputs = { classifierType, classifierFallback, tierBoundaries, tokenThresholds, dimensionWeights };
+ const scorerKnobs = scorerKnobPayload(scorerInputs);
return {
tiers,
@@ -218,5 +261,6 @@ export const buildComplexityRouterConfig = ({
adaptive_eligible: adaptiveEligible,
}),
...(returnRawModelName && { return_raw_model_name: true }),
+ ...scorerKnobs,
};
};
diff --git a/ui/litellm-dashboard/src/components/add_model/heuristic_scoring_knobs.test.ts b/ui/litellm-dashboard/src/components/add_model/heuristic_scoring_knobs.test.ts
new file mode 100644
index 00000000000..4f6c92e5a35
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/heuristic_scoring_knobs.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+
+import { heuristicScoringRoleFor } from "./ComplexityRouterConfig";
+import {
+ dimensionLabel,
+ hydrateDimensionWeights,
+ hydrateTierBoundaries,
+ hydrateTokenThresholds,
+ weightTotal,
+} from "./heuristic_scoring_knobs";
+
+describe("hydrating the scorer knobs", () => {
+ // The tri-state rests on this: hydrating an absent knob to the shipped defaults would make an untouched
+ // save write them out and pin the router to whatever they were when the modal was opened.
+ it.each([[undefined], [null], ["0.15"], [[0.15]]])("hydrates %s to undefined, not to the defaults", (raw) => {
+ expect(hydrateTierBoundaries(raw)).toBeUndefined();
+ expect(hydrateDimensionWeights(raw)).toBeUndefined();
+ });
+
+ it("keeps a stored dict exactly as stored, including negatives and zero", () => {
+ expect(hydrateTierBoundaries({ simple_medium: -1, medium_complex: 0, complex_reasoning: 0.6 })).toEqual({
+ simple_medium: -1,
+ medium_complex: 0,
+ complex_reasoning: 0.6,
+ });
+ });
+
+ it("leaves a partial dict partial, since the backend fills the rest at scoring time", () => {
+ expect(hydrateTokenThresholds({ complex: 900 })).toEqual({ complex: 900 });
+ });
+
+ it("drops non-numeric and non-finite entries", () => {
+ expect(hydrateTokenThresholds({ simple: "25", complex: Number.NaN, other: 900 })).toEqual({ other: 900 });
+ });
+
+ it("preserves a key it does not recognise rather than deleting an operator's config", () => {
+ // The dimension set is the proxy's, not the dashboard's, so an unknown key may be a newer backend
+ // rather than a typo. It is kept, and simply has no control rendered for it.
+ expect(hydrateDimensionWeights({ codePresence: 0.3, somethingNew: 0.4 })).toEqual({
+ codePresence: 0.3,
+ somethingNew: 0.4,
+ });
+ });
+
+ it("totals weights and rounds away float drift", () => {
+ expect(weightTotal({ a: 0.1, b: 0.2 })).toBe(0.3);
+ });
+
+ it("falls back to the raw key when a dimension has no label yet", () => {
+ expect(dimensionLabel("codePresence")).toBe("Code presence");
+ expect(dimensionLabel("somethingNew")).toBe("somethingNew");
+ });
+});
+
+describe("heuristicScoringRoleFor", () => {
+ it.each([
+ ["heuristic", undefined, "decides"],
+ ["heuristic", "default_model", "decides"],
+ ["llm", undefined, "fallback_only"],
+ ["llm", "heuristic", "fallback_only"],
+ ["llm", "default_model", "never"],
+ ] as const)("classifier %s with fallback %s scores as %s", (type, fallback, expected) => {
+ expect(heuristicScoringRoleFor(type, fallback)).toBe(expected);
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/add_model/heuristic_scoring_knobs.ts b/ui/litellm-dashboard/src/components/add_model/heuristic_scoring_knobs.ts
new file mode 100644
index 00000000000..46e145554ac
--- /dev/null
+++ b/ui/litellm-dashboard/src/components/add_model/heuristic_scoring_knobs.ts
@@ -0,0 +1,48 @@
+export type TierBoundaries = Record<string, number>;
+
+export type TokenThresholds = Record<string, number>;
+
+export type DimensionWeights = Record<string, number>;
+
+/**
+ * Display names for the scorer's dimensions. Only the wording lives here; the dimension set and its
+ * shipped weights come from the proxy (GET /public/complexity_router/scorer_defaults), so a dimension
+ * added backend-side still renders, under its raw key until it is given a label here.
+ */
+export const DIMENSION_LABELS: Record<string, string> = {
+ codePresence: "Code presence",
+ reasoningMarkers: "Reasoning markers",
+ technicalTerms: "Technical terms",
+ tokenCount: "Token count",
+ simpleIndicators: "Simple indicators",
+ multiStepPatterns: "Multi-step patterns",
+ questionComplexity: "Question complexity",
+};
+
+export const dimensionLabel = (key: string): string => DIMENSION_LABELS[key] ?? key;
+
+const asRecord = (raw: unknown): Record<string, unknown> | undefined =>
+ typeof raw === "object" && raw !== null && !Array.isArray(raw) ? (raw as Record<string, unknown>) : undefined;
+
+/**
+ * Absent means the router is tracking the shipped defaults, so it must hydrate to undefined rather than to
+ * a copy of them: hydrating defaults would make an untouched save write them out and pin the router to
+ * whatever they were the day the modal was opened. A stored dict is kept exactly as stored, since the
+ * backend fills in any key it omits at scoring time.
+ */
+const hydrateNumericMap = (raw: unknown): Record<string, number> | undefined => {
+ const stored = asRecord(raw);
+ if (stored === undefined) return undefined;
+ return Object.fromEntries(
+ Object.entries(stored).filter(([, value]) => typeof value === "number" && Number.isFinite(value)),
+ ) as Record<string, number>;
+};
+
+export const hydrateTierBoundaries = (raw: unknown): TierBoundaries | undefined => hydrateNumericMap(raw);
+
+export const hydrateTokenThresholds = (raw: unknown): TokenThresholds | undefined => hydrateNumericMap(raw);
+
+export const hydrateDimensionWeights = (raw: unknown): DimensionWeights | undefined => hydrateNumericMap(raw);
+
+export const weightTotal = (weights: DimensionWeights): number =>
+ Math.round(Object.values(weights).reduce((total, weight) => total + weight, 0) * 100) / 100;
diff --git a/ui/litellm-dashboard/src/components/edit_auto_router/build_updated_complexity_router_config.test.ts b/ui/litellm-dashboard/src/components/edit_auto_router/build_updated_complexity_router_config.test.ts
index b56ec734aeb..8acae918c9b 100644
--- a/ui/litellm-dashboard/src/components/edit_auto_router/build_updated_complexity_router_config.test.ts
+++ b/ui/litellm-dashboard/src/components/edit_auto_router/build_updated_complexity_router_config.test.ts
@@ -291,3 +291,26 @@ describe("buildUpdatedComplexityRouterConfig tier labels", () => {
expect(Object.keys(result.tiers as Record<string, unknown>)).toEqual(["SIMPLE", "MEDIUM", "COMPLEX", "REASONING"]);
});
});
+
+describe("buildUpdatedComplexityRouterConfig scorer knobs", () => {
+ const BOUNDARIES = { simple_medium: 0.22, medium_complex: 0.44, complex_reasoning: 0.66 };
+ const STORED_WITH_KNOBS = { ...STORED, tier_boundaries: BOUNDARIES };
+ const HYDRATED = { ...FORM_VALUE, tier_boundaries: BOUNDARIES };
+
+ it("round-trips explicit stored knobs through an untouched edit", () => {
+ // These keys are MANAGED now, so the stored copy is dropped before the rebuild and only a faithful
+ // hydration puts them back. A regression here silently resets a tuned router.
+ expect(buildUpdatedComplexityRouterConfig(STORED_WITH_KNOBS, HYDRATED).tier_boundaries).toEqual(BOUNDARIES);
+ });
+
+ it("drops a stored knob when the operator resets it, instead of preserving the old value", () => {
+ const result = buildUpdatedComplexityRouterConfig(STORED_WITH_KNOBS, FORM_VALUE);
+
+ expect(result).not.toHaveProperty("tier_boundaries");
+ expect(result.some_future_backend_key).toEqual({ nested: true });
+ });
+
+ it("never invents knobs for a router that never had them", () => {
+ expect(buildUpdatedComplexityRouterConfig(STORED, FORM_VALUE)).not.toHaveProperty("tier_boundaries");
+ });
+});
diff --git a/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.test.tsx b/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.test.tsx
index cd37e05c13b..da36063e68a 100644
--- a/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.test.tsx
+++ b/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.test.tsx
@@ -5,6 +5,10 @@ import { fireEvent, renderWithProviders, screen, waitFor, within } from "@/../te
import NotificationsManager from "@/components/molecules/notifications_manager";
import EditAutoRouterModal from "./edit_auto_router_modal";
+vi.mock(
+ "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults",
+ async () => await import("../../../tests/mocks/complexityScorerDefaults"),
+);
const { modelPatchUpdateCall, modelAvailableCall, getAutoRouterClassifierDefaultPromptCall } = vi.hoisted(() => ({
modelPatchUpdateCall: vi.fn().mockResolvedValue({}),
diff --git a/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.tsx b/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.tsx
index ae01584e174..32521a3e043 100644
--- a/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.tsx
+++ b/ui/litellm-dashboard/src/components/edit_auto_router/edit_auto_router_modal.tsx
@@ -17,6 +17,11 @@ import {
import { KeywordTierRule } from "../add_model/KeywordTierRules";
import { DEFAULT_MATCH_THRESHOLD } from "../add_model/SemanticKeywordMatching";
import { hydrateKeywordTierRules, serializeKeywordTierRules } from "../add_model/complexity_router_keywords";
+import {
+ hydrateDimensionWeights,
+ hydrateTierBoundaries,
+ hydrateTokenThresholds,
+} from "../add_model/heuristic_scoring_knobs";
import ComplexityRouterConfig, {
ComplexityRouterConfigValue,
ComplexityTiers,
@@ -24,6 +29,7 @@ import ComplexityRouterConfig, {
DEFAULT_SESSION_AFFINITY,
DEFAULT_DEPLOYMENT_AFFINITY,
DEFAULT_TIER_DISTANCE_PENALTY,
+ heuristicScoringRole,
} from "../add_model/ComplexityRouterConfig";
import NotificationsManager from "../molecules/notifications_manager";
import {
@@ -64,6 +70,9 @@ const MANAGED_COMPLEXITY_ROUTER_KEYS = new Set([
"tier_distance_penalty",
"adaptive_eligible",
"return_raw_model_name",
+ "tier_boundaries",
+ "token_thresholds",
+ "dimension_weights",
]);
// Managed only when the caller passes the corresponding state. A caller that does not render
@@ -125,6 +134,7 @@ export const buildUpdatedComplexityRouterConfig = (
const adaptiveEligible = value.adaptive_eligible ?? "all";
const storedKeywordRules = keywordMatching ? serializeKeywordTierRules(keywordMatching.keywordTierRules) : [];
const serializedTierLabels = serializeTierLabels(value.tier_labels);
+ const scorerRuns = heuristicScoringRole(value) !== "never";
return {
...preservedConfig,
@@ -175,6 +185,9 @@ export const buildUpdatedComplexityRouterConfig = (
match_threshold: keywordMatching.matchThreshold,
}),
}),
+ ...(scorerRuns && value.tier_boundaries !== undefined && { tier_boundaries: value.tier_boundaries }),
+ ...(scorerRuns && value.token_thresholds !== undefined && { token_thresholds: value.token_thresholds }),
+ ...(scorerRuns && value.dimension_weights !== undefined && { dimension_weights: value.dimension_weights }),
};
};
@@ -290,6 +303,9 @@ const EditAutoRouterModal: React.FC<EditAutoRouterModalProps> = ({
parsedConfig.classifier_fallback === "default_model" || parsedConfig.classifier_fallback === "heuristic"
? parsedConfig.classifier_fallback
: undefined,
+ tier_boundaries: hydrateTierBoundaries(parsedConfig.tier_boundaries),
+ token_thresholds: hydrateTokenThresholds(parsedConfig.token_thresholds),
+ dimension_weights: hydrateDimensionWeights(parsedConfig.dimension_weights),
session_affinity:
typeof parsedConfig.session_affinity === "boolean"
? parsedConfig.session_affinity
diff --git a/ui/litellm-dashboard/src/components/model_info_view.test.tsx b/ui/litellm-dashboard/src/components/model_info_view.test.tsx
index 4c8b9153077..74fd398eaab 100644
--- a/ui/litellm-dashboard/src/components/model_info_view.test.tsx
+++ b/ui/litellm-dashboard/src/components/model_info_view.test.tsx
@@ -6,6 +6,10 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import ModelInfoView from "./model_info_view";
import NotificationsManager from "./molecules/notifications_manager";
import * as networking from "./networking";
+vi.mock(
+ "@/app/(dashboard)/hooks/autoRouter/useComplexityScorerDefaults",
+ async () => await import("../../tests/mocks/complexityScorerDefaults"),
+);
vi.mock("../../utils/dataUtils", () => ({
copyToClipboard: vi.fn().mockResolvedValue(true),
diff --git a/ui/litellm-dashboard/src/components/networking.tsx b/ui/litellm-dashboard/src/components/networking.tsx
index 0578a28da79..56293339361 100644
--- a/ui/litellm-dashboard/src/components/networking.tsx
+++ b/ui/litellm-dashboard/src/components/networking.tsx
@@ -372,6 +372,21 @@ export const getProviderCreateMetadata = async (): Promise<ProviderCreateInfo[]>
return jsonData;
};
+export interface ComplexityScorerDefaults {
+ tier_boundaries: Record<string, number>;
+ token_thresholds: Record<string, number>;
+ dimension_weights: Record<string, number>;
+}
+
+export const getComplexityScorerDefaults = async (): Promise<ComplexityScorerDefaults> => {
+ /**
+ * Fetch the complexity router's shipped heuristic scorer defaults from the proxy's public endpoint.
+ * The Advanced scoring controls prefill from these rather than from a copy in the dashboard, so a
+ * recalibration of the defaults cannot leave the form reporting numbers the router no longer uses.
+ */
+ return await apiClient.get(`/public/complexity_router/scorer_defaults`);
+};
+
export const getAgentCreateMetadata = async (): Promise<AgentCreateInfo[]> => {
/**
* Fetch agent type metadata from the proxy's public endpoint.
diff --git a/ui/litellm-dashboard/src/lib/autorouter_presets.test.ts b/ui/litellm-dashboard/src/lib/autorouter_presets.test.ts
index 81f2dc79bda..2ff89fffe30 100644
--- a/ui/litellm-dashboard/src/lib/autorouter_presets.test.ts
+++ b/ui/litellm-dashboard/src/lib/autorouter_presets.test.ts
@@ -42,6 +42,14 @@ describe("autorouter_presets", () => {
}
});
+ it("keeps every preset on the shipped scorer knobs, so a preset cannot pin one to today's numbers", () => {
+ for (const { complexity_router_config: config } of getAllPresets()) {
+ expect(config.tier_boundaries).toBeUndefined();
+ expect(config.token_thresholds).toBeUndefined();
+ expect(config.dimension_weights).toBeUndefined();
+ }
+ });
+
it("keeps the model-family presets on the heuristic classifier", () => {
for (const key of ["anthropic_family", "openai_family"]) {
expect(getPresetByKey(key)!.complexity_router_config.classifier_type).toBe("heuristic");
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index be4f3217dbd..3d5e10c6696 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -11350,6 +11350,26 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/public/complexity_router/scorer_defaults": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ /**
+ * Get Complexity Scorer Defaults
+ * @description Return the complexity router's shipped heuristic scorer defaults, for the dashboard to prefill with.
+ */
+ get: operations["get_complexity_scorer_defaults_public_complexity_router_scorer_defaults_get"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/public/endpoints": {
parameters: {
query?: never;
@@ -23585,6 +23605,27 @@ export interface components {
*/
timezone?: string | null;
};
+ /**
+ * ComplexityScorerDefaults
+ * @description The complexity router's shipped heuristic scorer defaults.
+ *
+ * The dashboard prefills its Advanced scoring controls from these rather than keeping its own copy, so
+ * a recalibration of the defaults cannot leave the form reporting numbers the router no longer uses.
+ */
+ ComplexityScorerDefaults: {
+ /** Dimension Weights */
+ dimension_weights: {
+ [key: string]: number;
+ };
+ /** Tier Boundaries */
+ tier_boundaries: {
+ [key: string]: number;
+ };
+ /** Token Thresholds */
+ token_thresholds: {
+ [key: string]: number;
+ };
+ };
/**
* ComplexityTier
* @description Complexity tiers for routing decisions.
@@ -50592,6 +50633,26 @@ export interface operations {
};
};
};
+ get_complexity_scorer_defaults_public_complexity_router_scorer_defaults_get: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Successful Response */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ComplexityScorerDefaults"];
+ };
+ };
+ };
+ };
get_supported_endpoints_public_endpoints_get: {
parameters: {
query?: never;
diff --git a/ui/litellm-dashboard/tests/mocks/complexityScorerDefaults.ts b/ui/litellm-dashboard/tests/mocks/complexityScorerDefaults.ts
new file mode 100644
index 00000000000..3eb2d781213
--- /dev/null
+++ b/ui/litellm-dashboard/tests/mocks/complexityScorerDefaults.ts
@@ -0,0 +1,33 @@
+import { vi } from "vitest";
+import type { ComplexityScorerDefaults } from "@/components/networking";
+
+/**
+ * Stubs the proxy's shipped scorer defaults for any test that renders the auto-router tree.
+ *
+ * The Advanced scoring panel and the "How Classification Works" card read these over the network, so
+ * without a stub every render of that tree pays for a request jsdom cannot serve, which pushed the slowest
+ * auto-router tests past their timeout on CI. Exported as a vi.fn so a test can override the query state,
+ * which is how the failure path is covered.
+ */
+export const SHIPPED_SCORER_DEFAULTS: ComplexityScorerDefaults = {
+ tier_boundaries: { simple_medium: 0.15, medium_complex: 0.35, complex_reasoning: 0.6 },
+ token_thresholds: { simple: 15, complex: 400 },
+ dimension_weights: {
+ codePresence: 0.3,
+ reasoningMarkers: 0.25,
+ technicalTerms: 0.25,
+ tokenCount: 0.1,
+ simpleIndicators: 0.05,
+ multiStepPatterns: 0.03,
+ questionComplexity: 0.02,
+ },
+};
+
+export const LOADED_SCORER_DEFAULTS_QUERY = {
+ data: SHIPPED_SCORER_DEFAULTS,
+ isPending: false,
+ isError: false,
+ refetch: vi.fn(),
+};
+
+export const useComplexityScorerDefaults = vi.fn(() => LOADED_SCORER_DEFAULTS_QUERY);