adaptive-memory-multi-model-router 2.2.5 → 2.2.6

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 (63) hide show
  1. package/README.md +17 -22
  2. package/README.md.bak +836 -0
  3. package/dist/analytics/costAnalytics.d.ts +1 -0
  4. package/dist/cache/cacheKeyGenerator.d.ts +67 -0
  5. package/dist/cache/cacheKeyGenerator.d.ts.map +1 -0
  6. package/dist/cache/cacheKeyGenerator.js +211 -0
  7. package/dist/cache/cacheKeyGenerator.js.map +1 -0
  8. package/dist/cache/semanticCache.d.ts +41 -0
  9. package/dist/cache/semanticCache.d.ts.map +1 -1
  10. package/dist/cache/semanticCache.js +142 -0
  11. package/dist/cache/semanticCache.js.map +1 -1
  12. package/dist/cli.js +35 -478
  13. package/dist/cost/costTracker.js +0 -3
  14. package/dist/cost/preCallCostEstimator.d.ts +114 -0
  15. package/dist/cost/preCallCostEstimator.d.ts.map +1 -0
  16. package/dist/cost/preCallCostEstimator.js +256 -0
  17. package/dist/cost/preCallCostEstimator.js.map +1 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.d.ts.map +1 -1
  20. package/dist/index.js +264 -64
  21. package/dist/index.js.map +1 -1
  22. package/dist/inference/speculativeDecoding.d.ts +133 -0
  23. package/dist/inference/speculativeDecoding.d.ts.map +1 -0
  24. package/dist/inference/speculativeDecoding.js +276 -0
  25. package/dist/inference/speculativeDecoding.js.map +1 -0
  26. package/dist/integrations/langchainAdapter.d.ts +1 -0
  27. package/dist/integrations/oauth.d.ts +1 -0
  28. package/dist/memory/autoFetch.d.ts +1 -0
  29. package/dist/memory/memoryTree.d.ts +1 -0
  30. package/dist/memory/obsidianVault.d.ts +1 -0
  31. package/dist/providers/providerConfig.d.ts +1 -0
  32. package/dist/providers/providerConfig.js +2 -0
  33. package/dist/providers/providerHealth.d.ts +117 -0
  34. package/dist/providers/providerHealth.d.ts.map +1 -0
  35. package/dist/providers/providerHealth.js +309 -0
  36. package/dist/providers/providerHealth.js.map +1 -0
  37. package/dist/providers/registry.js +126 -128
  38. package/dist/routing/advancedRouter.js +310 -427
  39. package/dist/routing/difficultyClassifier.d.ts +79 -0
  40. package/dist/routing/difficultyClassifier.d.ts.map +1 -0
  41. package/dist/routing/difficultyClassifier.js +329 -0
  42. package/dist/routing/difficultyClassifier.js.map +1 -0
  43. package/dist/sdk.d.ts +125 -0
  44. package/dist/sdk.d.ts.map +1 -0
  45. package/dist/sdk.js +109 -100
  46. package/dist/sdk.js.map +1 -0
  47. package/dist/security/guardrails.d.ts +1 -0
  48. package/dist/server/dashboard.d.ts +1 -0
  49. package/dist/server/modelMapper.d.ts +1 -0
  50. package/dist/server/proxyServer.d.ts +1 -0
  51. package/package.json +4 -2
  52. package/src/cache/cacheKeyGenerator.ts +242 -0
  53. package/src/cache/semanticCache.ts +148 -0
  54. package/src/cost/preCallCostEstimator.ts +345 -0
  55. package/src/inference/speculativeDecoding.ts +373 -0
  56. package/src/providers/providerHealth.ts +397 -0
  57. package/src/routing/difficultyClassifier.ts +420 -0
  58. package/test/provider-test.js +2 -2
  59. package/test.js +7 -7
  60. package/test.js.bak +376 -0
  61. package/tsconfig.json +15 -5
  62. package/src/index.ts +0 -99
  63. package/src/skills/__tests__/skill_manager.test.ts +0 -328
