File size: 41,409 Bytes
8c10cf2 | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 | #!/usr/bin/env python3
"""Trajectory evaluation script - BookWriter-H_A2A project.
Supports 6 metrics: Exact / In-order / Any-order / Precision / Recall / Single-tool use.
Specialization:
- Chapter count (3-5): dynamically expand the chapter reference trajectory based on
`repeatable_patterns` and the actual trajectory.
- LangGraph `review_book`: dynamically build the Stage 3 reference trajectory based on
the per-sample `Chain: tools` parallel grouping pattern
(1+1+1+1, 2+1+1, 1+2+1, 1+1+2, 3+1, 1+3, 4).
Under the same `Chain: tools`, multiple tools are treated as one execution group in
the ideal order:
count_book_words → analyze_book_quality → extract_book_keywords → validate_book_markdown.
"""
import os
import re
import yaml
from pathlib import Path
from typing import List, Dict, Tuple, Optional
from collections import defaultdict
import pandas as pd
import math
from itertools import permutations, product
# ====================== Trajectory Parsing ======================
class TrajectoryParser:
"""Parse `execution_path.md` and extract SPAN/Chain/AGENT/LLM/Tool nodes."""
def __init__(self, md_file_path: str, extract_types: List[str] = None):
self.md_file_path = md_file_path
self.extract_types = extract_types or ["Tool"]
self.trajectory: List[str] = []
def parse(self) -> List[str]:
if not os.path.exists(self.md_file_path):
return []
with open(self.md_file_path, "r", encoding="utf-8") as f:
content = f.read()
m = re.search(r"## Execution Path Tree.*?```\n(.*?)```", content, re.DOTALL)
if not m:
return []
tree = m.group(1)
traj: List[str] = []
for line in tree.split("\n"):
clean = re.sub(r"^[│├└─\s]+", "", line).strip()
if not clean:
continue
clean = re.sub(r"^❌\s+", "", clean)
clean = re.sub(r"\s*\(retry\s+\d+\)", "", clean)
clean = re.sub(r"\s*\[RETRY\d+\]", "", clean)
clean = re.sub(r"\s*\[ERROR:[^\]]*\]", "", clean)
node = self._extract_node_info(clean)
if node and node["type"] in self.extract_types:
traj.append(node["action"])
self.trajectory = traj
return traj
def _extract_node_info(self, line: str) -> Optional[Dict[str, str]]:
# SPAN
span_match = re.match(r"\[SPAN\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
if span_match:
span_name = span_match.group(1).strip()
# a2a_call_chapter_writer_(chapter_title) → a2a_call_chapter_writer_*
span_name = re.sub(
r"a2a_call_chapter_writer_\([^)]*\)",
"a2a_call_chapter_writer_*",
span_name,
)
return {"type": "SPAN", "action": f"SPAN: {span_name}"}
# Chain (Crew_xxx.kickoff → Crew***.kickoff)
# Only take the part before the first "["; allow trailing stats and 📚BATCH tags
chain_match = re.match(r"\[Chain\]\s+([^\[]+)", line)
if chain_match:
chain_name = chain_match.group(1).strip()
chain_name = re.sub(
r"Crew_[a-f0-9\-]+\.kickoff", "Crew***.kickoff", chain_name
)
return {"type": "Chain", "action": f"Chain: {chain_name}"}
# AGENT
agent_match = re.match(r"\[AGENT\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
if agent_match:
agent_name = agent_match.group(1).strip()
agent_name = re.sub(r"\._execute_core$", "", agent_name)
return {"type": "AGENT", "action": f"AGENT: {agent_name}"}
# Tool (keep execute_tool prefix / ._use suffix / no prefix or suffix)
tool_match = re.match(
r"\[Tool\]\s+([^\[\]]+?)(?:\s+\[[\d.]+(?:ms|s)\])?(?:\s*@@@)?\s*$",
line,
)
if tool_match:
tool_name = tool_match.group(1).strip()
return {"type": "Tool", "action": f"Tool: {tool_name}"}
# LLM
llm_match = re.match(r"\[LLM\]\s+([^\(\[]+)", line)
if llm_match:
model_name = llm_match.group(1).strip()
return {"type": "LLM", "action": f"LLM: {model_name}"}
# Task / Crew Created (usually not extracted)
if re.match(r"\[Task Created\]", line):
return {"type": "Task Created", "action": "Task Created"}
if re.match(r"\[Crew Created\]", line):
return {"type": "Crew Created", "action": "Crew Created"}
return None
# ====================== Evaluator (with dynamic reference) ======================
class TrajectoryEvaluator:
def __init__(
self,
reference_trajectory: List[str],
repeatable_patterns: List[Dict] = None,
actual_chapter_count: Optional[int] = None,
review_book_pattern: Optional[List[int]] = None,
autogen_outline_pattern: Optional[str] = None,
) -> None:
self.base_reference = reference_trajectory[:]
self.repeatable_patterns = repeatable_patterns or []
self.review_book_pattern = review_book_pattern
self.autogen_outline_pattern = autogen_outline_pattern
# 1) Dynamic expansion for chapters
if actual_chapter_count is not None and self.repeatable_patterns:
ref_after_ch = self._build_dynamic_reference_for_chapters(
actual_chapter_count
)
else:
ref_after_ch = self.base_reference[:]
# 2) Dynamic expansion for AutoGen outline
if self.autogen_outline_pattern:
ref_after_autogen = self._build_dynamic_autogen_outline_reference(
ref_after_ch, self.autogen_outline_pattern
)
else:
ref_after_autogen = ref_after_ch
# 3) Dynamic expansion for LangGraph review_book
if self.review_book_pattern:
self.reference = self._build_dynamic_review_book_reference(
ref_after_autogen, self.review_book_pattern
)
else:
self.reference = ref_after_autogen
# ---------- Chapter count ----------
@staticmethod
def detect_chapter_count(predicted: List[str]) -> int:
write_idx = -1
review_idx = -1
for i, s in enumerate(predicted):
if s == "SPAN: write_chapters":
write_idx = i
elif s == "SPAN: review_book":
review_idx = i
break
if write_idx == -1:
return 4
end = review_idx if review_idx != -1 else len(predicted)
cnt = 0
for i in range(write_idx + 1, end):
if predicted[i] == "Chain: Crew***.kickoff":
cnt += 1
return cnt if cnt > 0 else 4
def _build_dynamic_reference_for_chapters(self, chapter_count: int) -> List[str]:
if not self.repeatable_patterns:
return self.base_reference[:]
pattern = self.repeatable_patterns[0]
ps, pe = pattern["start"], pattern["end"]
before = self.base_reference[:ps]
pat = self.base_reference[ps : pe + 1]
after = self.base_reference[pe + 1 :]
mn, mx = pattern.get("min", 3), pattern.get("max", 5)
if chapter_count < mn or chapter_count > mx:
repeat = 4
else:
repeat = chapter_count
out: List[str] = before.copy()
for _ in range(repeat):
out.extend(pat)
out.extend(after)
return out
# ---------- LangGraph review_book tools pattern ----------
@staticmethod
def detect_review_book_pattern(predicted: List[str]) -> Optional[List[int]]:
"""Infer the `Chain: tools` grouping pattern from actual LangGraph execution.
Returns a pattern like [1,1,1,1] / [2,1,1] / ... / [4], or None if detection fails.
"""
canonical = [
"Tool: count_book_words",
"Tool: analyze_book_quality",
"Tool: extract_book_keywords",
"Tool: validate_book_markdown",
]
# Start from Chain: LangGraph (fallback to SPAN: review_book)
start = -1
for i, s in enumerate(predicted):
if s == "Chain: LangGraph":
start = i
break
if start == -1:
for i, s in enumerate(predicted):
if s == "SPAN: review_book":
start = i
break
if start == -1:
return None
group_counts: List[int] = []
need = len(canonical)
idx = 0 # matched canonical index
i = start
while i < len(predicted) and idx < need:
s = predicted[i]
if s == "Chain: tools":
count_here = 0
i += 1
while i < len(predicted) and not predicted[i].startswith("Chain: "):
t = predicted[i]
if idx < need and t == canonical[idx]:
count_here += 1
idx += 1
i += 1
if count_here > 0:
group_counts.append(count_here)
else:
if s == "Chain: format_output":
break
i += 1
if idx != need or sum(group_counts) != need:
return None
allowed = {
(1, 1, 1, 1),
(2, 1, 1),
(1, 2, 1),
(1, 1, 2),
(3, 1),
(1, 3),
(4,),
}
if tuple(group_counts) not in allowed:
return None
return group_counts
def _split_review_book_stage(
self, stage3: List[str]
) -> Tuple[List[str], List[List[str]], List[str]]:
"""Split Stage3 into header, loops (up to 4), and footer."""
if len(stage3) < 4 + 5 + 4:
return stage3, [], []
header = stage3[:4]
loops: List[List[str]] = []
i = 4
while i + 4 < len(stage3) and len(loops) < 4:
a, b, c, d, e = stage3[i : i + 5]
if not a.startswith("AGENT: "):
break
if b != "LLM: *" or c != "Chain: _should_continue" or d != "Chain: tools":
break
if not e.startswith("Tool: "):
break
loops.append(stage3[i : i + 5])
i += 5
footer = stage3[i:]
return header, loops, footer
def _build_dynamic_review_book_reference(
self, reference: List[str], pattern: List[int]
) -> List[str]:
try:
start = reference.index("SPAN: review_book")
except ValueError:
return reference
before = reference[:start]
stage3 = reference[start:]
header, loops, footer = self._split_review_book_stage(stage3)
if not loops:
return reference
total = len(loops)
if sum(pattern) != total:
return reference
new_stage3: List[str] = header.copy()
idx = 0
for cnt in pattern:
first = loops[idx]
if cnt == 1:
new_stage3.extend(first)
else:
prefix = first[:-1] # exclude Tool
tools = [seg[-1] for seg in loops[idx : idx + cnt]]
new_stage3.extend(prefix + tools)
idx += cnt
new_stage3.extend(footer)
return before + new_stage3
# ---------- AutoGen outline dynamic pattern ----------
@staticmethod
def detect_autogen_outline_pattern(predicted: List[str]) -> str:
"""Detect the LLM/Tool pattern for AutoGen outline generation (researcher).
Returns:
- "compact": LLM → Tool1 → Tool2 → LLM (adjacent tools)
- "interleaved": LLM → Tool1 → LLM → Tool2 → LLM (one LLM between tools)
- "unknown": cannot be recognized or does not follow the rules
Rule: must start and end with LLM; between the two tools there can be at most one LLM.
"""
# Find the position of the researcher agent
start_idx = -1
for i, s in enumerate(predicted):
if s == "AGENT: invoke_agent researcher":
start_idx = i
break
if start_idx == -1:
return "unknown"
# Extract the LLM/Tool sequence under the researcher agent
sequence = []
i = start_idx + 1
# Find the next AGENT (end of researcher stage, then outliner)
while i < len(predicted):
s = predicted[i]
if s.startswith("AGENT: "):
break
if s.startswith("LLM: "):
sequence.append("LLM")
elif s.startswith("Tool: execute_tool bocha_websearch_tool"):
sequence.append("Tool1")
elif s.startswith("Tool: execute_tool extract_keywords"):
sequence.append("Tool2")
i += 1
# Validate the sequence
if not sequence or len(sequence) < 3:
return "unknown"
# Must start and end with LLM
if sequence[0] != "LLM" or sequence[-1] != "LLM":
return "unknown"
# The middle must include Tool1 and Tool2
middle = sequence[1:-1]
if "Tool1" not in middle or "Tool2" not in middle:
return "unknown"
# Determine the specific pattern
# Pattern A: LLM → Tool1 → Tool2 → LLM (adjacent tools)
if sequence == ["LLM", "Tool1", "Tool2", "LLM"]:
return "compact"
# Pattern B: LLM → Tool1 → LLM → Tool2 → LLM (one LLM between tools)
if sequence == ["LLM", "Tool1", "LLM", "Tool2", "LLM"]:
return "interleaved"
# Check for invalid patterns (more than one LLM between the two tools)
# Extract the elements between Tool1 and Tool2
try:
tool1_idx = middle.index("Tool1")
tool2_idx = middle.index("Tool2")
if tool1_idx < tool2_idx:
between = middle[tool1_idx + 1 : tool2_idx]
else:
# Tool2 appears before Tool1 (reversed order is accepted)
between = middle[tool2_idx + 1 : tool1_idx]
# At most one LLM in-between
llm_count = between.count("LLM")
if llm_count <= 1:
if llm_count == 0:
return "compact"
else:
return "interleaved"
except (ValueError, IndexError):
pass
return "unknown"
def _build_dynamic_autogen_outline_reference(
self, reference: List[str], pattern: str
) -> List[str]:
"""Build the reference trajectory variant for AutoGen outline generation.
Args:
reference: base reference trajectory
pattern: pattern type ("compact" or "interleaved")
Returns:
adjusted full reference trajectory
"""
if pattern == "compact":
# Already compact
return reference
if pattern != "interleaved":
# Unknown pattern
return reference
try:
# Locate the researcher agent
start_idx = reference.index("AGENT: invoke_agent researcher")
# Locate the outliner agent (end of researcher stage)
end_idx = -1
for i in range(start_idx + 1, len(reference)):
if reference[i] == "AGENT: invoke_agent outliner":
end_idx = i
break
if end_idx == -1:
return reference
# Split into 3 parts: prefix, researcher, suffix (starting from outliner)
before = reference[
: start_idx + 1
] # includes AGENT: invoke_agent researcher
after = reference[end_idx:] # starts from outliner
# Build the researcher segment for the interleaved pattern
researcher_part = [
"LLM: *",
"Tool: execute_tool bocha_websearch_tool",
"LLM: *", # insert an LLM between two tools
"Tool: execute_tool extract_keywords",
"LLM: *",
]
# Compose the full trajectory
return before + researcher_part + after
except (ValueError, IndexError):
# If parsing fails, return the original reference
return reference
# ---------- Matching and 6 metrics ----------
def _match_action(self, p: str, r: str) -> bool:
if p == r:
return True
if r == "LLM: *" and p.startswith("LLM: "):
return True
return False
def exact_match(self, predicted: List[str]) -> int:
if len(predicted) != len(self.reference):
return 0
for a, b in zip(predicted, self.reference):
if not self._match_action(a, b):
return 0
return 1
def in_order_match(self, predicted: List[str]) -> int:
if not self.reference:
return 1
ref_idx = 0
for s in predicted:
if ref_idx < len(self.reference) and self._match_action(
s, self.reference[ref_idx]
):
ref_idx += 1
return 1 if ref_idx == len(self.reference) else 0
def any_order_match(self, predicted: List[str]) -> int:
if not self.reference:
return 1
diagnosis = self.diagnose_any_order_match_failure(predicted)
return 1 if diagnosis["match"] else 0
def diagnose_any_order_match_failure(
self, predicted: List[str]
) -> Dict[str, object]:
"""Diagnose why `any_order_match` failed (simple overall match check)."""
if not self.reference:
return {
"match": True,
"failure_stage": None,
"missing_steps": [],
"missing_details": "",
}
pred_remaining = predicted.copy()
missing_steps: List[str] = []
for ref_action in self.reference:
matched = False
for i, pred_action in enumerate(pred_remaining):
if self._match_action(pred_action, ref_action):
pred_remaining.pop(i)
matched = True
break
if not matched:
missing_steps.append(ref_action)
if missing_steps:
return {
"match": False,
"failure_stage": "simple_match",
"missing_steps": missing_steps,
"missing_details": f"Missing {len(missing_steps)} required steps",
}
return {
"match": True,
"failure_stage": None,
"missing_steps": [],
"missing_details": "",
}
def precision(self, predicted: List[str]) -> float:
if not predicted:
return 1.0
if not self.reference:
return 0.0
ref_rem = self.reference.copy()
tp = 0
for p in predicted:
for i, r in enumerate(ref_rem):
if self._match_action(p, r):
tp += 1
ref_rem.pop(i)
break
fp = len(predicted) - tp
return tp / (tp + fp) if tp + fp > 0 else 0.0
def recall(self, predicted: List[str]) -> float:
if not self.reference:
return 1.0
if not predicted:
return 0.0
pred_rem = predicted.copy()
tp = 0
for r in self.reference:
for i, p in enumerate(pred_rem):
if self._match_action(p, r):
tp += 1
pred_rem.pop(i)
break
fn = len(self.reference) - tp
return tp / (tp + fn) if tp + fn > 0 else 0.0
def single_tool_use(self, predicted: List[str], tool_name: str) -> int:
for p in predicted:
if self._match_action(p, tool_name):
return 1
return 0
def evaluate_all(
self, predicted: List[str], target_tools: List[str]
) -> Dict[str, float]:
res = {
"exact_match": self.exact_match(predicted),
"in_order_match": self.in_order_match(predicted),
"any_order_match": self.any_order_match(predicted),
"precision": self.precision(predicted),
"recall": self.recall(predicted),
}
if target_tools:
used = sum(self.single_tool_use(predicted, t) for t in target_tools)
res["single_tool_use"] = used / len(target_tools)
return res
# ====================== Dataset Evaluation ======================
class DatasetEvaluator:
def __init__(self, config_file: str) -> None:
self.config_file = config_file
self.config = self._load_config()
self.reference_trajectory = self.config.get("reference_trajectory", [])
self.target_tools = self.config.get("target_tools", [])
self.models = self.config.get("models", [])
self.project_name = self.config.get("project_name", "BookWriter-H_A2A")
self.extract_types = self.config.get("extract_types", ["Tool"])
self.repeatable_patterns = self.config.get("repeatable_patterns", [])
# Permutable tool group configuration (used to generate dynamic reference trajectories)
self.permutable_tool_groups = self.config.get("permutable_tool_groups", {})
def _load_config(self) -> Dict:
if not os.path.exists(self.config_file):
print(f"⚠️ Config file not found: {self.config_file}")
return {}
with open(self.config_file, "r", encoding="utf-8") as f:
return yaml.safe_load(f)
def _generate_permuted_trajectories_for_mix(
self, base_trajectory: List[str]
) -> List[List[str]]:
"""
Generate all possible tool-permuted trajectories based on `permutable_tool_groups`
(specialized version).
Special handling:
1. CrewAI Chapter Writer: permute tools together with their surrounding LLM steps
2. LangGraph Book Reviewer: permute the entire loop block
(5 steps: AGENT → LLM → Chain → Chain tools → Tool)
Args:
base_trajectory: base reference trajectory
Returns:
A list of all possible permuted trajectories
"""
if not self.permutable_tool_groups:
return [base_trajectory]
# Collect all permutable tool groups and their positions in the trajectory
tool_groups_positions = []
for group_name, tools in self.permutable_tool_groups.items():
if "chapter_writer" in group_name:
# CrewAI Chapter Writer: simple permutation (Tool + surrounding LLM)
# Pattern: LLM → Tool → LLM
positions_blocks = []
for tool in tools:
# Find all occurrences of the tool in the trajectory
for i, action in enumerate(base_trajectory):
if action == tool:
# For a tool occurrence, look for an LLM before and after
if i > 0 and i < len(base_trajectory) - 1:
if (
base_trajectory[i - 1] == "LLM: *"
and base_trajectory[i + 1] == "LLM: *"
):
# Found the full block: LLM → Tool → LLM
positions_blocks.append((i - 1, i + 1, tool))
if len(positions_blocks) == len(tools):
tool_groups_positions.append(
(group_name, "chapter_writer", positions_blocks)
)
elif "book_reviewer" in group_name:
# LangGraph Book Reviewer: permute the entire loop block
# Pattern: AGENT: agent → LLM: * → Chain: _should_continue → Chain: tools → Tool: xxx
positions_blocks = []
for tool in tools:
# Find tool occurrences
for i, action in enumerate(base_trajectory):
if action == tool:
# Check whether it matches the LangGraph loop block pattern
if i >= 4:
block_start = i - 4
if (
base_trajectory[block_start] == "AGENT: agent"
and base_trajectory[block_start + 1] == "LLM: *"
and base_trajectory[block_start + 2]
== "Chain: _should_continue"
and base_trajectory[block_start + 3]
== "Chain: tools"
and base_trajectory[block_start + 4] == tool
):
# Found the full loop block (5 steps)
positions_blocks.append((block_start, i, tool))
if len(positions_blocks) == len(tools):
tool_groups_positions.append(
(group_name, "book_reviewer", positions_blocks)
)
if not tool_groups_positions:
return [base_trajectory]
# Generate all permutation combinations
all_trajectories = []
# Generate all permutations for each tool group
group_permutations = []
for group_name, group_type, blocks in tool_groups_positions:
# Extract tool order
tools_order = [tool for _, _, tool in blocks]
# Generate all permutations
perms = list(permutations(tools_order))
group_permutations.append([(blocks, perm, group_type) for perm in perms])
# Cartesian product: combine permutations across all tool groups
all_group_combinations = list(product(*group_permutations))
# Build a new trajectory for each combination
for combination in all_group_combinations:
new_trajectory = base_trajectory.copy()
# Apply all tool permutations in this combination
for blocks, perm, group_type in combination:
if group_type == "chapter_writer":
# CrewAI: swap LLM → Tool → LLM blocks
# blocks: [(start, end, tool), ...]
# perm: new tool order
old_blocks = []
for start, end, _ in blocks:
# Extract the full block (3 steps)
old_blocks.append(base_trajectory[start : end + 1])
# Reorder blocks based on the new order
old_tools = [tool for _, _, tool in blocks]
tool_to_block = dict(zip(old_tools, old_blocks))
# Replace blocks in the trajectory
for i, (start, end, old_tool) in enumerate(blocks):
new_tool = perm[i]
new_block = tool_to_block[new_tool].copy()
# Update the tool name inside the block (the middle element)
new_block[1] = new_tool
new_trajectory[start : end + 1] = new_block
elif group_type == "book_reviewer":
# LangGraph: swap entire loop blocks (5 steps)
# blocks: [(start, end, tool), ...]
# perm: new tool order
old_blocks = []
for start, end, _ in blocks:
# Extract the full block (5 steps)
old_blocks.append(base_trajectory[start : end + 1])
# Reorder blocks based on the new order
old_tools = [tool for _, _, tool in blocks]
tool_to_block = dict(zip(old_tools, old_blocks))
# Replace blocks in the trajectory
for i, (start, end, old_tool) in enumerate(blocks):
new_tool = perm[i]
new_block = tool_to_block[new_tool].copy()
# Update the tool name inside the block (the last element)
new_block[4] = new_tool
new_trajectory[start : end + 1] = new_block
all_trajectories.append(new_trajectory)
return all_trajectories
def _find_best_reference_trajectory(
self, predicted: List[str], candidate_references: List[List[str]]
) -> Tuple[List[str], Dict[str, float]]:
"""
Select the best reference trajectory among multiple candidates.
Strategy: compute match scores between each candidate reference and the predicted
trajectory using a weighted sum:
exact_match * 3 + in_order_match * 2 + any_order_match * 1
Args:
predicted: predicted trajectory
candidate_references: candidate reference trajectories
Returns:
(best reference trajectory, matching metrics for that best reference)
"""
best_reference = candidate_references[0]
best_score = -1
best_metrics = {}
for ref_trajectory in candidate_references:
evaluator = TrajectoryEvaluator(ref_trajectory)
# Compute key matching metrics
exact = evaluator.exact_match(predicted)
in_order = evaluator.in_order_match(predicted)
any_order = evaluator.any_order_match(predicted)
# Composite score: exact_match has the highest weight, then in_order_match
# Weighted sum: exact*3 + in_order*2 + any_order*1
score = exact * 3 + in_order * 2 + any_order * 1
if score > best_score:
best_score = score
best_reference = ref_trajectory
best_metrics = {
"exact_match": exact,
"in_order_match": in_order,
"any_order_match": any_order,
}
return best_reference, best_metrics
def collect_execution_paths(
self, model_name: str, base_dir: str
) -> List[Tuple[str, List[str]]]:
model_dir = Path(base_dir) / model_name / self.project_name / "test_results"
if not model_dir.exists():
print(f"⚠️ Model directory not found: {model_dir}")
return []
out: List[Tuple[str, List[str]]] = []
for session_dir in sorted(model_dir.iterdir()):
if not session_dir.is_dir():
continue
md_file = session_dir / "execution_path.md"
if not md_file.exists():
continue
parser = TrajectoryParser(str(md_file), extract_types=self.extract_types)
traj = parser.parse()
out.append((session_dir.name, traj))
return out
def evaluate_model(
self, model_name: str, base_dir: str, collect_failure_reasons: bool = False
) -> Dict[str, float]:
trajs = self.collect_execution_paths(model_name, base_dir)
if not trajs:
print(f"⚠️ No trajectory data found for model {model_name}")
return {}
all_metrics: Dict[str, List[float]] = defaultdict(list)
if collect_failure_reasons and not hasattr(self, "failure_reasons"):
self.failure_reasons = []
patterns: List[List[int]] = [
[1, 1, 1, 1],
[2, 1, 1],
[1, 2, 1],
[1, 1, 2],
[3, 1],
[1, 3],
[4],
]
for session_id, predicted in trajs:
chapter_count = TrajectoryEvaluator.detect_chapter_count(predicted)
# Detect AutoGen outline pattern
autogen_pattern_detected = (
TrajectoryEvaluator.detect_autogen_outline_pattern(predicted)
)
best_metrics: Optional[Dict[str, float]] = None
best_score: int = -1
best_evaluator: Optional[TrajectoryEvaluator] = None
# All possible AutoGen patterns
if autogen_pattern_detected and autogen_pattern_detected != "unknown":
autogen_patterns = ["compact", "interleaved"]
else:
autogen_patterns = [None] # no change
# Enumerate all combinations (AutoGen pattern × LangGraph pattern × tool permutations)
for autogen_pat in autogen_patterns:
for langgraph_pat in patterns:
# Step 1: create a base evaluator (apply chapter count, AutoGen pattern, LangGraph grouping)
base_evaluator = TrajectoryEvaluator(
self.reference_trajectory,
self.repeatable_patterns,
actual_chapter_count=chapter_count,
review_book_pattern=langgraph_pat,
autogen_outline_pattern=autogen_pat,
)
# Step 2: generate reference trajectories with tool permutations
if self.permutable_tool_groups:
candidate_refs = self._generate_permuted_trajectories_for_mix(
base_evaluator.reference
)
else:
candidate_refs = [base_evaluator.reference]
# Step 3: evaluate each permutation and pick the best
for candidate_ref in candidate_refs:
evaluator = TrajectoryEvaluator(candidate_ref)
m = evaluator.evaluate_all(predicted, self.target_tools)
# Use a weighted strategy: exact*3 + in_order*2 + any_order*1
score = (
int(m.get("exact_match", 0)) * 3
+ int(m.get("in_order_match", 0)) * 2
+ int(m.get("any_order_match", 0))
)
if score > best_score:
best_score = score
best_metrics = m
best_evaluator = evaluator
if best_metrics is None or best_evaluator is None:
evaluator = TrajectoryEvaluator(
self.reference_trajectory,
self.repeatable_patterns,
actual_chapter_count=chapter_count,
review_book_pattern=None,
autogen_outline_pattern=None,
)
best_metrics = best_evaluator.evaluate_all(predicted, self.target_tools)
metrics = best_metrics
for k, v in metrics.items():
all_metrics[k].append(v)
if collect_failure_reasons and metrics.get("any_order_match", 0) == 0:
diagnosis = best_evaluator.diagnose_any_order_match_failure(predicted)
missing_steps = diagnosis.get("missing_steps", [])
self.failure_reasons.append(
{
"model": model_name,
"session": session_id,
"chapter_count": chapter_count,
"failure_stage": diagnosis.get("failure_stage"),
"missing_steps_count": len(missing_steps),
"missing_details": diagnosis.get("missing_details", ""),
"first_missing_step": (
missing_steps[0] if missing_steps else "N/A"
),
}
)
avg: Dict[str, float] = {}
for k, vs in all_metrics.items():
avg[k] = sum(vs) / len(vs) if vs else 0.0
num_samples = len(trajs)
if num_samples > 0:
path_counter: Dict[Tuple[str, ...], int] = defaultdict(int)
for _, pred in trajs:
path_counter[tuple(pred)] += 1
unique_paths = len(path_counter)
avg["unique_path_ratio"] = unique_paths / num_samples
probs = [c / num_samples for c in path_counter.values()]
H = -sum(p * math.log(p) for p in probs if p > 0)
avg["path_entropy"] = H / math.log(len(probs)) if len(probs) > 1 else 0.0
else:
avg["unique_path_ratio"] = 0.0
avg["path_entropy"] = 0.0
avg["num_samples"] = num_samples
return avg
def evaluate_all_models(
self, base_dir: Optional[str] = None, collect_failure_reasons: bool = False
) -> pd.DataFrame:
if base_dir is None:
# Default RESULTS directory:
# This script is located at RESULTS/RQ1/BookWriter-H_A2A,
# so three levels up is RESULTS.
base_dir = str(Path(__file__).parent.parent.parent)
results = []
for model in self.models:
print(f"\n📊 Evaluating model: {model}")
metrics = self.evaluate_model(
model, base_dir, collect_failure_reasons=collect_failure_reasons
)
if metrics:
metrics["model"] = model
results.append(metrics)
print(f" ✅ Done, samples: {metrics['num_samples']}")
else:
print(" ❌ Skipped (no data)")
if not results:
print("\n❌ No model data found")
return pd.DataFrame()
df = pd.DataFrame(results)
cols = [
"model",
"num_samples",
"exact_match",
"in_order_match",
"any_order_match",
"precision",
"recall",
"single_tool_use",
"unique_path_ratio",
"path_entropy",
]
cols = [c for c in cols if c in df.columns]
return df[cols]
def save_failure_reasons(self, output_file: str = "any_order_match_failures.csv"):
if not hasattr(self, "failure_reasons") or not self.failure_reasons:
print("\n⚠️ No failure reason data collected")
return
output_path = Path(__file__).parent / output_file
df = pd.DataFrame(self.failure_reasons)
df.to_csv(output_path, index=False, encoding="utf-8")
print(f"\n✅ any_order_match failure reasons saved: {output_path}")
# ====================== CLI ======================
def main() -> None:
import argparse
parser = argparse.ArgumentParser(
description="Evaluate trajectory metrics for the BookWriter-H_A2A project"
)
parser.add_argument(
"--config",
type=str,
default="reference_trajectory.yaml",
help="Path to the reference trajectory config file (YAML)",
)
parser.add_argument(
"--base-dir",
type=str,
default=None,
help="Path to the RESULTS directory (defaults to two levels above this script)",
)
parser.add_argument(
"--output",
type=str,
default="evaluation_results.csv",
help="Output CSV file path",
)
parser.add_argument(
"--format",
type=str,
choices=["csv"],
default="csv",
help="Output format (Markdown output is disabled)",
)
parser.add_argument(
"--diagnose-failures",
action="store_true",
help="Diagnose any_order_match failures and generate a CSV",
)
args = parser.parse_args()
config_path = args.config
if not os.path.isabs(config_path):
config_path = os.path.join(os.path.dirname(__file__), config_path)
print("=" * 80)
print("Trajectory Evaluation Tool - BookWriter-H_A2A")
print("=" * 80)
print(f"\n📁 Config file: {config_path}")
evaluator = DatasetEvaluator(config_path)
print(f"📋 Project: {evaluator.project_name}")
print(f"🎯 Reference length: {len(evaluator.reference_trajectory)}")
print(f"🔧 Target tools: {len(evaluator.target_tools)}")
print(f"🤖 Models: {evaluator.models}")
if args.diagnose_failures:
print("🔍 Failure reason diagnosis enabled")
df = evaluator.evaluate_all_models(
args.base_dir, collect_failure_reasons=args.diagnose_failures
)
if df.empty:
print("\n❌ Evaluation failed: no data")
return
print("\n" + "=" * 80)
print("📊 Evaluation results summary")
print("=" * 80)
pd.set_option("display.max_columns", None)
pd.set_option("display.width", None)
pd.set_option("display.float_format", lambda x: f"{x:.4f}")
print("\n" + df.to_string(index=False))
out_dir = os.path.dirname(args.output) or "."
os.makedirs(out_dir, exist_ok=True)
if args.format in ["csv", "both"]:
df.to_csv(args.output, index=False)
print(f"\n✅ CSV saved: {args.output}")
if args.diagnose_failures:
evaluator.save_failure_reasons()
print("\n" + "=" * 80)
print("✅ Done")
print("=" * 80)
if __name__ == "__main__": # pragma: no cover
main()
|