| |
| """ |
| Agent-Level Time Comparison Analysis Script |
| |
| This script analyzes agent time data from Part2 directories, comparing: |
| - MCP vs Hardcoded |
| - MCP vs A2A |
| - A2A vs A2A_mix |
| |
| For each comparison, it shows: |
| - Agent time proportions (percentage of total time) |
| - Actual agent times (mean time per occurrence) |
| - Differences in both absolute and percentage terms |
| """ |
|
|
| import csv |
| import re |
| from pathlib import Path |
| from collections import defaultdict |
| from typing import Dict, List, Tuple, Optional |
| import logging |
|
|
| |
| logging.basicConfig( |
| level=logging.INFO, |
| format="%(asctime)s - %(levelname)s - %(message)s", |
| ) |
| logger = logging.getLogger(__name__) |
|
|
|
|
| def parse_agent_map(agent_map_path: Path) -> Dict[str, str]: |
| """ |
| Parse agent_map.md file to extract agent name mappings. |
| |
| Format example: |
| --agent-map "Expert SQL Query Generator:SQL Query Generator" |
| |
| Returns: |
| Dict mapping original name -> standardized name |
| """ |
| agent_map = {} |
|
|
| if not agent_map_path.exists(): |
| logger.warning(f"Agent map not found: {agent_map_path}") |
| return agent_map |
|
|
| try: |
| with open(agent_map_path, "r", encoding="utf-8") as f: |
| content = f.read() |
|
|
| |
| pattern = r'--agent-map\s+"([^:]+):([^"]+)"' |
| matches = re.findall(pattern, content) |
|
|
| for original, standardized in matches: |
| agent_map[original.strip()] = standardized.strip() |
|
|
| logger.info(f"Loaded {len(agent_map)} agent mappings from {agent_map_path}") |
| except Exception as e: |
| logger.error(f"Failed to parse agent map {agent_map_path}: {e}") |
|
|
| return agent_map |
|
|
|
|
| def load_agent_time_data( |
| csv_path: Path, agent_map: Dict[str, str] |
| ) -> Dict[str, Dict[str, float]]: |
| """ |
| Load agent time data from agent_llm_tool_breakdown_by_model.csv. |
| |
| Returns: |
| Dict[model][agent] = { |
| 'mean_time': mean time per occurrence in seconds, |
| 'total_time': total time in seconds, |
| 'occurrences': number of occurrences |
| } |
| """ |
| agent_data = defaultdict(lambda: defaultdict(dict)) |
|
|
| if not csv_path.exists(): |
| logger.warning(f"CSV file not found: {csv_path}") |
| return agent_data |
|
|
| try: |
| with open(csv_path, "r", encoding="utf-8") as f: |
| reader = csv.DictReader(f) |
| for row in reader: |
| model = row["model"] |
| agent_name = row["agent_name"] |
|
|
| |
| standardized_name = agent_map.get(agent_name, agent_name) |
|
|
| occurrences = int(row["occurrences"]) |
| total_time_ms = float(row["total_agent_llm_tool_time_ms"]) |
| total_time_s = total_time_ms / 1000.0 |
|
|
| mean_time = total_time_s / occurrences if occurrences > 0 else 0 |
|
|
| agent_data[model][standardized_name] = { |
| "mean_time": mean_time, |
| "total_time": total_time_s, |
| "occurrences": occurrences, |
| } |
|
|
| logger.info(f"Loaded agent data from {csv_path}") |
| except Exception as e: |
| logger.error(f"Failed to load agent data from {csv_path}: {e}") |
|
|
| return agent_data |
|
|
|
|
| def calculate_agent_proportions( |
| agent_data: Dict[str, Dict[str, float]], |
| ) -> Dict[str, Dict[str, float]]: |
| """ |
| Calculate what proportion of total time each agent takes per model. |
| |
| Returns: |
| Dict[model][agent] = proportion (0-1) |
| """ |
| proportions = defaultdict(dict) |
|
|
| for model, agents in agent_data.items(): |
| |
| total_time = sum(data["total_time"] for data in agents.values()) |
|
|
| if total_time > 0: |
| for agent, data in agents.items(): |
| proportions[model][agent] = data["total_time"] / total_time |
| else: |
| for agent in agents.keys(): |
| proportions[model][agent] = 0.0 |
|
|
| return proportions |
|
|
|
|
| def generate_project_comparison( |
| project_name: str, |
| version_a_suffix: str, |
| version_b_suffix: str, |
| part2_dir: Path, |
| version_a_name: str, |
| version_b_name: str, |
| ) -> str: |
| """Generate agent-level comparison for a single project, organized by agent.""" |
| lines = [] |
| lines.append(f"# {project_name}: {version_a_name} vs {version_b_name}\n\n") |
|
|
| |
| scenario_a = f"{project_name}{version_a_suffix}" |
| scenario_b = f"{project_name}{version_b_suffix}" |
|
|
| dir_a = part2_dir / scenario_a |
| dir_b = part2_dir / scenario_b |
|
|
| if not dir_a.exists() or not dir_b.exists(): |
| lines.append("_Data not available for comparison_\n\n") |
| return "".join(lines) |
|
|
| |
| map_a = parse_agent_map(dir_a / "agent_map.md") |
| map_b = parse_agent_map(dir_b / "agent_map.md") |
|
|
| |
| data_a = load_agent_time_data( |
| dir_a / "agent_llm_tool_breakdown_by_model.csv", map_a |
| ) |
| data_b = load_agent_time_data( |
| dir_b / "agent_llm_tool_breakdown_by_model.csv", map_b |
| ) |
|
|
| if not data_a or not data_b: |
| lines.append("_No agent data available_\n\n") |
| return "".join(lines) |
|
|
| |
| prop_a = calculate_agent_proportions(data_a) |
| prop_b = calculate_agent_proportions(data_b) |
|
|
| |
| all_models = sorted(set(data_a.keys()) | set(data_b.keys())) |
|
|
| |
| all_agents = set() |
| for model in all_models: |
| all_agents.update(data_a.get(model, {}).keys()) |
| all_agents.update(data_b.get(model, {}).keys()) |
| all_agents = sorted(all_agents) |
|
|
| |
| for agent in all_agents: |
| lines.append(f"## Agent: {agent}\n\n") |
|
|
| |
| lines.append(f"### Per-Model Comparison\n\n") |
| lines.append( |
| f"| Model | {version_a_name} Time (s) | {version_b_name} Time (s) | Time Diff | " |
| ) |
| lines.append(f"{version_a_name} % | {version_b_name} % | Proportion Diff |\n") |
| lines.append("| --- | --- | --- | --- | --- | --- | --- |\n") |
|
|
| |
| overall_time_a = [] |
| overall_time_b = [] |
| overall_prop_a = [] |
| overall_prop_b = [] |
|
|
| for model in all_models: |
| data_a_agent = data_a.get(model, {}).get( |
| agent, {"mean_time": 0, "total_time": 0} |
| ) |
| data_b_agent = data_b.get(model, {}).get( |
| agent, {"mean_time": 0, "total_time": 0} |
| ) |
|
|
| time_a = data_a_agent["mean_time"] |
| time_b = data_b_agent["mean_time"] |
|
|
| |
| if time_a == 0 and time_b == 0: |
| continue |
|
|
| prop_a_val = prop_a.get(model, {}).get(agent, 0) * 100 |
| prop_b_val = prop_b.get(model, {}).get(agent, 0) * 100 |
|
|
| time_diff = time_a - time_b |
| time_pct = (time_diff / time_b * 100) if time_b > 0 else 0 |
|
|
| prop_diff = prop_a_val - prop_b_val |
|
|
| lines.append( |
| f"| {model} | {time_a:.2f} | {time_b:.2f} | " |
| f"{time_diff:+.2f}s ({time_pct:+.1f}%) | " |
| f"{prop_a_val:.1f}% | {prop_b_val:.1f}% | " |
| f"{prop_diff:+.1f}pp |\n" |
| ) |
|
|
| |
| if time_a > 0: |
| overall_time_a.append(time_a) |
| overall_prop_a.append(prop_a_val) |
| if time_b > 0: |
| overall_time_b.append(time_b) |
| overall_prop_b.append(prop_b_val) |
|
|
| lines.append("\n") |
|
|
| |
| if overall_time_a or overall_time_b: |
| lines.append(f"### Overall Average Across All Models\n\n") |
| lines.append( |
| f"| Metric | {version_a_name} | {version_b_name} | Difference |\n" |
| ) |
| lines.append("| --- | --- | --- | --- |\n") |
|
|
| avg_time_a = ( |
| sum(overall_time_a) / len(overall_time_a) if overall_time_a else 0 |
| ) |
| avg_time_b = ( |
| sum(overall_time_b) / len(overall_time_b) if overall_time_b else 0 |
| ) |
| avg_prop_a = ( |
| sum(overall_prop_a) / len(overall_prop_a) if overall_prop_a else 0 |
| ) |
| avg_prop_b = ( |
| sum(overall_prop_b) / len(overall_prop_b) if overall_prop_b else 0 |
| ) |
|
|
| time_diff_avg = avg_time_a - avg_time_b |
| time_pct_avg = (time_diff_avg / avg_time_b * 100) if avg_time_b > 0 else 0 |
| prop_diff_avg = avg_prop_a - avg_prop_b |
|
|
| lines.append( |
| f"| Mean Time (s) | {avg_time_a:.2f} | {avg_time_b:.2f} | " |
| f"{time_diff_avg:+.2f}s ({time_pct_avg:+.1f}%) |\n" |
| ) |
| lines.append( |
| f"| Time Proportion (%) | {avg_prop_a:.1f}% | {avg_prop_b:.1f}% | " |
| f"{prop_diff_avg:+.1f}pp |\n" |
| ) |
| lines.append("\n") |
|
|
| lines.append("---\n\n") |
|
|
| return "".join(lines) |
|
|
|
|
| def generate_overall_comparison( |
| projects: List[str], |
| version_a_suffix: str, |
| version_b_suffix: str, |
| part2_dir: Path, |
| version_a_name: str, |
| version_b_name: str, |
| comparison_title: str, |
| ) -> str: |
| """Generate overall agent-level comparison across multiple projects.""" |
| lines = [] |
| lines.append(f"# Overall {comparison_title}\n\n") |
| lines.append(f"Averaged across all projects: {', '.join(projects)}\n\n") |
|
|
| |
| overall_data_a = defaultdict( |
| lambda: defaultdict(lambda: {"total_time": 0, "count": 0}) |
| ) |
| overall_data_b = defaultdict( |
| lambda: defaultdict(lambda: {"total_time": 0, "count": 0}) |
| ) |
|
|
| for project in projects: |
| scenario_a = f"{project}{version_a_suffix}" |
| scenario_b = f"{project}{version_b_suffix}" |
|
|
| dir_a = part2_dir / scenario_a |
| dir_b = part2_dir / scenario_b |
|
|
| if not dir_a.exists() or not dir_b.exists(): |
| continue |
|
|
| |
| map_a = parse_agent_map(dir_a / "agent_map.md") |
| map_b = parse_agent_map(dir_b / "agent_map.md") |
|
|
| |
| data_a = load_agent_time_data( |
| dir_a / "agent_llm_tool_breakdown_by_model.csv", map_a |
| ) |
| data_b = load_agent_time_data( |
| dir_b / "agent_llm_tool_breakdown_by_model.csv", map_b |
| ) |
|
|
| |
| prop_a = calculate_agent_proportions(data_a) |
| prop_b = calculate_agent_proportions(data_b) |
|
|
| |
| for model, agents in data_a.items(): |
| for agent, agent_data in agents.items(): |
| overall_data_a[model][agent]["total_time"] += agent_data["total_time"] |
| overall_data_a[model][agent]["count"] += agent_data["occurrences"] |
|
|
| for model, agents in data_b.items(): |
| for agent, agent_data in agents.items(): |
| overall_data_b[model][agent]["total_time"] += agent_data["total_time"] |
| overall_data_b[model][agent]["count"] += agent_data["occurrences"] |
|
|
| |
| all_models = sorted(set(overall_data_a.keys()) | set(overall_data_b.keys())) |
|
|
| for model in all_models: |
| lines.append(f"## {model}\n\n") |
|
|
| agents_a = set(overall_data_a[model].keys()) |
| agents_b = set(overall_data_b[model].keys()) |
| all_agents = sorted(agents_a | agents_b) |
|
|
| if not all_agents: |
| lines.append("_No agent data for this model_\n\n") |
| continue |
|
|
| |
| total_time_a = sum(d["total_time"] for d in overall_data_a[model].values()) |
| total_time_b = sum(d["total_time"] for d in overall_data_b[model].values()) |
|
|
| |
| lines.append( |
| f"| Agent | {version_a_name} Mean (s) | {version_b_name} Mean (s) | Time Diff | " |
| ) |
| lines.append(f"{version_a_name} % | {version_b_name} % | Proportion Diff |\n") |
| lines.append("| --- | --- | --- | --- | --- | --- | --- |\n") |
|
|
| for agent in all_agents: |
| data_a = overall_data_a[model][agent] |
| data_b = overall_data_b[model][agent] |
|
|
| mean_a = ( |
| data_a["total_time"] / data_a["count"] if data_a["count"] > 0 else 0 |
| ) |
| mean_b = ( |
| data_b["total_time"] / data_b["count"] if data_b["count"] > 0 else 0 |
| ) |
|
|
| prop_a = ( |
| (data_a["total_time"] / total_time_a * 100) if total_time_a > 0 else 0 |
| ) |
| prop_b = ( |
| (data_b["total_time"] / total_time_b * 100) if total_time_b > 0 else 0 |
| ) |
|
|
| time_diff = mean_a - mean_b |
| time_pct = (time_diff / mean_b * 100) if mean_b > 0 else 0 |
|
|
| prop_diff = prop_a - prop_b |
|
|
| lines.append( |
| f"| {agent} | {mean_a:.2f} | {mean_b:.2f} | " |
| f"{time_diff:+.2f}s ({time_pct:+.1f}%) | " |
| f"{prop_a:.1f}% | {prop_b:.1f}% | " |
| f"{prop_diff:+.1f}pp |\n" |
| ) |
| return "".join(lines) |
|
|
|
|
| def generate_overall_summary( |
| projects: List[str], |
| version_a_suffix: str, |
| version_b_suffix: str, |
| part2_dir: Path, |
| version_a_name: str, |
| version_b_name: str, |
| ) -> str: |
| """Generate overall summary across all projects and models.""" |
| lines = [] |
| lines.append("## Overall Summary (All Projects, All Models)\n\n") |
|
|
| |
| overall_data_a = defaultdict(lambda: {"total_time": 0, "count": 0}) |
| overall_data_b = defaultdict(lambda: {"total_time": 0, "count": 0}) |
|
|
| for project in projects: |
| scenario_a = f"{project}{version_a_suffix}" |
| scenario_b = f"{project}{version_b_suffix}" |
|
|
| dir_a = part2_dir / scenario_a |
| dir_b = part2_dir / scenario_b |
|
|
| if not dir_a.exists() or not dir_b.exists(): |
| continue |
|
|
| |
| map_a = parse_agent_map(dir_a / "agent_map.md") |
| map_b = parse_agent_map(dir_b / "agent_map.md") |
|
|
| |
| data_a = load_agent_time_data( |
| dir_a / "agent_llm_tool_breakdown_by_model.csv", map_a |
| ) |
| data_b = load_agent_time_data( |
| dir_b / "agent_llm_tool_breakdown_by_model.csv", map_b |
| ) |
|
|
| |
| for model, agents in data_a.items(): |
| for agent, agent_data in agents.items(): |
| overall_data_a[agent]["total_time"] += agent_data["total_time"] |
| overall_data_a[agent]["count"] += agent_data["occurrences"] |
|
|
| for model, agents in data_b.items(): |
| for agent, agent_data in agents.items(): |
| overall_data_b[agent]["total_time"] += agent_data["total_time"] |
| overall_data_b[agent]["count"] += agent_data["occurrences"] |
|
|
| |
| all_agents = sorted(set(overall_data_a.keys()) | set(overall_data_b.keys())) |
|
|
| if not all_agents: |
| lines.append("_No data available_\n\n") |
| return "".join(lines) |
|
|
| |
| total_time_a = sum(d["total_time"] for d in overall_data_a.values()) |
| total_time_b = sum(d["total_time"] for d in overall_data_b.values()) |
|
|
| |
| lines.append( |
| f"| Agent | {version_a_name} Mean (s) | {version_b_name} Mean (s) | Time Diff | " |
| ) |
| lines.append(f"{version_a_name} % | {version_b_name} % | Proportion Diff |\n") |
| lines.append("| --- | --- | --- | --- | --- | --- | --- |\n") |
|
|
| for agent in all_agents: |
| data_a = overall_data_a[agent] |
| data_b = overall_data_b[agent] |
|
|
| mean_a = data_a["total_time"] / data_a["count"] if data_a["count"] > 0 else 0 |
| mean_b = data_b["total_time"] / data_b["count"] if data_b["count"] > 0 else 0 |
|
|
| prop_a = (data_a["total_time"] / total_time_a * 100) if total_time_a > 0 else 0 |
| prop_b = (data_b["total_time"] / total_time_b * 100) if total_time_b > 0 else 0 |
|
|
| time_diff = mean_a - mean_b |
| time_pct = (time_diff / mean_b * 100) if mean_b > 0 else 0 |
|
|
| prop_diff = prop_a - prop_b |
|
|
| lines.append( |
| f"| {agent} | {mean_a:.2f} | {mean_b:.2f} | " |
| f"{time_diff:+.2f}s ({time_pct:+.1f}%) | " |
| f"{prop_a:.1f}% | {prop_b:.1f}% | " |
| f"{prop_diff:+.1f}pp |\n" |
| ) |
|
|
| lines.append("\n---\n\n") |
| return "".join(lines) |
|
|
|
|
| def generate_comparisons_for_projects( |
| projects: List[str], |
| version_a_suffix: str, |
| version_b_suffix: str, |
| part2_dir: Path, |
| version_a_name: str, |
| version_b_name: str, |
| comparison_title: str, |
| ) -> str: |
| """Generate project-by-project agent-level comparisons.""" |
| lines = [] |
| lines.append(f"# {comparison_title}\n\n") |
| lines.append(f"Projects included: {', '.join(projects)}\n\n") |
| lines.append("---\n\n") |
|
|
| |
| overall_summary = generate_overall_summary( |
| projects, |
| version_a_suffix, |
| version_b_suffix, |
| part2_dir, |
| version_a_name, |
| version_b_name, |
| ) |
| lines.append(overall_summary) |
|
|
| |
| for project in projects: |
| project_comparison = generate_project_comparison( |
| project, |
| version_a_suffix, |
| version_b_suffix, |
| part2_dir, |
| version_a_name, |
| version_b_name, |
| ) |
| lines.append(project_comparison) |
|
|
| return "".join(lines) |
|
|
|
|
| def main(): |
| """Main execution function""" |
| part2_dir = Path("/Users/wzr/TOSEM-2025/RESULTS/RQ2") |
| output_dir = Path("/Users/wzr/TOSEM-2025/RESULTS/RQ3/agent_time_reports") |
|
|
| output_dir.mkdir(parents=True, exist_ok=True) |
|
|
| logger.info("Starting agent-level time comparison analysis...") |
|
|
| |
| logger.info("Generating MCP vs Hardcoded comparisons...") |
| mcp_hardcoded_projects = [ |
| "MarkdownValidator", |
| "GameBuilder", |
| "EmailResponder", |
| ] |
|
|
| comparison_content = generate_comparisons_for_projects( |
| mcp_hardcoded_projects, |
| "-MCP", |
| "", |
| part2_dir, |
| "MCP", |
| "Hardcoded", |
| "MCP vs Hardcoded Agent-Level Comparison", |
| ) |
|
|
| output_path = output_dir / "Agent_Time_Comparison_MCP_vs_Hardcoded.md" |
| output_path.write_text(comparison_content, encoding="utf-8") |
| logger.info(f"Created: {output_path}") |
|
|
| |
| logger.info("Generating MCP vs A2A comparisons...") |
| version_projects = [ |
| "SQL_assistant", |
| "intelligent_recruitment_platform", |
| "landing_page_generator", |
| "self_evaluation_loop_flow", |
| "write_a_book_with_flows", |
| ] |
|
|
| comparison_content = generate_comparisons_for_projects( |
| version_projects, |
| "-MCP", |
| "-A2A", |
| part2_dir, |
| "MCP", |
| "A2A", |
| "MCP vs A2A Agent-Level Comparison", |
| ) |
|
|
| output_path = output_dir / "Agent_Time_Comparison_MCP_vs_A2A.md" |
| output_path.write_text(comparison_content, encoding="utf-8") |
| logger.info(f"Created: {output_path}") |
|
|
| |
| logger.info("Generating A2A vs A2A_mix comparisons...") |
|
|
| comparison_content = generate_comparisons_for_projects( |
| version_projects, |
| "-A2A", |
| "-A2A_mix", |
| part2_dir, |
| "A2A", |
| "A2A_mix", |
| "A2A vs A2A_mix Agent-Level Comparison", |
| ) |
|
|
| output_path = output_dir / "Agent_Time_Comparison_A2A_vs_A2A_mix.md" |
| output_path.write_text(comparison_content, encoding="utf-8") |
| logger.info(f"Created: {output_path}") |
|
|
| logger.info("Agent-level time comparison analysis complete!") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|