mirror of
https://github.com/BerriAI/litellm.git
synced 2026-12-06 02:09:04 +00:00
Response cache reads and writes open cache.get llm_response and cache.set llm_response phase spans with their Redis spans nested underneath, on the Python path and on the native Rust path, and deployment selection runs inside a route {model_group} phase so the cooldown, usage and model-id reads the router issues nest under it before chat {model}. The autorouter classifier call nests under that route phase as well and carries its typed internal origin on litellm.request.purpose, so it is told apart from the provider attempt. Service spans are named {service}.{verb} {target} from a low-cardinality key family the producer declares (llm_response, auth_objects, spend_counters, router_cooldowns, claude_code_session_router_binding, rate_limits, pod_lock, budget_reset, ...) instead of the raw method or a per-request pipeline length; a pipeline flush is targeted by the one family its ops share or by mixed with the sorted families on litellm.redis.families, a batch op keeps the family it was declared under whichever pipeline or standalone read settles it, and the ambient family labels Redis spans only, never the DB write-back a task spawned inside that context performs later. The raw method stays on litellm.service.call_type and on the Prometheus and Datadog labels. Caller attribution is carried across asyncio task boundaries on a ContextVar so forwarder-only chains no longer surface, the raw cache key is dropped from Redis span metadata, pipeline op counts land as an integer attribute, every call_type the Redis cache layer emits maps to a verb, and a scan over litellm/ and enterprise/ fails when a Redis producer, batch reservation included, declares no key family.
A V2 logger built for a key or team logging entry while the operator's V2 logger is already registered keeps only the exporters its own preset contributed, whether or not the operator holds credentials for that backend, so every chat span no longer reaches the operator's collector twice. A span the success callback has to open itself, with no pre-call carrier, starts at the provider handoff (api_call_start_time) instead of the logging object's creation.
Co-authored-by: yassin <yassin@berri.ai>
Co-authored-by: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com>
130 lines
5 KiB
Python
130 lines
5 KiB
Python
# +------------------------------+
|
|
#
|
|
# Blocked User List
|
|
#
|
|
# +------------------------------+
|
|
# Thank you users! We ❤️ you! - Krrish & Ishaan
|
|
## This accepts a list of user id's for whom calls will be rejected
|
|
|
|
|
|
from typing import Literal, Optional
|
|
|
|
from fastapi import HTTPException
|
|
|
|
import litellm
|
|
from litellm._internal_context import with_service_target
|
|
from litellm._logging import verbose_proxy_logger
|
|
from litellm.caching.caching import DualCache
|
|
from litellm.integrations.custom_logger import CustomLogger
|
|
from litellm.proxy._types import LiteLLM_EndUserTable, UserAPIKeyAuth
|
|
from litellm.proxy.common_utils.user_api_key_cache import AUTH_OBJECTS_TARGET
|
|
from litellm.proxy.utils import PrismaClient
|
|
|
|
|
|
class _ENTERPRISE_BlockedUserList(CustomLogger):
|
|
enforces_request_content: bool = True
|
|
# Class variables or attributes
|
|
def __init__(self, prisma_client: Optional[PrismaClient]):
|
|
self.prisma_client = prisma_client
|
|
|
|
blocked_user_list = litellm.blocked_user_list
|
|
if blocked_user_list is None:
|
|
self.blocked_user_list = None
|
|
return
|
|
|
|
if isinstance(blocked_user_list, list):
|
|
self.blocked_user_list = blocked_user_list
|
|
|
|
if isinstance(blocked_user_list, str): # assume it's a filepath
|
|
try:
|
|
with open(blocked_user_list, "r") as file:
|
|
data = file.read()
|
|
self.blocked_user_list = data.split("\n")
|
|
except FileNotFoundError:
|
|
raise Exception(
|
|
f"File not found. blocked_user_list={blocked_user_list}"
|
|
)
|
|
except Exception as e:
|
|
raise Exception(
|
|
f"An error occurred: {str(e)}, blocked_user_list={blocked_user_list}"
|
|
)
|
|
|
|
def print_verbose(self, print_statement, level: Literal["INFO", "DEBUG"] = "DEBUG"):
|
|
if level == "INFO":
|
|
verbose_proxy_logger.info(print_statement)
|
|
elif level == "DEBUG":
|
|
verbose_proxy_logger.debug(print_statement)
|
|
|
|
if litellm.set_verbose is True:
|
|
print(print_statement) # noqa
|
|
|
|
@with_service_target(AUTH_OBJECTS_TARGET)
|
|
async def async_pre_call_hook(
|
|
self,
|
|
user_api_key_dict: UserAPIKeyAuth,
|
|
cache: DualCache,
|
|
data: dict,
|
|
call_type: str,
|
|
):
|
|
try:
|
|
"""
|
|
- check if user id part of call
|
|
- check if user id part of blocked list
|
|
- if blocked list is none or user not in blocked list
|
|
- check if end-user in cache
|
|
- check if end-user in db
|
|
"""
|
|
self.print_verbose("Inside Blocked User List Pre-Call Hook")
|
|
if "user_id" in data or "user" in data:
|
|
user = data.get("user_id", data.get("user", ""))
|
|
if (
|
|
self.blocked_user_list is not None
|
|
and user in self.blocked_user_list
|
|
):
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail={
|
|
"error": f"User blocked from making LLM API Calls. User={user}"
|
|
},
|
|
)
|
|
|
|
cache_key = f"litellm:end_user_id:{user}"
|
|
end_user_cache_obj: Optional[LiteLLM_EndUserTable] = cache.get_cache( # type: ignore
|
|
key=cache_key
|
|
)
|
|
if end_user_cache_obj is None and self.prisma_client is not None:
|
|
# check db
|
|
end_user_obj = (
|
|
await self.prisma_client.db.litellm_endusertable.find_unique(
|
|
where={"user_id": user}
|
|
)
|
|
)
|
|
if end_user_obj is None: # user not in db - assume not blocked
|
|
end_user_obj = LiteLLM_EndUserTable(user_id=user, blocked=False)
|
|
cache.set_cache(key=cache_key, value=end_user_obj, ttl=60)
|
|
if end_user_obj is not None and end_user_obj.blocked is True:
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail={
|
|
"error": f"User blocked from making LLM API Calls. User={user}"
|
|
},
|
|
)
|
|
elif (
|
|
end_user_cache_obj is not None
|
|
and end_user_cache_obj.blocked is True
|
|
):
|
|
raise HTTPException(
|
|
status_code=400,
|
|
detail={
|
|
"error": f"User blocked from making LLM API Calls. User={user}"
|
|
},
|
|
)
|
|
|
|
except HTTPException as e:
|
|
raise e
|
|
except Exception as e:
|
|
verbose_proxy_logger.exception(
|
|
"litellm.enterprise.enterprise_hooks.blocked_user_list::async_pre_call_hook - Exception occurred - {}".format(
|
|
str(e)
|
|
)
|
|
)
|