@molecule/api-ai-quiz-generation 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,115 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work.
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-ai-quiz-generation` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-ai-quiz-generation is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,97 @@
1
+ /**
2
+ * `@molecule/api-ai-quiz-generation` — generate quizzes from source
3
+ * material + auto-grade student responses via the bonded AI provider.
4
+ *
5
+ * Extracted from ai-study-buddy flagship. For pure rule-based grading
6
+ * (multiple-choice → exact match), use `@molecule/api-utilities-quiz-grading`.
7
+ * This package adds AI-assisted generation + free-response grading.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { generateQuiz, gradeResponses } from '@molecule/api-ai-quiz-generation'
12
+ *
13
+ * const quiz = await generateQuiz({
14
+ * source: chapterText,
15
+ * questionCount: 10,
16
+ * types: ['multiple_choice', 'short_answer'],
17
+ * difficulty: 'medium',
18
+ * })
19
+ *
20
+ * const result = await gradeResponses({
21
+ * quiz,
22
+ * responses: studentAnswers,
23
+ * })
24
+ * ```
25
+ *
26
+ * @remarks
27
+ * Requires a bonded `ai` chat provider (`@molecule/api-ai`) — both functions
28
+ * throw if none is bonded.
29
+ *
30
+ * Failure shapes (no rejection): malformed model output — or a provider API
31
+ * failure, which arrives as an in-band `error` event this package does not
32
+ * treat as fatal — makes `generateQuiz()` resolve `{ questions: [] }` and
33
+ * `gradeResponses()` resolve `{ responses: [], earned: 0, percentage: 0 }`.
34
+ * An empty `questions` array means the model output failed to parse, not
35
+ * "the source had nothing to ask" — surface a retry instead of rendering an
36
+ * empty quiz, and don't record a 0% grade whose `responses` array is empty.
37
+ * `total`/`percentage` are computed from the quiz's own question count, so a
38
+ * partially-parsed grading under-reports `earned`, never over-reports.
39
+ *
40
+ * @module
41
+ */
42
+ export * from './browser-guard.js';
43
+ /** Union of supported quiz question formats. */
44
+ export type QuestionType = 'multiple_choice' | 'true_false' | 'short_answer' | 'fill_in_the_blank';
45
+ /** Relative difficulty level for a question or generated quiz. */
46
+ export type Difficulty = 'easy' | 'medium' | 'hard';
47
+ /** A single quiz question with prompt, answer, and optional metadata. */
48
+ export interface Question {
49
+ id: string;
50
+ type: QuestionType;
51
+ prompt: string;
52
+ /** For multiple_choice / true_false. */
53
+ options?: string[];
54
+ /** The correct answer (or one of the accepted forms). */
55
+ answer: string;
56
+ /** Why this is the right answer — surfaced after submission. */
57
+ explanation?: string;
58
+ difficulty?: Difficulty;
59
+ }
60
+ /** A generated quiz containing an ordered list of questions and an optional source summary. */
61
+ export interface Quiz {
62
+ questions: Question[];
63
+ source_summary?: string;
64
+ }
65
+ /** AI-graded result for a single student response, including correctness, score, and feedback. */
66
+ export interface GradedResponse {
67
+ question_id: string;
68
+ submitted: string;
69
+ correct: boolean;
70
+ score: number;
71
+ feedback?: string;
72
+ }
73
+ /** Aggregated grading outcome for a full set of student responses. */
74
+ export interface GradeResult {
75
+ responses: GradedResponse[];
76
+ total: number;
77
+ earned: number;
78
+ percentage: number;
79
+ }
80
+ /** Generates a quiz from source material using the bonded AI provider, returning structured questions. */
81
+ export declare function generateQuiz(opts: {
82
+ source: string;
83
+ questionCount?: number;
84
+ types?: QuestionType[];
85
+ difficulty?: Difficulty;
86
+ model?: string;
87
+ }): Promise<Quiz>;
88
+ /** Grades a set of student responses against the quiz answer key using the bonded AI provider. */
89
+ export declare function gradeResponses(opts: {
90
+ quiz: Quiz;
91
+ responses: Array<{
92
+ question_id: string;
93
+ submitted: string;
94
+ }>;
95
+ model?: string;
96
+ }): Promise<GradeResult>;
97
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAwCG;AAIH,cAAc,oBAAoB,CAAA;AAElC,gDAAgD;AAChD,MAAM,MAAM,YAAY,GAAG,iBAAiB,GAAG,YAAY,GAAG,cAAc,GAAG,mBAAmB,CAAA;AAClG,kEAAkE;AAClE,MAAM,MAAM,UAAU,GAAG,MAAM,GAAG,QAAQ,GAAG,MAAM,CAAA;AAEnD,yEAAyE;AACzE,MAAM,WAAW,QAAQ;IACvB,EAAE,EAAE,MAAM,CAAA;IACV,IAAI,EAAE,YAAY,CAAA;IAClB,MAAM,EAAE,MAAM,CAAA;IACd,wCAAwC;IACxC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAA;IAClB,yDAAyD;IACzD,MAAM,EAAE,MAAM,CAAA;IACd,gEAAgE;IAChE,WAAW,CAAC,EAAE,MAAM,CAAA;IACpB,UAAU,CAAC,EAAE,UAAU,CAAA;CACxB;AAED,+FAA+F;AAC/F,MAAM,WAAW,IAAI;IACnB,SAAS,EAAE,QAAQ,EAAE,CAAA;IACrB,cAAc,CAAC,EAAE,MAAM,CAAA;CACxB;AAED,kGAAkG;AAClG,MAAM,WAAW,cAAc;IAC7B,WAAW,EAAE,MAAM,CAAA;IACnB,SAAS,EAAE,MAAM,CAAA;IACjB,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,MAAM,CAAA;IACb,QAAQ,CAAC,EAAE,MAAM,CAAA;CAClB;AAED,sEAAsE;AACtE,MAAM,WAAW,WAAW;IAC1B,SAAS,EAAE,cAAc,EAAE,CAAA;IAC3B,KAAK,EAAE,MAAM,CAAA;IACb,MAAM,EAAE,MAAM,CAAA;IACd,UAAU,EAAE,MAAM,CAAA;CACnB;AAqED,0GAA0G;AAC1G,wBAAsB,YAAY,CAAC,IAAI,EAAE;IACvC,MAAM,EAAE,MAAM,CAAA;IACd,aAAa,CAAC,EAAE,MAAM,CAAA;IACtB,KAAK,CAAC,EAAE,YAAY,EAAE,CAAA;IACtB,UAAU,CAAC,EAAE,UAAU,CAAA;IACvB,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,GAAG,OAAO,CAAC,IAAI,CAAC,CAQhB;AAkBD,kGAAkG;AAClG,wBAAsB,cAAc,CAAC,IAAI,EAAE;IACzC,IAAI,EAAE,IAAI,CAAA;IACV,SAAS,EAAE,KAAK,CAAC;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,SAAS,EAAE,MAAM,CAAA;KAAE,CAAC,CAAA;IAC5D,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,GAAG,OAAO,CAAC,WAAW,CAAC,CAsBvB"}
package/dist/index.js ADDED
@@ -0,0 +1,154 @@
1
+ /**
2
+ * `@molecule/api-ai-quiz-generation` — generate quizzes from source
3
+ * material + auto-grade student responses via the bonded AI provider.
4
+ *
5
+ * Extracted from ai-study-buddy flagship. For pure rule-based grading
6
+ * (multiple-choice → exact match), use `@molecule/api-utilities-quiz-grading`.
7
+ * This package adds AI-assisted generation + free-response grading.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { generateQuiz, gradeResponses } from '@molecule/api-ai-quiz-generation'
12
+ *
13
+ * const quiz = await generateQuiz({
14
+ * source: chapterText,
15
+ * questionCount: 10,
16
+ * types: ['multiple_choice', 'short_answer'],
17
+ * difficulty: 'medium',
18
+ * })
19
+ *
20
+ * const result = await gradeResponses({
21
+ * quiz,
22
+ * responses: studentAnswers,
23
+ * })
24
+ * ```
25
+ *
26
+ * @remarks
27
+ * Requires a bonded `ai` chat provider (`@molecule/api-ai`) — both functions
28
+ * throw if none is bonded.
29
+ *
30
+ * Failure shapes (no rejection): malformed model output — or a provider API
31
+ * failure, which arrives as an in-band `error` event this package does not
32
+ * treat as fatal — makes `generateQuiz()` resolve `{ questions: [] }` and
33
+ * `gradeResponses()` resolve `{ responses: [], earned: 0, percentage: 0 }`.
34
+ * An empty `questions` array means the model output failed to parse, not
35
+ * "the source had nothing to ask" — surface a retry instead of rendering an
36
+ * empty quiz, and don't record a 0% grade whose `responses` array is empty.
37
+ * `total`/`percentage` are computed from the quiz's own question count, so a
38
+ * partially-parsed grading under-reports `earned`, never over-reports.
39
+ *
40
+ * @module
41
+ */
42
+ import { requireProvider as requireAI } from '@molecule/api-ai';
43
+ export * from './browser-guard.js';
44
+ /** Sends a single-turn chat prompt to the bonded AI provider and returns the full text response. */
45
+ async function callAI(prompt, model, temperature = 0.3) {
46
+ const ai = requireAI();
47
+ let raw = '';
48
+ for await (const event of ai.chat({
49
+ messages: [{ role: 'user', content: prompt }],
50
+ model,
51
+ temperature,
52
+ })) {
53
+ // A ChatEvent's text payload is `content` (NOT `text`, which is the
54
+ // ContentBlock shape) — reading `event.text` accumulated nothing.
55
+ if (event.type === 'text')
56
+ raw += event.content;
57
+ }
58
+ return raw;
59
+ }
60
+ /** Strips optional markdown code fences from an AI response and parses the result as JSON, returning null on parse failure. */
61
+ function parseJson(raw) {
62
+ try {
63
+ // Extract the JSON object even when the model wraps it in prose and/or a
64
+ // markdown fence (LLMs commonly add "Here is the result:" or trailing
65
+ // remarks). Prefer fenced content, then slice first `{` to last `}` — a bare
66
+ // fence-strip fails on prose around the block.
67
+ const fenced = raw.match(/```(?:json)?\s*([\s\S]*?)```/i);
68
+ const jsonBody = (fenced ? fenced[1] : raw).trim();
69
+ // Slice the outermost JSON value — object OR array — out of any prose.
70
+ const objAt = jsonBody.indexOf('{');
71
+ const arrAt = jsonBody.indexOf('[');
72
+ const useArray = arrAt >= 0 && (objAt < 0 || arrAt < objAt);
73
+ const valStart = useArray ? arrAt : objAt;
74
+ const valEnd = jsonBody.lastIndexOf(useArray ? ']' : '}');
75
+ const json = valStart >= 0 && valEnd > valStart ? jsonBody.slice(valStart, valEnd + 1) : jsonBody;
76
+ return JSON.parse(json);
77
+ }
78
+ catch (_error) {
79
+ // Intentional noop: AI may return malformed or non-JSON output; callers handle the null return.
80
+ return null;
81
+ }
82
+ }
83
+ const GENERATE_PROMPT = `Generate a quiz from the following source material.
84
+
85
+ Requirements:
86
+ - {{COUNT}} questions
87
+ - Question types: {{TYPES}}
88
+ - Difficulty: {{DIFFICULTY}}
89
+ - Each question must be answerable from the source
90
+
91
+ Return ONLY a JSON object:
92
+ {
93
+ "source_summary": "1-2 sentence summary of the material",
94
+ "questions": [
95
+ {
96
+ "id": "q1",
97
+ "type": "multiple_choice",
98
+ "prompt": "...",
99
+ "options": ["A", "B", "C", "D"],
100
+ "answer": "B",
101
+ "explanation": "...",
102
+ "difficulty": "medium"
103
+ }
104
+ ]
105
+ }
106
+
107
+ Source:
108
+ {{SOURCE}}`;
109
+ /** Generates a quiz from source material using the bonded AI provider, returning structured questions. */
110
+ export async function generateQuiz(opts) {
111
+ const prompt = GENERATE_PROMPT.replace('{{COUNT}}', String(opts.questionCount ?? 5))
112
+ .replace('{{TYPES}}', (opts.types ?? ['multiple_choice', 'short_answer']).join(', '))
113
+ .replace('{{DIFFICULTY}}', opts.difficulty ?? 'medium')
114
+ .replace('{{SOURCE}}', opts.source);
115
+ const raw = await callAI(prompt, opts.model);
116
+ const parsed = parseJson(raw);
117
+ return parsed ?? { questions: [] };
118
+ }
119
+ const GRADE_PROMPT = `Grade these student responses against the answer key.
120
+
121
+ For each response:
122
+ - "correct" — boolean
123
+ - "score" — 0..1 (partial credit for short_answer if substantively correct but not exact)
124
+ - "feedback" — 1-2 sentences explaining the grade
125
+
126
+ Return ONLY a JSON array:
127
+ [{"question_id": "q1", "submitted": "...", "correct": true, "score": 1.0, "feedback": "..."}]
128
+
129
+ Answer key:
130
+ {{ANSWER_KEY}}
131
+
132
+ Student responses:
133
+ {{RESPONSES}}`;
134
+ /** Grades a set of student responses against the quiz answer key using the bonded AI provider. */
135
+ export async function gradeResponses(opts) {
136
+ const answerKey = opts.quiz.questions.map((q) => ({
137
+ id: q.id,
138
+ type: q.type,
139
+ prompt: q.prompt,
140
+ answer: q.answer,
141
+ options: q.options,
142
+ }));
143
+ const prompt = GRADE_PROMPT.replace('{{ANSWER_KEY}}', JSON.stringify(answerKey, null, 2)).replace('{{RESPONSES}}', JSON.stringify(opts.responses, null, 2));
144
+ const raw = await callAI(prompt, opts.model);
145
+ const parsed = parseJson(raw) ?? [];
146
+ const total = opts.quiz.questions.length;
147
+ const earned = parsed.reduce((sum, r) => sum + (r.score ?? 0), 0);
148
+ return {
149
+ responses: parsed,
150
+ total,
151
+ earned: Math.round(earned * 100) / 100,
152
+ percentage: total > 0 ? Math.round((earned / total) * 100) : 0,
153
+ };
154
+ }
package/package.json ADDED
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@molecule/api-ai-quiz-generation",
3
+ "version": "1.0.0",
4
+ "description": "AI quiz generation from source material + auto-grading",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "ai",
25
+ "quiz",
26
+ "education",
27
+ "grading"
28
+ ],
29
+ "license": "Apache-2.0",
30
+ "devDependencies": {
31
+ "@types/node": "26.1.2",
32
+ "typescript": "6.0.3",
33
+ "vitest": "4.1.10"
34
+ },
35
+ "peerDependencies": {
36
+ "@molecule/api-bonds-default-express": "^1.0.0",
37
+ "@molecule/api-database": "^1.0.0",
38
+ "@molecule/api-i18n": "^1.0.0",
39
+ "@molecule/api-middleware-validation": "^1.0.0",
40
+ "@molecule/api-ai": "^1.0.0"
41
+ }
42
+ }