File size: 6,726 Bytes
af37a16
 
 
 
 
5e74397
 
b1a4fdb
 
 
 
 
 
 
 
5e74397
 
b1a4fdb
af37a16
b1a4fdb
 
 
 
af37a16
 
 
 
 
 
 
 
 
b1a4fdb
af37a16
 
 
 
 
 
 
5e74397
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af37a16
 
b1a4fdb
5e74397
b1a4fdb
af37a16
 
5e74397
 
b1a4fdb
5e74397
b1a4fdb
af37a16
 
5e74397
af37a16
b1a4fdb
af37a16
 
 
b1a4fdb
af37a16
 
 
 
 
 
b1a4fdb
5e74397
af37a16
b1a4fdb
af37a16
5e74397
 
af37a16
5e74397
 
b1a4fdb
5e74397
af37a16
5e74397
 
af37a16
5e74397
 
 
 
af37a16
 
 
 
5e74397
af37a16
 
5e74397
 
 
 
 
 
 
 
 
 
b1a4fdb
5e74397
b1a4fdb
5e74397
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
"""
EVA - Enterprise Virtual Assistant
Complete chatbot: greeting handling + router + memory + hybrid retrieval + extraction
"""

import re

GREETINGS = {
    "hi", "hello", "hey", "yo", "sup",
    "hi eva", "hello eva", "hey eva",
    "good morning", "good afternoon", "good evening",
    "thanks", "thank you", "thanks eva", "thank you eva",
    "bye", "goodbye", "see you", "ok", "okay", "cool",
}

NOT_FOUND_MARKER = "NOT_FOUND_IN_KB"


def is_small_talk(query, groq_client, generate_with_groq_fn):
    normalized = query.lower().strip().strip("!?.,")
    if normalized in GREETINGS:
        return True
    prompt = f"""Is this message small talk/greeting/casual conversation (like "hi", "hello", "how are you", "thanks", "bye")
rather than an actual question needing information lookup? Answer ONLY "yes" or "no".

Message: {query}"""
    response = generate_with_groq_fn(prompt, groq_client).strip().lower()
    return "yes" in response


def handle_small_talk(query, groq_client, generate_with_groq_fn, bot_name="EVA"):
    prompt = f"""You are {bot_name}, a friendly enterprise knowledge assistant chatbot for HR, Legal, Finance, and IT questions.
Respond naturally and briefly to this casual message. If it is a greeting, introduce yourself briefly and invite them to ask a question.

Message: {query}

Response:"""
    return generate_with_groq_fn(prompt, groq_client)


def _extract_company_names(context_text):
    """Pull company/source names out of the [Source: domain - title] tags so we can verify against them."""
    titles = re.findall(r"(?:\[Source:\s*[^\-]+\s*-\s*([^\]]+)\])", context_text)
    names = set()
    for t in titles:
        # take the first 1-3 capitalized words as the likely company name portion of the title
        words = t.strip().split()
        names.add(t.strip().lower())
        if words:
            names.add(words[0].strip(",.").lower())
    return names


def _verify_answer_grounded(answer, context_text, generate_with_groq_fn, groq_client):
    """Ask the model itself to fact-check the draft answer against the context, sentence by sentence."""
    check_prompt = f"""You will check a draft answer against a set of source excerpts.

Source excerpts:
{context_text}

Draft answer:
{answer}

Does the draft answer mention ANY company name, country, number, or specific fact that does NOT appear anywhere in the source excerpts above? Be strict — a fact must appear word-for-word or as a clear paraphrase of something actually in the excerpts, not just be plausible.

Answer ONLY "yes" (something was added that isn't in the sources) or "no" (everything in the draft is grounded in the sources)."""
    verdict = generate_with_groq_fn(check_prompt, groq_client, max_tokens=10).strip().lower()
    return "yes" in verdict  # True = hallucination detected


def ask_eva(query, conversation_history, 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.85, bot_name="EVA"):

    if is_small_talk(query, groq_client, generate_with_groq_fn):
        answer = handle_small_talk(query, groq_client, generate_with_groq_fn, bot_name)
        conversation_history.append({'question': query, 'answer': answer})
        return {'answer': answer, 'exact_quote': None, 'source': None, 'domain': None}

    router_domain, confidence_or_probs = classify_query_fn(query, router_model, tokenizer, label_encoder)

    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 a clear, standalone, explicit search query — resolving any references
to earlier parts of the conversation. Keep it short. Only output the rewritten question.

New question: {query}

Rewritten question:"""
    rewritten = generate_with_groq_fn(rewrite_prompt, groq_client).strip()

    results = retrieve_hybrid_fn(rewritten, router_domain, embedding_model, domain_indices, domain_chunks_map,
                                   index, all_chunks, top_k=top_k)

    best_distance = results[0][0]
    fallback_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?"

    if best_distance > hallucination_threshold:
        conversation_history.append({'question': query, 'answer': fallback_answer})
        return {'answer': fallback_answer, 'exact_quote': None, 'source': None, 'domain': router_domain}

    actual_domain = results[0][1].get('domain', router_domain)

    context_text = "\n\n".join([f"[Source: {c['domain']} - {c['title']}]\n{c['text']}" for dist, c in results])
    prompt = f"""You are {bot_name}, answering a colleague's question directly and conversationally — like a knowledgeable coworker, not a report generator.

STRICT RULES:
1. Use ONLY facts, numbers, company names, and country names that appear WORD-FOR-WORD in the context below. Never add outside facts, even ones you're confident are true.
2. Does the context below actually answer the question — not just share a word, but genuinely address what's asked? If not, respond with EXACTLY: {NOT_FOUND_MARKER}
3. Otherwise, answer normally: 1-2 sentence direct lead-in, then 2-4 short bullets only using facts/companies present in the context. No source names, no citations, no headers.

Context:
{context_text}

Question: {query}

Answer:"""
    answer = generate_with_groq_fn(prompt, groq_client, max_tokens=350)

    if NOT_FOUND_MARKER in answer:
        conversation_history.append({'question': query, 'answer': fallback_answer})
        return {'answer': fallback_answer, 'exact_quote': None, 'source': None, 'domain': actual_domain}

    # Second-pass fact-check: catches the model inventing a company/number even on an in-scope topic
    if _verify_answer_grounded(answer, context_text, generate_with_groq_fn, groq_client):
        conversation_history.append({'question': query, 'answer': fallback_answer})
        return {'answer': fallback_answer, 'exact_quote': None, 'source': None, 'domain': actual_domain}

    exact_quote, _ = extract_exact_answer_fn(rewritten, results[0][1]['text'], qa_model, qa_tokenizer)

    conversation_history.append({'question': query, 'answer': answer})
    return {'answer': answer, 'exact_quote': exact_quote, 'source': results[0][1]['title'], 'domain': actual_domain}