learngraph 0.2.0 → 0.4.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.
Files changed (76) hide show
  1. package/README.md +82 -1
  2. package/dist/cjs/llm/adapters/anthropic.js +124 -0
  3. package/dist/cjs/llm/adapters/anthropic.js.map +1 -0
  4. package/dist/cjs/llm/adapters/base.js +100 -0
  5. package/dist/cjs/llm/adapters/base.js.map +1 -0
  6. package/dist/cjs/llm/adapters/gemini.js +156 -0
  7. package/dist/cjs/llm/adapters/gemini.js.map +1 -0
  8. package/dist/cjs/llm/adapters/index.js +33 -0
  9. package/dist/cjs/llm/adapters/index.js.map +1 -0
  10. package/dist/cjs/llm/adapters/mediapipe.js +290 -0
  11. package/dist/cjs/llm/adapters/mediapipe.js.map +1 -0
  12. package/dist/cjs/llm/adapters/ollama.js +149 -0
  13. package/dist/cjs/llm/adapters/ollama.js.map +1 -0
  14. package/dist/cjs/llm/adapters/openai.js +126 -0
  15. package/dist/cjs/llm/adapters/openai.js.map +1 -0
  16. package/dist/cjs/llm/adapters/openrouter.js +190 -0
  17. package/dist/cjs/llm/adapters/openrouter.js.map +1 -0
  18. package/dist/cjs/llm/index.js +42 -5
  19. package/dist/cjs/llm/index.js.map +1 -1
  20. package/dist/cjs/llm/orchestrator.js +219 -0
  21. package/dist/cjs/llm/orchestrator.js.map +1 -0
  22. package/dist/cjs/llm/prompts.js +367 -0
  23. package/dist/cjs/llm/prompts.js.map +1 -0
  24. package/dist/cjs/types/llm.js +8 -0
  25. package/dist/cjs/types/llm.js.map +1 -0
  26. package/dist/esm/llm/adapters/anthropic.js +119 -0
  27. package/dist/esm/llm/adapters/anthropic.js.map +1 -0
  28. package/dist/esm/llm/adapters/base.js +95 -0
  29. package/dist/esm/llm/adapters/base.js.map +1 -0
  30. package/dist/esm/llm/adapters/gemini.js +151 -0
  31. package/dist/esm/llm/adapters/gemini.js.map +1 -0
  32. package/dist/esm/llm/adapters/index.js +13 -0
  33. package/dist/esm/llm/adapters/index.js.map +1 -0
  34. package/dist/esm/llm/adapters/mediapipe.js +252 -0
  35. package/dist/esm/llm/adapters/mediapipe.js.map +1 -0
  36. package/dist/esm/llm/adapters/ollama.js +144 -0
  37. package/dist/esm/llm/adapters/ollama.js.map +1 -0
  38. package/dist/esm/llm/adapters/openai.js +121 -0
  39. package/dist/esm/llm/adapters/openai.js.map +1 -0
  40. package/dist/esm/llm/adapters/openrouter.js +185 -0
  41. package/dist/esm/llm/adapters/openrouter.js.map +1 -0
  42. package/dist/esm/llm/index.js +12 -6
  43. package/dist/esm/llm/index.js.map +1 -1
  44. package/dist/esm/llm/orchestrator.js +214 -0
  45. package/dist/esm/llm/orchestrator.js.map +1 -0
  46. package/dist/esm/llm/prompts.js +360 -0
  47. package/dist/esm/llm/prompts.js.map +1 -0
  48. package/dist/esm/types/llm.js +7 -0
  49. package/dist/esm/types/llm.js.map +1 -0
  50. package/dist/types/llm/adapters/anthropic.d.ts +21 -0
  51. package/dist/types/llm/adapters/anthropic.d.ts.map +1 -0
  52. package/dist/types/llm/adapters/base.d.ts +46 -0
  53. package/dist/types/llm/adapters/base.d.ts.map +1 -0
  54. package/dist/types/llm/adapters/gemini.d.ts +30 -0
  55. package/dist/types/llm/adapters/gemini.d.ts.map +1 -0
  56. package/dist/types/llm/adapters/index.d.ts +14 -0
  57. package/dist/types/llm/adapters/index.d.ts.map +1 -0
  58. package/dist/types/llm/adapters/mediapipe.d.ts +113 -0
  59. package/dist/types/llm/adapters/mediapipe.d.ts.map +1 -0
  60. package/dist/types/llm/adapters/ollama.d.ts +30 -0
  61. package/dist/types/llm/adapters/ollama.d.ts.map +1 -0
  62. package/dist/types/llm/adapters/openai.d.ts +22 -0
  63. package/dist/types/llm/adapters/openai.d.ts.map +1 -0
  64. package/dist/types/llm/adapters/openrouter.d.ts +58 -0
  65. package/dist/types/llm/adapters/openrouter.d.ts.map +1 -0
  66. package/dist/types/llm/index.d.ts +5 -0
  67. package/dist/types/llm/index.d.ts.map +1 -1
  68. package/dist/types/llm/orchestrator.d.ts +35 -0
  69. package/dist/types/llm/orchestrator.d.ts.map +1 -0
  70. package/dist/types/llm/prompts.d.ts +269 -0
  71. package/dist/types/llm/prompts.d.ts.map +1 -0
  72. package/dist/types/types/index.d.ts +1 -0
  73. package/dist/types/types/index.d.ts.map +1 -1
  74. package/dist/types/types/llm.d.ts +337 -0
  75. package/dist/types/types/llm.d.ts.map +1 -0
  76. package/package.json +6 -2
