eva-assistant-assets / src /final_chatbot.py
irthayag's picture
Upload folder using huggingface_hub
af37a16 verified
Raw
History Blame Contribute Delete
2.56 kB
"""
Enterprise Knowledge Assistant - FINAL Complete Chatbot Function (v2)
Fixed: query rewriting now preserves intent instead of drifting/elaborating.
"""
def ask_chatbot_final_v2(query, embedding_model, index, all_chunks, groq_client,
router_model, tokenizer, label_encoder,
domain_indices, domain_chunks_map,
qa_model, qa_tokenizer,
classify_query_fn, retrieve_hybrid_fn, generate_with_groq_fn, extract_exact_answer_fn,
top_k=5, hallucination_threshold=0.95):
domain, confidence_or_probs = classify_query_fn(query, router_model, tokenizer, label_encoder)
router_confidence = float(confidence_or_probs.max()) if hasattr(confidence_or_probs, 'shape') else float(confidence_or_probs)
rewrite_prompt = f"""Rewrite this question to be clearer for a document search system.
Keep it SHORT and preserve the EXACT original meaning. Do not add new concepts, legal terms, or expand the scope.
If the question uses casual phrasing (e.g. "become a mother"), just convert it to the standard term (e.g. "maternity leave"), nothing more.
Original question: {query}
Rewritten question (short, same meaning):"""
rewritten = generate_with_groq_fn(rewrite_prompt, groq_client).strip()
results = retrieve_hybrid_fn(rewritten, domain, embedding_model, domain_indices, domain_chunks_map,
index, all_chunks, top_k=top_k)
best_distance = results[0][0]
if best_distance > hallucination_threshold:
return {'narrated_answer': "I couldn't find information about this in the available documents.",
'exact_quote': None, 'quote_confidence': None, 'source': None, 'domain': domain}
context_text = "\n\n".join([f"[Source: {c['domain']} - {c['title']}]\n{c['text']}" for dist, c in results])
prompt = f"""You are an enterprise knowledge assistant. Answer using ONLY the context below.
Directly explain WHAT the policy/content actually says, in clear detail. Cite sources after explaining substance.
Context:
{context_text}
Question: {query}
Answer:"""
generative_answer = generate_with_groq_fn(prompt, groq_client)
best_chunk_text = results[0][1]['text']
exact_answer, extract_confidence = extract_exact_answer_fn(rewritten, best_chunk_text, qa_model, qa_tokenizer)
return {'narrated_answer': generative_answer, 'exact_quote': exact_answer,
'quote_confidence': extract_confidence, 'source': results[0][1]['title'], 'domain': domain}