Skip to content

fix(router): tag-based routing for complexity_router deployments sharing a model_name - #33708

Closed
devin-ai-integration[bot] wants to merge 1 commit into
litellm_internal_stagingfrom
litellm_complexity_router_tag_routing_1784303149
Closed

devin-ai-integration[bot] wants to merge 1 commit into
litellm_internal_stagingfrom
litellm_complexity_router_tag_routing_1784303149

Conversation

@devin-ai-integration

@devin-ai-integration devin-ai-integration Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

Relevant issues

Fixes #33655

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Screenshots / Proof of Fix

Live proxy against real Anthropic APIs (costs real $), two auto_router/complexity_router deployments sharing model_name: smart-router, one tagged region-a and one tagged region-b, with enable_tag_filtering: true

# tag_complexity_config.yaml (abridged)
model_list:
  - model_name: smart-router
    litellm_params:
      model: auto_router/complexity_router
      complexity_router_default_model: region-a-simple
      complexity_router_config:
        tiers: {SIMPLE: region-a-simple, MEDIUM: region-a-simple, COMPLEX: region-a-complex, REASONING: region-a-complex}
      tags: ["region-a"]
  - model_name: smart-router
    litellm_params:
      model: auto_router/complexity_router
      complexity_router_default_model: region-b-simple
      complexity_router_config:
        tiers: {SIMPLE: region-b-simple, MEDIUM: region-b-simple, COMPLEX: region-b-complex, REASONING: region-b-complex}
      tags: ["region-b"]
  - {model_name: region-a-simple, litellm_params: {model: anthropic/claude-opus-4-1,    api_key: os.environ/ANTHROPIC_API_KEY, tags: ["region-a"]}}
  - {model_name: region-b-simple, litellm_params: {model: anthropic/claude-sonnet-4-5,  api_key: os.environ/ANTHROPIC_API_KEY, tags: ["region-b"]}}
  # ...region-a-complex / region-b-complex omitted for brevity
router_settings:
  enable_tag_filtering: true

Before the fix (base litellm_internal_staging), the second deployment is dropped at startup

LiteLLM Router:ERROR: router.py:7546 - Error creating deployment: Complexity-router deployment
smart-router already exists. Please use a different model name., ignoring and continuing with other deployments.

so a region-b request is forced onto the region-a config and 401s, exactly as reported

$ curl -s http://localhost:4000/v1/chat/completions -H "Authorization: Bearer sk-1234" \
    -H "Content-Type: application/json" \
    -d '{"model":"smart-router","messages":[{"role":"user","content":"hi"}],"tags":["region-b"]}'
{
  "message": "Not allowed to access model due to tags configuration. Passed model=region-a-simple and tags=['region-b']",
  "code": "401"
}

After the fix (this branch, commit 73524df72a), both configs register and each tag resolves to its own config

$ curl -s -D- http://localhost:4000/v1/chat/completions -H "Authorization: Bearer sk-1234" \
    -H "Content-Type: application/json" \
    -d '{"model":"smart-router","messages":[{"role":"user","content":"hi"}],"tags":["region-a"]}' -o /tmp/ra.json
x-litellm-model-id: 39fff0c13e04...           # region-a-simple = anthropic/claude-opus-4-1
# body: {"choices":[{"message":{"content":"Hello! How can I help you today?"}}], ...}

$ curl -s -D- http://localhost:4000/v1/chat/completions -H "Authorization: Bearer sk-1234" \
    -H "Content-Type: application/json" \
    -d '{"model":"smart-router","messages":[{"role":"user","content":"hi"}],"tags":["region-b"]}' -o /tmp/rb.json
x-litellm-model-id: f79f985b7f3d...           # region-b-simple = anthropic/claude-sonnet-4-5
# body: {"choices":[{"message":{"content":"Hello! How can I help you today?"}}], ...}

region-a resolves to region-a-simple (claude-opus-4-1) and region-b resolves to region-b-simple (claude-sonnet-4-5), so each tag group now hits its own tier config instead of colliding on the first one

Type

🐛 Bug Fix

Changes

Two auto_router/complexity_router deployments that share a model_name but carry different tags (e.g. one tier config per region) used to collide: self.complexity_routers was keyed by model_name alone, so the second registration raised "already exists" and was dropped when ignore_invalid_deployments swallowed it. Every request then resolved to the first deployment's tier config regardless of the request's tags, which produced 401 Not allowed to access model due to tags configuration for the second tag group

The registry now holds every config for a model_name and selection happens per request based on tags

self.complexity_routers: Dict[str, list[ComplexityRouter]]

# init: append instead of reject; only a duplicate tag-set is still an error
existing = self.complexity_routers.get(model_name, [])
if any(frozenset(r.deployment_tags) == frozenset(new_tags) for r in existing):
    raise ValueError(...)  # genuine duplicate
self.complexity_routers[model_name] = [*existing, new_router]

# async_pre_routing_hook: pick the config whose tags match the request
routers = self.complexity_routers.get(model)
if len(routers) == 1:
    return routers[0]                       # unchanged single-deployment behaviour
request_tags = _get_tags_from_request_kwargs(request_kwargs, metadata_variable_name)
match = first r where is_valid_deployment_tag(r.deployment_tags, request_tags, match_any)
     or first r tagged "default"
     or routers[0]

