Paying for Fewer Tokens Without Getting Worse Answers
Every tool on this site sends long prompts to a language model: retrieved documents, tool outputs, conversation
history. At the scale of a large manufacturer, those tokens become a real line in the cloud bill and a visible
wait for the user. This toolkit is middleware between the applications and the model endpoints. It counts and
budgets tokens, prunes and compresses context, answers repeated questions from a cache, and sends each request to
the cheapest model that can handle it. A change ships only if each tool’s own quality gates still pass.
ContextUniversity of Skövde · AI-COMPETE (Vinnova) & SMART (KK-stiftelsen) · 2025 · system design
ResultSystem design — techniques, safety rules for each one, and a replay-based evaluation. No savings figures are claimed yet.
What this page is. A system design for the shared model layer behind the AI-COMPETE and SMART
tools. It is not a report of a deployment at any partner. Figures marked target are release gates. They
are not measured results.
Problem formulation
Most of the tokens in a long prompt are not doing any work
Cost, latency and context overflow all come from the same place: the prompt.
A plant-knowledge answer carries eight retrieved chunks. A data-agent step carries a schema and a result table.
A copilot session drags weeks of history. Much of that is repeated, irrelevant or verbose. The model reads all of
it, charges for all of it, and takes longer to answer because of it. When a conversation finally exceeds the
context window, the application fails at the worst moment.
Cost. Input tokens dominate the bill in retrieval-heavy tools, and a large model is often used
for questions a small one answers equally well.
Latency. Time to first token grows with prompt length. Users feel it on every turn.
Blowouts. Long sessions and large tool outputs overflow the context window, and naive
truncation silently drops the instructions or the evidence.
The constraint that shapes everything below: an optimisation that makes answers worse is not a saving.
Every technique is measured against the quality gates the tools already have.
Architecture · middleware
Five stages between the application and the model
Each stage can be switched on per tool, and each is traced.
The two dashed shortcuts are where the money is: requests that skip the model, and requests that never need the large one.
Technique 1 · token budgeting & context pruning
Decide what the prompt is for, then fit it
A budget, not truncation. Pruning ranks the content; it does not cut from the end.
Count exactly. Every segment of the prompt is counted with the model’s own tokenizer
(tiktoken, Rust core, microseconds per call). The count is compared with a per-tool budget that reserves room for
the answer.
Protect what must survive. System rules, the user’s question, safety procedures, citation
IDs and numbers produced by tools are marked protected. They are always included in full.
Prune evidence by relevance. Retrieved chunks below a re-ranker score threshold are dropped,
near-duplicates are merged, and each kept chunk is trimmed to the sentences that match the question.
Compress tool output by shape. JSON becomes a compact table, nulls and constant columns are
removed, and long results are replaced by summary statistics plus a handle to fetch the rest.
Summarise history. Older turns roll into a running summary, and decisions the user confirmed
are pinned word for word. Learned token compression (LLMLingua-style) is applied only to low-risk narrative
text, and never to protected segments.
Technique 2 · semantic & prompt caching
A cache that knows “line 2” is not “line 3”
In a factory, the dangerous cache hit is the question that is almost the same.
A plain semantic cache compares question embeddings. “What was OEE on line 2 last week?” and the same
question about line 3 are nearly identical vectors, and returning one answer for the other is worse than no
cache at all. So the cache key has two parts:
Entities, matched exactly. Lines, machines, part numbers, plants and date ranges are extracted
and normalised. They must match exactly before similarity is even considered.
Meaning, matched by similarity. Only then is the question embedding compared, in Redis vector
search, with a threshold tuned on a labelled set of paraphrases and near-misses.
Freshness and scope. Entries are keyed to the index or data version, so new data invalidates
them automatically. They are namespaced by tenant and access group, and personal or session-specific answers
are never cached.
Separately, prompts are laid out so the provider’s own prompt cache can work: the stable parts (system rules,
tool definitions, workspace context) come first, and the parts that change come last. That cuts both the price
and the time to first token for the cached prefix on every repeat turn.
Technique 3 · model routing
The large model for hard questions, and only for hard questions
Route by difficulty, verify the cheap answer, escalate when it fails.
ClassifyA lightweight classifier, trained on logged requests labelled by which model
tier was needed, predicts difficulty from the question, the tool and the size of the context.
Try smallRoutine requests go to a small hosted model or the in-tenant fine-tuned model,
each with its own budget and tuned prompt.
Verify, then escalateThe tool’s own check runs on the small model’s answer:
citation verification, schema validation or numeric checks. On failure the request goes to the large model, and
the case is logged to retrain the router.
Escalation costs time, so the router is tuned for the combination of cost and p95 latency, not cost alone.
A router that saves money by escalating half its requests is slower than no router.
Evaluation · replay with quality gates
Every saving is measured against the answer it produced
Logged traffic is replayed with and without each technique, then scored with each tool’s own evaluation.
Each technique is evaluated alone and in combination by replaying recorded requests: the plant-knowledge golden
set, the data agent’s benchmark, and the planning copilot’s scenarios. Cost and latency are measured
alongside the tool’s own quality metrics, and a technique ships only if quality stays within a
non-inferiority margin.
Metric
How it is measured
Release gate (target)
Quality, per tool
Tool’s own gates (groundedness, execution accuracy, numeric faithfulness)
within 1 point of baseline
Cache false hits
Entity-swap test set: same question, different line, machine or date
0 (hard gate)
Cost per task
Provider-billed tokens (incl. cached-token pricing) and GPU seconds, per tool
≥ 50% lower
Time to first token
p95, per tool, replayed at production concurrency
≥ 30% lower
Compression ratio
Prompt tokens after vs before, by segment type
reported, not gated
Context overflows
Requests that exceed the model window
0
Observability
If the bill goes up, you can see which prompt did it
Tokenomics is an observability problem before it is an optimisation problem.
TracesOpenTelemetry spans following the GenAI semantic conventions: model, tokens in,
out and cached, route, cache result and cost, tagged with tenant and tool.
DashboardsCost per task, cache hit rate, escalation rate and p95 latency per tool in Grafana,
with alerts on sudden jumps in prompt size, the usual sign of a regression.
Drop-inPlain Python middleware with adapters for FastAPI and LangChain/LangGraph callbacks.
The tools on this site use it without changing their own code.
The toolkit sits under the GenAI platform. Its usage ledger and this
toolkit’s traces share one set of token counts, so the savings show up in the numbers partners actually see.