Skip to content

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]

Merge remote-tracking branch 'origin/litellm_internal_staging' into litellm_fix_post_call_policy_pipeline

mateo-berri45a6b1de23e1
diff --cc litellm/proxy/policy_engine/pipeline_executor.py
index acd2c2c973a,50cb813c6fa..21f3aca3f58
--- a/litellm/proxy/policy_engine/pipeline_executor.py
+++ b/litellm/proxy/policy_engine/pipeline_executor.py
@@@ -41,90 -31,6 +41,92 @@@ except ImportError
HTTPException = None
+class UndeliverableStreamRewrite(Exception):
+ def __init__(self, guardrail_name: str) -> None:
+ super().__init__(
+ f"Guardrail '{guardrail_name}' rewrote the streamed response, which streaming pipelines cannot deliver"
+ )
+ self.guardrail_name: Final = guardrail_name
+
+
+def _tool_call_shape(tool_call: object) -> tuple[object, object]:
+ plain: Final = tool_call.model_dump() if isinstance(tool_call, BaseModel) else tool_call
+ function: Final = plain.get("function") if isinstance(plain, Mapping) else None
+ if not isinstance(function, Mapping):
+ return (None, None)
+ return (function.get("name"), function.get("arguments"))
+
+
+def _rewrote_texts(sent: Sequence[str] | None, returned: Sequence[str] | None) -> bool:
- return sent is not None and returned is not None and list(returned) != list(sent)
++ return sent is not None and returned is not None and tuple(returned) != tuple(sent)
+
+
+def _rewrote_tool_calls(sent: Sequence[object] | None, returned: Sequence[object] | None) -> bool:
+ if sent is None or returned is None:
+ return False
- return [_tool_call_shape(tool_call) for tool_call in returned] != [
++ return tuple(_tool_call_shape(tool_call) for tool_call in returned) != tuple(
+ _tool_call_shape(tool_call) for tool_call in sent
- ]
++ )
+
+
+class _StreamRewriteObserver(CustomGuardrail):
+ """Stand-in handed to the endpoint translation in place of a streaming pipeline step's
+ guardrail. Translations cannot rewrite every buffered chunk consistently, so the gate
+ withholds the stream whenever the guardrail returned different output than it was given,
+ which for guardrails like Bedrock's ANONYMIZED action is only known at runtime."""
+
+ def __init__(self, inner: CustomGuardrail) -> None:
+ super().__init__(guardrail_name=inner.guardrail_name)
+ self.inner: Final = inner
+ self.rewrote = False
+
+ def structured_messages_cover_full_request(self) -> bool:
+ return self.inner.structured_messages_cover_full_request()
+
+ async def apply_guardrail(
+ self,
+ inputs: GenericGuardrailAPIInputs,
+ request_data: dict, # mutable-ok: matches CustomGuardrail.apply_guardrail
+ input_type: Literal["request", "response"],
+ logging_obj: "LiteLLMLoggingObj | None" = None,
+ ) -> GenericGuardrailAPIInputs:
+ outputs: Final = await self.inner.apply_guardrail(
+ inputs=inputs, request_data=request_data, input_type=input_type, logging_obj=logging_obj
+ )
+ self.rewrote = (
+ self.rewrote
+ or _rewrote_texts(inputs.get("texts"), outputs.get("texts"))
+ or _rewrote_tool_calls(inputs.get("tool_calls"), outputs.get("tool_calls"))
+ )
+ return outputs
+
+
+def _prepare_hook_input(
+ step: PipelineStep,
- callback: CustomLogger,
++ callback: CustomGuardrail,
+ data: dict, # mutable-ok: same request-payload shape the hooks mutate
+ raw_request_snapshot: dict | None, # mutable-ok: same request-payload shape as data
+) -> tuple[dict, bool]: # mutable-ok: returns that same request-payload dict
+ """Inject the step's guardrail name into metadata so should_run_guardrail() allows it,
+ and pick the payload the step scans: 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."""
+ if "metadata" not in data:
- data["metadata"] = {}
- data["metadata"]["guardrails"] = [step.guardrail]
++ data["metadata"] = {} # mutable-ok: request metadata bucket, hooks mutate it
++ data["metadata"]["guardrails"] = [
++ step.guardrail
++ ] # mutable-ok: guardrails list is part of the request-payload shape
+
- scans_raw_request: Final = getattr(callback, "scan_raw_request", False)
++ 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.setdefault("metadata", {})["guardrails"] = [step.guardrail] # mutable-ok: request metadata shape
+ return hook_input, scans_raw_request
+
+
class PipelineExecutor:
"""Executes guardrail pipelines with ordered, conditional step logic."""
@@@ -336,17 -227,12 +338,22 @@@
# same contract as run_in_parallel/scan_raw_request elsewhere: any
# data it returned is discarded, since applying it on top of the
# raw snapshot would silently undo whatever an earlier step in
- # this pipeline already did.
- modified_data = None
- if response is not None and isinstance(response, dict) and not scans_raw_request:
- modified_data = response
- return ("pass", modified_data, None, None)
+ # this pipeline already did. A post_call hook's non-None return is
+ # a replacement response (the flat callback-loop contract), carried
+ # under the same "response" key the step input uses.
+ if response is None or scans_raw_request:
+ return ("pass", None, None, None)
+ if mode == "post_call":
- return ("pass", {"response": response}, None, None)
++ return (
++ "pass",
++ {"response": response},
++ None,
++ None,
++ ) # mutable-ok: modified-data contract is a plain dict
+ return ("pass", response if isinstance(response, dict) else None, None, None)
+ except UndeliverableStreamRewrite:
+ raise
except Exception as e:
if CustomGuardrail._is_guardrail_intervention(e):
error_msg: Final = _extract_error_message(e)
diff --cc litellm/proxy/utils.py
index 6c990222e51,cf56fc0b1dd..f9d018bc452
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@@ -447,179 -446,13 +447,205 @@@ def _policy_pipelines(data: Mapping[str
)
-def _pipeline_managed_guardrail_names(data: Mapping[str, object]) -> frozenset[str]:
- managed: Final = _policy_state_metadata(data).get("_pipeline_managed_guardrails")
- return (
- frozenset(cast("Collection[str]", managed)) # cast-ok: the policy engine wrote these guardrail names
- if managed
- else frozenset()
+def _pipeline_managed_guardrail_names(
+ data: Mapping[str, object], mode: Literal["pre_call", "post_call"]
+) -> frozenset[str]:
+ return frozenset(
+ step.guardrail
+ for _policy_name, pipeline in _policy_pipelines(data)
+ if pipeline.mode == mode
+ for step in pipeline.steps
+ )
+
+
- def _merge_pipeline_metadata_bucket(data: dict, bucket_key: str, modified_bucket_value: object) -> None:
++def _partition_post_call_callbacks() -> tuple[tuple[CustomGuardrail, ...], tuple[CustomLogger, ...]]:
++ resolved: Final = tuple(
++ litellm.litellm_core_utils.litellm_logging.get_custom_logger_compatible_class(
++ cast( # cast-ok: the resolver returns None for unknown names, filtered below
++ _custom_logger_compatible_callbacks_literal, callback
++ )
++ )
++ if isinstance(callback, str)
++ else callback
++ for callback in litellm.callbacks
++ )
++ present: Final = tuple(callback for callback in resolved if callback is not None)
++ guardrails: Final = tuple(callback for callback in present if isinstance(callback, CustomGuardrail))
++ others: Final = cast( # cast-ok: mirrors the legacy loop, which treated every non-guardrail entry as a CustomLogger
++ "tuple[CustomLogger, ...]",
++ tuple(callback for callback in present if not isinstance(callback, CustomGuardrail)),
+ )
++ return (guardrails, others)
++
++
++def _merge_pipeline_metadata_bucket(
++ data: dict, bucket_key: str, modified_bucket_value: object
++) -> None: # mutable-ok: request payload dict, written in place
+ if not isinstance(modified_bucket_value, dict):
+ return
+ modified_bucket: Final = cast("dict[str, object]", modified_bucket_value) # cast-ok: metadata buckets are str-keyed
- surviving_writes: Final = {key: value for key, value in modified_bucket.items() if key != "guardrails"}
++ surviving_writes: Final = {
++ key: value for key, value in modified_bucket.items() if key != "guardrails"
++ } # mutable-ok: merged into the live request metadata bucket in place
+ existing_bucket: Final = data.get(bucket_key)
+ if isinstance(existing_bucket, dict):
+ cast("dict[str, object]", existing_bucket).update(surviving_writes) # cast-ok: metadata buckets are str-keyed
+ else:
+ data[bucket_key] = surviving_writes
+
+
- def _merge_pipeline_metadata_writes(data: dict, modified_data: Mapping[str, object]) -> None:
++def _merge_pipeline_metadata_writes(
++ data: dict, modified_data: Mapping[str, object]
++) -> None: # mutable-ok: request payload dict, written in place
+ """
+ Copy metadata-bucket writes from a pipeline's working copy back onto the request.
+
+ Post_call pipelines run step hooks against a copied request dict so the payload
+ already sent upstream stays untouched, but hooks record proxy-internal logging
+ state in the metadata buckets (``applied_guardrails`` for response headers,
+ ``standard_logging_guardrail_information`` for spend logs), and those writes
+ must reach the request dict the proxy keeps reading after the pipeline returns.
+
+ The ``guardrails`` key is the executor's per-step activation flag for
+ ``should_run_guardrail``, not a hook write, so it stays in the working copy.
+ """
+ for bucket_key in ("metadata", "litellm_metadata"):
+ _merge_pipeline_metadata_bucket(data, bucket_key, modified_data.get(bucket_key))
+
+
+def _pipeline_step_supports_unified_streaming(guardrail_name: str) -> bool:
+ callback: Final = PipelineExecutor.find_guardrail_callback(guardrail_name)
+ return callback is not None and PipelineExecutor.supports_unified_execution(callback)
+
+
+def _pipeline_step_rewrites_streamed_content(guardrail_name: str) -> bool:
+ callback: Final = PipelineExecutor.find_guardrail_callback(guardrail_name)
+ if callback is None:
+ return False
+ transform_mode: Final = unified_guardrail.resolve_streaming_flag(callback, "streaming_transform_mode", "block_only")
+ return callback.rewrites_streamed_output() or transform_mode == "incremental_diff"
+
+
+class _PipelineErrorBody(TypedDict):
+ message: ReadOnly[str]
+ type: ReadOnly[str]
+ policies: ReadOnly[tuple[str, ...]]
+ guardrails: NotRequired[ReadOnly[tuple[str, ...]]]
+
+
+class _PipelineErrorDetail(TypedDict):
+ error: ReadOnly[_PipelineErrorBody]
+
+
+def _undeliverable_stream_rewrite_error(policy_name: str, guardrail_name: str) -> HTTPException:
+ detail: Final[_PipelineErrorDetail] = {
+ "error": {
+ "message": (
+ f"Streaming response withheld by policy pipeline '{policy_name}' because guardrail "
+ f"'{guardrail_name}' rewrote the streamed output, and streaming pipelines cannot deliver "
+ "rewrites. Retry with stream=false, or drop it from the pipeline steps so guardrails.add "
+ "applies it to streamed output."
+ ),
+ "type": "guardrail_pipeline_error",
+ "policies": (policy_name,),
+ "guardrails": (guardrail_name,),
+ }
+ }
+ return HTTPException(status_code=400, detail=detail)
+
+
+def _raise_for_streaming_post_call_pipelines(data: Mapping[str, object], user_api_key_dict: UserAPIKeyAuth) -> None:
+ """
+ Reject up front the requests whose post_call pipelines could never run.
+
+ Background responses skip the post_call hooks entirely, so a pipeline
+ governing one would silently never execute. Streaming responses execute
+ pipelines against the buffered stream through the endpoint guardrail
+ translation of the request route, releasing the buffered chunks on allow.
+ That needs every step's guardrail to support the unified apply_guardrail
+ interface and to only allow or block (a step that rewrites streamed
+ content, via mask_response_content, a MASK action, or
+ streaming_transform_mode=incremental_diff, would have its rewrite silently
+ dropped), and needs the route to have a translation at all; anything else
+ keeps the 400 rather than letting ungoverned output stream through.
+ """
+ is_stream: Final = data.get("stream") is True
+ is_background: Final = data.get("background") is True
+ if not is_stream and not is_background:
+ return
+ post_call_pipelines: Final = tuple(
+ (policy_name, pipeline) for policy_name, pipeline in _policy_pipelines(data) if pipeline.mode == "post_call"
+ )
+ if not post_call_pipelines:
+ return
+ post_call_policies: Final = tuple(policy_name for policy_name, _pipeline in post_call_pipelines)
+ if is_background:
+ background_detail: Final[_PipelineErrorDetail] = {
+ "error": {
+ "message": (
+ "Policies with post_call guardrail pipelines cannot govern background "
+ f"responses: {', '.join(post_call_policies)}. Retry with background=false."
+ ),
+ "type": "guardrail_pipeline_error",
+ "policies": post_call_policies,
+ }
+ }
+ raise HTTPException(status_code=400, detail=background_detail)
+ step_guardrails: Final = tuple(
+ dict.fromkeys(step.guardrail for _policy_name, pipeline in post_call_pipelines for step in pipeline.steps)
+ )
+ unsupported_guardrails: Final = tuple(
+ guardrail for guardrail in step_guardrails if not _pipeline_step_supports_unified_streaming(guardrail)
+ )
+ if unsupported_guardrails:
+ unsupported_detail: Final[_PipelineErrorDetail] = {
+ "error": {
+ "message": (
+ "Policies with post_call guardrail pipelines cannot govern streaming responses "
+ "because these pipeline guardrails do not support the unified apply_guardrail "
+ f"interface: {', '.join(unsupported_guardrails)}. Retry with stream=false, or drop "
+ "them from the pipeline steps so guardrails.add scans them on streamed output."
+ ),
+ "type": "guardrail_pipeline_error",
+ "policies": post_call_policies,
+ "guardrails": unsupported_guardrails,
+ }
+ }
+ raise HTTPException(status_code=400, detail=unsupported_detail)
+ rewriting_guardrails: Final = tuple(
+ guardrail for guardrail in step_guardrails if _pipeline_step_rewrites_streamed_content(guardrail)
+ )
+ if rewriting_guardrails:
+ rewriting_detail: Final[_PipelineErrorDetail] = {
+ "error": {
+ "message": (
+ "Policies with post_call guardrail pipelines cannot govern streaming responses "
+ "because these pipeline guardrails rewrite streamed content (mask_response_content, "
+ "a MASK action, or streaming_transform_mode=incremental_diff), which pipeline steps would release "
+ f"unmodified: {', '.join(rewriting_guardrails)}. Retry with stream=false, or drop "
+ "them from the pipeline steps so guardrails.add applies them to streamed output."
+ ),
+ "type": "guardrail_pipeline_error",
+ "policies": post_call_policies,
+ "guardrails": rewriting_guardrails,
+ }
+ }
+ raise HTTPException(status_code=400, detail=rewriting_detail)
+ route: Final = user_api_key_dict.request_route
+ if not route or resolve_endpoint_translation(user_api_key_dict, None) is not None:
+ return
+ route_detail: Final[_PipelineErrorDetail] = {
+ "error": {
+ "message": (
+ "Policies with post_call guardrail pipelines cannot govern streaming responses on "
+ f"route {route} because it has no endpoint guardrail translation to scan the stream "
+ f"through: {', '.join(post_call_policies)}. Retry with stream=false."
+ ),
+ "type": "guardrail_pipeline_error",
+ "policies": post_call_policies,
+ }
+ }
+ raise HTTPException(status_code=400, detail=route_detail)
def _prompt_block_text(block: object) -> str:
@@@ -1745,8 -1578,7 +1771,8 @@@ class ProxyLogging
call_type: str,
event_hook: str,
raw_request_snapshot: dict | None = None, # mutable-ok: same request-payload shape as data
- ) -> dict:
+ response: LLMResponseTypes | None = None,
- ) -> tuple[dict, LLMResponseTypes | None]:
++ ) -> tuple[dict, LLMResponseTypes | None]: # mutable-ok: returns the request-payload dict onward
"""
Execute guardrail pipelines if any are configured for this request.
@@@ -1771,8 -1600,6 +1797,10 @@@
if pipeline.mode != event_hook:
continue
- step_input: dict = {**data, "response": current_response} if current_response is not None else data
++ step_input: dict = (
++ {**data, "response": current_response} if current_response is not None else data
++ ) # mutable-ok: same request-payload shape as data
+
result: PipelineExecutionResult = await PipelineExecutor.execute_steps(
steps=pipeline.steps,
mode=pipeline.mode,
@@@ -2965,37 -2770,26 +2989,19 @@@
from litellm.proxy.proxy_server import llm_router
from litellm.types.guardrails import GuardrailEventHooks
- guardrail_callbacks: Final[list[CustomGuardrail]] = []
- other_callbacks: Final[list[CustomLogger]] = []
- try:
- for callback in litellm.callbacks:
- _callback: CustomLogger | None = None
- if isinstance(callback, str):
- _callback = litellm.litellm_core_utils.litellm_logging.get_custom_logger_compatible_class(
- cast(_custom_logger_compatible_callbacks_literal, callback)
- )
- else:
- _callback = callback
-
- if _callback is not None:
- if isinstance(_callback, CustomGuardrail):
- guardrail_callbacks.append(_callback)
- else:
- other_callbacks.append(_callback)
- ############## Handle Guardrails ########################################
- #############################################################################
+ _, pipeline_response = await self._maybe_execute_pipelines(
+ data=data,
+ user_api_key_dict=user_api_key_dict,
+ call_type=getattr(data.get("litellm_logging_obj"), "call_type", None) or "acompletion",
+ event_hook="post_call",
+ response=response,
+ )
+ if pipeline_response is not None:
+ response = pipeline_response # rebind-ok: adopt the pipeline's replacement response, same contract as the callback loops below
+ pipeline_managed: Final = _pipeline_managed_guardrail_names(data, "post_call")
- guardrail_callbacks: Final[list[CustomGuardrail]] = []
- other_callbacks: Final[list[CustomLogger]] = []
++ guardrail_callbacks, other_callbacks = _partition_post_call_callbacks()
+ try:
- for callback in litellm.callbacks:
- _callback: CustomLogger | None = None
- if isinstance(callback, str):
- _callback = litellm.litellm_core_utils.litellm_logging.get_custom_logger_compatible_class(
- cast(_custom_logger_compatible_callbacks_literal, callback)
- )
- else:
- _callback = callback
-
- if _callback is not None:
- if isinstance(_callback, CustomGuardrail):
- guardrail_callbacks.append(_callback)
- else:
- other_callbacks.append(_callback)
- ############## Handle Guardrails ########################################
- #############################################################################
-
# Merge model-level guardrails before checking which guardrails to run
guardrail_data: Final = _check_and_merge_model_level_guardrails(data=data, llm_router=llm_router)
@@@ -3471,90 -3238,6 +3477,90 @@@
# we reach this point the metadata is fully populated.
ProxyLogging._fire_deferred_stream_logging(request_data)
+ async def _pipeline_gated_stream(
+ self,
+ response: "AsyncGenerator[object, None]",
+ user_api_key_dict: UserAPIKeyAuth,
- request_data: dict,
++ request_data: dict, # mutable-ok: same request-payload shape the hooks mutate
+ pipelines: "tuple[tuple[str, GuardrailPipeline], ...]",
+ ) -> "AsyncGenerator[Any, None]":
+ """
+ Execute post_call policy pipelines against a streamed response.
+
+ Buffers the whole stream (nothing reaches the client until every
+ pipeline allows it), then runs each pipeline's steps against the
+ assembled output through the endpoint guardrail translation, the same
+ machinery flat post_call guardrails use at end of stream. An allow
+ releases the buffered chunks verbatim; a step whose guardrail rewrote
+ the output withholds the stream with a 400 instead, since no
+ translation rewrites every buffered chunk consistently and some
+ rewrites (Bedrock's ANONYMIZED action, for one) are only decided at
+ runtime; a block or modify_response terminates with the translation's
+ block chunks or the raised error.
+ """
+ buffered: Final[list[object]] = [] # mutable-ok: accumulates the stream before the pipeline verdict
+ async for item in response:
+ buffered.append(item)
+ if not buffered:
+ return
+
+ resolved: Final = resolve_endpoint_translation(user_api_key_dict, buffered[0])
+ if resolved is None:
+ policy_names: Final = tuple(policy_name for policy_name, _pipeline in pipelines)
+ raise ProxyException(
+ message=(
+ "Policy pipelines could not govern this streaming response shape; "
+ f"the response was withheld: {', '.join(policy_names)}."
+ ),
+ type="guardrail_pipeline_error",
+ param=None,
+ code=500,
+ )
+ call_type, endpoint_translation = resolved
+
+ for policy_name, pipeline in pipelines:
+ try:
+ result: PipelineExecutionResult = await PipelineExecutor.execute_steps(
+ steps=pipeline.steps,
+ mode="post_call",
+ data=request_data,
+ user_api_key_dict=user_api_key_dict,
+ call_type=call_type,
+ policy_name=policy_name,
+ streaming_chunks=buffered,
+ endpoint_translation=endpoint_translation,
+ )
+ except UndeliverableStreamRewrite as rewrite:
+ async for error_chunk in unified_guardrail.emit_streaming_http_error(
+ _undeliverable_stream_rewrite_error(policy_name, rewrite.guardrail_name),
+ call_type,
+ buffered,
+ request_data,
+ ):
+ yield error_chunk
+ return
+ try:
+ ProxyLogging._handle_pipeline_result(
+ result, data=request_data, policy_name=policy_name, original_response=buffered
+ )
+ except ModifyResponseException as e:
+ if e.original_response is None:
+ e.original_response = buffered
+ async for block_chunk in unified_guardrail.handle_streaming_block(
+ e, endpoint_translation, stream_started=False, responses_so_far=()
+ ):
+ yield block_chunk
+ return
+ except HTTPException as e:
+ async for error_chunk in unified_guardrail.emit_streaming_http_error(
+ e, call_type, buffered, request_data
+ ):
+ yield error_chunk
+ return
+
+ for buffered_item in buffered:
+ yield buffered_item
+
@staticmethod
def _fire_deferred_stream_logging(request_data: dict) -> None:
"""