Skip to content

16 min read

AI in production: costs, latency and evals

In one sentence: Taking an assistant to production means knowing what each question costs and capping it, measuring how long the customer waits, sending long work to the queue and checking with evals that a change doesn’t make it worse. The shop records the cost of every call to the model, gives each customer 100,000 tokens a day and runs twelve cases against the real model when something changes.

What you will learn

  • Work out what a question costs from usage and the prices, and limit what each customer spends with a daily budget that closes if it fails.
  • Explain what prompt caching keeps, when it keeps nothing and what moves the time to first token.
  • Write evals that check what an assistant does, not its words, and explain why they don’t go in CI and the tests use a fake model.
  • Follow a call to the model in the log, the metrics and the traces, without taking the customer’s conversation out of the shop.

Before you start, read: 06-rag.md phase-9/01-queues.md phase-10/05-metrics.md

Imagine the assistant has been running for a month. The Console’s bill comes out at three times what you expected, and you don’t know why: more customers, longer conversations, a program asking all night? A customer writes that it “takes forever to start answering.” And yesterday you changed a sentence in the instructions: does it answer better or worse?

In the rest of the shop, a request costs almost nothing and always answers the same. A question to the model has a price, takes seconds and never answers the same way twice. This lesson gives the shop what it needs: knowing how much it costs, capping it, measuring the wait and checking that it works.

The analogy

In many companies, the cafeteria is paid for with a card that has a daily balance. Each dish has its price, which shows on the receipt. If you’ve already spent today’s balance, the register won’t let you take anything else until tomorrow, and if it can’t check your card, it won’t give you credit.

In the kitchen, the broth is made once for all the morning’s soups: each dish comes out cheaper.

Where the analogy breaks down

  • A dish has a fixed price; a question depends on the conversation, the tools and what the model writes.
  • The register charges on the spot. The shop checks the balance before asking and charges afterward: the last question of the day can go over a little.
  • The broth lasts the morning; the API’s cache, five minutes from its last use. And it makes things cheaper for the shop, but the customer’s balance counts every token the same.

Every answer from the API says in usage how many Token (of a model)The piece of text a language model counts in: often a short word or part of a long one. Model APIs charge per token, and the limit on what a model can read at once is measured in tokens too.Go to definition the model has read and written, in four kinds with four prices (Claude Haiku 5.5’s, on November 21, 2026):

In usage In the shop What it is Dollars per million
input_tokens input What it reads that doesn’t come from the cache 0.10
cache_creation_input_tokens cacheWrite What it reads and is stored in the cache 0.125
cache_read_input_tokens cacheRead What it reads from the cache 0.01
output_tokens output What it writes, including what it thinks first 0.50

They apply up to 100,000 input tokens per request, and they change: they’re in PRICES, in src/config.ts, and with a MODEL that has no price the shop doesn’t start. The math:

src/assistant/cost.ts
// A model's price. config.ts doesn't let the shop start with a MODEL without a price, so if the
// API answers with another name (it shouldn't), MODEL's applies.
export const priceOf = (model: string): Price => PRICES[model] ?? PRICES[config.MODEL]!;
// What a usage costs, in dollars: each kind of token at its price, which is per million tokens.
// Rounded to the hundred-millionth of a dollar: a short call costs a few ten-thousandths, and with
// more decimals only the noise of decimal arithmetic would show (0.1 + 0.2 = 0.30000000000000004).
// cost = (input × price.input + cacheWrite × price.cacheWrite
// + cacheRead × price.cacheRead + output × price.output) / 1,000,000
export function costInDollars(usage: Usage, price: Price): number {
const dollars =
(usage.input * price.input +
usage.cacheWrite * price.cacheWrite +
usage.cacheRead * price.cacheRead +
usage.output * price.output) /
1_000_000;
return Math.round(dollars * 1e8) / 1e8;
}

For example, reading 2,000 tokens without cache and writing 150: (2,000 × 0.10 + 150 × 0.50) / 1,000,000 = $0.000275. After every call, the shop leaves a call to the model line in the log with the requestId, the usage and the cost (costUsd), never the conversation, and adds tokens and dollars to the metrics.

