File size: 19,568 Bytes
aa3c874
 
 
 
 
 
 
 
 
 
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
 
 
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
 
 
 
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
752f5cc
aa3c874
 
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
752f5cc
 
 
 
 
aa3c874
 
 
 
 
 
 
752f5cc
aa3c874
 
 
752f5cc
 
 
 
 
 
 
 
aa3c874
 
 
 
 
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
 
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
 
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
 
 
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
 
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
752f5cc
aa3c874
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
752f5cc
 
aa3c874
 
752f5cc
 
 
 
 
aa3c874
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
 
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
 
 
 
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
 
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
752f5cc
aa3c874
752f5cc
aa3c874
752f5cc
aa3c874
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
 
 
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
 
 
 
 
 
752f5cc
aa3c874
752f5cc
aa3c874
752f5cc
aa3c874
752f5cc
 
 
 
aa3c874
 
 
 
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
 
 
752f5cc
aa3c874
752f5cc
 
 
aa3c874
 
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
752f5cc
aa3c874
752f5cc
aa3c874
 
 
 
 
 
 
 
 
 
 
 
 
752f5cc
 
aa3c874
752f5cc
aa3c874
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
 
 
 
 
 
752f5cc
aa3c874
752f5cc
aa3c874
752f5cc
aa3c874
 
752f5cc
aa3c874
752f5cc
aa3c874
 
 
 
 
 
 
 
 
 
 
 
 
 
 
752f5cc
aa3c874
 
 
 
 
 
752f5cc
 
 
 
aa3c874
752f5cc
aa3c874
 
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
752f5cc
aa3c874
 
 
 
 
 
752f5cc
 
 
 
 
 
aa3c874
752f5cc
aa3c874
752f5cc
aa3c874
752f5cc
aa3c874
 
 
 
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
 
 
 
 
 
 
752f5cc
aa3c874
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
 
 
752f5cc
 
 
aa3c874
 
 
 
 
 
752f5cc
aa3c874
 
752f5cc
aa3c874
 
 
 
 
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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
"""
Agent Evaluator - Industry-Level Testing Harness

Implements LLM-as-Judge pattern for evaluating Roger Intelligence Platform agents.
Integrates with LangSmith for trace logging and provides comprehensive quality metrics.

Key Features:
- Tool selection accuracy evaluation
- Response quality scoring (relevance, coherence, accuracy)
- BLEU score for text similarity measurement
- Hallucination detection
- Graceful degradation testing
- LangSmith trace integration
"""

import os
import sys
import json
import time
import re
from collections import Counter
from pathlib import Path
from typing import Dict, Any, List, Optional, Tuple
from datetime import datetime
from dataclasses import dataclass, field

# Add project root to path
PROJECT_ROOT = Path(__file__).parent.parent.parent
sys.path.insert(0, str(PROJECT_ROOT))


@dataclass
class EvaluationResult:
    """Result of a single evaluation test."""

    test_id: str
    category: str
    query: str
    passed: bool
    score: float  # 0.0 - 1.0
    tool_selection_correct: bool
    response_quality: float
    hallucination_detected: bool
    latency_ms: float
    details: Dict[str, Any] = field(default_factory=dict)
    error: Optional[str] = None


@dataclass
class EvaluationReport:
    """Aggregated evaluation report."""

    timestamp: str
    total_tests: int
    passed_tests: int
    failed_tests: int
    average_score: float
    tool_selection_accuracy: float
    response_quality_avg: float
    hallucination_rate: float
    average_latency_ms: float
    results: List[EvaluationResult] = field(default_factory=list)

    def to_dict(self) -> Dict[str, Any]:
        return {
            "timestamp": self.timestamp,
            "summary": {
                "total_tests": self.total_tests,
                "passed_tests": self.passed_tests,
                "failed_tests": self.failed_tests,
                "pass_rate": self.passed_tests / max(self.total_tests, 1),
                "average_score": self.average_score,
                "tool_selection_accuracy": self.tool_selection_accuracy,
                "response_quality_avg": self.response_quality_avg,
                "hallucination_rate": self.hallucination_rate,
                "average_latency_ms": self.average_latency_ms,
            },
            "results": [
                {
                    "test_id": r.test_id,
                    "category": r.category,
                    "passed": r.passed,
                    "score": r.score,
                    "tool_selection_correct": r.tool_selection_correct,
                    "response_quality": r.response_quality,
                    "hallucination_detected": r.hallucination_detected,
                    "latency_ms": r.latency_ms,
                    "error": r.error,
                }
                for r in self.results
            ],
        }


