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(complexity_router): add declarative custom dimensions to the heuristic scorer (#40156)

tin-berri1761fe236f1d
diff --git a/litellm/router_strategy/complexity_router/README.md b/litellm/router_strategy/complexity_router/README.md
index 93dddfb3d20..88ed374dd3f 100644
--- a/litellm/router_strategy/complexity_router/README.md
+++ b/litellm/router_strategy/complexity_router/README.md
@@ -195,6 +195,30 @@ model_list:
session_affinity_ttl_seconds: 300
```
+## Custom dimensions
+
+Add `custom_dimensions` under `complexity_router_config` to give domain keywords or regex patterns their own weighted signal
+
+```yaml
+custom_dimensions:
+ - name: internalFrameworks
+ weight: 0.9
+ keywords: [orbitmesh, fluxgate]
+ - name: sqlMigration
+ weight: 0.7
+ patterns: ['\b(create|alter|drop)\s{1,4}table\b']
+```
+
+Each dimension contributes its weight once when any matcher hits the current ask. Repeated matches do not increase it. The built-in score and tier boundaries are unchanged, and the total score is not renormalized. Keywords use the existing case-insensitive word-boundary and CJK rules. Regexes search the first 2048 characters case-insensitively and compile during configuration validation and router initialization, never per request
+
+Only `heuristic`, `heuristic_first` and `hybrid` accept custom dimensions. Each name must be a unique ASCII identifier starting with a letter, at most 64 characters, and cannot reuse a built-in dimension name or a key in `dimension_weights`. Set its weight inline, greater than zero and at most one
+
+Patterns are checked at configuration time against a grammar whose worst case stays a few milliseconds on 2048 characters. Every quantifier needs an explicit upper bound of at most 64 and must repeat a single character or character class, so `\s{1,4}` is accepted while `\s+`, `(a|aa){0,12}` and `(?:ab){0,64}` are refused. Backreferences, lookarounds, atomic groups and possessive quantifiers are refused as well. Each pattern is then costed: alternation branches and repeat lengths multiply the ways the engine can retry, and every later piece of the pattern is charged once per path that can reach it, so `a?a?a?a?a?a?a?a?` followed by a long fixed tail is refused even though each quantifier is small. The budget is 2048 work units per pattern and 8192 across the router. An invalid or over-budget pattern fails the write with a message naming the pattern and the rule it broke
+
+Limits are 16 dimensions, 32 combined keywords/patterns per dimension, 256 characters per matcher and 4096 matcher characters per dimension. Matching runs inline on the request path with no timeout and no worker thread, because the grammar is what bounds the cost. These are routing hints, not security enforcement rules
+
+The existing heuristic-v1 tuning quota covers custom dimensions and their weights: one changed router without an auto-router license, unlimited with the entitlement. Omitting `custom_dimensions` preserves existing scoring. Routing decisions and spend logs include signals such as `custom (sqlMigration)` without recording the configured pattern or matched text. The field is configured through YAML or the model API; this change adds no dashboard editor
+
## Usage
Once configured, use the model name like any other:
diff --git a/litellm/router_strategy/complexity_router/complexity_router.py b/litellm/router_strategy/complexity_router/complexity_router.py
index 7d4497fb6f7..c8644f52c57 100644
--- a/litellm/router_strategy/complexity_router/complexity_router.py
+++ b/litellm/router_strategy/complexity_router/complexity_router.py
@@ -67,6 +67,7 @@ from litellm.types.utils import (
from .classification_rubrics import BUSINESS_TIER_CRITERIA, calibration_examples_section
from .config import (
CALIBRATION_EXAMPLES_HEADING,
+ CUSTOM_PATTERN_SCAN_CHARS,
DEFAULT_CLASSIFICATION_RUBRIC,
DEFAULT_CODE_KEYWORDS,
DEFAULT_ESCALATION_KEYWORDS,
@@ -1119,6 +1120,10 @@ class ComplexityRouter(CustomLogger):
self.config.custom_technical_keywords,
)
self.simple_keywords = self.config.simple_keywords or DEFAULT_SIMPLE_KEYWORDS
+ self._custom_dimensions = tuple(
+ (dimension, tuple(re.compile(pattern, re.IGNORECASE) for pattern in dimension.patterns))
+ for dimension in self.config.custom_dimensions
+ )
if self.config.has_custom_tiers:
self.escalation_keywords: tuple[str, ...] = ()
elif self.config.escalation_keywords is not None:
@@ -1320,6 +1325,17 @@ class ComplexityRouter(CustomLogger):
score: Final = score_high if match_count >= high_threshold else score_low
return DimensionScore(name, score, f"{signal_label} ({detail})"), match_count
+ def _score_custom_dimensions(self, prompt: str, user_text: str) -> tuple[tuple[DimensionScore, float], ...]:
+ if not self._custom_dimensions:
+ return ()
+ scanned: Final = prompt[:CUSTOM_PATTERN_SCAN_CHARS]
+ return tuple(
+ (DimensionScore(dimension.name, 1.0, f"custom ({dimension.name})"), dimension.weight)
+ for dimension, patterns in self._custom_dimensions
+ if any(self._keyword_matches(user_text, keyword) for keyword in dimension.keywords)
+ or any(pattern.search(scanned) is not None for pattern in patterns)
+ )
+
def _score_multi_step(self, text: str) -> DimensionScore:
"""Score based on multi-step patterns."""
hits: Final = sum(1 for p in self._multi_step_patterns if p.search(text))
@@ -1415,12 +1431,13 @@ class ComplexityRouter(CustomLogger):
self._score_question_complexity(prompt),
]
- # Collect signals
- signals: Final = [d.signal for d in dimensions if d.signal is not None]
+ custom_dimensions: Final = self._score_custom_dimensions(prompt, user_text)
+ signals: Final = [d.signal for d in (*dimensions, *(d for d, _ in custom_dimensions)) if d.signal is not None]
- # Compute weighted score
weights: Final = self.config.dimension_weights
- weighted_score: Final = sum(d.score * weights.get(d.name, 0) for d in dimensions)
+ weighted_score: Final = sum(d.score * weights.get(d.name, 0) for d in dimensions) + sum(
+ dimension.score * weight for dimension, weight in custom_dimensions
+ )
boundaries: Final = self._effective_tier_boundaries()
clears_override_floor: Final = weighted_score >= self._effective_reasoning_override_min_score()
diff --git a/litellm/router_strategy/complexity_router/config.py b/litellm/router_strategy/complexity_router/config.py
index c483a0b7073..3ec9f9b5394 100644
--- a/litellm/router_strategy/complexity_router/config.py
+++ b/litellm/router_strategy/complexity_router/config.py
@@ -5,13 +5,21 @@ Contains default keyword lists, weights, tier boundaries, and configuration clas
All values are configurable via proxy config.yaml.
"""
-from collections.abc import Mapping
+import math
+import re
+import warnings
+from collections.abc import Iterable, Mapping
from enum import Enum
from types import MappingProxyType
-from typing import Annotated, Final, Literal
+from typing import Annotated, Final, Literal, NamedTuple
from pydantic import BaseModel, ConfigDict, Field, SkipValidation, field_serializer, field_validator, model_validator
+with warnings.catch_warnings():
+ warnings.simplefilter("ignore", DeprecationWarning)
+ import sre_constants
+ import sre_parse
+
from litellm.types.llms.openai import REASONING_EFFORT
from litellm.types.router import AdaptiveRouterWeights, ClassifierPlugin, RoutingPlugin
@@ -569,6 +577,117 @@ class ClassifierLLMConfig(BaseModel):
return self
+MAX_CUSTOM_PATTERN_REPEAT: Final[int] = 64
+MAX_CUSTOM_PATTERN_WORK: Final[int] = 2048
+MAX_CUSTOM_DIMENSIONS_WORK: Final[int] = 8192
+MAX_CUSTOM_PATTERN_DEPTH: Final[int] = 16
+CUSTOM_PATTERN_SCAN_CHARS: Final[int] = 2048
+
+_ATOM_OPCODES: Final = frozenset(
+ {sre_constants.LITERAL, sre_constants.NOT_LITERAL, sre_constants.ANY, sre_constants.IN, sre_constants.CATEGORY}
+)
+_REPEAT_OPCODES: Final = frozenset({sre_constants.MAX_REPEAT, sre_constants.MIN_REPEAT})
+
+
+class _PatternCost(NamedTuple):
+ paths: int
+ steps: int
+
+
+def _atom_steps(node: object) -> int:
+ if isinstance(node, tuple) and len(node) == 2 and node[0] is sre_constants.IN:
+ return 1 + len(node[1])
+ return 1
+
+
+def _repeat_cost(argument: object) -> _PatternCost | str:
+ if not isinstance(argument, tuple) or len(argument) != 3:
+ return "unsupported repeat structure"
+ low, high, body = argument
+ if high > MAX_CUSTOM_PATTERN_REPEAT or len(body) != 1 or body[0][0] not in _ATOM_OPCODES:
+ return "requires a single character or class repeated at most 64 times; use {n,m} instead of *, + or {n,}"
+ choices: Final = high - low + 1
+ return _PatternCost(choices, 1 + high * _atom_steps(body[0]) + choices)
+
+
+def _node_cost(node: object, depth: int) -> _PatternCost | str:
+ if not isinstance(node, tuple) or len(node) != 2:
+ return "unsupported regex structure"
+ opcode, argument = node
+ if opcode in _ATOM_OPCODES or opcode is sre_constants.AT:
+ return _PatternCost(1, _atom_steps(node))
+ if opcode is sre_constants.SUBPATTERN:
+ return _sequence_cost(argument[-1], depth + 1)
+ if opcode is sre_constants.BRANCH:
+ costs: Final = tuple(_sequence_cost(branch, depth + 1) for branch in argument[1])
+ refused: Final = next((cost for cost in costs if isinstance(cost, str)), None)
+ if refused is not None:
+ return refused
+ return _PatternCost(
+ sum(cost.paths for cost in costs if isinstance(cost, _PatternCost)),
+ len(costs) + sum(cost.steps for cost in costs if isinstance(cost, _PatternCost)),
+ )
+ if opcode in _REPEAT_OPCODES:
+ return _repeat_cost(argument)
+ return "contains an unsupported regex construct"
+
+
+def _sequence_cost(nodes: Iterable[object], depth: int) -> _PatternCost | str:
+ if depth > MAX_CUSTOM_PATTERN_DEPTH:
+ return "nests deeper than 16 levels"
+ costs: Final = tuple(_node_cost(node, depth) for node in nodes)
+ refused: Final = next((cost for cost in costs if isinstance(cost, str)), None)
+ if refused is not None:
+ return refused
+ valid: Final = tuple(cost for cost in costs if isinstance(cost, _PatternCost))
+ # Choices multiply across a sequence; every continuation can execute once per preceding path.
+ total: Final = _PatternCost(
+ math.prod(cost.paths for cost in valid),
+ 1 + sum(cost.steps * math.prod(prior.paths for prior in valid[:index]) for index, cost in enumerate(valid)),
+ )
+ if total.steps > MAX_CUSTOM_PATTERN_WORK:
+ return "exceeds the per-pattern regex work budget"
+ return total
+
+
+def custom_pattern_work(pattern: str) -> int | str:
+ try:
+ re.compile(pattern, re.IGNORECASE)
+ parsed: Final = sre_parse.parse(pattern, re.IGNORECASE)
+ except (re.error, RecursionError, OverflowError):
+ return "is not a valid regex"
+ cost: Final = _sequence_cost(tuple(parsed), 0)
+ return cost if isinstance(cost, str) else cost.steps
+
+
+class CustomDimension(BaseModel):
+ model_config = ConfigDict(extra="forbid", frozen=True)
+
+ name: str = Field(min_length=1, max_length=64, pattern=r"^[A-Za-z][A-Za-z0-9_]*$")
+ weight: float = Field(gt=0, le=1, allow_inf_nan=False)
+ keywords: tuple[Annotated[str, Field(min_length=1, max_length=256)], ...] = Field(default=(), max_length=32)
+ patterns: tuple[Annotated[str, Field(min_length=1, max_length=256)], ...] = Field(default=(), max_length=32)
+
+ @model_validator(mode="after")
+ def _validate_matchers(self) -> "CustomDimension":
+ matchers: Final = (*self.keywords, *self.patterns)
+ if not matchers or any(not matcher.strip() for matcher in matchers):
+ raise ValueError("custom dimensions require nonblank keywords and/or patterns")
+ if len(matchers) > 32 or sum(map(len, matchers)) > 4096:
+ raise ValueError("custom dimensions allow at most 32 matchers and 4096 matcher characters each")
+ costs: Final = tuple((pattern, custom_pattern_work(pattern)) for pattern in self.patterns)
+ rejected: Final = tuple(f"pattern {pattern!r} {work}" for pattern, work in costs if isinstance(work, str))
+ if rejected:
+ raise ValueError("custom dimension " + "; ".join(rejected))
+ return self
+
+ def pattern_work(self) -> int:
+ """Combined work estimate of the validated patterns."""
+ return sum(
+ work for work in (custom_pattern_work(pattern) for pattern in self.patterns) if isinstance(work, int)
+ )
+
+
class ComplexityRouterConfig(BaseModel):
"""Configuration for the ComplexityRouter."""
@@ -671,6 +790,19 @@ class ComplexityRouterConfig(BaseModel):
description="Weights for each scoring dimension",
)
+ custom_dimensions: tuple[CustomDimension, ...] = Field(
+ default=(),
+ max_length=16,
+ description=(
+ "Named binary dimensions added to the heuristic-v1 score. Each contributes its inline weight once "
+ "when any keyword matches the current ask or a case-insensitive regex matches its first 2048 characters. "
+ "Regex quantifiers repeat one character or class at most 64 times. Unbounded quantifiers, repeated groups, "
+ "backreferences and lookarounds are rejected. Conservative work limits include alternation paths, "
+ "repeat lengths and subsequent matching: 2048 units per pattern, 8192 across the router. "
+ "Only heuristic, heuristic_first and hybrid accept this field. Uses the existing heuristic tuning quota."
+ ),
+ )
+
# Keyword lists (overridable)
code_keywords: list[str] | None = Field(
default=None,
@@ -1245,6 +1377,27 @@ class ComplexityRouterConfig(BaseModel):
)
return self
+ @model_validator(mode="after")
+ def _validate_custom_dimensions(self) -> "ComplexityRouterConfig":
+ if not self.custom_dimensions:
+ return self
+ if self.classifier_type not in ("heuristic", "heuristic_first", "hybrid"):
+ raise ValueError("custom_dimensions requires classifier_type heuristic, heuristic_first or hybrid")
+ names: Final = tuple(dimension.name.casefold() for dimension in self.custom_dimensions)
+ reserved: Final = frozenset(name.casefold() for name in DEFAULT_DIMENSION_WEIGHTS)
+ weighted: Final = frozenset(name.casefold() for name in self.dimension_weights)
+ if len(frozenset(names)) != len(names) or frozenset(names) & reserved:
+ raise ValueError("custom dimension names must be unique and must not shadow built-in dimensions")
+ if frozenset(names) & weighted:
+ raise ValueError("custom dimension weights must be inline, not in dimension_weights")
+ work: Final = sum(dimension.pattern_work() for dimension in self.custom_dimensions)
+ if work > MAX_CUSTOM_DIMENSIONS_WORK:
+ raise ValueError(
+ f"custom_dimensions regex work estimate is {work}; the limit across the router is "
+ f"{MAX_CUSTOM_DIMENSIONS_WORK}"
+ )
+ return self
+
@field_validator("heuristic_first_max_tier", mode="before")
@classmethod
def _coerce_heuristic_first_max_tier(cls, value: object) -> object:
diff --git a/litellm/router_utils/auto_router_tuning_baseline.py b/litellm/router_utils/auto_router_tuning_baseline.py
index b82269d5824..74f7b82389a 100644
--- a/litellm/router_utils/auto_router_tuning_baseline.py
+++ b/litellm/router_utils/auto_router_tuning_baseline.py
@@ -20,6 +20,7 @@ HEURISTIC_V1_TUNING_FIELDS: Final = (
"reasoning_override_min_score",
"token_thresholds",
"dimension_weights",
+ "custom_dimensions",
"code_keywords",
"reasoning_keywords",
"technical_keywords",
diff --git a/tests/test_litellm/router_strategy/test_complexity_router.py b/tests/test_litellm/router_strategy/test_complexity_router.py
index ebfb631f93b..5b1d8562abd 100644
--- a/tests/test_litellm/router_strategy/test_complexity_router.py
+++ b/tests/test_litellm/router_strategy/test_complexity_router.py
@@ -7,7 +7,8 @@ Tests the rule-based complexity scoring and tier assignment logic.
import asyncio
import logging
import sys
-from typing import Dict, List
+import time
+from typing import Dict, Final, List
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
@@ -47,6 +48,7 @@ from litellm.router_strategy.complexity_router.config import (
ClassifierLLMConfig,
ComplexityRouterConfig,
ComplexityTier,
+ custom_pattern_work,
)
from litellm.router_strategy.complexity_router.tier_predictor import (
TierGlobalStatistic,
@@ -756,6 +758,205 @@ class TestCustomTechnicalKeywords:
assert custom_score > baseline_score
+class TestCustomDimensions:
+ @pytest.mark.parametrize(
+ "matchers,prompt",
+ [
+ pytest.param(
+ {"keywords": ["orbitmesh", "fluxgate"]},
+ "Connect ORBITMESH and fluxgate for the requested change",
+ id="keywords",
+ ),
+ pytest.param(
+ {"patterns": [r"\bCREATE\s{1,4}TABLE\b", r"\bALTER\s{1,4}TABLE\b"]},
+ "create table widgets (id integer); ALTER TABLE widgets ADD label text;",
+ id="regex",
+ ),
+ ],
+ )
+ def test_custom_dimension_changes_only_matching_requests(
+ self, mock_router_instance: MagicMock, matchers: dict[str, object], prompt: str
+ ) -> None:
+ baseline: Final = ComplexityRouter("test-router", mock_router_instance)
+ configured: Final = ComplexityRouter(
+ "test-router",
+ mock_router_instance,
+ {"custom_dimensions": [{"name": "internalFrameworks", "weight": 0.7, **matchers}]},
+ )
+ baseline_tier, baseline_score, baseline_signals = baseline.classify(prompt)
+ tier, score, signals = configured.classify(prompt)
+ assert baseline_tier == ComplexityTier.SIMPLE
+ assert tier != ComplexityTier.SIMPLE
+ assert score == pytest.approx(baseline_score + 0.7)
+ assert signals == [*baseline_signals, "custom (internalFrameworks)"]
+ plain: Final = "Hello!"
+ assert configured.classify(plain) == baseline.classify(plain)
+ assert configured.classify(plain)[0] == ComplexityTier.SIMPLE
+
+ @pytest.mark.parametrize(
+ "dimension_overrides,config_overrides",
+ [
+ pytest.param({"keywords": []}, {}, id="missing-matchers"),
+ pytest.param({"keywords": [" "]}, {}, id="blank-keyword"),
+ pytest.param({"patterns": ["\t"]}, {}, id="blank-pattern"),
+ pytest.param({"patterns": ["("]}, {}, id="invalid-regex"),
+ pytest.param({"patterns": [r"a*b"]}, {}, id="unbounded-star"),
+ pytest.param({"patterns": [r"a{2,}b"]}, {}, id="unbounded-brace"),
+ pytest.param({"patterns": [r"a{0,65}b"]}, {}, id="repeat-over-64"),
+ pytest.param({"patterns": [r"(a{0,8}){0,8}b"]}, {}, id="nested-repeat"),
+ pytest.param({"patterns": [r"(a|aa){0,12}b"]}, {}, id="alternation-in-repeat"),
+ pytest.param({"patterns": [r"(?:ab){0,64}c"]}, {}, id="group-repeat"),
+ pytest.param({"patterns": ["a?" * 9 + "b"]}, {}, id="pattern-work-over-budget"),
+ pytest.param({"patterns": ["(?:a|aa)" * 9 + "z"]}, {}, id="ambiguous-alternation-chain"),
+ pytest.param({"patterns": ["a?" * 8 + "a{64}" * 10 + "z"]}, {}, id="cheap-prefix-expensive-tail"),
+ pytest.param({"patterns": [r"(a)\1"]}, {}, id="backreference"),
+ pytest.param({"patterns": [r"(?=x)y"]}, {}, id="lookahead"),
+ pytest.param({"patterns": [r"(?>ab)"]}, {}, id="atomic-group"),
+ pytest.param({"patterns": [r"a*+b"]}, {}, id="possessive"),
+ pytest.param({"name": "CODEPRESENCE"}, {"dimension_weights": {"tokenCount": 0.1}}, id="reserved-name"),
+ pytest.param({}, {"dimension_weights": {"INTERNALFRAMEWORKS": 0.7}}, id="weight-in-map"),
+ pytest.param({"weight": 0}, {}, id="zero-weight"),
+ pytest.param({"weight": 1.1}, {}, id="excess-weight"),
+ pytest.param({"weight": float("nan")}, {}, id="nan-weight"),
+ pytest.param({"weight": float("inf")}, {}, id="infinite-weight"),
+ pytest.param({"name": "bad-name"}, {}, id="invalid-name"),
+ pytest.param({"name": "x" * 65}, {}, id="long-name"),
+ pytest.param({"keywords": [""]}, {}, id="empty-matcher"),
+ pytest.param({"keywords": ["x" * 257]}, {}, id="long-matcher"),
+ pytest.param({"keywords": ["x"] * 32, "patterns": ["y"]}, {}, id="combined-matcher-count"),
+ pytest.param({"keywords": ["x" * 256] * 17}, {}, id="matcher-character-budget"),
+ pytest.param({"unknown": True}, {}, id="extra-field"),
+ ],
+ )
+ def test_custom_dimension_invalid_configuration_rejected(
+ self, dimension_overrides: dict[str, object], config_overrides: dict[str, object]
+ ) -> None:
+ with pytest.raises(ValidationError, match=r"custom_dimensions|custom dimension"):
+ ComplexityRouterConfig.model_validate(
+ {
+ "custom_dimensions": [
+ {
+ "name": "internalFrameworks",
+ "weight": 0.7,
+ "keywords": ["orbitmesh"],
+ **dimension_overrides,
+ }
+ ],
+ **config_overrides,
+ }
+ )
+
+ @pytest.mark.parametrize(
+ "names",
+ [
+ pytest.param(("internalFrameworks", "INTERNALFRAMEWORKS"), id="duplicate-casefolded-name"),
+ pytest.param(tuple(f"dimension{i}" for i in range(17)), id="dimension-count"),
+ ],
+ )
+ def test_custom_dimension_names_and_count_are_bounded(self, names: tuple[str, ...]) -> None:
+ with pytest.raises(ValidationError, match=r"custom_dimensions|custom dimension"):
+ ComplexityRouterConfig.model_validate(
+ {"custom_dimensions": [{"name": name, "weight": 0.7, "keywords": ["orbitmesh"]} for name in names]}
+ )
+
+ @pytest.mark.parametrize("classifier_type", ("heuristic_v2", "llm", "custom"))
+ def test_custom_dimensions_reject_classifiers_outside_the_tuning_gate(self, classifier_type: str) -> None:
+ classifier_config: Final = (
+ {"classifier_plugin": _FixedTierClassifier("SIMPLE")}
+ if classifier_type == "custom"
+ else {"classifier_llm_config": {"model": "judge"}}
+ if classifier_type == "llm"
+ else {}
+ )
+ with pytest.raises(ValidationError, match="custom_dimensions requires classifier_type"):
+ ComplexityRouterConfig.model_validate(
+ {
+ "classifier_type": classifier_type,
+ "custom_dimensions": [{"name": "internalFrameworks", "weight": 0.7, "keywords": ["orbitmesh"]}],
+ **classifier_config,
+ }
+ )
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("current_ask", ("Hello!", "orbitmesh"))
+ async def test_custom_dimensions_public_hook_scores_only_current_ask(
+ self, mock_router_instance: MagicMock, current_ask: str
+ ) -> None:
+ router: Final = ComplexityRouter(
+ "test-router",
+ mock_router_instance,
+ {
+ "tiers": {"SIMPLE": "cheap", "MEDIUM": "mid", "COMPLEX": "strong", "REASONING": "top"},
+ "custom_dimensions": [{"name": "internalFrameworks", "weight": 0.7, "keywords": ["orbitmesh"]}],
+ },
+ )
+ result: Final = await router.async_pre_routing_hook(
+ model="test-router",
+ request_kwargs={},
+ messages=[
+ {"role": "system", "content": "orbitmesh"},
+ {"role": "user", "content": "orbitmesh"},
+ {"role": "assistant", "content": "orbitmesh is ready"},
+ {"role": "user", "content": current_ask},
+ {"role": "tool", "tool_call_id": "previous", "content": "orbitmesh"},
+ ],
+ )
+ assert result is not None
+ assert result.routing_decision is not None
+ assert ("custom (internalFrameworks)" in result.routing_decision["signals"]) is (current_ask == "orbitmesh")
+ assert result.model == ("top" if current_ask == "orbitmesh" else "cheap")
+ assert "orbitmesh" not in " ".join(result.routing_decision["signals"])
+
+ def test_custom_patterns_scan_only_the_first_2048_characters(self, mock_router_instance: MagicMock) -> None:
+ router: Final = ComplexityRouter(
+ "test-router",
+ mock_router_instance,
+ {"custom_dimensions": [{"name": "late", "weight": 0.7, "patterns": [r"zzz{1,3}"]}]},
+ )
+ assert "custom (late)" in router.classify("a" * 2040 + " zzz")[2]
+ assert "custom (late)" not in router.classify("a" * 2048 + " zzz")[2]
+
+ def test_custom_dimensions_router_wide_regex_work_is_capped(self) -> None:
+ heavy: Final = {"weight": 0.5, "patterns": ["a?" * 8 + "z"]}
+ ComplexityRouterConfig.model_validate({"custom_dimensions": [{"name": f"d{i}", **heavy} for i in range(6)]})
+ with pytest.raises(ValidationError, match="regex work estimate is 8939"):
+ ComplexityRouterConfig.model_validate({"custom_dimensions": [{"name": f"d{i}", **heavy} for i in range(7)]})
+
+ @pytest.mark.parametrize(
+ "pattern,work",
+ [
+ pytest.param(r"\b(create|alter|drop)\s{1,4}table\b", 135, id="sql-ddl"),
+ pytest.param("a?" * 8 + "z", 1277, id="optional-chain-near-cap"),
+ pytest.param(r"a{0,15}a{0,15}z", 801, id="adjacent-bounded-near-cap"),
+ pytest.param(r"[a-z0-9_]{3,63}\.(com|net|io)", 1291, id="class-repeat-plus-alternation"),
+ pytest.param("(?:a|aa)" * 8 + "z", 1787, id="ambiguous-alternation-near-cap"),
+ pytest.param("a{64}" * 10 + "z", 662, id="long-deterministic-tail"),
+ ],
+ )
+ def test_custom_pattern_work_stays_cheap_on_adversarial_text(
+ self, mock_router_instance: MagicMock, pattern: str, work: int
+ ) -> None:
+ assert custom_pattern_work(pattern) == work
+ router: Final = ComplexityRouter(
+ "test-router",
+ mock_router_instance,
+ {
+ "custom_dimensions": [
+ {"name": "bounded", "weight": 0.7, "patterns": [pattern]},
+ {"name": "internalFrameworks", "weight": 0.7, "keywords": ["orbitmesh"]},
+ ]
+ },
+ )
+ adversarial: Final = "orbitmesh " + "a" * 4000
+ started: Final = time.perf_counter()
+ tier, score, signals = router.classify(adversarial)
+ elapsed: Final = time.perf_counter() - started
+ assert signals == ["long (1002 tokens)", "custom (internalFrameworks)"]
+ assert score == pytest.approx(0.8)
+ assert tier == ComplexityTier.REASONING
+ assert elapsed < 0.1
+
+
class TestAsyncPreRoutingHookEdgeCases:
"""Test edge cases for async_pre_routing_hook method."""
diff --git a/tests/test_litellm/router_utils/test_auto_router_tuning_baseline.py b/tests/test_litellm/router_utils/test_auto_router_tuning_baseline.py
index fa7a96adb20..f686a62db76 100644
--- a/tests/test_litellm/router_utils/test_auto_router_tuning_baseline.py
+++ b/tests/test_litellm/router_utils/test_auto_router_tuning_baseline.py
@@ -3,6 +3,7 @@
from __future__ import annotations
from collections.abc import Mapping
+from typing import Final
import pytest
@@ -58,6 +59,7 @@ class TestTuningFingerprint:
"reasoning_override_min_score": 0.05,
"token_thresholds": {"simple": 20, "complex": 500},
"dimension_weights": {"codePresence": 0.9},
+ "custom_dimensions": [{"name": "internalFrameworks", "weight": 0.7, "keywords": ["orbitmesh"]}],
"code_keywords": ["orionflow"],
"reasoning_keywords": ["deduce"],
"technical_keywords": ["ledgerkit"],
@@ -216,6 +218,28 @@ class TestQuota:
is None
)
+ def test_custom_dimension_add_edit_and_revert_share_one_quota_slot(self) -> None:
+ baselines: Final = snapshot_tuning_baselines(())
+ original: Final = _router("a", {})
+ config: Final = {
+ "custom_dimensions": [{"name": "internalFrameworks", "weight": 0.7, "keywords": ["orbitmesh"]}]
+ }
+ edited_config: Final = {
+ "custom_dimensions": [{"name": "internalFrameworks", "weight": 0.9, "keywords": ["orbitmesh"]}]
+ }
+ added: Final = _router("a", config)
+ edited: Final = _router("a", edited_config)
+ second: Final = _router("b", config)
+
+ assert tuning_fingerprint(config) != tuning_fingerprint(edited_config)
+ assert mutable_tuned_identities((added,), baselines) == {router_identity(original)}
+ assert tuning_quota_violation(candidate=added, others=(original,), baselines=baselines, limit=1) is None
+ assert tuning_quota_violation(candidate=edited, others=(added,), baselines=baselines, limit=1) is None
+ assert tuning_quota_violation(candidate=second, others=(edited,), baselines=baselines, limit=1) is not None
+ assert tuning_quota_violation(candidate=original, others=(edited,), baselines=baselines, limit=1) is None
+ assert mutable_tuned_identities((original,), baselines) == frozenset()
+ assert tuning_quota_violation(candidate=second, others=(original,), baselines=baselines, limit=1) is None
+
def test_violation_message_names_the_limit_and_remedy(self) -> None:
message = tuning_limit_violation(held=2, limit=1)
assert message is not None
diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts
index 3540d2f6aea..7121124e64f 100644
--- a/ui/litellm-dashboard/src/lib/http/schema.d.ts
+++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts
@@ -26560,6 +26560,23 @@ export interface components {
[key: string]: unknown;
};
};
+ /** CustomDimension */
+ CustomDimension: {
+ /**
+ * Keywords
+ * @default []
+ */
+ keywords: string[];
+ /** Name */
+ name: string;
+ /**
+ * Patterns
+ * @default []
+ */
+ patterns: string[];
+ /** Weight */
+ weight: number;
+ };
/**
* CustomerResponse
* @description Customer object returned by the /customer read+write endpoints.
@@ -34873,6 +34890,12 @@ export interface components {
* @default 0.95
*/
context_window_escalation_buffer: number;
+ /**
+ * Custom Dimensions
+ * @description Named binary dimensions added to the heuristic-v1 score. Each contributes its inline weight once when any keyword matches the current ask or a case-insensitive regex matches its first 2048 characters. Regex quantifiers repeat one character or class at most 64 times. Unbounded quantifiers, repeated groups, backreferences and lookarounds are rejected. Conservative work limits include alternation paths, repeat lengths and subsequent matching: 2048 units per pattern, 8192 across the router. Only heuristic, heuristic_first and hybrid accept this field. Uses the existing heuristic tuning quota.
+ * @default []
+ */
+ custom_dimensions: components["schemas"]["CustomDimension"][];
/**
* Custom Technical Keywords
* @description Domain-specific technical keywords appended to the effective base list (technical_keywords if set, otherwise DEFAULT_TECHNICAL_KEYWORDS). Order is preserved; duplicates are removed case-insensitively against the base list and within this list.