AINativeBench / data /processed /RQ2 /BookWriter-A2A /analyze_performance_breakdown_a2a.py
王子睿
restructure + add files
8c10cf2
Raw
History Blame Contribute Delete
37.5 kB
#!/usr/bin/env python3
import csv
import re
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from collections import defaultdict
import yaml
class TraceNode:
def __init__(
self,
node_type: str,
name: str,
time: Optional[float] = None,
tokens: Optional[Dict[str, int]] = None,
raw_line: str = "",
):
self.type = node_type
self.name = name
self.time = time
self.tokens = tokens or {}
self.raw_line = raw_line
self.children: List["TraceNode"] = []
self.parent: Optional["TraceNode"] = None
self.depth: int = 0
self.in_mcp_subtree: bool = False
self.excluded_by_batch_filter: bool = False
def add_child(self, child: "TraceNode") -> None:
child.parent = self
self.children.append(child)
class ExecutionTreeParser:
def __init__(self, md_file_path: str):
self.file_path = Path(md_file_path)
self.model: Optional[str] = None
self.project: Optional[str] = None
self.session_id: str = self.file_path.parent.name
self.root: Optional[TraceNode] = None
def _extract_metadata_from_path(self) -> None:
parts = self.file_path.parts
if "RESULTS" in parts:
idx = parts.index("RESULTS")
if idx + 2 < len(parts):
self.model = parts[idx + 1]
self.project = parts[idx + 2]
@staticmethod
def _parse_tokens(line: str) -> Optional[Dict[str, int]]:
agg_pattern = r"\[∑ tokens: \((\d+)→(\d+) \[REASONING:(\d+), OUTPUT:(\d+)\], total: (\d+)\)"
m = re.search(agg_pattern, line)
if not m:
llm_pattern = (
r"\((\d+)→(\d+) \[REASONING:(\d+), OUTPUT:(\d+)\], total: (\d+)\)"
)
m = re.search(llm_pattern, line)
if not m:
return None
return {
"input": int(m.group(1)),
"output": int(m.group(2)),
"reasoning": int(m.group(3)),
"result": int(m.group(4)),
"total": int(m.group(5)),
}
@staticmethod
def _parse_time(line: str) -> Optional[float]:
m = re.search(r"time:\s*([\d.]+)(ms|s)", line)
if m:
val = float(m.group(1))
return val / 1000.0 if m.group(2) == "ms" else val
m = re.search(r"∑\s*time:\s*([\d.]+)(ms|s)", line)
if m:
val = float(m.group(1))
return val / 1000.0 if m.group(2) == "ms" else val
m = re.search(r"\[([\d.]+)(ms|s)\]", line)
if m:
val = float(m.group(1))
return val / 1000.0 if m.group(2) == "ms" else val
return None
@staticmethod
def _clean_content_line(line: str) -> str:
clean = re.sub(r"^[│├└─\s]+", "", line).strip()
if not clean:
return ""
clean = re.sub(r"^❌\s+", "", clean)
clean = re.sub(r"\s*\(retry\s+\d+\)", "", clean)
clean = re.sub(r"\s*\[RETRY\d+\]", "", clean)
clean = re.sub(r"\s*\[[TRUNCATED]\]", "", clean)
clean = re.sub(r"\s*\[ERROR:[^\]]*\]", "", clean)
return clean.strip()
@staticmethod
def _parse_node_from_content(line: str, raw_line: str) -> Optional[TraceNode]:
if not line:
return None
if line.startswith("[Task Created]"):
time_val = ExecutionTreeParser._parse_time(line)
return TraceNode(
"Task Created", "Task Created", time=time_val, raw_line=raw_line
)
if line.startswith("[Crew Created]"):
time_val = ExecutionTreeParser._parse_time(line)
return TraceNode(
"Crew Created", "Crew Created", time=time_val, raw_line=raw_line
)
if line.startswith("[SPAN]"):
m = re.match(r"\[SPAN\]\s+([^\[]+)", line)
name = m.group(1).strip() if m else "SPAN"
tokens = ExecutionTreeParser._parse_tokens(line)
time_val = ExecutionTreeParser._parse_time(line)
return TraceNode(
"SPAN", name, time=time_val, tokens=tokens, raw_line=raw_line
)
if line.startswith("[Chain]"):
m = re.match(r"\[Chain\]\s+([^\[]+)", line)
name = m.group(1).strip() if m else "Chain"
time_val = ExecutionTreeParser._parse_time(line)
return TraceNode("Chain", name, time=time_val, raw_line=raw_line)
if line.startswith("[AGENT]"):
m = re.match(r"\[AGENT\]\s+(.+?)(?:\s+\[|$)", line)
name = m.group(1).strip() if m else "AGENT"
tokens = ExecutionTreeParser._parse_tokens(line)
time_val = ExecutionTreeParser._parse_time(line)
return TraceNode(
"AGENT", name, time=time_val, tokens=tokens, raw_line=raw_line
)
if line.startswith("[Tool]"):
m = re.match(r"\[Tool\]\s+([^\[]+?)(?:\s+\[|\s+@@@|$)", line)
name = m.group(1).strip() if m else "Tool"
time_val = ExecutionTreeParser._parse_time(line)
return TraceNode("Tool", name, time=time_val, raw_line=raw_line)
if line.startswith("[LLM]"):
m = re.match(r"\[LLM\]\s+([^\(\[]+)", line)
name = m.group(1).strip() if m else "LLM"
tokens = ExecutionTreeParser._parse_tokens(line)
time_val = ExecutionTreeParser._parse_time(line)
return TraceNode(
"LLM", name, time=time_val, tokens=tokens, raw_line=raw_line
)
return None
def _mark_mcp_subtrees(self) -> None:
if not self.root:
return
def dfs(node: TraceNode, in_mcp: bool) -> None:
if node.type == "SPAN" and "mcp" in node.name:
in_mcp = True
node.in_mcp_subtree = in_mcp
for ch in node.children:
dfs(ch, in_mcp)
dfs(self.root, False)
def parse(self) -> Optional[TraceNode]:
if not self.file_path.exists():
return None
text = self.file_path.read_text(encoding="utf-8")
m = re.search(r"## Execution Path Tree.*?```\n(.*?)```", text, re.DOTALL)
if not m:
return None
block = m.group(1)
stack: List[TraceNode] = []
self.root = None
for raw in block.splitlines():
if not raw.strip():
continue
pm = re.match(r"^([│├└─\s]*)", raw)
prefix = pm.group(1) if pm else ""
depth = len(prefix)
clean = self._clean_content_line(raw)
node = self._parse_node_from_content(clean, raw)
if node is None:
continue
node.depth = depth
while stack and stack[-1].depth >= depth:
stack.pop()
if stack:
stack[-1].add_child(node)
else:
if self.root is None:
self.root = node
stack.append(node)
self._extract_metadata_from_path()
self._mark_mcp_subtrees()
return self.root
def iter_nodes(root: TraceNode):
stack = [root]
while stack:
node = stack.pop()
yield node
for ch in reversed(node.children):
stack.append(ch)
def iter_subtree(root: TraceNode):
stack = [root]
while stack:
node = stack.pop()
yield node
for ch in reversed(node.children):
stack.append(ch)
def _mark_excluded_subtree(root: TraceNode) -> None:
stack = [root]
while stack:
node = stack.pop()
node.excluded_by_batch_filter = True
for ch in node.children:
stack.append(ch)
def _collect_write_chapter_attempt_nodes(
root: TraceNode, parser: ExecutionTreeParser
) -> List[Dict[str, object]]:
attempts: List[Dict[str, object]] = []
model = parser.model or ""
session_id = parser.session_id
for node in iter_nodes(root):
if node.type == "SPAN" and node.name == "write_chapters":
write_node = node
for ch in write_node.children:
if ch.type == "SPAN" and ch.name.startswith("a2a_call_chapter_writer_"):
a2a_node = ch
server = None
for s in a2a_node.children:
if (
s.type == "SPAN"
and "chapter_writer_server_execution" in s.name
):
server = s
break
if server is None:
continue
crew = None
for c in server.children:
if c.type == "Chain" and re.match(r"Crew_.*\.kickoff", c.name):
crew = c
break
if crew is None:
continue
raw = crew.raw_line
m_batch = re.search(r"📚BATCH(\d+)", raw)
batch_id = m_batch.group(1) if m_batch else "1"
is_business_retry = "BUSINESS-RETRY" in raw
m_title = re.search(r"\(([^()]*)\)\s*$", raw)
chapter_title = m_title.group(1).strip() if m_title else crew.name
time_s = 0.0
if crew.time is not None:
time_s = crew.time
elif server.time is not None:
time_s = server.time
elif a2a_node.time is not None:
time_s = a2a_node.time
attempts.append(
{
"model": model,
"session_id": session_id,
"batch_id": batch_id,
"chapter_title": chapter_title,
"attempt_time_s": float(time_s or 0.0),
"is_business_retry": is_business_retry,
"a2a_node": a2a_node,
"server_node": server,
"crew_node": crew,
}
)
return attempts
def _apply_write_chapters_batch_filter(
root: TraceNode, parser: ExecutionTreeParser
) -> None:
attempts = _collect_write_chapter_attempt_nodes(root, parser)
if not attempts:
return
per_chapter: Dict[Tuple[str, str, str, str], Dict[str, object]] = {}
for att in attempts:
key = (
str(att["model"]),
str(att["session_id"]),
str(att["batch_id"]),
str(att["chapter_title"]),
)
rec = per_chapter.setdefault(
key,
{
"model": att["model"],
"session_id": att["session_id"],
"batch_id": att["batch_id"],
"chapter_title": att["chapter_title"],
"total_time_s": 0.0,
"attempts": [],
},
)
rec["total_time_s"] += float(att["attempt_time_s"])
rec["attempts"].append(att)
batches: Dict[Tuple[str, str, str], List[Dict[str, object]]] = defaultdict(list)
for (_, _, _, _), rec in per_chapter.items():
key_batch = (
str(rec["model"]),
str(rec["session_id"]),
str(rec["batch_id"]),
)
batches[key_batch].append(rec)
for _, chapters in batches.items():
if not chapters:
continue
max_rec = max(chapters, key=lambda c: c["total_time_s"])
for rec in chapters:
if rec is max_rec:
continue
for att in rec["attempts"]:
a2a_node = att["a2a_node"]
_mark_excluded_subtree(a2a_node)
def compute_retry_time(root: TraceNode) -> float:
total = 0.0
retry_pattern = re.compile(r"\(retry\s+\d+\)|\[RETRY\d+\]")
for node in iter_nodes(root):
if node.in_mcp_subtree or node.excluded_by_batch_filter:
continue
if node.time is None:
continue
if retry_pattern.search(node.raw_line):
total += node.time
return total
def compute_business_retry_time(root: TraceNode) -> float:
total = 0.0
retry_pattern = re.compile(r"\(retry\s+\d+\)|\[RETRY\d+\]")
for node in iter_nodes(root):
if node.in_mcp_subtree or node.excluded_by_batch_filter:
continue
if node.time is None:
continue
if "BUSINESS-RETRY" not in node.raw_line:
continue
under_retry = False
p = node.parent
while p is not None:
if retry_pattern.search(p.raw_line):
under_retry = True
break
p = p.parent
if under_retry:
continue
p2 = node.parent
parent_marked = False
while p2 is not None:
if "BUSINESS-RETRY" in p2.raw_line:
parent_marked = True
break
p2 = p2.parent
if parent_marked:
continue
total += node.time
return total
def compute_llm_overhead_for_subtree(root: TraceNode) -> float:
total = 0.0
for node in iter_subtree(root):
if node.in_mcp_subtree or node.excluded_by_batch_filter:
continue
if node.type == "LLM" and node.time is not None:
total += node.time
return total
def compute_tool_overhead_for_subtree(root: TraceNode) -> float:
total = 0.0
for node in iter_subtree(root):
if node.in_mcp_subtree or node.excluded_by_batch_filter:
continue
if node.type == "Tool" and node.time is not None:
total += node.time
return total
def find_orchestrator(root: TraceNode) -> TraceNode:
for node in iter_nodes(root):
if node.type == "SPAN" and "orchestrator" in node.name:
return node
return root
def compute_llm_overhead(root: TraceNode) -> float:
total = 0.0
for node in iter_nodes(root):
if node.in_mcp_subtree or node.excluded_by_batch_filter:
continue
if node.type == "LLM" and node.time is not None:
total += node.time
return total
def compute_tool_overhead(root: TraceNode) -> float:
total = 0.0
for node in iter_nodes(root):
if node.in_mcp_subtree or node.excluded_by_batch_filter:
continue
if node.type == "Tool" and node.time is not None:
total += node.time
return total
def compute_a2a_overhead(root: TraceNode) -> float:
total = 0.0
for node in iter_nodes(root):
if node.in_mcp_subtree or node.excluded_by_batch_filter:
continue
if node.type == "SPAN" and node.name.startswith("a2a_call_"):
if node.time is None:
continue
server = None
for ch in node.children:
if ch.type == "SPAN" and "server_execution" in ch.name:
server = ch
break
if server is not None and server.time is not None:
diff = node.time - server.time
if diff > 0:
total += diff
return total
def _sum_mcp_time(node: TraceNode) -> float:
total = 0.0
stack = [node]
while stack:
n = stack.pop()
if n is not node and n.in_mcp_subtree and n.time is not None:
total += n.time
for ch in n.children:
stack.append(ch)
return total
def _find_framework_child(server_node: TraceNode) -> Optional[TraceNode]:
for ch in server_node.children:
if ch.type == "Chain" and re.match(r"Crew_.*\.kickoff", ch.name):
return ch
return None
def compute_server_overhead(root: TraceNode) -> float:
total = 0.0
for node in iter_nodes(root):
if node.in_mcp_subtree or node.excluded_by_batch_filter:
continue
if node.type == "SPAN" and "server_execution" in node.name:
if node.time is None:
continue
framework = _find_framework_child(node)
framework_time = (
framework.time if framework and framework.time is not None else 0.0
)
mcp_time = _sum_mcp_time(node)
diff = node.time - framework_time - mcp_time
if diff > 0:
total += diff
return total
def _effective_framework_child_time(node: TraceNode) -> float:
if node.in_mcp_subtree or node.excluded_by_batch_filter:
return 0.0
if node.time is not None:
return node.time
max_time = 0.0
for sub in iter_subtree(node):
if sub is node or sub.in_mcp_subtree:
continue
if sub.time is not None and sub.time > max_time:
max_time = sub.time
return max_time
_FRAMEWORK_MAP: Optional[Dict[str, str]] = None
def _load_framework_map() -> Dict[str, str]:
global _FRAMEWORK_MAP
if _FRAMEWORK_MAP is not None:
return _FRAMEWORK_MAP
cfg_path = Path(__file__).resolve().parent / "FRAMEWORK_map.yaml"
if not cfg_path.exists():
raise FileNotFoundError(
f"Required framework mapping file not found: {cfg_path}. "
"Please create FRAMEWORK_map.yaml with business SPAN to framework mappings."
)
try:
with cfg_path.open("r", encoding="utf-8") as f:
data = yaml.safe_load(f) or {}
except Exception as e:
raise RuntimeError(f"Failed to load FRAMEWORK_map.yaml: {e}") from e
if not isinstance(data, dict):
raise ValueError(
"FRAMEWORK_map.yaml must be a YAML mapping (dict) from business SPAN name to framework name."
)
raw_map = data.get("framework_map")
if raw_map is None:
raw_map = {k: v for k, v in data.items() if isinstance(v, str)}
if not isinstance(raw_map, dict) or not raw_map:
raise ValueError(
"FRAMEWORK_map.yaml does not contain a non-empty 'framework_map' mapping or any string key/value pairs."
)
mapping: Dict[str, str] = {}
for span_name, fw_name in raw_map.items():
if not isinstance(span_name, str) or not isinstance(fw_name, str):
continue
key = span_name.strip()
val = fw_name.strip().lower()
if not key or not val:
continue
if val in ("langgraph", "lang_graph", "lg"):
bucket = "langgraph"
elif val in ("autogen", "auto_gen", "auto-gen"):
bucket = "autogen"
elif val in ("crewai", "crew", "crew_ai"):
bucket = "crew"
else:
raise ValueError(
f"Unsupported framework label '{fw_name}' for business SPAN '{span_name}' in FRAMEWORK_map.yaml. "
"Allowed values: LangGraph / CrewAI / AutoGen."
)
mapping[key] = bucket
if not mapping:
raise ValueError(
"FRAMEWORK_map.yaml did not yield any valid framework mappings."
)
_FRAMEWORK_MAP = mapping
return mapping
def _normalize_business_span_name(name: str) -> str:
name = re.sub(r"\s*\(business_retry\s+\d+\)$", "", name)
return name.strip()
def _collect_business_span_names(root: TraceNode):
names = set()
for node in iter_nodes(root):
if node.type != "SPAN":
continue
if (
"server_execution" in node.name
or node.name.startswith("a2a_call_")
or node.name in ("book_writing_orchestrator", "crew_execution")
):
continue
names.add(_normalize_business_span_name(node.name))
return names
def _categorize_framework_bucket(node: TraceNode) -> str:
"""Decide which framework bucket a CrewAI kickoff should contribute to.
Primary source is FRAMEWORK_map.yaml in the same directory, which should map
business-level SPAN names (e.g. generate_outline, write_chapters,
review_book) to framework labels (LangGraph/CrewAI/AutoGen).
"""
framework_map = _load_framework_map()
# Find the business-level SPAN this kickoff belongs to,
# e.g. generate_outline / write_chapters / review_book.
p = node.parent
business_name: Optional[str] = None
while p is not None:
if p.type == "SPAN":
if (
"server_execution" not in p.name
and not p.name.startswith("a2a_call_")
and p.name not in ("book_writing_orchestrator", "crew_execution")
):
business_name = _normalize_business_span_name(p.name)
break
p = p.parent
if not business_name:
raise RuntimeError(
f"Failed to locate business-level SPAN for framework node '{node.name}'. "
"Please ensure the execution tree has generate_outline / write_chapters / review_book, etc."
)
bucket = framework_map.get(business_name)
if bucket not in ("langgraph", "crew", "autogen"):
raise KeyError(
f"No framework mapping found for business SPAN '{business_name}' in FRAMEWORK_map.yaml. "
"Please add an entry for this SPAN."
)
return bucket
def compute_framework_breakdown(root: TraceNode) -> Tuple[float, float, float]:
lg_total = 0.0
crew_total = 0.0
autogen_total = 0.0
for node in iter_nodes(root):
if node.in_mcp_subtree or node.time is None or node.excluded_by_batch_filter:
continue
if node.type == "Chain" and re.match(r"Crew_.*\.kickoff", node.name):
children_time = 0.0
for ch in node.children:
if ch.in_mcp_subtree:
continue
children_time += _effective_framework_child_time(ch)
diff = node.time - children_time
if diff > 0:
bucket = _categorize_framework_bucket(node)
if bucket == "langgraph":
lg_total += diff
elif bucket == "autogen":
autogen_total += diff
else:
crew_total += diff
return lg_total, crew_total, autogen_total
def compute_framework_overhead(root: TraceNode) -> float:
lg_total, crew_total, autogen_total = compute_framework_breakdown(root)
return lg_total + crew_total + autogen_total
def analyze_file(path: Path) -> Optional[Dict[str, float]]:
parser = ExecutionTreeParser(str(path))
root = parser.parse()
if root is None:
return None
_apply_write_chapters_batch_filter(root, parser)
framework_map = _load_framework_map()
business_span_names = _collect_business_span_names(root)
undefined_business = {n for n in business_span_names if n not in framework_map}
if undefined_business:
raise RuntimeError(
"Found business SPAN names in execution_path that are not defined in FRAMEWORK_map.yaml: "
f"{sorted(undefined_business)}. Please add mappings for these SPANs."
)
orch = find_orchestrator(root)
total_time_s = orch.time if orch.time is not None else None
if total_time_s is None or total_time_s <= 0:
return None
llm_s = compute_llm_overhead(root)
tool_s = compute_tool_overhead(root)
a2a_s = compute_a2a_overhead(root)
lg_fw_s, crew_fw_s, autogen_fw_s = compute_framework_breakdown(root)
framework_s = lg_fw_s + crew_fw_s + autogen_fw_s
server_s = compute_server_overhead(root)
retry_s = compute_retry_time(root)
business_retry_s = compute_business_retry_time(root)
classified_s = llm_s + tool_s + a2a_s + framework_s + server_s
residual_s = total_time_s - classified_s
llm_ratio = llm_s / total_time_s
tool_ratio = tool_s / total_time_s
a2a_ratio = a2a_s / total_time_s
framework_ratio = framework_s / total_time_s
server_ratio = server_s / total_time_s
residual_ratio = residual_s / total_time_s
retry_ratio = retry_s / total_time_s if total_time_s > 0 else 0.0
business_retry_ratio = business_retry_s / total_time_s if total_time_s > 0 else 0.0
def to_ms(x: float) -> int:
return int(round(x * 1000.0))
total_time = to_ms(total_time_s)
llm = to_ms(llm_s)
tool = to_ms(tool_s)
a2a = to_ms(a2a_s)
lg_fw = to_ms(lg_fw_s)
crew_fw = to_ms(crew_fw_s)
autogen_fw = to_ms(autogen_fw_s)
framework = lg_fw + crew_fw + autogen_fw
server = to_ms(server_s)
retry_time = to_ms(retry_s)
business_retry_time = to_ms(business_retry_s)
classified = llm + tool + a2a + framework + server
residual = total_time - classified
result: Dict[str, float] = {
"model": parser.model or "",
"project": parser.project or "",
"session_id": parser.session_id,
"orchestrator_time": total_time,
"LLM_OVERHEAD": llm,
"Tool_OVERHEAD": tool,
"A2A_OVERHEAD": a2a,
"Framework_OVERHEAD": framework,
"LangGraph_Framework_OVERHEAD": lg_fw,
"CrewAI_Framework_OVERHEAD": crew_fw,
"AutoGen_Framework_OVERHEAD": autogen_fw,
"Server_OVERHEAD": server,
"retry_time_ms": retry_time,
"business_retry_time_ms": business_retry_time,
"total_classified": classified,
"residual": residual,
}
result.update(
{
"LLM_ratio": llm_ratio,
"Tool_ratio": tool_ratio,
"A2A_ratio": a2a_ratio,
"Framework_ratio": framework_ratio,
"Server_ratio": server_ratio,
"residual_ratio": residual_ratio,
"retry_ratio_vs_orch": retry_ratio,
"business_retry_ratio_vs_orch": business_retry_ratio,
}
)
return result
def find_results_root() -> Path:
p = Path(__file__).resolve()
for parent in p.parents:
if parent.name == "RESULTS":
return parent
return p.parent.parent.parent
def collect_execution_paths(results_dir: Path, project_name: str) -> List[Path]:
paths: List[Path] = []
for model_dir in results_dir.iterdir():
if not model_dir.is_dir():
continue
proj_dir = model_dir / project_name / "test_results"
if not proj_dir.exists():
continue
for session_dir in proj_dir.iterdir():
if not session_dir.is_dir():
continue
ep = session_dir / "execution_path.md"
if ep.exists():
paths.append(ep)
paths.sort()
return paths
def write_model_summary(rows: List[Dict[str, float]], out_path: Path) -> None:
agg = defaultdict(
lambda: {
"count": 0,
"total_orchestrator_time": 0.0,
"total_LLM_OVERHEAD": 0.0,
"total_Tool_OVERHEAD": 0.0,
"total_A2A_OVERHEAD": 0.0,
"total_Framework_OVERHEAD": 0.0,
"total_LangGraph_Framework_OVERHEAD": 0.0,
"total_CrewAI_Framework_OVERHEAD": 0.0,
"total_AutoGen_Framework_OVERHEAD": 0.0,
"total_Server_OVERHEAD": 0.0,
"total_retry_time_ms": 0.0,
"total_business_retry_time_ms": 0.0,
"total_classified": 0.0,
"total_residual": 0.0,
}
)
for row in rows:
model = str(row.get("model", ""))
m = agg[model]
m["count"] += 1
m["total_orchestrator_time"] += float(row.get("orchestrator_time", 0.0))
m["total_LLM_OVERHEAD"] += float(row.get("LLM_OVERHEAD", 0.0))
m["total_Tool_OVERHEAD"] += float(row.get("Tool_OVERHEAD", 0.0))
m["total_A2A_OVERHEAD"] += float(row.get("A2A_OVERHEAD", 0.0))
m["total_Framework_OVERHEAD"] += float(row.get("Framework_OVERHEAD", 0.0))
m["total_LangGraph_Framework_OVERHEAD"] += float(
row.get("LangGraph_Framework_OVERHEAD", 0.0)
)
m["total_CrewAI_Framework_OVERHEAD"] += float(
row.get("CrewAI_Framework_OVERHEAD", 0.0)
)
m["total_AutoGen_Framework_OVERHEAD"] += float(
row.get("AutoGen_Framework_OVERHEAD", 0.0)
)
m["total_Server_OVERHEAD"] += float(row.get("Server_OVERHEAD", 0.0))
m["total_retry_time_ms"] += float(row.get("retry_time_ms", 0.0))
m["total_business_retry_time_ms"] += float(
row.get("business_retry_time_ms", 0.0)
)
m["total_classified"] += float(row.get("total_classified", 0.0))
m["total_residual"] += float(row.get("residual", 0.0))
summary_rows: List[Dict[str, float]] = []
for model, m in sorted(agg.items(), key=lambda kv: kv[0]):
total_time = m["total_orchestrator_time"] or 1e-9
llm = m["total_LLM_OVERHEAD"]
tool = m["total_Tool_OVERHEAD"]
a2a = m["total_A2A_OVERHEAD"]
framework = m["total_Framework_OVERHEAD"]
lg_fw = m["total_LangGraph_Framework_OVERHEAD"]
crew_fw = m["total_CrewAI_Framework_OVERHEAD"]
autogen_fw = m["total_AutoGen_Framework_OVERHEAD"]
server = m["total_Server_OVERHEAD"]
residual = m["total_residual"]
components_time = llm + tool + a2a + framework + server + residual
denom = components_time or 1e-9
llm_share = llm / denom
tool_share = tool / denom
a2a_share = a2a / denom
framework_share = framework / denom
lg_share = lg_fw / denom
crew_share = crew_fw / denom
autogen_share = autogen_fw / denom
server_share = server / denom
residual_share = residual / denom
sum_component_shares = (
llm_share
+ tool_share
+ a2a_share
+ framework_share
+ server_share
+ residual_share
)
summary_rows.append(
{
"model": model,
"count": m["count"],
"total_orchestrator_time": total_time,
"total_LLM_OVERHEAD": llm,
"total_Tool_OVERHEAD": tool,
"total_A2A_OVERHEAD": a2a,
"total_Framework_OVERHEAD": framework,
"total_LangGraph_Framework_OVERHEAD": lg_fw,
"total_CrewAI_Framework_OVERHEAD": crew_fw,
"total_AutoGen_Framework_OVERHEAD": autogen_fw,
"total_Server_OVERHEAD": server,
"total_classified": m["total_classified"],
"total_residual": residual,
"total_components_time": components_time,
"LLM_share": llm_share,
"Tool_share": tool_share,
"A2A_share": a2a_share,
"Framework_share": framework_share,
"LangGraph_Framework_share": lg_share,
"CrewAI_Framework_share": crew_share,
"AutoGen_Framework_share": autogen_share,
"Server_share": server_share,
"residual_share": residual_share,
"sum_component_shares": sum_component_shares,
}
)
if not summary_rows:
return
fieldnames = list(summary_rows[0].keys())
with out_path.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(summary_rows)
def write_retry_breakdown_summary_by_model(
rows: List[Dict[str, float]], out_path: Path
) -> None:
agg = defaultdict(
lambda: {
"count": 0,
"total_orchestrator_time": 0.0,
"total_retry_time_ms": 0.0,
"total_business_retry_time_ms": 0.0,
}
)
for row in rows:
model = str(row.get("model", ""))
m = agg[model]
m["count"] += 1
m["total_orchestrator_time"] += float(row.get("orchestrator_time", 0.0))
m["total_retry_time_ms"] += float(row.get("retry_time_ms", 0.0))
m["total_business_retry_time_ms"] += float(
row.get("business_retry_time_ms", 0.0)
)
summary_rows: List[Dict[str, float]] = []
for model, m in sorted(agg.items(), key=lambda kv: kv[0]):
total_time = m["total_orchestrator_time"] or 1e-9
retry_total = m["total_retry_time_ms"]
business_retry_total = m["total_business_retry_time_ms"]
retry_all_total = retry_total + business_retry_total
retry_share_vs_orch = retry_total / total_time
business_retry_share_vs_orch = business_retry_total / total_time
retry_all_share_vs_orch = retry_all_total / total_time
summary_rows.append(
{
"model": model,
"count": m["count"],
"total_orchestrator_time": total_time,
"total_retry_time_ms": retry_total,
"total_business_retry_time_ms": business_retry_total,
"total_retry_all_ms": retry_all_total,
"retry_share_vs_orch": retry_share_vs_orch,
"business_retry_share_vs_orch": business_retry_share_vs_orch,
"retry_all_share_vs_orch": retry_all_share_vs_orch,
}
)
if not summary_rows:
return
fieldnames = list(summary_rows[0].keys())
with out_path.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(summary_rows)
def _normalize_crewai_agent_name(name: str) -> str:
name = re.sub(r"\._execute_core\]?$", "", name)
return name.strip()
def collect_agent_llm_tool_breakdown(exec_paths: List[Path]) -> List[Dict[str, float]]:
agg = defaultdict(
lambda: {
"llm_s": 0.0,
"tool_s": 0.0,
"occurrences": 0,
}
)
for ep in exec_paths:
parser = ExecutionTreeParser(str(ep))
root = parser.parse()
if root is None:
continue
model = parser.model or ""
for node in iter_nodes(root):
if node.in_mcp_subtree or node.excluded_by_batch_filter:
continue
if node.type == "Chain" and re.match(r"Crew_.*\.kickoff", node.name):
for ch in node.children:
if ch.in_mcp_subtree or ch.type != "AGENT":
continue
framework = "CrewAI"
agent_name = _normalize_crewai_agent_name(ch.name)
llm_s = compute_llm_overhead_for_subtree(ch)
tool_s = compute_tool_overhead_for_subtree(ch)
if llm_s == 0.0 and tool_s == 0.0:
continue
key = (model, framework, agent_name)
m = agg[key]
m["llm_s"] += llm_s
m["tool_s"] += tool_s
m["occurrences"] += 1
rows: List[Dict[str, float]] = []
for (model, framework, agent_name), st in sorted(
agg.items(), key=lambda kv: (kv[0][0], kv[0][1], kv[0][2])
):
llm_ms = int(round(st["llm_s"] * 1000.0))
tool_ms = int(round(st["tool_s"] * 1000.0))
total_ms = llm_ms + tool_ms
denom = total_ms or 1e-9
rows.append(
{
"model": model,
"framework": framework,
"agent_name": agent_name,
"occurrences": st["occurrences"],
"total_llm_time_ms": llm_ms,
"total_tool_time_ms": tool_ms,
"total_agent_llm_tool_time_ms": total_ms,
"llm_share_in_agent": llm_ms / denom,
"tool_share_in_agent": tool_ms / denom,
}
)
return rows
def main() -> None:
results_dir = find_results_root()
project_name = "BookWriter-A2A"
exec_paths = collect_execution_paths(results_dir, project_name)
rows: List[Dict[str, float]] = []
for ep in exec_paths:
metrics = analyze_file(ep)
if metrics is not None:
rows.append(metrics)
out_dir = Path(__file__).resolve().parent
per_run_path = out_dir / "performance_breakdown_summary.csv"
per_model_path = out_dir / "performance_breakdown_summary_by_model.csv"
agent_path = out_dir / "agent_llm_tool_breakdown_by_model.csv"
retry_model_path = out_dir / "retry_breakdown_summary_by_model.csv"
if rows:
exclude_keys = {
"retry_time_ms",
"business_retry_time_ms",
"retry_ratio_vs_orch",
"business_retry_ratio_vs_orch",
}
fieldnames = [k for k in rows[0].keys() if k not in exclude_keys]
with per_run_path.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames, extrasaction="ignore")
writer.writeheader()
writer.writerows(rows)
write_model_summary(rows, per_model_path)
write_retry_breakdown_summary_by_model(rows, retry_model_path)
agent_rows = collect_agent_llm_tool_breakdown(exec_paths)
if agent_rows:
agent_fieldnames = list(agent_rows[0].keys())
with agent_path.open("w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=agent_fieldnames)
writer.writeheader()
writer.writerows(agent_rows)
if __name__ == "__main__":
main()