Ravindra BagaleCourses & study guides Track your progress

Generative AI

Batch-Tag a CSV with an LLM in Python: Fixed Labels, Checkpoints and Accuracy

Generative AI course · Build with Gen AI (APIs, RAG) · Estimated reading time: 22 minutes, plus the lab

Every evening the support team at Annapurna Tiffins exports the day's tickets into a CSV file and asks one question: how many were about late delivery, how many about missing items, and how many need a refund? A developer writes a ten-line loop that sends each ticket to an AI model and prints the answer. The first night the loop crashes at row 140, and the next run starts again from row 1 and pays for the same 140 rows twice. The second night the model replies “Delivery Delay” for some rows, which is not one of the team's labels, and the report counts a category that does not exist. Today we will build the careful version of that loop, step by step, and test all of it offline.

This lab joins two earlier chapters. From the JSON validation chapter we take strict checking of every reply. From the API errors chapter we take retries with backoff and a cost budget. Here we add what a whole file needs: a fixed label list, a stable id for every row, a checkpoint so that a crash never costs money twice, an error file, and a simple accuracy check.

What you will learn in this chapter

  1. You will choose a fixed label list and keep every reply inside that list.
  2. You will give every CSV row a stable id, so that the same row is never paid for twice.
  3. You will validate each reply, retry bad rows a few times, and move rows that still fail into a separate error file.
  4. You will save a checkpoint after every row and resume after a crash without repeating finished work.
  5. You will estimate the worst-case cost before the first call and stop if it does not fit the budget.
  6. You will measure accuracy against a small gold set and do a quick human spot check.

Everything in this chapter is made up for learning

Synthetic classroom data only. Annapurna Tiffins and all twenty-one tickets in the lab are fictional and hand typed, and they contain no real names, phone numbers or addresses. The lab uses a fake model called FakeTagger, so it needs no API key, no internet and no installation beyond Python. The prices are made-up teaching “units,” not any provider's real price. Before you send real customer tickets to any AI service, remove personal details and follow your company's data policy, as explained in the privacy chapter.

1. Why a simple loop is not enough for a whole file

A loop that works for five rows can still fail badly for five thousand rows. The table below lists the problems that appear only at file size, and the part of this lab that fixes each one.

Problems that appear when you tag a whole CSV file, and the fix used in this lab.
ProblemWhat goes wrongFix in this lab
The model invents a new label.The report shows categories that the team never agreed on.A fixed label list, checked in code for every reply.
A reply is not valid JSON.The program crashes or saves rubbish in the output file.Strict validation, then a retry with a short note about the mistake.
The API returns 429 or a server error.One temporary error stops the whole job.A few retries with backoff, then the row goes to the error file.
The program crashes half way.The next run starts from row 1 and pays again for finished rows.A checkpoint file and a stable id for every row.
The file has empty or repeated rows.Money is spent on rows that need no answer.Empty rows go straight to the error file, and exact duplicates are skipped.
Nobody knows the cost until the bill arrives.A large file quietly spends more than planned.A worst-case estimate before the first call, with a budget check.
Nobody checks the quality.Wrong labels go straight into a management report.Accuracy against a small gold set, plus a human spot check.

2. Plan the job before you write code

A tagging job is easier to build when you decide the important things first. Follow these steps in order, and write the answers in a short note that the whole team can read.

  1. Write the fixed label list, with a one-line meaning for each label.
  2. Decide which columns the output file needs, for example the ticket id, the label, the urgency and a short reason.
  3. Tag twenty tickets by hand. These hand labels become your gold set, which is the answer key you compare the model with.
  4. Run the job on five rows and look at every reply yourself.
  5. Estimate the worst-case cost for the whole file and compare it with your budget.
  6. Run the whole file, then read the error file and check the accuracy before anyone uses the numbers.

3. Choose a fixed label list

A fixed label list means that every ticket must get exactly one label from a short list that you decided in advance. The model is not allowed to invent a new label. This makes the output easy to count, easy to filter in Excel and easy to compare with the gold set. Our lab uses the five labels from the Module 8 example in the course outline, and each ticket also gets an urgency of low, medium or high.

The label list used in the lab.
LabelMeaningExample synthetic ticket
late_deliveryThe food came late or has not come at all.Rider came 50 minutes late again.
missing_itemSomething that was ordered was not in the box.Curd packet was missing.
refundThe customer asks for money back or was charged wrongly.Please refund the cancelled dinner order.
food_qualityThe food tasted, smelled or looked wrong.Too much salt in the paneer today.
otherThe ticket fits none of the labels above.Do you have a Jain menu?

The labels are written in lower case with underscores, and no two labels differ only in capital letters. That choice matters, as section 5 explains. The lab keeps the list in one Python tuple called LABELS, and it builds a JSON Schema called LABEL_SCHEMA from the same tuple, so the prompt, the schema and the validation code can never disagree.

Ravindra Bagale's Tip

Write your label list on paper before you write any code. If two labels sound similar, such as “refund” and “payment problem,” the model will mix them up and so will your team. Keep the list short, give every label a one-line meaning, and always keep an “other” label for tickets that fit nowhere.

4. Give every row a stable id

An id is stable when the same row always gets the same id, on every run and on every computer. Our function row_id() joins the ticket id with the first ten characters of a SHA-256 fingerprint of the ticket text. The Python hashlib documentation describes sha256(). Before the fingerprint is made, the text is changed to lower case and extra spaces are removed, so a stray space does not create a new id.

What happens to the row id in common situations.
SituationRow idResult in the job
The same ticket appears in the next export.Same id as before.The checkpoint already has it, so it is not sent again.
The same ticket appears twice in one file.Same id twice.The second copy is skipped as a duplicate.
Someone edits the ticket text.A new id.The edited ticket is tagged again, which is what we want.
The ticket text is empty.An id is still made.The row goes to the error file without any API call.

The id uses only letters, digits, hyphens and underscores, and it is never longer than 64 characters. Anthropic's batch processing guide gives exactly this rule for its custom_id field, so the same id can later be reused if you move the job to a provider batch API.

5. Validate every reply before you save it

The model's reply is only text until your code has checked it. Our function validate_reply() uses the same strict approach as the JSON validation chapter, and it checks the reply in this order.

  1. Parse the reply as JSON. If parsing fails, the error is not_json.
  2. Check that the reply is a JSON object and that it has no extra keys.
  3. Check that label, urgency and reason are present and are not empty.
  4. Change the label and the urgency to lower case, then check that each one is in its allowed list.
  5. Clean up the reason and cut it to 120 characters, so that one long reply cannot break the output file.