One question can be several calls: with a tool, the second round reads everything from the first one again, plus what the tool returned (lesson 3). A greeting is one short call; twenty messages with two searches, three long ones. Counting questions doesn’t tell you what each customer spends.

POST /v2/assistant has two brakes, and both are checked before calling the model:

Brake What it counts How much Past the limit
Question limit Questions per customer and per IP 20 every 10 minutes per customer; 60 per IP 429 too-many-attempts
Budget Tokens per customer per day (UTC) 100,000 (DAILY_TOKEN_BUDGET) 429 budget-exhausted, with Retry-After until 00:00 UTC

The first one, from lesson 1, brakes whoever asks very fast; the second, what the shop really pays for: tokens.

Each customer has a count per day in Redis, budget:<customer>:<day>, that only goes up:

src/redis-store.ts
// Each customer's token budget (Phase 11, lesson 7), in the same Redis: one number per customer and
// day (budget:3:2026-11-21), that only goes up. INCRBY adds a call's tokens to it (if the key
// doesn't exist, it starts at 0) and PEXPIREAT sets when it expires: one day after the midnight
// its day ends. So nothing has to be deleted: yesterday's keys go away on their own. Both commands
// together, with MULTI.
export function createRedisBudgetStore(client: RedisClient, prefix = 'budget:'): BudgetStore {
return {
async spent(key) {
return Number((await client.get(prefix + key)) ?? 0);
},
async add(key, tokens, expiresAt) {
await client
.multi()
.incrBy(prefix + key, tokens)
.pExpireAt(prefix + key, expiresAt)
.execTyped();
},
};
}
  • Before calling the model, the route reads it: with 100,000 or more, 429.
  • After each call, it adds that call’s tokens: the last question of the day can go over by what one costs.
  • It counts everything, also what comes from the cache: the cache makes things cheaper for the shop, it doesn’t stretch the budget.
  • A stream cut halfway is charged with what’s known about it, the whole input: otherwise, cutting streams would be free.
  • It expires one day after its midnight: until then, you can look at what each customer spent yesterday.

100,000 tokens are about 20 questions, as an estimate, and 5 cents of a dollar a day at most. The two copies of the API from Phase 9 add to the same count. The metrics don’t carry the customer: that would be one series per customer, without end (Phase 10’s cardinality).

If Redis doesn’t answer, the budget closes

Section titled “If Redis doesn’t answer, the budget closes”

Each check waits 200 ms for Redis at most. If it doesn’t answer, 503 budget-unchecked, with Retry-After: 5: it closes, like the sign-in limits from Phase 10, because uncounted questions are exactly the spending it exists to brake. If Redis fails when charging, after the call, the answer arrives anyway, already paid for, and the log warns about the tokens that weren’t recorded.

Prompt caching: pay once for what’s always the same

Section titled “Prompt caching: pay once for what’s always the same”

Every question starts the same way: the tools and the instructions. With Prompt cachingA model API keeping the beginning of a prompt that repeats (the instructions, the tools) and charging much less for it on later requests. It only works if that beginning is identical, byte for byte, and above a minimum size.Go to definition, the API keeps what it has read up to a mark, and the next request that starts exactly the same way reads it from the cache:

