diff --git a/server/ai/assistant.ts b/server/ai/assistant.ts index 9a7f158..bd8430f 100644 --- a/server/ai/assistant.ts +++ b/server/ai/assistant.ts @@ -144,7 +144,11 @@ const TOOLS: ToolSpec[] = [ const documents = q>(`SELECT id, title, kind, status, page_count AS pages, token_count AS approx_tokens, folder_id FROM documents WHERE class_id = ? ORDER BY sort_order`); const notes = q>(`SELECT id, title, folder_id FROM notes WHERE class_id = ? ORDER BY sort_order`); const folders = q>(`SELECT id, name FROM folders WHERE class_id = ? ORDER BY sort_order`); - return { output: { class: { id: cls.id, name: cls.name }, folders, quizzes, decks, documents, notes }, summary: `${quizzes.length + decks.length + documents.length + notes.length} items in ${cls.name}` }; + const withUrl = (rows: Record[], base: string) => rows.map((x) => ({ ...x, url: `/${base}/${x.id}` })); + return { + output: { class: { id: cls.id, name: cls.name, url: `/classes/${cls.id}` }, folders, quizzes: withUrl(quizzes, 'quizzes'), decks: withUrl(decks, 'decks'), documents: withUrl(documents, 'documents'), notes: withUrl(notes, 'notes') }, + summary: `${quizzes.length + decks.length + documents.length + notes.length} items in ${cls.name}`, + }; }, }, { @@ -217,7 +221,7 @@ const TOOLS: ToolSpec[] = [ { def: { name: 'search_library', - description: 'Search quiz questions, flashcards and titles by keyword. Use to find existing material on a topic.', + description: 'Search quiz questions, flashcards, notes and titles by keyword. Use to find existing material on a topic. Every result has a url you can link to.', parameters: obj({ query: S, class_id: S }, ['query']), }, label: (i) => `Searching your library for "${clip(String(i.query ?? ''), 50)}"`, @@ -239,14 +243,28 @@ const TOOLS: ToolSpec[] = [ like, ...p, ); + const URL_BASE: Record = { quiz: 'quizzes', deck: 'decks', note: 'notes', document: 'documents' }; const titles = [ ...db.all>(`SELECT 'quiz' AS kind, z.id, z.title FROM quizzes z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p), ...db.all>(`SELECT 'deck' AS kind, z.id, z.title FROM decks z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p), ...db.all>(`SELECT 'note' AS kind, z.id, z.title FROM notes z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p), - ]; + ...db.all>(`SELECT 'document' AS kind, z.id, z.title FROM documents z WHERE z.title LIKE ? ESCAPE '\\' ${cls} LIMIT 8`, like, ...p), + ].map((x) => ({ ...x, url: `/${URL_BASE[x.kind]}/${x.id}` })); + const notes = db + .all>(`SELECT z.id, z.title, z.content FROM notes z WHERE z.content LIKE ? ESCAPE '\\' ${cls} LIMIT 6`, like, ...p) + .map((n) => { + const at = Math.max(0, String(n.content).toLowerCase().indexOf(String(input.query ?? '').toLowerCase()) - 120); + return { id: n.id, title: n.title, url: `/notes/${n.id}`, excerpt: clip(String(n.content).slice(at), 400) }; + }); return { - output: { titles, questions: questions.map((q) => ({ ...q, stem: clip(q.stem, 300) })), cards: cards.map((c) => ({ ...c, front: clip(c.front, 200), back: clip(c.back, 300) })) }, - summary: `${titles.length + questions.length + cards.length} matches`, + output: { + titles, + questions: questions.map((q) => ({ ...q, stem: clip(q.stem, 300), url: `/quizzes/${q.quiz_id}?q=${q.id}` })), + cards: cards.map((c) => ({ ...c, front: clip(c.front, 200), back: clip(c.back, 300), url: `/decks/${c.deck_id}?card=${c.id}` })), + notes, + note: 'For passages inside uploaded documents, use search_documents.', + }, + summary: `${titles.length + questions.length + cards.length + notes.length} matches`, }; }, }, @@ -262,6 +280,7 @@ const TOOLS: ToolSpec[] = [ output: { id: quiz.id, title: quiz.title, + url: `/quizzes/${quiz.id}`, class_id: quiz.class_id, total_questions: all.length, questions: all.slice(offset, offset + limit).map((q) => ({ @@ -286,11 +305,20 @@ const TOOLS: ToolSpec[] = [ const offset = Math.max(0, Number(input.offset) || 0); const limit = Math.max(1, Math.min(150, Number(input.limit) || 60)); return { - output: { id: deck.id, title: deck.title, class_id: deck.class_id, total_cards: all.length, cards: all.slice(offset, offset + limit).map((c) => ({ id: c.id, front: clip(c.front, 300), back: clip(c.back, 500) })) }, + output: { id: deck.id, title: deck.title, url: `/decks/${deck.id}`, class_id: deck.class_id, total_cards: all.length, cards: all.slice(offset, offset + limit).map((c) => ({ id: c.id, front: clip(c.front, 300), back: clip(c.back, 500) })) }, summary: `${deck.title} (${all.length} cards)`, }; }, }, + { + def: { name: 'read_note', description: 'Read one of the user\'s notes or study guides (Markdown).', parameters: obj({ note_id: S }, ['note_id']) }, + label: () => 'Reading a note', + run: (input, { app }) => { + const note = app.db.get<{ id: string; title: string; content: string; class_id: string }>('SELECT id, title, content, class_id FROM notes WHERE id = ?', String(input.note_id)); + if (!note) throw notFound('Note'); + return { output: { id: note.id, title: note.title, url: `/notes/${note.id}`, class_id: note.class_id, content: clip(note.content, 24000) }, summary: note.title }; + }, + }, { def: { name: 'get_performance', @@ -832,6 +860,8 @@ function systemPrompt(app: AppContext, context: AssistantContext): string { `How to work: - Use tools instead of guessing. To answer questions about their material, search or read the documents first and base the answer on what you find. - Cite document passages inline with the ref id in square brackets right after the claim, exactly as given, e.g. [c42]. Only cite refs that a tool returned in this conversation. If the documents do not cover something, say so, then answer from general knowledge and label it as such. +- You can browse everything: list_materials and search_library for quizzes, flashcards and notes; get_quiz, get_deck and read_note to open them; search_documents and read_document for uploaded files. +- When you mention a specific quiz, deck, note or document, link it with Markdown using the url the tool gave you, for example [Cardiac drug cards](/decks/abc123). Never invent a url. - To create study material, call generate_quiz, generate_flashcards or write_study_guide. They read the source documents themselves, so pass ids and a topic rather than text. Do not search first unless you need to work out which documents are relevant. - Everything you create is a DRAFT shown as a preview card. Never say it was saved or added; tell the user to review and save it. - Deleting, moving and renaming require propose_changes and the user's confirmation. Never claim a change was made before a system note confirms it. diff --git a/server/routes/data.ts b/server/routes/data.ts index 1adbd78..8f9c173 100644 --- a/server/routes/data.ts +++ b/server/routes/data.ts @@ -5,9 +5,9 @@ import { Hono } from 'hono'; import { bodyLimit } from 'hono/body-limit'; import { z } from 'zod'; import { questionToDraft, validateDraft, type ContentDraft } from '../../shared/content.ts'; -import { draftsFromValue } from '../../shared/importer.ts'; +import { draftsFromValue, LLM_INSTRUCTIONS } from '../../shared/importer.ts'; import { badRequest, HttpError, idParam, readBody, type AppContext } from '../http.ts'; -import { appSettingsSchema, getAppSettings, setSetting } from '../settings.ts'; +import { appSettingsSchema, deleteSetting, getAppSettings, getSetting, setSetting } from '../settings.ts'; import { createSnapshot, exportBundle, fullBackupStream, listBackups } from '../services/backup.ts'; import { createClass, createDeck, createFolder, createNote, createQuiz, draftCardToInput, draftQuestionToInput, getClass, getDeck, getQuiz, listCards, listQuestions } from '../services/content.ts'; import { createTemplate, deleteTemplate, listTemplates, templateInputSchema, updateTemplate } from '../services/templates.ts'; @@ -85,6 +85,24 @@ export function dataRoutes(app: AppContext): Hono { return c.json({ settings: next }); }); + /* ------------------------------ instructions for outside chatbots ------------------------------ */ + + r.get('/llm-instructions', (c) => + c.json({ + quiz: getSetting(db, 'llm.quiz', null) ?? LLM_INSTRUCTIONS.quiz, + deck: getSetting(db, 'llm.deck', null) ?? LLM_INSTRUCTIONS.deck, + customized: { quiz: getSetting(db, 'llm.quiz', null) !== null, deck: getSetting(db, 'llm.deck', null) !== null }, + }), + ); + + /** Saves an edited copy; `text: null` goes back to the built-in wording. */ + r.put('/llm-instructions', async (c) => { + const body = await readBody(c, z.object({ kind: z.enum(['quiz', 'deck']), text: z.string().trim().min(20).max(20000).nullable() })); + if (body.text === null) deleteSetting(db, `llm.${body.kind}`); + else setSetting(db, `llm.${body.kind}`, body.text); + return c.json({ ok: true }); + }); + /* ------------------------------ import ------------------------------ */ r.post('/import', bodyLimit({ maxSize: 30 * 1024 * 1024 }), async (c) => { diff --git a/shared/importer.ts b/shared/importer.ts index 591b59a..7d8e217 100644 --- a/shared/importer.ts +++ b/shared/importer.ts @@ -559,3 +559,73 @@ export function draftsFromValue(value: unknown): { items: ContentDraft[]; notice collect(value, items, notices); return { items, notices }; } + +/* ------------------------------------------------------------------ */ +/* Instructions for writing importable content with an outside chatbot */ +/* ------------------------------------------------------------------ */ + +export const LLM_INSTRUCTIONS: Record<'quiz' | 'deck', string> = { + quiz: `You are writing practice questions that will be imported into a study app. +Reply with ONE JSON object and nothing else: no commentary and no Markdown code fence. + +Use exactly this shape: +{ + "kind": "quiz", + "title": "Short title", + "description": "One sentence about what this covers", + "questions": [ + { + "type": "single", + "stem": "The question", + "options": [ + { "text": "Answer choice", "correct": true, "why": "Why this choice is right or wrong" } + ], + "rationale": "Teaching explanation of the correct answer", + "topic": "Short topic label", + "difficulty": "medium" + } + ] +} + +Rules: +- "type" is "single" (multiple choice) or "multi" (select all that apply). +- "single" questions have exactly 4 options and exactly one with "correct": true. +- "multi" questions have 5 or 6 options, 2 to 5 of them correct, and the stem ends with "Select all that apply." +- Write NCLEX-style questions that test clinical judgment: a short client scenario, one clear question, priority wording where it fits (first, best, most important), and distractors that are plausible but wrong for a specific reason. Never use "all of the above" or "none of the above". +- Every option needs a one-sentence "why". The "rationale" explains the principle behind the correct answer. +- "topic" is a short label. Reuse the same label for related questions and keep the number of different topics small. +- "difficulty" is "easy", "medium" or "hard". +- Markdown is allowed inside strings (bold, lists, tables). Write line breaks inside strings as \\n. +- The output must be valid JSON: double quotes around every key and string, no trailing commas. +- Base everything on the material below. Do not add facts that are not in it. + +Write 20 questions. + +Material: +[paste your notes or lecture content here]`, + deck: `You are writing flashcards that will be imported into a study app. +Reply with ONE JSON object and nothing else: no commentary and no Markdown code fence. + +Use exactly this shape: +{ + "kind": "deck", + "title": "Short title", + "description": "One sentence about what this covers", + "cards": [ + { "front": "Term or question", "back": "Answer", "hint": "Optional memory aid", "tags": ["topic"] } + ] +} + +Rules: +- One fact or idea per card. Fronts are specific questions or terms; backs are short. +- For medications, put the generic name on the front and use a short Markdown list on the back: class, action, key adverse effects, nursing considerations. +- "hint" is optional. Leave it out or use "" when there is no good memory aid. +- Markdown is allowed inside strings (bold, lists, tables). Write line breaks inside strings as \\n. +- The output must be valid JSON: double quotes around every key and string, no trailing commas. +- Base everything on the material below. Do not add facts that are not in it. + +Write 30 cards covering the most testable facts. + +Material: +[paste your notes or lecture content here]`, +}; diff --git a/web/src/app/Shell.tsx b/web/src/app/Shell.tsx index 4ed648d..008f78e 100644 --- a/web/src/app/Shell.tsx +++ b/web/src/app/Shell.tsx @@ -540,6 +540,8 @@ export function Shell() { const location = useLocation(); const { open: assistantOpen, seed } = useAssistantState(); const onAssistantPage = location.pathname.startsWith('/assistant'); + // Study screens lay themselves out edge to edge and bring their own header and footer. + const immersive = location.pathname === '/review' || /^\/decks\/[^/]+\/cram$/.test(location.pathname); useHotkeys({ 'mod+k': (e) => { @@ -578,8 +580,8 @@ export function Shell() { setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />
- setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} /> -
+ {!immersive && setPaletteOpen(true)} onNewClass={() => setClassDialog(true)} />} +
@@ -597,7 +599,7 @@ export function Shell() { )} - {!showDrawer && !onAssistantPage && isDesktop && ( + {!showDrawer && !onAssistantPage && !immersive && isDesktop && ( + )} + {dirty && ( + + )} + + + } + > + }, + { value: 'deck', label: 'Flashcards', icon: }, + ]} + /> + {data ? ( +