File size: 20,055 Bytes
8c10cf2 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 | #!/usr/bin/env python3
"""
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
# Setup 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 to match --agent-map "Original Name:Standardized Name"
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"]
# Apply agent name mapping if available
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 # Convert to seconds
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():
# Calculate total time across all agents for this model
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")
# Get paths
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)
# Load agent maps
map_a = parse_agent_map(dir_a / "agent_map.md")
map_b = parse_agent_map(dir_b / "agent_map.md")
# Load agent data
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)
# Calculate proportions
prop_a = calculate_agent_proportions(data_a)
prop_b = calculate_agent_proportions(data_b)
# Get all models and agents
all_models = sorted(set(data_a.keys()) | set(data_b.keys()))
# Get all unique agents across all models
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)
# Organize by agent
for agent in all_agents:
lines.append(f"## Agent: {agent}\n\n")
# Per-model comparison for this agent
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")
# Collect data for overall average
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"]
# Skip if both are 0 (agent not present in this model)
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"
)
# Collect for average
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")
# Overall average for this agent across all models
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")
# Collect data from all projects
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
# Load agent maps
map_a = parse_agent_map(dir_a / "agent_map.md")
map_b = parse_agent_map(dir_b / "agent_map.md")
# Load agent data
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
)
# Calculate proportions
prop_a = calculate_agent_proportions(data_a)
prop_b = calculate_agent_proportions(data_b)
# Aggregate data
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"]
# Calculate overall proportions and means
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
# Calculate total time for proportions
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())
# Table header
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")
# Collect data from all projects
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
# Load agent maps
map_a = parse_agent_map(dir_a / "agent_map.md")
map_b = parse_agent_map(dir_b / "agent_map.md")
# Load agent data
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
)
# Aggregate data across all models
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"]
# Get all agents
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)
# Calculate total time for proportions
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())
# Table header
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")
# Add overall summary first
overall_summary = generate_overall_summary(
projects,
version_a_suffix,
version_b_suffix,
part2_dir,
version_a_name,
version_b_name,
)
lines.append(overall_summary)
# Generate comparison for each project
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...")
# 1. MCP vs Hardcoded comparisons
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}")
# 2. MCP vs A2A comparisons
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}")
# 3. A2A vs A2A_mix comparisons
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()
|