Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 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 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 | import { eq } from 'drizzle-orm' import { LLMClient } from '@soroban/llm-client' import { z } from 'zod' import { db, schema } from '@/db' import { EMBEDDING_MODEL, embeddingToBuffer } from './embedding' import { cosineSimilarity } from './embedding-search' import { clearTaxonomyCache } from './taxonomy' /** * Common stop words to exclude from word frequency analysis */ const STOP_WORDS = new Set([ 'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'from', 'as', 'is', 'was', 'are', 'were', 'been', 'be', 'have', 'has', 'had', 'do', 'does', 'did', 'will', 'would', 'could', 'should', 'may', 'might', 'must', 'shall', 'can', 'need', 'dare', 'ought', 'used', 'it', 'its', 'this', 'that', 'these', 'those', 'i', 'you', 'he', 'she', 'we', 'they', 'what', 'which', 'who', 'whom', 'whose', 'where', 'when', 'why', 'how', 'all', 'each', 'every', 'both', 'few', 'more', 'most', 'other', 'some', 'such', 'no', 'nor', 'not', 'only', 'own', 'same', 'so', 'than', 'too', 'very', 'just', 'also', 'now', 'here', 'there', 'then', 'once', 'if', 'unless', 'until', 'while', 'although', 'because', 'since', 'about', 'into', 'through', 'during', 'before', 'after', 'above', 'below', 'between', 'under', 'again', 'further', 'any', 'up', 'down', 'out', 'off', 'over', 'students', 'learn', 'using', 'use', 'step', 'steps', 'practice', 'understand', 'like', 'different', 'various', 'based', 'given', 'find', 'solve', 'work', ]) /** * Extract word frequencies from flowchart content */ function extractWordFrequencies(texts: string[]): Map<string, number> { const frequencies = new Map<string, number>() for (const text of texts) { const words = text .toLowerCase() .split(/[^a-z]+/) .filter((w) => w.length > 2 && !STOP_WORDS.has(w)) for (const word of words) { frequencies.set(word, (frequencies.get(word) || 0) + 1) } } return frequencies } /** * Format top word frequencies for the prompt */ function formatWordFrequencies(frequencies: Map<string, number>, limit: number = 60): string { const sorted = [...frequencies.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit) if (sorted.length === 0) { return '(No existing flowcharts found)' } return sorted.map(([word, count]) => `${word} (${count})`).join(', ') } /** * Load flowchart content from the database for word frequency analysis */ async function loadFlowchartContent(): Promise<string[]> { const flowcharts = await db.query.teacherFlowcharts.findMany({ where: eq(schema.teacherFlowcharts.status, 'published'), columns: { title: true, description: true, }, }) const texts: string[] = [] for (const fc of flowcharts) { if (fc.title) texts.push(fc.title) if (fc.description) texts.push(fc.description) } return texts } /** * Generate topic labels using an LLM */ async function generateLabels(wordFreqHint: string): Promise<string[]> { const llm = new LLMClient() const response = await llm.call({ prompt: `Generate a comprehensive list of topic labels for categorizing educational flowcharts. The labels should cover the FULL spectrum of education from kindergarten through graduate/professional level, with multiple levels of specificity. ## Specificity Tiers (generate labels at ALL levels): **Tier 1 - Broad subjects (~20 labels):** Very broad categories that can group diverse content. Examples: "Mathematics", "Language Arts", "Science", "Social Studies", "Arts & Music", "Life Skills", "Technology", "Engineering", "Medicine" **Tier 2 - Domains (~50 labels):** Subject domains that group related topics. Examples: "Fractions", "Linear Algebra", "Organic Chemistry", "Grammar", "Physics", "Machine Learning", "Music Theory" **Tier 3 - Specific topics (~130 labels):** Focused topics for specific content. Examples: "Fraction Addition", "Matrix Operations", "Cramer's Rule", "Verb Tenses", "Newton's Laws", "Neural Networks" ## Content hints from existing flowcharts: Here are the most common terms from existing flowcharts in the system: ${wordFreqHint} Use these to ensure coverage of topics that actually exist, including any niche topics. ## Requirements: - Each label should be 2-5 words (broader labels can be 1-2 words) - Use Title Case - Cover the FULL educational spectrum: elementary, middle school, high school, undergraduate, graduate, professional - Avoid redundancy — each label should cover a distinct topic area - IMPORTANT: Include broad labels! When content is diverse, a cluster needs a broad label like "Mathematics" rather than being unlabeled. ## Topic coverage (ensure all levels are represented): **Mathematics:** - Elementary: counting, place value, basic operations, fractions, decimals, percentages, basic geometry, measurement - Middle/High School: algebra, linear equations, quadratic equations, polynomials, trigonometry, statistics, probability - Advanced: linear algebra, matrices, determinants, systems of equations, calculus, differential equations, abstract algebra, number theory, topology, real analysis **Language Arts:** - Elementary: phonics, reading comprehension, vocabulary, grammar, parts of speech, sentence structure, punctuation, spelling - Middle/High School: essay writing, literary analysis, rhetoric, research papers, citations - Advanced: linguistics, semantics, discourse analysis, technical writing **Science:** - Elementary/Middle: scientific method, life science, physical science, earth science, ecosystems - High School: biology, chemistry, physics, environmental science - Advanced: molecular biology, organic chemistry, quantum mechanics, thermodynamics, astrophysics, neuroscience **Engineering & Technology:** - Fundamentals: basic coding, algorithms, data structures, circuits - Advanced: machine learning, computer architecture, signal processing, control systems, aerospace, materials science **Social Studies & Humanities:** - History, geography, civics, economics, philosophy, psychology, sociology, anthropology **Professional/Applied:** - Medicine, law, business, finance, accounting, project management **Arts & Other:** - Music theory, art techniques, physical education, health, nutrition, practical life skills Return approximately 200 labels total across all tiers.`, schema: z.object({ labels: z.array(z.string()).min(150).max(250), }), model: 'gpt-4o-mini', }) return response.data.labels } /** * Deduplicate labels (case-insensitive) */ function deduplicateLabels(labels: string[]): string[] { const seen = new Set<string>() const result: string[] = [] for (const label of labels) { const normalized = label.trim() const key = normalized.toLowerCase() if (!seen.has(key) && normalized.length > 0) { seen.add(key) result.push(normalized) } } return result } /** * Build rich context for a taxonomy label to match how flowcharts are embedded. * This ensures labels and flowcharts are in the same semantic space. */ function buildLabelEmbeddingContent(label: string): string { return `Educational topic category: ${label} This is a topic label for categorizing educational flowcharts and learning materials. Flowcharts in this category teach concepts related to ${label.toLowerCase()}.` } /** * Embed labels using OpenAI with rich educational context. * Labels are embedded with context to match how flowcharts are embedded, * ensuring they're in the same semantic space. */ async function embedLabels(labels: string[]): Promise<Float32Array[]> { const llm = new LLMClient() // Build rich context for each label const labelContents = labels.map(buildLabelEmbeddingContent) const response = await llm.embed({ input: labelContents, model: EMBEDDING_MODEL, }) return response.embeddings } /** * Compute breadth scores for each label based on average proximity to all other labels. * Broader labels (e.g., "Mathematics") have lower average distance to all labels * because they're conceptually central. Specific labels (e.g., "Fraction Addition") * have higher average distance because they're in specialized "corners" of the space. * * Returns scores 0-100 where higher = broader. * * @param embeddings - Array of label embeddings * @returns Array of breadth scores (one per label) */ function computeLabelBreadths(embeddings: Float32Array[]): number[] { const n = embeddings.length const breadths: number[] = [] for (let i = 0; i < n; i++) { let totalDist = 0 for (let j = 0; j < n; j++) { if (i !== j) { totalDist += 1 - cosineSimilarity(embeddings[i], embeddings[j]) } } const avgDist = totalDist / (n - 1) // Convert to 0-100 scale where higher = broader (lower avg distance) // Typical distances range from ~0.3 to ~0.7, so scale accordingly const breadth = Math.round(Math.max(0, Math.min(100, (1 - avgDist) * 150 - 20))) breadths.push(breadth) } return breadths } export interface TaxonomyGenerationResult { labelCount: number labels: string[] } /** * Regenerate the topic taxonomy and store in the database. * * 1. Loads word frequencies from existing flowcharts for context * 2. Generates ~200 topic labels via LLM (broad, domain, and specific tiers) * 3. Embeds all labels via OpenAI * 4. Replaces the entire topic_taxonomy table with new labels * 5. Clears the in-memory taxonomy cache */ export async function regenerateTaxonomy(): Promise<TaxonomyGenerationResult> { // Load flowchart content for word frequency hints const flowchartTexts = await loadFlowchartContent() const wordFrequencies = extractWordFrequencies(flowchartTexts) const wordFreqHint = formatWordFrequencies(wordFrequencies, 60) // Generate labels via LLM const rawLabels = await generateLabels(wordFreqHint) const labels = deduplicateLabels(rawLabels) // Embed all labels const embeddings = await embedLabels(labels) // Compute breadth scores (how many other labels are nearby) const breadths = computeLabelBreadths(embeddings) // Replace the entire taxonomy table await db.delete(schema.topicTaxonomy) const now = new Date() const rows = labels.map((label, i) => ({ label, embedding: embeddingToBuffer(embeddings[i]), embeddingModel: EMBEDDING_MODEL, breadth: breadths[i], createdAt: now, })) // Insert in batches to avoid SQLite variable limit const BATCH_SIZE = 50 for (let i = 0; i < rows.length; i += BATCH_SIZE) { const batch = rows.slice(i, i + BATCH_SIZE) await db.insert(schema.topicTaxonomy).values(batch) } // Clear the in-memory cache so the new taxonomy is used clearTaxonomyCache() return { labelCount: labels.length, labels, } } |