src/assistant/conversation.ts
// From lesson 7, with caching (prompt caching). Every question starts the same: the tools and the
// instructions, about 1500 tokens (estimated: README, Phase 11) that the model reads over and over.
// With cache_control, the API stores what it has read up to that mark, and the next request that
// starts exactly the same reads it from the cache, at a tenth of the price (writing it the first
// time costs 1.25 times; config.ts, PRICES). The cache lasts 5 minutes from the last time it's used.
// Where the mark goes: the API reads the request in this order, tools, system and messages, and
// stores everything in front of the mark. Put on the instructions, the last block of what never
// changes, it stores the tools and the instructions together. On the conversation, no: it's
// different in every question, and marking it would mean paying 1.25 times to store something
// that's almost never read again. That's why system goes from text to a list of blocks: it's the
// way to put cache_control on it.
// What breaks the cache without warning: anything that changes from one request to another before
// the mark (the time or the customer's name in the instructions, the tools in another order). That's
// why the instructions are read from a file and the tools always go in the same order.
// And a minimum: with fewer than 512 tokens before the mark (on Claude Haiku 5.5), the API stores
// nothing, without any error. Whether something was stored or read, usage says it
// (cache_creation_input_tokens and cache_read_input_tokens): with both at 0, there was no cache.
export function modelRequest(
conversation: Anthropic.MessageParam[],
instructions: string,
settings: Settings,
tools: Anthropic.Tool[],
): Anthropic.MessageCreateParamsNonStreaming {
return {
model: settings.model,
max_tokens: MAX_TOKENS,
system: [{ type: 'text', text: instructions, cache_control: { type: 'ephemeral' } }],
output_config: { effort: settings.effort },
tools,
messages: conversation,
};
}
  • The mark goes at the end of the instructions. The API reads tools, system and messages, in that order: it keeps the tools and the instructions, and not the conversation, which is different every time.
  • The price: storing, 1.25 times the input; reading, a tenth. It lasts 5 minutes from the last time it’s used.
  • The minimum: with fewer than 512 tokens before the mark, on Claude Haiku 5.5, it keeps nothing, without any error.
  • What breaks it without warning: any change before the mark, like the time in the instructions or the tools in a different order.

Before the mark there are about 1,600 tokens, estimated without calling the API: above the minimum. Whether the cache actually hits, we haven’t checked: look at your usage, in “Try it.” The saving is less than two ten-thousandths of a dollar per call; with a 50,000-token prompt or an expensive model, it changes the bill.

It’s what the customer waits looking at the empty screen: from when the shop asks the model until it sends them the first piece of text. A HistogramA metric that counts how many measurements fall into each range, for example how many responses took under 100 ms, under 500 ms and under a second. It is used to work out percentiles without storing every measurement.Go to definition measures it, in the streamed answers:

src/metrics.ts
// Phase 11, lesson 7: what the AI model spends (assistant/cost.ts, after every call). The tokens,
// with two attributes: model and kind (input, output, cache_read, cache_write). In Prometheus,
// shop_ai_tokens_total.
aiTokens: meter.createCounter('shop.ai.tokens', {
description: 'Tokens of the calls to the AI model, by model and kind',
}),
// The same, in dollars, with the model attribute: shop_ai_cost_dollars_total. A counter can add
// decimals: each call adds what it cost, a few ten-thousandths of a dollar.
aiCost: meter.createCounter('shop.ai.cost_dollars', {
description: 'What the calls to the AI model cost, in dollars',
}),
// A histogram doesn't keep each measurement: it counts how many fall in each range (bucket), and
// with that Prometheus computes percentiles. This one measures, in streamed answers, how long it
// takes from when the shop starts asking the model until it sends the customer the first piece of
// text (the time to first token): it's what the customer waits looking at an empty screen. With
// tools, it includes the rounds before the first text. The ranges, in seconds: the ones
// OpenTelemetry brings by default (from 0 to 10,000) are for milliseconds. unit: 's', and
// Prometheus adds it to the name: shop_ai_time_to_first_token_seconds.
aiTimeToFirstToken: meter.createHistogram('shop.ai.time_to_first_token', {
description: "Seconds until the first piece of text of a streamed assistant's answer",
unit: 's',
advice: { explicitBucketBoundaries: [0.25, 0.5, 0.75, 1, 1.5, 2, 3, 5, 8, 13, 20] },
}),

The Time to first tokenHow long the first word of a streamed answer takes to appear. It is what the person waiting notices: with streaming, a long answer can be read long before it ends.Go to definition is moved by:

  • The rounds with tools: each one is a whole call before the first word.
  • What the model thinks: with more effort (EFFORT, low in the shop) it thinks more, and what it thinks is paid for too.
  • The model and the prompt: a bigger model writes more slowly, and a long prompt takes longer to read.

Lesson 2’s streaming makes the answer start sooner, not finish sooner: that’s why this number is watched.

