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]

fix(logging)!: redact Responses instructions and callback output (#43315)

Emerson Gomes74230b4d501a
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 78ff073fdcb..0d851ed38c2 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -117,7 +117,8 @@ from litellm.litellm_core_utils.ptu_pricing import is_spilled_over_ptu_request
from litellm.litellm_core_utils.redact_messages import (
redact_message_input_output_from_custom_logger,
redact_message_input_output_from_logging,
- redact_streaming_responses_for_custom_logger,
+ redacted_model_call_details_for_custom_logger,
+ redacted_response_obj_for_custom_logger,
should_redact_message_logging,
)
from litellm.litellm_core_utils.served_output_texts import (
@@ -3489,8 +3490,10 @@ class Logging(LiteLLMLoggingBaseClass):
): # custom logger class
if self.stream and complete_streaming_response is None:
callback.log_stream_event(
- kwargs=call_details,
- response_obj=result,
+ kwargs=redacted_model_call_details_for_custom_logger(
+ model_call_details=call_details, custom_logger=callback
+ ),
+ response_obj=redacted_response_obj_for_custom_logger(result, callback),
start_time=start_time,
end_time=end_time,
)
@@ -3500,8 +3503,13 @@ class Logging(LiteLLMLoggingBaseClass):
result = call_details_view["complete_response"]
callback.log_success_event(
- kwargs=callback.redact_standard_logging_payload_from_model_call_details(call_details),
- response_obj=result,
+ kwargs=redacted_model_call_details_for_custom_logger(
+ model_call_details=callback.redact_standard_logging_payload_from_model_call_details(
+ call_details
+ ),
+ custom_logger=callback,
+ ),
+ response_obj=redacted_response_obj_for_custom_logger(result, callback),
start_time=start_time,
end_time=end_time,
)
@@ -3844,7 +3852,7 @@ class Logging(LiteLLMLoggingBaseClass):
model_call_details = callback.redact_standard_logging_payload_from_model_call_details(
model_call_details=model_call_details
)
- model_call_details = redact_streaming_responses_for_custom_logger(
+ model_call_details = redacted_model_call_details_for_custom_logger(
model_call_details=model_call_details, custom_logger=callback
)
##################################
@@ -3855,7 +3863,7 @@ class Logging(LiteLLMLoggingBaseClass):
kwargs=model_call_details,
response_obj=model_call_details["async_complete_streaming_response"]
if self.stream
- else result,
+ else redacted_response_obj_for_custom_logger(result, callback),
start_time=start_time,
end_time=end_time,
guardrail_snapshot=self.shadow_eval_request_snapshot,
@@ -3871,14 +3879,14 @@ class Logging(LiteLLMLoggingBaseClass):
else:
await callback.async_log_stream_event( # [TODO]: move this to being an async log stream event function
kwargs=model_call_details,
- response_obj=result,
+ response_obj=redacted_response_obj_for_custom_logger(result, callback),
start_time=start_time,
end_time=end_time,
)
else:
await callback.async_log_success_event(
kwargs=model_call_details,
- response_obj=result,
+ response_obj=redacted_response_obj_for_custom_logger(result, callback),
start_time=start_time,
end_time=end_time,
)
diff --git a/litellm/litellm_core_utils/redact_messages.py b/litellm/litellm_core_utils/redact_messages.py
index c2cca5739cf..0168cdad7c0 100644
--- a/litellm/litellm_core_utils/redact_messages.py
+++ b/litellm/litellm_core_utils/redact_messages.py
@@ -10,10 +10,12 @@
import asyncio
import copy
import inspect
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from dataclasses import replace
from typing import TYPE_CHECKING, Any, Final
+from pydantic import TypeAdapter
+
import litellm
from litellm.constants import REDACTED_BY_LITELLM
from litellm.integrations.custom_logger import CustomLogger
@@ -40,36 +42,79 @@ else:
LiteLLMLoggingObject = Any
+def _opted_out_of_message_logging(custom_logger: CustomLogger) -> bool:
+ return hasattr(custom_logger, "message_logging") and custom_logger.message_logging is not True
+
+
def redact_message_input_output_from_custom_logger(
litellm_logging_obj: LiteLLMLoggingObject, result, custom_logger: CustomLogger
-):
- if hasattr(custom_logger, "message_logging") and custom_logger.message_logging is not True:
+) -> object:
+ if _opted_out_of_message_logging(custom_logger):
return perform_redaction(litellm_logging_obj.model_call_details, result, redact_streaming_responses=False)
return result
-def redact_streaming_responses_for_custom_logger(model_call_details: dict, custom_logger: CustomLogger) -> dict:
+def redacted_model_call_details_for_custom_logger(model_call_details: dict, custom_logger: CustomLogger) -> dict:
"""
- Returns a copy of model_call_details whose streaming response entries are redacted deepcopies
- when the custom logger has opted out of message logging. The shared model_call_details is left
- untouched so other callbacks still receive the unredacted response.
+ Returns a copy of model_call_details with the request messages, instructions and streaming responses
+ redacted when the custom logger has opted out of message logging. The shared model_call_details is left
+ untouched so other callbacks and the spend log still receive the unredacted values.
"""
- if not (hasattr(custom_logger, "message_logging") and custom_logger.message_logging is not True):
+ if not _opted_out_of_message_logging(custom_logger):
return model_call_details
- redacted_entries: Final = {
- streaming_key: _redacted_streaming_response_copy(model_call_details[streaming_key])
- for streaming_key in ("complete_streaming_response", "async_complete_streaming_response")
- if model_call_details.get(streaming_key) is not None
+ return {
+ **{key: value for key, value in model_call_details.items() if key != SERVED_OUTPUT_TEXTS_KEY},
+ **_redacted_entries_for_opted_out_logger(model_call_details),
}
- if not redacted_entries:
- return model_call_details
- return {**model_call_details, **redacted_entries}
-def _redacted_streaming_response_copy(streaming_response):
- redacted_response: Final = copy.deepcopy(streaming_response)
- _redact_streaming_response(redacted_response)
- return redacted_response
+def _redacted_entries_for_opted_out_logger(model_call_details: Mapping[str, object]) -> Mapping[str, object]:
+ optional_params: Final = _as_mapping(model_call_details.get("optional_params"))
+ litellm_params: Final = _as_mapping(model_call_details.get("litellm_params"))
+ standard_logging_object: Final = _as_mapping(model_call_details.get("standard_logging_object"))
+ return {
+ "messages": [{"role": "user", "content": REDACTED_BY_LITELLM}],
+ "prompt": "",
+ "input": "",
+ **({"instructions": REDACTED_BY_LITELLM} if model_call_details.get("instructions") is not None else {}),
+ **({"optional_params": _with_redacted_instructions(optional_params)} if optional_params is not None else {}),
+ **({"litellm_params": redacted_litellm_params(litellm_params)} if litellm_params is not None else {}),
+ **(
+ {"standard_logging_object": _redact_standard_logging_object(standard_logging_object)}
+ if standard_logging_object is not None
+ else {}
+ ),
+ **{
+ streaming_key: _redacted_streaming_response_copy(model_call_details[streaming_key])
+ for streaming_key in (
+ "complete_streaming_response",
+ "async_complete_streaming_response",
+ "complete_response",
+ )
+ if model_call_details.get(streaming_key) is not None
+ },
+ }
+
+
+def redacted_response_obj_for_custom_logger(response_obj: object, custom_logger: CustomLogger) -> object:
+ if not _opted_out_of_message_logging(custom_logger) or not _is_redactable_response(response_obj):
+ return response_obj
+ return perform_redaction({}, response_obj)
+
+
+def _is_redactable_response(response_obj: object) -> bool:
+ return isinstance(
+ response_obj, (litellm.ModelResponse, litellm.ResponsesAPIResponse, litellm.EmbeddingResponse)
+ ) or (isinstance(response_obj, dict) and ("choices" in response_obj or "output" in response_obj))
+
+
+def _redacted_streaming_response_copy(streaming_response: object) -> object:
+ redacted_response: Final = (
+ streaming_response
+ if isinstance(streaming_response, litellm.ResponsesAPIResponse)
+ else copy.deepcopy(streaming_response)
+ )
+ return _redact_streaming_response(redacted_response)
def _redact_streaming_response(streaming_response):
@@ -77,10 +122,13 @@ def _redact_streaming_response(streaming_response):
for choice in streaming_response.choices:
_redact_choice_content(choice)
redact_vertex_ai_metadata_from_logged_object(streaming_response)
+ elif isinstance(streaming_response, litellm.ResponsesAPIResponse):
+ return perform_redaction({}, streaming_response)
elif hasattr(streaming_response, "output"):
_redact_responses_api_output(streaming_response.output)
if hasattr(streaming_response, "reasoning") and streaming_response.reasoning is not None:
streaming_response.reasoning = None
+ return streaming_response
def _redact_tool_calls(tool_calls) -> None:
@@ -177,31 +225,75 @@ def _redact_responses_api_output(output_items):
output_item.input = REDACTED_BY_LITELLM
-def _redact_responses_api_output_dict(output_items, redacted_str: str):
- """Helper to redact ResponsesAPIResponse output items in dict form."""
- for output_item in output_items:
- if not isinstance(output_item, dict):
- continue
+_RESPONSE_ITEMS: Final = TypeAdapter(tuple[object, ...])
+
+
+def _redacted_responses_api_output_part(part: object, fields: tuple[str, ...], redacted_str: str) -> object:
+ if (part_mapping := _as_mapping(part)) is None:
+ return part
+ return {key: redacted_str if key in fields and value is not None else value for key, value in part_mapping.items()}
+
+
+def _redacted_responses_api_output_item(item: object, redacted_str: str) -> object:
+ if (item_mapping := _as_mapping(item)) is None:
+ return item
+ content: Final = item_mapping.get("content")
+ summary: Final = item_mapping.get("summary")
+ return {
+ **item_mapping,
+ **({"text": redacted_str} if item_mapping.get("text") is not None else {}),
+ **(
+ {
+ "content": [
+ _redacted_responses_api_output_part(part, ("text", "refusal"), redacted_str)
+ for part in _RESPONSE_ITEMS.validate_python(content)
+ ]
+ }
+ if isinstance(content, list)
+ else {}
+ ),
+ **(
+ {
+ "summary": [
+ _redacted_responses_api_output_part(part, ("text",), redacted_str)
+ for part in _RESPONSE_ITEMS.validate_python(summary)
+ ]
+ }
+ if item_mapping.get("type") == "reasoning" and isinstance(summary, list)
+ else {}
+ ),
+ **(
+ {"arguments": redacted_str}
+ if item_mapping.get("type") == "function_call" and "arguments" in item_mapping
+ else {}
+ ),
+ **(
+ {"input": redacted_str}
+ if item_mapping.get("type") == "custom_tool_call" and "input" in item_mapping
+ else {}
+ ),
+ }
+
- if output_item.get("text") is not None:
- output_item["text"] = redacted_str
+def _redact_responses_api_output_dict(output_items: Sequence[object], redacted_str: str) -> Sequence[object]:
+ return [_redacted_responses_api_output_item(item, redacted_str) for item in output_items]
- if isinstance(output_item.get("content"), list):
- for content_item in output_item["content"]:
- if isinstance(content_item, dict) and content_item.get("text") is not None:
- content_item["text"] = redacted_str
- if isinstance(content_item, dict) and content_item.get("refusal") is not None:
- content_item["refusal"] = redacted_str
- if output_item.get("type") == "reasoning" and isinstance(output_item.get("summary"), list):
- for summary_item in output_item["summary"]:
- if isinstance(summary_item, dict) and summary_item.get("text") is not None:
- summary_item["text"] = redacted_str
+def _with_redacted_instructions(params: Mapping[str, object]) -> Mapping[str, object]:
+ return params if params.get("instructions") is None else {**params, "instructions": REDACTED_BY_LITELLM}
- if output_item.get("type") == "function_call" and "arguments" in output_item:
- output_item["arguments"] = redacted_str
- if output_item.get("type") == "custom_tool_call" and "input" in output_item:
- output_item["input"] = redacted_str
+
+def _redacted_responses_api_response(
+ response: Mapping[str, object], *, redact_instructions: bool = True
+) -> Mapping[str, object]:
+ output: Final = response.get("output")
+ redacted: Final = {
+ **response,
+ "output": _redact_responses_api_output_dict(_RESPONSE_ITEMS.validate_python(output), REDACTED_BY_LITELLM)
+ if isinstance(output, list)
+ else output,
+ }
+ return _with_redacted_instructions(redacted) if redact_instructions else redacted
def redacted_standard_logging_payload(payload: Mapping[str, object]) -> Mapping[str, object]:
@@ -215,20 +307,25 @@ def redacted_standard_logging_payload(payload: Mapping[str, object]) -> Mapping[
return _redact_standard_logging_object(payload)
-def _redact_standard_logging_object(payload: Mapping[str, object]) -> dict[str, object]:
+def _redact_standard_logging_object(
+ payload: Mapping[str, object], *, redact_instructions: bool = True
+) -> dict[str, object]:
standard_logging_object: Final = copy.deepcopy(without_classifier_audit(payload))
redacted_str: Final = REDACTED_BY_LITELLM
if standard_logging_object.get("messages") is not None:
standard_logging_object["messages"] = [{"role": "user", "content": redacted_str}]
+ model_parameters: Final = _as_mapping(standard_logging_object.get("model_parameters"))
+ if model_parameters is not None and redact_instructions:
+ standard_logging_object["model_parameters"] = _with_redacted_instructions(model_parameters)
response: Final = 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):
- _redact_responses_api_output_dict(response["output"], redacted_str)
- redact_vertex_ai_metadata_from_logged_object(response)
+ standard_logging_object["response"] = _redacted_responses_api_response(
+ response, redact_instructions=redact_instructions
+ )
+ redact_vertex_ai_metadata_from_logged_object(standard_logging_object["response"])
elif isinstance(response, dict) and "choices" in response:
# ModelResponse dict format - redact content in choices
if isinstance(response.get("choices"), list):
@@ -320,11 +417,11 @@ def _redact_hidden_provider_specific_fields(params: Mapping[str, object]) -> Non
def redacted_litellm_params(params: Mapping[str, object], *, redact_request_body: bool = True) -> dict[str, object]:
"""
Copy of litellm_params without classifier audit fields or baseline route request parameters.
- redact_request_body also redacts the nested proxy_server_request body.
+ redact_request_body also redacts the request instructions and the nested proxy_server_request body.
"""
request: Final = _as_mapping(params.get("proxy_server_request"))
return {
- **params,
+ **(_with_redacted_instructions(params) if redact_request_body else params),
**{
key: _redacted_baseline_metadata(value)
for key, value in params.items()
@@ -344,8 +441,9 @@ def perform_redaction(model_call_details: dict, result, redact_streaming_respons
redact_streaming_responses=False skips the in-place redaction of the shared streaming
response entries; per-callback redaction hands each opted-out callback its own redacted
- copy via redact_streaming_responses_for_custom_logger instead. It also leaves the shared
- proxy request body and hidden provider fields as they are, since the spend log reads them.
+ copy via redacted_model_call_details_for_custom_logger instead. It also leaves the shared
+ request instructions, proxy request body and hidden provider fields as they are, since the
+ spend log and the other callbacks read them.
"""
# Redact model_call_details
params: Final = _as_mapping(model_call_details.get("litellm_params"))
@@ -358,16 +456,31 @@ def perform_redaction(model_call_details: dict, result, redact_streaming_respons
model_call_details["messages"] = [{"role": "user", "content": REDACTED_BY_LITELLM}]
model_call_details["prompt"] = ""
model_call_details["input"] = ""
+ optional_params: Final = _as_mapping(model_call_details.get("optional_params"))
+ if redact_streaming_responses:
+ model_call_details.update(
+ {
+ **({"instructions": REDACTED_BY_LITELLM} if model_call_details.get("instructions") is not None else {}),
+ **({"optional_params": _with_redacted_instructions(optional_params)} if optional_params else {}),
+ }
+ )
model_call_details.pop(SERVED_OUTPUT_TEXTS_KEY, None)
standard_logging_object: Final = model_call_details.get("standard_logging_object")
if isinstance(standard_logging_object, Mapping):
- model_call_details["standard_logging_object"] = _redact_standard_logging_object(standard_logging_object)
+ model_call_details["standard_logging_object"] = _redact_standard_logging_object(
+ standard_logging_object, redact_instructions=redact_streaming_responses
+ )
redact_vertex_ai_metadata_from_litellm_params(model_call_details)
# Redact streaming response
if redact_streaming_responses and model_call_details.get("stream", False) is True:
- for _streaming_key in ("complete_streaming_response", "async_complete_streaming_response"):
- _redact_streaming_response(model_call_details.get(_streaming_key))
+ model_call_details.update(
+ {
+ streaming_key: _redact_streaming_response(model_call_details[streaming_key])
+ for streaming_key in ("complete_streaming_response", "async_complete_streaming_response")
+ if model_call_details.get(streaming_key) is not None
+ }
+ )
# Redact result
if result is not None:
@@ -381,10 +494,7 @@ def perform_redaction(model_call_details: dict, result, redact_streaming_respons
# For async objects, return a simple redacted response without deepcopy
return {"text": REDACTED_BY_LITELLM}
- if not (
- isinstance(result, (litellm.ModelResponse, litellm.ResponsesAPIResponse, litellm.EmbeddingResponse))
- or (isinstance(result, dict) and ("choices" in result or "output" in result))
- ):
+ if not _is_redactable_response(result):
return {"text": REDACTED_BY_LITELLM}
_result: Final = copy.deepcopy(result)
@@ -399,14 +509,18 @@ def perform_redaction(model_call_details: dict, result, redact_streaming_respons
_redact_model_response_dict_choices(_result["choices"], REDACTED_BY_LITELLM)
redact_vertex_ai_metadata_from_logged_object(_result)
elif isinstance(_result, dict) and "output" in _result:
- if isinstance(_result.get("output"), list):
- _redact_responses_api_output_dict(_result["output"], REDACTED_BY_LITELLM)
+ return _redacted_responses_api_response(_result, redact_instructions=redact_streaming_responses)
elif isinstance(_result, litellm.ResponsesAPIResponse):
if hasattr(_result, "output"):
_redact_responses_api_output(_result.output)
# Redact reasoning field in ResponsesAPIResponse
if hasattr(_result, "reasoning") and _result.reasoning is not None:
_result.reasoning = None
+ return _result.model_copy(
+ update={"instructions": REDACTED_BY_LITELLM}
+ if redact_streaming_responses and _result.instructions is not None
+ else {}
+ )
elif isinstance(_result, litellm.EmbeddingResponse):
if hasattr(_result, "data") and _result.data is not None:
_result.data = []
diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py
index 2699dab2e29..2b2c55a8452 100644
--- a/litellm/proxy/utils.py
+++ b/litellm/proxy/utils.py
@@ -62,6 +62,7 @@ from litellm.constants import (
LITELLM_LOGGING_NO_UPSTREAM_LLM_CALL,
MAX_TEAM_LIST_LIMIT,
PROXY_REJECTED_BEFORE_ROUTING_KEY,
+ REDACTED_BY_LITELLM,
REDIS_SPEND_LOGS_BUFFER_DEQUEUE_COUNT,
SPEND_LOG_QUEUE_MAX_BYTES,
SPEND_LOG_WRITE_BATCH_MAX_BYTES,
@@ -1069,7 +1070,14 @@ def _estimated_prompt_usage(
if isinstance(optional_params, dict)
else None
)
- system_input: Final = dispatched_system or request_body.get("system") or request_body.get("instructions")
+ system_input: Final = next(
+ (
+ system
+ for system in (dispatched_system, request_body.get("system"), request_body.get("instructions"))
+ if system and system != REDACTED_BY_LITELLM
+ ),
+ None,
+ )
return _estimate_dispatched_failure_usage(
model=str(model_call_details.get("model") or ""),
request_input=model_call_details.get("messages"),
diff --git a/litellm/responses/litellm_completion_transformation/session_handler.py b/litellm/responses/litellm_completion_transformation/session_handler.py
index 615bdb5bbfb..35160830fdc 100644
--- a/litellm/responses/litellm_completion_transformation/session_handler.py
+++ b/litellm/responses/litellm_completion_transformation/session_handler.py
@@ -1,6 +1,6 @@
import asyncio
import json
-from collections.abc import Mapping
+from collections.abc import Mapping, Sequence
from typing import TYPE_CHECKING, Any, Final, cast
import litellm
@@ -71,6 +71,14 @@ def _stored_instructions(proxy_server_request: Mapping[str, object] | None) -> s
return instructions if isinstance(instructions, str) and instructions else None
+def _latest_replayable_instructions(proxy_server_requests: Sequence[Mapping[str, object] | None]) -> str | None:
+ latest: Final = next(
+ (instructions for instructions in map(_stored_instructions, reversed(proxy_server_requests)) if instructions),
+ None,
+ )
+ return None if latest == REDACTED_BY_LITELLM else latest
+
+
class ResponsesSessionHandler:
@staticmethod
async def get_chat_completion_message_history_for_previous_response_id(
@@ -127,14 +135,7 @@ class ResponsesSessionHandler:
return ChatCompletionSession(
messages=chat_completion_message_history,
litellm_session_id=litellm_session_id,
- instructions=next(
- (
- instructions
- for instructions in map(_stored_instructions, reversed(proxy_server_requests))
- if instructions
- ),
- None,
- ),
+ instructions=_latest_replayable_instructions(proxy_server_requests),
)
@staticmethod
diff --git a/tests/integration/observability/test_custom_logger_redaction.py b/tests/integration/observability/test_custom_logger_redaction.py
index 2abaa85df25..10340c51fea 100644
--- a/tests/integration/observability/test_custom_logger_redaction.py
+++ b/tests/integration/observability/test_custom_logger_redaction.py
@@ -370,7 +370,7 @@ def _drained(wire: Wire, count: int) -> tuple[Request, ...]:
return eventually(observed, lambda values: len(values) >= count, seconds=30)
-def test_redacted_responses_follow_up_replays_original_instructions(
+def test_redacted_responses_follow_up_replays_neither_instructions_nor_the_sentinel(
redaction_proxy: tuple[Gateway, Wire, Wire],
) -> None:
proxy, provider, sink = redaction_proxy
@@ -412,7 +412,7 @@ def test_redacted_responses_follow_up_replays_original_instructions(
assert len(sent) == 1, sent
assert len(sent[0]["messages"]) == 3, sent[0]
system: Final = json.dumps(sent[0].get("system"))
- assert INSTRUCTIONS in system and REDACTED_BY_LITELLM not in system, sent[0]
+ assert INSTRUCTIONS not in system and REDACTED_BY_LITELLM not in system, sent[0]
def test_redacted_router_usage_is_counted_once(redaction_proxy: tuple[Gateway, Wire, Wire]) -> None:
diff --git a/tests/unit/litellm_core_utils/test_redact_messages.py b/tests/unit/litellm_core_utils/test_redact_messages.py
index d14f236f765..a91888fea79 100644
--- a/tests/unit/litellm_core_utils/test_redact_messages.py
+++ b/tests/unit/litellm_core_utils/test_redact_messages.py
@@ -26,10 +26,12 @@ import litellm
from litellm.constants import LOGGING_WORKER_MAX_TIME_PER_COROUTINE
from litellm.integrations.custom_logger import CustomLogger
from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
+from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler, HTTPHandler
from litellm.litellm_core_utils.redact_messages import (
_redact_responses_api_output,
+ _redacted_responses_api_response,
perform_redaction,
- redact_streaming_responses_for_custom_logger,
+ redacted_model_call_details_for_custom_logger,
redacted_standard_logging_payload,
should_redact_message_logging,
)
@@ -163,6 +165,80 @@ def test_streaming_redaction_redacts_delta_provider_fields_without_touching_the_
assert fields == _provider_fields()
[email protected]("surface", ("typed", "dict", "standard", "callback", "helper"))
+def test_responses_redaction_removes_instructions_without_changing_the_response(surface: str) -> None:
+ response: Final = litellm.ResponsesAPIResponse.model_validate(
+ {
+ **mock_responses_api_response("private answer").model_dump(),
+ "instructions": "private system instructions",
+ "reasoning": {"effort": "low", "summary": "auto"},
+ "output": [
+ {
+ "type": "reasoning",
+ "id": "rs_test",
+ "summary": [{"type": "summary_text", "text": "private reasoning"}],
+ },
+ {
+ "type": "function_call",
+ "id": "fc_test",
+ "call_id": "call_test",
+ "name": "lookup",
+ "arguments": "private arguments",
+ },
+ ],
+ }
+ )
+ original: Final = response.model_dump()
+ payload: Final = {"response": copy.deepcopy(original), "model": "test-model"}
+ logger: Final = CustomLogger()
+ logger.turn_off_message_logging = True
+
+ surfaces: Final = {
+ "typed": lambda: perform_redaction({}, response).model_dump(),
+ "dict": lambda: perform_redaction({}, original),
+ "helper": lambda: _redacted_responses_api_response(original),
+ "standard": lambda: redacted_standard_logging_payload(payload)["response"],
+ "callback": lambda: logger.redact_standard_logging_payload_from_model_call_details(
+ {"standard_logging_object": payload}
+ )["standard_logging_object"]["response"],
+ }
+ redacted: Final = surfaces[surface]()
+
+ assert redacted == {
+ **original,
+ "instructions": "redacted-by-litellm",
+ **({"reasoning": None} if surface == "typed" else {}),
+ "output": [
+ {**original["output"][0], "summary": [{"type": "summary_text", "text": "redacted-by-litellm"}]},
+ {**original["output"][1], "arguments": "redacted-by-litellm"},
+ ],
+ }
+ assert "private" not in json.dumps(redacted)
+ assert response.model_dump() == original
+ assert payload["response"] == original
+
+
[email protected]("key", ("complete_streaming_response", "async_complete_streaming_response"))
[email protected]("redaction", ("global", "custom_logger"))
+def test_streaming_responses_redact_instructions_without_changing_the_client_response(key: str, redaction: str) -> None:
+ response: Final = mock_responses_api_response("private answer").model_copy(
+ update={"instructions": "private system instructions"}
+ )
+ original: Final = response.model_dump()
+ details: Final = {"stream": True, key: response}
+ if redaction == "global":
+ perform_redaction(details, result=None)
+ redacted_details: Final = (
+ redacted_model_call_details_for_custom_logger(details, CustomLogger(message_logging=False))
+ if redaction == "custom_logger"
+ else details
+ )
+
+ assert redacted_details[key].instructions == "redacted-by-litellm"
+ assert "private" not in json.dumps(redacted_details[key].model_dump())
+ assert response.model_dump() == original
+
+
@pytest.fixture(autouse=True)
def _reset_global_redaction():
"""Ensure the global setting is off for every test."""
@@ -335,7 +411,7 @@ class TestPerformRedaction:
result = {
"output": [
{"text": "top-level result"},
- {"content": [{"text": "nested result"}]},
+ {"content": [{"text": "nested result"}, "non-dict content item"]},
{"type": "reasoning", "summary": [{"text": "reasoning result"}]},
],
"usage": {"total_tokens": 1},
@@ -356,6 +432,7 @@ class TestPerformRedaction:
assert redacted["usage"] == {"total_tokens": 1}
assert redacted["output"][0]["text"] == "redacted-by-litellm"
assert redacted["output"][1]["content"][0]["text"] == "redacted-by-litellm"
+ assert redacted["output"][1]["content"][1] == "non-dict content item"
assert redacted["output"][2]["summary"][0]["text"] == "redacted-by-litellm"
assert result["output"][0]["text"] == "top-level result"
@@ -791,12 +868,14 @@ class TestPerformRedaction:
none_dict = {"type": "output_text", "text": None, "content": [{"text": None}]}
real_dict = {"type": "output_text", "text": "real answer", "content": [{"text": "real part"}]}
- _redact_responses_api_output_dict([none_dict, real_dict], "redacted-by-litellm")
+ redacted: Final = _redact_responses_api_output_dict([none_dict, real_dict], "redacted-by-litellm")
- assert none_dict["text"] is None
- assert none_dict["content"][0]["text"] is None
- assert real_dict["text"] == "redacted-by-litellm"
- assert real_dict["content"][0]["text"] == "redacted-by-litellm"
+ assert redacted == [
+ {"type": "output_text", "text": None, "content": [{"text": None}]},
+ {"type": "output_text", "text": "redacted-by-litellm", "content": [{"text": "redacted-by-litellm"}]},
+ ]
+ assert none_dict == {"type": "output_text", "text": None, "content": [{"text": None}]}
+ assert real_dict == {"type": "output_text", "text": "real answer", "content": [{"text": "real part"}]}
def test_skips_non_dict_response_output_items(self):
result = {
@@ -1003,33 +1082,36 @@ class TestPerformRedaction:
class TestRedactStreamingResponsesForCustomLogger:
- def _model_call_details(self):
+ def _model_call_details(self, key: str = "async_complete_streaming_response"):
response_obj = litellm.ModelResponse(
choices=[litellm.Choices(message=litellm.Message(content="secret content", role="assistant"))]
)
return {
"stream": True,
- "async_complete_streaming_response": response_obj,
+ key: response_obj,
}, response_obj
- def test_opted_out_logger_gets_redacted_copy(self):
- model_call_details, response_obj = self._model_call_details()
+ @pytest.mark.parametrize(
+ "key", ["async_complete_streaming_response", "complete_streaming_response", "complete_response"]
+ )
+ def test_opted_out_logger_gets_redacted_copy(self, key: str):
+ model_call_details, response_obj = self._model_call_details(key)
opted_out_logger = CustomLogger(message_logging=False)
- redacted_details = redact_streaming_responses_for_custom_logger(
+ redacted_details = redacted_model_call_details_for_custom_logger(
model_call_details=model_call_details, custom_logger=opted_out_logger
)
- redacted_response = redacted_details["async_complete_streaming_response"]
+ redacted_response = redacted_details[key]
assert redacted_response.choices[0].message.content == "redacted-by-litellm"
assert response_obj.choices[0].message.content == "secret content"
- assert model_call_details["async_complete_streaming_response"] is response_obj
+ assert model_call_details[key] is response_obj
def test_compliant_logger_gets_shared_response(self):
model_call_details, response_obj = self._model_call_details()
compliant_logger = CustomLogger()
- result_details = redact_streaming_responses_for_custom_logger(
+ result_details = redacted_model_call_details_for_custom_logger(
model_call_details=model_call_details, custom_logger=compliant_logger
)
@@ -1302,11 +1384,15 @@ class TestCustomLogger(CustomLogger):
super().__init__(*args, **kwargs)
self.logged_standard_logging_payload: Optional[StandardLoggingPayload] = None
self.response_obj: Optional[Union[ModelResponse, TextCompletionResponse, ResponsesAPIResponse]] = None
+ self.logged_kwargs: Optional[dict] = None
+ self.logged = asyncio.Event()
async def async_log_success_event(self, kwargs, response_obj, start_time, end_time):
standard_logging_payload = kwargs.get("standard_logging_object", None)
self.logged_standard_logging_payload = standard_logging_payload
self.response_obj = response_obj
+ self.logged_kwargs = kwargs
+ self.logged.set()
@pytest.mark.usefixtures("_vcr_outcome_gate", "drain_logging_worker", "isolate_litellm_state", "setup_and_teardown")
@@ -1506,6 +1592,141 @@ async def test_redaction_responses_api():
)
[email protected]("drain_logging_worker", "isolate_litellm_state", "setup_and_teardown")
+ "redaction, logged_keys",
+ [
+ ("global", ("instructions", "optional_params", "litellm_params", "standard_logging_object")),
+ ("custom_logger", ("litellm_params", "standard_logging_object")),
+ ],
+)
+async def test_responses_redaction_removes_request_instructions_from_logged_kwargs(
+ redaction: str, logged_keys: tuple[str, ...], monkeypatch: pytest.MonkeyPatch
+) -> None:
+ test_custom_logger: Final = TestCustomLogger(turn_off_message_logging=redaction == "custom_logger")
+ monkeypatch.setattr(litellm, "turn_off_message_logging", redaction == "global")
+ monkeypatch.setattr(litellm, "callbacks", [test_custom_logger])
+ provider_reply: Final = {**mock_responses_api_response("private answer").model_dump(), "instructions": SECRET}
+
+ await litellm.aresponses(
+ model="openai/gpt-5-mini",
+ input="hi",
+ instructions=SECRET,
+ api_key="fake-key",
+ client=AsyncHTTPHandler(
+ transport=httpx.MockTransport(lambda request: httpx.Response(200, json=provider_reply, request=request))
+ ),
+ )
+
+ await asyncio.wait_for(test_custom_logger.logged.wait(), timeout=LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS)
+ kwargs: Final = test_custom_logger.logged_kwargs
+ assert kwargs is not None
+ assert kwargs["standard_logging_object"]["model_parameters"]["instructions"] == "redacted-by-litellm"
+ assert SECRET not in json.dumps({key: kwargs.get(key) for key in logged_keys}, default=str)
+
+
[email protected]("drain_logging_worker", "isolate_litellm_state", "setup_and_teardown")
+async def test_one_callback_opting_out_redacts_instructions_only_for_itself(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ opted_out: Final = TestCustomLogger(message_logging=False)
+ sibling: Final = TestCustomLogger()
+ monkeypatch.setattr(litellm, "callbacks", [opted_out, sibling])
+ provider_reply: Final = {**mock_responses_api_response("private answer").model_dump(), "instructions": SECRET}
+
+ await litellm.aresponses(
+ model="openai/gpt-5-mini",
+ input="hi",
+ instructions=SECRET,
+ api_key="fake-key",
+ client=AsyncHTTPHandler(
+ transport=httpx.MockTransport(lambda request: httpx.Response(200, json=provider_reply, request=request))
+ ),
+ )
+
+ await asyncio.wait_for(
+ asyncio.gather(sibling.logged.wait(), opted_out.logged.wait()), timeout=LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS
+ )
+ assert _logged_instructions(sibling) == (SECRET,) * 6
+ assert _logged_instructions(opted_out) == ("redacted-by-litellm",) * 6
+
+
+class SyncTestCustomLogger(TestCustomLogger):
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.logged_in_thread = threading.Event()
+
+ def log_success_event(self, kwargs, response_obj, start_time, end_time):
+ self.response_obj = response_obj
+ self.logged_kwargs = kwargs
+ self.logged_in_thread.set()
+
+
[email protected]("drain_logging_worker", "isolate_litellm_state", "setup_and_teardown")
+def test_one_callback_opting_out_on_a_sync_call_gets_a_redacted_copy_only_for_itself(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ opted_out: Final = SyncTestCustomLogger(message_logging=False)
+ sibling: Final = SyncTestCustomLogger()
+ monkeypatch.setattr(litellm, "callbacks", [opted_out, sibling])
+ provider_reply: Final = {**mock_responses_api_response("private answer").model_dump(), "instructions": SECRET}
+
+ litellm.responses(
+ model="openai/gpt-5-mini",
+ input="private question",
+ instructions=SECRET,
+ api_key="fake-key",
+ client=HTTPHandler(
+ client=httpx.Client(
+ transport=httpx.MockTransport(lambda request: httpx.Response(200, json=provider_reply, request=request))
+ )
+ ),
+ )
+
+ assert sibling.logged_in_thread.wait(LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS)
+ assert opted_out.logged_in_thread.wait(LOGGING_WORKER_DRAIN_TIMEOUT_SECONDS)
+ assert _logged_instructions(sibling) == (SECRET,) * 6
+ assert _logged_instructions(opted_out) == ("redacted-by-litellm",) * 6
+ assert _logged_question_and_answer(sibling) == (True, True)
+ assert _logged_question_and_answer(opted_out) == (False, False)
+
+
+def _logged_question_and_answer(logger: TestCustomLogger) -> tuple[bool, bool]:
+ kwargs: Final = logger.logged_kwargs
+ assert kwargs is not None
+ assert isinstance(logger.response_obj, ResponsesAPIResponse)
+ request_text: Final = json.dumps([kwargs.get(key) for key in ("messages", "input", "prompt")], default=str)
+ return "private question" in request_text, "private answer" in logger.response_obj.model_dump_json()
+
+
+def _logged_instructions(logger: TestCustomLogger) -> tuple[object, ...]:
+ kwargs: Final = logger.logged_kwargs
+ assert kwargs is not None
+ assert isinstance(logger.response_obj, ResponsesAPIResponse)
+ return (
+ kwargs["instructions"],
+ kwargs["optional_params"]["instructions"],
+ kwargs["litellm_params"]["instructions"],
+ kwargs["standard_logging_object"]["model_parameters"]["instructions"],
+ kwargs["standard_logging_object"]["response"]["instructions"],
+ logger.response_obj.instructions,
+ )
+
+
+def test_request_body_redaction_replaces_instructions_only_when_sent() -> None:
+ responses_body: Final = {"model": "gpt-5-mini", "input": SECRET, "instructions": SECRET}
+ chat_body: Final = {"model": "gpt-5-mini", "messages": [{"role": "user", "content": SECRET}]}
+
+ perform_redaction(responses_body, result=None)
+ perform_redaction(chat_body, result=None)
+
+ assert responses_body["instructions"] == "redacted-by-litellm"
+ assert SECRET not in json.dumps(responses_body)
+ assert "instructions" not in chat_body
+
+
@pytest.mark.usefixtures("_vcr_outcome_gate", "drain_logging_worker", "isolate_litellm_state", "setup_and_teardown")
@pytest.mark.asyncio
async def test_redaction_responses_api_stream():
diff --git a/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py b/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py
index 99cd569eb63..59e29c9b33c 100644
--- a/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py
+++ b/tests/unit/proxy/test_proxy_utils_model_creation_and_error_logging.py
@@ -2084,6 +2084,31 @@ def test_usage_the_stream_already_recovered_beats_an_estimate():
assert lifted == (recovered, 0.25)
+def test_a_failed_request_counts_its_instructions_even_after_logging_redacted_them():
+ from litellm.constants import REDACTED_BY_LITELLM
+ from litellm.proxy.utils import _failure_usage_to_lift
+
+ instructions: Final = "Review every changed line and explain each risk you find. " * 40
+ call: Final[dict[str, object]] = {
+ "call_type": "aresponses",
+ "model": FAILURE_USAGE_MODEL,
+ "messages": ONE_USER_MESSAGE,
+ }
+
+ def estimated_prompt_tokens(dispatched_instructions: str) -> int:
+ lifted: Final = _failure_usage_to_lift(
+ model_call_details={**call, "optional_params": {"instructions": dispatched_instructions}},
+ request_body={"instructions": instructions},
+ dispatched=True,
+ )
+ assert lifted is not None
+ usage: Final = lifted[0]
+ assert isinstance(usage, Usage)
+ return usage.prompt_tokens
+
+ assert estimated_prompt_tokens(REDACTED_BY_LITELLM) == estimated_prompt_tokens(instructions)
+
+
def test_a_timed_out_request_on_an_unmapped_model_keeps_its_row_at_zero_cost():
from litellm.proxy.utils import _failure_usage_to_lift
diff --git a/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py b/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py
index 025f1315aab..94efef050a6 100644
--- a/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py
+++ b/tests/unit/responses/litellm_completion_transformation/test_anthropic_responses_bridge.py
@@ -10,6 +10,7 @@ import respx
from pydantic import BaseModel
import litellm
+from litellm.constants import REDACTED_BY_LITELLM
from litellm.llms.custom_httpx.http_handler import AsyncHTTPHandler
from litellm.responses.litellm_completion_transformation.handler import (
LiteLLMCompletionTransformationHandler,
@@ -138,7 +139,7 @@ class _AnthropicMessage(BaseModel, frozen=True):
class _AnthropicRequest(BaseModel, frozen=True):
messages: tuple[_AnthropicMessage, ...]
- system: tuple[_AnthropicBlock, ...]
+ system: tuple[_AnthropicBlock, ...] = ()
class _RecordingAnthropicMessages:
@@ -309,6 +310,25 @@ async def test_previous_response_id_without_instructions_carries_the_latest_ones
assert [block.text for block in anthropic.request.system] == [expected_system]
+async def test_previous_response_id_does_not_replay_redacted_instructions() -> None:
+ anthropic: Final = _RecordingAnthropicMessages()
+ with patch(
+ "litellm.proxy.proxy_server.prisma_client",
+ _FakePrismaClient([_FIRST_TURN, _second_turn(REDACTED_BY_LITELLM)]),
+ ):
+ await litellm.aresponses(
+ model=_MODEL,
+ previous_response_id="chatcmpl-second-turn",
+ input="What about Osaka?",
+ api_key="sk-ant-fake",
+ client=AsyncHTTPHandler(transport=httpx.MockTransport(anthropic)),
+ )
+
+ assert anthropic.request is not None
+ assert anthropic.request.system == ()
+
+
_SEARCH_CALL: Final = {
"id": "srvtoolu_search",
"type": "function",