Update api.py
Browse files6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404142434411 unmodified lines56575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921933 unmodified lines1971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643656 unmodified linesimport osimport loggingfrom time import timefrom datetime import datetime # ✅ FIXED: Added 'import'from enum import Enum# --- LOGGING SETUP ---logging.basicConfig(level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# --- INIT ---app = FastAPI()# CORS middlewareapp.add_middleware(CORSMiddleware,allow_origins=["https://mzfunnel.netlify.app"], # Your Netlify URLallow_credentials=True,allow_methods=["*"],allow_headers=["*"],)# --- CONFIG & CLIENTS ---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")# Validateif not all([SUPABASE_URL, SUPABASE_KEY, GEMINI_API_KEY, GROQ_API_KEY, API_SECRET_KEY]):logger.error("Missing required API credentials!")raise ValueError("Missing required environment variables")supabase = create_client(SUPABASE_URL, SUPABASE_KEY)11 unmodified linesclient_requests[client_id] = [t for t in client_requests[client_id] if now - t < WINDOW]else:client_requests[client_id] = []if len(client_requests[client_id]) >= RATE_LIMIT:raise HTTPException(status_code=429, detail=f"Rate limit exceeded. Max {RATE_LIMIT} requests per {WINDOW} seconds.")client_requests[client_id].append(now)def verify_api_key(x_api_key: str = Header(None)):if not x_api_key:raise HTTPException(status_code=401, detail="API key required")if x_api_key != API_SECRET_KEY:raise HTTPException(status_code=401, detail="Invalid API key")return True# --- ENUM FOR ANALYSIS MODE ---class AnalysisMode(str, Enum):CUSTOMER = "customer"MARKET = "market"HYBRID = "hybrid"# --- REQUEST MODEL ---class ChatRequest(BaseModel):message: strhistory: list = []budget: int = 500000analysis_mode: AnalysisMode = AnalysisMode.HYBRID# --- CONSTANTS ---SOM_VAL = 2900SAM_VAL = 14500# --- SYSTEM PROMPTS FOR EACH MODE ---def get_system_prompt(mode: AnalysisMode) -> str:"""Returns different system prompts based on analysis mode"""if mode == AnalysisMode.CUSTOMER:return """You are the Penafort **Customer Analysis Specialist**.Your FOCUS is on understanding the CUSTOMER:- Who are they? (Demographics, psychographics)- Why do they buy? (Jobs to be done, pain points, gains)- How do they experience our brand? (Customer journey mapping)- What is their satisfaction level? (NPS, retention analysis)FRAMEWORKS YOU USE:- Value Proposition Canvas- Customer Journey Mapping- Jobs-to-be-Done (JTBD)- NPS & Retention Analysis- Audience SegmentationYOUR RULE:- Always answer from the customer's perspective- Use phrases like "The customer needs..." or "Based on student behavior..."- If data is missing, ask: "To give you better customer insight, could you share [specific data needed]?"- Focus on Lagos/LASU student contextRemember: You are NOT analyzing internal operations or competition. You are the VOICE OF THE CUSTOMER."""elif mode == AnalysisMode.MARKET:return """You are the Penafort **Market Analysis Specialist**.Your FOCUS is on the COMPETITIVE LANDSCAPE:- Where do we stand vs competitors? (SWOT, VRIO)- What are market trends? (PESTLE)- How do we grow market share? (Ansoff Matrix, BCG)- Where is the opportunity? (Blue Ocean)FRAMEWORKS YOU USE:- SWOT Analysis (Strengths, Weaknesses, Opportunities, Threats)- VRIO (Value, Rarity, Imitability, Organization)- PESTLE (Political, Economic, Social, Tech, Legal, Environmental)- Ansoff Matrix (Market penetration, development, product development, diversification)- BCG Matrix (Stars, Cash Cows, Question Marks, Dogs)- Blue Ocean StrategyYOUR RULE:- Always analyze from market/competition perspective- Use phrases like "The market indicates..." or "Compared to competitors..."- If data is missing, ask: "To give you better market insight, could you share [specific competitor data]?"- Focus on Lagos fragrance market contextRemember: You are the MARKET INTELLIGENCE expert, not focused on internal customers."""else: # HYBRID modereturn """You are the Penafort **Chief Strategy Officer** - Hybrid Analysis Mode.You have FULL ACCESS to BOTH:1. CUSTOMER INSIGHTS (Journey, JTBD, NPS, Segmentation)2. MARKET INSIGHTS (SWOT, VRIO, PESTLE, Ansoff, BCG, Blue Ocean)Your role is to SYNTHESIZE:- Connect customer needs to market opportunities- Align internal capabilities with external threats- Create integrated strategic recommendationsYOUR PROCESS:1. First, understand the customer perspective2. Second, analyze the market landscape3. Third, synthesize into actionable strategyYOUR RULE:- Always bridge customer and market perspectives- Use phrases like "Students need X, and the market gap in Y suggests we should..."- If data is missing from either domain, ask for it specifically- Prioritize locally relevant solutions for Lagos/LASU marketRemember: You are the INTEGRATED STRATEGIST, connecting dots between customers, competition, and capabilities."""# --- API ENDPOINT ---@app.post("/chat")def chat(req: ChatRequest, x_api_key: str = Header(None)):# Step 1: Authenticateverify_api_key(x_api_key)# Step 2: Rate limitcheck_rate_limit(x_api_key)# Step 3: Log request with modelogger.info(f"Chat request - Mode: {req.analysis_mode.value}, Message: {req.message[:100]}")try:# Fetch dataleads_res = supabase.table("leads").select("*").execute()leads = leads_res.data or []actual_count = len(leads)current_cac = req.budget / actual_count if actual_count > 0 else 0# Fetch inventory for market analysisinventory_res = supabase.table("inventory").select("*").execute()inventory_data = inventory_res.data or []# Fetch strategic memories (vector search)emb = genai.embed_content(model="models/gemini-embedding-2-preview",content=req.message,3 unmodified linesres = supabase.rpc('match_memories', {'query_embedding': emb,'match_threshold': 0.3,'match_count': 5}).execute()context = "\n".join([c['content'] for c in res.data]) if res.data else ""# Enhanced business data based on modecustomer_metrics = f"""CUSTOMER DATA:- Total Leads: {actual_count}- Average Monthly Spend: ₦15,000 per student- Pipeline Value: ₦{actual_count * 15000:,}- Current CAC: ₦{int(current_cac):,}- Target CPA: ₦{int(2000000/SOM_VAL):,}"""market_metrics = f"""MARKET DATA:- SAM (Serviceable Available Market): {SAM_VAL}- SOM (Serviceable Obtainable Market): {SOM_VAL}- Market Penetration: {(actual_count/SAM_VAL)*100:.1f}%- Budget: ₦{req.budget:,}- Inventory Items: {len(inventory_data)}"""# Conversation historyhistory_text = "\n".join([f"{m['role']}: {m['content']}" for m in req.history[-6:]])# Build user prompt based on modeif req.analysis_mode == AnalysisMode.CUSTOMER:user_prompt = f"""You are in **CUSTOMER ANALYSIS MODE**.CONVERSATION HISTORY:{history_text}RETRIEVED STRATEGIC CONTEXT:{context}CUSTOMER METRICS:{customer_metrics}CUSTOMER QUESTION:{req.message}Provide a customer-focused analysis answering from the student's perspective."""elif req.analysis_mode == AnalysisMode.MARKET:user_prompt = f"""You are in **MARKET ANALYSIS MODE**.CONVERSATION HISTORY:{history_text}RETRIEVED STRATEGIC CONTEXT:{context}MARKET METRICS:{market_metrics}MARKET QUESTION:{req.message}Provide a market-focused analysis looking at competition and market positioning."""else: # HYBRIDuser_prompt = f"""You are in **HYBRID ANALYSIS MODE** (Customer + Market Integration).CONVERSATION HISTORY:{history_text}RETRIEVED STRATEGIC CONTEXT:{context}CUSTOMER METRICS:{customer_metrics}MARKET METRICS:{market_metrics}INTEGRATED QUESTION:{req.message}Provide a SYNTHESIZED analysis that connects customer needs to market opportunities."""# Generate AI responseresponse = groq_client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "system", "content": get_system_prompt(req.analysis_mode)},{"role": "user", "content": user_prompt}],temperature=0.3)answer = response.choices[0].message.content# Log to Supabasetry:supabase.table("api_logs").insert({"query": req.message[:500],"response": answer[:500],"budget": req.budget,"leads_count": actual_count,"analysis_mode": req.analysis_mode.value,"timestamp": datetime.now().isoformat()}).execute()except Exception as log_err:logger.warning(f"Failed to log to Supabase: {str(log_err)}")return {"response": answer,"analysis_mode": req.analysis_mode.value,"metrics": {"leads": actual_count,"cac": current_cac,"penetration_rate": (actual_count/SAM_VAL)*100 if SAM_VAL > 0 else 0}}except HTTPException:raiseexcept Exception as e:logger.error(f"Error: {str(e)}", exc_info=True)return {"response": "I'm having trouble analyzing right now. Please try again in a moment.","analysis_mode": req.analysis_mode.value if hasattr(req, 'analysis_mode') else "unknown","metrics": {}}# --- HEALTH CHECK ---@app.get("/health")def health():return {"status": "healthy","timestamp": datetime.now().isoformat(),"active_clients": len(client_requests)}# --- MODES INFO ENDPOINT ---@app.get("/modes")def get_modes():"""Returns available analysis modes for frontend"""return {"modes": [{"id": "customer","name": "👥 Customer Analysis","description": "Focus on student needs, journey, and experience","frameworks": ["Value Proposition", "Journey Mapping", "JTBD", "NPS"]},{"id": "market","name": "🏪 Market Analysis","description": "Focus on competition, positioning, and growth","frameworks": ["SWOT", "VRIO", "PESTLE", "Ansoff", "BCG", "Blue Ocean"]},{"id": "hybrid","name": "🔗 Hybrid Strategy","description": "Integrated customer + market strategic insights","frameworks": ["All frameworks + Synthesis"]}]}6 unmodified lines789101112131415161718192021222324252627282930313233343536373811 unmodified lines50515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571583 unmodified lines1621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392406 unmodified linesimport osimport loggingfrom time import timefrom datetime import datetimefrom typing import Optional# --- LOGGING ---logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')logger = logging.getLogger(__name__)# --- 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)11 unmodified linesclient_requests[client_id] = [t for t in client_requests[client_id] if now - t < WINDOW]else:client_requests[client_id] = []if len(client_requests[client_id]) >= RATE_LIMIT:raise HTTPException(status_code=429, detail=f"Rate limit exceeded")client_requests[client_id].append(now)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 MODEL ---class ChatRequest(BaseModel):message: strhistory: list = []budget: int = 500000location: Optional[str] = "Lagos, LASU"niche: Optional[str] = "student fragrance market"# --- INTELLIGENT FRAMEWORK OPTIMIZER ---def optimize_framework_selection(has_leads: bool, has_inventory: bool, user_query: str):"""Determines optimal framework based on available data"""# Customer-focused queriesif any(word in user_query.lower() for word in ["who", "customer", "student", "buy", "need"]):if has_leads:return {"mode": "CUSTOMER_ANALYSIS","status": "READY","pillar": 1,"frameworks": ["Audience Segmentation", "CJM", "Value Prop Canvas", "JTBD", "NPS", "PMF"],"message": "Customer analysis ready - lead data available"}return {"mode": "CUSTOMER_ANALYSIS","status": "DATA_MISSING","pillar": 1,"frameworks": ["Audience Segmentation", "CJM", "Value Prop Canvas", "JTBD", "NPS", "PMF"],"message": "Customer analysis requires lead data"}# Market-focused queriesif any(word in user_query.lower() for word in ["competitor", "market", "swot", "vrio", "bcg"]):return {"mode": "MARKET_ANALYSIS","status": "READY","pillar": 2,"frameworks": ["SWOT", "VRIO", "Value Chain", "BCG Matrix", "Ansoff", "Blue Ocean", "PESTLE"],"message": "Market analysis active - using competitive intelligence"}# Default hybriddata_quality = "HIGH" if has_leads and has_inventory else "MEDIUM" if (has_leads or has_inventory) else "LOW"return {"mode": "HYBRID_OPTIMIZATION","status": "READY","data_quality": data_quality,"pillar": 3,"frameworks": ["Cross-functional optimization", "Resource allocation", "Strategic synthesis"],"message": f"Hybrid optimization (Data Quality: {data_quality})"}def get_system_prompt(framework_result, location, niche):"""Generates dynamic system prompt"""pillar_goals = {1: "Aligning product-market fit through deep customer understanding",2: "Exploiting competitive advantages and identifying market gaps",3: "Cross-functional optimization and strategic resource allocation"}return f"""You are the Penafort Strategy Engine, a specialist in Prescriptive Analytics and Operations Research.### PILLAR {framework_result['pillar']}: {framework_result['mode'].replace('_', ' ').title()}- **Selected Frameworks:** {', '.join(framework_result['frameworks'][:3])}- **Goal:** {pillar_goals[framework_result['pillar']]}### CORE OPERATING RULES:1. **MARKET PERSPECTIVE:** Use phrases like "The market indicates..." or "Compared to competitors..."2. **DATA INTEGRITY:** If specific data is missing, ask: "To provide deeper insight, could you share [specific data needed]?"3. **DYNAMIC LOCALIZATION:** Adapt your analysis to {location} - specifically the {niche}.4. **OPTIMIZATION:** Always select the framework requiring the least assumptions based on available data.{framework_result['message']}"""# --- API ENDPOINT ---@app.post("/chat")def chat(req: ChatRequest, x_api_key: str = Header(None)):verify_api_key(x_api_key)check_rate_limit(x_api_key)logger.info(f"Request: {req.message[:100]} | Location: {req.location}")try:# Fetch dataleads = supabase.table("leads").select("*").execute().data or []inventory = supabase.table("inventory").select("*").execute().data or []has_leads = len(leads) > 0has_inventory = len(inventory) > 0# Step 1: Intelligently select frameworkframework_result = optimize_framework_selection(has_leads, has_inventory, req.message)# Step 2: Vector searchemb = genai.embed_content(model="models/gemini-embedding-2-preview",content=req.message,3 unmodified linesres = supabase.rpc('match_memories', {'query_embedding': emb,'match_threshold': 0.3,'match_count': 3}).execute()context = "\n".join([c['content'] for c in res.data]) if res.data else ""# Step 3: Prepare metricsactual_count = len(leads)current_cac = req.budget / actual_count if actual_count > 0 else 0SOM_VAL, SAM_VAL = 2900, 14500metrics = f"""Data Status:- Leads Available: {actual_count}- Inventory Items: {len(inventory)}- Current CAC: ₦{int(current_cac):,}- Framework: {framework_result['mode']}"""history_text = "\n".join([f"{m['role']}: {m['content']}" for m in req.history[-6:]])# Step 4: Generate responseresponse = groq_client.chat.completions.create(model="llama-3.3-70b-versatile",messages=[{"role": "system", "content": get_system_prompt(framework_result, req.location, req.niche)},{"role": "user", "content": f"""CONVERSATION:{history_text}RETRIEVED CONTEXT:{context}METRICS:{metrics}FRAMEWORK STATUS:{framework_result['message']}QUESTION:{req.message}Provide your strategic analysis using the selected framework."""}],temperature=0.3)answer = response.choices[0].message.content# Logtry:supabase.table("api_logs").insert({"query": req.message[:500],"response": answer[:500],"framework": framework_result['mode'],"timestamp": datetime.now().isoformat()}).execute()except:passreturn {"response": answer,"framework_used": framework_result['mode'],"data_quality": framework_result.get('data_quality', 'UNKNOWN'),"metrics": {"leads": actual_count, "cac": current_cac}}except Exception as e:logger.error(f"Error: {str(e)}")return {"response": "System error. Please try again.", "framework_used": "ERROR"}# --- HEALTH CHECK ---@app.get("/health")def health():return {"status": "healthy", "timestamp": datetime.now().isoformat()}
api.py+115-240