Production AI: Quality, Cost and Guardrails Before Optimisation
A demo that answers five questions well proves very little. In production, the same system has to be correct, safe, affordable, fast under load, observable and maintainable. Teams often start with speed tricks, but the order matters: measure quality first, add cost monitoring and agent limits second, secure tools and data third, and only then optimise.
Using an external API does not solve these problems for you. The provider runs the model. It does not check whether your retrieval finds the right document, whether the user is allowed to see it, or whether an agent stops after the tenth identical search.
1. Measure retrieval and generation separately
A RAG system can fail in several places: the right document was never retrieved, it was retrieved but ranked low, the context was too long or badly assembled, the model ignored relevant text, the answer contains an unsupported claim, or the source itself was wrong or outdated. If you measure only the final answer, you cannot tell which of these happened.
I would split the evaluation into three layers:
- Retrieval: did we find the right chunks, and in what order? Useful metrics are Precision@k (the share of relevant results among the top k), Recall@k (the share of all known relevant items found in the top k), MRR (how high the first relevant result sits) and nDCG (ranking quality with graded relevance).
- Generation: is the answer supported by the retrieved context (faithfulness), does it answer the question (relevancy), does it match a reference answer (correctness), and does it cite sources properly?
- End to end: did the user get what they needed, did the system respect permissions, and did it avoid unwanted actions?
A small example: three documents are known to be relevant, and the retriever returns five results, of which two are relevant. Precision@5 is 2/5 = 0.4, and Recall@5 is 2/3, about 0.67.
Faithfulness and correctness are not the same thing. If a source document contains a wrong year and the system repeats it accurately, the answer is faithful and still false. RAG does not replace checking the source data.
The evaluation dataset needs questions the knowledge base cannot answer. The right behaviour there is to say so, not to invent something plausible. Version the dataset together with the prompt, the embedding model and the retriever configuration. Otherwise you cannot reproduce last week’s result, and you will not know whether a change to chunking or top-k made things better or worse.
Technical notes on RAG are in the RAG skill , and a practical example on Drupal in A Knowledge Base for AI in Drupal .
2. Know what every request costs
Most unexpected token spend has a small number of causes: a long conversation history, too many retrieved chunks, repeated calls inside an agent loop, retries after errors, and reasoning tokens if the model uses them and the API bills them. Some frameworks also make extra model calls behind your back.
Track at least input tokens, output tokens, cached tokens, tool calls, retries and latency for each request. Tag every model call with a trace ID, a session, the tenant and the workflow it belongs to. Without these tags, you can see the bill but not the reason for it.
The most useful number is cost per successful task, not cost per answer. Take two agents:
- Agent A costs 0.20 per attempt and completes 50% of tasks. Its cost per successful task is 0.20 / 0.50 = 0.40.
- Agent B costs 0.30 per attempt and completes 90% of tasks. Its cost per successful task is 0.30 / 0.90 = 0.33.
Agent B is more expensive per attempt and cheaper per result. Choosing by the price of a single call gets this wrong.
Practical rules I would apply from the start: every agent has its own budget, every workflow has a maximum number of steps, and alerts fire on unusual behaviour, not only on the monthly total.
3. Put guardrails outside the prompt
An agent does more than write text. It reads databases, updates orders, sends emails and calls external APIs. So guardrails have to cover actions, not only the text going in and out. I think of four layers:
- Input: schema validation, size limits, authentication and authorisation, and detection of prompt injection. Injection can arrive in a retrieved document or in a tool’s response, not only in what the user types.
- Tool: which tools the agent may call, and with which parameters. This must be enforced by the tool or the API. A line in the system prompt saying “do not delete customers” is a request, not a control.
- Output: schema checks, required fields, citation checks, and screening for sensitive data or internal instructions.
- Execution: a maximum number of iterations and tool calls, timeouts, token and money budgets, and a limit on how deeply agents may delegate to other agents.
Start from least privilege. The default is no access, each tool has explicitly defined permissions, and those permissions are checked on every call. Sensitive operations, such as sending an important email, deleting records or changing permissions, need a human approval. The approval is tied to the exact parameters. If the parameters change, ask again.
Loop detection is the less obvious part. An agent can repeat the same search because it cannot judge that the first one failed. Detecting a repeated action is easy. Deciding what counts as a loop is harder, because polling a long-running job or retrying after a timeout is legitimate. I would fingerprint actions within a time window and set a threshold, not flag the first repetition. Pair this with a circuit breaker for external services that keep failing: closed means requests pass, open means they are blocked for a while, and half-open lets a few test requests through before resuming normal traffic.
How I test prompt injection and other attacks on LLM applications is summarised in the LLM attacks skill . Why working code from AI is not enough is the subject of Vibe Coding vs. Agentic Development .
4. Caching: prompt cache first, semantic cache with care
Two techniques reduce repeated work, but they work at different levels and carry different risks.
Prompt caching reuses the processed beginning of a prompt. It pays off when the same system instructions, tool descriptions and stable documentation go in front of every request. The rule is simple: put the stable parts first and the dynamic parts after them. The dynamic parts are the user’s identity and permissions, the retrieved documents and the question itself. Do not move user-specific data into a shared prefix to make the cache hit more often. Whether a cache hits depends on the exact prefix match and on the provider’s rules, such as minimum length and lifetime, so check the current documentation rather than trusting numbers from a blog post. That includes this one.
Semantic caching stores earlier answers and returns them for questions with a similar meaning. The risk is that similar questions can have different answers. “How much does product A cost?” and “How much does product B cost?” are close in embedding space and completely different as questions. I would never semantically cache prices, stock levels, personalised offers, order status or anything that depends on permissions.
If you do use a semantic cache, store the tenant, the user’s permissions, the language, the knowledge base version, the source version, and the creation and expiry times. Check the result against these before returning it. Calibrate the similarity threshold on your own data and read the false matches by hand. A low threshold gives more hits and more wrong answers, a high one gives few hits. There is no universal value. Invalidate entries when the product data, documentation, permissions, model or prompt changes.
5. Self-hosted inference: KV cache, quantization, speculative decoding
This section matters only if you run your own models. If you use an external API, the provider manages these things, and what remains for you is to measure latency and usage.
KV cache stores the key and value tensors of earlier tokens so the model does not recompute them at every step. Its memory grows with the context and with the number of concurrent sequences. An approximate formula is:
KV cache bytes ≈ 2 × layers × sequence length × KV heads × head dimension × bytes per value × sequences
For a model with 32 layers, 8 KV heads, head dimension 128, an 8,192-token context and FP16 values, one sequence needs 2 × 32 × 8192 × 8 × 128 × 2 bytes = 1 GiB. Sixteen concurrent sequences at full length need about 16 GiB, which can run out of VRAM before the weights themselves do. The formula is only an estimate, because allocation, padding and the inference server’s implementation all matter.
Quantization lowers the numerical precision of the weights. For an 8-billion-parameter model the weights take roughly 16 GB in FP16, 8 GB in INT8 and 4 GB in INT4, counting in decimal gigabytes and ignoring overheads. Smaller is not automatically better. Quality can drop on specific tasks, so test the quantized variant on your own evaluation set and under concurrent load, and choose by the total operating requirements, not by file size alone.
Speculative decoding lets a small draft model propose several tokens, which the larger target model then verifies. A correct implementation keeps the target model’s output distribution, so it is not a heuristic that accepts arbitrary guesses. The gain depends on the acceptance rate, the speed of the draft model and the hardware. Measure the acceptance rate and the end-to-end latency of a real request, not just the tokens per second.
Inference servers also offer PagedAttention (used in vLLM, which manages the KV cache in blocks), prefix caching and continuous batching. I would first check what the server already enables by default, then measure the effect of each feature on your own traffic.
Local LLMs and self-hosted AI make most sense where data must not leave the company. How to start with local models is in the Ollama skill .
The order I would follow
- Measure the quality of retrieval and generation, and the success rate of the workflow.
- Add cost monitoring and limits for agents.
- Secure tools, permissions and data.
- Optimise prompts and caches.
- Only if you run models yourself: tune the KV cache, quantization and speculative decoding.
The metric that matters is not tokens per second, and not the price of one API call. It is the cost, quality and safety of a successfully completed user task. Everything above exists to improve that number.