Este artigo está disponível apenas em inglês.

By UNST33R

Prompt caching for red-team scans: measure the hit rate, then trust the discount

Cached-input pricing decides what repeated probe suites and long recon loops cost on OpenAI-compatible endpoints. How prefix caching bills, how to read cached-token usage in both dialects, a runnable two-call audit, worked cost math at current public prices, and the prefix discipline that keeps acceptance runs cheap without skewing them.

Every scanning workload resends its own prefixes. A garak or PyRIT suite sends the same system prompt and tool schemas under hundreds of probe variants. An agent recon loop resends its whole accumulated context on every turn. Vendors noticed: this week's K3.1 hosting launches put cached-input lines on price cards, with LyberAI correcting its cached rate to $0.40 against $4.00 fresh input within fourteen minutes of posting (launch and correction, covered in our price-war breakdown). The unst33r-deepseek tier publishes $0.03125 cached against $0.15 fresh input.

The discounts are real. Whether your run collects them is a measurement question, and the meter, meaning the usage object on each response, answers it. This tutorial covers how prefix caching bills, how to read the cached-token fields in both OpenAI-compatible dialects, a two-call audit you can run in thirty lines, worked cost math, and the prefix discipline that keeps scan costs down without corrupting the results.

What actually gets the discount

Implementations differ, but the billing model is stable across the providers worth scanning:

  • The discount applies to a prefix, from token zero forward. DeepSeek's context caching hits automatically when a request repeats a previously seen prefix. Anthropic's prompt caching requires explicit cache_control breakpoints on message blocks. One is implicit, one is explicit, and both price the cached span at a fraction of fresh input.
  • Any change at position N invalidates everything from N onward. A one-character edit to the system prompt turns a 12,000-token cached prefix back into 12,000 fresh tokens.
  • Ordering is part of the cache key. System prompt, then tool schemas, then messages. Reordering messages that carry the same content produces a different prefix.
  • TTLs and minimum cacheable lengths are provider policy, not protocol. Eviction windows vary, are documented loosely at best, and can change silently. Trust the meter over the docs.

The stable rule for a scan harness: put everything invariant at the front of the request, everything variable at the back, and never assume a hit.

Read the meter: two dialects

OpenAI-compatible endpoints report cached billing inside the usage object, and two dialects are in the wild:

DialectFieldWhere you see it
OpenAI styleusage.prompt_tokens_details.cached_tokensMost OpenAI-compatible gateways and routers
DeepSeek styleusage.prompt_cache_hit_tokens and usage.prompt_cache_miss_tokensDeepSeek's own API and derivatives

A meter helper that handles both, so the same audit script runs against any endpoint in your fleet:

def cached_report(usage):
    """Return (prompt_tokens, cached_tokens) from either usage dialect."""
    prompt = usage.prompt_tokens
    details = getattr(usage, "prompt_tokens_details", None)
    if details is not None and getattr(details, "cached_tokens", None):
        return prompt, details.cached_tokens
    hit = getattr(usage, "prompt_cache_hit_tokens", None)
    if hit is not None:
        return prompt, hit
    return prompt, 0

The two-call audit

Before trusting any cached-input line on a price card, prove the endpoint reports cache hits on your actual request shape. Send one request twice with identical messages and compare the second response's usage:

import os
from openai import OpenAI

client = OpenAI(
    base_url="https://api.unst33r.si/v1",
    api_key=os.environ["UNST33R_API_KEY"],
)

SYSTEM = "You are a payload-analysis assistant for an authorized engagement. " * 120
messages = [{"role": "system", "content": SYSTEM},
            {"role": "user", "content": "Summarize the metering contract in one line."}]

first = client.chat.completions.create(model="unst33r-deepseek", messages=messages)
second = client.chat.completions.create(model="unst33r-deepseek", messages=messages)

for label, resp in (("first", first), ("second", second)):
    prompt, cached = cached_report(resp.usage)
    print(f"{label}: prompt={prompt} cached={cached} "
          f"hit_rate={cached / prompt:.1%}")

