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]

New feature: Add Python client library for LiteLLM Proxy (#10445)

Marc Abramowitz1e8674b611da
diff --git a/litellm/proxy/client/README.md b/litellm/proxy/client/README.md
new file mode 100644
index 00000000000..5f09817aaab
--- /dev/null
+++ b/litellm/proxy/client/README.md
@@ -0,0 +1,223 @@
+# LiteLLM Proxy Client
+
+A Python client library for interacting with the LiteLLM proxy server. This client provides a clean, typed interface for managing models, keys, credentials, and making chat completions.
+
+## Installation
+
+```bash
+pip install litellm
+```
+
+## Quick Start
+
+```python
+from litellm.proxy.client import Client
+
+# Initialize the client
+client = Client(
+ base_url="http://localhost:4000", # Your LiteLLM proxy server URL
+ api_key="sk-api-key" # Optional: API key for authentication
+)
+
+# Make a chat completion request
+response = client.chat.completions.create(
+ model="gpt-3.5-turbo",
+ messages=[
+ {"role": "user", "content": "Hello, how are you?"}
+ ]
+)
+print(response.choices[0].message.content)
+```
+
+## Features
+
+The client is organized into several resource clients for different functionality:
+
+- `chat`: Chat completions
+- `models`: Model management
+- `model_groups`: Model group management
+- `keys`: API key management
+- `credentials`: Credential management
+
+## Chat Completions
+
+Make chat completion requests to your LiteLLM proxy:
+
+```python
+# Basic chat completion
+response = client.chat.completions.create(
+ model="gpt-4",
+ messages=[
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "What's the capital of France?"}
+ ]
+)
+
+# Stream responses
+for chunk in client.chat.completions.create(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "Tell me a story"}],
+ stream=True
+):
+ print(chunk.choices[0].delta.content or "", end="")
+```
+
+## Model Management
+
+Manage available models on your proxy:
+
+```python
+# List available models
+models = client.models.list()
+
+# Add a new model
+client.models.add(
+ model_name="gpt-4",
+ litellm_params={
+ "api_key": "your-openai-key",
+ "api_base": "https://api.openai.com/v1"
+ }
+)
+
+# Delete a model
+client.models.delete(model_name="gpt-4")
+```
+
+## API Key Management
+
+Manage virtual API keys:
+
+```python
+# Generate a new API key
+key = client.keys.generate(
+ models=["gpt-4", "gpt-3.5-turbo"],
+ aliases={"gpt4": "gpt-4"},
+ duration="24h",
+ key_alias="my-key",
+ team_id="team123"
+)
+
+# List all keys
+keys = client.keys.list(
+ page=1,
+ size=10,
+ return_full_object=True
+)
+
+# Delete keys
+client.keys.delete(
+ keys=["sk-key1", "sk-key2"],
+ key_aliases=["alias1", "alias2"]
+)
+```
+
+## Credential Management
+
+Manage model credentials:
+
+```python
+# Create new credentials
+client.credentials.create(
+ credential_name="azure1",
+ credential_info={"api_type": "azure"},
+ credential_values={
+ "api_key": "your-azure-key",
+ "api_base": "https://example.azure.openai.com"
+ }
+)
+
+# List all credentials
+credentials = client.credentials.list()
+
+# Get a specific credential
+credential = client.credentials.get(credential_name="azure1")
+
+# Delete credentials
+client.credentials.delete(credential_name="azure1")
+```
+
+## Model Groups
+
+Manage model groups for load balancing and fallbacks:
+
+```python
+# Create a model group
+client.model_groups.create(
+ name="gpt4-group",
+ models=[
+ {"model_name": "gpt-4", "litellm_params": {"api_key": "key1"}},
+ {"model_name": "gpt-4-backup", "litellm_params": {"api_key": "key2"}}
+ ]
+)
+
+# List model groups
+groups = client.model_groups.list()
+
+# Delete a model group
+client.model_groups.delete(name="gpt4-group")
+```
+
+## Error Handling
+
+The client provides clear error handling with custom exceptions:
+
+```python
+from litellm.proxy.client.exceptions import UnauthorizedError
+
+try:
+ response = client.chat.completions.create(
+ model="gpt-4",
+ messages=[{"role": "user", "content": "Hello"}]
+ )
+except UnauthorizedError as e:
+ print("Authentication failed:", e)
+except Exception as e:
+ print("Request failed:", e)
+```
+
+## Advanced Usage
+
+### Request Customization
+
+All methods support returning the raw request object for inspection or modification:
+
+```python
+# Get the prepared request without sending it
+request = client.models.list(return_request=True)
+print(request.method) # GET
+print(request.url) # http://localhost:8000/models
+print(request.headers) # {'Content-Type': 'application/json', ...}
+```
+
+### Pagination
+
+Methods that return lists support pagination:
+
+```python
+# Get the first page of keys
+page1 = client.keys.list(page=1, size=10)
+
+# Get the second page
+page2 = client.keys.list(page=2, size=10)
+```
+
+### Filtering
+
+Many list methods support filtering:
+
+```python
+# Filter keys by user and team
+keys = client.keys.list(
+ user_id="user123",
+ team_id="team456",
+ include_team_keys=True
+)
+```
+
+## Contributing
+
+Contributions are welcome! Please check out our [contributing guidelines](../../CONTRIBUTING.md) for details.
+
+## License
+
+This project is licensed under the MIT License - see the [LICENSE](../../LICENSE) file for details.
\ No newline at end of file
diff --git a/litellm/proxy/client/__init__.py b/litellm/proxy/client/__init__.py
new file mode 100644
index 00000000000..6eb8cd1d426
--- /dev/null
+++ b/litellm/proxy/client/__init__.py
@@ -0,0 +1,7 @@
+from .client import Client
+from .chat import ChatClient
+from .models import ModelsManagementClient
+from .model_groups import ModelGroupsManagementClient
+from .exceptions import UnauthorizedError
+
+__all__ = ["Client", "ChatClient", "ModelsManagementClient", "ModelGroupsManagementClient", "UnauthorizedError"]
diff --git a/litellm/proxy/client/chat.py b/litellm/proxy/client/chat.py
new file mode 100644
index 00000000000..bf5ddbe85d9
--- /dev/null
+++ b/litellm/proxy/client/chat.py
@@ -0,0 +1,101 @@
+import requests
+from typing import List, Dict, Any, Optional, Union
+from .exceptions import UnauthorizedError
+
+
+class ChatClient:
+ def __init__(self, base_url: str, api_key: Optional[str] = None):
+ """
+ Initialize the ChatClient.
+
+ Args:
+ base_url (str): The base URL of the LiteLLM proxy server (e.g., "http://localhost:8000")
+ 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 completions(
+ self,
+ model: str,
+ messages: List[Dict[str, str]],
+ temperature: Optional[float] = None,
+ top_p: Optional[float] = None,
+ n: Optional[int] = None,
+ max_tokens: Optional[int] = None,
+ presence_penalty: Optional[float] = None,
+ frequency_penalty: Optional[float] = None,
+ user: Optional[str] = None,
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Create a chat completion.
+
+ Args:
+ model (str): The model to use for completion
+ messages (List[Dict[str, str]]): The messages to generate a completion for
+ temperature (Optional[float]): Sampling temperature between 0 and 2
+ top_p (Optional[float]): Nucleus sampling parameter between 0 and 1
+ n (Optional[int]): Number of completions to generate
+ max_tokens (Optional[int]): Maximum number of tokens to generate
+ presence_penalty (Optional[float]): Presence penalty between -2.0 and 2.0
+ frequency_penalty (Optional[float]): Frequency penalty between -2.0 and 2.0
+ user (Optional[str]): Unique identifier for the end user
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ Returns:
+ Union[Dict[str, Any], requests.Request]: Either the completion 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}/chat/completions"
+
+ # Build request data with required fields
+ data: Dict[str, Any] = {"model": model, "messages": messages}
+
+ # Add optional parameters if provided
+ if temperature is not None:
+ data["temperature"] = temperature
+ if top_p is not None:
+ data["top_p"] = top_p
+ if n is not None:
+ data["n"] = n
+ if max_tokens is not None:
+ data["max_tokens"] = max_tokens
+ if presence_penalty is not None:
+ data["presence_penalty"] = presence_penalty
+ if frequency_penalty is not None:
+ data["frequency_penalty"] = frequency_penalty
+ if user is not None:
+ data["user"] = user
+
+ request = requests.Request("POST", url, headers=self._get_headers(), json=data)
+
+ if return_request:
+ return request
+
+ # Prepare and send the request
+ 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
diff --git a/litellm/proxy/client/client.py b/litellm/proxy/client/client.py
new file mode 100644
index 00000000000..b4d0d77ffe4
--- /dev/null
+++ b/litellm/proxy/client/client.py
@@ -0,0 +1,28 @@
+from typing import Optional
+from .models import ModelsManagementClient
+from .model_groups import ModelGroupsManagementClient
+from .chat import ChatClient
+from .keys import KeysManagementClient
+from .credentials import CredentialsManagementClient
+
+
+class Client:
+ """Main client for interacting with the LiteLLM proxy API."""
+
+ def __init__(self, base_url: str, api_key: Optional[str] = None):
+ """
+ Initialize the LiteLLM proxy client.
+
+ Args:
+ base_url (str): The base URL of the LiteLLM proxy server (e.g., "http://localhost:8000")
+ 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
+
+ # Initialize resource clients
+ self.models = ModelsManagementClient(base_url=self._base_url, api_key=self._api_key)
+ self.model_groups = ModelGroupsManagementClient(base_url=self._base_url, api_key=self._api_key)
+ 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)
diff --git a/litellm/proxy/client/credentials.py b/litellm/proxy/client/credentials.py
new file mode 100644
index 00000000000..e0b41a91326
--- /dev/null
+++ b/litellm/proxy/client/credentials.py
@@ -0,0 +1,185 @@
+import requests
+from typing import Dict, Any, Optional, Union
+
+from .exceptions import UnauthorizedError
+
+
+class CredentialsManagementClient:
+ def __init__(self, base_url: str, api_key: Optional[str] = None):
+ """
+ Initialize the CredentialsManagementClient.
+
+ Args:
+ base_url (str): The base URL of the LiteLLM proxy server (e.g., "http://localhost:8000")
+ 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,
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ List all credentials.
+
+ Args:
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ 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}/credentials"
+
+ request = requests.Request("GET", url, headers=self._get_headers())
+
+ if return_request:
+ return request
+
+ 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 create(
+ self,
+ credential_name: str,
+ credential_info: Dict[str, Any],
+ credential_values: Dict[str, Any],
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Create a new credential.
+
+ Args:
+ credential_name (str): Name of the credential
+ credential_info (Dict[str, Any]): Additional information about the credential
+ credential_values (Dict[str, Any]): Values for the credential
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ 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}/credentials"
+
+ data = {
+ "credential_name": credential_name,
+ "credential_info": credential_info,
+ "credential_values": credential_values,
+ }
+
+ request = requests.Request("POST", url, headers=self._get_headers(), json=data)
+
+ if return_request:
+ return request
+
+ 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 delete(
+ self,
+ credential_name: str,
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Delete a credential by name.
+
+ Args:
+ credential_name (str): Name of the credential to delete
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ 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}/credentials/{credential_name}"
+
+ request = requests.Request("DELETE", url, headers=self._get_headers())
+
+ if return_request:
+ return request
+
+ 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 get(
+ self,
+ credential_name: str,
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Get a credential by name.
+
+ Args:
+ credential_name (str): Name of the credential to retrieve
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ 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}/credentials/by_name/{credential_name}"
+
+ request = requests.Request("GET", url, headers=self._get_headers())
+
+ if return_request:
+ return request
+
+ 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
diff --git a/litellm/proxy/client/exceptions.py b/litellm/proxy/client/exceptions.py
new file mode 100644
index 00000000000..4975fb84525
--- /dev/null
+++ b/litellm/proxy/client/exceptions.py
@@ -0,0 +1,17 @@
+import requests
+
+
+class UnauthorizedError(Exception):
+ """Exception raised when the API returns a 401 Unauthorized response."""
+
+ def __init__(self, orig_exception: requests.exceptions.HTTPError):
+ self.orig_exception = orig_exception
+ super().__init__(str(orig_exception))
+
+
+class NotFoundError(Exception):
+ """Exception raised when the API returns a 404 Not Found response or indicates a resource was not found."""
+
+ def __init__(self, orig_exception: requests.exceptions.HTTPError):
+ self.orig_exception = orig_exception
+ super().__init__(str(orig_exception))
diff --git a/litellm/proxy/client/keys.py b/litellm/proxy/client/keys.py
new file mode 100644
index 00000000000..3628dfd59f7
--- /dev/null
+++ b/litellm/proxy/client/keys.py
@@ -0,0 +1,222 @@
+import requests
+from typing import Dict, Any, Optional, Union, List
+from .exceptions import UnauthorizedError
+
+
+class KeysManagementClient:
+ def __init__(self, base_url: str, api_key: Optional[str] = None):
+ """
+ Initialize the KeysManagementClient.
+
+ Args:
+ base_url (str): The base URL of the LiteLLM proxy server (e.g., "http://localhost:8000")
+ 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,
+ page: Optional[int] = None,
+ size: Optional[int] = None,
+ user_id: Optional[str] = None,
+ team_id: Optional[str] = None,
+ organization_id: Optional[str] = None,
+ key_hash: Optional[str] = None,
+ key_alias: Optional[str] = None,
+ return_full_object: Optional[bool] = None,
+ include_team_keys: Optional[bool] = None,
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ List all API keys with optional filtering and pagination.
+
+ Args:
+ page (Optional[int]): Page number for pagination
+ size (Optional[int]): Number of items per page
+ user_id (Optional[str]): Filter keys by user ID
+ team_id (Optional[str]): Filter keys by team ID
+ organization_id (Optional[str]): Filter keys by organization ID
+ key_hash (Optional[str]): Filter by specific key hash
+ key_alias (Optional[str]): Filter by key alias
+ return_full_object (Optional[bool]): Whether to return the full key object
+ include_team_keys (Optional[bool]): Whether to include team keys in the response
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ Returns:
+ Union[Dict[str, Any], requests.Request]: Either the response from the server or
+ a prepared request object if return_request is True. The response contains a list
+ of API keys with their configurations.
+
+ 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/list"
+ params: Dict[str, Any] = {}
+
+ # Add optional query parameters
+ if page is not None:
+ params["page"] = page
+ if size is not None:
+ params["size"] = size
+ if user_id is not None:
+ params["user_id"] = user_id
+ if team_id is not None:
+ params["team_id"] = team_id
+ if organization_id is not None:
+ params["organization_id"] = organization_id
+ if key_hash is not None:
+ params["key_hash"] = key_hash
+ if key_alias is not None:
+ params["key_alias"] = key_alias
+ if return_full_object is not None:
+ params["return_full_object"] = str(return_full_object).lower()
+ if include_team_keys is not None:
+ params["include_team_keys"] = str(include_team_keys).lower()
+
+ request = requests.Request("GET", url, headers=self._get_headers(), params=params)
+
+ if return_request:
+ return request
+
+ 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 generate(
+ self,
+ 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,
+ budget_id: Optional[str] = None,
+ config: Optional[Dict[str, Any]] = None,
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Generate an API key based on the provided data.
+
+ Docs: https://docs.litellm.ai/docs/proxy/virtual_keys
+
+ Args:
+ models (Optional[List[str]]): List of allowed models for this key
+ aliases (Optional[Dict[str, str]]): Model alias mappings
+ spend (Optional[float]): Maximum spend limit for this key
+ duration (Optional[str]): Duration for which the key is valid (e.g. "24h", "7d")
+ key_alias (Optional[str]): Alias/name for the key for easier identification
+ team_id (Optional[str]): Team ID to associate the key with
+ user_id (Optional[str]): User ID to associate the key with
+ budget_id (Optional[str]): Budget ID to associate the key with
+ config (Optional[Dict[str, Any]]): Additional configuration parameters
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ 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/generate"
+
+ data: Dict[str, Any] = {}
+ if models is not None:
+ data["models"] = models
+ if aliases is not None:
+ data["aliases"] = aliases
+ if spend is not None:
+ data["spend"] = spend
+ if duration is not None:
+ data["duration"] = duration
+ if key_alias is not None:
+ data["key_alias"] = key_alias
+ if team_id is not None:
+ data["team_id"] = team_id
+ if user_id is not None:
+ data["user_id"] = user_id
+ if budget_id is not None:
+ data["budget_id"] = budget_id
+ if config is not None:
+ data["config"] = config
+
+ request = requests.Request("POST", url, headers=self._get_headers(), json=data)
+
+ if return_request:
+ return request
+
+ 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 delete(
+ self,
+ keys: Optional[List[str]] = None,
+ key_aliases: Optional[List[str]] = None,
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Delete existing keys
+
+ Args:
+ keys (List[str]): List of API keys to delete
+ key_aliases (List[str]): List of key aliases to delete
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ 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/delete"
+
+ data = {
+ "keys": keys,
+ "key_aliases": key_aliases,
+ }
+
+ request = requests.Request("POST", url, headers=self._get_headers(), json=data)
+
+ if return_request:
+ return request
+
+ 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
diff --git a/litellm/proxy/client/model_groups.py b/litellm/proxy/client/model_groups.py
new file mode 100644
index 00000000000..2be6e10e542
--- /dev/null
+++ b/litellm/proxy/client/model_groups.py
@@ -0,0 +1,60 @@
+import requests
+from typing import List, Dict, Any, Optional, Union
+from .exceptions import UnauthorizedError
+
+
+class ModelGroupsManagementClient:
+ def __init__(self, base_url: str, api_key: Optional[str] = None):
+ """
+ Initialize the ModelGroupsManagementClient.
+
+ Args:
+ base_url (str): The base URL of the LiteLLM proxy server (e.g., "http://localhost:8000")
+ 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 = {}
+ if self._api_key:
+ headers["Authorization"] = f"Bearer {self._api_key}"
+ return headers
+
+ def info(self, return_request: bool = False) -> Union[List[Dict[str, Any]], requests.Request]:
+ """
+ Get detailed information about all model groups from the server.
+
+ Args:
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ Returns:
+ Union[List[Dict[str, Any]], requests.Request]: Either a list of model group information dictionaries
+ 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}/model_group/info"
+ request = requests.Request("GET", url, headers=self._get_headers())
+
+ if return_request:
+ return request
+
+ # Prepare and send the request
+ session = requests.Session()
+ try:
+ response = session.send(request.prepare())
+ response.raise_for_status()
+ return response.json()["data"]
+ except requests.exceptions.HTTPError as e:
+ if e.response.status_code == 401:
+ raise UnauthorizedError(e)
+ raise
diff --git a/litellm/proxy/client/models.py b/litellm/proxy/client/models.py
new file mode 100644
index 00000000000..7943d25b998
--- /dev/null
+++ b/litellm/proxy/client/models.py
@@ -0,0 +1,287 @@
+import requests
+from typing import List, Dict, Any, Optional, Union
+from .exceptions import UnauthorizedError, NotFoundError
+
+
+class ModelsManagementClient:
+ def __init__(self, base_url: str, api_key: Optional[str] = None):
+ """
+ Initialize the ModelsManagementClient.
+
+ Args:
+ base_url (str): The base URL of the LiteLLM proxy server (e.g., "http://localhost:8000")
+ 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 = {}
+ if self._api_key:
+ headers["Authorization"] = f"Bearer {self._api_key}"
+ return headers
+
+ def list(self, return_request: bool = False) -> Union[List[Dict[str, Any]], requests.Request]:
+ """
+ Get the list of models supported by the server.
+
+ Args:
+ return_request (bool): If True, returns the prepared request object instead of executing it.
+ Useful for inspection or modification before sending.
+
+ Returns:
+ Union[List[Dict[str, Any]], requests.Request]: Either a list of model information dictionaries
+ 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}/models"
+ request = requests.Request("GET", url, headers=self._get_headers())
+
+ if return_request:
+ return request
+
+ # Prepare and send the request
+ session = requests.Session()
+ try:
+ response = session.send(request.prepare())
+ response.raise_for_status()
+ return response.json()["data"]
+ except requests.exceptions.HTTPError as e:
+ if e.response.status_code == 401:
+ raise UnauthorizedError(e)
+ raise
+
+ def new(
+ self,
+ model_name: str,
+ model_params: Dict[str, Any],
+ model_info: Optional[Dict[str, Any]] = None,
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Add a new model to the proxy.
+
+ Args:
+ model_name (str): Name of the model to add
+ model_params (Dict[str, Any]): Parameters for the model (e.g., model type, api_base, api_key)
+ model_info (Optional[Dict[str, Any]]): Additional information about the model
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ 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}/model/new"
+
+ data = {
+ "model_name": model_name,
+ "litellm_params": model_params,
+ }
+ if model_info:
+ data["model_info"] = model_info
+
+ request = requests.Request("POST", url, headers=self._get_headers(), json=data)
+
+ if return_request:
+ return request
+
+ # Prepare and send the request
+ 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 delete(self, model_id: str, return_request: bool = False) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Delete a model from the proxy.
+
+ Args:
+ model_id (str): ID of the model to delete (e.g., "2f23364f-4579-4d79-a43a-2d48dd551c2e")
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ 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
+ NotFoundError: If the request fails with a 404 status code or indicates the model was not found
+ requests.exceptions.RequestException: If the request fails with any other error
+ """
+ url = f"{self._base_url}/model/delete"
+ data = {"id": model_id}
+
+ request = requests.Request("POST", url, headers=self._get_headers(), json=data)
+
+ if return_request:
+ return request
+
+ # Prepare and send the request
+ 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)
+ if e.response.status_code == 404 or "not found" in e.response.text.lower():
+ raise NotFoundError(e)
+ raise
+
+ def get(
+ self, model_id: Optional[str] = None, model_name: Optional[str] = None, return_request: bool = False
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Get information about a specific model by its ID or name.
+
+ Args:
+ model_id (Optional[str]): ID of the model to retrieve
+ model_name (Optional[str]): Name of the model to retrieve
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ Returns:
+ Union[Dict[str, Any], requests.Request]: Either the model information from the server or
+ a prepared request object if return_request is True
+
+ Raises:
+ ValueError: If neither model_id nor model_name is provided, or if both are provided
+ UnauthorizedError: If the request fails with a 401 status code
+ NotFoundError: If the model is not found
+ requests.exceptions.RequestException: If the request fails with any other error
+ """
+ if (model_id is None and model_name is None) or (model_id is not None and model_name is not None):
+ raise ValueError("Exactly one of model_id or model_name must be provided")
+
+ # If return_request is True, delegate to info
+ if return_request:
+ result = self.info(return_request=True)
+ assert isinstance(result, requests.Request)
+ return result
+
+ # Get all models and filter
+ models = self.info()
+ assert isinstance(models, List)
+
+ # Find the matching model
+ for model in models:
+ if (model_id and model.get("model_info", {}).get("id") == model_id) or (
+ model_name and model.get("model_name") == model_name
+ ):
+ return model
+
+ # If we get here, no model was found
+ if model_id:
+ msg = f"Model with id={model_id} not found"
+ elif model_name:
+ msg = f"Model with model_name={model_name} not found"
+ else:
+ msg = "Unknown error trying to find model"
+ raise NotFoundError(
+ requests.exceptions.HTTPError(
+ msg,
+ response=requests.Response(), # Empty response since we didn't make a direct request
+ )
+ )
+
+ def info(self, return_request: bool = False) -> Union[List[Dict[str, Any]], requests.Request]:
+ """
+ Get detailed information about all models from the server.
+
+ Args:
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ Returns:
+ Union[List[Dict[str, Any]], requests.Request]: Either a list of model information dictionaries
+ 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}/v1/model/info"
+ request = requests.Request("GET", url, headers=self._get_headers())
+
+ if return_request:
+ return request
+
+ # Prepare and send the request
+ session = requests.Session()
+ try:
+ response = session.send(request.prepare())
+ response.raise_for_status()
+ return response.json()["data"]
+ except requests.exceptions.HTTPError as e:
+ if e.response.status_code == 401:
+ raise UnauthorizedError(e)
+ raise
+
+ def update(
+ self,
+ model_id: str,
+ model_params: Dict[str, Any],
+ model_info: Optional[Dict[str, Any]] = None,
+ return_request: bool = False,
+ ) -> Union[Dict[str, Any], requests.Request]:
+ """
+ Update an existing model's configuration.
+
+ Args:
+ model_id (str): ID of the model to update
+ model_params (Dict[str, Any]): New parameters for the model (e.g., model type, api_base, api_key)
+ model_info (Optional[Dict[str, Any]]): Additional information about the model
+ return_request (bool): If True, returns the prepared request object instead of executing it
+
+ 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
+ NotFoundError: If the model is not found
+ requests.exceptions.RequestException: If the request fails with any other error
+ """
+ url = f"{self._base_url}/model/update"
+
+ data = {
+ "id": model_id,
+ "litellm_params": model_params,
+ }
+ if model_info:
+ data["model_info"] = model_info
+
+ request = requests.Request("POST", url, headers=self._get_headers(), json=data)
+
+ if return_request:
+ return request
+
+ # Prepare and send the request
+ 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)
+ if e.response.status_code == 404 or "not found" in e.response.text.lower():
+ raise NotFoundError(e)
+ raise
diff --git a/poetry.lock b/poetry.lock
index 70bfeacc681..bb0f00d5715 100644
--- a/poetry.lock
+++ b/poetry.lock
@@ -1,4 +1,4 @@
-# This file is automatically @generated by Poetry 2.1.2 and should not be changed by hand.
+# This file is automatically @generated by Poetry 2.1.1 and should not be changed by hand.
[[package]]
name = "aiohappyeyeballs"
@@ -1063,7 +1063,7 @@ google-auth = ">=2.14.1,<3.0.0"
googleapis-common-protos = ">=1.56.2,<2.0.0"
grpcio = [
{version = ">=1.49.1,<2.0dev", optional = true, markers = "python_version >= \"3.11\" and extra == \"grpc\""},
- {version = ">=1.33.2,<2.0dev", optional = true, markers = "python_version < \"3.11\" and extra == \"grpc\""},
+ {version = ">=1.33.2,<2.0dev", optional = true, markers = "extra == \"grpc\""},
]
grpcio-status = [
{version = ">=1.49.1,<2.0.dev0", optional = true, markers = "python_version >= \"3.11\" and extra == \"grpc\""},
@@ -1927,8 +1927,8 @@ files = [
[package.dependencies]
numpy = [
{version = ">=1.23.3", markers = "python_version >= \"3.11\""},
- {version = ">1.20"},
- {version = ">=1.21.2", markers = "python_version >= \"3.10\""},
+ {version = ">=1.21.2", markers = "python_version == \"3.10\""},
+ {version = ">1.20", markers = "python_version < \"3.10\""},
{version = ">=1.26.0", markers = "python_version >= \"3.12\""},
]
@@ -2171,7 +2171,7 @@ description = "Fundamental package for array computing in Python"
optional = true
python-versions = ">=3.9"
groups = ["main"]
-markers = "python_version >= \"3.9\" and extra == \"extra-proxy\" and python_version < \"3.12\""
+markers = "(python_version == \"3.11\" or python_version == \"3.10\" or python_version == \"3.9\") and extra == \"extra-proxy\""
files = [
{file = "numpy-1.26.4-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:9ff0f4f29c51e2803569d7a51c2304de5554655a60c5d776e35b4a41413830d0"},
{file = "numpy-1.26.4-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:2e4ee3380d6de9c9ec04745830fd9e2eccb3e6cf790d39d7b98ffd19b0dd754a"},
@@ -3490,6 +3490,24 @@ urllib3 = ">=1.21.1,<3"
socks = ["PySocks (>=1.5.6,!=1.5.7)"]
use-chardet-on-py3 = ["chardet (>=3.0.2,<6)"]
+[[package]]
+name = "requests-mock"
+version = "1.12.1"
+description = "Mock out responses from the requests package"
+optional = false
+python-versions = ">=3.5"
+groups = ["dev"]
+files = [
+ {file = "requests-mock-1.12.1.tar.gz", hash = "sha256:e9e12e333b525156e82a3c852f22016b9158220d2f47454de9cae8a77d371401"},
+ {file = "requests_mock-1.12.1-py2.py3-none-any.whl", hash = "sha256:b1e37054004cdd5e56c84454cc7df12b25f90f382159087f4b6915aaeef39563"},
+]
+
+[package.dependencies]
+requests = ">=2.22,<3"
+
+[package.extras]
+fixture = ["fixtures"]
+
[[package]]
name = "resend"
version = "0.8.0"
@@ -4605,4 +4623,4 @@ proxy = ["PyJWT", "apscheduler", "backoff", "boto3", "cryptography", "fastapi",
[metadata]
lock-version = "2.1"
python-versions = ">=3.8.1,<4.0, !=3.9.7"
-content-hash = "541574d0a1ec192c57c615843e344193881718902bc4db0bb43d5530d07f2add"
+content-hash = "ba7691ffdf305d212bf661fbe0f2a6919043852d993721189c6b7b92d4a127c0"
diff --git a/pyproject.toml b/pyproject.toml
index 416c18350cd..acb418738d0 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -101,6 +101,7 @@ mypy = "^1.0"
pytest = "^7.4.3"
pytest-mock = "^3.12.0"
pytest-asyncio = "^0.21.1"
+requests-mock = "^1.12.1"
respx = "^0.22.0"
ruff = "^0.1.0"
types-requests = "*"
diff --git a/tests/litellm/proxy/client/test_chat.py b/tests/litellm/proxy/client/test_chat.py
new file mode 100644
index 00000000000..95646e6a26b
--- /dev/null
+++ b/tests/litellm/proxy/client/test_chat.py
@@ -0,0 +1,150 @@
+import pytest
+import requests
+from litellm.proxy.client.chat import ChatClient
+from litellm.proxy.client.exceptions import UnauthorizedError
+
+
+def base_url():
+ return "http://localhost:8000"
+
+
+def api_key():
+ return "test-api-key"
+
+
+def client(base_url, api_key):
+ return ChatClient(base_url=base_url, api_key=api_key)
+
+
+def sample_messages():
+ return [
+ {"role": "system", "content": "You are a helpful assistant."},
+ {"role": "user", "content": "Name 3 countries"},
+ ]
+
+
+def test_client_initialization(base_url, api_key):
+ """Test that the ChatClient is properly initialized"""
+ client = ChatClient(base_url=base_url, api_key=api_key)
+
+ assert client._base_url == base_url
+ assert client._api_key == api_key
+
+
+def test_client_initialization_strips_trailing_slash():
+ """Test that the client properly strips trailing slashes from base_url during initialization"""
+ base_url = "http://localhost:8000/////"
+ client = ChatClient(base_url=base_url)
+
+ assert client._base_url == "http://localhost:8000"
+
+
+def test_client_without_api_key(base_url):
+ """Test that the client works without an API key"""
+ client = ChatClient(base_url=base_url)
+
+ assert client._api_key is None
+
+
+def test_completions_request_creation(client, base_url, api_key, sample_messages):
+ """Test that completions creates a request with correct URL, headers, and body"""
+ request = client.completions(
+ model="gpt-4", messages=sample_messages, temperature=0.7, max_tokens=100, return_request=True
+ )
+
+ # Check request method and URL
+ assert request.method == "POST"
+ assert request.url == f"{base_url}/chat/completions"
+
+ # Check headers
+ assert request.headers["Content-Type"] == "application/json"
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+ # Check request body
+ assert request.json == {"model": "gpt-4", "messages": sample_messages, "temperature": 0.7, "max_tokens": 100}
+
+
+def test_completions_minimal_request(client, sample_messages):
+ """Test that completions works with only required parameters"""
+ request = client.completions(model="gpt-4", messages=sample_messages, return_request=True)
+
+ # Check request body has only required fields
+ assert request.json == {"model": "gpt-4", "messages": sample_messages}
+
+
+def test_completions_all_parameters(client, sample_messages):
+ """Test that completions accepts all optional parameters"""
+ request = client.completions(
+ model="gpt-4",
+ messages=sample_messages,
+ temperature=0.7,
+ top_p=0.9,
+ n=2,
+ max_tokens=100,
+ presence_penalty=0.5,
+ frequency_penalty=-0.5,
+ user="test-user",
+ return_request=True,
+ )
+
+ # Check all parameters are included in request body
+ assert request.json == {
+ "model": "gpt-4",
+ "messages": sample_messages,
+ "temperature": 0.7,
+ "top_p": 0.9,
+ "n": 2,
+ "max_tokens": 100,
+ "presence_penalty": 0.5,
+ "frequency_penalty": -0.5,
+ "user": "test-user",
+ }
+
+
+def test_completions_mock_response(client, sample_messages, requests_mock):
+ """Test completions with a mocked successful response"""
+ mock_response = {
+ "id": "chatcmpl-123",
+ "object": "chat.completion",
+ "created": 1677858242,
+ "model": "gpt-4",
+ "usage": {"prompt_tokens": 13, "completion_tokens": 7, "total_tokens": 20},
+ "choices": [
+ {
+ "message": {"role": "assistant", "content": "Hello! How can I help you today?"},
+ "finish_reason": "stop",
+ "index": 0,
+ }
+ ],
+ }
+
+ # Mock the POST request
+ requests_mock.post(f"{client._base_url}/chat/completions", json=mock_response)
+
+ response = client.completions(model="gpt-4", messages=sample_messages)
+
+ assert response == mock_response
+ assert response["choices"][0]["message"]["content"] == "Hello! How can I help you today?"
+
+
+def test_completions_unauthorized_error(client, sample_messages, requests_mock):
+ """Test that completions raises UnauthorizedError for 401 responses"""
+ # Mock a 401 response
+ requests_mock.post(f"{client._base_url}/chat/completions", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.completions(model="gpt-4", messages=sample_messages)
+
+
+def test_completions_other_errors(client, sample_messages, requests_mock):
+ """Test that completions raises HTTPError for other error responses"""
+ # Mock a 500 response
+ requests_mock.post(f"{client._base_url}/chat/completions", status_code=500, json={"error": "Internal Server Error"})
+
+ with pytest.raises(requests.exceptions.HTTPError) as exc_info:
+ client.completions(model="gpt-4", messages=sample_messages)
+ assert exc_info.value.response.status_code == 500
diff --git a/tests/litellm/proxy/client/test_client.py b/tests/litellm/proxy/client/test_client.py
new file mode 100644
index 00000000000..4a7f0fb93aa
--- /dev/null
+++ b/tests/litellm/proxy/client/test_client.py
@@ -0,0 +1,58 @@
+import pytest
+from litellm.proxy.client import Client, ModelsManagementClient, ChatClient
+from litellm.proxy.client.keys import KeysManagementClient
+
+
+def base_url():
+ return "http://localhost:8000"
+
+
+def api_key():
+ return "test-api-key"
+
+
+def test_client_initialization(base_url, api_key):
+ """Test that the Client is properly initialized with all resource clients"""
+ client = Client(base_url=base_url, api_key=api_key)
+
+ # Check base properties
+ assert client._base_url == base_url
+ assert client._api_key == api_key
+
+ # Check resource clients
+ assert isinstance(client.models, ModelsManagementClient)
+ assert client.models._base_url == base_url
+ assert client.models._api_key == api_key
+
+ # Check chat client
+ assert isinstance(client.chat, ChatClient)
+ assert client.chat._base_url == base_url
+ assert client.chat._api_key == api_key
+
+ # Check keys client
+ assert isinstance(client.keys, KeysManagementClient)
+ assert client.keys._base_url == base_url
+ assert client.keys._api_key == api_key
+
+
+def test_client_initialization_strips_trailing_slash():
+ """Test that the client properly strips trailing slashes from base_url during initialization"""
+ base_url = "http://localhost:8000/////"
+ client = Client(base_url=base_url)
+
+ assert client._base_url == "http://localhost:8000"
+ assert client.models._base_url == "http://localhost:8000"
+ assert client.chat._base_url == "http://localhost:8000"
+ assert client.keys._base_url == "http://localhost:8000"
+
+
+def test_client_without_api_key(base_url):
+ """Test that the client works without an API key"""
+ client = Client(base_url=base_url)
+
+ assert client._api_key is None
+ assert client.models._api_key is None
+ assert client.chat._api_key is None
+ assert client.keys._api_key is None
diff --git a/tests/litellm/proxy/client/test_credentials.py b/tests/litellm/proxy/client/test_credentials.py
new file mode 100644
index 00000000000..f5af522c598
--- /dev/null
+++ b/tests/litellm/proxy/client/test_credentials.py
@@ -0,0 +1,188 @@
+import pytest
+import requests
+from litellm.proxy.client.credentials import CredentialsManagementClient
+from litellm.proxy.client.exceptions import UnauthorizedError
+
+
+def base_url():
+ return "http://localhost:8000"
+
+
+def api_key():
+ return "test-api-key"
+
+
+def client(base_url, api_key):
+ return CredentialsManagementClient(base_url=base_url, api_key=api_key)
+
+
+def test_client_initialization(base_url, api_key):
+ """Test that the CredentialsManagementClient is properly initialized"""
+ client = CredentialsManagementClient(base_url=base_url, api_key=api_key)
+
+ assert client._base_url == base_url
+ assert client._api_key == api_key
+
+
+def test_client_initialization_strips_trailing_slash():
+ """Test that the client properly strips trailing slashes from base_url during initialization"""
+ base_url = "http://localhost:8000/////"
+ client = CredentialsManagementClient(base_url=base_url)
+
+ assert client._base_url == "http://localhost:8000"
+
+
+def test_client_without_api_key(base_url):
+ """Test that the client works without an API key"""
+ client = CredentialsManagementClient(base_url=base_url)
+
+ assert client._api_key is None
+
+
+def test_list_request(client, base_url, api_key):
+ """Test list request"""
+ request = client.list(return_request=True)
+
+ assert request.method == "GET"
+ assert request.url == f"{base_url}/credentials"
+ assert request.headers["Content-Type"] == "application/json"
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+
+def test_list_mock_response(client, requests_mock):
+ """Test list with a mocked successful response"""
+ mock_response = {
+ "credentials": [
+ {
+ "credential_name": "azure1",
+ "credential_info": {"api_type": "azure"},
+ "model_id": "gpt-4",
+ },
+ {
+ "credential_name": "anthropic1",
+ "credential_info": {"api_type": "anthropic"},
+ "model_id": "claude-2",
+ },
+ ]
+ }
+
+ requests_mock.get(f"{client._base_url}/credentials", json=mock_response)
+
+ response = client.list()
+ assert response == mock_response
+
+
+def test_list_unauthorized_error(client, requests_mock):
+ """Test that list raises UnauthorizedError for 401 responses"""
+ requests_mock.get(f"{client._base_url}/credentials", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.list()
+
+
+def test_create_request(client, base_url, api_key):
+ """Test create request"""
+ request = client.create(
+ credential_name="azure1",
+ credential_info={"api_type": "azure"},
+ credential_values={"api_key": "sk-123", "api_base": "https://example.azure.openai.com"},
+ return_request=True,
+ )
+
+ assert request.method == "POST"
+ assert request.url == f"{base_url}/credentials"
+ assert request.headers["Content-Type"] == "application/json"
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+ assert request.json == {
+ "credential_name": "azure1",
+ "credential_info": {"api_type": "azure"},
+ "credential_values": {"api_key": "sk-123", "api_base": "https://example.azure.openai.com"},
+ }
+
+
+def test_create_mock_response(client, requests_mock):
+ """Test create with a mocked successful response"""
+ mock_response = {"credential_name": "azure1", "credential_info": {"api_type": "azure"}, "status": "success"}
+
+ requests_mock.post(f"{client._base_url}/credentials", json=mock_response)
+
+ response = client.create(
+ credential_name="azure1",
+ credential_info={"api_type": "azure"},
+ credential_values={"api_key": "sk-123", "api_base": "https://example.azure.openai.com"},
+ )
+ assert response == mock_response
+
+
+def test_create_unauthorized_error(client, requests_mock):
+ """Test that create raises UnauthorizedError for 401 responses"""
+ requests_mock.post(f"{client._base_url}/credentials", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.create(
+ credential_name="azure1", credential_info={"api_type": "azure"}, credential_values={"api_key": "sk-123"}
+ )
+
+
+def test_delete_request(client, base_url, api_key):
+ """Test delete request"""
+ request = client.delete(credential_name="azure1", return_request=True)
+
+ assert request.method == "DELETE"
+ assert request.url == f"{base_url}/credentials/azure1"
+ assert request.headers["Content-Type"] == "application/json"
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+
+def test_delete_mock_response(client, requests_mock):
+ """Test delete with a mocked successful response"""
+ mock_response = {"credential_name": "azure1", "status": "deleted"}
+
+ requests_mock.delete(f"{client._base_url}/credentials/azure1", json=mock_response)
+
+ response = client.delete(credential_name="azure1")
+ assert response == mock_response
+
+
+def test_delete_unauthorized_error(client, requests_mock):
+ """Test that delete raises UnauthorizedError for 401 responses"""
+ requests_mock.delete(f"{client._base_url}/credentials/azure1", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.delete(credential_name="azure1")
+
+
+def test_get_request(client, base_url, api_key):
+ """Test get request"""
+ request = client.get(credential_name="azure1", return_request=True)
+
+ assert request.method == "GET"
+ assert request.url == f"{base_url}/credentials/by_name/azure1"
+ assert request.headers["Content-Type"] == "application/json"
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+
+def test_get_mock_response(client, requests_mock):
+ """Test get with a mocked successful response"""
+ mock_response = {
+ "credential_name": "azure1",
+ "credential_info": {"api_type": "azure"},
+ "credential_values": {"api_key": "sk-123", "api_base": "https://example.azure.openai.com"},
+ "status": "active",
+ }
+
+ requests_mock.get(f"{client._base_url}/credentials/by_name/azure1", json=mock_response)
+
+ response = client.get(credential_name="azure1")
+ assert response == mock_response
+
+
+def test_get_unauthorized_error(client, requests_mock):
+ """Test that get raises UnauthorizedError for 401 responses"""
+ requests_mock.get(f"{client._base_url}/credentials/by_name/azure1", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.get(credential_name="azure1")
diff --git a/tests/litellm/proxy/client/test_keys.py b/tests/litellm/proxy/client/test_keys.py
new file mode 100644
index 00000000000..82dcafde3e6
--- /dev/null
+++ b/tests/litellm/proxy/client/test_keys.py
@@ -0,0 +1,311 @@
+import pytest
+import requests
+from litellm.proxy.client.keys import KeysManagementClient
+from litellm.proxy.client.exceptions import UnauthorizedError
+
+
+def base_url():
+ return "http://localhost:8000"
+
+
+def api_key():
+ return "test-api-key"
+
+
+def client(base_url, api_key):
+ return KeysManagementClient(base_url=base_url, api_key=api_key)
+
+
+def test_client_initialization(base_url, api_key):
+ """Test that the KeysManagementClient is properly initialized"""
+ client = KeysManagementClient(base_url=base_url, api_key=api_key)
+
+ assert client._base_url == base_url
+ assert client._api_key == api_key
+
+
+def test_client_initialization_strips_trailing_slash():
+ """Test that the client properly strips trailing slashes from base_url during initialization"""
+ base_url = "http://localhost:8000/////"
+ client = KeysManagementClient(base_url=base_url)
+
+ assert client._base_url == "http://localhost:8000"
+
+
+def test_client_without_api_key(base_url):
+ """Test that the client works without an API key"""
+ client = KeysManagementClient(base_url=base_url)
+
+ assert client._api_key is None
+
+
+def test_list_request_minimal(client, base_url, api_key):
+ """Test list request with minimal parameters"""
+ request = client.list(return_request=True)
+
+ assert request.method == "GET"
+ assert request.url == f"{base_url}/key/list"
+ assert request.headers["Content-Type"] == "application/json"
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+ assert not request.params
+
+
+def test_list_request_pagination(client):
+ """Test list request with pagination parameters"""
+ request = client.list(page=2, size=10, return_request=True)
+
+ assert request.params == {"page": 2, "size": 10}
+
+
+def test_list_request_filters(client):
+ """Test list request with filtering parameters"""
+ request = client.list(
+ user_id="user123",
+ team_id="team456",
+ organization_id="org789",
+ key_hash="hash123",
+ key_alias="alias123",
+ return_request=True,
+ )
+
+ assert request.params == {
+ "user_id": "user123",
+ "team_id": "team456",
+ "organization_id": "org789",
+ "key_hash": "hash123",
+ "key_alias": "alias123",
+ }
+
+
+def test_list_request_flags(client):
+ """Test list request with boolean flag parameters"""
+ request = client.list(return_full_object=True, include_team_keys=False, return_request=True)
+
+ assert request.params == {"return_full_object": "true", "include_team_keys": "false"}
+
+
+def test_list_request_all_parameters(client):
+ """Test list request with all parameters"""
+ request = client.list(
+ page=2,
+ size=10,
+ user_id="user123",
+ team_id="team456",
+ organization_id="org789",
+ key_hash="hash123",
+ key_alias="alias123",
+ return_full_object=True,
+ include_team_keys=False,
+ return_request=True,
+ )
+
+ assert request.params == {
+ "page": 2,
+ "size": 10,
+ "user_id": "user123",
+ "team_id": "team456",
+ "organization_id": "org789",
+ "key_hash": "hash123",
+ "key_alias": "alias123",
+ "return_full_object": "true",
+ "include_team_keys": "false",
+ }
+
+
+def test_list_mock_response_pagination(client, requests_mock):
+ """Test list with a mocked paginated response"""
+ mock_response = {
+ "data": {
+ "keys": [
+ {
+ "key": "key1",
+ "expires": "2024-12-31T23:59:59Z",
+ "models": ["gpt-4"],
+ "aliases": {"gpt4": "gpt-4"},
+ "spend": 100.0,
+ },
+ {
+ "key": "key2",
+ "expires": None,
+ "models": ["gpt-3.5-turbo"],
+ "aliases": {},
+ "spend": None,
+ },
+ ],
+ "total": 5,
+ "page": 1,
+ "size": 2,
+ }
+ }
+
+ requests_mock.get(
+ f"{client._base_url}/key/list",
+ json=mock_response,
+ additional_matcher=lambda r: r.qs == {"page": ["1"], "size": ["2"]},
+ )
+
+ response = client.list(page=1, size=2)
+ assert response == mock_response
+
+
+def test_list_mock_response_filtered(client, requests_mock):
+ """Test list with a mocked filtered response"""
+ mock_response = {
+ "keys": [
+ {
+ "key": "key1",
+ "user_id": "user123",
+ "team_id": "team456",
+ "expires": "2024-12-31T23:59:59Z",
+ "models": ["gpt-4"],
+ "aliases": {"gpt4": "gpt-4"},
+ "spend": 100.0,
+ }
+ ]
+ }
+
+ requests_mock.get(
+ f"{client._base_url}/key/list",
+ json=mock_response,
+ additional_matcher=lambda r: (r.qs.get("user_id") == ["user123"] and r.qs.get("team_id") == ["team456"]),
+ )
+
+ response = client.list(user_id="user123", team_id="team456")
+ assert response == mock_response
+
+
+def test_list_unauthorized_error(client, requests_mock):
+ """Test that list raises UnauthorizedError for 401 responses"""
+ requests_mock.get(f"{client._base_url}/key/list", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.list()
+
+
+def test_generate_request_minimal(client, base_url, api_key):
+ """Test generate with minimal parameters"""
+ request = client.generate(return_request=True)
+
+ assert request.method == "POST"
+ assert request.url == f"{base_url}/key/generate"
+ assert request.headers["Content-Type"] == "application/json"
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+
+def test_generate_request_full(client):
+ """Test generate with all parameters"""
+ request = client.generate(
+ models=["gpt-4", "gpt-3.5-turbo"],
+ aliases={"gpt4": "gpt-4", "turbo": "gpt-3.5-turbo"},
+ spend=100.0,
+ duration="24h",
+ key_alias="test-key-alias",
+ team_id="team123",
+ user_id="user456",
+ budget_id="budget789",
+ config={"max_parallel_requests": 5},
+ return_request=True,
+ )
+
+ assert request.json == {
+ "models": ["gpt-4", "gpt-3.5-turbo"],
+ "aliases": {"gpt4": "gpt-4", "turbo": "gpt-3.5-turbo"},
+ "spend": 100.0,
+ "duration": "24h",
+ "key_alias": "test-key-alias",
+ "team_id": "team123",
+ "user_id": "user456",
+ "budget_id": "budget789",
+ "config": {"max_parallel_requests": 5},
+ }
+
+
+def test_generate_mock_response(client, requests_mock):
+ """Test generate with a mocked successful response"""
+ mock_response = {
+ "key": "new-test-key",
+ "expires": "2024-12-31T23:59:59Z",
+ "models": ["gpt-4"],
+ "aliases": {"gpt4": "gpt-4"},
+ "spend": 100.0,
+ "key_alias": "test-key-alias",
+ "team_id": "team123",
+ "user_id": "user456",
+ "budget_id": "budget789",
+ "config": {"max_parallel_requests": 5},
+ }
+
+ requests_mock.post(f"{client._base_url}/key/generate", json=mock_response)
+
+ response = client.generate(
+ key_alias="test-key-alias",
+ team_id="team123",
+ user_id="user456",
+ budget_id="budget789",
+ config={"max_parallel_requests": 5},
+ )
+ assert response == mock_response
+
+
+def test_generate_unauthorized_error(client, requests_mock):
+ """Test that generate raises UnauthorizedError for 401 responses"""
+ requests_mock.post(f"{client._base_url}/key/generate", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.generate()
+
+
+def test_delete_request_minimal(client, base_url, api_key):
+ """Test delete request with minimal parameters"""
+ request = client.delete(return_request=True)
+
+ assert request.method == "POST"
+ assert request.url == f"{base_url}/key/delete"
+ assert request.headers["Content-Type"] == "application/json"
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+ assert request.json == {"keys": None, "key_aliases": None}
+
+
+def test_delete_request_with_keys(client):
+ """Test delete request with keys list"""
+ keys_to_delete = ["key1", "key2", "key3"]
+ request = client.delete(keys=keys_to_delete, return_request=True)
+
+ assert request.json == {"keys": keys_to_delete, "key_aliases": None}
+
+
+def test_delete_request_with_aliases(client):
+ """Test delete request with key aliases list"""
+ aliases_to_delete = ["alias1", "alias2"]
+ request = client.delete(key_aliases=aliases_to_delete, return_request=True)
+
+ assert request.json == {"keys": None, "key_aliases": aliases_to_delete}
+
+
+def test_delete_request_with_keys_and_aliases(client):
+ """Test delete request with both keys and aliases"""
+ keys_to_delete = ["key1", "key2"]
+ aliases_to_delete = ["alias1", "alias2"]
+ request = client.delete(keys=keys_to_delete, key_aliases=aliases_to_delete, return_request=True)
+
+ assert request.json == {"keys": keys_to_delete, "key_aliases": aliases_to_delete}
+
+
+def test_delete_mock_response(client, requests_mock):
+ """Test delete with a mocked successful response"""
+ mock_response = {"status": "success", "deleted_keys": ["key1", "key2"], "deleted_aliases": ["alias1"]}
+ requests_mock.post(f"{client._base_url}/key/delete", json=mock_response)
+
+ response = client.delete(keys=["key1", "key2"], key_aliases=["alias1"])
+ assert response == mock_response
+
+
+def test_delete_unauthorized_error(client, requests_mock):
+ """Test that delete raises UnauthorizedError for 401 responses"""
+ requests_mock.post(f"{client._base_url}/key/delete", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.delete(keys=["key-to-delete"])
diff --git a/tests/litellm/proxy/client/test_model_groups.py b/tests/litellm/proxy/client/test_model_groups.py
new file mode 100644
index 00000000000..11921b1a721
--- /dev/null
+++ b/tests/litellm/proxy/client/test_model_groups.py
@@ -0,0 +1,144 @@
+import pytest
+import requests
+from litellm.proxy.client import Client, ModelGroupsManagementClient
+from litellm.proxy.client.exceptions import UnauthorizedError
+
+
+def base_url():
+ return "http://localhost:8000"
+
+
+def api_key():
+ return "test-api-key"
+
+
+def client(base_url, api_key):
+ return ModelGroupsManagementClient(base_url=base_url, api_key=api_key)
+
+
+def test_info_request_creation(client, base_url, api_key):
+ """Test that info creates a request with correct URL and headers when return_request=True"""
+ request = client.info(return_request=True)
+
+ # Check request method
+ assert request.method == "GET"
+
+ # Check URL construction
+ expected_url = f"{base_url}/model_group/info"
+ assert request.url == expected_url
+
+ # Check authorization header
+ assert "Authorization" in request.headers
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+
+def test_info_request_no_auth(base_url):
+ """Test that info creates a request without auth header when no api_key is provided"""
+ client = ModelGroupsManagementClient(base_url=base_url) # No API key
+ request = client.info(return_request=True)
+
+ # Check URL is still correct
+ assert request.url == f"{base_url}/model_group/info"
+
+ # Check that there's no authorization header
+ assert "Authorization" not in request.headers
+
+
+ "base_url,expected",
+ [
+ ("http://localhost:8000", "http://localhost:8000/model_group/info"),
+ ("http://localhost:8000/", "http://localhost:8000/model_group/info"), # With trailing slash
+ ("https://api.example.com", "https://api.example.com/model_group/info"),
+ ("http://127.0.0.1:3000", "http://127.0.0.1:3000/model_group/info"),
+ ],
+)
+def test_info_url_variants(base_url, expected):
+ """Test that info handles different base URL formats correctly"""
+ client = ModelGroupsManagementClient(base_url=base_url)
+ request = client.info(return_request=True)
+ assert request.url == expected
+
+
+def test_info_with_mock_response(client, requests_mock):
+ """Test the full info execution with a mocked response"""
+ mock_data = {
+ "data": [
+ {
+ "model_group_name": "gpt4-group",
+ "models": ["gpt-4", "gpt-4-32k"],
+ "litellm_params": {"timeout": 30, "max_retries": 3},
+ },
+ {
+ "model_group_name": "azure-group",
+ "models": ["azure-gpt-4", "azure-gpt-35"],
+ "litellm_params": {"api_base": "https://azure-endpoint.com", "api_version": "2023-05-15"},
+ },
+ ]
+ }
+ requests_mock.get(f"{client._base_url}/model_group/info", json=mock_data)
+
+ response = client.info()
+ assert response == mock_data["data"]
+ assert len(response) == 2
+ assert response[0]["model_group_name"] == "gpt4-group"
+ assert response[1]["model_group_name"] == "azure-group"
+
+
+def test_info_unauthorized_error(client, requests_mock):
+ """Test that info raises UnauthorizedError for 401 responses"""
+ requests_mock.get(f"{client._base_url}/model_group/info", status_code=401, json={"error": "Invalid API key"})
+
+ with pytest.raises(UnauthorizedError) as exc_info:
+ client.info()
+ assert exc_info.value.orig_exception.response.status_code == 401
+
+
+def test_info_other_errors(client, requests_mock):
+ """Test that info raises normal HTTPError for non-401 errors"""
+ requests_mock.get(f"{client._base_url}/model_group/info", status_code=500, json={"error": "Internal Server Error"})
+
+ with pytest.raises(requests.exceptions.HTTPError) as exc_info:
+ client.info()
+ assert exc_info.value.response.status_code == 500
+
+
+ "api_key",
+ [
+ "", # Empty string
+ None, # None value
+ ],
+)
+def test_info_invalid_api_keys(base_url, api_key):
+ """Test that the client handles invalid API keys appropriately"""
+ client = ModelGroupsManagementClient(base_url=base_url, api_key=api_key)
+ request = client.info(return_request=True)
+ assert "Authorization" not in request.headers
+
+
+def test_client_initialization_strips_trailing_slash():
+ """Test that the client properly strips trailing slashes from base_url during initialization"""
+ client = ModelGroupsManagementClient(base_url="http://localhost:8000/////")
+ assert client._base_url == "http://localhost:8000"
+
+
+def test_client_initialization(base_url, api_key):
+ """Test that the Client properly initializes the model_groups client"""
+ client = Client(base_url=base_url, api_key=api_key)
+
+ # Check that model_groups client is properly initialized
+ assert isinstance(client.model_groups, ModelGroupsManagementClient)
+ assert client.model_groups._base_url == base_url
+ assert client.model_groups._api_key == api_key
+
+
+def test_client_initialization_without_api_key(base_url):
+ """Test that the client works without an API key"""
+ client = Client(base_url=base_url)
+
+ assert client._api_key is None
+ assert client.model_groups._api_key is None
diff --git a/tests/litellm/proxy/client/test_models.py b/tests/litellm/proxy/client/test_models.py
new file mode 100644
index 00000000000..0e1fbfe1ca3
--- /dev/null
+++ b/tests/litellm/proxy/client/test_models.py
@@ -0,0 +1,592 @@
+import pytest
+import requests
+from litellm.proxy.client import Client, ModelsManagementClient
+from litellm.proxy.client.exceptions import UnauthorizedError, NotFoundError
+
+
+def base_url():
+ return "http://localhost:8000"
+
+
+def api_key():
+ return "test-api-key"
+
+
+def client(base_url, api_key):
+ return ModelsManagementClient(base_url=base_url, api_key=api_key)
+
+
+def test_list_request_creation(client, base_url, api_key):
+ """Test that list creates a request with correct URL and headers when return_request=True"""
+ request = client.list(return_request=True)
+
+ # Check request method
+ assert request.method == "GET"
+
+ # Check URL construction
+ expected_url = f"{base_url}/models"
+ assert request.url == expected_url
+
+ # Check authorization header
+ assert "Authorization" in request.headers
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+
+def test_list_request_no_auth(base_url):
+ """Test that list creates a request without auth header when no api_key is provided"""
+ client = ModelsManagementClient(base_url=base_url) # No API key
+ request = client.list(return_request=True)
+
+ # Check URL is still correct
+ assert request.url == f"{base_url}/models"
+
+ # Check that there's no authorization header
+ assert "Authorization" not in request.headers
+
+
+ "base_url,expected",
+ [
+ ("http://localhost:8000", "http://localhost:8000/models"),
+ ("http://localhost:8000/", "http://localhost:8000/models"), # With trailing slash
+ ("https://api.example.com", "https://api.example.com/models"),
+ ("http://127.0.0.1:3000", "http://127.0.0.1:3000/models"),
+ ],
+)
+def test_list_url_variants(base_url, expected):
+ """Test that list handles different base URL formats correctly"""
+ client = ModelsManagementClient(base_url=base_url)
+ request = client.list(return_request=True)
+ assert request.url == expected
+
+
+def test_list_with_mock_response(client, requests_mock):
+ """Test the full list execution with a mocked response"""
+ mock_data = {"data": [{"id": "gpt-4", "type": "model"}, {"id": "gpt-3.5-turbo", "type": "model"}]}
+ requests_mock.get("http://localhost:8000/models", json=mock_data)
+
+ response = client.list()
+ assert response == mock_data["data"]
+ assert len(response) == 2
+ assert response[0]["id"] == "gpt-4"
+
+
+def test_list_unauthorized_error(client, requests_mock):
+ """Test that list raises UnauthorizedError for 401 responses"""
+ requests_mock.get("http://localhost:8000/models", status_code=401, json={"error": "Invalid API key"})
+
+ with pytest.raises(UnauthorizedError) as exc_info:
+ client.list()
+ assert exc_info.value.orig_exception.response.status_code == 401
+
+
+def test_list_other_errors(client, requests_mock):
+ """Test that list raises normal HTTPError for non-401 errors"""
+ requests_mock.get("http://localhost:8000/models", status_code=500, json={"error": "Internal Server Error"})
+
+ with pytest.raises(requests.exceptions.HTTPError) as exc_info:
+ client.list()
+ assert exc_info.value.response.status_code == 500
+
+
+ "api_key",
+ [
+ "", # Empty string
+ None, # None value
+ ],
+)
+def test_list_invalid_api_keys(base_url, api_key):
+ """Test that the client handles invalid API keys appropriately"""
+ client = ModelsManagementClient(base_url=base_url, api_key=api_key)
+ request = client.list(return_request=True)
+ assert "Authorization" not in request.headers
+
+
+def test_client_initialization_strips_trailing_slash():
+ """Test that the client properly strips trailing slashes from base_url during initialization"""
+ client = ModelsManagementClient(base_url="http://localhost:8000/////")
+ assert client._base_url == "http://localhost:8000"
+
+
+def test_list_with_mock_response(client, requests_mock):
+ """Test the full list execution with a mocked response"""
+ mock_data = {"data": [{"id": "gpt-4", "type": "model"}, {"id": "gpt-3.5-turbo", "type": "model"}]}
+ requests_mock.get("http://localhost:8000/models", json=mock_data)
+
+ response = client.list()
+ assert response == mock_data["data"]
+ assert len(response) == 2
+ assert response[0]["id"] == "gpt-4"
+
+
+def test_list_unauthorized_error(client, requests_mock):
+ """Test that list raises UnauthorizedError for 401 responses"""
+ requests_mock.get("http://localhost:8000/models", status_code=401, json={"error": "Invalid API key"})
+
+ with pytest.raises(UnauthorizedError) as exc_info:
+ client.list()
+ assert exc_info.value.orig_exception.response.status_code == 401
+
+
+def test_list_other_errors(client, requests_mock):
+ """Test that list raises normal HTTPError for non-401 errors"""
+ requests_mock.get("http://localhost:8000/models", status_code=500, json={"error": "Internal Server Error"})
+
+ with pytest.raises(requests.exceptions.HTTPError) as exc_info:
+ client.list()
+ assert exc_info.value.response.status_code == 500
+
+
+ "api_key",
+ [
+ "", # Empty string
+ None, # None value
+ ],
+)
+def test_list_invalid_api_keys(base_url, api_key):
+ """Test that the client handles invalid API keys appropriately"""
+ client = ModelsManagementClient(base_url=base_url, api_key=api_key)
+ request = client.list(return_request=True)
+ assert "Authorization" not in request.headers
+
+
+def test_client_initialization(base_url, api_key):
+ """Test that the Client is properly initialized with all resource clients"""
+ client = Client(base_url=base_url, api_key=api_key)
+
+ # Check base properties
+ assert client._base_url == base_url
+ assert client._api_key == api_key
+
+ # Check resource clients
+ assert isinstance(client.models, ModelsManagementClient)
+ assert client.models._base_url == base_url
+ assert client.models._api_key == api_key
+
+
+def test_client_initialization_strips_trailing_slash():
+ """Test that the client properly strips trailing slashes from base_url during initialization"""
+ base_url = "http://localhost:8000/////"
+ client = Client(base_url=base_url)
+
+ assert client._base_url == "http://localhost:8000"
+ assert client.models._base_url == "http://localhost:8000"
+
+
+def test_client_without_api_key(base_url):
+ """Test that the client works without an API key"""
+ client = Client(base_url=base_url)
+
+ assert client._api_key is None
+ assert client.models._api_key is None
+
+
+def test_new_request_creation(client, base_url, api_key):
+ """Test that new creates a request with correct URL, headers, and body when return_request=True"""
+ model_name = "gpt-4"
+ model_params = {"model": "openai/gpt-4", "api_base": "https://api.openai.com/v1"}
+ model_info = {"description": "GPT-4 model", "metadata": {"version": "1.0"}}
+
+ request = client.new(model_name=model_name, model_params=model_params, model_info=model_info, return_request=True)
+
+ # Check request method and URL
+ assert request.method == "POST"
+ assert request.url == f"{base_url}/model/new"
+
+ # Check headers
+ assert "Authorization" in request.headers
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+ # Check request body
+ assert request.json == {"model_name": model_name, "litellm_params": model_params, "model_info": model_info}
+
+
+def test_new_without_model_info(client):
+ """Test that new works correctly without optional model_info"""
+ model_name = "gpt-4"
+ model_params = {"model": "openai/gpt-4", "api_base": "https://api.openai.com/v1"}
+
+ request = client.new(model_name=model_name, model_params=model_params, return_request=True)
+
+ # Check request body doesn't include model_info
+ assert request.json == {"model_name": model_name, "litellm_params": model_params}
+
+
+def test_new_mock_response(client, requests_mock):
+ """Test new with a mocked successful response"""
+ model_name = "gpt-4"
+ model_params = {"model": "openai/gpt-4"}
+ mock_response = {"model_id": "123", "status": "success"}
+
+ # Mock the POST request
+ requests_mock.post(f"{client._base_url}/model/new", json=mock_response)
+
+ response = client.new(model_name=model_name, model_params=model_params)
+
+ assert response == mock_response
+
+
+def test_new_unauthorized_error(client, requests_mock):
+ """Test that new raises UnauthorizedError for 401 responses"""
+ model_name = "gpt-4"
+ model_params = {"model": "openai/gpt-4"}
+
+ # Mock a 401 response
+ requests_mock.post(f"{client._base_url}/model/new", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.new(model_name=model_name, model_params=model_params)
+
+
+def test_delete_request_creation(client, base_url, api_key):
+ """Test that delete creates a request with correct URL, headers, and body when return_request=True"""
+ model_id = "model-123"
+
+ request = client.delete(model_id=model_id, return_request=True)
+
+ # Check request method and URL
+ assert request.method == "POST"
+ assert request.url == f"{base_url}/model/delete"
+
+ # Check headers
+ assert "Authorization" in request.headers
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+ # Check request body
+ assert request.json == {"id": model_id}
+
+
+def test_delete_mock_response(client, requests_mock):
+ """Test delete with a mocked successful response"""
+ model_id = "model-123"
+ mock_response = {"message": "Model: model-123 deleted successfully"}
+
+ # Mock the POST request
+ requests_mock.post(f"{client._base_url}/model/delete", json=mock_response)
+
+ response = client.delete(model_id=model_id)
+ assert response == mock_response
+
+
+def test_delete_unauthorized_error(client, requests_mock):
+ """Test that delete raises UnauthorizedError for 401 responses"""
+ model_id = "model-123"
+
+ # Mock a 401 response
+ requests_mock.post(f"{client._base_url}/model/delete", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.delete(model_id=model_id)
+
+
+def test_delete_404_error(client, requests_mock):
+ """Test that delete raises NotFoundError for 404 responses"""
+ model_id = "model-123"
+
+ # Mock a 404 response
+ requests_mock.post(f"{client._base_url}/model/delete", status_code=404, json={"error": "Model not found"})
+
+ with pytest.raises(NotFoundError) as exc_info:
+ client.delete(model_id=model_id)
+ assert exc_info.value.orig_exception.response.status_code == 404
+
+
+def test_delete_not_found_in_text(client, requests_mock):
+ """Test that delete raises NotFoundError when response contains 'not found'"""
+ model_id = "model-123"
+
+ # Mock a response with "not found" in text but different status code
+ requests_mock.post(
+ f"{client._base_url}/model/delete",
+ status_code=400, # Different status code
+ json={"error": "The specified model was not found in the system"},
+ )
+
+ with pytest.raises(NotFoundError) as exc_info:
+ client.delete(model_id=model_id)
+ assert "not found" in exc_info.value.orig_exception.response.text.lower()
+
+
+def test_delete_other_errors(client, requests_mock):
+ """Test that delete raises normal HTTPError for other error responses"""
+ model_id = "model-123"
+
+ # Mock a 500 response
+ requests_mock.post(f"{client._base_url}/model/delete", status_code=500, json={"error": "Internal Server Error"})
+
+ with pytest.raises(requests.exceptions.HTTPError) as exc_info:
+ client.delete(model_id=model_id)
+ assert exc_info.value.response.status_code == 500
+
+
+def test_info_request_creation(client, base_url, api_key):
+ """Test that info creates a correct request"""
+ request = client.info(return_request=True)
+
+ # Check request method and URL
+ assert request.method == "GET"
+ assert request.url == f"{base_url}/v1/model/info"
+
+ # Check headers
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+
+def test_info_success(client, requests_mock):
+ """Test info with a successful response"""
+ mock_response = {
+ "data": [
+ {
+ "model_name": "gpt-4",
+ "model_info": {"id": "model-123", "description": "GPT-4 model"},
+ "litellm_params": {"model": "openai/gpt-4", "api_base": "https://api.openai.com/v1"},
+ },
+ {
+ "model_name": "gpt-3.5-turbo",
+ "model_info": {"id": "model-456", "description": "GPT-3.5 Turbo model"},
+ "litellm_params": {"model": "openai/gpt-3.5-turbo"},
+ },
+ ]
+ }
+
+ requests_mock.get(f"{client._base_url}/v1/model/info", json=mock_response)
+
+ response = client.info()
+ assert response == mock_response["data"]
+ assert len(response) == 2
+ assert response[0]["model_name"] == "gpt-4"
+ assert response[1]["model_name"] == "gpt-3.5-turbo"
+
+
+def test_info_unauthorized(client, requests_mock):
+ """Test that info raises UnauthorizedError for unauthorized requests"""
+ requests_mock.get(f"{client._base_url}/v1/model/info", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError) as exc_info:
+ client.info()
+ assert exc_info.value.orig_exception.response.status_code == 401
+
+
+def test_info_server_error(client, requests_mock):
+ """Test that info raises HTTPError for server errors"""
+ requests_mock.get(f"{client._base_url}/v1/model/info", status_code=500, json={"error": "Internal Server Error"})
+
+ with pytest.raises(requests.exceptions.HTTPError) as exc_info:
+ client.info()
+ assert exc_info.value.response.status_code == 500
+
+
+def test_get_by_id_request_creation(client, base_url, api_key):
+ """Test that get creates a correct request when using model_id"""
+ model_id = "model-123"
+ request = client.get(model_id=model_id, return_request=True)
+
+ # Check request method and URL
+ assert request.method == "GET"
+ assert request.url == f"{base_url}/v1/model/info"
+
+ # Check headers
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+
+def test_get_by_name_request_creation(client, base_url):
+ """Test that get creates a correct request when using model_name"""
+ model_name = "gpt-4"
+ request = client.get(model_name=model_name, return_request=True)
+
+ # Check it's a GET request to /v1/model/info
+ assert request.method == "GET"
+ assert request.url == f"{base_url}/v1/model/info"
+
+
+def test_get_invalid_params():
+ """Test that get raises ValueError for invalid parameter combinations"""
+ client = ModelsManagementClient(base_url="http://localhost:8000")
+
+ # Test with no parameters
+ with pytest.raises(ValueError) as exc_info:
+ client.get()
+ assert "Exactly one of model_id or model_name must be provided" in str(exc_info.value)
+
+ # Test with both parameters
+ with pytest.raises(ValueError) as exc_info:
+ client.get(model_id="123", model_name="gpt-4")
+ assert "Exactly one of model_id or model_name must be provided" in str(exc_info.value)
+
+
+def test_get_success_by_id(client, requests_mock):
+ """Test get successfully finding a model by ID"""
+ model_id = "model-123"
+ mock_models = {
+ "data": [
+ {"model_name": "gpt-3.5-turbo", "model_info": {"id": "other-model"}},
+ {
+ "model_name": "gpt-4",
+ "model_info": {"id": model_id},
+ "litellm_params": {"model": "openai/gpt-4", "api_base": "https://api.openai.com/v1"},
+ },
+ ]
+ }
+
+ requests_mock.get(f"{client._base_url}/v1/model/info", json=mock_models)
+
+ response = client.get(model_id=model_id)
+ assert response["model_info"]["id"] == model_id
+ assert response["model_name"] == "gpt-4"
+
+
+def test_get_success_by_name(client, requests_mock):
+ """Test get successfully finding a model by name"""
+ model_name = "gpt-4"
+ mock_models = {
+ "data": [
+ {"model_name": model_name, "model_info": {"id": "model-123"}, "litellm_params": {"model": "openai/gpt-4"}}
+ ]
+ }
+
+ requests_mock.get(f"{client._base_url}/v1/model/info", json=mock_models)
+
+ response = client.get(model_name=model_name)
+ assert response["model_name"] == model_name
+
+
+def test_get_not_found(client, requests_mock):
+ """Test that get raises NotFoundError when model is not found"""
+ model_name = "nonexistent-model"
+
+ # Mock successful response but with no matching model
+ requests_mock.get(
+ f"{client._base_url}/v1/model/info",
+ json={"data": [{"model_name": "gpt-3.5-turbo", "model_info": {"id": "other-model"}}]},
+ )
+
+ with pytest.raises(NotFoundError) as exc_info:
+ client.get(model_name=model_name)
+ assert "not found" in str(exc_info.value).lower()
+ assert "model_name=" + model_name in str(exc_info.value)
+
+
+def test_get_unauthorized(client, requests_mock):
+ """Test that get raises UnauthorizedError for unauthorized requests"""
+ model_id = "model-123"
+
+ requests_mock.get(f"{client._base_url}/v1/model/info", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError) as exc_info:
+ client.get(model_id=model_id)
+ assert exc_info.value.orig_exception.response.status_code == 401
+
+
+def test_get_server_error(client, requests_mock):
+ """Test that get raises HTTPError for server errors"""
+ model_id = "model-123"
+
+ requests_mock.get(f"{client._base_url}/v1/model/info", status_code=500, json={"error": "Internal Server Error"})
+
+ with pytest.raises(requests.exceptions.HTTPError) as exc_info:
+ client.get(model_id=model_id)
+ assert exc_info.value.response.status_code == 500
+
+
+def test_update_request_creation(client, base_url, api_key):
+ """Test that update creates a request with correct URL, headers, and body when return_request=True"""
+ model_id = "model-123"
+ model_params = {"model": "openai/gpt-4", "api_base": "https://api.openai.com/v1"}
+ model_info = {"description": "Updated GPT-4 model", "metadata": {"version": "2.0"}}
+
+ request = client.update(model_id=model_id, model_params=model_params, model_info=model_info, return_request=True)
+
+ # Check request method and URL
+ assert request.method == "POST"
+ assert request.url == f"{base_url}/model/update"
+
+ # Check headers
+ assert "Authorization" in request.headers
+ assert request.headers["Authorization"] == f"Bearer {api_key}"
+
+ # Check request body
+ assert request.json == {"id": model_id, "litellm_params": model_params, "model_info": model_info}
+
+
+def test_update_without_model_info(client):
+ """Test that update works correctly without optional model_info"""
+ model_id = "model-123"
+ model_params = {"model": "openai/gpt-4", "api_base": "https://api.openai.com/v1"}
+
+ request = client.update(model_id=model_id, model_params=model_params, return_request=True)
+
+ # Check request body doesn't include model_info
+ assert request.json == {"id": model_id, "litellm_params": model_params}
+
+
+def test_update_mock_response(client, requests_mock):
+ """Test update with a mocked successful response"""
+ model_id = "model-123"
+ model_params = {"model": "openai/gpt-4"}
+ mock_response = {"id": model_id, "status": "success", "message": "Model updated successfully"}
+
+ # Mock the POST request
+ requests_mock.post(f"{client._base_url}/model/update", json=mock_response)
+
+ response = client.update(model_id=model_id, model_params=model_params)
+
+ assert response == mock_response
+
+
+def test_update_unauthorized_error(client, requests_mock):
+ """Test that update raises UnauthorizedError for 401 responses"""
+ model_id = "model-123"
+ model_params = {"model": "openai/gpt-4"}
+
+ # Mock a 401 response
+ requests_mock.post(f"{client._base_url}/model/update", status_code=401, json={"error": "Unauthorized"})
+
+ with pytest.raises(UnauthorizedError):
+ client.update(model_id=model_id, model_params=model_params)
+
+
+def test_update_404_error(client, requests_mock):
+ """Test that update raises NotFoundError for 404 responses"""
+ model_id = "model-123"
+ model_params = {"model": "openai/gpt-4"}
+
+ # Mock a 404 response
+ requests_mock.post(f"{client._base_url}/model/update", status_code=404, json={"error": "Model not found"})
+
+ with pytest.raises(NotFoundError) as exc_info:
+ client.update(model_id=model_id, model_params=model_params)
+ assert exc_info.value.orig_exception.response.status_code == 404
+
+
+def test_update_not_found_in_text(client, requests_mock):
+ """Test that update raises NotFoundError when response contains 'not found'"""
+ model_id = "model-123"
+ model_params = {"model": "openai/gpt-4"}
+
+ # Mock a response with "not found" in text but different status code
+ requests_mock.post(
+ f"{client._base_url}/model/update",
+ status_code=400, # Different status code
+ json={"error": "The specified model was not found in the system"},
+ )
+
+ with pytest.raises(NotFoundError) as exc_info:
+ client.update(model_id=model_id, model_params=model_params)
+ assert "not found" in exc_info.value.orig_exception.response.text.lower()
+
+
+def test_update_other_errors(client, requests_mock):
+ """Test that update raises normal HTTPError for other error responses"""
+ model_id = "model-123"
+ model_params = {"model": "openai/gpt-4"}
+
+ # Mock a 500 response
+ requests_mock.post(f"{client._base_url}/model/update", status_code=500, json={"error": "Internal Server Error"})
+
+ with pytest.raises(requests.exceptions.HTTPError) as exc_info:
+ client.update(model_id=model_id, model_params=model_params)
+ assert exc_info.value.response.status_code == 500