Files
litellm/tests/local_testing/test_basic_python_version.py
T
Mateo Wang 20e453f698 feat(cli): per-agent lite claude / codex / opencode commands that wrap coding agents through the proxy (#29850)
* feat(cli): add `litellm-proxy run -- <agent>` to wrap coding agents through the proxy

Wraps Claude Code, Codex, OpenCode, and any other coding agent so all of its
LLM traffic routes through a LiteLLM proxy, with the agent-vault style of "just
works" DX: one `run -- <agent>` command, auto SSO login when interactive,
env-key "agent mode" for containers/CI, and a fail-fast key check against the
proxy so bad credentials error immediately instead of deep inside the agent.

The wrapped binary is detected by name to pick the right variables. Claude Code
gets ANTHROPIC_BASE_URL (the bare proxy root, so it appends /v1/messages) and
ANTHROPIC_AUTH_TOKEN, with any stray ANTHROPIC_API_KEY cleared so the proxy
token wins. Codex and OpenCode get OPENAI_BASE_URL (proxy + /v1) and
OPENAI_API_KEY. Unrecognized commands get both sets so they work either way.
`litellm-proxy claude-code` remains as a shortcut for `run -- claude`.

The core logic is split into dependency-injected helpers (agent_profile,
build_agent_env, verify_proxy_key, run_agent) so env wiring, the preflight, and
the launch handoff are unit-tested without monkeypatching, alongside CliRunner
tests for auth resolution, agent mode, and auto-login. Mutation-tested the env
profiles, preflight, and agent-mode branch to confirm the tests fail when the
behavior is broken.

https://claude.ai/code/session_0154VpLXW7mMvk5wfbgPRJa6

* Make each coding agent its own litellm-proxy command

Replace the `run -- <agent>` interface and the `claude-code` shortcut with
top-level commands generated per known agent, so launching is just
`litellm-proxy claude`, `litellm-proxy codex`, or `litellm-proxy opencode`,
with everything after the agent name forwarded straight to it. This drops the
ceremony of `run --` and cuts typing.

The `--model`/`--small-fast-model` wrapper flags are gone; pass the agent's
own model flag instead, or export the model env vars (the wrapper preserves
what you already have set), which keeps the surface minimal and avoids
intercepting flags the agent owns. Rename the module to agents.py to match.

* fix(cli): route `litellm-proxy codex` through the proxy via a custom provider

Codex ignores OPENAI_BASE_URL (it always dials api.openai.com over the
Responses WebSocket transport), so the OpenAI env profile alone left
`litellm-proxy codex` talking to OpenAI directly instead of the proxy. Point
Codex at the proxy with a custom provider passed as `-c` config overrides, and
force the HTTP/SSE Responses transport with supports_websockets=false since the
proxy does not speak the Responses WebSocket protocol. The provider reads its
key from OPENAI_API_KEY, which the agent env already exports.

The overrides are injected ahead of the user's args so they precede Codex's
subcommand. Claude Code and OpenCode are unaffected; they honor the exported
env vars. Adds regression tests for the per-agent launch args and the
injection ordering.

Co-authored-by: Mateo Wang <mateo-berri@users.noreply.github.com>

* Rename litellm-proxy CLI command to lite

The proxy management CLI was invoked as litellm-proxy, which is a lot to
type for an everyday command. Rename the console script entry point to
lite and update the in-CLI usage examples, help text, error messages and
docs to match.

* fix(sso): stop CLI auth success page from hanging on "Closing..."

The CLI opens the SSO success page with webbrowser.open, so the tab is
not script-opened and the browser refuses window.close(). The countdown
would end on "Closing..." and the tab would sit there forever.

Drop the countdown and just show "You can now close this window and
return to your terminal." from the start, while still attempting
window.close() once so the tab auto-closes in the rare case the browser
allows it. Add a regression test asserting the manual-close instruction
is always present and the misleading countdown/"Closing..." text is gone.

* fix(cli): reattach controlling terminal after SSO login, keep litellm-proxy alias

When the first `lite claude` has to log in via browser SSO, completing the login could
leave stdin detached from the terminal, so a TUI agent like Claude Code would start in
non-interactive mode and exit with "Input must be provided". The wrapper now reopens the
controlling terminal onto stdin just before handoff when the session started interactively;
piped or redirected input is detected up front and left alone, so agent-mode and
non-interactive use are unchanged.

Also keep the `litellm-proxy` console script as an alias for `lite` so existing scripts and
CI that invoke `litellm-proxy` keep working; both names map to the same CLI.

* feat(install): make the curl installer need only curl, not a pre-existing Python

The installer now lets uv provision a managed Python 3.13 when no suitable
interpreter is found, instead of aborting. The minimum is also bumped from
3.9 to 3.10 to match the package's requires-python (>=3.10), so a system
Python 3.9 is no longer selected only for uv tool install to reject it.

* feat(cli): add thin litellm[cli] install path (install-cli.sh + brew) for the lite CLI

On a developer laptop the `lite` CLI only needs `lite login` and running coding
agents through a proxy, but the sole install path was `litellm[proxy]`, which
drags in the whole server tree (fastapi, uvicorn, boto3, polars, cryptography,
litellm-enterprise). The CLI's heavy imports are all guarded, so it runs on the
base SDK plus just rich, pyyaml and requests.

Add a `cli` extra carrying exactly those three, a `scripts/install-cli.sh` curl
one-liner that installs `litellm[cli]`, and a `BerriAI/homebrew-litellm` tap
formula with a release runbook under `packaging/homebrew/`. The installer passes
no `--python`, so uv honours litellm's requires-python and provisions a managed
interpreter, skipping a too-old (3.9) or too-new (3.14+) system Python instead
of failing to resolve.

A pyproject thin-contract test asserts the `cli` extra keeps the deps the CLI
imports and never leaks a server-only dependency from `proxy`, so the laptop
install cannot silently re-bloat

* fix(install): let uv pick the Python via --python-preference system

Both installers detected a system Python with a floor-only check and forced it
with `uv tool install --python <interp>`. On a host whose only Python is outside
litellm's requires-python (a too-old 3.9 or, increasingly, a too-new 3.14) that
forced an incompatible interpreter and the resolve failed. Drop the detection and
pass `--python-preference system`: uv reuses a compatible system Python when
present and downloads a managed one otherwise, always honouring requires-python

* test(router): filter aiohttp unclosed-session gc noise in test_async_fallbacks

test_async_fallbacks asserts the last three captured log records are the
router's fallback messages. Under the litellm_router_testing job (pytest -k
router -n 4) many router tests share the module-level in_memory_llm_clients_cache
(max 200, ttl 3600s). Older cached OpenAI/Azure clients get evicted while their
aiohttp ClientSession is still open, and when the gc reclaims them aiohttp emits
"Unclosed client session"/"Unclosed connector" through the asyncio logger.
Those records land in caplog mid-test and push the expected router logs out of
the last-three window, so the assertion flips to failing non-deterministically.

These warnings are async cleanup noise, not router debug logs, so filter them
out exactly like the existing leaked-task warnings before asserting order. The
assertion on the three router fallback messages is unchanged.

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: Mateo Wang <mateo-berri@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-06-10 13:52:26 -07:00

254 lines
7.9 KiB
Python

import asyncio
import os
import subprocess
import sys
import time
import traceback
import pytest
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
sys.path.insert(
0, os.path.abspath("../..")
) # Adds the parent directory to the system path
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}"
import os
import subprocess
import time
import pytest
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"
server_process = subprocess.Popen(
[
"uv",
"run",
"--no-sync",
"python",
"-m",
"litellm.proxy.proxy_cli",
"--config",
config_fp,
*extra_proxy_args,
],
cwd=PROJECT_ROOT,
)
# 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 (v1) migration resolver."""
_run_proxy_server_smoke_test()
def test_litellm_proxy_server_config_no_general_settings_v2_resolver():
"""Exercises the opt-in v2 migration resolver.
Runs in a separate CI job against a local Postgres to avoid collisions
with the v1 variant when they share a database.
"""
_run_proxy_server_smoke_test(extra_proxy_args=["--use_v2_migration_resolver"])