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
test: move packaging and install checks off CircleCI build_and_test (#45757)
devin-ai-integration[bot]16fcbffa7fd3
diff --git a/.circleci/config.yml b/.circleci/config.ymlindex 1e56aac89aa..786a0720991 100644--- a/.circleci/config.yml+++ b/.circleci/config.yml@@ -379,50 +379,6 @@ commands:- save_cargo_targetjobs:- # Add Windows testing job- using_litellm_on_windows:- executor:- name: win/default- shell: powershell.exe- working_directory: ~/project- environment:- UV_PYTHON: "3.11"- CARGO_HTTP_MULTIPLEXING: "false"- CARGO_NET_RETRY: "5"- steps:- - checkout- - run:- name: Install Python- command: |- choco install python --version=3.11.0 -y --no-progress --force- refreshenv- python --version- environment:- CHOCOLATEY_CONFIRM_ALL: "true"- - install_windows_toolchain- - run:- name: Install Dependencies- no_output_timeout: 30m- environment:- UV_HTTP_TIMEOUT: "300"- command: |- $env:Path = "$HOME\.cargo\bin;$HOME\.local\bin;$env:Path"- for ($attempt = 1; $attempt -le 5; $attempt++) {- Write-Host "uv sync attempt $attempt/5"- uv sync --frozen --group dev --python 3.11- if ($LASTEXITCODE -eq 0) {- break- }- if ($attempt -eq 5) {- exit $LASTEXITCODE- }- Start-Sleep -Seconds 15- }- - run:- name: Run Windows-specific test- command: |- uv run --no-sync python -m pytest --tb=short tests/windows_tests/ -v-windows_release_wheel:executor:name: win/default@@ -1384,89 +1340,6 @@ jobs:paths:- audio_coverage.xml- audio_coverage- installing_litellm_on_python:- docker:- - *python312_image- - *postgres16_sidecar- working_directory: ~/project- environment: *sidecar_database_url-- steps:- - checkout- - skip_if_unrelated_changes- - setup_google_dns- - install_uv- - install_rust- - run:- name: Install Dependencies- command: |- uv sync --frozen --all-groups --all-extras --python 3.12- - setup_litellm_enterprise_pip- - wait_for_service:- url: tcp://localhost:5432- timeout: "60"- - run:- name: Run tests- command: |- uv run --no-sync python -m pytest --tb=short -vv tests/local_testing/test_basic_python_version.py -k "not legacy_resolver"-- installing_litellm_on_python_3_13:- docker:- - image: cimg/python:3.13.1@sha256:87b243ae80d154db75ce5e58af16c72c5dd4b1e23e5c7264a816e85e0c440c13- auth:- username: ${DOCKERHUB_USERNAME}- password: ${DOCKERHUB_PASSWORD}- - *postgres16_sidecar- working_directory: ~/project- environment: *sidecar_database_url- resource_class: medium-- steps:- - checkout- - skip_if_unrelated_changes- - setup_google_dns- - install_uv- - install_rust- - run:- name: Install Dependencies- command: |- uv sync --frozen --all-groups --all-extras --python 3.13- - wait_for_service:- url: tcp://localhost:5432- timeout: "60"- - run:- name: Run tests- command: |- uv run --no-sync python -m pytest --tb=short -v tests/local_testing/test_basic_python_version.py -k "not legacy_resolver"-- installing_litellm_on_python_v2_migration_resolver:- docker:- - *python312_image- - *postgres16_sidecar- working_directory: ~/project- environment: *sidecar_database_url-- steps:- - checkout- - skip_if_unrelated_changes- - setup_google_dns- - install_uv- - install_rust- - run:- name: Install Dependencies- command: |- uv sync --frozen --all-groups --all-extras --python 3.12- - setup_litellm_enterprise_pip- - wait_for_service:- url: tcp://localhost:5432- timeout: "60"- - run:- name: Run both migration resolvers against Postgres- command: |- uv run --no-sync python -m pytest --tb=short -vv \- tests/local_testing/test_basic_python_version.py::test_litellm_proxy_server_config_no_general_settings \- tests/local_testing/test_basic_python_version.py::test_litellm_proxy_server_config_no_general_settings_legacy_resolver-helm_chart_testing:machine:image: ubuntu-2204:2024.04.1 # Use machine executor instead of docker@@ -2159,95 +2032,6 @@ jobs:- store_test_results:path: test-results- proxy_build_from_pip_tests:- # Change from docker to machine executor- machine:- image: ubuntu-2204:2024.04.1- resource_class: large- working_directory: ~/project- steps:- - checkout- - run:- name: Generate LiteLLM master key- command: |- key="$(openssl rand -hex 16)"- printf 'export LITELLM_MASTER_KEY=sk-%s\n' "$key" >> "$BASH_ENV"- - skip_if_unrelated_changes- - setup_google_dns- # Remove Docker CLI installation since it's already available in machine executor- - install_uv- - install_rust- - run:- name: Install Dependencies- command: |- uv sync --frozen --all-groups --all-extras --python 3.12- - run:- name: Build Docker image- command: |- docker build -t my-app:latest -f docker/build_from_pip/Dockerfile.build_from_pip .- - start_postgres- - start_fake_openai_endpoint- - run:- name: Run Docker container- # intentionally give bad redis credentials here- # the OTEL test - should get this as a trace- command: |- docker run -d \- -p 4000:4000 \- -e DATABASE_URL=postgresql://postgres:[email protected]:5432/circle_test \- -e REDIS_HOST=$REDIS_HOST \- -e REDIS_PASSWORD=$REDIS_PASSWORD \- -e REDIS_PORT=$REDIS_PORT \- -e LITELLM_MASTER_KEY="$LITELLM_MASTER_KEY" \- -e OPENAI_API_KEY=$OPENAI_API_KEY \- -e FAKE_OPENAI_API_BASE=http://host.docker.internal:8190 \- -e LITELLM_LICENSE=$LITELLM_LICENSE \- -e OTEL_EXPORTER="in_memory" \- -e AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID \- -e AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY \- -e AWS_REGION_NAME=$AWS_REGION_NAME \- -e COHERE_API_KEY=$COHERE_API_KEY \- -e USE_DDTRACE=True \- -e DD_API_KEY=$DD_API_KEY \- -e DD_SITE=$DD_SITE \- -e GCS_FLUSH_INTERVAL="1" \- -e LITELLM_LOG=ERROR \- --add-host host.docker.internal:host-gateway \- --name my-app \- -v $(pwd)/docker/build_from_pip/litellm_config.yaml:/app/config.yaml \- my-app:latest \- --config /app/config.yaml \- --port 4000- - run:- name: Start outputting logs- command: docker logs -f my-app- background: true- - wait_for_service:- url: http://localhost:4000- timeout: "300"- - run:- name: Run tests- command: |- mkdir -p test-results- TEST_FILES=$(circleci tests glob "tests/basic_proxy_startup_tests/**/test_*.py")- echo "$TEST_FILES" | circleci tests run \- --verbose \- --command="tr ' ' '\\n' | awk '/\\.py/ {print; next} {sub(/\\.[A-Z][^.]*$/, \"\"); gsub(/\\./, \"/\"); print \$0 \".py\"}' | xargs uv run --no-sync python -m pytest --tb=short \- -vv \- --junitxml=test-results/junit-2.xml \- --durations=5"- no_output_timeout: 15m- # Clean up first container- - store_test_results:- path: test-results- - run:- name: Stop and remove first container- command: |- docker stop my-app || true- docker rm my-app || true- docker stop postgres-db || true- docker rm postgres-db || true- when: alwaysproxy_pass_through_endpoint_tests:machine:image: ubuntu-2204:2024.04.1@@ -3371,6 +3155,8 @@ workflows:- "6.4.0"- "7.4.1"- "8.0.1"+ - windows_release_wheel+ - base_sdk_installbuild_and_test:unless:or:@@ -3378,10 +3164,7 @@ workflows:- not:equal: ["", << pipeline.parameters.routing_parity_base >>]jobs:- - using_litellm_on_windows- - windows_release_wheel- provider_replay_harness- - base_sdk_install- local_testing_part1- local_testing_part2- langfuse_logging_unit_tests@@ -3405,7 +3188,6 @@ workflows:- proxy_store_model_in_db_tests:requires:- build_docker_database_image- - proxy_build_from_pip_tests- proxy_pass_through_endpoint_tests:requires:- build_docker_database_image@@ -3442,9 +3224,6 @@ workflows:- db_migration_disable_update_check:requires:- build_docker_database_image- - installing_litellm_on_python- - installing_litellm_on_python_3_13- - installing_litellm_on_python_v2_migration_resolver- helm_chart_testing:requires:- build_docker_database_imagediff --git a/.github/workflows/test-merge-smoke.yml b/.github/workflows/test-merge-smoke.ymlindex 2472f2831b6..0133629d24a 100644--- a/.github/workflows/test-merge-smoke.yml+++ b/.github/workflows/test-merge-smoke.yml@@ -91,9 +91,158 @@ jobs:if: always()run: sudo ip netns delete smoke+ all-extras:+ name: all-extras-py${{ matrix.python-version }}+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ strategy:+ fail-fast: false+ matrix:+ python-version: ["3.12", "3.13"]+ env:+ LITELLM_LOCAL_MODEL_COST_MAP: "True"+ steps:+ - name: Checkout+ uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0+ with:+ persist-credentials: false++ - name: Set up Python+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0+ with:+ python-version: ${{ matrix.python-version }}++ - name: Set up uv+ uses: ./.github/actions/setup-uv-with-retries+ with:+ version: "0.10.9"++ - name: Install every extra and dependency group+ run: .github/scripts/uv_sync_with_retries.sh --frozen --all-groups --all-extras --python ${{ matrix.python-version }}++ - name: Import the SDK, the proxy server and the enterprise package+ run: .venv/bin/python -c "import litellm, litellm.proxy.proxy_server, litellm_enterprise"++ windows-sdk:+ name: windows-sdk+ runs-on: windows-2025+ timeout-minutes: 10+ env:+ LITELLM_LOCAL_MODEL_COST_MAP: "True"+ defaults:+ run:+ shell: bash+ steps:+ - name: Checkout+ uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0+ with:+ persist-credentials: false++ - name: Set up Python+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0+ with:+ python-version: "3.11"++ - name: Set up uv+ uses: ./.github/actions/setup-uv-with-retries+ with:+ version: "0.10.9"++ - name: Install dependencies+ run: .github/scripts/uv_sync_with_retries.sh --frozen --no-install-workspace --group dev --python 3.11++ - name: Run the Windows tests+ run: uv run --no-sync python -m pytest --tb=short -v tests/windows_tests++ proxy-build-from-pip:+ name: proxy-build-from-pip+ runs-on: ubuntu-24.04+ timeout-minutes: 10+ services:+ postgres:+ image: postgres:14@sha256:6a70deda415ec296f977890e11aba04a0db9f632a362e3fce45e845e3db74f26+ env:+ POSTGRES_USER: postgres+ POSTGRES_PASSWORD: postgres+ POSTGRES_DB: circle_test+ ports:+ - 5432:5432+ options: >-+ --health-cmd "pg_isready -U postgres"+ --health-interval 2s+ --health-timeout 5s+ --health-retries 30+ steps:+ - name: Checkout+ uses: actions/checkout@08eba0b27e820071cde6df949e0beb9ba4906955 # v4.3.0+ with:+ persist-credentials: false++ - name: Set up Python+ uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5.6.0+ with:+ python-version: "3.12"++ - name: Set up uv+ uses: ./.github/actions/setup-uv-with-retries+ with:+ version: "0.10.9"++ - name: Install the test client dependencies+ run: .github/scripts/uv_sync_with_retries.sh --frozen --no-install-workspace --extra proxy --group dev --python 3.12++ - name: Build the image from the published package+ run: docker build -t litellm-build-from-pip:smoke -f docker/build_from_pip/Dockerfile.build_from_pip .++ - name: Start the fake OpenAI endpoint+ run: |+ nohup .venv/bin/python tests/_fake_openai_endpoint_server.py --host 0.0.0.0 --port 8190 > "${RUNNER_TEMP}/fake-openai.log" 2>&1 &+ for _ in $(seq 1 30); do+ curl -sf http://localhost:8190/health > /dev/null && exit 0+ sleep 1+ done+ cat "${RUNNER_TEMP}/fake-openai.log"+ exit 1++ - name: Generate a master key+ run: |+ key="sk-$(openssl rand -hex 16)"+ echo "::add-mask::${key}"+ echo "LITELLM_MASTER_KEY=${key}" >> "${GITHUB_ENV}"++ - name: Start the proxy container+ run: |+ docker run -d \+ -p 4000:4000 \+ -e DATABASE_URL=postgresql://postgres:[email protected]:5432/circle_test \+ -e LITELLM_MASTER_KEY \+ -e FAKE_OPENAI_API_BASE=http://host.docker.internal:8190 \+ -e OTEL_EXPORTER=in_memory \+ -e USE_DDTRACE=True \+ -e GCS_FLUSH_INTERVAL=1 \+ -e LITELLM_LOG=ERROR \+ --add-host host.docker.internal:host-gateway \+ --name litellm-build-from-pip \+ -v "${GITHUB_WORKSPACE}/docker/build_from_pip/litellm_config.yaml:/app/config.yaml" \+ litellm-build-from-pip:smoke \+ --config /app/config.yaml \+ --port 4000+ for _ in $(seq 1 150); do+ curl -sf --max-time 5 -o /dev/null http://localhost:4000 && exit 0+ sleep 2+ done+ exit 1++ - name: Run the startup tests+ run: .venv/bin/python -m pytest --tb=short -vv tests/basic_proxy_startup_tests++ - name: Show the proxy logs+ if: always()+ run: docker logs litellm-build-from-pip || true+smoke-passed:name: smoke passed- needs: [dashboard-build, core-checks]+ needs: [dashboard-build, core-checks, all-extras, windows-sdk, proxy-build-from-pip]if: always()runs-on: ubuntu-latesttimeout-minutes: 2diff --git a/tests/base_sdk_tests/test_core_distribution.py b/tests/base_sdk_tests/test_core_distribution.pyindex e16226e1df8..ba68d08e4d1 100644--- a/tests/base_sdk_tests/test_core_distribution.py+++ b/tests/base_sdk_tests/test_core_distribution.py@@ -53,28 +53,6 @@ def source_repository(tmp_path: Path) -> Path:return source-def test_core_manifest_preserves_runtime_dependencies_without_extras() -> None:- manifest: Final = ROOT / "packaging/litellm-core/pyproject.toml"- assert manifest.is_file(), "The core distribution needs its own build manifest"- core: Final = tomllib.loads(manifest.read_text())- legacy: Final = tomllib.loads((ROOT / "pyproject.toml").read_text())- assert core["project"]["name"] == "litellm-core"- removed: Final = {"boto3", "tokenizers", "huggingface-hub"}- core_dependencies: Final = {Requirement(value).name for value in core["project"]["dependencies"]}- legacy_dependencies: Final = {Requirement(value).name for value in legacy["project"]["dependencies"]}- assert not core_dependencies & removed- assert removed <= legacy_dependencies- assert "jsonschema" in core_dependencies- assert legacy_dependencies - removed <= core_dependencies- core_requirements: Final = {Requirement(value) for value in core["project"]["dependencies"]}- retained_requirements: Final = {- Requirement(value) for value in legacy["project"]["dependencies"] if Requirement(value).name not in removed- }- assert retained_requirements <= core_requirements- assert not core["project"].get("optional-dependencies")- assert not core["project"].get("scripts")--def test_staging_stamps_release_version_without_modifying_sources(tmp_path: Path, source_repository: Path) -> None:from scripts.build_core_distribution import SOURCES, stage_core_distributiondiff --git a/tests/integration/database/test_proxy_boot_without_general_settings.py b/tests/integration/database/test_proxy_boot_without_general_settings.pynew file mode 100644index 00000000000..73254f3862f--- /dev/null+++ b/tests/integration/database/test_proxy_boot_without_general_settings.py@@ -0,0 +1,117 @@+import uuid+from pathlib import Path+from typing import Final++import httpx+import pytest+from pydantic import JsonValue+from integration._support.client import JSON_OBJECT, Gateway, list_value, object_value, string_value+from integration._support.database import read_rows, scratch_database+from integration._support.process import DB_PUSH, LEGACY_MIGRATE_DEPLOY, MIGRATE_DEPLOY, owned_proxy_process++pytestmark: Final = pytest.mark.timeout(300)++REPO_ROOT: Final = Path(__file__).resolve().parents[3]+MIGRATIONS_DIR: Final = REPO_ROOT / "litellm-proxy-extras" / "litellm_proxy_extras" / "migrations"+SHIPPED_MIGRATIONS: Final = frozenset(path.name for path in MIGRATIONS_DIR.iterdir() if path.is_dir())+CANNED_REPLY: Final = "Hello! This is a mock response from the fake OpenAI endpoint."+PROVIDER_KEY: Final = "integration-provider-key"+SCRATCH_ONLY: Final = ("DATABASE_URL_READ_REPLICA",)+RESOLVERS: Final = pytest.mark.parametrize(+ "database_setup", (MIGRATE_DEPLOY, LEGACY_MIGRATE_DEPLOY), ids=("v2-resolver", "legacy-resolver")+)+++def _config_without_general_settings(directory: Path) -> Path:+ config: Final = directory / "no_general_settings.yaml"+ config.write_text("model_list: []\n")+ return config+++def _upstream_requests(proxy: Gateway) -> tuple[dict[str, JsonValue], ...]:+ observed: Final = JSON_OBJECT.validate_json(+ httpx.get(f"{proxy.upstream_url}/__observations", timeout=5, trust_env=False).content+ )+ return tuple(object_value(value) for value in list_value(observed["requests"]))+++def _serves_a_completion_through_a_stored_key(proxy: Gateway, database_url: str) -> None:+ assert object_value(proxy.get("/health/readiness"))["db"] == "connected"+ model: Final = f"integration-{uuid.uuid4().hex}"+ prompt: Final = f"boot check {model}"+ proxy.post(+ "/model/new",+ {+ "model_name": model,+ "litellm_params": {+ "model": "openai/gpt-4o-mini",+ "api_key": PROVIDER_KEY,+ "api_base": f"{proxy.upstream_url}/v1",+ },+ "model_info": {},+ },+ )+ key: Final = string_value(proxy.post("/key/generate", {"models": [model]})["key"])+ reply: Final = proxy.chat(model, key=key, text=prompt)+ message: Final = object_value(object_value(list_value(reply["choices"])[0])["message"])+ assert string_value(message["content"]) == CANNED_REPLY+ assert string_value(message["role"]) == "assistant"+ forwarded: Final = tuple(+ request+ for request in _upstream_requests(proxy)+ if object_value(request["body"]).get("messages") == [{"role": "user", "content": prompt}]+ )+ assert [+ (request["path"], request["authorization"], object_value(request["body"])["model"]) for request in forwarded+ ] == [("/v1/chat/completions", f"Bearer {PROVIDER_KEY}", "gpt-4o-mini")]+ assert read_rows(+ 'SELECT models FROM "LiteLLM_VerificationToken" WHERE %s = ANY(models)',+ (model,),+ database_url=database_url,+ ) == [{"models": [model]}]+ assert read_rows(+ 'SELECT model_name FROM "LiteLLM_ProxyModelTable" WHERE model_name = %s',+ (model,),+ database_url=database_url,+ ) == [{"model_name": model}]+++def test_db_push_boots_without_general_settings_and_serves_a_stored_key(gateway: Gateway, tmp_path: Path) -> None:+ with (+ scratch_database() as database_url,+ owned_proxy_process(+ gateway,+ tmp_path,+ {"DATABASE_URL": database_url},+ config=_config_without_general_settings(tmp_path),+ remove_environment=SCRATCH_ONLY,+ database_setup=DB_PUSH,+ ) as owned,+ ):+ _serves_a_completion_through_a_stored_key(owned.gateway, database_url)+++@RESOLVERS+def test_migration_resolver_applies_every_shipped_migration_and_serves_a_stored_key(+ gateway: Gateway, tmp_path: Path, database_setup: tuple[str, ...]+) -> None:+ with (+ scratch_database() as database_url,+ owned_proxy_process(+ gateway,+ tmp_path,+ {"DATABASE_URL": database_url},+ config=_config_without_general_settings(tmp_path),+ remove_environment=SCRATCH_ONLY,+ database_setup=database_setup,+ ) as owned,+ ):+ ledger: Final = read_rows(+ "SELECT migration_name, finished_at IS NOT NULL AS finished, rolled_back_at IS NULL AS live"+ ' FROM "_prisma_migrations"',+ (),+ database_url=database_url,+ )+ assert frozenset(string_value(row["migration_name"]) for row in ledger) == SHIPPED_MIGRATIONS+ assert all(row["finished"] is True and row["live"] is True for row in ledger)+ _serves_a_completion_through_a_stored_key(owned.gateway, database_url)diff --git a/tests/local_testing/test_basic_python_version.py b/tests/local_testing/test_basic_python_version.pydeleted file mode 100644index f032486debd..00000000000--- a/tests/local_testing/test_basic_python_version.py+++ /dev/null@@ -1,321 +0,0 @@-import asyncio-import os-import subprocess-import time-import traceback-from typing import Final--import pytest--PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))----def _run_uv(*args: str, **kwargs) -> subprocess.CompletedProcess:- return subprocess.run(["uv", *args], check=True, cwd=PROJECT_ROOT, **kwargs)---def test_using_litellm():- try:- import litellm-- print("litellm imported successfully")- except Exception as e:- pytest.fail(f"Error occurred: {e}. Installing litellm failed please retry")---def test_litellm_proxy_server():- # Sync the local litellm[proxy] dependencies into the project environment- _run_uv("sync", "--frozen", "--extra", "proxy")-- # Import through the uv-managed interpreter that uv sync populated.- try:- _run_uv("run", "--no-sync", "python", "-c", "import litellm.proxy.proxy_server")- except subprocess.CalledProcessError:- pytest.fail("Failed to import litellm.proxy.proxy_server")-- # Assertion to satisfy the test, you can add other checks as needed- assert True---def test_package_dependencies():- """- Test that all optional dependency entries are exposed via project optional-dependencies.- """- try:- import pathlib- import litellm- from packaging.requirements import Requirement-- # Try to import tomllib (Python 3.11+) or tomli (older versions)- try:- import tomllib as tomli- except ImportError:- try:- import tomli- except ImportError:- pytest.skip("tomli/tomllib not available - skipping dependency check")-- # Get the litellm package root path- litellm_path = pathlib.Path(litellm.__file__).parent.parent- pyproject_path = litellm_path / "pyproject.toml"-- # Read and parse pyproject.toml- with open(pyproject_path, "rb") as f:- pyproject = tomli.load(f)-- optional_deps = pyproject["project"]["optional-dependencies"]- assert optional_deps, "Expected project.optional-dependencies to be defined"-- parsed_requirements = set()- for extra_name, requirements in optional_deps.items():- assert requirements, f"Optional dependency group '{extra_name}' is empty"- for requirement in requirements:- assert isinstance(- requirement, str- ), f"Expected string requirement in extra '{extra_name}'"- parsed = Requirement(requirement)- parsed_requirements.add(parsed.name.lower())-- print(parsed_requirements)- print(- f"Validated {len(parsed_requirements)} optional dependencies across {len(optional_deps)} extras groups"- )-- except Exception as e:- pytest.fail(- f"Error occurred while checking dependencies: {str(e)}\n"- + traceback.format_exc()- )---def test_cli_extra_is_a_thin_client_install():- """The `cli` extra must install a working `lite` client without dragging in the- proxy server runtime. It therefore has to declare the CLI's real third-party- deps (rich, pyyaml, requests) and must never contain a server-only dependency- from the `proxy` extra; a leak there silently re-bloats the laptop install.- """- import pathlib-- import litellm- from packaging.requirements import Requirement-- try:- import tomllib as tomli- except ImportError:- try:- import tomli- except ImportError:- pytest.skip("tomli/tomllib not available - skipping dependency check")-- pyproject_path = pathlib.Path(litellm.__file__).parent.parent / "pyproject.toml"- with open(pyproject_path, "rb") as f:- optional_deps = tomli.load(f)["project"]["optional-dependencies"]-- assert "cli" in optional_deps, "Expected a `cli` extra for the thin lite install"-- cli_names = {Requirement(req).name.lower() for req in optional_deps["cli"]}-- missing = {"rich", "pyyaml", "requests"} - cli_names- assert not missing, f"`cli` extra is missing deps the lite CLI imports: {missing}"-- server_only = {- "fastapi",- "uvicorn",- "gunicorn",- "granian",- "starlette",- "boto3",- "polars",- "soundfile",- "mcp",- "cryptography",- "apscheduler",- "rq",- "litellm-enterprise",- "litellm-proxy-extras",- }- leaked = cli_names & server_only- assert not leaked, f"`cli` extra leaks proxy-server deps onto laptops: {leaked}"---AIOHTTP_POOL_POISONING_RANGE = ">=3.14.0,<3.14.2"-AIOHTTP_POOL_POISONING_RELEASES = ("3.14.0", "3.14.1")---def _load_toml(path):- try:- import tomllib as tomli- except ImportError:- try:- import tomli- except ImportError:- pytest.skip("tomli/tomllib not available - skipping dependency check")-- with open(path, "rb") as f:- return tomli.load(f)---def _declared_aiohttp_specifier():- from packaging.requirements import Requirement-- pyproject = _load_toml(os.path.join(PROJECT_ROOT, "pyproject.toml"))- for requirement in pyproject["project"]["dependencies"]:- parsed = Requirement(requirement)- if parsed.name.lower() == "aiohttp":- return parsed.specifier- pytest.fail("aiohttp is no longer a declared runtime dependency of litellm")---def _locked_aiohttp_version():- lock = _load_toml(os.path.join(PROJECT_ROOT, "uv.lock"))- for package in lock["package"]:- if package["name"].lower() == "aiohttp":- return package["version"]- pytest.fail("aiohttp is missing from uv.lock")---def test_declared_aiohttp_floor_excludes_pool_poisoning_releases():- """aiohttp 3.14.0/3.14.1 re-arm the sock_read timer on a keep-alive connection- after it is back in the idle pool, so the next request to reuse it fails- instantly with a bogus timeout (aio-libs/aiohttp#12953, fixed in 3.14.2).-- The wheel's own metadata is what pip resolves against, so the floor declared- here - not just the lockfile - has to exclude that range.- """- specifier = _declared_aiohttp_specifier()-- admitted = [v for v in AIOHTTP_POOL_POISONING_RELEASES if specifier.contains(v)]- assert not admitted, (- f"litellm declares aiohttp{specifier}, which still admits {admitted}. "- "Those releases poison pooled keep-alive connections and cause "- "cross-provider sub-millisecond 'Connection timed out' failures; "- "keep the floor at >=3.14.2."- )---def test_locked_aiohttp_version_is_not_pool_poisoning():- """uv.lock is what the published Docker images install (uv sync --frozen), so a- lock that drifts back onto 3.14.0/3.14.1 ships the regression regardless of- what pyproject.toml declares.- """- from packaging.specifiers import SpecifierSet-- locked = _locked_aiohttp_version()-- assert not SpecifierSet(AIOHTTP_POOL_POISONING_RANGE).contains(locked), (- f"uv.lock resolves aiohttp {locked}, which is inside the pool-poisoning "- f"range {AIOHTTP_POOL_POISONING_RANGE} (aio-libs/aiohttp#12953). "- "Re-run `uv lock` against an aiohttp>=3.14.2 floor."- )---import os-import subprocess--import requests---def _run_proxy_server_smoke_test(extra_proxy_args=None):- """Sync deps, generate Prisma client, start proxy with optional extra args,- send a health check + chat/completions request, and tear down."""- if extra_proxy_args is None:- extra_proxy_args = []-- server_process = None- try:- _run_uv(- "sync",- "--frozen",- "--group",- "proxy-dev",- "--extra",- "proxy",- "--extra",- "extra_proxy",- )-- # Ensure Prisma client is generated- try:- print(f"Running prisma generate from: {PROJECT_ROOT}")-- result = _run_uv(- "run",- "--no-sync",- "prisma",- "generate",- capture_output=True,- text=True,- )- print(f"Prisma generate stdout: {result.stdout}")- except subprocess.CalledProcessError as e:- print(f"Prisma generate failed: {e}")- print(f"Prisma generate stderr: {e.stderr}")- raise- filepath = os.path.dirname(os.path.abspath(__file__))- config_fp = f"{filepath}/test_configs/test_config_no_auth.yaml"- proxy_env: Final = {**os.environ, "LITELLM_DANGEROUSLY_PERMIT_WEAK_OR_UNSET_MASTER_KEY": "true"}- server_process = subprocess.Popen(- [- "uv",- "run",- "--no-sync",- "python",- "-m",- "litellm.proxy.proxy_cli",- "--config",- config_fp,- *extra_proxy_args,- ],- cwd=PROJECT_ROOT,- env=proxy_env,- )-- # Allow some time for the server to start (increased for CI environments)- time.sleep(90) # Increased from 60s for slower CI runners-- # Send a request to the /health/liveliness endpoint- response = requests.get("http://localhost:4000/health/liveliness")-- # Check if the response is successful- assert response.status_code == 200- assert response.json() == "I'm alive!"-- # Test /chat/completions- response = requests.post(- "http://localhost:4000/chat/completions",- headers={"Authorization": "Bearer 1234567890"},- json={- "model": "test_openai_models",- "messages": [{"role": "user", "content": "Hello, how are you?"}],- },- )-- assert response.status_code == 200-- except ImportError:- pytest.fail("Failed to import litellm.proxy_server")- except requests.ConnectionError:- pytest.fail("Failed to connect to the server")- finally:- # Shut down the server- if server_process:- server_process.terminate()- server_process.wait()-- # Additional assertions can be added here- assert True---def test_litellm_proxy_server_config_no_general_settings():- """Exercises the default (v2) migration resolver."""- _run_proxy_server_smoke_test()---def test_litellm_proxy_server_config_no_general_settings_legacy_resolver():- """Exercises the opt-out legacy (v1) migration resolver.-- Runs after the default variant in the CI job that provides a local- Postgres, so both resolvers get real-database proxy-boot coverage.- """- _run_proxy_server_smoke_test(extra_proxy_args=["--use_legacy_migration_resolver"])diff --git a/tests/unit/test_build_core_distribution.py b/tests/unit/test_build_core_distribution.pynew file mode 100644index 00000000000..43a5b26aea4--- /dev/null+++ b/tests/unit/test_build_core_distribution.py@@ -0,0 +1,35 @@+import sys+from pathlib import Path+from typing import Final++from packaging.requirements import Requirement++if sys.version_info >= (3, 11):+ import tomllib+else:+ import tomli as tomllib+++ROOT: Final = Path(__file__).resolve().parents[2]+++def test_core_manifest_preserves_runtime_dependencies_without_extras() -> None:+ manifest: Final = ROOT / "packaging/litellm-core/pyproject.toml"+ assert manifest.is_file(), "The core distribution needs its own build manifest"+ core: Final = tomllib.loads(manifest.read_text())+ legacy: Final = tomllib.loads((ROOT / "pyproject.toml").read_text())+ assert core["project"]["name"] == "litellm-core"+ removed: Final = {"boto3", "tokenizers", "huggingface-hub"}+ core_dependencies: Final = {Requirement(value).name for value in core["project"]["dependencies"]}+ legacy_dependencies: Final = {Requirement(value).name for value in legacy["project"]["dependencies"]}+ assert not core_dependencies & removed+ assert removed <= legacy_dependencies+ assert "jsonschema" in core_dependencies+ assert legacy_dependencies - removed <= core_dependencies+ core_requirements: Final = {Requirement(value) for value in core["project"]["dependencies"]}+ retained_requirements: Final = {+ Requirement(value) for value in legacy["project"]["dependencies"] if Requirement(value).name not in removed+ }+ assert retained_requirements <= core_requirements+ assert not core["project"].get("optional-dependencies")+ assert not core["project"].get("scripts")diff --git a/tests/windows_tests/test_check_windows_wheel_install.py b/tests/unit/test_check_windows_wheel_install.pysimilarity index 94%rename from tests/windows_tests/test_check_windows_wheel_install.pyrename to tests/unit/test_check_windows_wheel_install.pyindex 7af369b0a2f..bd13667319e 100644--- a/tests/windows_tests/test_check_windows_wheel_install.py+++ b/tests/unit/test_check_windows_wheel_install.py@@ -2,7 +2,7 @@ import zipfileimport pytest-from check_windows_wheel_install import (+from tests.windows_tests.check_windows_wheel_install import (MAX_DIRECTORY_PATH,MAX_PATH,WORST_CASE_PREFIX,@@ -29,9 +29,7 @@ def test_flags_entry_one_char_over_budget(tmp_path):def test_allows_entry_exactly_at_budget(tmp_path):at_limit = "a" * FILE_BUDGET- assert (- overlong_install_paths(_wheel(tmp_path, at_limit, "litellm/__init__.py")) == []- )+ assert overlong_install_paths(_wheel(tmp_path, at_limit, "litellm/__init__.py")) == []def test_flags_directory_one_char_over_create_directory_limit(tmp_path):diff --git a/tests/unit/test_package_metadata.py b/tests/unit/test_package_metadata.pynew file mode 100644index 00000000000..fb6069291d8--- /dev/null+++ b/tests/unit/test_package_metadata.py@@ -0,0 +1,94 @@+import sys+from pathlib import Path+from typing import Final++from packaging.requirements import Requirement+from packaging.specifiers import SpecifierSet+from packaging.utils import NormalizedName, canonicalize_name++if sys.version_info >= (3, 11):+ import tomllib+else:+ import tomli as tomllib++PROJECT_ROOT: Final = Path(__file__).resolve().parents[2]+PYPROJECT: Final = tomllib.loads((PROJECT_ROOT / "pyproject.toml").read_text())+LOCK: Final = tomllib.loads((PROJECT_ROOT / "uv.lock").read_text())+OPTIONAL_DEPENDENCIES: Final = PYPROJECT["project"]["optional-dependencies"]+AIOHTTP_POOL_POISONING_RANGE: Final = SpecifierSet(">=3.14.0,<3.14.2")+AIOHTTP_POOL_POISONING_RELEASES: Final = ("3.14.0", "3.14.1")+AIOHTTP_POOL_POISONING_SOURCE: Final = "aio-libs/aiohttp#12953, fixed in aiohttp 3.14.2"+CLI_RUNTIME_DEPENDENCIES: Final = frozenset({"rich", "pyyaml", "requests"})+PROXY_SERVER_ONLY_DEPENDENCIES: Final = frozenset(+ {+ "fastapi",+ "uvicorn",+ "gunicorn",+ "granian",+ "starlette",+ "boto3",+ "polars",+ "soundfile",+ "mcp",+ "cryptography",+ "apscheduler",+ "rq",+ "litellm-enterprise",+ "litellm-proxy-extras",+ }+)+++def _locked_package(name: str) -> dict[str, object]:+ return next(package for package in LOCK["package"] if canonicalize_name(package["name"]) == name)+++def _requirement_names(requirements: list[str]) -> frozenset[NormalizedName]:+ return frozenset(canonicalize_name(Requirement(requirement).name) for requirement in requirements)+++def test_importing_litellm_reports_the_declared_release_version() -> None:+ import litellm++ assert litellm._version.version == PYPROJECT["project"]["version"]+++def test_every_declared_extra_is_locked_with_its_requirements() -> None:+ declared: Final = {+ canonicalize_name(extra): _requirement_names(requirements)+ for extra, requirements in OPTIONAL_DEPENDENCIES.items()+ }+ locked: Final = _locked_package("litellm")+ locked_extras: Final = {+ canonicalize_name(extra): frozenset(canonicalize_name(entry["name"]) for entry in entries)+ for extra, entries in locked["optional-dependencies"].items()+ }+ provided: Final = frozenset(canonicalize_name(extra) for extra in locked["metadata"]["provides-extras"])+ assert declared+ assert all(declared.values())+ assert frozenset(declared) == provided+ assert declared == locked_extras+++def test_cli_extra_is_a_thin_client_install() -> None:+ cli: Final = _requirement_names(OPTIONAL_DEPENDENCIES["cli"])+ assert CLI_RUNTIME_DEPENDENCIES - cli == frozenset()+ assert cli & PROXY_SERVER_ONLY_DEPENDENCIES == frozenset()+++def test_declared_aiohttp_floor_excludes_pool_poisoning_releases() -> None:+ declared: Final = tuple(+ Requirement(requirement)+ for requirement in PYPROJECT["project"]["dependencies"]+ if canonicalize_name(Requirement(requirement).name) == "aiohttp"+ )+ assert len(declared) == 1+ assert (+ tuple(release for release in AIOHTTP_POOL_POISONING_RELEASES if declared[0].specifier.contains(release)) == ()+ ), AIOHTTP_POOL_POISONING_SOURCE+++def test_locked_aiohttp_version_is_not_pool_poisoning() -> None:+ locked: Final = _locked_package("aiohttp")["version"]+ assert isinstance(locked, str)+ assert not AIOHTTP_POOL_POISONING_RANGE.contains(locked), AIOHTTP_POOL_POISONING_SOURCEdiff --git a/tests/windows_tests/test_litellm_on_windows.py b/tests/windows_tests/test_litellm_on_windows.pyindex 0a6058d6784..254a31fbcc0 100644--- a/tests/windows_tests/test_litellm_on_windows.py+++ b/tests/windows_tests/test_litellm_on_windows.py@@ -1,35 +1,17 @@-import asyncio-import subprocess-import time-import traceback-import platform+from typing import Final-import pytest+import litellm+MOCK_REPLY: Final = "windows runtime reply"-def test_using_litellm_on_windows():- """Test that LiteLLM can be imported on Windows systems."""-- try:- import litellm-- print(- f"litellm imported successfully on Windows ({platform.system()} {platform.release()})"- )-- response = litellm.completion(- model="gpt-4o",- messages=[- {- "role": "user",- "content": "This should never fail. Email [email protected] if this test ever fails.",- }- ],- mock_response="Hello, how are you?",- )- print(response)- except Exception as e:- pytest.fail(- f"Error occurred on Windows: {e}. Installing litellm on Windows failed."- )+def test_using_litellm_on_windows() -> None:+ response: Final = litellm.completion(+ model="gpt-4o",+ messages=[{"role": "user", "content": "windows smoke"}],+ mock_response=MOCK_REPLY,+ )+ assert response.choices[0].message.content == MOCK_REPLY+ assert response.choices[0].message.role == "assistant"+ assert response.choices[0].finish_reason == "stop"+ assert response.model == "gpt-4o"