|
| 1 | +""" |
| 2 | +Performance utilities for LiteLLM proxy server. |
| 3 | +
|
| 4 | +This module provides performance monitoring and profiling functionality for endpoint |
| 5 | +performance analysis using cProfile with configurable sampling rates. |
| 6 | +""" |
| 7 | + |
| 8 | +import asyncio |
| 9 | +import cProfile |
| 10 | +import functools |
| 11 | +import threading |
| 12 | +from pathlib import Path as PathLib |
| 13 | + |
| 14 | +from litellm._logging import verbose_proxy_logger |
| 15 | + |
| 16 | +# Global profiling state |
| 17 | +_profile_lock = threading.Lock() |
| 18 | +_profiler = None |
| 19 | +_last_profile_file_path = None |
| 20 | +_sample_counter = 0 |
| 21 | +_sample_counter_lock = threading.Lock() |
| 22 | + |
| 23 | + |
| 24 | +def _should_sample(profile_sampling_rate: float) -> bool: |
| 25 | + """Determine if current request should be sampled based on sampling rate.""" |
| 26 | + if profile_sampling_rate >= 1.0: |
| 27 | + return True # Always sample |
| 28 | + elif profile_sampling_rate <= 0.0: |
| 29 | + return False # Never sample |
| 30 | + |
| 31 | + # Use deterministic sampling based on counter for consistent rate |
| 32 | + global _sample_counter |
| 33 | + with _sample_counter_lock: |
| 34 | + _sample_counter += 1 |
| 35 | + # Sample based on rate (e.g., 0.1 means sample every 10th request) |
| 36 | + should_sample = (_sample_counter % int(1.0 / profile_sampling_rate)) == 0 |
| 37 | + return should_sample |
| 38 | + |
| 39 | + |
| 40 | +def _start_profiling(profile_sampling_rate: float) -> None: |
| 41 | + """Start cProfile profiling once globally.""" |
| 42 | + global _profiler |
| 43 | + with _profile_lock: |
| 44 | + if _profiler is None: |
| 45 | + _profiler = cProfile.Profile() |
| 46 | + _profiler.enable() |
| 47 | + verbose_proxy_logger.info(f"Profiling started with sampling rate: {profile_sampling_rate}") |
| 48 | + |
| 49 | + |
| 50 | +def _start_profiling_for_request(profile_sampling_rate: float) -> bool: |
| 51 | + """Start profiling for a specific request (if sampling allows).""" |
| 52 | + if _should_sample(profile_sampling_rate): |
| 53 | + _start_profiling(profile_sampling_rate) |
| 54 | + return True |
| 55 | + return False |
| 56 | + |
| 57 | + |
| 58 | +def _save_stats(profile_file: PathLib) -> None: |
| 59 | + """Save current stats directly to file.""" |
| 60 | + with _profile_lock: |
| 61 | + if _profiler is None: |
| 62 | + return |
| 63 | + try: |
| 64 | + # Disable profiler temporarily to dump stats |
| 65 | + _profiler.disable() |
| 66 | + _profiler.dump_stats(str(profile_file)) |
| 67 | + # Re-enable profiler to continue profiling |
| 68 | + _profiler.enable() |
| 69 | + verbose_proxy_logger.debug(f"Profiling stats saved to {profile_file}") |
| 70 | + except Exception as e: |
| 71 | + verbose_proxy_logger.error(f"Error saving profiling stats: {e}") |
| 72 | + # Make sure profiler is re-enabled even if there's an error |
| 73 | + try: |
| 74 | + _profiler.enable() |
| 75 | + except Exception: |
| 76 | + pass |
| 77 | + |
| 78 | + |
| 79 | +def profile_endpoint(sampling_rate: float = 1.0): |
| 80 | + """Decorator to sample endpoint hits and save to a profile file. |
| 81 | + |
| 82 | + Args: |
| 83 | + sampling_rate: Rate of requests to profile (0.0 to 1.0) |
| 84 | + - 1.0: Profile all requests (100%) |
| 85 | + - 0.1: Profile 1 in 10 requests (10%) |
| 86 | + - 0.0: Profile no requests (0%) |
| 87 | + """ |
| 88 | + def decorator(func): |
| 89 | + def set_last_profile_path(path: PathLib) -> None: |
| 90 | + global _last_profile_file_path |
| 91 | + _last_profile_file_path = path |
| 92 | + |
| 93 | + if asyncio.iscoroutinefunction(func): |
| 94 | + @functools.wraps(func) |
| 95 | + async def async_wrapper(*args, **kwargs): |
| 96 | + is_sampling = _start_profiling_for_request(sampling_rate) |
| 97 | + file_path_obj = PathLib("endpoint_profile.pstat") |
| 98 | + set_last_profile_path(file_path_obj) |
| 99 | + try: |
| 100 | + result = await func(*args, **kwargs) |
| 101 | + if is_sampling: |
| 102 | + _save_stats(file_path_obj) |
| 103 | + return result |
| 104 | + except Exception: |
| 105 | + if is_sampling: |
| 106 | + _save_stats(file_path_obj) |
| 107 | + raise |
| 108 | + return async_wrapper |
| 109 | + else: |
| 110 | + @functools.wraps(func) |
| 111 | + def sync_wrapper(*args, **kwargs): |
| 112 | + is_sampling = _start_profiling_for_request(sampling_rate) |
| 113 | + file_path_obj = PathLib("endpoint_profile.pstat") |
| 114 | + set_last_profile_path(file_path_obj) |
| 115 | + try: |
| 116 | + result = func(*args, **kwargs) |
| 117 | + if is_sampling: |
| 118 | + _save_stats(file_path_obj) |
| 119 | + return result |
| 120 | + except Exception: |
| 121 | + if is_sampling: |
| 122 | + _save_stats(file_path_obj) |
| 123 | + raise |
| 124 | + return sync_wrapper |
| 125 | + return decorator |
0 commit comments