""" Enterprise Knowledge Assistant - Core RAG Pipeline (v2) Improved hallucination guard: checks both original and rewritten query distances. """ def retrieve_relevant_chunks(query, embedding_model, index, all_chunks, top_k=5): query_embedding = embedding_model.encode([query], convert_to_numpy=True) distances, indices = index.search(query_embedding.astype('float32'), top_k) results = [all_chunks[idx] for idx in indices[0]] return results, distances[0][0] def generate_with_groq(prompt, groq_client, model="openai/gpt-oss-120b", max_tokens=150): response = groq_client.chat.completions.create( model=model, messages=[{"role": "user", "content": prompt}], reasoning_effort="low", max_tokens=max_tokens, temperature=0, ) return response.choices[0].message.content def ask_chatbot_v4(query, embedding_model, index, all_chunks, groq_client, conversation_history, top_k=5, similarity_threshold=0.88): # Handle greetings without sending them through RAG greetings = { "hi", "hello", "hey", "hi eva", "hello eva", "hey eva", "good morning", "good afternoon", "good evening" } if query.lower().strip() in greetings: return ( "Hello! I'm EVA, your Enterprise Knowledge Assistant. " "How can I help you with HR, Legal, Finance, or IT queries?", query, 1.0 ) history_text = "" if conversation_history: history_text = "\n".join([f"User: {h['question']}\nAssistant: {h['answer']}" for h in conversation_history[-3:]]) rewrite_prompt = f"""Given this conversation history: {history_text} Rewrite the new question to be clearer and more explicit for a document search system, resolving any references to earlier parts of the conversation. Only output the rewritten question, nothing else. New question: {query}""" rewritten = generate_with_groq(rewrite_prompt, groq_client).strip() original_embedding = embedding_model.encode([query], convert_to_numpy=True) rewritten_embedding = embedding_model.encode([rewritten], convert_to_numpy=True) orig_distances, orig_indices = index.search(original_embedding.astype('float32'), top_k) rewrite_distances, rewrite_indices = index.search(rewritten_embedding.astype('float32'), top_k) if orig_distances[0][0] <= rewrite_distances[0][0]: best_distance = orig_distances[0][0] indices = orig_indices else: best_distance = rewrite_distances[0][0] indices = rewrite_indices if best_distance > similarity_threshold: answer = "I couldn't find information about this in the available documents. This question may be outside the scope of the current knowledge base." else: relevant_chunks = [all_chunks[idx] for idx in indices[0]] context_text = "\n\n".join([f"[Source: {c['domain']} - {c['title']}]\n{c['text']}" for c in relevant_chunks]) answer_prompt = f"""You are an enterprise knowledge assistant having an ongoing conversation. Conversation so far: {history_text} Answer using ONLY the context below. If the context doesn't fully answer the question, say what's missing honestly. Context: {context_text} New question: {query} Answer:""" answer = generate_with_groq(answer_prompt, groq_client) conversation_history.append({'question': query, 'answer': answer}) return answer, rewritten, best_distance