feat: Add distillery enrichment cache
Caches AI enrichment results per distillery to save API calls: - New table: enrichment_cache (distillery, tags, hit_count) - New service: cache-enrichment.ts (get, save, increment, stats) - enrich-data.ts checks cache before AI query - Saves to cache after successful AI response - Returns cached: true/false flag for transparency Benefits: - 0 API cost for repeated distillery scans - Near-instant response for cached distilleries - Shared across all users
This commit is contained in:
@@ -6,6 +6,7 @@ import { trackApiUsage } from '@/services/track-api-usage';
|
||||
import { deductCredits } from '@/services/credit-service';
|
||||
import { getAllSystemTags } from '@/services/tags';
|
||||
import { getAIProvider, getOpenRouterClient, OPENROUTER_PROVIDER_PREFERENCES } from '@/lib/openrouter';
|
||||
import { getEnrichmentCache, saveEnrichmentCache, incrementCacheHit } from '@/services/cache-enrichment';
|
||||
|
||||
// Native Schema Definition for Enrichment Data
|
||||
const enrichmentSchema = {
|
||||
@@ -146,6 +147,31 @@ export async function enrichData(name: string, distillery: string, availableTags
|
||||
return { success: false, error: 'OPENROUTER_API_KEY is not configured.' };
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// CACHE CHECK - Return cached data if available
|
||||
// ========================================
|
||||
if (distillery?.trim()) {
|
||||
try {
|
||||
const cached = await getEnrichmentCache(distillery);
|
||||
if (cached) {
|
||||
console.log(`[EnrichData] ✅ CACHE HIT for: ${distillery}`);
|
||||
// Fire and forget: increment hit counter
|
||||
incrementCacheHit(distillery).catch(() => { });
|
||||
return {
|
||||
success: true,
|
||||
data: cached,
|
||||
cached: true,
|
||||
provider: 'cache',
|
||||
perf: { apiDuration: 0 }
|
||||
};
|
||||
}
|
||||
console.log(`[EnrichData] ❌ Cache MISS for: ${distillery}`);
|
||||
} catch (cacheError) {
|
||||
console.warn('[EnrichData] Cache lookup failed:', cacheError);
|
||||
// Continue with AI query
|
||||
}
|
||||
}
|
||||
|
||||
let supabase;
|
||||
try {
|
||||
let tagsToUse = availableTags;
|
||||
@@ -184,6 +210,15 @@ Instructions:
|
||||
|
||||
console.log('[EnrichData] Response:', result.data);
|
||||
|
||||
// ========================================
|
||||
// SAVE TO CACHE - Store for future lookups
|
||||
// ========================================
|
||||
if (distillery?.trim()) {
|
||||
saveEnrichmentCache(distillery, result.data).catch((err) => {
|
||||
console.warn('[EnrichData] Cache save failed:', err);
|
||||
});
|
||||
}
|
||||
|
||||
// Track usage
|
||||
await trackApiUsage({
|
||||
userId: userId,
|
||||
@@ -197,6 +232,7 @@ Instructions:
|
||||
return {
|
||||
success: true,
|
||||
data: result.data,
|
||||
cached: false,
|
||||
provider,
|
||||
perf: {
|
||||
apiDuration: result.apiTime
|
||||
|
||||
Reference in New Issue
Block a user