Skip to content

The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]

Switch to string constant based truncation

WilsonSunBritten07213457036a
diff --git a/litellm/constants.py b/litellm/constants.py
index 78d5e5760d1..56e0e4a0757 100644
--- a/litellm/constants.py
+++ b/litellm/constants.py
@@ -157,6 +157,7 @@ NON_LLM_CONNECTION_TIMEOUT = int(
os.getenv("NON_LLM_CONNECTION_TIMEOUT", 15)
) # timeout for adjacent services (e.g. jwt auth)
MAX_EXCEPTION_MESSAGE_LENGTH = int(os.getenv("MAX_EXCEPTION_MESSAGE_LENGTH", 2000))
+MAX_STRING_LENGTH_PROMPT_IN_DB = int(os.getenv("MAX_STRING_LENGTH_PROMPT_IN_DB", 1000))
BEDROCK_MAX_POLICY_SIZE = int(os.getenv("BEDROCK_MAX_POLICY_SIZE", 75))
REPLICATE_POLLING_DELAY_SECONDS = float(
os.getenv("REPLICATE_POLLING_DELAY_SECONDS", 0.5)
diff --git a/litellm/proxy/spend_tracking/spend_tracking_utils.py b/litellm/proxy/spend_tracking/spend_tracking_utils.py
index 653426e8bd2..fc62895be1b 100644
--- a/litellm/proxy/spend_tracking/spend_tracking_utils.py
+++ b/litellm/proxy/spend_tracking/spend_tracking_utils.py
@@ -10,7 +10,7 @@ from pydantic import BaseModel
import litellm
from litellm._logging import verbose_proxy_logger
-from litellm.constants import REDACTED_BY_LITELM_STRING
+from litellm.constants import REDACTED_BY_LITELM_STRING, MAX_STRING_LENGTH_PROMPT_IN_DB
from litellm.litellm_core_utils.core_helpers import get_litellm_metadata_from_kwargs
from litellm.litellm_core_utils.safe_json_dumps import safe_dumps
from litellm.proxy._types import SpendLogsMetadata, SpendLogsPayload
@@ -481,10 +481,9 @@ def _sanitize_request_body_for_spend_logs_payload(
) -> dict:
"""
Recursively sanitize request body to prevent logging large base64 strings or other large values.
- Truncates strings longer than 1000 characters and handles nested dictionaries.
+ Truncates strings longer than MAX_STRING_LENGTH_PROMPT_IN_DB characters and handles nested dictionaries.
"""
from litellm.constants import LITELLM_TRUNCATED_PAYLOAD_FIELD
- MAX_STRING_LENGTH = 1000
if visited is None:
visited = set()
@@ -501,8 +500,8 @@ def _sanitize_request_body_for_spend_logs_payload(
elif isinstance(value, list):
return [_sanitize_value(item) for item in value]
elif isinstance(value, str):
- if len(value) > MAX_STRING_LENGTH:
- return f"{value[:MAX_STRING_LENGTH]}... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} {len(value) - MAX_STRING_LENGTH} chars)"
+ if len(value) > MAX_STRING_LENGTH_PROMPT_IN_DB:
+ return f"{value[:MAX_STRING_LENGTH_PROMPT_IN_DB]}... ({LITELLM_TRUNCATED_PAYLOAD_FIELD} {len(value) - MAX_STRING_LENGTH_PROMPT_IN_DB} chars)"
return value
return value
diff --git a/tests/logging_callback_tests/test_spend_logs.py b/tests/logging_callback_tests/test_spend_logs.py
index 5eed5971605..46e4e2cfcc4 100644
--- a/tests/logging_callback_tests/test_spend_logs.py
+++ b/tests/logging_callback_tests/test_spend_logs.py
@@ -25,7 +25,7 @@ from typing import Optional
import pytest
import litellm
-from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload
+from litellm.proxy.spend_tracking.spend_tracking_utils import get_logging_payload, _sanitize_request_body_for_spend_logs_payload
from litellm.proxy._types import SpendLogsMetadata, SpendLogsPayload
@@ -396,3 +396,91 @@ def test_spend_logs_payload_with_prompts_enabled(monkeypatch):
payload_disabled: SpendLogsPayload = get_logging_payload(**input_args)
assert payload_disabled["messages"] == "{}"
assert payload_disabled["response"] == "{}"
+
+
+def test_large_request_no_truncation_threshold():
+ """
+ Test that MAX_STRING_LENGTH_PROMPT_IN_DB constant is used for request body sanitization
+ """
+ from litellm.constants import MAX_STRING_LENGTH_PROMPT_IN_DB, LITELLM_TRUNCATED_PAYLOAD_FIELD
+
+ # Create a large string that exceeds the threshold
+ large_content = "x" * (MAX_STRING_LENGTH_PROMPT_IN_DB + 500)
+
+ request_body = {
+ "messages": [
+ {"role": "user", "content": large_content}
+ ],
+ "model": "gpt-4"
+ }
+
+ sanitized = _sanitize_request_body_for_spend_logs_payload(request_body)
+
+ # Verify the content was truncated
+ truncated_content = sanitized["messages"][0]["content"]
+ assert len(truncated_content) > MAX_STRING_LENGTH_PROMPT_IN_DB # includes truncation message
+ assert truncated_content.startswith("x" * MAX_STRING_LENGTH_PROMPT_IN_DB)
+ assert LITELLM_TRUNCATED_PAYLOAD_FIELD in truncated_content
+ assert "500 chars" in truncated_content
+
+
+def test_small_request_no_truncation():
+ """
+ Test that small strings are not truncated by MAX_STRING_LENGTH_PROMPT_IN_DB
+ """
+ from litellm.constants import MAX_STRING_LENGTH_PROMPT_IN_DB
+
+ # Create a small string that's under the threshold
+ small_content = "x" * (MAX_STRING_LENGTH_PROMPT_IN_DB - 100)
+
+ request_body = {
+ "messages": [
+ {"role": "user", "content": small_content}
+ ],
+ "model": "gpt-4"
+ }
+
+ sanitized = _sanitize_request_body_for_spend_logs_payload(request_body)
+
+ # Verify the content was NOT truncated
+ assert sanitized["messages"][0]["content"] == small_content
+ assert len(sanitized["messages"][0]["content"]) == MAX_STRING_LENGTH_PROMPT_IN_DB - 100
+
+
+def test_configurable_string_length_env_var(monkeypatch):
+ """
+ Test that MAX_STRING_LENGTH_PROMPT_IN_DB can be configured via environment variable
+ """
+ # Set environment variable to a custom value
+ monkeypatch.setenv("MAX_STRING_LENGTH_PROMPT_IN_DB", "500")
+
+ # Import after setting env var to ensure it picks up the new value
+ import importlib
+ import litellm.constants
+ import litellm.proxy.spend_tracking.spend_tracking_utils
+ importlib.reload(litellm.constants)
+ importlib.reload(litellm.proxy.spend_tracking.spend_tracking_utils)
+
+ from litellm.constants import MAX_STRING_LENGTH_PROMPT_IN_DB, LITELLM_TRUNCATED_PAYLOAD_FIELD
+ from litellm.proxy.spend_tracking.spend_tracking_utils import _sanitize_request_body_for_spend_logs_payload
+
+ # Verify the constant was set to the env var value
+ assert MAX_STRING_LENGTH_PROMPT_IN_DB == 500
+
+ # Test truncation with the custom value
+ large_content = "y" * 750 # 250 chars over the custom limit
+
+ request_body = {
+ "messages": [
+ {"role": "user", "content": large_content}
+ ],
+ "model": "gpt-4"
+ }
+
+ sanitized = _sanitize_request_body_for_spend_logs_payload(request_body)
+
+ # Verify truncation occurred at the custom threshold
+ truncated_content = sanitized["messages"][0]["content"]
+ assert truncated_content.startswith("y" * 500)
+ assert LITELLM_TRUNCATED_PAYLOAD_FIELD in truncated_content
+ assert "250 chars" in truncated_content