Spaces:
Sleeping

docs-bot / app.py
Jabou124's picture
Upload app.py with huggingface_hub
ffeefc9
Raw History Blame Contribute Delete
23.7 kB
from dotenv import load_dotenv
load_dotenv()
import json
import os
import re
import faiss
import gradio as gr
import anthropic
from sentence_transformers import SentenceTransformer
from rank_bm25 import BM25Okapi
from nltk.stem import SnowballStemmer
import numpy as np
_stemmer = SnowballStemmer("english")
def stem(text):
return " ".join(_stemmer.stem(w) for w in text.lower().split())
# ── Config ──────────────────────────────────────────────────────────
CONCEPTS = {
"webhooks": {
"keywords": ["webhook", "webhooks", "event notification", "callback url"],
"heading_boost": ["Webhooks", "About webhooks", "Configure webhooks", "Events"],
"url_boost": ["/api/latest/#webhook", "/api/latest/#events"],
"heading_filter": ["Webhooks", "About webhooks", "Configure webhooks", "Events"],
"features": [],
"description": "",
},
"facial_similarity": {
"keywords": ["selfie", "motion", "liveness", "photo fully auto",
"facial similarity", "face match", "biometric"],
"heading_boost": ["Motion", "Photo and Photo Fully Auto", "Video",
"Facial Similarity reports"],
"url_boost": ["/facial-similarity-reports/"],
"heading_filter": ["Motion", "Photo and Photo Fully Auto", "Video",
"Facial Similarity reports", "re-verification", "Selfie"],
"features": [],
"description": "",
},
"getting_started": {
"keywords": ["integrate", "integration", "get started", "getting started",
"quick start", "setup", "how to start", "onboard"],
"heading_boost": ["Getting Started", "Quick Start", "General Introduction"],
"url_boost": ["/getting-started/", "/guide/"],
"features": [],
"description": "",
},
"smart_capture_link": {
"keywords": ["smart capture link", "capture link", "hosted solution",
"no-code", "low-code", "no code", "low code"],
"heading_boost": ["Smart Capture Link", "Smart Capture", "Hosted solution"],
"url_boost": ["/smart-capture-link/"],
"heading_filter": ["Smart Capture Link", "Smart Capture"],
"features": [],
"description": "",
},
"proof_of_address": {
"keywords": ["proof of address", "poa", "address verification", "utility bill",
"supported countries", "issuing countries", "bank statement"],
"heading_boost": ["Proof of Address", "Supported issuing countries", "PoA report",
"Start here"],
"url_boost": ["/proof-of-address-report/"],
"heading_filter": ["Proof of Address", "Supported issuing countries", "PoA"],
"features": [],
"description": "",
},
"sandbox": {
"keywords": ["sandbox", "test environment", "testing", "postman", "trial",
"test mode", "demo", "try out"],
"heading_boost": ["Sandbox", "Testing", "Postman", "Test environment"],
"url_boost": ["/sandbox/", "/testing/"],
"heading_filter": ["Sandbox", "Testing", "Postman"],
"features": [],
"description": "",
},
"api": {
"keywords": ["api", "endpoint", "token", "auth", "sdk_token", "http"],
"heading_boost": [],
"url_boost": ["/api/"],
"features": [],
"description": "",
},
"repeated_face_detection": {
"keywords": ["repeated face", "repeat faces", "known faces", "same face",
"already seen face", "previous applicants",
"different pii", "document reuse", "repeat attempts"],
"heading_boost": ["Known Faces", "Repeat Attempts", "Document Known Faces"],
"url_boost": [],
"heading_filter": ["Known Faces", "Document Known Faces", "Repeat Attempts"],
"features": [
"Known Faces report: standalone report that compares a user's selfie against all previous applicants to detect repeat identity attempts.",
"Document Known Faces: separate add-on that flags when identity documents contain the same face but different PII (name, DOB, document number) β€” detects document fraud/reuse.",
],
"description": (
"Known Faces report and Document Known Faces are separate, independent solutions. "
"Facial Similarity (selfie vs document) is NOT about repeated faces across applicants."
),
},
}
DOMAIN_RULES = [
'"Onfido" refers to the Entrust Identity Verification product.',
'The user term "repeated faces" maps to "same face" in the documentation.',
'"Document Known Faces" is part of the "Known Faces" capability.',
'"Selfie" in user questions refers to "Photo and Photo Fully Auto" in the documentation.',
]
# ── Load data ───────────────────────────────────────────────────────
index = faiss.read_index("data/index.faiss")
chunks = [json.loads(l) for l in open("data/chunks.jsonl")]
model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
# BM25 index for keyword matching
with open("data/bm25_tokens.json") as f:
_bm25_tokens = json.load(f)
bm25_index = BM25Okapi(_bm25_tokens)
CLAUDE_MODEL = "claude-haiku-4-5-20251001"
DAILY_LIMIT = 500
_daily_count = 0
_daily_date = ""
_claude = anthropic.Anthropic()
def _check_daily_limit():
"""Reset counter daily, block if over limit."""
global _daily_count, _daily_date
import datetime
today = datetime.date.today().isoformat()
if _daily_date != today:
_daily_date = today
_daily_count = 0
_daily_count += 1
if _daily_count > DAILY_LIMIT:
raise RuntimeError(f"Daily API limit ({DAILY_LIMIT}) reached.")
def _call_claude(system_prompt, user_prompt):
_check_daily_limit()
msg = _claude.messages.create(
model=CLAUDE_MODEL,
max_tokens=1024,
system=system_prompt,
messages=[{"role": "user", "content": user_prompt}],
)
return msg.content[0].text.strip()
# ── Layer 0: Query Translation ─────────────────────────────────────
def translate_query(query):
"""Translate non-English queries to English for better retrieval."""
# Quick heuristic: if most words are ASCII letters, assume English
ascii_words = sum(1 for w in query.split() if w.isascii())
if ascii_words >= len(query.split()) * 0.8:
return query
try:
translated = _call_claude(
"You are a translator. Output ONLY the English translation, nothing else.",
query,
)
if translated:
print(f" Translated: {query!r} -> {translated!r}", flush=True)
return translated
except Exception:
pass
return query
# ── Layer 1: Retrieval ──────────────────────────────────────────────
def retrieve(query, top_k=30, rrf_k=60):
# FAISS: semantic similarity
q_emb = model.encode([query], normalize_embeddings=True).astype("float32")
faiss_scores, faiss_ids = index.search(q_emb, top_k)
faiss_ranks = {}
for rank, i in enumerate(faiss_ids[0]):
if i >= 0 and float(faiss_scores[0][rank]) >= 0.3:
faiss_ranks[int(i)] = rank
# BM25: keyword matching
q_tokens = re.findall(r"[A-Za-z0-9_./:-]+", query.lower())
bm25_scores = bm25_index.get_scores(q_tokens)
bm25_top = np.argsort(bm25_scores)[::-1][:top_k]
bm25_ranks = {}
for rank, i in enumerate(bm25_top):
if bm25_scores[i] > 0:
bm25_ranks[int(i)] = rank
# Reciprocal Rank Fusion
all_ids = set(faiss_ranks.keys()) | set(bm25_ranks.keys())
rrf_scored = []
for i in all_ids:
score = 0.0
if i in faiss_ranks:
score += 1.0 / (rrf_k + faiss_ranks[i])
if i in bm25_ranks:
score += 1.0 / (rrf_k + bm25_ranks[i])
rrf_scored.append((i, score))
rrf_scored.sort(key=lambda x: -x[1])
seen = set()
entries = []
for i, rrf_score in rrf_scored[:top_k]:
chunk = chunks[i]
key = (tuple(chunk["heading_path"]), chunk["raw_text"])
if key in seen:
continue
seen.add(key)
entries.append({
"text": chunk["text"].strip()[:900],
"url": chunk["url"],
"heading": " > ".join(chunk.get("heading_path", [])),
"score": rrf_score,
"kind": chunk.get("kind", "text"),
})
return [e for e in entries if len(e["text"]) >= 50]
# ── Layer 2: Concept Classification ────────────────────────────────
def classify(query, entries):
q_stemmed = stem(query)
matched = []
for name, cfg in CONCEPTS.items():
if any(stem(kw) in q_stemmed for kw in cfg["keywords"]):
matched.append((name, cfg))
if not matched:
return entries, []
def boost_score(entry):
bonus = 0
for _, cfg in matched:
for pat in cfg.get("heading_boost", []):
if pat in entry["heading"]:
bonus += 2
for pat in cfg.get("url_boost", []):
if pat in entry["url"]:
bonus += 1
# Prefer descriptive text over code snippets and table rows
if entry.get("kind") == "text":
bonus += 1
return bonus
sorted_entries = sorted(entries, key=lambda e: (-boost_score(e), -e["score"]))
# Hard-filter: if any matched concept has heading_filter, keep only matching chunks
filters = []
for _, cfg in matched:
filters.extend(cfg.get("heading_filter", []))
if filters:
filtered = [e for e in sorted_entries if any(f.lower() in e["heading"].lower() for f in filters)]
if filtered:
sorted_entries = filtered
# Inject heading-matched text chunks from full corpus that FAISS missed (max 5)
if filters:
existing_texts = {e["text"] for e in sorted_entries}
injected = 0
candidates = []
for chunk in chunks:
heading = " > ".join(chunk.get("heading_path", []))
if not any(f.lower() in heading.lower() for f in filters):
continue
if chunk.get("kind") != "text":
continue
text = chunk["text"].strip()[:900]
if text in existing_texts:
continue
candidates.append((len(text), text, chunk["url"], heading))
# Prefer longer chunks (more descriptive)
candidates.sort(key=lambda x: -x[0])
for _, text, url, heading in candidates[:5]:
sorted_entries.append({
"text": text,
"url": url,
"heading": heading,
"score": 0.0,
"kind": "text",
})
# Re-sort so injected text chunks rank by boost then score
sorted_entries = sorted(sorted_entries, key=lambda e: (-boost_score(e), -e["score"]))
return sorted_entries, [name for name, _ in matched]
# ── Layer 3: Answer Synthesis ───────────────────────────────────────
def synthesize(question, passage_entries, concept_names=None, history=None):
context = "\n\n---\n\n".join(
f"[Passage {i+1} | {e['url']}]\n{e['text']}" for i, e in enumerate(passage_entries)
)
rules = "\n".join(f"- {r}" for r in DOMAIN_RULES)
# Format conversation history (last 3 exchanges)
history_block = ""
if history:
turns = []
for msg in history[-6:]: # last 6 messages = 3 exchanges
role = msg.get("role", "")
raw = msg.get("content", "")
# Content can be a string or a list of {"text": "...", "type": "text"}
if isinstance(raw, list):
content = " ".join(item.get("text", "") for item in raw if isinstance(item, dict))
else:
content = str(raw)
content = content.strip()
if not content:
continue
if role == "user":
turns.append(f"User: {content}")
elif role == "assistant":
turns.append(f"Assistant: {content}")
if turns:
history_block = "Previous conversation:\n" + "\n".join(turns) + "\n\n"
# Build concept knowledge block
concept_block = ""
for name in (concept_names or []):
cfg = CONCEPTS.get(name, {})
if cfg.get("features"):
features = "\n".join(f" - {f}" for f in cfg["features"])
desc = f" Note: {cfg['description']}\n" if cfg.get("description") else ""
concept_block += f"\nRelevant products ({name}):\n{features}\n{desc}"
grounding_rules = (
"STRICT GROUNDING RULES (never violate these):\n"
"- You may state facts from the passages below OR from the 'Relevant products' list.\n"
"- Claims from 'Relevant products' do not need a passage citation.\n"
"- Any claim beyond 'Relevant products' MUST be supported by a passage.\n"
"- NEVER infer, guess, or elaborate beyond the passages and product list.\n"
"- NEVER use phrases like: 'appears', 'suggests', 'based on context', 'it seems',\n"
" 'advanced algorithms', 'machine learning', 'not explicitly stated', 'inferred'.\n"
"- NEVER add disclaimers or caveats about what the documentation does not cover.\n"
" Do NOT say 'the documentation does not provide...', 'However, the docs don't mention...',\n"
" 'there is no information about...', or similar. Just answer with what IS available.\n"
"- If the passages partially cover the question or the question is ambiguous, ask a short clarification question.\n"
" Examples: \"Could you clarify whether you mean X or Y?\", \"Are you asking about X in the context of Y?\"\n"
"- If no passage or product list supports an answer at all, say \"Not enough evidence in docs\" and suggest what the user could ask instead.\n"
"- Do NOT fabricate technical details (e.g. detection logic, algorithms, sizes).\n"
"- Use product names EXACTLY as they appear in the passages or 'Relevant products' list. Do NOT rename them.\n"
)
if concept_block:
instructions = (
f"{grounding_rules}\n"
f"Instructions:\n"
f"- Structure your answer around EACH product listed in 'Relevant products' above.\n"
f"- For each product, state ONLY what the passages say about it.\n"
f"- If no passage mentions a product, say: \"Not enough evidence in docs for [product name].\"\n"
f"- Keep products clearly separated. Do NOT mix up their descriptions.\n"
f"- Do NOT include passage numbers or citations inline in the answer.\n"
f"- After the answer, add a Citations line listing used passage numbers, e.g.:\n"
f" Citations: 2, 1\n"
)
else:
instructions = (
f"{grounding_rules}\n"
f"Instructions:\n"
f"- Give a concise answer (3-5 sentences max) using ONLY facts from the passages.\n"
f"- Do NOT include passage numbers or citations inline in the answer.\n"
f"- After the answer, add a Citations line listing ALL used passage numbers, e.g.:\n"
f" Citations: 1, 2, 4\n"
)
system_prompt = (
f"Domain rules:\n{rules}\n\n"
+ (f"{concept_block}\n\n" if concept_block else "")
+ f"{instructions}"
)
user_prompt = (
(f"{history_block}" if history_block else "")
+ f"Context:\n{context}\n\n"
f"Question: {question}"
)
try:
answer = _call_claude(system_prompt, user_prompt)
except Exception as e:
answer = f"Error: {e}"
return answer
# ── Layer 4: Citation Extraction ────────────────────────────────────
def extract_citations(answer, passage_entries):
cite_match = re.search(r"Citations:\s*(.+)", answer)
clean_answer = answer[:cite_match.start()].strip() if cite_match else answer.strip()
# Trust inline [Passage N] refs in the answer body first
inline_ids = {int(x) for x in re.findall(r"\[Passage\s+(\d+)\]", clean_answer)}
# Fall back to Citations line only if no inline refs found
if not inline_ids and cite_match:
inline_ids = {int(x) for x in re.findall(r"(\d+)", cite_match.group(1))}
# Strip [Passage N] and [Passage N, Passage M, ...] markers from displayed answer
clean_answer = re.sub(r"\s*\[Passage[\s\d,]+\]", "", clean_answer).strip()
# Only return URLs from passages the LLM actually cited
if inline_ids:
cited_urls = []
seen_urls = set()
for idx in sorted(inline_ids):
if 1 <= idx <= len(passage_entries):
url = passage_entries[idx - 1]["url"]
if url not in seen_urls:
seen_urls.add(url)
cited_urls.append(url)
sources = cited_urls if cited_urls else list(dict.fromkeys(e["url"] for e in passage_entries[:3]))
else:
sources = list(dict.fromkeys(e["url"] for e in passage_entries[:3]))
return clean_answer, sources
# ── Pipeline ────────────────────────────────────────────────────────
_REFERENTIAL_PATTERNS = re.compile(
r"\b(it|its|this|that|these|those|they|them|their|the same|"
r"how about|what about|and also|as well|too\b|instead|"
r"the above|the previous|mentioned|said earlier|"
r"should i|is it|can it|does it)\b",
re.IGNORECASE,
)
def _build_retrieval_query(query, history=None):
"""Combine current query with recent user messages for context-aware retrieval.
Only enriches when the query contains referential/anaphoric words."""
if not history or not _REFERENTIAL_PATTERNS.search(query):
return query
recent = []
for msg in history[-6:]:
if msg.get("role") != "user":
continue
raw = msg.get("content", "")
if isinstance(raw, list):
raw = " ".join(item.get("text", "") for item in raw if isinstance(item, dict))
raw = str(raw).strip()
if raw:
recent.append(raw)
if not recent:
return query
context = recent[-1] # Only last user message, not last 2
combined = f"{query} {context}"
# Cap length to avoid polluting retrieval with too much context
words = combined.split()
if len(words) > 40:
combined = " ".join(words[:40])
return combined
def _extract_url_chunks(text):
"""Find URLs in user message and return matching chunks from the index."""
urls = re.findall(r"https?://[^\s,)]+", text)
if not urls:
return []
results = []
existing = set()
for url in urls:
url_base = url.split("#")[0].rstrip("/")
anchor = url.split("#")[1] if "#" in url else ""
for chunk in chunks:
chunk_url_base = chunk["url"].split("#")[0].rstrip("/")
if chunk_url_base != url_base:
continue
if chunk.get("kind") != "text":
continue
# If anchor specified, prefer chunks matching that anchor
chunk_anchor = chunk["url"].split("#")[1] if "#" in chunk["url"] else ""
text_snip = chunk["text"].strip()[:900]
if text_snip in existing:
continue
existing.add(text_snip)
heading = " > ".join(chunk.get("heading_path", []))
# Boost anchor-matched chunks higher
priority = 0 if (anchor and anchor.lower() in chunk_anchor.lower()) else 1
results.append((priority, len(text_snip), {
"text": text_snip,
"url": chunk["url"],
"heading": heading,
"score": 1.0,
"kind": "text",
}))
results.sort(key=lambda x: (x[0], -x[1]))
return [r[2] for r in results]
_NON_QUESTION = re.compile(
r"^\s*(thanks|thank you|thx|ok|okay|perfect|great|got it|understood|cool|cheers|bye|merci|gracias)\s*[.!]?\s*$",
re.IGNORECASE,
)
def ask(q, history=None):
if _NON_QUESTION.match(q):
return "You're welcome! Feel free to ask if you have more questions."
q_en = translate_query(q)
retrieval_query = _build_retrieval_query(q_en, history)
entries = retrieve(retrieval_query)
entries, concept_names = classify(q_en, entries)
# Inject chunks from URLs mentioned in the user message
url_chunks = _extract_url_chunks(q)
if url_chunks:
existing_texts = {e["text"] for e in entries}
for uc in url_chunks:
if uc["text"] not in existing_texts:
entries.insert(0, uc)
# Cap table_row chunks at 2, fill rest with text
text_entries = [e for e in entries if e["kind"] != "table_row"]
table_entries = [e for e in entries if e["kind"] == "table_row"]
passage_entries = (text_entries + table_entries[:2])[:8]
# Debug: show what reaches the LLM
print(f"\n--- Query: {q[:60]}", flush=True)
for i, e in enumerate(passage_entries):
print(f" [{i+1}] score={e['score']:.3f} kind={e['kind']:<10} heading={e['heading'][:60]}", flush=True)
if not passage_entries:
return "No relevant passages found. Try a more specific question."
raw_answer = synthesize(q, passage_entries, concept_names, history)
clean_answer, sources = extract_citations(raw_answer, passage_entries)
if sources:
return clean_answer + "\n\nSources:\n" + "\n".join(sources)
return clean_answer
# ── Gradio UI ───────────────────────────────────────────────────────
if __name__ == "__main__":
demo = gr.ChatInterface(
fn=ask,
title="Entrust Identity Verification β€” Docs Assistant",
description=(
"This chatbot answers questions based on the "
"[official Entrust Identity Verification documentation](https://documentation.identity.entrust.com). "
"It searches through the documentation to find relevant passages and generates answers grounded in those passages.\n\n"
"**Important:**\n"
"- Always verify answers using the **Sources** links provided below each response.\n"
"- This assistant may not cover every detail β€” treat it as a starting point, not a definitive reference.\n"
"- It does not have access to your account, configuration, or internal company data.\n\n"
"**Tips for better answers:**\n"
"- Be specific (e.g. \"How do I configure webhooks?\" rather than \"Tell me about the API\")\n"
"- Ask follow-up questions to dig deeper into a topic\n"
"- Paste a documentation URL to ask questions about a specific page"
),
)
demo.launch(
server_name="0.0.0.0",
server_port=7860,
auth=(os.environ["GRADIO_USER"], os.environ["GRADIO_PASS"]),
)