// 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 place-twin adjudication: whether a place the admin build * added from Overture or GeoNames, having matched no WOF record by id or by name key, is nevertheless * the same settlement as a WOF record within the match radius under a different spelling or script. */ import { stringifyJSON, tryParsingJSON } from "@mailwoman/core/values/json" import type { MessageBatchRequest } from "#tools/anthropic/batches" /** * Why the model paired, or declined to pair, an added place with a WOF record. */ export const TwinReason = { /** * The two names write one name in two scripts or romanizations. */ Transliteration: "transliteration", /** * The two names are one name in two languages. */ Translation: "translation", /** * The two names differ by spelling, spacing, an article, an abbreviation or an administrative suffix. */ Spelling: "spelling", /** * The model recalls that the two names belong to one settlement. */ Known: "known_same", /** * The names belong to different settlements. */ Different: "different_place", /** * The evidence decides neither way. */ Unclear: "unclear", } as const export type TwinReason = (typeof TwinReason)[keyof typeof TwinReason] const MATCH_REASONS: ReadonlySet = new Set([ TwinReason.Transliteration, TwinReason.Translation, TwinReason.Spelling, TwinReason.Known, ]) const CONFIDENCES = ["high", "medium", "low"] as const export type TwinConfidence = (typeof CONFIDENCES)[number] /** * A WOF record near an added place. */ export interface TwinCandidate { wofID: number /** * The record's primary name first, then its other names. */ names: string[] placetype: string km: number } /** * One added place with the WOF records inside the match radius. */ export interface AddedPlaceItem { /** * The id of the place's own row in the admin database. */ id: number source: "overture" | "geonames" /** * The place's id in its source: an Overture GERS id or a GeoNames id. */ sourceID: string /** * The place's primary name first, then its other names. */ names: string[] placetype: string country: string latitude: number longitude: number candidates: TwinCandidate[] /** * How the place's names compare with its candidates' names in code. * `rankItems` orders the items a budget admits by it. */ comparison: NameComparison /** * The highest romanized edit similarity between one of the place's names and one of a candidate's. * It is `null` unless `comparison` is `romanized`. */ similarity: number | null } /** * What the romanizer could compare between an added place's names and its candidates' names. */ export const NameComparison = { /** * At least one pair of names romanizes on both sides, so an edit similarity exists. */ Romanized: "romanized", /** * No pair romanizes on both sides, and at least one pair romanizes on exactly one: * the names are in different scripts. */ CrossScript: "cross_script", /** * No name on either side romanizes. */ Uncovered: "uncovered", } as const export type NameComparison = (typeof NameComparison)[keyof typeof NameComparison] /** * The model's answer for one added place. * * `match` is the paired candidate's index in the item's `candidates`, or `null` * when the place pairs with none. */ export interface TwinLabel { match: number | null reason: TwinReason confidence: TwinConfidence } /** * The system prompt of every place-twin request states the four reasons that pair an * added place with a candidate, the two that pair it with none, and the rule that a * short distance without a name relation pairs no two places. */ export const PLACE_TWIN_SYSTEM_PROMPT = `You adjudicate duplicate settlements for a gazetteer. The gazetteer holds Who's On First records and adds places from Overture and GeoNames. An added place joins a Who's On First record when the two share an identifier or a normalized name within 5 kilometers. Each item below is an added place that joined none, with the Who's On First settlements within 5 kilometers of it. The names differ, so either the added place is a separate settlement, or it is one of the candidates written in another script, language, romanization or spelling. For each item you receive the added place's names, placetype, country and coordinates, and each candidate's index, names, placetype and distance in kilometers. Decide whether the added place is the same settlement as exactly one candidate: - transliteration: the names write one name in two scripts or romanization systems. - translation: the names are one name in two languages, including an exonym. - spelling: the names differ by spelling, diacritics, spacing, an article, an abbreviation, or an administrative word such as village, commune, town or its local equivalent. - known_same: you recall that the two names belong to one settlement, although the strings do not show it. - different_place: the names belong to different settlements. Two villages a few kilometers apart with unrelated names are different places, and so are places distinguished by a qualifier such as upper and lower, old and new, north and south, or a number. - unclear: the evidence decides neither way. Give "match" as the index of the candidate for the first four reasons, and -1 for different_place and unclear. A neighborhood or hamlet inside a larger candidate is a different place. Distance alone never establishes a match. State your confidence as high, medium or low, and prefer unclear over a guess. Return one label per item, with the item's index.` /** * The structured-output schema of one response. */ export const PLACE_TWIN_RESPONSE_SCHEMA = { type: "object", additionalProperties: false, required: ["labels"], properties: { labels: { type: "array", items: { type: "object", additionalProperties: false, required: ["i", "match", "reason", "confidence"], properties: { i: { type: "integer" }, match: { type: "integer" }, reason: { type: "string", enum: Object.values(TwinReason) }, confidence: { type: "string", enum: [...CONFIDENCES] }, }, }, }, }, } as const /** * Renders the items of one request as the user message the model reads. */ export function renderPlaceTwinItems(items: readonly AddedPlaceItem[]): string { return items .map((item, i) => stringifyJSON({ i, added: { names: item.names, placetype: item.placetype, country: item.country }, lat: Number(item.latitude.toFixed(3)), lon: Number(item.longitude.toFixed(3)), candidates: item.candidates.map((candidate, index) => ({ index, names: candidate.names, placetype: candidate.placetype, km: Number(candidate.km.toFixed(1)), })), }) ) .join("\n") } /** * Builds the Messages parameters of one request. */ export function placeTwinRequestParams( items: readonly AddedPlaceItem[], options: { model: string; effort: string } ): MessageBatchRequest["params"] { return { model: options.model, max_tokens: 8000, system: PLACE_TWIN_SYSTEM_PROMPT, output_config: { effort: options.effort, format: { type: "json_schema", schema: PLACE_TWIN_RESPONSE_SCHEMA } }, messages: [{ role: "user", content: renderPlaceTwinItems(items) }], } } const REASONS: ReadonlySet = new Set(Object.values(TwinReason)) const CONFIDENCE_SET: ReadonlySet = new Set(CONFIDENCES) /** * Parses one response into a label per item, given the candidate count of each item of the request. * * @throws When the text fails to parse as the schema's object, an index is outside * the request or repeated, an item is unlabeled, a value is outside its enumeration, * a match index is outside the item's candidates, or a match and its reason disagree. */ export function parsePlaceTwinResponse(text: string, candidateCounts: readonly number[]): TwinLabel[] { 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 = candidateCounts.map(() => null) for (const entry of parsed.labels as Array>) { const { i, match, reason, confidence } = entry if (typeof i !== "number" || !Number.isInteger(i) || i < 0 || i >= labels.length) { throw new Error(`The response labels index ${String(i)}, and the request held ${labels.length} items`) } if (labels[i]) throw new Error(`The response labels index ${i} twice`) if (typeof reason !== "string" || !REASONS.has(reason)) throw new Error(`Index ${i} has the reason ${String(reason)}`) if (typeof confidence !== "string" || !CONFIDENCE_SET.has(confidence)) { throw new Error(`Index ${i} has the confidence ${String(confidence)}`) } if (typeof match !== "number" || !Number.isInteger(match) || match < -1 || match >= candidateCounts[i]!) { throw new Error(`Index ${i} pairs with candidate ${String(match)} of ${candidateCounts[i]}`) } if (MATCH_REASONS.has(reason) !== match >= 0) { throw new Error(`Index ${i} gives the reason ${reason} with the match ${match}`) } labels[i] = { match: match >= 0 ? match : null, reason: reason as TwinReason, confidence: confidence as TwinConfidence, } } const missing = labels.findIndex((label) => label == null) if (missing !== -1) throw new Error(`The response leaves index ${missing} of ${labels.length} unlabeled`) return labels as TwinLabel[] }