#!/usr/bin/env python3 """ Trajectory Evaluation Script - EmailResponder Project 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 execution_path.md file and extract complete execution trajectory""" def __init__(self, md_file_path: str, extract_types: List[str] = None): """ Args: md_file_path: execution_path.md file path extract_types: List of node types to extract, default ['Tool'] Available types: '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 file and return 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() # Extract Execution Path Tree section (in 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 structure characters, keep node content clean_line = re.sub(r"^[│├└─\s]+", "", line).strip() if not clean_line: continue # Remove 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 and name, remove [ERROR:...] part) clean_line = re.sub(r"\s*\[ERROR:[^\]]*\]", "", clean_line) # Extract node info 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 Note: Input line should already have error markers ❌, RETRY markers, and ERROR info removed Returns: {'type': str, 'action': str} or None """ # SPAN node: [SPAN] span_name [statistics] # More lenient matching, handling possible residual special 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 [statistics] # For Crew_xxx.kickoff format, use wildcard Crew***.kickoff chain_match = re.match(r"\[Chain\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line) if chain_match: chain_name = chain_match.group(1).strip() # Wildcard handling: 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 [statistics] agent_match = re.match(r"\[AGENT\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line) if agent_match: agent_name = agent_match.group(1).strip() # Remove ._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 ._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 - Implements 6 evaluation 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, supports wildcards Args: predicted_action: Actually executed action reference_action: Reference action (may contain 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 be exactly the same as reference (supports 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 trajectory must be a subsequence of predicted (supports wildcards) Allows extra actions, 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 if 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: As long as predicted contains all necessary actions (supports wildcards) Order doesn't matter, allows extra actions Returns: 1 if any-order match, 0 otherwise """ if not self.reference: return 1 # Create copy of predicted actions for matching pred_remaining = predicted.copy() # For each reference action, try to 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 matched matched = True break if not matched: return 0 # Reference action not found return 1 def precision(self, predicted: List[str]) -> float: """ Precision: How many in predicted trajectory are considered correct by reference (supports wildcards) Precision = TP / (TP + FP) TP: Correct tool calls in prediction FP: Incorrect/extra tool calls in prediction Returns: precision value (0.0 - 1.0) """ if not predicted: return 1.0 # No prediction, no false prediction if not self.reference: return 0.0 # Reference is empty but has prediction, all wrong # Create copy of reference actions for matching ref_remaining = self.reference.copy() tp = 0 # True Positives for pred_action in predicted: # Try to find match in reference 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: How many in reference trajectory are covered by predicted (supports wildcards) Recall = TP / (TP + FN) TP: Necessary calls covered by prediction FN: Missed necessary calls Returns: recall value (0.0 - 1.0) """ if not self.reference: return 1.0 # Reference is empty, nothing to recall if not predicted: return 0.0 # No prediction, recall is 0 # Create copy of predicted actions for matching pred_remaining = predicted.copy() tp = 0 # True Positives for ref_action in self.reference: # Try to find 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 if specific tool appears in trajectory (supports wildcards) Args: predicted: Predicted trajectory tool_name: Target tool name Returns: 1 if tool is used, 0 otherwise """ # Check if any action in predicted trajectory matches 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: List of tools to check usage (for single-tool use) Returns: Dictionary of all metric 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), } # Single-tool use metric - calculate overall usage rate (average of all 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: YAML config file path containing reference trajectory definition """ self.config_file = config_file self.config = self._load_config() self.reference_trajectory = self.config.get("reference_trajectory", []) # Dynamic reference trajectory: select based on unified_web_search count self.reference_trajectory_3x = self.config.get("reference_trajectory_3x", None) self.reference_trajectory_4x = self.config.get("reference_trajectory_4x", None) self.use_dynamic_reference = ( self.reference_trajectory_3x is not None and self.reference_trajectory_4x is not None ) self.target_tools = self.config.get("target_tools", []) self.models = self.config.get("models", []) self.project_name = self.config.get("project_name", "EmailResponder") # Trajectory extraction types: default only extract Tool, can also configure as ['Tool', 'AGENT', 'Task Created'] etc. self.extract_types = self.config.get("extract_types", ["Tool"]) # Permutable tool groups configuration (for dynamic tool permutation optimization) self.permutable_tool_groups = self.config.get("permutable_tool_groups", {}) def _load_config(self) -> Dict: """Load 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 _count_unified_web_search_in_analyze_job(self, exec_path_file: str) -> int: """ Count unified_web_search occurrences under analyze_job SPAN Args: exec_path_file: execution_path.md file path Returns: unified_web_search call count """ if not os.path.exists(exec_path_file): return 0 with open(exec_path_file, "r", encoding="utf-8") as f: content = f.read() # Extract Execution Path Tree tree_match = re.search( r"## Execution Path Tree.*?```\n(.*?)```", content, re.DOTALL ) if not tree_match: return 0 tree_content = tree_match.group(1) lines = tree_content.split("\n") # Find analyze_job SPAN range in_analyze_job = False analyze_job_level = -1 count = 0 for line in lines: # Calculate current line level (by leading tree characters) level = len(re.match(r"^([│├└─\s]*)", line).group(1)) # Clean line content clean_line = re.sub(r"^[│├└─\s]+", "", line).strip() clean_line = re.sub(r"^❌\s+", "", clean_line) # Check if entering analyze_job SPAN if "[SPAN] analyze_job" in clean_line: in_analyze_job = True analyze_job_level = level continue # If in analyze_job SPAN if in_analyze_job: # If encountering same or higher level SPAN, left analyze_job if "[SPAN]" in clean_line and level <= analyze_job_level: break # Count unified_web_search if "[Tool] unified_web_search" in clean_line: count += 1 return count def _generate_permuted_trajectories( self, base_trajectory: List[str] ) -> List[List[str]]: """ Generate all possible tool permutation trajectories based on permutable_tool_groups config Args: base_trajectory: Base reference trajectory Returns: List of all possible permutation trajectories (including original) """ if not self.permutable_tool_groups: # No permutable tool groups configured, return original trajectory return [base_trajectory] # Collect all permutable tool groups and their positions in trajectory tool_groups_positions = [] for group_name, tools in self.permutable_tool_groups.items(): # Find positions of this tool group in trajectory 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 # Only permute when all tools are found if len(positions) == len(tools): # Record positions and tools for this group tools_at_positions = [tool_indices[pos] for pos in positions] tool_groups_positions.append((positions, tools_at_positions)) if not tool_groups_positions: # No complete permutable tool groups found return [base_trajectory] # Generate all possible permutation combinations all_trajectories = [] # Generate all permutations for each tool group group_permutations = [] for positions, tools in tool_groups_positions: # Generate all permutations for this tool group perms = list(permutations(tools)) group_permutations.append([(positions, perm) for perm in perms]) # Cartesian product: combine all tool group permutations all_group_combinations = list(product(*group_permutations)) # Generate 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 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]]: """ Select the best reference trajectory from multiple candidates Args: predicted: Predicted trajectory candidate_references: Candidate reference trajectory list Returns: (Best reference trajectory, corresponding match score dict) """ best_reference = candidate_references[0] best_score = -1 best_metrics = {} for ref_trajectory in candidate_references: evaluator = TrajectoryEvaluator(ref_trajectory) # Calculate three 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 highest weight, followed by in_order_match # Use 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]]]: """ Collect and parse all execution_path.md files for specified model Args: model_name: Model name base_dir: RESULTS directory path Returns: [(session_id, trajectory), ...] list """ 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 through 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 extraction 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 single model's performance on all samples Args: model_name: Model name base_dir: RESULTS directory path Returns: Average metrics dictionary """ model_dir = Path(base_dir) / model_name / self.project_name / "test_results" if not model_dir.exists(): print(f"⚠️ Model {model_name} has no trajectory data found") return {} # Accumulate metrics for all samples all_metrics = defaultdict(list) trajectories = [] # Iterate through all sessions 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 parser = TrajectoryParser( str(exec_path_file), extract_types=self.extract_types ) predicted = parser.parse() # Dynamically select reference trajectory if self.use_dynamic_reference: # Count unified_web_search occurrences in analyze_job search_count = self._count_unified_web_search_in_analyze_job( str(exec_path_file) ) # Select reference trajectory based on count if search_count <= 3: reference = self.reference_trajectory_3x else: reference = self.reference_trajectory_4x else: # Use default reference trajectory reference = self.reference_trajectory # Dynamic tool permutation optimization if self.permutable_tool_groups: # Generate all possible tool permutation trajectories candidate_references = self._generate_permuted_trajectories(reference) # Select the best from all candidate reference trajectories if len(candidate_references) > 1: reference, _ = self._find_best_reference_trajectory( predicted, candidate_references ) # else: keep reference unchanged # Create evaluator and evaluate evaluator = TrajectoryEvaluator(reference) metrics = evaluator.evaluate_all(predicted, self.target_tools) for key, value in metrics.items(): all_metrics[key].append(value) trajectories.append((session_dir.name, predicted)) # Calculate 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 generate summary table Args: base_dir: RESULTS directory path, defaults to two levels up from script directory Returns: DataFrame containing all model evaluation results """ if base_dir is None: # Default path: two levels up from script directory base_dir = Path(__file__).parent.parent.parent results = [] for model_name in self.models: print(f"\n📊 Evaluating model: {model_name}") metrics = self.evaluate_model(model_name, str(base_dir)) if metrics: metrics["model"] = model_name results.append(metrics) print(f" ✅ Completed, sample count: {metrics['num_samples']}") else: print(f" ❌ Skipped (no data)") if not results: print("\n❌ No model data available") return pd.DataFrame() # Create DataFrame df = pd.DataFrame(results) # Adjust column order: 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 function""" import argparse parser = argparse.ArgumentParser( description="Evaluate trajectory metrics for EmailResponder project" ) parser.add_argument( "--config", type=str, default="reference_trajectory.yaml", help="Reference trajectory config file path (YAML format)", ) parser.add_argument( "--base-dir", type=str, default=None, help="RESULTS directory path (defaults to two levels up from script directory)", ) parser.add_argument( "--output", type=str, default="evaluation_results.csv", help="Output CSV file path", ) args = parser.parse_args() # If config not specified, use config file in script directory 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 - EmailResponder") print("=" * 80) print(f"\n📁 Config file: {config_path}") # Create evaluator evaluator = DatasetEvaluator(config_path) print(f"📋 Project name: {evaluator.project_name}") # Display reference trajectory info if evaluator.use_dynamic_reference: print(f"🎯 Reference trajectory: Dynamic selection") print( f" - 3x version (unified_web_search<=3): {len(evaluator.reference_trajectory_3x)} steps" ) print( f" - 4x version (unified_web_search>=4): {len(evaluator.reference_trajectory_4x)} steps" ) else: print(f"🎯 Reference trajectory: {evaluator.reference_trajectory}") print(f"🔧 Target tools: {evaluator.target_tools}") print(f"🤖 Evaluation models: {evaluator.models}") # Display tool permutation info if evaluator.permutable_tool_groups: print(f"\n🔀 Dynamic tool permutation optimization: Enabled") total_permutations = 1 for group_name, tools in evaluator.permutable_tool_groups.items(): num_perms = math.factorial(len(tools)) total_permutations *= num_perms print(f" - {group_name}: {len(tools)} tools, {num_perms} permutations") print(f" - Total permutation combinations: {total_permutations}") print( f" - Evaluation strategy: After dynamic 3x/4x selection, choose permutation with highest tool order match" ) else: print(f"\n🔀 Dynamic tool permutation optimization: Disabled") # Evaluate all models df = evaluator.evaluate_all_models(args.base_dir) if df.empty: print("\n❌ Evaluation failed: No data") return print("\n" + "=" * 80) print("📊 Evaluation Results Summary") print("=" * 80) # Format display 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"\n✅ CSV file saved: {csv_file}") print("\n" + "=" * 80) print("✅ Evaluation completed") print("=" * 80) if __name__ == "__main__": main()