Example replies and what the validator decides.
Reply from the modelValidator resultWhat the job does
{"label": "refund", "urgency": "medium", "reason": "asks for money back"}Valid.Saves the row.
{"label": "Late_Delivery", ...}Valid after changing it to lower case.Saves the row as late_delivery.
Sure! The label is refund.not_jsonRetries with a short note about the mistake.
{"label": "menu_question", ...}bad_labelRetries, and after the last attempt moves the row to the error file.
{"label": "refund", "reason": "..."}missing_urgencyRetries with a short note about the mistake.

Real providers can enforce a schema for you, but their own documentation still asks you to check the result. We opened each page on 16 November 2026 (IST).

  • OpenAI's Structured Outputs guide says that required fields and enum values follow the JSON Schema you supply. It also says that your application must still handle refusals, incomplete responses and API errors, and must validate any business rules that the schema does not express.
  • Anthropic's structured outputs page says the output can fail to match the schema when the model refuses or when the reply is cut off by the max_tokens limit. It also says that the capital letters of string enum values are not guaranteed, so you should compare enum values without caring about capital letters and avoid labels that differ only in capital letters. That is why our validator changes labels to lower case.
  • Google's Gemini structured output page shows an enum used for classification, and it advises you to always validate the values in your application, because a reply can be correct JSON and still be wrong in meaning.

6. Retry a bad row a few times, then move it to the error file

Our function tag_row() handles one row and never crashes the whole job. It deals with two kinds of failure in two different ways.

  1. If the API raises a temporary error, such as a 429 rate limit, the function waits a short random time that grows after each failure, and then tries again. The API errors chapter explains this backoff in detail, including the Retry-After header.
  2. If the reply arrives but fails validation, the function tries again and adds one sentence to the instructions that names the mistake, for example “Your last reply was rejected (not_json).”
  3. After the last allowed attempt, the function returns the row with the status error and the last error message, instead of raising an exception.
  4. The job writes every error row into tickets_errors.csv, so a person can look at it later.

This is called quarantine. A bad row is moved to one side, the rest of the file carries on, and no wrong answer is ever written into the main output file. In the lab, the ticket “Do you have a Jain menu?” keeps getting the invented label menu_question, and it ends up in the error file after three attempts.

7. Save a checkpoint after every row and resume after a crash

A checkpoint is a small file that remembers which rows are already finished. Our lab uses a JSON Lines file called checkpoint.jsonl, which means one JSON object on each line. Each line holds the row id, the result, the number of attempts and the token usage.

  1. When the job starts, it reads the checkpoint and collects the ids of the finished rows.
  2. It skips every row whose id is already in the checkpoint, so those rows cost nothing.
  3. After each new row, it adds one line to the checkpoint and forces the line onto the disk with flush() and os.fsync().
  4. If the computer stops in the middle of writing a line, the next run ignores that broken last line and simply tags that row again.
  5. By default, rows that ended in the error file are not retried on the next run. When you have fixed the cause, run the job with retry_errors=True, and only the error rows are sent again.

The output CSV files are always rebuilt from the checkpoint at the end of a run, and they are written to a temporary file first. The temporary file is then renamed with os.replace(). The Python os documentation says that a successful rename is an atomic operation on POSIX systems, which means anyone who opens the file sees either the old complete file or the new complete file, never half of one.

Ravindra Bagale's Tip

Run the job twice on purpose during testing. The second run should make zero API calls. If it makes even one call for a row that was already finished, your checkpoint is broken, and a broken checkpoint means you will pay again for the same work after every crash.

8. Estimate the cost before the first call

The job estimates the worst-case cost of the rows that still need tagging, before it sends anything. If the estimate is bigger than the budget you set, the job stops at once with a BudgetTooSmall error and makes no call at all.

How the lab calculates the worst-case cost estimate.
PartHow it is calculated
Input tokens for one rowThe characters in the instructions plus the characters in the ticket, divided by four, as a rough rule.
Output tokens for one rowThe full output token limit that we set on the request, which is 60 in the lab.
AttemptsBoth numbers are multiplied by the maximum attempts, because in the worst case every row needs every attempt.
CostInput tokens times the input price per million, plus output tokens times the output price per million, all divided by one million.

The rule of about four characters per token comes from Google's token counting page, which describes Gemini models. Other models count tokens differently, so treat it only as a rough planning number. After each real reply, the lab records the actual usage numbers, and at the end it prints the real amount spent. In the demo the worst case is 0.018567 units and the real spend is 0.003562 units, because most rows succeed on the first attempt and short replies use far fewer than 60 output tokens.

The lab prices of 1.00 and 4.00 units per million tokens are made up. Prices differ by model and change over time, so copy the current price for your chosen model from the provider's pricing page on the day you run the job.

9. Write the output file and the error file safely

The job writes two CSV files with Python's csv.DictWriter. The Python csv documentation says that a CSV file should be opened with newline='', and the lab does this for both reading and writing, so that line breaks inside a ticket do not break the rows.

Columns in the output file tickets_tagged.csv.
ColumnMeaning
row_idThe stable id of the row, made from the ticket id and a fingerprint of the text.
ticket_idThe ticket number copied from the input file.
textThe ticket text, made safe for spreadsheets.
labelOne label from the fixed list.
urgencyLow, medium or high.
reasonA short reason from the model, at most 120 characters.
attemptsHow many attempts the row needed.
Columns in the error file tickets_errors.csv.
ColumnMeaning
row_idThe stable id of the row.
ticket_idThe ticket number copied from the input file.
textThe ticket text, made safe for spreadsheets.
errorThe last error, such as empty_text, not_json, bad_label or transient.
attemptsHow many attempts were made before the row was moved here. Empty rows show zero.

There is one more safety step. If a cell starts with =, +, - or @, a spreadsheet program may treat the text as a formula when someone opens the file. A customer could type such text on purpose. Our function safe_cell() puts a single quote in front of those cells, so the spreadsheet shows them as plain text. In the lab, ticket T015 starts with “=2+3” to show this. The quote does change the stored text slightly, so keep the original input file if you need the exact words.

10. Check the quality with a gold set and a spot check

A finished job is not the same as a correct job. The lab checks quality in two simple ways.

  1. The function evaluate() compares the model's label with the gold label for every ticket that has both. It reports how many were compared, how many were correct, the accuracy, the count for each label and the list of mistakes.
  2. The function spot_check_sample() picks five tagged rows at random, using a fixed seed so that the same rows come back every time. A person reads those five rows and writes the correct label for each one.
  3. The function agreement() then shows the share of the spot-checked rows where the person and the model chose the same label.
Quality numbers from the lab demo (synthetic data).
MeasureResult in the demoWhat it tells us
Accuracy against the gold set15 correct out of 17, which is 0.882.Most labels are right, but two are wrong.
Gold rows not tagged2 rows.These rows are in the error file and need a person or a re-run.
Spot-check agreement4 of 5 rows, which is 80%.A person disagreed with the model on one random row.

