mirror of
https://github.com/BerriAI/litellm.git
synced 2026-08-28 05:25:59 +00:00
* feat(guardrails): add run_in_parallel opt-in for concurrent pre_call guardrails Pre-call guardrails run sequentially because each may mutate the request payload and later guardrails depend on earlier mutations. Deployments with several slow block-only pre_call guardrails (external moderation, Bedrock, LLM-judge) therefore pay the sum of their latencies. during_call guardrails run concurrently but alongside the LLM call, so a violating payload has already been sent, which is unacceptable when the request must never reach the model. This adds a per-guardrail run_in_parallel flag (default off). Guardrails that opt in are pulled out of the sequential loop and run concurrently via asyncio.gather after every sequential (payload-mutating) guardrail has run, so they observe the mutated payload and still form a hard barrier before the LLM call; the first to raise blocks the request. Their returned data is discarded since they are declared block-only. The flag is wired from LitellmParams onto the guardrail instance at the same generic choke point in initialize_guardrail that already sets skip_system_message_in_guardrail, so no per-provider initializer needs to change. * feat(guardrails): extend run_in_parallel opt-in to post_call guardrails post_call_success_hook ran guardrails sequentially for the same reason pre_call did: response-modifying guardrails thread the response forward. But block-only output scanners (which read the response and reject on violation without changing it) serialize for no benefit and add latency. This reuses the existing run_in_parallel flag for the post_call hook. Opted-in post_call guardrails are pulled out of the sequential loop and run concurrently via asyncio.gather after the sequential (response-modifying) guardrails and before the non-guardrail CustomLogger callbacks, so they inspect the final response and still block it from reaching the client if any raises. Their returned response is discarded since they are block-only. The apply_guardrail path sets data["guardrail_to_apply"] immediately before awaiting, and unified_guardrail pops it before its first suspension point, so concurrent guardrails never race on that key under asyncio's cooperative scheduling. * fix(guardrails): await all parallel guardrails and prioritize blocks over reroutes Addresses review feedback on the run_in_parallel opt-in. asyncio.gather propagated the first exception without cancelling or awaiting the siblings, so a block at t=0 left the other guardrails running as unobserved background tasks (wasted external calls plus event-loop warnings), and a fast SensitiveDataRouteException/ModifyResponseException could return a reroute or passthrough before a slower block finished, letting crafted input bypass the block. Both the pre_call and post_call parallel batches now gather with return_exceptions=True so every guardrail runs to completion, then raise any blocking exception ahead of a flow-changing one. The registry choke point wrote bool(None)==False onto every instance when the config omitted run_in_parallel, silently disabling a constructor-set default; it now only writes when the config provides an explicit value. * fix(guardrails): record lifecycle logs for every concurrently-run guardrail The log_guardrail_information decorator skipped its auto-record when it saw that the count of standard_logging_guardrail_information entries in the shared request_data had grown during the wrapped call, taking that as proof the wrapped function had recorded its own richer entry. That heuristic breaks the moment guardrails run concurrently (parallel pre_call/post_call, during_call): a sibling guardrail's append inflates the shared count, so a guardrail that did not self-record wrongly concludes it already did and drops its own entry. The result is that enabling run_in_parallel silently loses per-guardrail lifecycle logs, so the Admin UI Request Lifecycle timeline and downstream loggers (Datadog, Langfuse, OTEL, spend logs) show only one of the concurrent guardrails. Replace the shared-count heuristic with a ContextVar flag set when a guardrail records its own entry. asyncio copies the context into each gathered task, so the flag is isolated per concurrent guardrail while still catching the self-record-then-skip-auto-record case within a single invocation. * test(guardrails): declare run_in_parallel on post_call guardrail mocks The post_call partition reads run_in_parallel on every CustomGuardrail callback. A MagicMock(spec=CustomGuardrail) has no run_in_parallel (it is set in __init__, not on the class) so the attribute access raised, and even a class-level default would return a truthy child mock that wrongly routes the double into the parallel batch. Declare the flag False on the shared mock factories so these pre-existing hook tests exercise the sequential path they assert on. * fix(guardrails): harden run_in_parallel reads and address review feedback Read run_in_parallel via getattr(..., False) in the pre_call and post_call partitions so a third-party CustomGuardrail subclass that overrides __init__ without chaining super().__init__() no longer raises AttributeError on a path that previously worked. Drop the redundant in-function GuardrailEventHooks import in _run_parallel_post_call_guardrails (already imported module-level). Remove the flaky wall-clock upper-bound assertions from the two concurrency tests; the all-start-before-any-end overlap assertion is the timing-independent signal that actually proves concurrency. |
||
|---|---|---|
| .. | ||
| example_config_yaml | ||
| test_configs | ||
| test_model_response_typing | ||
| azure_fine_tune.jsonl | ||
| batch_job_results_furniture.jsonl | ||
| conftest copy.py | ||
| conftest.py | ||
| data_map.txt | ||
| eagle.wav | ||
| gettysburg.wav | ||
| large_text.py | ||
| messages_with_counts.py | ||
| model_cost.json | ||
| openai_batch_completions.jsonl | ||
| openai_batch_completions_router.jsonl | ||
| speech_vertex.mp3 | ||
| test_aproxy_startup.py | ||
| test_audit_logs_proxy.py | ||
| test_auth_checks.py | ||
| test_banned_keyword_list.py | ||
| test_blog_posts_endpoint.py | ||
| test_check_batch_cost.py | ||
| test_check_responses_cost.py | ||
| test_custom_callback_input.py | ||
| test_custom_logger_s3_gcs.py | ||
| test_custom_tokenizer_bug.py | ||
| test_db_schema_changes.py | ||
| test_default_end_user_budget_simple.py | ||
| test_deployed_proxy_keygen.py | ||
| test_deprecated_key_grace_period.py | ||
| test_e2e_pod_lock_manager.py | ||
| test_gemini_agents_endpoints.py | ||
| test_get_favicon.py | ||
| test_get_image.py | ||
| test_google_endpoint_routing.py | ||
| test_google_gemini_proxy_request.py | ||
| test_jwt.py | ||
| test_jwt_key_mapping.py | ||
| test_key_generate_dynamodb.py | ||
| test_key_generate_prisma.py | ||
| test_models_fallback_endpoint.py | ||
| test_multipart_bypass_repro.py | ||
| test_prisma_client_backoff_retry.py | ||
| test_prompt_test_endpoint.py | ||
| test_proxy_config_unit_test.py | ||
| test_proxy_custom_auth.py | ||
| test_proxy_custom_logger.py | ||
| test_proxy_encrypt_decrypt.py | ||
| test_proxy_exception_mapping.py | ||
| test_proxy_gunicorn.py | ||
| test_proxy_pass_user_config.py | ||
| test_proxy_reject_logging.py | ||
| test_proxy_routes.py | ||
| test_proxy_server.py | ||
| test_proxy_server_caching.py | ||
| test_proxy_server_keys.py | ||
| test_proxy_server_langfuse.py | ||
| test_proxy_server_spend.py | ||
| test_proxy_setting_guardrails.py | ||
| test_proxy_token_counter.py | ||
| test_proxy_utils.py | ||
| test_realtime_cache.py | ||
| test_reducto_ocr_route.py | ||
| test_request_size_limit_middleware.py | ||
| test_response_polling_handler.py | ||
| test_response_polling_pre_call_checks.py | ||
| test_search_api_logging.py | ||
| test_server_root_path.py | ||
| test_skills_db.py | ||
| test_ui_path_detection.py | ||
| test_unit_test_max_model_budget_limiter.py | ||
| test_unit_test_proxy_hooks.py | ||
| test_update_daily_tag_spend.py | ||
| test_update_spend.py | ||
| test_user_api_key_auth.py | ||
| test_zero_cost_model_budget_bypass.py | ||
| vertex_key.json | ||