Interpretation rules for the audit:

  • Second call shows a hit rate near the system-prompt share of total prompt tokens. The endpoint caches implicit prefixes and reports them. Your cost model can use the cached rate.
  • Second call reports zero cached tokens. Either the endpoint does not cache this request shape, the cache had already evicted, or the gateway strips the field. All three mean the same thing for budgeting: pay the fresh rate until a support answer or a repeated-run histogram says otherwise.
  • First call also reports cached tokens. Something upstream kept a prefix warm from earlier traffic. Run the audit on a genuinely cold shape before quoting numbers.

The system prompt above is deliberately repetitive so you can watch the hit rate track its share of the prompt. Swap in your real system prompt and tool schemas, because prefix rules interact with tool definitions differently across gateways.

Worked math: one loop, two price cards

A polling recon loop that resends the same 12,000-token context brief for 40 turns, with 200 output tokens per turn, prices out like this:

Cost lineNo cache billedCache billedSaving
Input at unst33r-deepseek rates ($0.15 / $0.03125 per 1M)$0.0720$0.016477%
Output at the same tier ($0.5625 per 1M), 8,000 tokens total$0.0045$0.00450%
Loop total$0.0765$0.020973%
Input at LyberAI K3.1 rates ($4.00 / $0.40 per 1M)$1.9200$0.235288%
Output at the same card ($15.00 per 1M)$0.1200$0.12000%
Loop total$2.0400$0.355283%

Two structural facts fall out of the table. Cache never discounts output tokens, so output-bound workloads gain little: a garak suite with a short shared prefix and five generations per probe is mostly paying for completions, and the lever there is tier selection, not caching. Input-bound workloads, meaning long-context loops and corpus reprocessing, are where the cached line changes decisions. The garak walkthrough and the PyRIT sweep guide both rescan the same corpus across model versions; move those rescans onto a cache-measured footing and the regression-gate cost drops with the input bill.

Prefix discipline for probe suites

The rules that keep a scan cache-friendly, in order of how often teams break them:

  1. Freeze the system prompt byte-for-byte. No timestamps, no request IDs, no per-run nonces in the system block. Variable data belongs in the final user message.
  2. Keep tool schemas stable and ordered. Schema position is prefix position. Adding a tool mid-suite re-prices everything sent before you noticed.
  3. Vary at the tail. A probe suite with 20 attack templates shares one long prefix; each template lands in the last user message. That shape collects hits by construction.
  4. Measure per model. Each model ID is a separate cache namespace. A 90% hit rate on one tier says nothing about another; the multi-tier acceptance guide needs the audit run per tier anyway.
  5. Re-audit after every pricing event. A repriced card, like this week's K3.1 launches, is the trigger to re-run the two-call audit and confirm the cached line still meters the way the card claims.

When to bust the cache on purpose

Cheap prefixes can quietly change what a test measures. Two cases where you should rotate the prefix deliberately:

  • Acceptance and regression runs need one cold pass. If a provider silently shortens its eviction window, what looks like a quality regression may be a cache miss changing your latency profile. A daily cold pass with a rotated leading token separates the two.
  • Prefix-injection testing needs an uncached control. A warm system prompt can make an injected instruction look newly arrived when the serving path has actually seen it before. Rotating the system prompt between adversarial rounds forces the injection surface back to its cold-path behavior, which is the behavior an attacker actually gets.

A thirty-minute checklist

  1. Pin the price card and its timestamp, including any correction tweets, per provider.
  2. Run the two-call audit on your real request shape, per model tier.
  3. Compute the warm and cold totals for your dominant loop with the math above.
  4. Freeze system prompts and tool schemas; move run-specific data to message tails.
  5. Schedule one cold pass per day for anything gating a release.

Cost engineering on the input side is engagement hygiene, the same as evidence handling. The scans still measure refusal behavior, format stability, and tool-call reliability, and every one of them runs inside the engagement's authorization scope. Measure the meter, freeze the prefix, and the discount stops being a marketing line and starts being a number in the report.