File size: 10,003 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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/**
 * 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<CuratedSource[]> {
  // 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<GroundedTeaching | null> {
  // 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<CuratedSource>[];
      // 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<boolean> {
  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<number> {
  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;
}