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
Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_fix_post_call_policy_pipeline
mateo-berricecd481ae3cc
diff --cc litellm/proxy/policy_engine/pipeline_executor.pyindex 9bc10949e9f,1bcda38657b..7bcb79cefc9--- a/litellm/proxy/policy_engine/pipeline_executor.py+++ b/litellm/proxy/policy_engine/pipeline_executor.py@@@ -20,8 -16,11 +20,12 @@@ from litellm.integrations.custom_guardrModifyResponseException,)from litellm.integrations.custom_logger import CustomLogger- from litellm.litellm_core_utils.core_helpers import independent_snapshot+ from litellm.litellm_core_utils.core_helpers import (+ get_metadata_variable_name_from_kwargs,+ get_or_create_metadata_bucket,+ independent_snapshot,+ )+from litellm.proxy.common_utils.callback_utils import add_guardrail_to_applied_guardrails_headerfrom litellm.proxy.guardrails.guardrail_hooks.unified_guardrail.unified_guardrail import (UnifiedLLMGuardrails,)@@@ -30,14 -29,7 +34,14 @@@ from litellm.types.proxy.policy_engine.PipelineStep,PipelineStepResult,)- from litellm.types.utils import GenericGuardrailAPIInputs-from litellm.types.utils import StandardLoggingGuardrailInformation++from litellm.types.utils import GenericGuardrailAPIInputs, StandardLoggingGuardrailInformation++if TYPE_CHECKING:+ from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+ from litellm.llms.base_llm.guardrail_translation.base_translation import (+ BaseTranslation,+ )+ from litellm.proxy._types import UserAPIKeyAuthtry:from fastapi.exceptions import HTTPException@@@ -357,16 -175,33 +363,17 @@@ class PipelineExecutorverbose_proxy_logger.warning("Pipeline: guardrail '%s' not found in callbacks", step.guardrail)return ("error", None, f"Guardrail '{step.guardrail}' not found", None)- try:- hook_input, scans_raw_request = _prepare_hook_input(step, callback, data, raw_request_snapshot)- # Inject guardrail name into metadata so should_run_guardrail() allows it- if "metadata" not in data:- data["metadata"] = {}- data["metadata"]["guardrails"] = [step.guardrail]-- # A scan_raw_request step evaluates the pristine pre-pipeline- # snapshot instead of `data` (which earlier pass_data steps in- # this same pipeline may have already rewritten), same reason- # the normal sequential/parallel guardrail loops do this.- scans_raw_request: Final = callback.scan_raw_request- hook_input: Final[dict] = ( # mutable-ok: same request-payload shape as data- independent_snapshot(raw_request_snapshot)- if scans_raw_request and raw_request_snapshot is not None- else data- )- if hook_input is not data:- hook_input.setdefault("metadata", {})["guardrails"] = [step.guardrail]++ hook_input, scans_raw_request = _prepare_hook_input(step, callback, data, raw_request_snapshot)+ snapshot_entries_before: Final = len(_recorded_guardrail_information(hook_input))- # Use unified_guardrail path if callback implements apply_guardrail- target: CustomLogger = callback- use_unified: Final = PipelineExecutor.supports_unified_execution(callback)- if use_unified and streaming_chunks is None:- hook_input["guardrail_to_apply"] = callback- target = UnifiedLLMGuardrails()+ # Use unified_guardrail path if callback implements apply_guardrail+ target: CustomLogger = callback- use_unified: Final = "apply_guardrail" in type(callback).__dict__ and not callback.use_native_lifecycle_hooks- if use_unified:++ use_unified: Final = PipelineExecutor.supports_unified_execution(callback)++ if use_unified and streaming_chunks is None:+ hook_input["guardrail_to_apply"] = callback+ target = UnifiedLLMGuardrails()+ try:if mode == "pre_call":response = await target.async_pre_call_hook(user_api_key_dict=user_api_key_dict,@@@ -430,13 -239,13 +437,19 @@@else:verbose_proxy_logger.error("Pipeline: unexpected error from guardrail '%s': %s", step.guardrail, e)return ("error", None, str(e), e)+ finally:+ if hook_input is not data:+ _append_guardrail_information(+ request_data=data,+ entries=_recorded_guardrail_information(hook_input)[snapshot_entries_before:],+ )+ @staticmethod+ def supports_unified_execution(callback: CustomGuardrail) -> bool:+ """Whether this guardrail runs through the unified apply_guardrail path,+ the interface streaming pipeline execution requires."""+ return "apply_guardrail" in type(callback).__dict__ and not callback.use_native_lifecycle_hooks+@staticmethoddef find_guardrail_callback(guardrail_name: str) -> CustomGuardrail | None:"""Look up an initialized guardrail callback by name from litellm.callbacks."""diff --cc tests/test_litellm/proxy/policy_engine/test_pipeline_executor.pyindex 54ef1f79f4d,e95d001bb12..61880a8c6f6--- a/tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py+++ b/tests/test_litellm/proxy/policy_engine/test_pipeline_executor.py@@@ -4,7 -4,8 +4,9 @@@ Tests for the pipeline executorUses mock guardrails to validate pipeline execution without external services."""+ import copy+import logging+ from typing import Literalfrom unittest.mock import MagicMockimport pytest@@@ -14,7 -17,8 +18,8 @@@ from litellm.proxy._types import UserAPfrom litellm.proxy.guardrails.guardrail_hooks.custom_code.custom_code_guardrail import (CustomCodeGuardrail,)-from litellm.proxy.policy_engine.pipeline_executor import PipelineExecutor+from litellm.proxy.policy_engine.pipeline_executor import PipelineExecutor, UndeliverableStreamRewrite+ from litellm.types.guardrails import GuardrailEventHooksfrom litellm.types.proxy.policy_engine.pipeline_types import (GuardrailPipeline,PipelineStep,