Repository navigation
chore(ci): promote internal staging to main #33491
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 45 commits
d7585cd
75faed1
90f495f
6372ca3
66f012a
a81c6ce
447d50f
8650f6c
feedab2
f1f33f5
2b9b681
719e1bf
587b8ac
f7fc679
24a438a
9121ae3
44d9737
06e8013
b907378
c6d49a8
ff4a40f
95fe868
ec4639f
e4a6516
056f85a
c59963e
923c325
daa15ba
edc38ea
79bfe2e
35e9471
e8bb9d7
585f21a
7b7bec1
fac43df
614dd87
63e0be6
c4fee0e
3cea243
39c01fe
906897b
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 |
|---|---|---|
|
|
@@ -7,7 +7,8 @@ | |
| # Thank you users! We ❤️ you! - Krrish & Ishaan | ||
| ## This provides an LLM Guard Integration for content moderation on the proxy | ||
|
|
||
| from typing import Literal, Optional | ||
| import asyncio | ||
| from typing import Optional | ||
|
|
||
| import aiohttp | ||
| from fastapi import HTTPException | ||
|
|
@@ -18,7 +19,6 @@ | |
| from litellm.proxy._types import UserAPIKeyAuth | ||
| from litellm.secret_managers.main import get_secret_str | ||
| from litellm.types.utils import CallTypesLiteral | ||
| from litellm.utils import get_formatted_prompt | ||
|
|
||
|
|
||
| class _ENTERPRISE_LLMGuard(CustomLogger): | ||
|
|
@@ -46,45 +46,44 @@ def print_verbose(self, print_statement): | |
| except Exception: | ||
| pass | ||
|
|
||
| async def moderation_check(self, text: str): | ||
| async def moderation_check(self, text: str) -> str: | ||
| """ | ||
| Runs the LLM Guard moderation check on ``text``. | ||
|
|
||
| Raises an HTTPException when the content violates the safety policy; | ||
| otherwise returns the sanitized prompt from LLM Guard, falling back to | ||
| the original text when the API does not provide one. | ||
|
|
||
| [TODO] make this more performant for high-throughput scenario | ||
| """ | ||
| try: | ||
| async with aiohttp.ClientSession() as session: | ||
| if self.mock_redacted_text is not None: | ||
| redacted_text = self.mock_redacted_text | ||
| else: | ||
| # Make the first request to /analyze | ||
| analyze_url = f"{self.llm_guard_api_base}analyze/prompt" | ||
| verbose_proxy_logger.debug("Making request to: %s", analyze_url) | ||
| analyze_payload = {"prompt": text} | ||
| redacted_text = None | ||
| if self.mock_redacted_text is not None: | ||
| redacted_text = self.mock_redacted_text | ||
| else: | ||
| analyze_url = f"{self.llm_guard_api_base}analyze/prompt" | ||
| verbose_proxy_logger.debug("Making request to: %s", analyze_url) | ||
| async with aiohttp.ClientSession() as session: | ||
| async with session.post( | ||
| analyze_url, json=analyze_payload | ||
| analyze_url, json={"prompt": text} | ||
| ) as response: | ||
| redacted_text = await response.json() | ||
| verbose_proxy_logger.debug( | ||
| f"LLM Guard: Received response - {redacted_text}" | ||
| verbose_proxy_logger.debug( | ||
| f"LLM Guard: Received response - {redacted_text}" | ||
| ) | ||
| if redacted_text is None: | ||
| raise HTTPException( | ||
| status_code=500, | ||
| detail={ | ||
| "error": f"Invalid content moderation response: {redacted_text}" | ||
| }, | ||
| ) | ||
| if redacted_text is not None: | ||
| if ( | ||
| redacted_text.get("is_valid", None) is not None | ||
| and redacted_text["is_valid"] is False | ||
| ): | ||
| raise HTTPException( | ||
| status_code=400, | ||
| detail={"error": "Violated content safety policy"}, | ||
| ) | ||
| else: | ||
| pass | ||
| else: | ||
| raise HTTPException( | ||
| status_code=500, | ||
| detail={ | ||
| "error": f"Invalid content moderation response: {redacted_text}" | ||
| }, | ||
| ) | ||
| if redacted_text.get("is_valid", None) is False: | ||
| raise HTTPException( | ||
| status_code=400, | ||
| detail={"error": "Violated content safety policy"}, | ||
| ) | ||
| sanitized_prompt = redacted_text.get("sanitized_prompt") | ||
| return sanitized_prompt if isinstance(sanitized_prompt, str) else text | ||
| except Exception as e: | ||
| verbose_proxy_logger.exception( | ||
| "litellm.enterprise.enterprise_hooks.llm_guard::moderation_check - Exception occurred - {}".format( | ||
|
|
@@ -138,23 +137,75 @@ async def async_moderation_hook( | |
| return | ||
|
|
||
| self.print_verbose("Makes LLM Guard Check") | ||
| try: | ||
| assert call_type in [ | ||
| "completion", | ||
| "embeddings", | ||
| "image_generation", | ||
| "moderation", | ||
| "audio_transcription", | ||
| ] | ||
| except Exception: | ||
| if call_type not in [ | ||
| "completion", | ||
| "embeddings", | ||
| "image_generation", | ||
| "moderation", | ||
| "audio_transcription", | ||
| ]: | ||
| self.print_verbose( | ||
| f"Call Type - {call_type}, not in accepted list - ['completion','embeddings','image_generation','moderation','audio_transcription']" | ||
| ) | ||
| return data | ||
|
|
||
| formatted_prompt = get_formatted_prompt(data=data, call_type=call_type) # type: ignore | ||
| self.print_verbose(f"LLM Guard, formatted_prompt: {formatted_prompt}") | ||
| return await self.moderation_check(text=formatted_prompt) | ||
| return await self._moderate_request(data=data) | ||
|
|
||
| async def _moderate_request(self, data: dict) -> dict: | ||
| """ | ||
| Sanitizes the request in place using the prompt returned by LLM Guard so | ||
| the provider-bound request carries the redacted content, then returns it. | ||
| """ | ||
| messages = data.get("messages") | ||
| if messages is not None: | ||
| data["messages"] = list( | ||
| await asyncio.gather( | ||
| *(self._moderate_message(message) for message in messages) | ||
| ) | ||
| ) | ||
| return data | ||
|
|
||
| input_ = data.get("input") | ||
| if input_ is not None: | ||
| data["input"] = await self._moderate_input(input_) | ||
| return data | ||
|
|
||
| prompt = data.get("prompt") | ||
| if isinstance(prompt, str): | ||
| data["prompt"] = await self.moderation_check(text=prompt) | ||
| return data | ||
|
|
||
| async def _moderate_message(self, message: dict) -> dict: | ||
| content = message.get("content") | ||
| if isinstance(content, str): | ||
| return {**message, "content": await self.moderation_check(text=content)} | ||
| if isinstance(content, list): | ||
| return { | ||
| **message, | ||
| "content": list( | ||
| await asyncio.gather( | ||
| *(self._moderate_content_part(part) for part in content) | ||
| ) | ||
| ), | ||
| } | ||
| return message | ||
|
|
||
| async def _moderate_content_part(self, part: dict) -> dict: | ||
| if part.get("type") == "text" and isinstance(part.get("text"), str): | ||
| return {**part, "text": await self.moderation_check(text=part["text"])} | ||
|
Comment on lines
+170
to
+195
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 refactored |
||
| return part | ||
|
|
||
| async def _moderate_input(self, input_: object) -> object: | ||
| if isinstance(input_, str): | ||
| return await self.moderation_check(text=input_) | ||
| if isinstance(input_, list): | ||
| return [ | ||
| await self.moderation_check(text=item) | ||
| if isinstance(item, str) | ||
| else item | ||
| for item in input_ | ||
| ] | ||
| return input_ | ||
|
|
||
| async def async_post_call_streaming_hook( | ||
| self, user_api_key_dict: UserAPIKeyAuth, response: str | ||
|
|
||
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.
Medium: Unbounded moderation request fan-out
Each message and nested text part now causes a separate
moderation_check, andasyncio.gatherstarts all message checks concurrently; list-valuedinputsimilarly causes one request per item. An authenticated user can submit thousands of small items and turn one proxy request into thousands of outbound sessions, exhausting sockets and LLM Guard quota. Send a combined or batched moderation request, or enforce an item limit and bounded concurrency while reusing a client session.