Read the two mistakes carefully, because they teach more than the score. Ticket T011 says the food was late and also cold, and the gold set calls it food_quality while the model chose late_delivery. That is a label-rule problem, so the team should decide which label wins when a ticket has two problems and write that rule into the instructions. Ticket T012 says “Great, the rice arrived an hour after lunch time,” which is sarcasm about a late delivery, and the simple model missed it. The evaluation set chapter shows how to grow a gold set like this one over time.

Ravindra Bagale's Tip

Never trust the job just because it finished. Before you share the tagged file, open the error file first, then read five random tagged rows yourself. If even one of the five looks wrong, check twenty more before anyone uses the numbers in a report.

11. Run the offline lab

Save the two files below in one folder. Use Python 3.9 or newer. No package installation is needed. Run python3 -B csv_tagger.py to see the demo, then run python3 -B -m unittest -v test_csv_tagger. You should see 55 tests pass. The tests also run with pytest if you have it installed. The demo creates a folder called lab_output next to the script, so you can open the CSV files and the checkpoint afterwards.

Demo output (synthetic)

Read 19 rows to tag, 1 empty row, 1 duplicate skipped
Worst-case estimate: 4887 in + 3420 out tokens = 0.018567 units
Run 1 crashed on purpose: stopped after 8 rows; calls so far 9
Run 2 resumed: skipped 8 finished rows, made 16 calls
Tagged 17, error rows 3, total spent 0.003562 units
  error row T010: bad_label:menu_question after 3 attempts
  error row T019: transient:429 rate limit (fake) after 3 attempts
  error row T017: empty_text after 0 attempts
  T015 starts with = so it is stored as plain text: '=2+3 please
Run 3 (nothing new): 0 calls
Accuracy against the gold set: 15/17 = 0.882 (2 gold rows were not tagged)
  mistake T011: gold food_quality, model late_delivery
  mistake T012: gold late_delivery, model other
Spot-check sample: T001, T005, T007, T012, T020 - agreement 80%
Files written: lab_output/out/tickets_tagged.csv, tickets_errors.csv, checkpoint.jsonl

Test runner tail

Ran 55 tests in 0.060s
OK

Read the demo from top to bottom. The file has 21 lines of tickets, but one is empty and one is an exact duplicate, so only 19 rows need the model. Run 1 stops on purpose after 8 rows, like a power cut. Run 2 skips those 8 finished rows and tags the rest. Run 3 finds nothing new and makes zero calls. The error file holds the menu question with an invented label, the ticket that kept getting 429 errors, and the empty row.

csv_tagger.py

"""Batch-tag a CSV of support tickets with an LLM, safely. Offline lab, standard library only.

SYNTHETIC classroom data: Annapurna Tiffins and every ticket below are made up.
FakeTagger plays the AI model, so no API key and no internet are needed.
Prices are made-up teaching "units", not any provider's real price.
"""
import csv, hashlib, io, json, math, os, random, re, tempfile
from decimal import Decimal

LABELS = ("late_delivery", "missing_item", "refund", "food_quality", "other")
URGENCY = ("low", "medium", "high")
MAX_REASON = 120
# JSON Schema you could pass to a provider's structured-output feature. Still validate every reply.
LABEL_SCHEMA = {
    "type": "object",
    "properties": {
        "label": {"type": "string", "enum": list(LABELS)},
        "urgency": {"type": "string", "enum": list(URGENCY)},
        "reason": {"type": "string"},
    },
    "required": ["label", "urgency", "reason"],
    "additionalProperties": False,
}
INSTRUCTIONS = (
    "You tag customer support tickets for a tiffin service. "
    "Choose exactly one label: late_delivery, missing_item, refund, food_quality or other. "
    "Choose urgency: low, medium or high. Give a short reason. "
    'Reply with JSON only, like {"label": "refund", "urgency": "medium", "reason": "asks for money back"}.'
)
OUT_FIELDS = ["row_id", "ticket_id", "text", "label", "urgency", "reason", "attempts"]
ERR_FIELDS = ["row_id", "ticket_id", "text", "error", "attempts"]
ID_RE = re.compile(r"^[a-zA-Z0-9_-]{1,64}$")  # safe as a batch custom_id too


class TransientAPIError(Exception):
    """Stands for 429, 5xx or a timeout from a real provider."""


class SimulatedCrash(Exception):
    """Used by the demo and tests to stop a run half way, like a power cut."""


class BudgetTooSmall(Exception):
    pass


# ---------- 1. Read rows and give each one a stable id ----------
def row_id(ticket_id, text):
    """Same ticket and same text always give the same id. Changed text gives a new id."""
    clean = " ".join(text.split()).lower()
    digest = hashlib.sha256(clean.encode("utf-8")).hexdigest()[:10]
    safe_ticket = re.sub(r"[^a-zA-Z0-9_-]", "_", ticket_id.strip())[:40] or "row"
    return f"{safe_ticket}-{digest}"


def read_tickets(path):
    """Return (rows to tag, rows rejected before any API call, duplicates skipped)."""
    rows, rejected, seen, dupes = [], [], set(), 0
    with open(path, newline="", encoding="utf-8") as f:
        for rec in csv.DictReader(f):
            tid = (rec.get("ticket_id") or "").strip()
            text = (rec.get("text") or "").strip()
            rid = row_id(tid, text)
            if rid in seen:
                dupes += 1
                continue
            seen.add(rid)
            row = {"row_id": rid, "ticket_id": tid, "text": text}
            if not text:
                rejected.append(dict(row, error="empty_text", attempts=0))
            else:
                rows.append(row)
    return rows, rejected, dupes


# ---------- 2. Estimate cost before spending anything ----------
def estimate_tokens(text):
    return math.ceil(len(text) / 4)  # rough rule: about 4 characters per token


def estimate_cost(rows, max_output_tokens, price_in, price_out, max_attempts=1):
    """Worst case for the given rows: every attempt used and the full output limit."""
    tin = sum(estimate_tokens(INSTRUCTIONS) + estimate_tokens(r["text"]) for r in rows) * max_attempts
    tout = len(rows) * max_output_tokens * max_attempts
    cost = (Decimal(tin) * Decimal(price_in) + Decimal(tout) * Decimal(price_out)) / Decimal(1_000_000)
    return {"rows": len(rows), "input_tokens": tin, "output_tokens": tout, "cost": cost}


def cost_of(usage, price_in, price_out):
    return (Decimal(usage["input_tokens"]) * Decimal(price_in)
            + Decimal(usage["output_tokens"]) * Decimal(price_out)) / Decimal(1_000_000)


