Applied AI Engineer

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.

Ship one bot three ways

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

What the Role Builds

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.

Trace one request

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.

The skills, as a table

SkillThe question it answersChapter
Model choiceWhich model is cheapest once wrong answers count?1
Prompt budgetWhat does each part of the prompt cost per month?2
RetrievalDid the model see the right documents?3
EvalsIs version B better, or is it noise?4
AgentsHow many steps can a task take and still finish?5
LayersHow many bad outputs get past all the checks?6
LatencyWhen does the user see the first word?7
Cost at scaleWhat 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.

The road

  1. Choose a model by expected cost: the API price plus the price of being wrong.
  2. Budget the prompt: tokens in, tokens out, dollars per month.
  3. Measure retrieval: recall at k, and why hybrid search helps.
  4. Put error bars on evals: when a 3-point gain is real.
  5. Budget agent steps: small per-step errors multiply.
  6. Stack checks: schemas, validators, retries and guardrails.
  7. Stream the answer: first token and tokens per second.
  8. Cut the bill: caching and routing, the hero rebuilt.
  9. Field guide: numbers, checklist, code and links.
A request takes 461 ms to the first word. The model is 350 ms of it. Which change saves the most time for a repeated question?

Chapter 1

Choose a Model by Expected Cost

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.

Say it aloud

E equals a, plus e times L.

E
E the expected cost of one request, in dollars.
a
a the API price of one call, in dollars.
e
e the error rate: the share of answers that are wrong, from 0 to 1.
L
L the cost of one wrong answer, in dollars: staff time, a refund, a lost sale.
In plain words

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 numbers

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.

Price a wrong answer

Each line is one model's expected cost. Drag the cost of an error and watch which line is lowest.

$0.50

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.

A wrong answer costs $2. Model A costs $0.001 and is wrong 10% of the time. Model B costs $0.02 and is wrong 4% of the time. Which has the lower expected cost?

Chapter 2

Budget the Prompt

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.

Say it aloud

c equals T-in times p-in, plus T-out times p-out, all divided by one million.

c
c the cost of one call, in dollars.
Tin
T-in the number of input tokens: system, examples, context and question.
pin
p-in the price of one million input tokens, in dollars.
Tout
T-out the number of tokens the model writes.
pout
p-out the price of one million output tokens, in dollars. Usually several times p-in.
1,000,000
one million turns a price per million tokens into a price per token.
In plain words

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 numbers

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.

Build the prompt, part by part

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.

When a long prompt should become weights

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.

A call reads 1,000 tokens and writes 400. Input costs $3 and output $15 per million. What does one call cost?

Chapter 3

Measure Retrieval with Recall at k

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.

Say it aloud

Recall at k equals r-k divided by R.

recall@k
recall at k the share of the relevant chunks that the model gets to read, from 0 to 1.
rk
r-k how many relevant chunks are in the top k results.
R
R how many relevant chunks exist for this question, marked by a person.
In plain words

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.

With numbers

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.

Fetch the top k

Ticks mark the three chunks that answer the question. Drag k, then switch from dense search to hybrid search.

5

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.

A question has 4 relevant chunks. The top 5 results contain 3 of them. What is recall at 5?

Chapter 4

Put Error Bars on Evals

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.

Say it aloud

SE equals the square root of p times one minus p, divided by n.

SE
S-E the standard error: how far the score typically moves between two eval sets of the same size.
√
the square root of undoes a square. It is why 4 times the questions only halves the error.
p
p the measured pass rate, from 0 to 1.
1 − p
one minus p the fail rate. The product p times one minus p is largest at p = 0.5.
n
n the number of questions in the eval set.
In plain words

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.

With numbers

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.

Grow the eval set

Each bar is a score with its 95% band. Drag the number of questions, then rerun the eval to see the scores wobble.

200

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.

Who scores the answer

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.

A score of 80% on 100 questions. About how wide is its 95% band?

Chapter 5

Budget Agent Steps

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.

