File size: 10,334 Bytes
e86dfae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
"""
RAG Evaluation Tests — Gemini-powered (no external eval services)

Uses your existing Gemini API key to judge faithfulness and relevancy.
No DeepEval, no OpenAI, no Confident AI required.

Run:
    pytest tests/eval/test_rag_eval.py -v -m synthetic    # quick, no DB
    pytest tests/eval/test_rag_eval.py -v -m live          # full pipeline, needs DB
    pytest tests/eval/test_rag_eval.py -v                   # both
"""

import asyncio
import json
import logging
import re

import pytest

logger = logging.getLogger(__name__)


# ═══════════════════════════════════════════════════════════════════════════════
# GEMINI JUDGE — uses your existing Gemini key to score answers
# ═══════════════════════════════════════════════════════════════════════════════


def _gemini_judge(query: str, answer: str, context_chunks: list[str]) -> dict:
    """
    Ask Gemini to score the answer on faithfulness and relevancy.

    Returns:
        {"faithfulness": float, "relevancy": float, "reason": str}
    """
    import google.generativeai as genai

    from app.config import settings

    genai.configure(api_key=settings.GEMINI_API_KEY)
    model = genai.GenerativeModel(settings.GEMINI_MODEL)

    context_text = "\n---\n".join(
        f"[Chunk {i}]: {chunk}" for i, chunk in enumerate(context_chunks, 1)
    )

    judge_prompt = f"""You are an evaluation judge for a RAG (Retrieval-Augmented Generation) system.

## User Question
{query}

## Retrieved Context Chunks
{context_text}

## AI Answer
{answer}

## Your Task
Evaluate the AI answer on two dimensions and return ONLY valid JSON:

1. **Faithfulness** (0.0 to 1.0): Does every claim in the answer come ONLY from the retrieved context? Score 1.0 if all claims are grounded. Score 0.0 if the answer makes up facts not in the context.

2. **Relevancy** (0.0 to 1.0): Does the answer actually address the user's question? Score 1.0 if it directly answers. Score 0.0 if it's off-topic.

Return JSON only, no other text:
{{"faithfulness": 0.0, "relevancy": 0.0, "reason": "brief explanation"}}"""

    response = model.generate_content(judge_prompt)
    raw = response.text.strip()

    # Extract JSON from response (handle markdown code blocks)
    json_match = re.search(r"\{.*\}", raw, re.DOTALL)
    if json_match:
        return json.loads(json_match.group())

    return {
        "faithfulness": 0.0,
        "relevancy": 0.0,
        "reason": f"Failed to parse judge output: {raw[:200]}",
    }


# ═══════════════════════════════════════════════════════════════════════════════
# PART 1 — SYNTHETIC TESTS (no DB, instant)
# ═══════════════════════════════════════════════════════════════════════════════

_QUERY = (
    "What are the standard safety illumination requirements "
    "for underground coal mine haulage roads?"
)

_RETRIEVED_CONTEXT = [
    "Underground coal mine haulage roads shall be maintained in a condition "
    "affording safe passage. Illumination levels on haulage roads must meet "
    "the minimum standards prescribed in the Coal Mines Regulations 2017, "
    "Schedule IV.",
    "Regulation 115 of CMR 2017 specifies that every underground road used "
    "for haulage shall be provided with adequate lighting at all junctions, "
    "loading points, and switches. Minimum illumination of 10 lux is "
    "required at the floor level of main haulage roads.",
    "Mine operators must conduct regular inspections of all electrical "
    "lighting systems on haulage roads. Defective lighting must be "
    "repaired within 24 hours of reporting.",
]

_LLM_OUTPUT = (
    "According to Regulation 115 of the Coal Mines Regulations 2017, "
    "underground coal mine haulage roads must maintain a minimum illumination "
    "level of 10 lux at floor level on main haulage roads. Junctions, loading "
    "points, and switches also require adequate lighting. Defective lighting "
    "must be repaired within 24 hours of reporting."
)

_THRESHOLD = 0.70


@pytest.mark.synthetic
class TestSyntheticFaithfulness:
    """Does the LLM ground its answer in the provided context?"""

    def test_faithfulness_above_threshold(self):
        scores = _gemini_judge(_QUERY, _LLM_OUTPUT, _RETRIEVED_CONTEXT)
        assert scores["faithfulness"] >= _THRESHOLD, (
            f"Faithfulness {scores['faithfulness']:.2f} < {_THRESHOLD}. "
            f"Reason: {scores['reason']}"
        )


