Skip to content

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]

Merge origin/litellm_internal_staging into litellm_lite_pi

yassin48849a6f3693
diff --cc litellm/proxy/client/cli/README.md
index 468b8d96123,ed1447e4e65..f7d9eb7da9a
--- a/litellm/proxy/client/cli/README.md
+++ b/litellm/proxy/client/cli/README.md
@@@ -479,10 -489,8 +490,10 @@@ lite codex exec "summarize the repo
Each command resolves your LiteLLM key (logging in via SSO when none is stored and you are at a terminal; otherwise it expects `LITELLM_PROXY_API_KEY` or `--api-key`), checks the key against the proxy so bad credentials fail immediately instead of deep inside the agent, exports the environment variables the agent reads, then replaces itself with the agent process.
- The right variables are picked per agent. Claude Code gets `ANTHROPIC_BASE_URL` (the 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` (the proxy plus `/v1`) and `OPENAI_API_KEY`. Codex ignores `OPENAI_BASE_URL`, so it is additionally pointed at the proxy through a custom provider passed as `-c` config overrides (HTTP/SSE Responses transport, since the proxy does not speak the Responses WebSocket protocol).
+ The right variables are picked per agent. Claude Code gets `ANTHROPIC_BASE_URL` (the proxy root, so it appends `/v1/messages`) and `ANTHROPIC_AUTH_TOKEN`, with any stray `ANTHROPIC_API_KEY` cleared so the proxy token wins, and `ENABLE_TOOL_SEARCH=true` (unless you already set it) so Claude Code keeps tool search on even though the base URL is a proxy rather than a first-party Anthropic host. It also gets `CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1` (again unless you already set it) so Claude Code v2.1.129+ fills its `/model` picker from the proxy's `/v1/models`; Claude Code only lists entries whose id contains `claude` or `anthropic`, and older versions ignore the variable. Export it as `0` to turn discovery off. Codex and OpenCode get `OPENAI_BASE_URL` (the proxy plus `/v1`) and `OPENAI_API_KEY`. Codex ignores `OPENAI_BASE_URL`, so it is additionally pointed at the proxy through a custom provider passed as `-c` config overrides (HTTP/SSE Responses transport, since the proxy does not speak the Responses WebSocket protocol). OpenCode additionally gets `OPENCODE_CONFIG_CONTENT` holding a generated `litellm` provider (`@ai-sdk/openai-compatible`, the proxy `/v1` URL, `{env:OPENAI_API_KEY}`) with one model entry per chat model your key can see on `/v1/models`, so its model picker mirrors the proxy without a hand-maintained `opencode.json`; OpenCode merges that over your own config files, and if you already export `OPENCODE_CONFIG_CONTENT` yours is left alone. When the list cannot be fetched, `lite opencode` says so on stderr and launches anyway.
+pi ignores base-URL environment variables entirely, so `lite pi` (kept out of the `lite --help` command listing for now, but fully functional) wires it up differently: before handoff it fetches the models your key can use from the proxy's `/v1/models` (plus each model's context window and output cap from `/model_group/info`, when available) and syncs them into a `litellm` provider entry in pi's `~/.pi/agent/models.json` (honoring `PI_CODING_AGENT_DIR`), then starts pi on that provider's first model via an injected `--model litellm/<id>`. Only that one provider entry is rewritten; the rest of the file, including any other custom providers, is left alone. The entry references the key as `$LITELLM_PROXY_API_KEY`, which the wrapper exports for the session, so the token itself never lands on disk and plain `pi` outside the wrapper simply shows the litellm models as unavailable. Your own flags come after the injected pin, so `lite pi --model litellm/<other-id>` wins, and inside the TUI the `/model` picker lists every synced litellm model.
+
Options (these belong to the wrapper, so put them before the agent's own flags):
- `--skip-verify`: Skip the pre-launch key check (useful offline or with non-standard auth).
@@@ -493,7 -501,7 +504,7 @@@ To pin the model, pass the agent's own
The token minted by `lite login` is a short-lived, per-session agent credential, not a managed virtual key. It is scoped to the user and team you authenticated as, inherits that user's and team's models and budgets, and is enforced on the proxy exactly like a virtual key on the same team (guardrails, routing, logging, spend). Spend is tracked against the shared team and user budgets, so running several agents (or logging in more than once) does not hand each session its own separate budget; they all draw down the same team/user allowance. There is no separate per-session cap, so sustained agent use is not capped at a small chat-session limit.
- The credential is short-lived by design (default 24h, configurable via `LITELLM_CLI_JWT_EXPIRATION_HOURS`); run `lite login` again to refresh it, which also re-reads your latest team and user settings. It does not appear in the Keys UI and cannot be rotated or revoked mid-session. `lite auth print-token` (usable as Claude Code's `apiKeyHelper`) prints it while it's still fresh and fails once it expires -- there is no silent renewal, so a long-running session needs a fresh `lite login` once a day. `lite claude`, `lite codex`, `lite opencode`, and `lite pi` work with it on a default deployment; `EXPERIMENTAL_UI_LOGIN` is not required. If you need a long-lived, rotatable key that shows up in the Keys UI, create a dedicated virtual key in the dashboard and pass it via `--api-key` or `LITELLM_PROXY_API_KEY` instead.
-The credential is short-lived by design (default 24h, configurable via `LITELLM_CLI_JWT_EXPIRATION_HOURS`); run `lite login` again to refresh it, which also re-reads your latest team and user settings. It does not appear in the Keys UI and cannot be rotated or revoked mid-session. `lite auth print-token` (usable as Claude Code's `apiKeyHelper`) prints it while it's still fresh and fails once it expires -- there is no silent renewal, so a long-running session needs a fresh `lite login` once a day. `lite claude`, `lite codex`, and `lite opencode` work with it on a default deployment; `EXPERIMENTAL_UI_LOGIN` is not required. `lite login --pkce` is the exception to the daily re-login: it signs in through your system browser with OAuth authorization code and PKCE and stores a refresh token next to the key, so every `lite` command and `lite auth print-token` renew the key on their own shortly before it expires, `lite whoami` shows when the current key expires, and `lite logout` revokes the refresh token on the proxy (it needs a proxy that serves `/.well-known/litellm-cli-auth`; see [Browser sign-in with PKCE](https://docs.litellm.ai/docs/proxy/cli_sso#browser-sign-in-with-pkce)). When a renewal is refused, for example after a `lite logout` run from another copy of the credential, the command prints why on stderr and, once the key has run out, tells you to run `lite login --pkce` again. Only the holder can end a `--pkce` session early, with `lite logout`; an admin has no button for it, but every renewal re-reads the user on the proxy, so deactivating the user or removing them from the team makes the next renewal fail and the key runs out within `LITELLM_CLI_JWT_EXPIRATION_HOURS`. On a proxy with more than one worker or replica, configure Redis (`litellm_settings.cache` with Redis `cache_params`, or `general_settings.coordination_redis`) so a refresh token stays single-use and `lite logout` holds on every worker; without Redis each worker keeps its own record. If you need a long-lived, rotatable key that shows up in the Keys UI, create a dedicated virtual key in the dashboard and pass it via `--api-key` or `LITELLM_PROXY_API_KEY` instead.
++The credential is short-lived by design (default 24h, configurable via `LITELLM_CLI_JWT_EXPIRATION_HOURS`); run `lite login` again to refresh it, which also re-reads your latest team and user settings. It does not appear in the Keys UI and cannot be rotated or revoked mid-session. `lite auth print-token` (usable as Claude Code's `apiKeyHelper`) prints it while it's still fresh and fails once it expires -- there is no silent renewal, so a long-running session needs a fresh `lite login` once a day. `lite claude`, `lite codex`, `lite opencode`, and `lite pi` work with it on a default deployment; `EXPERIMENTAL_UI_LOGIN` is not required. `lite login --pkce` is the exception to the daily re-login: it signs in through your system browser with OAuth authorization code and PKCE and stores a refresh token next to the key, so every `lite` command and `lite auth print-token` renew the key on their own shortly before it expires, `lite whoami` shows when the current key expires, and `lite logout` revokes the refresh token on the proxy (it needs a proxy that serves `/.well-known/litellm-cli-auth`; see [Browser sign-in with PKCE](https://docs.litellm.ai/docs/proxy/cli_sso#browser-sign-in-with-pkce)). When a renewal is refused, for example after a `lite logout` run from another copy of the credential, the command prints why on stderr and, once the key has run out, tells you to run `lite login --pkce` again. Only the holder can end a `--pkce` session early, with `lite logout`; an admin has no button for it, but every renewal re-reads the user on the proxy, so deactivating the user or removing them from the team makes the next renewal fail and the key runs out within `LITELLM_CLI_JWT_EXPIRATION_HOURS`. On a proxy with more than one worker or replica, configure Redis (`litellm_settings.cache` with Redis `cache_params`, or `general_settings.coordination_redis`) so a refresh token stays single-use and `lite logout` holds on every worker; without Redis each worker keeps its own record. If you need a long-lived, rotatable key that shows up in the Keys UI, create a dedicated virtual key in the dashboard and pass it via `--api-key` or `LITELLM_PROXY_API_KEY` instead.
### Route Every Claude Code Session Through the Proxy
diff --cc litellm/proxy/client/cli/commands/agents.py
index ba410673ec9,ce416ef237b..d9b8117c994
--- a/litellm/proxy/client/cli/commands/agents.py
+++ b/litellm/proxy/client/cli/commands/agents.py
@@@ -1,23 -1,18 +1,27 @@@
import os
import shutil
+ import subprocess
import sys
from collections.abc import Callable, Mapping, Sequence
+ from dataclasses import dataclass
from types import MappingProxyType
-from typing import Final
+from typing import Final, TypeAlias
import click
import requests
+ from pydantic import BaseModel, TypeAdapter, ValidationError
- from .auth import get_stored_api_key, login
+ from .auth import context_secret_vault, get_stored_api_key, login
+ from .cmd_quoting import quote_for_cmd
+from .pi import (
+ LITELLM_PROXY_API_KEY_ENV,
+ PI_PROVIDER_NAME,
+ PiSyncError,
+ fetch_model_ids,
+ fetch_model_limits,
+ models_json_path,
+ sync_models_json,
+)
ANTHROPIC_BASE_URL_ENV: Final = "ANTHROPIC_BASE_URL"
ANTHROPIC_AUTH_TOKEN_ENV: Final = "ANTHROPIC_AUTH_TOKEN"
@@@ -75,9 -75,12 +89,14 @@@ def build_agent_env
Anthropic clients (Claude Code) append /v1/messages to ANTHROPIC_BASE_URL,
so it stays the bare proxy root; OpenAI clients (Codex, OpenCode) expect the
/v1 suffix on OPENAI_BASE_URL. ANTHROPIC_API_KEY is dropped so a stray
- Anthropic key cannot win over the bearer token we set. pi ignores both base
- URL variables and instead resolves $LITELLM_PROXY_API_KEY from its synced
- models.json provider entry.
+ Anthropic key cannot win over the bearer token we set. ENABLE_TOOL_SEARCH
+ defaults to true because Claude Code turns tool search off when
+ ANTHROPIC_BASE_URL is not a first-party Anthropic host; a value already in
+ the environment is left alone. CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY
+ defaults to 1 so Claude Code (v2.1.129+) fills its /model picker from the
+ proxy's /v1/models; likewise left alone when already set.
++ pi ignores both base URL variables and instead resolves $LITELLM_PROXY_API_KEY
++ from its synced models.json provider entry.
"""
env: Final = dict(base_env)
root: Final = base_url.rstrip("/")
@@@ -228,9 -401,12 +453,13 @@@ def run_agent
base_env: Mapping[str, str] | None = None,
which: Callable[[str], str | None] = shutil.which,
verify: Callable[[str, str], None] = verify_proxy_key,
- launcher: Callable[[str, Sequence[str], Mapping[str, str]], None] = _exec,
+ sync_models: Callable[[str, Mapping[str, str], str, str, bool], Mapping[str, str] | ModelSyncSkipped] = (
+ agent_model_sync_env
+ ),
+ warn: Callable[[str], None] = _warn,
+ launcher: Callable[[str, Sequence[str], Mapping[str, str]], None] = _hand_off,
reattach_terminal: Callable[[], None] | None = None,
+ preparers: Mapping[str, _Preparer] = MappingProxyType(_PREPARERS),
) -> None:
"""Validate, wire the environment, and hand off to the agent.
@@@ -252,12 -430,18 +481,21 @@@
if not skip_verify:
verify(base_url, api_key)
- source_env: Final = base_env if base_env is not None else os.environ
+ env_before_sync: Final = base_env if base_env is not None else os.environ
+ synced: Final = sync_models(command[0], env_before_sync, base_url, api_key, skip_verify)
+ if isinstance(synced, ModelSyncSkipped):
+ warn(f"litellm: not syncing {display_name} models from the proxy: {synced.reason}")
+
+ prepare: Final = preparers.get(os.path.basename(command[0]))
- prepared_args: Final = list(prepare(base_url, api_key, source_env)) if prepare is not None else []
++ prepared_args: Final = tuple(prepare(base_url, api_key, env_before_sync)) if prepare is not None else ()
+
- env: Final = build_agent_env(source_env, base_url, api_key, profiles)
- extra_args: Final = [*agent_launch_args(command[0], base_url), *prepared_args]
+ env: Final = MappingProxyType(
+ {
+ **build_agent_env(env_before_sync, base_url, api_key, profiles),
+ **(_NO_EXTRA_ENV if isinstance(synced, ModelSyncSkipped) else synced),
+ }
+ )
- extra_args: Final = agent_launch_args(command[0], base_url)
++ extra_args: Final = (*agent_launch_args(command[0], base_url), *prepared_args)
if reattach_terminal is not None:
reattach_terminal()
launcher(binary, [command[0], *extra_args, *command[1:]], env)
@@@ -339,11 -522,15 +577,16 @@@ def agent_commands() -> tuple[click.Com
__all__ = [
"AgentRunError",
+ "ListedModel",
+ "ModelSyncSkipped",
"agent_commands",
"agent_launch_args",
+ "agent_model_sync_env",
"agent_profile",
"build_agent_env",
+ "opencode_model_sync_env",
+ "opencode_provider_config",
+ "prepare_pi",
"resolve_api_key",
"run_agent",
"verify_proxy_key",
diff --cc tests/test_litellm/proxy/client/cli/test_agents.py
index 99b2ff234e2,5b99d368cbb..bd18a5c6f94
--- a/tests/test_litellm/proxy/client/cli/test_agents.py
+++ b/tests/test_litellm/proxy/client/cli/test_agents.py
@@@ -29,20 -34,26 +34,35 @@@ def _agent_command(name)
return next(c for c in agent_commands() if c.name == name)
+ def _default_of(func, param):
+ return inspect.signature(func).parameters[param].default
+
+
class _FakeResponse:
- def __init__(self, status_code):
+ def __init__(self, status_code, body=None):
self.status_code = status_code
+ self.content = json.dumps(body).encode() if body is not None else b""
+
+
+ class _Recorder:
+ def __init__(self, returns=None):
+ self.returns = returns
+ self.calls = []
+
+ def __call__(self, *args):
+ self.calls.append(args)
+ return self.returns
+class _FakeJsonResponse:
+ def __init__(self, status_code, payload=None):
+ self.status_code = status_code
+ self._payload = payload
+
+ def json(self):
+ return self._payload
+
+
class TestAgentProfile:
def test_claude_is_anthropic(self):
name, profiles = agent_profile("claude")
@@@ -102,16 -132,8 +144,17 @@@ class TestBuildAgentEnv
assert env["OPENAI_BASE_URL"] == "http://localhost:4000/v1"
assert env["ANTHROPIC_AUTH_TOKEN"] == "sk-key"
assert env["OPENAI_API_KEY"] == "sk-key"
+ assert env["ENABLE_TOOL_SEARCH"] == "true"
+ def test_litellm_profile_exports_only_the_proxy_key(self):
+ env = build_agent_env(
+ {}, "http://localhost:4000/", "sk-key", frozenset({"litellm"})
+ )
+ assert env["LITELLM_PROXY_API_KEY"] == "sk-key"
+ assert "ANTHROPIC_BASE_URL" not in env
+ assert "OPENAI_BASE_URL" not in env
+ assert "OPENAI_API_KEY" not in env
+
def test_preserves_unrelated_env_and_does_not_mutate_input(self):
base = {"PATH": "/usr/bin", "ANTHROPIC_API_KEY": "real-key"}
env = build_agent_env(