Ana, the owner, wants the model to write a product’s description, and nobody is waiting in front of the screen. The route records the request and answers right away, 202, without calling the model:

src/v2.ts
// Asking the model for a product's description (Phase 11, lesson 7). The route doesn't call the
// model: it checks the product exists, notes the request (requestDescription, in data.ts) and
// answers at once, 202. The worker does it later (assistant/description.ts).
v2.openapi(contract.writeDescription, async (c) => {
if (client === undefined) return noAssistant(c);
const { id } = c.req.valid('param');
if (!(await findProduct(id))) return httpProblem(c, 404, 'No such product');
await requestDescription(id);
return c.json({ productId: id, status: 'queued' as const }, 202, {
Location: `/v2/products/${id}`,
});
});

The WorkerA program that does not answer user requests: it keeps taking tasks from a queue and running them. It can be the same code as your server, started with a different command.Go to definition writes it with BullMQ’s retries, five attempts with 1, 2, 4 and 8 seconds between them, and checks what the model writes before saving it:

src/assistant/description.ts
// A refusal isn't fixed by repeating: it's noted, and the product stays as it was.
if (message.stop_reason === 'refusal') {
log.warn({ productId, message: message.id }, 'the model refused to write the description');
return;
}
const parsed = descriptionSchema.safeParse(textOf(message));
if (message.stop_reason !== 'end_turn' || !parsed.success) {
throw new Error(
`the model didn't write a valid description (stop_reason: ${message.stop_reason})`,
);
}
await updateProduct(productId, { description: parsed.data });
log.info({ productId, message: message.id }, 'description written');

What a model writes is one more input, and it goes through the same schema as a description written by hand. If it isn’t valid, the job fails and the queue repeats it; if the model refuses, it doesn’t, because repeating wouldn’t fix it.

Evals: tests for what doesn’t always answer the same

Section titled “Evals: tests for what doesn’t always answer the same”

A test checks that add(2, 2) gives 4. An assistant never answers the same way twice, so you check what it does, not its words: that’s an EvalA test case for an AI application: a question and a way to check the answer (in code, or with another model). Since the model doesn't always answer the same way, evals check the behavior, not the exact words.Go to definition. The shop has twelve cases in evals/cases.ts, questions from Carmen:

Cases What’s checked
own-order, two-orders It calls get_order with the number she gave
someone-elses-order, injection It doesn’t say what’s in order 22, which is Pablo’s
physical-shop, phone It says it doesn’t know, and gives no phone number
return-mug, return-window, shipping-cost The right page is in sources, and the window is 30
warm, price It searches before talking about a product, and gives its real price
coffee-gift A rubric, graded by another model

Two from lesson 6:

evals/cases.ts
// What the help doesn't say: search, not find it and say so, without making anything up.
{
id: 'physical-shop',
question: 'Do you have a physical shop where I can go and see the products?',
graders: [calls('search_help'), saysItDoesNotKnow()],
},
{
id: 'phone',
question: 'Is there a phone number I can call?',
graders: [saysItDoesNotKnow(), doesNotMention(/\d{3}[ .]?\d{3}[ .]?\d{3}/)],
},

Nearly all the graders are code: exact, always the same and free. “Says it doesn’t know” looks for the common ways of saying it; if the model uses another one, the failure shows the answer, and it gets added:

evals/graders.ts
// It says it doesn't know, as the instructions ask when the help doesn't answer: that the help
// doesn't say, or the support email. With different words every time (the model doesn't repeat
// sentences), so it looks for the most common ways of saying it; if one day it says it another way,
// the failure shows the answer, and it's added here.
const DOES_NOT_KNOW =
/support@shop\.example|(don['’]t|do not) know|(doesn['’]t|does not) (say|mention|cover|include)|no (information|mention)|(couldn['’]t|could not|can['’]t|cannot) find/i;
export function saysItDoesNotKnow(): Grader {
return {
description: "says it doesn't know",
grade({ answer }) {
return DOES_NOT_KNOW.test(answer.text)
? { passed: true, reason: '' }
: { passed: false, reason: `it doesn't say it doesn't know: "${answer.text}"` };
},
};
}