# ---------- 3. Validate one reply ----------
def validate_reply(text):
    """Return (data, None) when the reply is usable, or (None, error_text)."""
    try:
        data = json.loads(text)
    except (json.JSONDecodeError, TypeError):
        return None, "not_json"
    if not isinstance(data, dict):
        return None, "not_an_object"
    extra = set(data) - {"label", "urgency", "reason"}
    if extra:
        return None, "extra_keys:" + ",".join(sorted(extra))
    for key in ("label", "urgency", "reason"):
        if not isinstance(data.get(key), str) or not data[key].strip():
            return None, "missing_" + key
    label = data["label"].strip().lower()       # compare labels without caring about capital letters
    urgency = data["urgency"].strip().lower()
    if label not in LABELS:
        return None, "bad_label:" + data["label"][:30]
    if urgency not in URGENCY:
        return None, "bad_urgency:" + data["urgency"][:30]
    reason = " ".join(data["reason"].split())[:MAX_REASON]
    return {"label": label, "urgency": urgency, "reason": reason}, None


# ---------- 4. Tag one row with retries ----------
def tag_row(client, row, max_attempts=3, max_output_tokens=60, sleep=lambda s: None, rng=None):
    """Return a result dict with status 'done' or 'error'. Never raises for one bad row."""
    rng = rng or random.Random(0)
    usage = {"input_tokens": 0, "output_tokens": 0}
    note, last_error = "", "unknown"
    for attempt in range(1, max_attempts + 1):
        try:
            reply = client.complete(INSTRUCTIONS + note, row["text"], row["row_id"], max_output_tokens)
        except TransientAPIError as e:
            last_error = "transient:" + str(e)
            if attempt < max_attempts:
                sleep(rng.uniform(0, min(8, 2 ** (attempt - 1))))  # capped backoff, full jitter
            continue
        usage["input_tokens"] += reply["usage"]["input_tokens"]
        usage["output_tokens"] += reply["usage"]["output_tokens"]
        data, err = validate_reply(reply["text"])
        if data:
            return dict(row, status="done", attempts=attempt, usage=usage, **data)
        last_error = err
        note = f" Your last reply was rejected ({err}). Reply with JSON only and use one allowed label."
    return dict(row, status="error", attempts=max_attempts, usage=usage, error=last_error)


# ---------- 5. Checkpoint: one JSON line per finished row ----------
def load_checkpoint(path):
    done = {}
    if not os.path.exists(path):
        return done
    with open(path, encoding="utf-8") as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            try:
                rec = json.loads(line)
            except json.JSONDecodeError:
                continue  # a half-written last line after a crash is ignored
            done[rec["row_id"]] = rec
    return done


def append_checkpoint(path, rec):
    with open(path, "a", encoding="utf-8") as f:
        f.write(json.dumps(rec, ensure_ascii=False) + "\n")
        f.flush()
        os.fsync(f.fileno())


# ---------- 6. Safe CSV writing ----------
def safe_cell(value):
    """Stop spreadsheet formula injection: text starting with = + - @ is shown as plain text."""
    s = str(value)
    return "'" + s if s[:1] in ("=", "+", "-", "@", "\t", "\r") else s


def write_csv_atomic(path, fields, rows):
    folder = os.path.dirname(os.path.abspath(path))
    fd, tmp = tempfile.mkstemp(dir=folder, suffix=".tmp")
    with os.fdopen(fd, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=fields, extrasaction="ignore")
        w.writeheader()
        for r in rows:
            w.writerow({k: safe_cell(r.get(k, "")) for k in fields})
    os.replace(tmp, path)  # readers see the old file or the new file, never half a file


# ---------- 7. The whole job ----------
def run_job(input_csv, out_dir, client, budget, price_in, price_out, max_output_tokens=60,
            max_attempts=3, retry_errors=False, crash_after=None, sleep=lambda s: None):
    os.makedirs(out_dir, exist_ok=True)
    ckpt = os.path.join(out_dir, "checkpoint.jsonl")
    rows, rejected, dupes = read_tickets(input_csv)
    done = load_checkpoint(ckpt)
    pending = [r for r in rows if r["row_id"] not in done
               or (retry_errors and done[r["row_id"]]["status"] == "error")]
    est = estimate_cost(pending, max_output_tokens, price_in, price_out, max_attempts)
    if est["cost"] > Decimal(budget):
        raise BudgetTooSmall(f"worst case {est['cost']} > budget {budget} for {len(pending)} rows")
    calls_before = client.calls
    for i, row in enumerate(pending):
        if crash_after is not None and i >= crash_after:
            raise SimulatedCrash(f"stopped after {i} rows")
        res = tag_row(client, row, max_attempts, max_output_tokens, sleep)
        res["cost"] = str(cost_of(res["usage"], price_in, price_out))
        append_checkpoint(ckpt, res)
        done[row["row_id"]] = res
    ordered = [done[r["row_id"]] for r in rows if r["row_id"] in done]
    ok = [r for r in ordered if r["status"] == "done"]
    bad = [r for r in ordered if r["status"] == "error"] + rejected
    write_csv_atomic(os.path.join(out_dir, "tickets_tagged.csv"), OUT_FIELDS, ok)
    write_csv_atomic(os.path.join(out_dir, "tickets_errors.csv"), ERR_FIELDS, bad)
    spent = sum((Decimal(r["cost"]) for r in ordered), Decimal(0))
    return {"rows": len(rows), "skipped_from_checkpoint": len(rows) - len(pending), "tagged": len(ok),
            "errors": len(bad), "duplicates": dupes, "calls_this_run": client.calls - calls_before,
            "estimate": est, "spent": spent}


# ---------- 8. Check quality: spot-check sample and accuracy ----------
def spot_check_sample(tagged_rows, k=5, seed=7):
    """A small, repeatable random sample for a person to read."""
    pool = sorted(tagged_rows, key=lambda r: r["row_id"])
    return sorted(random.Random(seed).sample(pool, min(k, len(pool))), key=lambda r: r["ticket_id"])


def agreement(model_labels, human_labels):
    """Share of rows where the person and the model chose the same label (rows both have)."""
    common = [k for k in model_labels if k in human_labels]
    if not common:
        return 0.0
    return sum(model_labels[k] == human_labels[k] for k in common) / len(common)


def evaluate(tagged_rows, gold):
    """Compare model labels with a gold set {ticket_id: label}."""
    pred = {r["ticket_id"]: r["label"] for r in tagged_rows}
    common = sorted(t for t in gold if t in pred)
    correct = sum(pred[t] == gold[t] for t in common)
    per_label = {}
    for lab in LABELS:
        g = [t for t in common if gold[t] == lab]
        per_label[lab] = {"gold": len(g), "correct": sum(pred[t] == lab for t in g)}
    mistakes = [(t, gold[t], pred[t]) for t in common if pred[t] != gold[t]]
    return {"compared": len(common), "not_tagged": len(gold) - len(common), "correct": correct,
            "accuracy": round(correct / len(common), 3) if common else 0.0,
            "per_label": per_label, "mistakes": mistakes}


