Spaces:
Sleeping
Sleeping
Update app.py
Browse files76 unmodified lines77787980818283848586878815 unmodified lines10410510610710810911038 unmodified lines14915015115215315415515615715815916016116216316416563 unmodified lines22923023123223323423552 unmodified lines2882892902912922932942952962972982993003013023033043053063073083093103113123133147 unmodified lines32232332432532632732822 unmodified lines35135235335435535635726 unmodified lines38438538638738838939039139239339439539639729 unmodified lines4274284294304314324334344354364374384392 unmodified lines44244344444544644744844945045153 unmodified lines50550650750850951051151251351451576 unmodified lines}}# 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",38 unmodified lines# 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",63 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:52 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,"match_count": top_k,}).execute()return 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. "7 unmodified linescontext_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})")22 unmodified linesANSWER (with inline citations, well-formatted):"""# Try Groq, fallback Geminireply = ""if GROQ_API_KEY:try:26 unmodified lines# 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()29 unmodified linesif 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. "2 unmodified lines)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}53 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}';76 unmodified lines777879808182838485868788899091929394959697989910015 unmodified lines11611711811912012112238 unmodified lines16116216316416516616716816917017117217363 unmodified lines23723823924024124224352 unmodified lines2962972982993003013023033043053063073083093103113123133143153163173183197 unmodified lines32732832933033133233322 unmodified lines35635735835936036126 unmodified lines38838939039139239339439539639739839940040129 unmodified lines4314324334344354364374384394404414424432 unmodified lines44644744844945045153 unmodified lines50550650750850951051151251351476 unmodified lines}}PRICING_KEYWORDS = re.compile(r'\b(how much|cost|price|pricing|retainer|fee|quote|bill|charge|what.*pay|budget)\b',re.IGNORECASE)# ------------------------------------------------------------------# API models (fixed missing definitions)# ------------------------------------------------------------------class ChatRequest(BaseModel):message: strclass ManualChunkRequest(BaseModel):content: strsource_url: str = "manual"class DeleteChunkRequest(BaseModel):chunk_id: int# ------------------------------------------------------------------# App & middleware# ------------------------------------------------------------------15 unmodified linessupabase: Optional[Client] = None# ------------------------------------------------------------------# Greeting & small-talk detection# ------------------------------------------------------------------GREETINGS = {"hello", "hi", "hey", "hiya", "howdy", "sup", "what's up", "whats up",38 unmodified lines# Deterministic pricing handler# ------------------------------------------------------------------def get_deterministic_pricing(user_query: str) -> Optional[str]:if not PRICING_KEYWORDS.search(user_query):return Nonequery_lower = user_query.lower()response_lines = []matched = Falsekeyword_to_service = {"inventory": "inventory_system_implementation","expiry": "inventory_system_implementation",63 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:52 unmodified lineslogger.info("Knowledge base refresh complete.")# ------------------------------------------------------------------# Vector search (returns chunks with source_url)# ------------------------------------------------------------------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()# The RPC should return at least id, content, source_urlreturn 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]]:if not relevant_chunks:escalation_msg = ("I couldn't find specific information about that in Michael's knowledge base. "7 unmodified linescontext_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})")22 unmodified linesANSWER (with inline citations, well-formatted):"""reply = ""if GROQ_API_KEY:try:26 unmodified lines# Append source list at the endif sources:unique_sources = list(dict.fromkeys(sources))source_footer = "\n\n**Sources:**\n" + "\n".join(f"• {src}" for src in unique_sources)reply += source_footerreturn reply, sources# ------------------------------------------------------------------# Manual knowledge management# ------------------------------------------------------------------async def add_manual_chunk(content: str, source_url: str = "manual"):model = get_embedder()29 unmodified linesif smalltalk:return {"response": smalltalk}# 2. Deterministic pricing (bypass LLM)pricing_answer = get_deterministic_pricing(req.message)if pricing_answer:return {"response": pricing_answer}# 3. Vector searchresults = vector_search(req.message, top_k=TOP_K)if not results:escalation = ("I don't have specific information on that in my knowledge base. "2 unmodified lines)return {"response": escalation}# 4. Grounded LLM reply with sourcesreply, _ = await get_grounded_reply_with_sources(req.message, results)return {"response": reply}53 unmodified lines}# ------------------------------------------------------------------# Chat widget JS (unchanged)# ------------------------------------------------------------------@app.get("/chat-widget.js", response_class=PlainTextResponse)async def widget_js():return f"""(function() {{const API_URL = '{PRODUCTION_HOST}';
app.py+25-26