@@ -0,0 +1,373 @@
1
+ /**
2
+ * A3M Router - Speculative Decoding Interface
3
+ *
4
+ * Interface for integrating speculative decoding.
5
+ * Currently a stub/interface for future Medusa/Lookahead integration.
6
+ *
7
+ * Speculative decoding uses a smaller "draft" model to predict
8
+ * multiple tokens ahead, which are then verified in parallel by
9
+ * the main model. This can provide 2-3x speedup in generation.
10
+ *
11
+ * Usage:
12
+ * const specDec = new SpeculativeDecoding();
13
+ * if (specDec.shouldUse(true)) {
14
+ * const draftModel = specDec.getDraftModel('medusa');
15
+ * // ... use draft model to generate and verify
16
+ * }
17
+ */
18
+
19
+ import { ProviderTier } from '../providers/providerConfig';
20
+
21
+ // ============================================================
22
+ // Types
23
+ // ============================================================
24
+
25
+ export type DraftModelType = 'medusa' | 'lookahead' | 'eagle' | 'spark';
26
+
27
+ export interface SpeculativeConfig {
28
+ /** Enable speculative decoding */
29
+ enabled: boolean;
30
+ /** Draft model type */
31
+ draftModelType?: DraftModelType;
32
+ /** Number of speculative tokens to generate */
33
+ speculationWindow?: number;
34
+ /** Temperature for draft model */
35
+ temperature?: number;
36
+ /** Provider to use for draft model */
37
+ provider?: string;
38
+ /** Model to use for draft model */
39
+ model?: string;
40
+ }
41
+
42
+ export interface DraftModel {
43
+ /** Model identifier */
44
+ id: string;
45
+ /** Model type */
46
+ type: DraftModelType;
47
+ /** Provider for this model */
48
+ provider: string;
49
+ /** Model size description */
50
+ size: string;
51
+ /** Supported speculation windows */
52
+ supportedWindows: number[];
53
+ }
54
+
55
+ export interface SpeculativeResult {
56
+ /** Whether speculative decoding was used */
57
+ used: boolean;
58
+ /** Number of tokens in draft */
59
+ draftTokens: number;
60
+ /** Number of tokens accepted */
61
+ acceptedTokens: number;
62
+ /** Acceptance rate */
63
+ acceptanceRate: number;
64
+ /** Time saved (ms, estimated) */
65
+ estimatedTimeSaved: number;
66
+ }
67
+
68
+ export interface VerificationResult {
69
+ /** All tokens verified successfully */
70
+ allAccepted: boolean;
71
+ /** Indices of accepted tokens */
72
+ acceptedIndices: number[];
73
+ /** Indices of rejected tokens */
74
+ rejectedIndices: number[];
75
+ /** Actual tokens to use (may differ from draft) */
76
+ actualTokens: string[];
77
+ /** Number of tokens to rewind */
78
+ rewindCount: number;
79
+ }
80
+
81
+ // ============================================================
82
+ // Speculative Decoding Interface
83
+ // ============================================================
84
+
85
+ export class SpeculativeDecoding {
86
+ private config: SpeculativeConfig;
87
+ private draftModels: Map<string, DraftModel> = new Map();
88
+
89
+ constructor(config?: Partial<SpeculativeConfig>) {
90
+ this.config = {
91
+ enabled: config?.enabled ?? false,
92
+ draftModelType: config?.draftModelType ?? 'medusa',
93
+ speculationWindow: config?.speculationWindow ?? 4,
94
+ temperature: config?.temperature ?? 0.0,
95
+ provider: config?.provider,
96
+ model: config?.model,
97
+ };
98
+
99
+ // Register available draft models
100
+ this.registerDraftModels();
101
+ }
102
+
103
+ /**
104
+ * Determine if speculative decoding should be used.
105
+ * Checks config, provider support, and model availability.
106
+ */
107
+ shouldUse(forceEnable?: boolean): boolean {
108
+ if (forceEnable) return true;
109
+ if (!this.config.enabled) return false;
110
+
111
+ // Speculative decoding beneficial for longer outputs
112
+ // Check if provider supports it
113
+ return this.config.enabled;
114
+ }
115
+
116
+ /**
117
+ * Get the draft model configuration.
118
+ */
119
+ getDraftModel(type?: DraftModelType): DraftModel | null {
120
+ const modelType = type || this.config.draftModelType || 'medusa';
121
+
122
+ const model = this.draftModels.get(modelType);
123
+ if (!model) {
124
+ // Return a generic configuration
125
+ return {
126
+ id: `draft-${modelType}`,
127
+ type: modelType,
128
+ provider: this.config.provider || 'auto',
129
+ size: 'small',
130
+ supportedWindows: [2, 4, 6, 8],
131
+ };
132
+ }
133
+
134
+ return model;
135
+ }
136
+
137
+ /**
138
+ * Generate draft tokens using the draft model.
139
+ * This is an async method to support API-based draft models.
140
+ */
141
+ async generateDraft(
142
+ prompt: string,
143
+ maxTokens: number
144
+ ): Promise<{ tokens: string[]; scores: number[] }> {
145
+ const draftModel = this.getDraftModel();
146
+ if (!draftModel) {
147
+ throw new Error('No draft model available');
148
+ }
149
+
150
+ // Stub: In production, this would call the draft model API
151
+ // For now, return empty draft
152
+ return {
153
+ tokens: [],
154
+ scores: [],
155
+ };
156
+ }
157
+
158
+ /**
159
+ * Verify draft tokens against the main model.
160
+ * Returns which tokens were accepted and corrections if needed.
161
+ */
162
+ async verifyDraft(
163
+ prompt: string,
164
+ draftTokens: string[]
165
+ ): Promise<VerificationResult> {
166
+ if (draftTokens.length === 0) {
167
+ return {
168
+ allAccepted: true,
169
+ acceptedIndices: [],
170
+ rejectedIndices: [],
171
+ actualTokens: [],
172
+ rewindCount: 0,
173
+ };
174
+ }
175
+
176
+ // Stub: In production, this would verify each draft token
177
+ // For now, accept all tokens (optimistic)
178
+ return {
179
+ allAccepted: true,
180
+ acceptedIndices: draftTokens.map((_, i) => i),
181
+ rejectedIndices: [],
182
+ actualTokens: draftTokens,
183
+ rewindCount: 0,
184
+ };
185
+ }
186
+
187
+ /**
188
+ * Calculate speedup from speculative decoding results.
189
+ */
190
+ calculateSpeedup(result: SpeculativeResult): number {
191
+ if (!result.used || result.draftTokens === 0) return 1.0;
192
+
193
+ // Approximate speedup based on acceptance rate
194
+ // Higher acceptance = more speedup
195
+ const acceptanceRate = result.acceptanceRate;
196
+
197
+ // Theoretical 2-3x speedup at 90%+ acceptance
198
+ if (acceptanceRate >= 0.9) return 2.5;
199
+ if (acceptanceRate >= 0.8) return 2.0;
200
+ if (acceptanceRate >= 0.7) return 1.7;
201
+ if (acceptanceRate >= 0.5) return 1.4;
202
+ if (acceptanceRate >= 0.3) return 1.2;
203
+ return 1.1;
204
+ }
205
+
206
+ /**
207
+ * Update configuration.
208
+ */
209
+ updateConfig(updates: Partial<SpeculativeConfig>): void {
210
+ this.config = { ...this.config, ...updates };
211
+ }
212
+
213
+ /**
214
+ * Get current configuration.
215
+ */
216
+ getConfig(): SpeculativeConfig {
217
+ return { ...this.config };
218
+ }
219
+
220
+ /**
221
+ * Check if a provider supports speculative decoding.
222
+ */
223
+ supportsSpeculativeDecoding(provider: string): boolean {
224
+ // Local providers (Ollama, vLLM) typically support it
225
+ const localProviders = ['ollama', 'lmstudio', 'vllm'];
226
+ if (localProviders.includes(provider)) return true;
227
+
228
+ // Check if provider has known speculative support
229
+ const supportedProviders = ['together', 'fireworks', 'anyscale'];
230
+ return supportedProviders.includes(provider);
231
+ }
232
+
233
+ /**
234
+ * Get recommended speculation window based on model size.
235
+ */
236
+ getRecommendedWindow(modelSize: 'small' | 'medium' | 'large'): number {
237
+ switch (modelSize) {
238
+ case 'small': return 6;
239
+ case 'medium': return 4;
240
+ case 'large': return 2;
241
+ default: return 4;
242
+ }
243
+ }
244
+
245
+ // ---- Private helpers ----
246
+
247
+ private registerDraftModels(): void {
248
+ // Medusa-style models (multiple draft heads)
249
+ this.draftModels.set('medusa', {
250
+ id: 'medusa-7b',
251
+ type: 'medusa',
252
+ provider: 'auto',
253
+ size: '7B equivalent',
254
+ supportedWindows: [2, 4, 6, 8, 10],
255
+ });
256
+
257
+ // Lookahead decoding
258
+ this.draftModels.set('lookahead', {
259
+ id: 'lookahead-7b',
260
+ type: 'lookahead',
261
+ provider: 'auto',
262
+ size: '7B equivalent',
263
+ supportedWindows: [2, 4, 6],
264
+ });
265
+
266
+ // EAGLE decoding
267
+ this.draftModels.set('eagle', {
268
+ id: 'eagle-7b',
269
+ type: 'eagle',
270
+ provider: 'auto',
271
+ size: '7B equivalent',
272
+ supportedWindows: [2, 4, 6, 8],
273
+ });
274
+
275
+ // Spark (speculative decoding for transformers)
276
+ this.draftModels.set('spark', {
277
+ id: 'spark-7b',
278
+ type: 'spark',
279
+ provider: 'auto',
280
+ size: '7B equivalent',
281
+ supportedWindows: [2, 4, 6, 8, 10, 12],
282
+ });
283
+ }
284
+ }
285
+
286
+ // ============================================================
287
+ // Speculative Decoding Wrapper for LLM calls
288
+ // ============================================================
289
+
290
+ export class SpeculativeDecodingWrapper {
291
+ private specDec: SpeculativeDecoding;
292
+ private mainModelCall: (prompt: string, options?: any) => Promise<string>;
293
+
294
+ constructor(
295
+ mainModelCall: (prompt: string, options?: any) => Promise<string>,
296
+ config?: Partial<SpeculativeConfig>
297
+ ) {
298
+ this.mainModelCall = mainModelCall;
299
+ this.specDec = new SpeculativeDecoding(config);
300
+ }
301
+
302
+ /**
303
+ * Generate with speculative decoding.
304
+ */
305
+ async generate(
306
+ prompt: string,
307
+ maxTokens: number,
308
+ options?: { temperature?: number; useSpecDec?: boolean }
309
+ ): Promise<{ text: string; result: SpeculativeResult }> {
310
+ if (!this.specDec.shouldUse(options?.useSpecDec)) {
311
+ // Fallback to normal generation
312
+ const text = await this.mainModelCall(prompt, options);
313
+ return {
314
+ text,
315
+ result: {
316
+ used: false,
317
+ draftTokens: 0,
318
+ acceptedTokens: 0,
319
+ acceptanceRate: 0,
320
+ estimatedTimeSaved: 0,
321
+ },
322
+ };
323
+ }
324
+
325
+ // Speculative generation
326
+ const startTime = Date.now();
327
+ const draftTokens = await this.specDec.generateDraft(prompt, maxTokens);
328
+ const verification = await this.specDec.verifyDraft(prompt, draftTokens.tokens);
329
+
330
+ let text: string;
331
+
332
+ if (verification.allAccepted) {
333
+ // All draft tokens accepted, continue with main model
334
+ text = verification.actualTokens.join('') +
335
+ await this.mainModelCall(prompt, options);
336
+ } else {
337
+ // Some tokens rejected, need to rewind
338
+ text = verification.actualTokens.join('');
339
+ // Re-prompt with corrected context
340
+ text += await this.mainModelCall(prompt + text, options);
341
+ }
342
+
343
+ const endTime = Date.now();
344
+ const speedup = this.specDec.calculateSpeedup({
345
+ used: true,
346
+ draftTokens: draftTokens.tokens.length,
347
+ acceptedTokens: verification.acceptedIndices.length,
348
+ acceptanceRate: verification.acceptedIndices.length / draftTokens.tokens.length,
349
+ estimatedTimeSaved: endTime - startTime,
350
+ });
351
+
352
+ return {
353
+ text,
354
+ result: {
355
+ used: true,
356
+ draftTokens: draftTokens.tokens.length,
357
+ acceptedTokens: verification.acceptedIndices.length,
358
+ acceptanceRate: verification.acceptedIndices.length / draftTokens.tokens.length,
359
+ estimatedTimeSaved: Math.round((1 - 1 / speedup) * (endTime - startTime)),
360
+ },
361
+ };
362
+ }
363
+ }
364
+
365
+ // ============================================================
366
+ // Factory
367
+ // ============================================================
368
+
369
+ export function createSpeculativeDecoding(
370
+ config?: Partial<SpeculativeConfig>
371
+ ): SpeculativeDecoding {
372
+ return new SpeculativeDecoding(config);
373
+ }