Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
4 changes: 4 additions & 0 deletions litellm/caching/dual_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -348,6 +348,8 @@ async def async_set_cache(self, key, value, local_only: bool = False, **kwargs):
)
try:
if self.in_memory_cache is not None:
if "ttl" not in kwargs and self.default_in_memory_ttl is not None:
kwargs["ttl"] = self.default_in_memory_ttl
await self.in_memory_cache.async_set_cache(key, value, **kwargs)

if self.redis_cache is not None and local_only is False:
Expand All @@ -369,6 +371,8 @@ async def async_set_cache_pipeline(
)
try:
if self.in_memory_cache is not None:
if "ttl" not in kwargs and self.default_in_memory_ttl is not None:
kwargs["ttl"] = self.default_in_memory_ttl
await self.in_memory_cache.async_set_cache_pipeline(
cache_list=cache_list, **kwargs
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,7 @@ def _convert_response_output_to_choices(
ResponseOutputMessage,
ResponseReasoningItem,
)
from openai.types.responses.response_output_item import ResponseApplyPatchToolCall

from litellm.types.utils import Choices, Message

Expand Down Expand Up @@ -456,6 +457,18 @@ def _convert_response_output_to_choices(
accumulated_tool_calls.append(tool_call_dict)
tool_call_index += 1

elif isinstance(item, ResponseApplyPatchToolCall):
from litellm.responses.litellm_completion_transformation.transformation import (
LiteLLMCompletionResponsesConfig,
)

tool_call_dict = LiteLLMCompletionResponsesConfig.convert_apply_patch_tool_call_to_chat_completion_tool_call(
tool_call_item=item,
index=tool_call_index,
)
accumulated_tool_calls.append(tool_call_dict)
tool_call_index += 1

elif isinstance(item, dict) and handle_raw_dict_callback is not None:
# Handle raw dict responses (e.g., from GPT-5 Codex)
choice, index = handle_raw_dict_callback(item=item, index=index)
Expand Down
10 changes: 4 additions & 6 deletions litellm/litellm_core_utils/duration_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,10 @@ def duration_in_seconds(duration: str) -> int:
now = time.time()
current_time = datetime.fromtimestamp(now)

if current_time.month == 12:
target_year = current_time.year + 1
target_month = 1
else:
target_year = current_time.year
target_month = current_time.month + value
# Calculate target month and year, handling overflow past December
total_months = current_time.month - 1 + value # 0-indexed months
target_year = current_time.year + total_months // 12
target_month = total_months % 12 + 1 # back to 1-indexed

# Determine the day to set for next month
target_day = current_time.day
Expand Down
47 changes: 47 additions & 0 deletions litellm/litellm_core_utils/redact_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,53 @@ def _redact_responses_api_output(output_items):
summary_item.text = "redacted-by-litellm"


def _redact_standard_logging_object(model_call_details: dict):
"""Redact messages and response inside standard_logging_object if present."""
standard_logging_object = model_call_details.get("standard_logging_object")
if standard_logging_object is None:
return

redacted_str = "redacted-by-litellm"

if standard_logging_object.get("messages") is not None:
standard_logging_object["messages"] = [
{"role": "user", "content": redacted_str}
]

response = standard_logging_object.get("response")
if response is not None:
if isinstance(response, dict) and "output" in response:
# ResponsesAPIResponse format - redact content in output items
if isinstance(response.get("output"), list):
for output_item in response["output"]:
if isinstance(output_item, dict) and "content" in output_item:
if isinstance(output_item["content"], list):
for content_item in output_item["content"]:
if (
isinstance(content_item, dict)
and "text" in content_item
):
content_item["text"] = redacted_str
elif isinstance(response, dict) and "choices" in response:
# ModelResponse dict format - redact content in choices
if isinstance(response.get("choices"), list):
for choice in response["choices"]:
if isinstance(choice, dict):
if "message" in choice and isinstance(choice["message"], dict):
choice["message"]["content"] = redacted_str
if "audio" in choice["message"]:
choice["message"]["audio"] = None
elif "delta" in choice and isinstance(choice["delta"], dict):
choice["delta"]["content"] = redacted_str
if "audio" in choice["delta"]:
choice["delta"]["audio"] = None
elif isinstance(response, str):
standard_logging_object["response"] = redacted_str
else:
# For other formats (empty dict, None, etc.), use simple text format
standard_logging_object["response"] = {"text": redacted_str}


def perform_redaction(model_call_details: dict, result):
"""
Comment on lines +78 to 126

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.

_redact_standard_logging_object is defined but never called

The helper function _redact_standard_logging_object is added to handle redacting the standard_logging_object inside model_call_details, but it is never invoked anywhere in the codebase (confirmed via global grep).

As a result, model_call_details["standard_logging_object"]["response"] and model_call_details["standard_logging_object"]["messages"] are not redacted when turn_off_message_logging is enabled, even though the e2e tests in tests/logging_callback_tests/test_logging_redaction_e2e_test.py were updated to assert the new finer-grained redaction behavior (e.g. response["choices"][0]["message"]["content"] == "redacted-by-litellm").

The function needs to be called from perform_redaction:

def perform_redaction(model_call_details: dict, result):
    # Redact model_call_details
    model_call_details["messages"] = [
        {"role": "user", "content": "redacted-by-litellm"}
    ]
    model_call_details["prompt"] = ""
    model_call_details["input"] = ""

    # Redact standard_logging_object if present
    _redact_standard_logging_object(model_call_details)
    ...

Without this call, the updated e2e test assertions will fail and users who rely on turn_off_message_logging will continue to have unredacted content leaked via the standard_logging_object.

Performs the actual redaction on the logging object and result.
Expand Down
27 changes: 25 additions & 2 deletions litellm/llms/bedrock/chat/converse_transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@
)
from litellm.types.utils import (
ChatCompletionMessageToolCall,
CompletionTokensDetailsWrapper,
Function,
Message,
ModelResponse,
Expand All @@ -63,6 +64,7 @@
has_tool_call_blocks,
last_assistant_with_tool_calls_has_no_thinking_blocks,
supports_reasoning,
token_counter,
)

from ..common_utils import (
Expand Down Expand Up @@ -1640,7 +1642,11 @@ def _transform_thinking_blocks(
thinking_blocks_list.append(_redacted_block)
return thinking_blocks_list

def _transform_usage(self, usage: ConverseTokenUsageBlock) -> Usage:
def _transform_usage(
self,
usage: ConverseTokenUsageBlock,
reasoning_content: Optional[str] = None,
) -> Usage:
input_tokens = usage["inputTokens"]
output_tokens = usage["outputTokens"]
total_tokens = usage["totalTokens"]
Expand All @@ -1657,13 +1663,27 @@ def _transform_usage(self, usage: ConverseTokenUsageBlock) -> Usage:
prompt_tokens_details = PromptTokensDetailsWrapper(
cached_tokens=cache_read_input_tokens
)
reasoning_tokens = (
token_counter(text=reasoning_content, count_response_tokens=True)
if reasoning_content
else 0
)
completion_tokens_details = CompletionTokensDetailsWrapper(
reasoning_tokens=reasoning_tokens,
text_tokens=(
output_tokens - reasoning_tokens
if reasoning_tokens > 0
else output_tokens
),
)
openai_usage = Usage(
prompt_tokens=input_tokens,
completion_tokens=output_tokens,
total_tokens=total_tokens,
prompt_tokens_details=prompt_tokens_details,
cache_creation_input_tokens=cache_creation_input_tokens,
cache_read_input_tokens=cache_read_input_tokens,
completion_tokens_details=completion_tokens_details,
)
return openai_usage

Expand Down Expand Up @@ -2000,7 +2020,10 @@ def _transform_response( # noqa: PLR0915
chat_completion_message["tool_calls"] = filtered_tools

## CALCULATING USAGE - bedrock returns usage in the headers
usage = self._transform_usage(completion_response["usage"])
usage = self._transform_usage(
completion_response["usage"],
reasoning_content=chat_completion_message.get("reasoning_content"),
)

## HANDLE TOOL CALLS
_message = Message(**chat_completion_message)
Expand Down
5 changes: 4 additions & 1 deletion litellm/llms/fireworks_ai/chat/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -429,8 +429,11 @@ def get_models(self, api_key: Optional[str] = None, api_base: Optional[str] = No
"FIREWORKS_ACCOUNT_ID is not set. Please set the environment variable, to query Fireworks AI's `/models` endpoint."
)

base = api_base.rstrip("/")
if base.endswith("/v1"):
base = base[: -len("/v1")]
response = litellm.module_level_client.get(
url=f"{api_base}/v1/accounts/{account_id}/models",
url=f"{base}/v1/accounts/{account_id}/models",
headers={"Authorization": f"Bearer {api_key}"},
)

Expand Down
56 changes: 20 additions & 36 deletions litellm/llms/sagemaker/completion/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -583,35 +583,17 @@ def embedding(
### BOTO3 INIT
import boto3

# pop aws_secret_access_key, aws_access_key_id, aws_region_name from kwargs, since completion calls fail with them
aws_secret_access_key = optional_params.pop("aws_secret_access_key", None)
aws_access_key_id = optional_params.pop("aws_access_key_id", None)
aws_region_name = optional_params.pop("aws_region_name", None)
# Use _load_credentials to support role assumption (aws_role_name, aws_session_name)
credentials, aws_region_name = self._load_credentials(optional_params)

if aws_access_key_id is not None:
# uses auth params passed to completion
# aws_access_key_id is not None, assume user is trying to auth using litellm.completion
client = boto3.client(
service_name="sagemaker-runtime",
aws_access_key_id=aws_access_key_id,
aws_secret_access_key=aws_secret_access_key,
region_name=aws_region_name,
)
else:
# aws_access_key_id is None, assume user is trying to auth using env variables
# boto3 automaticaly reads env variables

# we need to read region name from env
# I assume majority of users use .env for auth
region_name = (
get_secret("AWS_REGION_NAME")
or aws_region_name # get region from config file if specified
or "us-west-2" # default to us-west-2 if region not specified
)
client = boto3.client(
service_name="sagemaker-runtime",
region_name=region_name,
)
# Create boto3 session with the loaded credentials
session = boto3.Session(
aws_access_key_id=credentials.access_key,
aws_secret_access_key=credentials.secret_key,
aws_session_token=credentials.token,
region_name=aws_region_name,
)
client = session.client(service_name="sagemaker-runtime")

# pop streaming if it's in the optional params as 'stream' raises an error with sagemaker
inference_params = deepcopy(optional_params)
Expand All @@ -628,7 +610,9 @@ def embedding(
#### EMBEDDING LOGIC
# Transform request based on model type
provider_config = SagemakerEmbeddingConfig.get_model_config(model)
request_data = provider_config.transform_embedding_request(model, input, optional_params, {})
request_data = provider_config.transform_embedding_request(
model, input, optional_params, {}
)
data = json.dumps(request_data).encode("utf-8")

## LOGGING
Expand Down Expand Up @@ -673,19 +657,19 @@ def embedding(
)

print_verbose(f"raw model_response: {response}")

# Transform response based on model type
from httpx import Response as HttpxResponse

# Create a mock httpx Response object for the transformation
mock_response = HttpxResponse(
status_code=200,
content=json.dumps(response).encode('utf-8'),
headers={"content-type": "application/json"}
content=json.dumps(response).encode("utf-8"),
headers={"content-type": "application/json"},
)

model_response = EmbeddingResponse()

# Use the request_data that was already transformed above
return provider_config.transform_embedding_response(
model=model,
Expand All @@ -695,5 +679,5 @@ def embedding(
api_key=None,
request_data=request_data,
optional_params=optional_params,
litellm_params=litellm_params or {}
litellm_params=litellm_params or {},
)
4 changes: 4 additions & 0 deletions litellm/llms/vertex_ai/gemini/transformation.py
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,10 @@ def _gemini_convert_messages_with_history( # noqa: PLR0915
raise e


# Keys that LiteLLM consumes internally and must never be forwarded to the
_LITELLM_INTERNAL_EXTRA_BODY_KEYS: frozenset = frozenset({"cache", "tags"})


def _pop_and_merge_extra_body(data: RequestBody, optional_params: dict) -> None:
"""Pop extra_body from optional_params and shallow-merge into data, deep-merging dict values."""
extra_body: Optional[dict] = optional_params.pop("extra_body", None)
Expand Down
11 changes: 7 additions & 4 deletions litellm/proxy/_experimental/mcp_server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,7 @@ def _tool_name_matches(tool_name: str, filter_list: List[str]) -> bool:

Checks both the full tool name and unprefixed version (without server prefix).
This allows users to configure simple tool names regardless of prefixing.
Comparison is case-insensitive to handle OpenAPI operationIds that may be in camelCase.

Args:
tool_name: The tool name to check (may be prefixed like "server-tool_name")
Expand All @@ -730,13 +731,15 @@ def _tool_name_matches(tool_name: str, filter_list: List[str]) -> bool:
split_server_prefix_from_name,
)

# Check if the full name is in the list
if tool_name in filter_list:
# Normalize filter list to lowercase for case-insensitive comparison
filter_list_lower = [f.lower() for f in filter_list]

if tool_name.lower() in filter_list_lower:
return True

# Check if the unprefixed name is in the list
# Check if the unprefixed name is in the list (case-insensitive)
unprefixed_name, _ = split_server_prefix_from_name(tool_name)
return unprefixed_name in filter_list
return unprefixed_name.lower() in filter_list_lower

def filter_tools_by_allowed_tools(
tools: List[MCPTool],
Expand Down
18 changes: 14 additions & 4 deletions litellm/proxy/auth/model_checks.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,12 +111,19 @@ def get_key_models(
if SpecialModelNames.all_team_models.value in all_models:
all_models = list(user_api_key_dict.team_models) # copy to avoid mutating cached objects
if SpecialModelNames.all_proxy_models.value in all_models:
all_models = proxy_model_list
all_models = list(proxy_model_list) # copy to avoid mutating caller's list
if include_model_access_groups:
all_models.extend(model_access_groups.keys())

all_models = _get_models_from_access_groups(
model_access_groups=model_access_groups, all_models=all_models
model_access_groups=model_access_groups,
all_models=all_models,
include_model_access_groups=include_model_access_groups,
)

# deduplicate while preserving order
all_models = list(dict.fromkeys(all_models))

verbose_proxy_logger.debug("ALL KEY MODELS - {}".format(len(all_models)))
return all_models

Expand All @@ -140,15 +147,18 @@ def get_team_models(
all_models_set.update(team_models)
if SpecialModelNames.all_proxy_models.value in all_models_set:
all_models_set.update(proxy_model_list)

all_models = list(all_models_set)
if include_model_access_groups:
all_models_set.update(model_access_groups.keys())

all_models = _get_models_from_access_groups(
model_access_groups=model_access_groups,
all_models=list(all_models_set),
include_model_access_groups=include_model_access_groups,
)

# deduplicate while preserving order
all_models = list(dict.fromkeys(all_models))

verbose_proxy_logger.debug("ALL TEAM MODELS - {}".format(len(all_models)))
return all_models

Expand Down
Loading
Loading