File size: 7,993 Bytes
9580dce | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | import { claude, parseClaudeJson } from "@/lib/claude";
import type { PerformanceSummary } from "@/lib/performance";
import type { DifficultyRecommendations } from "@/lib/difficulty";
import { getRecommendedSettings } from "@/lib/difficulty";
import { CATEGORY_LABELS, type Category } from "@/config/xp";
import { createHash } from "crypto";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface CoachFeedback {
feedback: string;
recommendedExercise: {
category: Category;
difficulty: string;
};
encouragement: string;
}
interface CacheEntry {
feedback: CoachFeedback;
cachedAt: number;
}
// ---------------------------------------------------------------------------
// Configuration
// ---------------------------------------------------------------------------
/** Cache TTL: 3 hours in milliseconds */
const CACHE_TTL_MS = 3 * 60 * 60 * 1000;
/** Max requests per user per hour */
const RATE_LIMIT_MAX = 10;
/** Rate limit window: 1 hour in milliseconds */
const RATE_LIMIT_WINDOW_MS = 60 * 60 * 1000;
// ---------------------------------------------------------------------------
// In-memory caches (reset on server restart, which is fine for dev/MVP)
// ---------------------------------------------------------------------------
const feedbackCache = new Map<string, CacheEntry>();
/** Map of userId → array of request timestamps */
const rateLimitMap = new Map<number, number[]>();
// ---------------------------------------------------------------------------
// Cache key generation
// ---------------------------------------------------------------------------
/**
* Build a cache key by hashing the user ID + rounded performance metrics.
* Small changes (±2% success rate, same streak bucket) won't bust the cache.
*/
export function buildCacheKey(
userId: number,
summary: PerformanceSummary,
): string {
const roundedCategories = summary.categories.map((c) => ({
cat: c.category,
sr: Math.round(c.successRate / 5) * 5, // Round to nearest 5%
trend: c.trend,
attempts: Math.round(c.attempts / 5) * 5, // Round to nearest 5
}));
const payload = JSON.stringify({
userId,
streak: Math.min(summary.streakDays, 30), // Cap streak granularity
overallScore: Math.round(summary.overallScore / 5) * 5,
cats: roundedCategories,
});
return createHash("sha256").update(payload).digest("hex").slice(0, 16);
}
// ---------------------------------------------------------------------------
// Rate limiting
// ---------------------------------------------------------------------------
/**
* Check if a user has exceeded the rate limit.
* Returns true if the request should be blocked.
*/
export function isRateLimited(userId: number): boolean {
const now = Date.now();
const timestamps = rateLimitMap.get(userId) ?? [];
// Prune expired entries
const active = timestamps.filter(
(t) => now - t < RATE_LIMIT_WINDOW_MS,
);
rateLimitMap.set(userId, active);
return active.length >= RATE_LIMIT_MAX;
}
/**
* Record a request for rate-limiting purposes.
*/
export function recordRequest(userId: number): void {
const now = Date.now();
const timestamps = rateLimitMap.get(userId) ?? [];
timestamps.push(now);
rateLimitMap.set(userId, timestamps);
}
// ---------------------------------------------------------------------------
// Cache operations
// ---------------------------------------------------------------------------
/**
* Get a cached feedback response if it exists and hasn't expired.
*/
export function getCachedFeedback(key: string): CoachFeedback | null {
const entry = feedbackCache.get(key);
if (!entry) return null;
if (Date.now() - entry.cachedAt > CACHE_TTL_MS) {
feedbackCache.delete(key);
return null;
}
return entry.feedback;
}
/**
* Store feedback in cache.
*/
export function cacheFeedback(key: string, feedback: CoachFeedback): void {
feedbackCache.set(key, { feedback, cachedAt: Date.now() });
}
// ---------------------------------------------------------------------------
// Prompt construction
// ---------------------------------------------------------------------------
/**
* Build the Claude prompt from performance data and difficulty recommendations.
*/
export function buildPrompt(
summary: PerformanceSummary,
recommendations: DifficultyRecommendations,
): string {
const catSummaries = summary.categories
.filter((c) => c.attempts > 0)
.map((c) => {
const rec = recommendations.recommendations[c.category];
return `- ${CATEGORY_LABELS[c.category]}: ${c.successRate}% success rate, ${c.attempts} attempts, level ${c.level}, trend: ${c.trend}, recommended difficulty: ${rec?.difficulty ?? "medium"}`;
})
.join("\n");
const inactiveCategories = summary.categories
.filter((c) => c.attempts === 0)
.map((c) => CATEGORY_LABELS[c.category]);
const inactiveNote =
inactiveCategories.length > 0
? `\nUnexplored categories: ${inactiveCategories.join(", ")}`
: "";
return `You are the Active Coach for RotNot, a brain training app that combats cognitive atrophy from AI over-reliance. Analyze the user's performance and provide personalized coaching feedback.
User Performance:
- Overall score: ${summary.overallScore}%
- Streak: ${summary.streakDays} days (longest: ${summary.longestStreak})
- Total exercises completed: ${summary.totalExercises}
- Active days: ${summary.activeDays}
- Last activity: ${summary.lastActivityAt ?? "never"}
Category Breakdown:
${catSummaries || "No exercises completed yet."}${inactiveNote}
Instructions:
1. "feedback": 2-3 actionable sentences about their performance. Reference specific categories and trends. Do NOT be generic.
2. "recommendedExercise": Pick the single best category and difficulty for them right now. Use one of: chess, reading, feynman, logic, critical-thinking, quests. Difficulty: easy, medium, or hard.
3. "encouragement": 1 sentence of genuine, specific encouragement (not generic "keep it up!" — reference something real from their data).
Respond ONLY in valid JSON (no markdown, no code fences):
{ "feedback": "...", "recommendedExercise": { "category": "...", "difficulty": "..." }, "encouragement": "..." }`;
}
// ---------------------------------------------------------------------------
// Main feedback generator
// ---------------------------------------------------------------------------
/**
* Generate coach feedback for a user. Uses cache if available,
* otherwise calls Claude Haiku.
*
* Throws if Claude call fails or returns invalid JSON.
*/
export async function generateCoachFeedback(
userId: number,
summary: PerformanceSummary,
): Promise<{ feedback: CoachFeedback; cached: boolean }> {
const recommendations = getRecommendedSettings(summary);
const cacheKey = buildCacheKey(userId, summary);
// Check cache first
const cached = getCachedFeedback(cacheKey);
if (cached) {
return { feedback: cached, cached: true };
}
// Build prompt and call Claude
const prompt = buildPrompt(summary, recommendations);
const message = await claude.messages.create({
model: "claude-haiku-4-5-20251001",
max_tokens: 512,
messages: [{ role: "user", content: prompt }],
});
const text =
message.content[0].type === "text" ? message.content[0].text : "";
const parsed = parseClaudeJson(text) as CoachFeedback;
// Validate response shape
if (
!parsed.feedback ||
typeof parsed.feedback !== "string" ||
!parsed.recommendedExercise ||
!parsed.recommendedExercise.category ||
!parsed.recommendedExercise.difficulty ||
!parsed.encouragement ||
typeof parsed.encouragement !== "string"
) {
throw new Error("Claude returned invalid feedback structure");
}
// Cache the result
cacheFeedback(cacheKey, parsed);
return { feedback: parsed, cached: false };
}
|