The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
[Feat] Allow reading custom logger python scripts from s3 (#12623)
Ishaan Jaff9b817b511e70
diff --git a/docs/my-website/docs/proxy/logging.md b/docs/my-website/docs/proxy/logging.mdindex b5b2b8bf50f..7e42790604e 100644--- a/docs/my-website/docs/proxy/logging.md+++ b/docs/my-website/docs/proxy/logging.md@@ -1768,6 +1768,72 @@ litellm_settings:```+#### Step 2b - Loading Custom Callbacks from S3/GCS (Alternative)++Instead of using local Python files, you can load custom callbacks directly from S3 or GCS buckets. This is useful for centralized callback management or when deploying in containerized environments.++**URL Format:**+- **S3**: `s3://bucket-name/module_name.instance_name`+- **GCS**: `gcs://bucket-name/module_name.instance_name`++**Example - Loading from S3:**++Let's say you have a file `custom_callbacks.py` stored in your S3 bucket `litellm-proxy` with the following content:++```python+# custom_callbacks.py (stored in S3)+from litellm.integrations.custom_logger import CustomLogger+import litellm++class MyCustomHandler(CustomLogger):+ async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):+ print(f"Custom UI SSO callback executed!")+ # Your custom logic here++ async def async_log_failure_event(self, kwargs, response_obj, start_time, end_time):+ print(f"Custom UI SSO failure callback!")+ # Your failure handling logic++# Instance that will be loaded by LiteLLM+custom_handler = MyCustomHandler()+```++**Configuration:**++```yaml+model_list:+ - model_name: gpt-3.5-turbo+ litellm_params:+ model: gpt-3.5-turbo++litellm_settings:+ callbacks: ["s3://litellm-proxy/custom_callbacks.custom_handler"]+```++**Example - Loading from GCS:**++```yaml+model_list:+ - model_name: gpt-3.5-turbo+ litellm_params:+ model: gpt-3.5-turbo++litellm_settings:+ callbacks: ["gcs://my-gcs-bucket/custom_callbacks.custom_handler"]+```++**How it works:**+1. LiteLLM detects the S3/GCS URL prefix+2. Downloads the Python file to a temporary location+3. Loads the module and extracts the specified instance+4. Cleans up the temporary file+5. Uses the callback instance for logging++This approach allows you to:+- Centrally manage callback files across multiple proxy instances+- Share callbacks across different environments+- Version control callback files in cloud storage+#### Step 3 - Start proxy + test request```shelldiff --git a/litellm/proxy/common_utils/load_config_utils.py b/litellm/proxy/common_utils/load_config_utils.pyindex 34554cbb260..b8533ad00dd 100644--- a/litellm/proxy/common_utils/load_config_utils.py+++ b/litellm/proxy/common_utils/load_config_utils.py@@ -1,3 +1,5 @@+import os+import yamlfrom litellm._logging import verbose_proxy_logger@@ -62,6 +64,108 @@ async def get_config_file_contents_from_gcs(bucket_name, object_key):return None+def download_python_file_from_s3(+ bucket_name: str,+ object_key: str,+ local_file_path: str,+) -> bool:+ """+ Download a Python file from S3 and save it to local filesystem.++ Args:+ bucket_name (str): S3 bucket name+ object_key (str): S3 object key (file path in bucket)+ local_file_path (str): Local path where file should be saved++ Returns:+ bool: True if successful, False otherwise+ """+ try:+ import boto3+ from botocore.credentials import Credentials++ from litellm.llms.bedrock.base_aws_llm import BaseAWSLLM+ base_aws_llm = BaseAWSLLM()++ credentials: Credentials = base_aws_llm.get_credentials()+ s3_client = boto3.client(+ "s3",+ aws_access_key_id=credentials.access_key,+ aws_secret_access_key=credentials.secret_key,+ aws_session_token=credentials.token,+ )++ verbose_proxy_logger.debug(+ f"Downloading Python file {object_key} from S3 bucket: {bucket_name}"+ )+ response = s3_client.get_object(Bucket=bucket_name, Key=object_key)++ # Read the file contents+ file_contents = response["Body"].read().decode("utf-8")+ verbose_proxy_logger.debug(f"File contents: {file_contents}")++ # Ensure directory exists+ os.makedirs(os.path.dirname(local_file_path), exist_ok=True)++ # Write to local file+ with open(local_file_path, 'w') as f:+ f.write(file_contents)++ verbose_proxy_logger.debug(f"Python file downloaded successfully to {local_file_path}")+ return True++ except ImportError as e:+ verbose_proxy_logger.error(f"ImportError: {str(e)}")+ return False+ except Exception as e:+ verbose_proxy_logger.exception(f"Error downloading Python file: {str(e)}")+ return False+++async def download_python_file_from_gcs(+ bucket_name: str,+ object_key: str,+ local_file_path: str,+) -> bool:+ """+ Download a Python file from GCS and save it to local filesystem.++ Args:+ bucket_name (str): GCS bucket name+ object_key (str): GCS object key (file path in bucket)+ local_file_path (str): Local path where file should be saved++ Returns:+ bool: True if successful, False otherwise+ """+ try:+ from litellm.integrations.gcs_bucket.gcs_bucket import GCSBucketLogger++ gcs_bucket = GCSBucketLogger(+ bucket_name=bucket_name,+ )+ file_contents = await gcs_bucket.download_gcs_object(object_key)+ if file_contents is None:+ raise Exception(f"File contents are None for {object_key}")++ # file_contents is a bytes object, decode it+ file_contents = file_contents.decode("utf-8")++ # Ensure directory exists+ os.makedirs(os.path.dirname(local_file_path), exist_ok=True)++ # Write to local file+ with open(local_file_path, 'w') as f:+ f.write(file_contents)++ verbose_proxy_logger.debug(f"Python file downloaded successfully to {local_file_path}")+ return True++ except Exception as e:+ verbose_proxy_logger.exception(f"Error downloading Python file from GCS: {str(e)}")+ return False++# # Example usage# bucket_name = 'litellm-proxy'# object_key = 'litellm_proxy_config.yaml'diff --git a/litellm/proxy/proxy_config.yaml b/litellm/proxy/proxy_config.yamlindex 0cab62c71be..03d083fbfde 100644--- a/litellm/proxy/proxy_config.yaml+++ b/litellm/proxy/proxy_config.yaml@@ -5,6 +5,10 @@ model_list:- model_name: openai/*litellm_params:model: openai/*+++litellm_settings:+ callbacks: ["s3://litellm-proxy/custom_ui_sso_hook.custom_ui_sso_sign_in_handler"]- model_name: gemini/*litellm_params:model: gemini/*diff --git a/litellm/proxy/types_utils/utils.py b/litellm/proxy/types_utils/utils.pyindex e159da49549..ed50da3aa1f 100644--- a/litellm/proxy/types_utils/utils.py+++ b/litellm/proxy/types_utils/utils.py@@ -1,4 +1,6 @@+import asyncioimport importlib+import importlib.utilimport osfrom typing import Any, Callable, Literal, Optional, get_type_hints@@ -7,6 +9,10 @@ def get_instance_fn(value: str, config_file_path: Optional[str] = None) -> Any:module_name = valueinstance_name = Nonetry:+ # Check if value starts with s3:// or gcs://+ if value.startswith("s3://") or value.startswith("gcs://"):+ return _load_instance_from_remote_storage(value, config_file_path)+# Split the path by dots to separate module from instanceparts = value.split(".")@@ -20,12 +26,22 @@ def get_instance_fn(value: str, config_file_path: Optional[str] = None) -> Any:module_file_path = os.path.join(directory, *module_name.split("."))module_file_path += ".py"+ # Check if the file exists before trying to load it+ if not os.path.exists(module_file_path):+ raise ImportError(+ f"Could not find module file {module_file_path}"+ )+spec = importlib.util.spec_from_file_location(module_name, module_file_path) # type: ignoreif spec is None:raise ImportError(f"Could not find a module specification for {module_file_path}")module = importlib.util.module_from_spec(spec) # type: ignore+ if spec.loader is None:+ raise ImportError(+ f"Could not find a module loader for {module_file_path}"+ )spec.loader.exec_module(module) # type: ignoreelse:# Dynamically import the module@@ -47,6 +63,132 @@ def get_instance_fn(value: str, config_file_path: Optional[str] = None) -> Any:raise e+def _load_instance_from_remote_storage(remote_url: str, config_file_path: Optional[str] = None) -> Any:+ """+ Load custom logger instance from S3 or GCS URL.++ Expected format:+ - s3://bucket-name/path/to/module.instance_name+ - gcs://bucket-name/path/to/module.instance_name++ Args:+ remote_url (str): The s3:// or gcs:// URL+ config_file_path (str): Optional config file path for temp directory context++ Returns:+ Any: The loaded instance+ """+ try:+ from litellm._logging import verbose_proxy_logger++ # Parse the URL+ if remote_url.startswith("s3://"):+ storage_type = "s3"+ url_without_prefix = remote_url[5:] # Remove 's3://'+ elif remote_url.startswith("gcs://"):+ storage_type = "gcs"+ url_without_prefix = remote_url[6:] # Remove 'gcs://'+ else:+ raise ValueError(f"Unsupported URL scheme in {remote_url}")++ # Split bucket and path+ parts = url_without_prefix.split("/", 1)+ if len(parts) < 2:+ raise ValueError(f"Invalid URL format: {remote_url}. Expected: {storage_type}://bucket-name/path/to/module.instance")++ bucket_name = parts[0]+ path_and_module = parts[1]++ # Extract module path and instance name+ # Example: "loggers/custom_callbacks.proxy_handler_instance"+ # Handle case where user accidentally includes .py extension+ if path_and_module.endswith('.py'):+ module_name_without_py = path_and_module[:-3] # Remove .py+ raise ValueError(+ f"Invalid URL format in {remote_url}. "+ f"Don't include '.py' extension and you must specify the instance name. "+ f"Expected format: {storage_type}://{bucket_name}/{module_name_without_py}.instance_name "+ f"(e.g., {storage_type}://{bucket_name}/{module_name_without_py}.proxy_handler_instance)"+ )++ # Split by last dot to separate module from instance+ module_parts = path_and_module.split(".")+ if len(module_parts) < 2:+ raise ValueError(f"Invalid module specification in {remote_url}. Expected: path/to/module.instance_name")++ instance_name = module_parts[-1]+ module_path = ".".join(module_parts[:-1])++ # Create object key (file path in bucket)+ object_key = f"{module_path}.py"++ verbose_proxy_logger.debug(+ f"Loading custom logger from {storage_type}: bucket={bucket_name}, "+ f"object_key={object_key}, instance={instance_name}"+ )++ import tempfile++ # Create temporary file for the downloaded module using the actual module name+ temp_file = tempfile.NamedTemporaryFile(suffix='.py', delete=False)+ local_file_path = temp_file.name+ temp_file.close() # Close the file so we can write to it++ # Download the file+ if storage_type == "s3":+ from litellm.proxy.common_utils.load_config_utils import (+ download_python_file_from_s3,+ )+ success = download_python_file_from_s3(+ bucket_name=bucket_name,+ object_key=object_key,+ local_file_path=local_file_path,+ )+ else: # gcs+ success = asyncio.run(_download_gcs_file_wrapper(bucket_name, object_key, local_file_path))++ if not success:+ raise ImportError(f"Failed to download {object_key} from {storage_type} bucket {bucket_name}")++ # Load the module from the downloaded file using the actual module name+ spec = importlib.util.spec_from_file_location(module_path, local_file_path)+ if spec is None or spec.loader is None:+ raise ImportError(f"Could not create module spec for {local_file_path}")++ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)++ # Get the instance+ instance = getattr(module, instance_name)++ # Clean up the temporary file+ try:+ os.remove(local_file_path)+ except Exception as cleanup_error:+ verbose_proxy_logger.warning(f"Could not clean up temporary file {local_file_path}: {cleanup_error}")++ verbose_proxy_logger.info(f"Successfully loaded custom logger from {remote_url}")+ return instance++ except Exception as e:+ raise ImportError(f"Failed to load custom logger from {remote_url}: {str(e)}") from e+++async def _download_gcs_file_wrapper(bucket_name: str, object_key: str, local_file_path: str) -> bool:+ """Wrapper for GCS download to handle async properly"""+ try:+ from litellm.proxy.common_utils.load_config_utils import (+ download_python_file_from_gcs,+ )+ return await download_python_file_from_gcs(bucket_name, object_key, local_file_path)+ except Exception as e:+ from litellm._logging import verbose_proxy_logger+ verbose_proxy_logger.error(f"Error downloading from GCS: {str(e)}")+ return False++++def validate_custom_validate_return_type(fn: Optional[Callable[..., Any]],) -> Optional[Callable[..., Literal[True]]]:diff --git a/tests/proxy_unit_tests/test_custom_logger_s3_gcs.py b/tests/proxy_unit_tests/test_custom_logger_s3_gcs.pynew file mode 100644index 00000000000..01ce1acf1c2--- /dev/null+++ b/tests/proxy_unit_tests/test_custom_logger_s3_gcs.py@@ -0,0 +1,216 @@+import pytest+import os+import tempfile+import importlib.util+from unittest.mock import patch, MagicMock+from litellm.proxy.types_utils.utils import get_instance_fn, _load_instance_from_remote_storage+++class TestCustomLoggerS3GCS:+ """Test custom logger loading from S3/GCS using URL prefixes"""++ @pytest.fixture+ def sample_custom_logger_content(self):+ """Sample custom logger file content"""+ return '''+from litellm.integrations.custom_logger import CustomLogger++class TestCustomLogger(CustomLogger):+ def __init__(self):+ super().__init__()+ self.initialized = True++ def log_pre_api_call(self, model, messages, kwargs):+ print(f"Pre-API call to {model}")++# Instance to be imported+test_logger_instance = TestCustomLogger()+'''++ @pytest.fixture+ def temp_config_dir(self):+ """Create a temporary directory for config files"""+ with tempfile.TemporaryDirectory() as temp_dir:+ yield temp_dir++ def test_local_file_loading_still_works(self, temp_config_dir, sample_custom_logger_content):+ """Test that local file loading continues to work (no URL prefix)"""+ # Create a local custom logger file+ custom_logger_path = os.path.join(temp_config_dir, "test_custom_logger.py")+ with open(custom_logger_path, 'w') as f:+ f.write(sample_custom_logger_content)++ # Create a dummy config file+ config_path = os.path.join(temp_config_dir, "config.yaml")+ with open(config_path, 'w') as f:+ f.write("model_list: []")++ # Test loading the custom logger (traditional way)+ instance = get_instance_fn("test_custom_logger.test_logger_instance", config_path)++ assert instance is not None+ assert hasattr(instance, 'initialized')+ assert instance.initialized is True++ def test_s3_url_parsing(self):+ """Test S3 URL parsing"""+ test_url = "s3://my-bucket/loggers/custom_callbacks.proxy_handler_instance"++ # Mock the download function to avoid actual S3 calls+ with patch('litellm.proxy.common_utils.load_config_utils.download_python_file_from_s3') as mock_download:+ mock_download.return_value = False # Will cause failure, but we just want to test parsing++ with pytest.raises(ImportError, match="Failed to download"):+ _load_instance_from_remote_storage(test_url)++ # Verify the download was called with correct parameters+ mock_download.assert_called_once()+ call_args = mock_download.call_args+ assert call_args.kwargs['bucket_name'] == "my-bucket"+ assert call_args.kwargs['object_key'] == "loggers/custom_callbacks.py"++ def test_gcs_url_parsing(self):+ """Test GCS URL parsing"""+ test_url = "gcs://my-bucket/custom_logger.my_instance"++ # Mock the download function+ with patch('litellm.proxy.types_utils.utils._download_gcs_file_wrapper') as mock_download:+ mock_download.return_value = False # Will cause failure++ with pytest.raises(ImportError, match="Failed to download"):+ _load_instance_from_remote_storage(test_url)++ # Verify the download was called with correct parameters+ mock_download.assert_called_once()+ call_args = mock_download.call_args+ assert call_args[0][0] == "my-bucket" # bucket_name (positional for _download_gcs_file_wrapper)+ assert call_args[0][1] == "custom_logger.py" # object_key++ @patch('litellm.proxy.common_utils.load_config_utils.download_python_file_from_s3')+ def test_s3_download_success(self, mock_s3_download, sample_custom_logger_content):+ """Test successful S3 download and loading"""+ # Configure S3 download to succeed and create the file+ def mock_download(bucket_name, object_key, local_file_path):+ with open(local_file_path, 'w') as f:+ f.write(sample_custom_logger_content)+ return True++ mock_s3_download.side_effect = mock_download++ # Test loading with S3 URL+ test_url = "s3://test-bucket/test_custom_logger.test_logger_instance"+ instance = get_instance_fn(test_url)++ assert instance is not None+ assert hasattr(instance, 'initialized')+ assert instance.initialized is True++ # Verify S3 download was called with correct parameters+ mock_s3_download.assert_called_once()+ call_args = mock_s3_download.call_args+ assert call_args.kwargs['bucket_name'] == 'test-bucket'+ assert call_args.kwargs['object_key'] == 'test_custom_logger.py'++ @patch('litellm.proxy.types_utils.utils._download_gcs_file_wrapper')+ def test_gcs_download_success(self, mock_gcs_download, sample_custom_logger_content):+ """Test successful GCS download and loading"""+ # Configure GCS download to succeed and create the file+ def mock_download(bucket_name, object_key, local_file_path):+ with open(local_file_path, 'w') as f:+ f.write(sample_custom_logger_content)+ return True++ mock_gcs_download.side_effect = mock_download++ # Test loading with GCS URL+ test_url = "gcs://test-bucket/test_custom_logger.test_logger_instance"+ instance = get_instance_fn(test_url)++ assert instance is not None+ assert hasattr(instance, 'initialized')+ assert instance.initialized is True++ def test_nested_path_parsing(self):+ """Test parsing of nested paths in URLs"""+ test_url = "s3://my-bucket/loggers/production/advanced_logger.handler_instance"++ with patch('litellm.proxy.common_utils.load_config_utils.download_python_file_from_s3') as mock_download:+ mock_download.return_value = False++ with pytest.raises(ImportError):+ _load_instance_from_remote_storage(test_url)++ # Verify correct object key was generated+ call_args = mock_download.call_args+ assert call_args.kwargs['object_key'] == "loggers/production/advanced_logger.py"++ def test_invalid_url_schemes(self):+ """Test error handling for invalid URL schemes"""+ # URLs that look like URLs but aren't s3:// or gcs:// will be treated as module names+ # and fail with regular ImportError+ with pytest.raises(ImportError):+ get_instance_fn("http://bucket/module.instance")++ with pytest.raises(ImportError):+ get_instance_fn("ftp://bucket/module.instance")++ def test_invalid_url_format(self):+ """Test error handling for invalid URL formats"""+ # Missing bucket+ with pytest.raises(ImportError, match="Invalid URL format"):+ get_instance_fn("s3://")++ # Missing path+ with pytest.raises(ImportError, match="Invalid URL format"):+ get_instance_fn("s3://bucket-only")++ # Missing instance name+ with pytest.raises(ImportError, match="Invalid module specification"):+ get_instance_fn("s3://bucket/module-only")++ # Including .py extension (common mistake)+ with pytest.raises(ImportError, match="Don't include '\\.py' extension and you must specify the instance name"):+ get_instance_fn("s3://bucket/custom_guardrail.py")++ @patch('litellm.proxy.common_utils.load_config_utils.download_python_file_from_s3')+ def test_download_failure_handling(self, mock_s3_download):+ """Test handling of download failures"""+ mock_s3_download.return_value = False++ test_url = "s3://test-bucket/failing_logger.instance"++ with pytest.raises(ImportError, match="Failed to download"):+ get_instance_fn(test_url)++ @patch('litellm.proxy.common_utils.load_config_utils.download_python_file_from_s3')+ def test_file_cleanup(self, mock_s3_download, sample_custom_logger_content):+ """Test that temporary files are cleaned up"""+ created_files = []++ def mock_download(bucket_name, object_key, local_file_path):+ created_files.append(local_file_path)+ with open(local_file_path, 'w') as f:+ f.write(sample_custom_logger_content)+ return True++ mock_s3_download.side_effect = mock_download++ test_url = "s3://test-bucket/test_custom_logger.test_logger_instance"+ instance = get_instance_fn(test_url)++ assert instance is not None++ # Verify file was created and then cleaned up+ assert len(created_files) == 1+ temp_file = created_files[0]+ assert not os.path.exists(temp_file), f"Temporary file {temp_file} was not cleaned up"++ def test_no_url_prefix_fallback(self, temp_config_dir):+ """Test fallback when no URL prefix is used and local file doesn't exist"""+ config_path = os.path.join(temp_config_dir, "config.yaml")+ with open(config_path, 'w') as f:+ f.write("model_list: []")++ # Test that it tries local loading when no URL prefix is used+ with pytest.raises(ImportError, match="Could not import instance from nonexistent_logger"):+ get_instance_fn("nonexistent_logger.instance", config_path)\ No newline at end of file