| |
| """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 |
|
|
|
|
| |
|
|
|
|
| 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_match = re.match(r"\[SPAN\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line) |
| if span_match: |
| span_name = span_match.group(1).strip() |
| |
| span_name = re.sub( |
| r"a2a_call_chapter_writer_\([^)]*\)", |
| "a2a_call_chapter_writer_*", |
| span_name, |
| ) |
| return {"type": "SPAN", "action": f"SPAN: {span_name}"} |
|
|
| |
| |
| 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_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_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_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}"} |
|
|
| |
| 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 |
|
|
|
|
| |
|
|
|
|
| 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 |
|
|
| |
| 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[:] |
|
|
| |
| 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 |
|
|
| |
| 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 |
|
|
| |
|
|
| @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 |
|
|
| |
|
|
| @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 = -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 |
|
|
| 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] |
| 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 |
|
|
| |
|
|
| @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. |
| """ |
| |
| 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" |
|
|
| |
| sequence = [] |
| i = start_idx + 1 |
|
|
| |
| 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 |
|
|
| |
| if not sequence or len(sequence) < 3: |
| return "unknown" |
|
|
| |
| if sequence[0] != "LLM" or sequence[-1] != "LLM": |
| return "unknown" |
|
|
| |
| middle = sequence[1:-1] |
| if "Tool1" not in middle or "Tool2" not in middle: |
| return "unknown" |
|
|
| |
| |
| if sequence == ["LLM", "Tool1", "Tool2", "LLM"]: |
| return "compact" |
|
|
| |
| if sequence == ["LLM", "Tool1", "LLM", "Tool2", "LLM"]: |
| return "interleaved" |
|
|
| |
| |
| try: |
| tool1_idx = middle.index("Tool1") |
| tool2_idx = middle.index("Tool2") |
|
|
| if tool1_idx < tool2_idx: |
| between = middle[tool1_idx + 1 : tool2_idx] |
| else: |
| |
| between = middle[tool2_idx + 1 : tool1_idx] |
|
|
| |
| 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": |
| |
| return reference |
|
|
| if pattern != "interleaved": |
| |
| return reference |
|
|
| try: |
| |
| start_idx = reference.index("AGENT: invoke_agent researcher") |
|
|
| |
| 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 |
|
|
| |
| before = reference[ |
| : start_idx + 1 |
| ] |
| after = reference[end_idx:] |
|
|
| |
| researcher_part = [ |
| "LLM: *", |
| "Tool: execute_tool bocha_websearch_tool", |
| "LLM: *", |
| "Tool: execute_tool extract_keywords", |
| "LLM: *", |
| ] |
|
|
| |
| return before + researcher_part + after |
|
|
| except (ValueError, IndexError): |
| |
| return reference |
|
|
| |
|
|
| 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 |
|
|
|
|
| |
|
|
|
|
| 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", []) |
| |
| 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] |
|
|
| |
| tool_groups_positions = [] |
|
|
| for group_name, tools in self.permutable_tool_groups.items(): |
| if "chapter_writer" in group_name: |
| |
| |
| positions_blocks = [] |
| for tool in tools: |
| |
| for i, action in enumerate(base_trajectory): |
| if action == tool: |
| |
| if i > 0 and i < len(base_trajectory) - 1: |
| if ( |
| base_trajectory[i - 1] == "LLM: *" |
| and base_trajectory[i + 1] == "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: |
| |
| |
| positions_blocks = [] |
| for tool in tools: |
| |
| for i, action in enumerate(base_trajectory): |
| if action == tool: |
| |
| 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 |
| ): |
| |
| 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] |
|
|
| |
| all_trajectories = [] |
|
|
| |
| group_permutations = [] |
| for group_name, group_type, blocks in tool_groups_positions: |
| |
| tools_order = [tool for _, _, tool in blocks] |
| |
| perms = list(permutations(tools_order)) |
| group_permutations.append([(blocks, perm, group_type) for perm in perms]) |
|
|
| |
| all_group_combinations = list(product(*group_permutations)) |
|
|
| |
| for combination in all_group_combinations: |
| new_trajectory = base_trajectory.copy() |
|
|
| |
| for blocks, perm, group_type in combination: |
| if group_type == "chapter_writer": |
| |
| |
| |
| old_blocks = [] |
| for start, end, _ in blocks: |
| |
| old_blocks.append(base_trajectory[start : end + 1]) |
|
|
| |
| old_tools = [tool for _, _, tool in blocks] |
| tool_to_block = dict(zip(old_tools, old_blocks)) |
|
|
| |
| for i, (start, end, old_tool) in enumerate(blocks): |
| new_tool = perm[i] |
| new_block = tool_to_block[new_tool].copy() |
| |
| new_block[1] = new_tool |
| new_trajectory[start : end + 1] = new_block |
|
|
| elif group_type == "book_reviewer": |
| |
| |
| |
| old_blocks = [] |
| for start, end, _ in blocks: |
| |
| old_blocks.append(base_trajectory[start : end + 1]) |
|
|
| |
| old_tools = [tool for _, _, tool in blocks] |
| tool_to_block = dict(zip(old_tools, old_blocks)) |
|
|
| |
| for i, (start, end, old_tool) in enumerate(blocks): |
| new_tool = perm[i] |
| new_block = tool_to_block[new_tool].copy() |
| |
| 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) |
|
|
| |
| exact = evaluator.exact_match(predicted) |
| in_order = evaluator.in_order_match(predicted) |
| any_order = evaluator.any_order_match(predicted) |
|
|
| |
| |
| 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) |
|
|
| |
| 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 |
|
|
| |
| if autogen_pattern_detected and autogen_pattern_detected != "unknown": |
| autogen_patterns = ["compact", "interleaved"] |
| else: |
| autogen_patterns = [None] |
|
|
| |
| for autogen_pat in autogen_patterns: |
| for langgraph_pat in patterns: |
| |
| base_evaluator = TrajectoryEvaluator( |
| self.reference_trajectory, |
| self.repeatable_patterns, |
| actual_chapter_count=chapter_count, |
| review_book_pattern=langgraph_pat, |
| autogen_outline_pattern=autogen_pat, |
| ) |
|
|
| |
| if self.permutable_tool_groups: |
| candidate_refs = self._generate_permuted_trajectories_for_mix( |
| base_evaluator.reference |
| ) |
| else: |
| candidate_refs = [base_evaluator.reference] |
|
|
| |
| for candidate_ref in candidate_refs: |
| evaluator = TrajectoryEvaluator(candidate_ref) |
| m = evaluator.evaluate_all(predicted, self.target_tools) |
| |
| 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: |
| |
| |
| |
| 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}") |
|
|
|
|
| |
|
|
|
|
| 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__": |
| main() |
|
|