adaptive-memory-multi-model-router 1.2.2

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 (95) hide show
  1. package/README.md +114 -0
  2. package/demo/research-demo.js +266 -0
  3. package/dist/cache/prefixCache.d.ts +114 -0
  4. package/dist/cache/prefixCache.d.ts.map +1 -0
  5. package/dist/cache/prefixCache.js +285 -0
  6. package/dist/cache/prefixCache.js.map +1 -0
  7. package/dist/cache/responseCache.d.ts +58 -0
  8. package/dist/cache/responseCache.d.ts.map +1 -0
  9. package/dist/cache/responseCache.js +153 -0
  10. package/dist/cache/responseCache.js.map +1 -0
  11. package/dist/cli.js +59 -0
  12. package/dist/cost/costTracker.d.ts +95 -0
  13. package/dist/cost/costTracker.d.ts.map +1 -0
  14. package/dist/cost/costTracker.js +240 -0
  15. package/dist/cost/costTracker.js.map +1 -0
  16. package/dist/index.d.ts +723 -0
  17. package/dist/index.d.ts.map +1 -0
  18. package/dist/index.js +239 -0
  19. package/dist/index.js.map +1 -0
  20. package/dist/memory/episodicMemory.d.ts +82 -0
  21. package/dist/memory/episodicMemory.d.ts.map +1 -0
  22. package/dist/memory/episodicMemory.js +145 -0
  23. package/dist/memory/episodicMemory.js.map +1 -0
  24. package/dist/orchestration/haloOrchestrator.d.ts +102 -0
  25. package/dist/orchestration/haloOrchestrator.d.ts.map +1 -0
  26. package/dist/orchestration/haloOrchestrator.js +207 -0
  27. package/dist/orchestration/haloOrchestrator.js.map +1 -0
  28. package/dist/orchestration/mctsWorkflow.d.ts +85 -0
  29. package/dist/orchestration/mctsWorkflow.d.ts.map +1 -0
  30. package/dist/orchestration/mctsWorkflow.js +210 -0
  31. package/dist/orchestration/mctsWorkflow.js.map +1 -0
  32. package/dist/providers/localProvider.d.ts +102 -0
  33. package/dist/providers/localProvider.d.ts.map +1 -0
  34. package/dist/providers/localProvider.js +338 -0
  35. package/dist/providers/localProvider.js.map +1 -0
  36. package/dist/providers/registry.d.ts +55 -0
  37. package/dist/providers/registry.d.ts.map +1 -0
  38. package/dist/providers/registry.js +138 -0
  39. package/dist/providers/registry.js.map +1 -0
  40. package/dist/routing/advancedRouter.d.ts +68 -0
  41. package/dist/routing/advancedRouter.d.ts.map +1 -0
  42. package/dist/routing/advancedRouter.js +332 -0
  43. package/dist/routing/advancedRouter.js.map +1 -0
  44. package/dist/tools/tmlpdTools.d.ts +101 -0
  45. package/dist/tools/tmlpdTools.d.ts.map +1 -0
  46. package/dist/tools/tmlpdTools.js +368 -0
  47. package/dist/tools/tmlpdTools.js.map +1 -0
  48. package/dist/utils/batchProcessor.d.ts +96 -0
  49. package/dist/utils/batchProcessor.d.ts.map +1 -0
  50. package/dist/utils/batchProcessor.js +170 -0
  51. package/dist/utils/batchProcessor.js.map +1 -0
  52. package/dist/utils/compression.d.ts +61 -0
  53. package/dist/utils/compression.d.ts.map +1 -0
  54. package/dist/utils/compression.js +281 -0
  55. package/dist/utils/compression.js.map +1 -0
  56. package/dist/utils/reliability.d.ts +74 -0
  57. package/dist/utils/reliability.d.ts.map +1 -0
  58. package/dist/utils/reliability.js +177 -0
  59. package/dist/utils/reliability.js.map +1 -0
  60. package/dist/utils/speculativeDecoding.d.ts +117 -0
  61. package/dist/utils/speculativeDecoding.d.ts.map +1 -0
  62. package/dist/utils/speculativeDecoding.js +246 -0
  63. package/dist/utils/speculativeDecoding.js.map +1 -0
  64. package/dist/utils/tokenUtils.d.ts +50 -0
  65. package/dist/utils/tokenUtils.d.ts.map +1 -0
  66. package/dist/utils/tokenUtils.js +124 -0
  67. package/dist/utils/tokenUtils.js.map +1 -0
  68. package/examples/QUICKSTART.md +183 -0
  69. package/notebooks/quickstart.ipynb +157 -0
  70. package/package.json +83 -0
  71. package/python/examples.py +53 -0
  72. package/python/integrations.py +330 -0
  73. package/python/setup.py +28 -0
  74. package/python/tmlpd.py +369 -0
  75. package/qna/REDDIT_GAP_ANALYSIS.md +299 -0
  76. package/qna/TMLPD_QNA.md +751 -0
  77. package/rust/tmlpd.h +268 -0
  78. package/skill/SKILL.md +238 -0
  79. package/src/cache/prefixCache.ts +365 -0
  80. package/src/cache/responseCache.ts +147 -0
  81. package/src/cost/costTracker.ts +302 -0
  82. package/src/index.ts +224 -0
  83. package/src/memory/episodicMemory.ts +185 -0
  84. package/src/orchestration/haloOrchestrator.ts +266 -0
  85. package/src/orchestration/mctsWorkflow.ts +262 -0
  86. package/src/providers/localProvider.ts +406 -0
  87. package/src/providers/registry.ts +164 -0
  88. package/src/routing/advancedRouter.ts +406 -0
  89. package/src/tools/tmlpdTools.ts +433 -0
  90. package/src/utils/batchProcessor.ts +232 -0
  91. package/src/utils/compression.ts +325 -0
  92. package/src/utils/reliability.ts +221 -0
  93. package/src/utils/speculativeDecoding.ts +344 -0
  94. package/src/utils/tokenUtils.ts +145 -0
  95. package/tsconfig.json +18 -0