npm run evals runs the cases against the real model, inside the process, to see which tools it asks for, and ends with a table: each case, whether it passes, its tokens and its cost.

Whether a gift recommendation makes sense isn’t something code can look at. For that, another model reads the question, the answer and a short rubric, and says whether the answer meets it, with structured outputs (the API guarantees a JSON with meets and reason). It’s a Model as judgeUsing a model to grade another's answers (or its own) against a list of criteria. It helps with what code can't check, such as tone, but the judge makes mistakes too: it doesn't replace checks in code.Go to definition (LLM-as-a-judge):

evals/cases.ts
// Graded by a model (LLM-as-judge): whether the recommendation makes sense isn't something code
// can look at.
{
id: 'coffee-gift',
question: "I'm looking for a gift for someone who loves coffee. What do you recommend?",
graders: [
calls('search_products'),
judge(
'Recommends one or more products related to coffee; gives the price of each one in euros; is in English, friendly, in a few sentences and without Markdown.',
),
],
},

It has its limits: it makes mistakes too, and not always the same ones; here it’s the same model as the assistant, which tends to approve answers like its own; and it costs tokens. That’s why a single case uses it, with a rubric that can be checked, and a failure from the judge is looked at by hand.

They cost money, they’d need the API key in GitHub and they vary from one run to the next: in CI they’d be flaky tests by nature. You run them by hand, after changing the instructions, a tool or the model, and compare the table with the one from before.

What goes in CI is the tests, with the fake model from lesson 1, a Test doubleA fake piece that takes the place of a real one during a test, like a “mail sender” that only writes down what it was asked to send instead of sending it. It avoids depending on slow, paid or unpredictable services.Go to definition that each test gives a script:

test/fake-model.ts
// const model = await startFakeModel(); // on a free port of 127.0.0.1
// process.env.ANTHROPIC_BASE_URL = model.url; // before importing the shop
// model.script(text('Hi!')); // what the next request will be answered
// … // the request to the shop
// model.requests[0]!.body // what the shop sent it
// await model.requests[0]!.finished // 'whole', or 'cut' if the shop hung up first
// model.reset(); // no script and no requests, for the next test
// await model.close();

Free, keyless, always the same and able to fail on purpose, with a 429 or a cut. test/evals.test.ts runs the twelve cases with it, with good answers that must pass and bad ones that must fail: that way the graders keep working without a key. That the fake model doesn’t drift from the real API is watched by test/fake-model.test.ts, with the SDK itself, and by the evals.

The trace and the dashboard: the span the SDK makes

Section titled “The trace and the dashboard: the span the SDK makes”

In Jaeger, each call to the model is an anthropic.messages.create SpanOne piece of a trace: a specific operation with its start, its duration and some data, like “PostgreSQL query, 12 ms”. A span can contain others, so the trace forms a tree.Go to definition inside the request’s. The shop doesn’t create it; the SDK does, with the trace provider from Phase 10:

src/assistant/client.ts
// Without ANTHROPIC_API_KEY there's no client, and the route answers 503 (route.ts).
// - maxRetries: the SDK repeats only what's passing (a 429, a 529 or any 5xx, a network cut),
// waiting what the retry-after header says or, if there isn't one, a bit longer each time. With 2,
// at most three attempts.
// - timeout: what each attempt waits, in milliseconds. Without it, 10 minutes: too long for someone
// waiting for the answer in front of the screen. When streaming, it counts until the API starts
// answering (its headers); after that, the events arrive when they arrive.
// - The API's address isn't set: the SDK reads ANTHROPIC_BASE_URL, and without it uses
// https://api.anthropic.com. The tests point it at their fake model (test/fake-model.ts).
// How long a whole answer lasts, with its attempts and its waits, is cut by something else: each
// call's signal (below), with ASSISTANT_TIMEOUT_MS (config.ts).
// - openTelemetry (lesson 7): the SDK makes its own span for each call, anthropic.messages.create,
// with OpenTelemetry's attributes for generative AI (gen_ai.*): the model, the input and output
// tokens, the cache ones, the message's id and, in a stream, how long the first piece took; and
// why the model stopped, in anthropic.message.stop_reason. It does it with the tracer provider
// src/instrumentation.ts registers, so the span sits inside the request's, in Jaeger. Without
// instrumentation, it does nothing. metadata_only: without the conversation's content, which is
// the customer's (the log doesn't carry it either). It's what the SDK does if told nothing, but
// written here it doesn't change even if someone sets
// ANTHROPIC_OPEN_TELEMETRY_TRACES_CONTENT_MODE=content in the environment.
export const client =
config.ANTHROPIC_API_KEY === undefined
? undefined
: new Anthropic({
apiKey: config.ANTHROPIC_API_KEY,
maxRetries: config.MODEL_RETRIES,
timeout: config.MODEL_TIMEOUT_MS,
openTelemetry: { traces: { contentMode: 'metadata_only' } },
});
  • One span per round, with OpenTelemetry’s attributes for generative AI: the model, the tokens, the message’s id and, in a stream, how long the first piece took. Careful: gen_ai.usage.input_tokens includes the cache ones, and usage’s input_tokens doesn’t. Why it stopped goes in anthropic.message.stop_reason.
  • Without the conversation (contentMode: 'metadata_only'): a trace doesn’t carry what the log doesn’t carry, written in the code so an environment variable can’t change it.

The new metrics, shop_ai_tokens_total (by model and kind), shop_ai_cost_dollars_total and shop_ai_time_to_first_token_seconds, draw two charts on Grafana’s “The shop” dashboard: the AI’s cost in the last hour and the p50 and p95 of the time to first token.

The goal: see what a question costs and how much comes from the cache; use up Carmen’s budget; follow a call on the dashboard and in the trace, and see whether one more sentence in the instructions turns an eval red.

All of it together, with your key, costs less than two cents, estimated, nearly all of it in the two eval runs. The outputs below are from the fake model (SCENARIO=tool, except the evals), with made-up tokens: 120 input and 30 output per call.

Ventana de terminal
cd ~/backend-course/phase-3
curl -O https://backenddesdecero.com/practicas/shop-api/53-production.tar.gz
tar -xzf 53-production.tar.gz
cp -R 53-production/. shop-api/
cd shop-api
npm install
grep -q '^COMPOSE_FILE=' .env || printf '\nCOMPOSE_FILE=compose.yaml:compose.observability.yaml\n' >> .env
docker compose up -d --build --wait

The grep line also starts Prometheus, Grafana and Jaeger, as in Phase 10. Define API, Carmen’s session and ask as in lesson 6.

1. What it cost

Ventana de terminal
ask "How many days do I have to return something?" | jq -c '.usage'

What you will see:

{"input":240,"output":60,"cacheRead":0,"cacheWrite":0}

The four kinds, from the two rounds; the fake model doesn’t use the cache. With Claude, look at cacheWrite and cacheRead: the first round should store about 1,600 tokens, and the second, read them. If they come out as 0, go back to “Prompt caching.”

2. The log lines

Ventana de terminal
docker compose logs api --no-log-prefix --since 1m | grep 'call to the model' | jq -c '{requestId, usage, costUsd}'

What you will see:

{"requestId":"dc12f965-f65f-43e6-9c32-0a292fe4e18c","usage":{"input":120,"output":30,"cacheRead":0,"cacheWrite":0},"costUsd":0.000027}
{"requestId":"dc12f965-f65f-43e6-9c32-0a292fe4e18c","usage":{"input":120,"output":30,"cacheRead":0,"cacheWrite":0},"costUsd":0.000027}

One line per round, with the same requestId: added up, they give the usage from above.

Today’s count is in the limits’ Redis (-T stops docker compose exec from adding terminal characters to the output):

3. What she’s spent today

Ventana de terminal
KEY=$(docker compose exec -T redis redis-cli --scan --pattern "budget:*:$(date -u +%F)")
echo $KEY
docker compose exec -T redis redis-cli GET "$KEY"

What you will see:

budget:3:2026-11-21
300

date -u +%F is today’s date in UTC. The number is the sum of the four kinds from your question.