def results_by_id(result_lines, expected_ids):
    """Batch APIs may return results in any order. Match them by id, never by position."""
    got = {}
    for line in result_lines:
        rec = json.loads(line)
        got[rec["custom_id"]] = rec
    missing = [i for i in expected_ids if i not in got]
    unknown = sorted(set(got) - set(expected_ids))
    return got, missing, unknown


# ---------- Synthetic data and a fake model ----------
TICKETS = [
    ("T001", "My lunch box has still not arrived and it is 2 pm."),
    ("T002", "The roti was missing from today's thali."),
    ("T003", "I was charged twice for Monday. Please give my money back."),
    ("T004", "Please refund the cancelled dinner order."),
    ("T005", "The dal smelled sour and I could not eat it."),
    ("T006", "Can I change my delivery time to 1 pm from next week?"),
    ("T007", "Rider came 50 minutes late again."),
    ("T008", "Sweet dish not in the box today."),
    ("T009", "Found a hair in the sabzi. This is not acceptable."),
    ("T010", "Do you have a Jain menu?"),
    ("T011", "The food reached very late and the rice was cold too."),
    ("T012", "Great, the rice arrived an hour after lunch time."),
    ("T013", "Curd packet was missing."),
    ("T014", "Too much salt in the paneer today."),
    ("T015", "=2+3 please call me back about my plan"),
    ("T016", "I want my money back for the stale chapati."),
    ("T017", ""),
    ("T018", "Order still waiting, the app says delivered."),
    ("T019", "Please add one extra salad from tomorrow."),
    ("T020", "Pickle packet was forgotten again."),
    ("T002", "The roti was missing from today's thali."),
]
GOLD = {"T001": "late_delivery", "T002": "missing_item", "T003": "refund", "T004": "refund",
        "T005": "food_quality", "T006": "other", "T007": "late_delivery", "T008": "missing_item",
        "T009": "food_quality", "T010": "other", "T011": "food_quality", "T012": "late_delivery",
        "T013": "missing_item", "T014": "food_quality", "T015": "other", "T016": "refund",
        "T018": "late_delivery", "T019": "other", "T020": "missing_item"}


def write_sample_csv(path):
    with open(path, "w", newline="", encoding="utf-8") as f:
        w = csv.writer(f)
        w.writerow(["ticket_id", "text"])
        w.writerows(TICKETS)


class FakeTagger:
    """Plays the AI model with simple keyword rules, plus scripted bad replies and errors.
    script maps a ticket_id to a list of planned results for its first attempts:
    'error' raises TransientAPIError; any other string is returned as the reply text."""
    RULES = [("refund", ("refund", "money back", "charged twice")),
             ("late_delivery", ("late", "not arrived", "still waiting", "waiting")),
             ("missing_item", ("missing", "not in the box", "forgotten")),
             ("food_quality", ("smell", "sour", "hair", "salt", "stale", "cold"))]

    def __init__(self, script=None):
        self.script = {k: list(v) for k, v in (script or {}).items()}
        self.calls = 0
        self.seen = []

    def complete(self, instructions, text, rid, max_output_tokens):
        self.calls += 1
        self.seen.append(rid)
        tid = rid.rsplit("-", 1)[0]
        plan = self.script.get(tid)
        if plan:
            step = plan.pop(0)
            if step == "error":
                raise TransientAPIError("429 rate limit (fake)")
            out = step
        else:
            out = json.dumps(self._rule(text))
        return {"text": out, "usage": {"input_tokens": estimate_tokens(instructions) + estimate_tokens(text),
                                       "output_tokens": min(max_output_tokens, estimate_tokens(out))}}

    def _rule(self, text):
        low = text.lower()
        label = next((lab for lab, words in self.RULES if any(w in low for w in words)), "other")
        urgency = "high" if any(w in low for w in ("hair", "charged twice", "not acceptable")) else \
                  "medium" if label != "other" else "low"
        return {"label": label, "urgency": urgency, "reason": "matched words in the ticket"}


DEMO_SCRIPT = {
    "T004": ["Sure! The label is refund."],                       # not JSON, fixed on retry
    "T007": ['{"label": "Late_Delivery", "urgency": "medium", "reason": "rider late"}'],  # casing only
    "T010": ['{"label": "menu_question", "urgency": "low", "reason": "asks about menu"}'] * 3,
    "T013": ["error"],                                             # one 429, then fine
    "T019": ["error", "error", "error"],                           # keeps failing
}


def demo():
    folder = "lab_output"  # created next to this file so you can open the CSV files afterwards
    out = os.path.join(folder, "out")
    os.makedirs(out, exist_ok=True)
    for name in ("checkpoint.jsonl", "tickets_tagged.csv", "tickets_errors.csv"):
        if os.path.exists(os.path.join(out, name)):
            os.remove(os.path.join(out, name))  # start the demo fresh every time
    src = os.path.join(folder, "tickets.csv")
    write_sample_csv(src)
    client = FakeTagger(DEMO_SCRIPT)
    prices = {"price_in": "1.00", "price_out": "4.00"}  # made-up units per million tokens
    rows, rejected, dupes = read_tickets(src)
    est = estimate_cost(rows, 60, max_attempts=3, **prices)
    print(f"Read {len(rows)} rows to tag, {len(rejected)} empty row, {dupes} duplicate skipped")
    print(f"Worst-case estimate: {est['input_tokens']} in + {est['output_tokens']} out tokens = {est['cost']} units")
    try:
        run_job(src, out, client, budget="0.05", crash_after=8, **prices)
    except SimulatedCrash as e:
        print(f"Run 1 crashed on purpose: {e}; calls so far {client.calls}")
    s = run_job(src, out, client, budget="0.05", **prices)
    print(f"Run 2 resumed: skipped {s['skipped_from_checkpoint']} finished rows, made {s['calls_this_run']} calls")
    print(f"Tagged {s['tagged']}, error rows {s['errors']}, total spent {s['spent']} units")
    with open(os.path.join(out, "tickets_errors.csv"), newline="", encoding="utf-8") as f:
        for r in csv.DictReader(f):
            print(f"  error row {r['ticket_id']}: {r['error']} after {r['attempts']} attempts")
    with open(os.path.join(out, "tickets_tagged.csv"), newline="", encoding="utf-8") as f:
        tagged = list(csv.DictReader(f))
    t15 = next(r for r in tagged if r["ticket_id"] == "T015")
    print(f"  T015 starts with = so it is stored as plain text: {t15['text'][:12]}")
    again = run_job(src, out, client, budget="0.05", **prices)
    print(f"Run 3 (nothing new): {again['calls_this_run']} calls")
    ev = evaluate(tagged, GOLD)
    print(f"Accuracy against the gold set: {ev['correct']}/{ev['compared']} = {ev['accuracy']}"
          f" ({ev['not_tagged']} gold rows were not tagged)")
    for tid, g, p in ev["mistakes"]:
        print(f"  mistake {tid}: gold {g}, model {p}")
    sample = spot_check_sample(tagged, k=5)
    human = {r["ticket_id"]: GOLD[r["ticket_id"]] for r in sample}  # a person would type these
    model = {r["ticket_id"]: r["label"] for r in sample}
    print("Spot-check sample:", ", ".join(r["ticket_id"] for r in sample),
          f"- agreement {agreement(model, human):.0%}")
    print("Files written: lab_output/out/tickets_tagged.csv, tickets_errors.csv, checkpoint.jsonl")