class AgentEvaluator:
    """
    Comprehensive agent evaluation harness.

    Implements the LLM-as-Judge pattern for evaluating:
    1. Tool Selection: Did the agent use the right tools?
    2. Response Quality: Is the response relevant and coherent?
    3. Hallucination Detection: Did the agent fabricate information?
    4. Graceful Degradation: Does it handle failures properly?
    """

    def __init__(self, llm=None, use_langsmith: bool = True):
        self.llm = llm
        self.use_langsmith = use_langsmith
        self.langsmith_client = None

        if use_langsmith:
            self._setup_langsmith()

    def _setup_langsmith(self):
        """Initialize LangSmith client for evaluation logging."""
        try:
            from src.config.langsmith_config import (
                get_langsmith_client,
                LangSmithConfig,
            )

            config = LangSmithConfig()
            config.configure()
            self.langsmith_client = get_langsmith_client()
            if self.langsmith_client:
                print("[Evaluator] ✓ LangSmith connected for evaluation tracing")
        except ImportError:
            print("[Evaluator] ⚠️ LangSmith not available, running without tracing")

    def load_golden_dataset(self, path: Optional[Path] = None) -> List[Dict]:
        """Load golden dataset for evaluation."""
        if path is None:
            path = (
                PROJECT_ROOT
                / "tests"
                / "evaluation"
                / "golden_datasets"
                / "expected_responses.json"
            )

        if path.exists():
            with open(path, "r", encoding="utf-8") as f:
                return json.load(f)
        else:
            print(f"[Evaluator] ⚠️ Golden dataset not found at {path}")
            return []

    def evaluate_tool_selection(
        self, expected_tools: List[str], actual_tools: List[str]
    ) -> Tuple[bool, float]:
        """
        Evaluate if the agent selected the correct tools.

        Returns:
            Tuple of (passed, score)
        """
        if not expected_tools:
            return True, 1.0

        expected_set = set(expected_tools)
        actual_set = set(actual_tools)

        # Calculate intersection
        correct = len(expected_set & actual_set)
        total_expected = len(expected_set)

        score = correct / total_expected if total_expected > 0 else 0.0
        passed = score >= 0.5  # At least half the expected tools used

        return passed, score

    def evaluate_response_quality(
        self,
        query: str,
        response: str,
        expected_contains: List[str],
        quality_threshold: float = 0.7,
    ) -> Tuple[bool, float]:
        """
        Evaluate response quality using keyword matching and structure.

        For production, this should use LLM-as-Judge with a quality rubric.
        This implementation provides a baseline heuristic.
        """
        if not response:
            return False, 0.0

        response_lower = response.lower()

        # Keyword matching score
        keyword_score = 0.0
        if expected_contains:
            matched = sum(1 for kw in expected_contains if kw.lower() in response_lower)
            keyword_score = matched / len(expected_contains)

        # Length and structure score
        word_count = len(response.split())
        length_score = min(1.0, word_count / 50)  # Expect at least 50 words

        # Combined score
        score = (keyword_score * 0.6) + (length_score * 0.4)
        passed = score >= quality_threshold

        return passed, score

    def calculate_bleu_score(
        self, reference: str, candidate: str, n_gram: int = 4
    ) -> float:
        """
        Calculate BLEU (Bilingual Evaluation Understudy) score for text similarity.

        BLEU measures the similarity between a candidate text and reference text
        based on n-gram precision. Higher scores indicate better similarity.

        Args:
            reference: Reference/expected text
            candidate: Generated/candidate text
            n_gram: Maximum n-gram to consider (default 4 for BLEU-4)

        Returns:
            BLEU score between 0.0 and 1.0
        """

        def tokenize(text: str) -> List[str]:
            """Simple tokenization - lowercase and split on non-alphanumeric."""
            return re.findall(r"\b\w+\b", text.lower())

        def get_ngrams(tokens: List[str], n: int) -> List[Tuple[str, ...]]:
            """Generate n-grams from token list."""
            return [tuple(tokens[i : i + n]) for i in range(len(tokens) - n + 1)]

        def modified_precision(
            ref_tokens: List[str], cand_tokens: List[str], n: int
        ) -> float:
            """Calculate modified n-gram precision with clipping."""
            if len(cand_tokens) < n:
                return 0.0

            cand_ngrams = get_ngrams(cand_tokens, n)
            ref_ngrams = get_ngrams(ref_tokens, n)

            if not cand_ngrams:
                return 0.0

            # Count n-grams
            cand_counts = Counter(cand_ngrams)
            ref_counts = Counter(ref_ngrams)

            # Clip counts by reference counts
            clipped_count = 0
            for ngram, count in cand_counts.items():
                clipped_count += min(count, ref_counts.get(ngram, 0))

            return clipped_count / len(cand_ngrams)

        def brevity_penalty(ref_len: int, cand_len: int) -> float:
            """Calculate brevity penalty for short candidates."""
            if cand_len == 0:
                return 0.0
            if cand_len >= ref_len:
                return 1.0
            return math.exp(1 - ref_len / cand_len)

        import math

        # Tokenize
        ref_tokens = tokenize(reference)
        cand_tokens = tokenize(candidate)

        if not ref_tokens or not cand_tokens:
            return 0.0

        # Calculate n-gram precisions
        precisions = []
        for n in range(1, n_gram + 1):
            p = modified_precision(ref_tokens, cand_tokens, n)
            precisions.append(p)

        # Avoid log(0)
        if any(p == 0 for p in precisions):
            return 0.0

        # Geometric mean of precisions (BLEU formula)
        log_precision_sum = sum(math.log(p) for p in precisions) / len(precisions)

        # Apply brevity penalty
        bp = brevity_penalty(len(ref_tokens), len(cand_tokens))

        bleu = bp * math.exp(log_precision_sum)

        return round(bleu, 4)

    def evaluate_bleu(
        self, expected_response: str, actual_response: str, threshold: float = 0.3
    ) -> Tuple[bool, float]:
        """
        Evaluate response using BLEU score.

        Args:
            expected_response: Reference/expected response text
            actual_response: Generated response text
            threshold: Minimum BLEU score to pass (default 0.3)

        Returns:
            Tuple of (passed, bleu_score)
        """
        bleu = self.calculate_bleu_score(expected_response, actual_response)
        passed = bleu >= threshold
        return passed, bleu

    def evaluate_response_quality_llm(
        self, query: str, response: str, context: str = ""
    ) -> Tuple[bool, float, str]:
        """
        LLM-as-Judge evaluation for response quality.

        Uses the configured LLM to judge response quality on a rubric.
        Requires self.llm to be set.

        Returns:
            Tuple of (passed, score, reasoning)
        """
        if not self.llm:
            # Fallback to heuristic
            passed, score = self.evaluate_response_quality(query, response, [])
            return passed, score, "LLM not available, used heuristic"

        judge_prompt = f"""You are an expert evaluator for an AI intelligence system.
Rate the following response on a scale of 0-10 based on:
1. Relevance to the query
2. Accuracy of information
3. Clarity and coherence
4. Completeness

Query: {query}

Response: {response}

{f"Context: {context}" if context else ""}

Provide your evaluation as JSON:
{{"score": <0-10>, "reasoning": "<brief explanation>", "issues": ["<issue1>", ...]}}
"""
        try:
            result = self.llm.invoke(judge_prompt)
            parsed = json.loads(result.content)
            score = parsed.get("score", 5) / 10.0
            reasoning = parsed.get("reasoning", "")
            return score >= 0.7, score, reasoning
        except Exception as e:
            return False, 0.5, f"Evaluation error: {e}"

    def detect_hallucination(
        self, response: str, source_data: Optional[Dict] = None
    ) -> Tuple[bool, float]:
        """
        Detect potential hallucinations in the response.

        Heuristic approach - checks for fabricated specifics.
        For production, should compare against source data.
        """
        hallucination_indicators = [
            "I don't have access to",
            "I cannot verify",
            "As of my knowledge",
            "I'm not able to confirm",
        ]

        response_lower = response.lower()

        # Check for uncertainty indicators (good sign - honest about limitations)
        has_uncertainty = any(
            ind.lower() in response_lower for ind in hallucination_indicators
        )

        # Check for overly specific claims without source
        # This is a simplified heuristic
        if source_data:
            # Compare claimed facts against source data
            pass

        # For now, if the response admits uncertainty when appropriate, less likely hallucinating
        hallucination_score = 0.2 if has_uncertainty else 0.5
        detected = hallucination_score > 0.6

        return detected, hallucination_score

    def evaluate_single(
        self,
        test_case: Dict[str, Any],
        agent_response: str,
        tools_used: List[str],
        latency_ms: float,
    ) -> EvaluationResult:
        """Run evaluation for a single test case."""
        test_id = test_case.get("id", "unknown")
        category = test_case.get("category", "unknown")
        query = test_case.get("query", "")
        expected_tools = test_case.get("expected_tools", [])
        expected_contains = test_case.get("expected_response_contains", [])
        quality_threshold = test_case.get("quality_threshold", 0.7)

        # Evaluate components
        tool_correct, tool_score = self.evaluate_tool_selection(
            expected_tools, tools_used
        )
        quality_passed, quality_score = self.evaluate_response_quality(
            query, agent_response, expected_contains, quality_threshold
        )
        hallucination_detected, halluc_score = self.detect_hallucination(agent_response)

        # Calculate overall score
        overall_score = (
            tool_score * 0.3 + quality_score * 0.5 + (1 - halluc_score) * 0.2
        )

        passed = tool_correct and quality_passed and not hallucination_detected

        return EvaluationResult(
            test_id=test_id,
            category=category,
            query=query,
            passed=passed,
            score=overall_score,
            tool_selection_correct=tool_correct,
            response_quality=quality_score,
            hallucination_detected=hallucination_detected,
            latency_ms=latency_ms,
            details={
                "tool_score": tool_score,
                "expected_tools": expected_tools,
                "actual_tools": tools_used,
            },
        )

    def run_evaluation(
        self, golden_dataset: Optional[List[Dict]] = None, agent_executor=None
    ) -> EvaluationReport:
        """
        Run full evaluation suite against golden dataset.

        Args:
            golden_dataset: List of test cases (loads default if None)
            agent_executor: Optional callable to execute agent (for live testing)

        Returns:
            EvaluationReport with aggregated results
        """
        if golden_dataset is None:
            golden_dataset = self.load_golden_dataset()

        if not golden_dataset:
            print("[Evaluator] ⚠️ No test cases to evaluate")
            return EvaluationReport(
                timestamp=datetime.now().isoformat(),
                total_tests=0,
                passed_tests=0,
                failed_tests=0,
                average_score=0.0,
                tool_selection_accuracy=0.0,
                response_quality_avg=0.0,
                hallucination_rate=0.0,
                average_latency_ms=0.0,
            )

        results = []

        for test_case in golden_dataset:
            print(f"[Evaluator] Running test: {test_case.get('id', 'unknown')}")

            start_time = time.time()

            if agent_executor:
                # Live evaluation with actual agent
                try:
                    response, tools_used = agent_executor(test_case["query"])
                except Exception as e:
                    result = EvaluationResult(
                        test_id=test_case.get("id", "unknown"),
                        category=test_case.get("category", "unknown"),
                        query=test_case.get("query", ""),
                        passed=False,
                        score=0.0,
                        tool_selection_correct=False,
                        response_quality=0.0,
                        hallucination_detected=False,
                        latency_ms=0.0,
                        error=str(e),
                    )
                    results.append(result)
                    continue
            else:
                # Mock evaluation (for testing the evaluator itself)
                response = f"Mock response for: {test_case.get('query', '')}"
                tools_used = test_case.get("expected_tools", [])[
                    :1
                ]  # Simulate partial tool use

            latency_ms = (time.time() - start_time) * 1000

            result = self.evaluate_single(
                test_case=test_case,
                agent_response=response,
                tools_used=tools_used,
                latency_ms=latency_ms,
            )
            results.append(result)

        # Aggregate results
        total = len(results)
        passed = sum(1 for r in results if r.passed)

        report = EvaluationReport(
            timestamp=datetime.now().isoformat(),
            total_tests=total,
            passed_tests=passed,
            failed_tests=total - passed,
            average_score=sum(r.score for r in results) / max(total, 1),
            tool_selection_accuracy=sum(1 for r in results if r.tool_selection_correct)
            / max(total, 1),
            response_quality_avg=sum(r.response_quality for r in results)
            / max(total, 1),
            hallucination_rate=sum(1 for r in results if r.hallucination_detected)
            / max(total, 1),
            average_latency_ms=sum(r.latency_ms for r in results) / max(total, 1),
            results=results,
        )

        return report

    def save_report(self, report: EvaluationReport, path: Optional[Path] = None):
        """Save evaluation report to JSON file."""
        if path is None:
            path = PROJECT_ROOT / "tests" / "evaluation" / "reports"
            path.mkdir(parents=True, exist_ok=True)
            path = path / f"eval_report_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"

        with open(path, "w", encoding="utf-8") as f:
            json.dump(report.to_dict(), f, indent=2)

        print(f"[Evaluator] ✓ Report saved to {path}")
        return path


def run_evaluation_cli():
    """CLI entry point for running evaluations."""
    print("=" * 60)
    print("Roger Intelligence Platform - Agent Evaluator")
    print("=" * 60)

    evaluator = AgentEvaluator(use_langsmith=True)

    # Run evaluation with mock executor (for testing)
    report = evaluator.run_evaluation()

    # Print summary
    print("\n" + "=" * 60)
    print("EVALUATION SUMMARY")
    print("=" * 60)
    print(f"Total Tests: {report.total_tests}")
    print(
        f"Passed: {report.passed_tests} ({report.passed_tests/max(report.total_tests,1)*100:.1f}%)"
    )
    print(f"Failed: {report.failed_tests}")
    print(f"Average Score: {report.average_score:.2f}")
    print(f"Tool Selection Accuracy: {report.tool_selection_accuracy*100:.1f}%")
    print(f"Response Quality Avg: {report.response_quality_avg*100:.1f}%")
    print(f"Hallucination Rate: {report.hallucination_rate*100:.1f}%")
    print(f"Average Latency: {report.average_latency_ms:.1f}ms")

    # Save report
    evaluator.save_report(report)

    return report


if __name__ == "__main__":
    run_evaluation_cli()