|
| 1 | +import { Injectable } from '@nestjs/common'; |
| 2 | +import { Variant } from '../entities/variant.entity'; |
| 3 | +import { Result } from '../entities/result.entity'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Simple ε‑greedy multi‑armed bandit implementation. |
| 7 | + * For each variant we track successes (metric > 0) and attempts. |
| 8 | + * With probability ε we explore a random variant, otherwise we exploit the best. |
| 9 | + */ |
| 10 | +@Injectable() |
| 11 | +export class BanditService { |
| 12 | + private readonly epsilon = 0.1; // exploration rate |
| 13 | + |
| 14 | + // In‑memory statistics – in production you would persist these. |
| 15 | + private stats: Record<string, { successes: number; attempts: number }> = {}; |
| 16 | + |
| 17 | + recordResult(variantId: string, metric?: number) { |
| 18 | + if (!this.stats[variantId]) this.stats[variantId] = { successes: 0, attempts: 0 }; |
| 19 | + this.stats[variantId].attempts += 1; |
| 20 | + if (metric && metric > 0) this.stats[variantId].successes += 1; |
| 21 | + } |
| 22 | + |
| 23 | + chooseVariant(variants: Variant[]): Variant { |
| 24 | + if (Math.random() < this.epsilon) { |
| 25 | + // Explore random variant |
| 26 | + return variants[Math.floor(Math.random() * variants.length)]; |
| 27 | + } |
| 28 | + // Exploit: pick variant with highest success rate |
| 29 | + let best = variants[0]; |
| 30 | + let bestRate = this.successRate(best.id); |
| 31 | + for (const v of variants) { |
| 32 | + const rate = this.successRate(v.id); |
| 33 | + if (rate > bestRate) { |
| 34 | + best = v; |
| 35 | + bestRate = rate; |
| 36 | + } |
| 37 | + } |
| 38 | + return best; |
| 39 | + } |
| 40 | + |
| 41 | + private successRate(variantId: string): number { |
| 42 | + const s = this.stats[variantId]; |
| 43 | + if (!s || s.attempts === 0) return 0; |
| 44 | + return s.successes / s.attempts; |
| 45 | + } |
| 46 | +} |
0 commit comments