Three measured levers for AI agent token spend on a MuleSoft Model Proxy: route the agent through governed metadata instead of context-stuffing (reproducible benchmark harness, with the honest result that governed selection cut prompt tokens 96.9-97.9% with higher F1 but did not clear its preregistered ceiling against a lexical baseline), enable Model Proxy Request Compression correctly (one measured run: 5,812 to 4,045 prompt tokens, -30.4%), and cap tokens per client with llm-token-rate-limit plus a token-to-dollar cost report. Includes gateway sizing for the policy chain. Synthetic data, one frozen configuration, not an ROI claim.
Tags: cross-industry, mulesoft-ai-gateway, model-proxy, llm-proxy, flex-gateway, omni-gateway, api-manager, token-optimization, request-compression, rate-limiting, finops, cost-management, governed-metadata, ai-agents, benchmark
Cutting AI Agent Token Spend: Governed Routes, Request Compression and Token Limits on MuleSoft AI Gateway
Deliverable: A measured, repeatable way to cut and cap what an AI agent spends on tokens: a benchmark harness that compares context-stuffing with governed metadata selection on your own model, Model Proxy Request Compression configured so it actually fires, a per-client llm-token-rate-limit, and a token-to-dollar cost report, all on a gateway sized to carry the policy chain.
Objective: Agent token spend leaks in three places: the agent dumps whole schemas or tool results into the prompt, the same bulky JSON is replayed on every turn, and nothing stops one client from burning the budget. This blueprint treats each as a lever with a measurement: route (send the agent governed metadata, not everything), compress (shrink what is still sent), cap and measure (limit tokens per client, convert usage to dollars). It is a runtime characterization method, not an ROI promise.
What's Getting Built
- Token-bleed benchmark harness (open-source, MIT, Python) — runs the same task over any OpenAI-style endpoint through an ungoverned and a governed route and reports real
usage tokens and F1 · POST {base-url}/chat/completions
- Model Proxy Request Compression (
llm-proxy-request-compression-policy, Model Proxy) — rewrites bulky replayed tool results before the provider bills them · POST {gateway}/{proxy-path}/chat/completions
- Per-client token budget (
llm-token-rate-limit, Model Proxy) — caps tokens per client_id per window, returns 429 and an x-llm-proxy-ratelimit header · POST {gateway}/{proxy-path}/chat/completions
- Cost report (script over the LLM Usage Insights CSV export plus a rate card) — usage to dollars per app and per model
Prerequisites
- An Anypoint organization with Model Proxy available and the
llmProxy entitlement; without it, token metering showed zero usage in one deployment.
- An LLM Model Proxy fronting a provider you control, with
client-id-enforcement so every caller has a client_id. Provider keys stay on the gateway.
- A managed Flex/Omni Gateway sized per step 6. Policy changes are applied through a UI Save and Apply in API Manager.
- Python 3 with
faker, and a model endpoint that accepts OpenAI-style POST /chat/completions and returns a usage block.
- Current per-model prices from your provider or contract.
Choose your path
- Measure first — run the benchmark and read
usage on your real traffic. Skip this and the rest is guesswork.
- Route — pick this when prompts carry catalogs, schemas or long document lists the model must search. It shrinks the prompt most but needs governed metadata to exist.
- Compress — pick this when bulky JSON arrays come back from tools and are replayed in the conversation. It is a gateway policy change with no application change.
- Cap and measure — always; it limits blast radius and gives finance a dollar view, but does not reduce tokens per task.
Architecture
1. Measure your baseline
- Stand up the harness on your own endpoint. It makes live calls and reads the real
usage block; only the data is synthetic.
python3 -m venv .venv && . .venv/bin/activate && pip install faker
export OPENAI_BASE_URL="{base-url}/v1" # OpenAI, Azure OpenAI v1 path, or your gateway
export OPENAI_API_KEY="{api-key-from-secret-store}"
export OPENAI_MODEL="{model}"
python3 token_bleed_benchmark.py --tiers 300 1500 3000 --out report.json
- Do the same for production: read
usage on real agent runs and group by task, not by call; a task that loops five times costs five prompts.
- The models named in this plan (Gemini 2.5 Flash, gpt-4.1-nano, qwen3-coder) are the ones these runs used, not recommendations; run the same steps on your own model.
- Read the reasoning tokens. A Gemini 2.5 Flash run reported 1,619
reasoning_tokens on an ungoverned 300-column prompt, inside total_tokens 5,540 (3,886 prompt, 35 completion). The harness cost field there prices only prompt and completion, so it understates billing for reasoning models. Budget for them; a tight max_completion_tokens truncates answers with finish_reason: length.
2. Route: give the agent governed metadata, not the catalog
- The benchmark holds the model and the task constant and changes only how the agent reaches data. Ungoverned dumps the whole raw column catalog into the prompt. Governed passes only columns a metadata layer classified up front (the stand-in for a governed catalog surfaced to the agent, for example over MCP).
- The task: "Show me all the assets needed to build a report that involves Government ID." The answer key is frozen by seed before any model call; scoring is precision, recall and F1. The data is synthetic (Faker) and reproduces the structure of a published vendor-sponsored governed-metadata benchmark, not its numbers.
- A measured run (Gemini 2.5 Flash class model through a gateway, seed 42):
| Catalog |
Route |
Total tokens |
F1 |
| 300 columns |
context-stuffing |
5,540 |
0.750 |
| 300 columns |
governed |
690 |
0.889 |
| 1,500 columns |
context-stuffing |
22,897 |
0.516 |
| 1,500 columns |
governed |
1,635 |
0.878 |
| 3,000 columns |
context-stuffing |
43,911 |
0.286 |
| 3,000 columns |
governed |
3,040 |
0.898 |
- As the catalog grows, recall of the stuffed prompt collapses while cost climbs; selection fixes both.
- A stricter, preregistered run (R5) used a local
qwen3-coder:30b on an OpenAI-compatible endpoint: 20 fresh seeds, catalog sizes 300, 800 and 1,200, three routes, 540 rows, all passing context preflight. Compact governed selection used 96.9%, 97.8% and 97.9% fewer prompt tokens than full-context stuffing, with mean F1 0.910, 0.896 and 0.893 against 0.466, 0.205 and 0.212. At the 1,200 holdout: 763.5 mean prompt tokens governed, 37,045.6 full-context, 110.0 for a lexical prefilter.
- Honest limit, read this before quoting numbers: governed selection did not clear its preregistered ceiling against the lexical baseline. Governed used 6.94 times the lexical prompt tokens against a frozen maximum of 3.0, so the value claim versus lexical was REJECTED, including with 5% and 10% classifier false negatives. The lexical route scored F1 0.000 on this opaque-column task, so governance wins on quality but not on the preregistered cost test. R5 supports a bounded claim: on one frozen configuration, compact governed metadata beats raw stuffing on cost and quality. It is not a production policy-engine test or an ROI claim. A cheap prefilter may be enough on your schemas; run both on your data.
- For the same rigor, add
--r5 --r2 --tiers 300 800 1200 --seed 102 --replicates 20 --classifier-fn-rates 0 0.05 0.10 --max-completion-tokens 1024 --context-window-tokens {model-context}, with --preflight-only first so oversized prompts fail closed.
3. Compress what is still sent
- Apply Model Proxy Request Compression to the Model Proxy. At defaults it is a no-op, which is the usual reason a first test shows 0%. The four booleans in
configurationData:
{
"compressMessages": false,
"compressToolResults": true,
"enableCleanPayload": true,
"enableToon": true
}
enableToon is off by default and is the lever that matters: it rewrites uniform arrays of flat objects into a compact tabular notation (TOON). compressToolResults is on by default but acts only on role:tool message content, so bulk data must ride in a replayed tool result. The same JSON pasted into a user message was untouched, because compressMessages is off by default.
- Measure with a fixed payload so before and after compare: same request, policy off, then on. One measured run, 60 uniform order records as a replayed
get_orders result on a gpt-4.1-nano deployment:
| Run |
Prompt |
Completion |
Total |
| Policy off |
5,812 |
16 |
5,828 |
Policy on (enableToon) |
4,045 |
17 |
4,062 |
That is 1,767 fewer prompt tokens, -30.4%, on one payload; your data will differ, and heterogeneous or free-text content should compress less (advice).
- In that run an API PATCH of
configurationData reached the gateway in about 45 seconds. Do not rely on it; confirm by the token drop.
4. Cap tokens per client
- Apply
llm-token-rate-limit to the Model Proxy. Keys: maximumTokens, timePeriodInMilliseconds (minimum 1000) and keySelector.
{
"maximumTokens": 1000000,
"timePeriodInMilliseconds": 60000,
"keySelector": "#[attributes.headers['client_id']]"
}
- Use the
client_id header selector. #[attributes.principal] evaluated to null on these proxies and the gateway returned 400 "Failed to evaluate keySelector".
- Advice: set
maximumTokens from step 1 data, the most a healthy client uses in a window plus reasoning-token headroom. Start high, watch the header, then lower per client tier.
- Enforce with a UI Save and Apply in API Manager; an API PATCH registered the configuration but did not reliably push it. No
x-llm-proxy-ratelimit header on a normal response means it is not enforcing.
- Chain order on a working proxy:
client-id-enforcement, llm-token-rate-limit, cors, header transformation, llm-proxy-core, model-based-routing, provider transcoding. Authentication runs first so the limiter keys on a verified client_id; llm-proxy-core attributes usage to it.
5. Turn tokens into dollars
- In API Manager open LLM Usage Insights for the proxy, choose the month and export as CSV. Keep a rate card in dollars per 1,000,000 tokens, keyed
provider/model:
{ "currency": "USD", "prices": { "azureopenai/gpt-4.1-nano": { "input": 0.1, "output": 0.4 } } }
- Cost per call is
prompt / 1e6 * input + completion / 1e6 * output. Apply it per application (chargeback) and per model. Unpriced rows must be listed, never counted as zero.
- At those example rates the step 3 run costs 0.000588 dollars per call before and 0.000411 after. Replace the rates with your contract prices.
- Convert to cost per task: tokens per task from step 1 times your rate card. That is the number the success metrics track.
6. Size the gateway for the chain
- Every distinct policy adds memory at config load. In one managed deployment a SMALL gateway serving 35 API instances at about nine policies each went into a silent crash-loop (no error, panic or OOM line in customer logs) after model-based routing was added to an LLM connection. Resizing to LARGE fixed it and it stayed stable.
- Reported mechanism (not verified here): the gateway agent compiles each policy module at startup, so memory grows with distinct policies. The guidance given was to deploy LLM proxies on LARGE gateways.
- Published capacity: SMALL up to 50 APIs at 50 TPS without autoscaling; LARGE up to 500 APIs at 1,500 TPS with CPU autoscaling.
- Advice: do not co-locate a long LLM policy chain with dozens of other instances on SMALL; add policies one at a time and watch restarts.
7. Security and compliance
- The limiter and the cost report depend on a verified
client_id; enforce it first, and keep provider keys on the gateway so no application holds them.
- Compression rewrites the request body before it leaves your boundary; confirm it preserves your fields, and skip it if policy forbids transformation.
- Do not log prompts or tool results to measure savings; token counts and client identifiers are enough. Keep the benchmark on synthetic data.
Sample payload — compressed request, token usage and a throttled call
A request where the bulky array rides in a role:tool message (record list shortened):
{
"model": "azureopenai/gpt-4.1-nano",
"max_completion_tokens": 60,
"messages": [
{"role": "system", "content": "Use ONLY the tool results provided. Be concise."},
{"role": "user", "content": "How many total cases are on CONFIRMED orders for {warehouse}?"},
{"role": "assistant", "content": null, "tool_calls": [{"id": "call_get_orders_1", "type": "function",
"function": {"name": "get_orders", "arguments": "{\"warehouse\":\"{warehouse}\"}"}}]},
{"role": "tool", "tool_call_id": "call_get_orders_1", "name": "get_orders",
"content": "[{\"order_id\":\"SO-100000\",\"sku\":\"{sku}\",\"qty\":24,\"status\":\"CONFIRMED\"}, ...60 records]"},
{"role": "user", "content": "Based only on that tool result, reply in one sentence with the total confirmed cases."}
]
}
Headers on every call: client_id: {client-id} and client_secret: {client-secret}. Response usage with the policy on: {"prompt_tokens":4045,"completion_tokens":17,"total_tokens":4062}; with it off: 5812, 16, 5828.
A normal call carries the budget header; once the window is spent the gateway returns HTTP 429 with the same header:
HTTP/1.1 429
x-llm-proxy-ratelimit: Token rate limit: {n} tokens remaining of {limit}. Reset in {ms}
The 429 body was not captured; code to the status and header.
Cost report shape (per application, per model, grand total):
=== Cost by Application (chargeback view) ===
key prompt completion cost
{app-name} {n} {n} ${0.0000}
TOTAL COST : ${0.0000} (USD)
!! UNPRICED (NOT in the total): {provider}/{model}
Deterministic checks
- The harness answer key is frozen by seed before any model call; the same seed gives the same key.
- The fixed payload reports 5,812 prompt tokens with compression off and a lower count with
enableToon on and the array in a role:tool message. The same array in a user message reports no drop.
- A request with a missing or invalid
client_id is rejected (401) before the limiter or provider.
- A normal response carries
x-llm-proxy-ratelimit; when the budget is spent the call returns 429 and nothing reaches the provider. An absent header means the policy is not applied.
- The cost report lists any
provider/model with no price as unpriced and excludes it from the total; it never reports it as zero.
- Benchmark preflight fails closed: a prompt that exceeds the declared context window or completion cap is refused before any call.
Testing and validation
- Happy path: run the benchmark, the fixed payload off and on, then drive one client past a low budget and confirm the
429.
- Edge case that breaks a naive test: a compression test shows 0% when the data is in a user message or TOON is off, and an unapplied limiter never returns
429.
- Quality held: compare answers or F1 with each lever on and off; a cut that lowers accuracy is a regression.
- Context overflow: if the stuffed prompt exceeds the context window the correct outcome is a refusal; one round of the study recorded exactly that as inconclusive.
Phased rollout
Phase 1 — Connect
- Run the benchmark, put
client-id-enforcement and llm-proxy-core on a Model Proxy on a LARGE gateway, and confirm Usage Insights shows per-client tokens.
Phase 2 — Map and validate
- Add compression and test a fixed payload. Add the token limit high, watch the header, then lower. Build the rate card and first cost report.
Phase 3 — Production
- Lower limits per client tier, alert on
429 rate and gateway restarts, review the cost report monthly, and re-run the benchmark when the model or catalog changes.
Success metrics
- Tokens per task (prompt and total, including reasoning tokens) before and after each lever.
- Accuracy or F1 held at or above baseline on the same tasks.
- Dollars per task from the cost report, by application and model.
- Share of calls throttled with
429; gateway restarts after each policy added (target zero).
Troubleshooting
- Compression shows 0% drop — Likely cause:
enableToon is off, or the bulk data sits in a user message with compressMessages off. Fix: enable TOON and replay the data as a role:tool message.
- Token limit never returns 429 — Likely cause: configuration registered by API but not pushed. Fix: UI Save and Apply, then check for
x-llm-proxy-ratelimit.
- 400 "Failed to evaluate keySelector" — Likely cause:
#[attributes.principal] is null. Fix: #[attributes.headers['client_id']].
- Gateway restarts silently after adding a routing policy — Likely cause: SMALL gateway memory with many policies. Fix: resize to LARGE and add policies one at a time.
- Model not found or wrong route — Likely cause: model-name format. A single-route proxy wants the bare name (
gemini-2.5-flash); a multi-route model-based proxy wants provider/model (azureopenai/gpt-4o-mini).
- Azure upstream rejects the gateway's auth — Likely cause: the OpenAI provider sends
Authorization: Bearer, which the classic Azure path rejects. Fix: use the Azure /openai/v1 path.
- No tokens in Usage Insights — Likely cause: missing
llmProxy entitlement or no llm-proxy-core. Fix: enable it and keep the policy in the chain.