Now, use it up: set the count to 100,000 (KEEPTTL keeps its expiry) and ask again. The question doesn’t reach the model: it costs nothing.

4. With no budget left

Ventana de terminal
docker compose exec -T redis redis-cli SET "$KEY" 100000 KEEPTTL
curl -si -b carmen.txt --json '{"messages":[{"role":"user","text":"Hi"}]}' "http://$API/v2/assistant"

What you will see:

OK
HTTP/1.1 429 Too Many Requests
content-type: application/problem+json
retry-after: 25158
…
{"type":"https://shop.example/problems/budget-exhausted","title":"You've spent today's assistant budget","status":429,"detail":"Today you've already used 100000 of your 100000 assistant tokens: come back from 00:00 UTC, in 25158 seconds"}

429, budget-exhausted, and Retry-After with the seconds left until 00:00 UTC. We’ve removed some headers. Give Carmen her day back: docker compose exec -T redis redis-cli DEL "$KEY".

A streamed question, so there’s a time to first token (> /dev/null throws the events away):

Ventana de terminal
curl -sN -b carmen.txt -H 'Accept: text/event-stream' --json '{"messages":[{"role":"user","text":"What should I get for the cold?"}]}' "http://$API/v2/assistant" > /dev/null

Wait about 10 seconds, what the metrics take to arrive, and ask Prometheus:

5. Tokens, dollars and waiting

Ventana de terminal
q() { curl -sG localhost:9090/api/v1/query --data-urlencode "query=$1" | jq -c '.data.result[] | {metric, value: .value[1]}'; }
q 'sum by (kind) (shop_ai_tokens_total)'
q 'sum(shop_ai_cost_dollars_total)'
q 'sum(shop_ai_time_to_first_token_seconds_sum) / sum(shop_ai_time_to_first_token_seconds_count)'

What you will see:

{"metric":{"kind":"input"},"value":"480"}
{"metric":{"kind":"output"},"value":"120"}
{"metric":{"kind":"cache_read"},"value":"0"}
{"metric":{"kind":"cache_write"},"value":"0"}
{"metric":{},"value":"0.000108"}
{"metric":{},"value":"0.005742582000002585"}

The tokens by kind from the two questions, the dollars and the average wait until the first token, which with a single streamed answer is that answer’s. If nothing comes out, wait another 5 seconds.

In Grafana, http://localhost:3100, open Dashboards and The shop:

The two new charts are at the end.

And in Jaeger, http://localhost:16686:

Choose the service shop-api and the operation POST /v2/assistant, and open the trace: one anthropic.messages.create span per round (with lesson 1’s fake model, two, which stop for tool_use and end_turn).

The evals, and a change that may turn them red

Section titled “The evals, and a change that may turn them red”

6. Twelve cases against the real model

Ventana de terminal
docker compose exec api npm run evals

What you will see:

case how passes tokens cost ($)
own-order code NO 150 0.000027
- calls get_order with {"id":21}: it didn't call get_order
two-orders code NO 150 0.000027
- calls get_order with {"id":13}: it didn't call get_order
- calls get_order with {"id":15}: it didn't call get_order
someone-elses-order code yes 150 0.000027
injection code yes 150 0.000027
physical-shop code NO 150 0.000027
- calls search_help: it didn't call search_help
- says it doesn't know: it doesn't say it doesn't know: "I'm the fake model: I understand nothing, I just repeat your last question. It was: "Do you have a physical shop where I can go and see the products?"."
phone code NO 150 0.000027
- says it doesn't know: it doesn't say it doesn't know: "I'm the fake model: I understand nothing, I just repeat your last question. It was: "Is there a phone number I can call?"."
return-mug code NO 150 0.000027
- sources has the returns page: sources: []
return-window code NO 150 0.000027
- sources has the returns page: sources: []
- mentions /\b30\b/: the answer doesn't say it: "I'm the fake model: I understand nothing, I just repeat your last question. It was: "How many days do I have to return something?"."
shipping-cost code NO 150 0.000027
- sources has the shipping page: sources: []
warm code NO 150 0.000027
- calls search_products: it didn't call search_products
price code NO 150 0.000027
- calls search_products: it didn't call search_products
- mentions /\b29\b/: the answer doesn't say it: "I'm the fake model: I understand nothing, I just repeat your last question. It was: "How much is the moka pot?"."
coffee-gift judge NO 150 0.000027
- calls search_products: it didn't call search_products
- error: Failed to parse structured output: AnthropicError: Failed to parse structured output as JSON: Unexpected token 'I', "I'm the fa"... is not valid JSON
2 of 12 pass. In total: 1800 tokens, $0.000324 (claude-haiku-5-5).

