AI-COMPETE & SMART use case · system design

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
Analytics stages
QualitativeDescriptiveDiagnosticPredictivePrescriptiveSoftware
Technology
Pythontiktoken (Rust core)Custom FastAPI middlewareLangChain / LangGraph callbacksRedis (vector search)Provider prompt cachingSmall-model routerOpenTelemetry (GenAI conventions)Grafana
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.

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.
Count, reuse, trim, route, and check Budgetcount tokens,split the window Semantic cacheentity-aware,data-versioned Prune + compressevidence, tools,history Routesmall or largemodel Model callstable prefix first,provider prompt cache Checktool’s own verifierpasses? cache hit → answer returned without a model call small model failed the check → escalate to the large model OpenTelemetry span per stage: tokens in / out / cached, cache hit, route, cost, latency, tenant, tool Safety text, citations and numbers from tools are marked as protected and are never pruned or compressed.
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.
  1. 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.
  2. 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.
  3. 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.
  4. 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.
  5. 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:

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.

MetricHow it is measuredRelease gate (target)
Quality, per toolTool’s own gates (groundedness, execution accuracy, numeric faithfulness)within 1 point of baseline
Cache false hitsEntity-swap test set: same question, different line, machine or date0 (hard gate)
Cost per taskProvider-billed tokens (incl. cached-token pricing) and GPU seconds, per tool≥ 50% lower
Time to first tokenp95, per tool, replayed at production concurrency≥ 30% lower
Compression ratioPrompt tokens after vs before, by segment typereported, not gated
Context overflowsRequests that exceed the model window0
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.