""" Insurance AI Reliability Benchmark - Evaluation Script Scores AI agent responses against a ground-truth benchmark for insurance domain tasks: intent classification, routing decisions, and action completeness. Usage as CLI: python evaluate.py --benchmark data/test.jsonl --predictions predictions.jsonl --output results.json Usage as library: from evaluate import BenchmarkEvaluator evaluator = BenchmarkEvaluator.from_jsonl("data/test.jsonl") results = evaluator.evaluate(predictions) """ from __future__ import annotations import argparse import json import sys from collections import defaultdict from dataclasses import dataclass, field from pathlib import Path from typing import Any # --- Data Models --- @dataclass class BenchmarkItem: """A single ground-truth benchmark entry.""" id: str expected_intent: str expected_routing: str expected_actions: list[str] category: str = "uncategorized" difficulty: str = "medium" @classmethod def from_dict(cls, data: dict[str, Any]) -> BenchmarkItem: """Parse a benchmark item from a dictionary.""" return cls( id=data["id"], expected_intent=data["expected_intent"], expected_routing=data["expected_routing"], expected_actions=data["expected_actions"], category=data.get("category", "uncategorized"), difficulty=data.get("difficulty", "medium"), ) @dataclass class Prediction: """A single prediction from the AI agent.""" id: str predicted_intent: str predicted_routing: str predicted_actions: list[str] @classmethod def from_dict(cls, data: dict[str, Any]) -> Prediction: """Parse a prediction from a dictionary.""" return cls( id=data["id"], predicted_intent=data["predicted_intent"], predicted_routing=data["predicted_routing"], predicted_actions=data["predicted_actions"], ) @dataclass class ItemScore: """Scores for a single benchmark item.""" id: str intent_correct: bool routing_correct: bool action_completeness: float category: str difficulty: str @dataclass class GroupMetrics: """Aggregated metrics for a group of items (category, difficulty, or overall).""" count: int = 0 intent_accuracy: float = 0.0 routing_accuracy: float = 0.0 mean_action_completeness: float = 0.0 composite_score: float = 0.0 @dataclass class EvaluationResults: """Full evaluation results across all items.""" overall: GroupMetrics = field(default_factory=GroupMetrics) by_category: dict[str, GroupMetrics] = field(default_factory=dict) by_difficulty: dict[str, GroupMetrics] = field(default_factory=dict) item_scores: list[ItemScore] = field(default_factory=list) missing_predictions: list[str] = field(default_factory=list) extra_predictions: list[str] = field(default_factory=list) def to_dict(self) -> dict[str, Any]: """Serialize results to a dictionary.""" return { "overall": _group_to_dict(self.overall), "by_category": {k: _group_to_dict(v) for k, v in self.by_category.items()}, "by_difficulty": {k: _group_to_dict(v) for k, v in self.by_difficulty.items()}, "item_scores": [ { "id": s.id, "intent_correct": s.intent_correct, "routing_correct": s.routing_correct, "action_completeness": round(s.action_completeness, 4), "category": s.category, "difficulty": s.difficulty, } for s in self.item_scores ], "missing_predictions": self.missing_predictions, "extra_predictions": self.extra_predictions, } def summary(self) -> str: """Return a human-readable summary.""" lines = [ "=" * 60, "Insurance AI Reliability Benchmark - Results", "=" * 60, "", f" Items evaluated: {self.overall.count}", f" Missing predictions: {len(self.missing_predictions)}", f" Extra predictions: {len(self.extra_predictions)}", "", "Overall Metrics:", f" Intent Accuracy: {self.overall.intent_accuracy:.2%}", f" Routing Accuracy: {self.overall.routing_accuracy:.2%}", f" Action Completeness: {self.overall.mean_action_completeness:.2%}", f" Composite Score: {self.overall.composite_score:.2%}", "", ] if self.by_category: lines.append("By Category:") for name, m in sorted(self.by_category.items()): lines.append( f" {name:30s} n={m.count:3d} " f"intent={m.intent_accuracy:.2%} " f"routing={m.routing_accuracy:.2%} " f"actions={m.mean_action_completeness:.2%} " f"composite={m.composite_score:.2%}" ) lines.append("") if self.by_difficulty: lines.append("By Difficulty:") for name, m in sorted(self.by_difficulty.items()): lines.append( f" {name:30s} n={m.count:3d} " f"intent={m.intent_accuracy:.2%} " f"routing={m.routing_accuracy:.2%} " f"actions={m.mean_action_completeness:.2%} " f"composite={m.composite_score:.2%}" ) lines.append("") lines.append("=" * 60) return "\n".join(lines) def _group_to_dict(g: GroupMetrics) -> dict[str, Any]: """Serialize a GroupMetrics to a dictionary.""" return { "count": g.count, "intent_accuracy": round(g.intent_accuracy, 4), "routing_accuracy": round(g.routing_accuracy, 4), "mean_action_completeness": round(g.mean_action_completeness, 4), "composite_score": round(g.composite_score, 4), } # --- Core Metrics --- # Weights for the composite reliability score. INTENT_WEIGHT = 0.3 ROUTING_WEIGHT = 0.4 ACTIONS_WEIGHT = 0.3 def jaccard_similarity(a: list[str], b: list[str]) -> float: """Jaccard similarity between two lists treated as sets. Returns 1.0 if both are empty (nothing expected, nothing predicted). """ set_a = set(a) set_b = set(b) if not set_a and not set_b: return 1.0 union = set_a | set_b if not union: return 1.0 return len(set_a & set_b) / len(union) def composite_score( intent_acc: float, routing_acc: float, action_comp: float, ) -> float: """Weighted composite reliability score.""" return ( INTENT_WEIGHT * intent_acc + ROUTING_WEIGHT * routing_acc + ACTIONS_WEIGHT * action_comp ) def _aggregate(scores: list[ItemScore]) -> GroupMetrics: """Aggregate a list of item scores into group metrics.""" if not scores: return GroupMetrics() n = len(scores) intent_acc = sum(s.intent_correct for s in scores) / n routing_acc = sum(s.routing_correct for s in scores) / n action_comp = sum(s.action_completeness for s in scores) / n return GroupMetrics( count=n, intent_accuracy=intent_acc, routing_accuracy=routing_acc, mean_action_completeness=action_comp, composite_score=composite_score(intent_acc, routing_acc, action_comp), ) # --- Evaluator --- class BenchmarkEvaluator: """Evaluates AI agent predictions against a ground-truth benchmark. Args: benchmark: List of ground-truth benchmark items. """ def __init__(self, benchmark: list[BenchmarkItem]) -> None: self.benchmark = {item.id: item for item in benchmark} if len(self.benchmark) != len(benchmark): dupes = len(benchmark) - len(self.benchmark) raise ValueError(f"Benchmark contains {dupes} duplicate ID(s).") @classmethod def from_jsonl(cls, path: str | Path) -> BenchmarkEvaluator: """Load benchmark from a JSONL file. Each line must be a JSON object with at least: id, expected_intent, expected_routing, expected_actions Optional fields: category, difficulty """ items: list[BenchmarkItem] = [] path = Path(path) with path.open("r", encoding="utf-8") as f: for lineno, line in enumerate(f, start=1): line = line.strip() if not line: continue try: data = json.loads(line) except json.JSONDecodeError as e: raise ValueError(f"Invalid JSON at {path}:{lineno}: {e}") from e try: items.append(BenchmarkItem.from_dict(data)) except KeyError as e: raise ValueError(f"Missing field {e} at {path}:{lineno}") from e if not items: raise ValueError(f"No benchmark items found in {path}") return cls(items) def score_item(self, item: BenchmarkItem, pred: Prediction) -> ItemScore: """Score a single prediction against its benchmark item.""" return ItemScore( id=item.id, intent_correct=pred.predicted_intent == item.expected_intent, routing_correct=pred.predicted_routing == item.expected_routing, action_completeness=jaccard_similarity( pred.predicted_actions, item.expected_actions ), category=item.category, difficulty=item.difficulty, ) def evaluate( self, predictions: list[Prediction] | list[dict[str, Any]], ) -> EvaluationResults: """Evaluate a list of predictions against the benchmark. Args: predictions: List of Prediction objects or raw dicts. Returns: Full evaluation results with overall, category, and difficulty breakdowns. """ # Normalize input: accept dicts or Prediction objects. preds: dict[str, Prediction] = {} for p in predictions: if isinstance(p, dict): p = Prediction.from_dict(p) if p.id in preds: raise ValueError(f"Duplicate prediction ID: {p.id}") preds[p.id] = p # Score each benchmark item that has a prediction. item_scores: list[ItemScore] = [] missing: list[str] = [] for bid, item in self.benchmark.items(): if bid not in preds: missing.append(bid) continue item_scores.append(self.score_item(item, preds[bid])) # Identify extra predictions not in benchmark. extra = [pid for pid in preds if pid not in self.benchmark] # Build breakdowns. by_category: dict[str, list[ItemScore]] = defaultdict(list) by_difficulty: dict[str, list[ItemScore]] = defaultdict(list) for s in item_scores: by_category[s.category].append(s) by_difficulty[s.difficulty].append(s) return EvaluationResults( overall=_aggregate(item_scores), by_category={k: _aggregate(v) for k, v in by_category.items()}, by_difficulty={k: _aggregate(v) for k, v in by_difficulty.items()}, item_scores=item_scores, missing_predictions=missing, extra_predictions=extra, ) def evaluate_from_jsonl(self, path: str | Path) -> EvaluationResults: """Load predictions from a JSONL file and evaluate. Each line must be a JSON object with: id, predicted_intent, predicted_routing, predicted_actions """ predictions: list[Prediction] = [] path = Path(path) with path.open("r", encoding="utf-8") as f: for lineno, line in enumerate(f, start=1): line = line.strip() if not line: continue try: data = json.loads(line) except json.JSONDecodeError as e: raise ValueError( f"Invalid JSON at {path}:{lineno}: {e}" ) from e try: predictions.append(Prediction.from_dict(data)) except KeyError as e: raise ValueError( f"Missing field {e} at {path}:{lineno}" ) from e return self.evaluate(predictions) # --- CLI --- def parse_args(argv: list[str] | None = None) -> argparse.Namespace: """Parse command-line arguments.""" parser = argparse.ArgumentParser( description="Evaluate AI agent predictions against the insurance reliability benchmark.", formatter_class=argparse.RawDescriptionHelpFormatter, epilog=( "Example:\n" " python evaluate.py \\\n" " --benchmark data/test.jsonl \\\n" " --predictions predictions.jsonl \\\n" " --output results.json\n" ), ) parser.add_argument( "--benchmark", required=True, type=Path, help="Path to benchmark JSONL file (ground truth).", ) parser.add_argument( "--predictions", required=True, type=Path, help="Path to predictions JSONL file.", ) parser.add_argument( "--output", type=Path, default=None, help="Path to write JSON results. Prints to stdout if omitted.", ) parser.add_argument( "--quiet", action="store_true", help="Suppress the human-readable summary.", ) return parser.parse_args(argv) def main(argv: list[str] | None = None) -> None: """CLI entry point.""" args = parse_args(argv) evaluator = BenchmarkEvaluator.from_jsonl(args.benchmark) results = evaluator.evaluate_from_jsonl(args.predictions) # Print summary unless suppressed. if not args.quiet: print(results.summary(), file=sys.stderr) # Write or print JSON results. results_dict = results.to_dict() json_str = json.dumps(results_dict, indent=2, ensure_ascii=False) if args.output: args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(json_str, encoding="utf-8") print(f"\nResults written to {args.output}", file=sys.stderr) else: print(json_str) if __name__ == "__main__": main()