apac-strategy-dashboard/geminiService.ts
2026-04-15 11:12:23 +05:30

91 lines
4.9 KiB
TypeScript

import { GoogleGenAI } from "@google/genai";
import { DashboardData } from "./types";
const MODEL_NAME = 'gemini-3-flash-preview';
export const fetchMarketInsights = async (product: string, category: string): Promise<DashboardData> => {
const ai = new GoogleGenAI({ apiKey: process.env.API_KEY });
const currentDate = new Date().toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' });
const prompt = `Task: APAC Strategic Market Audit for "${product}" in "${category}".
Current Date for Context: ${currentDate}.
You are a Strategic Data Analyst. Use the Google Search tool to conduct a deep-dive audit.
Your analysis must be grounded in data available up to ${currentDate}.
Focus on:
1. Real-time Market Metrics: Find the most recent industry benchmarks (2024-2025).
2. Competitor Share of Search: Use recent search volume trends to estimate share.
3. Efficacy Benchmark: Identify 3-4 key performance radar metrics for this category (e.g. Price, Quality, Innovation, Sustainability).
4. High-Impact Creators: Identify the top 3-4 creators/influencers currently dominating the conversation in this space.
5. Industry Pulse: Find the most recent (last 30 days) news headlines, sentiment, and sources. Provide AT LEAST 4 items.
6. Strategic Whitespace: Identify EXACTLY 2 OPPORTUNITIES and EXACTLY 2 RISKS.
7. Competitor Claims: Identify AT LEAST 7 strategic marketing claims. These should be "fuzzy" but verifiable (e.g., instead of just "10% faster", use "Velocity-Driven Performance" or "Heritage-Infused Innovation").
8. Cultural Nuance: Identify EXACTLY 4 nuances. At least two MUST be specifically about local traditions, cultural behaviors, or regional etiquette relevant to "${category}" in APAC.
Generate a strictly valid JSON response.
IMPORTANT: Do not include markdown code blocks. Return ONLY the raw JSON string.
JSON Structure:
{
"marketMetrics": {
"roas": {"label": "ROAS", "value": "string", "trend": "up|down|stable", "explanation": "string", "source": "string", "methodology": "string"},
"engagement": {"label": "Engagement", "value": "string", "trend": "up|down|stable", "explanation": "string", "source": "string", "methodology": "string"},
"fatigue": {"label": "Ad Fatigue", "value": "string", "trend": "up|down|stable", "explanation": "string", "source": "string", "methodology": "string"},
"sov": {"label": "SOV", "value": "string", "trend": "up|down|stable", "explanation": "string", "source": "string", "methodology": "string"}
},
"platformVelocity": [{"platform": "string", "region": "string", "trend": "up|stable|down", "value": number}],
"radarMetrics": [{"label": "string", "score": number, "benchmark": number}],
"newsFeed": [{"headline": "string", "source": "string", "sentiment": "positive|negative|neutral", "score": number}],
"competitorClaims": [{"keyword": "string", "frequency": number, "explanation": "string", "source": "string", "methodology": "string"}],
"whitespaceAnalysis": [{"type": "OPPORTUNITY|RISK", "title": "string", "description": "string"}],
"socialHighlights": [{"platform": "TikTok|Instagram", "headline": "string", "metrics": "string", "thumbnail": "string", "sourceUrl": "string"}],
"topCreators": [{"name": "string", "handle": "string", "category": "string", "impact": "string"}],
"agencyBrief": {
"objective": "string",
"targetAudience": "string",
"keyMessage": "string",
"creativeHooks": ["string"],
"tacticalContent": [{"format": "string", "channel": "string", "description": "string"}]
},
"culturalNuances": [
{
"term": "string",
"insight": "string",
"strategyTip": "string",
"sourceTitle": "string",
"sourceUrl": "string"
}
],
"summary": {"overview": "string", "strategicTakeaways": ["string"], "sources": [{"title": "string", "url": "string"}]},
"shareOfSearch": [{"competitor": "string", "percentage": number}]
}
Strict Rules:
1. GROUNDING: Use Google Search to find ACTUAL names, news, and trends relative to ${currentDate}.
2. CREATORS: Find top 3-4 specific real-world creators for this specific category.
3. NEWS: Find real, recent headlines with specific sources. At least 4.
4. CULTURAL: Precisely 4 nuances. Include local traditions.
5. JSON: Return only the JSON object. No markdown.
6. CLAIMS: At least 7 strategic, "fuzzy" but grounded claims.`;
const response = await ai.models.generateContent({
model: MODEL_NAME,
contents: prompt,
config: {
tools: [{ googleSearch: {} }],
},
});
const text = response.text;
if (!text) throw new Error("AI returned empty content");
try {
const jsonString = text.trim().replace(/^```json\n?/, "").replace(/\n?```$/, "");
return JSON.parse(jsonString);
} catch (e) {
console.error("Failed to parse AI response:", text);
throw new Error("Data synthesis failed. Please try a different category or retry.");
}
};