mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-01 01:18:34 +00:00
* refactor(typing): narrow Any sources across providers, proxy and guardrails (wave 1) * refactor(typing): narrow Any sources across hubs, providers and proxy (wave 2) * refactor(typing): validate RunwayML task JSON and let dotprompt loaders accept exported prompts * fix: restore pass-through behavior on paths the typing pass tightened MCP client IP extraction trusts X-Forwarded-For only when use_x_forwarded_for is True, dotprompt skips a malformed JSON prompt entry instead of raising, RunwayML task payloads pass through unvalidated, and a malformed provider body raises the same AttributeError as before at the CompactifAI, Gemini, and mock transport parse sites * fix(runwayml): keep a malformed 2xx task body on the 500 path * fix(edenai,cli): keep a non-object body in the error and fail on a malformed migration report EdenAI's embedding and image generation parse dropped a non-object body from the error they raised, so the message no longer named what the provider sent. A helper now raises with the body in the message, and both paths have a regression test. `lite encryption migrate` exited 0 with no message when the proxy's report was not an object or its residual_legacy was not a number, where base crashed. It now fails with a message naming the value. The CompactifAI and Gemini image-edit non-object body tests accept TypeError or AttributeError, which both base and this branch raise, so they guard against a ValidationError instead of pinning one class. RunwayML's async parse gets the same non-object body test as the sync one. * fix: keep base's error classes, duck-typed checks and fail-closed guardrails the typing pass changed * test: annotate the new regression tests' locals with Final * test: annotate the remaining new test locals with Final
143 lines
5 KiB
Python
143 lines
5 KiB
Python
# +-----------------------------------------------+
|
|
#
|
|
# Google Text Moderation
|
|
# https://cloud.google.com/natural-language/docs/moderating-text
|
|
#
|
|
# +-----------------------------------------------+
|
|
# Thank you users! We ❤️ you! - Krrish & Ishaan
|
|
|
|
from typing import Final
|
|
|
|
from fastapi import HTTPException
|
|
from pydantic import TypeAdapter
|
|
|
|
import litellm
|
|
from litellm._logging import verbose_proxy_logger
|
|
from litellm.integrations.custom_logger import CustomLogger
|
|
from litellm.proxy._types import UserAPIKeyAuth
|
|
from litellm.proxy.guardrails._content_utils import iter_message_text
|
|
from litellm.types.utils import CallTypesLiteral
|
|
|
|
_THRESHOLD_VALUE: Final = TypeAdapter(object)
|
|
|
|
|
|
class ENTERPRISE_GoogleTextModeration(CustomLogger):
|
|
user_api_key_cache = None
|
|
confidence_categories = [
|
|
"toxic",
|
|
"insult",
|
|
"profanity",
|
|
"derogatory",
|
|
"sexual",
|
|
"death_harm_and_tragedy",
|
|
"violent",
|
|
"firearms_and_weapons",
|
|
"public_safety",
|
|
"health",
|
|
"religion_and_belief",
|
|
"illicit_drugs",
|
|
"war_and_conflict",
|
|
"politics",
|
|
"finance",
|
|
"legal",
|
|
] # https://cloud.google.com/natural-language/docs/moderating-text#safety_attribute_confidence_scores
|
|
|
|
# Class variables or attributes
|
|
def __init__(self):
|
|
try:
|
|
from google.cloud import language_v1 # type: ignore
|
|
except Exception:
|
|
raise Exception(
|
|
"Missing google.cloud package. Run `pip install --upgrade google-cloud-language`"
|
|
)
|
|
|
|
# Instantiates a client
|
|
self.client = language_v1.LanguageServiceClient()
|
|
self.moderate_text_request = language_v1.ModerateTextRequest
|
|
self.language_document = language_v1.types.Document # type: ignore
|
|
self.document_type = language_v1.types.Document.Type.PLAIN_TEXT # type: ignore
|
|
|
|
default_confidence_threshold = (
|
|
litellm.google_moderation_confidence_threshold or 0.8
|
|
) # by default require a high confidence (80%) to fail
|
|
|
|
for category in self.confidence_categories:
|
|
if hasattr(litellm, f"{category}_confidence_threshold"):
|
|
setattr(
|
|
self,
|
|
f"{category}_confidence_threshold",
|
|
getattr(litellm, f"{category}_confidence_threshold"),
|
|
)
|
|
else:
|
|
setattr(
|
|
self,
|
|
f"{category}_confidence_threshold",
|
|
default_confidence_threshold,
|
|
)
|
|
set_confidence_value = _THRESHOLD_VALUE.validate_python(
|
|
getattr(
|
|
self,
|
|
f"{category}_confidence_threshold",
|
|
)
|
|
)
|
|
verbose_proxy_logger.info(
|
|
f"Google Text Moderation: {category}_confidence_threshold: {set_confidence_value}"
|
|
)
|
|
|
|
def print_verbose(self, print_statement):
|
|
try:
|
|
verbose_proxy_logger.debug(print_statement)
|
|
if litellm.set_verbose:
|
|
print(print_statement) # noqa
|
|
except Exception:
|
|
pass
|
|
|
|
async def async_moderation_hook(
|
|
self,
|
|
data: dict,
|
|
user_api_key_dict: UserAPIKeyAuth,
|
|
call_type: CallTypesLiteral,
|
|
):
|
|
"""
|
|
- Calls Google's Text Moderation API
|
|
- Rejects request if it fails safety check
|
|
"""
|
|
# Covers multimodal list content + Responses-API input.
|
|
text = "".join(iter_message_text(data))
|
|
if text:
|
|
document = self.language_document(content=text, type_=self.document_type)
|
|
|
|
request = self.moderate_text_request(
|
|
document=document,
|
|
)
|
|
|
|
# Make the request
|
|
response = self.client.moderate_text(request=request)
|
|
for category in response.moderation_categories:
|
|
category_name = category.name
|
|
category_name = category_name.lower()
|
|
category_name = category_name.replace("&", "and")
|
|
category_name = category_name.replace(",", "")
|
|
category_name = category_name.replace(
|
|
" ", "_"
|
|
) # e.g. go from 'Firearms & Weapons' to 'firearms_and_weapons'
|
|
if category.confidence > getattr(
|
|
self, f"{category_name}_confidence_threshold"
|
|
):
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail={
|
|
"error": f"Violated content safety policy. Category={category}"
|
|
},
|
|
)
|
|
# Handle the response
|
|
return data
|
|
_ENTERPRISE_GoogleTextModeration = ENTERPRISE_GoogleTextModeration
|
|
|
|
|
|
# google_text_moderation_obj = ENTERPRISE_GoogleTextModeration()
|
|
# asyncio.run(
|
|
# google_text_moderation_obj.async_moderation_hook(
|
|
# data={"messages": [{"role": "user", "content": "Hey, how's it going?"}]}
|
|
# )
|
|
# )
|