// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file The request and response shapes of the variant-name role labeling: what one variant name on a * Who's On First locality is, as a language model reads it from the place, its county and the other * localities that hold the same name as their primary one. */ import { stringifyJSON, tryParsingJSON } from "@mailwoman/core/values/json" import type { MessageBatchRequest } from "#tools/anthropic/batches" /** * What a variant name is in relation to the place that holds it. */ export const VariantNameRole = { /** * A respelling of the place's own primary name, such as `Cross Roads` on `Crossroads`. */ Spelling: "same_place_spelling", /** * An earlier name of the same settlement. */ Former: "same_place_former", /** * Another name in present use for the same settlement. */ Alternate: "same_place_alternate", /** * The name of a separate community, standing or absorbed, near the holder. */ OtherPlace: "other_place", /** * The name of a post office, station, landing, mine or other feature that isn't a settlement. */ Feature: "feature", /** * The evidence supplied and the model's recall decide no role. */ Unknown: "unknown", } as const export type VariantNameRole = (typeof VariantNameRole)[keyof typeof VariantNameRole] /** * What a label rests on. */ export const LabelBasis = { /** * The model recalls this specific place's naming history. */ Known: "known", /** * The supplied collision and distance decide it. */ Context: "context", /** * Only the shape of the two strings decides it. */ Form: "form", } as const export type LabelBasis = (typeof LabelBasis)[keyof typeof LabelBasis] const CONFIDENCES = ["high", "medium", "low"] as const export type LabelConfidence = (typeof CONFIDENCES)[number] /** * One variant name with the evidence the model reads beside it. */ export interface VariantNameItem { /** * The holder's WOF id. */ wofID: number /** * The variant name as the `names` table writes it. */ name: string /** * The `names.language` of the row, `und` for a GNIS variant. */ language: string /** * The holder's primary name. */ holder: string county: string | null region: string | null latitude: number longitude: number /** * The holder's other variant names. */ siblings: string[] /** * The count of other US localities whose primary name has this name's key. */ collisions: number /** * The nearest of those localities, or `null` when the count is zero. */ nearest: { wofID: number; name: string; county: string | null; region: string | null; km: number } | null } /** * A label states the role the model assigned to one item, what the role rests on, * and the model's confidence. */ export interface VariantNameLabel { role: VariantNameRole basis: LabelBasis confidence: LabelConfidence } /** * The system prompt of every name-role request states the six roles, the three bases, * and the rule that a locality holding the variant as its primary name within about * 15 kilometers is evidence of a separate community. */ export const NAME_ROLE_SYSTEM_PROMPT = `You label variant names of United States populated places for a gazetteer. Each item is one variant name that the USGS Geographic Names Information System or Who's On First records on a locality. A geocoder returns the locality when a user types the variant, so the gazetteer needs to know what the variant is. Some variants are earlier or alternate names of the same settlement. Others are the names of separate communities that a record absorbed, and many of those are also the primary name of a different locality elsewhere. For each item you receive: the variant name, the locality that holds it with its county, state and coordinates, the locality's other variant names, the number of other US localities whose primary name is this variant, and the nearest of those with its distance in kilometers. Assign one role: - same_place_spelling: a respelling, spacing, punctuation or abbreviation difference of the holder's own primary name. - same_place_former: an earlier name of the same settlement. - same_place_alternate: another name in present use for the same settlement. - other_place: the name of a separate community, standing today or absorbed, including a neighboring settlement that the nearest collision identifies. - feature: the name of a post office, railroad station, landing, mine, camp or other feature that was never the settlement's name. - unknown: neither your knowledge of the place nor the supplied evidence decides. State the basis: "known" when you recall this specific place's naming history, "context" when the supplied collision and distance decide it, "form" when only the two strings decide it. State your confidence as high, medium or low. A nearby locality with the variant as its primary name, within about 15 kilometers, is strong evidence for other_place. A collision hundreds of kilometers away is a coincidence of common names and decides no role. Prefer unknown at low confidence over a guess. Return one label per item, with the item's index.` /** * The structured-output schema of one response: a label per item, addressed * by the item's index in the request. */ export const NAME_ROLE_RESPONSE_SCHEMA = { type: "object", additionalProperties: false, required: ["labels"], properties: { labels: { type: "array", items: { type: "object", additionalProperties: false, required: ["i", "role", "basis", "confidence"], properties: { i: { type: "integer" }, role: { type: "string", enum: Object.values(VariantNameRole) }, basis: { type: "string", enum: Object.values(LabelBasis) }, confidence: { type: "string", enum: [...CONFIDENCES] }, }, }, }, }, } as const /** * Renders the items of one request as the user message the model reads. */ export function renderNameRoleItems(items: readonly VariantNameItem[]): string { const rows = items.map((item, i) => ({ i, variant: item.name, holder: item.holder, county: item.county, state: item.region, lat: Number(item.latitude.toFixed(3)), lon: Number(item.longitude.toFixed(3)), other_variants: item.siblings, localities_with_this_primary_name: item.collisions, nearest: item.nearest ? { name: item.nearest.name, county: item.nearest.county, state: item.nearest.region, km: Math.round(item.nearest.km), } : null, })) return rows.map((row) => stringifyJSON(row)).join("\n") } /** * Builds the Messages parameters of one request. */ export function nameRoleRequestParams( items: readonly VariantNameItem[], options: { model: string; effort: string } ): MessageBatchRequest["params"] { return { model: options.model, max_tokens: 8000, system: NAME_ROLE_SYSTEM_PROMPT, output_config: { effort: options.effort, format: { type: "json_schema", schema: NAME_ROLE_RESPONSE_SCHEMA } }, messages: [{ role: "user", content: renderNameRoleItems(items) }], } } const ROLES: ReadonlySet = new Set(Object.values(VariantNameRole)) const BASES: ReadonlySet = new Set(Object.values(LabelBasis)) const CONFIDENCE_SET: ReadonlySet = new Set(CONFIDENCES) /** * Parses one response into a label per item index. * * @throws When the text fails to parse as the schema's object, an index is outside * the request or repeated, a value is outside its enumeration, or the response * labels a different number of items than the request held. */ export function parseNameRoleResponse(text: string, itemCount: number): VariantNameLabel[] { const parsed = tryParsingJSON(text) as { labels?: unknown } | null if (!parsed || !Array.isArray(parsed.labels)) throw new Error("The response holds no `labels` array") const labels: Array = Array.from({ length: itemCount }, () => null) for (const entry of parsed.labels as Array>) { const { i, role, basis, confidence } = entry if (typeof i !== "number" || !Number.isInteger(i) || i < 0 || i >= itemCount) { throw new Error(`The response labels index ${String(i)}, and the request held ${itemCount} items`) } if (labels[i]) throw new Error(`The response labels index ${i} twice`) if (typeof role !== "string" || !ROLES.has(role)) throw new Error(`Index ${i} has the role ${String(role)}`) if (typeof basis !== "string" || !BASES.has(basis)) throw new Error(`Index ${i} has the basis ${String(basis)}`) if (typeof confidence !== "string" || !CONFIDENCE_SET.has(confidence)) { throw new Error(`Index ${i} has the confidence ${String(confidence)}`) } labels[i] = { role: role as VariantNameRole, basis: basis as LabelBasis, confidence: confidence as LabelConfidence } } const missing = labels.findIndex((label) => label == null) if (missing !== -1) throw new Error(`The response leaves index ${missing} of ${itemCount} unlabeled`) return labels as VariantNameLabel[] }