File size: 7,260 Bytes
9580dce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | /**
* 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<string, string> = {
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<WikidataSearchResult[]> {
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<WikidataEntity | null> {
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<WikidataEntity | null> {
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<string, unknown[]>): 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;
}
|