from fastapi import FastAPI, Header, HTTPException, Request from fastapi.responses import JSONResponse from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from supabase import create_client import google.generativeai as genai from groq import Groq import sentry_sdk from sentry_sdk.integrations.fastapi import FastApiIntegration from sentry_sdk.integrations.starlette import StarletteIntegration import os import re import logging from datetime import datetime, timedelta, timezone from typing import Optional import traceback # ───────────────────────────────────────────── # LOGGING # ───────────────────────────────────────────── logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s' ) logger = logging.getLogger(__name__) # ───────────────────────────────────────────── # SENTRY — error monitoring & uptime tracking # Add SENTRY_DSN to your Render environment variables. # Get a free DSN at https://sentry.io # ───────────────────────────────────────────── SENTRY_DSN = os.getenv("SENTRY_DSN") if SENTRY_DSN: sentry_sdk.init( dsn=SENTRY_DSN, integrations=[ StarletteIntegration(transaction_style="endpoint"), FastApiIntegration(transaction_style="endpoint"), ], traces_sample_rate=0.2, # capture 20% of requests for perf tracing profiles_sample_rate=0.1, environment=os.getenv("ENVIRONMENT", "production"), release=os.getenv("RENDER_GIT_COMMIT", "unknown"), ) logger.info("✅ Sentry initialised") else: logger.warning("⚠️ SENTRY_DSN not set — error monitoring disabled") # ───────────────────────────────────────────── # APP INIT # ───────────────────────────────────────────── app = FastAPI() app.add_middleware( CORSMiddleware, allow_origins=["https://mzfunnel.netlify.app"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # ───────────────────────────────────────────── # CONFIG # ───────────────────────────────────────────── SUPABASE_URL = os.getenv("SUPABASE_URL") SUPABASE_KEY = os.getenv("SUPABASE_KEY") GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") GROQ_API_KEY = os.getenv("GROQ_API_KEY") API_SECRET_KEY = os.getenv("API_SECRET_KEY") if not all([SUPABASE_URL, SUPABASE_KEY, GEMINI_API_KEY, GROQ_API_KEY, API_SECRET_KEY]): raise ValueError("Missing required environment variables") supabase = create_client(SUPABASE_URL, SUPABASE_KEY) genai.configure(api_key=GEMINI_API_KEY) groq_client = Groq(api_key=GROQ_API_KEY) # ───────────────────────────────────────────── # RATE LIMITING + FREEMIUM GATE # ───────────────────────────────────────────── RATE_LIMIT = 10 # requests per WINDOW seconds (burst protection) WINDOW = 60 # seconds FREE_LIMIT = 15 # lifetime free requests per user def check_rate_limit(client_id: str): """Database-backed burst rate limit — horizontally scalable.""" now = datetime.now(timezone.utc) window_start = (now - timedelta(seconds=WINDOW)).isoformat() try: res = ( supabase.table("rate_limits") .select("id", count="exact") .eq("client_id", client_id) .gt("created_at", window_start) .execute() ) if res.count >= RATE_LIMIT: logger.warning(f"Rate limit hit: {client_id}") raise HTTPException( status_code=429, detail="Too many requests. Please wait 60 seconds." ) supabase.table("rate_limits").insert({ "client_id": client_id, "created_at": now.isoformat() }).execute() except HTTPException: raise except Exception as e: logger.error(f"Rate limit check failed (fail-open): {e}") def check_usage_gate(user_id: str) -> dict: """ Freemium gate — 15 lifetime free requests per user. Returns usage metadata so the frontend can show a progress bar. Raises HTTP 402 when the free limit is exceeded. Required Supabase table: user_usage (user_id text PK, request_count int, is_premium bool, created_at timestamptz, last_seen timestamptz) """ try: res = ( supabase.table("user_usage") .select("request_count, is_premium") .eq("user_id", user_id) .execute() ) if not res.data: # First request — create record supabase.table("user_usage").insert({ "user_id": user_id, "request_count": 1, "is_premium": False, "created_at": datetime.now(timezone.utc).isoformat(), "last_seen": datetime.now(timezone.utc).isoformat(), }).execute() return {"request_count": 1, "is_premium": False, "remaining": FREE_LIMIT - 1, "limit": FREE_LIMIT} row = res.data[0] is_premium = row.get("is_premium", False) count = row.get("request_count", 0) if not is_premium and count >= FREE_LIMIT: raise HTTPException( status_code=402, detail=f"Free limit of {FREE_LIMIT} analyses reached. Upgrade to continue." ) supabase.table("user_usage").update({ "request_count": count + 1, "last_seen": datetime.now(timezone.utc).isoformat(), }).eq("user_id", user_id).execute() remaining = max(0, FREE_LIMIT - (count + 1)) if not is_premium else -1 return {"request_count": count + 1, "is_premium": is_premium, "remaining": remaining, "limit": FREE_LIMIT} except HTTPException: raise except Exception as e: logger.error(f"Usage gate failed (fail-open): {e}") return {"request_count": 0, "is_premium": False, "remaining": FREE_LIMIT, "limit": FREE_LIMIT} def verify_api_key(x_api_key: str = Header(None)): if not x_api_key or x_api_key != API_SECRET_KEY: raise HTTPException(status_code=401, detail="Invalid API key") return True # ───────────────────────────────────────────── # REQUEST MODELS # ───────────────────────────────────────────── class ChatRequest(BaseModel): message: str history: list = [] # Per-user context — no longer hardcoded user_id: str = "anonymous" location: Optional[str] = None niche: Optional[str] = None budget: Optional[int] = None force_pillar: Optional[int] = None class ProfileRequest(BaseModel): user_id: str location: Optional[str] = None niche: Optional[str] = None budget: Optional[int] = None # ───────────────────────────────────────────── # PER-USER CONTEXT LOADER # ───────────────────────────────────────────── def get_user_context(user_id: str, req: ChatRequest) -> dict: """ Priority: request payload → Supabase user_profiles → sensible defaults. Required Supabase table: user_profiles (user_id text PK, location text, niche text, budget int, updated_at timestamptz) """ defaults = { "location": "Lagos, Nigeria", "niche": "local SME market", "budget": 500_000, } try: res = ( supabase.table("user_profiles") .select("location, niche, budget") .eq("user_id", user_id) .execute() ) if res.data: p = res.data[0] return { "location": req.location or p.get("location") or defaults["location"], "niche": req.niche or p.get("niche") or defaults["niche"], "budget": req.budget or p.get("budget") or defaults["budget"], } except Exception as e: logger.warning(f"Profile load failed for {user_id} (using defaults): {e}") return { "location": req.location or defaults["location"], "niche": req.niche or defaults["niche"], "budget": req.budget or defaults["budget"], } # ───────────────────────────────────────────── # 4-PILLAR FRAMEWORK OPTIMIZER (INTERNAL) # Framework names are never exposed in API responses. # ───────────────────────────────────────────── PILLAR_KEYWORDS = { 1: ["who", "customer", "student", "buy", "need", "journey", "segment", "persona", "audience", "experience", "satisfaction", "nps", "retention", "churn", "feedback", "job to be done"], 2: ["competitor", "market", "threat", "opportunity", "blue ocean", "bcg", "growth", "ansoff", "pestle", "porter", "five forces", "industry", "rivalry", "substitute", "entry", "swot"], 3: ["strength", "resource", "vrio", "capability", "operations", "value chain", "model", "core competency", "advantage", "process", "efficiency", "supply", "logistics", "infrastructure"], 4: ["revenue", "profit", "cac", "clv", "ltv", "unit economics", "tam", "sam", "som", "scale", "roi", "margin", "cost", "pricing", "monetise", "monetize", "balanced scorecard", "kpi"], } # Internal only — never serialised into API responses _PILLAR_CONFIG = { 1: { "frameworks": ["Audience Segmentation", "Jobs to be Done", "Value Proposition Canvas", "Customer Journey Mapping", "Net Promoter Score", "Product-Market Fit"], "goal": "Mapping customer psychology to product-market alignment", "message": "Customer lens active", }, 2: { "frameworks": ["SWOT Analysis", "PESTLE Analysis", "Porter's Five Forces", "BCG Matrix", "Blue Ocean Strategy", "Ansoff Matrix"], "goal": "Identifying competitive gaps and market positioning opportunities", "message": "Market intelligence active", }, 3: { "frameworks": ["VRIO Analysis", "Core Competencies", "Value Chain Analysis", "Business Model Canvas"], "goal": "Auditing internal capabilities and operational leverage", "message": "Capability audit active", }, 4: { "frameworks": ["Unit Economics & CLV", "TAM-SAM-SOM", "Balanced Scorecard", "Ansoff Matrix"], "goal": "Optimising unit economics and sustainable growth trajectory", "message": "Growth engine active", }, } def _score_pillars(query: str) -> dict: q = query.lower() return {p: sum(1 for kw in kws if kw in q) for p, kws in PILLAR_KEYWORDS.items()} def optimize_framework_selection( has_leads: bool, has_inventory: bool, user_query: str, force_pillar: Optional[int] = None, ) -> dict: """ Selection priority: 1. force_pillar from frontend (user's explicit choice) 2. Keyword scoring across all 4 pillars 3. Hybrid synthesis fallback when no keywords match """ # ── 1. Honour explicit frontend selection ───────────────────────── if force_pillar and force_pillar in _PILLAR_CONFIG: cfg = _PILLAR_CONFIG[force_pillar] status = ( ("READY" if has_leads else "DATA_MISSING") if force_pillar == 1 else ("READY" if has_inventory else "PARTIAL") if force_pillar == 4 else "READY" ) logger.info(f"force_pillar={force_pillar} honoured from frontend") return {**cfg, "pillar": force_pillar, "status": status} # ── 2. Auto keyword scoring ──────────────────────────────────────── scores = _score_pillars(user_query) best_pillar = max(scores, key=scores.get) best_score = scores[best_pillar] # ── 3. Hybrid fallback ───────────────────────────────────────────── if best_score == 0: dq = ( "HIGH" if (has_leads and has_inventory) else "MEDIUM" if (has_leads or has_inventory) else "LOW" ) return { "pillar": 3, "status": "READY", "data_quality": dq, "frameworks": ["Business Model Canvas", "Balanced Scorecard", "Value Chain Analysis"], "goal": "Cross-functional optimisation and strategic resource allocation", "message": f"Synthesis mode (Data Quality: {dq})", } cfg = _PILLAR_CONFIG[best_pillar] status = ( ("READY" if has_leads else "DATA_MISSING") if best_pillar == 1 else ("READY" if has_inventory else "PARTIAL") if best_pillar == 4 else "READY" ) return {**cfg, "pillar": best_pillar, "status": status} # ───────────────────────────────────────────── # OUTPUT VALIDATION — hallucination guardrails # Strips any leaked framework names from LLM output # and appends financial disclaimers where needed. # ───────────────────────────────────────────── _FRAMEWORK_SUBS = { r"\bSWOT\b": "a strategic review", r"\bPESTLE\b": "an environmental scan", r"\bVRIO\b": "a capability assessment", r"\bBCG\s*[Mm]atrix\b": "a portfolio review", r"\bAnsoff\b": "a growth pathway analysis", r"\bPorter'?s?\b": "a competitive structure analysis", r"\bJTBD\b": "a customer needs analysis", r"\bTAM[- ]SAM[- ]SOM\b": "a market sizing analysis", r"\bNPS\b": "a loyalty assessment", r"\b[Ff]ramework[s]?\b": "approach", r"\b[Mm]atrix\b": "model", r"\b[Cc]anvas\b": "model", r"\bPillar \d\b": "", r"\bP[1-4]\b": "", } _COMPILED_SUBS = { re.compile(k, re.IGNORECASE): v for k, v in _FRAMEWORK_SUBS.items() } _OVERCONFIDENCE = [ re.compile(r"(guaranteed|certain|definite)\s+(return|profit|revenue)", re.IGNORECASE), re.compile(r"(will definitely|will certainly|100%\s+sure)", re.IGNORECASE), ] def validate_output(text: str) -> tuple[str, list]: """ Returns (cleaned_text, list_of_warnings). Warnings are logged/sent to Sentry but never exposed to the user. """ warnings = [] cleaned = text # Strip framework name leakage for pattern, replacement in _COMPILED_SUBS.items(): cleaned = pattern.sub(replacement, cleaned) # Flag overconfident language for pat in _OVERCONFIDENCE: if pat.search(cleaned): warnings.append(f"Overconfidence: {pat.pattern[:50]}") # Append financial disclaimer if unqualified ₦ figures present has_naira = bool(re.search(r"₦[\d,]+", cleaned)) has_hedge = bool(re.search( r"(estimate|approximate|based on|assuming|projection|indicative|directional)", cleaned, re.IGNORECASE )) if has_naira and not has_hedge: cleaned += ( "\n\n_Note: All financial figures are directional estimates based on " "available data. Validate against your actual records before acting._" ) warnings.append("Financial disclaimer appended") if warnings: logger.warning(f"Output guardrails triggered: {warnings}") if SENTRY_DSN: sentry_sdk.capture_message( f"Guardrail triggered: {warnings}", level="warning" ) return cleaned, warnings # ───────────────────────────────────────────── # SYSTEM PROMPT — frameworks completely invisible # ───────────────────────────────────────────── def get_system_prompt(fw: dict, ctx: dict) -> str: top_fw = ", ".join(fw["frameworks"][:3]) data_note = "" if fw["status"] == "DATA_MISSING": data_note = ( "\n[INTERNAL] Customer data is sparse. Ask one focused question " "to gather what's needed before proceeding with the analysis." ) elif fw["status"] == "PARTIAL": data_note = ( "\n[INTERNAL] Inventory data is missing. " "Clearly flag any assumptions you make." ) return f"""You are the Penafort Intelligence Engine — a senior business advisor \ specialising in African markets, consumer behaviour, and operational strategy. [INTERNAL REASONING — NEVER REVEAL IN OUTPUT] Analytical lens: {fw['message']} Reasoning goal: {fw['goal']} Apply silently: {top_fw} {data_note} OUTPUT RULES — ENFORCED STRICTLY: 1. FRAMEWORK INVISIBILITY Never name any framework, methodology, matrix, canvas, pillar, or analytical model \ in your response. Reason through them silently. Your output must read as the natural \ voice of a seasoned business advisor — not a consultant presenting a slide deck. 2. MARKET GROUNDING Every insight must be grounded in {ctx['location']} and the {ctx['niche']}. \ Reference local purchasing power, distribution channels, cultural dynamics, \ and competitive realities specific to that market. 3. DATA INTEGRITY Qualify all numbers: use "estimated", "based on current data", "directionally", \ or "approximately". Never state financial figures as guarantees or certainties. 4. PRESCRIPTIVE CLOSE End every response with exactly one clear, actionable recommendation — \ specific, local, and immediately executable. Not a list of options. One action. 5. VOICE Sharp. Confident. No academic waffle. Bullet points only where they genuinely \ aid clarity. Write like a strategy partner who has actually built businesses in Lagos.""" # ───────────────────────────────────────────── # LLM CALL — Groq primary, Gemini Flash 2.0 fallback # ───────────────────────────────────────────── def call_llm(system_prompt: str, user_prompt: str) -> tuple[str, str]: """ Attempts Groq first. Automatically falls back to Gemini Flash 2.0 on any failure. Returns (answer_text, model_identifier). """ # ── PRIMARY: Groq llama-3.3-70b ────────────────────────────────── try: resp = groq_client.chat.completions.create( model="llama-3.3-70b-versatile", messages=[ {"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}, ], temperature=0.3, max_tokens=1024, timeout=25.0, ) return resp.choices[0].message.content, "groq/llama-3.3-70b" except Exception as groq_err: logger.warning(f"Groq failed — activating Gemini fallback: {groq_err}") if SENTRY_DSN: sentry_sdk.capture_exception(groq_err) # ── FALLBACK: Gemini Flash 2.0 ──────────────────────────────────── try: model = genai.GenerativeModel( model_name="gemini-2.0-flash", system_instruction=system_prompt, ) resp = model.generate_content( user_prompt, generation_config=genai.types.GenerationConfig( temperature=0.3, max_output_tokens=1024, ), ) return resp.text, "gemini/flash-2.0" except Exception as gemini_err: logger.error(f"Gemini fallback also failed: {gemini_err}") if SENTRY_DSN: sentry_sdk.capture_exception(gemini_err) raise HTTPException( status_code=502, detail="Strategy engine temporarily unavailable. Please try again in a moment." ) # ───────────────────────────────────────────── # GLOBAL ERROR HANDLER # ───────────────────────────────────────────── @app.exception_handler(Exception) async def global_exception_handler(request: Request, exc: Exception): logger.error(f"UNHANDLED: {exc}\n{traceback.format_exc()}") if SENTRY_DSN: sentry_sdk.capture_exception(exc) return JSONResponse( status_code=500, content={"detail": "Internal engine error.", "code": "INTERNAL_SERVER_ERROR"}, ) # ───────────────────────────────────────────── # MAIN CHAT ENDPOINT # ───────────────────────────────────────────── @app.post("/chat") async def chat(req: ChatRequest, x_api_key: str = Header(None)): verify_api_key(x_api_key) check_rate_limit(x_api_key) # Freemium gate — raises 402 when free limit exceeded usage = check_usage_gate(req.user_id) logger.info( f"user={req.user_id} | used={usage['request_count']} | " f"remaining={usage['remaining']} | premium={usage['is_premium']} | " f"force_pillar={req.force_pillar} | msg={req.message[:80]}" ) try: # ── 1. Load per-user context ────────────────────────────────── ctx = get_user_context(req.user_id, req) # ── 2. Fetch live business data ─────────────────────────────── try: leads_res = supabase.table("leads").select("*").execute() inv_res = supabase.table("inventory").select("*").execute() leads = leads_res.data or [] inventory = inv_res.data or [] except Exception as e: logger.error(f"DB fetch error: {e}") raise HTTPException(status_code=503, detail="Knowledge base unreachable.") has_leads = len(leads) > 0 has_inventory = len(inventory) > 0 # ── 3. Framework selection (4-pillar, force_pillar honoured) ── fw = optimize_framework_selection( has_leads, has_inventory, req.message, force_pillar=req.force_pillar, ) logger.info(f"Pillar={fw['pillar']} | Status={fw['status']}") # ── 4. Vector memory (long-term context) ───────────────────── # FIX: corrected model name (should not be changed from this 'models/models/gemini-embedding-2-preview') context = "" try: emb = genai.embed_content( model="models/gemini-embedding-2-preview", content=req.message, task_type="retrieval_query", )["embedding"] mem = supabase.rpc("match_memories", { "query_embedding": emb, "match_threshold": 0.3, "match_count": 5, }).execute() context = ( "\n".join([c["content"] for c in mem.data])[:2000] if mem.data else "" ) except Exception as e: logger.warning(f"Vector search failed (proceeding without memory): {e}") # ── 5. Build prompt ─────────────────────────────────────────── actual_count = len(leads) current_cac = ctx["budget"] / actual_count if actual_count > 0 else 0 som_val, sam_val = 2_900, 14_500 metrics = ( f"- Leads: {actual_count}\n" f"- Inventory items: {len(inventory)}\n" f"- Estimated CAC: ₦{int(current_cac):,}\n" f"- Budget: ₦{ctx['budget']:,}\n" f"- SAM: {sam_val:,} | SOM: {som_val:,}\n" f"- Market: {ctx['location']} / {ctx['niche']}" ) history_text = "\n".join( [f"{m['role']}: {m['content']}" for m in req.history[-6:]] )[:1500] user_prompt = ( f"CONVERSATION HISTORY:\n{history_text}\n\n" f"STRATEGIC MEMORY:\n{context}\n\n" f"LIVE METRICS:\n{metrics}\n\n" f"QUESTION: {req.message}\n\n" "Provide expert strategic analysis. End with one clear, actionable recommendation." ) # ── 6. LLM with automatic fallback ─────────────────────────── raw_answer, model_used = call_llm(get_system_prompt(fw, ctx), user_prompt) logger.info(f"LLM response from: {model_used}") # ── 7. Validate + strip framework leakage ──────────────────── answer, guardrail_warnings = validate_output(raw_answer) # ── 8. Save to chat_history (powers dashboard) ─────────────── # Required table: chat_history (user_id, query, response, pillar, # model, timestamp) try: supabase.table("chat_history").insert({ "user_id": req.user_id, "query": req.message[:500], "response": answer[:1000], "pillar": fw["pillar"], "model": model_used, "timestamp": datetime.now(timezone.utc).isoformat(), }).execute() except Exception as e: logger.warning(f"chat_history insert failed: {e}") # ── 9. Internal API log ─────────────────────────────────────── try: supabase.table("api_logs").insert({ "query": req.message[:500], "response": answer[:500], "pillar": fw["pillar"], "model": model_used, "guardrails": str(guardrail_warnings), "timestamp": datetime.now(timezone.utc).isoformat(), }).execute() except Exception as e: logger.warning(f"api_logs insert failed: {e}") # ── 10. Response — zero framework data exposed externally ───── return { "status": "success", "response": answer, # Usage info for frontend progress bar "usage": { "requests_used": usage["request_count"], "remaining": usage["remaining"], "is_premium": usage["is_premium"], "limit": FREE_LIMIT, }, # Minimal metadata — no framework names, no pillar labels "meta": { "model": model_used, "data_status": fw["status"], }, } except HTTPException as he: raise he except Exception as e: logger.critical(f"Critical failure: {e}") if SENTRY_DSN: sentry_sdk.capture_exception(e) raise HTTPException( status_code=500, detail="Operational failure in the strategic pipeline." ) # ───────────────────────────────────────────── # HISTORY ENDPOINT — powers the dashboard tab # ───────────────────────────────────────────── @app.get("/history/{user_id}") async def get_history(user_id: str, x_api_key: str = Header(None)): verify_api_key(x_api_key) try: res = ( supabase.table("chat_history") .select("query, response, pillar, model, timestamp") .eq("user_id", user_id) .order("timestamp", desc=True) .limit(50) .execute() ) return {"status": "success", "history": res.data or []} except Exception as e: logger.error(f"History fetch failed: {e}") raise HTTPException(status_code=500, detail="Could not load history.") # ───────────────────────────────────────────── # PROFILE ENDPOINT — per-user context setup # ───────────────────────────────────────────── @app.post("/profile") async def upsert_profile(req: ProfileRequest, x_api_key: str = Header(None)): verify_api_key(x_api_key) try: supabase.table("user_profiles").upsert({ "user_id": req.user_id, "location": req.location, "niche": req.niche, "budget": req.budget, "updated_at": datetime.now(timezone.utc).isoformat(), }).execute() return {"status": "success", "message": "Profile updated."} except Exception as e: logger.error(f"Profile upsert failed: {e}") raise HTTPException(status_code=500, detail="Could not save profile.") # ───────────────────────────────────────────── # HEALTH CHECK # ───────────────────────────────────────────── @app.get("/health") def health(): return { "status": "healthy", "engine": "Penafort Strategy Engine v3.0", "monitoring": "sentry" if SENTRY_DSN else "disabled", "timestamp": datetime.now(timezone.utc).isoformat(), }