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]

[Feat] Proxy CLI: Create a python method to login using litellm proxy (#14782)

Ishaan Jaffb9ffa98c5583
diff --git a/cookbook/litellm_proxy_server/cli_token_usage.py b/cookbook/litellm_proxy_server/cli_token_usage.py
new file mode 100644
index 00000000000..6ee5555695e
--- /dev/null
+++ b/cookbook/litellm_proxy_server/cli_token_usage.py
@@ -0,0 +1,62 @@
+#!/usr/bin/env python3
+"""
+Example: Using CLI token with LiteLLM SDK
+
+This example shows how to use the CLI authentication token
+in your Python scripts after running `litellm-proxy login`.
+"""
+
+from textwrap import indent
+import litellm
+LITELLM_BASE_URL = "http://localhost:4000/"
+
+
+def main():
+ """Using CLI token with LiteLLM SDK"""
+ print("🚀 Using CLI Token with LiteLLM SDK")
+ print("=" * 40)
+ #litellm._turn_on_debug()
+
+ # Get the CLI token
+ api_key = litellm.get_litellm_gateway_api_key()
+
+ if not api_key:
+ print("❌ No CLI token found. Please run 'litellm-proxy login' first.")
+ return
+
+ print("✅ Found CLI token.")
+
+ available_models = litellm.get_valid_models(
+ check_provider_endpoint=True,
+ custom_llm_provider="litellm_proxy",
+ api_key=api_key,
+ api_base=LITELLM_BASE_URL
+ )
+
+ print("✅ Available models:")
+ if available_models:
+ for i, model in enumerate(available_models, 1):
+ print(f" {i:2d}. {model}")
+ else:
+ print(" No models available")
+
+ # Use with LiteLLM
+ try:
+ response = litellm.completion(
+ model="litellm_proxy/gemini/gemini-2.5-flash",
+ messages=[{"role": "user", "content": "Hello from CLI token!"}],
+ api_key=api_key,
+ base_url=LITELLM_BASE_URL
+ )
+ print(f"✅ LLM Response: {response.model_dump_json(indent=4)}")
+ except Exception as e:
+ print(f"❌ Error: {e}")
+
+
+if __name__ == "__main__":
+ main()
+
+ print("\n💡 Tips:")
+ print("1. Run 'litellm-proxy login' to authenticate first")
+ print("2. Replace 'https://your-proxy.com' with your actual proxy URL")
+ print("3. The token is stored locally at ~/.litellm/token.json")
diff --git a/enterprise/litellm_enterprise/integrations/prometheus.py b/enterprise/litellm_enterprise/integrations/prometheus.py
index 4a1e8d75435..4451d76bed0 100644
--- a/enterprise/litellm_enterprise/integrations/prometheus.py
+++ b/enterprise/litellm_enterprise/integrations/prometheus.py
@@ -2328,7 +2328,6 @@ def get_custom_labels_from_tags(tags: List[str]) -> Dict[str, str]:
"tag_Service_web_app_v1": "false",
}
"""
- import re
from litellm.router_utils.pattern_match_deployments import PatternMatchRouter
from litellm.types.integrations.prometheus import _sanitize_prometheus_label_name
diff --git a/enterprise/litellm_enterprise/proxy/management_endpoints/internal_user_endpoints.py b/enterprise/litellm_enterprise/proxy/management_endpoints/internal_user_endpoints.py
index e60b4d69905..2f53f9e9281 100644
--- a/enterprise/litellm_enterprise/proxy/management_endpoints/internal_user_endpoints.py
+++ b/enterprise/litellm_enterprise/proxy/management_endpoints/internal_user_endpoints.py
@@ -2,7 +2,6 @@
Enterprise internal user management endpoints
"""
-import os
from fastapi import APIRouter, Depends, HTTPException
diff --git a/enterprise/litellm_enterprise/proxy/vector_stores/endpoints.py b/enterprise/litellm_enterprise/proxy/vector_stores/endpoints.py
index 43bdfa3844f..bb4b546b8d3 100644
--- a/enterprise/litellm_enterprise/proxy/vector_stores/endpoints.py
+++ b/enterprise/litellm_enterprise/proxy/vector_stores/endpoints.py
@@ -11,7 +11,7 @@ All /vector_store management endpoints
import copy
from typing import List, Optional
-from fastapi import APIRouter, Depends, HTTPException, Request, Response
+from fastapi import APIRouter, Depends, HTTPException
import litellm
from litellm._logging import verbose_proxy_logger
diff --git a/litellm/__init__.py b/litellm/__init__.py
index aa8357b6c78..7a68aa3a8d6 100644
--- a/litellm/__init__.py
+++ b/litellm/__init__.py
@@ -1343,5 +1343,8 @@ disable_hf_tokenizer_download: Optional[bool] = (
)
global_disable_no_log_param: bool = False
+### CLI UTILITIES ###
+from litellm.litellm_core_utils.cli_token_utils import get_litellm_gateway_api_key
+
### PASSTHROUGH ###
from .passthrough import allm_passthrough_route, llm_passthrough_route
diff --git a/litellm/litellm_core_utils/cli_token_utils.py b/litellm/litellm_core_utils/cli_token_utils.py
new file mode 100644
index 00000000000..2aedb1c19d2
--- /dev/null
+++ b/litellm/litellm_core_utils/cli_token_utils.py
@@ -0,0 +1,58 @@
+"""
+CLI Token Utilities
+
+SDK-level utilities for reading CLI authentication tokens.
+This module has no dependencies on proxy code and can be safely imported at the SDK level.
+"""
+
+import json
+import os
+from pathlib import Path
+from typing import Optional
+
+
+def get_cli_token_file_path() -> str:
+ """Get the path to the CLI token file"""
+ home_dir = Path.home()
+ config_dir = home_dir / ".litellm"
+ return str(config_dir / "token.json")
+
+
+def load_cli_token() -> Optional[dict]:
+ """Load CLI token data from file"""
+ token_file = get_cli_token_file_path()
+ if not os.path.exists(token_file):
+ return None
+
+ try:
+ with open(token_file, 'r') as f:
+ return json.load(f)
+ except (json.JSONDecodeError, IOError):
+ return None
+
+
+def get_litellm_gateway_api_key() -> Optional[str]:
+ """
+ Get the stored CLI API key for use with LiteLLM SDK.
+
+ This function reads the token file created by `litellm-proxy login`
+ and returns the API key for use in Python scripts.
+
+ Returns:
+ str: The API key if found, None otherwise
+
+ Example:
+ >>> import litellm
+ >>> api_key = litellm.get_litellm_gateway_api_key()
+ >>> if api_key:
+ >>> response = litellm.completion(
+ >>> model="gpt-3.5-turbo",
+ >>> messages=[{"role": "user", "content": "Hello"}],
+ >>> api_key=api_key,
+ >>> base_url="https://your-proxy.com/v1"
+ >>> )
+ """
+ token_data = load_cli_token()
+ if token_data and 'key' in token_data:
+ return token_data['key']
+ return None
diff --git a/litellm/proxy/client/cli/commands/auth.py b/litellm/proxy/client/cli/commands/auth.py
index ec57f649463..9be74268059 100644
--- a/litellm/proxy/client/cli/commands/auth.py
+++ b/litellm/proxy/client/cli/commands/auth.py
@@ -1,11 +1,15 @@
import json
import os
+import sys
import time
import webbrowser
from pathlib import Path
-from typing import Any, Dict, Optional
+from typing import Any, Dict, List, Optional
import click
+import requests
+from rich.console import Console
+from rich.table import Table
# Token storage utilities
@@ -44,10 +48,256 @@ def clear_token() -> None:
def get_stored_api_key() -> Optional[str]:
"""Get the stored API key from token file"""
- token_data = load_token()
- if token_data and 'key' in token_data:
- return token_data['key']
- return None
+ # Use the SDK-level utility
+ from litellm.litellm_core_utils.cli_token_utils import get_litellm_gateway_api_key
+ return get_litellm_gateway_api_key()
+
+# Team selection utilities
+def display_teams_table(teams: List[Dict[str, Any]]) -> None:
+ """Display teams in a formatted table"""
+ console = Console()
+
+ if not teams:
+ console.print("❌ No teams found for your user.")
+ return
+
+ table = Table(title="Available Teams")
+ table.add_column("Index", style="cyan", no_wrap=True)
+ table.add_column("Team Alias", style="magenta")
+ table.add_column("Team ID", style="green")
+ table.add_column("Models", style="yellow")
+ table.add_column("Max Budget", style="blue")
+
+ for i, team in enumerate(teams):
+ team_alias = team.get("team_alias") or "N/A"
+ team_id = team.get("team_id", "N/A")
+ models = team.get("models", [])
+ max_budget = team.get("max_budget")
+
+ # Format models list
+ if models:
+ if len(models) > 3:
+ models_str = ", ".join(models[:3]) + f" (+{len(models) - 3} more)"
+ else:
+ models_str = ", ".join(models)
+ else:
+ models_str = "All models"
+
+ # Format budget
+ budget_str = f"${max_budget}" if max_budget else "Unlimited"
+
+ table.add_row(
+ str(i + 1),
+ team_alias,
+ team_id,
+ models_str,
+ budget_str
+ )
+
+ console.print(table)
+
+
+def get_user_teams(base_url: str, api_key: str, user_id: str) -> List[Dict[str, Any]]:
+ """Fetch teams for the current user"""
+ from litellm.proxy.client import Client
+
+ client = Client(base_url=base_url, api_key=api_key)
+ try:
+ response = client.teams.list_v2(user_id=user_id)
+ # Extract just the teams array from the paginated response
+ if isinstance(response, dict) and 'teams' in response:
+ return response['teams']
+ else:
+ # Fallback in case the response structure is different
+ return response if isinstance(response, list) else []
+ except Exception as e:
+ click.echo(f"❌ Error fetching teams: {e}")
+ return []
+
+
+def get_key_input():
+ """Get a single key input from the user (cross-platform)"""
+ try:
+ if sys.platform == 'win32':
+ import msvcrt
+ key = msvcrt.getch()
+ if key == b'\xe0': # Arrow keys on Windows
+ key = msvcrt.getch()
+ if key == b'H': # Up arrow
+ return 'up'
+ elif key == b'P': # Down arrow
+ return 'down'
+ elif key == b'\r': # Enter key
+ return 'enter'
+ elif key == b'\x1b': # Escape key
+ return 'escape'
+ elif key == b'q':
+ return 'quit'
+ return None
+ else:
+ import termios
+ import tty
+ fd = sys.stdin.fileno()
+ old_settings = termios.tcgetattr(fd)
+ try:
+ tty.setraw(sys.stdin.fileno())
+ key = sys.stdin.read(1)
+
+ if key == '\x1b': # Escape sequence
+ key += sys.stdin.read(2)
+ if key == '\x1b[A': # Up arrow
+ return 'up'
+ elif key == '\x1b[B': # Down arrow
+ return 'down'
+ elif key == '\x1b': # Just escape
+ return 'escape'
+ elif key == '\r' or key == '\n': # Enter key
+ return 'enter'
+ elif key == 'q':
+ return 'quit'
+ return None
+ finally:
+ termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
+ except ImportError:
+ # Fallback to simple input if termios/msvcrt not available
+ return None
+
+
+def display_interactive_team_selection(teams: List[Dict[str, Any]], selected_index: int = 0) -> None:
+ """Display teams with one highlighted for selection"""
+ console = Console()
+
+ # Clear the screen using Rich's method
+ console.clear()
+
+ console.print("🎯 Select a Team (Use ↑↓ arrows, Enter to select, 'q' to skip):\n")
+
+ for i, team in enumerate(teams):
+ team_alias = team.get("team_alias") or "N/A"
+ team_id = team.get("team_id", "N/A")
+ models = team.get("models", [])
+ max_budget = team.get("max_budget")
+
+ # Format models list
+ if models:
+ if len(models) > 3:
+ models_str = ", ".join(models[:3]) + f" (+{len(models) - 3} more)"
+ else:
+ models_str = ", ".join(models)
+ else:
+ models_str = "All models"
+
+ # Format budget
+ budget_str = f"${max_budget}" if max_budget else "Unlimited"
+
+ # Highlight the selected item
+ if i == selected_index:
+ console.print(f"➤ [bold cyan]{team_alias}[/bold cyan] ({team_id})")
+ console.print(f" Models: [yellow]{models_str}[/yellow]")
+ console.print(f" Budget: [blue]{budget_str}[/blue]\n")
+ else:
+ console.print(f" [dim]{team_alias}[/dim] ({team_id})")
+ console.print(f" Models: [dim]{models_str}[/dim]")
+ console.print(f" Budget: [dim]{budget_str}[/dim]\n")
+
+
+def prompt_team_selection(teams: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
+ """Interactive team selection with arrow keys"""
+ if not teams:
+ return None
+
+ selected_index = 0
+
+ try:
+ # Check if we can use interactive mode
+ if not sys.stdin.isatty():
+ # Fallback to simple selection for non-interactive environments
+ return prompt_team_selection_fallback(teams)
+
+ while True:
+ display_interactive_team_selection(teams, selected_index)
+
+ key = get_key_input()
+
+ if key == 'up':
+ selected_index = (selected_index - 1) % len(teams)
+ elif key == 'down':
+ selected_index = (selected_index + 1) % len(teams)
+ elif key == 'enter':
+ selected_team = teams[selected_index]
+ # Clear screen and show selection
+ console = Console()
+ console.clear()
+ click.echo(f"✅ Selected team: {selected_team.get('team_alias', 'N/A')} ({selected_team.get('team_id')})")
+ return selected_team
+ elif key == 'quit' or key == 'escape':
+ # Clear screen
+ console = Console()
+ console.clear()
+ click.echo("ℹ️ Team selection skipped.")
+ return None
+ elif key is None:
+ # If we can't get key input, fall back to simple selection
+ return prompt_team_selection_fallback(teams)
+
+ except KeyboardInterrupt:
+ console = Console()
+ console.clear()
+ click.echo("\n❌ Team selection cancelled.")
+ return None
+ except Exception:
+ # If interactive mode fails, fall back to simple selection
+ return prompt_team_selection_fallback(teams)
+
+
+def prompt_team_selection_fallback(teams: List[Dict[str, Any]]) -> Optional[Dict[str, Any]]:
+ """Fallback team selection for non-interactive environments"""
+ if not teams:
+ return None
+
+ while True:
+ try:
+ choice = click.prompt(
+ "\nSelect a team by entering the index number (or 'skip' to continue without a team)",
+ type=str
+ ).strip()
+
+ if choice.lower() == 'skip':
+ return None
+
+ index = int(choice) - 1
+ if 0 <= index < len(teams):
+ selected_team = teams[index]
+ click.echo(f"\n✅ Selected team: {selected_team.get('team_alias', 'N/A')} ({selected_team.get('team_id')})")
+ return selected_team
+ else:
+ click.echo(f"❌ Invalid selection. Please enter a number between 1 and {len(teams)}")
+ except ValueError:
+ click.echo("❌ Invalid input. Please enter a number or 'skip'")
+ except KeyboardInterrupt:
+ click.echo("\n❌ Team selection cancelled.")
+ return None
+
+
+def update_key_with_team(base_url: str, api_key: str, team_id: str) -> bool:
+ """Update the API key to be associated with the selected team"""
+
+ from litellm.proxy.client import Client
+
+ client = Client(base_url=base_url, api_key=api_key)
+ try:
+ result = client.keys.update(key=api_key, team_id=team_id)
+ click.echo(f"✅ Successfully assigned key to team: {team_id}")
+ return True
+ except requests.exceptions.HTTPError as e:
+ # Bubble up the response text for detailed error info
+ error_msg = e.response.text if e.response else str(e)
+ click.echo(f"❌ Error updating key with team: {error_msg}")
+ return False
+ except Exception as e:
+ click.echo(f"❌ Error updating key with team: {e}")
+ return False
+
# Polling-based authentication - no local server needed
@@ -57,8 +307,6 @@ def login(ctx: click.Context):
"""Login to LiteLLM proxy using SSO authentication"""
import uuid
- import requests
-
from litellm.constants import LITELLM_CLI_SOURCE_IDENTIFIER
from litellm.proxy.client.cli.interface import show_commands
@@ -116,6 +364,36 @@ def login(ctx: click.Context):
click.echo(f"API Key: {api_key[:20]}...")
click.echo("You can now use the CLI without specifying --api-key")
+ # Fetch and display user's teams
+ click.echo("\n" + "="*60)
+ click.echo("📋 Fetching your teams...")
+
+ teams = get_user_teams(
+ base_url=base_url,
+ api_key=api_key,
+ user_id=data.get("user_id"),
+ )
+
+
+ if teams:
+ # Prompt for team selection (will display teams interactively)
+ selected_team = prompt_team_selection(teams)
+
+ if selected_team:
+ team_id = selected_team.get('team_id')
+ if team_id:
+ click.echo(f"\n🔄 Assigning your key to team: {selected_team.get('team_alias', team_id)}")
+ success = update_key_with_team(base_url, api_key, team_id)
+ if success:
+ click.echo(f"✅ Your CLI key is now associated with team: {selected_team.get('team_alias', team_id)}")
+ click.echo(f"🎯 You can now access models: {', '.join(selected_team.get('models', ['All models']))}")
+ else:
+ click.echo("⚠️ Key assignment failed, but you can still use the CLI")
+ else:
+ click.echo("ℹ️ Continuing without team assignment. You can assign a team later using the CLI.")
+ else:
+ click.echo("ℹ️ No teams found. You can create or join teams using the web interface.")
+
# Show available commands after successful login
click.echo("\n" + "="*60)
show_commands()
@@ -171,5 +449,8 @@ def whoami():
if age_hours > 24:
click.echo("⚠️ Warning: Token is more than 24 hours old and may have expired.")
+# Export functions for use by other CLI commands
+__all__ = ['login', 'logout', 'whoami', 'prompt_team_selection']
+
# Export individual commands instead of grouping them
# login, logout, and whoami will be added as top-level commands
\ No newline at end of file
diff --git a/litellm/proxy/client/cli/commands/teams.py b/litellm/proxy/client/cli/commands/teams.py
new file mode 100644
index 00000000000..d4e05c890dc
--- /dev/null
+++ b/litellm/proxy/client/cli/commands/teams.py
@@ -0,0 +1,179 @@
+"""Team management commands for LiteLLM CLI."""
+
+from typing import Any, Dict, List, Optional
+
+import click
+import requests
+from rich.console import Console
+from rich.table import Table
+
+from litellm.proxy.client import Client
+
+
+def teams():
+ """Manage teams and team assignments"""
+ pass
+
+
+def display_teams_table(teams: List[Dict[str, Any]]) -> None:
+ """Display teams in a formatted table"""
+ console = Console()
+
+ if not teams:
+ console.print("❌ No teams found for your user.")
+ return
+
+ table = Table(title="Available Teams")
+ table.add_column("Index", style="cyan", no_wrap=True)
+ table.add_column("Team Alias", style="magenta")
+ table.add_column("Team ID", style="green")
+ table.add_column("Models", style="yellow")
+ table.add_column("Max Budget", style="blue")
+ table.add_column("Role", style="red")
+
+ for i, team in enumerate(teams):
+ team_alias = team.get("team_alias") or "N/A"
+ team_id = team.get("team_id", "N/A")
+ models = team.get("models", [])
+ max_budget = team.get("max_budget")
+
+ # Format models list
+ if models:
+ if len(models) > 3:
+ models_str = ", ".join(models[:3]) + f" (+{len(models) - 3} more)"
+ else:
+ models_str = ", ".join(models)
+ else:
+ models_str = "All models"
+
+ # Format budget
+ budget_str = f"${max_budget}" if max_budget else "Unlimited"
+
+ # Try to determine role (this might vary based on API response structure)
+ role = "Member" # Default role
+ if isinstance(team, dict) and 'members_with_roles' in team and team['members_with_roles']:
+ # This would need to be implemented based on actual API response structure
+ pass
+
+ table.add_row(
+ str(i + 1),
+ team_alias,
+ team_id,
+ models_str,
+ budget_str,
+ role
+ )
+
+ console.print(table)
+
+
+def list(ctx: click.Context):
+ """List teams that you belong to"""
+ client = Client(ctx.obj["base_url"], ctx.obj["api_key"])
+
+ try:
+ # Use list() for simpler response structure (returns array directly)
+ teams = client.teams.list()
+ display_teams_table(teams)
+ except requests.exceptions.HTTPError as e:
+ click.echo(f"Error: HTTP {e.response.status_code}", err=True)
+ try:
+ error_body = e.response.json()
+ click.echo(f"Details: {error_body.get('detail', 'Unknown error')}", err=True)
+ except:
+ click.echo(e.response.text, err=True)
+ raise click.Abort()
+ except Exception as e:
+ click.echo(f"Error: {str(e)}", err=True)
+ raise click.Abort()
+
+
+def available(ctx: click.Context):
+ """List teams that are available to join"""
+ client = Client(ctx.obj["base_url"], ctx.obj["api_key"])
+
+ try:
+ teams = client.teams.get_available()
+ if teams:
+ console = Console()
+ console.print("\n🎯 Available Teams to Join:")
+ display_teams_table(teams)
+ else:
+ click.echo("ℹ️ No available teams to join.")
+ except requests.exceptions.HTTPError as e:
+ click.echo(f"Error: HTTP {e.response.status_code}", err=True)
+ try:
+ error_body = e.response.json()
+ click.echo(f"Details: {error_body.get('detail', 'Unknown error')}", err=True)
+ except:
+ click.echo(e.response.text, err=True)
+ raise click.Abort()
+ except Exception as e:
+ click.echo(f"Error: {str(e)}", err=True)
+ raise click.Abort()
+
+
[email protected]("--team-id", type=str, help="Team ID to assign the key to")
+def assign_key(ctx: click.Context, team_id: Optional[str]):
+ """Assign your current CLI key to a team"""
+ client = Client(ctx.obj["base_url"], ctx.obj["api_key"])
+ api_key = ctx.obj["api_key"]
+
+ if not api_key:
+ click.echo("❌ No API key found. Please login first using 'litellm login'")
+ raise click.Abort()
+
+ try:
+ # If no team_id provided, show teams and let user select
+ if not team_id:
+ teams = client.teams.list()
+
+ if not teams:
+ click.echo("❌ No teams found for your user.")
+ return
+
+ # Use interactive selection from auth module
+ from .auth import prompt_team_selection
+ selected_team = prompt_team_selection(teams)
+
+ if selected_team:
+ team_id = selected_team.get('team_id')
+ else:
+ click.echo("❌ Operation cancelled.")
+ return
+
+ # Update the key with the selected team
+ if team_id:
+ click.echo(f"\n🔄 Assigning your key to team: {team_id}")
+ result = client.keys.update(key=api_key, team_id=team_id)
+ click.echo(f"✅ Successfully assigned key to team: {team_id}")
+
+ # Show team details if available
+ teams = client.teams.list()
+ for team in teams:
+ if team.get('team_id') == team_id:
+ models = team.get('models', [])
+ if models:
+ click.echo(f"🎯 You can now access models: {', '.join(models)}")
+ else:
+ click.echo("🎯 You can now access all available models")
+ break
+
+ except requests.exceptions.HTTPError as e:
+ click.echo(f"Error: HTTP {e.response.status_code}", err=True)
+ try:
+ error_body = e.response.json()
+ click.echo(f"Details: {error_body.get('detail', 'Unknown error')}", err=True)
+ except:
+ click.echo(e.response.text, err=True)
+ raise click.Abort()
+ except Exception as e:
+ click.echo(f"Error: {str(e)}", err=True)
+ raise click.Abort()
diff --git a/litellm/proxy/client/cli/interface.py b/litellm/proxy/client/cli/interface.py
index d3f3a24eb45..78aeb442351 100644
--- a/litellm/proxy/client/cli/interface.py
+++ b/litellm/proxy/client/cli/interface.py
@@ -87,6 +87,7 @@ def show_commands():
("chat", "Interactive chat with models"),
("http", "Make HTTP requests to the proxy"),
("keys", "Manage API keys"),
+ ("teams", "Manage teams and team assignments"),
("users", "Manage users"),
("version", "Show version information"),
("help", "Show this help message"),
diff --git a/litellm/proxy/client/cli/main.py b/litellm/proxy/client/cli/main.py
index fb4a37c3a17..eab9b31482a 100644
--- a/litellm/proxy/client/cli/main.py
+++ b/litellm/proxy/client/cli/main.py
@@ -15,6 +15,7 @@ from .commands.keys import keys
# local imports
from .commands.models import models
+from .commands.teams import teams
from .commands.users import users
from .interface import interactive_shell
@@ -98,6 +99,8 @@ cli.add_command(chat)
cli.add_command(http)
# 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)
diff --git a/litellm/proxy/client/client.py b/litellm/proxy/client/client.py
index 93e877d1563..8ed9a4ff89f 100644
--- a/litellm/proxy/client/client.py
+++ b/litellm/proxy/client/client.py
@@ -1,11 +1,12 @@
from typing import Optional
-from .http_client import HTTPClient
-from .models import ModelsManagementClient
-from .model_groups import ModelGroupsManagementClient
from .chat import ChatClient
-from .keys import KeysManagementClient
from .credentials import CredentialsManagementClient
+from .http_client import HTTPClient
+from .keys import KeysManagementClient
+from .model_groups import ModelGroupsManagementClient
+from .models import ModelsManagementClient
+from .teams import TeamsManagementClient
class Client:
@@ -36,3 +37,4 @@ class Client:
self.chat = ChatClient(base_url=self._base_url, api_key=self._api_key)
self.keys = KeysManagementClient(base_url=self._base_url, api_key=self._api_key)
self.credentials = CredentialsManagementClient(base_url=self._base_url, api_key=self._api_key)
+ self.teams = TeamsManagementClient(base_url=self._base_url, api_key=self._api_key)
diff --git a/litellm/proxy/client/keys.py b/litellm/proxy/client/keys.py
index 8c62eb8e4d0..fc307648a2f 100644
--- a/litellm/proxy/client/keys.py
+++ b/litellm/proxy/client/keys.py
@@ -1,5 +1,7 @@
+from typing import Any, Dict, List, Optional, Union
+
import requests
-from typing import Dict, Any, Optional, Union, List
+
from .exceptions import UnauthorizedError
@@ -221,6 +223,66 @@ class KeysManagementClient:
raise UnauthorizedError(e)
raise
+ def update(
+ self,
+ key: str,
+ models: Optional[List[str]] = None,
+ aliases: Optional[Dict[str, str]] = None,
+ spend: Optional[float] = None,
+ duration: Optional[str] = None,
+ key_alias: Optional[str] = None,
+ team_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Update an existing API key's parameters.
+
+ Args:
+ models: Optional[List[str]] = None,
+ aliases: Optional[Dict[str, str]] = None,
+ spend: Optional[float] = None,
+ duration: Optional[str] = None,
+ key_alias: Optional[str] = None,
+ team_id: Optional[str] = None,
+ user_id: Optional[str] = None,
+
+ Returns:
+ Union[Dict[str, Any], requests.Request]: Either the response from the server or
+ a prepared request object if return_request is True
+
+ Raises:
+ UnauthorizedError: If the request fails with a 401 status code
+ requests.exceptions.RequestException: If the request fails with any other error
+ """
+ url = f"{self._base_url}/key/update"
+
+ data: Dict[str, Any] = {"key": key}
+
+ if key_alias is not None:
+ data["key_alias"] = key_alias
+ if user_id is not None:
+ data["user_id"] = user_id
+ if team_id is not None:
+ data["team_id"] = team_id
+ if models is not None:
+ data["models"] = models
+ if spend is not None:
+ data["spend"] = spend
+ if duration is not None:
+ data["duration"] = duration
+ if aliases is not None:
+ data["aliases"] = aliases
+ request = requests.Request("POST", url, headers=self._get_headers(), json=data)
+ session = requests.Session()
+ try:
+ response = session.send(request.prepare())
+ response.raise_for_status()
+ return response.json()
+ except requests.exceptions.HTTPError as e:
+ if e.response.status_code == 401:
+ raise UnauthorizedError(e)
+ raise
+
def info(self, key: str, return_request: bool = False) -> Union[Dict[str, Any], requests.Request]:
"""
Get information about API keys.
diff --git a/litellm/proxy/client/teams.py b/litellm/proxy/client/teams.py
new file mode 100644
index 00000000000..61ddbe6adae
--- /dev/null
+++ b/litellm/proxy/client/teams.py
@@ -0,0 +1,146 @@
+"""Teams management client for LiteLLM proxy."""
+
+from typing import Any, Dict, List, Optional
+
+import requests
+
+from .exceptions import UnauthorizedError
+
+
+class TeamsManagementClient:
+ """Client for managing teams in LiteLLM proxy."""
+
+ def __init__(self, base_url: str, api_key: Optional[str] = None):
+ """
+ Initialize the TeamsManagementClient.
+
+ Args:
+ base_url (str): The base URL of the LiteLLM proxy server (e.g., "http://localhost:4000")
+ api_key (Optional[str]): API key for authentication. If provided, it will be sent as a Bearer token.
+ """
+ self._base_url = base_url.rstrip("/") # Remove trailing slash if present
+ self._api_key = api_key
+
+ def _get_headers(self) -> Dict[str, str]:
+ """
+ Get the headers for API requests, including authorization if api_key is set.
+
+ Returns:
+ Dict[str, str]: Headers to use for API requests
+ """
+ headers = {"Content-Type": "application/json"}
+ if self._api_key:
+ headers["Authorization"] = f"Bearer {self._api_key}"
+ return headers
+
+ def list(
+ self,
+ user_id: Optional[str] = None,
+ organization_id: Optional[str] = None,
+ ) -> List[Dict[str, Any]]:
+ """
+ List teams that the user belongs to.
+
+ Args:
+ user_id (Optional[str]): Only return teams which this user belongs to
+ organization_id (Optional[str]): Only return teams which belong to this organization
+
+ Returns:
+ List[Dict[str, Any]]: List of team objects
+
+ Raises:
+ requests.exceptions.HTTPError: If the request fails
+ UnauthorizedError: If authentication fails
+ """
+ url = f"{self._base_url}/team/list"
+ params = {}
+ if user_id:
+ params["user_id"] = user_id
+ if organization_id:
+ params["organization_id"] = organization_id
+
+ response = requests.get(url, headers=self._get_headers(), params=params)
+
+ if response.status_code == 401:
+ raise UnauthorizedError("Authentication failed. Check your API key.")
+
+ response.raise_for_status()
+ return response.json()
+
+ def list_v2(
+ self,
+ user_id: Optional[str] = None,
+ organization_id: Optional[str] = None,
+ team_id: Optional[str] = None,
+ team_alias: Optional[str] = None,
+ page: int = 1,
+ page_size: int = 10,
+ sort_by: Optional[str] = None,
+ sort_order: str = "asc",
+ ) -> Dict[str, Any]:
+ """
+ Get a paginated list of teams with filtering and sorting options.
+
+ Args:
+ user_id (Optional[str]): Only return teams which this user belongs to
+ organization_id (Optional[str]): Only return teams which belong to this organization
+ team_id (Optional[str]): Filter teams by exact team_id match
+ team_alias (Optional[str]): Filter teams by partial team_alias match
+ page (int): Page number for pagination
+ page_size (int): Number of teams per page
+ sort_by (Optional[str]): Column to sort by (e.g. 'team_id', 'team_alias', 'created_at')
+ sort_order (str): Sort order ('asc' or 'desc')
+
+ Returns:
+ Dict[str, Any]: Paginated response containing teams and pagination info
+
+ Raises:
+ requests.exceptions.HTTPError: If the request fails
+ UnauthorizedError: If authentication fails
+ """
+ url = f"{self._base_url}/v2/team/list"
+ params = {
+ "page": page,
+ "page_size": page_size,
+ "sort_order": sort_order,
+ }
+
+ if user_id:
+ params["user_id"] = user_id
+ if organization_id:
+ params["organization_id"] = organization_id
+ if team_id:
+ params["team_id"] = team_id
+ if team_alias:
+ params["team_alias"] = team_alias
+ if sort_by:
+ params["sort_by"] = sort_by
+
+ response = requests.get(url, headers=self._get_headers(), params=params)
+
+ if response.status_code == 401:
+ raise UnauthorizedError("Authentication failed. Check your API key.")
+
+ response.raise_for_status()
+ return response.json()
+
+ def get_available(self) -> List[Dict[str, Any]]:
+ """
+ Get list of available teams that the user can join.
+
+ Returns:
+ List[Dict[str, Any]]: List of available team objects
+
+ Raises:
+ requests.exceptions.HTTPError: If the request fails
+ UnauthorizedError: If authentication fails
+ """
+ url = f"{self._base_url}/team/available"
+
+ response = requests.get(url, headers=self._get_headers())
+
+ if response.status_code == 401:
+ raise UnauthorizedError("Authentication failed. Check your API key.")
+
+ response.raise_for_status()
+ return response.json()
diff --git a/litellm/proxy/management_endpoints/ui_sso.py b/litellm/proxy/management_endpoints/ui_sso.py
index 3c9fec3dee2..3828f7318c1 100644
--- a/litellm/proxy/management_endpoints/ui_sso.py
+++ b/litellm/proxy/management_endpoints/ui_sso.py
@@ -67,6 +67,7 @@ from litellm.proxy.utils import (
)
from litellm.secret_managers.main import get_secret_bool, str_to_bool
from litellm.types.proxy.management_endpoints.ui_sso import *
+from litellm.types.proxy.ui_sso import ParsedOpenIDResult
if TYPE_CHECKING:
from fastapi_sso.sso.base import OpenID
@@ -588,17 +589,6 @@ async def auth_callback(request: Request, state: Optional[str] = None): # noqa:
# Check if this is a CLI login (state starts with our CLI prefix)
from litellm.constants import LITELLM_CLI_SESSION_TOKEN_PREFIX
-
- if state and state.startswith(f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:"):
- # Extract the key ID from the state
- key_id = state.split(":", 1)[1]
-
- # Get existing_key from query parameters if provided
- existing_key = request.query_params.get("existing_key")
-
- verbose_proxy_logger.info(f"CLI SSO callback detected for key: {key_id}, existing_key: {existing_key}")
- return await cli_sso_callback(request, key=key_id, existing_key=existing_key)
-
from litellm.proxy._types import LiteLLM_JWTAuth
from litellm.proxy.auth.handle_jwt import JWTHandler
from litellm.proxy.proxy_server import (
@@ -674,6 +664,17 @@ async def auth_callback(request: Request, state: Optional[str] = None): # noqa:
status_code=401,
detail="Result not returned by SSO provider.",
)
+
+
+ if state and state.startswith(f"{LITELLM_CLI_SESSION_TOKEN_PREFIX}:"):
+ # Extract the key ID from the state
+ key_id = state.split(":", 1)[1]
+
+ # Get existing_key from query parameters if provided
+ existing_key = request.query_params.get("existing_key")
+
+ verbose_proxy_logger.info(f"CLI SSO callback detected for key: {key_id}, existing_key: {existing_key}")
+ return await cli_sso_callback(request=request, key=key_id, existing_key=existing_key, result=result)
return await SSOAuthenticationHandler.get_redirect_response_from_openid(
result=result,
@@ -684,7 +685,7 @@ async def auth_callback(request: Request, state: Optional[str] = None): # noqa:
)
-async def _regenerate_cli_key(existing_key: str, new_key: str) -> None:
+async def _regenerate_cli_key(existing_key: str, new_key: str, user_id: Optional[str] = None) -> None:
"""Regenerate an existing CLI key with a new token"""
from litellm.proxy._types import RegenerateKeyRequest, UserAPIKeyAuth
from litellm.proxy.management_endpoints.key_management_endpoints import (
@@ -698,7 +699,8 @@ async def _regenerate_cli_key(existing_key: str, new_key: str) -> None:
regenerate_request = RegenerateKeyRequest(
key=existing_key,
new_key=new_key,
- duration="24hr"
+ duration="24hr",
+ user_id=user_id,
)
await regenerate_key_fn(
@@ -710,7 +712,10 @@ async def _regenerate_cli_key(existing_key: str, new_key: str) -> None:
verbose_proxy_logger.info(f"Regenerated CLI key: {new_key}")
-async def _create_new_cli_key(key: str) -> None:
+async def _create_new_cli_key(
+ key: str,
+ user_id: Optional[str] = None,
+) -> None:
"""Create a new CLI key"""
from litellm.proxy.management_endpoints.key_management_endpoints import (
generate_key_helper_fn,
@@ -725,6 +730,7 @@ async def _create_new_cli_key(key: str) -> None:
aliases={},
config={},
spend=0,
+ user_id=user_id,
team_id="litellm-cli",
table_name="key",
token=key,
@@ -733,7 +739,7 @@ async def _create_new_cli_key(key: str) -> None:
verbose_proxy_logger.info(f"Created new CLI key: {key}")
-async def cli_sso_callback(request: Request, key: Optional[str] = None, existing_key: Optional[str] = None):
+async def cli_sso_callback(request: Request, key: Optional[str] = None, existing_key: Optional[str] = None, result: Optional[Union[OpenID, dict]] = None):
"""CLI SSO callback - regenerates existing CLI key or creates new one"""
verbose_proxy_logger.info(f"CLI SSO callback for key: {key}, existing_key: {existing_key}")
@@ -749,12 +755,22 @@ async def cli_sso_callback(request: Request, key: Optional[str] = None, existing
raise HTTPException(
status_code=500, detail=CommonProxyErrors.db_not_connected_error.value
)
+
+ parsed_openid_result = SSOAuthenticationHandler._get_user_email_and_id_from_result(result=result)
+ verbose_proxy_logger.debug(f"parsed_openid_result: {parsed_openid_result}")
try:
if existing_key:
- await _regenerate_cli_key(existing_key, key)
+ await _regenerate_cli_key(
+ existing_key=existing_key,
+ new_key=key,
+ user_id=parsed_openid_result.get("user_id"),
+ )
else:
- await _create_new_cli_key(key)
+ await _create_new_cli_key(
+ key=key,
+ user_id=parsed_openid_result.get("user_id"),
+ )
# Return success page
from fastapi.responses import HTMLResponse
@@ -774,6 +790,7 @@ async def cli_sso_callback(request: Request, key: Optional[str] = None, existing
@router.get("/sso/cli/poll/{key_id}", tags=["experimental"], include_in_schema=False)
async def cli_poll_key(key_id: str):
"""CLI polling endpoint - checks if key exists in DB"""
+ from litellm.proxy._types import LiteLLM_VerificationToken
from litellm.proxy.proxy_server import prisma_client
if not key_id.startswith("sk-"):
@@ -793,10 +810,11 @@ async def cli_poll_key(key_id: str):
key_obj = await prisma_client.db.litellm_verificationtoken.find_unique(
where={"token": hashed_token}
)
+ key_obj: LiteLLM_VerificationToken = cast(LiteLLM_VerificationToken, key_obj)
if key_obj:
verbose_proxy_logger.info(f"CLI key found: {key_id}")
- return {"status": "ready", "key": key_id}
+ return {"status": "ready", "key": key_id, "user_id": key_obj.user_id}
else:
return {"status": "pending"}
@@ -1315,38 +1333,18 @@ class SSOAuthenticationHandler:
return None
@staticmethod
- async def get_redirect_response_from_openid( # noqa: PLR0915
- result: Union[OpenID, dict, CustomOpenID],
- request: Request,
- received_response: Optional[dict] = None,
+ def _get_user_email_and_id_from_result(
+ result: Optional[Union[OpenID, dict]],
generic_client_id: Optional[str] = None,
- ui_access_mode: Optional[Dict] = None,
- ) -> RedirectResponse:
- import jwt
-
- from litellm.proxy.proxy_server import (
- general_settings,
- generate_key_helper_fn,
- master_key,
- premium_user,
- proxy_logging_obj,
- user_api_key_cache,
- user_custom_sso,
- )
- from litellm.proxy.utils import get_prisma_client_or_throw
- from litellm.types.proxy.ui_sso import ReturnedUITokenObject
-
- prisma_client = get_prisma_client_or_throw(
- "Prisma client is None, connect a database to your proxy"
- )
-
- # User is Authe'd in - generate key for the UI to access Proxy
- verbose_proxy_logger.info(f"SSO callback result: {result}")
-
+ ) -> ParsedOpenIDResult:
+ """
+ Gets the user email and id from the OpenID result after validating the email domain
+ """
user_email: Optional[str] = getattr(result, "email", None)
user_id: Optional[str] = (
getattr(result, "id", None) if result is not None else None
)
+ user_role: Optional[str] = None
if user_email is not None and os.getenv("ALLOWED_EMAIL_DOMAINS") is not None:
email_domain = user_email.split("@")[1]
@@ -1377,6 +1375,46 @@ class SSOAuthenticationHandler:
if user_email is not None and (user_id is None or len(user_id) == 0):
user_id = user_email
+
+ return ParsedOpenIDResult(
+ user_email=user_email,
+ user_id=user_id,
+ user_role=user_role,
+ )
+
+ @staticmethod
+ async def get_redirect_response_from_openid( # noqa: PLR0915
+ result: Union[OpenID, dict, CustomOpenID],
+ request: Request,
+ received_response: Optional[dict] = None,
+ generic_client_id: Optional[str] = None,
+ ui_access_mode: Optional[Dict] = None,
+ ) -> RedirectResponse:
+ import jwt
+
+ from litellm.proxy.proxy_server import (
+ general_settings,
+ generate_key_helper_fn,
+ master_key,
+ premium_user,
+ proxy_logging_obj,
+ user_api_key_cache,
+ user_custom_sso,
+ )
+ from litellm.proxy.utils import get_prisma_client_or_throw
+ from litellm.types.proxy.ui_sso import ReturnedUITokenObject
+
+ prisma_client = get_prisma_client_or_throw(
+ "Prisma client is None, connect a database to your proxy"
+ )
+
+ # User is Authe'd in - generate key for the UI to access Proxy
+ parsed_openid_result = SSOAuthenticationHandler._get_user_email_and_id_from_result(result=result, generic_client_id=generic_client_id)
+ user_email = parsed_openid_result.get("user_email")
+ user_id = parsed_openid_result.get("user_id")
+ user_role = parsed_openid_result.get("user_role")
+ verbose_proxy_logger.info(f"SSO callback result: {result}")
+
user_info = None
user_id_models: List = []
diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yaml
index fdd2e51dfde..addf2443d36 100644
--- a/litellm/proxy/proxy_config.yaml
+++ b/litellm/proxy/proxy_config.yaml
@@ -11,3 +11,15 @@ model_list:
aws_batch_role_arn: arn:aws:iam::888602223428:role/service-role/AmazonBedrockExecutionRoleForAgents_BB9HNW6V4CV
model_info:
mode: batch
+ - model_name: anthropic/*
+ litellm_params:
+ model: anthropic/*
+ api_key: os.environ/ANTHROPIC_API_KEY
+ - model_name: openai/*
+ litellm_params:
+ model: openai/*
+ api_key: os.environ/OPENAI_API_KEY
+ - model_name: gemini/*
+ litellm_params:
+ model: gemini/*
+ api_key: os.environ/GEMINI_API_KEY
diff --git a/litellm/types/proxy/ui_sso.py b/litellm/types/proxy/ui_sso.py
index 0c036274c79..04523e88b1b 100644
--- a/litellm/types/proxy/ui_sso.py
+++ b/litellm/types/proxy/ui_sso.py
@@ -17,3 +17,12 @@ class ReturnedUITokenObject(TypedDict):
auth_header_name: str
disabled_non_admin_personal_key_creation: bool
server_root_path: str # e.g. `/litellm`
+
+
+class ParsedOpenIDResult(TypedDict, total=False):
+ """
+ Parsed OpenID result
+ """
+ user_email: Optional[str]
+ user_id: Optional[str]
+ user_role: Optional[str]
\ No newline at end of file
diff --git a/litellm/utils.py b/litellm/utils.py
index 515b6990eee..ee5f9753943 100644
--- a/litellm/utils.py
+++ b/litellm/utils.py
@@ -59,12 +59,6 @@ import litellm.litellm_core_utils.audio_utils.utils
import litellm.litellm_core_utils.json_validation_rule
import litellm.llms
import litellm.llms.gemini
-# Import cached imports utilities
-from litellm.litellm_core_utils.cached_imports import (
- get_coroutine_checker,
- get_litellm_logging_class,
- get_set_callbacks,
-)
from litellm.caching._internal_lru_cache import lru_cache_wrapper
from litellm.caching.caching import DualCache
from litellm.caching.caching_handler import CachingHandlerResponse, LLMCachingHandler
@@ -87,6 +81,13 @@ from litellm.integrations.custom_logger import CustomLogger
from litellm.integrations.vector_store_integrations.base_vector_store import (
BaseVectorStore,
)
+
+# Import cached imports utilities
+from litellm.litellm_core_utils.cached_imports import (
+ get_coroutine_checker,
+ get_litellm_logging_class,
+ get_set_callbacks,
+)
from litellm.litellm_core_utils.core_helpers import (
map_finish_reason,
process_response_headers,
@@ -228,7 +229,6 @@ from typing import (
get_args,
)
-
from openai import OpenAIError as OriginalError
from litellm.litellm_core_utils.thread_pool_executor import executor
@@ -6422,6 +6422,8 @@ def get_valid_models(
check_provider_endpoint: Optional[bool] = None,
custom_llm_provider: Optional[str] = None,
litellm_params: Optional[LiteLLM_Params] = None,
+ api_key: Optional[str] = None,
+ api_base: Optional[str] = None,
) -> List[str]:
"""
Returns a list of valid LLMs based on the set environment variables
@@ -6429,11 +6431,24 @@ def get_valid_models(
Args:
check_provider_endpoint: If True, will check the provider's endpoint for valid models.
custom_llm_provider: If provided, will only check the provider's endpoint for valid models.
+ api_key: If provided, will use the API key to get valid models.
+ api_base: If provided, will use the API base to get valid models.
Returns:
A list of valid LLMs
"""
try:
+ ################################
+ # init litellm_params
+ #################################
+ if litellm_params is None:
+ litellm_params = LiteLLM_Params(model="")
+ if api_key is not None:
+ litellm_params.api_key = api_key
+ if api_base is not None:
+ litellm_params.api_base = api_base
+ #################################
+
check_provider_endpoint = (
check_provider_endpoint or litellm.check_provider_endpoint
)
diff --git a/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py b/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py
new file mode 100644
index 00000000000..fe78b6ecfe3
--- /dev/null
+++ b/tests/test_litellm/litellm_core_utils/test_cli_token_utils.py
@@ -0,0 +1,69 @@
+"""
+Unit tests for CLI token utilities
+"""
+
+import json
+import os
+import tempfile
+from pathlib import Path
+from unittest.mock import mock_open, patch
+
+import pytest
+
+from litellm.litellm_core_utils.cli_token_utils import get_litellm_gateway_api_key
+
+
+class TestCLITokenUtils:
+ """Test CLI token utility functions"""
+
+ def test_get_litellm_gateway_api_key_success(self):
+ """Test getting CLI API key when token file exists and is valid"""
+ token_data = {
+ 'key': 'sk-test-cli-key-123',
+ 'user_id': 'test-user',
+ 'user_email': '[email protected]',
+ 'timestamp': 1234567890
+ }
+
+ with patch('os.path.exists', return_value=True), \
+ patch('builtins.open', mock_open(read_data=json.dumps(token_data))), \
+ patch('litellm.litellm_core_utils.cli_token_utils.get_cli_token_file_path', return_value='/test/.litellm/token.json'):
+
+ result = get_litellm_gateway_api_key()
+
+ assert result == 'sk-test-cli-key-123'
+
+ def test_get_litellm_gateway_api_key_no_file(self):
+ """Test getting CLI API key when token file doesn't exist"""
+ with patch('os.path.exists', return_value=False), \
+ patch('litellm.litellm_core_utils.cli_token_utils.get_cli_token_file_path', return_value='/test/.litellm/token.json'):
+
+ result = get_litellm_gateway_api_key()
+
+ assert result is None
+
+ def test_get_litellm_gateway_api_key_invalid_json(self):
+ """Test getting CLI API key when token file has invalid JSON"""
+ with patch('os.path.exists', return_value=True), \
+ patch('builtins.open', mock_open(read_data='invalid json')), \
+ patch('litellm.litellm_core_utils.cli_token_utils.get_cli_token_file_path', return_value='/test/.litellm/token.json'):
+
+ result = get_litellm_gateway_api_key()
+
+ assert result is None
+
+ def test_get_litellm_gateway_api_key_no_key_field(self):
+ """Test getting CLI API key when token file exists but has no key field"""
+ token_data = {
+ 'user_id': 'test-user',
+ 'user_email': '[email protected]'
+ # Missing 'key' field
+ }
+
+ with patch('os.path.exists', return_value=True), \
+ patch('builtins.open', mock_open(read_data=json.dumps(token_data))), \
+ patch('litellm.litellm_core_utils.cli_token_utils.get_cli_token_file_path', return_value='/test/.litellm/token.json'):
+
+ result = get_litellm_gateway_api_key()
+
+ assert result is None
diff --git a/tests/test_litellm/test_utils.py b/tests/test_litellm/test_utils.py
index fc7088f4b62..618a2902540 100644
--- a/tests/test_litellm/test_utils.py
+++ b/tests/test_litellm/test_utils.py
@@ -2409,3 +2409,53 @@ def test_model_info_for_vertex_ai_deepseek_model():
assert model_info["input_cost_per_token"] is not None
assert model_info["output_cost_per_token"] is not None
print("vertex deepseek model info", model_info)
+
+
+class TestGetValidModelsWithCLI:
+ """Test get_valid_models function as used in CLI token usage"""
+
+ def test_get_valid_models_with_cli_pattern(self):
+ """Test get_valid_models with litellm_proxy provider and CLI token pattern"""
+
+ # Mock the HTTP request that get_valid_models makes to the proxy
+ mock_response = MagicMock()
+ mock_response.status_code = 200
+ mock_response.json.return_value = {
+ "data": [
+ {"id": "gpt-3.5-turbo", "object": "model"},
+ {"id": "gpt-4", "object": "model"},
+ {"id": "litellm_proxy/gemini/gemini-2.5-flash", "object": "model"},
+ {"id": "claude-3-sonnet", "object": "model"}
+ ]
+ }
+
+ with patch('requests.get', return_value=mock_response) as mock_get:
+ # Test the exact pattern used in cli_token_usage.py
+ result = litellm.get_valid_models(
+ check_provider_endpoint=True,
+ custom_llm_provider="litellm_proxy",
+ api_key="sk-test-cli-key-123",
+ api_base="http://localhost:4000/"
+ )
+
+ # Verify the function returns a list of model names
+ assert isinstance(result, list)
+ assert len(result) == 4
+ assert "gpt-3.5-turbo" in result
+ assert "gpt-4" in result
+ assert "litellm_proxy/gemini/gemini-2.5-flash" in result
+ assert "claude-3-sonnet" in result
+
+ # Verify the HTTP request was made with correct parameters
+ mock_get.assert_called_once()
+ call_args = mock_get.call_args
+
+ # Check that the request was made to the correct endpoint
+ assert "http://localhost:4000/" in call_args[0][0]
+ assert "/v1/models" in call_args[0][0]
+
+ # Check that the API key was included in headers
+ assert "headers" in call_args.kwargs
+ headers = call_args.kwargs["headers"]
+ assert "Authorization" in headers
+ assert "Bearer sk-test-cli-key-123" == headers["Authorization"]