#!/usr/bin/env python3 """ Trajectory evaluation script. 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 class TrajectoryParser: """Parse execution_path.md and extract the execution trajectory.""" def __init__(self, md_file_path: str, extract_types: List[str] = None): """ Args: md_file_path: Path to execution_path.md extract_types: Node types to extract, default ['Tool']. Optional: '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 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() # Extract the "Execution Path Tree" section (inside the code block) 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"): # Remove tree drawing characters while keeping the node content clean_line = re.sub(r"^[│├└─\s]+", "", line).strip() if not clean_line: continue # Remove the error marker clean_line = re.sub(r"^❌\s+", "", clean_line) # Remove retry markers: (retry N) and [RETRYN] clean_line = re.sub(r"\s*\(retry\s+\d+\)", "", clean_line) clean_line = re.sub(r"\s*\[RETRY\d+\]", "", clean_line) # Remove ERROR info (keep node type/name; drop the [ERROR: ...] part) clean_line = re.sub(r"\s*\[ERROR:[^\]]*\]", "", clean_line) # Extract node info node_info = self._extract_node_info(clean_line) # Filter out the intermediate crew_execution SPAN layer (normalize across models) if ( node_info and node_info["type"] == "SPAN" and "crew_execution" in node_info.get("action", "") ): continue # Skip this intermediate SPAN 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 single line. Note: the input line should already have the error marker (❌), retry markers, and ERROR info removed. Returns: {'type': str, 'action': str} or None """ # SPAN node: [SPAN] span_name [stats] # Use a more permissive match to handle potential leftover characters span_match = re.match(r"\[SPAN\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line) if span_match: span_name = span_match.group(1).strip() return {"type": "SPAN", "action": f"SPAN: {span_name}"} # Chain node: [Chain] chain_name [stats] # For Crew_xxx.kickoff, normalize to Crew***.kickoff chain_match = re.match(r"\[Chain\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line) if chain_match: chain_name = chain_match.group(1).strip() # Wildcard normalization: Crew_UUID.kickoff -> Crew***.kickoff chain_name = re.sub( r"Crew_[a-f0-9\-]+\.kickoff", "Crew***.kickoff", chain_name ) return {"type": "Chain", "action": f"Chain: {chain_name}"} # AGENT node: [AGENT] agent_name._execute_core [stats] agent_match = re.match(r"\[AGENT\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line) if agent_match: agent_name = agent_match.group(1).strip() # Remove the ._execute_core suffix agent_name = re.sub(r"\._execute_core$", "", agent_name) return {"type": "AGENT", "action": f"Agent: {agent_name}"} # Tool node: [Tool] tool_name._use [time] tool_match = re.match( r"\[Tool\]\s+([^\[\]]+?)(?:\s+\[[\d.]+(?:ms|s)\])?(?:\s*@@@)?\s*$", line ) if tool_match: tool_name = tool_match.group(1).strip() # Remove the ._use suffix tool_name = re.sub(r"\._use$", "", tool_name) return {"type": "Tool", "action": f"Tool: {tool_name}"} # LLM node: [LLM] model_name (tokens) [time] 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 Created node: [Task Created] [time] task_match = re.match(r"\[Task Created\]", line) if task_match: return {"type": "Task Created", "action": "Task Created"} # Crew Created node: [Crew Created] [time] crew_match = re.match(r"\[Crew Created\]", line) if crew_match: return {"type": "Crew Created", "action": "Crew Created"} return None class TrajectoryEvaluator: """Trajectory evaluator implementing 6 metrics.""" def __init__(self, reference_trajectory: List[str]): """ Args: reference_trajectory: Reference trajectory (ground truth) """ self.reference = reference_trajectory def _match_action(self, predicted_action: str, reference_action: str) -> bool: """ Match two actions with wildcard support. Args: predicted_action: Predicted action reference_action: Reference action (may include wildcards) Returns: True if match, False otherwise """ # Exact match if predicted_action == reference_action: return True # Wildcard match: "LLM: *" matches any "LLM: " if reference_action == "LLM: *" and predicted_action.startswith("LLM: "): return True return False def exact_match(self, predicted: List[str]) -> int: """ Exact match: predicted trajectory must equal the reference (with wildcards). 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 must be a subsequence of the predicted trajectory (with wildcards). Extra actions are allowed, but core steps must appear in order. Returns: 1 if in-order match, 0 otherwise """ if not self.reference: return 1 # Empty reference always matches 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 # Check whether all reference steps were found in order return 1 if ref_idx == len(self.reference) else 0 def any_order_match(self, predicted: List[str]) -> int: """ Any-order match: predicted must contain all required actions (with wildcards). Order is ignored; extra actions are allowed. Returns: 1 if any-order match, 0 otherwise """ if not self.reference: return 1 # Work on a copy for matching pred_remaining = predicted.copy() # For each reference action, find a match in predicted 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) # Remove the matched one matched = True break if not matched: return 0 # A reference action was not matched return 1 def precision(self, predicted: List[str]) -> float: """ Precision: fraction of predicted actions considered correct by the reference (with wildcards). Precision = TP / (TP + FP) TP: Correctly predicted actions FP: Incorrectly predicted actions Returns: precision value (0.0 - 1.0) """ if not predicted: return 1.0 # No predictions implies no false positives if not self.reference: return 0.0 # Empty reference but non-empty prediction => all wrong # Work on a copy for matching ref_remaining = self.reference.copy() tp = 0 # True Positives for pred_action in predicted: # Try to match in the remaining reference actions for i, ref_action in enumerate(ref_remaining): if self._match_action(pred_action, ref_action): tp += 1 ref_remaining.pop(i) # Remove matched break fp = len(predicted) - tp # False Positives return tp / (tp + fp) if (tp + fp) > 0 else 0.0 def recall(self, predicted: List[str]) -> float: """ Recall: fraction of reference actions covered by the prediction (with wildcards). Recall = TP / (TP + FN) TP: Correctly predicted actions FN: Missed actions Returns: recall value (0.0 - 1.0) """ if not self.reference: return 1.0 # Empty reference: nothing to recall if not predicted: return 0.0 # No prediction => recall is 0 # Work on a copy for matching pred_remaining = predicted.copy() tp = 0 # True Positives for ref_action in self.reference: # Try to find a match in predicted for i, pred_action in enumerate(pred_remaining): if self._match_action(pred_action, ref_action): tp += 1 pred_remaining.pop(i) # Remove matched break fn = len(self.reference) - tp # False Negatives 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 appears in the trajectory (with wildcards). Args: predicted: Predicted trajectory tool_name: Target tool name Returns: 1 if tool is used, 0 otherwise """ # Check whether any action matches the target tool 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 to check usage for (for single-tool use) Returns: A dict of metrics. """ 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), } # Single-tool use: overall usage rate (mean across tools) 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 defining 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", "EmailResponder") # Extract types: default is only Tool; can be configured as ['Tool', 'AGENT', ...] self.extract_types = self.config.get("extract_types", ["Tool"]) 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 collect_execution_paths( self, model_name: str, base_dir: str ) -> List[Tuple[str, List[str]]]: """ Collect and parse all execution_path.md files for the given model. Args: model_name: Model name base_dir: RESULTS directory path 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 = [] # Iterate over all session subdirectories 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 # Parse trajectory (using configured extract types) 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) -> Dict[str, float]: """ Evaluate a single model across all samples. Args: model_name: Model name base_dir: RESULTS directory path Returns: A dict of averaged metrics """ trajectories = self.collect_execution_paths(model_name, base_dir) if not trajectories: print(f"No trajectory data found for model {model_name}") return {} evaluator = TrajectoryEvaluator(self.reference_trajectory) # Accumulate metrics across samples all_metrics = defaultdict(list) for session_id, predicted in trajectories: metrics = evaluator.evaluate_all(predicted, self.target_tools) for key, value in metrics.items(): all_metrics[key].append(value) # Compute averages 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 # Add sample count avg_metrics["num_samples"] = num_samples return avg_metrics def evaluate_all_models(self, base_dir: str = None) -> pd.DataFrame: """ Evaluate all models and produce a summary table. Args: base_dir: RESULTS directory path; defaults to two levels above this script Returns: DataFrame with evaluation results """ if base_dir is None: # Default: two levels above this script base_dir = Path(__file__).parent.parent.parent results = [] for model_name in self.models: print(f"\nEvaluating model: {model_name}") metrics = self.evaluate_model(model_name, str(base_dir)) if metrics: metrics["model"] = model_name results.append(metrics) print(f" Done. Samples: {metrics['num_samples']}") else: print(" Skipped (no data)") if not results: print("\nNo model data") return pd.DataFrame() # Build DataFrame df = pd.DataFrame(results) # Reorder columns: model name first cols = [ "model", "num_samples", "exact_match", "in_order_match", "any_order_match", "precision", "recall", "single_tool_use", "unique_path_ratio", "path_entropy", ] # Keep only existing columns cols = [col for col in cols if col in df.columns] df = df[cols] return df def main(): """Main entry point.""" import argparse parser = argparse.ArgumentParser( description="Evaluate trajectory metrics for the configured project" ) parser.add_argument( "--config", type=str, default="reference_trajectory.yaml", help="Reference trajectory config file path (YAML)", ) parser.add_argument( "--base-dir", type=str, default=None, help="RESULTS directory path (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 (csv only)", ) args = parser.parse_args() # If config is relative, resolve it relative to this script 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") print("=" * 80) print(f"\nConfig file: {config_path}") # Create evaluator 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}") # Evaluate all models df = evaluator.evaluate_all_models(args.base_dir) if df.empty: print("\nEvaluation failed: no data") return print("\n" + "=" * 80) print("Evaluation Summary") print("=" * 80) # Formatting 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)) # Save results 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"\nCSV saved: {csv_file}") print("\n" + "=" * 80) print("Evaluation complete") print("=" * 80) if __name__ == "__main__": main()