Skip to content

fix: report real token usage on guardrail-blocked /v1/responses replies - #36907

Merged
mateo-berri merged 3 commits into
BerriAI:litellm_internal_stagingfrom
guptaishaan:fix/issue-36880-8933
Aug 15, 2026
Merged

mateo-berri merged 3 commits into
BerriAI:litellm_internal_stagingfrom
guptaishaan:fix/issue-36880-8933

Conversation

@guptaishaan

@guptaishaan guptaishaan commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

TLDR

Problem this solves:

  • Guardrail-blocked /v1/responses replies always reported zero token usage
  • The upstream LLM call had already consumed real tokens
  • /v1/chat/completions and /v1/messages already report real counts on blocks

How it solves it:

  • Shared blocked-usage helper now builds the /v1/responses usage object
  • Lives next to the existing /v1/messages helper in guardrail_translation utils
  • Maps bridged chat prompt/completion tokens to input/output tokens
  • Post-call guardrails can attach the blocked response via raise_passthrough_exception
  • Pre-call blocks still report zeros since no upstream call was made

User Flow

Before: a developer whose app tracks per-request token spend from response bodies gets zeros for every guardrail-blocked Responses API call

  1. They send POST https://litellm-domain/v1/responses with {"model": "gpt-4o-mini", "input": "..."} and the reply trips a post-call guardrail
  2. They receive a 200 whose usage reads "input_tokens": 0, "output_tokens": 0, "total_tokens": 0
  3. Their cost dashboard records that request at zero spend despite a real upstream call

After: the same blocked call reports the real token counts

  1. They send the same POST https://litellm-domain/v1/responses and the reply trips the same post-call guardrail
  2. They receive a 200 whose usage now carries the real counts, e.g. "input_tokens": 12, "output_tokens": 8, "total_tokens": 20
  3. Their cost dashboard records the request at its real token consumption

Relevant issues

Fixes #36880

Linear ticket

Resolves LIT-5615

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Live proxy, real OpenAI and Anthropic calls, no mocks. Both legs boot the same config: a post_call custom guardrail that is default_on and raises ModifyResponseException with the blocked response attached, one native model (openai/gpt-4o-mini) and one chat-bridged model (anthropic/claude-haiku-4-5). Before runs at the merge base 2d3c3e3098, after at this PR's head e06e2e6c12. Every call returns 200 carrying the guardrail's blocked message instead of a model reply; only the reported usage differs

Route Model Before 2d3c3e3098 After e06e2e6c12
/v1/responses gpt-4o-mini 0 / 0 / 0 12 / 8 / 20
/v1/responses claude-haiku-4-5 0 / 0 / 0 12 / 10 / 22
/v1/messages claude-haiku-4-5 12 in, 10 out 12 in, 10 out
/v1/chat/completions gpt-4o-mini 12 / 7 / 19 12 / 7 / 19
Repro setup (config.yaml and the guardrail module)
model_list:
  - model_name: gpt-4o-mini
    litellm_params:
      model: openai/gpt-4o-mini
      api_key: os.environ/OPENAI_API_KEY
  - model_name: claude-haiku-4-5
    litellm_params:
      model: anthropic/claude-haiku-4-5
      api_key: os.environ/ANTHROPIC_API_KEY

guardrails:
  - guardrail_name: zero-usage-repro
    litellm_params:
      guardrail: c17_zero_usage_guardrail.ZeroUsageReproGuardrail
      mode: post_call
      default_on: true

general_settings:
  master_key: sk-1234

litellm_settings:
  drop_params: true
from litellm.exceptions import ModifyResponseException
from litellm.integrations.custom_guardrail import CustomGuardrail
from litellm.proxy._types import UserAPIKeyAuth


class ZeroUsageReproGuardrail(CustomGuardrail):
    async def async_post_call_success_hook(
        self,
        data: dict,
        user_api_key_dict: UserAPIKeyAuth,
        response,
    ):
        raise ModifyResponseException(
            message="Content flagged by policy, response withheld",
            model=data.get("model", "unknown") or "unknown",
            request_data=data,
            guardrail_name=self.guardrail_name or "zero-usage-repro",
            original_response=response,
        )
