Repository navigation
Expand file tree
/
Copy patheval.py
More file actions
1463 lines (1228 loc) · 47.9 KB
/
Copy patheval.py
File metadata and controls
1463 lines (1228 loc) · 47.9 KB
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Schema-Driven Evaluation Script for Document Processing Agents
Two-layer evaluation:
1. Deterministic — field-by-field comparison (instant, reproducible, zero cost)
2. LLM-as-judge — single Gemini call per case producing a holistic alignment verdict
All field paths, section names, comparison groups, and status mappings are read
from master_data.yaml (or .json) — making this evaluator domain-agnostic.
The LLM layer is optional (--skip-llm to disable) and produces one of:
- ALIGNED: Agent output matches ground truth in all material respects
- PARTIALLY_ALIGNED: Correct decision but some field differences
- NOT_ALIGNED: Wrong decision or critical data errors
Usage:
# Full evaluation (deterministic + LLM)
python eval.py --ground-truth "exemplary_data" --agent-output output
# With explicit master data file
python eval.py --ground-truth "exemplary_data" --agent-output output \
--master-data ../invoice_master_data.yaml
# Deterministic only (no LLM, no cost)
python eval.py --ground-truth "exemplary_data" --agent-output output --skip-llm
# Single case
python eval.py --ground-truth "exemplary_data" --agent-output output --case case_001
# Custom financial tolerance (default: $0.02)
python eval.py --ground-truth "exemplary_data" --agent-output output --tolerance 0.05
"""
import argparse
import json
import os
import re
import sys
from datetime import datetime
from pathlib import Path
from typing import Any, Optional
# Optional LLM imports — only needed when --skip-llm is NOT set
_LLM_AVAILABLE = False
try:
from dotenv import load_dotenv
from google.cloud import aiplatform
from vertexai.generative_models import GenerativeModel
_LLM_AVAILABLE = True
except ImportError:
pass
# Resolve: eval/ -> invoice_processing/ -> agents/ -> project root
SCRIPT_DIR = Path(__file__).resolve().parent
AGENT_DIR = SCRIPT_DIR.parent
PROJECT_ROOT = AGENT_DIR.parent.parent
# Master data loader — provides domain-agnostic configuration
sys.path.insert(0, str(AGENT_DIR / "invoice_processing" / "shared_libraries"))
from master_data_loader import MasterData, load_master_data # noqa: E402
# ============================================================================
# CONFIGURATION
# ============================================================================
EVAL_OUTPUT_DIR = PROJECT_ROOT / "data" / "eval_results"
# Default financial tolerance for amount comparisons
DEFAULT_TOLERANCE = 0.02
# LLM configuration (only used when LLM evaluation is enabled)
def _init_llm() -> Optional["GenerativeModel"]:
"""Initialize LLM model. Returns None if unavailable."""
if not _LLM_AVAILABLE:
return None
# Load .env from project root
env_file = PROJECT_ROOT / ".env"
if not env_file.exists():
env_file = SCRIPT_DIR / ".env"
if env_file.exists():
load_dotenv(env_file)
else:
load_dotenv()
project_id = os.getenv("PROJECT_ID")
location = os.getenv("LOCATION", "us-central1")
model_name = os.getenv("GEMINI_FLASH_MODEL", "gemini-2.5-flash")
if not project_id:
return None
aiplatform.init(project=project_id, location=location)
return GenerativeModel(model_name)
# Hardcoded fallback — used only when no master data is provided
_FALLBACK_STATUS_TO_DECISION = {
"pending payment": "ACCEPT",
"rejected": "REJECT",
"to verify": "SET_ASIDE",
}
# ============================================================================
# COMPARISON FUNCTIONS
# ============================================================================
def parse_amount(value: str) -> float | None:
"""Parse a formatted amount string like '1,100.00' into a float."""
if value is None:
return None
try:
return float(str(value).replace(",", "").strip())
except (ValueError, TypeError):
return None
def amounts_match(gt_val: str, agent_val: str, tolerance: float) -> bool:
"""Check if two amount strings match within tolerance."""
gt = parse_amount(gt_val)
agent = parse_amount(agent_val)
if gt is None and agent is None:
return True
if gt is None or agent is None:
return False
return abs(gt - agent) <= tolerance
def normalize_string(val: str | None) -> str:
"""Normalize a string for comparison (lowercase, strip, collapse whitespace)."""
if val is None:
return ""
return " ".join(str(val).strip().lower().split())
def status_to_decision(
status: str, mapping: dict[str, str] | None = None
) -> str:
"""Map Invoice Status to decision class using master data or fallback."""
if mapping is None:
mapping = _FALLBACK_STATUS_TO_DECISION
return mapping.get(normalize_string(status), "UNKNOWN")
def parse_line_items(line_items_field: Any) -> list[dict]:
"""Parse the Line Items field (stored as JSON string in the schema)."""
if line_items_field is None:
return []
if isinstance(line_items_field, list):
return line_items_field
if isinstance(line_items_field, str):
try:
parsed = json.loads(line_items_field)
return parsed if isinstance(parsed, list) else []
except (json.JSONDecodeError, TypeError):
return []
return []
def compare_decision(
gt: dict, agent: dict, master: MasterData | None = None
) -> dict:
"""Compare the processing decision (ACCEPT/REJECT/SET_ASIDE).
Reads the decision field path and status-to-decision mapping from master data.
Falls back to hardcoded "Invoice Processing.Invoice Status" if no master data.
"""
if master:
decision_path = master.get_eval_decision_path()
status_mapping = master.get_eval_status_to_decision()
else:
decision_path = "Invoice Processing.Invoice Status"
status_mapping = _FALLBACK_STATUS_TO_DECISION
# Resolve the decision path (e.g., "Invoice Processing.Invoice Status")
parts = decision_path.split(".")
gt_status = gt
agent_status = agent
for part in parts:
gt_status = (
(gt_status or {}).get(part, "")
if isinstance(gt_status, dict)
else ""
)
agent_status = (
(agent_status or {}).get(part, "")
if isinstance(agent_status, dict)
else ""
)
gt_decision = status_to_decision(gt_status, status_mapping)
agent_decision = status_to_decision(agent_status, status_mapping)
match = gt_decision == agent_decision
return {
"ground_truth_status": gt_status,
"agent_status": agent_status,
"ground_truth_decision": gt_decision,
"agent_decision": agent_decision,
"match": match,
}
def compare_financials(gt: dict, agent: dict, tolerance: float) -> dict:
"""Compare financial amounts (total, pretax, tax)."""
gt_details = gt.get("Invoice Details") or {}
agent_details = agent.get("Invoice Details") or {}
fields = {
"Invoice Total": ("Invoice Total", tolerance),
"Pretax Total": ("Pretax Total", tolerance),
"Tax Amount": ("Tax Amount", tolerance),
}
results = {}
all_match = True
for label, (field_name, tol) in fields.items():
gt_val = gt_details.get(field_name, "")
agent_val = agent_details.get(field_name, "")
match = amounts_match(gt_val, agent_val, tol)
if not match:
all_match = False
results[label] = {
"ground_truth": gt_val,
"agent": agent_val,
"match": match,
}
# Currency
gt_currency = gt_details.get("Currency", "")
agent_currency = agent_details.get("Currency", "")
currency_match = normalize_string(gt_currency) == normalize_string(
agent_currency
)
results["Currency"] = {
"ground_truth": gt_currency,
"agent": agent_currency,
"match": currency_match,
}
if not currency_match:
all_match = False
results["all_match"] = all_match
return results
def compare_vendor(gt: dict, agent: dict) -> dict:
"""Compare vendor information."""
gt_vendor = gt.get("Vendor Information") or {}
agent_vendor = agent.get("Vendor Information") or {}
# Vendor name — normalized comparison
gt_name = normalize_string(gt_vendor.get("Vendor Name", ""))
agent_name = normalize_string(agent_vendor.get("Vendor Name", ""))
name_match = gt_name == agent_name
# Tax ID — exact after stripping whitespace
gt_tax_id = str(gt_vendor.get("Tax ID", "")).replace(" ", "").strip()
agent_tax_id = str(agent_vendor.get("Tax ID", "")).replace(" ", "").strip()
tax_id_match = gt_tax_id == agent_tax_id
return {
"Vendor Name": {
"ground_truth": gt_vendor.get("Vendor Name", ""),
"agent": agent_vendor.get("Vendor Name", ""),
"match": name_match,
},
"Tax ID": {
"ground_truth": gt_vendor.get("Tax ID", ""),
"agent": agent_vendor.get("Tax ID", ""),
"match": tax_id_match,
},
"all_match": name_match and tax_id_match,
}
def compare_header(gt: dict, agent: dict) -> dict:
"""Compare invoice header fields (number, date)."""
gt_details = gt.get("Invoice Details") or {}
agent_details = agent.get("Invoice Details") or {}
results = {}
all_match = True
for field in ["Vendor Invoice", "Invoice Date"]:
gt_val = str(gt_details.get(field, "")).strip()
agent_val = str(agent_details.get(field, "")).strip()
match = normalize_string(gt_val) == normalize_string(agent_val)
if not match:
all_match = False
results[field] = {
"ground_truth": gt_val,
"agent": agent_val,
"match": match,
}
results["all_match"] = all_match
return results
def compare_field_group(
gt: dict, agent: dict, group_config: dict, tolerance: float
) -> dict:
"""Generic field group comparison driven by eval_schema.comparison_groups.
This is the schema-driven replacement for compare_financials, compare_vendor,
and compare_header. Each group config specifies the section name and a list of
fields with their comparison type ("amount" or "string").
"""
section = group_config.get("section", "")
gt_section = gt.get(section) or {}
agent_section = agent.get(section) or {}
results = {}
all_match = True
for field in group_config.get("fields", []):
field_name = field["name"]
field_type = field.get("type", "string")
gt_val = str(gt_section.get(field_name, "")).strip()
agent_val = str(agent_section.get(field_name, "")).strip()
if field_type == "amount":
match = amounts_match(gt_val, agent_val, tolerance)
else:
match = normalize_string(gt_val) == normalize_string(agent_val)
if not match:
all_match = False
results[field_name] = {
"ground_truth": gt_val,
"agent": agent_val,
"match": match,
}
results["all_match"] = all_match
return results
def _compare_per_line_fields(
gt_items: list[dict],
agent_items: list[dict],
per_line_fields: list[str],
per_line_types: dict[str, str],
tolerance: float,
) -> list[dict]:
"""Compare individual line items field by field, returning a list of diffs."""
line_diffs = []
gt_sorted = sorted(gt_items, key=lambda x: x.get("line_number", 0))
agent_sorted = sorted(agent_items, key=lambda x: x.get("line_number", 0))
for gt_line, agent_line in zip(gt_sorted, agent_sorted, strict=False):
diffs = {}
for field_name in per_line_fields:
gt_val = str(gt_line.get(field_name, "")).strip()
agent_val = str(agent_line.get(field_name, "")).strip()
if per_line_types.get(field_name) == "amount":
match = amounts_match(gt_val, agent_val, tolerance)
else:
match = normalize_string(gt_val) == normalize_string(agent_val)
if not match:
diffs[field_name] = {"ground_truth": gt_val, "agent": agent_val}
if diffs:
line_diffs.append(
{
"line_number": gt_line.get("line_number"),
"differences": diffs,
}
)
return line_diffs
def compare_line_items_generic(
gt: dict, agent: dict, group_config: dict, tolerance: float
) -> dict:
"""Schema-driven line item comparison using per_line_fields from master data."""
source_key = group_config.get("source", "Line Items")
per_line_fields = [
f["name"] for f in group_config.get("per_line_fields", [])
]
per_line_types = {
f["name"]: f.get("type", "string")
for f in group_config.get("per_line_fields", [])
}
gt_items = parse_line_items(gt.get(source_key))
agent_items = parse_line_items(agent.get(source_key))
gt_count = len(gt_items)
agent_count = len(agent_items)
count_match = gt_count == agent_count
# Compare item codes (if item_code is in per_line_fields)
code_field = "item_code" if "item_code" in per_line_fields else None
if code_field:
gt_codes = sorted(
[item.get(code_field, "UNKNOWN") for item in gt_items]
)
agent_codes = sorted(
[item.get(code_field, "UNKNOWN") for item in agent_items]
)
codes_match = gt_codes == agent_codes
else:
gt_codes = []
agent_codes = []
codes_match = True
# Compare totals for amount fields
amount_fields = [
f for f in per_line_fields if per_line_types.get(f) == "amount"
]
total_checks = {}
for af in amount_fields:
gt_total = sum(
parse_amount(item.get(af, "0")) or 0 for item in gt_items
)
agent_total = sum(
parse_amount(item.get(af, "0")) or 0 for item in agent_items
)
total_checks[af] = {
"ground_truth": f"{gt_total:.2f}",
"agent": f"{agent_total:.2f}",
"match": abs(gt_total - agent_total) <= tolerance,
}
# Per-line comparison (by line_number if counts match)
line_diffs = (
_compare_per_line_fields(
gt_items, agent_items, per_line_fields, per_line_types, tolerance
)
if count_match
else []
)
all_match = (
count_match
and codes_match
and all(tc["match"] for tc in total_checks.values())
and len(line_diffs) == 0
)
result = {
"count": {
"ground_truth": gt_count,
"agent": agent_count,
"match": count_match,
},
"line_diffs": line_diffs,
"all_match": all_match,
}
if code_field:
result["item_codes"] = {
"ground_truth": gt_codes,
"agent": agent_codes,
"match": codes_match,
}
for af, tc in total_checks.items():
result[f"total_{af}"] = tc
return result
def compare_line_items(gt: dict, agent: dict, tolerance: float) -> dict:
"""Compare line items between ground truth and agent output (legacy fallback)."""
gt_items = parse_line_items(gt.get("Line Items"))
agent_items = parse_line_items(agent.get("Line Items"))
gt_count = len(gt_items)
agent_count = len(agent_items)
count_match = gt_count == agent_count
# Compare item codes
gt_codes = sorted([item.get("item_code", "UNKNOWN") for item in gt_items])
agent_codes = sorted(
[item.get("item_code", "UNKNOWN") for item in agent_items]
)
codes_match = gt_codes == agent_codes
# Compare total line cost
gt_total = sum(
parse_amount(item.get("line_cost", "0")) or 0 for item in gt_items
)
agent_total = sum(
parse_amount(item.get("line_cost", "0")) or 0 for item in agent_items
)
total_match = abs(gt_total - agent_total) <= tolerance
# Compare total tax
gt_tax = sum(parse_amount(item.get("tax", "0")) or 0 for item in gt_items)
agent_tax = sum(
parse_amount(item.get("tax", "0")) or 0 for item in agent_items
)
tax_match = abs(gt_tax - agent_tax) <= tolerance
# Per-line comparison (by line_number if counts match)
line_diffs = []
if count_match:
# Sort both by line_number
gt_sorted = sorted(gt_items, key=lambda x: x.get("line_number", 0))
agent_sorted = sorted(
agent_items, key=lambda x: x.get("line_number", 0)
)
for gt_line, agent_line in zip(gt_sorted, agent_sorted, strict=False):
diffs = {}
for field in [
"item_code",
"description",
"quantity",
"unit_cost",
"line_cost",
"tax",
"tax_code",
]:
gt_val = str(gt_line.get(field, "")).strip()
agent_val = str(agent_line.get(field, "")).strip()
if field in ["line_cost", "unit_cost", "tax", "quantity"]:
match = amounts_match(gt_val, agent_val, tolerance)
else:
match = normalize_string(gt_val) == normalize_string(
agent_val
)
if not match:
diffs[field] = {"ground_truth": gt_val, "agent": agent_val}
if diffs:
line_diffs.append(
{
"line_number": gt_line.get("line_number"),
"differences": diffs,
}
)
all_match = (
count_match
and codes_match
and total_match
and tax_match
and len(line_diffs) == 0
)
return {
"count": {
"ground_truth": gt_count,
"agent": agent_count,
"match": count_match,
},
"item_codes": {
"ground_truth": gt_codes,
"agent": agent_codes,
"match": codes_match,
},
"total_line_cost": {
"ground_truth": f"{gt_total:.2f}",
"agent": f"{agent_total:.2f}",
"match": total_match,
},
"total_tax": {
"ground_truth": f"{gt_tax:.2f}",
"agent": f"{agent_tax:.2f}",
"match": tax_match,
},
"line_diffs": line_diffs,
"all_match": all_match,
}
# ============================================================================
# LLM-AS-JUDGE EVALUATION
# ============================================================================
LLM_EVAL_PROMPT_TEMPLATE = """You are evaluating a {domain_name} agent's output against ground truth.
Compare these two JSON documents and produce a holistic alignment verdict.
===GROUND TRUTH===
{ground_truth}
===AGENT OUTPUT===
{agent_output}
===DETERMINISTIC MISMATCHES ALREADY DETECTED===
{mismatches}
VERDICT CRITERIA:
ALIGNED — Agent output matches ground truth in all material respects.
The processing decision is correct. Financial amounts match. Vendor info matches.
Minor formatting differences (commas, whitespace, date format) are acceptable.
Outcome message timestamp/wording differences are acceptable.
PARTIALLY_ALIGNED — The processing decision (accept/reject) is correct, but
there are differences in non-critical fields such as line item descriptions,
item code classifications, or minor amount rounding.
NOT_ALIGNED — The processing decision is wrong (accepted when should reject
or vice versa), OR there are critical financial errors (wrong totals, wrong
tax amounts), OR vendor identification is wrong.
Respond with ONLY valid JSON, no markdown:
{{
"verdict": "ALIGNED" or "PARTIALLY_ALIGNED" or "NOT_ALIGNED",
"reason": "One sentence explaining the verdict"
}}"""
def llm_evaluate(
model: "GenerativeModel",
ground_truth: dict,
agent_output: dict,
mismatches: list[str],
domain_name: str = "invoice processing",
) -> dict | None:
"""Run a single LLM call to get holistic alignment verdict."""
prompt = LLM_EVAL_PROMPT_TEMPLATE.format(
domain_name=domain_name,
ground_truth=json.dumps(ground_truth, indent=2),
agent_output=json.dumps(agent_output, indent=2),
mismatches="\n".join(f"- {m}" for m in mismatches)
if mismatches
else "None detected",
)
try:
response = model.generate_content(prompt)
text = response.text.strip()
# Strip markdown code fences if present
if text.startswith("```"):
match = re.search(r"```(?:json)?\s*\n?(.*?)\n?```", text, re.DOTALL)
if match:
text = match.group(1).strip()
result = json.loads(text)
# Validate verdict value
verdict = result.get("verdict", "").upper()
if verdict not in ("ALIGNED", "PARTIALLY_ALIGNED", "NOT_ALIGNED"):
result["verdict"] = "NOT_ALIGNED"
result["reason"] = (
result.get("reason", "")
+ f" (original verdict '{verdict}' was invalid)"
)
return result
except Exception as e:
return {"verdict": "ERROR", "reason": str(e)}
# ============================================================================
# CASE EVALUATION
# ============================================================================
def _run_comparison_groups(
gt: dict, agent: dict, master: MasterData, tolerance: float
) -> dict[str, dict]:
"""Run all schema-driven comparison groups and return results keyed by group ID."""
group_results = {}
for group in master.get_eval_comparison_groups():
group_id = group.get("id", "")
if group.get("type", "") == "array":
group_results[group_id] = compare_line_items_generic(
gt, agent, group, tolerance
)
else:
group_results[group_id] = compare_field_group(
gt, agent, group, tolerance
)
return group_results
def _collect_schema_mismatches(
decision: dict, group_results: dict[str, dict]
) -> list[str]:
"""Collect mismatch descriptions from schema-driven comparison results."""
mismatches = []
if not decision["match"]:
mismatches.append(
f"Decision: {decision['ground_truth_decision']} vs {decision['agent_decision']}"
)
for _group_id, result in group_results.items():
if result.get("all_match"):
continue
for key, val in result.items():
if isinstance(val, dict) and "match" in val and not val["match"]:
mismatches.append(
f"{key}: {val.get('ground_truth', '?')} vs {val.get('agent', '?')}"
)
return mismatches
def _evaluate_schema_driven(
case_id: str,
gt: dict,
agent: dict,
decision: dict,
master: MasterData,
tolerance: float,
) -> dict:
"""Evaluate a case using schema-driven comparison groups from master data."""
group_results = _run_comparison_groups(gt, agent, master, tolerance)
mismatches = _collect_schema_mismatches(decision, group_results)
all_correct = decision["match"] and all(
r.get("all_match", True) for r in group_results.values()
)
result_dict = {
"case_id": case_id,
"status": "PASS" if all_correct else "FAIL",
"all_correct": all_correct,
"decision": decision,
"mismatches": mismatches,
}
for gid, result in group_results.items():
result_dict[gid] = result
# Keep backward-compatible keys for the standard invoice groups
for compat_key in ("financials", "vendor", "header", "line_items"):
if compat_key in group_results:
result_dict[compat_key] = group_results[compat_key]
return result_dict
def _evaluate_legacy(
case_id: str,
gt: dict,
agent: dict,
decision: dict,
tolerance: float,
) -> dict:
"""Evaluate a case using hardcoded invoice-specific comparators (legacy fallback)."""
financials = compare_financials(gt, agent, tolerance)
vendor = compare_vendor(gt, agent)
header = compare_header(gt, agent)
line_items = compare_line_items(gt, agent, tolerance)
all_correct = (
decision["match"]
and financials["all_match"]
and vendor["all_match"]
and header["all_match"]
and line_items["all_match"]
)
mismatches = _collect_legacy_mismatches(
decision, financials, vendor, header, line_items
)
return {
"case_id": case_id,
"status": "PASS" if all_correct else "FAIL",
"all_correct": all_correct,
"decision": decision,
"financials": financials,
"vendor": vendor,
"header": header,
"line_items": line_items,
"mismatches": mismatches,
}
def _collect_field_mismatches(section: dict, labels: list[str]) -> list[str]:
"""Collect mismatch strings for a list of field labels from a comparison section."""
mismatches = []
for label in labels:
if not section[label]["match"]:
mismatches.append(
f"{label}: {section[label]['ground_truth']} vs {section[label]['agent']}"
)
return mismatches
def _collect_line_item_mismatches(line_items: dict) -> list[str]:
"""Collect mismatch strings from line item comparison results."""
mismatches = []
if not line_items["count"]["match"]:
mismatches.append(
f"Line item count: {line_items['count']['ground_truth']} vs {line_items['count']['agent']}"
)
if not line_items["item_codes"]["match"]:
mismatches.append("Item codes differ")
if not line_items["total_line_cost"]["match"]:
mismatches.append(
f"Line cost total: {line_items['total_line_cost']['ground_truth']} vs {line_items['total_line_cost']['agent']}"
)
return mismatches
def _collect_legacy_mismatches(
decision: dict,
financials: dict,
vendor: dict,
header: dict,
line_items: dict,
) -> list[str]:
"""Collect mismatch descriptions from legacy comparator results."""
mismatches = []
if not decision["match"]:
mismatches.append(
f"Decision: {decision['ground_truth_decision']} vs {decision['agent_decision']}"
)
mismatches.extend(
_collect_field_mismatches(
financials,
["Invoice Total", "Pretax Total", "Tax Amount", "Currency"],
)
)
mismatches.extend(
_collect_field_mismatches(vendor, ["Vendor Name", "Tax ID"])
)
mismatches.extend(
_collect_field_mismatches(header, ["Vendor Invoice", "Invoice Date"])
)
mismatches.extend(_collect_line_item_mismatches(line_items))
return mismatches
def evaluate_case(
case_id: str,
gt_file: Path,
agent_file: Path,
tolerance: float,
llm_model: Any | None = None,
master: MasterData | None = None,
) -> dict:
"""Evaluate a single case by comparing ground truth and agent output.
When master data is provided, uses schema-driven comparison groups.
Otherwise falls back to the hardcoded invoice-specific comparators.
"""
# Load files
try:
gt = json.loads(gt_file.read_text(encoding="utf-8"))
except Exception as e:
return {
"case_id": case_id,
"status": "ERROR",
"error": f"Failed to load ground truth: {e}",
}
try:
agent = json.loads(agent_file.read_text(encoding="utf-8"))
except Exception as e:
return {
"case_id": case_id,
"status": "ERROR",
"error": f"Failed to load agent output: {e}",
}
# Decision comparison (always schema-driven when master data available)
decision = compare_decision(gt, agent, master)
# Field group comparisons — schema-driven or legacy fallback
if master:
result_dict = _evaluate_schema_driven(
case_id, gt, agent, decision, master, tolerance
)
else:
result_dict = _evaluate_legacy(case_id, gt, agent, decision, tolerance)
# LLM alignment verdict (optional)
llm_verdict = None
if llm_model is not None:
domain_name = master.display_name if master else "invoice processing"
llm_verdict = llm_evaluate(
llm_model, gt, agent, result_dict["mismatches"], domain_name
)
result_dict["llm_verdict"] = llm_verdict
return result_dict
# ============================================================================
# AGGREGATE STATISTICS
# ============================================================================
def _compute_decision_matrix(evaluated: list[dict]) -> dict[str, int]:
"""Compute the confusion matrix for accept/reject decisions."""
matrix = {"TP": 0, "FP": 0, "FN": 0, "TN": 0}
for r in evaluated:
gt_d = r["decision"]["ground_truth_decision"]
ag_d = r["decision"]["agent_decision"]
if gt_d == "ACCEPT" and ag_d == "ACCEPT":
matrix["TP"] += 1
elif gt_d == "REJECT" and ag_d == "REJECT":
matrix["TN"] += 1
elif gt_d == "REJECT" and ag_d == "ACCEPT":
matrix["FP"] += 1
elif gt_d == "ACCEPT" and ag_d == "REJECT":
matrix["FN"] += 1
return matrix
def _compute_group_and_field_stats_schema(
evaluated: list[dict], master: MasterData, total: int
) -> tuple:
"""Compute group-level and field-level accuracy using schema-driven config."""
group_accuracy = {}
field_stats = {}
for group in master.get_eval_comparison_groups():
group_id = group.get("id", "")
group_display = group.get("display_name", group_id)
group_type = group.get("type", "")
correct = sum(
1 for r in evaluated if r.get(group_id, {}).get("all_match", True)
)
group_accuracy[group_id] = {
"display_name": group_display,
"correct": correct,
"total": total,
"accuracy": correct / total,
}
if group_type != "array":
for field in group.get("fields", []):
fname = field["name"]
fc = sum(
1
for r in evaluated
if r.get(group_id, {}).get(fname, {}).get("match", True)
)
field_stats[fname] = {
"correct": fc,
"total": total,
"accuracy": fc / total,
}
return group_accuracy, field_stats
def _compute_group_and_field_stats_legacy(
evaluated: list[dict], total: int
) -> tuple:
"""Compute group-level and field-level accuracy using legacy hardcoded fields."""
group_accuracy = {}
field_stats = {}
for group_key in ["financials", "vendor", "header", "line_items"]:
correct = sum(
1 for r in evaluated if r.get(group_key, {}).get("all_match", True)
)
group_accuracy[group_key] = {
"display_name": group_key.replace("_", " ").title(),
"correct": correct,
"total": total,
"accuracy": correct / total,
}
legacy_field_groups = [
(
"financials",
["Invoice Total", "Pretax Total", "Tax Amount", "Currency"],
),
("vendor", ["Vendor Name", "Tax ID"]),
("header", ["Vendor Invoice", "Invoice Date"]),
]
for section_key, fields in legacy_field_groups:
for field in fields:
correct = sum(
1
for r in evaluated
if r.get(section_key, {}).get(field, {}).get("match", True)
)
field_stats[field] = {
"correct": correct,
"total": total,
"accuracy": correct / total,
}
return group_accuracy, field_stats
def _compute_llm_stats(evaluated: list[dict]) -> dict | None:
"""Compute LLM alignment statistics from evaluation results."""
llm_results = [
r
for r in evaluated
if r.get("llm_verdict") and r["llm_verdict"].get("verdict") != "ERROR"