Spaces:
Sleeping
Sleeping
Update main.py
Browse files12346 unmodified lines1112131415161718192012 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495966 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617723 unmodified lines20120220320420520620720820921021121212 unmodified lines225226227228229230231232233234from fastapi import FastAPI, Request, HTTPException, Responsefrom fastapi.responses import JSONResponse, PlainTextResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel6 unmodified linesfrom supabase import create_clientimport google.generativeai as genaifrom groq import Groqfrom textblob import TextBlob# --- CONFIGURATION ---app = FastAPI(title="Penafort Hybrid API - Knowledge Restored")app.add_middleware(CORSMiddleware,12 unmodified linesGROQ_API_KEY = os.environ.get("GROQ_API_KEY")PRODUCTION_HOST = "https://kevsono-penafort-concierge.hf.space"# --- CLIENTS ---def get_supabase():if not SUPABASE_URL or not SUPABASE_KEY: return Nonetry: return create_client(SUPABASE_URL, SUPABASE_KEY)except: return Nonedef get_groq():if not GROQ_API_KEY: return Nonetry: return Groq(api_key=GROQ_API_KEY)except: return Noneclass ChatRequest(BaseModel):message: struser_id: Optional[str] = Nonesession_id: Optional[str] = Nonechannel: str = "website"# --- CORE LOGIC ---async def get_ai_reply_with_context(text: str, session_id: str):"""Fetches internal niche context so the AI knows about Penafort/MuzoScents"""client = get_supabase()context = "You are the Penafort Assistant."if client:try:# Fetch Niche Config for brand voice and general infoniche_res = client.table("niche_configs").select("*").eq("niche_name", "Penafort Multi-Sector").maybe_single().execute()if niche_res.data:c = niche_res.datacontext = f"Niche: {c['niche_name']}. Info: {c['general_info']}. Voice: {c['brand_voice']}"except: passprompt = f"System: {context}\nUser: {text}\nAssistant (concise, only use provided info):"# Try Groqtry:groq = get_groq()if groq:res = groq.chat.completions.create(messages=[{"role": "user", "content": prompt}], model="llama3-8b-8192")return res.choices[0].message.contentexcept: pass# Try Geminiif GEMINI_API_KEY:try:genai.configure(api_key=GEMINI_API_KEY)model = genai.GenerativeModel('gemini-pro')return model.generate_content(prompt).textexcept: passreturn "I'm here to help! Could you please clarify your request?"async def search_knowledge_safe(query: str):"""Improved Search: Higher sensitivity to keywords like 'time', 'close', 'location'"""client = get_supabase()if not client: return Nonetry:result = client.table("general_knowledge").select("*").execute()if not result.data: return None6 unmodified linestry: keywords = ast.literal_eval(keywords)except: keywords = [k.strip() for k in keywords.split(',')]# Boost score for keyword matchesscore = sum(25 for k in keywords if k.lower() in q_lower)# Additional boost for specific intent matchesif any(word in q_lower for word in ["time", "close", "open", "hour"]) and any(k in ["hours", "schedule"] for k in keywords):score += 30if score > best_score:best_score, best_match = score, entryreturn best_match.get('content') if best_score > 15 else Noneexcept Exception as e:logger.error(f"Search error: {e}")return None# --- CHAT ENDPOINT ---@app.post("/api/chat")async def website_chat(request: ChatRequest):try:start_time = datetime.now()session_id = request.session_id or str(uuid.uuid4())msg_lower = request.message.lower()# 1. Check Internal Database Knowledge (Hours, Locations, Facts)db_reply = await search_knowledge_safe(request.message)if db_reply:reply = db_reply# 2. Check for Handoff Intentelif any(x in msg_lower for x in ["agent", "human", "speak to someone"]):reply = "I've queued you for a human agent. They will be with you shortly. 📞"# 3. Fallback to AI with Brand Contextelse:reply = await get_ai_reply_with_context(request.message, session_id)# 4. Background Loggingtry:client = get_supabase()if client:client.table("chat_messages").insert({"session_id": session_id,"message": request.message,"response": reply,"response_time_ms": int((datetime.now() - start_time).total_seconds() * 1000),"created_at": datetime.now().isoformat()}).execute()except: passreturn {"response": reply, "session_id": session_id}except Exception as e:logger.error(f"System Error: {e}")return {"response": "I'm having a bit of trouble. Please try again later.", "session_id": "error"}@app.get("/chat-widget.js", response_class=PlainTextResponse)async def chat_widget_js():return f"""(function() {{const config = {{ apiUrl: '{PRODUCTION_HOST}', primaryColor: '#6c5ce7', title: 'Penafort Assistant' }};let sessionId = localStorage.getItem('penafort_session_id') || 'sess_' + Date.now();localStorage.setItem('penafort_session_id', sessionId);const widget = document.createElement('div');widget.innerHTML = `<div id="pf-btn" style="position:fixed;bottom:20px;right:20px;width:60px;height:60px;background:${{config.primaryColor}};border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;z-index:9999;box-shadow: 0 4px 12px rgba(0,0,0,0.2);"><svg width="30" height="30" 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></div><div id="pf-win" style="position:fixed;bottom:90px;right:20px;width:350px;height:480px;background:white;display:none;flex-direction:column;border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,0.15);z-index:9999;border:1px solid #eee;font-family: sans-serif;"><div style="background:${{config.primaryColor}};color:white;padding:15px;font-weight:bold;border-radius:12px 12px 0 0;display:flex;justify-content:space-between;"><span>${{config.title}}</span><span onclick="document.getElementById('pf-win').style.display='none'" style="cursor:pointer;">×</span>23 unmodified linesconst res = await fetch(`${{config.apiUrl}}/api/chat`, {{method: 'POST',headers: {{'Content-Type': 'application/json'}},body: JSON.stringify({{ message: val, user_id: 'guest', session_id: sessionId }})}});const data = await res.json();appendMsg(data.response, 'ai');}} catch(e) {{appendMsg('Sorry, I am having trouble connecting.', 'ai');}}}}12 unmodified lines}})();"""@app.get("/")async def root():return {"status": "active", "info": "Penafort Concierge Knowledge-Base Active"}if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)12346 unmodified lines11121314151617181912 unmodified lines32333435363738394041424344454647484950515253546 unmodified lines61626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017123 unmodified lines19519619719819920020120220320420520612 unmodified lines219220221222223224from fastapi import FastAPI, Requestfrom fastapi.responses import JSONResponse, PlainTextResponsefrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModel6 unmodified linesfrom supabase import create_clientimport google.generativeai as genaifrom groq import Groq# --- CONFIGURATION ---app = FastAPI(title="Penafort Hybrid API - Final Production Fix")app.add_middleware(CORSMiddleware,12 unmodified linesGROQ_API_KEY = os.environ.get("GROQ_API_KEY")PRODUCTION_HOST = "https://kevsono-penafort-concierge.hf.space"def get_supabase():try: return create_client(SUPABASE_URL, SUPABASE_KEY)except: return Noneclass ChatRequest(BaseModel):message: struser_id: Optional[str] = Nonesession_id: Optional[str] = None# --- IMPROVED SEARCH LOGIC ---async def search_knowledge_aggressive(query: str):"""Tier 1: High-sensitivity internal database search"""client = get_supabase()if not client: return Nonetry:# Get all entries from knowledge baseresult = client.table("general_knowledge").select("*").execute()if not result.data: return None6 unmodified linestry: keywords = ast.literal_eval(keywords)except: keywords = [k.strip() for k in keywords.split(',')]# High weight for keyword matchesscore = sum(30 for k in keywords if k.lower() in q_lower)# Content-based word matchingcontent_lower = entry.get('content', '').lower()score += sum(5 for word in q_lower.split() if len(word) > 3 and word in content_lower)# Intent Boosting (Locations and Hours)if any(w in q_lower for w in ["where", "located", "address", "branch", "festac"]):if any(k in ["location", "address", "branches"] for k in keywords): score += 50if any(w in q_lower for w in ["time", "close", "open", "hour", "schedule"]):if any(k in ["hours", "schedule", "opening"] for k in keywords): score += 50if score > best_score:best_score, best_match = score, entry# Return DB content if even a moderate match is foundif best_match and best_score > 15:logger.info(f"MATCH FOUND in DB: {best_match.get('source')}")return best_match.get('content')return Noneexcept Exception as e:logger.error(f"Search error: {e}")return Noneasync def get_ai_reply_with_strict_context(text: str):"""Tier 2: AI reply strictly using niche context"""client = get_supabase()context_info = "You are the Penafort Assistant."if client:try:niche = client.table("niche_configs").select("*").eq("niche_name", "Penafort Multi-Sector").maybe_single().execute()if niche.data:c = niche.datacontext_info = f"Business Info: {c['general_info']}. Brand Voice: {c['brand_voice']}"except: passprompt = f"System: {context_info}\nUser Question: {text}\nAssistant (Answer only using the Business Info above. Be helpful but brief):"try:# Try Groq firstif GROQ_API_KEY:groq = Groq(api_key=GROQ_API_KEY)res = groq.chat.completions.create(messages=[{"role": "user", "content": prompt}], model="llama3-8b-8192")return res.choices[0].message.content# Try Geminiif GEMINI_API_KEY:genai.configure(api_key=GEMINI_API_KEY)model = genai.GenerativeModel('gemini-pro')return model.generate_content(prompt).textexcept: passreturn "I'm here to help! Could you please clarify your request?"# --- UPDATED ENDPOINT ---@app.post("/api/chat")async def website_chat(request: ChatRequest):session_id = request.session_id or str(uuid.uuid4())msg_lower = request.message.lower()# 1. SEARCH DB FIRST (Highest Priority)db_reply = await search_knowledge_aggressive(request.message)if db_reply:reply = db_reply# 2. Check for Loyalty/Agent intentselif any(x in msg_lower for x in ["points", "balance", "loyalty"]):reply = "To check your points, please provide your registered phone number."elif any(x in msg_lower for x in ["agent", "human", "speak to someone"]):reply = "I'm connecting you with a human agent. Please stay on the line. 📞"# 3. USE CONTEXTUAL AIelse:reply = await get_ai_reply_with_strict_context(request.message)# Log interaction safelytry:client = get_supabase()if client:client.table("chat_messages").insert({"session_id": session_id,"message": request.message,"response": reply,"created_at": datetime.now().isoformat()}).execute()except: passreturn {"response": reply, "session_id": session_id}@app.get("/chat-widget.js", response_class=PlainTextResponse)async def chat_widget_js():return f"""(function() {{const config = {{ apiUrl: '{PRODUCTION_HOST}', primaryColor: '#6b4b9a', title: 'Penafort Assistant' }};let sessionId = localStorage.getItem('penafort_session_id') || 'sess_' + Date.now();localStorage.setItem('penafort_session_id', sessionId);const widget = document.createElement('div');widget.id = 'penafort-chat-widget';widget.innerHTML = `<div id="pf-btn" style="position:fixed;bottom:20px;right:20px;width:60px;height:60px;background:${{config.primaryColor}};border-radius:50%;cursor:pointer;display:flex;align-items:center;justify-content:center;z-index:10000;box-shadow:0 4px 12px rgba(0,0,0,0.2);"><svg width="30" height="30" 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></div><div id="pf-win" style="position:fixed;bottom:90px;right:20px;width:350px;height:500px;background:white;display:none;flex-direction:column;border-radius:12px;box-shadow:0 8px 24px rgba(0,0,0,0.15);z-index:10000;border:1px solid #eee;font-family:sans-serif;"><div style="background:${{config.primaryColor}};color:white;padding:15px;font-weight:bold;border-radius:12px 12px 0 0;display:flex;justify-content:space-between;"><span>${{config.title}}</span><span onclick="document.getElementById('pf-win').style.display='none'" style="cursor:pointer;">×</span>23 unmodified linesconst res = await fetch(`${{config.apiUrl}}/api/chat`, {{method: 'POST',headers: {{'Content-Type': 'application/json'}},body: JSON.stringify({{ message: val, session_id: sessionId }})}});const data = await res.json();appendMsg(data.response, 'ai');}} catch(e) {{appendMsg('Error connecting to assistant.', 'ai');}}}}12 unmodified lines}})();"""if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=7860)
main.py+88-98