QA AND TEST AUTOMATION · PART 10 · TESTING AI FEATURES · PRACTICE · 96 OF 112

Testing AI Cost and Latency in CI

Every AI answer costs tokens and time, and a prompt or context change can multiply both without failing a single functional test. Measured on ShopRung's chat: about 330 tokens per answer, 2.6 times that for order questions, p95 1.4 s with a 3.9 s cold start, and tokens wasted on blocked answers. Then token and latency budget tests in CI, which caught a context bloat bug, a lost refusal and a slow chat.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 67
  63. 68
  64. 69
  65. 70
  66. 71
  67. 72
  68. 73
  69. 74
  70. 75
  71. 76
  72. 77
  73. 78
  74. 79
  75. 80
  76. 81
  77. 82
  78. 83
  79. 84
  80. 85
  81. 86
  82. 87
  83. 88
  84. 89
  85. 90
  86. 91
  87. 92
  88. 93
  89. 94
  90. 95
  91. 96
  92. 97
  93. 98
  94. 99
  95. 100
  96. 101
  97. 102
  98. 103
  99. 104
  100. 105
  101. 106
  102. 107
  103. 108
  104. 109
  105. 110
  106. 111
  107. 112
1 / 13

Press play to hear the narration, or step through at your own pace.

Key takeaways

  • About 330 tokens an answer
  • tools 2.6x
  • p95 1.4 s, cold start 3.9 s
  • waste
  • budget tests caught 2 bugs

Notes

Measure per answer

Start by measuring every answer. ShopRung's chat returns its token usage and latency with each response: prompt tokens are everything sent to the model, the instructions, the help extracts and the question; completion tokens are what the model wrote. Real providers report the same numbers in their API responses. Log them with the model and prompt version, and you can compare any two runs.

One response
{"answer": "Shipping costs
   $4.99 per order ...",
 "model": "llama3.2:3b",
 "promptVersion": "v1",
 "usage": {"promptTokens": 277,
           "completionTokens": 44},
 "latencyMs": 892}

prompt tokens: what we send
completion: what it writes

Where tokens go

Here is where the tokens went on the real model. A normal answer used about two hundred and ninety five prompt tokens and thirty five completion tokens, about three hundred and thirty in all. Order questions call the tool, so the model runs twice, with around seven hundred and ninety prompt tokens. Refused questions cost nothing, because the model is never called. And sending every help section tripled the prompt.

Tokens per question
golden answers (33):
  prompt 232-339, avg 295
  completion 12-64, avg 34.5
  total about 330
order questions (tool):
  2 model calls, 783-799 prompt
refused (out of scope): 0
all help sections in the
  prompt (bug): 818 vs 277

Latency

Latency, as percentiles, like any performance test. The median answer took seven hundred and sixty six milliseconds and the ninety fifth percentile about one point four seconds. The slowest, almost four seconds, was the very first call, while the model was loading: a cold start. Report it separately from warm runs, or one restart ruins your numbers. Order questions took 1.3 to two point four seconds, because of the second model call.

33 golden answers
p50     766 ms
p95   1,388 ms
max   3,908 ms  ← the first call:
                 model loading
order questions 1.3-2.4 s
refusal          about 1 ms

report warm runs and the cold
  start separately

Do the math

Turn tokens into money with simple math: prompt tokens times the input price, plus completion tokens times the output price, which is usually higher. Ten thousand questions a day at three hundred and thirty tokens is three point three million tokens a day; order questions cost about two point six times more. A local model has no token bill, but it costs hardware and time per answer. Either way, tokens per answer is the number to guard.

A cost estimate
cost per answer =
  prompt tokens x input price
  + completion x output price

10,000 questions a day x 330
  = 3.3 million tokens a day
order questions: about 2.6x

local model: no token bill, but
  hardware time per answer

Hidden waste

Look for waste too. The nine prompt leak answers blocked by the canary each made the model write about one hundred and thirty tokens, for two and a half seconds, before the guardrail threw them away: eight hundred and fifty two tokens nobody saw. The out of scope refusal, by contrast, happens before the model, so it is free. Put cheap checks before the model where you can.

Blocked prompt-leak answers
9 answers blocked by the canary
  852 completion tokens
  about 2.5 s each
  then replaced with "Sorry, I
  can't share that."

out-of-scope refusal: checked
  before the model, 0 tokens
cheap checks first

Budget tests

Now make it a test. For every golden question, assert the prompt tokens, completion tokens and latency stay under a budget, set with some margin above today's numbers. And assert the out of scope refusal uses zero tokens. In CI this runs against the deterministic fake model in a fraction of a second, so it can run on every pull request.

test_budget.py
@pytest.mark.parametrize("item",
                         GOLDEN)
