|
| 1 | +const endpoint = "https://zh.wikipedia.org/w/api.php"; |
| 2 | +const userAgent = "QuickLearn/1.0 (https://github.com/fly1d/quicklearn-agent)"; |
| 3 | + |
| 4 | +function cleanText(value = "") { |
| 5 | + return String(value).replace(/\s+/g, " ").trim(); |
| 6 | +} |
| 7 | + |
| 8 | +function sentenceList(value, limit = 6) { |
| 9 | + return cleanText(value) |
| 10 | + .split(/(?<=[。!?.!?])\s*/) |
| 11 | + .map((item) => item.trim()) |
| 12 | + .filter((item) => item.length >= 12) |
| 13 | + .slice(0, limit); |
| 14 | +} |
| 15 | + |
| 16 | +function normalizeTerm(value = "") { |
| 17 | + return value.toLowerCase().replace(/[\s_()()·.-]+/g, ""); |
| 18 | +} |
| 19 | + |
| 20 | +function isDisambiguation(page) { |
| 21 | + return Object.hasOwn(page.pageprops || {}, "disambiguation") || /消歧[义義][页頁]/.test(page.description || ""); |
| 22 | +} |
| 23 | + |
| 24 | +function sourceUrl(title) { |
| 25 | + return `https://zh.wikipedia.org/wiki/${encodeURIComponent(title.replace(/\s+/g, "_"))}`; |
| 26 | +} |
| 27 | + |
| 28 | +function clarificationResult(input, pages) { |
| 29 | + const top = pages[0]; |
| 30 | + const disambiguation = pages.find(isDisambiguation); |
| 31 | + if (!top || !disambiguation) return null; |
| 32 | + |
| 33 | + const exactDisambiguation = normalizeTerm(disambiguation.title) === normalizeTerm(input); |
| 34 | + const topIsExact = normalizeTerm(top.title) === normalizeTerm(input); |
| 35 | + const likelyAmbiguous = top === disambiguation || exactDisambiguation || (!topIsExact && disambiguation.index <= 2); |
| 36 | + if (!likelyAmbiguous) return null; |
| 37 | + |
| 38 | + const options = [...new Set(pages |
| 39 | + .filter((page) => !isDisambiguation(page) && !/列表条目|列表條目/.test(page.description || "")) |
| 40 | + .map((page) => page.title))] |
| 41 | + .slice(0, 3); |
| 42 | + if (options.length < 2) return null; |
| 43 | + |
| 44 | + return { |
| 45 | + needsClarification: true, |
| 46 | + question: `“${input}”可能有几种意思,你想了解哪一个?`, |
| 47 | + options |
| 48 | + }; |
| 49 | +} |
| 50 | + |
| 51 | +function learningResult(page) { |
| 52 | + const facts = sentenceList(page.extract); |
| 53 | + const description = cleanText(page.description); |
| 54 | + const summary = (facts.slice(0, 2).join(" ") || description).slice(0, 360); |
| 55 | + const details = [ |
| 56 | + facts[0] || description || `这是关于 ${page.title} 的百科条目。`, |
| 57 | + facts[1] || `${page.title} 的背景和适用语境值得结合原文继续确认。`, |
| 58 | + facts[2] || `可以通过相近概念和实际例子进一步理解 ${page.title}。` |
| 59 | + ]; |
| 60 | + const takeaways = facts.slice(0, 3).map((item) => item.slice(0, 92)); |
| 61 | + while (takeaways.length < 3) { |
| 62 | + takeaways.push(["先掌握准确定义", "再确认背景与边界", "用例子验证理解"][takeaways.length]); |
| 63 | + } |
| 64 | + |
| 65 | + return { |
| 66 | + title: page.title, |
| 67 | + category: "维基百科速览", |
| 68 | + summary, |
| 69 | + definition: details[0], |
| 70 | + why: description |
| 71 | + ? `${page.title}通常被概括为“${description}”。理解它有助于建立相关主题的基础背景和概念边界。` |
| 72 | + : `理解 ${page.title} 的定义、背景与边界,可以为继续阅读专业资料建立稳定起点。`, |
| 73 | + concepts: [["基本定义", details[0]], ["关键背景", details[1]], ["延伸理解", details[2]]], |
| 74 | + takeaways, |
| 75 | + misconception: "百科摘要适合建立第一层认识,但条目可能持续更新;涉及专业判断时仍应核对原始资料。", |
| 76 | + steps: [`用一句话复述 ${page.title}`, `区分 ${page.title} 与相近概念`, "打开来源,重点查看定义、背景和示例"], |
| 77 | + source: { |
| 78 | + url: sourceUrl(page.title), |
| 79 | + host: "zh.wikipedia.org", |
| 80 | + title: page.title, |
| 81 | + provider: "维基百科", |
| 82 | + license: "CC BY-SA 4.0" |
| 83 | + } |
| 84 | + }; |
| 85 | +} |
| 86 | + |
| 87 | +export async function lookupWikipedia(input, options = {}) { |
| 88 | + const query = input.trim(); |
| 89 | + if (!query || query.length > 120) return null; |
| 90 | + |
| 91 | + const fetchImpl = options.fetchImpl || fetch; |
| 92 | + const controller = new AbortController(); |
| 93 | + const timeout = setTimeout(() => controller.abort(), options.timeoutMs ?? 3500); |
| 94 | + timeout.unref?.(); |
| 95 | + |
| 96 | + try { |
| 97 | + const url = new URL(endpoint); |
| 98 | + url.search = new URLSearchParams({ |
| 99 | + action: "query", |
| 100 | + generator: "search", |
| 101 | + gsrsearch: query, |
| 102 | + gsrnamespace: "0", |
| 103 | + gsrlimit: "6", |
| 104 | + prop: "extracts|description|pageprops", |
| 105 | + exintro: "1", |
| 106 | + explaintext: "1", |
| 107 | + exsentences: "6", |
| 108 | + ppprop: "disambiguation", |
| 109 | + redirects: "1", |
| 110 | + format: "json", |
| 111 | + formatversion: "2" |
| 112 | + }); |
| 113 | + const response = await fetchImpl(url, { |
| 114 | + signal: controller.signal, |
| 115 | + headers: { Accept: "application/json", "User-Agent": userAgent } |
| 116 | + }); |
| 117 | + if (!response.ok) return null; |
| 118 | + const data = await response.json(); |
| 119 | + const pages = Array.isArray(data?.query?.pages) |
| 120 | + ? data.query.pages |
| 121 | + .filter((page) => page?.ns === 0 && typeof page.title === "string") |
| 122 | + .sort((a, b) => (a.index ?? Number.MAX_SAFE_INTEGER) - (b.index ?? Number.MAX_SAFE_INTEGER)) |
| 123 | + : []; |
| 124 | + if (!pages.length) return null; |
| 125 | + |
| 126 | + const clarification = clarificationResult(query, pages); |
| 127 | + if (clarification) return clarification; |
| 128 | + const page = pages.find((item) => !isDisambiguation(item) && cleanText(item.extract).length >= 30); |
| 129 | + return page ? learningResult(page) : null; |
| 130 | + } catch { |
| 131 | + return null; |
| 132 | + } finally { |
| 133 | + clearTimeout(timeout); |
| 134 | + } |
| 135 | +} |
0 commit comments