Repository navigation
feat(guardrails): add fire_and_forget dispatch to generic_guardrail_api #43681
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
Open
caduri
wants to merge
5
commits into
BerriAI:main
Choose a base branch
from
caduri:feature/generic-guardrail-fire-and-forget
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
73904c9
feat(guardrails): add fire_and_forget dispatch to generic_guardrail_api
caduri f7e9346
fix(guardrails): harden generic_guardrail_api fire_and_forget dispatch
caduri 09922b7
perf(guardrails): build fire_and_forget payloads only when a slot is …
caduri de06532
fix(guardrails): observe abandoned streams for fire_and_forget guardr…
caduri de597a5
test(guardrails): cover an observe-only stream that no handler unders…
caduri File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
112 changes: 112 additions & 0 deletions
112
litellm/proxy/guardrails/guardrail_hooks/generic_guardrail_api/background_dispatch.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,112 @@ | ||
| import asyncio | ||
| import contextvars | ||
| from collections.abc import Awaitable, Callable | ||
| from typing import Annotated, Final | ||
|
|
||
| from pydantic import Field, TypeAdapter, ValidationError | ||
|
|
||
| from litellm._logging import verbose_proxy_logger | ||
|
|
||
| DEFAULT_FIRE_AND_FORGET_MAX_INFLIGHT: Final = 100 | ||
|
|
||
| FIRE_AND_FORGET_POST_TIMEOUT_SECONDS: Final = 30.0 | ||
|
|
||
| FIRE_AND_FORGET_DISPATCHED_REASON: Final = "fire_and_forget dispatched, verdict not read" | ||
|
|
||
| FIRE_AND_FORGET_DROPPED_REASON: Final = "fire_and_forget_max_inflight reached, call dropped" | ||
|
|
||
| FIRE_AND_FORGET_NOT_DISPATCHED_REASON: Final = "fire_and_forget payload could not be built, call not dispatched" | ||
|
|
||
| _DROP_LOG_INTERVAL: Final = 100 | ||
| _FIRE_AND_FORGET_ADAPTER: Final[TypeAdapter[bool]] = TypeAdapter(bool) | ||
| _MAX_INFLIGHT_ADAPTER: Final[TypeAdapter[int]] = TypeAdapter(Annotated[int, Field(ge=1)]) | ||
|
|
||
|
|
||
| def fire_and_forget_from_config(value: object) -> bool: | ||
| if value is None: | ||
| return False | ||
| try: | ||
| return _FIRE_AND_FORGET_ADAPTER.validate_python(value) | ||
| except ValidationError: | ||
| verbose_proxy_logger.warning( | ||
| "Ignoring fire_and_forget=%r, expected true or false. Awaiting every guardrail call", value | ||
| ) | ||
| return False | ||
|
|
||
|
|
||
| def _parsed_max_inflight(value: object) -> int | None: | ||
| if isinstance(value, bool): | ||
| return None | ||
| try: | ||
| return _MAX_INFLIGHT_ADAPTER.validate_python(value) | ||
| except ValidationError: | ||
| return None | ||
|
|
||
|
|
||
| def max_inflight_from_config(value: object) -> int: | ||
| if value is None: | ||
| return DEFAULT_FIRE_AND_FORGET_MAX_INFLIGHT | ||
| parsed: Final = _parsed_max_inflight(value) | ||
| if parsed is None: | ||
| verbose_proxy_logger.warning( | ||
| "Ignoring fire_and_forget_max_inflight=%r, expected an integer of at least 1. Using %d", | ||
| value, | ||
| DEFAULT_FIRE_AND_FORGET_MAX_INFLIGHT, | ||
| ) | ||
| return DEFAULT_FIRE_AND_FORGET_MAX_INFLIGHT | ||
| return parsed | ||
|
|
||
|
|
||
| class BackgroundDispatcher: | ||
| def __init__(self, *, guardrail_name: str | None, max_inflight: int) -> None: | ||
| if max_inflight < 1: | ||
| raise ValueError(f"fire_and_forget_max_inflight must be >= 1 (got {max_inflight})") | ||
| self._guardrail_name: Final = guardrail_name | ||
| self._max_inflight: Final = max_inflight | ||
| self._pending: Final[set[asyncio.Task[None]]] = set() # mutable-ok: strong refs, asyncio keeps only weak ones | ||
| self._dropped: int = 0 | ||
|
|
||
| @property | ||
| def pending_count(self) -> int: | ||
| return len(self._pending) | ||
|
|
||
| @property | ||
| def dropped_count(self) -> int: | ||
| return self._dropped | ||
|
|
||
| def dispatch(self, prepare: Callable[[], Callable[[], Awaitable[object]]], *, context: str) -> bool: | ||
| if len(self._pending) >= self._max_inflight: | ||
| self._dropped += 1 | ||
| if self._dropped % _DROP_LOG_INTERVAL == 1: | ||
| verbose_proxy_logger.warning( | ||
| "Generic Guardrail API (%s, fire_and_forget): dropped %d call(s) so far, " | ||
| "%d already in flight (fire_and_forget_max_inflight=%d). %s", | ||
| self._guardrail_name, | ||
| self._dropped, | ||
| len(self._pending), | ||
| self._max_inflight, | ||
| context, | ||
| ) | ||
| return False | ||
|
|
||
| run: Final = prepare() | ||
| task: Final = contextvars.Context().run(asyncio.create_task, self._run_logging_failures(run, context=context)) | ||
| self._pending.add(task) | ||
| task.add_done_callback(self._pending.discard) | ||
| return True | ||
|
|
||
| async def _run_logging_failures(self, run: Callable[[], Awaitable[object]], *, context: str) -> None: | ||
| try: | ||
| await run() | ||
| except Exception as e: # noqa: BLE001 # a detached task has no caller to raise into | ||
| verbose_proxy_logger.warning( | ||
| "Generic Guardrail API (%s, fire_and_forget) call failed. %s: %s", | ||
| self._guardrail_name, | ||
| context, | ||
| e, | ||
| ) | ||
|
|
||
| async def wait_for_pending(self) -> None: | ||
| pending: Final = tuple(self._pending) | ||
| if pending: | ||
| await asyncio.gather(*pending, return_exceptions=True) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.