Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
249 changes: 144 additions & 105 deletions litellm/proxy/common_request_processing.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,8 @@
from litellm.proxy.route_llm_request import route_request
from litellm.proxy.utils import ProxyLogging
from litellm.router import Router
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.types.guardrails import GuardrailEventHooks
from litellm.types.utils import ServerToolUse

# Type alias for streaming chunk serializer (chunk after hooks + cost injection -> wire format)
Expand Down Expand Up @@ -801,7 +803,7 @@ def _debug_log_request_payload(self) -> None:
json.dumps(self.data, indent=4, default=str),
)

async def base_process_llm_request(
async def base_process_llm_request( # noqa: PLR0915
self,
request: Request,
fastapi_response: Response,
Expand Down Expand Up @@ -926,6 +928,11 @@ async def base_process_llm_request(
llm_router=llm_router,
)

# Defer async logging when post-call guardrails are configured so the
# StandardLoggingPayload is built after guardrails write to metadata.
if self._has_post_call_guardrails():
logging_obj._defer_async_logging = True # type: ignore
Comment on lines +931 to +942

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 _defer_async_logging flag is set even for requests that will take a streaming early-return

_has_post_call_guardrails() is evaluated unconditionally before route_request, so when post-call guardrails are registered, _defer_async_logging = True is set on every logging_obj — including those for streaming requests that will ultimately return from within the try block (e.g., allm_passthrough_route, anthropic_messages streaming, select_data_generator). For those paths wrapper_async returns a CustomStreamWrapper before reaching the closure-storage code in utils.py, so _enqueue_deferred_logging is never stored and the finally block is a harmless no-op.

However, the _defer_async_logging = True flag persists on logging_obj for the lifetime of the streaming wrapper, and any future code that reads this flag on the streaming logging_obj could behave unexpectedly. A guard like if not (self._is_streaming_request(...) or ...) around the flag-set, or a reset of the flag inside the streaming exit path, would make the invariant explicit.


tasks = []
# Start the moderation check (during_call_hook) as early as possible
# This gives it a head start to mask/validate input while the proxy handles routing
Expand Down Expand Up @@ -962,124 +969,136 @@ async def base_process_llm_request(

response = responses[1]

hidden_params = getattr(response, "_hidden_params", {}) or {}
model_id = self._get_model_id_from_response(hidden_params, self.data)

cache_key, api_base, response_cost = (
hidden_params.get("cache_key", None) or "",
hidden_params.get("api_base", None) or "",
hidden_params.get("response_cost", None) or "",
)
fastest_response_batch_completion, additional_headers = (
hidden_params.get("fastest_response_batch_completion", None),
hidden_params.get("additional_headers", {}) or {},
)
try:
hidden_params = getattr(response, "_hidden_params", {}) or {}
model_id = self._get_model_id_from_response(hidden_params, self.data)

# Post Call Processing
if llm_router is not None:
self.data["deployment"] = llm_router.get_deployment(model_id=model_id)
asyncio.create_task(
proxy_logging_obj.update_request_status(
litellm_call_id=self.data.get("litellm_call_id", ""), status="success"
cache_key, api_base, response_cost = (
hidden_params.get("cache_key", None) or "",
hidden_params.get("api_base", None) or "",
hidden_params.get("response_cost", None) or "",
)
)
if self._is_streaming_request(
data=self.data, is_streaming_request=is_streaming_request
) or self._is_streaming_response(
response
): # use generate_responses to stream responses
custom_headers = ProxyBaseLLMRequestProcessing.get_custom_headers(
user_api_key_dict=user_api_key_dict,
call_id=logging_obj.litellm_call_id,
model_id=model_id,
cache_key=cache_key,
api_base=api_base,
version=version,
response_cost=response_cost,
model_region=getattr(user_api_key_dict, "allowed_model_region", ""),
fastest_response_batch_completion=fastest_response_batch_completion,
request_data=self.data,
hidden_params=hidden_params,
litellm_logging_obj=logging_obj,
**additional_headers,
fastest_response_batch_completion, additional_headers = (
hidden_params.get("fastest_response_batch_completion", None),
hidden_params.get("additional_headers", {}) or {},
)

# Call response headers hook for streaming success
callback_headers = await proxy_logging_obj.post_call_response_headers_hook(
data=self.data,
user_api_key_dict=user_api_key_dict,
response=response,
request_headers=dict(request.headers),
# Post Call Processing
if llm_router is not None:
self.data["deployment"] = llm_router.get_deployment(model_id=model_id)
asyncio.create_task(
proxy_logging_obj.update_request_status(
litellm_call_id=self.data.get("litellm_call_id", ""), status="success"
)
)
if callback_headers:
custom_headers.update(callback_headers)

# Preserve the original client-requested model (pre-alias mapping) for downstream
# streaming generators. Pre-call processing can rewrite `self.data["model"]` for
# aliasing/routing, but the OpenAI-compatible response `model` field should reflect
# what the client sent.
if requested_model_from_client:
self.data[
"_litellm_client_requested_model"
] = requested_model_from_client
if route_type == "allm_passthrough_route":
# Check if response is an async generator
if self._is_streaming_response(response):
if asyncio.iscoroutine(response):
generator = await response
else:
generator = response
if self._is_streaming_request(
data=self.data, is_streaming_request=is_streaming_request
) or self._is_streaming_response(
response
): # use generate_responses to stream responses
custom_headers = ProxyBaseLLMRequestProcessing.get_custom_headers(
user_api_key_dict=user_api_key_dict,
call_id=logging_obj.litellm_call_id,
model_id=model_id,
cache_key=cache_key,
api_base=api_base,
version=version,
response_cost=response_cost,
model_region=getattr(user_api_key_dict, "allowed_model_region", ""),
fastest_response_batch_completion=fastest_response_batch_completion,
request_data=self.data,
hidden_params=hidden_params,
litellm_logging_obj=logging_obj,
**additional_headers,
)

# For passthrough routes, stream directly without error parsing
# since we're dealing with raw binary data (e.g., AWS event streams)
return StreamingResponse(
content=generator,
status_code=status.HTTP_200_OK,
headers=custom_headers,
)
else:
# Traditional HTTP response with aiter_bytes
return StreamingResponse(
content=response.aiter_bytes(),
status_code=response.status_code,
headers=custom_headers,
)
elif route_type == "anthropic_messages":
# Check if response is actually a streaming response (async generator)
# Non-streaming responses (dict) should be returned directly
# This handles cases like websearch_interception agentic loop
# which returns a non-streaming dict even for streaming requests
if self._is_streaming_response(response):
selected_data_generator = (
ProxyBaseLLMRequestProcessing.async_sse_data_generator(
response=response,
user_api_key_dict=user_api_key_dict,
request_data=self.data,
proxy_logging_obj=proxy_logging_obj,
# Call response headers hook for streaming success
callback_headers = await proxy_logging_obj.post_call_response_headers_hook(
data=self.data,
user_api_key_dict=user_api_key_dict,
response=response,
request_headers=dict(request.headers),
)
if callback_headers:
custom_headers.update(callback_headers)

# Preserve the original client-requested model (pre-alias mapping) for downstream
# streaming generators. Pre-call processing can rewrite `self.data["model"]` for
# aliasing/routing, but the OpenAI-compatible response `model` field should reflect
# what the client sent.
if requested_model_from_client:
self.data[
"_litellm_client_requested_model"
] = requested_model_from_client
if route_type == "allm_passthrough_route":
# Check if response is an async generator
if self._is_streaming_response(response):
if asyncio.iscoroutine(response):
generator = await response
else:
generator = response

# For passthrough routes, stream directly without error parsing
# since we're dealing with raw binary data (e.g., AWS event streams)
return StreamingResponse(
content=generator,
status_code=status.HTTP_200_OK,
headers=custom_headers,
)
else:
# Traditional HTTP response with aiter_bytes
return StreamingResponse(
content=response.aiter_bytes(),
status_code=response.status_code,
headers=custom_headers,
)
elif route_type == "anthropic_messages":
# Check if response is actually a streaming response (async generator)
# Non-streaming responses (dict) should be returned directly
# This handles cases like websearch_interception agentic loop
# which returns a non-streaming dict even for streaming requests
if self._is_streaming_response(response):
selected_data_generator = (
ProxyBaseLLMRequestProcessing.async_sse_data_generator(
response=response,
user_api_key_dict=user_api_key_dict,
request_data=self.data,
proxy_logging_obj=proxy_logging_obj,
)
)
return await create_response(
generator=selected_data_generator,
media_type="text/event-stream",
headers=custom_headers,
)
# Non-streaming response - fall through to normal response handling
elif select_data_generator:
selected_data_generator = select_data_generator(
response=response,
user_api_key_dict=user_api_key_dict,
request_data=self.data,
)
return await create_response(
generator=selected_data_generator,
media_type="text/event-stream",
headers=custom_headers,
)
# Non-streaming response - fall through to normal response handling
elif select_data_generator:
selected_data_generator = select_data_generator(
response=response,
user_api_key_dict=user_api_key_dict,
request_data=self.data,
)
return await create_response(
generator=selected_data_generator,
media_type="text/event-stream",
headers=custom_headers,
)

### CALL HOOKS ### - modify outgoing data
response = await proxy_logging_obj.post_call_success_hook(
data=self.data, user_api_key_dict=user_api_key_dict, response=response
)
### CALL HOOKS ### - modify outgoing data
response = await proxy_logging_obj.post_call_success_hook(
data=self.data, user_api_key_dict=user_api_key_dict, response=response
)
Comment on lines +1180 to +1189

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Standard streaming + post-call guardrails still race

For standard OpenAI-compatible streaming requests (i.e. those that don't hit the allm_passthrough_route, anthropic_messages, or select_data_generator early-returns), control flows straight through the streaming branch and arrives at post_call_success_hook on line 1086. So guardrails DO run. However, because wrapper_async returned the CustomStreamWrapper early (before the closure-storage block in utils.py), _enqueue_deferred_logging is never set.

As a result the per-chunk success logging emitted by CustomStreamWrapper still fires before post_call_success_hook completes, reproducing the original guardrail_information=None bug for streaming requests with post-call guardrails.

The PR description is clear that this fix targets the non-streaming case, but the limitation may be worth documenting with a TODO or follow-up issue so it isn't lost.

finally:
# Enqueue deferred logging after post-call guardrails have written
# guardrail_information to metadata. The finally block ensures
# logging fires even if a guardrail raises (matching the current
# behavior where create_task fires before post_call_success_hook).
# For streaming early-returns: no closure is stored (wrapper_async
# returns before line 1946), so _enqueue_fn is None — this is a no-op.
_enqueue_fn = getattr(logging_obj, "_enqueue_deferred_logging", None)
if _enqueue_fn is not None:
logging_obj._enqueue_deferred_logging = None # type: ignore[attr-defined]
_enqueue_fn()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Exception in finally can mask guardrail error

If post_call_success_hook raises (e.g., a guardrail blocks content with HTTPException) and then _enqueue_fn() also raises (e.g., a RuntimeError from asyncio.create_task in a degraded state), Python will replace the original exception with the one from finally. The caller — and the client — will see a logging error instead of the guardrail's blocking response.

Wrapping the closure call in a bare except (log-and-swallow) prevents this:

finally:
    _enqueue_fn = getattr(logging_obj, "_enqueue_deferred_logging", None)
    if _enqueue_fn is not None:
        logging_obj._enqueue_deferred_logging = None  # type: ignore[attr-defined]
        try:
            _enqueue_fn()
        except Exception:
            verbose_proxy_logger.exception(
                "Failed to enqueue deferred async logging"
            )

This mirrors the existing pattern throughout the proxy where logging errors are swallowed so they never surface to clients.


# Always return the client-requested model name (not provider-prefixed internal identifiers)
# for OpenAI-compatible responses.
Expand Down Expand Up @@ -1217,6 +1236,26 @@ def _is_streaming_request(
return True
return False

@staticmethod
def _has_post_call_guardrails() -> bool:
"""
Check if any registered callback is a post-call guardrail.

Uses the global litellm.callbacks list rather than per-request
should_run_guardrail() — intentionally conservative so that the
check is simple and stateless. The deferral path produces
identical logging output, just fires it slightly later, so
false-positives are harmless.
"""
for cb in litellm.callbacks:
if (
not isinstance(cb, str)
and isinstance(cb, CustomGuardrail)
and cb._event_hook_is_event_type(GuardrailEventHooks.post_call)
):
return True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Redundant isinstance guard

The not isinstance(cb, str) check on line 1251 is redundant: isinstance(cb, CustomGuardrail) already returns False for any str (since str doesn't inherit from CustomGuardrail). Removing it makes the intent clearer.

Suggested change
if (
not isinstance(cb, str)
and isinstance(cb, CustomGuardrail)
and cb._event_hook_is_event_type(GuardrailEventHooks.post_call)
):
return True
for cb in litellm.callbacks:
if (
isinstance(cb, CustomGuardrail)
and cb._event_hook_is_event_type(GuardrailEventHooks.post_call)
):
return True

return False

async def _handle_llm_api_exception(
self,
Comment on lines 1340 to 1362

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Per-request scan of global callbacks list

_has_post_call_guardrails() is a static method that iterates the entire litellm.callbacks list (and re-imports two modules) on every call to base_process_llm_request. For high-throughput deployments with many callbacks this adds avoidable latency in the hot path.

A simple improvement would be to cache the result and invalidate it when litellm.callbacks is mutated (e.g. via a module-level flag), or move the scan to proxy startup/config load time. At minimum, move the imports to module level so the import lookup overhead is paid once:

# at module top
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.types.guardrails import GuardrailEventHooks

e: Exception,
Expand Down
46 changes: 36 additions & 10 deletions litellm/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1944,20 +1944,46 @@ async def wrapper_async(*args, **kwargs): # noqa: PLR0915
)

# LOG SUCCESS - handle streaming success logging in the _next_ object
asyncio.create_task(
_client_async_logging_helper(
logging_obj=logging_obj,
# NOTE: streaming requests return early (before this point) via
# CustomStreamWrapper, so this block is non-streaming only.
if getattr(logging_obj, "_defer_async_logging", False):
# Proxy has post-call guardrails that must complete before the
# SLO is built. Store a closure the proxy will call after
# post_call_success_hook so guardrail_information is in metadata.
# Both async (create_task) and sync callbacks are deferred so
# all callbacks see consistent guardrail_information state.
def _enqueue_deferred_logging() -> None:
asyncio.create_task(
_client_async_logging_helper(
logging_obj=logging_obj,
result=result,
start_time=start_time,
end_time=end_time,
is_completion_with_fallbacks=is_completion_with_fallbacks,
)
)
logging_obj.handle_sync_success_callbacks_for_async_calls(
result=result,
start_time=start_time,
end_time=end_time,
)

logging_obj._enqueue_deferred_logging = _enqueue_deferred_logging # type: ignore
Comment on lines +1955 to +1967

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 handle_sync_success_callbacks_for_async_calls is also deferred

In the original code, handle_sync_success_callbacks_for_async_calls was called synchronously and immediately (before post_call_success_hook ran). In the deferred closure it now fires only after guardrails complete. This is a behavioral change for the sync-callback path that isn't mentioned in the PR description.

If any sync callback relies on being called promptly (e.g. for billing meters, rate-limit counters, or cache warming that must happen before the response is returned to the client), deferring it may cause subtle bugs. Consider whether the sync callbacks should remain immediate and only asyncio.create_task (the async logging) should be deferred:

# Sync callbacks fire immediately; only async logging is deferred
logging_obj.handle_sync_success_callbacks_for_async_calls(
    result=result,
    start_time=start_time,
    end_time=end_time,
)

def _enqueue_deferred_logging() -> None:
    asyncio.create_task(
        _client_async_logging_helper(
            logging_obj=logging_obj,
            result=result,
            start_time=start_time,
            end_time=end_time,
            is_completion_with_fallbacks=is_completion_with_fallbacks,
        )
    )

logging_obj._enqueue_deferred_logging = _enqueue_deferred_logging

Comment on lines +1955 to +1967

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 asyncio.create_task called inside a synchronous closure

_enqueue_deferred_logging is defined as a plain def (synchronous) yet calls asyncio.create_task, which requires a running event loop at call time. This works correctly today because the closure is always invoked from inside the async def base_process_llm_request finally block where an event loop is guaranteed.

However, the type signature () -> None gives no indication of this constraint. If the closure were accidentally called from a sync context (e.g., a cleanup path added in the future), it would raise RuntimeError: no running event loop. Consider documenting this requirement with a comment or an assertion:

def _enqueue_deferred_logging() -> None:
    # Must be called from within a running event loop (async context).
    asyncio.create_task(
        _client_async_logging_helper(
            ...
        )
    )

else:
asyncio.create_task(
_client_async_logging_helper(
logging_obj=logging_obj,
result=result,
start_time=start_time,
end_time=end_time,
is_completion_with_fallbacks=is_completion_with_fallbacks,
)
)
logging_obj.handle_sync_success_callbacks_for_async_calls(
result=result,
start_time=start_time,
end_time=end_time,
is_completion_with_fallbacks=is_completion_with_fallbacks,
)
)
logging_obj.handle_sync_success_callbacks_for_async_calls(
result=result,
start_time=start_time,
end_time=end_time,
)
# REBUILD EMBEDDING CACHING
if (
isinstance(result, EmbeddingResponse)
Expand Down
Loading
Loading