Repository navigation
fix(proxy): defer async logging until post-call guardrails complete #23929
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
5242986
f746e4c
313355b
6a4e742
ffde40c
b4122c6
4a867b6
10e3829
aa2e358
a564c1b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||||||||||||||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
|
@@ -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) | ||||||||||||||||||||||||||
|
|
@@ -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, | ||||||||||||||||||||||||||
|
|
@@ -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 | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| 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 | ||||||||||||||||||||||||||
|
|
@@ -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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
For standard OpenAI-compatible streaming requests (i.e. those that don't hit the As a result the per-chunk success logging emitted by 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() | ||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
If Wrapping the closure call in a bare 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. | ||||||||||||||||||||||||||
|
|
@@ -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 | ||||||||||||||||||||||||||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The
Suggested change
|
||||||||||||||||||||||||||
| return False | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| async def _handle_llm_api_exception( | ||||||||||||||||||||||||||
| self, | ||||||||||||||||||||||||||
|
Comment on lines
1340
to
1362
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
A simple improvement would be to cache the result and invalidate it when # at module top
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.types.guardrails import GuardrailEventHooks |
||||||||||||||||||||||||||
| e: Exception, | ||||||||||||||||||||||||||
|
|
||||||||||||||||||||||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
In the original code, 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 # 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
However, the type signature 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) | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
_defer_async_loggingflag is set even for requests that will take a streaming early-return_has_post_call_guardrails()is evaluated unconditionally beforeroute_request, so when post-call guardrails are registered,_defer_async_logging = Trueis set on everylogging_obj— including those for streaming requests that will ultimatelyreturnfrom within thetryblock (e.g.,allm_passthrough_route,anthropic_messagesstreaming,select_data_generator). For those pathswrapper_asyncreturns aCustomStreamWrapperbefore reaching the closure-storage code inutils.py, so_enqueue_deferred_loggingis never stored and thefinallyblock is a harmless no-op.However, the
_defer_async_logging = Trueflag persists onlogging_objfor the lifetime of the streaming wrapper, and any future code that reads this flag on the streaminglogging_objcould behave unexpectedly. A guard likeif 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.