import os import re import logging from datetime import datetime from typing import List, Dict, Optional, Tuple from fastapi import FastAPI, HTTPException, BackgroundTasks from fastapi.responses import PlainTextResponse from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from sentence_transformers import SentenceTransformer from google import genai from groq import Groq from supabase import create_client, Client # ------------------------------------------------------------------ # Configuration # ------------------------------------------------------------------ GROQ_API_KEY = os.environ.get("GROQ_API_KEY") GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY") SUPABASE_URL = os.environ.get("SUPABASE_URL") SUPABASE_KEY = os.environ.get("SUPABASE_KEY") WHATSAPP_NUMBER = os.environ.get("WHATSAPP_NUMBER", "+2347067666205") PRODUCTION_HOST = os.environ.get("PRODUCTION_HOST", "https://YOUR-SPACE.hf.space") SIMILARITY_THRESHOLD = float(os.environ.get("SIMILARITY_THRESHOLD", "0.15")) TEMPERATURE = float(os.environ.get("TEMPERATURE", "0.2")) TOP_K = int(os.environ.get("TOP_K", "12")) ALLOWED_ORIGINS = os.environ.get( "ALLOWED_ORIGINS", "https://kevs-ono-portfolio.netlify.app,http://localhost:3000,http://localhost:8000" ).split(",") # Stronger embedder (768 dimensions) EMBEDDER_MODEL = "all-mpnet-base-v2" # ------------------------------------------------------------------ # Pricing keywords & deterministic contact # ------------------------------------------------------------------ PRICING_KEYWORDS = re.compile( r'\b(how much|cost|price|pricing|retainer|fee|quote|bill|charge|what.*pay|budget)\b', re.IGNORECASE ) CONTACT_KEYWORDS = re.compile( r'\b(phone|contact|whatsapp|number|reach|call|email|get in touch)\b', re.IGNORECASE ) # Fallback pricing (only used if DB fails) FALLBACK_PRICING = [ {"service_key": "inventory_system", "service_name": "Inventory Management System", "price_naira": None, "price_range_low": 450000, "price_range_high": 750000, "is_one_time": True, "note": "One-time setup."}, {"service_key": "erp_design", "service_name": "ERP Design & Integration", "price_naira": None, "price_range_low": 600000, "price_range_high": 1200000, "is_one_time": True, "note": "One-time setup."}, ] # ------------------------------------------------------------------ # API models # ------------------------------------------------------------------ class ChatRequest(BaseModel): message: str class ManualChunkRequest(BaseModel): content: str source_url: str = "manual" class DeleteChunkRequest(BaseModel): chunk_id: int # ------------------------------------------------------------------ # App & middleware # ------------------------------------------------------------------ app = FastAPI(title="Kevs Portfolio + Services AI Assistant") app.add_middleware( CORSMiddleware, allow_origins=ALLOWED_ORIGINS, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # ------------------------------------------------------------------ # Globals # ------------------------------------------------------------------ embedder: Optional[SentenceTransformer] = None supabase: Optional[Client] = None pricing_cache: List[Dict] = [] # ------------------------------------------------------------------ # Greeting & small-talk # ------------------------------------------------------------------ GREETINGS = { "hello", "hi", "hey", "hiya", "howdy", "sup", "what's up", "whats up", "good morning", "good afternoon", "good evening", "good day", "greetings", "yo", "hello there", "hi there", "hey there", } GREETING_RESPONSE = ( "Hello! I'm Kevs AI β Michael Onoriode's portfolio assistant. π\n\n" "I can help you with:\n" "β’ Michael's AI & automation systems (inventory intelligence, AI concierge, ERP, workflow automation)\n" "β’ His skills β Growth Engineering, AI systems, marketing infrastructure, paid ads, SEO, analytics\n" "β’ Work experience β Kevs Digital, Penafort Energy, MuzoScents, Dispatch Hub\n" "β’ Services & pricing offered by Kevs Digital\n" "β’ How to hire or work with Michael\n\n" "What would you like to know?" ) THANKS_PHRASES = {"thanks", "thank you", "thank you so much", "thx", "ty", "cheers"} THANKS_RESPONSE = ( "You're welcome! Feel free to ask anything else about Michael's work, " "projects, or services. You can also reach him directly via the WhatsApp button. π" ) GOODBYE_PHRASES = {"bye", "goodbye", "see you", "see ya", "later", "ciao", "take care"} GOODBYE_RESPONSE = ( "Thanks for stopping by! If you'd like to discuss a project with Michael, " "hit the WhatsApp button anytime. Have a great day! π" ) def detect_smalltalk(message: str) -> Optional[str]: clean = message.strip().lower().rstrip("!.,?") if clean in GREETINGS: return GREETING_RESPONSE if clean in THANKS_PHRASES: return THANKS_RESPONSE if clean in GOODBYE_PHRASES: return GOODBYE_RESPONSE return None def get_deterministic_contact(user_query: str) -> Optional[str]: if CONTACT_KEYWORDS.search(user_query): return ( f"Michael's WhatsApp number is {WHATSAPP_NUMBER}. " f"Click the WhatsApp button (π±) in this chat to message him directly.\n\n" f"You can also email him at mickevsono@gmail.com." ) return None # ------------------------------------------------------------------ # Pricing (from DB cache) # ------------------------------------------------------------------ async def load_pricing_from_db() -> List[Dict]: try: db = get_supabase() result = db.table("service_pricing").select("*").eq("is_active", True).execute() return result.data except Exception as e: logger.error(f"Failed to load pricing from DB: {e}") return [] def get_deterministic_pricing(user_query: str) -> Optional[str]: global pricing_cache if not PRICING_KEYWORDS.search(user_query): return None query_lower = user_query.lower() response_lines = [] matched = False pricing_data = pricing_cache if pricing_cache else FALLBACK_PRICING keyword_to_service = { "inventory": "inventory_system", "expiry": "inventory_system", "erp": "erp_design", "concierge": "ai_concierge", "chatbot": "ai_concierge", "website": "website_design", "site": "website_design", "audit": "business_systems_audit", "retainer": "monthly_systems_management", "monthly": "monthly_systems_management", "workflow": "ai_workflow_automation", "automation": "ai_workflow_automation", } service_key = None for kw, key in keyword_to_service.items(): if kw in query_lower: service_key = key matched = True break if service_key: service = next((s for s in pricing_data if s.get("service_key") == service_key), None) if service: desc = service.get("service_name", "") price_naira = service.get("price_naira") low = service.get("price_range_low") high = service.get("price_range_high") is_one_time = service.get("is_one_time", True) note = service.get("note", "") if price_naira: price_str = f"β¦{price_naira:,}" elif low and high: price_str = f"β¦{low:,} β β¦{high:,}" else: price_str = "custom quote required" period = "one-time setup" if is_one_time else "per month" response_lines.append(f"{desc} β {price_str} ({period})") if note: response_lines.append(note) else: matched = False if not matched: response_lines.append("Here are Michael's standard pricing ranges for common services:\n") for s in pricing_data: name = s.get("service_name", "") price_naira = s.get("price_naira") low = s.get("price_range_low") high = s.get("price_range_high") if price_naira: price_str = f"β¦{price_naira:,}" elif low and high: price_str = f"β¦{low:,} β β¦{high:,}" else: continue is_one_time = s.get("is_one_time", True) period = "(one-time)" if is_one_time else "(per month)" response_lines.append(f"β’ {name} β {price_str} {period}") matched = True if matched: response_lines.append("\nπ For a precise quote tailored to your specific needs, click the WhatsApp button (π±) in this chat to contact Michael directly.") return "\n".join(response_lines) return None # ------------------------------------------------------------------ # Supabase & embedder # ------------------------------------------------------------------ def get_supabase() -> Client: global supabase if supabase is None: if not SUPABASE_URL or not SUPABASE_KEY: raise RuntimeError("SUPABASE_URL and SUPABASE_KEY environment variables are required.") supabase = create_client(SUPABASE_URL, SUPABASE_KEY) return supabase def get_embedder() -> SentenceTransformer: global embedder if embedder is None: logger.info(f"Loading stronger embedder: {EMBEDDER_MODEL}...") embedder = SentenceTransformer(EMBEDDER_MODEL) logger.info("Embedder loaded.") return embedder # ------------------------------------------------------------------ # Vector search # ------------------------------------------------------------------ def vector_search(query: str, top_k: int = TOP_K) -> List[Dict]: model = get_embedder() q_emb = model.encode([query], convert_to_numpy=True)[0].tolist() db = get_supabase() result = db.rpc("match_portfolio_chunks", { "query_embedding": q_emb, "match_threshold": SIMILARITY_THRESHOLD, "match_count": top_k, }).execute() return result.data or [] # ------------------------------------------------------------------ # LLM reply with grounding # ------------------------------------------------------------------ async def get_grounded_reply_with_sources(user_message: str, relevant_chunks: List[Dict]) -> Tuple[str, List[str]]: if not relevant_chunks: escalation_msg = ( "I couldn't find specific information about that in Michael's knowledge base. " "Please click the WhatsApp button (π±) in this chat to contact Michael directly.\n\n" "You can also ask me about his AI systems, skills, experience, or services." ) return escalation_msg, [] context_parts = [] sources = [] for idx, chunk in enumerate(relevant_chunks, start=1): content = chunk.get("content", "") src_url = chunk.get("source_url", "manual") sources.append(src_url) context_parts.append(f"[{idx}] {content}\n(Source: {src_url})") context = "\n\n---\n\n".join(context_parts) system_prompt = f"""You are Kevs AI β the intelligent portfolio assistant for Michael Onoriode (Business Systems & Operational Intelligence Analyst, founder of Kevs Digital). IDENTITY & TONE: - Warm, confident, professional. Speak in third person about Michael. - Always cite sources using [number] from the provided context. STRICT GROUNDING RULES: 1. ONLY use the provided context below. Never invent facts, prices, or projects. 2. When answering, include inline citations like [1], [2] referencing the numbered chunks. 3. If the question is about pricing, do NOT answer β the system already handled pricing deterministically. 4. For broad skill questions, retrieve ALL skill categories from context (AI & Systems, Growth & Marketing, Technical, Analytics, Creative, Frameworks) and synthesise them into a grouped answer. Do not limit to one category. 5. For project questions, include problem, tech stack, outcome if available. 6. If partially covered, answer what you can and suggest WhatsApp for details. 7. Never invent URLs, names, or dates. 8. End with "π Want a tailored quote? β WhatsApp" only if the user seems interested in hiring. CONTEXT (with sources): {context} USER QUESTION: {user_message} ANSWER (with inline citations, well-formatted):""" reply = "" if GROQ_API_KEY: try: groq_client = Groq(api_key=GROQ_API_KEY) resp = groq_client.chat.completions.create( messages=[{"role": "user", "content": system_prompt}], model="openai/gpt-oss-120b", temperature=TEMPERATURE, max_tokens=600, ) reply = resp.choices[0].message.content except Exception as e: logger.warning(f"Groq failed: {e}") if not reply and GEMINI_API_KEY: try: client = genai.Client(api_key=GEMINI_API_KEY) response = client.models.generate_content( model="gemini-2.0-flash", contents=system_prompt, ) reply = response.text except Exception as e: logger.error(f"Gemini failed: {e}") if not reply: reply = ( "I'm experiencing technical difficulties. " "Please click the WhatsApp button (π±) in this chat to reach Michael directly." ) if sources: unique_sources = list(dict.fromkeys(sources)) source_footer = "\n\n**Sources:**\n" + "\n".join(f"β’ {src}" for src in unique_sources) reply += source_footer return reply, sources # ------------------------------------------------------------------ # Manual knowledge management # ------------------------------------------------------------------ async def add_manual_chunk(content: str, source_url: str = "manual"): model = get_embedder() emb = model.encode([content], convert_to_numpy=True)[0].tolist() db = get_supabase() db.table("portfolio_knowledge").insert({ "source_url": source_url, "content": content, "embedding": emb, }).execute() logger.info(f"Manually added chunk: {content[:60]}...") async def delete_chunk(chunk_id: int): db = get_supabase() db.table("portfolio_knowledge").delete().eq("id", chunk_id).execute() logger.info(f"Deleted chunk ID {chunk_id}") async def list_chunks(source_url: Optional[str] = None, limit: int = 50) -> List[Dict]: db = get_supabase() query = db.table("portfolio_knowledge").select("id, source_url, content, created_at").limit(limit) if source_url: query = query.eq("source_url", source_url) return query.execute().data or [] # ------------------------------------------------------------------ # Admin endpoint: reβembed all manual chunks with the new model # ------------------------------------------------------------------ @app.post("/api/admin/reembed") async def reembed_manual_chunks(background_tasks: BackgroundTasks): """Re-embed all chunks with source_url = 'manual' using the current embedder.""" async def reembed(): logger.info("Starting re-embedding of manual chunks...") db = get_supabase() model = get_embedder() # Fetch all manual chunks chunks = db.table("portfolio_knowledge").select("id, content").eq("source_url", "manual").execute() data = chunks.data if not data: logger.info("No manual chunks found.") return logger.info(f"Found {len(data)} manual chunks to re-embed.") for chunk in data: chunk_id = chunk["id"] content = chunk["content"] emb = model.encode([content], convert_to_numpy=True)[0].tolist() db.table("portfolio_knowledge").update({"embedding": emb}).eq("id", chunk_id).execute() if chunk_id % 10 == 0: logger.info(f"Re-embedded {chunk_id}/{len(data)}") logger.info(f"Re-embedding complete. Updated {len(data)} chunks.") background_tasks.add_task(reembed) return {"message": "Re-embedding started. This may take a few minutes."} # ------------------------------------------------------------------ # API endpoints # ------------------------------------------------------------------ @app.post("/api/chat") async def chat(req: ChatRequest): try: smalltalk = detect_smalltalk(req.message) if smalltalk: return {"response": smalltalk} contact_answer = get_deterministic_contact(req.message) if contact_answer: return {"response": contact_answer} pricing_answer = get_deterministic_pricing(req.message) if pricing_answer: return {"response": pricing_answer} results = vector_search(req.message, top_k=TOP_K) if not results: escalation = ( "I don't have specific information on that in my knowledge base. " "Please click the WhatsApp button (π±) in this chat to contact Michael directly.\n\n" "I can help with his AI systems, skills, work experience, and services." ) return {"response": escalation} reply, _ = await get_grounded_reply_with_sources(req.message, results) return {"response": reply} except Exception as e: logger.exception(f"Chat error: {e}") raise HTTPException(status_code=500, detail="Internal error during search.") @app.post("/api/knowledge/add") async def add_knowledge(req: ManualChunkRequest): try: await add_manual_chunk(req.content, req.source_url) return {"message": "Knowledge entry added successfully."} except Exception as e: logger.exception(f"Add knowledge error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.delete("/api/knowledge/delete") async def delete_knowledge(req: DeleteChunkRequest): try: await delete_chunk(req.chunk_id) return {"message": f"Chunk {req.chunk_id} deleted."} except Exception as e: logger.exception(f"Delete error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/knowledge/list") async def list_knowledge(source_url: Optional[str] = None, limit: int = 50): try: chunks = await list_chunks(source_url, limit) return {"count": len(chunks), "chunks": chunks} except Exception as e: logger.exception(f"List error: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.get("/api/status") async def status(): try: db = get_supabase() count = db.table("portfolio_knowledge").select("id", count="exact").execute().count or 0 except Exception: count = -1 return { "knowledge_chunks_in_db": count, "embedder_loaded": embedder is not None, "embedder_model": EMBEDDER_MODEL, "supabase_connected": supabase is not None, "pricing_cache_entries": len(pricing_cache), "threshold": SIMILARITY_THRESHOLD, "top_k": TOP_K, "temperature": TEMPERATURE, "timestamp": datetime.now().isoformat(), } @app.post("/api/admin/refresh-pricing") async def refresh_pricing(background_tasks: BackgroundTasks): async def reload(): global pricing_cache pricing_cache = await load_pricing_from_db() logger.info(f"Pricing cache refreshed. {len(pricing_cache)} entries loaded.") background_tasks.add_task(reload) return {"message": "Pricing cache refresh started."} # ------------------------------------------------------------------ # Chat widget JS (full with green WhatsApp button) # ------------------------------------------------------------------ @app.get("/chat-widget.js", response_class=PlainTextResponse) async def widget_js(): return f""" (function() {{ const API_URL = '{PRODUCTION_HOST}'; const WHATSAPP_NUMBER = '{WHATSAPP_NUMBER}'; if (document.getElementById('kevs-chat-root')) return; const root = document.createElement('div'); root.id = 'kevs-chat-root'; document.body.appendChild(root); root.innerHTML = `