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]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
feat(guardrails): count bedrock guardrail cost against spend and budgets
mateo-berribe594f598470
diff --git a/ci_cd/generate_model_prices_schema.py b/ci_cd/generate_model_prices_schema.pyindex 1b60f986ca4..153fbc0fdc2 100644--- a/ci_cd/generate_model_prices_schema.py+++ b/ci_cd/generate_model_prices_schema.py@@ -41,6 +41,11 @@ OBJECT_KEYS: dict[str, JsonSchema] = {},"additionalProperties": False,},+ "guardrail_cost_per_unit": {+ "type": "object",+ "description": "USD cost per billable guardrail unit, keyed by the provider's usage counter name (e.g. Bedrock's contentPolicyUnits).",+ "additionalProperties": NONNEG_NUMBER,+ },"metadata": {"type": "object","description": "Free-form notes about the entry (e.g. pricing derivation).",diff --git a/litellm/__init__.py b/litellm/__init__.pyindex ae0fee11aeb..1ecb04b6e54 100644--- a/litellm/__init__.py+++ b/litellm/__init__.py@@ -792,6 +792,8 @@ def _populate_provider_model_sets(model_cost_map: Dict) -> None:nlp_cloud_models.add(key)elif value.get("litellm_provider") == "aleph_alpha":aleph_alpha_models.add(key)+ elif value.get("litellm_provider") == "bedrock" and value.get("mode") == "guardrail":+ passelif value.get("litellm_provider") == "bedrock" and not is_bedrock_pricing_only_model(key):bedrock_models.add(key)elif value.get("litellm_provider") == "bedrock_converse":diff --git a/litellm/litellm_core_utils/litellm_logging.py b/litellm/litellm_core_utils/litellm_logging.pyindex edb4d56a5b7..10e681b816e 100644--- a/litellm/litellm_core_utils/litellm_logging.py+++ b/litellm/litellm_core_utils/litellm_logging.py@@ -64,6 +64,10 @@ from litellm.integrations.mlflow import MlflowLoggerfrom litellm.integrations.sqs import SQSLoggerfrom litellm.litellm_core_utils.core_helpers import reconstruct_model_namefrom litellm.litellm_core_utils.get_litellm_params import get_litellm_params+from litellm.litellm_core_utils.llm_cost_calc.guardrail_cost import (+ cost_breakdown_with_guardrail,+ guardrail_information_cost,+)from litellm.litellm_core_utils.llm_cost_calc.tool_call_cost_tracking import (StandardBuiltInToolCostTracking,)@@ -5650,12 +5654,14 @@ def get_standard_logging_object_payload(base_model = metadata.get("deployment")custom_pricing: Final = use_custom_pricing_for_model(litellm_params=litellm_params)raw_response_cost: Final = kwargs.get("response_cost")- response_cost: Final[float] = raw_response_cost or 0.0+ llm_response_cost: Final[float] = raw_response_cost or 0.0+ guardrail_cost: Final = guardrail_information_cost(metadata.get("standard_logging_guardrail_information"))+ response_cost: Final[float] = llm_response_cost + guardrail_cost# clean up litellm hidden paramsclean_hidden_params: Final = StandardLoggingPayloadSetup.get_hidden_params(hidden_params)if clean_hidden_params["response_cost"] is None and raw_response_cost is not None:- clean_hidden_params["response_cost"] = response_cost+ clean_hidden_params["response_cost"] = llm_response_costmodel_cost_information: Final = StandardLoggingPayloadSetup.get_model_cost_information(base_model=base_model,@@ -5735,7 +5741,7 @@ def get_standard_logging_object_payload(metadata=clean_metadata,cache_key=clean_hidden_params["cache_key"],response_cost=response_cost,- cost_breakdown=logging_obj.cost_breakdown,+ cost_breakdown=cost_breakdown_with_guardrail(logging_obj.cost_breakdown, guardrail_cost),total_tokens=usage_dict.get("total_tokens", 0),prompt_tokens=usage_dict.get("prompt_tokens", 0),completion_tokens=usage_dict.get("completion_tokens", 0),diff --git a/litellm/litellm_core_utils/llm_cost_calc/guardrail_cost.py b/litellm/litellm_core_utils/llm_cost_calc/guardrail_cost.pynew file mode 100644index 00000000000..dede84c63d1--- /dev/null+++ b/litellm/litellm_core_utils/llm_cost_calc/guardrail_cost.py@@ -0,0 +1,70 @@+from collections.abc import Mapping+from typing import Final++from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError++import litellm+from litellm._logging import verbose_logger+from litellm.types.utils import CostBreakdown++BEDROCK_GUARDRAIL_PRICING_KEY: Final = "bedrock/guardrails"+++class GuardrailPricing(BaseModel):+ model_config = ConfigDict(extra="ignore", frozen=True)++ guardrail_cost_per_unit: Mapping[str, float]+++class GuardrailCostEntry(BaseModel):+ model_config = ConfigDict(extra="ignore", frozen=True)++ guardrail_cost: float | None = None+++GuardrailInformationShape = tuple[GuardrailCostEntry, ...] | GuardrailCostEntry | None++_GUARDRAIL_INFORMATION_ADAPTER: Final[TypeAdapter[GuardrailInformationShape]] = TypeAdapter(GuardrailInformationShape)+++def _bedrock_guardrail_pricing(aws_region_name: str | None) -> GuardrailPricing | None:+ regional_key: Final = f"bedrock/{aws_region_name}/guardrails" if aws_region_name else None+ for key in (regional_key, BEDROCK_GUARDRAIL_PRICING_KEY):+ if key is None or key not in litellm.model_cost:+ continue+ try:+ return GuardrailPricing.model_validate(litellm.model_cost[key])+ except ValidationError as e:+ verbose_logger.warning("Ignoring malformed guardrail pricing entry %s: %s", key, e)+ return None+++def bedrock_guardrail_cost(usage_units: Mapping[str, int], aws_region_name: str | None) -> float:+ pricing: Final = _bedrock_guardrail_pricing(aws_region_name)+ if pricing is None:+ return 0.0+ return sum(units * pricing.guardrail_cost_per_unit.get(counter, 0.0) for counter, units in usage_units.items())+++def guardrail_information_cost(guardrail_information: object) -> float:+ try:+ parsed: Final = _GUARDRAIL_INFORMATION_ADAPTER.validate_python(guardrail_information)+ except ValidationError:+ return 0.0+ if parsed is None:+ return 0.0+ if isinstance(parsed, GuardrailCostEntry):+ return parsed.guardrail_cost or 0.0+ return sum(entry.guardrail_cost or 0.0 for entry in parsed)+++def cost_breakdown_with_guardrail(cost_breakdown: CostBreakdown | None, guardrail_cost: float) -> CostBreakdown | None:+ if guardrail_cost <= 0.0:+ return cost_breakdown+ existing: Final[CostBreakdown] = cost_breakdown if cost_breakdown is not None else CostBreakdown()+ merged: Final[CostBreakdown] = {+ **existing,+ "guardrail_cost": guardrail_cost,+ "total_cost": existing.get("total_cost", 0.0) + guardrail_cost,+ }+ return mergeddiff --git a/litellm/model_prices_and_context_window_backup.json b/litellm/model_prices_and_context_window_backup.jsonindex 78b53cefc53..409022016b0 100644--- a/litellm/model_prices_and_context_window_backup.json+++ b/litellm/model_prices_and_context_window_backup.json@@ -10052,6 +10052,21 @@"output_cost_per_second": 0.0066027,"supports_tool_choice": true},+ "bedrock/guardrails": {+ "guardrail_cost_per_unit": {+ "automatedReasoningPolicyUnits": 0.00017,+ "contentPolicyImageUnits": 0.00075,+ "contentPolicyUnits": 0.00015,+ "contextualGroundingPolicyUnits": 0.0001,+ "sensitiveInformationPolicyFreeUnits": 0.0,+ "sensitiveInformationPolicyUnits": 0.0001,+ "topicPolicyUnits": 0.00015,+ "wordPolicyUnits": 0.0+ },+ "litellm_provider": "bedrock",+ "mode": "guardrail",+ "source": "https://aws.amazon.com/bedrock/pricing/"+ },"bedrock/ap-northeast-1/1-month-commitment/anthropic.claude-instant-v1": {"input_cost_per_second": 0.01475,"litellm_provider": "bedrock",diff --git a/litellm/proxy/common_request_processing.py b/litellm/proxy/common_request_processing.pyindex adae59a1174..0fb66f9381a 100644--- a/litellm/proxy/common_request_processing.py+++ b/litellm/proxy/common_request_processing.py@@ -31,11 +31,13 @@ from litellm.constants import (UNSAFE_PROXY_RESPONSE_HEADERS,)from litellm.integrations.custom_guardrail import CustomGuardrail+from litellm.litellm_core_utils.core_helpers import get_or_create_metadata_bucketfrom litellm.litellm_core_utils.dd_tracing import NullTracer, tracerfrom litellm.litellm_core_utils.get_supported_openai_params import (get_supported_openai_params,)from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj+from litellm.litellm_core_utils.llm_cost_calc.guardrail_cost import guardrail_information_costfrom litellm.litellm_core_utils.llm_response_utils.get_headers import (get_response_headers,)@@ -2197,11 +2199,21 @@ class ProxyBaseLLMRequestProcessing:additional_headers = hidden_params.get("additional_headers", {}) or {}recover_response_cost: Final = not response_cost and hidden_params.get("response_cost") is None- response_cost_for_headers: Final = (+ llm_cost_for_headers: Final = (self._response_cost_from_logging_obj(response=response, logging_obj=logging_obj) or ""if recover_response_costelse response_cost)+ _, request_metadata_bucket = get_or_create_metadata_bucket(self.data)+ guardrail_cost_for_headers: Final = guardrail_information_cost(+ request_metadata_bucket.get("standard_logging_guardrail_information")+ )+ response_cost_for_headers: Final = (+ (llm_cost_for_headers if isinstance(llm_cost_for_headers, (int, float)) else 0.0)+ + guardrail_cost_for_headers+ if guardrail_cost_for_headers > 0+ else llm_cost_for_headers+ )fastapi_response.headers.update(ProxyBaseLLMRequestProcessing.get_custom_headers(diff --git a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.pyindex 93cbb989e23..db9e2586a90 100644--- a/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py+++ b/litellm/proxy/guardrails/guardrail_hooks/bedrock_guardrails.py@@ -31,6 +31,7 @@ from litellm.constants import BEDROCK_APPLY_GUARDRAIL_CHUNK_BUDGET_CHARSfrom litellm.exceptions import ModifyResponseExceptionfrom litellm.integrations.custom_guardrail import CustomGuardrailfrom litellm.litellm_core_utils.core_helpers import redact_nested_match_and_regex_keys+from litellm.litellm_core_utils.llm_cost_calc.guardrail_cost import bedrock_guardrail_costfrom litellm.llms.anthropic.chat.guardrail_translation.handler import AnthropicMessagesHandlerfrom litellm.llms.base_llm.guardrail_translation.utils import (effective_scan_only_tool_results_for_guardrail,@@ -899,6 +900,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):request_data=request_data,event_type=event_type,start_time=start_time,+ aws_region_name=aws_region_name,)return merged_response@@ -1151,6 +1153,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):request_data=request_data,event_type=event_type,start_time=start_time,+ aws_region_name=aws_region_name,)raise self._get_http_exception_for_blocked_guardrail(bedrock_guardrail_response, request_data=request_data@@ -1172,11 +1175,14 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):request_data: dict | None, # mutable-ok: proxy request body dict, mutated by the logging helperevent_type: GuardrailEventHooks,start_time: "datetime",+ aws_region_name: str | None,) -> None:"""Log a single ApplyGuardrail HTTP attempt as-is (its own status,derived from its own response). Used only for the blocked-contentcase, which ends the whole chunking flow immediately."""- tracing_detail: Final = self._build_tracing_detail(BedrockGuardrailResponse(**json_response))+ tracing_detail: Final = self._build_tracing_detail(+ BedrockGuardrailResponse(**json_response), aws_region_name=aws_region_name+ )self.add_standard_logging_guardrail_information_to_request_data(guardrail_provider=self.guardrail_provider,guardrail_json_response=json_response,@@ -1195,6 +1201,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):request_data: dict | None, # mutable-ok: proxy request body dict, mutated by the logging helperevent_type: GuardrailEventHooks,start_time: "datetime",+ aws_region_name: str | None,) -> None:"""Log one logical ApplyGuardrail call -- possibly several chunk callsunder the hood -- using its final merged response, so a chunked@@ -1205,7 +1212,7 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):``Output.__type`` with an exception marker. That marker survives the merge,so the status is derived from the merged response rather than assumed to bea success, which is what the pre-chunking code reported for that shape."""- tracing_detail: Final = self._build_tracing_detail(merged_response)+ tracing_detail: Final = self._build_tracing_detail(merged_response, aws_region_name=aws_region_name)self.add_standard_logging_guardrail_information_to_request_data(guardrail_provider=self.guardrail_provider,guardrail_json_response=dict(merged_response), # mutable-ok: logging helper requires a dict@@ -2036,7 +2043,9 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):return (status_code, err)return (status_code, message)- def _build_tracing_detail(self, response: BedrockGuardrailResponse) -> GuardrailTracingDetail:+ def _build_tracing_detail(+ self, response: BedrockGuardrailResponse, aws_region_name: str | None+ ) -> GuardrailTracingDetail:"""Build the tracing detail from the raw Bedrock response, beforeredaction, so downstream loggers (OTEL, Langfuse, ...) get the@@ -2060,6 +2069,9 @@ class BedrockGuardrail(CustomGuardrail, BaseAWSLLM):}if usage_units:tracing_detail["guardrail_usage"] = usage_units+ tracing_detail["guardrail_cost"] = bedrock_guardrail_cost(+ usage_units=usage_units, aws_region_name=aws_region_name+ )return tracing_detaildef _extract_violation_category_names(self, response: BedrockGuardrailResponse) -> list[str]:diff --git a/litellm/proxy/hooks/proxy_track_cost_callback.py b/litellm/proxy/hooks/proxy_track_cost_callback.pyindex 5dc92d82bda..99d0c94d11b 100644--- a/litellm/proxy/hooks/proxy_track_cost_callback.py+++ b/litellm/proxy/hooks/proxy_track_cost_callback.py@@ -11,6 +11,7 @@ from litellm.litellm_core_utils.core_helpers import (get_litellm_metadata_from_kwargs,)from litellm.litellm_core_utils.litellm_logging import StandardLoggingPayloadSetup+from litellm.litellm_core_utils.llm_cost_calc.guardrail_cost import guardrail_information_costfrom litellm.proxy._types import UserAPIKeyAuthfrom litellm.proxy.auth.auth_checks import (get_key_object,@@ -184,9 +185,14 @@ class _ProxyDBLogger(CustomLogger):# recovered cost onto request_data (the usage rides along in# ``combined_usage_object`` for the token columns), so attribute the# real partial spend to this failure row instead of zero.- recovered_response_cost = 0.0- if isinstance(request_data.get("combined_usage_object"), litellm.Usage):- recovered_response_cost = max(float(request_data.get("response_cost") or 0.0), 0.0)+ recovered_stream_cost: Final = (+ max(float(request_data.get("response_cost") or 0.0), 0.0)+ if isinstance(request_data.get("combined_usage_object"), litellm.Usage)+ else 0.0+ )+ recovered_response_cost: Final = recovered_stream_cost + guardrail_information_cost(+ existing_metadata.get("standard_logging_guardrail_information")+ )await proxy_logging_obj.db_spend_update_writer.update_database(token=user_api_key_dict.api_key,diff --git a/litellm/types/utils.py b/litellm/types/utils.pyindex 13831799c7f..8130ebdfd8d 100644--- a/litellm/types/utils.py+++ b/litellm/types/utils.py@@ -3020,6 +3020,11 @@ class StandardLoggingGuardrailInformation(TypedDict, total=False):provider's counter name (e.g. Bedrock's ``contentPolicyUnits``). Kept as asibling of guardrail_response so spend-log prompt redaction never drops it."""+ guardrail_cost: ReadOnly[float | None]+ """USD cost of this guardrail invocation, priced from ``guardrail_usage`` by the+ provider hook. Summed into the request's ``response_cost`` so it counts against+ spend and budgets like token cost."""+class EvalVerdict(TypedDict, total=False):criterion_name: str@@ -3064,6 +3069,7 @@ class GuardrailTracingDetail(TypedDict, total=False):violation_categories: list[str] | Noneguardrail_action: str | Noneguardrail_usage: ReadOnly[Mapping[str, int] | None]+ guardrail_cost: ReadOnly[float | None]StandardLoggingPayloadStatus = Literal["success", "failure"]@@ -3103,8 +3109,9 @@ class CostBreakdown(TypedDict, total=False):cache_creation_cost: float # Cost of cache-write tokens (premium rate)output_cost: float # Cost of output/completion tokens (includes reasoning if applicable)reasoning_cost: float # Cost of reasoning tokens (subset of output_cost)- total_cost: float # Total cost (input + output + tool usage)+ total_cost: ReadOnly[float] # Total cost (input + output + tool usage + guardrail)tool_usage_cost: float # Cost of usage of built-in tools+ guardrail_cost: ReadOnly[float] # Cost of guardrail invocations billed by the guardrail provideradditional_costs: dict[str, float] # Free-form additional costs (e.g., {"azure_model_router_flat_cost": 0.00014})original_cost: float # Cost before discount (optional)discount_percent: float # Discount percentage applied (e.g., 0.05 = 5%) (optional)diff --git a/model_prices_and_context_window.json b/model_prices_and_context_window.jsonindex 78b53cefc53..409022016b0 100644--- a/model_prices_and_context_window.json+++ b/model_prices_and_context_window.json@@ -10052,6 +10052,21 @@"output_cost_per_second": 0.0066027,"supports_tool_choice": true},+ "bedrock/guardrails": {+ "guardrail_cost_per_unit": {+ "automatedReasoningPolicyUnits": 0.00017,+ "contentPolicyImageUnits": 0.00075,+ "contentPolicyUnits": 0.00015,+ "contextualGroundingPolicyUnits": 0.0001,+ "sensitiveInformationPolicyFreeUnits": 0.0,+ "sensitiveInformationPolicyUnits": 0.0001,+ "topicPolicyUnits": 0.00015,+ "wordPolicyUnits": 0.0+ },+ "litellm_provider": "bedrock",+ "mode": "guardrail",+ "source": "https://aws.amazon.com/bedrock/pricing/"+ },"bedrock/ap-northeast-1/1-month-commitment/anthropic.claude-instant-v1": {"input_cost_per_second": 0.01475,"litellm_provider": "bedrock",diff --git a/model_prices_and_context_window.schema.json b/model_prices_and_context_window.schema.jsonindex 4c54822736c..cd02fde595f 100644--- a/model_prices_and_context_window.schema.json+++ b/model_prices_and_context_window.schema.json@@ -186,6 +186,14 @@"gemini_native_audio": {"type": "boolean"},+ "guardrail_cost_per_unit": {+ "type": "object",+ "description": "USD cost per billable guardrail unit, keyed by the provider's usage counter name (e.g. Bedrock's contentPolicyUnits).",+ "additionalProperties": {+ "type": "number",+ "minimum": 0+ }+ },"input_cost_per_audio_per_second": {"type": "number","minimum": 0@@ -361,6 +369,7 @@"chat","completion","embedding",+ "guardrail","image_edit","image_generation","moderation",diff --git a/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_guardrail_cost.py b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_guardrail_cost.pynew file mode 100644index 00000000000..f9a2a498e38--- /dev/null+++ b/tests/test_litellm/litellm_core_utils/llm_cost_calc/test_guardrail_cost.py@@ -0,0 +1,102 @@+import os++import pytest++import litellm+from litellm.litellm_core_utils.llm_cost_calc.guardrail_cost import (+ bedrock_guardrail_cost,+ cost_breakdown_with_guardrail,+ guardrail_information_cost,+)+++def synthetic_cost_map(monkeypatch):+ monkeypatch.setattr(+ litellm,+ "model_cost",+ {+ "bedrock/guardrails": {+ "guardrail_cost_per_unit": {+ "contentPolicyUnits": 0.00015,+ "topicPolicyUnits": 0.00015,+ "wordPolicyUnits": 0.0,+ }+ },+ "bedrock/eu-west-1/guardrails": {"guardrail_cost_per_unit": {"contentPolicyUnits": 0.0002}},+ "bedrock/us-west-2/guardrails": {"guardrail_cost_per_unit": "malformed"},+ },+ )+++def test_bedrock_guardrail_cost_prices_each_counter(synthetic_cost_map):+ cost = bedrock_guardrail_cost(+ usage_units={"contentPolicyUnits": 2, "topicPolicyUnits": 1, "wordPolicyUnits": 5},+ aws_region_name="us-east-1",+ )+ assert cost == pytest.approx(0.00045)+++def test_bedrock_guardrail_cost_prefers_regional_entry(synthetic_cost_map):+ cost = bedrock_guardrail_cost(usage_units={"contentPolicyUnits": 1}, aws_region_name="eu-west-1")+ assert cost == pytest.approx(0.0002)+++def test_bedrock_guardrail_cost_unknown_counter_is_free(synthetic_cost_map):+ assert bedrock_guardrail_cost(usage_units={"someFutureCounter": 3}, aws_region_name="us-east-1") == 0.0+++def test_bedrock_guardrail_cost_malformed_regional_entry_falls_back(synthetic_cost_map):+ cost = bedrock_guardrail_cost(usage_units={"contentPolicyUnits": 1}, aws_region_name="us-west-2")+ assert cost == pytest.approx(0.00015)+++def test_bedrock_guardrail_cost_no_pricing_entry(monkeypatch):+ monkeypatch.setattr(litellm, "model_cost", {})+ assert bedrock_guardrail_cost(usage_units={"contentPolicyUnits": 1}, aws_region_name="us-east-1") == 0.0+++def test_shipped_bedrock_guardrail_prices_match_aws_pricing_page():+ os.environ["LITELLM_LOCAL_MODEL_COST_MAP"] = "True"+ litellm.model_cost = litellm.get_model_cost_map(url="")+ assert litellm.model_cost["bedrock/guardrails"]["guardrail_cost_per_unit"] == {+ "automatedReasoningPolicyUnits": 0.00017,+ "contentPolicyImageUnits": 0.00075,+ "contentPolicyUnits": 0.00015,+ "contextualGroundingPolicyUnits": 0.0001,+ "sensitiveInformationPolicyFreeUnits": 0.0,+ "sensitiveInformationPolicyUnits": 0.0001,+ "topicPolicyUnits": 0.00015,+ "wordPolicyUnits": 0.0,+ }+ assert "bedrock/guardrails" not in litellm.bedrock_models+++def test_guardrail_information_cost_sums_entries():+ entries = [+ {"guardrail_name": "a", "guardrail_cost": 0.0003},+ {"guardrail_name": "b", "guardrail_cost": None},+ {"guardrail_name": "c"},+ {"guardrail_name": "d", "guardrail_cost": 0.0001},+ ]+ assert guardrail_information_cost(entries) == pytest.approx(0.0004)+++def test_guardrail_information_cost_single_entry_and_garbage():+ assert guardrail_information_cost({"guardrail_cost": 0.0001}) == pytest.approx(0.0001)+ assert guardrail_information_cost(None) == 0.0+ assert guardrail_information_cost("not-guardrail-info") == 0.0+ assert guardrail_information_cost([{"guardrail_cost": "bad"}]) == 0.0+++def test_cost_breakdown_with_guardrail_merges_and_creates():+ assert cost_breakdown_with_guardrail(None, 0.0) is None+ untouched = {"input_cost": 0.1, "total_cost": 0.4}+ assert cost_breakdown_with_guardrail(untouched, 0.0) is untouched+ merged = cost_breakdown_with_guardrail({"input_cost": 0.1, "total_cost": 0.4}, 0.0003)+ assert merged is not None+ assert merged["guardrail_cost"] == pytest.approx(0.0003)+ assert merged["total_cost"] == pytest.approx(0.4003)+ assert merged["input_cost"] == pytest.approx(0.1)+ created = cost_breakdown_with_guardrail(None, 0.0003)+ assert created == {"guardrail_cost": 0.0003, "total_cost": 0.0003}diff --git a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py b/tests/test_litellm/litellm_core_utils/test_litellm_logging.pyindex 946f19b7658..39559b9acdd 100644--- a/tests/test_litellm/litellm_core_utils/test_litellm_logging.py+++ b/tests/test_litellm/litellm_core_utils/test_litellm_logging.py@@ -4826,3 +4826,88 @@ async def test_restore_correlation_context_works_across_asyncio_task_boundary():finally:trace_id_var.set("")session_id_var.set("")+++def _build_success_payload(logging_obj, kwargs):+ import datetime++ from litellm.litellm_core_utils.litellm_logging import (+ get_standard_logging_object_payload,+ )++ now = datetime.datetime.now()+ return get_standard_logging_object_payload(+ kwargs=kwargs,+ init_response_obj={},+ start_time=now,+ end_time=now,+ logging_obj=logging_obj,+ status="success",+ )+++def _guardrail_kwargs(response_cost):+ return {+ "litellm_call_id": "guardrail-cost-call",+ "model": "gpt-4o",+ "messages": [],+ "response_cost": response_cost,+ "litellm_params": {+ "metadata": {+ "standard_logging_guardrail_information": [+ {+ "guardrail_name": "bedrock-pre",+ "guardrail_status": "success",+ "guardrail_usage": {"topicPolicyUnits": 1, "contentPolicyUnits": 1},+ "guardrail_cost": 0.0003,+ },+ {"guardrail_name": "no-usage-guardrail", "guardrail_status": "success"},+ ]+ }+ },+ }+++def test_payload_response_cost_includes_guardrail_cost(logging_obj):+ """LIT-5651: guardrail invocations billed by the provider must count in+ response_cost so spend and budget enforcement see them like token cost."""+ payload = _build_success_payload(logging_obj, _guardrail_kwargs(response_cost=0.0000429))++ assert payload is not None+ assert payload["response_cost"] == pytest.approx(0.0003429)+ assert payload["cost_breakdown"] is not None+ assert payload["cost_breakdown"]["guardrail_cost"] == pytest.approx(0.0003)+ assert payload["cost_breakdown"]["total_cost"] == pytest.approx(0.0003)+ assert payload["hidden_params"]["response_cost"] == pytest.approx(0.0000429)+++def test_payload_guardrail_cost_merges_into_existing_cost_breakdown(logging_obj):+ logging_obj.set_cost_breakdown(+ input_cost=0.00003,+ output_cost=0.0000129,+ total_cost=0.0000429,+ cost_for_built_in_tools_cost_usd_dollar=0.0,+ )+ payload = _build_success_payload(logging_obj, _guardrail_kwargs(response_cost=0.0000429))++ assert payload is not None+ assert payload["response_cost"] == pytest.approx(0.0003429)+ assert payload["cost_breakdown"]["guardrail_cost"] == pytest.approx(0.0003)+ assert payload["cost_breakdown"]["total_cost"] == pytest.approx(0.0003429)+ assert payload["cost_breakdown"]["input_cost"] == pytest.approx(0.00003)+ assert logging_obj.cost_breakdown["total_cost"] == pytest.approx(0.0000429)+++def test_payload_without_guardrail_cost_is_unchanged(logging_obj):+ kwargs = {+ "litellm_call_id": "no-guardrail-call",+ "model": "gpt-4o",+ "messages": [],+ "response_cost": 0.0000429,+ "litellm_params": {"metadata": {}},+ }+ payload = _build_success_payload(logging_obj, kwargs)++ assert payload is not None+ assert payload["response_cost"] == pytest.approx(0.0000429)+ assert payload["cost_breakdown"] is Nonediff --git a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.pyindex 53921e7e74a..bcd0dfc716f 100644--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_bedrock_guardrails.py@@ -5079,24 +5079,43 @@ async def test_apply_guardrail_failure_logs_a_dict_not_a_bare_string():assert "error" in logged-def test_build_tracing_detail_surfaces_usage_counters():- """LIT-5650: the billable usage block Bedrock returns per ApplyGuardrail call must- land on the tracing detail as guardrail_usage so it reaches spend logs as a- sibling of guardrail_response (which default redaction replaces wholesale)."""+def test_build_tracing_detail_surfaces_usage_counters_and_cost(monkeypatch):+ """LIT-5650/LIT-5651: the billable usage block Bedrock returns per ApplyGuardrail+ call must land on the tracing detail as guardrail_usage, priced into+ guardrail_cost, so spend logs and budgets see what AWS bills."""+ monkeypatch.setattr(+ litellm,+ "model_cost",+ {+ "bedrock/guardrails": {+ "guardrail_cost_per_unit": {+ "topicPolicyUnits": 0.00015,+ "contentPolicyUnits": 0.00015,+ "wordPolicyUnits": 0.0,+ }+ }+ },+ )guardrail = BedrockGuardrail(guardrailIdentifier="test-guardrail", guardrailVersion="DRAFT")detail = guardrail._build_tracing_detail({"action": "GUARDRAIL_INTERVENED","usage": {"topicPolicyUnits": 1, "contentPolicyUnits": 2, "wordPolicyUnits": 0, "oddball": "not-an-int"},- }+ },+ aws_region_name="us-east-1",)assert detail["guardrail_usage"] == {"topicPolicyUnits": 1, "contentPolicyUnits": 2, "wordPolicyUnits": 0}+ assert detail["guardrail_cost"] == pytest.approx(0.00045)def test_build_tracing_detail_omits_guardrail_usage_when_bedrock_reports_none():guardrail = BedrockGuardrail(guardrailIdentifier="test-guardrail", guardrailVersion="DRAFT")- assert "guardrail_usage" not in guardrail._build_tracing_detail({"action": "NONE"})- assert "guardrail_usage" not in guardrail._build_tracing_detail({"action": "NONE", "usage": {}})+ for detail in (+ guardrail._build_tracing_detail({"action": "NONE"}, aws_region_name="us-east-1"),+ guardrail._build_tracing_detail({"action": "NONE", "usage": {}}, aws_region_name="us-east-1"),+ ):+ assert "guardrail_usage" not in detail+ assert "guardrail_cost" not in detaildiff --git a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.pyindex bca8210baa6..50c93ed5275 100644--- a/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py+++ b/tests/test_litellm/proxy/hooks/test_proxy_track_cost_callback.py@@ -17,7 +17,7 @@ from litellm.proxy.hooks.proxy_track_cost_callback import (_should_track_cost_callback,_update_database_and_spend_counters,)-from litellm.types.utils import CallTypes+from litellm.types.utils import CallTypes, Usage@pytest.mark.asyncio@@ -152,6 +152,70 @@ async def test_async_post_call_failure_hook_does_not_clobber_guardrail_info_in_massert metadata["standard_logging_guardrail_information"] == metadata_bucket_info+async def test_async_post_call_failure_hook_bills_guardrail_cost_on_blocked_request():+ """LIT-5651: a request blocked by a guardrail never reaches the LLM, but the+ guardrail invocation itself is billed by the provider. The failure row must+ charge that cost against the key instead of recording zero spend."""+ logger = _ProxyDBLogger()+ request_data = {+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "Hello"}],+ "metadata": {+ "standard_logging_guardrail_information": [+ {+ "guardrail_name": "bedrock-guard",+ "guardrail_status": "guardrail_intervened",+ "guardrail_usage": {"topicPolicyUnits": 1, "contentPolicyUnits": 1},+ "guardrail_cost": 0.0003,+ }+ ]+ },+ "proxy_server_request": {"request_id": "test_request_id"},+ }++ with patch(+ "litellm.proxy.db.db_spend_update_writer.DBSpendUpdateWriter.update_database",+ new_callable=AsyncMock,+ ) as mock_update_database:+ await logger.async_post_call_failure_hook(+ request_data=request_data,+ original_exception=Exception("Violated guardrail policy"),+ user_api_key_dict=UserAPIKeyAuth(api_key="test_api_key"),+ )++ assert mock_update_database.call_args[1]["response_cost"] == pytest.approx(0.0003)+++async def test_async_post_call_failure_hook_adds_guardrail_cost_to_recovered_stream_cost():+ logger = _ProxyDBLogger()+ request_data = {+ "model": "gpt-4",+ "messages": [{"role": "user", "content": "Hello"}],+ "metadata": {+ "standard_logging_guardrail_information": [+ {"guardrail_name": "bedrock-guard", "guardrail_status": "success", "guardrail_cost": 0.0003}+ ]+ },+ "proxy_server_request": {"request_id": "test_request_id"},+ "combined_usage_object": Usage(prompt_tokens=10, completion_tokens=5, total_tokens=15),+ "response_cost": 0.001,+ }++ with patch(+ "litellm.proxy.db.db_spend_update_writer.DBSpendUpdateWriter.update_database",+ new_callable=AsyncMock,+ ) as mock_update_database:+ await logger.async_post_call_failure_hook(+ request_data=request_data,+ original_exception=Exception("stream broke mid-flight"),+ user_api_key_dict=UserAPIKeyAuth(api_key="test_api_key"),+ )++ assert mock_update_database.call_args[1]["response_cost"] == pytest.approx(0.0013)++@pytest.mark.asyncioasync def test_async_post_call_failure_hook_non_llm_route():# Setup