adaptive-memory-multi-model-router 2.15.2 → 2.15.4

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.
@@ -0,0 +1,427 @@
1
+ /**
2
+ * ShadowSampler — Value-Proportional Shadow Verification
3
+ *
4
+ * Implements Optimal Defense Theory (Rhoades 1979; McKey 1974; Zangerl & Bazzaz 1992)
5
+ * from plant ecological economics:
6
+ *
7
+ * "A plant allocates defensive compounds (defense cost) in proportion to
8
+ * tissue value, attack probability, and the marginal cost of defense."
9
+ *
10
+ * Mapped to A3M routing:
11
+ * - Tissue value → query stakes / expected cost of wrong answer
12
+ * - Attack probability → probability that the primary provider fails/misbehaves
13
+ * - Defense cost → cost of the shadow verification call
14
+ * - Marginal return → expected reduction in error rate from verification
15
+ *
16
+ * Instead of binary always-on (wasteful) or always-off (risky), ODT says:
17
+ * Sample shadow verification PROPORTIONALLY to expected value of verification.
18
+ *
19
+ * The sampling probability is:
20
+ * P(shadow) = f(expected_error_cost_reduction, query_risk)
21
+ *
22
+ * This is NOT the Zahavi "shared expert" (which always runs on 100% of queries).
23
+ * ODT shadow runs probabilistically — only on queries where the expected
24
+ * verification benefit exceeds the verification cost.
25
+ *
26
+ * Usage:
27
+ * const sampler = new ShadowSampler();
28
+ * const decision = await sampler.routeWithShadow(query, { strategy: 'auto' });
29
+ * // decision.hasShadow === true iff we sampled a shadow provider
30
+ * // decision.primaryResult and decision.shadowResult are compared automatically
31
+ */
32
+
33
+ import { routeQuery, extractQueryFeatures, RouteDecision } from './advancedRouter';
34
+ import { getAvailableProviders, ProviderDefinition } from '../providers/providerConfig';
35
+ import { estimateCost } from '../utils/tokenUtils';
36
+
37
+ export interface ShadowSamplerConfig {
38
+ /**
39
+ * Minimum query stakes (estimated cost of wrong answer) to consider shadow.
40
+ * Below this, P(shadow) = 0 regardless of other factors.
41
+ * In dollars — what a wrong answer costs you.
42
+ * Default: $0.01 (1 cent — roughly equivalent to a simple API call cost)
43
+ */
44
+ minQueryStake?: number;
45
+
46
+ /**
47
+ * Maximum probability of shadow verification.
48
+ * Set to 1.0 for always-on (Zahavi-style, expensive).
49
+ * Default: 0.15 (15% — ODT-proportional sampling)
50
+ */
51
+ maxShadowProbability?: number;
52
+
53
+ /**
54
+ * Risk threshold (from QueryFeatures.risk_profile) above which
55
+ * shadow probability scales up linearly.
56
+ * 0.0 = no risk scaling (all queries get same P(shadow))
57
+ * 0.5 = medium risk scales P(shadow) by 50%
58
+ * 1.0 = high risk scales P(shadow) by 100%
59
+ */
60
+ riskScalingFactor?: number;
61
+
62
+ /**
63
+ * Cost scaling factor — if query is expensive (large output),
64
+ * shadow is more worthwhile (higher P(shadow)).
65
+ * 0.0 = no cost scaling.
66
+ * Default: 0.3 (expensive queries get moderate boost in P(shadow))
67
+ */
68
+ costScalingFactor?: number;
69
+
70
+ /**
71
+ * Provider to use as shadow (cheapest reliable provider).
72
+ * If not specified, auto-selected from available providers.
73
+ */
74
+ shadowProvider?: string;
75
+
76
+ /**
77
+ * Always use this shadow provider (overrides auto-selection).
78
+ */
79
+ forceShadowProvider?: boolean;
80
+
81
+ /**
82
+ * If true, use complexity as a signal for verification value.
83
+ * Complex queries (code, math, reasoning) benefit more from verification.
84
+ * Default: true
85
+ */
86
+ useComplexitySignal?: boolean;
87
+
88
+ /**
89
+ * Debug mode: always shadow regardless of sampling.
90
+ * Default: false
91
+ */
92
+ forceShadow?: boolean;
93
+ }
94
+
95
+ export interface ShadowDecision extends RouteDecision {
96
+ /** Whether a shadow provider was sampled for this query */
97
+ hasShadow: boolean;
98
+ /** The sampled shadow provider (null if no shadow) */
99
+ shadowProvider: string | null;
100
+ /** Shadow sampling probability that was used */
101
+ shadowProbability: number;
102
+ /** The query features that triggered shadow decision */
103
+ features: ReturnType<typeof extractQueryFeatures>;
104
+ /** ODT rationale for the shadow decision */
105
+ shadowReasoning: string;
106
+ }
107
+
108
+ export interface ShadowedResponse {
109
+ primary: string;
110
+ shadow: string | null;
111
+ winner: 'primary' | 'shadow' | 'tie' | 'no-shadow';
112
+ confidenceDelta: number;
113
+ }
114
+
115
+ /**
116
+ * Optimal Defense Theory Shadow Sampler
117
+ *
118
+ * Allocates shadow verification proportionally to query value and risk.
119
+ *
120
+ * The ODT sampling probability:
121
+ * P_shadow = min(maxP, baseP + risk_adj + cost_adj + complexity_adj)
122
+ *
123
+ * where:
124
+ * baseP = baseline verification rate (ODT " constitutive defense")
125
+ * risk_adj = risk_profile scaling (ODT "induced defense")
126
+ * cost_adj = output cost scaling (value of correct answer)
127
+ * complexity_adj = query complexity signal
128
+ */
129
+ export class ShadowSampler {
130
+ private config: Required<Omit<ShadowSamplerConfig, 'forceShadowProvider'>> & { forceShadowProvider: boolean };
131
+
132
+ // Cached shadow provider (auto-selected on first call)
133
+ private _shadowProvider: string | null = null;
134
+
135
+ // Counters for sampling statistics
136
+ private _shadowCount = 0;
137
+ private _totalCount = 0;
138
+
139
+ constructor(config: ShadowSamplerConfig = {}) {
140
+ this.config = {
141
+ minQueryStake: config.minQueryStake ?? 0.01,
142
+ maxShadowProbability: config.maxShadowProbability ?? 0.15,
143
+ riskScalingFactor: config.riskScalingFactor ?? 0.5,
144
+ costScalingFactor: config.costScalingFactor ?? 0.3,
145
+ shadowProvider: config.shadowProvider ?? null,
146
+ forceShadowProvider: config.forceShadowProvider ?? false,
147
+ useComplexitySignal: config.useComplexitySignal ?? true,
148
+ forceShadow: config.forceShadow ?? false,
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Auto-select the cheapest available provider as the shadow.
154
+ * Excludes the primary provider to ensure diversity.
155
+ */
156
+ private selectShadowProvider(primaryProvider: string): string {
157
+ if (this.config.forceShadowProvider && this.config.shadowProvider) {
158
+ return this.config.shadowProvider;
159
+ }
160
+
161
+ if (this._shadowProvider) return this._shadowProvider;
162
+
163
+ const profiles = getAvailableProviders();
164
+ const candidates = Object.entries(profiles)
165
+ .filter(([name, p]: [string, ProviderDefinition]) => {
166
+ // Exclude primary
167
+ if (name === primaryProvider) return false;
168
+ // Must be available (has API key) — cost must be finite
169
+ const cost = (p.costPerK.input + p.costPerK.output) / 2;
170
+ return cost < Infinity;
171
+ })
172
+ .sort((a, b) => {
173
+ const costA = (a[1].costPerK.input + a[1].costPerK.output) / 2;
174
+ const costB = (b[1].costPerK.input + b[1].costPerK.output) / 2;
175
+ return costA - costB;
176
+ });
177
+
178
+ if (candidates.length === 0) {
179
+ // Fallback: pick any non-primary
180
+ const fallback = Object.keys(profiles).find(n => n !== primaryProvider);
181
+ this._shadowProvider = fallback || primaryProvider;
182
+ } else {
183
+ this._shadowProvider = candidates[0][0];
184
+ }
185
+
186
+ return this._shadowProvider;
187
+ }
188
+
189
+ /**
190
+ * Estimate the query "stakes" — the expected cost of a wrong answer.
191
+ *
192
+ * ODT maps this to "tissue value": how much is this asset worth protecting?
193
+ * In routing terms: if this query fails, how much does it cost?
194
+ *
195
+ * We approximate this as:
196
+ * stake ≈ estimated_output_tokens × cost_per_token × criticality_multiplier
197
+ *
198
+ * where criticality is derived from query complexity and risk_profile.
199
+ */
200
+ private estimateQueryStake(features: ReturnType<typeof extractQueryFeatures>): number {
201
+ const estimatedTokens = features.length * 1.5; // rough estimate
202
+ const avgCostPerToken = 0.0001; // roughly $0.10/1K tokens
203
+ const stake = estimatedTokens * avgCostPerToken;
204
+
205
+ // Criticality multiplier from risk profile
206
+ const riskMultiplier: Record<string, number> = {
207
+ high: 10.0, // Wrong answer could cause real harm — worth verifying
208
+ medium: 2.0, // Some cost to wrong answer
209
+ low: 0.5, // Low stakes — skip verification
210
+ };
211
+ const riskMult = riskMultiplier[features.risk_profile || 'medium'] ?? 1.0;
212
+
213
+ // Complexity multiplier — complex queries are harder to verify but more valuable
214
+ // We use complexity as a proxy for "correctness is harder to judge"
215
+ const complexityMultiplier = 1 + (features.complexity || 0) * 2;
216
+
217
+ return stake * riskMult * complexityMultiplier;
218
+ }
219
+
220
+ /**
221
+ * Compute the ODT sampling probability for this query.
222
+ *
223
+ * ODT principle: defense (shadow) allocation ∝ expected benefit of defense.
224
+ * Expected benefit = P(failure) × cost_of_failure
225
+ *
226
+ * So P(shadow) scales with:
227
+ * 1. Query stake (expected cost of wrong answer)
228
+ * 2. Risk profile (probability of primary failure)
229
+ * 3. Output cost (verification ROI — cheaper outputs need less verification)
230
+ * 4. Complexity (complex queries benefit more from verification)
231
+ */
232
+ private computeShadowProbability(
233
+ features: ReturnType<typeof extractQueryFeatures>,
234
+ stake: number
235
+ ): number {
236
+ // Base probability (ODT "constitutive defense" — baseline verification rate)
237
+ let p = 0.02; // 2% baseline
238
+
239
+ // === STAKES ADJUSTMENT (ODT "tissue value") ===
240
+ // Higher stake → proportionally higher verification probability
241
+ // Scale from 2% to maxP as stake goes from minStake to $1.00
242
+ if (stake >= this.config.minQueryStake) {
243
+ const stakeAdj = Math.min(
244
+ (stake - this.config.minQueryStake) / (1.0 - this.config.minQueryStake),
245
+ 1.0
246
+ ) * (this.config.maxShadowProbability - 0.02);
247
+ p += stakeAdj;
248
+ } else {
249
+ // Below minimum stake — no verification regardless
250
+ return 0;
251
+ }
252
+
253
+ // === RISK ADJUSTMENT (ODT "attack probability") ===
254
+ // High-risk queries are more likely to have primary failures
255
+ // Scale risk_adj by riskScalingFactor (0.5 = 50% boost for high-risk)
256
+ const riskAdj: Record<string, number> = {
257
+ high: 0.10 * this.config.riskScalingFactor,
258
+ medium: 0.03 * this.config.riskScalingFactor,
259
+ low: 0.0,
260
+ };
261
+ p += riskAdj[features.risk_profile || 'medium'] ?? 0;
262
+
263
+ // === COMPLEXITY ADJUSTMENT (ODT "defense efficacy") ===
264
+ // Complex queries benefit more from verification (more errors to catch)
265
+ // But also harder to verify (requires domain knowledge to judge)
266
+ if (this.config.useComplexitySignal) {
267
+ if (features.has_code) {
268
+ p += 0.05; // Code verification has high ROI (bugs are costly)
269
+ }
270
+ if (features.requires_reasoning) {
271
+ p += 0.03; // Reasoning errors are subtle but costly
272
+ }
273
+ if (features.has_math) {
274
+ p += 0.04; // Math has objective ground truth — easy to verify (note: field is has_math)
275
+ }
276
+ }
277
+
278
+ // === COST SCALING (ODT "marginal defense cost") ===
279
+ // Expensive outputs are harder to produce — verify to avoid waste
280
+ if (this.config.costScalingFactor > 0 && features.length > 500) {
281
+ const costAdj = Math.min(
282
+ (features.length - 500) / 10000, // scale up for very long outputs
283
+ 0.05
284
+ ) * this.config.costScalingFactor;
285
+ p += costAdj;
286
+ }
287
+
288
+ // Clamp to [0, maxShadowProbability]
289
+ return Math.min(Math.max(p, 0), this.config.maxShadowProbability);
290
+ }
291
+
292
+ /**
293
+ * Route a query, with optional ODT-proportional shadow verification.
294
+ *
295
+ * @param prompt - The user query
296
+ * @param options - Routing options (same as routeQuery)
297
+ * @returns ShadowDecision with shadow metadata
298
+ */
299
+ routeWithShadow(
300
+ prompt: string,
301
+ options?: { available_models?: string[]; budget_multiplier?: number }
302
+ ): ShadowDecision {
303
+ const features = extractQueryFeatures(prompt);
304
+ const primaryDecision = routeQuery(prompt, options?.available_models, options?.budget_multiplier);
305
+
306
+ // Compute query stakes and shadow probability
307
+ const stake = this.estimateQueryStake(features);
308
+ const shadowProb = this.computeShadowProbability(features, stake);
309
+
310
+ // ODT sampling decision
311
+ const shouldShadow = this.config.forceShadow || Math.random() < shadowProb;
312
+ const shadowProvider = shouldShadow
313
+ ? this.selectShadowProvider(primaryDecision.primary_model || '')
314
+ : null;
315
+
316
+ if (shouldShadow) {
317
+ this._shadowCount++;
318
+ }
319
+ this._totalCount++;
320
+
321
+ const reasoning = shouldShadow
322
+ ? `ODT shadow: stake=${stake.toFixed(4)}, risk=${features.risk_profile}, P=${shadowProb.toFixed(3)}, complexity=${features.complexity.toFixed(2)}`
323
+ : `ODT no-shadow: stake=${stake.toFixed(4)} below threshold`;
324
+
325
+ return {
326
+ ...primaryDecision,
327
+ hasShadow: shouldShadow,
328
+ shadowProvider,
329
+ shadowProbability: shadowProb,
330
+ features,
331
+ shadowReasoning: reasoning,
332
+ };
333
+ }
334
+
335
+ /**
336
+ * Compare primary and shadow outputs.
337
+ * Returns the "better" answer and confidence delta.
338
+ *
339
+ * For production use: this would call both providers in parallel
340
+ * and compare outputs. For now, returns a stub that signals
341
+ * the caller should handle comparison.
342
+ */
343
+ async compareOutputs(
344
+ primaryAnswer: string,
345
+ shadowAnswer: string | null
346
+ ): Promise<ShadowedResponse> {
347
+ if (!shadowAnswer) {
348
+ return {
349
+ primary: primaryAnswer,
350
+ shadow: null,
351
+ winner: 'no-shadow',
352
+ confidenceDelta: 0,
353
+ };
354
+ }
355
+
356
+ // Simple comparison: length + character overlap as proxy for agreement
357
+ // In production, this would use a proper semantic similarity check
358
+ const primaryLen = primaryAnswer.length;
359
+ const shadowLen = shadowAnswer.length;
360
+ const lengthRatio = Math.min(primaryLen, shadowLen) / Math.max(primaryLen, shadowLen);
361
+
362
+ // Count common bigrams as a simple similarity proxy
363
+ const primaryBigrams = new Set<string>();
364
+ const shadowBigrams = new Set<string>();
365
+ for (let i = 0; i < primaryAnswer.length - 1; i++) {
366
+ primaryBigrams.add(primaryAnswer.slice(i, i + 2));
367
+ }
368
+ for (let i = 0; i < shadowAnswer.length - 1; i++) {
369
+ shadowBigrams.add(shadowAnswer.slice(i, i + 2));
370
+ }
371
+
372
+ let intersection = 0;
373
+ for (const bg of primaryBigrams) {
374
+ if (shadowBigrams.has(bg)) intersection++;
375
+ }
376
+ const union = primaryBigrams.size + shadowBigrams.size - intersection;
377
+ const jaccard = union > 0 ? intersection / union : 0;
378
+
379
+ // High agreement (jaccard > 0.8) → trust primary
380
+ // Low agreement → flag for review or prefer primary
381
+ const winner: ShadowedResponse['winner'] =
382
+ jaccard > 0.8 ? 'primary'
383
+ : jaccard > 0.5 ? 'tie'
384
+ : 'shadow'; // Low agreement: shadow might have caught something
385
+
386
+ const confidenceDelta = jaccard > 0.8 ? 0 : -0.1; // Reduce confidence if they differ
387
+
388
+ return {
389
+ primary: primaryAnswer,
390
+ shadow: shadowAnswer,
391
+ winner,
392
+ confidenceDelta,
393
+ };
394
+ }
395
+
396
+ /**
397
+ * Get sampling statistics for monitoring.
398
+ */
399
+ getStats(): { shadowCount: number; totalCount: number; shadowRate: number } {
400
+ return {
401
+ shadowCount: this._shadowCount,
402
+ totalCount: this._totalCount,
403
+ shadowRate: this._totalCount > 0 ? this._shadowCount / this._totalCount : 0,
404
+ };
405
+ }
406
+
407
+ /**
408
+ * Reset statistics counters.
409
+ */
410
+ resetStats(): void {
411
+ this._shadowCount = 0;
412
+ this._totalCount = 0;
413
+ }
414
+
415
+ /**
416
+ * Update configuration at runtime.
417
+ */
418
+ configure(config: Partial<ShadowSamplerConfig>): void {
419
+ this.config = { ...this.config, ...config };
420
+ }
421
+ }
422
+
423
+ // ============================================================
424
+ // NOTE: Named exports are at declaration level above.
425
+ // ShadowSampler, ShadowSamplerConfig, ShadowDecision, ShadowedResponse
426
+ // are all exported via 'export interface' / 'export class'
427
+ // ============================================================
@@ -1,35 +0,0 @@
1
- GitHub Pages Checker Checklist
2
-
3
- ## Phase 1: Content Ready
4
- - [x] GitHub Pages workflow configured
5
- - [x] README.md updated with TL;DR and latest stats
6
- - [x] popular-boosters.md ready with quick wins
7
- - [ ] Anim workshops for sponsors
8
- - [ ] PI-assistant memory setup
9
- - [ ] Orion assistant memory setup
10
-
11
- ## Phase 2: Deploy: GitHub Pages
12
- - [x] /docs/index.html exists (activated and deployed)
13
- - [ ] Primary landing page URL
14
- - [ ] Right domain (das-rebel.github.io/a3m-router)
15
- - [ ] CNAME file if needed
16
- - [ ] Deployed? -> https://das-rebel.github.io/a3m-router/docs/index.html
17
-
18
- ## Phase 3: Traffic Greasing
19
- - [x] Twitter thread
20
- - [x] Reddit post
21
- - [x] HackerNews
22
- - [x] Lint checklist files
23
-
24
- ---
25
-
26
- You need to set up a nitro django project (or similar) for tracking usage.
27
-
28
- **Key status:**
29
- - GitHub Pages is working (deployed from /docs)
30
- - Latest commit was July 7, 2026
31
- - Repo has 10 stars, 1 fork
32
- - If you need advanced ORM/batch processing, maybe try something else (like Data Stewards)
33
- - If you need standard server-side script support, this should work.
34
-
35
- Want me to: 1) Create deployment instructions, or 2) Set up script environment?