/** * Wikidata API client for structured fact verification. * * Uses the Wikidata REST / wbsearchentities + wbgetentities APIs to: * 1. Search for entities matching a topic * 2. Extract structured descriptions, aliases, and key claims * 3. Provide a structured-data complement to Wikipedia prose * * All Wikidata content is CC0 (public domain). */ const WIKIDATA_API = "https://www.wikidata.org/w/api.php"; const USER_AGENT = "RotNot/1.0 (educational app; contact: github.com/CuriosityQuantified/rotnot)"; export interface WikidataSearchResult { id: string; // e.g. "Q11348" label: string; description: string; url: string; } export interface WikidataEntity { id: string; label: string; description: string; aliases: string[]; url: string; wikipediaUrl: string | null; /** Key property-value pairs extracted from claims. */ facts: WikidataFact[]; } export interface WikidataFact { property: string; // human-readable label, e.g. "instance of" propertyId: string; // e.g. "P31" value: string; } /** * Well-known Wikidata properties that are educationally useful. * We only extract these to keep responses focused. */ const USEFUL_PROPERTIES: Record = { P31: "instance of", P279: "subclass of", P361: "part of", P527: "has parts", P138: "named after", P61: "discoverer or inventor", P575: "time of discovery", P1343: "described by source", P910: "topic's main category", P18: "image", P1114: "quantity", P1552: "has characteristic", P2670: "has parts of the class", P366: "has use", }; /** * Search Wikidata for entities matching a query. * Returns up to `limit` results (default 3). */ export async function searchWikidata( query: string, limit: number = 3, ): Promise { const params = new URLSearchParams({ action: "wbsearchentities", search: query, language: "en", limit: String(limit), format: "json", origin: "*", }); const response = await fetch(`${WIKIDATA_API}?${params}`, { headers: { "User-Agent": USER_AGENT }, }); if (!response.ok) { throw new Error(`Wikidata search failed: ${response.status} ${response.statusText}`); } const data = await response.json(); const results = data?.search ?? []; return results.map( (r: { id: string; label: string; description?: string; url: string }) => ({ id: r.id, label: r.label, description: r.description ?? "", url: r.url || `https://www.wikidata.org/wiki/${r.id}`, }), ); } /** * Fetch a full entity by Wikidata ID (e.g. "Q11348"). * Extracts labels, descriptions, aliases, sitelinks, and key claims. */ export async function getWikidataEntity(entityId: string): Promise { const params = new URLSearchParams({ action: "wbgetentities", ids: entityId, languages: "en", props: "labels|descriptions|aliases|claims|sitelinks", format: "json", origin: "*", }); const response = await fetch(`${WIKIDATA_API}?${params}`, { headers: { "User-Agent": USER_AGENT }, }); if (!response.ok) { throw new Error(`Wikidata entity fetch failed: ${response.status} ${response.statusText}`); } const data = await response.json(); const entity = data?.entities?.[entityId]; if (!entity || entity.missing !== undefined) { return null; } const label = entity.labels?.en?.value ?? entityId; const description = entity.descriptions?.en?.value ?? ""; const aliases = (entity.aliases?.en ?? []).map((a: { value: string }) => a.value); // Extract Wikipedia sitelink const enWikiSitelink = entity.sitelinks?.enwiki; const wikipediaUrl = enWikiSitelink ? `https://en.wikipedia.org/wiki/${encodeURIComponent(enWikiSitelink.title.replace(/ /g, "_"))}` : null; // Extract useful claims const facts = extractFacts(entity.claims ?? {}); return { id: entityId, label, description, aliases, url: `https://www.wikidata.org/wiki/${entityId}`, wikipediaUrl, facts, }; } /** * Search for a topic and return the best-matching entity with full data. * This is the main entry point — combines search + entity fetch. * * Returns null if no matching entity is found. */ export async function fetchWikidataSource(topic: string): Promise { const searchResults = await searchWikidata(topic, 3); if (searchResults.length === 0) { return null; } // Try the top result first (usually the best match) const entity = await getWikidataEntity(searchResults[0].id); return entity; } /** * Format a Wikidata entity into a readable source excerpt * suitable for use in the grounded teaching pipeline. */ export function formatEntityAsExcerpt(entity: WikidataEntity): string { const parts: string[] = []; // Core identity parts.push(`${entity.label}: ${entity.description}`); // Aliases give alternative names/framings if (entity.aliases.length > 0) { parts.push(`Also known as: ${entity.aliases.slice(0, 5).join(", ")}`); } // Structured facts if (entity.facts.length > 0) { parts.push(""); parts.push("Key facts:"); for (const fact of entity.facts) { parts.push(`• ${fact.property}: ${fact.value}`); } } return parts.join("\n"); } /** * Extract human-readable facts from Wikidata claims. * Only extracts properties in our USEFUL_PROPERTIES allowlist. * Handles entity-value claims by resolving labels where available. */ function extractFacts(claims: Record): WikidataFact[] { const facts: WikidataFact[] = []; for (const [propId, propClaims] of Object.entries(claims)) { const propertyLabel = USEFUL_PROPERTIES[propId]; if (!propertyLabel) continue; // Only take the first claim per property to keep things concise const claim = propClaims[0] as { mainsnak?: { datavalue?: { type: string; value: unknown; }; }; }; if (!claim?.mainsnak?.datavalue) continue; const datavalue = claim.mainsnak.datavalue; let value: string | null = null; switch (datavalue.type) { case "string": value = datavalue.value as string; break; case "wikibase-entityid": { const entityValue = datavalue.value as { id?: string; "numeric-id"?: number }; // We store the entity ID; could resolve labels in a follow-up if needed value = entityValue.id ?? `Q${entityValue["numeric-id"]}`; break; } case "time": { const timeValue = datavalue.value as { time?: string }; if (timeValue.time) { // Format: "+1905-06-30T00:00:00Z" → "1905-06-30" value = timeValue.time.replace(/^\+/, "").replace(/T.*$/, ""); } break; } case "quantity": { const qtyValue = datavalue.value as { amount?: string; unit?: string }; value = qtyValue.amount?.replace(/^\+/, "") ?? null; break; } case "monolingualtext": { const textValue = datavalue.value as { text?: string }; value = textValue.text ?? null; break; } } if (value) { facts.push({ property: propertyLabel, propertyId: propId, value }); } } return facts; }