AINativeBench / data /processed /RQ1 /SocialMediaManager-H_A2A /evaluate_trajectory-mix.py
王子睿
restructure + add files
8c10cf2
Raw
History Blame Contribute Delete
41.6 kB
#!/usr/bin/env python3
"""
Trajectory evaluation script - SocialMediaManager-H_A2A.
Evaluates 6 trajectory metrics:
1. Exact match
2. In-order match
3. Any-order match
4. Precision
5. Recall
6. Single-tool use
A2A_mix hybrid-architecture notes:
- LangGraph (Topic Analysis): dynamic matching for batched tool execution
- CrewAI (Content Generation): tool-order permutation support
- AutoGen (Post Review): dynamic LLM/Tool pattern matching; filters create_agent and MCP spans
- Triple dynamic composition: LangGraph × CrewAI × AutoGen
"""
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` and extract the full 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'].
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 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()
# Extract the "Execution Path Tree" section (inside a fenced 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 and 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/name, drop the [ERROR: ...] payload)
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 info from one line.
Note: the input `line` should already have had error markers (), retry markers, and ERROR info removed.
Returns:
{'type': str, 'action': str} or None
"""
# SPAN node: [SPAN] span_name [stats]
# Use a tolerant match to handle any remaining special characters.
span_match = re.match(r"\[SPAN\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
if span_match:
span_name = span_match.group(1).strip()
# A2A_mix special-case: filter AutoGen MCP client/operation spans
if span_name == "mcp client/operation" or span_name.startswith("mcp "):
return None
return {"type": "SPAN", "action": f"SPAN: {span_name}"}
# Chain node: [Chain] chain_name [stats]
# 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 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]
# A2A_mix special-case: filter AutoGen create_agent; keep only invoke_agent
agent_match = re.match(r"\[AGENT\]\s+([^\[]+?)(?:\s+\[.*?\])*\s*$", line)
if agent_match:
agent_name = agent_match.group(1).strip()
# Filter create_agent (AutoGen-specific init, excluded from evaluation)
if agent_name.startswith("create_agent"):
return None
# 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 implementing 6 evaluation metrics.
A2A_mix: supports dynamic reference-trajectory selection.
"""
def __init__(self, reference_trajectory: List[str]):
"""
Args:
reference_trajectory: Reference trajectory (ground truth)
"""
self.reference = reference_trajectory
@staticmethod
def detect_langgraph_tools_pattern(predicted: List[str]) -> tuple:
"""Detect the LangGraph Topic Analysis `tools` grouping pattern and actual tool order.
Returns:
(pattern, actual_tools)
- pattern: grouping pattern, e.g. [1,1] / [2]
- actual_tools: tools observed in the trace (in order)
If detection fails, returns ([], [])
"""
# Locate Chain: LangGraph
start_idx = -1
for i, s in enumerate(predicted):
if s == "Chain: LangGraph":
start_idx = i
break
if start_idx == -1:
return ([], [])
# Count Chain: tools groups and collect actual tools
group_counts = []
actual_tools = []
i = start_idx
while i < len(predicted):
s = predicted[i]
# When hitting Chain: tools, count tools under it
if s == "Chain: tools":
count = 0
i += 1
# Count until the next Chain or AGENT
while i < len(predicted):
if predicted[i].startswith("Chain: ") or predicted[i].startswith(
"AGENT: "
):
break
if predicted[i].startswith("Tool: "):
actual_tools.append(predicted[i])
count += 1
i += 1
if count > 0:
group_counts.append(count)
# Chain: format_output indicates the end of LangGraph stage
elif s == "Chain: format_output":
break
else:
i += 1
# Validate grouping pattern
if not group_counts:
return ([], [])
total = sum(group_counts)
# Topic Analysis has 2 tools
if total != 2:
return ([], [])
# Validate allowed patterns
allowed = {(1, 1), (2,)}
if tuple(group_counts) not in allowed:
return ([], [])
return (group_counts, actual_tools)
@staticmethod
def build_langgraph_reference_variant(
base_reference: List[str], pattern: List[int], tool_order: List[str] = None
) -> List[str]:
"""Build a reference trajectory variant for the Topic Analysis part based on the tools grouping pattern and tool order.
Args:
base_reference: Base reference trajectory
pattern: tools grouping pattern, e.g. [1,1] or [2]
tool_order: Tool order, default is ["Tool: keyword_extractor", "Tool: topic_complexity_analyzer"]
Returns:
Adjusted reference trajectory
"""
try:
# Find the start and end positions of the Topic Analysis stage
start_idx = base_reference.index("Chain: LangGraph")
# Find the position of Chain: format_output (end of Topic Analysis)
end_idx = -1
for i in range(start_idx, len(base_reference)):
if base_reference[i] == "Chain: format_output":
end_idx = i
break
if end_idx == -1:
return base_reference
# Separate the trajectory into three parts: before, Topic Analysis, and after
before = base_reference[: start_idx + 1] # includes Chain: LangGraph
after = base_reference[end_idx:] # from format_output onwards
# Build the new Topic Analysis part
topic_analysis_part = [
"AGENT: agent",
"LLM: *",
"Chain: _should_continue",
]
# Default tool order
if tool_order is None:
tools = ["Tool: keyword_extractor", "Tool: topic_complexity_analyzer"]
else:
tools = tool_order
# Add Chain: tools and Tool based on the pattern
tool_idx = 0
for count in pattern:
topic_analysis_part.append("Chain: tools")
for _ in range(count):
if tool_idx < len(tools):
topic_analysis_part.append(tools[tool_idx])
tool_idx += 1
# Add the second AGENT
topic_analysis_part.extend(
[
"AGENT: agent",
"LLM: *",
"Chain: _should_continue",
]
)
# Combine the full trajectory
return before + topic_analysis_part + after
except (ValueError, IndexError):
# If parsing fails, return the original reference
return base_reference
@staticmethod
def detect_autogen_tools(predicted: List[str]) -> List[str]:
"""Detect the tools used in the AutoGen Post Review stage.
Returns:
List of tool names (in order), or an empty list if not found
"""
# Find the position of invoke_agent x_post_verifier
start_idx = -1
for i, s in enumerate(predicted):
if s == "AGENT: invoke_agent x_post_verifier":
start_idx = i
break
if start_idx == -1:
return []
# Extract the tools under invoke_agent
tools = []
i = start_idx + 1
# Find the next SPAN (end of Post Review)
while i < len(predicted):
s = predicted[i]
if s.startswith("SPAN: "):
break
if s.startswith("Tool: execute_tool "):
tools.append(s)
i += 1
return tools
@staticmethod
def generate_autogen_llm_patterns(num_tools: int) -> List[List[int]]:
"""Generate all possible LLM insertion patterns for the AutoGen stage.
Args:
num_tools: Number of tools
Returns:
List of LLM insertion patterns, where each pattern is a list of 0/1 values
"""
if num_tools < 2:
return [[]] # Less than 2 tools, no insertion needed
# n tools have n-1 gaps
num_gaps = num_tools - 1
# Enumerate all 0/1 combinations: 2^(n-1) possibilities
patterns = []
for i in range(2**num_gaps):
pattern = []
for j in range(num_gaps):
# Extract the j-th bit value (0 or 1)
pattern.append((i >> j) & 1)
patterns.append(pattern)
return patterns
@staticmethod
def build_autogen_reference_variant(
base_reference: List[str], llm_pattern: List[int], tool_order: List[str] = None
) -> List[str]:
"""Build a reference trajectory variant for the Post Review part based on the LLM insertion pattern and tool order.
Args:
base_reference: Base reference trajectory
llm_pattern: LLM insertion pattern, e.g. [0,0,0,0] or [1,1,1,1]
tool_order: Tool order, default is the order in the base reference
Returns:
Adjusted reference trajectory
"""
try:
# Find the position of invoke_agent x_post_verifier
start_idx = base_reference.index("AGENT: invoke_agent x_post_verifier")
# Find the end of this stage (next SPAN or end of list)
end_idx = len(base_reference)
for i in range(start_idx + 1, len(base_reference)):
if base_reference[i].startswith("SPAN: "):
end_idx = i
break
# Extract the tool list from the base reference (if tool_order is not specified)
if tool_order is None:
tools = []
for i in range(start_idx + 1, end_idx):
if base_reference[i].startswith("Tool: execute_tool "):
tools.append(base_reference[i])
else:
tools = tool_order
if not tools:
return base_reference
# Separate the trajectory into three parts: before, Post Review, and after
before = base_reference[: start_idx + 1] # includes AGENT
after = base_reference[end_idx:] # from next SPAN onwards
# Build the Post Review part based on the LLM insertion pattern
review_part = ["LLM: *"] # starting LLM
for i, tool in enumerate(tools):
review_part.append(tool)
# If not the last tool, check if LLM should be inserted
if i < len(tools) - 1 and i < len(llm_pattern):
if llm_pattern[i] == 1:
review_part.append("LLM: *")
review_part.append("LLM: *") # ending LLM
# Combine the full trajectory
return before + review_part + after
except (ValueError, IndexError):
# If parsing fails, return the original reference
return base_reference
def _match_action(self, predicted_action: str, reference_action: str) -> bool:
"""
Match two actions, supporting wildcards.
Args:
predicted_action: Actual 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: <model_name>
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 match the reference trajectory exactly (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 the predicted trajectory (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 trajectory 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: predicted trajectory must contain all necessary actions (supports wildcards).
Does not care about order, allows extra actions.
Returns:
1 if any-order match, 0 otherwise
"""
if not self.reference:
return 1
# Create a copy of the predicted actions for matching
pred_remaining = predicted.copy()
# For each reference action, try to find a match in the predicted actions
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 action
matched = True
break
if not matched:
return 0 # Reference action not found
return 1
def precision(self, predicted: List[str]) -> float:
"""
Precision: proportion of predicted actions that are correct according to the reference trajectory (supports wildcards).
Precision = TP / (TP + FP)
TP: number of correct tool calls in the predicted trajectory
FP: number of incorrect or extra tool calls in the predicted trajectory
Returns:
precision value (0.0 - 1.0)
"""
if not predicted:
return 1.0 # No predicted actions, no incorrect predictions
if not self.reference:
return 0.0 # Reference is empty, but there are predicted actions, all incorrect
# Create a copy of the reference actions for matching
ref_remaining = self.reference.copy()
tp = 0 # True Positives
for pred_action in predicted:
# Try to find a match in the 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 the matched action
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: proportion of reference actions that are covered by the predicted trajectory (supports wildcards).
Recall = TP / (TP + FN)
TP: number of necessary actions covered by the predicted trajectory
FN: number of necessary actions not covered by the predicted trajectory
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 predicted actions, recall is 0
# Create a copy of the predicted actions for matching
pred_remaining = predicted.copy()
tp = 0 # True Positives
for ref_action in self.reference:
# Try to find a match in the predicted actions
for i, pred_action in enumerate(pred_remaining):
if self._match_action(pred_action, ref_action):
tp += 1
pred_remaining.pop(i) # Remove the matched action
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 a specific tool is used in the 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 the predicted trajectory 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: List of tools to check for single-tool use
Returns:
Dictionary of all metric 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 across 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 path containing reference-trajectory definitions
"""
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", "SocialMediaManager-A2A")
# Extraction types: default is Tool only; can be configured to include AGENT, SPAN, etc.
self.extract_types = self.config.get("extract_types", ["Tool"])
# Permutable tool-group configuration
self.permutable_tool_groups = self.config.get("permutable_tool_groups", {})
def _load_config(self) -> Dict:
"""Load YAML config."""
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 permuted trajectories based on the permutable tool groups.
Args:
base_trajectory: Base reference trajectory
Returns:
List of all possible permuted trajectories (including the original)
"""
if not self.permutable_tool_groups:
# No permutable tool groups configured; return the base trajectory.
return [base_trajectory]
# Collect all permutable tool groups and their positions in the trajectory
tool_groups_positions = []
for group_name, tools in self.permutable_tool_groups.items():
# Find positions of this tool group in the 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 if 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 group found
return [base_trajectory]
# Generate all possible permutation combinations
all_trajectories = []
# Generate permutations per 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 permutations across tool groups
all_group_combinations = list(product(*group_permutations))
# Build a new trajectory for each combination
for combination in all_group_combinations:
new_trajectory = base_trajectory.copy()
# Apply tool permutations for 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 (with early-stop optimization).
Args:
predicted: Predicted trajectory
candidate_references: Candidate reference trajectories
Returns:
(best reference trajectory, matching metrics)
"""
best_reference = candidate_references[0]
best_score = -1
best_metrics = {}
for ref_trajectory in candidate_references:
evaluator = TrajectoryEvaluator(ref_trajectory)
# Compute the three key matching metrics
exact = evaluator.exact_match(predicted)
# Early stop: return immediately on an exact match
if exact == 1:
return ref_trajectory, {
"exact_match": 1,
"in_order_match": 1,
"any_order_match": 1,
}
in_order = evaluator.in_order_match(predicted)
any_order = evaluator.any_order_match(predicted)
# Composite score: exact_match has the highest weight, then in_order_match
# Weighted sum: exact*3 + in_order*2 + any_order*1
score = exact * 3 + in_order * 2 + any_order * 1
if score > best_score:
best_score = score
best_reference = ref_trajectory
best_metrics = {
"exact_match": exact,
"in_order_match": in_order,
"any_order_match": any_order,
}
return best_reference, best_metrics
def collect_execution_paths(
self, model_name: str, base_dir: str
) -> List[Tuple[str, List[str]]]:
"""
Collect and parse all `execution_path.md` files for a 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 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 a single model across all samples (A2A_mix enhanced).
Args:
model_name: Model name
base_dir: RESULTS directory path
Returns:
Dictionary of average metrics
"""
model_dir = Path(base_dir) / model_name / self.project_name / "test_results"
if not model_dir.exists():
print(f"⚠️ No trajectory data found for model {model_name}")
return {}
# Accumulate metrics for all samples
all_metrics = defaultdict(list)
trajectories = []
# Iterate over 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()
# Use the default reference trajectory as the base
base_reference = self.reference_trajectory
# ====== A2A_mix optimization: detect actual tool order ======
# 1. Detect LangGraph tools grouping pattern and actual tool order
langgraph_pattern, langgraph_actual_tools = (
TrajectoryEvaluator.detect_langgraph_tools_pattern(predicted)
)
# 2. Only use the LangGraph tool order observed in this sample
if langgraph_actual_tools:
langgraph_tool_orders = [langgraph_actual_tools] # observed order only
else:
langgraph_tool_orders = [None]
# 3. Detect the AutoGen tool order observed in this sample
autogen_actual_tools = TrajectoryEvaluator.detect_autogen_tools(predicted)
num_autogen_tools = len(autogen_actual_tools)
# 4. Generate AutoGen LLM insertion patterns (still enumerated; structural variability)
autogen_llm_patterns = (
TrajectoryEvaluator.generate_autogen_llm_patterns(num_autogen_tools)
if num_autogen_tools > 0
else [[]]
)
# 5. Only use the AutoGen tool order observed in this sample
if autogen_actual_tools:
autogen_tool_orders = [autogen_actual_tools] # observed order only
else:
autogen_tool_orders = [None]
# 6. Generate CrewAI tool permutations (still enumerated; order is genuinely variable)
crewai_references = self._generate_permuted_trajectories(base_reference)
# 7. Combine variants across all dimensions (reduced search space)
# Now: 1 (LG order) × 16 (AG LLM) × 1 (AG order) × 120 (CA perm) = 1,920 candidates
candidate_references = []
# If a LangGraph pattern is detected, generate corresponding variants
if langgraph_pattern:
for crewai_ref in crewai_references:
for lg_tool_order in langgraph_tool_orders:
langgraph_ref = (
TrajectoryEvaluator.build_langgraph_reference_variant(
crewai_ref, langgraph_pattern, lg_tool_order
)
)
# For each LangGraph variant, generate all AutoGen combinations
for ag_llm_pattern in autogen_llm_patterns:
for ag_tool_order in autogen_tool_orders:
final_ref = (
TrajectoryEvaluator.build_autogen_reference_variant(
langgraph_ref, ag_llm_pattern, ag_tool_order
)
)
candidate_references.append(final_ref)
else:
# If no LangGraph pattern is detected, combine CrewAI and AutoGen only
for crewai_ref in crewai_references:
for ag_llm_pattern in autogen_llm_patterns:
for ag_tool_order in autogen_tool_orders:
final_ref = (
TrajectoryEvaluator.build_autogen_reference_variant(
crewai_ref, ag_llm_pattern, ag_tool_order
)
)
candidate_references.append(final_ref)
# If no candidates were generated, fall back to the base reference
if not candidate_references:
candidate_references = [base_reference]
# Select the best reference trajectory from all candidates
if len(candidate_references) > 1:
reference, _ = self._find_best_reference_trajectory(
predicted, candidate_references
)
else:
reference = candidate_references[0]
# Create evaluator and evaluate (using the best reference trajectory)
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))
# 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 build a summary table.
Args:
base_dir: RESULTS directory path (default: two levels above this script)
Returns:
A DataFrame containing evaluation results for all models
"""
if base_dir is None:
# Default path: two levels above this script
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" ✅ Done. Samples: {metrics['num_samples']}")
else:
print(" ❌ Skipped (no data)")
if not results:
print("\n❌ No model data found")
return pd.DataFrame()
# Create DataFrame
df = pd.DataFrame(results)
# Reorder columns: model 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():
"""Entry point."""
import argparse
parser = argparse.ArgumentParser(
description="Evaluate trajectory metrics for SocialMediaManager-H_A2A (hybrid architecture)"
)
parser.add_argument(
"--config",
type=str,
default="reference_trajectory.yaml",
help="Reference-trajectory config path (YAML)",
)
parser.add_argument(
"--base-dir",
type=str,
default=None,
help="RESULTS directory path (default: two levels above this script)",
)
parser.add_argument(
"--output",
type=str,
default="evaluation_results.csv",
help="Output CSV file path",
)
args = parser.parse_args()
# If config is not an absolute path, resolve 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 - SocialMediaManager-H_A2A (Hybrid Architecture)")
print("=" * 80)
print(f"\n📁 Config: {config_path}")
# Create evaluator
evaluator = DatasetEvaluator(config_path)
print(f"📋 Project: {evaluator.project_name}")
print(f"🎯 Reference length: {len(evaluator.reference_trajectory)} steps")
print(f"🔧 Target tools: {len(evaluator.target_tools)}")
print(f"🤖 Models: {evaluator.models}")
# Display A2A_mix dynamic-matching information
print("\n🔀 A2A_mix dynamic matching: enabled")
print(
" ✨ Optimization: detect the actual tool order per sample to avoid blind enumeration"
)
print(f"")
print(" Supported dynamic dimensions:")
print(" - LangGraph tools grouping: auto-detect [1,1] or [2]")
print(" - LangGraph tool order: adapt to the sample's actual order")
print(" - AutoGen LLM/Tool interleaving: enumerate 2^4 = 16 patterns")
print(" - AutoGen tool order: adapt to the sample's actual order")
# CrewAI tool permutations
if evaluator.permutable_tool_groups:
crewai_permutations = 1
for group_name, tools in evaluator.permutable_tool_groups.items():
num_perms = math.factorial(len(tools))
crewai_permutations *= num_perms
print(f" - CrewAI {group_name}: enumerate {num_perms} permutations")
actual_combinations = 1 * 16 * 1 * crewai_permutations
print(f"")
print(
f" Actual candidates: 1 (LG order) × 16 (AG interleave) × 1 (AG order) × {crewai_permutations} (CA perm) = {actual_combinations:,}"
)
print(
f" Theoretical max: 2 × 2 × 16 × 120 × {crewai_permutations} = {2 * 2 * 16 * 120 * crewai_permutations:,}"
)
else:
print(" - CrewAI tool permutations: disabled")
actual_combinations = 1 * 16 * 1
print(f"")
print(f" Actual candidates: 1 × 16 × 1 = {actual_combinations:,}")
print(f" Theoretical max: 2 × 2 × 16 × 120 = {2 * 2 * 16 * 120:,}")
print(f"")
print(" 📈 Performance:")
print(" - Smart detection: only match the tool order actually used by the sample")
print(" - Early stop: stop immediately when exact_match = 1")
print(" - Scoring: exact×3 + in_order×2 + any_order×1")
# 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("📊 Summary")
print("=" * 80)
# Formatting for 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 (CSV only)
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 saved: {csv_file}")
print("\n" + "=" * 80)
print("✅ Done")
print("=" * 80)
if __name__ == "__main__":
main()