Spaces:
Sleeping
Sleeping
Download app.py from KevsOno/KevsDigitalBot: direct link, hf CLI and curl.
- Browser
- Download file 28.6 kB
-
https://huggingface.co/spaces/KevsOno/KevsDigitalBot/resolve/main/app.py
- Command line
-
hf download hf://spaces/KevsOno/KevsDigitalBot/app.py
-
curl -L -o app.py https://huggingface.co/spaces/KevsOno/KevsDigitalBot/resolve/main/app.py
28.6 kB
| 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 | |
| # ------------------------------------------------------------------ | |
| 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 | |
| # ------------------------------------------------------------------ | |
| 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.") | |
| 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)) | |
| 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)) | |
| 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)) | |
| 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(), | |
| } | |
| 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) | |
| # ------------------------------------------------------------------ | |
| 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 = ` | |
| <div id="kevs-chat-btn" style="position:fixed;bottom:20px;left:20px;width:60px;height:60px;background:#2563eb;border-radius:50%;cursor:pointer;z-index:99999;display:flex;align-items:center;justify-content:center;box-shadow:0 4px 12px rgba(0,0,0,0.25);"> | |
| <svg width="28" height="28" viewBox="0 0 24 24" fill="white"><path d="M20 2H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14l4 4V4c0-1.1-.9-2-2-2z"/></svg> | |
| <span id="kevs-unread" style="display:none;position:absolute;top:-4px;right:-4px;background:#ef4444;color:white;border-radius:50%;width:18px;height:18px;font-size:11px;font-weight:bold;align-items:center;justify-content:center;">1</span> | |
| </div> | |
| <div id="kevs-chat-window" style="position:fixed;bottom:90px;left:20px;width:370px;height:540px;background:white;border-radius:16px;display:none;flex-direction:column;z-index:99999;box-shadow:0 8px 32px rgba(0,0,0,0.2);overflow:hidden;font-family:'Segoe UI',system-ui,sans-serif;"> | |
| <div style="background:#2563eb;color:white;padding:12px 16px;display:flex;justify-content:space-between;align-items:center;"> | |
| <div style="display:flex;align-items:center;gap:8px;"> | |
| <div style="width:32px;height:32px;background:rgba(255,255,255,0.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:16px;">π€</div> | |
| <div> | |
| <div style="font-weight:bold;font-size:14px;">Kevs AI</div> | |
| <div style="font-size:11px;opacity:0.85;">Michael's portfolio assistant</div> | |
| </div> | |
| </div> | |
| <div style="display:flex;align-items:center;gap:10px;"> | |
| <span id="kevs-wa-btn" style="cursor:pointer;background:#25D366;padding:4px 10px;border-radius:20px;font-size:11px;font-weight:600;">π± WhatsApp</span> | |
| <span id="kevs-close-btn" style="cursor:pointer;font-size:22px;line-height:1;opacity:0.8;">Γ</span> | |
| </div> | |
| </div> | |
| <div id="kevs-messages" style="flex:1;overflow-y:auto;padding:14px;background:#f9fafb;display:flex;flex-direction:column;gap:8px;"></div> | |
| <div id="kevs-typing" style="display:none;padding:6px 14px;background:#f9fafb;font-size:12px;color:#6b7280;font-style:italic;">Kevs AI is typing...</div> | |
| <div style="padding:12px;border-top:1px solid #e5e7eb;display:flex;gap:8px;background:white;"> | |
| <input id="kevs-input" placeholder="Ask about skills, projects, pricing..." style="flex:1;padding:9px 14px;border:1px solid #d1d5db;border-radius:24px;outline:none;font-size:13px;" autocomplete="off"/> | |
| <button id="kevs-send-btn" style="background:#2563eb;color:white;border:none;padding:9px 16px;border-radius:24px;cursor:pointer;font-size:13px;font-weight:600;">Send</button> | |
| </div> | |
| </div> | |
| `; | |
| const btn = document.getElementById('kevs-chat-btn'); | |
| const win = document.getElementById('kevs-chat-window'); | |
| const closeBtn = document.getElementById('kevs-close-btn'); | |
| const waBtn = document.getElementById('kevs-wa-btn'); | |
| const input = document.getElementById('kevs-input'); | |
| const sendBtn = document.getElementById('kevs-send-btn'); | |
| const msgs = document.getElementById('kevs-messages'); | |
| const typing = document.getElementById('kevs-typing'); | |
| const unread = document.getElementById('kevs-unread'); | |
| let opened = false; | |
| function bubble(text, isUser) {{ | |
| const d = document.createElement('div'); | |
| d.style.cssText = ` | |
| padding:9px 13px;border-radius:${{isUser ? '16px 16px 4px 16px' : '16px 16px 16px 4px'}}; | |
| max-width:82%;word-wrap:break-word;font-size:13px;line-height:1.5; | |
| background:${{isUser ? '#2563eb' : '#ffffff'}}; | |
| color:${{isUser ? 'white' : '#1f2937'}}; | |
| align-self:${{isUser ? 'flex-end' : 'flex-start'}}; | |
| box-shadow:0 1px 3px rgba(0,0,0,0.08); | |
| white-space:pre-wrap; | |
| `; | |
| d.innerText = text; | |
| msgs.appendChild(d); | |
| msgs.scrollTop = msgs.scrollHeight; | |
| return d; | |
| }} | |
| async function send() {{ | |
| const msg = input.value.trim(); | |
| if (!msg) return; | |
| bubble(msg, true); | |
| input.value = ''; | |
| input.disabled = true; | |
| sendBtn.disabled = true; | |
| typing.style.display = 'block'; | |
| msgs.scrollTop = msgs.scrollHeight; | |
| try {{ | |
| const res = await fetch(API_URL + '/api/chat', {{ | |
| method: 'POST', | |
| headers: {{'Content-Type': 'application/json'}}, | |
| body: JSON.stringify({{message: msg}}) | |
| }}); | |
| const data = await res.json(); | |
| typing.style.display = 'none'; | |
| bubble(data.response, false); | |
| }} catch(e) {{ | |
| typing.style.display = 'none'; | |
| bubble('β οΈ Connection issue. Please try again or use WhatsApp.', false); | |
| }} finally {{ | |
| input.disabled = false; | |
| sendBtn.disabled = false; | |
| input.focus(); | |
| }} | |
| }} | |
| function openChat() {{ | |
| win.style.display = 'flex'; | |
| unread.style.display = 'none'; | |
| setTimeout(() => {{ | |
| input.removeAttribute('readonly'); | |
| input.disabled = false; | |
| input.style.pointerEvents = 'auto'; | |
| input.focus(); | |
| }}, 100); | |
| if (!opened) {{ | |
| opened = true; | |
| bubble("π Hello! I'm Kevs AI, Michael Onoriode's portfolio assistant.\\n\\nAsk me about his AI systems, skills, work experience, or services. I can also help with pricing and how to hire Michael.", false); | |
| }} | |
| }} | |
| btn.addEventListener('click', openChat); | |
| closeBtn.addEventListener('click', () => win.style.display = 'none'); | |
| sendBtn.addEventListener('click', send); | |
| input.addEventListener('keydown', e => {{ if (e.key === 'Enter') {{ e.preventDefault(); send(); }} }}); | |
| waBtn.addEventListener('click', () => {{ | |
| window.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'; | |
| }} | |
| }}, 8000); | |
| }})(); | |
| """ | |
| # ------------------------------------------------------------------ | |
| # Startup | |
| # ------------------------------------------------------------------ | |
| async def startup(): | |
| global pricing_cache | |
| logger.info("Starting Kevs Portfolio AI Assistant (stronger embedder, manual KB only)...") | |
| get_embedder() # loads all-mpnet-base-v2 | |
| pricing_cache = await load_pricing_from_db() | |
| if not pricing_cache: | |
| logger.warning("No pricing data from DB, using fallback.") | |
| pricing_cache = FALLBACK_PRICING | |
| else: | |
| logger.info(f"Loaded {len(pricing_cache)} pricing entries.") | |
| try: | |
| db = get_supabase() | |
| count = db.table("portfolio_knowledge").select("id", count="exact").execute().count or 0 | |
| logger.info(f"Supabase connected. {count} knowledge chunks (manual only).") | |
| logger.info("If you just upgraded the embedder, call POST /api/admin/reembed to recompute embeddings.") | |
| except Exception as e: | |
| logger.error(f"Startup error: {e}") | |
| async def root(): | |
| return { | |
| "service": "Kevs Portfolio AI Assistant (Stronger Embedder + Manual KB)", | |
| "status": "active", | |
| "backend": f"Supabase pgvector + openai/gpt-oss-120b + {EMBEDDER_MODEL}", | |
| "pricing_source": "database", | |
| "knowledge_source": "manual chunks only (no scraping)", | |
| "endpoints": [ | |
| "/api/chat", | |
| "/api/status", | |
| "/api/knowledge/add", | |
| "/api/knowledge/list", | |
| "/api/knowledge/delete", | |
| "/api/admin/refresh-pricing", | |
| "/api/admin/reembed", | |
| "/chat-widget.js" | |
| ], | |
| "whatsapp": f"https://wa.me/{WHATSAPP_NUMBER}", | |
| } | |
| async def health(): | |
| return {"status": "ok", "timestamp": datetime.now().isoformat()} |