""" Evaluation script: measures Recall@K, MAP@K, Precision, Latency, hallucination rate, and conversation quality against ground-truth test cases. Usage: python -m evaluation.evaluate python -m evaluation.evaluate --base-url https://your-deployment.onrender.com Outputs: - Console summary table - evaluation/results/eval_results.json """ from __future__ import annotations import argparse import json import statistics import time from dataclasses import dataclass, field from pathlib import Path from typing import Dict, List, Optional, Set import httpx # ────────────────────────────────────────────── # Ground-truth test cases — each has known relevant assessment IDs # These represent realistic HR professional queries. # ────────────────────────────────────────────── EVAL_CASES: List[Dict] = [ { "id": "tc001", "name": "Software Engineer (Python/SQL)", "query": "I need to assess a software engineer who will write Python and SQL code", "relevant_ids": [ "coding-python", "coding-sql", "verify-numerical", "verify-inductive", "tech-hiring-solution", ], "min_recommendations": 3, }, { "id": "tc002", "name": "Senior Manager Leadership", "query": "Looking for personality assessment for senior manager leadership role", "relevant_ids": [ "opq32r", "mq", "management-solution", "shl-360", "gsa", ], "min_recommendations": 2, }, { "id": "tc003", "name": "Graduate Cognitive", "query": "Graduate recruitment program — need cognitive reasoning tests", "relevant_ids": [ "verify-g-plus", "verify-numerical", "verify-verbal", "verify-inductive", "graduate-solution", ], "min_recommendations": 3, }, { "id": "tc004", "name": "Customer Service BPO", "query": "Customer service representative hiring, volume hiring, BPO", "relevant_ids": [ "customer-service-solution", "call-center-sim", "sjt", "verify-verbal", "retail-solution", ], "min_recommendations": 2, }, { "id": "tc005", "name": "Data Analyst", "query": "Data analyst role, Excel, Power BI, numerical skills", "relevant_ids": [ "excel-2016", "powerbi-assessment", "verify-numerical", "coding-sql", ], "min_recommendations": 2, }, { "id": "tc006", "name": "Sales Director", "query": "Sales director assessment with motivation and personality", "relevant_ids": [ "opq32r", "mq", "sales-assessment", "sjt", ], "min_recommendations": 2, }, { "id": "tc007", "name": "Java Backend Developer", "query": "Java developer backend engineer 3 years experience", "relevant_ids": [ "coding-java", "verify-inductive", "verify-numerical", "tech-hiring-solution", ], "min_recommendations": 2, }, { "id": "tc008", "name": "HiPo / Succession", "query": "High potential identification succession planning executive", "relevant_ids": [ "hipo-assessment", "opq32r", "management-solution", "shl-360", ], "min_recommendations": 2, }, { "id": "tc009", "name": "Administrative Assistant", "query": "Administrative assistant typing data entry office skills", "relevant_ids": [ "typing-test", "numerical-entry", "word-2016", "outlook-2016", ], "min_recommendations": 2, }, { "id": "tc010", "name": "Mechanical Engineer", "query": "Mechanical engineer manufacturing technical aptitude", "relevant_ids": [ "verify-mechanical", "verify-spatial", "verify-inductive", ], "min_recommendations": 2, }, { "id": "tc011", "name": "JD — Frontend Developer", "query": ( "We are looking for a Frontend Developer with 2+ years experience. " "Responsibilities include building responsive UIs with React and JavaScript. " "Requirements: proficiency in JavaScript, HTML/CSS, React. " "Nice to have: TypeScript, testing frameworks." ), "relevant_ids": [ "coding-javascript", "tech-hiring-solution", "verify-inductive", ], "min_recommendations": 2, }, { "id": "tc012", "name": "C# .NET Developer", "query": "Need to assess a C# .NET backend developer for enterprise applications", "relevant_ids": [ "coding-csharp", "tech-hiring-solution", "verify-inductive", ], "min_recommendations": 2, }, { "id": "tc013", "name": "Retail Volume Hiring", "query": "High volume retail store hiring for sales associates and cashiers", "relevant_ids": [ "retail-solution", "customer-service-solution", "sjt", ], "min_recommendations": 2, }, { "id": "tc014", "name": "Executive Assessment", "query": "Executive VP assessment for strategic leadership and decision making", "relevant_ids": [ "management-solution", "opq32r", "shl-360", "hipo-assessment", ], "min_recommendations": 2, }, { "id": "tc015", "name": "English Language BPO", "query": "English language proficiency test for BPO customer support agents", "relevant_ids": [ "language-english", "customer-service-solution", "call-center-sim", ], "min_recommendations": 2, }, ] @dataclass class EvalResult: """Result of evaluating a single test case against the API.""" case_id: str case_name: str query: str relevant_ids: List[str] returned_ids: List[str] = field(default_factory=list) latency_ms: float = 0.0 reply_length: int = 0 num_recommendations: int = 0 error: Optional[str] = None hallucinated_ids: List[str] = field(default_factory=list) schema_valid: bool = True def recall_at_k(self, k: int = 10) -> float: """Fraction of relevant docs found in top-k.""" if not self.relevant_ids: return 1.0 retrieved_set = set(self.returned_ids[:k]) relevant_set = set(self.relevant_ids) return len(retrieved_set & relevant_set) / len(relevant_set) def precision_at_k(self, k: int = 10) -> float: """Fraction of top-k that are relevant.""" if not self.returned_ids: return 0.0 retrieved = self.returned_ids[:k] relevant_set = set(self.relevant_ids) hits = sum(1 for rid in retrieved if rid in relevant_set) return hits / len(retrieved) def average_precision(self, k: int = 10) -> float: """Average Precision at k (for MAP calculation).""" relevant_set = set(self.relevant_ids) hits = 0 sum_precision = 0.0 for i, rid in enumerate(self.returned_ids[:k]): if rid in relevant_set: hits += 1 sum_precision += hits / (i + 1) if not relevant_set: return 1.0 return sum_precision / min(len(relevant_set), k) @property def hit_at_1(self) -> bool: return bool(self.returned_ids) and self.returned_ids[0] in set(self.relevant_ids) @property def hit_at_3(self) -> bool: return bool(set(self.returned_ids[:3]) & set(self.relevant_ids)) @property def hallucination_rate(self) -> float: """Fraction of returned IDs that don't exist in catalog.""" if not self.returned_ids: return 0.0 return len(self.hallucinated_ids) / len(self.returned_ids) def validate_response_schema(data: dict) -> List[str]: """Check that the response follows the exact assignment schema.""" errors = [] if "reply" not in data: errors.append("Missing 'reply' field") elif not isinstance(data["reply"], str): errors.append("'reply' must be a string") if "recommendations" not in data: errors.append("Missing 'recommendations' field") elif not isinstance(data["recommendations"], list): errors.append("'recommendations' must be a list") if "end_of_conversation" not in data: errors.append("Missing 'end_of_conversation' field") elif not isinstance(data["end_of_conversation"], bool): errors.append("'end_of_conversation' must be a boolean") for i, rec in enumerate(data.get("recommendations", [])): required = ["id", "name", "url", "test_type", "description", "reason", "confidence"] for field_name in required: if field_name not in rec: errors.append(f"Recommendation[{i}] missing '{field_name}'") if "confidence" in rec: if not (0.0 <= rec["confidence"] <= 1.0): errors.append(f"Recommendation[{i}] confidence out of [0,1] range") if "url" in rec: if not rec["url"].startswith("https://"): errors.append(f"Recommendation[{i}] URL not HTTPS") return errors def run_evaluation( base_url: str = "http://localhost:8000", catalog_ids: Optional[Set[str]] = None, ) -> Dict: """Run full evaluation suite against a running API instance.""" print(f"\n{'=' * 70}") print(" SHL Assessment Recommender — Evaluation Suite") print(f" Target: {base_url}") print(f" Cases: {len(EVAL_CASES)}") print(f"{'=' * 70}\n") results: List[EvalResult] = [] with httpx.Client(timeout=60.0) as client: # Health check try: health = client.get(f"{base_url}/health").json() catalog_size = health.get("catalog_size", 0) index_ready = health.get("vector_index_ready", False) print( f" ✓ Health OK | Catalog: {catalog_size} assessments | " f"Index: {'ready' if index_ready else 'NOT ready'}\n" ) except Exception as e: print(f" ✗ Health check failed: {e}\n") return {"error": str(e)} # Run each test case print(f" {'ID':<8} {'Name':<30} {'R@10':>6} {'P@10':>6} {'AP':>6} {'ms':>7} {'Recs':>5}") print(f" {'-'*8} {'-'*30} {'-'*6} {'-'*6} {'-'*6} {'-'*7} {'-'*5}") for tc in EVAL_CASES: result = EvalResult( case_id=tc["id"], case_name=tc["name"], query=tc["query"], relevant_ids=tc["relevant_ids"], ) t0 = time.perf_counter() try: resp = client.post( f"{base_url}/chat", json={"messages": [{"role": "user", "content": tc["query"]}]}, ) elapsed = (time.perf_counter() - t0) * 1000 result.latency_ms = elapsed if resp.status_code == 200: data = resp.json() # Schema validation schema_errors = validate_response_schema(data) result.schema_valid = len(schema_errors) == 0 result.returned_ids = [ r["id"] for r in data.get("recommendations", []) ] result.reply_length = len(data.get("reply", "")) result.num_recommendations = len(data.get("recommendations", [])) # Check for hallucinated IDs (not in catalog) if catalog_ids: result.hallucinated_ids = [ rid for rid in result.returned_ids if rid not in catalog_ids ] else: result.error = f"HTTP {resp.status_code}" except Exception as e: result.error = str(e) result.latency_ms = (time.perf_counter() - t0) * 1000 results.append(result) # Print per-case status = "✓" if not result.error else "✗" recall = result.recall_at_k(10) precision = result.precision_at_k(10) ap = result.average_precision(10) print( f" {status} {tc['id']:<6} {tc['name']:<30} " f"{recall:>5.2f} {precision:>5.2f} {ap:>5.2f} " f"{result.latency_ms:>6.0f} {result.num_recommendations:>4}" ) if result.error: print(f" ERROR: {result.error}") if result.hallucinated_ids: print(f" ⚠ Hallucinated: {result.hallucinated_ids}") # ── Summary statistics ── valid = [r for r in results if not r.error] if not valid: print("\n ✗ No valid results to summarize.") return {"error": "All cases failed"} recalls = [r.recall_at_k(10) for r in valid] precisions = [r.precision_at_k(10) for r in valid] aps = [r.average_precision(10) for r in valid] latencies = [r.latency_ms for r in valid] hits_1 = [r.hit_at_1 for r in valid] hits_3 = [r.hit_at_3 for r in valid] schema_ok = sum(1 for r in valid if r.schema_valid) halluc_rates = [r.hallucination_rate for r in valid] print(f"\n{'=' * 70}") print(" SUMMARY") print(f"{'=' * 70}") print(f" Cases evaluated: {len(valid)}/{len(EVAL_CASES)}") print(f" Mean Recall@10: {statistics.mean(recalls):.3f}") print(f" Mean Precision@10: {statistics.mean(precisions):.3f}") print(f" MAP@10: {statistics.mean(aps):.3f}") print(f" Hit@1: {sum(hits_1)}/{len(valid)} ({sum(hits_1)/len(valid):.1%})") print(f" Hit@3: {sum(hits_3)}/{len(valid)} ({sum(hits_3)/len(valid):.1%})") print(f" Schema compliance: {schema_ok}/{len(valid)}") print(f" Hallucination rate: {statistics.mean(halluc_rates):.3f}") print(f" Mean latency: {statistics.mean(latencies):.0f}ms") if len(latencies) > 1: sorted_lat = sorted(latencies) p95_idx = min(int(len(sorted_lat) * 0.95), len(sorted_lat) - 1) print(f" P50 latency: {statistics.median(latencies):.0f}ms") print(f" P95 latency: {sorted_lat[p95_idx]:.0f}ms") print(f" Max latency: {max(latencies):.0f}ms") print(f" Under 5s: {sum(1 for lt in latencies if lt < 5000)}/{len(latencies)}") # Save results output_dir = Path(__file__).parent / "results" output_dir.mkdir(exist_ok=True) output_path = output_dir / "eval_results.json" output_data = { "summary": { "cases_evaluated": len(valid), "total_cases": len(EVAL_CASES), "mean_recall_at_10": round(statistics.mean(recalls), 4), "mean_precision_at_10": round(statistics.mean(precisions), 4), "map_at_10": round(statistics.mean(aps), 4), "hit_at_1": round(sum(hits_1) / len(valid), 4), "hit_at_3": round(sum(hits_3) / len(valid), 4), "schema_compliance": f"{schema_ok}/{len(valid)}", "mean_hallucination_rate": round(statistics.mean(halluc_rates), 4), "mean_latency_ms": round(statistics.mean(latencies), 1), "p95_latency_ms": round(sorted(latencies)[min(int(len(latencies) * 0.95), len(latencies) - 1)], 1), "max_latency_ms": round(max(latencies), 1), "under_5s_pct": round(sum(1 for lt in latencies if lt < 5000) / len(latencies), 4), }, "cases": [ { "id": r.case_id, "name": r.case_name, "query": r.query, "recall_at_10": round(r.recall_at_k(10), 4), "precision_at_10": round(r.precision_at_k(10), 4), "average_precision": round(r.average_precision(10), 4), "hit_at_1": r.hit_at_1, "hit_at_3": r.hit_at_3, "latency_ms": round(r.latency_ms, 1), "num_recommendations": r.num_recommendations, "returned_ids": r.returned_ids, "relevant_ids": r.relevant_ids, "hallucinated_ids": r.hallucinated_ids, "schema_valid": r.schema_valid, "error": r.error, } for r in results ], } output_path.write_text(json.dumps(output_data, indent=2)) print(f"\n Results saved to: {output_path}") return output_data if __name__ == "__main__": parser = argparse.ArgumentParser(description="Evaluate SHL Recommender API") parser.add_argument( "--base-url", default="http://localhost:8000", help="API base URL (default: http://localhost:8000)", ) args = parser.parse_args() # Load catalog IDs for comprehensive hallucination check catalog_ids = None catalog_path = Path(__file__).parent.parent / "data" / "shl_catalog.json" if catalog_path.exists(): try: with open(catalog_path, "r", encoding="utf-8") as f: data = json.load(f) catalog_ids = {item["id"] for item in data} except Exception as e: print(f"Warning: Could not load catalog for hallucination check: {e}") run_evaluation(base_url=args.base_url, catalog_ids=catalog_ids)