All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s
- Built-in Parallel web search (keyless; optional sign-in for higher limits and research) with its own settings page; OAuth sign-in (RFC 9728/8414/7591, PKCE, RFC 8707) for any MCP server, with token refresh and pre-registered client support - Friendly tool steps (icon, name, status; details on click) and ids stripped from results; per-chat tool switches; taller thinking box - Exams within classes: exam tabs, scoped lists, uploads, imports and Generate; exam-only material for generation; class setting for what the groups are called - Assistant can ask clarifying questions in an inline form before generating - OpenUI blocks (charts, questions, flashcards, inputs) in assistant, Explain and share chats - Explain beside the quiz on wide screens, grounded in the cited source pages - Quiz results: percentage ring coloured by score band, rainbow at 100 - Share links: assistant button like the owner's, hidden during quizzes; documents readable in the browser - Live draft and library updates over server-sent events Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
105 lines
5.5 KiB
TypeScript
105 lines
5.5 KiB
TypeScript
/** "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.`;
|
||
|
||
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')}`;
|
||
}
|
||
|