@pytest.mark.synthetic
class TestSyntheticRelevancy:
    """Does the LLM answer actually address the question?"""

    def test_relevancy_above_threshold(self):
        scores = _gemini_judge(_QUERY, _LLM_OUTPUT, _RETRIEVED_CONTEXT)
        assert scores["relevancy"] >= _THRESHOLD, (
            f"Relevancy {scores['relevancy']:.2f} < {_THRESHOLD}. "
            f"Reason: {scores['reason']}"
        )


# ═══════════════════════════════════════════════════════════════════════════════
# PART 2 — LIVE PIPELINE TESTS (needs PostgreSQL + API keys)
# ═══════════════════════════════════════════════════════════════════════════════

_LIVE_QUERIES = [
    "What are the MSHA requirements for underground coal mine ventilation?",
    "How often should mining equipment be inspected for safety compliance?",
    "What are the emergency evacuation procedures for coal mines?",
]


def _get_embedding_sync(text: str) -> list[float]:
    import google.generativeai as genai

    from app.config import settings

    genai.configure(api_key=settings.GEMINI_API_KEY)
    result = genai.embed_content(
        model=settings.EMBEDDING_MODEL,
        content=text,
        task_type="retrieval_query",
        output_dimensionality=768,
    )
    return result["embedding"]


def _get_llm_answer_sync(query: str, context_chunks: list[dict]) -> str:
    from app.services.chat_service import _SYSTEM_PROMPT
    from app.services.llm_provider import get_groq_client

    context_parts = []
    for i, chunk in enumerate(context_chunks, 1):
        pages = chunk.get("page_numbers", [])
        page_str = f"{pages[0]}" if pages else "unknown"
        file_name = chunk.get("file_name", "unknown.pdf")
        context_parts.append(
            f"Context chunk {i}: {chunk['text']} (Source: {file_name}, Page: {page_str})"
        )
    context = "\n".join(context_parts)

    user_msg = (
        f"## Document Context:\n{context}\n\n"
        f"## User Question:\n{query}\n\n"
        f"## Your Answer (cite [FileName, Page X] for every claim):\n"
    )

    client = get_groq_client()
    response = client.chat.completions.create(
        model="llama-3.3-70b-versatile",
        messages=[
            {"role": "system", "content": _SYSTEM_PROMPT},
            {"role": "user", "content": user_msg},
        ],
    )
    return response.choices[0].message.content


@pytest.mark.live
class TestLiveRAGPipeline:
    """End-to-end RAG evaluation against the real database."""

    @pytest.mark.parametrize("query", _LIVE_QUERIES, ids=lambda q: q[:50])
    def test_pipeline_faithfulness(self, query: str):
        from sqlalchemy import create_engine
        from sqlalchemy.orm import Session

        from app.config import settings

        query_embedding = _get_embedding_sync(query)

        engine = create_engine(settings.DATABASE_URL)
        with Session(engine) as db:
            from app.services.hybrid_search import hybrid_search

            chunks = asyncio.get_event_loop().run_until_complete(
                hybrid_search(
                    query_text=query,
                    query_embedding=query_embedding,
                    db=db,
                    user_id="eval-test-user",
                    top_k=5,
                )
            )

        if not chunks:
            pytest.skip("No documents in DB — upload documents first")

        answer = _get_llm_answer_sync(query, chunks)
        retrieval_context = [c["text"] for c in chunks]

        scores = _gemini_judge(query, answer, retrieval_context)

        assert scores["faithfulness"] >= _THRESHOLD, (
            f"Pipeline faithfulness {scores['faithfulness']:.2f} < {_THRESHOLD} "
            f"for: {query[:60]}... Reason: {scores['reason']}"
        )

    @pytest.mark.parametrize("query", _LIVE_QUERIES, ids=lambda q: q[:50])
    def test_pipeline_relevancy(self, query: str):
        from sqlalchemy import create_engine
        from sqlalchemy.orm import Session

        from app.config import settings

        query_embedding = _get_embedding_sync(query)

        engine = create_engine(settings.DATABASE_URL)
        with Session(engine) as db:
            from app.services.hybrid_search import hybrid_search

            chunks = asyncio.get_event_loop().run_until_complete(
                hybrid_search(
                    query_text=query,
                    query_embedding=query_embedding,
                    db=db,
                    user_id="eval-test-user",
                    top_k=5,
                )
            )

        if not chunks:
            pytest.skip("No documents in DB — upload documents first")

        answer = _get_llm_answer_sync(query, chunks)
        retrieval_context = [c["text"] for c in chunks]

        scores = _gemini_judge(query, answer, retrieval_context)

        assert scores["relevancy"] >= _THRESHOLD, (
            f"Pipeline relevancy {scores['relevancy']:.2f} < {_THRESHOLD} "
            f"for: {query[:60]}... Reason: {scores['reason']}"
        )