Before at 2d3c3e3: /v1/responses reports zeros, control endpoints report real usage
curl -sS http://localhost:47913/v1/responses -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o-mini", "input": "Say hello in five words"}' | python3 -m json.tool
{
    "id": "resp_2fe68d15-194c-4129-ada8-8fe5b75adb0e",
    "model": "gpt-4o-mini",
    "object": "response",
    "output": [
        {
            "content": [
                {
                    "type": "text",
                    "text": "Content flagged by policy, response withheld"
                }
            ]
        }
    ],
    "status": "completed",
    "usage": {
        "input_tokens": 0,
        "input_tokens_details": null,
        "output_tokens": 0,
        "output_tokens_details": null,
        "total_tokens": 0,
        "cost": null
    }
}
curl -sS http://localhost:47913/v1/responses -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model": "claude-haiku-4-5", "input": "Say hello in five words"}' | python3 -m json.tool
{
    "id": "resp_2d97f82d-b77e-44a8-a945-894a7cf3b996",
    "model": "claude-haiku-4-5",
    "object": "response",
    "output": [
        {
            "content": [
                {
                    "type": "text",
                    "text": "Content flagged by policy, response withheld"
                }
            ]
        }
    ],
    "status": "completed",
    "usage": {
        "input_tokens": 0,
        "input_tokens_details": null,
        "output_tokens": 0,
        "output_tokens_details": null,
        "total_tokens": 0,
        "cost": null
    }
}
curl -sS http://localhost:47913/v1/messages -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model": "claude-haiku-4-5", "max_tokens": 64, "messages": [{"role": "user", "content": "Say hello in five words"}]}' | python3 -m json.tool
{
    "id": "msg_28dd94f4-8df5-497c-9e1d-441b31cab61d",
    "type": "message",
    "role": "assistant",
    "content": [
        {
            "type": "text",
            "text": "Content flagged by policy, response withheld"
        }
    ],
    "model": "claude-haiku-4-5",
    "stop_reason": "end_turn",
    "usage": {
        "input_tokens": 12,
        "output_tokens": 10
    }
}
curl -sS http://localhost:47913/v1/chat/completions -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Say hello in five words"}]}' | python3 -m json.tool
{
    "id": "chatcmpl-b4f56270-ae32-49ac-a178-ad36c2910279",
    "model": "gpt-4o-mini",
    "object": "chat.completion",
    "choices": [
        {
            "finish_reason": "content_filter",
            "index": 0,
            "message": {
                "content": "Content flagged by policy, response withheld",
                "role": "assistant"
            }
        }
    ],
    "usage": {
        "completion_tokens": 7,
        "prompt_tokens": 12,
        "total_tokens": 19
    }
}
After at e06e2e6: /v1/responses reports real usage for native and bridged models, control endpoints unchanged
curl -sS -X POST http://localhost:52741/v1/responses -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o-mini", "input": "Say hello in five words"}' | python3 -m json.tool
{
    "id": "resp_830b71b5-2aa2-4d48-bbf5-cd5913cc3f24",
    "model": "gpt-4o-mini",
    "object": "response",
    "output": [
        {
            "content": [
                {
                    "type": "text",
                    "text": "Content flagged by policy, response withheld"
                }
            ]
        }
    ],
    "status": "completed",
    "usage": {
        "input_tokens": 12,
        "input_tokens_details": {
            "audio_tokens": null,
            "cached_tokens": 0,
            "text_tokens": null,
            "cache_write_tokens": 0
        },
        "output_tokens": 8,
        "output_tokens_details": {
            "reasoning_tokens": 0,
            "text_tokens": null
        },
        "total_tokens": 20,
        "cost": null
    }
}
curl -sS -X POST http://localhost:52741/v1/responses -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model": "claude-haiku-4-5", "input": "Say hello in five words"}' | python3 -m json.tool
{
    "id": "resp_9d500821-ad5b-4b88-9afc-fbf0f7ccd788",
    "model": "claude-haiku-4-5",
    "object": "response",
    "output": [
        {
            "content": [
                {
                    "type": "text",
                    "text": "Content flagged by policy, response withheld"
                }
            ]
        }
    ],
    "status": "completed",
    "usage": {
        "input_tokens": 12,
        "input_tokens_details": {
            "audio_tokens": null,
            "cached_tokens": 0,
            "text_tokens": 12,
            "cache_write_tokens": 0
        },
        "output_tokens": 10,
        "output_tokens_details": {
            "reasoning_tokens": 0,
            "text_tokens": 10
        },
        "total_tokens": 22,
        "cost": null
    }
}
curl -sS -X POST http://localhost:52741/v1/messages -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model": "claude-haiku-4-5", "max_tokens": 64, "messages": [{"role": "user", "content": "Say hello in five words"}]}' | python3 -m json.tool
{
    "id": "msg_cf458d37-a442-4fdd-aff4-c0eb0ca838a8",
    "type": "message",
    "role": "assistant",
    "content": [
        {
            "type": "text",
            "text": "Content flagged by policy, response withheld"
        }
    ],
    "model": "claude-haiku-4-5",
    "stop_reason": "end_turn",
    "usage": {
        "input_tokens": 12,
        "output_tokens": 10
    }
}
curl -sS -X POST http://localhost:52741/v1/chat/completions -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Say hello in five words"}]}' | python3 -m json.tool
{
    "id": "chatcmpl-c8946773-1cc4-41ad-9403-89559d582194",
    "model": "gpt-4o-mini",
    "object": "chat.completion",
    "choices": [
        {
            "finish_reason": "content_filter",
            "index": 0,
            "message": {
                "content": "Content flagged by policy, response withheld",
                "role": "assistant"
            }
        }
    ],
    "usage": {
        "completion_tokens": 7,
        "prompt_tokens": 12,
        "total_tokens": 19
    }
}

