litellm/docs/my-website/docs
Ishaan Jaff b1b96ff3cf
[Perf] Alexsander fixes round 2 - Oct 18th (#15695)
* perf(router): Optimize prompt management model check with early exit

Add early return for models without '/' to avoid expensive get_model_list()
calls for 99% of standard model requests (gpt-4, claude-3, etc).

- Refactor _is_prompt_management_model() with "/" check before model lookup
- Add unit tests to verify optimization doesn't break detection

* perf(caching): optimize Redis batch cache operations and reduce unnecessary queries

This commit introduces several performance optimizations to the Redis caching layer:

**DualCache Improvements (dual_cache.py):**

1. Increase batch cache size limit from 100 to 1000
   - Allows for larger batch operations, reducing Redis round-trips

2. Throttle repeated Redis queries for cache misses
   - Update last_redis_batch_access_time for ALL queried keys, including those
     with None values
   - Prevents excessive Redis queries for frequently-accessed non-existent keys

3. Add early exit optimization
   - Short-circuit when redis_result is None or contains only None values
   - Avoids unnecessary processing when no cache hits are found

4. Optimize key lookup performance
   - Replace O(n) keys.index() calls with O(1) dict lookup via key_to_index mapping
   - Reduces algorithmic complexity in batch operations

5. Streamline cache updates
   - Combine result updates and in-memory cache updates in single loop
   - Only cache non-None values to avoid polluting in-memory cache

**CooldownCache Improvements (cooldown_cache.py):**

1. Enhanced early return logic
   - Check if all values in results are None, not just if results is None
   - Prevents unnecessary iteration when no valid cooldown data exists

These changes significantly improve Redis caching performance, especially for:
- High-throughput batch operations
- Scenarios with frequent cache misses
- Large-scale deployments with many concurrent requests

* fix: remove unnecessary test

* refactor: move default_max_redis_batch_cache_size to constants

- Add DEFAULT_MAX_REDIS_BATCH_CACHE_SIZE constant (default: 1000)
- Update DualCache to use constant from constants.py
- Document new environment variable in config_settings.md

* fix: only use in memory cache when set

* fix(router): improve prompt management model detection with smart early return

The previous early return optimization in _is_prompt_management_model() was
checking if the model name parameter contained '/' and returning False if it
didn't. This broke detection for model aliases (e.g., 'chatbot_actions') that
don't have '/' in their name but map to prompt management models
(e.g., 'langfuse/openai-gpt-3.5-turbo').

Changed the early return logic to only exit early when:
- Model name contains '/' AND
- The prefix is NOT a known prompt management provider

This maintains the performance optimization for 99% of direct model calls
(avoiding expensive get_model_list lookups) while correctly handling:
- Direct prompt management calls (e.g., 'langfuse/model')
- Model aliases without '/' (e.g., 'chatbot_actions')
- Regular models with/without '/' (e.g., 'gpt-3.5-turbo', 'openai/gpt-4')

Fixes test: test_router_prompt_management_factory

* perf(router): optimize _pre_call_checks with shallow copy (1400x faster)

Replace deepcopy with list() in _pre_call_checks - runs on every request.
Only pops from list, never modifies deployment dicts, so shallow copy is safe.

Performance: 1400x faster on hot path
Impact: 2-5x overall throughput improvement for routing workloads
Tests: Added regression test to ensure no mutation + filtering works

* perf(router): replace deepcopy with shallow copy for default deployment

Replace expensive copy.deepcopy() with shallow copy for default_deployment
in _common_checks_available_deployment() hot path.

Changes:
- Use dict.copy() for top-level deployment dict
- Use dict.copy() for nested litellm_params dict
- Only the 'model' field is modified, so deep recursion is unnecessary

Impact:
- 100x+ faster for default deployment path (every request when used)
- deepcopy recursively traverses entire object tree
- Shallow copy only copies two dict levels (exactly what's needed)

Test coverage:
- Added regression test to verify deployment isolation
- Ensures returned deployments don't mutate original default_deployment
- Validates multiple concurrent requests get independent copies

* perf(router): remove unnecessary dict copy in completion hot paths

Remove unnecessary deployment['litellm_params'].copy() in _completion
and _acompletion functions. The dict is only read and spread into a new
dict, never modified, making the defensive copy wasteful.

Changes:
- Remove .copy() in _completion (sync hot path)
- Remove .copy() in _acompletion (async hot path)

Impact:
- Every completion request (highest traffic endpoints)
- Eliminates unnecessary dict allocation and copy on every call
- Dict spreading already creates new dict, so no mutation possible

Test coverage:
- Added tests verifying deployment params unchanged after calls
- Tests both sync and async completion paths
- Validates optimization doesn't introduce mutations

* perf(router): optimize deployment filtering in pre-call checks

Replace O(n²) list pop pattern with O(n) set-based filtering in
_pre_call_checks() to improve routing performance under high load.

Changes:
- Use set() instead of list for invalid_model_indices tracking
- Replace reversed list.pop() loop with single-pass list comprehension
- Eliminate redundant list→set conversion overhead

Impact:
- Hot path optimization: runs on every request through the router
- ~2-5x faster filtering when many deployments fail validation
- Most beneficial with 50+ deployments per model group or high
  invalidation rates (rate limits, context window exceeded)

Technical details:
Old: O(k²) where k = invalid deployments (pop shifts remaining elements)
New: O(n) single pass with O(1) set membership checks

* add: memory profiler

feat(proxy): Add configurable GC thresholds and enhance memory debugging endpoints

- Add PYTHON_GC_THRESHOLD env var to configure garbage collection thresholds
- Add POST /debug/memory/gc/configure endpoint for runtime GC tuning
- Enhance memory debugging endpoints with better structure and explanations
- Add comprehensive router and cache memory tracking
- Include worker PID in all debug responses for multi-worker debugging

* refactor: reduce complexity in get_memory_details endpoint

Extract 6 helper functions from get_memory_details to fix linter
error PLR0915 (too many statements). Improves maintainability
while preserving functionality.

* fix(router): remove incorrect early exit in _is_prompt_management_model

Removes early exit optimization that checked model_name prefix instead
of the actual litellm_params model. This incorrectly returned False for
custom model aliases that map to prompt management providers.

Example: "my-langfuse-prompt/test_id" -> "langfuse_prompt/actual_id"

The method now correctly checks the underlying model's prefix.

Fixes test_is_prompt_management_model_optimization

* fix(proxy): add explicit type annotations to debug_utils dictionaries

Resolved 6 mypy type errors in proxy/common_utils/debug_utils.py by adding
explicit Dict[str, Any] annotations to dictionary variables where mypy was
incorrectly inferring narrow types. This allows the dictionaries to accept
different value types (strings, nested dicts) for error handling and various
return structures.

Fixed:
- Line 246: caches dictionary in get_memory_summary()
- Line 371: cache_stats dictionary in _get_cache_memory_stats()
- Line 439: litellm_router_memory dictionary in _get_router_memory_stats()

* fix(proxy): fix Python 3.8 compatibility in debug_utils type annotations

- Replace tuple[...], list[...] with Tuple[...], List[...] from typing
- Replace Dict | None with Optional[Dict] for Python 3.8 compatibility
- Add missing imports: List, Optional, Tuple to typing imports

Fixes TypeError: 'type' object is not subscriptable in Python 3.8

---------

Co-authored-by: AlexsanderHamir <alexsanderhamirgomesbaptista@gmail.com>
2025-10-18 11:12:00 -07:00
..
adding_provider [Feat] Add Nvidia NIM Rerank Support (#15152) 2025-10-02 18:58:52 -07:00
caching [Redis IAM] Change documentation (#13306) 2025-08-05 15:04:46 -07:00
completion Bedrock + MCP - working MCP calls to bedrock via Responses API + Log hidden params for OTEL calls (#15677) 2025-10-18 10:39:28 -07:00
debugging Update local_debugging.md (#8308) 2025-02-06 16:19:32 -08:00
embedding (feat)Litellm x twelvelabs bedrock[Async Invoke Support] (#14871) 2025-10-02 18:52:33 -07:00
extras feat(openrouter.py): add image generation via google on openrouter support 2025-09-01 18:39:41 -07:00
guides feat(ssl): add configurable ECDH curve for TLS performance 2025-10-14 13:57:39 -07:00
integrations docs: Letta Guide (#14798) 2025-09-23 16:18:57 -07:00
langchain added tags to langchain 2025-09-10 00:32:26 -04:00
observability feat: posthog per request api key 2025-10-09 18:32:11 +02:00
pass_through doc fix 2025-10-16 16:36:24 -07:00
projects added railtracks to projects using litellm (#15144) 2025-10-02 14:21:38 -07:00
provider_registration Integration: Bytez as a model provider (#12121) 2025-07-12 10:50:39 -07:00
providers [Oct Staging Branch] (#15460) 2025-10-17 17:52:25 -07:00
proxy [Perf] Alexsander fixes round 2 - Oct 18th (#15695) 2025-10-18 11:12:00 -07:00
tutorials docs: fix url 2025-10-15 08:33:28 -07:00
vector_stores docs - vector stores (#12781) 2025-07-19 17:07:44 -07:00
aiohttp_benchmarks.md docs benchmarks 2025-05-24 17:43:38 -07:00
anthropic_unified.md [Feat] Add Guardrails for /v1/messages and /v1/responses API (#15686) 2025-10-17 18:09:00 -07:00
apply_guardrail.md docs apply guard (#10923) 2025-05-17 18:34:35 -07:00
assistants.md Use the -d flag in docs instead of -D (#12179) 2025-06-30 15:25:42 -07:00
audio_transcription.md [Docs] - Show how to use fallbacks with audio transcriptions endpoints (#12115) 2025-06-27 12:43:55 -07:00
batches.md docs fix 2025-09-12 19:51:14 -07:00
bedrock_converse.md docs boto3 instructions 2025-10-16 16:34:56 -07:00
bedrock_invoke.md docs boto3 instructions 2025-10-16 16:34:56 -07:00
benchmarks.md fix: add missing context (#15688) 2025-10-17 17:39:21 -07:00
budget_manager.md docs - use consistent name for LiteLLM proxy server 2024-08-03 12:54:07 -07:00
contact.md docs add slack support 2025-06-30 10:45:37 -07:00
contributing.md docs: cleanup docs 2025-10-02 09:51:16 -07:00
data_retention.md docs - Custom Retention Policies 2025-01-20 07:29:48 -08:00
data_security.md docs(data_security.md): data_security.md 2025-06-09 17:53:11 -07:00
default_code_snippet.md update docs 2023-08-25 17:02:43 -07:00
enterprise.md Corrected docs updates sept 2025 (#14916) 2025-09-25 15:49:19 -07:00
exception_mapping.md [Bug fix] Misclassified 500 error on invalid image_url in /chat/completions request (#14149) 2025-09-01 15:26:27 -07:00
files_endpoints.md Litellm managed files docs (#9948) 2025-04-12 13:02:33 -07:00
fine_tuning.md Corrected docs updates sept 2025 (#14916) 2025-09-25 15:49:19 -07:00
generateContent.md docs - 1.74.0.rc (#12347) 2025-07-05 13:17:51 -07:00
getting_started.md Corrected docs updates sept 2025 (#14916) 2025-09-25 15:49:19 -07:00
image_edits.md Corrected docs updates sept 2025 (#14916) 2025-09-25 15:49:19 -07:00
image_generation.md Corrected docs updates sept 2025 (#14916) 2025-09-25 15:49:19 -07:00
image_variations.md New stable release - release notes (#8148) 2025-01-31 10:02:59 -08:00
index.md Corrected docs updates sept 2025 (#14916) 2025-09-25 15:49:19 -07:00
load_test.md (docs) add 1k rps load test doc (#6059) 2024-10-04 16:56:34 +05:30
load_test_advanced.md Remove aiohttp_ prefix from config (#14920) 2025-09-25 16:09:41 -07:00
load_test_rpm.md docs: usaged-based routing perf warnings (#14080) 2025-08-29 17:31:12 -07:00
load_test_sdk.md (docs) add 1k rps load test doc (#6059) 2024-10-04 16:56:34 +05:30
mcp.md docs(index.md): document mcp oauth support 2025-10-11 15:14:15 -07:00
mcp_control.md [MCP Gateway] QA/Fixes - Ensure Team/Key level enforcement works for MCPs (#15305) 2025-10-07 17:34:48 -07:00
mcp_cost.md [MCP Gateway] QA/Fixes - Ensure Team/Key level enforcement works for MCPs (#15305) 2025-10-07 17:34:48 -07:00
mcp_guardrail.md [MCP Gateway] QA/Fixes - Ensure Team/Key level enforcement works for MCPs (#15305) 2025-10-07 17:34:48 -07:00
mcp_usage.md [MCP Gateway] QA/Fixes - Ensure Team/Key level enforcement works for MCPs (#15305) 2025-10-07 17:34:48 -07:00
migration.md (docs) update migration 2023-11-21 11:22:54 -08:00
migration_policy.md docs migration policy 2024-08-09 18:06:37 -07:00
moderation.md Corrected docs updates sept 2025 (#14916) 2025-09-25 15:49:19 -07:00
ocr.md [Feat] Add Cost Tracking for /ocr endpoints (#15678) 2025-10-17 15:54:10 -07:00
oidc.md Azure OIDC provider improvements + OIDC audience bug fix (#10054) 2025-05-28 09:33:13 -07:00
old_guardrails.md Use the -d flag in docs instead of -D (#12179) 2025-06-30 15:25:42 -07:00
projects.md docs 2023-09-08 20:55:04 -07:00
proxy_api.md Corrected docs updates sept 2025 (#14916) 2025-09-25 15:49:19 -07:00
proxy_server.md Contributor PR - Support OPENAI_BASE_URL in addition to OPENAI_API_BASE (#9995) (#10423) 2025-04-29 21:27:37 -07:00
realtime.md docs(realtime): yaml config example for realtime model (#10489) 2025-05-01 21:43:48 -07:00
reasoning_content.md update docs 2025-09-06 21:15:59 +09:00
rerank.md [Oct Staging Branch] (#15460) 2025-10-17 17:52:25 -07:00
response_api.md [Feat] Add Guardrails for /v1/messages and /v1/responses API (#15686) 2025-10-17 18:09:00 -07:00
router_architecture.md docs(router_architecture.md): add router architecture docs 2024-11-26 12:54:38 +05:30
routing.md docs: usaged-based routing perf warnings (#14080) 2025-08-29 17:31:12 -07:00
rules.md docs(rules.md): adding rules to docs 2023-11-20 19:14:07 -08:00
scheduler.md docs: usaged-based routing perf warnings (#14080) 2025-08-29 17:31:12 -07:00
sdk_custom_pricing.md organize docs 2024-08-03 12:54:07 -07:00
secret.md docs(admin_ui_sso.md): document /fallback/login flow 2025-07-16 09:07:42 -07:00
set_keys.md Contributor PR - Support OPENAI_BASE_URL in addition to OPENAI_API_BASE (#9995) (#10423) 2025-04-29 21:27:37 -07:00
text_completion.md docs naming on sidebar 2025-03-12 21:00:30 -07:00
text_to_speech.md docs Gemini Text-to-Speech 2025-06-26 15:59:48 -07:00
troubleshoot.md changed docs 2025-09-16 00:58:08 -04:00
wildcard_routing.md Litellm dev 12 28 2024 p2 (#7458) 2024-12-28 19:38:06 -08:00