ComplexityRouter now stores the deployment_tags it was built with so the selection above can disambiguate. _finalize_adaptive_router_if_configured was updated to iterate the list values. Single-deployment setups are unchanged because a one-element list short-circuits to that router

Scope is intentionally limited to the complexity router, which is the case reported and reproduced. auto_routers, adaptive_routers and quality_routers share the same Dict[model_name, router] shape and the same latent limitation; extending them can follow the same pattern in a separate change (adaptive is more involved because of its per-instance post-call hooks and DB-backed state)

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

Link to Devin session: https://app.devin.ai/sessions/eb65ae6ee3c04263a44e7a3054cad015

@devin-ai-integration

Copy link
Copy Markdown
Contributor Author

🤖 Devin AI Engineer

I'll be helping with this pull request! Here's what you should know:

✅ I will automatically:

  • Address comments on this PR. Add '(aside)' to your comment to have me ignore it.
  • Look at CI failures and help fix them

Note: I can only respond to comments from users who have write access to this repository.

⚙️ Control Options:

  • Disable automatic comment, CI, and merge conflict monitoring

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a collision bug where two auto_router/complexity_router deployments sharing the same model_name but carrying different tags (e.g. per-region configs) would silently drop the second registration, routing all requests to the first deployment's tier config regardless of the request's tags.

  • self.complexity_routers is widened from Dict[str, ComplexityRouter] to Dict[str, list[ComplexityRouter]]; registration appends to the list and only rejects a genuinely duplicate tag-set.
  • A new _select_complexity_router helper resolves the correct ComplexityRouter per request using tag-based matching (with fallback to a default-tagged router or routers[0] for single-deployment setups).
  • ComplexityRouter.__init__ gains a deployment_tags parameter so each instance can identify itself during selection.
  • _finalize_adaptive_router_if_configured is updated to iterate the list values; the scope limitation for adaptive routers is acknowledged and deferred.

Confidence Score: 4/5

The core fix is correctly scoped and the new tests cover registration, duplicate rejection, and per-tag selection. Two minor concerns around the adaptive-router init fallback and the no-match silent fallback keep this from a clean bill of health.

The key structural change (list-based registry + tag selection) is sound, the single-deployment fast-path is preserved, and the tests match real-world scenarios described in the linked issue. The break placement in the adaptive-router init loop and the silent routers[0] fallback when request tags match no deployment are present-but-edge-case concerns that do not affect the primary fix.

litellm/router.py — specifically the _finalize_adaptive_router_if_configured inner loop and the _select_complexity_router fallback path

Important Files Changed

Filename Overview
litellm/router.py Core fix: changes complexity_routers dict value from a single ComplexityRouter to a list, adds _select_complexity_router for per-request tag-based selection; one subtle issue with break placement in _finalize_adaptive_router_if_configured
litellm/router_strategy/complexity_router/complexity_router.py Adds deployment_tags parameter to ComplexityRouter.init and stores it as self.deployment_tags; straightforward and correct
tests/test_litellm/router_strategy/test_complexity_router.py Adds targeted regression tests for the dual-deployment tag collision bug; all tests are mock-only (no network calls), covering registration, duplicate rejection, tag-based selection, and the pre-routing hook

Reviews (1): Last reviewed commit: "fix(router): support tag-based routing f..." | Re-trigger Greptile

Comment thread litellm/router.py
Comment on lines +7709 to +7715
for complexity_router in complexity_router_list:
if not complexity_router.config.adaptive:
continue
adaptive_router = complexity_router._ensure_adaptive_router()
if adaptive_router is not None:
self.adaptive_routers[model_name] = adaptive_router
break

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 break fires even when adaptive-router init returns None

The break sits outside the if adaptive_router is not None: guard, so the inner loop exits regardless of whether the first adaptive=True complexity router successfully produced an AdaptiveRouter. If a config-reload path caused the first router's _adaptive_init_attempted to be True with self.adaptive_router=None (a failed prior init), this loop exits without registering anything and silently skips any subsequent routers in the list that might succeed. Moving break inside the if block would ensure the loop keeps searching until it registers a valid adaptive router.

Comment thread litellm/router.py
Comment on lines +10854 to +10858
for router in routers:
if "default" in router.deployment_tags:
return router

return routers[0]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Silent fallback to wrong tier config when no tags match

When request_tags is non-empty but no deployment's deployment_tags satisfy is_valid_deployment_tag, the function falls through to the "default" check and finally returns routers[0]. This means a request tagged ["row-dev"] with no matching deployment silently gets the cn tier config (wrong region's model list), which can still produce 401 Not allowed errors for the cn models. Consider whether a hard failure (or at least a warning log) is more appropriate when the request carries tags that match no registered deployment.

@codecov

codecov Bot commented Jul 17, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.87500% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/router.py 96.77% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_complexity_router_tag_routing_1784303149 (73524df) with litellm_internal_staging (4d33964)

Open in CodSpeed

@yuneng-berri
yuneng-berri deleted the branch litellm_internal_staging September 13, 2026 04:32
@yuneng-berri yuneng-berri reopened this Sep 13, 2026
@github-actions

Copy link
Copy Markdown
Contributor

#33655 was fixed by #33691 on main, so this pull request is closed. Reopen it if something was missed.

@github-actions github-actions Bot closed this Sep 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: complexity_router does not support tag-based routing — same model_name with different tags silently uses only the first registered config

2 participants