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]

Merge pull request #34578 from BerriAI/litellm_headroom_tokens_saved

tin-berri2d6b57407da7
diff --cc tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
index 776df985d46,85f04d82360..4dc527ca45d
--- a/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
+++ b/tests/test_litellm/proxy/guardrails/guardrail_hooks/test_headroom.py
@@@ -157,14 -144,114 +163,121 @@@ async def test_apply_guardrail_compress
assert result.get("structured_messages") == COMPRESSED_MESSAGES
+ entries = _recorded_guardrail_entries(request_data)
+ assert len(entries) == 1
+ assert entries[0]["guardrail_name"] == "headroom"
+ assert entries[0]["guardrail_status"] == "success"
+ assert entries[0]["guardrail_provider"] == "headroom"
+ assert "headroom" in _applied_guardrails(request_data)
+
+ def _recorded_guardrail_response(request_data: dict) -> dict:
+ entries = request_data["metadata"]["standard_logging_guardrail_information"]
+ assert len(entries) == 1
+ return entries[0]["guardrail_response"]
+
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_derives_tokens_saved_when_service_omits_it(
+ guardrail: HeadroomGuardrail,
+ ):
+ inputs = GenericGuardrailAPIInputs(
+ texts=["A" * 5000],
+ structured_messages=ORIGINAL_MESSAGES,
+ )
+ # _make_compress_response omits tokens_saved, matching the live service.
+ mock_response = _make_compress_response(COMPRESSED_MESSAGES)
+ request_data: dict = {"model": "gpt-4o"}
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ return_value=mock_response,
+ ):
+ await guardrail.apply_guardrail(
+ inputs=inputs,
+ request_data=request_data,
+ input_type="request",
+ )
+
+ stats = _recorded_guardrail_response(request_data)
+ assert stats["tokens_saved"] == 900
+
+ # Spend tracking reads the entry under the spend-log metadata key.
+ entry = request_data["metadata"]["standard_logging_guardrail_information"][0]
+ assert extract_compression_saved_tokens({"guardrail_information": [entry]}) == 900
+
+
+ @pytest.mark.asyncio
+ async def test_apply_guardrail_passes_through_service_sent_tokens_saved(
+ guardrail: HeadroomGuardrail,
+ ):
+ inputs = GenericGuardrailAPIInputs(
+ texts=["A" * 5000],
+ structured_messages=ORIGINAL_MESSAGES,
+ )
+ mock_response = _make_compress_response(COMPRESSED_MESSAGES)
+ # Deliberately different from tokens_before - tokens_after (900): the
+ # service-sent value must win over the derived one.
+ mock_response.json.return_value["tokens_saved"] = 123
+ request_data: dict = {"model": "gpt-4o"}
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ return_value=mock_response,
+ ):
+ await guardrail.apply_guardrail(
+ inputs=inputs,
+ request_data=request_data,
+ input_type="request",
+ )
+
+ assert _recorded_guardrail_response(request_data)["tokens_saved"] == 123
+
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ "tokens_before, tokens_after",
+ [
+ ("1000", "100"),
+ (True, False),
+ (None, None),
+ ],
+ )
+ async def test_apply_guardrail_skips_derivation_for_non_numeric_token_counts(
+ guardrail: HeadroomGuardrail,
+ tokens_before,
+ tokens_after,
+ ):
+ inputs = GenericGuardrailAPIInputs(
+ texts=["A" * 5000],
+ structured_messages=ORIGINAL_MESSAGES,
+ )
+ mock_response = _make_compress_response(COMPRESSED_MESSAGES)
+ mock_response.json.return_value["tokens_before"] = tokens_before
+ mock_response.json.return_value["tokens_after"] = tokens_after
+ request_data: dict = {"model": "gpt-4o"}
+
+ with patch.object(
+ guardrail.async_handler,
+ "post",
+ new_callable=AsyncMock,
+ return_value=mock_response,
+ ):
+ result = await guardrail.apply_guardrail(
+ inputs=inputs,
+ request_data=request_data,
+ input_type="request",
+ )
+
+ assert "tokens_saved" not in _recorded_guardrail_response(request_data)
+ # Compression itself is unaffected by the skipped derivation.
+ assert result.get("structured_messages") == COMPRESSED_MESSAGES
+
+
@pytest.mark.asyncio
async def test_apply_guardrail_injects_retrieve_tool_when_hashes_present(
guardrail: HeadroomGuardrail,