Running AI data in production
Part of the free LogicWiz Data Engineering course, Module 16: Databases for AI agents. The SQL and Python run in the app, on real Postgres and real Python in the browser.
It is 9:30 on Monday, two weeks after launch. Tess has three things on her screen. The model bill: three times the forecast. A ticket: the assistant told a customer that refunds take 5 business days, and the page has said 3 since 12 June. And a screenshot: a customer's phone number, returned by the help search. Nora reads them and says: "Which conversations cost the money? Did last week's search change help? How did that number get in? We cannot answer one of these."
You'll learn to
- Log runs, model calls and tool calls, and cost them in SQL
- Measure search with an evaluation set, recall@k, MRR and nDCG
- Find stale and waiting chunks with one freshness query
- Redact personal data before embedding, and remove duplicate chunks
Learn
Three questions nobody can answer
The agent works. What is missing is everything around it. An agent is a pipeline that runs once per question, so it needs what every pipeline needs: logs, numbers and tests.
It takes four plain tables.
agent_runs: one row per question. Who asked, when, and how it ended: answered, handed over to a person, or failed.llm_calls: one row per call to a model, with its input tokens (what was sent) and output tokens (what came back). Providers charge per million tokens, and output costs several times more than input.tool_calls: one row per tool call, with its status and its time in milliseconds.- An evaluation set: questions with known right answers, run every night.
With these in place, "why did the bill triple?" is a GROUP BY.
Cost per run
SELECT l.run_id,
COUNT(*) AS model_calls,
SUM(l.input_tokens) AS input_tokens,
SUM(l.output_tokens) AS output_tokens,
ROUND(SUM(l.input_tokens * p.usd_per_m_input
+ l.output_tokens * p.usd_per_m_output) / 1000000, 4) AS cost_usd
FROM llm_calls AS l
JOIN model_prices AS p ON p.model = l.model
GROUP BY l.run_id
ORDER BY cost_usd DESC, l.run_id;
Tokens times the price per million, divided by a million. Run r-3 is at the top, with 0.1077 USD. The prices in model_prices are made up. Keep real ones in a table like this, with the date they apply from, never hard-coded in queries.
What the cost report shows
| Run | Model calls | Input tokens | Cost (USD) | What happened |
|---|---|---|---|---|
| r-3 | 6 | 33,000 | 0.1077 | The payments tool kept failing, and the agent kept retrying |
| r-1 | 2 | 3,900 | 0.0144 | Maya's order 1064: two calls, one tool |
| r-2 | 3 | 7,300 | 0.0134 | Mostly the small model; the large one only for the answer |
| r-4 | 1 | 1,700 | 0.0005 | One small-model call |
One run costs more than the other three together. The next picture opens it up.
Run r-3: input tokens sent at each step
Six bars for the six model calls of run r-3: 2,000 input tokens at step 1, then 3,400, 4,800, 6,200, 7,600 and 9,000 at step 6. The tool calls after steps 2, 3 and 4 failed after about five seconds each.
Read it top to bottom. Every step sends more than the one before, because it resends the whole conversation so far. The three red steps bought nothing: the same tool failed each time. Three calls that all stop at about 5,000 ms are the mark of a statement timeout.
Remember: a step limit, and a retry limit on every tool, are cost controls as much as safety.
One number for finance
Tess wants one number: what do 1,000 answered questions cost? Build it from parts.
- Model tokens. Last night's four runs cost 0.1361 USD in all. That is 0.0340 a run, or $34.02 per 1,000.
- Reranking: 1,000 × 26,000 tokens through a small model (Lesson 16.4).
- Embedding the questions: 1,000 × 20 tokens. A fraction of a cent.
- The database: a fixed monthly bill, divided by the month's questions.
But an average hides the shape. Run r-3 alone is 79% of the model cost. The middle run, the median, costs $13.92 per 1,000, less than half the mean. So report the median and the 95th percentile next to the mean. And report cost per resolved question: a cheap run that hands over to a person is not cheap.
From the logs to cost per 1,000
WITH run_cost AS (
SELECT l.run_id,
SUM(l.input_tokens * p.usd_per_m_input
+ l.output_tokens * p.usd_per_m_output) / 1000000 AS cost
FROM llm_calls AS l
JOIN model_prices AS p ON p.model = l.model
GROUP BY l.run_id
)
SELECT COUNT(*) AS runs,
ROUND(SUM(cost), 4) AS total_usd,
ROUND(AVG(cost) * 1000, 2) AS mean_per_1000,
ROUND((PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY cost) * 1000)::numeric, 2) AS median_per_1000,
ROUND(MAX(cost) / SUM(cost), 2) AS worst_run_share
FROM run_cost;
One row: 4 runs, 0.1361 USD, a mean of 34.02 and a median of 13.92 per 1,000, and a worst run with 0.79 of the cost. PERCENTILE_CONT(0.5) is the median. Use 0.95 for the 95th percentile on a real day's runs. With four runs the numbers are only an illustration. With a million they are the budget.
Cost per 1,000 questions, by part
Bars showing the cost per 1,000 questions: 34.02 USD of model tokens, 2.60 of reranking, 1.20 of database and almost nothing for embedding the questions.
Each bar is one part of the cost of 1,000 questions. All the prices are made up, so check where your own bars fall. Here the model's tokens dominate. The biggest levers are the number of steps, the size of what each step resends, and which model each step uses.
Did last week's change help?
Second question. Last week the search went from vectors only to hybrid (Lesson 16.4). Better or worse? Trying five questions by hand will not tell you.
Build an evaluation set: real questions, taken from tickets and search logs, each with the chunks a person marked as relevant. It is two tables. Run it every night, and before every change.
The first number to track is recall@k: of the relevant chunks for a question, what share appeared in the top k results? Lesson 16.2 used the same idea to test an index. Here "relevant" means what a person marked. If the model is given the top 2 chunks, recall@2 is the one that matters. Average it over all the questions, and count a question where nothing was found as 0.
Recall@2 per question, for two set-ups
SELECT runs.run_label,
e.question_id,
COUNT(*) AS relevant,
COUNT(r.chunk_id) AS found_in_top_2,
ROUND(COUNT(r.chunk_id)::numeric / COUNT(*), 2) AS recall_at_2
FROM eval_relevant AS e
CROSS JOIN (VALUES ('vector_only'), ('hybrid')) AS runs(run_label)
LEFT JOIN retrieved AS r
ON r.run_label = runs.run_label
AND r.question_id = e.question_id
AND r.chunk_id = e.chunk_id
AND r.rank <= 2
GROUP BY runs.run_label, e.question_id
ORDER BY runs.run_label, e.question_id;
Start from the relevant chunks and LEFT JOIN the results, so a relevant chunk that was not retrieved still counts, as a miss. The CROSS JOIN gives every question to both set-ups. Averaged, vector-only scores 0.75: it missed PAY-402 in its top 2. Hybrid scores 1.00. Last week's change was worth it.
Where in the list
Recall@k only asks whether the relevant chunks made the top k. The model reads the top of the list most carefully, so where they sit matters too. Two more numbers measure that.
- MRR, mean reciprocal rank. For each question take 1 / the rank of the first relevant chunk, or 0 if there is none. Rank 1 scores 1, rank 3 scores 0.33. Then average over the questions.
- nDCG@k, normalised discounted cumulative gain. A relevant chunk at rank i earns 1 / log2(i + 1): 1 at rank 1, 0.63 at rank 2, 0.5 at rank 3. Add up what the list earned, then divide by the best total that question could have had. The result runs from 0 to 1.
Step through one result list and score it all three ways.
One result list, scored three ways
Five steps scoring the list of chunks 5, 7 and 6 returned for question 2, whose only relevant chunk is 6: recall at 2 is 0, recall at 3 is 1.0, the reciprocal rank is 0.33 and nDCG at 3 is 0.5.
One question, one list. Question 2 asks about PAY-402. One chunk is relevant: chunk 6. Vector-only search returned chunks 5, 7 and 6, in that order.
recall@2. Look at the top 2 only. Chunk 6 is not there: 0 of the 1 relevant chunk was found. recall@2 = 0.
recall@3. Widen the window to 3. Chunk 6 is in: 1 of 1. recall@3 = 1.0, a perfect score for a list that has the answer last.
Reciprocal rank. The first relevant chunk sits at rank 3, so the score is 1 / 3 = 0.33.
nDCG@3. Rank 3 earns 1 / log2(4) = 0.5. The best possible list has chunk 6 at rank 1 and earns 1. So nDCG@3 = 0.5 / 1 = 0.5.
The left box is the list and never changes. Watch the right box fill in. recall@3 calls this list perfect. The other two numbers show that the answer sat lower than the model may read. With graded labels (2 = answers it, 1 = related), nDCG puts the grade on top of each fraction.
Both set-ups on all four questions (top 3)
| Question (relevant) | vectoronly top 3 | RR, nDCG@3 | hybrid top 3 | RR, nDCG@3 |
|---|---|---|---|---|
| 1 (chunks 1, 2) | 1, 2, 12 | 1, 1.0 | 1, 2, 6 | 1, 1.0 |
| 2 (chunk 6) | 5, 7, 6 | 0.33, 0.5 | 6, 5, 7 | 1, 1.0 |
| 3 (chunk 8) | 8, 11, 3 | 1, 1.0 | 8, 9, 10 | 1, 1.0 |
| 4 (chunks 5, 7) | 7, 5, 6 | 1, 1.0 | 7, 5, 6 | 1, 1.0 |
| Mean | MRR 0.83, nDCG 0.88 | MRR 1.00, nDCG 1.00 |
RR is the reciprocal rank. Question 1 has two relevant chunks at ranks 1 and 2: DCG = 1 + 1 / log2(3) = 1.63, which is also the best possible, so nDCG = 1. Question 2 is the list you stepped through. Means: (1 + 0.33 + 1 + 1) / 4 = 0.83 and (1 + 0.5 + 1 + 1) / 4 = 0.875.
MRR and nDCG@3 in SQL
WITH hits AS (
SELECT r.run_label, r.question_id, r.rank
FROM retrieved AS r
JOIN eval_relevant AS e
ON e.question_id = r.question_id AND e.chunk_id = r.chunk_id
WHERE r.rank <= 3
),
per_question AS (
SELECT runs.run_label,
q.question_id,
COALESCE(1.0 / MIN(h.rank), 0) AS rr,
COALESCE(SUM(1 / LOG(2, h.rank + 1)), 0) AS dcg,
(SELECT SUM(1 / LOG(2, i + 1))
FROM generate_series(1, LEAST(3, (SELECT COUNT(*) FROM eval_relevant AS e2
WHERE e2.question_id = q.question_id))) AS i) AS idcg
FROM eval_questions AS q
CROSS JOIN (SELECT DISTINCT run_label FROM retrieved) AS runs
LEFT JOIN hits AS h ON h.run_label = runs.run_label AND h.question_id = q.question_id
GROUP BY runs.run_label, q.question_id
)
SELECT run_label,
ROUND(AVG(rr), 2) AS mrr,
ROUND(AVG(dcg / idcg), 2) AS ndcg_at_3
FROM per_question
GROUP BY run_label
ORDER BY run_label;
Hybrid scores 1.00 on both. Vector-only scores 0.83 and 0.88, although its recall@3 is perfect. Start from all questions and LEFT JOIN the hits, so a question with nothing found scores 0 and does not vanish. MIN(rank) is the first relevant hit. The best possible DCG sums the discounts for ranks 1 to min(3, relevant chunks). LOG(2, x) is the base-2 logarithm.
The three metrics in Python
import math
def recall_at_k(retrieved, relevant, k):
"""Fraction of the relevant ids found in the first k retrieved ids."""
return len(set(retrieved[:k]) & set(relevant)) / len(relevant)
def reciprocal_rank(retrieved, relevant):
for rank, chunk_id in enumerate(retrieved, start=1):
if chunk_id in relevant:
return 1 / rank
return 0.0
def ndcg_at_k(retrieved, relevant, k):
dcg = sum(1 / math.log2(rank + 1) for rank, c in enumerate(retrieved[:k], start=1) if c in relevant)
ideal = sum(1 / math.log2(rank + 1) for rank in range(1, min(k, len(relevant)) + 1))
return dcg / ideal
relevant = {1: [1, 2], 2: [6], 3: [8], 4: [5, 7]}
runs = {
"vector_only": {1: [1, 2, 12], 2: [5, 7, 6], 3: [8, 11, 3], 4: [7, 5, 6]},
"hybrid": {1: [1, 2, 6], 2: [6, 5, 7], 3: [8, 9, 10], 4: [7, 5, 6]},
}
for label, results in runs.items():
mean = lambda f: sum(f(results[q], relevant[q]) for q in relevant) / len(relevant)
print(f"{label:12} recall@2 {mean(lambda r, g: recall_at_k(r, g, 2)):.2f}"
f" MRR {mean(reciprocal_rank):.2f} nDCG@3 {mean(lambda r, g: ndcg_at_k(r, g, 3)):.2f}")
The same three numbers in Python, the language evaluation code is usually written in: a notebook or a scheduled job. The results go back into a table, so a dashboard can chart recall night by night next to cost.
Is the index still fresh?
Now the ticket. The assistant quoted a 5-day refund, and the page has said 3 days since 12 June.
An index goes stale in two ways. A document is edited after its chunks were embedded, so search still returns the old text. Or new chunks are still waiting for an embedding, so search cannot find them at all. One query finds both.
Is the index fresh?
SELECT d.doc_id,
d.title,
d.updated_at,
MIN(c.embedded_at) AS oldest_embedding,
COUNT(*) FILTER (WHERE c.embedding IS NULL) AS waiting
FROM documents AS d
JOIN chunks AS c ON c.doc_id = d.doc_id
WHERE d.deleted_at IS NULL
GROUP BY d.doc_id, d.title, d.updated_at
HAVING MIN(c.embedded_at) < d.updated_at
OR COUNT(*) FILTER (WHERE c.embedding IS NULL) > 0
ORDER BY d.doc_id;
Two rows. The refund page was edited on 12 June and its chunks were embedded on 1 May: that is the 5-day answer. The payments page has one chunk still waiting. Alert when either lasts longer than your freshness target, like a late table in Module 7. Lesson 16.3's check for deleted documents that still have chunks belongs in the same job.
Two ways an index goes stale
Four live documents: Delivery times and Northwind returns are fresh, Returns and refunds was edited on 12 June after its chunks were embedded on 1 May, and Payment problems has one chunk still waiting for an embedding.
Each box is one live document. The freshness query returns the red one and the amber one, and leaves the green ones out.
A phone number in the index
Last, the phone number. Help pages are safe. But the assistant is also fed tickets, chats and order notes, and those hold emails, phone numbers and sometimes card numbers. Data that identifies a person is called PII, personally identifiable information.
Anything you embed is copied twice: into the chunks table, and to the embedding provider. Once a phone number is in the index, a clever question can bring it back.
So redact before you embed: replace personal data with placeholders such as [email]. Regular expressions catch the easy patterns. Dedicated detectors, such as Microsoft Presidio or your cloud's PII detection, catch names and addresses too. Keep the original in the source system, where access and deletion are controlled.
A first redaction pass
import re
EMAIL = re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+")
CARD = re.compile(r"\b(?:\d[ -]?){12,15}\d\b") # 13 to 16 digits, spaces or dashes allowed
PHONE = re.compile(r"\+?\d[\d -]{7,}\d") # 9 or more digits and spaces
def redact(text):
text = EMAIL.sub("[email]", text)
text = CARD.sub("[card]", text) # before phones: a card number also looks like a phone number
text = PHONE.sub("[phone]", text)
return text
ticket = ("Order 1012 never came. Call me on +47 22 12 34 56 or write to "
"[email protected]. I paid with 4111 1111 1111 1111.")
print(redact(ticket))
The phone number, the email and the card are gone. Order 1012 survives, because it is too short to be a phone or a card. The order of the rules matters: run the phone rule first and the card number becomes [phone]. Test redaction with real-looking samples, then try this lesson's trap.
The same footer, forty times
One more piece of hygiene. The same paragraph often sits in many documents: a footer, a legal notice, a returns policy pasted into every product page. If it is indexed 40 times, a question about returns gets the same text three times in its top 3, and two of the model's slots are wasted.
Remove duplicates twice. When indexing, hash the tidied text (Lesson 16.3) and store each distinct chunk once, linked to every document that contains it. When retrieving, keep one result per hash, with DISTINCT ON (content_hash), before you take the top k.
For near-duplicates, the same text with one word changed, compare embeddings. Two chunks with a cosine similarity above about 0.98 are usually the same content.
Logs are personal data too. The prompts, tool arguments and answers you log contain exactly what you redacted from the index: names, addresses, order details. Redact before logging, limit who can read the logs, and give them a retention period. And keep the evaluation set honest. If you tune chunk size on the same 50 questions you report, the score flatters you. Hold some questions back, and add new ones from real failures every week.
Numbers to remember
| What | How it is worked out | Good to know |
|---|---|---|
| Cost of a run | Tokens × price per million / 1,000,000, input and output apart | Output tokens cost several times more than input |
| Last night's four runs | 0.1361 USD: a mean of $34.02 per 1,000 and a median of $13.92 | One looping run was 79% of it |
| recall@k | Relevant chunks in the top k / relevant chunks | It divides by the number of relevant chunks, not by k. "What share of what we returned was relevant" is a different number, precision |
| Reciprocal rank | 1 / the rank of the first relevant chunk, 0 if none | MRR is its mean over the questions |
| nDCG@k | The sum of grade / log2(rank + 1) over the top k, divided by the best possible sum | Rank 1 earns 1, rank 2 0.63, rank 3 0.5 |
| Median and 95th percentile in SQL | PERCENTILECONT(0.5) and PERCENTILECONT(0.95) | Written with WITHIN GROUP (ORDER BY cost) |
| Near-duplicate chunks | Cosine similarity above about 0.98 | Usually the same content with a word changed |
LLM observability tools such as Langfuse, LangSmith, Arize Phoenix and MLflow Tracing record runs, steps, tokens and costs as traces, and the OpenTelemetry GenAI conventions standardise the field names (input and output token counts, model name). Ragas and similar libraries compute retrieval and answer metrics. Many teams also land traces in the warehouse as tables like these, where cost can be joined to customers and outcomes. Teams track answer quality as well, often graded by another model, but retrieval comes first: the model cannot use a chunk it never saw.
What changed at SwiftKart
By Friday Tess has a dashboard with an answer to each question.
The bill: one kind of run, the tool that times out and is retried, was most of it. Every tool now has a retry limit, and cost per 1,000 questions is charted every morning. The search: hybrid scores 1.00 on recall@2 where vectors alone scored 0.75, and the evaluation set runs every night. The refund page was embedded again, and a freshness check watches for the next one. Tickets are redacted before they are embedded, and before they are logged.
One chart still worries Nora: search gets slower every week as the index grows. Lesson 16.8 opens the vector index to see why.
In one line
Log runs, model calls and tool calls to know what each answer costs, measure retrieval every night with an evaluation set, check freshness, redact personal data before embedding and logging, and remove duplicates.
Interview corner
How do you evaluate a retrieval system?
Build an evaluation set of real questions, each labelled with the chunks that answer it, and run it nightly and before every change. Measure recall@k at the k the model is given, MRR for how high the first relevant chunk sits, and nDCG@k, which discounts each hit by 1 / log2(rank + 1) and handles graded labels. They disagree usefully: a chunk found third gives recall@3 of 1.0 but a reciprocal rank of 0.33 and nDCG@3 of 0.5. Average over all questions, including those with zero hits, and keep some questions held out.
How would you monitor and control the cost of an agent?
Log every model call with its run, model, and input and output tokens, keep prices in a table, and compute cost per run, per customer and per feature in the warehouse. Watch for runs with many steps, since each step resends the growing conversation. Control it with step limits, retry limits on failing tools, smaller models for simple steps, caching, and alerts on cost per run.
How do you handle personal data in a RAG pipeline?
Redact before embedding and before logging, using a PII detector rather than only regular expressions, because embedded text is stored in the index and sent to the embedding provider. Filter retrieval by the user's rights, so one customer's data cannot reach another. Keep originals in the source system and make deletion requests remove chunks, vectors, memories and logs too.
Finance asks what the assistant costs. What do you report?
Cost per 1,000 questions, built from logged tokens times a price table: model calls, reranking and embeddings per question, plus fixed costs such as the database spread over monthly volume. Then the distribution, not just the mean: in our logs one looping run was 79% of the model cost and the median was $13.92 per 1,000 against a mean of $34.02. I would add cost per resolved question, because a run that hands over to a person costs the model bill and an agent's time, and break it down by route and model so the expensive path is visible.