Skip to content
Merged
Show file tree
Hide file tree
Changes from 45 commits
Commits
Show all changes
41 commits
Select commit Hold shift + click to select a range
d7585cd
fix(proxy): route master key to team-scoped models (#32926)
kunal2002 Jul 14, 2026
75faed1
fix(bedrock_mantle): route xai.grok-4.3 via /openai/v1 frontier path …
marty-sullivan Jul 14, 2026
90f495f
chore(ci): sync litellm_internal_staging into daily OSS branch (#33337)
yuneng-berri Jul 15, 2026
6372ca3
Revert "chore(ci): sync litellm_internal_staging into daily OSS branc…
yuneng-berri Jul 15, 2026
66f012a
fix(mcp): discover missing OAuth scopes and token_url when authorizat…
tin-berri Jul 15, 2026
a81c6ce
fix(mcp): reject discovered token endpoints uncorroborated by the man…
tin-berri Jul 15, 2026
447d50f
fix(mcp): enforce the OAuth endpoint trust rule at carry-forward too,…
tin-berri Jul 15, 2026
8650f6c
fix(mcp): bound pinned-config discovery to the corroborated authoriza…
tin-berri Jul 15, 2026
feedab2
fix(mcp): normalize blank OAuth endpoint fields to None at build entr…
tin-berri Jul 15, 2026
f1f33f5
Merge pull request #33335 from BerriAI/litellm_oss_daily_2026_07_10
yuneng-berri Jul 15, 2026
2b9b681
fix(ui/chat): resolve chat routes at render time so navigation works …
yuneng-berri Jul 15, 2026
719e1bf
Merge remote-tracking branch 'origin/litellm_internal_staging' into l…
yuneng-berri Jul 15, 2026
587b8ac
feat(guardrails): add Compresr guardrail for query-aware context comp…
yucheng-berri Jul 15, 2026
f7fc679
fix(logging): preserve callback order in get_combined_callback_list (…
devin-ai-integration[bot] Jul 15, 2026
24a438a
fix(logging): redact assistant tool call arguments in spend logs (#33…
devin-ai-integration[bot] Jul 15, 2026
9121ae3
fix(anthropic): honor messages request timeout (#33418)
yucheng-berri Jul 15, 2026
44d9737
fix(llm_guard): apply sanitized prompt returned by moderation API to …
devin-ai-integration[bot] Jul 15, 2026
06e8013
fix(logging): stop pinning large request payloads past request end (#…
yassin-berriai Jul 15, 2026
b907378
feat(guardrails): forward optional metadata on POST /guardrails/apply…
devin-ai-integration[bot] Jul 15, 2026
c6d49a8
build: raise requires-python cap to <3.15 so Python 3.14 installs cur…
ryan-crabbe-berri Jul 15, 2026
ff4a40f
feat(ui): add reusable BetaBadge and use it for Projects sidebar item…
devin-ai-integration[bot] Jul 15, 2026
95fe868
test(e2e/claude_code): add passthrough matrix row for the big-3 cloud…
mateo-berri Jul 15, 2026
ec4639f
test(claude_code): rename misleading REPO_ROOT to SUITE_ROOT in test_…
mateo-berri Jul 15, 2026
e4a6516
fix(mcp): keep scope selection resource-driven, not authorization-ser…
tin-berri Jul 15, 2026
056f85a
feat(ui): show exact license expiration date in usage cards
yuneng-berri Jul 15, 2026
c59963e
Merge remote-tracking branch 'origin/litellm_internal_staging' into l…
mateo-berri Jul 15, 2026
923c325
Merge pull request #33317 from BerriAI/litellm_mcp_field_granular_oau…
tin-berri Jul 15, 2026
daa15ba
chore(ui): remove unmounted UsageIndicator component
yuneng-berri Jul 16, 2026
edc38ea
build(deps): update ddtrace to the 4.x line
yuneng-berri Jul 16, 2026
79bfe2e
docs(e2e/claude_code): document the known-red azure passthrough cell …
mateo-berri Jul 16, 2026
35e9471
Merge pull request #33478 from BerriAI/litellm_/license-expiration-da…
yuneng-berri Jul 16, 2026
e8bb9d7
Merge pull request #33472 from BerriAI/litellm_v0_layout_suite_root
mateo-berri Jul 16, 2026
585f21a
chore(ui): remove Hide Usage Indicator flag and hook
yuneng-berri Jul 16, 2026
7b7bec1
Merge pull request #33484 from BerriAI/litellm_/ddtrace-security-regr…
yuneng-berri Jul 16, 2026
fac43df
fix(complexity_router): return empty dict from _classifier_call_metad…
devin-ai-integration[bot] Jul 16, 2026
614dd87
Merge pull request #33446 from BerriAI/litellm_/chat-ui-first-message…
yuneng-berri Jul 16, 2026
63e0be6
Merge remote-tracking branch 'origin/litellm_internal_staging' into l…
yuneng-berri Jul 16, 2026
c4fee0e
test(e2e/claude_code): retry rate-limit-shaped CLI failures with backoff
mateo-berri Jul 16, 2026
3cea243
fix(key management): enforce minimum custom key length and mask short…
yucheng-berri Jul 16, 2026
39c01fe
Merge pull request #33482 from BerriAI/litellm_/laughing-herschel-d4f735
yuneng-berri Jul 16, 2026
906897b
Merge pull request #33473 from BerriAI/litellm_claude_code_passthrough
mateo-berri Jul 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docker/build_from_pip/Dockerfile.build_from_pip
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ RUN uv venv --python python && \
"opentelemetry-api==1.28.0" \
"opentelemetry-sdk==1.28.0" \
"opentelemetry-exporter-otlp==1.28.0" \
"ddtrace==2.19.0" \
"ddtrace==4.11.0" \
"sentry-sdk==2.21.0" \
"mangum==0.17.0" \
"azure-ai-contentsafety==1.0.0" \
Expand Down
141 changes: 96 additions & 45 deletions enterprise/litellm_enterprise/enterprise_callbacks/llm_guard.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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):
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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(

Copy link
Copy Markdown
Contributor

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, and asyncio.gather starts all message checks concurrently; list-valued input similarly 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.

*(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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Concurrent LLM Guard calls may overload the API

The refactored _moderate_request issues one moderation_check call per message (and one per text content-part inside multimodal messages) via asyncio.gather. Previously the entire conversation was collapsed to a single get_formatted_prompt call and checked once. For agentic sessions with long tool-call histories (dozens of messages), this could fan out to many parallel requests hitting the LLM Guard /analyze/prompt endpoint simultaneously, potentially hitting its rate limits or increasing latency significantly.

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
Expand Down
22 changes: 19 additions & 3 deletions litellm/caching/caching_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,22 @@ class CachingHandlerResponse(BaseModel):
in_memory_cache_obj = InMemoryCache()


def _drop_logging_obj_from_kwargs(request_kwargs: dict[str, object]) -> dict[str, object]:
"""
The caching handler is stored on the Logging object
(``logging_obj._llm_caching_handler``), so keeping ``litellm_logging_obj``
inside ``request_kwargs`` closes a reference cycle
(Logging -> LLMCachingHandler -> kwargs -> Logging) that keeps the full
request payload (messages included) alive until a generational GC pass
instead of being freed by refcount when the request ends. Nothing in the
caching layer reads the logging object from these kwargs; cache-key
generation ignores litellm-internal params.
"""
if "litellm_logging_obj" not in request_kwargs:
return request_kwargs
return {k: v for k, v in request_kwargs.items() if k != "litellm_logging_obj"}


def _is_chat_completion_cached_dict(cached_result: dict) -> bool:
cached_id = cached_result.get("id")
if isinstance(cached_id, str) and cached_id.startswith("chatcmpl"):
Expand Down Expand Up @@ -118,7 +134,7 @@ def __init__(

self.async_streaming_chunks: List[ModelResponse] = []
self.sync_streaming_chunks: List[ModelResponse] = []
self.request_kwargs = request_kwargs
self.request_kwargs = _drop_logging_obj_from_kwargs(request_kwargs)
self.preset_cache_key: Optional[str] = None
self.original_function = original_function
self.start_time = start_time
Expand Down Expand Up @@ -297,7 +313,7 @@ def _sync_get_cache(
new_kwargs.pop("metadata", None)
if new_kwargs.get("stream") is True and "cache_key" not in new_kwargs:
new_kwargs["cache_key"] = litellm.cache.get_cache_key(**new_kwargs)
self.request_kwargs = new_kwargs
self.request_kwargs = _drop_logging_obj_from_kwargs(new_kwargs)
print_verbose("Checking Sync Cache")
cached_result = litellm.cache.get_cache(**new_kwargs)
if cached_result is not None:
Expand Down Expand Up @@ -693,7 +709,7 @@ async def _retrieve_from_cache(
new_kwargs.pop("metadata", None)
if new_kwargs.get("stream") is True and "cache_key" not in new_kwargs:
new_kwargs["cache_key"] = litellm.cache.get_cache_key(**new_kwargs)
self.request_kwargs = new_kwargs
self.request_kwargs = _drop_logging_obj_from_kwargs(new_kwargs)
cached_result: Optional[Any] = None
if call_type == CallTypes.aembedding.value:
if isinstance(new_kwargs["input"], str):
Expand Down
1 change: 1 addition & 0 deletions litellm/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -1496,6 +1496,7 @@
MAX_POLICY_ESTIMATE_IMPACT_ROWS = int(os.getenv("MAX_POLICY_ESTIMATE_IMPACT_ROWS", 1000))
DEFAULT_PROMPT_INJECTION_SIMILARITY_THRESHOLD = float(os.getenv("DEFAULT_PROMPT_INJECTION_SIMILARITY_THRESHOLD", 0.7))
LENGTH_OF_LITELLM_GENERATED_KEY = int(os.getenv("LENGTH_OF_LITELLM_GENERATED_KEY", 16))
MINIMUM_CUSTOM_KEY_LENGTH = int(os.getenv("MINIMUM_CUSTOM_KEY_LENGTH", 16))
SECRET_MANAGER_REFRESH_INTERVAL = int(os.getenv("SECRET_MANAGER_REFRESH_INTERVAL", 86400))
LITELLM_SETTINGS_SAFE_DB_OVERRIDES = [
"default_internal_user_params",
Expand Down
2 changes: 1 addition & 1 deletion litellm/litellm_core_utils/dd_tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from litellm.secret_managers.main import get_secret_bool

if TYPE_CHECKING:
from ddtrace.tracer import Tracer as DD_TRACER
from ddtrace.trace import Tracer as DD_TRACER
else:
DD_TRACER = Any

Expand Down
4 changes: 1 addition & 3 deletions litellm/litellm_core_utils/litellm_logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -925,7 +925,6 @@ def _pre_call(self, input, api_key, model=None, additional_args={}):

def pre_call(self, input, api_key, model=None, additional_args={}):
# Log the exact input to the LLM API
litellm.error_logs["PRE_CALL"] = locals()
try:
self._pre_call(
input=input,
Expand Down Expand Up @@ -1135,7 +1134,6 @@ def _get_masked_headers(self, headers: dict, ignore_sensitive_headers: bool = Fa

def post_call(self, original_response, input=None, api_key=None, additional_args={}):
# Log the exact result from the LLM API, for streaming - log the type of response received
litellm.error_logs["POST_CALL"] = locals()
if isinstance(original_response, dict):
original_response = json.dumps(original_response, default=str)
try:
Expand Down Expand Up @@ -3074,7 +3072,7 @@ def _should_run_sync_callbacks_for_async_calls(self) -> bool:
def get_combined_callback_list(self, dynamic_success_callbacks: Optional[List], global_callbacks: List) -> List:
if dynamic_success_callbacks is None:
return list(global_callbacks)
return list(set(dynamic_success_callbacks + global_callbacks))
return list(dict.fromkeys(dynamic_success_callbacks + global_callbacks))

def _remove_internal_litellm_callbacks(self, callbacks: List) -> List:
"""
Expand Down
41 changes: 41 additions & 0 deletions litellm/litellm_core_utils/redact_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,22 @@ def _redact_streaming_response(streaming_response):
streaming_response.reasoning = None


def _redact_tool_calls(tool_calls) -> None:
"""Redact tool call arguments (assistant tool calls carry prompt-derived data)."""
if not tool_calls:
return
for tool_call in tool_calls:
function = getattr(tool_call, "function", None)
if function is not None and hasattr(function, "arguments"):
function.arguments = "redacted-by-litellm"


def _redact_function_call(function_call) -> None:
"""Redact legacy assistant function_call arguments."""
if function_call is not None and hasattr(function_call, "arguments"):
function_call.arguments = "redacted-by-litellm"


def _redact_choice_content(choice):
"""Helper to redact content in a choice (message or delta)."""
if isinstance(choice, litellm.Choices):
Expand All @@ -85,12 +101,16 @@ def _redact_choice_content(choice):
choice.message.reasoning_content = "redacted-by-litellm"
if hasattr(choice.message, "thinking_blocks"):
choice.message.thinking_blocks = None
_redact_tool_calls(getattr(choice.message, "tool_calls", None))
_redact_function_call(getattr(choice.message, "function_call", None))
elif isinstance(choice, litellm.utils.StreamingChoices):
choice.delta.content = "redacted-by-litellm"
if hasattr(choice.delta, "reasoning_content"):
choice.delta.reasoning_content = "redacted-by-litellm"
if hasattr(choice.delta, "thinking_blocks"):
choice.delta.thinking_blocks = None
_redact_tool_calls(getattr(choice.delta, "tool_calls", None))
_redact_function_call(getattr(choice.delta, "function_call", None))


def _redact_responses_api_output(output_items):
Expand All @@ -111,6 +131,9 @@ def _redact_responses_api_output(output_items):
if hasattr(summary_item, "text"):
summary_item.text = "redacted-by-litellm"

if hasattr(output_item, "type") and output_item.type == "function_call" and hasattr(output_item, "arguments"):
output_item.arguments = "redacted-by-litellm"


def _redact_responses_api_output_dict(output_items, redacted_str: str):
"""Helper to redact ResponsesAPIResponse output items in dict form."""
Expand All @@ -131,6 +154,9 @@ def _redact_responses_api_output_dict(output_items, redacted_str: str):
if isinstance(summary_item, dict) and "text" in summary_item:
summary_item["text"] = redacted_str

if output_item.get("type") == "function_call" and "arguments" in output_item:
output_item["arguments"] = redacted_str


def _redact_standard_logging_object(model_call_details: dict):
"""Redact messages and response inside standard_logging_object if present."""
Expand Down Expand Up @@ -162,6 +188,19 @@ def _redact_standard_logging_object(model_call_details: dict):
standard_logging_object["response"] = {"text": redacted_str}


def _redact_tool_calls_dict(message: dict, redacted_str: str) -> None:
"""Redact tool call / function_call arguments in a dict-form message or delta."""
tool_calls = message.get("tool_calls")
if isinstance(tool_calls, list):
for tool_call in tool_calls:
if isinstance(tool_call, dict) and isinstance(tool_call.get("function"), dict):
tool_call["function"]["arguments"] = redacted_str

function_call = message.get("function_call")
if isinstance(function_call, dict) and "arguments" in function_call:
function_call["arguments"] = redacted_str


def _redact_model_response_dict_choices(choices, redacted_str: str):
for choice in choices:
if isinstance(choice, dict):
Expand All @@ -173,6 +212,7 @@ def _redact_model_response_dict_choices(choices, redacted_str: str):
choice["message"]["thinking_blocks"] = None
if "audio" in choice["message"]:
choice["message"]["audio"] = None
_redact_tool_calls_dict(choice["message"], redacted_str)
elif "delta" in choice and isinstance(choice["delta"], dict):
choice["delta"]["content"] = redacted_str
if "reasoning_content" in choice["delta"]:
Expand All @@ -181,6 +221,7 @@ def _redact_model_response_dict_choices(choices, redacted_str: str):
choice["delta"]["thinking_blocks"] = None
if "audio" in choice["delta"]:
choice["delta"]["audio"] = None
_redact_tool_calls_dict(choice["delta"], redacted_str)
else:
_redact_choice_content(choice)

Expand Down
4 changes: 3 additions & 1 deletion litellm/litellm_core_utils/secret_redaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
import re
from typing import List

from litellm.constants import MINIMUM_CUSTOM_KEY_LENGTH

_REDACTED = "REDACTED"


Expand All @@ -30,7 +32,7 @@ def _build_secret_patterns() -> "re.Pattern[str]":
# Basic auth headers
r"Basic\s+[A-Za-z0-9+/]{10,}={0,2}",
# OpenAI / Anthropic sk- prefixed keys
r"sk-[A-Za-z0-9\-_]{20,}",
rf"sk-[A-Za-z0-9\-_]{{{MINIMUM_CUSTOM_KEY_LENGTH - len('sk-')},}}",
# Generic api_key / api-key / apikey (handles 'key': 'value' dict repr)
r"(?:api[_-]?key)['\"]?\s*[:=]\s*['\"]?[^\s,'\"})\]{}>]{8,}",
# x-api-key / api-key header values (handles 'key': 'value' dict repr)
Expand Down
Loading
Loading