#!/usr/bin/env python3 """ Generic Langfuse trace tree extraction tool. Builds a parent-child tree and sorts siblings by timestamp. """ import json import sys import os import re from typing import Dict, List, Tuple, Optional from datetime import datetime def format_time(latency_ms: float) -> str: """Format latency for display. `latency_ms` is in milliseconds.""" if latency_ms < 1000: return f"{latency_ms:.0f}ms" else: seconds = latency_ms / 1000 return f"{seconds:.2f}s" def format_tokens( prompt_tokens: int, completion_tokens: int, total_tokens: int, reasoning_tokens: int = 0, ) -> str: """Format token usage. Always shows REASONING tokens (0 for non-reasoning models).""" actual_output = completion_tokens - reasoning_tokens return f"({prompt_tokens}→{completion_tokens} [REASONING:{reasoning_tokens}, OUTPUT:{actual_output}], total: {total_tokens})" def calculate_subtree_stats( obs_id: str, children_map: Dict[str, List[Dict]] ) -> Tuple[int, int, int, int, float]: """Compute subtree stats: prompt, completion, reasoning, total tokens, and total time (ms).""" total_prompt = 0 total_completion = 0 total_reasoning = 0 total_tokens = 0 total_time = 0.0 children = children_map.get(obs_id, []) for child in children: child_type = child.get("type", "") # Accumulate tokens for the current node (LLM only) if child_type == "GENERATION": total_prompt += child.get("promptTokens", 0) total_completion += child.get("completionTokens", 0) total_tokens += child.get("totalTokens", 0) # Extract REASONING tokens usage_details = child.get("usageDetails", {}) if isinstance(usage_details, dict): total_reasoning += usage_details.get("completion_details.reasoning", 0) # Accumulate time for the current node (LLM and Tool) if child_type in ["GENERATION", "TOOL"]: total_time += child.get("latency", 0.0) # Recurse into children child_stats = calculate_subtree_stats(child["id"], children_map) total_prompt += child_stats[0] total_completion += child_stats[1] total_reasoning += child_stats[2] total_tokens += child_stats[3] total_time += child_stats[4] return total_prompt, total_completion, total_reasoning, total_tokens, total_time def simplify_name( obs_type: str, obs_name: str, obs: Dict, children_map: Dict[str, List[Dict]] = None ) -> str: """Build a display name and append token/time information.""" base_name = "" suffix = "" error_prefix = "" # Error handling obs_level = obs.get("level", "DEFAULT") status_message = obs.get("statusMessage") if obs_level == "ERROR" and status_message: error_prefix = "[ERROR] " # Keep error text short for readability (cannot update error_stats here) if len(status_message) > 80: error_msg = status_message[:70] + "[TRUNCATED]" else: error_msg = status_message suffix = f" [ERROR: {error_msg}]" + suffix # SPAN if obs_type == "SPAN": if "Crew Created" in obs_name: base_name = "[Crew Created]" elif "Task Created" in obs_name: base_name = "[Task Created]" # Note: check longer strings first to avoid partial matches elif "Tool Usage Error" in obs_name: base_name = "[Tool Usage Error]" elif "Tool Repeated Usage" in obs_name: base_name = "[Tool Repeated Usage]" elif "Tool Usage" in obs_name: base_name = "[Tool Usage]" else: base_name = f"[SPAN] {obs_name}" # AGENT elif obs_type == "AGENT": base_name = f"[AGENT] {obs_name}" # GENERATION (LLM) - token/time elif obs_type == "GENERATION": model = obs.get("model", "unknown") if "/" in model: model = model.split("/")[-1] base_name = f"[LLM] {model}" # Token usage prompt_tokens = obs.get("promptTokens", 0) completion_tokens = obs.get("completionTokens", 0) total_tokens = obs.get("totalTokens", 0) # Extract REASONING tokens reasoning_tokens = 0 usage_details = obs.get("usageDetails", {}) if isinstance(usage_details, dict): reasoning_tokens = usage_details.get("completion_details.reasoning", 0) if total_tokens > 0: suffix += f" {format_tokens(prompt_tokens, completion_tokens, total_tokens, reasoning_tokens)}" # Latency latency = obs.get("latency", 0.0) if latency > 0: suffix += f" [{format_time(latency)}]" # TOOL - latency elif obs_type == "TOOL": base_name = f"[Tool] {obs_name}" # Latency latency = obs.get("latency", 0.0) if latency > 0: suffix += f" [{format_time(latency)}]" # CHAIN elif obs_type == "CHAIN": base_name = f"[Chain] {obs_name}" # Other else: base_name = f"[{obs_type}] {obs_name}" # For parent nodes (SPAN/CHAIN/AGENT), show subtree summary. if obs_type in ["SPAN", "CHAIN", "AGENT"] and children_map: stats = calculate_subtree_stats(obs["id"], children_map) ( total_prompt, total_completion, total_reasoning, total_tokens_sum, total_time, ) = stats stats_parts = [] if total_tokens_sum > 0: stats_parts.append( f"tokens: {format_tokens(total_prompt, total_completion, total_tokens_sum, total_reasoning)}" ) # Time: SPAN/CHAIN/AGENT use their own latency node_latency = obs.get("latency", 0.0) if node_latency and node_latency > 0: stats_parts.append(f"time: {format_time(node_latency)}") if stats_parts: suffix += f" [∑ {', '.join(stats_parts)}]" return error_prefix + base_name + suffix def should_filter_observation(obs: Dict, is_a2a_project: bool) -> bool: """Return True if an observation should be filtered out.""" obs_name = obs.get("name", "") obs_type = obs.get("type", "") # 1) Filter HTTP client tracing nodes (noise) metadata = obs.get("metadata", {}) scope_name = metadata.get("scope", {}).get("name", "") if scope_name == "opentelemetry.instrumentation.httpx" and obs_type == "SPAN": # HTTP method nodes if obs_name in ["POST", "GET", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]: return True # 2) A2A framework noise patterns if is_a2a_project: a2a_noise_patterns = [ "a2a.server.events.event_queue.", "a2a.server.events.in_memory_queue_manager.", "a2a.server.events.event_consumer.", "a2a.server.request_handlers.default_request_handler.", "a2a.server.request_handlers.jsonrpc_handler.", ] # Prefix match for pattern in a2a_noise_patterns: if obs_name.startswith(pattern): return True return False def detect_project_variant_from_path(trace_file: str) -> Optional[str]: file_path = os.path.abspath(trace_file) path_lower = file_path.lower() m = re.search(r"(?:^|/)[^/]+[-_](mcp|a2a_mix|a2a|h_a2a)(?:/|$)", path_lower) if m: return m.group(1) return None def build_children_map( observations: List[Dict], is_a2a_project: bool = False, is_a2a_mix: bool = False ) -> Tuple[Dict[str, List[Dict]], Dict]: """Build parent->children mapping; children are sorted by timestamp and name. Returns: children_map: mapping of parent observation id -> list of child observations error_stats: error statistics """ children_map = {} filtered_obs = [] error_stats = { "total_errors": 0, "filtered_errors": 0, "visible_errors": 0, "error_messages": [], "http_filtered": 0, # number of filtered HTTP request nodes # Error categories "a2a_framework_errors": [], # A2A framework/internal errors "http_request_errors": [], # HTTP request node errors "tool_usage_errors": [], # Tool Usage node errors "tool_child_span_errors": [], # Tool child SPAN errors (A2A_mix only) # Context-related errors "filtered_errors_no_parent_error": [], # filtered error node with no ancestor error "filtered_errors_no_child_error": [], # filtered error node with no descendant error # Truncation stats "truncated_errors_count": 0, # number of truncated error messages } # Map id -> observation (for ancestor/descendant lookup) all_obs_map = {obs["id"]: obs for obs in observations} # Build raw children mapping (for descendant lookup) all_children_map = {} for obs in observations: parent_id = obs.get("parentObservationId") if parent_id: if parent_id not in all_children_map: all_children_map[parent_id] = [] all_children_map[parent_id].append(obs) # Helper: any ancestor has ERROR def has_ancestor_error(obs_id: str) -> bool: """Check whether any ancestor node has level=ERROR.""" obs = all_obs_map.get(obs_id) if not obs: return False parent_id = obs.get("parentObservationId") while parent_id: parent_obs = all_obs_map.get(parent_id) if not parent_obs: break if parent_obs.get("level") == "ERROR": return True parent_id = parent_obs.get("parentObservationId") return False # Helper: any descendant has ERROR def has_descendant_error(obs_id: str) -> bool: """Check whether any descendant node has level=ERROR.""" children = all_children_map.get(obs_id, []) for child in children: if child.get("level") == "ERROR": return True if has_descendant_error(child["id"]): return True return False # Step 1: filter noise observations and collect error statistics for obs in observations: obs_name = obs.get("name", "") obs_type = obs.get("type", "") obs_level = obs.get("level", "DEFAULT") status_msg = obs.get("statusMessage") or "Unknown error" # Count errors if obs_level == "ERROR": error_stats["total_errors"] += 1 if should_filter_observation(obs, is_a2a_project): error_stats["filtered_errors"] += 1 # Categorize filtered errors metadata = obs.get("metadata", {}) scope_name = metadata.get("scope", {}).get("name", "") # Determine filtered-node type obs_id = obs.get("id") error_info = { "name": obs_name, "type": obs_type, "message": status_msg, "id": obs_id, } if ( scope_name == "opentelemetry.instrumentation.httpx" and obs_name in ["POST", "GET", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"] ): error_stats["http_request_errors"].append(error_info) else: # A2A framework/internal errors error_stats["a2a_framework_errors"].append(error_info) # Check context (ancestors/descendants) if not has_ancestor_error(obs_id): error_stats["filtered_errors_no_parent_error"].append(error_info) if not has_descendant_error(obs_id): error_stats["filtered_errors_no_child_error"].append(error_info) else: error_stats["visible_errors"] += 1 # Record visible errors (for the summary section) if status_msg and status_msg not in error_stats["error_messages"]: error_stats["error_messages"].append(status_msg) # Filtering is_filtered = should_filter_observation(obs, is_a2a_project) if is_filtered: # Count filtered HTTP request nodes metadata = obs.get("metadata", {}) scope_name = metadata.get("scope", {}).get("name", "") if scope_name == "opentelemetry.instrumentation.httpx" and obs_name in [ "POST", "GET", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS", ]: error_stats["http_filtered"] += 1 else: filtered_obs.append(obs) # Step 2: rebuild parent-child relationships (skipping filtered nodes) # Map id -> filtered observation id_to_obs = {obs["id"]: obs for obs in filtered_obs} # Helper: check if a node is under Crew***.kickoff chain def is_under_crew_chain(obs: Dict, all_observations: List[Dict]) -> bool: """Return True if the node is under a Crew_*.kickoff CHAIN.""" parent_id = obs.get("parentObservationId") visited = set() # avoid cycles while parent_id and parent_id not in visited: visited.add(parent_id) parent = next((o for o in all_observations if o["id"] == parent_id), None) if not parent: break # Check Crew chain if parent.get("type") == "CHAIN": chain_name = parent.get("name", "") # Match Crew_.kickoff if re.match(r"Crew_[a-f0-9\-]+\.kickoff", chain_name): return True parent_id = parent.get("parentObservationId") return False # Helper: parent-based filtering rules def should_filter_by_parent( child_obs: Dict, parent_obs: Dict, is_a2a_mix_project: bool ) -> bool: """Decide whether to filter a child based on its parent and project type.""" if not parent_obs: return False parent_type = parent_obs.get("type", "") child_name = child_obs.get("name", "") child_type = child_obs.get("type", "") # Rule 1: all projects - filter [Tool] -> Tool Usage spans if parent_type == "TOOL": if "Tool Usage" in child_name or "Tool Repeated Usage" in child_name: return True # Rule 2: A2A_mix only - filter specific MCP spans under [Tool] if is_a2a_mix_project and child_type == "SPAN": mcp_tool_noise = [ "GET", "POST", "mcp client/operation", "mcp initialize", "mcp tools/call", "mcp tools/list", ] if child_name in mcp_tool_noise: return True # Rule 3: only under Crew chain - filter [AGENT] telemetry spans. if parent_type == "AGENT": if child_type == "SPAN" and ( "Tool Usage" in child_name or "Tool Repeated Usage" in child_name ): # Only apply under Crew chain if is_under_crew_chain(parent_obs, observations): return True return False # Build parent-child relationships; if the direct parent is filtered, climb upwards for obs in filtered_obs: parent_id = obs.get("parentObservationId") # Find a valid parent (skip filtered nodes) while parent_id and parent_id not in id_to_obs: # Lookup parent in the original list parent_obs = next((o for o in observations if o["id"] == parent_id), None) if parent_obs: parent_id = parent_obs.get("parentObservationId") else: parent_id = None # Parent-based filtering parent_obs = id_to_obs.get(parent_id) if parent_id else None if should_filter_by_parent(obs, parent_obs, is_a2a_mix): # If this node has an error, count it into the appropriate category if obs.get("level") == "ERROR": obs_name = obs.get("name", "") obs_type = obs.get("type", "") status_msg = obs.get("statusMessage") or "Unknown error" obs_id = obs.get("id") error_info = { "name": obs_name, "type": obs_type, "message": status_msg, "id": obs_id, } if "Tool Usage" in obs_name or "Tool Repeated Usage" in obs_name: error_stats["tool_usage_errors"].append(error_info) elif is_a2a_mix and parent_obs and parent_obs.get("type") == "TOOL": # Tool child SPAN error (A2A_mix only) error_stats["tool_child_span_errors"].append(error_info) # Context checks if not has_ancestor_error(obs_id): error_stats["filtered_errors_no_parent_error"].append(error_info) if not has_descendant_error(obs_id): error_stats["filtered_errors_no_child_error"].append(error_info) continue # skip this node if parent_id: if parent_id not in children_map: children_map[parent_id] = [] children_map[parent_id].append(obs) else: # Root node if "ROOT" not in children_map: children_map["ROOT"] = [] children_map["ROOT"].append(obs) # Sort children by timestamp, then by name for parent_id in children_map: children = children_map[parent_id] children.sort(key=lambda x: (x.get("startTime", ""), x.get("name", ""))) return children_map, error_stats def print_tree_recursive( obs: Dict, children_map: Dict[str, List[Dict]], prefix: str, is_last: bool, output_lines: List[str], batch_info: Dict[str, Dict] = None, self_eval_retry_info: Dict[str, bool] = None, ): """Recursively render the tree.""" obs_type = obs.get("type", "UNKNOWN") obs_name = obs.get("name", "unnamed") obs_id = obs["id"] # Display name (pass children_map to compute subtree stats) display_name = simplify_name(obs_type, obs_name, obs, children_map) # SQL series: detect business_retry (can appear at any level) if obs_type == "SPAN" and "business_retry" in obs_name.lower(): m_business = re.search(r"\bbusiness_retry\s*(\d+)\b", obs_name, re.IGNORECASE) if m_business and "[BUSINESS-RETRY]" not in display_name: display_name = f"{display_name} [BUSINESS-RETRY]" # Add batch annotation (write_a_book_with_flows only) if batch_info and obs_id in batch_info: info = batch_info[obs_id] batch_str = f"BATCH{info['batch']}" if info["is_retry"]: batch_str += " [BUSINESS-RETRY]" if info["chapter_title"]: batch_str += f" ({info['chapter_title']})" display_name = f"{display_name} {batch_str}" # Add self_evaluation_loop retry annotations if self_eval_retry_info and obs_id in self_eval_retry_info: if self_eval_retry_info[obs_id]: display_name = f"{display_name} [BUSINESS-RETRY]" # Current line connector = "└─ " if is_last else "├─ " output_lines.append(f"{prefix}{connector}{display_name}") # Prefix for children if is_last: new_prefix = prefix + " " # 3 spaces else: new_prefix = prefix + "│ " # │ + 2 spaces # Recurse into children children = children_map.get(obs_id, []) # Filter nested LLM calls: for a GENERATION node, hide its GENERATION children if obs_type == "GENERATION": children = [child for child in children if child.get("type") != "GENERATION"] for i, child in enumerate(children): is_last_child = i == len(children) - 1 print_tree_recursive( child, children_map, new_prefix, is_last_child, output_lines, batch_info, self_eval_retry_info, ) def build_tree_structure( observations: List[Dict], is_a2a_project: bool = False, is_a2a_mix: bool = False, project_type: Optional[str] = None, self_eval_project_type: Optional[str] = None, ) -> Tuple[List[str], Dict]: """Build the tree output lines.""" output_lines = [] # Parent-child map children_map, error_stats = build_children_map( observations, is_a2a_project, is_a2a_mix ) # Batch analysis (write_a_book_with_flows only) batch_info = {} if project_type: batch_info = analyze_write_chapters_batches( observations, children_map, project_type ) # Retry analysis (self_evaluation_loop_flow only) self_eval_retry_info = {} if self_eval_project_type: self_eval_retry_info = analyze_self_evaluation_retries( observations, children_map, self_eval_project_type ) # Render from root nodes root_nodes = children_map.get("ROOT", []) for i, root in enumerate(root_nodes): obs_type = root.get("type", "UNKNOWN") obs_name = root.get("name", "unnamed") display_name = simplify_name(obs_type, obs_name, root, children_map) # Root node (no prefix) output_lines.append(display_name) # Children children = children_map.get(root["id"], []) for j, child in enumerate(children): # Detect RETRY on the first layer SPAN under root if child.get("type") == "SPAN": name = child.get("name", "") # Detect business_retry N (SQL series) m_business = re.search( r"\bbusiness_retry\s*(\d+)\b", name, re.IGNORECASE ) if ( m_business and "[BUSINESS-RETRY]" not in name and "[RETRY" not in name ): child["name"] = f"{name} [BUSINESS-RETRY]" # Detect retry N (orchestrator-level) elif not m_business: m = re.search(r"\bretry\s*(\d+)\b", name, re.IGNORECASE) if m: retry_idx = m.group(1) # Add marker if missing if "[RETRY" not in name: child["name"] = f"{name} [RETRY{retry_idx}]" is_last_child = j == len(children) - 1 print_tree_recursive( child, children_map, "", is_last_child, output_lines, batch_info, self_eval_retry_info, ) return output_lines, error_stats def detect_a2a_project(trace_file: str) -> bool: """Detect whether the trace belongs to an A2A/A2A_mix project (by path).""" file_path = os.path.abspath(trace_file) path_lower = file_path.lower() variant = detect_project_variant_from_path(file_path) if variant in {"a2a", "a2a_mix", "h_a2a"}: return True if "-a2a" in path_lower or "_a2a" in path_lower: return True if "a2a-" in path_lower or "a2a_" in path_lower: return True return False def detect_a2a_mix_project(trace_file: str) -> bool: """Detect whether the trace belongs to an A2A_mix project (by path).""" file_path = os.path.abspath(trace_file) path_lower = file_path.lower() variant = detect_project_variant_from_path(file_path) if variant == "a2a_mix": return True # Check A2A_mix markers if "-a2a_mix" in path_lower or "_a2a_mix" in path_lower: return True if "a2a-mix" in path_lower or "a2a_mix" in path_lower: return True return False def detect_write_book_project(trace_file: str) -> Optional[str]: """Detect write_a_book_with_flows traces and return project type (MCP/A2A/A2A_mix) or None.""" file_path = os.path.abspath(trace_file) path_lower = file_path.lower() if ( "write_a_book_with_flows" not in path_lower and "write-a-book-with-flows" not in path_lower ): return None variant = detect_project_variant_from_path(file_path) if variant == "a2a_mix": return "A2A_mix" if variant in {"a2a", "h_a2a"}: return "A2A" if variant == "mcp": return "MCP" if ( "-a2a_mix" in path_lower or "_a2a_mix" in path_lower or "a2a-mix" in path_lower or "a2a_mix" in path_lower ): return "A2A_mix" elif ( "-a2a" in path_lower or "_a2a" in path_lower or "a2a-" in path_lower or "a2a_" in path_lower ): return "A2A" elif ( "-mcp" in path_lower or "_mcp" in path_lower or "mcp-" in path_lower or "mcp_" in path_lower ): return "MCP" return None def detect_self_evaluation_project(trace_file: str) -> Optional[str]: """Detect self_evaluation_loop_flow traces and return project type MCP/A2A/A2A_mix.""" path_lower = trace_file.lower() # Check marker if ( "self_evaluation_loop_flow" not in path_lower and "self-evaluation-loop-flow" not in path_lower ): return None # Detect concrete type if ( "-a2a_mix" in path_lower or "_a2a_mix" in path_lower or "a2a-mix" in path_lower or "a2a_mix" in path_lower ): return "A2A_mix" elif ( "-a2a" in path_lower or "_a2a" in path_lower or "a2a-" in path_lower or "a2a_" in path_lower ): return "A2A" elif ( "-mcp" in path_lower or "_mcp" in path_lower or "mcp-" in path_lower or "mcp_" in path_lower ): return "MCP" return None def analyze_self_evaluation_retries( observations: List[Dict], children_map: Dict[str, List[Dict]], project_type: str, ) -> Dict[str, bool]: """Analyze RETRY behavior for self_evaluation_loop_flow. Returns: {obs_id: is_retry} """ retry_info = {} # Find all content_generation_loop SPANs content_loop_nodes = [] for obs in observations: if ( obs.get("type") == "SPAN" and "content_generation_loop" in obs.get("name", "").lower() ): content_loop_nodes.append(obs) if not content_loop_nodes: return {} if project_type == "MCP": # MCP: detect retries within each loop for content_loop_node in content_loop_nodes: # Recursively find CHAIN kickoff nodes under the loop chain_nodes = [] def find_chain_nodes(parent_id: str, depth: int = 0, max_depth: int = 5): if depth > max_depth: return children = children_map.get(parent_id, []) for child in children: if ( child.get("type") == "CHAIN" and "kickoff" in child.get("name", "").lower() ): chain_nodes.append(child) else: find_chain_nodes(child["id"], depth + 1, max_depth) find_chain_nodes(content_loop_node["id"]) # Extract agent role from each CHAIN node (retry detection within this loop) role_seen = {} # role -> first-seen node for node in chain_nodes: # Try to extract role from AGENT children agent_children = children_map.get(node["id"], []) for agent in agent_children: if agent.get("type") == "AGENT": agent_name = agent.get("name", "") # Extract role name (before _execute_core) role = ( agent_name.split("._execute_core")[0] if "._execute_core" in agent_name else agent_name ) # Target roles if "Shakespearean Bard" in role or "X Post Verifier" in role: if role in role_seen: # Second occurrence => RETRY retry_info[node["id"]] = True else: # First occurrence role_seen[role] = node retry_info[node["id"]] = False break else: # A2A/A2A_mix: detect retries within each loop for content_loop_node in content_loop_nodes: # Find a2a_call_content_generator / a2a_call_post_reviewer spans under the loop target_spans = [] def find_target_spans(parent_id: str, depth: int = 0, max_depth: int = 5): if depth > max_depth: return children = children_map.get(parent_id, []) for child in children: if child.get("type") == "SPAN": name = child.get("name", "").lower() if ( "a2a_call_content_generator" in name or "a2a_call_post_reviewer" in name ): target_spans.append(child) else: find_target_spans(child["id"], depth + 1, max_depth) find_target_spans(content_loop_node["id"]) # Sort by time target_spans_with_time = [] for node in target_spans: start_time = node.get("startTime", "") if start_time: try: dt = datetime.fromisoformat(start_time.replace("Z", "+00:00")) target_spans_with_time.append((node, dt)) except: pass target_spans_with_time.sort(key=lambda x: x[1]) # Detect retry within the loop span_type_seen = {} # span_type -> first-seen for node, dt in target_spans_with_time: name = node.get("name", "").lower() # Determine type if "content_generator" in name: span_type = "content_generator" elif "post_reviewer" in name: span_type = "post_reviewer" else: continue if span_type in span_type_seen: # Second occurrence => RETRY retry_info[node["id"]] = True else: # First occurrence span_type_seen[span_type] = node retry_info[node["id"]] = False return retry_info def extract_chapter_title(obs: Dict) -> Optional[str]: """Extract chapter_title from an observation.""" # Try `input` obs_input = obs.get("input") if obs_input: if isinstance(obs_input, dict): return obs_input.get("chapter_title") elif isinstance(obs_input, str): try: input_dict = json.loads(obs_input) if isinstance(input_dict, dict): return input_dict.get("chapter_title") except: pass # Try `metadata` metadata = obs.get("metadata", {}) if isinstance(metadata, dict): return metadata.get("chapter_title") return None def analyze_write_chapters_batches( observations: List[Dict], children_map: Dict[str, List[Dict]], project_type: str, ) -> Dict[str, Dict]: """Analyze batch info under write_chapters. Returns: {obs_id: {'batch': batch_no, 'is_retry': is_retry, 'chapter_title': chapter_title}} """ # Find all write_chapters SPANs write_chapters_nodes = [] for obs in observations: if ( obs.get("type") == "SPAN" and "write_chapters" in obs.get("name", "").lower() ): write_chapters_nodes.append(obs) if not write_chapters_nodes: return {} # Locate crew nodes based on project type. # Collect all crew nodes to detect retries across orchestrator retries. crew_nodes = [] if project_type == "MCP": # MCP: CHAIN kickoff nodes are directly under write_chapters for write_chapters_node in write_chapters_nodes: children = children_map.get(write_chapters_node["id"], []) for child in children: if ( child.get("type") == "CHAIN" and "kickoff" in child.get("name", "").lower() ): crew_nodes.append(child) else: # A2A/A2A_mix: write_chapters has extra SPAN wrappers; find CHAIN kickoff recursively def find_crew_nodes(parent_id: str, depth: int = 0, max_depth: int = 3): if depth > max_depth: return children = children_map.get(parent_id, []) for child in children: if ( child.get("type") == "CHAIN" and "kickoff" in child.get("name", "").lower() ): crew_nodes.append(child) elif child.get("type") == "SPAN": # Keep searching find_crew_nodes(child["id"], depth + 1, max_depth) for write_chapters_node in write_chapters_nodes: find_crew_nodes(write_chapters_node["id"]) if not crew_nodes: return {} # Sort by start time crew_nodes_with_time = [] for node in crew_nodes: start_time = node.get("startTime", "") if start_time: try: dt = datetime.fromisoformat(start_time.replace("Z", "+00:00")) crew_nodes_with_time.append((node, dt)) except: pass crew_nodes_with_time.sort(key=lambda x: x[1]) # Extract chapter_title and detect retry crew_info = [] chapter_titles_seen = {} for node, dt in crew_nodes_with_time: chapter_title = extract_chapter_title(node) is_retry = False is_error = node.get("level") == "ERROR" # Method 1: retry by repeated chapter_title (A2A/A2A_mix) if chapter_title and chapter_title in chapter_titles_seen: is_retry = True # Method 2: without chapter_title, infer from failure + large time gap (MCP) if not chapter_title and crew_info: # Heuristic: if the previous task failed and the gap is large, treat as retry prev_info = crew_info[-1] time_diff = (dt - prev_info["dt"]).total_seconds() # If the gap is large (>60s) and previous failed, this may be a retry if time_diff > 60 and prev_info.get("is_error"): is_retry = True crew_info.append( { "node": node, "dt": dt, "chapter_title": chapter_title, "is_retry": is_retry, "is_error": is_error, } ) if chapter_title: chapter_titles_seen[chapter_title] = True # Batch assignment logic: # 1) group by time (starts within 10s belong to the same batch for initial tasks) # 2) retry tasks inherit the original chapter's batch number # 3) each batch has at most 4 distinct chapters; retries do not count as new chapters batch_info = {} current_batch = 1 batch_start_time = None batch_chapters = set() # chapters in the current batch (excluding retries) chapter_to_batch = {} # chapter_title -> batch_no for info in crew_info: node = info["node"] dt = info["dt"] chapter_title = info["chapter_title"] is_retry = info["is_retry"] assigned_batch = current_batch if is_retry and chapter_title: # Retry: inherit original batch if chapter_title in chapter_to_batch: assigned_batch = chapter_to_batch[chapter_title] # If not found (shouldn't happen), use the current batch else: # Non-retry: batch by time and capacity if batch_start_time is None: # First task starts batch 1 batch_start_time = dt batch_chapters = {chapter_title} if chapter_title else set() else: time_diff = (dt - batch_start_time).total_seconds() # Start a new batch if >10s or batch already has 4 chapters if time_diff > 10 or len(batch_chapters) >= 4: current_batch += 1 batch_start_time = dt batch_chapters = {chapter_title} if chapter_title else set() else: # Add to current batch if chapter_title: batch_chapters.add(chapter_title) assigned_batch = current_batch # Record mapping if chapter_title: chapter_to_batch[chapter_title] = assigned_batch batch_info[node["id"]] = { "batch": assigned_batch, "is_retry": is_retry, "chapter_title": chapter_title, } return batch_info def extract_trace_tree(trace_file: str) -> None: """Extract and render the trace tree.""" # Validate file if not os.path.exists(trace_file): print(f"ERROR: File not found: {trace_file}") return # Detect project type is_a2a_project = detect_a2a_project(trace_file) is_a2a_mix = detect_a2a_mix_project(trace_file) write_book_project_type = detect_write_book_project(trace_file) self_eval_project_type = detect_self_evaluation_project(trace_file) # Read JSON try: with open(trace_file, "r", encoding="utf-8") as f: data = json.load(f) except json.JSONDecodeError as e: print(f"ERROR: JSON parse error: {e}") return except Exception as e: print(f"ERROR: Failed to read file: {e}") return # Basic info trace_id = data.get("id", "N/A") timestamp = data.get("timestamp", "N/A") observations = data.get("observations", []) if not observations: print("WARNING: This trace has no observations") return # Build tree tree_lines, error_stats = build_tree_structure( observations, is_a2a_project, is_a2a_mix, write_book_project_type, self_eval_project_type, ) # Helper: truncate error messages and count truncations (display-stage only) def truncate_error_msg(msg: str, max_length: int = 80) -> str: """Truncate error message and update truncation counter.""" if len(msg) > max_length: error_stats["truncated_errors_count"] += 1 return msg[: max_length - 10] + "[TRUNCATED]" return msg # Build full output (Markdown) header_lines = [ f"# Trace Execution Path", f"", f"**Trace ID**: `{trace_id}`", f"", f"**Time**: {timestamp}", f"", ] if is_a2a_project: header_lines.append("**Project Type**: A2A (framework noise filtered)") header_lines.append(f"") if write_book_project_type: header_lines.append( f"**write_a_book_with_flows Project Type**: {write_book_project_type}" ) header_lines.append( "**Batch Annotation**: enabled (concurrent writing batch analysis)" ) header_lines.append(f"") if self_eval_project_type: header_lines.append( f"**self_evaluation_loop_flow Project Type**: {self_eval_project_type}" ) header_lines.append( "**RETRY Annotation**: enabled (content_generator and post_reviewer retry detection)" ) header_lines.append(f"") # Statistics original_count = len(observations) filtered_count = len( [ obs for obs in observations if not should_filter_observation(obs, is_a2a_project) ] ) # Tree section header_lines.append("## Execution Path Tree") header_lines.append(f"") header_lines.append(f"```") # Tree block (code fenced) tree_block = tree_lines # Summary footer_lines = [ f"```", f"", f"## Statistics", f"", ] if is_a2a_project: footer_lines.append(f"- **Original observations**: {original_count}") footer_lines.append(f"- **Observations after filtering**: {filtered_count}") a2a_filtered = original_count - filtered_count - error_stats["http_filtered"] footer_lines.append(f"- **Filtered**: {original_count - filtered_count} nodes") if error_stats["http_filtered"] > 0: footer_lines.append(f" - A2A framework internals: {a2a_filtered} nodes") footer_lines.append( f' - HTTP request nodes: {error_stats["http_filtered"]} nodes' ) else: footer_lines.append(f"- **Total observations**: {original_count}") if error_stats["http_filtered"] > 0: footer_lines.append( f'- **Filtered HTTP request nodes**: {error_stats["http_filtered"]} nodes' ) # Error summary if error_stats["total_errors"] > 0: footer_lines.append(f"") footer_lines.append("### Error Summary") footer_lines.append(f"") footer_lines.append(f'- **Total errors**: {error_stats["total_errors"]}') footer_lines.append(f'- **Visible errors**: {error_stats["visible_errors"]}') if error_stats["filtered_errors"] > 0: footer_lines.append( f'- **Filtered errors**: {error_stats["filtered_errors"]}' ) if error_stats["visible_errors"] == 0: footer_lines.append( "- **Note**: All errors are inside filtered nodes; the tree does not show error nodes" ) # Truncation stats if error_stats["truncated_errors_count"] > 0: footer_lines.append( f'- **Truncated error messages**: {error_stats["truncated_errors_count"]}' ) if error_stats["filtered_errors"] > 0: # Details of errors inside filtered nodes footer_lines.append(f"") footer_lines.append("#### Errors Inside Filtered Nodes") footer_lines.append(f"") # A2A framework/internal errors if error_stats["a2a_framework_errors"]: footer_lines.append( f'**A2A framework/internal errors** ({len(error_stats["a2a_framework_errors"])}):' ) for i, err in enumerate(error_stats["a2a_framework_errors"], 1): msg = truncate_error_msg(err["message"]) footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`: {msg}') footer_lines.append(f"") # HTTP request node errors if error_stats["http_request_errors"]: footer_lines.append( f'**HTTP request node errors** ({len(error_stats["http_request_errors"])}):' ) for i, err in enumerate(error_stats["http_request_errors"], 1): msg = truncate_error_msg(err["message"]) footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`: {msg}') footer_lines.append(f"") # Tool Usage node errors if error_stats["tool_usage_errors"]: footer_lines.append( f'**Tool Usage node errors** ({len(error_stats["tool_usage_errors"])}):' ) for i, err in enumerate(error_stats["tool_usage_errors"], 1): msg = truncate_error_msg(err["message"]) footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`: {msg}') footer_lines.append(f"") # Tool child SPAN errors if error_stats["tool_child_span_errors"]: footer_lines.append( f'**Tool child SPAN errors (A2A_mix only)** ({len(error_stats["tool_child_span_errors"])}):' ) for i, err in enumerate(error_stats["tool_child_span_errors"], 1): msg = truncate_error_msg(err["message"]) footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`: {msg}') footer_lines.append(f"") # Context notes if error_stats["filtered_errors_no_parent_error"]: footer_lines.append("#### Context Notes") footer_lines.append(f"") footer_lines.append( f'**Filtered error nodes with no ancestor error** ({len(error_stats["filtered_errors_no_parent_error"])}):' ) # De-duplicate (a node may appear in multiple categories) unique_errors = { err["id"]: err for err in error_stats["filtered_errors_no_parent_error"] }.values() for i, err in enumerate(unique_errors, 1): footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`') footer_lines.append(f"") if error_stats["filtered_errors_no_child_error"]: if not error_stats["filtered_errors_no_parent_error"]: footer_lines.append("#### Context Notes") footer_lines.append(f"") footer_lines.append( f'**Filtered error nodes with no descendant error** ({len(error_stats["filtered_errors_no_child_error"])}):' ) # De-duplicate (a node may appear in multiple categories) unique_errors = { err["id"]: err for err in error_stats["filtered_errors_no_child_error"] }.values() for i, err in enumerate(unique_errors, 1): footer_lines.append(f'{i}. `[{err["type"]}] {err["name"]}`') footer_lines.append(f"") if error_stats["error_messages"]: footer_lines.append("**Visible error types**:") for i, msg in enumerate(error_stats["error_messages"], 1): # Show full messages in the summary (do not truncate) if not msg: msg = "Unknown error" footer_lines.append(f"{i}. `{msg}`") footer_lines.append(f"") output_lines = header_lines + tree_block + footer_lines # Print to console print("\n".join(output_lines)) # Write Markdown file next to the trace file output_file = os.path.join(os.path.dirname(trace_file), "execution_path.md") try: with open(output_file, "w", encoding="utf-8") as f: f.write("\n".join(output_lines)) print(f"\nSaved: {os.path.basename(output_file)}") except Exception as e: print(f"\nERROR: Failed to write output file: {e}") def main(): """CLI entrypoint.""" if len(sys.argv) < 2: print("Usage: python3 extract_trace_tree.py ") print("\nNotes:") print(" - Extracts the tree from langfuse_trace.json") print(" - Sorts by timestamp and renders a hierarchy") print(" - Writes execution_path.md next to the trace file") sys.exit(1) trace_file = sys.argv[1] extract_trace_tree(trace_file) if __name__ == "__main__": main()