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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(proxy): resolve router_settings.plugins dotted paths and load plugins from installed packages (#33644)
devin-ai-integration[bot]8a4f3808ad72
diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.pyindex dbdfdd5fdd3..b0a2b65f927 100644--- a/litellm/proxy/proxy_server.py+++ b/litellm/proxy/proxy_server.py@@ -3708,22 +3708,22 @@ def _attach_redis_usage_cache(redis_cache: RedisCache, enable_redis_auth_cache:litellm_config_cache.redis_cache = redis_cache-def resolve_complexity_router_plugins(- model_name: str,- complexity_router_config: dict,+def resolve_routing_plugins(+ plugin_paths: list,config_file_path: str | None,-) -> None:+ source_label: str,+) -> list:"""- Resolves `complexity_router_config["plugins"]` dotted-path strings to live- instances via `get_instance_fn` (the same convention `litellm_settings.callbacks`- uses), in place. Raises at config-load time if a path resolves to something that- doesn't implement `RoutingPlugin`, rather than deferring to a confusing- `AttributeError` on the first request that reaches the plugin pipeline.+ Resolves a list of routing-plugin entries to live `RoutingPlugin` instances.+ Each string entry is resolved through `get_instance_fn` (the same dotted-path+ convention `litellm_settings.callbacks` uses, which resolves both local module+ files next to the config and modules installed as Python packages); non-string+ entries are assumed to already be instances and passed through. Raises at+ config-load time if any entry resolves to something that doesn't implement+ `RoutingPlugin`, rather than deferring to a confusing `AttributeError` on the+ first request that reaches the plugin pipeline. `source_label` names the config+ key being resolved so the error points the operator at the right place."""- plugin_paths = complexity_router_config.get("plugins")- if not isinstance(plugin_paths, list):- return-resolved_plugins = [get_instance_fn(value=plugin_path, config_file_path=config_file_path)if isinstance(plugin_path, str)@@ -3739,12 +3739,31 @@ def resolve_complexity_router_plugins(getattr(resolved_plugin, "run", None)):raise ValueError(- f"complexity_router_config.plugins entry {plugin_path!r} on model {model_name!r} "- f"resolved to {resolved_plugin!r}, which does not implement the RoutingPlugin "- "interface (an async `run(context)` method). Fix the referenced module before "- "starting the proxy."+ f"{source_label} entry {plugin_path!r} resolved to {resolved_plugin!r}, which does "+ "not implement the RoutingPlugin interface (an async `run(context)` method). Fix the "+ "referenced module before starting the proxy.")- complexity_router_config["plugins"] = resolved_plugins+ return resolved_plugins+++def resolve_complexity_router_plugins(+ model_name: str,+ complexity_router_config: dict,+ config_file_path: str | None,+) -> None:+ """+ Resolves `complexity_router_config["plugins"]` dotted-path strings to live+ instances in place, via `resolve_routing_plugins`.+ """+ plugin_paths = complexity_router_config.get("plugins")+ if not isinstance(plugin_paths, list):+ return++ complexity_router_config["plugins"] = resolve_routing_plugins(+ plugin_paths=plugin_paths,+ config_file_path=config_file_path,+ source_label=f"complexity_router_config.plugins on model {model_name!r}",+ )class ProxyConfig:@@ -4874,6 +4893,12 @@ class ProxyConfig:for k, v in router_settings.items():if k in available_args:+ if k == "plugins" and isinstance(v, list):+ v = resolve_routing_plugins(+ plugin_paths=v,+ config_file_path=config_file_path,+ source_label="router_settings.plugins",+ )router_params[k] = velif k in {"health_check_interval", "health_check_concurrency"}:raise ValueError(diff --git a/litellm/proxy/types_utils/utils.py b/litellm/proxy/types_utils/utils.pyindex e2206541fc6..8d7aedce4d0 100644--- a/litellm/proxy/types_utils/utils.py+++ b/litellm/proxy/types_utils/utils.py@@ -34,16 +34,12 @@ def get_instance_fn(value: str, config_file_path: Optional[str] = None) -> Any:module_name = ".".join(parts[:-1])instance_name = parts[-1]- # If config_file_path is provided, use it to determine the module spec and load the module+ module_file_path = Noneif config_file_path is not None:directory = os.path.dirname(config_file_path)- module_file_path = os.path.join(directory, *module_name.split("."))- module_file_path += ".py"-- # Check if the file exists before trying to load it- if not os.path.exists(module_file_path):- raise ImportError(f"Could not find module file {module_file_path}")+ module_file_path = os.path.join(directory, *module_name.split(".")) + ".py"+ if module_file_path is not None and os.path.exists(module_file_path):spec = importlib.util.spec_from_file_location(module_name, module_file_path) # type: ignoreif spec is None:raise ImportError(f"Could not find a module specification for {module_file_path}")@@ -52,7 +48,6 @@ def get_instance_fn(value: str, config_file_path: Optional[str] = None) -> Any:raise ImportError(f"Could not find a module loader for {module_file_path}")spec.loader.exec_module(module) # type: ignoreelse:- # Dynamically import the modulemodule = importlib.import_module(module_name)# Get the instance from the modulediff --git a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py b/tests/test_litellm/proxy/proxy_server/test_proxy_config.pyindex 45d35419680..bd8e92c3cc2 100644--- a/tests/test_litellm/proxy/proxy_server/test_proxy_config.py+++ b/tests/test_litellm/proxy/proxy_server/test_proxy_config.py@@ -22,6 +22,7 @@ from litellm.proxy.proxy_server import (_scrub_db_overlay_remote_module_loads,_scrub_guardrail_inner,resolve_complexity_router_plugins,+ resolve_routing_plugins,)from .conftest import normalize@@ -185,6 +186,75 @@ def test_resolve_complexity_router_plugins_rejects_synchronous_run_method(tmp_pa)+# ---------------------------------------------------------------------------+# resolve_routing_plugins+# ---------------------------------------------------------------------------+++def test_resolve_routing_plugins_resolves_dotted_paths(tmp_path):+ plugin_file = tmp_path / "rs_plugin.py"+ plugin_file.write_text(+ "class _Plugin:\n"+ " async def run(self, context):\n"+ " return context\n"+ "\n"+ "rs_plugin_instance = _Plugin()\n"+ )++ resolved = resolve_routing_plugins(+ plugin_paths=["rs_plugin.rs_plugin_instance"],+ config_file_path=str(tmp_path / "config.yaml"),+ source_label="router_settings.plugins",+ )++ assert len(resolved) == 1+ assert type(resolved[0]).__name__ == "_Plugin"+++def test_resolve_routing_plugins_passes_through_instances(tmp_path):+ class _Plugin:+ async def run(self, context):+ return context++ instance = _Plugin()+ resolved = resolve_routing_plugins(+ plugin_paths=[instance],+ config_file_path=None,+ source_label="router_settings.plugins",+ )+ assert resolved == [instance]+++def test_resolve_routing_plugins_rejects_non_routing_plugin(tmp_path):+ plugin_file = tmp_path / "bad_rs_plugin.py"+ plugin_file.write_text("not_a_plugin = object()\n")++ with pytest.raises(ValueError, match="router_settings.plugins"):+ resolve_routing_plugins(+ plugin_paths=["bad_rs_plugin.not_a_plugin"],+ config_file_path=str(tmp_path / "config.yaml"),+ source_label="router_settings.plugins",+ )+++def test_resolve_routing_plugins_rejects_synchronous_run(tmp_path):+ plugin_file = tmp_path / "sync_rs_plugin.py"+ plugin_file.write_text(+ "class _SyncPlugin:\n"+ " def run(self, context):\n"+ " return context\n"+ "\n"+ "sync_plugin_instance = _SyncPlugin()\n"+ )++ with pytest.raises(ValueError, match="does not implement the RoutingPlugin interface"):+ resolve_routing_plugins(+ plugin_paths=["sync_rs_plugin.sync_plugin_instance"],+ config_file_path=str(tmp_path / "config.yaml"),+ source_label="router_settings.plugins",+ )++# ---------------------------------------------------------------------------# ProxyConfig.__init__# ---------------------------------------------------------------------------@@ -793,6 +863,62 @@ async def test_ProxyConfig_load_config_minimal_yaml(tmp_path, monkeypatch):}+async def test_ProxyConfig_load_config_resolves_router_settings_plugins(tmp_path, monkeypatch):+ """Regression: router_settings.plugins dotted-path strings must be resolved to+ live RoutingPlugin instances on the created Router. Previously they were passed+ through as raw strings and only blew up at request time when the pipeline tried+ to `await "some.string".run(context)`."""+ plugin_file = tmp_path / "rs_plugin.py"+ plugin_file.write_text(+ "class _Plugin:\n"+ " async def run(self, context):\n"+ " return context\n"+ "\n"+ "rs_plugin_instance = _Plugin()\n"+ )+ f = tmp_path / "c.yaml"+ f.write_text(+ "model_list: []\n"+ "general_settings: {}\n"+ "litellm_settings: {}\n"+ "router_settings:\n"+ " plugins:\n"+ " - rs_plugin.rs_plugin_instance\n"+ )+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", False)+ monkeypatch.delenv("LITELLM_CONFIG_BUCKET_NAME", raising=False)++ router, _model_list, _general_settings = await ProxyConfig().load_config(+ router=None, config_file_path=str(f)+ )++ assert len(router.routing_plugins) == 1+ assert type(router.routing_plugins[0]).__name__ == "_Plugin"+++async def test_ProxyConfig_load_config_rejects_bad_router_settings_plugin(tmp_path, monkeypatch):+ plugin_file = tmp_path / "bad_rs_plugin.py"+ plugin_file.write_text("not_a_plugin = object()\n")+ f = tmp_path / "c.yaml"+ f.write_text(+ "model_list: []\n"+ "general_settings: {}\n"+ "litellm_settings: {}\n"+ "router_settings:\n"+ " plugins:\n"+ " - bad_rs_plugin.not_a_plugin\n"+ )+ monkeypatch.setattr("litellm.proxy.proxy_server.prisma_client", None)+ monkeypatch.setattr("litellm.proxy.proxy_server.store_model_in_db", False)+ monkeypatch.delenv("LITELLM_CONFIG_BUCKET_NAME", raising=False)++ with pytest.raises(ValueError, match="does not implement the RoutingPlugin interface"):+ await ProxyConfig().load_config(router=None, config_file_path=str(f))++@pytest.mark.asyncioasync def test_ProxyConfig_load_config_wires_general_settings_url_validation(tmp_path, monkeypatch):"""Regression for #26599: SSRF settings in general_settings must reach litellm globals."""diff --git a/tests/test_litellm/proxy/types_utils/test_get_instance_fn_runtime_gate.py b/tests/test_litellm/proxy/types_utils/test_get_instance_fn_runtime_gate.pyindex bf77ef81641..3d76ad54a9c 100644--- a/tests/test_litellm/proxy/types_utils/test_get_instance_fn_runtime_gate.py+++ b/tests/test_litellm/proxy/types_utils/test_get_instance_fn_runtime_gate.py@@ -64,6 +64,65 @@ def test_dotted_module_path_is_unaffected_by_gate():assert result == "loaded"+def test_installed_package_resolved_when_local_file_absent(tmp_path, monkeypatch):+ # Regression: with config_file_path set (startup load path) but no local+ # module file next to it, get_instance_fn must fall back to importing the+ # dotted name as an installed package. Previously it raised ImportError+ # ("Could not find module file ..."), so plugins shipped as pip packages+ # (e.g. router_settings/complexity_router plugins) could not be referenced.+ pkg_dir = tmp_path / "site"+ pkg_dir.mkdir()+ (pkg_dir / "my_installed_plugin.py").write_text(+ "class _P:\n"+ " async def run(self, context):\n"+ " return context\n"+ "\n"+ "instance = _P()\n"+ )+ monkeypatch.syspath_prepend(str(pkg_dir))+ config_dir = tmp_path / "cfg"+ config_dir.mkdir()++ result = get_instance_fn(+ value="my_installed_plugin.instance",+ config_file_path=str(config_dir / "config.yaml"),+ )++ assert type(result).__name__ == "_P"+++def test_local_module_file_wins_over_installed_package(tmp_path, monkeypatch):+ # A local module file next to the config must still take precedence over an+ # installed package of the same dotted name -- the fallback only kicks in+ # when no local file exists.+ pkg_dir = tmp_path / "site"+ pkg_dir.mkdir()+ (pkg_dir / "shadowed_mod.py").write_text("value = 'from-installed'\n")+ monkeypatch.syspath_prepend(str(pkg_dir))+ config_dir = tmp_path / "cfg"+ config_dir.mkdir()+ (config_dir / "shadowed_mod.py").write_text("value = 'from-local-file'\n")++ result = get_instance_fn(+ value="shadowed_mod.value",+ config_file_path=str(config_dir / "config.yaml"),+ )++ assert result == "from-local-file"+++def test_missing_module_everywhere_raises_import_error(tmp_path):+ # Neither a local file nor an installed package: the fallback import must+ # surface a real ImportError rather than silently succeeding.+ config_dir = tmp_path / "cfg"+ config_dir.mkdir()+ with pytest.raises(ImportError):+ get_instance_fn(+ value="definitely_not_a_real_module_xyz.instance",+ config_file_path=str(config_dir / "config.yaml"),+ )++def test_pass_through_route_threads_config_file_path():# ``create_pass_through_route`` must forward ``config_file_path`` so# an operator with ``custom_handler: s3://...`` declared in