Skip to content
← All writing
2026-06-29 · 9 min read llmpipelinestructured-outputpython

Mining a Sitcom for Slang with a Resumable LLM Pipeline

Anki cards in, a curated bilingual deck out — schema-validated LLM calls, MD5 checkpoints, and three passes that each do one job.

What you'll get out of this post

The worked example is small and concrete: pull flashcards from an Anki deck built while watching Modern Family, and turn them into a curated, deduplicated, bilingual vocabulary deck — the kind where every entry is a colloquial word a dictionary would mislead you on (chip in = 凑钱, snap = 发火, nab = 顺走). The shape of the problem is the same one you hit anywhere you point a model at a pile of records.


The naïve version, and exactly where it breaks

The first draft writes itself:

for card in cards:
    words = call_llm(prompt(card))   # "find the slang in this line"
    results.append(words)

It works for ten cards. At three thousand, every weakness surfaces at once:

None of these are exotic. They're the default failure modes of "LLM in a for-loop," and each one has a structural fix that costs almost nothing if you build it in from the start.


Decision 1: the cache is the database

The single highest-leverage move is to make every model call content-addressed and persisted immediately. Hash the inputs that determine the output, key the result by that hash, write to disk after every batch.

def card_key(model, c):
    raw = f"{model}|{c['target']}|{c['english']}"
    return hashlib.md5(raw.encode("utf-8")).hexdigest()

That one function buys four properties at once:

What a content-addressed cache gives you for free

Resumable
crash at 2400 → restart skips the first 2400
→
Idempotent
re-run = no-op for unchanged cards

↓

Shardable
8 processes, one cache each, merge at the end
→
Cheap to iterate
change the prompt → only changed keys re-run