@@ -0,0 +1,365 @@
1
+ /**
2
+ * TMLPD Prefix Cache - RadixAttention Style
3
+ *
4
+ * Inspired by SGLang's RadixAttention (arXiv:2312.07104)
5
+ * Caches KV states for common prefixes (system prompts, etc.)
6
+ * 5-10x speedup for repeated prompt patterns
7
+ */
8
+
9
+ export interface CacheEntry {
10
+ key: string; // Hash of the prefix
11
+ prefix: string; // Original prefix text
12
+ kv_state?: Buffer; // Cached KV state (if using actual KV cache)
13
+ response_hash?: string; // Hash of cached response
14
+ hit_count: number; // Times this prefix was used
15
+ last_used: number; // Timestamp
16
+ token_count: number; // Tokens in this prefix
17
+ children: Map<string, string>; // child_key -> child_cache_key
18
+ }
19
+
20
+ export interface PrefixCacheStats {
21
+ total_entries: number;
22
+ total_hits: number;
23
+ total_misses: number;
24
+ hit_rate: number;
25
+ memory_estimate_mb: number;
26
+ oldest_entry_age_ms: number;
27
+ }
28
+
29
+ export class PrefixCache {
30
+ private entries: Map<string, CacheEntry> = new Map();
31
+ private access_order: string[] = []; // LRU tracking
32
+ private max_entries: number;
33
+ private max_memory_mb: number;
34
+
35
+ constructor(options?: {
36
+ max_entries?: number;
37
+ max_memory_mb?: number;
38
+ }) {
39
+ this.max_entries = options?.max_entries || 10000;
40
+ this.max_memory_mb = options?.max_memory_mb || 512;
41
+ }
42
+
43
+ /**
44
+ * Generate cache key from text prefix
45
+ */
46
+ private generateKey(text: string, model?: string): string {
47
+ // Simple hash for now - in production use SHA-256
48
+ const normalized = text.toLowerCase().trim().substring(0, 500);
49
+ const str = `${model || "default"}:${normalized}`;
50
+
51
+ let hash = 0;
52
+ for (let i = 0; i < str.length; i++) {
53
+ const char = str.charCodeAt(i);
54
+ hash = ((hash << 5) - hash) + char;
55
+ hash = hash & hash; // Convert to 32bit integer
56
+ }
57
+
58
+ return `pc_${Math.abs(hash).toString(16)}`;
59
+ }
60
+
61
+ /**
62
+ * Check if prefix is cached
63
+ */
64
+ has(prefix: string, model?: string): boolean {
65
+ const key = this.generateKey(prefix, model);
66
+ return this.entries.has(key);
67
+ }
68
+
69
+ /**
70
+ * Get cached entry
71
+ */
72
+ get(prefix: string, model?: string): CacheEntry | undefined {
73
+ const key = this.generateKey(prefix, model);
74
+ const entry = this.entries.get(key);
75
+
76
+ if (entry) {
77
+ // Update LRU
78
+ this.updateLRU(key);
79
+ entry.hit_count++;
80
+ entry.last_used = Date.now();
81
+ }
82
+
83
+ return entry;
84
+ }
85
+
86
+ /**
87
+ * Store a new prefix with its KV state
88
+ */
89
+ store(
90
+ prefix: string,
91
+ options?: {
92
+ kv_state?: Buffer;
93
+ response_hash?: string;
94
+ model?: string;
95
+ children?: Map<string, string>;
96
+ }
97
+ ): string {
98
+ const key = this.generateKey(prefix, options?.model);
99
+
100
+ // Check if already exists
101
+ if (this.entries.has(key)) {
102
+ const existing = this.entries.get(key)!;
103
+ existing.hit_count++;
104
+ existing.last_used = Date.now();
105
+ return key;
106
+ }
107
+
108
+ // Estimate memory
109
+ const token_count = Math.ceil(prefix.split(/\s+/).length * 1.3);
110
+ const memory_bytes = token_count * 16 * 128 * 2; // Rough KV estimate
111
+ const memory_mb = memory_bytes / (1024 * 1024);
112
+
113
+ const entry: CacheEntry = {
114
+ key,
115
+ prefix: prefix.substring(0, 1000), // Store truncated
116
+ kv_state: options?.kv_state,
117
+ response_hash: options?.response_hash,
118
+ hit_count: 1,
119
+ last_used: Date.now(),
120
+ token_count,
121
+ children: options?.children || new Map()
122
+ };
123
+
124
+ // Evict if necessary
125
+ while (this.entries.size >= this.max_entries || this.getMemoryUsage() + memory_mb > this.max_memory_mb) {
126
+ this.evictLRU();
127
+ }
128
+
129
+ this.entries.set(key, entry);
130
+ this.access_order.push(key);
131
+
132
+ return key;
133
+ }
134
+
135
+ /**
136
+ * Extend cached prefix with completion
137
+ */
138
+ extend(
139
+ prefix: string,
140
+ completion: string,
141
+ options?: { model?: string }
142
+ ): string {
143
+ const prefix_key = this.generateKey(prefix, options?.model);
144
+ const parent = this.entries.get(prefix_key);
145
+
146
+ if (!parent) {
147
+ // No parent - just store completion as new entry
148
+ return this.store(completion, { model: options?.model });
149
+ }
150
+
151
+ // Create child entry for the extended sequence
152
+ const extended = prefix + completion;
153
+ const child_key = this.store(extended, { model: options?.model });
154
+
155
+ // Link child to parent
156
+ const completion_key = this.generateKey(completion);
157
+ parent.children.set(completion_key, child_key);
158
+
159
+ return child_key;
160
+ }
161
+
162
+ /**
163
+ * Find common prefix between two texts
164
+ */
165
+ findCommonPrefix(text1: string, text2: string): string {
166
+ const words1 = text1.split(/\s+/);
167
+ const words2 = text2.split(/\s+/);
168
+
169
+ let common_length = 0;
170
+ for (let i = 0; i < Math.min(words1.length, words2.length); i++) {
171
+ if (words1[i].toLowerCase() === words2[i].toLowerCase()) {
172
+ common_length = i + 1;
173
+ } else {
174
+ break;
175
+ }
176
+ }
177
+
178
+ return words1.slice(0, common_length).join(" ");
179
+ }
180
+
181
+ /**
182
+ * Lookup with prefix matching
183
+ * Returns cached entry if any prefix is found
184
+ */
185
+ lookup(text: string, model?: string): { cached: boolean; prefix?: string; remaining?: string } {
186
+ // Try exact match first
187
+ const exact_key = this.generateKey(text, model);
188
+ if (this.entries.has(exact_key)) {
189
+ return { cached: true };
190
+ }
191
+
192
+ // Try progressively shorter prefixes
193
+ const words = text.split(/\s+/);
194
+ for (let len = words.length - 1; len >= 5; len--) { // Min 5 words
195
+ const prefix = words.slice(0, len).join(" ");
196
+ const key = this.generateKey(prefix, model);
197
+
198
+ if (this.entries.has(key)) {
199
+ const remaining = words.slice(len).join(" ");
200
+ return { cached: true, prefix, remaining };
201
+ }
202
+ }
203
+
204
+ return { cached: false };
205
+ }
206
+
207
+ /**
208
+ * Batch lookup for multiple texts
209
+ */
210
+ lookupBatch(texts: string[], model?: string): Array<{ cached: boolean; prefix?: string; remaining?: string }> {
211
+ return texts.map(t => this.lookup(t, model));
212
+ }
213
+
214
+ /**
215
+ * Get cache statistics
216
+ */
217
+ getStats(): PrefixCacheStats {
218
+ const now = Date.now();
219
+ let oldest_age = 0;
220
+ let total_hits = 0;
221
+
222
+ for (const entry of this.entries.values()) {
223
+ total_hits += entry.hit_count;
224
+ const age = now - entry.last_used;
225
+ if (age > oldest_age) oldest_age = age;
226
+ }
227
+
228
+ const total_requests = total_hits + this.entries.size; // Approximate
229
+ const hit_rate = total_requests > 0 ? total_hits / total_requests : 0;
230
+
231
+ return {
232
+ total_entries: this.entries.size,
233
+ total_hits: total_hits,
234
+ total_misses: this.entries.size, // Approximate
235
+ hit_rate,
236
+ memory_estimate_mb: this.getMemoryUsage(),
237
+ oldest_entry_age_ms: oldest_age
238
+ };
239
+ }
240
+
241
+ /**
242
+ * Get estimated memory usage
243
+ */
244
+ private getMemoryUsage(): number {
245
+ let total_bytes = 0;
246
+
247
+ for (const entry of this.entries.values()) {
248
+ // Base entry overhead
249
+ total_bytes += 200;
250
+
251
+ // Prefix text
252
+ total_bytes += entry.prefix.length * 2;
253
+
254
+ // KV state (if stored)
255
+ if (entry.kv_state) {
256
+ total_bytes += entry.kv_state.length;
257
+ }
258
+
259
+ // Children map
260
+ total_bytes += entry.children.size * 50;
261
+ }
262
+
263
+ return total_bytes / (1024 * 1024);
264
+ }
265
+
266
+ /**
267
+ * Update LRU order
268
+ */
269
+ private updateLRU(key: string): void {
270
+ const index = this.access_order.indexOf(key);
271
+ if (index > -1) {
272
+ this.access_order.splice(index, 1);
273
+ }
274
+ this.access_order.push(key);
275
+ }
276
+
277
+ /**
278
+ * Evict least recently used entry
279
+ */
280
+ private evictLRU(): boolean {
281
+ if (this.access_order.length === 0) return false;
282
+
283
+ const lru_key = this.access_order.shift()!;
284
+ const entry = this.entries.get(lru_key);
285
+
286
+ if (entry) {
287
+ // If has children, re-parent them
288
+ for (const [child_key, child_cache_key] of entry.children) {
289
+ const child = this.entries.get(child_cache_key);
290
+ if (child) {
291
+ // Promote child to standalone
292
+ this.access_order.push(child_cache_key);
293
+ }
294
+ }
295
+
296
+ this.entries.delete(lru_key);
297
+ return true;
298
+ }
299
+
300
+ return false;
301
+ }
302
+
303
+ /**
304
+ * Clear all cache
305
+ */
306
+ clear(): void {
307
+ this.entries.clear();
308
+ this.access_order = [];
309
+ }
310
+
311
+ /**
312
+ * Invalidate entries matching pattern
313
+ */
314
+ invalidate(pattern?: string): number {
315
+ let count = 0;
316
+
317
+ if (!pattern) {
318
+ // Clear all
319
+ count = this.entries.size;
320
+ this.clear();
321
+ return count;
322
+ }
323
+
324
+ // Pattern-based invalidation
325
+ for (const [key, entry] of this.entries) {
326
+ if (entry.prefix.includes(pattern)) {
327
+ this.entries.delete(key);
328
+ count++;
329
+ }
330
+ }
331
+
332
+ return count;
333
+ }
334
+
335
+ /**
336
+ * Warm up cache with common system prompts
337
+ */
338
+ warmup(common_prefixes: string[], model?: string): void {
339
+ for (const prefix of common_prefixes) {
340
+ this.store(prefix, { model });
341
+ }
342
+ console.log(`[PrefixCache] Warmed up with ${common_prefixes.length} common prefixes`);
343
+ }
344
+ }
345
+
346
+ // Common system prompts that benefit from prefix caching
347
+ const COMMON_SYSTEM_PROMPTS = [
348
+ "You are a helpful assistant.",
349
+ "You are a coding assistant. Help with programming tasks.",
350
+ "You are an expert data scientist.",
351
+ "You are a senior software engineer.",
352
+ "Analyze the following code and provide feedback.",
353
+ "Explain this concept in simple terms.",
354
+ "Write clean, well-documented code.",
355
+ "Think step by step and explain your reasoning."
356
+ ];
357
+
358
+ export default PrefixCache;
359
+
360
+ // Utility function for creating pre-warmed cache
361
+ export function createWarmedCache(): PrefixCache {
362
+ const cache = new PrefixCache({ max_entries: 5000 });
363
+ cache.warmup(COMMON_SYSTEM_PROMPTS);
364
+ return cache;
365
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * TMLPD Response Cache
3
+ *
4
+ * Caches LLM responses to avoid redundant API calls.
5
+ * Uses content hash for cache key and supports TTL.
6
+ */
7
+
8
+ import * as crypto from "crypto";
9
+
10
+ export interface CacheEntry {
11
+ content: string;
12
+ model: string;
13
+ provider: string;
14
+ tokens: number;
15
+ cost: number;
16
+ cached_at: number;
17
+ expires_at: number;
18
+ }
19
+
20
+ export interface CacheConfig {
21
+ enabled: boolean;
22
+ ttl_seconds: number;
23
+ max_entries: number;
24
+ cache_dir?: string;
25
+ }
26
+
27
+ export class ResponseCache {
28
+ private cache: Map<string, CacheEntry> = new Map();
29
+ private config: CacheConfig;
30
+ private hits = 0;
31
+ private misses = 0;
32
+
33
+ constructor(config: Partial<CacheConfig> = {}) {
34
+ this.config = {
35
+ enabled: config.enabled ?? true,
36
+ ttl_seconds: config.ttl_seconds ?? 3600, // 1 hour default
37
+ max_entries: config.max_entries ?? 1000,
38
+ cache_dir: config.cache_dir,
39
+ };
40
+ }
41
+
42
+ /**
43
+ * Generate cache key from prompt + model
44
+ */
45
+ generateKey(prompt: string, model: string): string {
46
+ const hash = crypto.createHash("sha256");
47
+ hash.update(prompt + "|" + model);
48
+ return hash.digest("hex").substring(0, 32);
49
+ }
50
+
51
+ /**
52
+ * Get cached response if available and not expired
53
+ */
54
+ get(prompt: string, model: string): CacheEntry | null {
55
+ if (!this.config.enabled) return null;
56
+
57
+ const key = this.generateKey(prompt, model);
58
+ const entry = this.cache.get(key);
59
+
60
+ if (!entry) {
61
+ this.misses++;
62
+ return null;
63
+ }
64
+
65
+ // Check expiration
66
+ if (Date.now() > entry.expires_at) {
67
+ this.cache.delete(key);
68
+ this.misses++;
69
+ return null;
70
+ }
71
+
72
+ this.hits++;
73
+ return entry;
74
+ }
75
+
76
+ /**
77
+ * Store response in cache
78
+ */
79
+ set(prompt: string, model: string, response: Partial<CacheEntry>): void {
80
+ if (!this.config.enabled) return;
81
+
82
+ const key = this.generateKey(prompt, model);
83
+ const now = Date.now();
84
+
85
+ // Evict oldest if at capacity
86
+ if (this.cache.size >= this.config.max_entries) {
87
+ this.evictOldest();
88
+ }
89
+
90
+ this.cache.set(key, {
91
+ content: response.content ?? "",
92
+ model: response.model ?? model,
93
+ provider: response.provider ?? "unknown",
94
+ tokens: response.tokens ?? 0,
95
+ cost: response.cost ?? 0,
96
+ cached_at: now,
97
+ expires_at: now + this.config.ttl_seconds * 1000,
98
+ });
99
+ }
100
+
101
+ /**
102
+ * Invalidate cache for specific model or all
103
+ */
104
+ invalidate(model?: string): void {
105
+ if (model) {
106
+ for (const [key, entry] of this.cache.entries()) {
107
+ if (entry.model.includes(model)) {
108
+ this.cache.delete(key);
109
+ }
110
+ }
111
+ } else {
112
+ this.cache.clear();
113
+ }
114
+ }
115
+
116
+ /**
117
+ * Get cache statistics
118
+ */
119
+ getStats(): { hits: number; misses: number; size: number; hit_rate: number } {
120
+ const total = this.hits + this.misses;
121
+ return {
122
+ hits: this.hits,
123
+ misses: this.misses,
124
+ size: this.cache.size,
125
+ hit_rate: total > 0 ? this.hits / total : 0,
126
+ };
127
+ }
128
+
129
+ /**
130
+ * Evict oldest entry by cached_at timestamp
131
+ */
132
+ private evictOldest(): void {
133
+ let oldestKey: string | null = null;
134
+ let oldestTime = Infinity;
135
+
136
+ for (const [key, entry] of this.cache.entries()) {
137
+ if (entry.cached_at < oldestTime) {
138
+ oldestTime = entry.cached_at;
139
+ oldestKey = key;
140
+ }
141
+ }
142
+
143
+ if (oldestKey) {
144
+ this.cache.delete(oldestKey);
145
+ }
146
+ }
147
+ }