@@ -0,0 +1,367 @@
1
+ "use strict";
2
+ /**
3
+ * Prompts for LLM-based educational tasks
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ exports.DECOMPOSITION_SCHEMA = exports.BLOOM_ANALYSIS_SCHEMA = exports.PREREQUISITE_SCHEMA = exports.EXTRACTION_SCHEMA = exports.SYSTEM_PROMPTS = void 0;
9
+ exports.buildExtractionPrompt = buildExtractionPrompt;
10
+ exports.buildPrerequisitePrompt = buildPrerequisitePrompt;
11
+ exports.buildBloomPrompt = buildBloomPrompt;
12
+ exports.buildDecompositionPrompt = buildDecompositionPrompt;
13
+ // ─────────────────────────────────────────────────────────────────────────────
14
+ // System Prompts
15
+ // ─────────────────────────────────────────────────────────────────────────────
16
+ exports.SYSTEM_PROMPTS = {
17
+ skillExtraction: `You are an expert educational curriculum analyst specializing in competency-based education and learning science.
18
+
19
+ Your task is to analyze curriculum content and extract discrete, measurable skills that learners should master.
20
+
21
+ For each skill you identify:
22
+ 1. Name: A concise, action-oriented name (e.g., "Calculate derivative of polynomial")
23
+ 2. Description: A clear explanation of what mastery of this skill looks like
24
+ 3. Bloom's Level: Classify using Bloom's Taxonomy (remember, understand, apply, analyze, evaluate, create)
25
+ 4. Difficulty: Estimate difficulty on a 0-1 scale based on cognitive complexity
26
+ 5. Threshold Concept: Identify if this is a transformative "gateway" skill that changes understanding
27
+ 6. Estimated Time: How long a typical learner needs to achieve mastery
28
+
29
+ Focus on:
30
+ - Observable, measurable outcomes
31
+ - Skills that can be assessed
32
+ - Appropriate granularity (not too broad, not too narrow)
33
+ - Clear prerequisite relationships
34
+
35
+ Bloom's Level Guidelines:
36
+ - remember (0.20): Recall facts, terms, basic concepts
37
+ - understand (0.35): Explain ideas, interpret, summarize
38
+ - apply (0.50): Use information in new situations, solve problems
39
+ - analyze (0.65): Draw connections, organize, compare, contrast
40
+ - evaluate (0.80): Justify decisions, make judgments, critique
41
+ - create (0.90): Produce new work, design, construct`,
42
+ prerequisiteInference: `You are an expert in learning science and curriculum design, specializing in prerequisite mapping and learning path optimization.
43
+
44
+ Your task is to analyze skills and infer prerequisite relationships between them.
45
+
46
+ For each prerequisite relationship:
47
+ 1. Identify which skill must be learned first (source/prerequisite)
48
+ 2. Identify which skill depends on it (target/dependent)
49
+ 3. Classify the relationship type:
50
+ - hard: Absolutely required - cannot learn target without source
51
+ - soft: Strongly beneficial but not strictly required
52
+ - recommended: Helpful for optimal learning path
53
+ 4. Estimate strength (0-1): How critical is this prerequisite?
54
+ 5. Provide clear reasoning for the relationship
55
+
56
+ Consider:
57
+ - Bloom's level progression (lower levels typically prerequisite to higher)
58
+ - Conceptual dependencies (foundational concepts before advanced)
59
+ - Skill hierarchies within domains
60
+ - Transfer of learning between related skills
61
+ - Avoid circular dependencies`,
62
+ bloomAnalysis: `You are an expert in Bloom's Taxonomy and educational assessment design.
63
+
64
+ Analyze the given text and determine its cognitive level according to Bloom's Taxonomy:
65
+
66
+ 1. remember - Recall facts and basic concepts
67
+ Verbs: define, identify, list, name, recall, recognize, state
68
+
69
+ 2. understand - Explain ideas or concepts
70
+ Verbs: describe, explain, interpret, summarize, classify, compare
71
+
72
+ 3. apply - Use information in new situations
73
+ Verbs: apply, calculate, solve, demonstrate, implement, use
74
+
75
+ 4. analyze - Draw connections among ideas
76
+ Verbs: analyze, compare, contrast, differentiate, examine, organize
77
+
78
+ 5. evaluate - Justify a decision or course of action
79
+ Verbs: evaluate, assess, critique, judge, justify, recommend
80
+
81
+ 6. create - Produce new or original work
82
+ Verbs: create, design, develop, construct, formulate, produce
83
+
84
+ Provide:
85
+ - The Bloom's level
86
+ - Confidence score (0-1)
87
+ - Key indicators (verbs/phrases) that led to this classification
88
+ - Brief reasoning`,
89
+ curriculumDecomposition: `You are an expert curriculum designer and learning scientist.
90
+
91
+ Your task is to decompose curriculum content into a structured skill graph suitable for adaptive learning systems.
92
+
93
+ Process:
94
+ 1. Identify the overall learning goals and outcomes
95
+ 2. Break down content into discrete, measurable skills
96
+ 3. Classify each skill by Bloom's level and difficulty
97
+ 4. Identify threshold concepts (transformative gateway skills)
98
+ 5. Map prerequisite relationships between skills
99
+ 6. Ensure appropriate granularity for personalized learning
100
+
101
+ Output a complete skill graph with:
102
+ - Skills: Name, description, Bloom's level, difficulty, estimated time
103
+ - Prerequisites: Source skill, target skill, type, strength, reasoning
104
+
105
+ Principles:
106
+ - Every skill should be assessable
107
+ - Skills should be at appropriate granularity (15-45 min to master)
108
+ - Clear progression from foundational to advanced
109
+ - Identify threshold concepts that unlock new understanding
110
+ - Consider both hard prerequisites (required) and soft (beneficial)`,
111
+ };
112
+ // ─────────────────────────────────────────────────────────────────────────────
113
+ // JSON Schemas for Structured Output
114
+ // ─────────────────────────────────────────────────────────────────────────────
115
+ exports.EXTRACTION_SCHEMA = {
116
+ type: 'object',
117
+ properties: {
118
+ skills: {
119
+ type: 'array',
120
+ items: {
121
+ type: 'object',
122
+ properties: {
123
+ name: { type: 'string', description: 'Concise, action-oriented skill name' },
124
+ description: { type: 'string', description: 'What mastery of this skill looks like' },
125
+ bloomLevel: {
126
+ type: 'string',
127
+ enum: ['remember', 'understand', 'apply', 'analyze', 'evaluate', 'create'],
128
+ description: "Bloom's Taxonomy level",
129
+ },
130
+ difficulty: {
131
+ type: 'number',
132
+ minimum: 0,
133
+ maximum: 1,
134
+ description: 'Difficulty on 0-1 scale',
135
+ },
136
+ confidence: {
137
+ type: 'number',
138
+ minimum: 0,
139
+ maximum: 1,
140
+ description: 'Confidence in this extraction',
141
+ },
142
+ isThresholdConcept: {
143
+ type: 'boolean',
144
+ description: 'Is this a transformative gateway skill?',
145
+ },
146
+ estimatedMinutes: {
147
+ type: 'number',
148
+ description: 'Estimated time to master in minutes',
149
+ },
150
+ keywords: {
151
+ type: 'array',
152
+ items: { type: 'string' },
153
+ description: 'Associated keywords/concepts',
154
+ },
155
+ reasoning: {
156
+ type: 'string',
157
+ description: 'Why this skill was extracted',
158
+ },
159
+ },
160
+ required: ['name', 'description', 'bloomLevel', 'difficulty', 'confidence'],
161
+ },
162
+ },
163
+ warnings: {
164
+ type: 'array',
165
+ items: { type: 'string' },
166
+ description: 'Any warnings or notes about the extraction',
167
+ },
168
+ },
169
+ required: ['skills'],
170
+ };
171
+ exports.PREREQUISITE_SCHEMA = {
172
+ type: 'object',
173
+ properties: {
174
+ prerequisites: {
175
+ type: 'array',
176
+ items: {
177
+ type: 'object',
178
+ properties: {
179
+ sourceId: { type: 'string', description: 'ID of the prerequisite skill' },
180
+ targetId: { type: 'string', description: 'ID of the dependent skill' },
181
+ strength: {
182
+ type: 'number',
183
+ minimum: 0,
184
+ maximum: 1,
185
+ description: 'How critical is this prerequisite (0-1)',
186
+ },
187
+ type: {
188
+ type: 'string',
189
+ enum: ['hard', 'soft', 'recommended'],
190
+ description: 'Type of prerequisite relationship',
191
+ },
192
+ confidence: {
193
+ type: 'number',
194
+ minimum: 0,
195
+ maximum: 1,
196
+ description: 'Confidence in this inference',
197
+ },
198
+ reasoning: {
199
+ type: 'string',
200
+ description: 'Why this prerequisite relationship exists',
201
+ },
202
+ },
203
+ required: ['sourceId', 'targetId', 'strength', 'type', 'confidence', 'reasoning'],
204
+ },
205
+ },
206
+ },
207
+ required: ['prerequisites'],
208
+ };
209
+ exports.BLOOM_ANALYSIS_SCHEMA = {
210
+ type: 'object',
211
+ properties: {
212
+ level: {
213
+ type: 'string',
214
+ enum: ['remember', 'understand', 'apply', 'analyze', 'evaluate', 'create'],
215
+ description: "Detected Bloom's level",
216
+ },
217
+ confidence: {
218
+ type: 'number',
219
+ minimum: 0,
220
+ maximum: 1,
221
+ description: 'Confidence in detection',
222
+ },
223
+ indicators: {
224
+ type: 'array',
225
+ items: { type: 'string' },
226
+ description: 'Key verbs/phrases indicating this level',
227
+ },
228
+ reasoning: {
229
+ type: 'string',
230
+ description: 'Explanation for the classification',
231
+ },
232
+ },
233
+ required: ['level', 'confidence', 'indicators', 'reasoning'],
234
+ };
235
+ exports.DECOMPOSITION_SCHEMA = {
236
+ type: 'object',
237
+ properties: {
238
+ title: { type: 'string', description: 'Course/curriculum title' },
239
+ skills: {
240
+ type: 'array',
241
+ items: {
242
+ type: 'object',
243
+ properties: {
244
+ id: { type: 'string', description: 'Unique skill identifier' },
245
+ name: { type: 'string' },
246
+ description: { type: 'string' },
247
+ bloomLevel: {
248
+ type: 'string',
249
+ enum: ['remember', 'understand', 'apply', 'analyze', 'evaluate', 'create'],
250
+ },
251
+ difficulty: { type: 'number', minimum: 0, maximum: 1 },
252
+ isThresholdConcept: { type: 'boolean' },
253
+ estimatedMinutes: { type: 'number' },
254
+ keywords: { type: 'array', items: { type: 'string' } },
255
+ },
256
+ required: ['id', 'name', 'description', 'bloomLevel', 'difficulty'],
257
+ },
258
+ },
259
+ prerequisites: {
260
+ type: 'array',
261
+ items: {
262
+ type: 'object',
263
+ properties: {
264
+ sourceId: { type: 'string' },
265
+ targetId: { type: 'string' },
266
+ strength: { type: 'number', minimum: 0, maximum: 1 },
267
+ type: { type: 'string', enum: ['hard', 'soft', 'recommended'] },
268
+ reasoning: { type: 'string' },
269
+ },
270
+ required: ['sourceId', 'targetId', 'strength', 'type'],
271
+ },
272
+ },
273
+ warnings: {
274
+ type: 'array',
275
+ items: { type: 'string' },
276
+ },
277
+ },
278
+ required: ['title', 'skills', 'prerequisites'],
279
+ };
280
+ // ─────────────────────────────────────────────────────────────────────────────
281
+ // Prompt Builders
282
+ // ─────────────────────────────────────────────────────────────────────────────
283
+ /**
284
+ * Build a skill extraction prompt
285
+ */
286
+ function buildExtractionPrompt(content, options) {
287
+ let prompt = `Analyze the following curriculum content and extract all discrete, measurable skills.\n\n`;
288
+ if (options?.domain) {
289
+ prompt += `Domain: ${options.domain}\n`;
290
+ }
291
+ if (options?.gradeLevel) {
292
+ prompt += `Target Audience: ${options.gradeLevel}\n`;
293
+ }
294
+ if (options?.context) {
295
+ prompt += `Additional Context: ${options.context}\n`;
296
+ }
297
+ prompt += `\n--- CURRICULUM CONTENT ---\n${content}\n--- END CONTENT ---\n\n`;
298
+ prompt += `Extract all skills from this content. For each skill, provide name, description, Bloom's level, difficulty (0-1), and identify if it's a threshold concept.`;
299
+ return prompt;
300
+ }
301
+ /**
302
+ * Build a prerequisite inference prompt
303
+ */
304
+ function buildPrerequisitePrompt(skills, options) {
305
+ let prompt = `Analyze the following skills and infer prerequisite relationships between them.\n\n`;
306
+ if (options?.domain) {
307
+ prompt += `Domain: ${options.domain}\n`;
308
+ }
309
+ prompt += `\n--- SKILLS ---\n`;
310
+ for (const skill of skills) {
311
+ prompt += `ID: ${skill.id}\n`;
312
+ prompt += `Name: ${skill.name}\n`;
313
+ prompt += `Description: ${skill.description}\n`;
314
+ prompt += `Bloom's Level: ${skill.bloomLevel}\n`;
315
+ prompt += `Difficulty: ${skill.difficulty}\n\n`;
316
+ }
317
+ prompt += `--- END SKILLS ---\n\n`;
318
+ prompt += `For each prerequisite relationship you identify:\n`;
319
+ prompt += `1. Specify sourceId (prerequisite) and targetId (dependent)\n`;
320
+ prompt += `2. Classify as hard, soft, or recommended\n`;
321
+ prompt += `3. Provide strength (0-1) and reasoning\n`;
322
+ if (options?.inferTransitive === false) {
323
+ prompt += `\nNote: Only infer direct prerequisites, not transitive ones.`;
324
+ }
325
+ return prompt;
326
+ }
327
+ /**
328
+ * Build a Bloom's analysis prompt
329
+ */
330
+ function buildBloomPrompt(text, context) {
331
+ let prompt = `Analyze the following text and determine its Bloom's Taxonomy level.\n\n`;
332
+ if (context) {
333
+ prompt += `Context: ${context}\n\n`;
334
+ }
335
+ prompt += `--- TEXT ---\n${text}\n--- END TEXT ---\n\n`;
336
+ prompt += `Classify this text according to Bloom's Taxonomy (remember, understand, apply, analyze, evaluate, create).`;
337
+ return prompt;
338
+ }
339
+ /**
340
+ * Build a curriculum decomposition prompt
341
+ */
342
+ function buildDecompositionPrompt(content, options) {
343
+ let prompt = `Decompose the following curriculum into a complete skill graph.\n\n`;
344
+ if (options?.title) {
345
+ prompt += `Course Title: ${options.title}\n`;
346
+ }
347
+ if (options?.domain) {
348
+ prompt += `Domain: ${options.domain}\n`;
349
+ }
350
+ if (options?.gradeLevel) {
351
+ prompt += `Target Audience: ${options.gradeLevel}\n`;
352
+ }
353
+ if (options?.context) {
354
+ prompt += `Additional Context: ${options.context}\n`;
355
+ }
356
+ if (options?.maxDepth) {
357
+ prompt += `Maximum Skill Hierarchy Depth: ${options.maxDepth}\n`;
358
+ }
359
+ prompt += `\n--- CURRICULUM CONTENT ---\n${content}\n--- END CONTENT ---\n\n`;
360
+ prompt += `Create a complete skill graph with:\n`;
361
+ prompt += `1. All discrete, measurable skills with unique IDs\n`;
362
+ prompt += `2. Bloom's level and difficulty for each skill\n`;
363
+ prompt += `3. Prerequisite relationships between skills\n`;
364
+ prompt += `4. Identify threshold concepts that unlock understanding\n`;
365
+ return prompt;
366
+ }
367
+ //# sourceMappingURL=prompts.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../../src/llm/prompts.ts"],"names":[],"mappings":";AAAA;;;;GAIG;;;AAgSH,sDAwBC;AAKD,0DAuCC;AAKD,4CAWC;AAKD,4DAoCC;AAzZD,gFAAgF;AAChF,iBAAiB;AACjB,gFAAgF;AAEnE,QAAA,cAAc,GAAG;IAC5B,eAAe,EAAE;;;;;;;;;;;;;;;;;;;;;;;;qDAwBkC;IAEnD,qBAAqB,EAAE;;;;;;;;;;;;;;;;;;;8BAmBK;IAE5B,aAAa,EAAE;;;;;;;;;;;;;;;;;;;;;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,MAAM,IAAI,gDAAgD,CAAC;IAC3D,MAAM,IAAI,4DAA4D,CAAC;IAEvE,OAAO,MAAM,CAAC;AAChB,CAAC"}
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+ /**
3
+ * LLM provider types for skill extraction and prerequisite inference
4
+ *
5
+ * @packageDocumentation
6
+ */
7
+ Object.defineProperty(exports, "__esModule", { value: true });
8
+ //# sourceMappingURL=llm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"llm.js","sourceRoot":"","sources":["../../../src/types/llm.ts"],"names":[],"mappings":";AAAA;;;;GAIG"}
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Anthropic adapter for LLM integration
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ import { BaseLLMAdapter, LLMError, DEFAULT_CONFIG } from './base.js';
7
+ /**
8
+ * Anthropic adapter for Claude models
9
+ */
10
+ export class AnthropicAdapter extends BaseLLMAdapter {
11
+ baseUrl;
12
+ constructor(config) {
13
+ super(config);
14
+ this.baseUrl = config.baseUrl ?? 'https://api.anthropic.com/v1';
15
+ }
16
+ get provider() {
17
+ return 'anthropic';
18
+ }
19
+ async complete(request) {
20
+ if (!this.isConfigured()) {
21
+ throw new LLMError('Anthropic adapter not configured. Set ANTHROPIC_API_KEY or pass apiKey in config.', 'NOT_CONFIGURED', this.provider);
22
+ }
23
+ return this.withRetry(async () => {
24
+ // Extract system message
25
+ const systemMessage = request.messages.find((m) => m.role === 'system');
26
+ const otherMessages = request.messages.filter((m) => m.role !== 'system');
27
+ const headers = {
28
+ 'Content-Type': 'application/json',
29
+ 'x-api-key': this.config.apiKey,
30
+ 'anthropic-version': '2023-06-01',
31
+ };
32
+ const body = {
33
+ model: this.config.model,
34
+ messages: otherMessages.map((m) => ({
35
+ role: m.role,
36
+ content: m.content,
37
+ })),
38
+ max_tokens: request.maxTokens ?? this.config.maxTokens ?? DEFAULT_CONFIG.maxTokens,
39
+ };
40
+ // Add system message if present
41
+ if (systemMessage) {
42
+ body.system = systemMessage.content;
43
+ }
44
+ // Temperature (Anthropic uses 0-1 scale like OpenAI)
45
+ const temp = request.temperature ?? this.config.temperature ?? DEFAULT_CONFIG.temperature;
46
+ if (temp !== undefined) {
47
+ body.temperature = temp;
48
+ }
49
+ const controller = new AbortController();
50
+ const timeout = setTimeout(() => controller.abort(), this.config.timeout ?? DEFAULT_CONFIG.timeout);
51
+ try {
52
+ const response = await fetch(`${this.baseUrl}/messages`, {
53
+ method: 'POST',
54
+ headers,
55
+ body: JSON.stringify(body),
56
+ signal: controller.signal,
57
+ });
58
+ clearTimeout(timeout);
59
+ if (!response.ok) {
60
+ const errorData = (await response.json().catch(() => ({})));
61
+ const errorMessage = errorData.error?.message ?? `HTTP ${response.status}`;
62
+ if (response.status === 429) {
63
+ throw new LLMError(`Rate limit exceeded: ${errorMessage}`, 'RATE_LIMIT', this.provider);
64
+ }
65
+ throw new LLMError(`Anthropic API error: ${errorMessage}`, 'API_ERROR', this.provider);
66
+ }
67
+ const data = (await response.json());
68
+ // Get text content
69
+ const textBlock = data.content.find((block) => block.type === 'text');
70
+ const content = textBlock?.text ?? '';
71
+ let json;
72
+ if (request.responseFormat === 'json') {
73
+ json = this.parseJSON(content);
74
+ }
75
+ return {
76
+ content,
77
+ json,
78
+ usage: {
79
+ promptTokens: data.usage.input_tokens,
80
+ completionTokens: data.usage.output_tokens,
81
+ totalTokens: data.usage.input_tokens + data.usage.output_tokens,
82
+ },
83
+ model: data.model,
84
+ finishReason: data.stop_reason === 'end_turn' ? 'stop' :
85
+ data.stop_reason === 'max_tokens' ? 'length' : 'error',
86
+ };
87
+ }
88
+ catch (error) {
89
+ clearTimeout(timeout);
90
+ if (error instanceof LLMError) {
91
+ throw error;
92
+ }
93
+ if (error instanceof Error) {
94
+ if (error.name === 'AbortError') {
95
+ throw new LLMError('Request timeout', 'TIMEOUT', this.provider, error);
96
+ }
97
+ throw new LLMError(`Network error: ${error.message}`, 'NETWORK_ERROR', this.provider, error);
98
+ }
99
+ throw new LLMError('Unknown error', 'API_ERROR', this.provider);
100
+ }
101
+ });
102
+ }
103
+ }
104
+ /**
105
+ * Create an Anthropic adapter from environment variables
106
+ */
107
+ export function createAnthropicAdapter(model = 'claude-3-5-sonnet-20241022', overrides) {
108
+ const apiKey = typeof process !== 'undefined' ? process.env.ANTHROPIC_API_KEY : undefined;
109
+ const config = {
110
+ provider: 'anthropic',
111
+ model,
112
+ ...overrides,
113
+ };
114
+ if (apiKey) {
115
+ config.apiKey = apiKey;
116
+ }
117
+ return new AnthropicAdapter(config);
118
+ }
119
+ //# sourceMappingURL=anthropic.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"anthropic.js","sourceRoot":"","sources":["../../../../src/llm/adapters/anthropic.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAQH,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAiCrE;;GAEG;AACH,MAAM,OAAO,gBAAiB,SAAQ,cAAc;IACjC,OAAO,CAAS;IAEjC,YAAY,MAAuB;QACjC,KAAK,CAAC,MAAM,CAAC,CAAC;QACd,IAAI,CAAC,OAAO,GAAG,MAAM,CAAC,OAAO,IAAI,8BAA8B,CAAC;IAClE,CAAC;IAED,IAAI,QAAQ;QACV,OAAO,WAAW,CAAC;IACrB,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,OAA0B;QACvC,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;YACzB,MAAM,IAAI,QAAQ,CAChB,mFAAmF,EACnF,gBAAgB,EAChB,IAAI,CAAC,QAAQ,CACd,CAAC;QACJ,CAAC;QAED,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,IAAI,EAAE;YAC/B,yBAAyB;YACzB,MAAM,aAAa,GAAG,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,QAAQ,CAAC,CAAC;YACxE,MAAM,aAAa,G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K,WAAW,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,iBAAiB,CAAC,CAAC,CAAC,SAAS,CAAC;IAE1F,MAAM,MAAM,GAAoB;QAC9B,QAAQ,EAAE,WAAW;QACrB,KAAK;QACL,GAAG,SAAS;KACb,CAAC;IAEF,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC;IACzB,CAAC;IAED,OAAO,IAAI,gBAAgB,CAAC,MAAM,CAAC,CAAC;AACtC,CAAC"}
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Base adapter class for LLM providers
3
+ *
4
+ * @packageDocumentation
5
+ */
6
+ /**
7
+ * LLM-related errors
8
+ */
9
+ export class LLMError extends Error {
10
+ code;
11
+ provider;
12
+ cause;
13
+ constructor(message, code, provider, cause) {
14
+ super(message);
15
+ this.code = code;
16
+ this.provider = provider;
17
+ this.cause = cause;
18
+ this.name = 'LLMError';
19
+ }
20
+ }
21
+ /**
22
+ * Default configuration values
23
+ */
24
+ export const DEFAULT_CONFIG = {
25
+ maxTokens: 4096,
26
+ temperature: 0.3,
27
+ timeout: 60000,
28
+ retries: 2,
29
+ };
30
+ /**
31
+ * Abstract base class for LLM adapters
32
+ */
33
+ export class BaseLLMAdapter {
34
+ config;
35
+ constructor(config) {
36
+ this.config = {
37
+ ...DEFAULT_CONFIG,
38
+ ...config,
39
+ };
40
+ }
41
+ get model() {
42
+ return this.config.model;
43
+ }
44
+ isConfigured() {
45
+ if (this.provider === 'ollama') {
46
+ return !!this.config.model;
47
+ }
48
+ return !!this.config.apiKey && !!this.config.model;
49
+ }
50
+ getConfig() {
51
+ const { apiKey: _, ...rest } = this.config;
52
+ return rest;
53
+ }
54
+ /**
55
+ * Retry a function with exponential backoff
56
+ */
57
+ async withRetry(fn, maxRetries = this.config.retries ?? DEFAULT_CONFIG.retries) {
58
+ let lastError;
59
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
60
+ try {
61
+ return await fn();
62
+ }
63
+ catch (error) {
64
+ lastError = error instanceof Error ? error : new Error(String(error));
65
+ // Don't retry on certain errors
66
+ if (error instanceof LLMError) {
67
+ if (error.code === 'NOT_CONFIGURED' || error.code === 'INVALID_RESPONSE') {
68
+ throw error;
69
+ }
70
+ }
71
+ if (attempt < maxRetries) {
72
+ // Exponential backoff: 1s, 2s, 4s, ...
73
+ const delay = Math.pow(2, attempt) * 1000;
74
+ await new Promise((resolve) => setTimeout(resolve, delay));
75
+ }
76
+ }
77
+ }
78
+ throw lastError;
79
+ }
80
+ /**
81
+ * Parse JSON from LLM response, handling common issues
82
+ */
83
+ parseJSON(content) {
84
+ // Try to extract JSON from markdown code blocks
85
+ const jsonMatch = content.match(/```(?:json)?\s*([\s\S]*?)```/);
86
+ const jsonStr = jsonMatch && jsonMatch[1] ? jsonMatch[1].trim() : content.trim();
87
+ try {
88
+ return JSON.parse(jsonStr);
89
+ }
90
+ catch (error) {
91
+ throw new LLMError(`Failed to parse JSON response: ${error instanceof Error ? error.message : 'Unknown error'}`, 'PARSE_ERROR', this.provider, error instanceof Error ? error : undefined);
92
+ }
93
+ }
94
+ }
95
+ //# sourceMappingURL=base.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base.js","sourceRoot":"","sources":["../../../../src/llm/adapters/base.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAUH;;GAEG;AACH,MAAM,OAAO,QAAS,SAAQ,KAAK;IAGf;IACA;IACA;IAJlB,YACE,OAAe,EACC,IAAkB,EAClB,QAAqB,EACrB,KAAa;QAE7B,KAAK,CAAC,OAAO,CAAC,CAAC;QAJC,SAAI,GAAJ,IAAI,CAAc;QAClB,aAAQ,GAAR,QAAQ,CAAa;QACrB,UAAK,GAAL,KAAK,CAAQ;QAG7B,IAAI,CAAC,IAAI,GAAG,UAAU,CAAC;IACzB,CAAC;CACF;AAWD;;GAEG;AACH,MAAM,CAAC,MAAM,cAAc,GAAG;IAC5B,SAAS,EAAE,IAAI;IACf,WAAW,EAAE,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