// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file Writes candidate rows of the ordinary query forms of each country's prominent places (#3156). * * Usage: * node --env-file=.env packages/corpus/lib/tools/prominent-shapes/prominent-shapes.run.ts --out \ * [--places ] [--wof-db ] [--model ] [--effort ] [--forms N] \ * [--places-per-request N] [--max-tokens N] [--max-per-band N] [--budget ] [--probe-request N] \ * [--results ] * * `seeds` reads the seeds and writes `seeds.jsonl` and their counts. * `probe` sends one request outside a batch and writes `probe.json`: its token counts, what the * validator kept, and the cost those counts project for every seed at the batch price. * `submit` creates the batch, and refuses when the probe's projection exceeds `--budget`. * `status` prints the batch's state. * `collect` saves the batch's results, validates them, and writes `candidates.jsonl` and `summary.json`. * With `--results` it validates that saved results file and sends no request. * Its summary lists each request whose every form dropped under one reason. * * The output is a candidates file for review. No corpus build reads it. */ import { pluckResponseData } from "@mailwoman/core/api" import { readLocalJSONFile, readLocalTextFile } from "@mailwoman/core/fs/readers" import { makeDirectories, writeLocalJSONFile, writeLocalJSONLFile } from "@mailwoman/core/fs/writers" import { parseArguments } from "@mailwoman/core/scripting/arguments" import { stringifyJSON } from "@mailwoman/core/values/json" import { wofDatabasePath } from "@mailwoman/resolver-wof-sqlite/paths" import { resolvePath } from "path-ts" import { JSONSpliterator } from "spliterator" import { batchCostUSD, createAnthropicClient, createMessageBatch, type MessageBatchRequest, type MessageBatchResult, type MessageUsage, parseMessageBatchResults, readMessageBatch, readMessageBatchResults, resultText, type TokenPrice, } from "#tools/anthropic/batches" import { renderShapeRequest, shapeRequestID, shapeRequestParams } from "#tools/prominent-shapes/prompt" import { readShapeSeeds } from "#tools/prominent-shapes/read-seeds" import { chunkSeedsByCountry, limitSeedsPerBand, type ShapeSeed } from "#tools/prominent-shapes/seeds" import { type FormDrop, type ValidatedForm, validateResponse, wholeResponseDropReason, } from "#tools/prominent-shapes/validate" /** * The batch price of the default model, in dollars per million tokens. */ const BATCH_PRICE: TokenPrice = { input: 2, output: 10 } const MESSAGES_URL = "https://api.anthropic.com/v1/messages" const { values, positionals } = parseArguments({ allowPositionals: true, options: { out: { type: "string" }, places: { type: "string" }, "wof-db": { type: "string" }, model: { type: "string" }, effort: { type: "string" }, forms: { type: "string" }, "places-per-request": { type: "string" }, "max-tokens": { type: "string" }, "max-per-band": { type: "string" }, budget: { type: "string" }, "probe-request": { type: "string" }, results: { type: "string" }, }, }) const [mode] = positionals if (!values.out) throw new Error("--out names the run directory") const out = resolvePath(values.out).toString() const outFile = (name: string) => resolvePath(out, name).toString() const settings = { model: values.model ?? "claude-opus-5-5", effort: values.effort ?? "low", formsPerPlace: Number(values.forms ?? 12), maxTokens: Number(values["max-tokens"] ?? 4000), } const placesPerRequest = Number(values["places-per-request"] ?? 10) const budget = Number(values.budget ?? 60) /** * The record `submit` writes and `status` and `collect` read. */ interface BatchRecord { batch_id: string model: string effort: string forms_per_place: number requests: Array<{ custom_id: string; wof_ids: number[] }> } /** * The record `probe` writes and `submit` reads. */ interface ProbeRecord { model: string forms_per_place: number places: number usage: MessageUsage stop_reason: string | null forms_returned: number forms_kept: number drops: Partial> seeds: number requests: number projected_batch_cost_usd: number } function count(items: readonly T[], key: (item: T) => string): Record { const counts: Record = {} for (const item of items) { counts[key(item)] = (counts[key(item)] ?? 0) + 1 } return Object.fromEntries(Object.entries(counts).toSorted(([a], [b]) => a.localeCompare(b))) } async function readSeedFile(): Promise { const seeds: ShapeSeed[] = [] for await (const seed of JSONSpliterator.fromAsync(outFile("seeds.jsonl"))) { seeds.push(seed) } if (!seeds.length) throw new Error(`${outFile("seeds.jsonl")} holds no seed; run the seeds mode first`) return seeds } await makeDirectories(out) if (mode === "seeds") { const read = await readShapeSeeds({ placesParquet: resolvePath( values.places ?? "/mnt/mw/audits/v0822-build/prominent-census-2/places.parquet" ).toString(), wofDatabase: (values["wof-db"] ?? wofDatabasePath("admin-global-priority.db")).toString(), }) const seeds = values["max-per-band"] ? limitSeedsPerBand(read.seeds, Number(values["max-per-band"])) : read.seeds await writeLocalJSONLFile(seeds, outFile("seeds.jsonl")) const record = { selected: read.selected, skipped: read.skipped, seeds_read: read.seeds.length, seeds: seeds.length, by_band: count(seeds, (seed) => seed.band), by_place_tag: count(seeds, (seed) => `${seed.place_tag}${seed.parent_tag ? `+${seed.parent_tag}` : ""}`), countries: new Set(seeds.map((seed) => seed.country)).size, countries_by_band: count( [...new Set(seeds.map((seed) => `${seed.band}\u0000${seed.country}`))], (key) => key.split("\u0000")[0]! ), by_country: count(seeds, (seed) => seed.country), requests: chunkSeedsByCountry(seeds, placesPerRequest).length, } await writeLocalJSONFile(record, outFile("seeds-summary.json")) console.log(stringifyJSON(record)) } else if (mode === "probe") { const seeds = await readSeedFile() const chunks = chunkSeedsByCountry(seeds, placesPerRequest) const full = chunks.map((chunk, index) => ({ chunk, index })).filter(({ chunk }) => chunk.length === placesPerRequest) const index = values["probe-request"] ? Number(values["probe-request"]) : full[Math.floor(full.length / 2)]!.index const chunk = chunks[index] if (!chunk) throw new Error(`--probe-request ${index} is outside the ${chunks.length} requests`) console.error(renderShapeRequest(chunk, settings.formsPerPlace)) const message = (await createAnthropicClient() .fetch({ url: MESSAGES_URL, method: "post", timeout: 600_000, data: shapeRequestParams(chunk, settings), cache: false, }) .then(pluckResponseData)) as NonNullable const text = message.content.find((block) => block.type === "text")?.text ?? "" console.error(text) const validated = validateResponse(text, chunk) if (!validated) throw new Error(`The probe response isn't the schema's shape (stop reason ${message.stop_reason})`) // Tokens per place from this request, applied to every seed at the batch price. const scale = seeds.length / chunk.length const record: ProbeRecord = { model: settings.model, forms_per_place: settings.formsPerPlace, places: chunk.length, usage: message.usage, stop_reason: message.stop_reason, forms_returned: validated.returned, forms_kept: validated.kept.length, drops: validated.drops, seeds: seeds.length, requests: chunks.length, projected_batch_cost_usd: (message.usage.input_tokens * scale * BATCH_PRICE.input + message.usage.output_tokens * scale * BATCH_PRICE.output) / 1_000_000, } await writeLocalJSONFile(record, outFile("probe.json")) await writeLocalJSONLFile(validated.kept, outFile("probe-kept.jsonl")) console.log(stringifyJSON(record)) } else if (mode === "submit") { const seeds = await readSeedFile() const probe = await readLocalJSONFile(outFile("probe.json")) if ( probe.seeds !== seeds.length || probe.forms_per_place !== settings.formsPerPlace || probe.model !== settings.model ) { throw new Error("probe.json measures other seeds, forms or model than this submit; run the probe mode again") } if (!(probe.projected_batch_cost_usd <= budget)) { throw new Error(`The probe projects $${probe.projected_batch_cost_usd.toFixed(2)}, over the $${budget} budget`) } const chunks = chunkSeedsByCountry(seeds, placesPerRequest) const requests: MessageBatchRequest[] = chunks.map((chunk, index) => ({ custom_id: shapeRequestID(index), params: shapeRequestParams(chunk, settings), })) const batch = await createMessageBatch(createAnthropicClient(), requests) const record: BatchRecord = { batch_id: batch.id, model: settings.model, effort: settings.effort, forms_per_place: settings.formsPerPlace, requests: chunks.map((chunk, index) => ({ custom_id: shapeRequestID(index), wof_ids: chunk.map((seed) => seed.wof_id), })), } await writeLocalJSONFile(record, outFile("batch.json")) console.log(stringifyJSON({ batch_id: batch.id, requests: requests.length, status: batch.processing_status })) } else if (mode === "status") { const record = await readLocalJSONFile(outFile("batch.json")) console.log(stringifyJSON(await readMessageBatch(createAnthropicClient(), record.batch_id))) } else if (mode === "collect") { const record = await readLocalJSONFile(outFile("batch.json")) const seeds = await readSeedFile() const seedByID = new Map(seeds.map((seed) => [seed.wof_id, seed])) const savedResults = values.results ? resolvePath(values.results).toString() : null let results: MessageBatchResult[] if (savedResults) { // A saved file is validated again without a request to the API, and is left as it is. results = parseMessageBatchResults(await readLocalTextFile(savedResults), savedResults) } else { results = await readMessageBatchResults(createAnthropicClient(), record.batch_id) // The paid responses are saved before anything reads them. await writeLocalJSONLFile(results, outFile("results.jsonl")) } const wholeDrops: Array<{ custom_id: string; country: string; places: number; forms: number; reason: string }> = [] const resultByID = new Map(results.map((result) => [result.custom_id, result])) const outcomes: Record = {} const drops: Record = {} const candidates: Array = [] const answered = new Set() let formsReturned = 0 const tally = (outcome: string) => { outcomes[outcome] = (outcomes[outcome] ?? 0) + 1 } for (const request of record.requests) { const result = resultByID.get(request.custom_id) if (!result) { tally("missing") continue } if (result.result.type !== "succeeded") { tally(result.result.type) continue } const text = resultText(result) if (text == null) { tally(`succeeded_stop_${result.result.message?.stop_reason ?? "unknown"}`) continue } const requestSeeds = request.wof_ids.map((id) => { const seed = seedByID.get(id) if (!seed) throw new Error(`batch.json names place ${id}, which seeds.jsonl doesn't hold`) return seed }) const validated = validateResponse(text, requestSeeds) if (!validated) { tally("succeeded_unreadable") continue } tally("succeeded") formsReturned += validated.returned const wholeDrop = wholeResponseDropReason(validated) if (wholeDrop != null) { wholeDrops.push({ custom_id: request.custom_id, country: requestSeeds[0]?.country ?? "", places: requestSeeds.length, forms: validated.returned, reason: wholeDrop, }) } for (const id of validated.answered) { answered.add(id) } for (const [reason, n] of Object.entries(validated.drops)) { drops[reason] = (drops[reason] ?? 0) + (n ?? 0) } for (const form of validated.kept) { candidates.push({ ...form, model: record.model, batch_id: record.batch_id, custom_id: request.custom_id }) } } await writeLocalJSONLFile(candidates, outFile("candidates.jsonl")) const keptPlaces = new Set(candidates.map((candidate) => candidate.wof_id)) const keptCountries = new Set(candidates.map((candidate) => candidate.country)) const summary = { batch_id: record.batch_id, model: record.model, effort: record.effort, forms_per_place: record.forms_per_place, seeds: seeds.length, seeds_by_band: count(seeds, (seed) => seed.band), requests: record.requests.length, results: results.length, results_by_outcome: outcomes, places_answered: answered.size, forms_returned: formsReturned, candidates_kept: candidates.length, candidates_with_keys_from_letters: candidates.filter((candidate) => candidate.keys_from_letters).length, drops_by_reason: Object.fromEntries(Object.entries(drops).toSorted(([a], [b]) => a.localeCompare(b))), requests_dropped_whole_for_one_reason: wholeDrops, requests_dropped_whole_by_reason: count(wholeDrops, (drop) => drop.reason), places_without_a_candidate: seeds.length - keptPlaces.size, results_read_from: savedResults ?? "the batch's results endpoint", kept_by_shape: count(candidates, (candidate) => candidate.shape), kept_by_band: count(candidates, (candidate) => candidate.band), kept_by_band_and_shape: count(candidates, (candidate) => `${candidate.band}:${candidate.shape}`), places_with_a_candidate: keptPlaces.size, places_with_a_candidate_by_band: count( seeds.filter((seed) => keptPlaces.has(seed.wof_id)), (seed) => seed.band ), countries_with_a_candidate: keptCountries.size, countries_with_zero_candidates: [...new Set(seeds.map((seed) => seed.country))] .filter((country) => !keptCountries.has(country)) .toSorted(), span_offsets: "UTF-16 code units, end exclusive", price_usd_per_million_tokens: BATCH_PRICE, measured_cost_usd: batchCostUSD(results, BATCH_PRICE), } await writeLocalJSONFile(summary, outFile("summary.json")) console.log(stringifyJSON(summary)) } else { throw new Error("expected one of seeds, probe, submit, status, collect") }