/** * Source curation pipeline for grounded teaching content. * * Layer 1: Fetch sources from Tier 1 providers (Wikipedia first) * Layer 2: Generate teaching content grounded in retrieved sources * Layer 3: Verify URLs and cache the result * * A topic is "source-ready" when it has ≥2 verified Tier 1 sources. */ import { fetchWikipediaSources, verifyWikipediaUrl } from "./wikipedia"; import { fetchWikidataSource, formatEntityAsExcerpt } from "./wikidata"; import { fetchOpenStaxSources } from "./openstax"; import { claude, parseClaudeJson } from "@/lib/claude"; import { prisma } from "@/lib/db"; /** Minimum sources required before we'll generate grounded teaching content. */ export const MIN_SOURCES = 2; export interface CuratedSource { url: string; title: string; excerpt: string; domain: string; license: string; confidence: string; } export interface GroundedTeaching { topic: string; explanation: string; keyTakeaways: string[]; sources: CuratedSource[]; confidenceScore: string; cached: boolean; } /** * Fetch and store sources for a Feynman topic. * Currently uses Wikipedia; designed to add more providers. * * Returns the curated sources, or an empty array if insufficient coverage. */ export async function curateSources(topicId: string, topicName: string, domain?: string): Promise { // Check if we already have cached sources const existing = await prisma.topicSource.findMany({ where: { topicId }, }); if (existing.length >= MIN_SOURCES) { return existing.map((s) => ({ url: s.url, title: s.title, excerpt: s.excerpt, domain: s.domain, license: s.license, confidence: s.confidence, })); } // Fetch from Wikipedia const wikiExtracts = await fetchWikipediaSources(topicName, 3); const sources: CuratedSource[] = wikiExtracts.map((ext) => ({ url: ext.url, title: ext.title, excerpt: ext.extract, domain: "wikipedia", license: "CC BY-SA 4.0", confidence: "high", // Wikipedia articles found via direct search are high confidence })); // Fetch from Wikidata (structured facts, CC0) try { const wikidataEntity = await fetchWikidataSource(topicName); if (wikidataEntity) { const excerpt = formatEntityAsExcerpt(wikidataEntity); // Only add if the excerpt has meaningful content (description + at least some data) if (excerpt.length > 30) { sources.push({ url: wikidataEntity.url, title: `${wikidataEntity.label} (Wikidata)`, excerpt, domain: "wikidata", license: "CC0", confidence: "high", }); } } } catch { // Wikidata is supplementary — don't fail the pipeline if it's unavailable } // Fetch from OpenStax (peer-reviewed college textbooks, CC BY 4.0) try { const openstaxSections = await fetchOpenStaxSources(topicName, domain, 1); for (const section of openstaxSections) { sources.push({ url: section.url, title: `${section.sectionTitle} — ${section.bookTitle} (OpenStax)`, excerpt: section.excerpt, domain: "openstax", license: "CC BY 4.0", confidence: "high", // Peer-reviewed college textbook content }); } } catch { // OpenStax is supplementary — don't fail the pipeline if it's unavailable } // Store sources in DB (upsert to avoid duplicates on re-runs) for (const source of sources) { const existingSource = await prisma.topicSource.findFirst({ where: { topicId, url: source.url }, }); if (!existingSource) { await prisma.topicSource.create({ data: { topicId, url: source.url, title: source.title, excerpt: source.excerpt, domain: source.domain, license: source.license, confidence: source.confidence, verifiedAt: new Date(), }, }); } } return sources; } /** * Generate grounded teaching content from curated sources. * * If a cached teaching exists and is verified, returns it. * Otherwise generates new content from source material. * * Returns null if insufficient sources are available. */ export async function getGroundedTeaching( topicId: string, topicName: string, difficulty?: string, domain?: string, ): Promise { // Check cache first const cached = await prisma.teachingCache.findUnique({ where: { topicId }, }); if (cached) { let parsedSources: CuratedSource[] = []; try { const raw = JSON.parse(cached.sourcesJson) as Partial[]; // Backfill any fields that older cache entries may be missing parsedSources = raw.map((s) => ({ url: s.url ?? "", title: s.title ?? "", excerpt: s.excerpt ?? "", domain: s.domain ?? "", license: s.license ?? "", confidence: s.confidence ?? "high", })); } catch { // Corrupted cache entry — fall through to regenerate await prisma.teachingCache.delete({ where: { topicId } }); return getGroundedTeaching(topicId, topicName, difficulty, domain); } return { topic: topicName, explanation: cached.content, keyTakeaways: extractTakeaways(cached.content), sources: parsedSources, confidenceScore: cached.confidenceScore, cached: true, }; } // Curate sources const sources = await curateSources(topicId, topicName, domain); if (sources.length < MIN_SOURCES) { return null; // insufficient source coverage } // Build source context for the LLM prompt const sourceContext = sources .map((s, i) => `[Source ${i + 1}: ${s.title}]\n${s.excerpt}`) .join("\n\n---\n\n"); const difficultyCtx = difficulty ? ` The topic is considered ${difficulty}-level.` : ""; // Generate grounded teaching content const message = await claude.messages.create({ model: "claude-haiku-4-5-20251001", max_tokens: 2000, messages: [ { role: "user", content: `You are a brilliant teacher creating a grounded explanation of "${topicName}".${difficultyCtx} IMPORTANT: Use ONLY the provided source material below. Do not add any claims not supported by these sources. Cite sources inline using [1], [2], etc. SOURCE MATERIAL: ${sourceContext} Write a clear, engaging explanation that: 1. Starts with the core idea in one sentence 2. Builds understanding step by step (2-3 paragraphs) 3. Uses a concrete analogy or real-world example 4. Highlights the 2-3 most important takeaways 5. Cites sources inline using [1], [2], [3] format Keep it accessible — a motivated beginner should be able to understand this. Be concise but thorough. Write in flowing prose. You may use a short bullet list only for the key takeaways at the end. Respond ONLY in valid JSON (no markdown, no code fences): { "explanation": "...", "keyTakeaways": ["...", "...", "..."] }`, }, ], }); const text = message.content[0].type === "text" ? message.content[0].text : ""; let parsed: { explanation: string; keyTakeaways: string[] }; try { parsed = parseClaudeJson(text) as { explanation: string; keyTakeaways: string[] }; } catch { // Claude returned non-JSON — treat the raw text as the explanation, no takeaways parsed = { explanation: text, keyTakeaways: [] }; } // Determine confidence score const confidenceScore = sources.length >= 3 ? "high" : sources.length >= 2 ? "moderate" : "low"; // Cache the result — store full CuratedSource shape so cached responses are identical to live ones const sourceSummary = sources.map((s) => ({ url: s.url, title: s.title, excerpt: s.excerpt, domain: s.domain, license: s.license, confidence: s.confidence, })); await prisma.teachingCache.create({ data: { topicId, content: parsed.explanation, sourcesJson: JSON.stringify(sourceSummary), confidenceScore, verifiedAt: new Date(), }, }); return { topic: topicName, explanation: parsed.explanation, keyTakeaways: parsed.keyTakeaways, sources, confidenceScore, cached: false, }; } /** * Check if a topic has sufficient source coverage for grounded teaching. * Does NOT fetch new sources — checks existing DB records only. */ export async function hasSourceCoverage(topicId: string): Promise { const count = await prisma.topicSource.count({ where: { topicId }, }); return count >= MIN_SOURCES; } /** * Verify all source URLs for a topic are still live. * Updates verifiedAt timestamps for live URLs. * Returns the count of verified sources. */ export async function verifySources(topicId: string): Promise { const sources = await prisma.topicSource.findMany({ where: { topicId }, }); let verified = 0; for (const source of sources) { // verifyWikipediaUrl works for any URL (generic HEAD check) const isLive = await verifyWikipediaUrl(source.url); if (isLive) { await prisma.topicSource.update({ where: { id: source.id }, data: { verifiedAt: new Date() }, }); verified++; } } return verified; } /** * Extract key takeaways from cached content (simple heuristic). * The cached content may include takeaways as a bullet list at the end. */ function extractTakeaways(content: string): string[] { // Look for lines that start with "- " or "• " near the end const lines = content.split("\n"); const takeaways: string[] = []; for (let i = Math.max(0, lines.length - 10); i < lines.length; i++) { const line = lines[i].trim(); if (line.startsWith("- ") || line.startsWith("• ") || line.match(/^\d+\.\s/)) { takeaways.push(line.replace(/^[-•]\s*/, "").replace(/^\d+\.\s*/, "")); } } // If no structured takeaways found, return empty — the caller should use keyTakeaways from the original generation return takeaways; }