if __name__ == "__main__":
    demo()

test_csv_tagger.py

"""Offline tests for csv_tagger.py. Run: python3 -B -m unittest -v test_csv_tagger (pytest also works)."""
import csv, json, os, shutil, tempfile, unittest
from decimal import Decimal
import csv_tagger as ct

PRICES = {"price_in": "1.00", "price_out": "4.00"}


def read(path):
    with open(path, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


class Base(unittest.TestCase):
    def setUp(self):
        self.dir = tempfile.mkdtemp(prefix="tagtest_")
        self.addCleanup(shutil.rmtree, self.dir, True)
        self.src = os.path.join(self.dir, "tickets.csv")
        self.out = os.path.join(self.dir, "out")
        ct.write_sample_csv(self.src)

    def run_job(self, client, **kw):
        kw.setdefault("budget", "1")
        return ct.run_job(self.src, self.out, client, **PRICES, **kw)


class TestRowIds(unittest.TestCase):
    def test_same_input_same_id(self):
        self.assertEqual(ct.row_id("T1", "Hello there"), ct.row_id("T1", "Hello there"))

    def test_whitespace_and_case_do_not_change_id(self):
        self.assertEqual(ct.row_id("T1", "Hello  there"), ct.row_id("T1", "hello there "))

    def test_changed_text_gives_new_id(self):
        self.assertNotEqual(ct.row_id("T1", "late"), ct.row_id("T1", "missing"))

    def test_id_is_safe_custom_id(self):
        for tid, text in ct.TICKETS:
            self.assertRegex(ct.row_id(tid, text), ct.ID_RE)

    def test_odd_ticket_id_is_cleaned(self):
        self.assertRegex(ct.row_id("A/7 x", "t"), ct.ID_RE)
        self.assertTrue(ct.row_id("", "t").startswith("row-"))


class TestReadTickets(Base):
    def test_counts(self):
        rows, rejected, dupes = ct.read_tickets(self.src)
        self.assertEqual((len(rows), len(rejected), dupes), (19, 1, 1))

    def test_empty_row_rejected_before_api(self):
        _, rejected, _ = ct.read_tickets(self.src)
        self.assertEqual(rejected[0]["ticket_id"], "T017")
        self.assertEqual(rejected[0]["error"], "empty_text")


class TestValidate(unittest.TestCase):
    def ok(self, **over):
        d = {"label": "refund", "urgency": "medium", "reason": "asks for money back"}
        d.update(over)
        return json.dumps(d)

    def test_valid(self):
        data, err = ct.validate_reply(self.ok())
        self.assertIsNone(err)
        self.assertEqual(data["label"], "refund")

    def test_label_casing_is_normalised(self):
        data, err = ct.validate_reply(self.ok(label="Late_Delivery"))
        self.assertEqual((data["label"], err), ("late_delivery", None))

    def test_not_json(self):
        self.assertEqual(ct.validate_reply("Sure! The label is refund.")[1], "not_json")

    def test_none_reply(self):
        self.assertEqual(ct.validate_reply(None)[1], "not_json")

    def test_list_is_not_object(self):
        self.assertEqual(ct.validate_reply("[1, 2]")[1], "not_an_object")

    def test_label_outside_enum(self):
        self.assertTrue(ct.validate_reply(self.ok(label="menu_question"))[1].startswith("bad_label"))

    def test_bad_urgency(self):
        self.assertTrue(ct.validate_reply(self.ok(urgency="urgent"))[1].startswith("bad_urgency"))

    def test_missing_key(self):
        self.assertEqual(ct.validate_reply('{"label": "refund", "reason": "x"}')[1], "missing_urgency")

    def test_empty_reason(self):
        self.assertEqual(ct.validate_reply(self.ok(reason="  "))[1], "missing_reason")

    def test_extra_key(self):
        self.assertEqual(ct.validate_reply(self.ok(score=5))[1], "extra_keys:score")

    def test_long_reason_is_trimmed(self):
        data, _ = ct.validate_reply(self.ok(reason="x" * 500))
        self.assertEqual(len(data["reason"]), ct.MAX_REASON)

    def test_schema_matches_label_list(self):
        self.assertEqual(ct.LABEL_SCHEMA["properties"]["label"]["enum"], list(ct.LABELS))
        self.assertFalse(ct.LABEL_SCHEMA["additionalProperties"])


class TestTagRow(unittest.TestCase):
    row = {"row_id": "T1-abc", "ticket_id": "T1", "text": "Please refund me"}

    def test_first_try(self):
        r = ct.tag_row(ct.FakeTagger(), self.row)
        self.assertEqual((r["status"], r["attempts"], r["label"]), ("done", 1, "refund"))

    def test_bad_reply_then_good(self):
        c = ct.FakeTagger({"T1": ["oops"]})
        r = ct.tag_row(c, self.row)
        self.assertEqual((r["status"], r["attempts"], c.calls), ("done", 2, 2))

    def test_always_bad_goes_to_error(self):
        c = ct.FakeTagger({"T1": ['{"label": "x", "urgency": "low", "reason": "r"}'] * 3})
        r = ct.tag_row(c, self.row, max_attempts=3)
        self.assertEqual(r["status"], "error")
        self.assertTrue(r["error"].startswith("bad_label"))

    def test_transient_error_retried_with_sleep(self):
        waits = []
        c = ct.FakeTagger({"T1": ["error"]})
        r = ct.tag_row(c, self.row, sleep=waits.append)
        self.assertEqual(r["status"], "done")
        self.assertEqual(len(waits), 1)
        self.assertTrue(0 <= waits[0] <= 1)

    def test_transient_exhausted(self):
        waits = []
        c = ct.FakeTagger({"T1": ["error"] * 3})
        r = ct.tag_row(c, self.row, max_attempts=3, sleep=waits.append)
        self.assertEqual(r["error"], "transient:429 rate limit (fake)")
        self.assertEqual(len(waits), 2)  # no sleep after the last attempt

    def test_retry_note_mentions_error(self):
        class Spy(ct.FakeTagger):
            def complete(self, instructions, *a):
                self.last = instructions
                return super().complete(instructions, *a)
        c = Spy({"T1": ["oops"]})
        ct.tag_row(c, self.row)
        self.assertIn("not_json", c.last)

    def test_usage_adds_up_over_attempts(self):
        c = ct.FakeTagger({"T1": ["oops"]})
        r = ct.tag_row(c, self.row)
        self.assertGreater(r["usage"]["input_tokens"], ct.estimate_tokens(ct.INSTRUCTIONS))


class TestCost(unittest.TestCase):
    rows = [{"text": "a" * 40}, {"text": "b" * 4}]

    def test_estimate_tokens(self):
        self.assertEqual(ct.estimate_tokens("abcde"), 2)

    def test_estimate_worst_case(self):
        e = ct.estimate_cost(self.rows, 60, "1.00", "4.00")
        self.assertEqual(e["output_tokens"], 120)
        self.assertIsInstance(e["cost"], Decimal)

    def test_more_attempts_cost_more(self):
        a = ct.estimate_cost(self.rows, 60, "1", "4", max_attempts=1)["cost"]
        b = ct.estimate_cost(self.rows, 60, "1", "4", max_attempts=3)["cost"]
        self.assertEqual(b, a * 3)

    def test_cost_of(self):
        self.assertEqual(ct.cost_of({"input_tokens": 1_000_000, "output_tokens": 500_000}, "1.00", "4.00"),
                         Decimal("3"))


class TestCheckpoint(Base):
    def test_missing_file_is_empty(self):
        self.assertEqual(ct.load_checkpoint(os.path.join(self.dir, "none.jsonl")), {})

    def test_half_written_line_ignored(self):
        p = os.path.join(self.dir, "c.jsonl")
        ct.append_checkpoint(p, {"row_id": "a", "status": "done"})
        with open(p, "a") as f:
            f.write('{"row_id": "b", "sta')
        self.assertEqual(list(ct.load_checkpoint(p)), ["a"])

    def test_crash_then_resume_does_not_repay(self):
        c = ct.FakeTagger()
        with self.assertRaises(ct.SimulatedCrash):
            self.run_job(c, crash_after=5)
        first = c.calls
        s = self.run_job(c)
        self.assertEqual(s["skipped_from_checkpoint"], 5)
        self.assertEqual(first + s["calls_this_run"], 19)
        self.assertEqual(len(set(c.seen)), len(c.seen))  # no row was sent twice

    def test_second_run_makes_no_calls(self):
        c = ct.FakeTagger()
        self.run_job(c)
        self.assertEqual(self.run_job(c)["calls_this_run"], 0)

    def test_errors_not_retried_by_default(self):
        c = ct.FakeTagger({"T019": ["error"] * 3})
        self.run_job(c)
        self.assertEqual(self.run_job(c)["calls_this_run"], 0)

    def test_retry_errors_only_resends_error_rows(self):
        c = ct.FakeTagger({"T019": ["error"] * 3})
        self.run_job(c)
        s = self.run_job(c, retry_errors=True)
        self.assertEqual(s["calls_this_run"], 1)
        self.assertEqual(s["errors"], 1)  # only the empty row is left

    def test_edited_ticket_is_tagged_again(self):
        c = ct.FakeTagger()
        self.run_job(c)
        rows = read(self.src)
        rows[0]["text"] = "My refund has not come"
        with open(self.src, "w", newline="", encoding="utf-8") as f:
            w = csv.DictWriter(f, fieldnames=["ticket_id", "text"])
            w.writeheader()
            w.writerows(rows)
        self.assertEqual(self.run_job(c)["calls_this_run"], 1)


class TestJobOutputs(Base):
    def setUp(self):
        super().setUp()
        self.summary = self.run_job(ct.FakeTagger(ct.DEMO_SCRIPT))
        self.tagged = read(os.path.join(self.out, "tickets_tagged.csv"))
        self.errors = read(os.path.join(self.out, "tickets_errors.csv"))

    def test_counts(self):
        self.assertEqual((self.summary["tagged"], self.summary["errors"]), (17, 3))

    def test_output_header(self):
        self.assertEqual(list(self.tagged[0]), ct.OUT_FIELDS)

    def test_output_keeps_input_order(self):
        ids = [r["ticket_id"] for r in self.tagged]
        self.assertEqual(ids, sorted(ids))

    def test_every_label_is_allowed(self):
        self.assertTrue(all(r["label"] in ct.LABELS for r in self.tagged))

    def test_error_reasons(self):
        errs = {r["ticket_id"]: r["error"] for r in self.errors}
        self.assertEqual(errs["T017"], "empty_text")
        self.assertTrue(errs["T010"].startswith("bad_label"))
        self.assertTrue(errs["T019"].startswith("transient"))

    def test_formula_cell_is_neutralised(self):
        t15 = next(r for r in self.tagged if r["ticket_id"] == "T015")
        self.assertTrue(t15["text"].startswith("'="))

    def test_no_temp_files_left(self):
        self.assertFalse([f for f in os.listdir(self.out) if f.endswith(".tmp")])

    def test_spent_not_more_than_estimate(self):
        self.assertLessEqual(self.summary["spent"], self.summary["estimate"]["cost"])


class TestBudget(Base):
    def test_budget_too_small_stops_before_any_call(self):
        c = ct.FakeTagger()
        with self.assertRaises(ct.BudgetTooSmall):
            self.run_job(c, budget="0.001")
        self.assertEqual(c.calls, 0)


class TestSafeCell(unittest.TestCase):
    def test_formula_prefixes(self):
        for s in ("=1+1", "+91", "-5", "@x"):
            self.assertTrue(ct.safe_cell(s).startswith("'"))

    def test_normal_text_unchanged(self):
        self.assertEqual(ct.safe_cell("Rider late"), "Rider late")


class TestQuality(unittest.TestCase):
    def test_evaluate(self):
        rows = [{"ticket_id": "a", "label": "refund"}, {"ticket_id": "b", "label": "other"}]
        ev = ct.evaluate(rows, {"a": "refund", "b": "late_delivery", "c": "other"})
        self.assertEqual((ev["compared"], ev["correct"], ev["accuracy"], ev["not_tagged"]), (2, 1, 0.5, 1))
        self.assertEqual(ev["mistakes"], [("b", "late_delivery", "other")])
        self.assertEqual(ev["per_label"]["late_delivery"], {"gold": 1, "correct": 0})

    def test_evaluate_empty(self):
        self.assertEqual(ct.evaluate([], {"a": "refund"})["accuracy"], 0.0)

    def test_agreement(self):
        self.assertEqual(ct.agreement({"a": "x", "b": "y"}, {"a": "x", "b": "z"}), 0.5)
        self.assertEqual(ct.agreement({"a": "x"}, {}), 0.0)

    def test_spot_check_is_repeatable_and_small(self):
        rows = [{"row_id": f"r{i}", "ticket_id": f"T{i:03d}"} for i in range(20)]
        a, b = ct.spot_check_sample(rows, 5), ct.spot_check_sample(list(reversed(rows)), 5)
        self.assertEqual(a, b)
        self.assertEqual(len(a), 5)
        self.assertEqual(len(ct.spot_check_sample(rows[:3], 5)), 3)

    def test_results_matched_by_id_not_order(self):
        lines = [json.dumps({"custom_id": "b", "v": 2}), json.dumps({"custom_id": "a", "v": 1}),
                 json.dumps({"custom_id": "zz", "v": 9})]
        got, missing, unknown = ct.results_by_id(lines, ["a", "b", "c"])
        self.assertEqual(got["a"]["v"], 1)
        self.assertEqual((missing, unknown), (["c"], ["zz"]))


class TestDataIsSynthetic(unittest.TestCase):
    def test_no_emails_or_phone_numbers(self):
        import re
        for _, text in ct.TICKETS:
            self.assertIsNone(re.search(r"@\w|\d{10}", text))

    def test_gold_labels_are_allowed(self):
        self.assertTrue(all(v in ct.LABELS for v in ct.GOLD.values()))


if __name__ == "__main__":
    unittest.main()

12. When a provider batch API is the better choice

The lab sends one request per row and waits for each answer. Large jobs that do not need an answer straight away can often use a provider's batch API instead. You upload many requests together, the provider processes them in the background, and you download the results later. We read the official batch pages on 16 November 2026 (IST), and the table below lists only facts stated on those pages on that day.

Batch API facts from each provider's official documentation, checked on 16 November 2026 (IST).
ProviderPrice compared with normal callsTurnaroundHow results are matched to requests
OpenAI Batch APIThe guide says a 50% cost discount compared with the synchronous APIs.Each batch completes within 24 hours, and often sooner.Each request needs a unique custom_id, and the guide warns that the output order may not match the input order.
Anthropic Message BatchesThe guide says all usage is charged at 50 percent of the standard API prices.Most batches finish within 1 hour, and a batch expires if processing does not complete within 24 hours.Each request needs a custom_id of 1 to 64 letters, digits, hyphens or underscores, and results can come back in any order.
Google Gemini Batch APIThe guide says 50% of the standard interactive cost for the equivalent model.The target turnaround is 24 hours, and most jobs are much quicker.Each line of the input file has a key that you choose, and each response carries the same key.

The pages also list size limits, expiry rules and which models are supported, and these details change, so read the page again on the day you build. Two lessons from this chapter carry straight over to batch jobs. First, use your stable row id as the custom_id or key. Second, never match results by position. The lab's function results_by_id() matches results by id and reports any ids that are missing or unexpected. You still validate every result, write error rows to the error file and check accuracy, exactly as in the lab.

13. Connect a real model later, without changing the job

The job only needs an object with a complete() method that returns the reply text and its usage numbers, or raises TransientAPIError for a temporary failure. To use a real provider, write one small wrapper with that shape.

  1. Keep your API key in a .env file, as shown in the first API call chapter, and never put it in the CSV file or the code.
  2. Inside complete(), call the provider and, if it supports structured output, pass LABEL_SCHEMA so the model is guided towards the label list.
  3. Translate the provider's rate limit, server and timeout errors into TransientAPIError, and decide whether the SDK or your code does the retrying, as the API errors chapter explains.
  4. Translate the provider's usage fields into input_tokens and output_tokens.
  5. Remove personal details from the ticket text before it leaves your computer.
  6. Run the job on five rows, compare the spent amount with your provider dashboard, and only then run the full file.

14. Beginner mistakes and quick fixes

Common mistakes when tagging a CSV file with an AI model.
MistakeQuick fix
Letting the model choose any label it likes.Give a fixed label list and reject any label that is not in it.
Saving the reply without checking it.Validate every reply, and save only rows that pass.
Stopping the whole job because of one bad row.Retry a few times, then move the row to the error file and carry on.
Using the row number as the id.Use a stable id made from the ticket id and the text, because row numbers change when the file changes.
Writing the output file only at the very end, with no checkpoint.Save a checkpoint line after every row, so that a crash loses nothing.
Starting a large file without a cost estimate.Estimate the worst case first and set a budget that stops the job.
Matching batch results by their position.Match results by custom_id or key, because the order is not guaranteed.
Reporting numbers without checking accuracy.Compare with a small gold set and spot-check a few random rows.

15. Practise before you connect a real model

  1. Add a new label called payment_problem, then update the gold set and run the tests. Notice which tests you must change and why.
  2. Write a rule in the instructions that says which label wins when a ticket has two problems, and add a gold row that tests it.
  3. Change crash_after to 3 in the demo and predict how many rows Run 2 will skip before you run it.
  4. Add a test that puts a line break inside a ticket and checks that the output CSV still has one row for that ticket.
  5. Print the accuracy for each label from per_label and find the label that the model gets wrong most often.
  6. Write a function that turns the pending rows into a JSON Lines file with one request per line, using the row id as the custom_id, and check that every id passes the ID_RE rule.

Quick self-check quiz (5 questions)

Client-only quiz — not saved. Browser-only practice. Your answers are not sent anywhere, are not saved, and do not count towards any course progress or certificate.

1. The model replies with the label “menu_question,” which is not in your fixed label list. What should the job do?
2. The job crashed after 140 rows. Why does the next run not pay for those 140 rows again?
3. Why does the lab change the label to lower case before checking it?
4. The worst-case cost estimate is bigger than your budget. What happens in the lab?
5. You get batch results back from a provider. How should you match each result to its row?

Recap

  1. Decide a short fixed label list first, with a meaning for each label and an “other” label.
  2. Give every row a stable id made from the ticket id and its text, so the same row is never paid for twice.
  3. Validate every reply, compare labels without caring about capital letters, and retry a few times before moving a row to the error file.
  4. Save a checkpoint line after every row, and rebuild the output files from it with an atomic rename.
  5. Estimate the worst-case cost before the first call and stop if it does not fit the budget.
  6. Check accuracy against a small gold set and spot-check a few random rows before anyone uses the numbers.

Continue learning

Ravindra Bagale, trainer: linkedin.com/in/ravindra-bagale. Annapurna Tiffins, its tickets, the gold labels, every model reply in the lab and the example prices are made up / SYNTHETIC classroom material. Official interface details were checked against the linked documentation on 16 Nov 2026 (Asia/Calcutta); real limits, prices and batch rules vary by account and model and can change, and no provider endorsement or guarantee is claimed.