Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456726 unmodified lines34353637383915 unmodified lines5556575859606134 unmodified lines9697989910010113 unmodified lines11511611711811912012121 unmodified lines14314414514614714814915015125 unmodified lines1771781791801811821831841851861871882 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652663 unmodified lines2702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183191 unmodified line32132232332432532632732832933033133233333433533651 unmodified lines388389390391392393394395396397113 unmodified lines5115125135145155165178 unmodified lines52652752852953053153210 unmodified lines543544545546547548549550551import osimport loggingfrom datetime import datetimefrom typing import List, Dict, Optionalfrom fastapi import FastAPI, HTTPException, BackgroundTasksfrom fastapi.responses import PlainTextResponsefrom fastapi.middleware.cors import CORSMiddleware26 unmodified lines"https://kevs-ono-portfolio.netlify.app,http://localhost:3000,http://localhost:8000").split(",")# ------------------------------------------------------------------# App & middleware# ------------------------------------------------------------------15 unmodified linessupabase: Optional[Client] = None# ------------------------------------------------------------------# Greeting & small-talk detection# ------------------------------------------------------------------GREETINGS = {"hello", "hi", "hey", "hiya", "howdy", "sup", "what's up", "whats up",34 unmodified linesreturn GOODBYE_RESPONSEreturn None# ------------------------------------------------------------------# Supabase & embedder# ------------------------------------------------------------------13 unmodified linesreturn embedder# ------------------------------------------------------------------# HTML fetching & chunking# ------------------------------------------------------------------async def fetch_html(url: str) -> str:async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:21 unmodified lineslogger.info(f"Extracted {len(unique)} chunks from {url}")return unique# ------------------------------------------------------------------# Upsert chunks into Supabase# ------------------------------------------------------------------async def upsert_chunks_to_supabase(chunks: List[str], source_url: str):db = get_supabase()model = get_embedder()25 unmodified lineslogger.info("Knowledge base refresh complete.")# ------------------------------------------------------------------# Vector search via Supabase pgvector# ------------------------------------------------------------------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,2 unmodified linesreturn result.data or []# ------------------------------------------------------------------# 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 []# ------------------------------------------------------------------# LLM β Groq primary, Gemini fallback# ------------------------------------------------------------------async def get_grounded_reply(user_message: str, relevant_chunks: List[str]) -> str:if not relevant_chunks:return ("I don't have specific information on that in my knowledge base. ""Here's what I can help with:\n\n""β’ Michael's AI & automation systems\n""β’ His skills across Growth Engineering, AI, marketing, and analytics\n""β’ Work experience at Kevs Digital, Penafort Energy, MuzoScents, and Dispatch Hub\n""β’ Services and pricing from Kevs Digital\n""β’ How to hire or work with Michael\n\n""You can also reach Michael directly via the WhatsApp button.")context = "\n\n---\n\n".join(relevant_chunks)system_prompt = f"""You are Kevs AI β the intelligent portfolio assistant for Michael Onoriode (also known as Kevs Ono), a Business Systems & Operational Intelligence Analyst and founder of Kevs Digital.IDENTITY & TONE:- You represent Michael's professional profile, skills, systems, and services- Be warm, confident, and professional β like a knowledgeable colleague- Speak in third person about Michael or on his behalfSTRICT GROUNDING RULES:1. ONLY use the provided context below to answer. Never use external knowledge or invent facts.2. For broad skill questions (e.g. "tell me about his skills"), synthesise ALL relevant skill categories from context β AI & Systems, Growth & Marketing, Technical, Analytics & Tools, Creative β into a complete grouped answer. Do not limit to one category.3. For project questions, include the business problem solved, the tech stack, and the outcome where available in context.4. For pricing questions, give the specific figures from context and suggest WhatsApp for custom scoping.5. For contact or hiring questions, provide email (mickevsono@gmail.com), WhatsApp (+2347067666205), and portfolio URL.6. If a question is partially covered, answer what you can from context then offer WhatsApp for details.7. If genuinely not covered in context, say so clearly and list what topics you can help with.8. Never invent URLs, prices, project names, or dates not in the context.9. Format responses clearly β use bullet points or short paragraphs for readability.10. Keep responses focused β comprehensive but not exhaustive.CONTEXT FROM KNOWLEDGE BASE:{context}USER QUESTION: {user_message}ANSWER (strictly from context, well-formatted):"""# Primary: Groq Llama 3.3 70Bif GROQ_API_KEY:try:groq_client = Groq(api_key=GROQ_API_KEY)3 unmodified linestemperature=TEMPERATURE,max_tokens=600,)return resp.choices[0].message.contentexcept Exception as e:logger.warning(f"Groq 70B failed: {e} β trying 8B fallback")try:resp = groq_client.chat.completions.create(messages=[{"role": "user", "content": system_prompt}],model="llama3-8b-8192",temperature=TEMPERATURE,max_tokens=600,)return resp.choices[0].message.contentexcept Exception as e2:logger.error(f"Groq 8B failed: {e2}")# Fallback: Gemini 2.0 Flash (updated SDK)if 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,)return response.textexcept Exception as e:logger.error(f"Gemini fallback failed: {e}")return ("I'm having technical difficulties right now. ""Please use the WhatsApp button to reach Michael directly β ""he typically responds within a few hours.")# ------------------------------------------------------------------# API models# ------------------------------------------------------------------class ChatRequest(BaseModel):message: strclass ManualChunkRequest(BaseModel):content: strsource_url: str = "manual"class DeleteChunkRequest(BaseModel):chunk_id: int# ------------------------------------------------------------------# API endpoints1 unmodified line@app.post("/api/chat")async def chat(req: ChatRequest):try:# 1. Handle greetings and small talk without hitting the DBsmalltalk = detect_smalltalk(req.message)if smalltalk:return {"response": smalltalk}# 2. Vector search + grounded LLM replyresults = vector_search(req.message, top_k=TOP_K)chunks = [r["content"] for r in results]logger.info(f"Query: '{req.message[:60]}' β {len(chunks)} chunks retrieved (threshold={SIMILARITY_THRESHOLD})")reply = await get_grounded_reply(req.message, chunks)return {"response": reply}except Exception as e:51 unmodified lines}# ------------------------------------------------------------------# Chat widget JS# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget_js():return f"""(function() {{const API_URL = '{PRODUCTION_HOST}';113 unmodified lineswindow.open(`https://wa.me/${{WHATSAPP_NUMBER.replace('+','')}}?text=Hello%20Michael%2C%20I%20visited%20your%20portfolio%20and%20have%20a%20question.`, '_blank');}});// Show unread badge after 8 seconds to nudge visitorssetTimeout(() => {{if (!opened) {{unread.style.display = 'flex';8 unmodified lines# ------------------------------------------------------------------@app.on_event("startup")async def startup():logger.info("Starting Kevs Portfolio AI Assistant...")get_embedder()try:db = get_supabase()10 unmodified lines@app.get("/")async def root():return {"service": "Kevs Portfolio + Services AI Assistant","status": "active","backend": "Supabase pgvector + Groq Llama 3.3 70B","endpoints": ["/api/chat","/api/refresh",1234567826 unmodified lines35363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878815 unmodified lines10410510610710810911034 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421513 unmodified lines22923023123223323423521 unmodified lines25725825926026126225 unmodified lines2882892902912922932942952962972982993002 unmodified lines3033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583 unmodified lines3623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194201 unmodified line42242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245351 unmodified lines505506507508509510511512513514515113 unmodified lines6296306316326336348 unmodified lines64364464564664764864910 unmodified lines660661662663664665666667668import osimport reimport loggingfrom datetime import datetimefrom typing import List, Dict, Optional, Tuplefrom fastapi import FastAPI, HTTPException, BackgroundTasksfrom fastapi.responses import PlainTextResponsefrom fastapi.middleware.cors import CORSMiddleware26 unmodified lines"https://kevs-ono-portfolio.netlify.app,http://localhost:3000,http://localhost:8000").split(",")# ------------------------------------------------------------------# Deterministic pricing table (source of truth)# ------------------------------------------------------------------PRICING_TABLE = {"business_systems_audit": {"description": "Full audit of existing business systems, workflows, and data infrastructure","price_naira": 150000,"price_range": None,"note": "One-time engagement. Delivers audit report + prioritized recommendations."},"inventory_system_implementation": {"description": "Custom inventory intelligence system (FEFO, multiβbranch, expiry tracking, transfer recommendations)","price_naira": None,"price_range": "β¦200,000 β β¦350,000","note": "Monthly retainer. Includes hosting, maintenance, and daily email reports."},"erp_customization": {"description": "Custom ERP module (sales ledger, purchasing, financial reporting)","price_naira": None,"price_range": "β¦250,000 β β¦400,000","note": "One-time setup + optional monthly retainer for support."},"ai_concierge_setup": {"description": "RAGβpowered customer operations layer (WhatsApp + web, inventory/loyalty integration)","price_naira": None,"price_range": "β¦300,000 β β¦500,000","note": "One-time setup. Hosting and API costs billed separately (approx β¦20,000/month)."},"website_development": {"description": "Responsive, SEOβoptimized website (static or lightweight CMS)","price_naira": None,"price_range": "Contact for quote","note": "Price depends on complexity, number of pages, and integrations."},"monthly_retainer_business_systems": {"description": "Ongoing management of business systems (inventory, ERP, reporting, analytics)","price_naira": None,"price_range": "β¦200,000 β β¦350,000","note": "Per month. Includes monitoring, adjustments, and stakeholder reporting."}}# Preβcompile pricing keywordsPRICING_KEYWORDS = re.compile(r'\b(how much|cost|price|pricing|retainer|fee|quote|bill|charge|what.*pay|budget)\b',re.IGNORECASE)# ------------------------------------------------------------------# App & middleware# ------------------------------------------------------------------15 unmodified linessupabase: Optional[Client] = None# ------------------------------------------------------------------# Greeting & small-talk detection (unchanged)# ------------------------------------------------------------------GREETINGS = {"hello", "hi", "hey", "hiya", "howdy", "sup", "what's up", "whats up",34 unmodified linesreturn GOODBYE_RESPONSEreturn None# ------------------------------------------------------------------# Deterministic pricing handler# ------------------------------------------------------------------def get_deterministic_pricing(user_query: str) -> Optional[str]:"""Return a formatted pricing answer if query is about cost/price.Returns None if not a pricing query."""if not PRICING_KEYWORDS.search(user_query):return None# Try to match specific service keywordsquery_lower = user_query.lower()response_lines = []matched = False# Map keywords to pricing keyskeyword_to_service = {"inventory": "inventory_system_implementation","expiry": "inventory_system_implementation","erp": "erp_customization","concierge": "ai_concierge_setup","chatbot": "ai_concierge_setup","website": "website_development","site": "website_development","audit": "business_systems_audit","retainer": "monthly_retainer_business_systems","monthly": "monthly_retainer_business_systems"}service_key = Nonefor kw, key in keyword_to_service.items():if kw in query_lower:service_key = keymatched = Truebreakif service_key and service_key in PRICING_TABLE:item = PRICING_TABLE[service_key]if item["price_naira"]:price_str = f"β¦{item['price_naira']:,}"elif item["price_range"]:price_str = item["price_range"]else:price_str = "custom quote required"response_lines.append(f"**{item['description']}** β {price_str}")response_lines.append(f"_{item['note']}_")else:# General pricing overviewresponse_lines.append("Here are Michael's standard pricing ranges for common services:\n")for key, item in PRICING_TABLE.items():if item["price_naira"]:price_str = f"β¦{item['price_naira']:,}"elif item["price_range"]:price_str = item["price_range"]else:continueresponse_lines.append(f"β’ **{item['description']}** β {price_str}")matched = Trueif matched:response_lines.append("\nπ For a precise quote tailored to your specific needs, please reach out via WhatsApp:")response_lines.append(f" https://wa.me/{WHATSAPP_NUMBER.replace('+', '')}")return "\n".join(response_lines)return None# ------------------------------------------------------------------# Supabase & embedder# ------------------------------------------------------------------13 unmodified linesreturn embedder# ------------------------------------------------------------------# HTML fetching & chunking (unchanged)# ------------------------------------------------------------------async def fetch_html(url: str) -> str:async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:21 unmodified lineslogger.info(f"Extracted {len(unique)} chunks from {url}")return uniqueasync def upsert_chunks_to_supabase(chunks: List[str], source_url: str):db = get_supabase()model = get_embedder()25 unmodified lineslogger.info("Knowledge base refresh complete.")# ------------------------------------------------------------------# Vector search with scores (for confidence)# ------------------------------------------------------------------def vector_search_with_scores(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()# Assumes match_portfolio_chunks returns (id, content, source_url, similarity)result = db.rpc("match_portfolio_chunks", {"query_embedding": q_emb,"match_threshold": SIMILARITY_THRESHOLD,2 unmodified linesreturn result.data or []# ------------------------------------------------------------------# LLM with source grounding# ------------------------------------------------------------------async def get_grounded_reply_with_sources(user_message: str, relevant_chunks: List[Dict]) -> Tuple[str, List[str]]:"""Returns (response_text_with_citations, list_of_source_urls)"""if not relevant_chunks:escalation_msg = ("I couldn't find specific information about that in Michael's knowledge base. ""Please reach out directly on WhatsApp for a detailed answer:\n"f"https://wa.me/{WHATSAPP_NUMBER.replace('+', '')}\n\n""You can also ask me about his AI systems, skills, experience, or services.")return escalation_msg, []# Build context with numbered citationscontext_parts = []sources = []for idx, chunk in enumerate(relevant_chunks, start=1):content = chunk["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. Instead say: "For pricing, please check the pricing information above or contact Michael on WhatsApp."4. For skill questions, synthesize all relevant categories from context.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 a short "π 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):"""# Try Groq, fallback Geminireply = ""if GROQ_API_KEY:try:groq_client = Groq(api_key=GROQ_API_KEY)3 unmodified linestemperature=TEMPERATURE,max_tokens=600,)reply = resp.choices[0].message.contentexcept 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.textexcept Exception as e:logger.error(f"Gemini failed: {e}")if not reply:reply = ("I'm experiencing technical difficulties. "f"Please reach Michael directly on WhatsApp: https://wa.me/{WHATSAPP_NUMBER.replace('+', '')}")# Append source list at the endif sources:unique_sources = list(dict.fromkeys(sources)) # preserve order, dedupsource_footer = "\n\n**Sources:**\n" + "\n".join(f"β’ {src}" for src in unique_sources)reply += source_footerreturn reply, sources# ------------------------------------------------------------------# Manual knowledge management (unchanged)# ------------------------------------------------------------------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 []# ------------------------------------------------------------------# API endpoints1 unmodified line@app.post("/api/chat")async def chat(req: ChatRequest):try:# 1. Small talksmalltalk = detect_smalltalk(req.message)if smalltalk:return {"response": smalltalk}# 2. Deterministic pricing (bypass LLM entirely)pricing_answer = get_deterministic_pricing(req.message)if pricing_answer:return {"response": pricing_answer}# 3. Vector search with scoresresults = vector_search_with_scores(req.message, top_k=TOP_K)if not results:escalation = ("I don't have specific information on that in my knowledge base. "f"Please contact Michael directly on WhatsApp: https://wa.me/{WHATSAPP_NUMBER.replace('+', '')}\n\n""I can help with his AI systems, skills, work experience, and services.")return {"response": escalation}# Optional: check average similarity score and force escalation if too low# avg_sim = sum(r.get("similarity", 0) for r in results) / len(results)# if avg_sim < 0.4: ... but we already have threshold in RPC# 4. Grounded LLM reply with sourcesreply, _ = await get_grounded_reply_with_sources(req.message, results)return {"response": reply}except Exception as e:51 unmodified lines}# ------------------------------------------------------------------# Chat widget JS (unchanged except we keep same interface)# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget_js():# Same as original but using the updated API (no change needed)return f"""(function() {{const API_URL = '{PRODUCTION_HOST}';113 unmodified lineswindow.open(`https://wa.me/${{WHATSAPP_NUMBER.replace('+','')}}?text=Hello%20Michael%2C%20I%20visited%20your%20portfolio%20and%20have%20a%20question.`, '_blank');}});setTimeout(() => {{if (!opened) {{unread.style.display = 'flex';8 unmodified lines# ------------------------------------------------------------------@app.on_event("startup")async def startup():logger.info("Starting Kevs Portfolio AI Assistant (deterministic + RAG hybrid)...")get_embedder()try:db = get_supabase()10 unmodified lines@app.get("/")async def root():return {"service": "Kevs Portfolio + Services AI Assistant (Deterministic + RAG)","status": "active","backend": "Supabase pgvector + Groq Llama 3.3 70B with deterministic pricing","endpoints": ["/api/chat","/api/refresh",
app.py+223-106