Observations from the QA run, all pre-existing behaviors this PR leaves alone:

  • Blocked /v1/responses replies report usage.cost null
  • Blocked /v1/responses output items lack type, role, id, status
  • Blocked replies say status completed, not a refusal signal
  • Only /v1/chat/completions flags blocks via finish_reason content_filter

Type

🐛 Bug Fix

Caveats (if any)

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

## TLDR

Signed-off-by: Ishaan <ishaangupta0408@gmail.com>
@CLAassistant

CLAassistant commented Aug 14, 2026 •

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you all sign our Contributor License Agreement before we can accept your contribution.
1 out of 2 committers have signed the CLA.

✅ mateo-berri
❌ guptaishaan
You have signed the CLA already but the status is still pending? Let us recheck it.

@greptile-apps

greptile-apps Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

The PR propagates upstream token usage into synthetic guardrail-blocked Responses API replies while preserving zero usage for pre-call blocks.

  • Adds a shared Responses API usage conversion helper for native and bridged chat responses.
  • Passes the original post-call response through the guardrail exception path.
  • Replaces hardcoded endpoint usage and adds serialized endpoint regression coverage.

Confidence Score: 5/5

The PR appears safe to merge.

No blocking failure remains.

Important Files Changed

Filename Overview
litellm/integrations/custom_guardrail.py Extends the passthrough exception helper to carry the blocked upstream response.
litellm/llms/base_llm/guardrail_translation/utils.py Centralizes blocked-response usage extraction and adds Responses API token-shape conversion.
litellm/proxy/response_api_endpoints/endpoints.py Uses original response usage when serializing guardrail-blocked Responses API replies.
tests/test_litellm/proxy/response_api_endpoints/test_endpoints.py Exercises native, bridged-chat, and pre-call usage through the serialized endpoint response.
tests/test_litellm/proxy/test_blocked_response_usage.py Adds focused coverage for usage conversion and propagation through the passthrough exception helper.

Reviews (2): Last reviewed commit: "Merge remote-tracking branch 'origin/lit..." | Re-trigger Greptile

@codecov

codecov Bot commented Aug 14, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@codspeed

codspeed Bot commented Aug 14, 2026 •

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing guptaishaan:fix/issue-36880-8933 (e06e2e6) with litellm_internal_staging (29fe342)1

Open in CodSpeed

Footnotes

  1. No successful run was found on litellm_internal_staging (f99d0a4) during the generation of this report, so 29fe342 was used instead as the comparison base. There might be some changes unrelated to this pull request in this report. ↩

Move the blocked-usage mapping for /v1/responses next to
blocked_response_usage in guardrail_translation utils, map bridged chat
prompt/completion tokens to Responses API input/output tokens, and let
raise_passthrough_exception attach the blocked response so post-call
guardrail blocks report real usage
@mateo-berri

Copy link
Copy Markdown
Contributor

@greptileai

@mateo-berri

Copy link
Copy Markdown
Contributor

bugbot run

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ Bugbot reviewed your changes and found no new issues!

Comment @cursor review or bugbot run to trigger another review on this PR

Reviewed by Cursor Bugbot for commit e06e2e6. Configure here.

@mateo-berri

mateo-berri commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

The added tests execute every new helper line in CI's unit suite; the low codecov patch number reflects coverage upload wiring, not missing tests

@mateo-berri mateo-berri left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: /v1/responses guardrail-blocked replies report zero token usage despite real upstream consumption

3 participants