/** * Rationale layout. New rationales are written as Markdown (a bold key point, then short * bullets); older ones are often one long paragraph. `formatRationale` breaks such a paragraph * into readable pieces for display: the first sentence on its own, then short paragraphs, and * a list when it walks through the choices ("Option A…", "Choice 2…"). Text that already has * structure (line breaks, lists, headings) is returned unchanged. */ /** Words that end with a period without ending the sentence. */ const ABBREVIATIONS = /(?:^|\s|\()(?:e\.g|i\.e|vs|etc|approx|dr|mr|mrs|ms|st|no|fig|min|max|hr|hrs|mg|mcg|kg|ml|mL|dL|mEq|U|gtt|q|b\.i\.d|t\.i\.d|q\.i\.d|p\.r\.n|a\.m|p\.m)\.$/i; /** Splits plain prose into sentences, keeping decimals ("2.5 mg") and abbreviations together. */ export function splitSentences(text: string): string[] { const out: string[] = []; let start = 0; const re = /([.!?])(["'”’)*_]*)\s+(?=["“'(*_]*[A-Z0-9])/g; let m: RegExpExecArray | null; while ((m = re.exec(text))) { const end = m.index + m[1].length + m[2].length; const piece = text.slice(start, end); if (m[1] === '.' && ABBREVIATIONS.test(text.slice(start, m.index + 1))) continue; if (piece.trim()) out.push(piece.trim()); start = re.lastIndex; } const rest = text.slice(start).trim(); if (rest) out.push(rest); return out; } const CHOICE_START = /^(?:\*\*)?(?:option|choice|answer|distractor)\s*(?:[A-F]|[1-6])\b/i; const FOLLOW_ON = /^(?:it|this|that|these|those|they|however|instead|also|because|but)\b/i; export function formatRationale(text: string): string { const value = text.trim(); // Already laid out, or short enough to read at a glance. if (value.length < 260 || /\n/.test(value)) return value; const sentences = splitSentences(value); if (sentences.length < 3) return value; const [lead, ...rest] = sentences; // The key point leads in bold, as new rationales do (unless it already has emphasis). const blocks: string[] = [/[*_]/.test(lead!) ? lead! : `**${lead}**`]; let paragraph: string[] = []; const flush = () => { if (paragraph.length) blocks.push(paragraph.join(' ')); paragraph = []; }; let bullets: string[] = []; const flushBullets = () => { if (bullets.length) blocks.push(bullets.map((b) => `- ${b}`).join('\n')); bullets = []; }; // Walk-throughs of the choices become a list when there are at least two of them. const choiceCount = rest.filter((s) => CHOICE_START.test(s)).length; for (const sentence of rest) { if (choiceCount >= 2 && CHOICE_START.test(sentence)) { flush(); bullets.push(sentence); continue; } if (bullets.length) { // A follow-on sentence about the same choice ("It…", "This…") stays in its bullet. if (FOLLOW_ON.test(sentence) && sentence.length < 160) { bullets[bullets.length - 1] += ` ${sentence}`; continue; } flushBullets(); } paragraph.push(sentence); if (paragraph.length >= 2 || paragraph.join(' ').length > 220) flush(); } flush(); flushBullets(); return blocks.join('\n\n'); }