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(cli): skip remote model cost map fetch in lite CLI processes
kerry25a6c2a2749b
diff --git a/litellm/litellm_core_utils/get_model_cost_map.py b/litellm/litellm_core_utils/get_model_cost_map.pyindex cdc4810ff04..7d3b67e58c8 100644--- a/litellm/litellm_core_utils/get_model_cost_map.py+++ b/litellm/litellm_core_utils/get_model_cost_map.py@@ -2,6 +2,7 @@Pulls the cost + context window + provider route for known models from https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.jsonThis can be disabled by setting the LITELLM_LOCAL_MODEL_COST_MAP environment variable to True.+The ``lite`` and ``litellm-proxy`` CLI entry points also use the bundled map without fetching.```export LITELLM_LOCAL_MODEL_COST_MAP=True@@ -13,11 +14,13 @@ import hashlibimport jsonimport osimport random+import sysimport timefrom collections.abc import Awaitable, Callablefrom dataclasses import dataclass, replacefrom datetime import datetime, timezonefrom importlib.resources import files+from pathlib import Pathfrom typing import Final, Protocolimport httpx@@ -33,6 +36,12 @@ from litellm.litellm_core_utils.fallback_generalizations import ()FALLBACK_GENERALIZATIONS_KEY: Final = "fallback_generalizations"+_CLI_ENTRYPOINT_NAMES: Final = frozenset({"lite", "litellm-proxy"})+++def _is_cli_process() -> bool:+ return Path(sys.argv[0]).stem in _CLI_ENTRYPOINT_NAMES+# Reserved top-level keys that are not model entries. They must be excluded# from the model-count integrity check so a real upstream shrink can't be masked.@@ -531,7 +540,8 @@ def get_model_cost_map("""Public entry point — returns the model cost map dict.- 1. If ``LITELLM_LOCAL_MODEL_COST_MAP`` is set, uses the local backup only.+ 1. If ``LITELLM_LOCAL_MODEL_COST_MAP`` is set or this is a ``lite`` /+ ``litellm-proxy`` CLI process, uses the local backup only.2. Otherwise fetches from ``url``, retrying transient HTTP errors(429/5xx/transport) with Retry-After-aware backoff, validatesintegrity, and falls back to the local backup on any failure.@@ -543,7 +553,7 @@ def get_model_cost_map(_cost_map_source_info.loaded_at = datetime.now(timezone.utc)# Note: can't use get_secret_bool here — this runs during litellm.__init__# before litellm._key_management_settings is set.- if os.getenv("LITELLM_LOCAL_MODEL_COST_MAP", "").lower() == "true":+ if os.getenv("LITELLM_LOCAL_MODEL_COST_MAP", "").lower() == "true" or _is_cli_process():_cost_map_source_info.source = "local"_cost_map_source_info.url = None_cost_map_source_info.is_env_forced = Truediff --git a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.pyindex 0495440c51c..d092b387259 100644--- a/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py+++ b/tests/test_litellm/litellm_core_utils/test_get_model_cost_map.py@@ -6,6 +6,7 @@ count actual model entries, not reserved meta keys) and the extraction of theimport jsonimport os+import sysimport pytest@@ -711,3 +712,27 @@ def test_boot_load_that_fails_the_integrity_check_reports_the_backup_not_the_rejassert source["etag"] is Noneassert source["source_revision"] == _bundled_blob_id()assert source["source_revision"] != git_blob_id(shrunk_body)+++ ("argv0", "request_count"),+ [+ ("/some/venv/bin/lite", 0),+ ("/some/venv/bin/lite.exe", 0),+ ("/some/venv/bin/python", 1),+ ],+)+def test_boot_load_skips_remote_fetch_for_cli_processes(monkeypatch, argv0, request_count):+ monkeypatch.setattr(sys, "argv", [argv0, "--version"])+ monkeypatch.delenv("LITELLM_LOCAL_MODEL_COST_MAP", raising=False)+ client, calls = _mock_client([httpx.Response(200, content=_real_map_bytes())], client_cls=httpx.Client)++ cost_map = get_model_cost_map(url=_URL, client=client)++ assert calls["count"] == request_count+ assert cost_map+ source = get_model_cost_map_source_info()+ if request_count == 0:+ assert source["source"] == "local"+ else:+ assert source["source"] == "remote"diff --git a/tests/test_litellm/proxy/client/cli/test_global_options.py b/tests/test_litellm/proxy/client/cli/test_global_options.pyindex 0dd388919a5..02b1cdf4296 100644--- a/tests/test_litellm/proxy/client/cli/test_global_options.py+++ b/tests/test_litellm/proxy/client/cli/test_global_options.py@@ -1,14 +1,16 @@# stdlib importsimport jsonimport os+import shutil+import subprocess+import threading+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import Pathfrom unittest.mock import Mock, patchimport pytestfrom click.testing import CliRunner--import litellm.proxy.client.clifrom litellm._version import version as litellm_versionfrom litellm.proxy.client.cli import cli@@ -35,6 +37,56 @@ def test_cli_version_flag(cli_runner):assert "LiteLLM Proxy Server Version: 1.2.3" in result.output+def test_lite_version_does_not_fetch_model_cost_map():+ lite_path = shutil.which("lite")+ if lite_path is None:+ pytest.skip("lite executable is unavailable")++ requests = []++ class _CostMapHandler(BaseHTTPRequestHandler):+ def do_GET(self):+ requests.append(self.path)+ body = b'{"test-model": {"litellm_provider": "openai", "mode": "chat"}}'+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def log_message(self, format, *args):+ return++ server = ThreadingHTTPServer(("127.0.0.1", 0), _CostMapHandler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ env = {key: value for key, value in os.environ.items() if key != "LITELLM_LOCAL_MODEL_COST_MAP"}+ source_root = str(Path(__file__).resolve().parents[5])+ env["PYTHONPATH"] = os.pathsep.join(filter(None, (source_root, env.get("PYTHONPATH"))))+ env.update(+ {+ "LITELLM_MODEL_COST_MAP_URL": f"http://127.0.0.1:{server.server_port}/map.json",+ "LITELLM_PROXY_URL": "http://127.0.0.1:9",+ }+ )+ result = subprocess.run(+ [lite_path, "--version"],+ capture_output=True,+ text=True,+ timeout=120,+ env=env,+ )+ finally:+ server.shutdown()+ server.server_close()+ thread.join(timeout=10)++ assert result.returncode == 0+ assert "LiteLLM Proxy CLI Version" in result.stdout+ assert requests == []++def test_cli_source_is_ascii_only():"""Non-ASCII output (emoji, box-drawing chars) raises UnicodeEncodeError on legacy Windowsconsoles (cp1252), so the whole CLI package must stay ASCII-only."""