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
perf(cli): start lite without initializing the litellm SDK (#46803)
Mateo Wang355dea26e7b1
diff --git a/litellm/__init__.py b/litellm/__init__.pyindex cdcf9d1d80c..959c9fb406d 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -1,34 +1,13 @@-### Hide pydantic namespace conflict warnings globally ###from __future__ import annotations-import warnings+from litellm._process_defaults import apply_process_defaults as _apply_process_defaults++_apply_process_defaults()-warnings.filterwarnings("ignore", message=".*conflict with protected namespace.*")-# Suppress Pydantic 2.11+ deprecation warning about accessing model_fields on instances-# This warning can accumulate during streaming and cause memory leaks-warnings.filterwarnings("ignore", message=".*Accessing the.*attribute on the instance is deprecated.*")-# ReadOnly on TypedDict fields is repo-wide static discipline (LIT012); pydantic warns it-# cannot enforce it at runtime, which floods proxy boot once such a type is schema-walked-warnings.filterwarnings("ignore", message=".*`ReadOnly` qualifier.*")### INIT VARIABLES #########################import threadingimport os-# Load .env before any other litellm imports so env vars (e.g. LITELLM_UI_SESSION_DURATION) are available-import dotenv as _dotenv---def _dev_env_hot_reload_enabled() -> bool:- """The proxy exports this flag when started with ``--reload``. A reloaded- worker is a fresh process that inherits the reloader's environment, so an- edited ``.env`` value stays masked by the stale inherited one unless we- let the file win; overriding makes the edit take effect on reload."""- return os.getenv("LITELLM_DEV_ENV_HOT_RELOAD") == "True"---if os.getenv("LITELLM_MODE", "DEV") == "DEV":- _dotenv.load_dotenv(override=_dev_env_hot_reload_enabled())-from collections.abc import Mapping, Sequencefrom typing import (Any,diff --git a/litellm/_process_defaults.py b/litellm/_process_defaults.pynew file mode 100644index 00000000000..7501215f108--- /dev/null+++ b/litellm/_process_defaults.py@@ -0,0 +1,24 @@+import os+import warnings++import dotenv+++def _dev_env_hot_reload_enabled() -> bool:+ """The proxy exports this flag when started with ``--reload``. A reloaded+ worker is a fresh process that inherits the reloader's environment, so an+ edited ``.env`` value stays masked by the stale inherited one unless we+ let the file win; overriding makes the edit take effect on reload."""+ return os.getenv("LITELLM_DEV_ENV_HOT_RELOAD") == "True"+++def apply_process_defaults() -> None:+ warnings.filterwarnings("ignore", message=".*conflict with protected namespace.*")+ # Suppress Pydantic 2.11+ deprecation warning about accessing model_fields on instances+ # This warning can accumulate during streaming and cause memory leaks+ warnings.filterwarnings("ignore", message=".*Accessing the.*attribute on the instance is deprecated.*")+ # ReadOnly on TypedDict fields is repo-wide static discipline (LIT012); pydantic warns it+ # cannot enforce it at runtime, which floods proxy boot once such a type is schema-walked+ warnings.filterwarnings("ignore", message=".*`ReadOnly` qualifier.*")+ if os.getenv("LITELLM_MODE", "DEV") == "DEV":+ dotenv.load_dotenv(override=_dev_env_hot_reload_enabled())diff --git a/litellm/constants.py b/litellm/constants.pyindex f448fc351c3..2c63e27b528 100644--- a/litellm/constants.py+++ b/litellm/constants.py@@ -1,4 +1,5 @@import os+import reimport sysfrom enum import Enumfrom types import MappingProxyType@@ -18,6 +19,9 @@ MICROSOFT_365_COPILOT_DEFAULT_TOKEN_EXCHANGE_PROFILE: Final = "jwt_bearer_obo"MICROSOFT_365_COPILOT_DEFAULT_TOKEN_EXCHANGE_SCOPE: Final = "https://graph.microsoft.com/.default"# Replies depend on the caller's delegated identity, which response-cache keys do not include.RESPONSE_CACHE_EXCLUDED_PROVIDERS: Final = frozenset({"microsoft_365_copilot", "databricks_agent"})+CLAUDE_CODE_PICKER_PATTERN: Final = re.compile(r"claude|anthropic", re.IGNORECASE)+GATEWAY_CLIENT_HEADER: Final = "x-gateway-client"+CLAUDE_CODE_CLIENT: Final = "claude-code"MICROSOFT_365_COPILOT_DEFAULT_TIME_ZONE: Final = "UTC"GITHUB_COPILOT_PER_USER_AUTH_TYPE: Final = "per_user_oauth"GITHUB_COPILOT_AUTH_TYPE_KEY: Final = "github_copilot_auth_type"diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.pyindex ab386e10951..ffe2c4433a0 100644--- a/litellm/litellm_core_utils/cli_token_utils.py+++ b/litellm/litellm_core_utils/cli_token_utils.py@@ -44,7 +44,7 @@ from litellm.litellm_core_utils.private_json import (stage_private_json,write_private_json,)-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModel@dataclass(frozen=True, slots=True)diff --git a/litellm/proxy/client/cli/commands/agents.py b/litellm/proxy/client/cli/commands/agents.pyindex 5fa52e5e4f4..03540a7395e 100644--- a/litellm/proxy/client/cli/commands/agents.py+++ b/litellm/proxy/client/cli/commands/agents.py@@ -22,7 +22,7 @@ from litellm.proxy.common_utils.codex_model_catalog import (CodexStockModel,codex_models_response_json,)-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelfrom .auth import cli_context_obj, context_secret_vault, get_stored_api_key, loginfrom .claude_settings import ClaudeSettingsError, install_statusline_scriptdiff --git a/litellm/proxy/client/cli/commands/autoroute/config.py b/litellm/proxy/client/cli/commands/autoroute/config.pyindex 28a57f71d08..eaee886f148 100644--- a/litellm/proxy/client/cli/commands/autoroute/config.py+++ b/litellm/proxy/client/cli/commands/autoroute/config.py@@ -3,7 +3,7 @@ from typing import Final, Literalfrom pydantic import ConfigDict, Field, JsonValue, TypeAdapter-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelTIER_NAMES: Final[tuple[str, ...]] = ("SIMPLE", "MEDIUM", "COMPLEX", "REASONING")AUTOROUTER_MODEL_NAME: Final = "autorouter"diff --git a/litellm/proxy/client/cli/commands/claude_settings.py b/litellm/proxy/client/cli/commands/claude_settings.pyindex cdceb91712b..60492a81cab 100644--- a/litellm/proxy/client/cli/commands/claude_settings.py+++ b/litellm/proxy/client/cli/commands/claude_settings.py@@ -35,7 +35,7 @@ from litellm.litellm_core_utils.private_json import (stage_private_json,write_private_bytes,)-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelfrom . import statusline_scriptfrom .cmd_quoting import quote_for_cmddiff --git a/litellm/proxy/client/cli/commands/codex_settings.py b/litellm/proxy/client/cli/commands/codex_settings.pyindex ca133d3f1e5..557f4379773 100644--- a/litellm/proxy/client/cli/commands/codex_settings.py+++ b/litellm/proxy/client/cli/commands/codex_settings.py@@ -23,7 +23,7 @@ from litellm.litellm_core_utils.private_json import (stage_private_bytes,stage_private_json,)-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelfrom .agents import CODEX_PROXY_PROVIDER, codex_proxy_providerdiff --git a/litellm/proxy/client/cli/commands/configure.py b/litellm/proxy/client/cli/commands/configure.pyindex 45c79ccf014..7903a978a4a 100644--- a/litellm/proxy/client/cli/commands/configure.py+++ b/litellm/proxy/client/cli/commands/configure.py@@ -7,7 +7,7 @@ from typing import Finalimport clickfrom InquirerPy import inquirer-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelfrom .auth import CliContextObjfrom .claude_settings import (diff --git a/litellm/proxy/client/cli/commands/configure_profiles.py b/litellm/proxy/client/cli/commands/configure_profiles.pyindex 3ae651ff6db..dfd855dcb9b 100644--- a/litellm/proxy/client/cli/commands/configure_profiles.py+++ b/litellm/proxy/client/cli/commands/configure_profiles.py@@ -17,7 +17,7 @@ from litellm.litellm_core_utils.private_json import (ensure_private_dir,stage_private_json,)-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelfrom .agents import codex_config_pathfrom .claude_settings import claude_settings_path, configure_state_pathdiff --git a/litellm/proxy/client/cli/commands/configure_setup.py b/litellm/proxy/client/cli/commands/configure_setup.pyindex 7a262650cc2..6004de72e18 100644--- a/litellm/proxy/client/cli/commands/configure_setup.py+++ b/litellm/proxy/client/cli/commands/configure_setup.py@@ -14,12 +14,8 @@ from InquirerPy import inquirerfrom InquirerPy.base.control import Choicefrom pydantic import TypeAdapter, ValidationError-from litellm.proxy.common_utils.model_listing_utils import (- CLAUDE_CODE_CLIENT,- CLAUDE_CODE_PICKER_PATTERN,- GATEWAY_CLIENT_HEADER,-)-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.constants import CLAUDE_CODE_CLIENT, CLAUDE_CODE_PICKER_PATTERN, GATEWAY_CLIENT_HEADER+from litellm.types.llms.base_model import LiteLLMBaseModelfrom .agents import codex_config_pathfrom .claude_settings import (diff --git a/litellm/proxy/client/cli/commands/debug.py b/litellm/proxy/client/cli/commands/debug.pyindex 3db3662b021..8728a9323b7 100644--- a/litellm/proxy/client/cli/commands/debug.py+++ b/litellm/proxy/client/cli/commands/debug.py@@ -20,7 +20,7 @@ import clickimport requestsfrom pydantic import ConfigDict, Field, JsonValue, TypeAdapter, ValidationError, field_validator-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelfrom ...http_client import HTTPClientfrom ._cli_context import cli_context_valuesdiff --git a/litellm/proxy/client/cli/commands/pi.py b/litellm/proxy/client/cli/commands/pi.pyindex 4cb2372e07e..b228617699c 100644--- a/litellm/proxy/client/cli/commands/pi.py+++ b/litellm/proxy/client/cli/commands/pi.py@@ -19,7 +19,7 @@ import requestsfrom pydantic import ConfigDict, JsonValue, TypeAdapter, ValidationError, model_validatorfrom pydantic.types import StringConstraints-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelPI_CONFIG_DIR_ENV: Final = "PI_CODING_AGENT_DIR"PI_PROVIDER_NAME: Final = "litellm"diff --git a/litellm/proxy/client/cli/commands/pkce_login.py b/litellm/proxy/client/cli/commands/pkce_login.pyindex 7cf846bdf9a..c9dd542eb36 100644--- a/litellm/proxy/client/cli/commands/pkce_login.py+++ b/litellm/proxy/client/cli/commands/pkce_login.py@@ -24,7 +24,7 @@ from pydantic import ConfigDict, Field, TypeAdapter, ValidationErrorfrom typing_extensions import ReadOnly, TypedDictfrom litellm.litellm_core_utils.cli_token_utils import CLI_TOKEN_FRESHNESS_BUFFER_SECONDS-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelif TYPE_CHECKING:from .auth import CliTokenDatadiff --git a/litellm/proxy/client/cli/interface.py b/litellm/proxy/client/cli/interface.pyindex f6ecaf1a9be..f7c545ef48e 100644--- a/litellm/proxy/client/cli/interface.py+++ b/litellm/proxy/client/cli/interface.py@@ -8,6 +8,7 @@ from typing import Final, TypeAliasimport clickfrom litellm._logging import verbose_logger+from litellm.proxy.common_utils.banner import show_bannerfrom .commands.auth import cli_context_obj, context_secret_vault@@ -115,8 +116,6 @@ def show_commands():def setup_shell(ctx: click.Context):"""Set up the interactive shell with banner and initial info."""- from litellm.proxy.common_utils.banner import show_banner-show_banner()# Show server connection info@@ -137,8 +136,6 @@ def handle_special_commands(user_input: str) -> bool:return Trueelif user_input.lower() == "clear":click.clear()- from litellm.proxy.common_utils.banner import show_banner-show_banner()show_commands()return Truediff --git a/litellm/proxy/client/cli/main.py b/litellm/proxy/client/cli/main.pyindex 0f4bbc911c6..3f1e7f4259c 100644--- a/litellm/proxy/client/cli/main.py+++ b/litellm/proxy/client/cli/main.py@@ -1,42 +1,20 @@-# stdlib imports--# third party imports+import functools+import importlib+from collections.abc import Callable, Iterator, Mapping, MutableMappingfrom typing import Final, Literal, Protocolimport clickfrom litellm._version import version as litellm_versionfrom litellm.litellm_core_utils.cli_token_utils import load_cli_token-from litellm.proxy.client.health import HealthManagementClient-from .commands.agents import agent_commandsfrom .commands.auth import (- auth_group,cli_context_obj,context_secret_vault,get_stored_api_key,keychain_unreadable_notice,- login,- logout,- whoami,)-from .commands.autoroute.commands import autoroute_group-from .commands.chat import chat-from .commands.config import config_commands, get_config_value, hidden_command_names-from .commands.configure import configure_group, reconfigure_group, unconfigure_group-from .commands.credentials import credentials-from .commands.debug import debug-from .commands.encryption import encryption-from .commands.http import http-from .commands.keys import keys-from .commands.model_groups import model_groups--# local imports-from .commands.models import models-from .commands.teams import teams-from .commands.up import down, up-from .commands.users import users-from .interface import interactive_shell+from .commands.config import get_config_value, hidden_command_namesclass _CliContextObjSlots(Protocol):@@ -62,6 +40,8 @@ def print_version(base_url: str, api_key: str | None):click.echo(f"LiteLLM Proxy CLI Version: {litellm_version}")if base_url:click.echo(f"LiteLLM Proxy Server URL: {base_url}")+ from litellm.proxy.client.health import HealthManagementClient+try:health_client: Final = HealthManagementClient(base_url=base_url, api_key=api_key)server_version: Final = health_client.get_server_version()@@ -87,7 +67,81 @@ class HideConfiguredCommandsGroup(click.Group):return [name for name in super().list_commands(ctx) if name not in hidden][email protected](cls=HideConfiguredCommandsGroup, invoke_without_command=True)+class LazyCommands(MutableMapping[str, click.Command]):+ """Subcommands by name, each imported only when Click looks it up, so `lite <cmd>` loads just that command"""++ def __init__(self, loaders: Mapping[str, Callable[[], click.Command]]) -> None:+ self._loaders = dict(loaders)++ def __getitem__(self, name: str) -> click.Command:+ return self._loaders[name]()++ def __setitem__(self, name: str, command: click.Command) -> None:+ self._loaders[name] = lambda: command++ def __delitem__(self, name: str) -> None:+ del self._loaders[name]++ def __iter__(self) -> Iterator[str]:+ return iter(self._loaders)++ def __len__(self) -> int:+ return len(self._loaders)+++def _command_in(module: str, attribute: str) -> Callable[[], click.Command]:+ @functools.cache+ def load() -> click.Command:+ match getattr(importlib.import_module(module, __package__), attribute):+ case click.Command() as command:+ return command+ case _:+ raise TypeError(f"{module}.{attribute} is not a click command")++ return load+++def _agent_command(name: str) -> Callable[[], click.Command]:+ @functools.cache+ def load() -> click.Command:+ from .commands.agents import agent_commands++ return next(command for command in agent_commands() if command.name == name)++ return load+++AGENT_COMMAND_NAMES: Final = ("claude", "codex", "opencode", "pi")++LITE_COMMANDS: Final = LazyCommands(+ {+ "login": _command_in(".commands.auth", "login"),+ "logout": _command_in(".commands.auth", "logout"),+ "whoami": _command_in(".commands.auth", "whoami"),+ "auth": _command_in(".commands.auth", "auth_group"),+ "models": _command_in(".commands.models", "models"),+ "credentials": _command_in(".commands.credentials", "credentials"),+ "encryption": _command_in(".commands.encryption", "encryption"),+ "chat": _command_in(".commands.chat", "chat"),+ "http": _command_in(".commands.http", "http"),+ "debug": _command_in(".commands.debug", "debug"),+ "keys": _command_in(".commands.keys", "keys"),+ "teams": _command_in(".commands.teams", "teams"),+ "users": _command_in(".commands.users", "users"),+ **{name: _agent_command(name) for name in AGENT_COMMAND_NAMES},+ "up": _command_in(".commands.up", "up"),+ "down": _command_in(".commands.up", "down"),+ "model-groups": _command_in(".commands.model_groups", "model_groups"),+ "autoroute": _command_in(".commands.autoroute.commands", "autoroute_group"),+ "config": _command_in(".commands.config", "config_commands"),+ "configure": _command_in(".commands.configure", "configure_group"),+ "reconfigure": _command_in(".commands.configure", "reconfigure_group"),+ "unconfigure": _command_in(".commands.configure", "unconfigure_group"),+ }+)++[email protected](cls=HideConfiguredCommandsGroup, invoke_without_command=True, commands=LITE_COMMANDS)@click.option("--version","-v",@@ -166,6 +220,8 @@ def cli(ctx: click.Context, show_version: bool, base_url: str | None, api_key: s# If no subcommand was invoked, start interactive modeif ctx.invoked_subcommand is None:+ from .interface import interactive_shell+interactive_shell(ctx, cli)@@ -177,46 +233,6 @@ def version(ctx: click.Context):print_version(ctx_obj.get("base_url"), ctx_obj.get("api_key"))-# Add authentication commands as top-level commands-cli.add_command(login)-cli.add_command(logout)-cli.add_command(whoami)-# Add the auth command group (e.g. `lite auth print-token`, used as Claude Code's apiKeyHelper)-cli.add_command(auth_group, name="auth")-# Add the models command group-cli.add_command(models)-# Add the credentials command group-cli.add_command(credentials)-# Add the encryption migration command group-cli.add_command(encryption)-# Add the chat command group-cli.add_command(chat)-# Add the http command group-cli.add_command(http)-cli.add_command(debug)-# Add the keys command group-cli.add_command(keys)-# Add the teams command group-cli.add_command(teams)-# Add the users command group-cli.add_command(users)-# Add a top-level command per coding agent (claude, codex, opencode, ...)-for agent_command in agent_commands():- cli.add_command(agent_command)-# Add the up/down commands (route Claude Code through the local LiteLLM proxy)-cli.add_command(up)-cli.add_command(down)-# Add the model-groups command group (discover models your key can access)-cli.add_command(model_groups)-# Add the autoroute command group (QA auto-routing against your real proxy)-cli.add_command(autoroute_group, name="autoroute")-cli.add_command(config_commands)-# Add configure/unconfigure (persistently wire a coding agent to the proxy with a virtual key)-cli.add_command(configure_group)-cli.add_command(reconfigure_group)-cli.add_command(unconfigure_group)--LITELLM_PROXY_DEPRECATION_NOTICE: Final = ("The `litellm-proxy` command is deprecated and will be removed in a future release; ""run `lite` instead, it takes the same commands and options."diff --git a/litellm/proxy/common_utils/codex_model_catalog.py b/litellm/proxy/common_utils/codex_model_catalog.pyindex 825b07b3c3c..9b42f99305e 100644--- a/litellm/proxy/common_utils/codex_model_catalog.py+++ b/litellm/proxy/common_utils/codex_model_catalog.py@@ -29,7 +29,7 @@ from typing import TYPE_CHECKING, Annotated, Final, Literalfrom pydantic import ConfigDict, StringConstraints, TypeAdapter, ValidationErrorfrom litellm._logging import verbose_proxy_logger-from litellm.types.llms.base import LiteLLMBaseModel+from litellm.types.llms.base_model import LiteLLMBaseModelif TYPE_CHECKING:from litellm.router import Routerdiff --git a/litellm/proxy/common_utils/model_listing_utils.py b/litellm/proxy/common_utils/model_listing_utils.pyindex 898b296e83e..175432d1dc1 100644--- a/litellm/proxy/common_utils/model_listing_utils.py+++ b/litellm/proxy/common_utils/model_listing_utils.py@@ -10,7 +10,6 @@ legacy internal names with `general_settings.use_team_public_model_name: false`.from __future__ import annotations-import refrom collections.abc import Container, Mapping, Sequencefrom dataclasses import dataclassfrom functools import reduce@@ -21,15 +20,13 @@ from typing import TYPE_CHECKING, Final, castfrom pydantic import TypeAdapter, ValidationErrorimport litellm+from litellm.constants import CLAUDE_CODE_CLIENT, CLAUDE_CODE_PICKER_PATTERN, GATEWAY_CLIENT_HEADERfrom litellm.router_utils.common_utils import resolve_model_group_aliasif TYPE_CHECKING:from litellm.router import Routerfrom litellm.types.proxy.model_listing import ModelInfoResponse-CLAUDE_CODE_PICKER_PATTERN: Final = re.compile(r"claude|anthropic", re.IGNORECASE)-GATEWAY_CLIENT_HEADER: Final = "x-gateway-client"-CLAUDE_CODE_CLIENT: Final = "claude-code"_CLAUDE_CODE_ALIAS_PREFIX: Final = "claude-router-"_ONE_MILLION_SUFFIX: Final = "[1m]"_ONE_MILLION_TOKENS: Final = 1_000_000diff --git a/litellm/types/llms/base.py b/litellm/types/llms/base.pyindex 43b4adc099c..47fec914f9c 100644--- a/litellm/types/llms/base.py+++ b/litellm/types/llms/base.py@@ -1,48 +1,9 @@-import threading-from collections.abc import Mapping-from typing import TYPE_CHECKING, Any, Final+from typing import Any, Finalfrom openai._models import BaseModel as OpenAIObject-from pydantic import BaseModel, ConfigDict--from litellm.constants import DEFER_PYDANTIC_BUILD--_SCHEMA_BUILD_LOCK: Final = threading.RLock()---class LiteLLMBaseModel(BaseModel):- model_config = ConfigDict(defer_build=DEFER_PYDANTIC_BUILD)-- if TYPE_CHECKING:-- def __init__(self, /, **data: object) -> None: ...-- @classmethod- def model_rebuild(- cls,- *,- force: bool = False,- raise_errors: bool = True,- _parent_namespace_depth: int = 2,- _types_namespace: Mapping[str, object] | None = None,- ) -> bool | None:- # Resolve names from the model's own module, never a caller frame: a deferred first-use build- # reads f_locals 5 frames up, and on Python < 3.13 that rewrites the dict the caller's locals() returned- with _SCHEMA_BUILD_LOCK:- return super().model_rebuild(- force=force,- raise_errors=raise_errors,- _parent_namespace_depth=0,- _types_namespace=_types_namespace,- )-- def model_post_init(self, context: object, /) -> None:- # Instances built by a parent's validator or by model_construct skip this class's own- # first-use build, leaving a MockValSer that fails when the instance is serialized as Any- # TODO: drop once pydantic ships a fix for https://github.com/pydantic/pydantic/issues/13647- model = type(self)- if not model.__pydantic_complete__:- model.model_rebuild(raise_errors=False)+from pydantic import ConfigDict++from litellm.types.llms.base_model import LiteLLMBaseModelclass LiteLLMPydanticObjectBase(LiteLLMBaseModel):diff --git a/litellm/types/llms/base_model.py b/litellm/types/llms/base_model.pynew file mode 100644index 00000000000..44088b7a4f1--- /dev/null+++ b/litellm/types/llms/base_model.py@@ -0,0 +1,44 @@+import threading+from collections.abc import Mapping+from typing import TYPE_CHECKING, Final++from pydantic import BaseModel, ConfigDict++from litellm.constants import DEFER_PYDANTIC_BUILD++_SCHEMA_BUILD_LOCK: Final = threading.RLock()+++class LiteLLMBaseModel(BaseModel):+ model_config = ConfigDict(defer_build=DEFER_PYDANTIC_BUILD)++ if TYPE_CHECKING:++ def __init__(self, /, **data: object) -> None: ...++ @classmethod+ def model_rebuild(+ cls,+ *,+ force: bool = False,+ raise_errors: bool = True,+ _parent_namespace_depth: int = 2,+ _types_namespace: Mapping[str, object] | None = None,+ ) -> bool | None:+ # Resolve names from the model's own module, never a caller frame: a deferred first-use build+ # reads f_locals 5 frames up, and on Python < 3.13 that rewrites the dict the caller's locals() returned+ with _SCHEMA_BUILD_LOCK:+ return super().model_rebuild(+ force=force,+ raise_errors=raise_errors,+ _parent_namespace_depth=0,+ _types_namespace=_types_namespace,+ )++ def model_post_init(self, context: object, /) -> None:+ # Instances built by a parent's validator or by model_construct skip this class's own+ # first-use build, leaving a MockValSer that fails when the instance is serialized as Any+ # TODO: drop once pydantic ships a fix for https://github.com/pydantic/pydantic/issues/13647+ model = type(self)+ if not model.__pydantic_complete__:+ model.model_rebuild(raise_errors=False)diff --git a/litellm_cli/__init__.py b/litellm_cli/__init__.pynew file mode 100644index 00000000000..e69de29bb2ddiff --git a/litellm_cli/main.py b/litellm_cli/main.pynew file mode 100644index 00000000000..7b23d0a5bb5--- /dev/null+++ b/litellm_cli/main.py@@ -0,0 +1,183 @@+"""Console entry points for `lite` and `litellm-proxy`.++The CLI is a thin HTTP client, but it lives inside the `litellm` package, so a plain+import would run the whole SDK `__init__` before Click parses argv. These entry points+import the CLI against an uninitialized `litellm` package object instead. CLI code under+`litellm.proxy.client`, and whatever it imports, loads without the SDK whenever it is+first imported. The first attribute read on the SDK, or the first import of any other+new code under `litellm`, initializes the SDK in place before that code runs, so code+that needs the SDK sees it exactly as a plain `import litellm` would leave it. An init that+raises leaves the SDK uninitialized, so the next use runs it again and raises the same error.+"""++import builtins+import contextvars+import importlib+import importlib.util+import sys+import threading+import types+from collections.abc import Callable, Mapping, Sequence+from typing import Final++SDK_PACKAGE: Final = "litellm"+CLI_PACKAGE: Final = "litellm.proxy.client"+_INITIALIZATION_LOCK: Final = threading.RLock()+_BUILTIN_IMPORT: Final = builtins.__import__+_IMPORT_MODULE: Final = importlib.import_module+_LOADING_CLI_CODE: Final = contextvars.ContextVar("_LOADING_CLI_CODE", default=False)+++def _is_dunder(name: str) -> bool:+ return name.startswith("__") and name.endswith("__")+++class _SDKUntilFirstUse(types.ModuleType):+ def __getattribute__(self, name: str) -> object:+ if not _is_dunder(name):+ _initialize(self)+ return types.ModuleType.__getattribute__(self, name)+++class _SDKInitializing(types.ModuleType):+ def __getattr__(self, name: str) -> object:+ with _INITIALIZATION_LOCK:+ if type(self) is _SDKInitializing:+ raise AttributeError(f"partially initialized module {SDK_PACKAGE!r} has no attribute {name!r}")+ return getattr(self, name)+++def _become(sdk: types.ModuleType, state: type[types.ModuleType]) -> None:+ sdk.__class__ = state # rebind-ok: every holder of the litellm module must see its state change in place+++def _restore_interpreter_imports() -> None:+ if builtins.__import__ is _import_initializing_sdk:+ builtins.__import__ = _BUILTIN_IMPORT+ if importlib.import_module is _import_module_initializing_sdk:+ importlib.import_module = _IMPORT_MODULE+++def _initialize(sdk: types.ModuleType) -> None:+ with _INITIALIZATION_LOCK:+ if type(sdk) is not _SDKUntilFirstUse:+ return+ spec: Final = sdk.__spec__+ if spec is None or spec.loader is None:+ raise ModuleNotFoundError(f"No module named {SDK_PACKAGE!r}", name=SDK_PACKAGE)+ _become(sdk, _SDKInitializing)+ try:+ spec.loader.exec_module(sdk)+ except BaseException:+ _become(sdk, _SDKUntilFirstUse)+ raise+ _become(sdk, types.ModuleType)+ _restore_interpreter_imports()+++def _in_package(target: str, package: str) -> bool:+ return target == package or target.startswith(f"{package}.")+++def _needs_more_of(loaded: types.ModuleType, name: str) -> bool:+ if name == "*":+ return type(loaded) is _SDKUntilFirstUse+ return name not in vars(loaded)+++def _loads_new_sdk_code(target: str, fromlist: Sequence[str]) -> bool:+ if not _in_package(target, SDK_PACKAGE):+ return False+ loaded: Final = sys.modules.get(target)+ if loaded is None:+ return True+ return any(_needs_more_of(loaded, name) for name in fromlist)+++def _load_cli_code(load: Callable[[], types.ModuleType]) -> types.ModuleType:+ token: Final = _LOADING_CLI_CODE.set(True)+ try:+ return load()+ finally:+ _LOADING_CLI_CODE.reset(token)+++def _imported(target: str | None, fromlist: Sequence[str], load: Callable[[], types.ModuleType]) -> types.ModuleType:+ if _LOADING_CLI_CODE.get() or target is None or not _loads_new_sdk_code(target, fromlist):+ return load()+ if _in_package(target, CLI_PACKAGE):+ return _load_cli_code(load)+ sdk: Final = sys.modules.get(SDK_PACKAGE)+ if sdk is not None:+ _initialize(sdk)+ return load()+++def _import_target(name: str, importer_globals: Mapping[str, object] | None, level: int) -> str | None:+ if level == 0:+ return name+ package: Final = (importer_globals or {}).get("__package__")+ if not isinstance(package, str) or not package:+ return None+ return importlib.util.resolve_name("." * level + name, package)+++def _import_initializing_sdk(+ name: str,+ globals: Mapping[str, object] | None = None,+ locals: Mapping[str, object] | None = None,+ fromlist: Sequence[str] | None = (),+ level: int = 0,+) -> types.ModuleType:+ return _imported(+ _import_target(name, globals, level),+ fromlist or (),+ lambda: _BUILTIN_IMPORT(name, globals, locals, fromlist or (), level),+ )+++def _import_module_target(name: str, package: str | None) -> str | None:+ if not name.startswith("."):+ return name+ if not package:+ return None+ return importlib.util.resolve_name(name, package)+++def _import_module_initializing_sdk(name: str, package: str | None = None) -> types.ModuleType:+ return _imported(_import_module_target(name, package), (), lambda: _IMPORT_MODULE(name, package))+++def _install_sdk_until_first_use() -> None:+ sdk_spec: Final = importlib.util.find_spec(SDK_PACKAGE)+ if sdk_spec is None:+ raise ModuleNotFoundError(f"No module named {SDK_PACKAGE!r}", name=SDK_PACKAGE)+ sdk: Final = importlib.util.module_from_spec(sdk_spec)+ sdk.__class__ = _SDKUntilFirstUse+ sys.modules[SDK_PACKAGE] = sdk++ from litellm._process_defaults import apply_process_defaults++ apply_process_defaults()+ builtins.__import__ = _import_initializing_sdk+ importlib.import_module = _import_module_initializing_sdk+++def _entry_points() -> tuple[Callable[[], None], Callable[[], None]]:+ if SDK_PACKAGE not in sys.modules:+ _install_sdk_until_first_use()++ from litellm.proxy.client.cli.main import cli as lite+ from litellm.proxy.client.cli.main import litellm_proxy_cli as deprecated_litellm_proxy++ return lite, deprecated_litellm_proxy+++def cli() -> None:+ lite, _ = _entry_points()+ lite()+++def litellm_proxy_cli() -> None:+ _, deprecated_litellm_proxy = _entry_points()+ deprecated_litellm_proxy()diff --git a/pyproject.toml b/pyproject.tomlindex 854811799a0..9262630f63e 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -190,8 +190,8 @@ proxy-runtime = [[project.scripts]litellm = "litellm:run_server"-lite = "litellm.proxy.client.cli:cli"-litellm-proxy = "litellm.proxy.client.cli:litellm_proxy_cli"+lite = "litellm_cli.main:cli"+litellm-proxy = "litellm_cli.main:litellm_proxy_cli"[dependency-groups]dev = [@@ -312,6 +312,7 @@ build-backend = "maturin"manifest-path = "litellm-rust/crates/python-bridge/Cargo.toml"module-name = "litellm.rust_bridge._native"python-source = "."+python-packages = ["litellm_cli"]bindings = "pyo3"features = ["extension-module"]profile = "release"diff --git a/pyrightconfig.json b/pyrightconfig.jsonindex 2264c29be37..3a0812413c3 100644--- a/pyrightconfig.json+++ b/pyrightconfig.json@@ -1,5 +1,5 @@{- "include": ["litellm"],+ "include": ["litellm", "litellm_cli"],"ignore": [],"exclude": ["**/node_modules", "**/__pycache__", "tests/e2e/claude_code", "tests/e2e_harness/claude_code", "tests/e2e/ui", "litellm/types/utils.py", "litellm/proxy/_types.py"],"executionEnvironments": [diff --git a/tests/unit/proxy/client/cli/test_agents.py b/tests/unit/proxy/client/cli/test_agents.pyindex f6f1c2fec3b..7be98521f8e 100644--- a/tests/unit/proxy/client/cli/test_agents.py+++ b/tests/unit/proxy/client/cli/test_agents.py@@ -28,6 +28,7 @@ from litellm.proxy.client.cli.commands.agents import (run_agent,verify_proxy_key,)+from litellm.proxy.client.cli.main import cli as liteAGENTS_MODULE = "litellm.proxy.client.cli.commands.agents"CLAUDE_SETTINGS_MODULE = "litellm.proxy.client.cli.commands.claude_settings"@@ -1490,6 +1491,13 @@ class TestAgentCommands:def test_one_command_per_known_agent(self):assert {c.name for c in agent_commands()} == {"claude", "codex", "opencode", "pi"}+ @pytest.mark.parametrize("agent", [c.name for c in agent_commands()])+ def test_lite_runs_every_known_agent_command(self, agent):+ result = self.runner.invoke(lite, [agent, "--help"], prog_name="lite")++ assert result.exit_code == 0, result.output+ assert result.output.splitlines()[0].startswith(f"Usage: lite {agent} ")+def test_pi_is_hidden_from_help_but_still_registered(self):hidden_by_name = {c.name: c.hidden for c in agent_commands()}assert hidden_by_name == {"claude": False, "codex": False, "opencode": False, "pi": True}diff --git a/tests/unit/proxy/client/cli/test_claude_settings.py b/tests/unit/proxy/client/cli/test_claude_settings.pyindex 9353c149d15..9451598aa40 100644--- a/tests/unit/proxy/client/cli/test_claude_settings.py+++ b/tests/unit/proxy/client/cli/test_claude_settings.py@@ -15,6 +15,7 @@ import pytestfrom click.testing import CliRunnerfrom litellm.litellm_core_utils.private_json import commit_staged_json, write_private_bytes+from litellm.proxy.client.cli.commands.autoroute.process import AUTOROUTE_DIRfrom litellm.proxy.client.cli.commands.claude_settings import (ANTHROPIC_DEFAULT_MODEL_ENV_KEYS,AUTOROUTE_BACKUP_PATH,@@ -196,8 +197,6 @@ class TestConflictingOwnersOfTheSettingsFile:def test_the_registry_matches_the_paths_the_commands_actually_use(self):"""A second definition of the autoroute dir must not drift from this one."""- from litellm.proxy.client.cli.commands.autoroute.process import AUTOROUTE_DIR-assert AUTOROUTE_BACKUP_PATH == AUTOROUTE_DIR / "claude_settings_backup.json"assert {o.backup_path for o in SETTINGS_FILE_OWNERS} == {BACKUP_PATH, AUTOROUTE_BACKUP_PATH}assert {o.stop_command for o in SETTINGS_FILE_OWNERS} == {"lite down", "lite autoroute stop"}diff --git a/tests/unit/proxy/client/cli/test_credentials_commands.py b/tests/unit/proxy/client/cli/test_credentials_commands.pyindex fe9bc333f37..cdbd73057a0 100644--- a/tests/unit/proxy/client/cli/test_credentials_commands.py+++ b/tests/unit/proxy/client/cli/test_credentials_commands.py@@ -14,10 +14,6 @@ from litellm.proxy.client.cli.main import clidef mock_credentials_client(monkeypatch):"""Patch the CredentialsManagementClient used by the CLI commands."""mock_client = MagicMock()- monkeypatch.setattr(- "litellm.proxy.client.credentials.CredentialsManagementClient",- mock_client,- )monkeypatch.setattr("litellm.proxy.client.cli.commands.credentials.CredentialsManagementClient",mock_client,diff --git a/tests/unit/proxy/client/cli/test_global_options.py b/tests/unit/proxy/client/cli/test_global_options.pyindex 3b9f6820b69..8a1e9a3d141 100644--- a/tests/unit/proxy/client/cli/test_global_options.py+++ b/tests/unit/proxy/client/cli/test_global_options.py@@ -473,3 +473,13 @@ def test_version_command_without_a_context_object_fails_reading_it(cli_runner):assert result.exit_code == 1assert type(result.exception) is AttributeErrorassert result.output == ""+++def test_every_listed_command_runs_the_command_of_that_name():+ from litellm.proxy.client.cli.commands.agents import agent_commands++ commands: Final = {name: cli.commands[name] for name in cli.commands}++ assert {name: command.name for name, command in commands.items()} == {name: name for name in commands}+ assert {command.name for command in agent_commands()} <= commands.keys()+ assert all(cli.commands[name] is command for name, command in commands.items())diff --git a/tests/unit/proxy/test_proxy_cli.py b/tests/unit/proxy/test_proxy_cli.pyindex 9566b6e30a2..ff45610ac72 100644--- a/tests/unit/proxy/test_proxy_cli.py+++ b/tests/unit/proxy/test_proxy_cli.py@@ -369,16 +369,16 @@ class TestProxyInitializationHelpers:assert config_file.resolve() in yielded_pathsdef test_dev_env_hot_reload_enabled_reads_flag(self, monkeypatch):- import litellm+ from litellm._process_defaults import _dev_env_hot_reload_enabledmonkeypatch.setenv("LITELLM_DEV_ENV_HOT_RELOAD", "True")- assert litellm._dev_env_hot_reload_enabled() is True+ assert _dev_env_hot_reload_enabled() is Truemonkeypatch.setenv("LITELLM_DEV_ENV_HOT_RELOAD", "false")- assert litellm._dev_env_hot_reload_enabled() is False+ assert _dev_env_hot_reload_enabled() is Falsemonkeypatch.delenv("LITELLM_DEV_ENV_HOT_RELOAD", raising=False)- assert litellm._dev_env_hot_reload_enabled() is False+ assert _dev_env_hot_reload_enabled() is False@patch("asyncio.run")@patch("builtins.print")diff --git a/tests/unit/test_litellm_cli.py b/tests/unit/test_litellm_cli.pynew file mode 100644index 00000000000..5d1e510742a--- /dev/null+++ b/tests/unit/test_litellm_cli.py@@ -0,0 +1,344 @@+import json+import os+import subprocess+import sys+from collections.abc import Mapping+from pathlib import Path+from typing import Final++import pytest++import litellm+from litellm_cli.main import cli++_HELP_ARGV: Final = (+ ("--help",),+ ("logout", "--help"),+ ("login", "--help"),+ ("models", "list", "--help"),+ ("claude", "--help"),+ ("opencode", "--help"),+ ("codex", "--help"),+ ("pi", "--help"),+ ("keys", "list", "--help"),+)++_COMMAND_ARGV: Final = (("logout",), ("whoami",))++_RUN_EACH_ARGV: Final = """+import contextlib, io, json, sys+from {module} import cli+runs = {{}}+for argv in json.loads(sys.argv[1]):+ sys.argv = ["lite", *argv]+ output = io.StringIO()+ with contextlib.redirect_stdout(output):+ try:+ cli()+ except SystemExit as stopped:+ code = stopped.code+ else:+ code = 0+ runs[" ".join(argv)] = {{"exit": code, "output": output.getvalue()}}+print(json.dumps({{"runs": runs, "sdk_initialized": "completion" in vars(sys.modules["litellm"])}}))+"""++_USE_SDK_AFTER_HELP: Final = """+import builtins, importlib, json, sys+interpreter_imports = (builtins.__import__, importlib.import_module)+from {module} import cli+sys.argv = ["lite", "--help"]+try:+ cli()+except SystemExit:+ pass+before = "completion" in vars(sys.modules["litellm"])+{first_use}+from litellm.router import Router+import litellm+import litellm.responses.main+from litellm import acompletion+print(json.dumps({{+ "before": before,+ "router": Router.__name__,+ "completion": callable(litellm.completion),+ "acompletion": acompletion is litellm.acompletion,+ "responses_is_function": callable(litellm.responses) and not isinstance(litellm.responses, type(litellm)),+ "namespace": sorted(vars(litellm)),+ "module_type": type(litellm).__name__,+ "imports_restored": (builtins.__import__, importlib.import_module) == interpreter_imports,+}}))+"""++_FIRST_USE_FROM_THREADS: Final = """+import json, sys, threading+from litellm_cli.main import cli+sys.argv = ["lite", "--help"]+try:+ cli()+except SystemExit:+ pass+import litellm+start = threading.Barrier(4)+seen = []+def use_sdk():+ start.wait()+ try:+ seen.append(callable(litellm.completion))+ except AttributeError as error:+ seen.append(str(error))+threads = [threading.Thread(target=use_sdk) for _ in range(4)]+for thread in threads:+ thread.start()+for thread in threads:+ thread.join()+print(json.dumps({"seen": seen}))+"""++_STAR_IMPORT_AFTER_HELP: Final = """+import json, sys+from litellm_cli.main import cli+sys.argv = ["lite", "--help"]+try:+ cli()+except SystemExit:+ pass+before = "completion" in vars(sys.modules["litellm"])+from litellm import *+print(json.dumps({"before": before, "completion": callable(globals().get("completion")), "acompletion": callable(globals().get("acompletion"))}))+"""++_SDK_WHOSE_SUBMODULE_READS_IT_WHILE_LOADING: Final = {+ "sdk_sync.py": """+import threading+initializing = threading.Event()+submodule_loading = threading.Event()+""",+ "litellm/__init__.py": """+import sdk_sync+sdk_sync.initializing.set()+sdk_sync.submodule_loading.wait(2)+from litellm import submodule+ready = True+""",+ "litellm/submodule.py": """+import litellm+import sdk_sync+sdk_sync.submodule_loading.set()+ready_when_loaded = getattr(litellm, "ready", False)+""",+ "litellm/_process_defaults.py": "def apply_process_defaults() -> None: ...\n",+ "litellm/proxy/__init__.py": "",+ "litellm/proxy/client/__init__.py": "",+ "litellm/proxy/client/cli/__init__.py": "",+ "litellm/proxy/client/cli/main.py": """+import json, threading+import litellm+import sdk_sync++def cli():+ def initialize_sdk():+ litellm.ready++ def import_submodule_once_initialization_starts():+ sdk_sync.initializing.wait()+ import litellm.submodule++ threads = [threading.Thread(target=initialize_sdk, daemon=True),+ threading.Thread(target=import_submodule_once_initialization_starts, daemon=True)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(10)+ print(json.dumps({"finished": [not thread.is_alive() for thread in threads]}))++litellm_proxy_cli = cli+""",+}++_SDK_WHOSE_INIT_FAILS: Final = {+ "litellm/__init__.py": 'raise ImportError("a dependency of the SDK is broken")\n',+ "litellm/utils.py": "",+ "litellm/_process_defaults.py": "def apply_process_defaults() -> None: ...\n",+ "litellm/proxy/__init__.py": "",+ "litellm/proxy/client/__init__.py": "",+ "litellm/proxy/client/cli/__init__.py": "",+ "litellm/proxy/client/cli/main.py": """+import json+import litellm++def error_from(use):+ try:+ use()+ except Exception as error:+ return f"{type(error).__name__}: {error}"+ return None++def import_sdk_code():+ import litellm.utils++def cli():+ print(json.dumps([error_from(lambda: litellm.completion), error_from(lambda: litellm.completion), error_from(import_sdk_code)]))++litellm_proxy_cli = cli+""",+}++_RUN_LITE_AGAINST_SDK_AT: Final = """+import sys+sys.path.insert(0, sys.argv[1])+from litellm_cli.main import cli+cli()+"""++_COMMAND_MODULES_LOADED_BY: Final = """+import json, sys+from litellm_cli.main import cli+sys.argv = ["lite", *sys.argv[1:]]+try:+ cli()+except SystemExit:+ pass+prefix = "litellm.proxy.client.cli.commands."+print(json.dumps({"modules": sorted(name[len(prefix):] for name in sys.modules if name.startswith(prefix))}))+"""+++def _run(source: str, argv: tuple[str, ...], home: Path) -> dict[str, object]:+ result: Final = subprocess.run(+ [sys.executable, "-I", "-c", source, *argv],+ capture_output=True,+ text=True,+ timeout=120,+ env={**os.environ, "HOME": str(home), "LITELLM_LOCAL_MODEL_COST_MAP": "True"},+ )+ assert result.returncode == 0, result.stderr+ return json.loads(result.stdout.rstrip("\n").rpartition("\n")[2])++[email protected](scope="module")+def cli_runs(tmp_path_factory: pytest.TempPathFactory) -> Mapping[str, dict[str, object]]:+ argv: Final = (json.dumps(_HELP_ARGV + _COMMAND_ARGV),)+ return {+ "thin": _run(_RUN_EACH_ARGV.format(module="litellm_cli.main"), argv, tmp_path_factory.mktemp("thin")),+ "full": _run(+ _RUN_EACH_ARGV.format(module="litellm.proxy.client.cli.main"), argv, tmp_path_factory.mktemp("full")+ ),+ }+++def test_lite_runs_commands_without_initializing_the_sdk(cli_runs: Mapping[str, dict[str, object]]):+ assert cli_runs["thin"]["sdk_initialized"] is False+ assert cli_runs["full"]["sdk_initialized"] is True++[email protected]("argv", _HELP_ARGV + _COMMAND_ARGV, ids=" ".join)+def test_lite_prints_what_the_full_sdk_cli_prints(argv: tuple[str, ...], cli_runs: Mapping[str, dict[str, object]]):+ thin: Final = cli_runs["thin"]["runs"]+ full: Final = cli_runs["full"]["runs"]+ assert isinstance(thin, dict) and isinstance(full, dict)++ assert thin[" ".join(argv)] == full[" ".join(argv)]+ assert thin[" ".join(argv)]["output"]+++ ("argv", "loaded", "not_loaded"),+ [+ (("logout", "--help"), {"auth"}, {"agents", "autoroute.commands", "models", "keys"}),+ (("models", "list", "--help"), {"models"}, {"agents", "autoroute.commands", "keys"}),+ (("claude", "--help"), {"agents"}, {"autoroute.commands", "models", "keys"}),+ ],+)+def test_lite_imports_only_the_command_it_runs(+ argv: tuple[str, ...], loaded: set[str], not_loaded: set[str], tmp_path: Path+):+ modules: Final = _run(_COMMAND_MODULES_LOADED_BY, argv, tmp_path)["modules"]+ assert isinstance(modules, list)++ assert loaded <= set(modules)+ assert not not_loaded & set(modules)++[email protected](scope="module")+def sdk_used_after_full_cli(tmp_path_factory: pytest.TempPathFactory) -> dict[str, object]:+ return _run(+ _USE_SDK_AFTER_HELP.format(module="litellm.proxy.client.cli.main", first_use="pass"),+ (),+ tmp_path_factory.mktemp("full"),+ )+++ "first_use",+ [+ "import litellm; litellm.completion",+ "import litellm; litellm.types.utils.ModelResponse",+ "from litellm import acompletion",+ "from litellm.router import Router",+ "from litellm.types import utils",+ "import litellm.responses.main",+ 'importlib.import_module("litellm.router")',+ 'importlib.import_module(".utils", "litellm")',+ 'exec("from .types import utils", {"__name__": "litellm.lazy_import", "__package__": "litellm"})',+ ],+)+def test_sdk_initializes_in_place_on_first_use_after_lite_imports(+ first_use: str, sdk_used_after_full_cli: dict[str, object], tmp_path: Path+):+ thin: Final = _run(_USE_SDK_AFTER_HELP.format(module="litellm_cli.main", first_use=first_use), (), tmp_path)++ assert thin["before"] is False+ assert sdk_used_after_full_cli["before"] is True+ assert {**thin, "before": True} == sdk_used_after_full_cli+ assert (thin["router"], thin["completion"], thin["acompletion"], thin["responses_is_function"]) == (+ "Router",+ True,+ True,+ True,+ )+++def test_star_import_after_lite_imports_gets_the_whole_sdk(tmp_path: Path):+ assert _run(_STAR_IMPORT_AFTER_HELP, (), tmp_path) == {"before": False, "completion": True, "acompletion": True}+++def test_threads_that_use_the_sdk_at_once_all_wait_for_one_initialization(tmp_path: Path):+ used: Final = _run(_FIRST_USE_FROM_THREADS, (), tmp_path)++ assert used == {"seen": [True, True, True, True]}+++def _write_sdk(root: Path, files: Mapping[str, str]) -> Path:+ for relative_path, source in files.items():+ (root / relative_path).parent.mkdir(parents=True, exist_ok=True)+ (root / relative_path).write_text(source)+ return root+++def test_importing_sdk_code_while_another_thread_initializes_the_sdk_does_not_hang(tmp_path: Path):+ sdk_root: Final = _write_sdk(tmp_path / "sdk", _SDK_WHOSE_SUBMODULE_READS_IT_WHILE_LOADING)++ assert _run(_RUN_LITE_AGAINST_SDK_AT, (str(sdk_root),), tmp_path) == {"finished": [True, True]}+++def test_every_use_after_a_failed_sdk_init_raises_the_init_error(tmp_path: Path):+ sdk_root: Final = _write_sdk(tmp_path / "sdk", _SDK_WHOSE_INIT_FAILS)++ assert _run(_RUN_LITE_AGAINST_SDK_AT, (str(sdk_root),), tmp_path) == ["ImportError: a dependency of the SDK is broken"] * 3+++def test_lite_keeps_an_sdk_that_was_already_imported(+ monkeypatch: pytest.MonkeyPatch, capsys: pytest.CaptureFixture[str]+):+ monkeypatch.setitem(sys.modules, "litellm", litellm)+ monkeypatch.setattr(litellm, "success_callback", ["kept"])+ monkeypatch.setattr(sys, "argv", ["lite", "--help"])++ with pytest.raises(SystemExit) as exited:+ cli()++ assert exited.value.code == 0+ assert "LiteLLM Proxy CLI - Manage your LiteLLM proxy server" in capsys.readouterr().out+ assert sys.modules["litellm"] is litellm+ assert litellm.success_callback == ["kept"]