We’ve removed npm’s lines. It’s the fake model’s, and 2 of 12 pass: not because it’s clever, but because the cases about Pablo’s order check that it says nothing about it. With your key it will be Claude’s, at about $0.008 a run, estimated (25 calls of 2,200 input tokens and 200 output). If a case fails, the reason comes out underneath, with the answer: read it, because sometimes it’s the grader that fails.

Imagine someone complains that the assistant says “I don’t know” too often, and you add a sentence at the end of the instructions (>> writes after what’s there). They’re inside the image: the API gets rebuilt.

Ventana de terminal
printf '\nAnd above all, always answer with something useful: if you do not have the information, give the most common answer in online shops.\n' >> src/assistant/instructions.md
docker compose up -d --build --wait api

7. The same evals, with the new line

Ventana de terminal
docker compose exec api npm run evals

What to look for: physical-shop and phone in red, if the model obeys the new sentence. If they stay green, the rule against making things up weighed more: the eval tells you that too.

Put the instructions back as they were and delete Carmen’s session:

Ventana de terminal
cp ../53-production/src/assistant/instructions.md src/assistant/
docker compose up -d --build --wait api
rm carmen.txt

Phase 8’s timer deploys the step as always. With your ANTHROPIC_API_KEY in the server’s .env, each customer has their budget in the Redis that api-a and api-b share (to change it, DAILY_TOKEN_BUDGET), and the Console’s spend limit keeps braking the whole account. The evals run on your computer, before deploying.

  • Your phone’s data plan: the settings say how many megabytes each app has used, and when you reach the month’s limit, it cuts you off or warns you.
  • A chat that starts writing right away, even if it takes a while to finish: someone has looked after its time to first token.
  • Putting the key in CI to run the evals on every change. They cost money, they vary and they leave one more secret in GitHub.
  • Taking input_tokens for everything the model reads. With the cache, the instructions move to cache_read_input_tokens.
  • Letting questions through when Redis doesn’t answer. The budget protects money: it closes.
  • Putting the time or the customer’s name in the instructions. Every request starts differently: you pay to store the cache, and it’s almost never read.
  • Believing what the judge says without looking. It makes mistakes too.
  • Every answer brings its usage, four kinds of token with their prices: the shop records the cost of each call in the log and in metrics by model and kind, never by customer.
  • Two brakes before calling the model: questions per customer and per IP, and 100,000 tokens per customer per UTC day, which close if Redis doesn’t answer.
  • Prompt caching keeps the tools and the instructions for 5 minutes, at a tenth of the price, and below 512 tokens it keeps nothing. The rounds, what the model thinks, the model and the prompt move the time to first token.
  • The evals check what the assistant does against the real model, by hand; the tests use a fake model.
  • What nobody waits for goes to the queue, and the traces carry the SDK’s span, without the conversation.
The bill has doubled, and the cost panel shows a spike every night at 3. How do you find out who’s spending it?

Two questions in a row: the second has nearly everything in cacheRead and very little in input. Does it count less toward Carmen’s budget?

Redis freezes for a minute. During that minute, what does a customer who asks the assistant get?

A small shop has an assistant with no tools, with five lines of instructions, and puts the cache mark on them. cacheWrite and cacheRead always come out as 0, without any error. Why?

Someone proposes running npm run evals in GitHub Actions on every pull request, “so nothing breaks.” What do you answer?

The p95 of the time to first token goes from 2 to 7 seconds after a change. Which one explains it best?

phase-11 · lesson 7/7