""" Enterprise Knowledge Assistant - Extractive QA Layer Combines generative narration with exact-quote extraction for verifiable answers. """ import torch def extract_exact_answer(question, context, qa_model, qa_tokenizer): inputs = qa_tokenizer(question, context, return_tensors="pt", truncation=True, max_length=384) with torch.no_grad(): outputs = qa_model(**inputs) answer_start = torch.argmax(outputs.start_logits) answer_end = torch.argmax(outputs.end_logits) + 1 answer_tokens = inputs['input_ids'][0][answer_start:answer_end] answer_text = qa_tokenizer.decode(answer_tokens, skip_special_tokens=True) confidence = torch.softmax(outputs.start_logits, dim=1).max().item() return answer_text, confidence def ask_with_extraction(query, domain, embedding_model, domain_indices, domain_chunks_map, index, all_chunks, groq_client, qa_model, qa_tokenizer, retrieve_hybrid_fn, generate_with_groq_fn, top_k=5): results = retrieve_hybrid_fn(query, domain, embedding_model, domain_indices, domain_chunks_map, index, all_chunks, top_k=top_k) 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. IMPORTANT: Do not just tell the user "refer to source X" or "see document Y." Instead, directly explain WHAT the clause/policy/fact actually says, in your own words, synthesizing the actual content. Only mention source names as supporting citations after explaining the substance. Context: {context_text} Question: {query} Answer (explain the actual content directly, then cite sources):""" generative_answer = generate_with_groq_fn(prompt, groq_client) best_chunk_text = results[0][1]['text'] exact_answer, confidence = extract_exact_answer(query, best_chunk_text, qa_model, qa_tokenizer) return { 'narrated_answer': generative_answer, 'exact_quote': exact_answer, 'quote_confidence': confidence, 'source': results[0][1]['title'] }