// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file A client for Anthropic's Message Batches endpoint. The corpus labeling tools submit their requests through it. * * A batch is asynchronous: `createMessageBatch` returns an id, `readMessageBatch` reports its state, * and `readMessageBatchResults` returns one line per request once the state is `ended`. * Result lines arrive in any order, so a caller joins them to its requests by `custom_id`. */ import { APIClient, pluckResponseData } from "@mailwoman/core/api" import { tryParsingJSON } from "@mailwoman/core/values/json" import { TextSpliterator } from "spliterator" import { $private } from "#env" const BATCHES_URL = "https://api.anthropic.com/v1/messages/batches" /** * The most requests one batch accepts. */ export const MAX_BATCH_REQUESTS = 100_000 /** * One Messages request inside a batch, addressed by a caller-chosen id of at most 64 characters. */ export interface MessageBatchRequest { custom_id: string params: Record } /** * The state of a submitted batch. */ export interface MessageBatch { id: string processing_status: "in_progress" | "canceling" | "ended" request_counts: { processing: number; succeeded: number; errored: number; canceled: number; expired: number } results_url: string | null } /** * Token counts the API bills a response for. */ export interface MessageUsage { input_tokens: number output_tokens: number cache_creation_input_tokens?: number | null cache_read_input_tokens?: number | null } /** * One request's outcome in a finished batch. * * `message` is present only when `type` is `succeeded`. */ export interface MessageBatchResult { custom_id: string result: { type: "succeeded" | "errored" | "canceled" | "expired" message?: { content: Array<{ type: string; text?: string }> stop_reason: string | null usage: MessageUsage } error?: unknown } } /** * Dollars per million tokens for one model on the batch endpoint. */ export interface TokenPrice { input: number output: number } /** * Creates the client every batch call shares. * * @throws When `ANTHROPIC_API_KEY` is unset. */ export function createAnthropicClient(): APIClient { const apiKey = $private.ANTHROPIC_API_KEY if (!apiKey) throw new Error("ANTHROPIC_API_KEY is required to call Anthropic") return new APIClient({ displayName: "anthropic", retry: true, axios: { headers: { "x-api-key": apiKey, "anthropic-version": "2023-06-01", "Content-Type": "application/json" }, }, }) } /** * Sends one Messages request outside a batch, at the standard price, * and returns it in a batch result's shape. * * A labeling tool sends one of these before a batch to confirm the API accepts its * parameters and to measure the tokens one request uses. */ export async function createMessage(client: APIClient, request: MessageBatchRequest): Promise { const message = (await client .fetch>({ url: "https://api.anthropic.com/v1/messages", method: "post", timeout: 600_000, data: request.params, cache: false, }) .then(pluckResponseData)) as NonNullable return { custom_id: request.custom_id, result: { type: "succeeded", message } } } /** * Submits `requests` as one batch and returns its initial state. * * @throws When `requests` is empty or exceeds `MAX_BATCH_REQUESTS`. */ export async function createMessageBatch(client: APIClient, requests: MessageBatchRequest[]): Promise { if (!requests.length || requests.length > MAX_BATCH_REQUESTS) { throw new Error(`A batch takes 1 to ${MAX_BATCH_REQUESTS} requests, and this one has ${requests.length}`) } return client .fetch({ url: BATCHES_URL, method: "post", timeout: 600_000, data: { requests }, cache: false }) .then(pluckResponseData) as Promise } /** * Reads the current state of the batch `id`. */ export async function readMessageBatch(client: APIClient, id: string): Promise { return client .fetch({ url: `${BATCHES_URL}/${id}`, timeout: 60_000, cache: false }) .then(pluckResponseData) as Promise } /** * Reads every result line of the finished batch `id`. * * @throws When the batch is still in progress, or when a line of the result file fails to parse. */ export async function readMessageBatchResults(client: APIClient, id: string): Promise { const batch = await readMessageBatch(client, id) if (batch.processing_status !== "ended") { throw new Error(`Batch ${id} is ${batch.processing_status}; its results exist only once it has ended`) } const { data } = await client.fetch({ url: `${BATCHES_URL}/${id}/results`, timeout: 600_000, responseType: "text", transformResponse: (body: unknown) => body, cache: false, }) return parseMessageBatchResults(String(data), `Batch ${id}`) } /** * Parses the JSONL body of a batch's results, as the API returns it or as a run saved it. * * @param source Where the body came from, as an error states it. * @throws When a line fails to parse or lacks a request id or outcome, or when the body holds no result. */ export function parseMessageBatchResults(body: string, source: string): MessageBatchResult[] { const results: MessageBatchResult[] = [] for (const line of TextSpliterator.from(body)) { if (line.trim() === "") continue const parsed = tryParsingJSON(line) as MessageBatchResult | null if (parsed?.custom_id == null || parsed.result?.type == null) { throw new Error(`${source} holds a result line that is not a batch result: ${line.slice(0, 200)}`) } results.push(parsed) } if (!results.length) throw new Error(`${source} holds no batch result`) return results } /** * Returns the text of a succeeded result, or `null` for any other outcome * or a response that stopped at `max_tokens`. */ export function resultText(result: MessageBatchResult): string | null { const message = result.result.message if (result.result.type !== "succeeded" || !message || message.stop_reason !== "end_turn") return null return message.content.find((block) => block.type === "text")?.text ?? null } /** * Sums the dollars the succeeded results cost at `price`. */ export function batchCostUSD(results: readonly MessageBatchResult[], price: TokenPrice): number { let input = 0 let output = 0 for (const { result } of results) { const usage = result.message?.usage if (!usage) continue input += usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0) output += usage.output_tokens } return (input * price.input + output * price.output) / 1_000_000 }