@mailwoman/corpus 11.5.0 → 12.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/data/address-source-register.json +545 -11
- package/data/builds/v0.8.22-wofrank-overlay/OVERLAY_PLAN.json +51 -0
- package/data/builds/v0.8.24-everyplace/inputs.json +35 -0
- package/data/license-decisions.json +440 -9
- package/data/licenses/PROVENANCE.md +27 -18
- package/data/licenses/at-bev-adressregister-cc-by-4.0.md +25 -0
- package/data/licenses/br-ibge-cnefe-open-data.md +21 -0
- package/data/licenses/ca-qc-mrnf-cc-by-4.0.md +29 -0
- package/data/licenses/ca-statcan-open-licence.md +41 -0
- package/data/licenses/ca-yukon-ogl-2.0.md +19 -0
- package/data/licenses/dk-dmikg-cc-by-4.0.md +43 -0
- package/data/licenses/jp-mlit-isj-pdl-1.0.md +35 -0
- package/data/source-additions.json +90 -0
- package/data/source-resolutions.json +3 -2
- package/data/training-configs/v8.17.0-stage1-gazetteer-v0822-s42.yaml +557 -0
- package/data/training-configs/v8.17.0-stage2-corpus-v0822-s42.yaml +1008 -0
- package/data/training-configs/v8.18.0-gazetteer-then-mixture-v0822-s42.yaml +1225 -0
- package/data/training-configs/v8.20.0-wofrank-v0822-s42.yaml +863 -0
- package/data/training-configs/v8.21.0-outcomes-v0822-s42.yaml +873 -0
- package/data/training-configs/v8.22.0-stage1-everyplace-v0824-s42.yaml +374 -0
- package/data/training-configs/v8.22.0-stage2-corpus-v0824-s42.yaml +808 -0
- package/data/training-configs/v8.22.1-stage1-everyplace-v0824-s42.yaml +376 -0
- package/data/training-configs/v8.22.1-stage2-corpus-v0824-s42.yaml +793 -0
- package/data/training-configs/v9.0.0-bytestem-v090-s42.yaml +665 -0
- package/data/training-configs/v9.1.0-bytestem-global-v091-s42.yaml +710 -0
- package/data/training-configs/v9.2.0-bytestem-global-v092-s42.yaml +714 -0
- package/data/training-manifests/v0.8.22-wofrank-overlay.json +9000 -0
- package/data/training-manifests/v0.8.24-everyplace-overlay.json +9000 -0
- package/data/training-manifests/v0.9.0-compact.effective.json +2556 -0
- package/data/training-manifests/v0.9.0-compact.json +9000 -0
- package/data/training-manifests/v0.9.1-compact.json +9660 -0
- package/data/training-manifests/v0.9.2-compact.effective.json +2670 -0
- package/data/training-manifests/v0.9.2-compact.json +9660 -0
- package/lib/adapters/geonames/features/adapter.ts +29 -11
- package/lib/adapters/overture/adapter.ts +26 -6
- package/lib/adapters/street/line.ts +6 -5
- package/lib/adapters/street/unit.ts +7 -0
- package/lib/adapters/wof/admin/json/adapter.ts +38 -3
- package/lib/adapters/wof/json-rows.ts +84 -5
- package/lib/adapters/wof/sample.ts +42 -6
- package/lib/au/adapters/gnaf/source.ts +12 -0
- package/lib/build/code-hash.ts +1 -1
- package/lib/cjk/foreign-places.ts +1 -1
- package/lib/fr/adapters/ban/adapter.ts +57 -8
- package/lib/fr/recipes/admin-split.ts +14 -2
- package/lib/fr/recipes/lieudit.ts +1 -1
- package/lib/fr/recipes/order.ts +14 -5
- package/lib/international/recipes/locale.ts +1 -1
- package/lib/kr/adapters/localdata/permit-rows.ts +1 -1
- package/lib/parquet/schema.ts +7 -0
- package/lib/recipes/po/box/cedex/recipe.ts +1 -1
- package/lib/recipes/po/box/cedex/vocabulary.ts +4 -4
- package/lib/recipes/trailing-region.ts +147 -17
- package/lib/synthesizers/po-box.ts +51 -12
- package/lib/test-kit/corpus-recipe.ts +3 -0
- package/lib/tools/anthropic/batches.ts +221 -0
- package/lib/tools/anthropic/labeling.ts +263 -0
- package/lib/tools/compact-v9.ts +890 -0
- package/lib/tools/fetch/wikidata/vital-places/entities.ts +20 -2
- package/lib/tools/fetch/wikidata/vital-places/qrank.ts +5 -4
- package/lib/tools/fragment-assay.run.ts +2 -1
- package/lib/tools/name-roles/name-roles.run.ts +296 -0
- package/lib/tools/name-roles/prompt.ts +253 -0
- package/lib/tools/overlay/deletions.ts +1 -1
- package/lib/tools/overlay/draw-weight.ts +275 -0
- package/lib/tools/place-twins/place-twins.run.ts +528 -0
- package/lib/tools/place-twins/prompt.ts +276 -0
- package/lib/tools/prominent-shapes/prominent-shapes.run.ts +420 -0
- package/lib/tools/prominent-shapes/prompt.ts +189 -0
- package/lib/tools/prominent-shapes/read-seeds.ts +286 -0
- package/lib/tools/prominent-shapes/seeds.ts +281 -0
- package/lib/tools/prominent-shapes/validate.ts +563 -0
- package/lib/tools/source-register/build.ts +1 -0
- package/lib/training/config/admission.ts +9 -2
- package/lib/training/config/schema.ts +68 -1
- package/lib/types.ts +23 -0
- package/lib/us/adapters/usgov/usgs-structures/adapter.ts +103 -6
- package/lib/utils/split.ts +1 -1
- package/out/adapters/geonames/features/adapter.d.ts +2 -2
- package/out/adapters/geonames/features/adapter.d.ts.map +1 -1
- package/out/adapters/geonames/features/adapter.js +25 -11
- package/out/adapters/geonames/features/adapter.js.map +1 -1
- package/out/adapters/overture/adapter.d.ts.map +1 -1
- package/out/adapters/overture/adapter.js +21 -5
- package/out/adapters/overture/adapter.js.map +1 -1
- package/out/adapters/street/line.d.ts +4 -4
- package/out/adapters/street/line.d.ts.map +1 -1
- package/out/adapters/street/line.js +5 -5
- package/out/adapters/street/line.js.map +1 -1
- package/out/adapters/street/unit.d.ts +4 -0
- package/out/adapters/street/unit.d.ts.map +1 -1
- package/out/adapters/street/unit.js +3 -0
- package/out/adapters/street/unit.js.map +1 -1
- package/out/adapters/wof/admin/json/adapter.d.ts +7 -0
- package/out/adapters/wof/admin/json/adapter.d.ts.map +1 -1
- package/out/adapters/wof/admin/json/adapter.js +28 -3
- package/out/adapters/wof/admin/json/adapter.js.map +1 -1
- package/out/adapters/wof/json-rows.d.ts +8 -0
- package/out/adapters/wof/json-rows.d.ts.map +1 -1
- package/out/adapters/wof/json-rows.js +56 -4
- package/out/adapters/wof/json-rows.js.map +1 -1
- package/out/adapters/wof/sample.d.ts +12 -0
- package/out/adapters/wof/sample.d.ts.map +1 -1
- package/out/adapters/wof/sample.js +37 -6
- package/out/adapters/wof/sample.js.map +1 -1
- package/out/au/adapters/gnaf/source.d.ts +9 -0
- package/out/au/adapters/gnaf/source.d.ts.map +1 -1
- package/out/au/adapters/gnaf/source.js +9 -0
- package/out/au/adapters/gnaf/source.js.map +1 -1
- package/out/build/code-hash.js +1 -1
- package/out/build/code-hash.js.map +1 -1
- package/out/cjk/foreign-places.js +1 -1
- package/out/cjk/foreign-places.js.map +1 -1
- package/out/fr/adapters/ban/adapter.d.ts.map +1 -1
- package/out/fr/adapters/ban/adapter.js +49 -7
- package/out/fr/adapters/ban/adapter.js.map +1 -1
- package/out/fr/recipes/admin-split.d.ts.map +1 -1
- package/out/fr/recipes/admin-split.js +15 -2
- package/out/fr/recipes/admin-split.js.map +1 -1
- package/out/fr/recipes/lieudit.js +1 -1
- package/out/fr/recipes/lieudit.js.map +1 -1
- package/out/fr/recipes/order.d.ts.map +1 -1
- package/out/fr/recipes/order.js +16 -5
- package/out/fr/recipes/order.js.map +1 -1
- package/out/international/recipes/locale.js +1 -1
- package/out/international/recipes/locale.js.map +1 -1
- package/out/kr/adapters/localdata/permit-rows.js +1 -1
- package/out/kr/adapters/localdata/permit-rows.js.map +1 -1
- package/out/parquet/schema.d.ts +6 -0
- package/out/parquet/schema.d.ts.map +1 -1
- package/out/parquet/schema.js +6 -0
- package/out/parquet/schema.js.map +1 -1
- package/out/recipes/po/box/cedex/recipe.js +1 -1
- package/out/recipes/po/box/cedex/recipe.js.map +1 -1
- package/out/recipes/po/box/cedex/vocabulary.d.ts +1 -1
- package/out/recipes/po/box/cedex/vocabulary.d.ts.map +1 -1
- package/out/recipes/po/box/cedex/vocabulary.js +4 -4
- package/out/recipes/po/box/cedex/vocabulary.js.map +1 -1
- package/out/recipes/trailing-region.d.ts.map +1 -1
- package/out/recipes/trailing-region.js +122 -17
- package/out/recipes/trailing-region.js.map +1 -1
- package/out/synthesizers/po-box.d.ts +7 -0
- package/out/synthesizers/po-box.d.ts.map +1 -1
- package/out/synthesizers/po-box.js +36 -12
- package/out/synthesizers/po-box.js.map +1 -1
- package/out/test-kit/corpus-recipe.d.ts +3 -0
- package/out/test-kit/corpus-recipe.d.ts.map +1 -1
- package/out/test-kit/corpus-recipe.js.map +1 -1
- package/out/tools/anthropic/batches.d.ts +117 -0
- package/out/tools/anthropic/batches.d.ts.map +1 -0
- package/out/tools/anthropic/batches.js +141 -0
- package/out/tools/anthropic/batches.js.map +1 -0
- package/out/tools/anthropic/labeling.d.ts +97 -0
- package/out/tools/anthropic/labeling.d.ts.map +1 -0
- package/out/tools/anthropic/labeling.js +146 -0
- package/out/tools/anthropic/labeling.js.map +1 -0
- package/out/tools/compact-v9.d.ts +124 -0
- package/out/tools/compact-v9.d.ts.map +1 -0
- package/out/tools/compact-v9.js +507 -0
- package/out/tools/compact-v9.js.map +1 -0
- package/out/tools/fetch/wikidata/vital-places/entities.d.ts +3 -0
- package/out/tools/fetch/wikidata/vital-places/entities.d.ts.map +1 -1
- package/out/tools/fetch/wikidata/vital-places/entities.js +19 -1
- package/out/tools/fetch/wikidata/vital-places/entities.js.map +1 -1
- package/out/tools/fetch/wikidata/vital-places/qrank.d.ts.map +1 -1
- package/out/tools/fetch/wikidata/vital-places/qrank.js +4 -4
- package/out/tools/fetch/wikidata/vital-places/qrank.js.map +1 -1
- package/out/tools/fragment-assay.run.js +1 -1
- package/out/tools/fragment-assay.run.js.map +1 -1
- package/out/tools/name-roles/name-roles.run.d.ts +2 -0
- package/out/tools/name-roles/name-roles.run.d.ts.map +1 -0
- package/out/tools/name-roles/name-roles.run.js +230 -0
- package/out/tools/name-roles/name-roles.run.js.map +1 -0
- package/out/tools/name-roles/prompt.d.ts +166 -0
- package/out/tools/name-roles/prompt.d.ts.map +1 -0
- package/out/tools/name-roles/prompt.js +176 -0
- package/out/tools/name-roles/prompt.js.map +1 -0
- package/out/tools/overlay/deletions.js +1 -1
- package/out/tools/overlay/deletions.js.map +1 -1
- package/out/tools/overlay/draw-weight.d.ts +86 -0
- package/out/tools/overlay/draw-weight.d.ts.map +1 -0
- package/out/tools/overlay/draw-weight.js +131 -0
- package/out/tools/overlay/draw-weight.js.map +1 -0
- package/out/tools/place-twins/place-twins.run.d.ts +2 -0
- package/out/tools/place-twins/place-twins.run.d.ts.map +1 -0
- package/out/tools/place-twins/place-twins.run.js +385 -0
- package/out/tools/place-twins/place-twins.run.js.map +1 -0
- package/out/tools/place-twins/prompt.d.ts +169 -0
- package/out/tools/place-twins/prompt.d.ts.map +1 -0
- package/out/tools/place-twins/prompt.js +183 -0
- package/out/tools/place-twins/prompt.js.map +1 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.d.ts +2 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.d.ts.map +1 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.js +302 -0
- package/out/tools/prominent-shapes/prominent-shapes.run.js.map +1 -0
- package/out/tools/prominent-shapes/prompt.d.ts +74 -0
- package/out/tools/prominent-shapes/prompt.d.ts.map +1 -0
- package/out/tools/prominent-shapes/prompt.js +156 -0
- package/out/tools/prominent-shapes/prompt.js.map +1 -0
- package/out/tools/prominent-shapes/read-seeds.d.ts +23 -0
- package/out/tools/prominent-shapes/read-seeds.d.ts.map +1 -0
- package/out/tools/prominent-shapes/read-seeds.js +219 -0
- package/out/tools/prominent-shapes/read-seeds.js.map +1 -0
- package/out/tools/prominent-shapes/seeds.d.ts +132 -0
- package/out/tools/prominent-shapes/seeds.d.ts.map +1 -0
- package/out/tools/prominent-shapes/seeds.js +178 -0
- package/out/tools/prominent-shapes/seeds.js.map +1 -0
- package/out/tools/prominent-shapes/validate.d.ts +152 -0
- package/out/tools/prominent-shapes/validate.d.ts.map +1 -0
- package/out/tools/prominent-shapes/validate.js +389 -0
- package/out/tools/prominent-shapes/validate.js.map +1 -0
- package/out/tools/source-register/build.d.ts.map +1 -1
- package/out/tools/source-register/build.js +1 -0
- package/out/tools/source-register/build.js.map +1 -1
- package/out/training/config/admission.d.ts +2 -1
- package/out/training/config/admission.d.ts.map +1 -1
- package/out/training/config/admission.js +9 -2
- package/out/training/config/admission.js.map +1 -1
- package/out/training/config/schema.d.ts +276 -1
- package/out/training/config/schema.d.ts.map +1 -1
- package/out/training/config/schema.js +64 -1
- package/out/training/config/schema.js.map +1 -1
- package/out/types.d.ts +21 -0
- package/out/types.d.ts.map +1 -1
- package/out/types.js +13 -0
- package/out/types.js.map +1 -1
- package/out/us/adapters/usgov/usgs-structures/adapter.d.ts.map +1 -1
- package/out/us/adapters/usgov/usgs-structures/adapter.js +78 -4
- package/out/us/adapters/usgov/usgs-structures/adapter.js.map +1 -1
- package/out/utils/split.js +1 -1
- package/out/utils/split.js.map +1 -1
- package/package.json +24 -24
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @file A client for Anthropic's Message Batches endpoint. The corpus labeling tools submit their requests through it.
|
|
6
|
+
*
|
|
7
|
+
* A batch is asynchronous: `createMessageBatch` returns an id, `readMessageBatch` reports its state,
|
|
8
|
+
* and `readMessageBatchResults` returns one line per request once the state is `ended`.
|
|
9
|
+
* Result lines arrive in any order, so a caller joins them to its requests by `custom_id`.
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { APIClient, pluckResponseData } from "@mailwoman/core/api"
|
|
13
|
+
import { tryParsingJSON } from "@mailwoman/core/values/json"
|
|
14
|
+
import { TextSpliterator } from "spliterator"
|
|
15
|
+
|
|
16
|
+
import { $private } from "#env"
|
|
17
|
+
|
|
18
|
+
const BATCHES_URL = "https://api.anthropic.com/v1/messages/batches"
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The most requests one batch accepts.
|
|
22
|
+
*/
|
|
23
|
+
export const MAX_BATCH_REQUESTS = 100_000
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* One Messages request inside a batch, addressed by a caller-chosen id of at most 64 characters.
|
|
27
|
+
*/
|
|
28
|
+
export interface MessageBatchRequest {
|
|
29
|
+
custom_id: string
|
|
30
|
+
params: Record<string, unknown>
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* The state of a submitted batch.
|
|
35
|
+
*/
|
|
36
|
+
export interface MessageBatch {
|
|
37
|
+
id: string
|
|
38
|
+
processing_status: "in_progress" | "canceling" | "ended"
|
|
39
|
+
request_counts: { processing: number; succeeded: number; errored: number; canceled: number; expired: number }
|
|
40
|
+
results_url: string | null
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Token counts the API bills a response for.
|
|
45
|
+
*/
|
|
46
|
+
export interface MessageUsage {
|
|
47
|
+
input_tokens: number
|
|
48
|
+
output_tokens: number
|
|
49
|
+
cache_creation_input_tokens?: number | null
|
|
50
|
+
cache_read_input_tokens?: number | null
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* One request's outcome in a finished batch.
|
|
55
|
+
*
|
|
56
|
+
* `message` is present only when `type` is `succeeded`.
|
|
57
|
+
*/
|
|
58
|
+
export interface MessageBatchResult {
|
|
59
|
+
custom_id: string
|
|
60
|
+
result: {
|
|
61
|
+
type: "succeeded" | "errored" | "canceled" | "expired"
|
|
62
|
+
message?: {
|
|
63
|
+
content: Array<{ type: string; text?: string }>
|
|
64
|
+
stop_reason: string | null
|
|
65
|
+
usage: MessageUsage
|
|
66
|
+
}
|
|
67
|
+
error?: unknown
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Dollars per million tokens for one model on the batch endpoint.
|
|
73
|
+
*/
|
|
74
|
+
export interface TokenPrice {
|
|
75
|
+
input: number
|
|
76
|
+
output: number
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Creates the client every batch call shares.
|
|
81
|
+
*
|
|
82
|
+
* @throws When `ANTHROPIC_API_KEY` is unset.
|
|
83
|
+
*/
|
|
84
|
+
export function createAnthropicClient(): APIClient {
|
|
85
|
+
const apiKey = $private.ANTHROPIC_API_KEY
|
|
86
|
+
|
|
87
|
+
if (!apiKey) throw new Error("ANTHROPIC_API_KEY is required to call Anthropic")
|
|
88
|
+
|
|
89
|
+
return new APIClient({
|
|
90
|
+
displayName: "anthropic",
|
|
91
|
+
retry: true,
|
|
92
|
+
axios: {
|
|
93
|
+
headers: { "x-api-key": apiKey, "anthropic-version": "2023-06-01", "Content-Type": "application/json" },
|
|
94
|
+
},
|
|
95
|
+
})
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Sends one Messages request outside a batch, at the standard price,
|
|
100
|
+
* and returns it in a batch result's shape.
|
|
101
|
+
*
|
|
102
|
+
* A labeling tool sends one of these before a batch to confirm the API accepts its
|
|
103
|
+
* parameters and to measure the tokens one request uses.
|
|
104
|
+
*/
|
|
105
|
+
export async function createMessage(client: APIClient, request: MessageBatchRequest): Promise<MessageBatchResult> {
|
|
106
|
+
const message = (await client
|
|
107
|
+
.fetch<NonNullable<MessageBatchResult["result"]["message"]>>({
|
|
108
|
+
url: "https://api.anthropic.com/v1/messages",
|
|
109
|
+
method: "post",
|
|
110
|
+
timeout: 600_000,
|
|
111
|
+
data: request.params,
|
|
112
|
+
cache: false,
|
|
113
|
+
})
|
|
114
|
+
.then(pluckResponseData)) as NonNullable<MessageBatchResult["result"]["message"]>
|
|
115
|
+
|
|
116
|
+
return { custom_id: request.custom_id, result: { type: "succeeded", message } }
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Submits `requests` as one batch and returns its initial state.
|
|
121
|
+
*
|
|
122
|
+
* @throws When `requests` is empty or exceeds `MAX_BATCH_REQUESTS`.
|
|
123
|
+
*/
|
|
124
|
+
export async function createMessageBatch(client: APIClient, requests: MessageBatchRequest[]): Promise<MessageBatch> {
|
|
125
|
+
if (!requests.length || requests.length > MAX_BATCH_REQUESTS) {
|
|
126
|
+
throw new Error(`A batch takes 1 to ${MAX_BATCH_REQUESTS} requests, and this one has ${requests.length}`)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return client
|
|
130
|
+
.fetch<MessageBatch>({ url: BATCHES_URL, method: "post", timeout: 600_000, data: { requests }, cache: false })
|
|
131
|
+
.then(pluckResponseData) as Promise<MessageBatch>
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Reads the current state of the batch `id`.
|
|
136
|
+
*/
|
|
137
|
+
export async function readMessageBatch(client: APIClient, id: string): Promise<MessageBatch> {
|
|
138
|
+
return client
|
|
139
|
+
.fetch<MessageBatch>({ url: `${BATCHES_URL}/${id}`, timeout: 60_000, cache: false })
|
|
140
|
+
.then(pluckResponseData) as Promise<MessageBatch>
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Reads every result line of the finished batch `id`.
|
|
145
|
+
*
|
|
146
|
+
* @throws When the batch is still in progress, or when a line of the result file fails to parse.
|
|
147
|
+
*/
|
|
148
|
+
export async function readMessageBatchResults(client: APIClient, id: string): Promise<MessageBatchResult[]> {
|
|
149
|
+
const batch = await readMessageBatch(client, id)
|
|
150
|
+
|
|
151
|
+
if (batch.processing_status !== "ended") {
|
|
152
|
+
throw new Error(`Batch ${id} is ${batch.processing_status}; its results exist only once it has ended`)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const { data } = await client.fetch<string>({
|
|
156
|
+
url: `${BATCHES_URL}/${id}/results`,
|
|
157
|
+
timeout: 600_000,
|
|
158
|
+
responseType: "text",
|
|
159
|
+
transformResponse: (body: unknown) => body,
|
|
160
|
+
cache: false,
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
return parseMessageBatchResults(String(data), `Batch ${id}`)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Parses the JSONL body of a batch's results, as the API returns it or as a run saved it.
|
|
168
|
+
*
|
|
169
|
+
* @param source Where the body came from, as an error states it.
|
|
170
|
+
* @throws When a line fails to parse or lacks a request id or outcome, or when the body holds no result.
|
|
171
|
+
*/
|
|
172
|
+
export function parseMessageBatchResults(body: string, source: string): MessageBatchResult[] {
|
|
173
|
+
const results: MessageBatchResult[] = []
|
|
174
|
+
|
|
175
|
+
for (const line of TextSpliterator.from(body)) {
|
|
176
|
+
if (line.trim() === "") continue
|
|
177
|
+
|
|
178
|
+
const parsed = tryParsingJSON(line) as MessageBatchResult | null
|
|
179
|
+
|
|
180
|
+
if (parsed?.custom_id == null || parsed.result?.type == null) {
|
|
181
|
+
throw new Error(`${source} holds a result line that is not a batch result: ${line.slice(0, 200)}`)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
results.push(parsed)
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (!results.length) throw new Error(`${source} holds no batch result`)
|
|
188
|
+
|
|
189
|
+
return results
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Returns the text of a succeeded result, or `null` for any other outcome
|
|
194
|
+
* or a response that stopped at `max_tokens`.
|
|
195
|
+
*/
|
|
196
|
+
export function resultText(result: MessageBatchResult): string | null {
|
|
197
|
+
const message = result.result.message
|
|
198
|
+
|
|
199
|
+
if (result.result.type !== "succeeded" || !message || message.stop_reason !== "end_turn") return null
|
|
200
|
+
|
|
201
|
+
return message.content.find((block) => block.type === "text")?.text ?? null
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Sums the dollars the succeeded results cost at `price`.
|
|
206
|
+
*/
|
|
207
|
+
export function batchCostUSD(results: readonly MessageBatchResult[], price: TokenPrice): number {
|
|
208
|
+
let input = 0
|
|
209
|
+
let output = 0
|
|
210
|
+
|
|
211
|
+
for (const { result } of results) {
|
|
212
|
+
const usage = result.message?.usage
|
|
213
|
+
|
|
214
|
+
if (!usage) continue
|
|
215
|
+
|
|
216
|
+
input += usage.input_tokens + (usage.cache_creation_input_tokens ?? 0) + (usage.cache_read_input_tokens ?? 0)
|
|
217
|
+
output += usage.output_tokens
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
return (input * price.input + output * price.output) / 1_000_000
|
|
221
|
+
}
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors
|
|
2
|
+
// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* @file The submit, status and collect steps every batch labeling tool shares.
|
|
6
|
+
*
|
|
7
|
+
* A labeling tool splits its items into chunks, one request each, and the model returns one label per item.
|
|
8
|
+
* `submitLabelingBatch` writes `chunks.jsonl` and `batch.json` to the tool's output directory,
|
|
9
|
+
* and `collectLabelingBatch` joins the finished batch back to those chunks by `custom_id`.
|
|
10
|
+
* A request that failed, stopped at `max_tokens`, or returned labels the tool's parser refuses is listed as failed
|
|
11
|
+
* with its reason, and its items receive no label.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { readLocalJSONFile } from "@mailwoman/core/fs/readers"
|
|
15
|
+
import { writeLocalJSONFile, writeLocalJSONLFile } from "@mailwoman/core/fs/writers"
|
|
16
|
+
import type { PathBuilder } from "path-ts"
|
|
17
|
+
import { JSONSpliterator } from "spliterator"
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
batchCostUSD,
|
|
21
|
+
createAnthropicClient,
|
|
22
|
+
createMessage,
|
|
23
|
+
createMessageBatch,
|
|
24
|
+
readMessageBatch,
|
|
25
|
+
readMessageBatchResults,
|
|
26
|
+
resultText,
|
|
27
|
+
type MessageBatch,
|
|
28
|
+
type MessageBatchRequest,
|
|
29
|
+
type MessageBatchResult,
|
|
30
|
+
type MessageUsage,
|
|
31
|
+
type TokenPrice,
|
|
32
|
+
} from "#tools/anthropic/batches"
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Dollars per million tokens on the batch endpoint, at half the standard price.
|
|
36
|
+
*/
|
|
37
|
+
const BATCH_PRICES: Record<string, TokenPrice> = {
|
|
38
|
+
"claude-opus-5-5": { input: 2, output: 10 },
|
|
39
|
+
"claude-sonnet-5-5": { input: 1, output: 5 },
|
|
40
|
+
"claude-haiku-5-5": { input: 0.05, output: 0.25 },
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Returns the batch price of `model`.
|
|
45
|
+
*
|
|
46
|
+
* @throws When no price is recorded for it, so a cost is never reported from a guessed rate.
|
|
47
|
+
*/
|
|
48
|
+
export function batchPrice(model: string): TokenPrice {
|
|
49
|
+
const price = BATCH_PRICES[model]
|
|
50
|
+
|
|
51
|
+
if (!price) throw new Error(`No batch price is recorded for ${model}; add it to BATCH_PRICES`)
|
|
52
|
+
|
|
53
|
+
return price
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* The items one request labels.
|
|
58
|
+
*/
|
|
59
|
+
export interface LabelingChunk<Item> {
|
|
60
|
+
custom_id: string
|
|
61
|
+
items: Item[]
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* What `submitLabelingBatch` records, so a later `status` or `collect` reads
|
|
66
|
+
* the settings the batch ran under.
|
|
67
|
+
*/
|
|
68
|
+
export interface LabelingBatchRecord {
|
|
69
|
+
id: string
|
|
70
|
+
model: string
|
|
71
|
+
effort: string
|
|
72
|
+
requests: number
|
|
73
|
+
items: number
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The model and effort a tool's requests run under.
|
|
78
|
+
*/
|
|
79
|
+
export interface LabelingSettings {
|
|
80
|
+
model: string
|
|
81
|
+
effort: string
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
type ToParams<Item> = (items: readonly Item[], settings: LabelingSettings) => MessageBatchRequest["params"]
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Parses one response into a label per item of its request, in item order,
|
|
88
|
+
* and throws on a response it refuses.
|
|
89
|
+
*/
|
|
90
|
+
type ParseLabels<Item, Label> = (text: string, items: readonly Item[]) => Label[]
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Splits `items` into requests of `size`, with ids `<prefix>-<n>`.
|
|
94
|
+
*/
|
|
95
|
+
export function toLabelingChunks<Item>(items: readonly Item[], size: number, prefix: string): LabelingChunk<Item>[] {
|
|
96
|
+
if (!Number.isInteger(size) || size < 1)
|
|
97
|
+
throw new Error(`A chunk holds a whole number of items, and --chunk was ${size}`)
|
|
98
|
+
|
|
99
|
+
const chunks: LabelingChunk<Item>[] = []
|
|
100
|
+
|
|
101
|
+
for (let start = 0; start < items.length; start += size) {
|
|
102
|
+
chunks.push({ custom_id: `${prefix}-${chunks.length}`, items: items.slice(start, start + size) })
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
return chunks
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Sends `count` evenly spaced chunks one at a time at the standard price.
|
|
110
|
+
*
|
|
111
|
+
* @returns Each chunk with its labels and token use, and the batch cost per request those requests imply.
|
|
112
|
+
* @throws When a response stops at `max_tokens` or the parser refuses it,
|
|
113
|
+
* since a batch of the same requests would fail the same way.
|
|
114
|
+
*/
|
|
115
|
+
export async function pilotLabelingRequests<Item, Label>(
|
|
116
|
+
chunks: ReadonlyArray<LabelingChunk<Item>>,
|
|
117
|
+
count: number,
|
|
118
|
+
settings: LabelingSettings,
|
|
119
|
+
toParams: ToParams<Item>,
|
|
120
|
+
parse: ParseLabels<Item, Label>
|
|
121
|
+
): Promise<{
|
|
122
|
+
requests: Array<{ chunk: LabelingChunk<Item>; labels: Label[]; usage: MessageUsage }>
|
|
123
|
+
batchCostPerRequestUSD: number
|
|
124
|
+
}> {
|
|
125
|
+
const client = createAnthropicClient()
|
|
126
|
+
const stride = Math.max(1, Math.floor(chunks.length / count))
|
|
127
|
+
const requests: Array<{ chunk: LabelingChunk<Item>; labels: Label[]; usage: MessageUsage }> = []
|
|
128
|
+
const results: MessageBatchResult[] = []
|
|
129
|
+
|
|
130
|
+
for (let n = 0; n < count && n * stride < chunks.length; n++) {
|
|
131
|
+
const chunk = chunks[n * stride]!
|
|
132
|
+
const result = await createMessage(client, { custom_id: chunk.custom_id, params: toParams(chunk.items, settings) })
|
|
133
|
+
const text = resultText(result)
|
|
134
|
+
|
|
135
|
+
if (text == null)
|
|
136
|
+
throw new Error(`${chunk.custom_id} stopped at ${result.result.message?.stop_reason ?? "no message"}`)
|
|
137
|
+
|
|
138
|
+
requests.push({ chunk, labels: parse(text, chunk.items), usage: result.result.message!.usage })
|
|
139
|
+
results.push(result)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return { requests, batchCostPerRequestUSD: batchCostUSD(results, batchPrice(settings.model)) / results.length }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/**
|
|
146
|
+
* Writes `chunks.jsonl`, creates one batch of the chunks, and records it in `batch.json`.
|
|
147
|
+
*/
|
|
148
|
+
export async function submitLabelingBatch<Item>(
|
|
149
|
+
out: PathBuilder,
|
|
150
|
+
chunks: ReadonlyArray<LabelingChunk<Item>>,
|
|
151
|
+
settings: LabelingSettings,
|
|
152
|
+
toParams: ToParams<Item>
|
|
153
|
+
): Promise<LabelingBatchRecord> {
|
|
154
|
+
batchPrice(settings.model)
|
|
155
|
+
await writeLocalJSONLFile(chunks, out("chunks.jsonl"))
|
|
156
|
+
|
|
157
|
+
const batch = await createMessageBatch(
|
|
158
|
+
createAnthropicClient(),
|
|
159
|
+
chunks.map((chunk) => ({ custom_id: chunk.custom_id, params: toParams(chunk.items, settings) }))
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
const record: LabelingBatchRecord = {
|
|
163
|
+
id: batch.id,
|
|
164
|
+
...settings,
|
|
165
|
+
requests: chunks.length,
|
|
166
|
+
items: chunks.reduce((sum, chunk) => sum + chunk.items.length, 0),
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
await writeLocalJSONFile(record, out("batch.json"))
|
|
170
|
+
|
|
171
|
+
return record
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Reads the state of the batch `batch.json` records.
|
|
176
|
+
*/
|
|
177
|
+
export async function readLabelingBatch(out: PathBuilder): Promise<MessageBatch> {
|
|
178
|
+
const { id } = await readLocalJSONFile<LabelingBatchRecord>(out("batch.json"))
|
|
179
|
+
|
|
180
|
+
return readMessageBatch(createAnthropicClient(), id)
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* A request whose items received no label, and why.
|
|
185
|
+
*/
|
|
186
|
+
export interface FailedChunk {
|
|
187
|
+
custom_id: string
|
|
188
|
+
reason: string
|
|
189
|
+
items: number
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Joins the finished batch to its chunks and writes `failed-chunks.jsonl`.
|
|
194
|
+
*
|
|
195
|
+
* @returns Every labeled item beside its label, the failed requests, the result
|
|
196
|
+
* count per outcome type, and the dollars the batch cost.
|
|
197
|
+
* @throws When the batch is still in progress.
|
|
198
|
+
*/
|
|
199
|
+
export async function collectLabelingBatch<Item, Label>(
|
|
200
|
+
out: PathBuilder,
|
|
201
|
+
parse: ParseLabels<Item, Label>
|
|
202
|
+
): Promise<{
|
|
203
|
+
record: LabelingBatchRecord
|
|
204
|
+
labeled: Array<{ item: Item; label: Label }>
|
|
205
|
+
failed: FailedChunk[]
|
|
206
|
+
resultsByType: Record<string, number>
|
|
207
|
+
costUSD: number
|
|
208
|
+
}> {
|
|
209
|
+
const record = await readLocalJSONFile<LabelingBatchRecord>(out("batch.json"))
|
|
210
|
+
const chunks = await JSONSpliterator.fromAsync<LabelingChunk<Item>>(out("chunks.jsonl")).toArray()
|
|
211
|
+
const results = await readMessageBatchResults(createAnthropicClient(), record.id)
|
|
212
|
+
const byCustomID = new Map(results.map((result) => [result.custom_id, result]))
|
|
213
|
+
const labeled: Array<{ item: Item; label: Label }> = []
|
|
214
|
+
const failed: FailedChunk[] = []
|
|
215
|
+
|
|
216
|
+
for (const chunk of chunks) {
|
|
217
|
+
const result = byCustomID.get(chunk.custom_id)
|
|
218
|
+
const text = result ? resultText(result) : null
|
|
219
|
+
|
|
220
|
+
if (!result || text == null) {
|
|
221
|
+
const reason = result
|
|
222
|
+
? `${result.result.type}:${result.result.message?.stop_reason ?? "no message"}`
|
|
223
|
+
: "no result line"
|
|
224
|
+
|
|
225
|
+
failed.push({ custom_id: chunk.custom_id, reason, items: chunk.items.length })
|
|
226
|
+
|
|
227
|
+
continue
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
try {
|
|
231
|
+
const labels = parse(text, chunk.items)
|
|
232
|
+
|
|
233
|
+
for (const [i, item] of chunk.items.entries()) {
|
|
234
|
+
labeled.push({ item, label: labels[i]! })
|
|
235
|
+
}
|
|
236
|
+
} catch (error) {
|
|
237
|
+
failed.push({ custom_id: chunk.custom_id, reason: (error as Error).message, items: chunk.items.length })
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
await writeLocalJSONLFile(failed, out("failed-chunks.jsonl"))
|
|
242
|
+
|
|
243
|
+
return {
|
|
244
|
+
record,
|
|
245
|
+
labeled,
|
|
246
|
+
failed,
|
|
247
|
+
resultsByType: countEach(results.map((result) => result.result.type)),
|
|
248
|
+
costUSD: Number(batchCostUSD(results, batchPrice(record.model)).toFixed(2)),
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/**
|
|
253
|
+
* Counts each distinct value.
|
|
254
|
+
*/
|
|
255
|
+
export function countEach(values: Iterable<string>): Record<string, number> {
|
|
256
|
+
const counts: Record<string, number> = {}
|
|
257
|
+
|
|
258
|
+
for (const value of values) {
|
|
259
|
+
counts[value] = (counts[value] ?? 0) + 1
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return counts
|
|
263
|
+
}
|