Second revision: MCP servers, shared-link AI, flashcard modes, document previews
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 30s
Generation - Every quiz is NCLEX style; "Practice exam" writes 50 questions. - Calculation questions only when the material involves calculations (max 5 per exam). - Broad topics: the class's topics are listed in the prompt, a quick grouping call maps narrow labels onto broad ones, and leftover variants are merged. - Exact select-all count per batch; option order shuffled. - Python check: at most 3 runs, fixed problems count as passed, cosmetic remarks ignored. Assistant - Text, tool steps and cards appear in the order they happen, with paragraph breaks between steps. - Optional thinking box: fixed height, follows the newest text, can be scrolled back. - "+" opens a material picker listing recent items; items can be dragged in from class pages; shorter placeholder. MCP servers - Streamable HTTP client; encrypted headers. - Per-server instructions and switches for chat, Explain, generation and the quiz check. - Settings UI. Share links - Optional "Explain this" and "Ask about this material" per link, off by default. - Items are loaded on the server and checked against the share; no tools; rate-limited. - Migration 4 stores the switches. Study and documents - Standard flashcard mode (optionally repeat missed cards until known) next to spaced repetition. - Streak visuals restyled in the app palette. - Side by side / Original document views, with sandboxed previews of Word and PowerPoint files. Other - Built-in embedding model baked into the image; sharp stubbed if it cannot load; real load error shown in Settings. - Python runner blocks network and process modules in JavaScript too. - "View questions and answers" removed from the quiz start screen. - Docs updated. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
5ea61c882c
commit
031f7bec31
45 changed files with 2918 additions and 397 deletions
|
|
@ -41,7 +41,7 @@ import { hybridSearch } from '../services/semantic.ts';
|
|||
import { weakTopics } from '../services/stats.ts';
|
||||
import { getSetting, setSetting } from '../settings.ts';
|
||||
import { newId, now, parseJson } from '../util.ts';
|
||||
import { generateStructured, resolveModel, runChat } from './service.ts';
|
||||
import { generateStructured, resolveModel, runChat, runChatWithMcp } from './service.ts';
|
||||
import { verifyQuizDraft } from './verify.ts';
|
||||
import { AIError } from './types.ts';
|
||||
|
||||
|
|
@ -279,7 +279,10 @@ export const generateRequestSchema = z.object({
|
|||
focus: z.string().trim().max(600).optional(),
|
||||
instructions: z.string().trim().max(4000).optional(),
|
||||
count: z.number().int().min(1).max(200).optional(),
|
||||
/** Kept for old presets and API callers; every quiz is written NCLEX style. */
|
||||
style: z.enum(['nclex', 'standard', 'recall']).optional(),
|
||||
/** practice: a short set (default 15). exam: a full practice exam (default 50, at most 5 calculations). */
|
||||
format: z.enum(['practice', 'exam']).optional(),
|
||||
difficulty: z.enum(['easy', 'medium', 'hard', 'mixed']).optional(),
|
||||
/** Share of select-all-that-apply questions, 0..1. */
|
||||
sataShare: z.number().min(0).max(1).optional(),
|
||||
|
|
@ -321,7 +324,10 @@ const QUESTION_SCHEMA = {
|
|||
},
|
||||
},
|
||||
rationale: { type: 'string', description: 'Teaching explanation of the correct answer. Markdown allowed.' },
|
||||
topic: { type: 'string', description: 'Short topic label, reused across related questions (2-4 words).' },
|
||||
topic: {
|
||||
type: 'string',
|
||||
description: 'Broad topic: the main condition, drug class or body system in 1-3 words (e.g. "Stroke", "Heart failure", "Anticoagulants"). Never a subtype or aspect such as "Hemorrhagic stroke" or "Heparin client teaching". Reuse the same label for every question on that subject.',
|
||||
},
|
||||
difficulty: { type: 'string', enum: ['easy', 'medium', 'hard'] },
|
||||
source: { type: 'string', description: 'Id of the excerpt this question is based on, e.g. "c42". Empty if none.' },
|
||||
},
|
||||
|
|
@ -352,7 +358,7 @@ const CARD_SCHEMA = {
|
|||
required: ['cards'],
|
||||
};
|
||||
|
||||
const NUMERIC_RULE = `- Calculation items (dosages, weight-based doses, IV and drip rates, conversions, intake and output) use type "numeric": the student types the number instead of choosing. Give exactly one option, the correct answer with its unit (for example "12.5 mL"), marked correct, with "why" showing the working. State the unit and the rounding rule in the stem ("Round to the nearest tenth."). Only the number is checked, so the student may leave out the unit.`;
|
||||
const NUMERIC_RULE = `- Only write calculation items when the source material itself involves calculations, and never more than the number allowed in the request. Calculation items (dosages, weight-based doses, IV and drip rates, conversions, intake and output) use type "numeric": the student types the number instead of choosing. Give exactly one option, the correct answer with its unit (for example "12.5 mL"), marked correct, with "why" showing the working. State the unit and the rounding rule in the stem ("Round to the nearest tenth."). Only the number is checked, so the student may leave out the unit.`;
|
||||
|
||||
const NCLEX_RULES = `Write NCLEX-style (Next Generation NCLEX) items:
|
||||
- Test clinical judgment at the application and analysis level: recognise cues, analyse, prioritise, choose and evaluate actions. Avoid pure recall.
|
||||
|
|
@ -365,18 +371,7 @@ const NCLEX_RULES = `Write NCLEX-style (Next Generation NCLEX) items:
|
|||
- The rationale teaches: state why the correct answer is correct, name the principle behind it, and give each choice its own "why".
|
||||
${NUMERIC_RULE}`;
|
||||
|
||||
const STANDARD_RULES = `Write clear exam-quality questions:
|
||||
- Each question tests one idea and has one defensible answer set.
|
||||
- Mix understanding and application; avoid trivia and trick wording.
|
||||
- Distractors are plausible and parallel. Never use "all of the above" or "none of the above".
|
||||
- Multiple-choice items have 4 choices with exactly one correct. Select-all items have 4 to 6 choices with at least 2 correct.
|
||||
- The rationale explains the correct answer, and each choice gets its own "why".
|
||||
${NUMERIC_RULE}`;
|
||||
|
||||
const RECALL_RULES = `Write straightforward recall questions that check key facts, definitions, normal values and classifications.
|
||||
- Multiple-choice items have 4 choices with exactly one correct. Select-all items have 4 to 6 choices with at least 2 correct.
|
||||
- Keep stems short and unambiguous. Each choice gets a brief "why".
|
||||
${NUMERIC_RULE}`;
|
||||
|
||||
const CARD_RULES: Record<string, string> = {
|
||||
concise: 'Each card tests exactly one fact. Fronts are specific questions or terms; backs are short (a phrase or one or two lines).',
|
||||
|
|
@ -407,8 +402,6 @@ const BASE_ROLE = 'You are an expert educator writing study material for a nursi
|
|||
export const GENERATION_INSTRUCTIONS = {
|
||||
base: { group: 'All content', label: 'Role', text: BASE_ROLE },
|
||||
'quiz.nclex': { group: 'Quiz questions', label: 'NCLEX style', text: NCLEX_RULES },
|
||||
'quiz.standard': { group: 'Quiz questions', label: 'Standard exam style', text: STANDARD_RULES },
|
||||
'quiz.recall': { group: 'Quiz questions', label: 'Quick recall', text: RECALL_RULES },
|
||||
'deck.concise': { group: 'Flashcards', label: 'Concise', text: CARD_RULES.concise },
|
||||
'deck.detailed': { group: 'Flashcards', label: 'Detailed', text: CARD_RULES.detailed },
|
||||
'deck.medication': { group: 'Flashcards', label: 'Medication', text: CARD_RULES.medication },
|
||||
|
|
@ -593,11 +586,111 @@ function defaultTitle(app: AppContext, req: GenerateRequest, sources: Sources):
|
|||
(req.source.quizId ? getQuiz(app.db, req.source.quizId).title : '') ||
|
||||
(req.source.weakAreas ? 'Weak areas' : '') ||
|
||||
(req.classId ? getClass(app.db, req.classId).name : 'Untitled');
|
||||
const suffix = req.kind === 'quiz' ? (req.source.weakAreas ? 'practice' : req.style === 'nclex' ? 'NCLEX practice' : 'quiz') : req.kind === 'deck' ? 'flashcards' : NOTE_TITLES[req.noteStyle ?? 'study_guide'];
|
||||
const suffix = req.kind === 'quiz' ? (req.source.weakAreas ? 'practice' : req.format === 'exam' ? 'NCLEX practice exam' : 'NCLEX practice') : req.kind === 'deck' ? 'flashcards' : NOTE_TITLES[req.noteStyle ?? 'study_guide'];
|
||||
const cap = subject.charAt(0).toUpperCase() + subject.slice(1);
|
||||
return `${cap} · ${suffix}`.slice(0, 200);
|
||||
}
|
||||
|
||||
/* ------------------------------ quiz helpers ------------------------------ */
|
||||
|
||||
const CALCULATION_RE =
|
||||
/\b(dosage calculation|dose calculation|calculat\w*|mg\/kg|mcg\/kg|units?\/kg|mg\/m2|ml\/h(?:r|our)?|ml per hour|gtt\/min|gtts?|drops? per minute|drop factor|drip rate|flow rate|infusion rate|units?\/ml|mg\/ml|mcg\/ml|round(?:ed)? to the nearest|body surface area|desired over have|dimensional analysis|intake and output|i ?& ?o)\b/i;
|
||||
|
||||
const TOPIC_SCHEMA = {
|
||||
type: 'object',
|
||||
properties: {
|
||||
topics: {
|
||||
type: 'array',
|
||||
items: { type: 'object', properties: { label: { type: 'string' }, topic: { type: 'string', description: 'Broad topic, 1-2 words' } }, required: ['label', 'topic'] },
|
||||
},
|
||||
},
|
||||
required: ['topics'],
|
||||
};
|
||||
|
||||
/**
|
||||
* Maps the topic labels of a new quiz onto a few broad topics ("Heparin client teaching" ->
|
||||
* "Heparin") with one quick model call, reusing the class's existing broad topics. Any failure
|
||||
* keeps the labels as they are.
|
||||
*/
|
||||
async function broadenTopics(app: AppContext, modelId: string | null | undefined, labels: string[], known: string[], signal: AbortSignal): Promise<Map<string, string>> {
|
||||
const out = new Map<string, string>();
|
||||
const broadKnown = [...new Set(known.filter((t) => t.trim() && t.trim().split(/\s+/).length <= 2))].slice(0, 40);
|
||||
if (labels.length === 0 || labels.every((l) => broadKnown.includes(l))) return out;
|
||||
try {
|
||||
const result = await generateStructured(app, {
|
||||
task: 'generate',
|
||||
purpose: 'topic grouping',
|
||||
modelId,
|
||||
reasoningEffort: 'low',
|
||||
maxOutputTokens: 2_000,
|
||||
signal,
|
||||
system: 'You organise nursing exam questions into topics.',
|
||||
messages: [
|
||||
{
|
||||
role: 'user',
|
||||
content: [
|
||||
{
|
||||
type: 'text',
|
||||
text: `Map each topic label below to a broad exam topic of 1-2 words, the way a test blueprint or textbook chapter names it: a condition, a drug or drug class, or a body system (for example "Stroke", "Heparin", "Anticoagulants", "Heart failure", "Fluid balance"). Leave the nursing activity (teaching, monitoring, plan of care, adverse effects, priorities) out of the topic. Labels about the same condition or drug must get the same topic.${broadKnown.length ? `\nReuse one of the class's existing topics when it fits: ${broadKnown.join(', ')}.` : ''}\n\nLabels:\n${labels.map((l) => `- ${l}`).join('\n')}`,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
toolName: 'submit_topics',
|
||||
toolDescription: 'Submit the broad topic for every label.',
|
||||
schema: TOPIC_SCHEMA,
|
||||
});
|
||||
const rows = (result.data as { topics?: { label?: unknown; topic?: unknown }[] })?.topics ?? [];
|
||||
for (const row of Array.isArray(rows) ? rows : []) {
|
||||
const label = typeof row?.label === 'string' ? row.label.trim() : '';
|
||||
const topic = typeof row?.topic === 'string' ? row.topic.replace(/\s+/g, ' ').trim() : '';
|
||||
if (label && topic && topic.length <= 40 && topic.split(' ').length <= 4 && labels.includes(label)) out.set(label, topic);
|
||||
}
|
||||
} catch (err) {
|
||||
if (err instanceof AIError && err.code === 'aborted') throw err;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** True when the material involves calculations, so calculation questions are fair game. */
|
||||
export function mentionsCalculations(text: string): boolean {
|
||||
return CALCULATION_RE.test(text);
|
||||
}
|
||||
|
||||
function sourcesText(sources: { groups: { text: string }[][]; inline: string }): string {
|
||||
return [sources.inline, ...sources.groups.flat().map((c) => c.text)].join('\n');
|
||||
}
|
||||
|
||||
/** Random answer order, so the keyed answer is not always first. "All/none of the above" stay last. */
|
||||
function shuffleOptions<T extends { text: string }>(options: T[]): T[] {
|
||||
const pinned = options.filter((o) => /^(all|none|both|neither)\b.*\b(above|these)\b/i.test(o.text.trim()));
|
||||
const free = options.filter((o) => !pinned.includes(o));
|
||||
for (let i = free.length - 1; i > 0; i -= 1) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[free[i], free[j]] = [free[j], free[i]];
|
||||
}
|
||||
return [...free, ...pinned];
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds narrow topic labels into broad ones: case and spacing differences merge, and a label
|
||||
* that contains another label as whole words ("Hemorrhagic stroke" and "Stroke") takes the
|
||||
* broader one. Existing class topics win ties so results line up with earlier quizzes.
|
||||
*/
|
||||
export function consolidateTopics<T extends { topic: string }>(questions: T[], known: string[] = []): T[] {
|
||||
const norm = (t: string) => t.toLowerCase().replace(/\s+/g, ' ').trim();
|
||||
const canonical = new Map<string, string>();
|
||||
for (const t of [...known, ...questions.map((q) => q.topic)]) if (t.trim() && !canonical.has(norm(t))) canonical.set(norm(t), t.trim());
|
||||
const labels = [...canonical.keys()].sort((a, b) => a.length - b.length);
|
||||
const target = (t: string): string => {
|
||||
const n = norm(t);
|
||||
if (!n) return t;
|
||||
const broader = labels.find((l) => l !== n && l.length >= 4 && new RegExp(`(^|\\s)${l.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}($|\\s)`).test(n));
|
||||
return canonical.get(broader ?? n) ?? t;
|
||||
};
|
||||
return questions.map((q) => ({ ...q, topic: target(q.topic) }));
|
||||
}
|
||||
|
||||
const NOTE_TITLES: Record<string, string> = { study_guide: 'study guide', summary: 'summary', outline: 'outline', cheat_sheet: 'cheat sheet' };
|
||||
|
||||
/**
|
||||
|
|
@ -655,7 +748,7 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
const isQuiz = req.kind === 'quiz';
|
||||
const perBatch = isQuiz ? 8 : 25;
|
||||
const defaultCount = isQuiz ? 15 : 30;
|
||||
let count = req.count ?? defaultCount;
|
||||
let count = req.count ?? (isQuiz && req.format === 'exam' ? 50 : defaultCount);
|
||||
if ((req.source.deckId || req.source.quizId) && !req.count) {
|
||||
// Conversions default to one item per source item.
|
||||
count = req.source.deckId ? listCards(db, req.source.deckId).length : listQuestions(db, req.source.quizId!).length;
|
||||
|
|
@ -673,20 +766,33 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
const seen = new Set<string>();
|
||||
const notes: string[] = [];
|
||||
|
||||
const style = req.style ?? 'nclex';
|
||||
const rules = isQuiz ? instruction(db, `quiz.${style}`) : instruction(db, `deck.${req.cardStyle ?? 'concise'}`);
|
||||
// Every quiz is NCLEX style (the student's exams are); older presets asking for another style get it too.
|
||||
const style = 'nclex' as const;
|
||||
const rules = isQuiz ? instruction(db, 'quiz.nclex') : instruction(db, `deck.${req.cardStyle ?? 'concise'}`);
|
||||
const system = `${baseSystem(db, req, hasSources)}\n\n${rules}`;
|
||||
const sata = req.sataShare ?? (style === 'nclex' ? 0.3 : 0.2);
|
||||
const sata = req.sataShare ?? 0.3;
|
||||
const difficulty = req.difficulty ?? 'mixed';
|
||||
// Calculation questions: only when the material involves calculations, and at most 5 per
|
||||
// 50-question exam (10% of a practice set).
|
||||
const mathAllowed = isQuiz && mentionsCalculations([sourcesText(sources), req.focus ?? '', req.instructions ?? ''].join('\n'));
|
||||
const numericCap = !mathAllowed ? 0 : req.format === 'exam' ? Math.min(5, Math.max(1, Math.round(count / 10))) : Math.max(1, Math.round(count / 10));
|
||||
const numericCount = () => (draft.kind === 'quiz' ? draft.questions.filter((q) => q.type === 'numeric').length : 0);
|
||||
// Broad topic labels, shared with the class's existing quizzes so results group sensibly.
|
||||
const knownTopics = isQuiz && req.classId ? db.all<{ topic: string }>(`SELECT DISTINCT q.topic FROM questions q JOIN quizzes z ON z.id = q.quiz_id WHERE z.class_id = ? AND q.topic != '' LIMIT 60`, req.classId).map((r) => r.topic) : [];
|
||||
|
||||
const runBatch = async (index: number, want: number): Promise<number> => {
|
||||
const written = items().map((x) => `- ${('stem' in x ? x.stem : x.front).replace(/\s+/g, ' ').slice(0, 140)}`);
|
||||
const sataCount = Math.round(want * sata);
|
||||
const numericLeft = Math.max(0, numericCap - numericCount());
|
||||
const topicsSoFar = [...new Set([...knownTopics, ...(draft.kind === 'quiz' ? draft.questions.map((q) => q.topic) : [])].filter(Boolean))];
|
||||
const ask = isQuiz
|
||||
? [
|
||||
`Write ${want} ${style === 'nclex' ? 'NCLEX-style ' : ''}questions${req.focus ? ` about: ${req.focus}` : ''}.`,
|
||||
sata <= 0 ? 'Use only multiple-choice (single) questions, apart from calculations.' : sata >= 1 ? 'Use only select-all-that-apply (multi) questions, apart from calculations.' : `About ${sataCount} of them should be select-all-that-apply (multi); the rest multiple choice (single).`,
|
||||
'If the material involves calculations (dosages, IV rates, conversions), write those as numeric questions the student answers by typing the number.',
|
||||
`Write ${want} NCLEX-style questions${req.focus ? ` about: ${req.focus}` : ''}.`,
|
||||
sata <= 0 ? 'Use only multiple-choice (single) questions, apart from calculations.' : sata >= 1 ? 'Use only select-all-that-apply (multi) questions, apart from calculations.' : `Exactly ${sataCount} of them must be select-all-that-apply (type "multi"); the rest multiple choice (single).`,
|
||||
numericLeft === 0
|
||||
? 'Do not write any calculation (numeric) questions in this batch.'
|
||||
: `The material involves calculations: you may include up to ${numericLeft} calculation question${numericLeft === 1 ? '' : 's'} (type "numeric", the student types the number). Do not exceed that.`,
|
||||
`Topic labels must be broad (the main condition, drug class or body system, 1-3 words), not subtypes or aspects.${topicsSoFar.length ? ` Reuse these existing topics wherever they fit: ${topicsSoFar.slice(0, 40).join(', ')}.` : ''}`,
|
||||
difficulty === 'mixed' ? 'Mix difficulty: mostly medium, with a few easy and a few hard.' : `Difficulty: ${difficulty}.`,
|
||||
sources.groups.length > 0 ? 'Spread the questions across the excerpts instead of clustering on one. Set "source" to the id of the excerpt each question is based on.' : '',
|
||||
req.source.deckId ? 'Turn the flashcards into questions: use each card\'s answer as the correct choice and write distractors that a student could confuse with it.' : '',
|
||||
|
|
@ -710,6 +816,7 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
schema: isQuiz ? QUESTION_SCHEMA : CARD_SCHEMA,
|
||||
maxOutputTokens: resolved.params.maxOutputTokens ?? 16_000,
|
||||
signal,
|
||||
mcpArea: 'generate',
|
||||
});
|
||||
const parsed = draftsFromValue(result.data).items.find((x) => x.kind === req.kind) as QuizDraft | DeckDraft | undefined;
|
||||
const incoming: (DraftQuestion | DraftCard)[] = parsed ? (parsed.kind === 'quiz' ? parsed.questions : parsed.cards) : [];
|
||||
|
|
@ -723,6 +830,8 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
const ref = (item.source ?? '').replace(/[[\]\s]/g, '');
|
||||
item.source = sources.refs.get(ref) ?? undefined;
|
||||
}
|
||||
if ('stem' in item && item.type === 'numeric' && numericCount() >= numericCap) continue; // over the calculation allowance; a top-up replaces it
|
||||
if ('stem' in item && item.type !== 'numeric') item.options = shuffleOptions(item.options);
|
||||
seen.add(k);
|
||||
(items() as (DraftQuestion | DraftCard)[]).push(item);
|
||||
added += 1;
|
||||
|
|
@ -760,10 +869,19 @@ async function runGeneration(app: AppContext, draftId: string, req: GenerateRequ
|
|||
if (items().length === 0) throw new AIError('invalid_response', 'The model did not produce any usable items. Try again, or choose a different model for content generation.');
|
||||
if (items().length < count) notes.push(`Generated ${items().length} of the ${count} requested.`);
|
||||
|
||||
if (draft.kind === 'quiz') {
|
||||
setProgress(db, draftId, 0.95, 'Grouping topics', draft);
|
||||
const mapping = await broadenTopics(app, req.modelId, [...new Set(draft.questions.map((q) => q.topic).filter(Boolean))], knownTopics, signal);
|
||||
draft.questions = consolidateTopics(
|
||||
draft.questions.map((q) => ({ ...q, topic: mapping.get(q.topic) ?? q.topic })),
|
||||
knownTopics.filter((t) => t.trim().split(/\s+/).length <= 2),
|
||||
);
|
||||
}
|
||||
|
||||
// Check counts, the type mix, answer keys and calculations with Python before review.
|
||||
if (draft.kind === 'quiz' && req.verify !== false) {
|
||||
setProgress(db, draftId, 0.96, 'Checking the questions with Python', draft);
|
||||
const checked = await verifyQuizDraft(app, draft, { count, style, sataShare: sata, difficulty }, { modelId: req.modelId, signal, onStep: (label) => setProgress(db, draftId, 0.97, label) });
|
||||
const checked = await verifyQuizDraft(app, draft, { count, style, sataShare: sata, difficulty, numericCap }, { modelId: req.modelId, signal, onStep: (label) => setProgress(db, draftId, 0.97, label) });
|
||||
draft.questions = checked.draft.questions;
|
||||
notes.push(...checked.notes);
|
||||
}
|
||||
|
|
@ -813,7 +931,7 @@ async function generateNote(app: AppContext, draftId: string, req: GenerateReque
|
|||
if (passes.length <= 1) {
|
||||
setProgress(db, draftId, 0.2, 'Writing');
|
||||
const body = [passes[0]?.length ? `SOURCE EXCERPTS:\n\n${formatExcerpts(passes[0])}` : '', sources.inline, ask].filter(Boolean).join('\n\n======\n\n');
|
||||
const res = await runChat(app, { task: 'generate', purpose: 'study guide', modelId: req.modelId, system, messages: [{ role: 'user', content: [{ type: 'text', text: body }] }], maxOutputTokens: resolved.params.maxOutputTokens ?? 16_000, signal });
|
||||
const res = await runChatWithMcp(app, { task: 'generate', purpose: 'study guide', modelId: req.modelId, system, messages: [{ role: 'user', content: [{ type: 'text', text: body }] }], maxOutputTokens: resolved.params.maxOutputTokens ?? 16_000, signal }, 'generate');
|
||||
content = res.text;
|
||||
} else {
|
||||
// Long material: condense each part, then write the final piece from the condensed notes.
|
||||
|
|
@ -833,15 +951,19 @@ async function generateNote(app: AppContext, draftId: string, req: GenerateReque
|
|||
partials.push(res.text.trim());
|
||||
}
|
||||
setProgress(db, draftId, 0.8, 'Writing');
|
||||
const res = await runChat(app, {
|
||||
task: 'generate',
|
||||
purpose: 'study guide',
|
||||
modelId: req.modelId,
|
||||
system,
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: `CONDENSED NOTES FROM THE FULL MATERIAL:\n\n${partials.join('\n\n---\n\n')}\n\n======\n\n${sources.inline ? `${sources.inline}\n\n======\n\n` : ''}${ask}` }] }],
|
||||
maxOutputTokens: resolved.params.maxOutputTokens ?? 16_000,
|
||||
signal,
|
||||
});
|
||||
const res = await runChatWithMcp(
|
||||
app,
|
||||
{
|
||||
task: 'generate',
|
||||
purpose: 'study guide',
|
||||
modelId: req.modelId,
|
||||
system,
|
||||
messages: [{ role: 'user', content: [{ type: 'text', text: `CONDENSED NOTES FROM THE FULL MATERIAL:\n\n${partials.join('\n\n---\n\n')}\n\n======\n\n${sources.inline ? `${sources.inline}\n\n======\n\n` : ''}${ask}` }] }],
|
||||
maxOutputTokens: resolved.params.maxOutputTokens ?? 16_000,
|
||||
signal,
|
||||
},
|
||||
'generate',
|
||||
);
|
||||
content = res.text;
|
||||
}
|
||||
content = content.trim().replace(/^```(?:markdown|md)?\s*\n([\s\S]*?)\n```$/i, '$1');
|
||||
|
|
@ -934,6 +1056,7 @@ Return the questions in the same order, one output question per input question.$
|
|||
schema: QUESTION_SCHEMA,
|
||||
maxOutputTokens: resolved.params.maxOutputTokens ?? 16_000,
|
||||
signal: controller.signal,
|
||||
mcpArea: 'generate',
|
||||
});
|
||||
const parsed = draftsFromValue(result.data).items.find((x) => x.kind === 'quiz') as QuizDraft | undefined;
|
||||
const improved = parsed?.questions ?? [];
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue