Study/server/ai/explain.ts
Elijah 25bc03ea75
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 29s
Fourth revision: OpenRouter, live tool stages, Explain layout, share sections
- Interactive blocks are encouraged by default; Explain gets a reduced library
  and never writes practice questions.
- Assistant tool steps breathe while running, show live stages from generation
  and the Python check, and read in the past tense when done.
- The assistant asks before searching the web when class materials do not
  cover a question; clarifying questions list every class's exams and never
  ask about format (always NCLEX).
- Explain opens beside the question from 900px wide, moving the question left
  while open and back on the next one.
- Generate dialog drops the practice set/exam switch (presets cover it) and the
  Generate buttons lose their icon.
- Python check notes are green when every check passed, applied fixes neutral.
- Share pages group by exam, then Quizzes, Flashcards, Notes, Class Materials,
  hiding empty groups; the class page uses the same order. "Documents" is now
  "Class Materials".
- OpenRouter provider replaces the Ollama type; migration 6 turns Ollama
  connections into OpenAI-compatible ones at /v1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 21:54:39 -07:00

106 lines
5.6 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/** "Explain this": the prompt shared by the owner's study pages and AI-enabled share links. */
import type { DB } from '../db.ts';
import { searchChunks } from '../services/documents.ts';
export const EXPLAIN_SYSTEM = `You are a patient nursing instructor helping a student while they study. Explain clearly and briefly (aim for under 200 words unless asked for more).
Use Markdown. Lead with the key idea, explain the reasoning, and connect it to patient care. If answer choices are given, say why the correct one is right and, in a line each, why the others are wrong. Do not restate the whole question.
When the student's cited source pages are included, ground the explanation in them and say which page a point comes from.
Give information only: do not write practice questions, quizzes or flashcards, and do not quiz the student.`;
export type ExplainInput =
| { kind: 'question'; stem: string; options: { text: string; correct: boolean }[]; selected?: string[]; rationale?: string; ask?: string }
| { kind: 'card'; front: string; back: string; ask?: string }
| { kind: 'text'; text: string; ask?: string };
export function explainPrompt(body: ExplainInput): string {
if (body.kind === 'question') {
return [
`Question:\n${body.stem}`,
`Choices:\n${body.options.map((o) => `- ${o.text}${o.correct ? ' (correct)' : ''}`).join('\n')}`,
body.selected?.length ? `The student chose: ${body.selected.join('; ')}` : '',
body.rationale ? `Existing rationale:\n${body.rationale}` : '',
body.ask ? `The student asks: ${body.ask}` : 'Explain this question so it finally makes sense. If the student chose wrongly, address the misunderstanding behind their choice.',
]
.filter(Boolean)
.join('\n\n');
}
if (body.kind === 'card') {
return `Flashcard front:\n${body.front}\n\nFlashcard back:\n${body.back}\n\n${body.ask ? `The student asks: ${body.ask}` : 'Explain this card in more depth and give one way to remember it.'}`;
}
return `${body.text}\n\n${body.ask ? `The student asks: ${body.ask}` : 'Explain this passage in simpler terms and point out what is most important to remember.'}`;
}
/* ------------------------------ cited source pages ------------------------------ */
export interface CitedSource {
label: string;
documentId: string;
text: string;
}
/** "Seizures, pp. 8-9" → title and page range; a bare title has no pages. */
export function parseSourceLabel(label: string): { title: string; start: number | null; end: number | null } {
const m = /^(.*?)(?:,\s*|\s+)(?:pp?\.|pages?|slides?)\s*(\d+)(?:\s*[-–]\s*(\d+))?\s*$/i.exec(label.trim());
if (!m) return { title: label.trim(), start: null, end: null };
const start = Number(m[2]);
const end = m[3] ? Number(m[3]) : start;
return { title: m[1].trim(), start: Math.min(start, end), end: Math.max(start, end) };
}
/** The labels a rationale cites, from its "Source: …" line(s). */
export function sourceLabelsIn(rationale: string): string[] {
const out: string[] = [];
for (const m of rationale.matchAll(/Sources?:\s*\**\s*([^\n*]+)/gi)) {
for (const part of m[1].split(/;\s*/)) {
const label = part.trim().replace(/[.\s]+$/, '');
if (label && !out.includes(label)) out.push(label);
}
}
return out.slice(0, 3);
}
/**
* The pages a question's rationale cites ("Source: Seizures, pp. 8-9"), read from the student's
* own documents so an explanation can build on them. Documents are matched by title, inside
* `classIds` when given (a share link may only read documents of the shared class).
*/
export function citedPassages(db: DB, rationale: string, opts: { classIds?: string[]; stem?: string; maxChars?: number } = {}): CitedSource[] {
const maxChars = opts.maxChars ?? 9000;
const out: CitedSource[] = [];
let used = 0;
for (const label of sourceLabelsIn(rationale)) {
const { title, start, end } = parseSourceLabel(label);
if (!title) continue;
const scope = opts.classIds?.length ? ` AND class_id IN (${opts.classIds.map(() => '?').join(',')})` : '';
const doc =
db.get<{ id: string }>(`SELECT id FROM documents WHERE status = 'ready' AND title = ? COLLATE NOCASE${scope} ORDER BY updated_at DESC LIMIT 1`, title, ...(opts.classIds ?? [])) ??
db.get<{ id: string }>(`SELECT id FROM documents WHERE status = 'ready' AND instr(lower(title), lower(?)) > 0${scope} ORDER BY length(title) LIMIT 1`, title, ...(opts.classIds ?? []));
if (!doc) continue;
let rows: { text: string }[];
if (start !== null && end !== null) {
rows = db.all<{ text: string }>(
'SELECT text FROM chunks WHERE document_id = ? AND page_start IS NOT NULL AND page_start <= ? AND COALESCE(page_end, page_start) >= ? ORDER BY seq LIMIT 14',
doc.id,
end,
start,
);
} else {
// No page numbers (Word files, notes): the passages that best match the question.
rows = opts.stem ? searchChunks(db, opts.stem, { documentIds: [doc.id] }, 4).map((h) => ({ text: h.text })) : [];
}
let text = rows.map((r) => r.text).join('\n\n');
if (!text) continue;
if (used + text.length > maxChars) text = `${text.slice(0, Math.max(0, maxChars - used))}…`;
used += text.length;
out.push({ label, documentId: doc.id, text });
if (used >= maxChars) break;
}
return out;
}
/** Prompt text carrying the cited pages. */
export function citedPassagesPrompt(sources: CitedSource[]): string {
if (!sources.length) return '';
return `\n\nThe rationale cites these pages from the student's course material. Base your explanation on them, and mention the page when you use it:\n\n${sources.map((s) => `[${s.label}]\n${s.text}`).join('\n\n---\n\n')}`;
}