The same support bot can cost $32,490 or $6,065 a month at the same eval score. An applied AI engineer builds the system around the model and makes that choice with numbers.
Pick a design and watch where the requests go. Then we build each skill, piece by piece: model choice, prompt budgets, retrieval, evals, agents, guardrails, latency and cost.
You need some Python and a rough idea of what a language model is (text in, text out, priced per token). We build the rest from zero.
A Day in the Life guide. Every price, rate and latency on this page is an illustrative round number, not any vendor's list price. The arithmetic is exact.
Illustrative: 100,000 requests a day, 2,610 tokens in and 200 out per call, a large model at $3 and $15 per million tokens in and out, a small one at $0.25 and $1.25, a 30% cache hit rate, and eval scores on 500 questions. Chapter 8 rebuilds every number.
Chapter 0
Follow one user question through the system an applied AI engineer owns, and see where its time and money go
A customer types "How do I get my money back?" into your help widget. Half a second later the first words of a correct answer appear. Nobody trained a model for this. Someone built the system around one.
An applied AI engineer builds products on top of models that other people trained. The job is everything between the user and the model: what the model reads, which model runs, how you know the answer is good, and what it costs. Each of those is a skill with numbers attached.
Here is one request. It passes a gateway, a cache, a retriever, an optional reranker, a safety check and then the model. Each stage adds time before the first word, and some add cost.
The bar is the time before the first word. Switch stages on and off, change the model, or make it a cache hit.
Illustrative stage times (median) and costs. The model cost uses 2,610 tokens in and 200 out at the prices in the hero.
With every stage on and the large model, the first word comes after 461 ms and the request costs about $0.011. The model is 350 of those milliseconds and almost all of the cost. A cache hit skips everything after the lookup: 10 ms and no model bill.
| Skill | The question it answers | Chapter |
|---|---|---|
| Model choice | Which model is cheapest once wrong answers count? | 1 |
| Prompt budget | What does each part of the prompt cost per month? | 2 |
| Retrieval | Did the model see the right documents? | 3 |
| Evals | Is version B better, or is it noise? | 4 |
| Agents | How many steps can a task take and still finish? | 5 |
| Layers | How many bad outputs get past all the checks? | 6 |
| Latency | When does the user see the first word? | 7 |
| Cost at scale | What is the monthly bill, and what cuts it? | 8 |
Failure: the bill jumps from $31,000 to $47,000 in a month with no code change. Measure: log tokens in, tokens out and model name for every call, then group the cost by feature. Fix: the log shows a forgotten debug job that sends each query twice. Turn it off and add an alert on cost per request.
Chapter 1
Add the price of a wrong answer to the price of the call, and watch the cheapest model change
You route support tickets into 15 queues. A small model costs $0.0009 a call and sends 9% of tickets to the wrong queue. A large model costs $0.0108 and gets 5% wrong. The small one is 12 times cheaper. Is it the better choice?
Only if a wrong answer is cheap. A misrouted ticket waits in the wrong queue. Someone must find it and move it. That person's time is a cost too, and it is often far larger than the call.
So compare expected cost: the average cost per request once errors count. Call the price of one call a. Call the share of answers that are wrong, the error rate, e. Call the cost of one wrong answer L, for loss.
E equals a, plus e times L.
Multiply the error rate e by the cost of an error L. Add the call price a. The model with the smallest E is the cheapest.
With made-up numbers and L = $0.50: the small model gives E = 0.0009 + 0.09 × 0.50 = $0.0459. The large model gives E = 0.0108 + 0.05 × 0.50 = $0.0358. The large model is cheaper per ticket.
Each line is one model's expected cost. Drag the cost of an error and watch which line is lowest.
Illustrative: small $0.0009 and 9% wrong, large $0.0108 and 5% wrong, small fine-tuned $0.0006 and 6% wrong (shorter prompt, Chapter 2).
The small and large lines cross where both costs are equal: L = (0.0108 − 0.0009) / (0.09 − 0.05) = $0.2475. If an error costs less than about 25 cents, the small model wins. Above that, the large one wins. A fine-tuned small model with 6% errors holds out against the large one until L = $1.02.
Failure: the model scored 95% on your test set and 82% in production. Measure: label 500 real production requests and score the model on them. Fix: build the eval set from real traffic, with its typos and long emails, and choose again.
Chapter 2
Count the tokens in each part of the prompt and turn them into dollars per month
Your prompt has four parts. A system prompt of 600 tokens sets the rules. Three few-shot examples of 150 tokens each show the answer format. Five retrieved chunks of 300 tokens add knowledge. The user's question adds 60. The model then writes about 200 tokens.
Providers charge per token, and output tokens cost more than input tokens. So you price a call by counting both. Call the number of input tokens Tin and their price per million pin. Call the output tokens Tout and their price per million pout.
c equals T-in times p-in, plus T-out times p-out, all divided by one million.
Multiply the input tokens T-in by their price p-in. Multiply the output tokens T-out by their price p-out. Add the two and divide by one million.
With made-up prices for the small model, p-in $0.25 and p-out $1.25: c = (2,610 × 0.25 + 200 × 1.25) / 1,000,000 = $0.0009025. At 3 million calls a month that is $2,707.50.
Each block is a part of the prompt, drawn to scale in tokens. Switch parts on and off and change the model.
Illustrative token counts and prices; 3 million calls a month (100,000 a day for 30 days); output written at 80 tokens a second.
Two facts fall out. First, the 1,500 tokens of context are the largest input part, so retrieval depth (Chapter 3) is a cost knob. Second, asking for step-by-step reasoning adds output tokens, which cost five times more each and add seconds of writing time.
Fine-tuning trains a model on examples so it learns the behaviour without being told each time. If it removes the 1,050 tokens of system prompt and examples, 3 million calls save 1,050 × 3,000,000 × 0.25 / 1,000,000 = $787.50 a month on the small model. Training on 1,000 examples of 500 tokens for 3 passes reads 1.5 million tokens, about $4.50 at a made-up $3 per million. The training is cheap. The data, the evals and the retraining when your product changes are the real cost.
Failure: the bill rises 15% after "a small prompt fix". Measure: count the tokens of every prompt template in CI and print the monthly cost of the change. Fix: fail the build when cost per call rises more than 10% without a note.
Chapter 3
Count how many of the right chunks reach the model, and see how hybrid search moves them up
The model never saw your refund policy, so it cannot answer "How do I get my money back?" from memory. Retrieval-augmented generation (RAG) fixes this. It finds the most relevant pieces of your documents and puts them in the prompt.
RAG is two pipelines. The indexing pipeline runs when documents change. It splits each document into chunks of a few hundred tokens. It turns each chunk into an embedding, a vector that places similar meanings close together, and stores it. The query pipeline runs on every request: embed the question, fetch the closest chunks, and hand the top k to the model.
If the right chunk is not in the top k, the model cannot use it. So the first number to watch is recall at k. Call the number of relevant chunks for a question R. Call the number of them that land in the top k results rk.
Recall at k equals r-k divided by R.
Mark the chunks that answer the question. Count them: that is R. Count how many of them are in the top k results: that is r-k. Divide r-k by R.
In the toy below, R = 3. Dense search puts them at ranks 2, 5 and 9, so with k = 5, r-k = 2 and recall at 5 = 2 / 3 = 0.67. One answer chunk never reaches the model.
Ticks mark the three chunks that answer the question. Drag k, then switch from dense search to hybrid search.
Illustrative ranking for one question; chunks of 300 tokens; context cost at the large model's made-up $3 per million input tokens.
Why does hybrid search help? The user wrote "money back". The policy says "refund". Dense embeddings place these near each other, but not always near enough. BM25 is a keyword score that rewards exact word matches, such as "refund" in a query that names it. Hybrid search blends the two scores, so a chunk strong on either rises.
Raising k is the lazy fix. At k = 9 dense search finds all three chunks, but the model reads 2,700 tokens of context, nine tenths of it noise. A reranker reads the question and each candidate together and reorders the top 20. That buys recall at a small k.
Failure: recall at 5 falls from 0.83 to 0.71 after the docs team adds 400 pages. Measure: run your labelled questions every night and split recall by document source. Fix: the new pages use a different layout and the splitter cuts tables in half; chunk them by heading.
Chapter 4
Size the noise in an eval score and find out when a 3-point gain is real
You rewrite the prompt. On your 200-question eval set (a fixed list of questions with a way to score each answer), version A scores 86% and version B scores 89%. Do you ship B?
Not yet. 200 questions is a sample. Draw another 200 from the same traffic and the scores move by a few points. You must know how far they move before you trust a 3-point gap.
The size of that wobble is the standard error. Call the measured pass rate p and the number of questions n.
SE equals the square root of p times one minus p, divided by n.
Multiply the pass rate p by the fail rate. Divide by the number of questions n. Take the square root. Go 1.96 SE either side of p for a 95% band.
For B, p = 0.89 and n = 200: SE = √(0.89 × 0.11 / 200) = 0.0221. The 95% band is 89% ± 4.3 points. For A it is 86% ± 4.8. The bands overlap a lot.
Each bar is a score with its 95% band. Drag the number of questions, then rerun the eval to see the scores wobble.
Simulated: the true pass rates are 86% and 89%; each rerun draws n fresh pass or fail results for each version. The gap test treats the two sets as independent.
The fair question is about the gap, not each score. The gap has its own standard error, √(0.0245² + 0.0221²) = 0.033, so its band is ± 6.5 points. A 3-point gap sits well inside it: a tie. To separate a true 3-point gap you need about 932 questions per version. Scoring both versions on the same questions and counting where they differ needs fewer.
For free-text answers, a person or an LLM judge (a model prompted to grade answers) gives the pass or fail. Zheng et al. (2023) found strong judges agree with human raters about as often as humans agree with each other, above 80% in their setting. Judges also favour long, confident answers. So check yours: grade 50 to 100 answers by hand and measure agreement before you trust it.
Failure: the judge rates faithfulness 4.2 out of 5 while users are unhappy. Measure: read 50 low-rated sessions next to their judge scores. Fix: faithfulness is only one criterion; add "did it answer the question" and give the judge a reference answer.
Chapter 5
See why small errors per step multiply, and why each step costs more than the last
"Book the cheapest flight to New York next Tuesday, aisle seat." That is not one answer. It is a search, a comparison, a booking and a seat change, each depending on the last. An agent is a model in a loop. Each turn it picks a tool (a function it may call, described by a schema), your code runs the tool, and the result goes back into the context.
Every step can go wrong: a bad argument, a misread result, a wrong tool. Suppose each step succeeds with the same chance, independent of the others. Call that chance s and the number of steps n.
P equals s to the n.
The task finishes only if every step works. Multiply the step success s by itself n times. The product is P.
With made-up numbers s = 0.95 and n = 10: P = 0.9510 = 0.60. A step that works 19 times in 20 gives a 10-step task that fails 4 times in 10.
Each row is one task. Green steps worked; a red step ended the task. Set the step success and the number of steps, then run.
Simulated with independent steps. Real agents can retry a failed step, which raises s, and real errors cluster, which lowers P. Token counts assume a 2,000-token start and 500 new tokens per step.
The cost grows too. The model rereads the whole context each turn. Start with 2,000 tokens and add 500 per step: ten steps read 2,000 + 2,500 + ... + 6,500 = 42,500 input tokens. That is about $0.13 per task on the large model, not $0.006.
So an agent needs limits. A step budget stops the loop after a set number of turns. A token budget stops it before the bill grows. Tools that change the world, such as a booking, ask the user to confirm first.
Failure: the agent calls the flight search again and again with the same arguments. Measure: log every tool call and count repeats per session. Fix: stop after two identical calls, and return the earlier result marked as already fetched.
Chapter 6
Chain a schema, a validator and a retry, and count how many bad outputs get through
Your code expects {"category": "billing"}. One day the model writes "The category is billing, I think." The parser throws. The ticket sits in a dead queue for four hours. At a million calls a day, a 2% bad-output rate is 20,000 of these.
No single check catches everything, so you stack them. Three common ones:
Call the share of outputs that are bad before any check f. Call the share of the remaining bad outputs that each layer catches c1, c2 and c3. If the layers fail for unrelated reasons, the share that slips through all of them, r, is a product.
r equals f, times one minus c-one, times one minus c-two, times one minus c-three.
Start with the bad share f. Each layer lets through one minus its catch rate. Multiply f by what each layer lets through. The result is r.
With made-up rates f = 0.02, c-one 0.9, c-two 0.8, c-three 0.7: r = 0.02 × 0.1 × 0.2 × 0.3 = 0.00012. That is 120 bad outputs per million, down from 20,000.
Each bar is the number of bad outputs per million still alive after that layer. The scale is logarithmic: each grid line is ten times the last.
Illustrative catch rates. The product rule holds only if the layers fail for unrelated reasons.
Guardrails are checks for harm: an input filter for prompt injection (text that tries to override your instructions), scope rules in the system prompt, and an output filter. Here the product rule breaks. An attacker who beats one filter often beats the next with the same trick, so the layers do not fail for unrelated reasons.
Guardrails also fail the other way. A regex that blocks "ignore ... previous" also blocks "Can I ignore the previous invoice?". A 3% false-positive rate on 100,000 daily users turns away 3,000 honest people a day.
Failure: valid JSON with the same confidence, 0.99, on every ticket. Measure: plot the confidence values and compare them with accuracy. Fix: the schema checks shape, not truth; add examples with low confidence and score calibration in your eval.
Chapter 7
Split latency into the wait for the first token and the speed after it, and see what streaming changes
A user asks a question. Three seconds pass with a blank box. They click again. Now two requests run and two answers arrive. The model was not slow. The page waited for the whole answer before it showed anything.
A model writes one token at a time, so latency has two parts. The time to first token (TTFT) is the wait before anything appears: the network, the stages of Chapter 0, and the model reading the prompt. Then the model writes at some speed in tokens per second. Call the TTFT t0, the answer length N tokens, and the speed v tokens per second.
T equals t-zero, plus N divided by v.
Wait t-zero for the first token. Then divide the answer length N by the speed v to get the writing time. Add the two to get T.
With made-up numbers t-zero = 0.35 s, N = 200 and v = 80: T = 0.35 + 200 / 80 = 2.85 s. Without streaming the user stares at nothing for 2.85 s. With streaming, words appear at 0.35 s.
Top: the page waits for the whole answer. Middle: it shows tokens as they arrive. Bottom: the share of the answer a person has read. Set the numbers and press Play.
Illustrative. The read row assumes about 5 tokens a second, a relaxed reading pace. The playback runs faster than real time for long answers.
Streaming does not make the model faster. It moves the first visible word from T to t-zero. Once the model writes faster than a person reads, the reader never catches up, so v above that pace buys little. Cutting t-zero is what the user feels.
Where does t-zero go? The table adds the stages before the first token, from Chapter 0. The model's own share grows with prompt length, because it must read every input token first.
| Stage | Median time |
|---|---|
| Gateway and cache lookup | 6 ms |
| Embed the query and search | 25 ms |
| Rerank the top 20 | 60 ms |
| Input check | 20 ms |
| Model, to first token | 350 ms |
| Total before the first word | 461 ms |
Failure: the provider reports 400 ms to first token, users see 2 seconds, and text arrives in bursts. Measure: log the first-token time at the server and in the browser and compare. Fix: a proxy buffers the stream; turn off response buffering for that route.
Chapter 8
Rebuild the hero's numbers: skip repeated calls, and send easy requests to the small model
Finance asks what the bot will cost next month. You serve 100,000 requests a day, and each large-model call costs $0.01083 (Chapter 2's prompt at the large model's prices). That is $1,083 a day, or $32,490 a month. Two levers cut it.
A cache stores answers and returns them for repeated requests. An exact-match cache hashes the full prompt. A semantic cache embeds the question and reuses the answer of a close earlier question, so "How do I return something?" can hit "What is your return policy?". A router sends each request that misses the cache to the cheapest model that can handle it.
Call the requests per day Q, the cache hit rate h, the share of misses the router sends to the small model w, and the per-call costs of the small and large models cS and cL.
D equals Q times one minus h, times the quantity w c-S plus one minus w, times c-L.
Remove the cache hits: Q times one minus h is the number of model calls. Average the call cost over the two models, weighted by w. Multiply the two to get D.
With the made-up numbers Q = 100,000, h = 0.3, w = 0.8, c-S = $0.0009025 and c-L = $0.01083: the average call is 0.8 × 0.0009025 + 0.2 × 0.01083 = $0.002888. D = 70,000 × 0.002888 = $202.16 a day, $6,064.80 a month. That is 73% below cache alone and 81% below the start.
The grey bar is the large model for everything, with no cache. The bar below it is your design, split by model. Move the knobs.
Illustrative prices and times: small model 150 ms to first token, large 350 ms, 111 ms of other stages, a cache hit 10 ms. The router's own classifier and the cache store are left out; both are small next to the model bill.
The savings are real only if quality held. Route a sample of traffic both ways and score it with the eval from Chapter 4. In the hero, the router scores 93% and the large model 94%, each ± 2.2 points on 500 questions: within the noise, so the cheaper design ships.
Failure: after a semantic cache goes live, users report answers about the wrong product. Measure: sample cache hits and have the judge compare question and cached answer. Fix: raise the similarity threshold, and put the product and user plan into the cache key.
Chapter 9
Keep the terms, the numbers, the checklist and the code in one place
An applied AI engineer turns product requests into systems with a price, a speed and a measured quality. Each skill on this page is one number you can compute and one failure you can catch.
| Term | What it is | Worked number here |
|---|---|---|
| Expected cost | Call price plus error rate times cost of an error | Small and large models tie at L = $0.2475 |
| Cost per call | (tokens in × price in + tokens out × price out) / 1,000,000 | $0.0009025 small, $0.01083 large |
| Recall at k | Relevant chunks in the top k, divided by all relevant chunks | Dense 2 / 3 = 0.67, hybrid 3 / 3 at k = 5 |
| Standard error | √(p(1 − p) / n); the 95% band is ± 1.96 SE | 89% on 200 questions: ± 4.3 points |
| Questions to see 3 points | n per version so the gap's band is 3 points | About 932 (86% against 89%) |
| Agent success | Step success to the power of steps | 0.9510 = 0.60 |
| Residual bad outputs | f times what each layer lets through | 120 per million, from 20,000 |
| Total time | First token plus tokens divided by speed | 0.35 + 200 / 80 = 2.85 s |
| Daily cost | Requests × (1 − hit rate) × average call cost | $202.16 a day with cache and router |
pythonfrom math import sqrt def call_cost(t_in, t_out, p_in, p_out): # prices are $ per million tokens return (t_in * p_in + t_out * p_out) / 1e6 def daily_cost(q, hit, w_small, c_small, c_large): return q * (1 - hit) * (w_small * c_small + (1 - w_small) * c_large) def score_with_band(passes): # passes: list of 0/1, one per question n = len(passes); p = sum(passes) / n se = sqrt(p * (1 - p) / n) return p, 1.96 * se # score and half-width of the 95% band def recall_at_k(ranked_ids, relevant_ids, k): return len(set(ranked_ids[:k]) & set(relevant_ids)) / len(relevant_ids) c_s = call_cost(2610, 200, 0.25, 1.25) # 0.0009025 c_l = call_cost(2610, 200, 3, 15) # 0.01083 print(daily_cost(100_000, 0.3, 0.8, c_s, c_l)) # 202.16
Now press Present or Teach and explain from memory: expected cost, the cost of a call, recall at k, the standard error, why agent steps multiply, and the daily cost formula. Then go back to the hero and say which lever moved each bar.