// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file The submit, status and collect steps every batch labeling tool shares. * * A labeling tool splits its items into chunks, one request each, and the model returns one label per item. * `submitLabelingBatch` writes `chunks.jsonl` and `batch.json` to the tool's output directory, * and `collectLabelingBatch` joins the finished batch back to those chunks by `custom_id`. * A request that failed, stopped at `max_tokens`, or returned labels the tool's parser refuses is listed as failed * with its reason, and its items receive no label. */ import { readLocalJSONFile } from "@mailwoman/core/fs/readers" import { writeLocalJSONFile, writeLocalJSONLFile } from "@mailwoman/core/fs/writers" import type { PathBuilder } from "path-ts" import { JSONSpliterator } from "spliterator" import { batchCostUSD, createAnthropicClient, createMessage, createMessageBatch, readMessageBatch, readMessageBatchResults, resultText, type MessageBatch, type MessageBatchRequest, type MessageBatchResult, type MessageUsage, type TokenPrice, } from "#tools/anthropic/batches" /** * Dollars per million tokens on the batch endpoint, at half the standard price. */ const BATCH_PRICES: Record = { "claude-opus-5-5": { input: 2, output: 10 }, "claude-sonnet-5-5": { input: 1, output: 5 }, "claude-haiku-5-5": { input: 0.05, output: 0.25 }, } /** * Returns the batch price of `model`. * * @throws When no price is recorded for it, so a cost is never reported from a guessed rate. */ export function batchPrice(model: string): TokenPrice { const price = BATCH_PRICES[model] if (!price) throw new Error(`No batch price is recorded for ${model}; add it to BATCH_PRICES`) return price } /** * The items one request labels. */ export interface LabelingChunk { custom_id: string items: Item[] } /** * What `submitLabelingBatch` records, so a later `status` or `collect` reads * the settings the batch ran under. */ export interface LabelingBatchRecord { id: string model: string effort: string requests: number items: number } /** * The model and effort a tool's requests run under. */ export interface LabelingSettings { model: string effort: string } type ToParams = (items: readonly Item[], settings: LabelingSettings) => MessageBatchRequest["params"] /** * Parses one response into a label per item of its request, in item order, * and throws on a response it refuses. */ type ParseLabels = (text: string, items: readonly Item[]) => Label[] /** * Splits `items` into requests of `size`, with ids `-`. */ export function toLabelingChunks(items: readonly Item[], size: number, prefix: string): LabelingChunk[] { if (!Number.isInteger(size) || size < 1) throw new Error(`A chunk holds a whole number of items, and --chunk was ${size}`) const chunks: LabelingChunk[] = [] for (let start = 0; start < items.length; start += size) { chunks.push({ custom_id: `${prefix}-${chunks.length}`, items: items.slice(start, start + size) }) } return chunks } /** * Sends `count` evenly spaced chunks one at a time at the standard price. * * @returns Each chunk with its labels and token use, and the batch cost per request those requests imply. * @throws When a response stops at `max_tokens` or the parser refuses it, * since a batch of the same requests would fail the same way. */ export async function pilotLabelingRequests( chunks: ReadonlyArray>, count: number, settings: LabelingSettings, toParams: ToParams, parse: ParseLabels ): Promise<{ requests: Array<{ chunk: LabelingChunk; labels: Label[]; usage: MessageUsage }> batchCostPerRequestUSD: number }> { const client = createAnthropicClient() const stride = Math.max(1, Math.floor(chunks.length / count)) const requests: Array<{ chunk: LabelingChunk; labels: Label[]; usage: MessageUsage }> = [] const results: MessageBatchResult[] = [] for (let n = 0; n < count && n * stride < chunks.length; n++) { const chunk = chunks[n * stride]! const result = await createMessage(client, { custom_id: chunk.custom_id, params: toParams(chunk.items, settings) }) const text = resultText(result) if (text == null) throw new Error(`${chunk.custom_id} stopped at ${result.result.message?.stop_reason ?? "no message"}`) requests.push({ chunk, labels: parse(text, chunk.items), usage: result.result.message!.usage }) results.push(result) } return { requests, batchCostPerRequestUSD: batchCostUSD(results, batchPrice(settings.model)) / results.length } } /** * Writes `chunks.jsonl`, creates one batch of the chunks, and records it in `batch.json`. */ export async function submitLabelingBatch( out: PathBuilder, chunks: ReadonlyArray>, settings: LabelingSettings, toParams: ToParams ): Promise { batchPrice(settings.model) await writeLocalJSONLFile(chunks, out("chunks.jsonl")) const batch = await createMessageBatch( createAnthropicClient(), chunks.map((chunk) => ({ custom_id: chunk.custom_id, params: toParams(chunk.items, settings) })) ) const record: LabelingBatchRecord = { id: batch.id, ...settings, requests: chunks.length, items: chunks.reduce((sum, chunk) => sum + chunk.items.length, 0), } await writeLocalJSONFile(record, out("batch.json")) return record } /** * Reads the state of the batch `batch.json` records. */ export async function readLabelingBatch(out: PathBuilder): Promise { const { id } = await readLocalJSONFile(out("batch.json")) return readMessageBatch(createAnthropicClient(), id) } /** * A request whose items received no label, and why. */ export interface FailedChunk { custom_id: string reason: string items: number } /** * Joins the finished batch to its chunks and writes `failed-chunks.jsonl`. * * @returns Every labeled item beside its label, the failed requests, the result * count per outcome type, and the dollars the batch cost. * @throws When the batch is still in progress. */ export async function collectLabelingBatch( out: PathBuilder, parse: ParseLabels ): Promise<{ record: LabelingBatchRecord labeled: Array<{ item: Item; label: Label }> failed: FailedChunk[] resultsByType: Record costUSD: number }> { const record = await readLocalJSONFile(out("batch.json")) const chunks = await JSONSpliterator.fromAsync>(out("chunks.jsonl")).toArray() const results = await readMessageBatchResults(createAnthropicClient(), record.id) const byCustomID = new Map(results.map((result) => [result.custom_id, result])) const labeled: Array<{ item: Item; label: Label }> = [] const failed: FailedChunk[] = [] for (const chunk of chunks) { const result = byCustomID.get(chunk.custom_id) const text = result ? resultText(result) : null if (!result || text == null) { const reason = result ? `${result.result.type}:${result.result.message?.stop_reason ?? "no message"}` : "no result line" failed.push({ custom_id: chunk.custom_id, reason, items: chunk.items.length }) continue } try { const labels = parse(text, chunk.items) for (const [i, item] of chunk.items.entries()) { labeled.push({ item, label: labels[i]! }) } } catch (error) { failed.push({ custom_id: chunk.custom_id, reason: (error as Error).message, items: chunk.items.length }) } } await writeLocalJSONLFile(failed, out("failed-chunks.jsonl")) return { record, labeled, failed, resultsByType: countEach(results.map((result) => result.result.type)), costUSD: Number(batchCostUSD(results, batchPrice(record.model)).toFixed(2)), } } /** * Counts each distinct value. */ export function countEach(values: Iterable): Record { const counts: Record = {} for (const value of values) { counts[value] = (counts[value] ?? 0) + 1 } return counts }