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]

Logging: prevent double logging logs when bridge is used (anthropic <-> chat completion OR chat completion <-> responses api) (#11687)

Krish Dholakia07472ce21f67
diff --git a/litellm/completion_extras/litellm_responses_transformation/handler.py b/litellm/completion_extras/litellm_responses_transformation/handler.py
index 76ad6917743..ae73f153f22 100644
--- a/litellm/completion_extras/litellm_responses_transformation/handler.py
+++ b/litellm/completion_extras/litellm_responses_transformation/handler.py
@@ -104,6 +104,7 @@ class ResponsesToCompletionBridgeHandler:
optional_params=optional_params,
litellm_params=litellm_params,
headers=headers,
+ litellm_logging_obj=logging_obj,
)
result = responses(
**request_data,
@@ -160,6 +161,7 @@ class ResponsesToCompletionBridgeHandler:
optional_params=optional_params,
litellm_params=litellm_params,
headers=headers,
+ litellm_logging_obj=logging_obj,
)
result = await aresponses(
**request_data,
diff --git a/litellm/completion_extras/litellm_responses_transformation/transformation.py b/litellm/completion_extras/litellm_responses_transformation/transformation.py
index 7f6d64e0d66..b9ef00b693e 100644
--- a/litellm/completion_extras/litellm_responses_transformation/transformation.py
+++ b/litellm/completion_extras/litellm_responses_transformation/transformation.py
@@ -106,6 +106,7 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
optional_params: dict,
litellm_params: dict,
headers: dict,
+ litellm_logging_obj: "LiteLLMLoggingObj",
) -> dict:
from litellm.types.llms.openai import ResponsesAPIOptionalRequestParams
@@ -162,9 +163,14 @@ class LiteLLMResponsesTransformationHandler(CompletionTransformationBridge):
api_model = model
+ from litellm.types.utils import CallTypes
+
+ setattr(litellm_logging_obj, "call_type", CallTypes.responses.value)
+
request_data = {
"model": api_model,
"input": input_items,
+ "litellm_logging_obj": litellm_logging_obj,
**litellm_params,
}
diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.py
index 4515bbc7fa4..f1d9f1ff1de 100644
--- a/litellm/litellm_core_utils/litellm_logging.py
+++ b/litellm/litellm_core_utils/litellm_logging.py
@@ -1170,6 +1170,21 @@ class Logging(LiteLLMLoggingBaseClass):
) -> Optional[float]:
return self._response_cost_calculator(result=result, cache_hit=cache_hit)
+ def should_run_logging(
+ self,
+ event_type: Literal[
+ "async_success", "sync_success", "async_failure", "sync_failure"
+ ],
+ ) -> bool:
+ try:
+ if self.model_call_details.get(f"has_logged_{event_type}", False) is True:
+ return False
+
+ self.model_call_details[f"has_logged_{event_type}"] = True
+ return True
+ except Exception:
+ return True
+
def should_run_callback(
self, callback: litellm.CALLBACK_TYPES, litellm_params: dict, event_hook: str
) -> bool:
@@ -1365,6 +1380,10 @@ class Logging(LiteLLMLoggingBaseClass):
verbose_logger.debug(
f"Logging Details LiteLLM-Success Call: Cache_hit={cache_hit}"
)
+ if not self.should_run_logging(
+ event_type="sync_success"
+ ): # prevent double logging
+ return
start_time, end_time, result = self._success_handler_helper_fn(
start_time=start_time,
end_time=end_time,
@@ -1841,6 +1860,10 @@ class Logging(LiteLLMLoggingBaseClass):
print_verbose(
"Logging Details LiteLLM-Async Success Call, cache_hit={}".format(cache_hit)
)
+ if not self.should_run_logging(
+ event_type="async_success"
+ ): # prevent double logging
+ return
## CALCULATE COST FOR BATCH JOBS
if self.call_type == CallTypes.aretrieve_batch.value and isinstance(
@@ -2177,6 +2200,10 @@ class Logging(LiteLLMLoggingBaseClass):
verbose_logger.debug(
f"Logging Details LiteLLM-Failure Call: {litellm.failure_callback}"
)
+ if not self.should_run_logging(
+ event_type="sync_failure"
+ ): # prevent double logging
+ return
try:
start_time, end_time = self._failure_handler_helper_fn(
exception=exception,
@@ -2361,6 +2388,10 @@ class Logging(LiteLLMLoggingBaseClass):
Implementing async callbacks, to handle asyncio event loop issues when custom integrations need to use async functions.
"""
await self.special_failure_handlers(exception=exception)
+ if not self.should_run_logging(
+ event_type="async_failure"
+ ): # prevent double logging
+ return
start_time, end_time = self._failure_handler_helper_fn(
exception=exception,
traceback_exception=traceback_exception,
@@ -2612,6 +2643,8 @@ class Logging(LiteLLMLoggingBaseClass):
"""
if self.stream and isinstance(result, ModelResponse):
return result
+ elif isinstance(result, ModelResponse):
+ return result
if "httpx_response" in self.model_call_details:
result = litellm.AnthropicConfig().transform_response(
diff --git a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
index e9d704b0a8a..3c85f5327e8 100644
--- a/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
+++ b/litellm/llms/anthropic/experimental_pass_through/adapters/handler.py
@@ -48,6 +48,9 @@ class LiteLLMMessagesToCompletionTransformationHandler:
extra_kwargs: Optional[Dict[str, Any]] = None,
) -> Dict[str, Any]:
"""Prepare kwargs for litellm.completion/acompletion"""
+ from litellm.litellm_core_utils.litellm_logging import (
+ Logging as LiteLLMLoggingObject,
+ )
request_data = {
"model": model,
@@ -86,9 +89,17 @@ class LiteLLMMessagesToCompletionTransformationHandler:
if stream:
completion_kwargs["stream"] = stream
- excluded_keys = {"litellm_logging_obj", "anthropic_messages"}
+ excluded_keys = {"anthropic_messages"}
extra_kwargs = extra_kwargs or {}
for key, value in extra_kwargs.items():
+ if (
+ key == "litellm_logging_obj"
+ and value is not None
+ and isinstance(value, LiteLLMLoggingObject)
+ ):
+ from litellm.types.utils import CallTypes
+
+ setattr(value, "call_type", CallTypes.completion.value)
if (
key not in excluded_keys
and key not in completion_kwargs
diff --git a/litellm/llms/base_llm/bridges/completion_transformation.py b/litellm/llms/base_llm/bridges/completion_transformation.py
index deadeab6d3c..911f53fb76f 100644
--- a/litellm/llms/base_llm/bridges/completion_transformation.py
+++ b/litellm/llms/base_llm/bridges/completion_transformation.py
@@ -22,6 +22,7 @@ class CompletionTransformationBridge(ABC):
optional_params: dict,
litellm_params: dict,
headers: dict,
+ litellm_logging_obj: "LiteLLMLoggingObj",
) -> dict:
"""Transform /chat/completions api request to another request"""
pass
diff --git a/litellm/responses/main.py b/litellm/responses/main.py
index e1d8b54ef93..8775157ec8b 100644
--- a/litellm/responses/main.py
+++ b/litellm/responses/main.py
@@ -37,6 +37,58 @@ litellm_completion_transformation_handler = LiteLLMCompletionTransformationHandl
#################################################
+def mock_responses_api_response(
+ mock_response: str = "In a peaceful grove beneath a silver moon, a unicorn named Lumina discovered a hidden pool that reflected the stars. As she dipped her horn into the water, the pool began to shimmer, revealing a pathway to a magical realm of endless night skies. Filled with wonder, Lumina whispered a wish for all who dream to find their own hidden magic, and as she glanced back, her hoofprints sparkled like stardust.",
+):
+ return ResponsesAPIResponse(
+ **{ # type: ignore
+ "id": "resp_67ccd2bed1ec8190b14f964abc0542670bb6a6b452d3795b",
+ "object": "response",
+ "created_at": 1741476542,
+ "status": "completed",
+ "error": None,
+ "incomplete_details": None,
+ "instructions": None,
+ "max_output_tokens": None,
+ "model": "gpt-4.1-2025-04-14",
+ "output": [
+ {
+ "type": "message",
+ "id": "msg_67ccd2bf17f0819081ff3bb2cf6508e60bb6a6b452d3795b",
+ "status": "completed",
+ "role": "assistant",
+ "content": [
+ {
+ "type": "output_text",
+ "text": mock_response,
+ "annotations": [],
+ }
+ ],
+ }
+ ],
+ "parallel_tool_calls": True,
+ "previous_response_id": None,
+ "reasoning": {"effort": None, "summary": None},
+ "store": True,
+ "temperature": 1.0,
+ "text": {"format": {"type": "text"}},
+ "tool_choice": "auto",
+ "tools": [],
+ "top_p": 1.0,
+ "truncation": "disabled",
+ "usage": {
+ "input_tokens": 36,
+ "input_tokens_details": {"cached_tokens": 0},
+ "output_tokens": 87,
+ "output_tokens_details": {"reasoning_tokens": 0},
+ "total_tokens": 123,
+ },
+ "user": None,
+ "metadata": {},
+ }
+ )
+
+
@client
async def aresponses(
input: Union[str, ResponseInputParam],
@@ -181,6 +233,14 @@ def responses(
# get llm provider logic
litellm_params = GenericLiteLLMParams(**kwargs)
+ ## MOCK RESPONSE LOGIC
+ if litellm_params.mock_response and isinstance(
+ litellm_params.mock_response, str
+ ):
+ return mock_responses_api_response(
+ mock_response=litellm_params.mock_response
+ )
+
(
model,
custom_llm_provider,
diff --git a/litellm/types/router.py b/litellm/types/router.py
index a8b94c96328..1b8a0944e52 100644
--- a/litellm/types/router.py
+++ b/litellm/types/router.py
@@ -96,18 +96,16 @@ class ModelInfo(BaseModel):
id: Optional[
str
] # Allow id to be optional on input, but it will always be present as a str in the model instance
- db_model: bool = (
- False # used for proxy - to separate models which are stored in the db vs. config.
- )
+ db_model: bool = False # used for proxy - to separate models which are stored in the db vs. config.
updated_at: Optional[datetime.datetime] = None
updated_by: Optional[str] = None
created_at: Optional[datetime.datetime] = None
created_by: Optional[str] = None
- base_model: Optional[str] = (
- None # specify if the base model is azure/gpt-3.5-turbo etc for accurate cost tracking
- )
+ base_model: Optional[
+ str
+ ] = None # specify if the base model is azure/gpt-3.5-turbo etc for accurate cost tracking
tier: Optional[Literal["free", "paid"]] = None
"""
@@ -182,12 +180,12 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):
custom_llm_provider: Optional[str] = None
tpm: Optional[int] = None
rpm: Optional[int] = None
- timeout: Optional[Union[float, str, httpx.Timeout]] = (
- None # if str, pass in as os.environ/
- )
- stream_timeout: Optional[Union[float, str]] = (
- None # timeout when making stream=True calls, if str, pass in as os.environ/
- )
+ timeout: Optional[
+ Union[float, str, httpx.Timeout]
+ ] = None # if str, pass in as os.environ/
+ stream_timeout: Optional[
+ Union[float, str]
+ ] = None # timeout when making stream=True calls, if str, pass in as os.environ/
max_retries: Optional[int] = None
organization: Optional[str] = None # for openai orgs
configurable_clientside_auth_params: CONFIGURABLE_CLIENTSIDE_AUTH_PARAMS = None
@@ -206,6 +204,7 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):
model_config = ConfigDict(extra="allow", arbitrary_types_allowed=True)
merge_reasoning_content_in_choices: Optional[bool] = False
model_info: Optional[Dict] = None
+ mock_response: Optional[Union[str, ModelResponse, Exception, Any]] = None
def __init__(
self,
@@ -250,6 +249,7 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):
# This will merge the reasoning content in the choices
merge_reasoning_content_in_choices: Optional[bool] = False,
model_info: Optional[Dict] = None,
+ mock_response: Optional[Union[str, ModelResponse, Exception, Any]] = None,
**params,
):
args = locals()
@@ -260,9 +260,9 @@ class GenericLiteLLMParams(CredentialLiteLLMParams, CustomPricingLiteLLMParams):
if max_retries is not None and isinstance(max_retries, str):
max_retries = int(max_retries) # cast to int
# We need to keep max_retries in args since it's a parameter of GenericLiteLLMParams
- args["max_retries"] = (
- max_retries # Put max_retries back in args after popping it
- )
+ args[
+ "max_retries"
+ ] = max_retries # Put max_retries back in args after popping it
super().__init__(**args, **params)
def __contains__(self, key):
diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
index f6f6c889178..7744e34117a 100644
--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py
@@ -11,7 +11,8 @@ sys.path.insert(
import time
-from litellm.litellm_core_utils.litellm_logging import Logging as LitellmLogging, set_callbacks
+from litellm.litellm_core_utils.litellm_logging import Logging as LitellmLogging
+from litellm.litellm_core_utils.litellm_logging import set_callbacks
@pytest.fixture
@@ -60,6 +61,8 @@ def test_sentry_sample_rate():
else:
if "SENTRY_API_SAMPLE_RATE" in os.environ:
del os.environ["SENTRY_API_SAMPLE_RATE"]
+
+
def test_use_custom_pricing_for_model():
from litellm.litellm_core_utils.litellm_logging import use_custom_pricing_for_model
@@ -68,3 +71,39 @@ def test_use_custom_pricing_for_model():
"input_cost_per_pixel": 10,
}
assert use_custom_pricing_for_model(litellm_params) == True
+
+
+def test_logging_prevent_double_logging(logging_obj):
+ """
+ When using a bridge, log only once from the underlying bridge call.
+ This is to avoid double logging.
+ """
+ logging_obj.should_run_logging(event_type="sync_success")
+ assert logging_obj.should_run_logging(event_type="sync_success") == False
+ assert logging_obj.should_run_logging(event_type="sync_failure") == True
+ assert logging_obj.should_run_logging(event_type="async_success") == True
+ assert logging_obj.should_run_logging(event_type="async_failure") == True
+
+
+async def test_logging_result_for_bridge_calls(logging_obj):
+ """
+ When using a bridge, log only once from the underlying bridge call.
+ This is to avoid double logging.
+ """
+ import asyncio
+
+ import litellm
+
+ with patch.object(
+ litellm.litellm_core_utils.litellm_logging,
+ "get_standard_logging_object_payload",
+ ) as mock_should_run_logging:
+ await litellm.anthropic_messages(
+ max_tokens=100,
+ messages=[{"role": "user", "content": "Hey"}],
+ model="openai/codex-mini-latest",
+ mock_response="Hello, world!",
+ )
+ await asyncio.sleep(1)
+ assert mock_should_run_logging.call_count == 2 # called twice per call