| |
| """ |
| 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", "") |
|
|
| |
| if child_type == "GENERATION": |
| total_prompt += child.get("promptTokens", 0) |
| total_completion += child.get("completionTokens", 0) |
| total_tokens += child.get("totalTokens", 0) |
|
|
| |
| usage_details = child.get("usageDetails", {}) |
| if isinstance(usage_details, dict): |
| total_reasoning += usage_details.get("completion_details.reasoning", 0) |
|
|
| |
| if child_type in ["GENERATION", "TOOL"]: |
| total_time += child.get("latency", 0.0) |
|
|
| |
| 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 = "" |
|
|
| |
| obs_level = obs.get("level", "DEFAULT") |
| status_message = obs.get("statusMessage") |
| if obs_level == "ERROR" and status_message: |
| error_prefix = "[ERROR] " |
| |
| if len(status_message) > 80: |
| error_msg = status_message[:70] + "[TRUNCATED]" |
| else: |
| error_msg = status_message |
| suffix = f" [ERROR: {error_msg}]" + suffix |
|
|
| |
| if obs_type == "SPAN": |
| if "Crew Created" in obs_name: |
| base_name = "[Crew Created]" |
| elif "Task Created" in obs_name: |
| base_name = "[Task Created]" |
| |
| 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}" |
|
|
| |
| elif obs_type == "AGENT": |
| base_name = f"[AGENT] {obs_name}" |
|
|
| |
| elif obs_type == "GENERATION": |
| model = obs.get("model", "unknown") |
| if "/" in model: |
| model = model.split("/")[-1] |
| base_name = f"[LLM] {model}" |
|
|
| |
| prompt_tokens = obs.get("promptTokens", 0) |
| completion_tokens = obs.get("completionTokens", 0) |
| total_tokens = obs.get("totalTokens", 0) |
|
|
| |
| 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 = obs.get("latency", 0.0) |
| if latency > 0: |
| suffix += f" [{format_time(latency)}]" |
|
|
| |
| elif obs_type == "TOOL": |
| base_name = f"[Tool] {obs_name}" |
|
|
| |
| latency = obs.get("latency", 0.0) |
| if latency > 0: |
| suffix += f" [{format_time(latency)}]" |
|
|
| |
| elif obs_type == "CHAIN": |
| base_name = f"[Chain] {obs_name}" |
|
|
| |
| else: |
| base_name = f"[{obs_type}] {obs_name}" |
|
|
| |
| 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)}" |
| ) |
|
|
| |
| 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", "") |
|
|
| |
| metadata = obs.get("metadata", {}) |
| scope_name = metadata.get("scope", {}).get("name", "") |
| if scope_name == "opentelemetry.instrumentation.httpx" and obs_type == "SPAN": |
| |
| if obs_name in ["POST", "GET", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]: |
| return True |
|
|
| |
| 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.", |
| ] |
|
|
| |
| 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, |
| |
| "a2a_framework_errors": [], |
| "http_request_errors": [], |
| "tool_usage_errors": [], |
| "tool_child_span_errors": [], |
| |
| "filtered_errors_no_parent_error": [], |
| "filtered_errors_no_child_error": [], |
| |
| "truncated_errors_count": 0, |
| } |
|
|
| |
| all_obs_map = {obs["id"]: obs for obs in observations} |
|
|
| |
| 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) |
|
|
| |
| 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 |
|
|
| |
| 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 |
|
|
| |
| 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" |
|
|
| |
| if obs_level == "ERROR": |
| error_stats["total_errors"] += 1 |
|
|
| if should_filter_observation(obs, is_a2a_project): |
| error_stats["filtered_errors"] += 1 |
|
|
| |
| metadata = obs.get("metadata", {}) |
| scope_name = metadata.get("scope", {}).get("name", "") |
|
|
| |
| 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: |
| |
| error_stats["a2a_framework_errors"].append(error_info) |
|
|
| |
| 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 |
| |
| if status_msg and status_msg not in error_stats["error_messages"]: |
| error_stats["error_messages"].append(status_msg) |
|
|
| |
| is_filtered = should_filter_observation(obs, is_a2a_project) |
| if is_filtered: |
| |
| 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) |
|
|
| |
| |
| id_to_obs = {obs["id"]: obs for obs in filtered_obs} |
|
|
| |
| 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() |
|
|
| 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 |
|
|
| |
| if parent.get("type") == "CHAIN": |
| chain_name = parent.get("name", "") |
| |
| if re.match(r"Crew_[a-f0-9\-]+\.kickoff", chain_name): |
| return True |
|
|
| parent_id = parent.get("parentObservationId") |
|
|
| return False |
|
|
| |
| 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", "") |
|
|
| |
| if parent_type == "TOOL": |
| if "Tool Usage" in child_name or "Tool Repeated Usage" in child_name: |
| return True |
|
|
| |
| 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 |
|
|
| |
| if parent_type == "AGENT": |
| if child_type == "SPAN" and ( |
| "Tool Usage" in child_name or "Tool Repeated Usage" in child_name |
| ): |
| |
| if is_under_crew_chain(parent_obs, observations): |
| return True |
|
|
| return False |
|
|
| |
| for obs in filtered_obs: |
| parent_id = obs.get("parentObservationId") |
|
|
| |
| while parent_id and parent_id not in id_to_obs: |
| |
| 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_obs = id_to_obs.get(parent_id) if parent_id else None |
| if should_filter_by_parent(obs, parent_obs, is_a2a_mix): |
| |
| 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": |
| |
| error_stats["tool_child_span_errors"].append(error_info) |
|
|
| |
| 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 |
|
|
| if parent_id: |
| if parent_id not in children_map: |
| children_map[parent_id] = [] |
| children_map[parent_id].append(obs) |
| else: |
| |
| if "ROOT" not in children_map: |
| children_map["ROOT"] = [] |
| children_map["ROOT"].append(obs) |
|
|
| |
| 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 = simplify_name(obs_type, obs_name, obs, children_map) |
|
|
| |
| 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]" |
|
|
| |
| 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}" |
|
|
| |
| 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]" |
|
|
| |
| connector = "└─ " if is_last else "├─ " |
| output_lines.append(f"{prefix}{connector}{display_name}") |
|
|
| |
| if is_last: |
| new_prefix = prefix + " " |
| else: |
| new_prefix = prefix + "│ " |
|
|
| |
| children = children_map.get(obs_id, []) |
|
|
| |
| 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 = [] |
|
|
| |
| children_map, error_stats = build_children_map( |
| observations, is_a2a_project, is_a2a_mix |
| ) |
|
|
| |
| batch_info = {} |
| if project_type: |
| batch_info = analyze_write_chapters_batches( |
| observations, children_map, project_type |
| ) |
|
|
| |
| self_eval_retry_info = {} |
| if self_eval_project_type: |
| self_eval_retry_info = analyze_self_evaluation_retries( |
| observations, children_map, self_eval_project_type |
| ) |
|
|
| |
| 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) |
|
|
| |
| output_lines.append(display_name) |
|
|
| |
| children = children_map.get(root["id"], []) |
| for j, child in enumerate(children): |
| |
| if child.get("type") == "SPAN": |
| name = child.get("name", "") |
|
|
| |
| 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]" |
|
|
| |
| elif not m_business: |
| m = re.search(r"\bretry\s*(\d+)\b", name, re.IGNORECASE) |
| if m: |
| retry_idx = m.group(1) |
| |
| 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 |
|
|
| |
| 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() |
|
|
| |
| if ( |
| "self_evaluation_loop_flow" not in path_lower |
| and "self-evaluation-loop-flow" not in path_lower |
| ): |
| return None |
|
|
| |
| 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 = {} |
|
|
| |
| 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": |
| |
| for content_loop_node in content_loop_nodes: |
| |
| 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"]) |
|
|
| |
| role_seen = {} |
|
|
| for node in chain_nodes: |
| |
| agent_children = children_map.get(node["id"], []) |
| for agent in agent_children: |
| if agent.get("type") == "AGENT": |
| agent_name = agent.get("name", "") |
| |
| role = ( |
| agent_name.split("._execute_core")[0] |
| if "._execute_core" in agent_name |
| else agent_name |
| ) |
|
|
| |
| if "Shakespearean Bard" in role or "X Post Verifier" in role: |
| if role in role_seen: |
| |
| retry_info[node["id"]] = True |
| else: |
| |
| role_seen[role] = node |
| retry_info[node["id"]] = False |
| break |
|
|
| else: |
| |
| for content_loop_node in content_loop_nodes: |
| |
| 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"]) |
|
|
| |
| 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]) |
|
|
| |
| span_type_seen = {} |
|
|
| for node, dt in target_spans_with_time: |
| name = node.get("name", "").lower() |
|
|
| |
| 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: |
| |
| retry_info[node["id"]] = True |
| else: |
| |
| 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.""" |
| |
| 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 |
|
|
| |
| 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}} |
| """ |
| |
| 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 {} |
|
|
| |
| |
| crew_nodes = [] |
|
|
| if project_type == "MCP": |
| |
| 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: |
| |
| 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": |
| |
| 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 {} |
|
|
| |
| 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]) |
|
|
| |
| 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" |
|
|
| |
| if chapter_title and chapter_title in chapter_titles_seen: |
| is_retry = True |
|
|
| |
| if not chapter_title and crew_info: |
| |
| prev_info = crew_info[-1] |
| time_diff = (dt - prev_info["dt"]).total_seconds() |
| |
| 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_info = {} |
| current_batch = 1 |
| batch_start_time = None |
| batch_chapters = set() |
| chapter_to_batch = {} |
|
|
| 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: |
| |
| if chapter_title in chapter_to_batch: |
| assigned_batch = chapter_to_batch[chapter_title] |
| |
| else: |
| |
| if batch_start_time is None: |
| |
| batch_start_time = dt |
| batch_chapters = {chapter_title} if chapter_title else set() |
| else: |
| time_diff = (dt - batch_start_time).total_seconds() |
|
|
| |
| 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: |
| |
| if chapter_title: |
| batch_chapters.add(chapter_title) |
|
|
| assigned_batch = current_batch |
|
|
| |
| 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.""" |
|
|
| |
| if not os.path.exists(trace_file): |
| print(f"ERROR: File not found: {trace_file}") |
| return |
|
|
| |
| 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) |
|
|
| |
| 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 |
|
|
| |
| 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 |
|
|
| |
| tree_lines, error_stats = build_tree_structure( |
| observations, |
| is_a2a_project, |
| is_a2a_mix, |
| write_book_project_type, |
| self_eval_project_type, |
| ) |
|
|
| |
| 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 |
|
|
| |
| 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"") |
|
|
| |
| original_count = len(observations) |
| filtered_count = len( |
| [ |
| obs |
| for obs in observations |
| if not should_filter_observation(obs, is_a2a_project) |
| ] |
| ) |
|
|
| |
| header_lines.append("## Execution Path Tree") |
| header_lines.append(f"") |
| header_lines.append(f"```") |
|
|
| |
| tree_block = tree_lines |
|
|
| |
| 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' |
| ) |
|
|
| |
| 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" |
| ) |
|
|
| |
| 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: |
| |
| footer_lines.append(f"") |
| footer_lines.append("#### Errors Inside Filtered Nodes") |
| footer_lines.append(f"") |
|
|
| |
| 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"") |
|
|
| |
| 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"") |
|
|
| |
| 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"") |
|
|
| |
| 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"") |
|
|
| |
| 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"])}):' |
| ) |
| |
| 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"])}):' |
| ) |
| |
| 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): |
| |
| 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("\n".join(output_lines)) |
|
|
| |
| 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 <trace_file.json>") |
| 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() |
|
|