Spaces:
Sleeping
Sleeping
Update app.py
Browse files76 unmodified lines77787980808182838485868788899091929394959697989910015 unmodified lines11611711810711912012112238 unmodified lines16116216315215316416516615716716816917016217117217363 unmodified lines23723823923224024124224352 unmodified lines2962972982912993002933013023033042973053063073083093103113123133143153163093103113173183197 unmodified lines32732832932533033133233322 unmodified lines35635735835435936036126 unmodified lines38838939038739139239339439539639739439839940040129 unmodified lines4314324334304344354364374384354364394404414424432 unmodified lines44644744844544644744844945045153 unmodified lines50550650750850850951051151251251351476 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)
# ------------------------------------------------------------------# API models (fixed missing definitions)# ------------------------------------------------------------------class ChatRequest(BaseModel): message: str
class ManualChunkRequest(BaseModel): content: str source_url: str = "manual"
class DeleteChunkRequest(BaseModel): chunk_id: int
# ------------------------------------------------------------------# App & middleware# ------------------------------------------------------------------15 unmodified linessupabase: Optional[Client] = None
# ------------------------------------------------------------------# Greeting & small-talk detection (unchanged)# 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]: """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 keywords query_lower = user_query.lower() response_lines = [] matched = False
# Map keywords to pricing keys keyword_to_service = { "inventory": "inventory_system_implementation", "expiry": "inventory_system_implementation",63 unmodified lines return embedder
# ------------------------------------------------------------------# HTML fetching & chunking (unchanged)# HTML fetching & chunking# ------------------------------------------------------------------async def fetch_html(url: str) -> str: async with httpx.AsyncClient(timeout=30.0, follow_redirects=True) as client:52 unmodified lines logger.info("Knowledge base refresh complete.")
# ------------------------------------------------------------------# Vector search with scores (for confidence)# Vector search (returns chunks with source_url)# ------------------------------------------------------------------def vector_search_with_scores(query: str, top_k: int = TOP_K) -> List[Dict]: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() # 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() # The RPC should return at least id, content, source_url 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 lines context_parts = [] sources = [] for idx, chunk in enumerate(relevant_chunks, start=1): content = chunk["content"] 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 lines
ANSWER (with inline citations, well-formatted):"""
# Try Groq, fallback Gemini reply = "" if GROQ_API_KEY: try:26 unmodified lines
# Append source list at the end if sources: unique_sources = list(dict.fromkeys(sources)) # preserve order, dedup 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 (unchanged)# Manual knowledge management# ------------------------------------------------------------------async def add_manual_chunk(content: str, source_url: str = "manual"): model = get_embedder()29 unmodified lines if smalltalk: return {"response": smalltalk}
# 2. Deterministic pricing (bypass LLM entirely) # 2. Deterministic pricing (bypass LLM) pricing_answer = get_deterministic_pricing(req.message) if pricing_answer: return {"response": pricing_answer}
# 3. Vector search with scores results = vector_search_with_scores(req.message, top_k=TOP_K) # 3. Vector search 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. "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 sources reply, _ = await get_grounded_reply_with_sources(req.message, results) return {"response": reply}53 unmodified lines }
# ------------------------------------------------------------------# Chat widget JS (unchanged except we keep same interface)# Chat widget JS (unchanged)# ------------------------------------------------------------------@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}';app.py+25-26