// SPDX-FileCopyrightText: Teffen Ellis and Mailwoman contributors // SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Commercial /** * @file The request that asks a language model for the query forms of a country's prominent places (#3156). * * One request lists about ten places of one country. * Each place lists its surfaces under keys, and the model returns texts with the keys each contains. * The model decides which surfaces people combine, in which order, case and punctuation. * It supplies no name: `#tools/prominent-shapes/validate` drops a text holding anything but cited surfaces. */ import { stringifyJSON } from "@mailwoman/core/values/json" import type { MessageBatchRequest } from "#tools/anthropic/batches" import { type SeedSurface, type ShapeSeed, SurfaceSlot } from "#tools/prominent-shapes/seeds" /** * The worked example of the instructions: a place's surface lines as a request renders them, * and one form citing the second name and the second country by their numbered keys. */ const SHAPE_KEY_EXAMPLE = { surfaces: 'n1="Munich" n2="München"[deu] with country surfaces c1="Germany" c2="Deutschland"[deu],', form: '{"raw": "München, Deutschland", "uses": ["n2", "c2"]}', } as const /** * The instructions every request shares. */ export const SHAPE_SYSTEM_PROMPT = [ "You write the short queries people type into a map or geocoder search box to find a well-known place.", "", "Each request names one country and lists places in it. Every place lists its surfaces, each under a key", "made of a slot letter and a number, such as n1, n2 or c3. The letter is the surface's slot:", "n = the place's own name, p = its parent city, r = its region (state, province, prefecture),", "a = the region's abbreviation, c = the country. A bracket after a surface is its language code.", "", "For each place, write the queries a person would plausibly type, and for each give `raw` (the query text)", "and `uses` (the keys of the surfaces it contains, in the order they appear in `raw`).", "`uses` lists the numbered keys exactly as supplied, never the bare letter: for a place listing", SHAPE_KEY_EXAMPLE.surfaces, `the form ${SHAPE_KEY_EXAMPLE.form} is right, and "uses": ["n", "c"] is wrong.`, "", "Rules:", "- `raw` contains only the cited surfaces and separators (spaces, commas, and the separators the country's", " own writing uses). Add no other word: no street, postcode, 'city', 'near', article, preposition or suffix.", "- Write each surface exactly as supplied, letter for letter, including its diacritics. You may change its", " letter case only (lower, UPPER, Title). Never abbreviate, translate, transliterate, respell, shorten,", " extend or misspell a surface, and never use a name that isn't in the list.", "- Use exactly one n surface. Use at most one p, at most one of r or a, and at most one c.", "- A place's line states which keys every form must contain; follow it.", "- Keep one language per query: do not put a surface in one script beside a surface in another script.", " Queries in the country's own language and script matter as much as English ones; use each supplied", " language's surfaces together and in that language's customary order and punctuation (for example", " larger-to-smaller without separators where that is how the language writes places).", "- Vary the forms the way real typing varies: the name alone, name then region, name then region", " abbreviation, name then country, with a comma, without a comma, all lower case, and sometimes upper case.", " Prefer the combinations people type most. Skip a combination nobody would type.", "- Do not repeat a `raw`. Return each place under the id given, and every place of the request.", ].join("\n") /** * The structured-output schema of a response. */ export const SHAPE_RESPONSE_SCHEMA = { type: "object", additionalProperties: false, required: ["places"], properties: { places: { type: "array", items: { type: "object", additionalProperties: false, required: ["id", "forms"], properties: { id: { type: "string" }, forms: { type: "array", items: { type: "object", additionalProperties: false, required: ["raw", "uses"], properties: { raw: { type: "string" }, uses: { type: "array", items: { type: "string" } }, }, }, }, }, }, }, }, } as const function renderSurfaces(surfaces: readonly SeedSurface[], slot: SurfaceSlot): string | null { const listed = surfaces.filter((surface) => surface.slot === slot) if (!listed.length) return null return listed .map((surface) => `${surface.key}=${stringifyJSON(surface.text)}${surface.language ? `[${surface.language}]` : ""}`) .join(" ") } /** * The keys every form of `seed` must contain, in the words the request states them. */ function requiredKeys(seed: ShapeSeed): string { if (seed.parent_tag === "locality") return "every form contains one n and one p" if (seed.parent_tag === "region") { return seed.surfaces.some((surface) => surface.slot === SurfaceSlot.RegionAbbreviation) ? "every form contains one n and either one p or one a" : "every form contains one n and one p" } return "every form contains one n" } /** * Renders the places of one request as the user message. * * Every seed is of one country, and that country's surfaces are listed once from the first seed. * * @throws When the seeds are empty or of more than one country. */ export function renderShapeRequest(seeds: readonly ShapeSeed[], formsPerPlace: number): string { const [first] = seeds if (!first || seeds.some((seed) => seed.country !== first.country)) { throw new Error("A request lists the places of exactly one country") } const lines = [ `Country ${first.country}. Country surfaces: ${renderSurfaces(first.surfaces, SurfaceSlot.Country) ?? "none; write no country"}`, `Write about ${formsPerPlace} forms for each place, fewer when the place has few surfaces.`, "", ] for (const seed of seeds) { const kind = seed.band === "locality" ? "city or town" : "district of its parent city" lines.push(`Place ${seed.wof_id} (${kind}; ${requiredKeys(seed)})`) for (const slot of [SurfaceSlot.Name, SurfaceSlot.Parent, SurfaceSlot.Region, SurfaceSlot.RegionAbbreviation]) { const rendered = renderSurfaces(seed.surfaces, slot) if (rendered) { lines.push(` ${rendered}`) } } } return lines.join("\n") } /** * The settings of a run's requests. */ export interface ShapeRequestOptions { model: string effort: string formsPerPlace: number maxTokens: number } /** * Builds the Messages parameters of one request. */ export function shapeRequestParams( seeds: readonly ShapeSeed[], options: ShapeRequestOptions ): MessageBatchRequest["params"] { return { model: options.model, max_tokens: options.maxTokens, system: SHAPE_SYSTEM_PROMPT, output_config: { effort: options.effort, format: { type: "json_schema", schema: SHAPE_RESPONSE_SCHEMA } }, messages: [{ role: "user", content: renderShapeRequest(seeds, options.formsPerPlace) }], } } /** * The batch id of the request at `index`. */ export function shapeRequestID(index: number): string { return `shapes-${String(index).padStart(5, "0")}` }