The key includes the model name (claude and codex results don't collide) and the inputs the prompt actually reads — the target word and the line. Change the prompt's wording and the cache stays valid; change what goes into it and the key changes, so stale results never leak.

Persistence is per-batch, not per-run, via a tiny atomic write:

def save_cache(cache, path):
    tmp = path + ".tmp"
    json.dump(cache, open(tmp, "w"), ensure_ascii=False)
    os.replace(tmp, path)   # atomic: a crash mid-write never corrupts the cache

Key Concept

Content-addressed checkpointing

Treat each expensive call's result as immutable and address it by a hash of its inputs. The cache stops being an optimization and becomes the job's state: progress, resumability, and parallel-safety all fall out of the same dictionary. The run becomes a pure function of (inputs, prompt) — re-running can only fill gaps, never double-charge you.

Sharding is then four lines, because the cache already makes parallel runs safe:

# --shard i/N : this process only handles cards where index % N == i,
# writing to its own cache file; a final pass merges all shards.
idxs = [k for k in range(len(cards)) if k % n == i]
eight shards in parallel, each resumable
$for i in $(seq 0 7); do python mf_slang.py --episodes ALL \
$ --shard $i/8 --cache .cache.shard$i.json --extract-only & done
# kill it halfway, rerun the same line — each shard resumes from its own cache
[shard3] 需抽取 41 张(已缓存 327)

Decision 2: one interface, swappable models behind it

The extractor supports two completely different backends — OpenAI's codex CLI and Anthropic's claude CLI — which disagree about everything: how you pass a schema, how the JSON comes back, how it's wrapped.

💡

This is the indirection move, in miniature

App code depends on one interface — run_batch(model, lines) → results — and never on a specific vendor's CLI. Adding a model is writing one adapter; nothing upstream changes. It's the same principle as another level of indirection: name the thing in the middle, and both sides become free to vary.

def run_batch(model, lines):
    if model == "codex":
        return codex_extract_batch(lines)        # codex exec --output-schema
    if model.startswith("claude"):
        cm = model.split(":", 1)[1] if ":" in model else "sonnet"
        return claude_extract_batch(lines, cm)    # claude -p --output-format json
    raise ValueError(f"unknown model {model}")

The two adapters absorb the vendor quirks so nothing above them has to know. codex writes schema-validated JSON to a file you pass with --output-schema; claude returns a wrapper object with the answer as a string field you have to unpack:

# claude --output-format json wraps the real answer in {"result": "...", ...}
wrapper = json.loads(out)
inner = wrapper.get("result", out) if isinstance(wrapper, dict) else out
return _extract_json(inner)

That _extract_json is the third small piece of armor: strip code fences, find the first {, decode from there, and on any failure return an empty result rather than crashing the batch. A single bad response costs one card, not the whole run.


Decision 3: three passes, each with one job

The instinct is to ask the model for everything in one prompt: find the slang, rate how useful it is, and clean up the senses. That prompt is worse at all three jobs than three prompts are at one each. The pipeline splits the work along the axis of what each pass optimizes for:

Recall, then precision, then dedup

Pass 0 · Extract
high recall — keep anything plausibly colloquial

schema-validated mining over batches of cards

↓

Pass A · Tier
high precision — rate each word 1 / 2 / 3, keep 1–2

a strict second opinion the extraction prompt can't give itself

↓

Pass B · Merge senses
dedup — cluster a word's many context-glosses into 2–4 real senses

only for polysemous, high-frequency words

Why separate them? Because the jobs pull in opposite directions. Extraction should be generous — better to surface a borderline word and cut it later than to miss a gem. Tiering should be strict — its entire job is to be the harsh judge that demotes "throw a ball" (literal, every beginner owns it) while keeping "chunk" (= to toss, colloquial). Asking one prompt to be generous and strict at once gets you mush.

The tier pass runs as a concurrent fan-out, because it's pure per-batch work over the already-cached words:

with ThreadPoolExecutor(max_workers=8) as ex:
    futs = {ex.submit(select_batch, words, b, batch): b for b in todo}
    for f in as_completed(futs):
        cache.update(f.result())

The merge pass is the most "agentic" of the three: for a word that picked up a dozen near-identical Chinese glosses across episodes, it asks the model to cluster them into 2–4 canonical senses and assign every input gloss to exactly one — a small, bounded judgment that would be tedious and inconsistent to hand-rule.

⚠️

Gate the expensive pass

Pass B only runs for words with more than 3 senses and 5+ occurrences. Most words never qualify, so you spend the clustering calls only where polysemy is real. A pipeline that runs every pass on every row is paying for judgment nobody asked for — the same lesson as the corollary in the indirection post: every layer bills you, so make each one earn its place.


What the shape gets you

Put the three decisions together and the job stops being fragile:

Failure mode of the naïve loopThe fix, structurally
Crash loses all progressContent-addressed cache, persisted per batch
Re-run after a tweak pays for everythingOnly changed keys re-run; the rest are cache hits
One bad JSON kills the runSchema validation + per-batch fallback to empty
Single-threaded, slowShard by index % N, cache makes it parallel-safe
Locked to one vendorrun_batch interface, one adapter per model
One prompt doing three jobs badlyThree passes: recall → precision → dedup

None of it is framework-grade machinery. It's a hash function, an atomic write, a dispatch function, and a decision to split one prompt into three. The leverage is in building them in from the first version instead of bolting them on after the run dies at card 2,400 for the third time.


Iron rules

⚡ Iron Rule #1

Make the cache the state, not an optimization

Key every expensive call by a hash of the inputs that determine its output, and persist after every batch. Resumability, idempotency, and parallel-safety stop being features you build and become properties you already have. A batch LLM job without this is a job that hasn't crashed yet.

⚡ Iron Rule #2

Put one interface between your code and the model

Depend on extract(lines) → words, never on a vendor's CLI or wire format. Adding or swapping a model becomes one adapter, and you get a fake implementation for free — replay the cache, run your whole pipeline in CI for zero dollars.

⚡ Iron Rule #3

One prompt, one job

Recall, precision, and dedup pull in different directions; a prompt asked to do all three does each one worse. Split the work into passes you can tune, cache, and gate independently — and run the expensive pass only where it earns its cost.