Say it aloud

P equals s to the n.

P
P the chance that the whole task finishes with no failed step, from 0 to 1.
s
s the chance that one step succeeds, from 0 to 1.
n
to the n multiply s by itself once for each of the n steps.
In plain words

The task finishes only if every step works. Multiply the step success s by itself n times. The product is P.

With numbers

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.

Run twenty tasks

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.

0.950
10

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.

Each step works 99% of the time. About what share of 10-step tasks finish?

Chapter 6

Stack Checks That Catch Bad Outputs

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:

  1. Schema-constrained decoding: the API only lets the model write tokens that fit your JSON schema. Wrong shapes become impossible.
  2. A validator: your code checks the values, such as a category from the allowed list and a confidence between 0 and 1.
  3. A retry: on a failed check, call again with the error message, or send the item to a person.

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.

Say it aloud

r equals f, times one minus c-one, times one minus c-two, times one minus c-three.

r
r the residual: the share of all outputs that are bad and pass every check.
f
f the share of outputs that are bad before any check.
c1
c-one the share of bad outputs the schema layer stops.
c2
c-two the share of the remaining bad outputs the validator stops.
c3
c-three the share of what is left that the retry fixes.
In plain words

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 numbers

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.

Switch the layers on

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.

The same rule, for safety

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.

5% of outputs are bad. Two independent checks catch 80% and 50% of what reaches them. What share is bad and passes both?

Chapter 7

Stream the Answer

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.

Say it aloud

T equals t-zero, plus N divided by v.

T
T the total time until the last token, in seconds.
t0
t-zero the time to first token, in seconds.
N
N the number of tokens in the answer.
v
v the writing speed, in tokens per second.
In plain words

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 numbers

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.

Race wait against stream

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.

350 ms
80
200

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.

StageMedian time
Gateway and cache lookup6 ms
Embed the query and search25 ms
Rerank the top 2060 ms
Input check20 ms
Model, to first token350 ms
Total before the first word461 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.

t-zero is 0.5 s, the speed is 50 tokens a second and the answer is 300 tokens. When does the last token arrive?

Chapter 8

Cut the Bill with Caching and Routing

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.

Say it aloud

D equals Q times one minus h, times the quantity w c-S plus one minus w, times c-L.

D
D the model cost per day, in dollars.
Q
Q the requests per day.
h
h the cache hit rate: the share of requests served from the cache, from 0 to 1.
w
w the share of cache misses the router sends to the small model.
cS
c-S the cost of one small-model call, in dollars.
cL
c-L the cost of one large-model call, in dollars.
In plain words

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 numbers

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.

Run the bill

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.

100k
30%
80%

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.

10,000 requests a day, a 30% cache hit rate, and every miss on a model that costs $0.0015 a call. What is the daily model cost?

Chapter 9

Field Guide

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.

Terms and numbers

TermWhat it isWorked number here
Expected costCall price plus error rate times cost of an errorSmall 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 kRelevant chunks in the top k, divided by all relevant chunksDense 2 / 3 = 0.67, hybrid 3 / 3 at k = 5
Standard error√(p(1 − p) / n); the 95% band is ± 1.96 SE89% on 200 questions: ± 4.3 points
Questions to see 3 pointsn per version so the gap's band is 3 pointsAbout 932 (86% against 89%)
Agent successStep success to the power of steps0.9510 = 0.60
Residual bad outputsf times what each layer lets through120 per million, from 20,000
Total timeFirst token plus tokens divided by speed0.35 + 200 / 80 = 2.85 s
Daily costRequests × (1 − hit rate) × average call cost$202.16 a day with cache and router

Checklist before you ship a feature

The core as code

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

Keep going

Papers behind the ideas

The takeaway. Every design choice has a price per call, a time to first token and an eval score with a band. Compute all three before you argue for any of them.

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.

Applied AI Engineer: Evals, RAG, Cost and Latency Budgets
Evaluation Statistics · RAG · Semantic Caching · Back to Gleams