irthayag commited on
Commit
af37a16
·
verified ·
1 Parent(s): 29f64fe

Upload folder using huggingface_hub

Browse files
src/__pycache__/eva_chatbot.cpython-312.pyc ADDED
Binary file (4.05 kB). View file
 
src/__pycache__/extractive_qa.cpython-312.pyc ADDED
Binary file (2.93 kB). View file
 
src/__pycache__/final_chatbot.cpython-312.pyc ADDED
Binary file (2.73 kB). View file
 
src/__pycache__/hybrid_retrieval.cpython-312.pyc ADDED
Binary file (1.8 kB). View file
 
src/__pycache__/rag_pipeline.cpython-312.pyc ADDED
Binary file (4 kB). View file
 
src/__pycache__/reranker_utils.cpython-312.pyc ADDED
Binary file (1.29 kB). View file
 
src/__pycache__/router_utils.cpython-312.pyc ADDED
Binary file (1.33 kB). View file
 
src/agent_graph.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enterprise Knowledge Assistant - Multi-Agent Graph
3
+ Router -> Hybrid Retrieval -> Generation, orchestrated via LangGraph.
4
+ """
5
+
6
+ from langgraph.graph import StateGraph, END
7
+ from typing import TypedDict
8
+
9
+ class AgentState(TypedDict):
10
+ query: str
11
+ domain: str
12
+ confidence: float
13
+ retrieved_chunks: list
14
+ answer: str
15
+
16
+
17
+ def build_agent_graph(router_model, tokenizer, label_encoder, embedding_model,
18
+ domain_indices, domain_chunks_map, index, all_chunks, groq_client,
19
+ classify_query_fn, retrieve_hybrid_fn, generate_with_groq_fn):
20
+
21
+ def router_node(state):
22
+ domain, confidence_or_probs = classify_query_fn(state['query'], router_model, tokenizer, label_encoder)
23
+ if hasattr(confidence_or_probs, 'shape') and confidence_or_probs.numel() > 1:
24
+ confidence = float(confidence_or_probs.max())
25
+ else:
26
+ confidence = float(confidence_or_probs)
27
+ print(f"[Router] Domain: {domain} (confidence: {confidence:.2f})")
28
+ return {**state, 'domain': domain, 'confidence': confidence}
29
+
30
+ def retrieval_node(state):
31
+ results = retrieve_hybrid_fn(
32
+ state['query'], state['domain'],
33
+ embedding_model, domain_indices, domain_chunks_map, index, all_chunks
34
+ )
35
+ return {**state, 'retrieved_chunks': results}
36
+
37
+ def generation_node(state):
38
+ context_text = "\n\n".join([f"[Source: {c['domain']} - {c['title']}]\n{c['text']}"
39
+ for dist, c in state['retrieved_chunks']])
40
+ prompt = f"""You are an enterprise knowledge assistant. Answer using ONLY the context below.
41
+ If the context doesn't fully answer the question, say what's missing honestly.
42
+
43
+ Context:
44
+ {context_text}
45
+
46
+ Question: {state['query']}
47
+
48
+ Answer:"""
49
+ answer = generate_with_groq_fn(prompt, groq_client)
50
+ return {**state, 'answer': answer}
51
+
52
+ graph = StateGraph(AgentState)
53
+ graph.add_node("router", router_node)
54
+ graph.add_node("retrieval", retrieval_node)
55
+ graph.add_node("generation", generation_node)
56
+
57
+ graph.set_entry_point("router")
58
+ graph.add_edge("router", "retrieval")
59
+ graph.add_edge("retrieval", "generation")
60
+ graph.add_edge("generation", END)
61
+
62
+ return graph.compile()
src/eva_chatbot.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ EVA - Enterprise Virtual Assistant
3
+ Complete chatbot: greeting handling + router + memory + hybrid retrieval + extraction
4
+ """
5
+
6
+ def is_small_talk(query, groq_client, generate_with_groq_fn):
7
+ prompt = f"""Is this message small talk/greeting/casual conversation (like "hi", "hello", "how are you", "thanks", "bye")
8
+ rather than an actual question needing information lookup? Answer ONLY "yes" or "no".
9
+
10
+ Message: {query}"""
11
+ response = generate_with_groq_fn(prompt, groq_client).strip().lower()
12
+ return "yes" in response
13
+
14
+
15
+ def handle_small_talk(query, groq_client, generate_with_groq_fn, bot_name="EVA"):
16
+ prompt = f"""You are {bot_name}, a friendly enterprise knowledge assistant chatbot for HR, Legal, Finance, and IT questions.
17
+ Respond naturally and briefly to this casual message. If it's a greeting, introduce yourself briefly and invite them to ask a question.
18
+
19
+ Message: {query}
20
+
21
+ Response:"""
22
+ return generate_with_groq_fn(prompt, groq_client)
23
+
24
+
25
+ def ask_eva(query, conversation_history, embedding_model, index, all_chunks, groq_client,
26
+ router_model, tokenizer, label_encoder, domain_indices, domain_chunks_map,
27
+ qa_model, qa_tokenizer, classify_query_fn, retrieve_hybrid_fn, generate_with_groq_fn,
28
+ extract_exact_answer_fn, top_k=5, hallucination_threshold=0.95, bot_name="EVA"):
29
+
30
+ if is_small_talk(query, groq_client, generate_with_groq_fn):
31
+ answer = handle_small_talk(query, groq_client, generate_with_groq_fn, bot_name)
32
+ conversation_history.append({'question': query, 'answer': answer})
33
+ return {'answer': answer, 'exact_quote': None, 'source': None, 'domain': None}
34
+
35
+ domain, confidence_or_probs = classify_query_fn(query, router_model, tokenizer, label_encoder)
36
+
37
+ history_text = ""
38
+ if conversation_history:
39
+ history_text = "\n".join([f"User: {h['question']}\nAssistant: {h['answer']}"
40
+ for h in conversation_history[-3:]])
41
+
42
+ rewrite_prompt = f"""Given this conversation history:
43
+ {history_text}
44
+
45
+ Rewrite the NEW question to be a clear, standalone, explicit search query — resolving any references
46
+ to earlier parts of the conversation. Keep it short. Only output the rewritten question.
47
+
48
+ New question: {query}
49
+
50
+ Rewritten question:"""
51
+ rewritten = generate_with_groq_fn(rewrite_prompt, groq_client).strip()
52
+
53
+ results = retrieve_hybrid_fn(rewritten, domain, embedding_model, domain_indices, domain_chunks_map,
54
+ index, all_chunks, top_k=top_k)
55
+
56
+ best_distance = results[0][0]
57
+ if best_distance > hallucination_threshold:
58
+ answer = f"I'm {bot_name}, and I couldn't find information about this in my current knowledge base. Could you rephrase, or ask about HR, Legal, Finance, or IT topics?"
59
+ conversation_history.append({'question': query, 'answer': answer})
60
+ return {'answer': answer, 'exact_quote': None, 'source': None, 'domain': domain}
61
+
62
+ context_text = "\n\n".join([f"[Source: {c['domain']} - {c['title']}]\n{c['text']}" for dist, c in results])
63
+ prompt = f"""You are {bot_name}, an enterprise knowledge assistant having an ongoing conversation.
64
+
65
+ Conversation so far:
66
+ {history_text}
67
+
68
+ Answer using ONLY the context below. Directly explain what it says, in clear detail.
69
+
70
+ Context:
71
+ {context_text}
72
+
73
+ New question: {query}
74
+
75
+ Answer:"""
76
+ answer = generate_with_groq_fn(prompt, groq_client)
77
+
78
+ exact_quote, _ = extract_exact_answer_fn(rewritten, results[0][1]['text'], qa_model, qa_tokenizer)
79
+
80
+ conversation_history.append({'question': query, 'answer': answer})
81
+ return {'answer': answer, 'exact_quote': exact_quote, 'source': results[0][1]['title'], 'domain': domain}
src/extractive_qa.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enterprise Knowledge Assistant - Extractive QA Layer
3
+ Combines generative narration with exact-quote extraction for verifiable answers.
4
+ """
5
+
6
+ import torch
7
+
8
+ def extract_exact_answer(question, context, qa_model, qa_tokenizer):
9
+ inputs = qa_tokenizer(question, context, return_tensors="pt", truncation=True, max_length=384)
10
+
11
+ with torch.no_grad():
12
+ outputs = qa_model(**inputs)
13
+
14
+ answer_start = torch.argmax(outputs.start_logits)
15
+ answer_end = torch.argmax(outputs.end_logits) + 1
16
+
17
+ answer_tokens = inputs['input_ids'][0][answer_start:answer_end]
18
+ answer_text = qa_tokenizer.decode(answer_tokens, skip_special_tokens=True)
19
+
20
+ confidence = torch.softmax(outputs.start_logits, dim=1).max().item()
21
+
22
+ return answer_text, confidence
23
+
24
+
25
+ def ask_with_extraction(query, domain, embedding_model, domain_indices, domain_chunks_map,
26
+ index, all_chunks, groq_client, qa_model, qa_tokenizer,
27
+ retrieve_hybrid_fn, generate_with_groq_fn, top_k=5):
28
+
29
+ results = retrieve_hybrid_fn(query, domain, embedding_model, domain_indices, domain_chunks_map,
30
+ index, all_chunks, top_k=top_k)
31
+
32
+ context_text = "\n\n".join([f"[Source: {c['domain']} - {c['title']}]\n{c['text']}" for dist, c in results])
33
+
34
+ prompt = f"""You are an enterprise knowledge assistant. Answer using ONLY the context below.
35
+
36
+ IMPORTANT: Do not just tell the user "refer to source X" or "see document Y." Instead, directly explain
37
+ WHAT the clause/policy/fact actually says, in your own words, synthesizing the actual content.
38
+ Only mention source names as supporting citations after explaining the substance.
39
+
40
+ Context:
41
+ {context_text}
42
+
43
+ Question: {query}
44
+
45
+ Answer (explain the actual content directly, then cite sources):"""
46
+
47
+ generative_answer = generate_with_groq_fn(prompt, groq_client)
48
+
49
+ best_chunk_text = results[0][1]['text']
50
+ exact_answer, confidence = extract_exact_answer(query, best_chunk_text, qa_model, qa_tokenizer)
51
+
52
+ return {
53
+ 'narrated_answer': generative_answer,
54
+ 'exact_quote': exact_answer,
55
+ 'quote_confidence': confidence,
56
+ 'source': results[0][1]['title']
57
+ }
src/final_chatbot.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enterprise Knowledge Assistant - FINAL Complete Chatbot Function (v2)
3
+ Fixed: query rewriting now preserves intent instead of drifting/elaborating.
4
+ """
5
+
6
+ def ask_chatbot_final_v2(query, embedding_model, index, all_chunks, groq_client,
7
+ router_model, tokenizer, label_encoder,
8
+ domain_indices, domain_chunks_map,
9
+ qa_model, qa_tokenizer,
10
+ classify_query_fn, retrieve_hybrid_fn, generate_with_groq_fn, extract_exact_answer_fn,
11
+ top_k=5, hallucination_threshold=0.95):
12
+
13
+ domain, confidence_or_probs = classify_query_fn(query, router_model, tokenizer, label_encoder)
14
+ router_confidence = float(confidence_or_probs.max()) if hasattr(confidence_or_probs, 'shape') else float(confidence_or_probs)
15
+
16
+ rewrite_prompt = f"""Rewrite this question to be clearer for a document search system.
17
+ Keep it SHORT and preserve the EXACT original meaning. Do not add new concepts, legal terms, or expand the scope.
18
+ If the question uses casual phrasing (e.g. "become a mother"), just convert it to the standard term (e.g. "maternity leave"), nothing more.
19
+
20
+ Original question: {query}
21
+
22
+ Rewritten question (short, same meaning):"""
23
+ rewritten = generate_with_groq_fn(rewrite_prompt, groq_client).strip()
24
+
25
+ results = retrieve_hybrid_fn(rewritten, domain, embedding_model, domain_indices, domain_chunks_map,
26
+ index, all_chunks, top_k=top_k)
27
+
28
+ best_distance = results[0][0]
29
+ if best_distance > hallucination_threshold:
30
+ return {'narrated_answer': "I couldn't find information about this in the available documents.",
31
+ 'exact_quote': None, 'quote_confidence': None, 'source': None, 'domain': domain}
32
+
33
+ context_text = "\n\n".join([f"[Source: {c['domain']} - {c['title']}]\n{c['text']}" for dist, c in results])
34
+ prompt = f"""You are an enterprise knowledge assistant. Answer using ONLY the context below.
35
+ Directly explain WHAT the policy/content actually says, in clear detail. Cite sources after explaining substance.
36
+
37
+ Context:
38
+ {context_text}
39
+
40
+ Question: {query}
41
+
42
+ Answer:"""
43
+ generative_answer = generate_with_groq_fn(prompt, groq_client)
44
+
45
+ best_chunk_text = results[0][1]['text']
46
+ exact_answer, extract_confidence = extract_exact_answer_fn(rewritten, best_chunk_text, qa_model, qa_tokenizer)
47
+
48
+ return {'narrated_answer': generative_answer, 'exact_quote': exact_answer,
49
+ 'quote_confidence': extract_confidence, 'source': results[0][1]['title'], 'domain': domain}
src/hybrid_retrieval.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enterprise Knowledge Assistant - Hybrid Domain-Aware Retrieval
3
+ Tries domain-specific search first; falls back to global search if the match is weak.
4
+ """
5
+
6
+ def retrieve_from_domain_index(query, domain, embedding_model, domain_indices, domain_chunks_map, top_k=5):
7
+ query_embedding = embedding_model.encode([query], convert_to_numpy=True)
8
+ distances, indices = domain_indices[domain].search(query_embedding.astype('float32'), top_k)
9
+
10
+ results = []
11
+ for dist, idx in zip(distances[0], indices[0]):
12
+ results.append((dist, domain_chunks_map[domain][idx]))
13
+
14
+ return results
15
+
16
+
17
+ def retrieve_hybrid(query, domain, embedding_model, domain_indices, domain_chunks_map,
18
+ index, all_chunks, top_k=5, domain_fallback_threshold=0.95):
19
+
20
+ domain_results = retrieve_from_domain_index(query, domain, embedding_model, domain_indices, domain_chunks_map, top_k)
21
+ best_domain_distance = domain_results[0][0]
22
+
23
+ if best_domain_distance <= domain_fallback_threshold:
24
+ return domain_results
25
+ else:
26
+ query_embedding = embedding_model.encode([query], convert_to_numpy=True)
27
+ distances, indices = index.search(query_embedding.astype('float32'), top_k)
28
+ return [(dist, all_chunks[idx]) for dist, idx in zip(distances[0], indices[0])]
src/rag_pipeline.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enterprise Knowledge Assistant - Core RAG Pipeline (v2)
3
+ Improved hallucination guard: checks both original and rewritten query distances.
4
+ """
5
+
6
+ def retrieve_relevant_chunks(query, embedding_model, index, all_chunks, top_k=5):
7
+ query_embedding = embedding_model.encode([query], convert_to_numpy=True)
8
+ distances, indices = index.search(query_embedding.astype('float32'), top_k)
9
+ results = [all_chunks[idx] for idx in indices[0]]
10
+ return results, distances[0][0]
11
+
12
+
13
+ def generate_with_groq(prompt, groq_client, model="llama-3.3-70b-versatile"):
14
+ response = groq_client.chat.completions.create(
15
+ model=model,
16
+ messages=[{"role": "user", "content": prompt}]
17
+ )
18
+ return response.choices[0].message.content
19
+
20
+
21
+ def ask_chatbot_v4(query, embedding_model, index, all_chunks, groq_client,
22
+ conversation_history, top_k=5, similarity_threshold=0.88):
23
+ history_text = ""
24
+ if conversation_history:
25
+ history_text = "\n".join([f"User: {h['question']}\nAssistant: {h['answer']}"
26
+ for h in conversation_history[-3:]])
27
+
28
+ rewrite_prompt = f"""Given this conversation history:
29
+ {history_text}
30
+
31
+ Rewrite the new question to be clearer and more explicit for a document search system, resolving any references to earlier parts of the conversation.
32
+ Only output the rewritten question, nothing else.
33
+
34
+ New question: {query}"""
35
+
36
+ rewritten = generate_with_groq(rewrite_prompt, groq_client).strip()
37
+
38
+ original_embedding = embedding_model.encode([query], convert_to_numpy=True)
39
+ rewritten_embedding = embedding_model.encode([rewritten], convert_to_numpy=True)
40
+
41
+ orig_distances, orig_indices = index.search(original_embedding.astype('float32'), top_k)
42
+ rewrite_distances, rewrite_indices = index.search(rewritten_embedding.astype('float32'), top_k)
43
+
44
+ if orig_distances[0][0] <= rewrite_distances[0][0]:
45
+ best_distance = orig_distances[0][0]
46
+ indices = orig_indices
47
+ else:
48
+ best_distance = rewrite_distances[0][0]
49
+ indices = rewrite_indices
50
+
51
+ if best_distance > similarity_threshold:
52
+ answer = "I couldn't find information about this in the available documents. This question may be outside the scope of the current knowledge base."
53
+ else:
54
+ relevant_chunks = [all_chunks[idx] for idx in indices[0]]
55
+ context_text = "\n\n".join([f"[Source: {c['domain']} - {c['title']}]\n{c['text']}"
56
+ for c in relevant_chunks])
57
+
58
+ answer_prompt = f"""You are an enterprise knowledge assistant having an ongoing conversation.
59
+
60
+ Conversation so far:
61
+ {history_text}
62
+
63
+ Answer using ONLY the context below. If the context doesn't fully answer the question, say what's missing honestly.
64
+
65
+ Context:
66
+ {context_text}
67
+
68
+ New question: {query}
69
+
70
+ Answer:"""
71
+ answer = generate_with_groq(answer_prompt, groq_client)
72
+
73
+ conversation_history.append({'question': query, 'answer': answer})
74
+ return answer, rewritten, best_distance
src/reload_session.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Run this at the start of every session to instantly restore everything."""
2
+
3
+ from google.colab import drive
4
+ drive.mount('/content/drive')
5
+
6
+ import pickle, numpy as np, faiss, torch
7
+ from sentence_transformers import SentenceTransformer
8
+ from google.colab import userdata
9
+ from groq import Groq
10
+ import sys
11
+
12
+ PROJECT_ROOT = "/content/drive/MyDrive/Enterprise_Knowledge_Assistant"
13
+
14
+ device = 'cuda' if torch.cuda.is_available() else 'cpu'
15
+ print(f"Using device: {device}")
16
+
17
+ index = faiss.read_index(f"{PROJECT_ROOT}/embeddings/faiss_index.bin")
18
+
19
+ with open(f"{PROJECT_ROOT}/embeddings/all_chunks_metadata.pkl", 'rb') as f:
20
+ all_chunks = pickle.load(f)
21
+
22
+ embeddings = np.load(f"{PROJECT_ROOT}/embeddings/embeddings.npy")
23
+
24
+ embedding_model = SentenceTransformer(f"{PROJECT_ROOT}/models/embedding_model", device=device)
25
+
26
+ groq_client = Groq(api_key=userdata.get('GROQ_API_KEY'))
27
+
28
+ sys.path.append(f"{PROJECT_ROOT}/src")
29
+ from rag_pipeline import retrieve_relevant_chunks, generate_with_groq, ask_chatbot_v4
30
+ from router_utils import classify_query
31
+
32
+ conversation_history = []
33
+
34
+ print("Everything reloaded successfully. Ready to chat.")
35
+ print(f"Total chunks in index: {index.ntotal}")
src/reranker_utils.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enterprise Knowledge Assistant - Cross-Encoder Reranking
3
+ """
4
+
5
+ def retrieve_with_reranking(query, domain, embedding_model, domain_indices, domain_chunks_map,
6
+ index, all_chunks, reranker, retrieve_hybrid_fn,
7
+ initial_k=15, final_k=5, domain_fallback_threshold=0.95):
8
+
9
+ initial_results = retrieve_hybrid_fn(query, domain, embedding_model, domain_indices, domain_chunks_map,
10
+ index, all_chunks, top_k=initial_k, domain_fallback_threshold=domain_fallback_threshold)
11
+
12
+ pairs = [[query, chunk['text']] for dist, chunk in initial_results]
13
+ rerank_scores = reranker.predict(pairs)
14
+
15
+ scored_results = list(zip(rerank_scores, [chunk for dist, chunk in initial_results]))
16
+ scored_results.sort(key=lambda x: x[0], reverse=True)
17
+
18
+ return scored_results[:final_k]
src/router_utils.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Enterprise Knowledge Assistant - Query Router
3
+ Uses fine-tuned DistilBERT to classify queries into HR/Legal/Finance/IT domains.
4
+ """
5
+
6
+ import torch
7
+
8
+ def classify_query(query, model, tokenizer, label_encoder):
9
+ inputs = tokenizer(query, return_tensors="pt", truncation=True, padding=True, max_length=64)
10
+ with torch.no_grad():
11
+ outputs = model(**inputs)
12
+ predicted_class = torch.argmax(outputs.logits, dim=1).item()
13
+ predicted_domain = label_encoder.inverse_transform([predicted_class])[0]
14
+ probs = torch.nn.functional.softmax(outputs.logits, dim=1)[0]
15
+ confidence = probs[predicted_class].item()
16
+ return predicted_domain, confidence