| |
| """Trajectory evaluation script for the BookWriter-A2A project. |
| |
| This script evaluates 6 trajectory metrics: |
| 1. Exact match |
| 2. In-order match |
| 3. Any-order match |
| 4. Precision |
| 5. Recall |
| 6. Single-tool use |
| """ |
|
|
| import os |
| import re |
| import yaml |
| from pathlib import Path |
| from typing import List, Dict, Tuple, Set |
| from collections import defaultdict |
| import pandas as pd |
| import math |
| from itertools import permutations, product |
|
|
|
|
| class TrajectoryParser: |
| """Parse an execution_path.md file and extract the execution trajectory.""" |
|
|
| def __init__(self, md_file_path: str, extract_types: List[str] = None): |
| """ |
| Args: |
| md_file_path: Path to the execution_path.md file |
| extract_types: Node types to extract. Default: ['Tool']. |
| Options: 'SPAN', 'Chain', 'Tool', 'AGENT', 'LLM', 'Task Created', 'Crew Created' |
| """ |
| self.md_file_path = md_file_path |
| self.extract_types = extract_types or ["Tool"] |
| self.trajectory = [] |
|
|
| def parse(self) -> List[str]: |
| """Parse the file and return the execution trajectory sequence.""" |
| 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() |
|
|
| |
| tree_match = re.search( |
| r"## Execution Path Tree.*?```\n(.*?)```", content, re.DOTALL |
| ) |
| if not tree_match: |
| return [] |
|
|
| tree_content = tree_match.group(1) |
| trajectory = [] |
|
|
| for line in tree_content.split("\n"): |
| |
| clean_line = re.sub(r"^[│├└─\s]+", "", line).strip() |
| if not clean_line: |
| continue |
|
|
| |
| clean_line = re.sub(r"^❌\s+", "", clean_line) |
|
|
| |
| clean_line = re.sub(r"\s*\(retry\s+\d+\)", "", clean_line) |
| clean_line = re.sub(r"\s*\[RETRY\d+\]", "", clean_line) |
|
|
| |
| clean_line = re.sub(r"\s*\[ERROR:[^\]]*\]", "", clean_line) |
|
|
| |
| node_info = self._extract_node_info(clean_line) |
|
|
| if node_info and node_info["type"] in self.extract_types: |
| trajectory.append(node_info["action"]) |
|
|
| self.trajectory = trajectory |
| return trajectory |
|
|
| def _extract_node_info(self, line: str) -> dict: |
| """Extract node information from a line. |
| |
| Returns: |
| {'type': str, 'action': str} or None |
| """ |
| |
| |
| |
| 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+([^\[\s]+(?:\.[^\[\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() |
| |
| tool_name = re.sub(r"\._use$", "", tool_name) |
| 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}"} |
|
|
| |
| task_match = re.match(r"\[Task Created\]", line) |
| if task_match: |
| return {"type": "Task Created", "action": "Task Created"} |
|
|
| |
| crew_match = re.match(r"\[Crew Created\]", line) |
| if crew_match: |
| return {"type": "Crew Created", "action": "Crew Created"} |
|
|
| return None |
|
|
|
|
| class TrajectoryEvaluator: |
| """Trajectory evaluator (implements the 6 metrics).""" |
|
|
| def __init__( |
| self, |
| reference_trajectory: List[str], |
| repeatable_patterns: List[Dict] = None, |
| actual_chapter_count: int = None, |
| ): |
| """ |
| Args: |
| reference_trajectory: Base reference trajectory (ground truth, includes single-chapter pattern) |
| repeatable_patterns: Repeatable pattern definitions; each contains start, end, min, max |
| actual_chapter_count: Actual executed chapter count. If provided, a reference trajectory will be |
| generated dynamically for that count. |
| """ |
| self.base_reference = ( |
| reference_trajectory |
| ) |
| self.repeatable_patterns = repeatable_patterns or [] |
| self.use_simple_matching = False |
|
|
| |
| if actual_chapter_count is not None and self.repeatable_patterns: |
| self.reference = self._build_dynamic_reference(actual_chapter_count) |
| |
| |
| self.use_simple_matching = True |
| else: |
| self.reference = reference_trajectory |
| self.use_simple_matching = False |
|
|
| @staticmethod |
| def detect_chapter_count(predicted: List[str]) -> int: |
| """ |
| Detect the actual number of executed chapters. |
| |
| Heuristic: count the number of `Chain: Crew***.kickoff` entries inside the |
| `SPAN: write_chapters` region. |
| |
| Args: |
| predicted: The actual (predicted) trajectory |
| |
| Returns: |
| Chapter count. If detection fails, return 4 by default. |
| """ |
| |
| write_chapters_idx = -1 |
| review_book_idx = -1 |
|
|
| for i, step in enumerate(predicted): |
| if step == "SPAN: write_chapters": |
| write_chapters_idx = i |
| elif step == "SPAN: review_book": |
| review_book_idx = i |
| break |
|
|
| if write_chapters_idx == -1: |
| |
| return 4 |
|
|
| |
| if review_book_idx != -1: |
| search_end = review_book_idx |
| else: |
| search_end = len(predicted) |
|
|
| |
| chapter_count = 0 |
| for i in range(write_chapters_idx + 1, search_end): |
| if predicted[i] == "Chain: Crew***.kickoff": |
| chapter_count += 1 |
|
|
| |
| return chapter_count if chapter_count > 0 else 4 |
|
|
| def _build_dynamic_reference(self, chapter_count: int) -> List[str]: |
| """ |
| Dynamically build the reference trajectory based on the actual chapter count. |
| |
| Args: |
| chapter_count: Chapter count |
| |
| Returns: |
| Dynamically generated reference trajectory |
| """ |
| if not self.repeatable_patterns: |
| return self.base_reference |
|
|
| pattern = self.repeatable_patterns[0] |
| pattern_start = pattern["start"] |
| pattern_end = pattern["end"] |
|
|
| |
| before_pattern = self.base_reference[:pattern_start] |
| pattern_steps = self.base_reference[pattern_start : pattern_end + 1] |
| after_pattern = self.base_reference[pattern_end + 1 :] |
|
|
| |
| |
| if chapter_count < 3 or chapter_count > 5: |
| repeat_count = 4 |
| else: |
| repeat_count = chapter_count |
|
|
| |
| dynamic_reference = before_pattern.copy() |
| for _ in range(repeat_count): |
| dynamic_reference.extend(pattern_steps) |
| dynamic_reference.extend(after_pattern) |
|
|
| return dynamic_reference |
|
|
| def _match_action(self, predicted_action: str, reference_action: str) -> bool: |
| """ |
| Match two actions, supporting wildcards. |
| |
| Args: |
| predicted_action: Action from the actual trajectory |
| reference_action: Action from the reference trajectory (may contain wildcards) |
| |
| Returns: |
| True if match, False otherwise |
| """ |
| |
| if predicted_action == reference_action: |
| return True |
|
|
| |
| if reference_action == "LLM: *" and predicted_action.startswith("LLM: "): |
| return True |
|
|
| |
| if ( |
| reference_action == "SPAN: a2a_call_chapter_writer_*" |
| and predicted_action.startswith("SPAN: a2a_call_chapter_writer_") |
| ): |
| return True |
|
|
| return False |
|
|
| def exact_match(self, predicted: List[str]) -> int: |
| """ |
| Exact match: predicted trajectory must be identical to the reference trajectory (wildcards supported). |
| |
| Returns: |
| 1 if exact match, 0 otherwise |
| """ |
| if len(predicted) != len(self.reference): |
| return 0 |
|
|
| for i in range(len(predicted)): |
| if not self._match_action(predicted[i], self.reference[i]): |
| return 0 |
|
|
| return 1 |
|
|
| def in_order_match(self, predicted: List[str]) -> int: |
| """ |
| In-order match: reference trajectory must be a subsequence of the predicted trajectory (wildcards supported). |
| Allows extra actions, but core steps must appear in order. |
| Supports repeatable patterns (e.g., chapter repetition). |
| |
| Returns: |
| 1 if in-order match, 0 otherwise |
| """ |
| if not self.reference: |
| return 1 |
|
|
| |
| if self.use_simple_matching or not self.repeatable_patterns: |
| ref_idx = 0 |
| for pred_action in predicted: |
| if ref_idx < len(self.reference) and self._match_action( |
| pred_action, self.reference[ref_idx] |
| ): |
| ref_idx += 1 |
| return 1 if ref_idx == len(self.reference) else 0 |
|
|
| |
| |
| pattern = self.repeatable_patterns[0] |
| pattern_start = pattern["start"] |
| pattern_end = pattern["end"] |
|
|
| |
| before_pattern = self.reference[:pattern_start] |
| pattern_steps = self.reference[pattern_start : pattern_end + 1] |
| after_pattern = self.reference[pattern_end + 1 :] |
|
|
| pred_idx = 0 |
|
|
| |
| for ref_action in before_pattern: |
| while pred_idx < len(predicted): |
| if self._match_action(predicted[pred_idx], ref_action): |
| pred_idx += 1 |
| break |
| pred_idx += 1 |
| else: |
| return 0 |
|
|
| |
| pattern_matches = 0 |
| while pattern_matches < pattern["max"]: |
| |
| pattern_idx = 0 |
| start_pred_idx = pred_idx |
|
|
| for pattern_action in pattern_steps: |
| while pred_idx < len(predicted): |
| if self._match_action(predicted[pred_idx], pattern_action): |
| pred_idx += 1 |
| pattern_idx += 1 |
| break |
| pred_idx += 1 |
| else: |
| |
| break |
|
|
| |
| if pattern_idx == len(pattern_steps): |
| pattern_matches += 1 |
| else: |
| |
| pred_idx = start_pred_idx |
| break |
|
|
| |
| if pattern_matches < pattern["min"]: |
| return 0 |
|
|
| |
| for ref_action in after_pattern: |
| while pred_idx < len(predicted): |
| if self._match_action(predicted[pred_idx], ref_action): |
| pred_idx += 1 |
| break |
| pred_idx += 1 |
| else: |
| return 0 |
|
|
| return 1 |
|
|
| def diagnose_any_order_match_failure(self, predicted: List[str]) -> dict: |
| """ |
| Diagnose why any_order_match fails. |
| |
| Returns: |
| { |
| 'match': bool, |
| 'failure_stage': str ('before_pattern', 'pattern', 'after_pattern', None), |
| 'missing_steps': [str], |
| 'missing_details': str |
| } |
| """ |
| if not self.reference: |
| return { |
| "match": True, |
| "failure_stage": None, |
| "missing_steps": [], |
| "missing_details": "", |
| } |
|
|
| |
| if self.use_simple_matching or not self.repeatable_patterns: |
| pred_remaining = predicted.copy() |
| missing_steps = [] |
| 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": "", |
| } |
|
|
| |
| pattern = self.repeatable_patterns[0] |
| pattern_start = pattern["start"] |
| pattern_end = pattern["end"] |
|
|
| before_pattern = self.reference[:pattern_start] |
| pattern_steps = self.reference[pattern_start : pattern_end + 1] |
| after_pattern = self.reference[pattern_end + 1 :] |
|
|
| pred_remaining = predicted.copy() |
|
|
| |
| missing_before = [] |
| for ref_action in before_pattern: |
| 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_before.append(ref_action) |
|
|
| if missing_before: |
| return { |
| "match": False, |
| "failure_stage": "before_pattern", |
| "missing_steps": missing_before, |
| "missing_details": f"Missing {len(missing_before)} steps in the Outline stage", |
| } |
|
|
| |
| pattern_missing = [] |
| for ref_action in pattern_steps: |
| required_count = pattern["min"] |
| found_count = 0 |
|
|
| i = 0 |
| while i < len(pred_remaining) and found_count < required_count: |
| if self._match_action(pred_remaining[i], ref_action): |
| pred_remaining.pop(i) |
| found_count += 1 |
| else: |
| i += 1 |
|
|
| if found_count < required_count: |
| pattern_missing.append( |
| f"{ref_action} (required {required_count}, found {found_count})" |
| ) |
|
|
| if pattern_missing: |
| return { |
| "match": False, |
| "failure_stage": "pattern", |
| "missing_steps": pattern_missing, |
| "missing_details": f"Missing {len(pattern_missing)} steps in the chapter pattern (min {pattern['min']} per chapter)", |
| } |
|
|
| |
| missing_after = [] |
| for ref_action in after_pattern: |
| 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_after.append(ref_action) |
|
|
| if missing_after: |
| return { |
| "match": False, |
| "failure_stage": "after_pattern", |
| "missing_steps": missing_after, |
| "missing_details": f"Missing {len(missing_after)} steps in the Review stage", |
| } |
|
|
| return { |
| "match": True, |
| "failure_stage": None, |
| "missing_steps": [], |
| "missing_details": "", |
| } |
|
|
| def any_order_match(self, predicted: List[str]) -> int: |
| """ |
| Any-order match: the predicted trajectory must contain all required actions (wildcards supported). |
| Order is ignored and extra actions are allowed. |
| Supports repeatable patterns (e.g., chapter repetition). |
| |
| Returns: |
| 1 if any-order match, 0 otherwise |
| """ |
| diagnosis = self.diagnose_any_order_match_failure(predicted) |
| return 1 if diagnosis["match"] else 0 |
|
|
| def precision(self, predicted: List[str]) -> float: |
| """ |
| Precision: fraction of predicted actions that are considered correct by the reference (wildcards supported). |
| |
| Precision = TP / (TP + FP) |
| TP: number of correct actions in the prediction |
| FP: number of incorrect/extra actions in the prediction |
| |
| Returns: |
| precision value (0.0 - 1.0) |
| """ |
| if not predicted: |
| return 1.0 |
|
|
| if not self.reference: |
| return 0.0 |
|
|
| |
| ref_remaining = self.reference.copy() |
|
|
| tp = 0 |
| for pred_action in predicted: |
| |
| for i, ref_action in enumerate(ref_remaining): |
| if self._match_action(pred_action, ref_action): |
| tp += 1 |
| ref_remaining.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: |
| """ |
| Recall: fraction of the reference trajectory covered by the predicted trajectory (wildcards supported). |
| |
| Recall = TP / (TP + FN) |
| TP: number of required actions covered by the prediction |
| FN: number of required actions missed by the prediction |
| |
| Returns: |
| recall value (0.0 - 1.0) |
| """ |
| if not self.reference: |
| return 1.0 |
|
|
| if not predicted: |
| return 0.0 |
|
|
| |
| pred_remaining = predicted.copy() |
|
|
| tp = 0 |
| for ref_action in self.reference: |
| |
| for i, pred_action in enumerate(pred_remaining): |
| if self._match_action(pred_action, ref_action): |
| tp += 1 |
| pred_remaining.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: |
| """ |
| Single-tool use: check whether a specific tool/action appears in the trajectory (wildcards supported). |
| |
| Args: |
| predicted: Predicted trajectory |
| tool_name: Target tool/action name |
| |
| Returns: |
| 1 if tool is used, 0 otherwise |
| """ |
| |
| for pred_action in predicted: |
| if self._match_action(pred_action, tool_name): |
| return 1 |
| return 0 |
|
|
| def evaluate_all( |
| self, predicted: List[str], target_tools: List[str] = None |
| ) -> Dict[str, float]: |
| """ |
| Evaluate all metrics. |
| |
| Args: |
| predicted: Predicted trajectory |
| target_tools: Tools/actions to check for single-tool use |
| |
| Returns: |
| Dictionary of evaluation results |
| """ |
| results = { |
| "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: |
| tool_usage_count = sum( |
| self.single_tool_use(predicted, tool) for tool in target_tools |
| ) |
| results["single_tool_use"] = ( |
| tool_usage_count / len(target_tools) if target_tools else 0.0 |
| ) |
|
|
| return results |
|
|
|
|
| class DatasetEvaluator: |
| """Dataset-level evaluator.""" |
|
|
| def __init__(self, config_file: str): |
| """ |
| Args: |
| config_file: Path to the YAML config file that defines the reference trajectory |
| """ |
| 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-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: |
| """Load the YAML config file.""" |
| 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( |
| self, base_trajectory: List[str] |
| ) -> List[List[str]]: |
| """ |
| Generate all possible tool-order permutations according to permutable_tool_groups. |
| |
| Args: |
| base_trajectory: Base reference trajectory |
| |
| Returns: |
| List of permuted trajectories (including the original) |
| """ |
| if not self.permutable_tool_groups: |
| |
| return [base_trajectory] |
|
|
| |
| tool_groups_positions = [] |
|
|
| for group_name, tools in self.permutable_tool_groups.items(): |
| |
| positions = [] |
| tool_indices = {} |
|
|
| for i, action in enumerate(base_trajectory): |
| for tool in tools: |
| if action == tool: |
| positions.append(i) |
| tool_indices[i] = tool |
| break |
|
|
| |
| if len(positions) == len(tools): |
| |
| tools_at_positions = [tool_indices[pos] for pos in positions] |
| tool_groups_positions.append((positions, tools_at_positions)) |
|
|
| if not tool_groups_positions: |
| |
| return [base_trajectory] |
|
|
| |
| all_trajectories = [] |
|
|
| |
| group_permutations = [] |
| for positions, tools in tool_groups_positions: |
| |
| perms = list(permutations(tools)) |
| group_permutations.append([(positions, perm) for perm in perms]) |
|
|
| |
| all_group_combinations = list(product(*group_permutations)) |
|
|
| |
| for combination in all_group_combinations: |
| new_trajectory = base_trajectory.copy() |
|
|
| |
| for positions, perm in combination: |
| for pos, tool in zip(positions, perm): |
| new_trajectory[pos] = tool |
|
|
| 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]]: |
| """ |
| Choose the best reference trajectory among candidates. |
| |
| Strategy: compute a match score for each candidate vs. 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, best_match_metrics) |
| """ |
| 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]]]: |
| """ |
| Collect and parse all execution_path.md files for a given model. |
| |
| Args: |
| model_name: Model name |
| base_dir: Path to RESULTS directory |
| |
| Returns: |
| List of (session_id, trajectory) |
| """ |
| 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 [] |
|
|
| results = [] |
|
|
| |
| for session_dir in sorted(model_dir.iterdir()): |
| if not session_dir.is_dir(): |
| continue |
|
|
| exec_path_file = session_dir / "execution_path.md" |
| if not exec_path_file.exists(): |
| continue |
|
|
| |
| parser = TrajectoryParser( |
| str(exec_path_file), extract_types=self.extract_types |
| ) |
| trajectory = parser.parse() |
|
|
| results.append((session_dir.name, trajectory)) |
|
|
| return results |
|
|
| def evaluate_model( |
| self, model_name: str, base_dir: str, collect_failure_reasons: bool = False |
| ) -> Dict[str, float]: |
| """ |
| Evaluate a single model over all samples. |
| |
| Args: |
| model_name: Model name |
| base_dir: Path to RESULTS directory |
| collect_failure_reasons: Whether to collect any_order_match failure reasons |
| |
| Returns: |
| Dictionary of averaged metrics |
| """ |
| trajectories = self.collect_execution_paths(model_name, base_dir) |
|
|
| if not trajectories: |
| print(f"⚠️ No trajectories found for model {model_name}") |
| return {} |
|
|
| |
| all_metrics = defaultdict(list) |
|
|
| |
| if collect_failure_reasons: |
| if not hasattr(self, "failure_reasons"): |
| self.failure_reasons = [] |
|
|
| for session_id, predicted in trajectories: |
| |
| chapter_count = TrajectoryEvaluator.detect_chapter_count(predicted) |
|
|
| |
| base_evaluator = TrajectoryEvaluator( |
| self.reference_trajectory, |
| self.repeatable_patterns, |
| actual_chapter_count=chapter_count, |
| ) |
| dynamic_reference = base_evaluator.reference |
|
|
| |
| candidate_references = self._generate_permuted_trajectories( |
| dynamic_reference |
| ) |
|
|
| |
| if len(candidate_references) > 1: |
| best_reference, best_match_metrics = ( |
| self._find_best_reference_trajectory( |
| predicted, candidate_references |
| ) |
| ) |
| else: |
| |
| best_reference = dynamic_reference |
|
|
| |
| evaluator = TrajectoryEvaluator( |
| best_reference, |
| |
| repeatable_patterns=None, |
| actual_chapter_count=None, |
| ) |
|
|
| metrics = evaluator.evaluate_all(predicted, self.target_tools) |
|
|
| for key, value in metrics.items(): |
| all_metrics[key].append(value) |
|
|
| |
| if collect_failure_reasons and metrics["any_order_match"] == 0: |
| diagnosis = evaluator.diagnose_any_order_match_failure(predicted) |
| self.failure_reasons.append( |
| { |
| "model": model_name, |
| "session": session_id, |
| "chapter_count": chapter_count, |
| "failure_stage": diagnosis["failure_stage"], |
| "missing_steps_count": len(diagnosis["missing_steps"]), |
| "missing_details": diagnosis["missing_details"], |
| "first_missing_step": ( |
| diagnosis["missing_steps"][0] |
| if diagnosis["missing_steps"] |
| else "N/A" |
| ), |
| } |
| ) |
|
|
| |
| avg_metrics = {} |
| for key, values in all_metrics.items(): |
| avg_metrics[key] = sum(values) / len(values) if values else 0.0 |
|
|
| num_samples = len(trajectories) |
|
|
| if num_samples > 0: |
| path_counter = defaultdict(int) |
| for session_id, predicted in trajectories: |
| path_key = tuple(predicted) |
| path_counter[path_key] += 1 |
|
|
| unique_paths = len(path_counter) |
| unique_path_ratio = unique_paths / num_samples if num_samples > 0 else 0.0 |
|
|
| probs = [count / num_samples for count in path_counter.values()] |
| H = -sum(p * math.log(p) for p in probs if p > 0) |
| if len(probs) > 1: |
| path_entropy = H / math.log(len(probs)) |
| else: |
| path_entropy = 0.0 |
| else: |
| unique_path_ratio = 0.0 |
| path_entropy = 0.0 |
|
|
| avg_metrics["unique_path_ratio"] = unique_path_ratio |
| avg_metrics["path_entropy"] = path_entropy |
|
|
| |
| avg_metrics["num_samples"] = num_samples |
|
|
| return avg_metrics |
|
|
| def evaluate_all_models( |
| self, base_dir: str = None, collect_failure_reasons: bool = False |
| ) -> pd.DataFrame: |
| """ |
| Evaluate all models and generate a summary table. |
| |
| Args: |
| base_dir: RESULTS directory path. Defaults to two levels above this script. |
| collect_failure_reasons: Whether to collect any_order_match failure reasons |
| |
| Returns: |
| DataFrame with all model evaluation results |
| """ |
| if base_dir is None: |
| |
| base_dir = Path(__file__).parent.parent.parent |
|
|
| results = [] |
|
|
| |
| if collect_failure_reasons: |
| self.failure_reasons = [] |
|
|
| for model_name in self.models: |
| print(f"\n📊 Evaluating model: {model_name}") |
| metrics = self.evaluate_model( |
| model_name, str(base_dir), collect_failure_reasons |
| ) |
|
|
| if metrics: |
| metrics["model"] = model_name |
| results.append(metrics) |
| print(f" ✅ Done, samples: {metrics['num_samples']}") |
| else: |
| print(f" ❌ Skipped (no data)") |
|
|
| if not results: |
| print("\n❌ No model data") |
| 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 = [col for col in cols if col in df.columns] |
|
|
| df = df[cols] |
|
|
| return df |
|
|
| def save_failure_reasons(self, output_file: str = "any_order_match_failures.csv"): |
| """ |
| Save any_order_match failure reasons to a CSV file. |
| |
| Args: |
| output_file: Output filename |
| """ |
| if not hasattr(self, "failure_reasons") or not self.failure_reasons: |
| print("\n⚠️ No failure reasons were 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✅ Saved any_order_match failure reasons: {output_path}") |
|
|
| |
| print(f"\n📊 Failure reason summary:") |
| print(f" Total failures: {len(self.failure_reasons)}") |
|
|
| |
| print(f"\n By model:") |
| model_counts = df["model"].value_counts() |
| for model, count in model_counts.items(): |
| print(f" {model}: {count} failures") |
|
|
| |
| print(f"\n By failure stage:") |
| stage_counts = df["failure_stage"].value_counts() |
| for stage, count in stage_counts.items(): |
| stage_name = { |
| "before_pattern": "Outline stage", |
| "pattern": "Chapter pattern stage", |
| "after_pattern": "Review stage", |
| "simple_match": "Simple match", |
| }.get(stage, stage) |
| print(f" {stage_name}: {count}") |
|
|
| |
|
|
|
|
| def main(): |
| """Main entry point.""" |
| import argparse |
|
|
| parser = argparse.ArgumentParser( |
| description="Evaluate trajectory metrics for the BookWriter-A2A project" |
| ) |
| parser.add_argument( |
| "--config", |
| type=str, |
| default="reference_trajectory.yaml", |
| help="Path to the reference trajectory YAML config file", |
| ) |
| 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( |
| "--diagnose-failures", |
| action="store_true", |
| help="Diagnose any_order_match failures and export a CSV report", |
| ) |
|
|
| 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-A2A") |
| print("=" * 80) |
| print(f"\n Config file: {config_path}") |
|
|
| |
| evaluator = DatasetEvaluator(config_path) |
|
|
| print(f" Project: {evaluator.project_name}") |
| print(f" Reference trajectory: {evaluator.reference_trajectory}") |
| print(f" Target tools: {evaluator.target_tools}") |
| print(f" Models: {evaluator.models}") |
|
|
| if args.diagnose_failures: |
| print(" Failure 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 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)) |
|
|
| |
| output_dir = os.path.dirname(args.output) or "." |
| os.makedirs(output_dir, exist_ok=True) |
|
|
| csv_file = args.output |
| df.to_csv(csv_file, index=False) |
| print(f"\n Saved CSV: {csv_file}") |
|
|
| |
| if args.diagnose_failures: |
| evaluator.save_failure_reasons() |
|
|
| print("\n" + "=" * 80) |
| print("✅ Evaluation completed") |
| print("=" * 80) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|