def test_answer_within_budget(item):
  r = ask(item["q"])
  assert r["usage"]["promptTokens"]
         <= 400
  assert r["usage"]
    ["completionTokens"] <= 150
  assert r["latencyMs"] <= 1000
refusal: usage must be 0, 0

Caught

We ran the suite against two of ShopRung's bugs. With the long context bug, all thirteen tests failed: prompts of eight hundred and thirteen to eight hundred and eighteen tokens. It also exposed a side effect: the capital of France was no longer refused, because every section now counts as found, so it cost eight hundred and sixteen tokens instead of zero. With the slow chat bug, twelve answers took three seconds. Functional checks would have passed both.

test_budget.py results
normal:            13 passed
chat-long-context: 13 failed
  assert 813 <= 400 ... 818
  France: refused False,
  816 tokens instead of 0
chat-slow:         12 failed
  assert 3000 <= 1000 ... 3004

answers still correct:
  functional tests pass

Real-model budgets

On the real model, set budgets by what is stable. Prompt tokens were identical across runs of the same question, two hundred and seventy seven for shipping every time, so they can have a tight budget. Completion tokens varied from twelve to sixty four, so give them more room. Latency depends on hardware and load, so check the ninety fifth percentile over many runs, on the same machine, after a warm up, in a nightly job rather than on every pull request.

On llama3.2:3b
prompt tokens: the same every
  run for the same question
  (shipping: 277, 277, 277)
  → tight budget
completion: 12-64 tokens
  → a looser budget
latency: varies by machine and
  load → p95 over many runs,
  same hardware, after warm-up

In production

In production, keep measuring: log tokens, latency, model and prompt version for every request, and chart the median, the ninety fifth percentile and the cost per conversation. Alert on jumps after releases. The levers to reduce cost are the same things you tested: shorter prompts, fewer context sections, offering tools only when needed as ShopRung does, caching repeated answers, and a smaller model for easy questions.

Monitor and reduce
  • log tokens, latency, model and prompt version per request
  • dashboards: p50, p95, cost per conversation, per feature
  • alerts on jumps after releases
  • levers: shorter prompts, top-k context, routing (tools only when needed), caching, a smaller model for easy cases

Common mistakes

Mistakes. Not logging usage per answer, so nobody notices a doubled prompt. Reporting averages instead of percentiles. Mixing the cold start into warm runs. Enforcing tight latency budgets for a real model on shared CI machines, where timing is noisy. Ignoring tokens spent on answers that guardrails block or that get retried. And having no budget test at all, so a cost regression ships with green builds.

Avoid these
  • no usage logged per answer
  • averages instead of p95
  • cold start mixed into warm runs
  • latency budgets on shared CI machines with a real model
  • ignoring tokens spent on blocked or retried answers
  • no budget test in CI

Say it like this

In the interview: every response logs its tokens, latency, model and prompt version. In CI, budget tests run the golden set against a deterministic fake and assert prompt tokens, completion tokens, latency, and zero cost for refusals. Nightly, the real model is checked on the ninety fifth percentile after a warm up, on fixed hardware. In production, dashboards and alerts compare each release with the last.

In the interview
  • "Every response logs tokens, latency, model and prompt
  • version. CI runs budget tests
  • on the golden set with a deterministic fake: prompt and completion tokens, latency, zero
  • for refusals. Nightly, the real
  • model: p95 after warm-up. In production: dashboards and alerts per release."

Interview questions

Q1What are prompt and completion tokens?

Prompt tokens are everything sent to the model (instructions, context, question); completion tokens are what the model writes. Providers bill both, usually completion at a higher rate.

Q2How many tokens did ShopRung's chat use per answer?

About 330 for a normal answer (295 prompt, 35 completion); order questions with a tool call used about 790 prompt tokens over two model calls.

Q3Why report latency as percentiles?

Averages hide slow answers; p50 and p95 show the typical and the slow experience. On ShopRung: p50 766 ms, p95 about 1.4 s.

Q4What is a cold start?

The first call after start-up, slower because the model loads: 3.9 s on ShopRung versus under 1.4 s warm. Measure it separately.

Q5What is a budget test?

A test that fails when tokens or latency exceed a limit, run on the golden set, so cost regressions fail the build.

Q6What did the budget tests catch on ShopRung?

Long context: prompts of 813-818 tokens, and the out-of-scope refusal lost (816 tokens instead of 0). Slow chat: answers taking 3 seconds.

Q7How do you set budgets for a real model?

Tight on prompt tokens, which are stable per question; looser on completion tokens; latency as p95 over many runs on fixed hardware after warm-up.

Q8How can you reduce AI cost?

Shorter prompts, fewer context chunks, tools only when needed, cheap checks before the model, caching and a smaller model for easy questions.